summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAlexander Kutsan <AKutsan@luxoft.com>2016-08-26 18:48:22 +0300
committerAlexander Kutsan <AKutsan@luxoft.com>2016-08-26 18:48:57 +0300
commitd73e6dc8724c5799fae14efd4dcb214af74e4904 (patch)
tree9ebed8b422490c4d669e90e70783e4f5b55b65c9
parentc201c11a35d360c0b96f36b103a2590bfaeb6026 (diff)
parent61ef8c42badb879216f53d240e1101b9f83a9bb7 (diff)
downloadsdl_core-d73e6dc8724c5799fae14efd4dcb214af74e4904.tar.gz
Merge branch 'release/4.1.0'
-rw-r--r--.clang-format11
-rw-r--r--.gitignore2
-rw-r--r--.travis.yml63
-rw-r--r--CMakeLists.txt270
-rw-r--r--COMMITTERS.md5
-rw-r--r--README.md26
-rw-r--r--cmake/Modules/FindLibavahi.cmake29
-rw-r--r--src/3rd_party-static/MessageBroker/include/mb_controller.hpp9
-rw-r--r--src/3rd_party-static/MessageBroker/src/client/mb_controller.cpp3
-rw-r--r--src/3rd_party-static/MessageBroker/src/lib_messagebroker/system.cpp8
-rw-r--r--src/3rd_party-static/gmock-1.7.0/include/gmock/gmock-spec-builders.h41
-rw-r--r--src/3rd_party-static/gmock-1.7.0/src/gmock-spec-builders.cc162
-rw-r--r--src/appMain/CMakeLists.txt17
-rwxr-xr-x[-rw-r--r--]src/appMain/hmi_capabilities.json40
-rw-r--r--src/appMain/life_cycle.cc458
-rw-r--r--src/appMain/life_cycle.h96
-rw-r--r--src/appMain/log4cxx.properties88
-rw-r--r--src/appMain/main.cc86
-rw-r--r--src/appMain/sdl_preloaded_pt.json4574
-rw-r--r--src/appMain/signal_handlers.cc12
-rw-r--r--src/appMain/signal_handlers.h14
-rw-r--r--src/appMain/smartDeviceLink.ini132
-rw-r--r--src/components/CMakeLists.txt4
-rw-r--r--src/components/HMI/app/controller/PhoneController.js34
-rw-r--r--src/components/HMI/app/controller/sdl/RPCController.js65
-rw-r--r--src/components/HMI/app/view/phone/dialpadView.js71
-rw-r--r--src/components/HMI/ffw/BasicCommunicationRPC.js26
-rw-r--r--src/components/application_manager/CMakeLists.txt50
-rw-r--r--src/components/application_manager/include/application_manager/application.h1191
-rw-r--r--src/components/application_manager/include/application_manager/application_data_impl.h466
-rw-r--r--src/components/application_manager/include/application_manager/application_impl.h245
-rw-r--r--src/components/application_manager/include/application_manager/application_manager.h516
-rw-r--r--src/components/application_manager/include/application_manager/application_manager_impl.h813
-rw-r--r--src/components/application_manager/include/application_manager/application_state.h159
-rw-r--r--src/components/application_manager/include/application_manager/commands/command.h27
-rw-r--r--src/components/application_manager/include/application_manager/commands/command_impl.h54
-rw-r--r--src/components/application_manager/include/application_manager/commands/command_notification_from_mobile_impl.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/command_notification_impl.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/command_request_impl.h44
-rw-r--r--src/components/application_manager/include/application_manager/commands/command_response_impl.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/activate_app_request.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/activate_app_response.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/add_statistics_info_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/allow_all_apps_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/allow_all_apps_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/allow_app_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/allow_app_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/basic_communication_system_request.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/basic_communication_system_response.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/button_get_capabilities_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/button_get_capabilities_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/close_popup_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/close_popup_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/dial_number_request.h11
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/dial_number_response.h11
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/get_system_info_request.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/get_system_info_response.h45
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/get_urls.h75
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/get_urls_response.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/mixing_audio_supported_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/mixing_audio_supported_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_alert_maneuver_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_alert_maneuver_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_audio_start_stream_request.h20
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_audio_start_stream_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_audio_stop_stream_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_audio_stop_stream_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_get_way_points_request.h71
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_get_way_points_response.h73
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_is_ready_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_is_ready_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_send_location_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_send_location_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_show_constant_tbt_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_show_constant_tbt_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_start_stream_request.h64
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_start_stream_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_stop_stream_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_stop_stream_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_subscribe_way_points_request.h71
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_subscribe_way_points_response.h73
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_unsubscribe_way_points_request.h71
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_unsubscribe_way_points_response.h72
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_update_turn_list_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/navi_update_turn_list_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/notification_from_hmi.h6
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/notification_to_hmi.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_allow_sdl_functionality_notification.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_app_activated_notification.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_app_deactivated_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_app_permission_changed_notification.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_app_permission_consent_notification.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_app_registered_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_app_unregistered_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_audio_data_streaming_notification.h36
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_button_event_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_button_press_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_button_subscription_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_device_chosen_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_device_state_changed_notification.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_driver_distraction_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_emergency_event_notification.h72
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_event_changed_notification.h73
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_exit_all_applications_notification.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_exit_application_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_file_removed_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_find_applications.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_ignition_cycle_over_notification.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_navi_tbt_client_state_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_navi_way_point_change_notification.h73
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_phone_call_notification.h77
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_play_tone_notification.h72
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_policy_update.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_put_file_notification.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_ready_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_received_policy_update.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_record_start_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_resume_audio_source_notification.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_sdl_close_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_sdl_consent_needed_notification.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_sdl_persistence_complete_notification.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_start_device_discovery.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_status_update_notification.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_system_context_notification.h6
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_system_error_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_system_info_changed_notification.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_system_request_notification.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_tts_language_change_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_tts_reset_timeout_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_tts_started_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_tts_stopped_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_ui_command_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_ui_keyboard_input_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_ui_language_change_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_ui_reset_timeout_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_ui_touch_event_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_update_device_list.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_acc_pedal_position_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_belt_status_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_body_information_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_device_status_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_driver_braking_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_engine_torque_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_external_temperature_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_fuel_level_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_fuel_level_state_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_gps_data_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_head_lamp_status_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_instant_fuel_consumption_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_my_key_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_odometer_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_prndl_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_rpm_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_speed_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_steering_wheel_angle_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_tire_pressure_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_vehicle_data_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_vin_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vi_wiper_status_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_video_data_streaming_notification.h36
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vr_command_notification.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vr_language_change_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vr_started_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/on_vr_stopped_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/request_from_hmi.h153
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/request_to_hmi.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/response_from_hmi.h7
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/response_to_hmi.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/sdl_activate_app_request.h98
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/sdl_activate_app_response.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/sdl_get_list_of_permissions_request.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/sdl_get_list_of_permissions_response.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/sdl_get_status_update_request.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/sdl_get_status_update_response.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/sdl_get_user_friendly_message_request.h36
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/sdl_get_user_friendly_message_response.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/sdl_policy_update.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/sdl_policy_update_response.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_change_registration_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_change_registration_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_get_capabilities_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_get_capabilities_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_get_language_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_get_language_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_get_supported_languages_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_get_supported_languages_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_is_ready_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_is_ready_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_set_global_properties_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_set_global_properties_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_speak_request.h6
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_speak_response.h6
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_stop_speaking_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/tts_stop_speaking_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_add_command_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_add_command_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_add_submenu_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_add_submenu_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_alert_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_alert_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_change_registration_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_change_registration_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_delete_command_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_delete_command_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_delete_submenu_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_delete_submenu_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_end_audio_pass_thru_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_end_audio_pass_thru_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_get_capabilities_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_get_capabilities_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_get_language_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_get_language_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_get_supported_languages_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_get_supported_languages_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_is_ready_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_is_ready_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_perform_interaction_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_perform_interaction_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_scrollable_message_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_scrollable_message_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_set_app_icon_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_set_app_icon_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_set_display_layout_request.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_set_display_layout_response.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_set_global_properties_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_set_global_properties_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_set_icon_request.h6
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_set_icon_response.h6
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_set_media_clock_timer_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_set_media_clock_timer_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_show_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_show_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_slider_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/ui_slider_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/update_app_list_request.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/update_app_list_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/update_device_list_request.h13
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/update_device_list_response.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/update_sdl_request.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/update_sdl_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_diagnostic_message_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_diagnostic_message_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_get_dtcs_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_get_dtcs_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_request_template.h10
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_response.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_response_template.h13
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_type_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_type_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_is_ready_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_is_ready_response.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_read_did_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_read_did_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request_template.h11
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response_template.h15
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request_template.h11
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response_template.h15
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_add_command_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_add_command_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_change_registration_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_change_registration_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_delete_command_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_delete_command_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_get_capabilities_request.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_get_capabilities_response.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_get_language_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_get_language_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_get_supported_languages_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_get_supported_languages_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_is_ready_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_is_ready_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_perform_interaction_request.h35
-rw-r--r--src/components/application_manager/include/application_manager/commands/hmi/vr_perform_interaction_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/add_command_request.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/add_command_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/add_sub_menu_request.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/add_sub_menu_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/alert_maneuver_request.h9
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/alert_maneuver_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/alert_request.h38
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/alert_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/change_registration_request.h93
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/change_registration_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/create_interaction_choice_set_request.h341
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/create_interaction_choice_set_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/delete_command_request.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/delete_command_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/delete_file_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/delete_file_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/delete_interaction_choice_set_request.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/delete_interaction_choice_set_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/delete_sub_menu_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/delete_sub_menu_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/diagnostic_message_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/diagnostic_message_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/dial_number_request.h12
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/dial_number_response.h10
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/end_audio_pass_thru_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/end_audio_pass_thru_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/generic_response.h9
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/get_dtcs_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/get_dtcs_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/get_vehicle_data_request.h6
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/get_vehicle_data_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/get_way_points_request.h77
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/get_way_points_response.h72
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/list_files_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/list_files_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_app_interface_unregistered_notification.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_audio_pass_thru_notification.h6
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_button_event_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_button_press_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_command_notification.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_driver_distraction_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_hash_change_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_hmi_status_notification.h5
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_hmi_status_notification_from_mobile.h10
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_keyboard_input_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_language_change_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_permissions_change_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_system_request_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_tbt_client_state_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_touch_event_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_vehicle_data_notification.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/on_way_point_change_notification.h69
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/perform_audio_pass_thru_request.h12
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/perform_audio_pass_thru_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/perform_interaction_request.h82
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/perform_interaction_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/put_file_request.h17
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/put_file_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/read_did_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/read_did_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/register_app_interface_request.h49
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/register_app_interface_response.h9
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/reset_global_properties_request.h6
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/reset_global_properties_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/scrollable_message_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/scrollable_message_response.h6
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/send_location_request.h14
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/send_location_response.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/set_app_icon_request.h12
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/set_app_icon_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/set_display_layout_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/set_display_layout_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/set_global_properties_request.h48
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/set_global_properties_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/set_icon_request.h9
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/set_icon_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/set_media_clock_timer_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/set_media_clock_timer_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/show_constant_tbt_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/show_constant_tbt_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/show_request.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/show_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/slider_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/slider_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/speak_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/speak_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/subscribe_button_request.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/subscribe_button_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/subscribe_vehicle_data_request.h41
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/subscribe_vehicle_data_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/subscribe_way_points_request.h77
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/subscribe_way_points_response.h72
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/system_request.h12
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/system_response.h4
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/unregister_app_interface_request.h9
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/unregister_app_interface_response.h9
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_button_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_button_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_vehicle_data_request.h39
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_vehicle_data_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_way_points_request.h74
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_way_points_response.h72
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/update_turn_list_request.h3
-rw-r--r--src/components/application_manager/include/application_manager/commands/mobile/update_turn_list_response.h3
-rw-r--r--src/components/application_manager/include/application_manager/event_engine/event.h30
-rw-r--r--src/components/application_manager/include/application_manager/event_engine/event_dispatcher.h62
-rw-r--r--src/components/application_manager/include/application_manager/event_engine/event_dispatcher_impl.h129
-rw-r--r--src/components/application_manager/include/application_manager/event_engine/event_observer.h23
-rw-r--r--src/components/application_manager/include/application_manager/hmi_capabilities.h204
-rw-r--r--src/components/application_manager/include/application_manager/hmi_command_factory.h7
-rw-r--r--src/components/application_manager/include/application_manager/hmi_language_handler.h187
-rw-r--r--src/components/application_manager/include/application_manager/hmi_state.h390
-rw-r--r--src/components/application_manager/include/application_manager/message.h10
-rw-r--r--src/components/application_manager/include/application_manager/message_helper.h1104
-rw-r--r--src/components/application_manager/include/application_manager/mobile_command_factory.h8
-rw-r--r--src/components/application_manager/include/application_manager/mobile_message_handler.h22
-rw-r--r--src/components/application_manager/include/application_manager/policies/delegates/app_permission_delegate.h67
-rw-r--r--src/components/application_manager/include/application_manager/policies/delegates/statistics_delegate.h80
-rw-r--r--src/components/application_manager/include/application_manager/policies/policy_event_observer.h22
-rw-r--r--src/components/application_manager/include/application_manager/policies/policy_handler.h371
-rw-r--r--src/components/application_manager/include/application_manager/policies/policy_handler_observer.h15
-rw-r--r--src/components/application_manager/include/application_manager/policies/pt_exchange_handler.h8
-rw-r--r--src/components/application_manager/include/application_manager/request_controller.h456
-rw-r--r--src/components/application_manager/include/application_manager/request_info.h586
-rw-r--r--src/components/application_manager/include/application_manager/resume_ctrl.h525
-rw-r--r--src/components/application_manager/include/application_manager/resumption/resume_ctrl.h506
-rw-r--r--src/components/application_manager/include/application_manager/resumption/resumption_data.h274
-rw-r--r--src/components/application_manager/include/application_manager/resumption/resumption_data_db.h838
-rw-r--r--src/components/application_manager/include/application_manager/resumption/resumption_data_json.h235
-rw-r--r--src/components/application_manager/include/application_manager/resumption/resumption_sql_queries.h138
-rw-r--r--src/components/application_manager/include/application_manager/smart_object_keys.h707
-rw-r--r--src/components/application_manager/include/application_manager/state_context.h75
-rw-r--r--src/components/application_manager/include/application_manager/state_controller.h408
-rw-r--r--src/components/application_manager/include/application_manager/state_controller_impl.h448
-rw-r--r--src/components/application_manager/include/application_manager/telemetry_observer.h58
-rw-r--r--src/components/application_manager/include/application_manager/time_metric_observer.h59
-rw-r--r--src/components/application_manager/include/application_manager/usage_statistics.h21
-rw-r--r--src/components/application_manager/include/application_manager/vehicle_info_data.h8
-rw-r--r--src/components/application_manager/src/application_data_impl.cc163
-rw-r--r--src/components/application_manager/src/application_impl.cc655
-rw-r--r--src/components/application_manager/src/application_manager_impl.cc2212
-rw-r--r--src/components/application_manager/src/application_state.cc249
-rw-r--r--src/components/application_manager/src/commands/command_impl.cc100
-rw-r--r--src/components/application_manager/src/commands/command_notification_from_mobile_impl.cc15
-rw-r--r--src/components/application_manager/src/commands/command_notification_impl.cc15
-rw-r--r--src/components/application_manager/src/commands/command_request_impl.cc201
-rw-r--r--src/components/application_manager/src/commands/command_response_impl.cc20
-rw-r--r--src/components/application_manager/src/commands/hmi/activate_app_request.cc50
-rw-r--r--src/components/application_manager/src/commands/hmi/activate_app_response.cc14
-rw-r--r--src/components/application_manager/src/commands/hmi/add_statistics_info_notification.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/allow_all_apps_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/allow_all_apps_response.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/allow_app_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/allow_app_response.cc19
-rw-r--r--src/components/application_manager/src/commands/hmi/basic_communication_on_awake_sdl.cc2
-rw-r--r--src/components/application_manager/src/commands/hmi/basic_communication_system_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/basic_communication_system_response.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/button_get_capabilities_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/button_get_capabilities_response.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/close_popup_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/close_popup_response.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/dial_number_request.cc14
-rw-r--r--src/components/application_manager/src/commands/hmi/dial_number_response.cc18
-rw-r--r--src/components/application_manager/src/commands/hmi/get_system_info_request.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/get_system_info_response.cc63
-rw-r--r--src/components/application_manager/src/commands/hmi/get_urls.cc64
-rw-r--r--src/components/application_manager/src/commands/hmi/get_urls_response.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/mixing_audio_supported_request.cc8
-rw-r--r--src/components/application_manager/src/commands/hmi/mixing_audio_supported_response.cc16
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_alert_maneuver_request.cc8
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_alert_maneuver_response.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_audio_start_stream_request.cc140
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_audio_start_stream_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_audio_stop_stream_request.cc8
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_audio_stop_stream_response.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_get_way_points_request.cc53
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_get_way_points_response.cc57
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_is_ready_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_is_ready_response.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_send_location_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_send_location_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_show_constant_tbt_request.cc8
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_show_constant_tbt_response.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_start_stream_request.cc92
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_start_stream_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_stop_stream_request.cc8
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_stop_stream_response.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_subscribe_way_points_request.cc53
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_subscribe_way_points_response.cc58
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_unsubscribe_way_points_request.cc53
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_unsubscribe_way_points_response.cc59
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_update_turn_list_request.cc8
-rw-r--r--src/components/application_manager/src/commands/hmi/navi_update_turn_list_response.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/notification_from_hmi.cc26
-rw-r--r--src/components/application_manager/src/commands/hmi/notification_to_hmi.cc18
-rw-r--r--src/components/application_manager/src/commands/hmi/on_allow_sdl_functionality_notification.cc16
-rw-r--r--src/components/application_manager/src/commands/hmi/on_app_activated_notification.cc19
-rw-r--r--src/components/application_manager/src/commands/hmi/on_app_deactivated_notification.cc76
-rw-r--r--src/components/application_manager/src/commands/hmi/on_app_permission_changed_notification.cc8
-rw-r--r--src/components/application_manager/src/commands/hmi/on_app_permission_consent_notification.cc46
-rw-r--r--src/components/application_manager/src/commands/hmi/on_app_registered_notification.cc14
-rw-r--r--src/components/application_manager/src/commands/hmi/on_app_unregistered_notification.cc17
-rw-r--r--src/components/application_manager/src/commands/hmi/on_audio_data_streaming_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_button_event_notification.cc7
-rw-r--r--src/components/application_manager/src/commands/hmi/on_button_press_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_button_subscription_notification.cc8
-rw-r--r--src/components/application_manager/src/commands/hmi/on_device_chosen_notification.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/on_device_state_changed_notification.cc99
-rw-r--r--src/components/application_manager/src/commands/hmi/on_driver_distraction_notification.cc28
-rw-r--r--src/components/application_manager/src/commands/hmi/on_emergency_event_notification.cc59
-rw-r--r--src/components/application_manager/src/commands/hmi/on_event_changed_notification.cc55
-rw-r--r--src/components/application_manager/src/commands/hmi/on_exit_all_applications_notification.cc30
-rw-r--r--src/components/application_manager/src/commands/hmi/on_exit_application_notification.cc70
-rw-r--r--src/components/application_manager/src/commands/hmi/on_file_removed_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_find_applications.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/on_ignition_cycle_over_notification.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/on_navi_tbt_client_state_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_navi_way_point_change_notification.cc57
-rw-r--r--src/components/application_manager/src/commands/hmi/on_phone_call_notification.cc64
-rw-r--r--src/components/application_manager/src/commands/hmi/on_play_tone_notification.cc55
-rw-r--r--src/components/application_manager/src/commands/hmi/on_policy_update.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/on_put_file_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_ready_notification.cc15
-rw-r--r--src/components/application_manager/src/commands/hmi/on_received_policy_update.cc17
-rw-r--r--src/components/application_manager/src/commands/hmi/on_record_start_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_resume_audio_source_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_sdl_close_notification.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/on_sdl_consent_needed_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_sdl_persistence_complete_notification.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/on_start_device_discovery.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/on_status_update_notification.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/on_system_context_notification.cc38
-rw-r--r--src/components/application_manager/src/commands/hmi/on_system_error_notification.cc17
-rw-r--r--src/components/application_manager/src/commands/hmi/on_system_info_changed_notification.cc16
-rw-r--r--src/components/application_manager/src/commands/hmi/on_system_request_notification.cc46
-rw-r--r--src/components/application_manager/src/commands/hmi/on_tts_language_change_notification.cc34
-rw-r--r--src/components/application_manager/src/commands/hmi/on_tts_reset_timeout_notification.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/on_tts_started_notification.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/on_tts_stopped_notification.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/on_ui_command_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_ui_keyboard_input_notification.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/on_ui_language_change_notification.cc35
-rw-r--r--src/components/application_manager/src/commands/hmi/on_ui_reset_timeout_notification.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/on_ui_touch_event_notification.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/on_update_device_list.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_acc_pedal_position_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_belt_status_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_body_information_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_device_status_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_driver_braking_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_engine_torque_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_external_temperature_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_fuel_level_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_fuel_level_state_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_gps_data_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_head_lamp_status_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_instant_fuel_consumption_notification.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_my_key_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_odometer_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_prndl_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_rpm_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_speed_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_steering_wheel_angle_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_tire_pressure_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_vehicle_data_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_vin_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vi_wiper_status_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/on_video_data_streaming_notification.cc8
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vr_command_notification.cc42
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vr_language_change_notification.cc41
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vr_started_notification.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/on_vr_stopped_notification.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/request_from_hmi.cc69
-rw-r--r--src/components/application_manager/src/commands/hmi/request_to_hmi.cc17
-rw-r--r--src/components/application_manager/src/commands/hmi/response_from_hmi.cc29
-rw-r--r--src/components/application_manager/src/commands/hmi/response_to_hmi.cc15
-rw-r--r--src/components/application_manager/src/commands/hmi/sdl_activate_app_request.cc239
-rw-r--r--src/components/application_manager/src/commands/hmi/sdl_activate_app_response.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/sdl_get_list_of_permissions_request.cc18
-rw-r--r--src/components/application_manager/src/commands/hmi/sdl_get_list_of_permissions_response.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/sdl_get_status_update_request.cc17
-rw-r--r--src/components/application_manager/src/commands/hmi/sdl_get_status_update_response.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/sdl_get_user_friendly_message_request.cc30
-rw-r--r--src/components/application_manager/src/commands/hmi/sdl_get_user_friendly_message_response.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/sdl_policy_update.cc5
-rw-r--r--src/components/application_manager/src/commands/hmi/sdl_policy_update_response.cc7
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_change_registration_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_change_registration_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_get_capabilities_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_get_capabilities_response.cc22
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_get_language_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_get_language_response.cc36
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_get_supported_languages_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_get_supported_languages_response.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_is_ready_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_is_ready_response.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_set_global_properties_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_set_global_properties_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_speak_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_speak_response.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_stop_speaking_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/tts_stop_speaking_response.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_add_command_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_add_command_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_add_submenu_request.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_add_submenu_response.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_alert_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_alert_response.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_change_registration_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_change_registration_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_delete_command_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_delete_command_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_delete_submenu_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_delete_submenu_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_end_audio_pass_thru_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_end_audio_pass_thru_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_get_capabilities_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_get_capabilities_response.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_get_language_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_get_language_response.cc36
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_get_supported_languages_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_get_supported_languages_response.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_is_ready_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_is_ready_response.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_perform_audio_pass_thru_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_perform_audio_pass_thru_response.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_perform_interaction_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_perform_interaction_response.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_scrollable_message_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_scrollable_message_response.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_set_app_icon_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_set_app_icon_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_set_display_layout_request.cc8
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_set_display_layout_response.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_set_global_properties_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_set_global_properties_response.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_set_icon_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_set_icon_response.cc57
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_set_media_clock_timer_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_set_media_clock_timer_response.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_show_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_show_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_slider_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/ui_slider_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/update_app_list_request.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/update_app_list_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/update_device_list_request.cc24
-rw-r--r--src/components/application_manager/src/commands/hmi/update_device_list_response.cc8
-rw-r--r--src/components/application_manager/src/commands/hmi/update_sdl_request.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/update_sdl_response.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_diagnostic_message_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_diagnostic_message_response.cc14
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_get_dtcs_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_get_dtcs_response.cc11
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_get_vehicle_data_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_get_vehicle_data_response.cc17
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_get_vehicle_type_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_get_vehicle_type_response.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_is_ready_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_is_ready_response.cc16
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_read_did_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_read_did_response.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_subscribe_vehicle_data_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_subscribe_vehicle_data_response.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_unsubscribe_vehicle_data_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/vi_unsubscribe_vehicle_data_response.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_add_command_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_add_command_response.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_change_registration_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_change_registration_response.cc12
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_delete_command_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_delete_command_response.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_get_capabilities_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_get_capabilities_response.cc14
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_get_language_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_get_language_response.cc37
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_get_supported_languages_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_get_supported_languages_response.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_is_ready_request.cc10
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_is_ready_response.cc13
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_perform_interaction_request.cc9
-rw-r--r--src/components/application_manager/src/commands/hmi/vr_perform_interaction_response.cc10
-rw-r--r--src/components/application_manager/src/commands/mobile/add_command_request.cc310
-rw-r--r--src/components/application_manager/src/commands/mobile/add_command_response.cc12
-rw-r--r--src/components/application_manager/src/commands/mobile/add_sub_menu_request.cc57
-rw-r--r--src/components/application_manager/src/commands/mobile/add_sub_menu_response.cc13
-rw-r--r--src/components/application_manager/src/commands/mobile/alert_maneuver_request.cc174
-rw-r--r--src/components/application_manager/src/commands/mobile/alert_maneuver_response.cc13
-rw-r--r--src/components/application_manager/src/commands/mobile/alert_request.cc285
-rw-r--r--src/components/application_manager/src/commands/mobile/alert_response.cc13
-rw-r--r--src/components/application_manager/src/commands/mobile/change_registration_request.cc226
-rw-r--r--src/components/application_manager/src/commands/mobile/change_registration_response.cc11
-rw-r--r--src/components/application_manager/src/commands/mobile/create_interaction_choice_set_request.cc308
-rw-r--r--src/components/application_manager/src/commands/mobile/create_interaction_choice_set_response.cc10
-rw-r--r--src/components/application_manager/src/commands/mobile/delete_command_request.cc173
-rw-r--r--src/components/application_manager/src/commands/mobile/delete_command_response.cc12
-rw-r--r--src/components/application_manager/src/commands/mobile/delete_file_request.cc47
-rw-r--r--src/components/application_manager/src/commands/mobile/delete_file_response.cc21
-rw-r--r--src/components/application_manager/src/commands/mobile/delete_interaction_choice_set_request.cc114
-rw-r--r--src/components/application_manager/src/commands/mobile/delete_interaction_choice_set_response.cc10
-rw-r--r--src/components/application_manager/src/commands/mobile/delete_sub_menu_request.cc66
-rw-r--r--src/components/application_manager/src/commands/mobile/delete_sub_menu_response.cc13
-rw-r--r--src/components/application_manager/src/commands/mobile/diagnostic_message_request.cc53
-rw-r--r--src/components/application_manager/src/commands/mobile/diagnostic_message_response.cc12
-rw-r--r--src/components/application_manager/src/commands/mobile/dial_number_request.cc20
-rw-r--r--src/components/application_manager/src/commands/mobile/dial_number_response.cc14
-rw-r--r--src/components/application_manager/src/commands/mobile/end_audio_pass_thru_request.cc15
-rw-r--r--src/components/application_manager/src/commands/mobile/end_audio_pass_thru_response.cc11
-rw-r--r--src/components/application_manager/src/commands/mobile/generic_response.cc4
-rw-r--r--src/components/application_manager/src/commands/mobile/get_dtcs_request.cc17
-rw-r--r--src/components/application_manager/src/commands/mobile/get_dtcs_response.cc12
-rw-r--r--src/components/application_manager/src/commands/mobile/get_vehicle_data_request.cc172
-rw-r--r--src/components/application_manager/src/commands/mobile/get_vehicle_data_response.cc13
-rw-r--r--src/components/application_manager/src/commands/mobile/get_way_points_request.cc59
-rw-r--r--src/components/application_manager/src/commands/mobile/get_way_points_response.cc22
-rw-r--r--src/components/application_manager/src/commands/mobile/list_files_request.cc58
-rw-r--r--src/components/application_manager/src/commands/mobile/list_files_response.cc13
-rw-r--r--src/components/application_manager/src/commands/mobile/on_app_interface_unregistered_notification.cc9
-rw-r--r--src/components/application_manager/src/commands/mobile/on_audio_pass_thru_notification.cc8
-rw-r--r--src/components/application_manager/src/commands/mobile/on_button_event_notification.cc60
-rw-r--r--src/components/application_manager/src/commands/mobile/on_button_press_notification.cc56
-rw-r--r--src/components/application_manager/src/commands/mobile/on_command_notification.cc22
-rw-r--r--src/components/application_manager/src/commands/mobile/on_driver_distraction_notification.cc10
-rw-r--r--src/components/application_manager/src/commands/mobile/on_hash_change_notification.cc18
-rw-r--r--src/components/application_manager/src/commands/mobile/on_hmi_status_notification.cc27
-rw-r--r--src/components/application_manager/src/commands/mobile/on_hmi_status_notification_from_mobile.cc54
-rw-r--r--src/components/application_manager/src/commands/mobile/on_keyboard_input_notification.cc31
-rw-r--r--src/components/application_manager/src/commands/mobile/on_language_change_notification.cc8
-rw-r--r--src/components/application_manager/src/commands/mobile/on_permissions_change_notification.cc8
-rw-r--r--src/components/application_manager/src/commands/mobile/on_system_request_notification.cc68
-rw-r--r--src/components/application_manager/src/commands/mobile/on_tbt_client_state_notification.cc12
-rw-r--r--src/components/application_manager/src/commands/mobile/on_touch_event_notification.cc12
-rw-r--r--src/components/application_manager/src/commands/mobile/on_vehicle_data_notification.cc50
-rw-r--r--src/components/application_manager/src/commands/mobile/on_way_point_change_notification.cc61
-rw-r--r--src/components/application_manager/src/commands/mobile/perform_audio_pass_thru_request.cc193
-rw-r--r--src/components/application_manager/src/commands/mobile/perform_audio_pass_thru_response.cc12
-rw-r--r--src/components/application_manager/src/commands/mobile/perform_interaction_request.cc557
-rw-r--r--src/components/application_manager/src/commands/mobile/perform_interaction_response.cc11
-rw-r--r--src/components/application_manager/src/commands/mobile/put_file_request.cc142
-rw-r--r--src/components/application_manager/src/commands/mobile/put_file_response.cc17
-rw-r--r--src/components/application_manager/src/commands/mobile/read_did_request.cc47
-rw-r--r--src/components/application_manager/src/commands/mobile/read_did_response.cc12
-rw-r--r--src/components/application_manager/src/commands/mobile/register_app_interface_request.cc592
-rw-r--r--src/components/application_manager/src/commands/mobile/register_app_interface_response.cc47
-rw-r--r--src/components/application_manager/src/commands/mobile/reset_global_properties_request.cc186
-rw-r--r--src/components/application_manager/src/commands/mobile/reset_global_properties_response.cc11
-rw-r--r--src/components/application_manager/src/commands/mobile/scrollable_message_request.cc59
-rw-r--r--src/components/application_manager/src/commands/mobile/scrollable_message_response.cc19
-rw-r--r--src/components/application_manager/src/commands/mobile/send_location_request.cc214
-rw-r--r--src/components/application_manager/src/commands/mobile/send_location_response.cc13
-rw-r--r--src/components/application_manager/src/commands/mobile/set_app_icon_request.cc133
-rw-r--r--src/components/application_manager/src/commands/mobile/set_app_icon_response.cc12
-rw-r--r--src/components/application_manager/src/commands/mobile/set_display_layout_request.cc35
-rw-r--r--src/components/application_manager/src/commands/mobile/set_display_layout_response.cc12
-rw-r--r--src/components/application_manager/src/commands/mobile/set_global_properties_request.cc514
-rw-r--r--src/components/application_manager/src/commands/mobile/set_global_properties_response.cc12
-rw-r--r--src/components/application_manager/src/commands/mobile/set_icon_request.cc44
-rw-r--r--src/components/application_manager/src/commands/mobile/set_icon_response.cc15
-rw-r--r--src/components/application_manager/src/commands/mobile/set_media_clock_timer_request.cc27
-rw-r--r--src/components/application_manager/src/commands/mobile/set_media_clock_timer_response.cc11
-rw-r--r--src/components/application_manager/src/commands/mobile/show_constant_tbt_request.cc101
-rw-r--r--src/components/application_manager/src/commands/mobile/show_constant_tbt_response.cc13
-rw-r--r--src/components/application_manager/src/commands/mobile/show_request.cc136
-rw-r--r--src/components/application_manager/src/commands/mobile/show_response.cc13
-rw-r--r--src/components/application_manager/src/commands/mobile/slider_request.cc92
-rw-r--r--src/components/application_manager/src/commands/mobile/slider_response.cc12
-rw-r--r--src/components/application_manager/src/commands/mobile/speak_request.cc64
-rw-r--r--src/components/application_manager/src/commands/mobile/speak_response.cc13
-rw-r--r--src/components/application_manager/src/commands/mobile/subscribe_button_request.cc42
-rw-r--r--src/components/application_manager/src/commands/mobile/subscribe_button_response.cc8
-rw-r--r--src/components/application_manager/src/commands/mobile/subscribe_vehicle_data_request.cc337
-rw-r--r--src/components/application_manager/src/commands/mobile/subscribe_vehicle_data_response.cc12
-rw-r--r--src/components/application_manager/src/commands/mobile/subscribe_way_points_request.cc72
-rw-r--r--src/components/application_manager/src/commands/mobile/subscribe_way_points_response.cc22
-rw-r--r--src/components/application_manager/src/commands/mobile/system_request.cc231
-rw-r--r--src/components/application_manager/src/commands/mobile/system_response.cc12
-rw-r--r--src/components/application_manager/src/commands/mobile/unregister_app_interface_request.cc18
-rw-r--r--src/components/application_manager/src/commands/mobile/unsubscribe_button_request.cc23
-rw-r--r--src/components/application_manager/src/commands/mobile/unsubscribe_button_response.cc9
-rw-r--r--src/components/application_manager/src/commands/mobile/unsubscribe_vehicle_data_request.cc335
-rw-r--r--src/components/application_manager/src/commands/mobile/unsubscribe_vehicle_data_response.cc8
-rw-r--r--src/components/application_manager/src/commands/mobile/unsubscribe_way_points_request.cc65
-rw-r--r--src/components/application_manager/src/commands/mobile/unsubscribe_way_points_response.cc22
-rw-r--r--src/components/application_manager/src/commands/mobile/update_turn_list_request.cc93
-rw-r--r--src/components/application_manager/src/commands/mobile/update_turn_list_response.cc13
-rw-r--r--src/components/application_manager/src/commands/pending.cc8
-rw-r--r--src/components/application_manager/src/event_engine/event.cc16
-rw-r--r--src/components/application_manager/src/event_engine/event_dispatcher.cc138
-rw-r--r--src/components/application_manager/src/event_engine/event_dispatcher_impl.cc126
-rw-r--r--src/components/application_manager/src/event_engine/event_observer.cc21
-rw-r--r--src/components/application_manager/src/hmi_capabilities.cc722
-rw-r--r--src/components/application_manager/src/hmi_command_factory.cc1720
-rw-r--r--src/components/application_manager/src/hmi_language_handler.cc352
-rw-r--r--src/components/application_manager/src/hmi_state.cc199
-rw-r--r--src/components/application_manager/src/message.cc34
-rw-r--r--src/components/application_manager/src/message_helper.cc2620
-rw-r--r--src/components/application_manager/src/message_helper/message_helper.cc2501
-rw-r--r--src/components/application_manager/src/mobile_command_factory.cc499
-rw-r--r--src/components/application_manager/src/mobile_message_handler.cc152
-rw-r--r--src/components/application_manager/src/policies/delegates/app_permission_delegate.cc23
-rw-r--r--src/components/application_manager/src/policies/delegates/statistics_delegate.cc120
-rw-r--r--src/components/application_manager/src/policies/policy_event_observer.cc38
-rw-r--r--src/components/application_manager/src/policies/policy_handler.cc919
-rw-r--r--src/components/application_manager/src/policies/policy_retry_sequence.cc7
-rw-r--r--src/components/application_manager/src/policies/pt_exchange_handler_ext.cc26
-rw-r--r--src/components/application_manager/src/policies/pt_exchange_handler_impl.cc8
-rw-r--r--src/components/application_manager/src/request_controller.cc342
-rw-r--r--src/components/application_manager/src/request_info.cc144
-rw-r--r--src/components/application_manager/src/resume_ctrl.cpp1311
-rw-r--r--src/components/application_manager/src/resumption/resume_ctrl.cc795
-rw-r--r--src/components/application_manager/src/resumption/resumption_data.cc218
-rw-r--r--src/components/application_manager/src/resumption/resumption_data_db.cc2810
-rw-r--r--src/components/application_manager/src/resumption/resumption_data_json.cc487
-rw-r--r--src/components/application_manager/src/resumption/resumption_sql_queries.cc981
-rw-r--r--src/components/application_manager/src/smart_object_keys.cc405
-rw-r--r--src/components/application_manager/src/state_context.cc62
-rw-r--r--src/components/application_manager/src/state_controller.cc469
-rw-r--r--src/components/application_manager/src/state_controller_impl.cc966
-rw-r--r--src/components/application_manager/src/usage_statistics.cc67
-rw-r--r--src/components/application_manager/test/CMakeLists.txt186
-rw-r--r--src/components/application_manager/test/application_impl_test.cc732
-rw-r--r--src/components/application_manager/test/application_state_test.cc268
-rw-r--r--src/components/application_manager/test/command_impl_test.cc76
-rw-r--r--src/components/application_manager/test/commands/mobile/subscribe_way_points_request_test.cc124
-rw-r--r--src/components/application_manager/test/commands/mobile/unsubscribe_way_points_request_test.cc99
-rw-r--r--src/components/application_manager/test/event_engine_test.cc183
-rw-r--r--src/components/application_manager/test/hmi_capabilities.json466
-rw-r--r--src/components/application_manager/test/hmi_capabilities_test.cc527
-rw-r--r--src/components/application_manager/test/include/application_manager/application_manager_mock.h112
-rw-r--r--src/components/application_manager/test/include/application_manager/application_mock.h280
-rw-r--r--src/components/application_manager/test/include/application_manager/event_observer_mock.h58
-rw-r--r--src/components/application_manager/test/include/application_manager/hmi_capabilities_for_testing.h62
-rw-r--r--src/components/application_manager/test/include/application_manager/mock_application.h285
-rw-r--r--src/components/application_manager/test/include/application_manager/mock_application_manager.h248
-rw-r--r--src/components/application_manager/test/include/application_manager/mock_event_dispatcher.h68
-rw-r--r--src/components/application_manager/test/include/application_manager/mock_message_helper.h174
-rw-r--r--src/components/application_manager/test/include/application_manager/mock_resumption_data.h95
-rw-r--r--src/components/application_manager/test/include/application_manager/mock_statistics_manager.h65
-rw-r--r--src/components/application_manager/test/include/application_manager/mock_telemetry_observer.h53
-rw-r--r--src/components/application_manager/test/include/application_manager/policy_handler_interface_mock.h203
-rw-r--r--src/components/application_manager/test/include/application_manager/resumption_data_mock.h94
-rw-r--r--src/components/application_manager/test/include/application_manager/resumption_data_test.h156
-rw-r--r--src/components/application_manager/test/include/application_manager/statistics_manager_mock.h59
-rw-r--r--src/components/application_manager/test/include/application_manager/test_resumption_data_db.h62
-rwxr-xr-xsrc/components/application_manager/test/message_helper/CMakeLists.txt61
-rwxr-xr-xsrc/components/application_manager/test/message_helper/CMakeLists.txt.user189
-rw-r--r--src/components/application_manager/test/message_helper/message_helper_test.cc906
-rw-r--r--src/components/application_manager/test/mobile_message_handler_test.cc311
-rw-r--r--src/components/application_manager/test/mobile_message_handler_v1_test.cc126
l---------src/components/application_manager/test/mock/include/application_manager/application.h1
l---------src/components/application_manager/test/mock/include/application_manager/application_data_impl.h1
l---------src/components/application_manager/test/mock/include/application_manager/application_impl.h1
l---------src/components/application_manager/test/mock/include/application_manager/application_manager.h1
-rw-r--r--src/components/application_manager/test/mock/include/application_manager/application_manager_impl.h373
l---------src/components/application_manager/test/mock/include/application_manager/commands/command.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/command_impl.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/command_notification_from_mobile_impl.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/command_notification_impl.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/command_request_impl.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/command_response_impl.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/activate_app_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/activate_app_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/add_statistics_info_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_all_apps_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_all_apps_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_app_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_app_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/basic_communication_on_awake_sdl.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/basic_communication_system_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/basic_communication_system_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/button_get_capabilities_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/button_get_capabilities_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/close_popup_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/close_popup_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_system_info_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_system_info_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_urls.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_urls_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/mixing_audio_supported_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/mixing_audio_supported_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_alert_maneuver_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_alert_maneuver_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_start_stream_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_start_stream_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_stop_stream_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_stop_stream_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_is_ready_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_is_ready_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_send_location_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_send_location_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_show_constant_tbt_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_show_constant_tbt_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_start_stream_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_start_stream_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_stop_stream_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_stop_stream_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_update_turn_list_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_update_turn_list_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/notification_from_hmi.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/notification_to_hmi.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_allow_sdl_functionality_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_activated_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_deactivated_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_permission_changed_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_permission_consent_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_registered_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_unregistered_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_button_event_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_button_press_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_button_subscription_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_device_chosen_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_device_state_changed_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_driver_distraction_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_emergency_event_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_exit_all_applications_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_exit_application_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_file_removed_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_find_applications.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ignition_cycle_over_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_navi_tbt_client_state_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_phone_call_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_play_tone_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_policy_update.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_put_file_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ready_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_received_policy_update.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_record_start_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_resume_audio_source_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_sdl_close_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_sdl_consent_needed_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_sdl_persistence_complete_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_start_device_discovery.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_status_update_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_context_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_error_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_info_changed_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_request_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_language_change_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_reset_timeout_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_started_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_stopped_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_command_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_keyboard_input_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_language_change_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_reset_timeout_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_touch_event_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_update_device_list.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_acc_pedal_position_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_belt_status_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_body_information_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_device_status_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_driver_braking_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_engine_torque_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_external_temperature_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_fuel_level_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_fuel_level_state_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_gps_data_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_head_lamp_status_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_instant_fuel_consumption_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_my_key_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_odometer_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_prndl_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_rpm_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_speed_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_steering_wheel_angle_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_tire_pressure_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_vehicle_data_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_vin_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_wiper_status_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_command_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_language_change_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_started_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_stopped_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/request_from_hmi.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/request_to_hmi.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/response_from_hmi.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/response_to_hmi.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_activate_app_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_activate_app_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_list_of_permissions_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_list_of_permissions_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_status_update_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_status_update_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_user_friendly_message_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_user_friendly_message_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_policy_update.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_policy_update_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_change_registration_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_change_registration_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_capabilities_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_capabilities_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_language_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_language_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_supported_languages_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_supported_languages_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_is_ready_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_is_ready_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_set_global_properties_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_set_global_properties_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_speak_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_speak_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_stop_speaking_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_stop_speaking_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_command_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_command_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_submenu_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_submenu_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_alert_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_alert_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_change_registration_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_change_registration_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_command_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_command_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_submenu_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_submenu_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_end_audio_pass_thru_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_end_audio_pass_thru_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_capabilities_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_capabilities_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_language_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_language_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_supported_languages_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_supported_languages_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_is_ready_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_is_ready_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_interaction_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_interaction_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_scrollable_message_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_scrollable_message_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_app_icon_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_app_icon_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_display_layout_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_display_layout_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_global_properties_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_global_properties_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_icon_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_icon_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_media_clock_timer_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_media_clock_timer_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_show_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_show_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_slider_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_slider_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_app_list_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_app_list_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_device_list_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_device_list_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_sdl_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_sdl_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_diagnostic_message_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_diagnostic_message_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_dtcs_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_dtcs_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_request_template.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_response_template.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_type_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_type_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_is_ready_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_is_ready_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_read_did_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_read_did_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request_template.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response_template.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request_template.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response_template.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_add_command_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_add_command_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_change_registration_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_change_registration_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_delete_command_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_delete_command_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_capabilities_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_capabilities_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_language_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_language_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_supported_languages_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_supported_languages_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_is_ready_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_is_ready_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_perform_interaction_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_perform_interaction_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_command_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_command_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_sub_menu_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_sub_menu_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_maneuver_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_maneuver_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/change_registration_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/change_registration_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/create_interaction_choice_set_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/create_interaction_choice_set_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_command_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_command_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_file_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_file_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_interaction_choice_set_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_interaction_choice_set_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_sub_menu_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_sub_menu_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/diagnostic_message_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/diagnostic_message_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/dial_number_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/end_audio_pass_thru_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/end_audio_pass_thru_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/generic_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_dtcs_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_dtcs_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_vehicle_data_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_vehicle_data_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/list_files_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/list_files_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_app_interface_unregistered_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_audio_pass_thru_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_button_event_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_button_press_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_command_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_driver_distraction_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_hash_change_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_hmi_status_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_hmi_status_notification_from_mobile.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_keyboard_input_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_language_change_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_permissions_change_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_system_request_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_tbt_client_state_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_touch_event_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_vehicle_data_notification.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_audio_pass_thru_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_audio_pass_thru_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_interaction_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_interaction_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/put_file_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/put_file_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/read_did_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/read_did_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/register_app_interface_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/register_app_interface_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/reset_global_properties_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/reset_global_properties_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/scrollable_message_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/scrollable_message_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/send_location_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/send_location_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_app_icon_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_app_icon_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_display_layout_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_display_layout_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_global_properties_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_global_properties_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_icon_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_icon_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_media_clock_timer_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_media_clock_timer_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_constant_tbt_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_constant_tbt_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/slider_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/slider_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/speak_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/speak_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_button_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_button_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_vehicle_data_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_vehicle_data_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/system_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/system_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/unregister_app_interface_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/unregister_app_interface_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_button_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_button_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_vehicle_data_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_vehicle_data_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/update_turn_list_request.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/mobile/update_turn_list_response.h1
l---------src/components/application_manager/test/mock/include/application_manager/commands/pending.h1
l---------src/components/application_manager/test/mock/include/application_manager/event_engine/event.h1
l---------src/components/application_manager/test/mock/include/application_manager/event_engine/event_dispatcher.h1
l---------src/components/application_manager/test/mock/include/application_manager/event_engine/event_observer.h1
l---------src/components/application_manager/test/mock/include/application_manager/hmi_capabilities.h1
l---------src/components/application_manager/test/mock/include/application_manager/hmi_command_factory.h1
l---------src/components/application_manager/test/mock/include/application_manager/hmi_state.h1
l---------src/components/application_manager/test/mock/include/application_manager/message.h1
l---------src/components/application_manager/test/mock/include/application_manager/message_helper.h1
l---------src/components/application_manager/test/mock/include/application_manager/mobile_command_factory.h1
l---------src/components/application_manager/test/mock/include/application_manager/mobile_message_handler.h1
l---------src/components/application_manager/test/mock/include/application_manager/policies/delegates/app_permission_delegate.h1
l---------src/components/application_manager/test/mock/include/application_manager/policies/delegates/statistics_delegate.h1
l---------src/components/application_manager/test/mock/include/application_manager/policies/policy_event_observer.h1
l---------src/components/application_manager/test/mock/include/application_manager/policies/policy_handler.h1
l---------src/components/application_manager/test/mock/include/application_manager/policies/policy_handler_observer.h1
l---------src/components/application_manager/test/mock/include/application_manager/policies/policy_retry_sequence.h1
l---------src/components/application_manager/test/mock/include/application_manager/policies/pt_exchange_handler.h1
l---------src/components/application_manager/test/mock/include/application_manager/policies/pt_exchange_handler_ext.h1
l---------src/components/application_manager/test/mock/include/application_manager/policies/pt_exchange_handler_impl.h1
l---------src/components/application_manager/test/mock/include/application_manager/request_controller.h1
l---------src/components/application_manager/test/mock/include/application_manager/request_info.h1
l---------src/components/application_manager/test/mock/include/application_manager/resume_ctrl.h1
l---------src/components/application_manager/test/mock/include/application_manager/smart_object_keys.h1
l---------src/components/application_manager/test/mock/include/application_manager/state_context.h1
l---------src/components/application_manager/test/mock/include/application_manager/state_controller.h1
l---------src/components/application_manager/test/mock/include/application_manager/time_metric_observer.h1
l---------src/components/application_manager/test/mock/include/application_manager/usage_statistics.h1
l---------src/components/application_manager/test/mock/include/application_manager/vehicle_info_data.h1
-rw-r--r--src/components/application_manager/test/mock/src/application_manager_impl.cc33
-rw-r--r--src/components/application_manager/test/mock_message_helper.cc309
-rw-r--r--src/components/application_manager/test/policy_event_observer_test.cc140
-rw-r--r--src/components/application_manager/test/policy_handler_test.cc1478
-rw-r--r--src/components/application_manager/test/request_controller/request_controller_test.cc186
-rw-r--r--src/components/application_manager/test/request_info_test.cc537
-rw-r--r--src/components/application_manager/test/resumption/include/application_mock.h266
-rw-r--r--src/components/application_manager/test/resumption/include/resumption_data_mock.h86
-rw-r--r--src/components/application_manager/test/resumption/include/resumption_data_test.h133
-rw-r--r--src/components/application_manager/test/resumption/resume_ctrl_test.cc676
-rw-r--r--src/components/application_manager/test/resumption/resumption_data_db_test.cc134
-rw-r--r--src/components/application_manager/test/resumption/resumption_data_json_test.cc135
-rw-r--r--src/components/application_manager/test/resumption/resumption_data_test.cc67
-rw-r--r--src/components/application_manager/test/resumption_sql_queries_test.cc3090
-rw-r--r--src/components/application_manager/test/sdl_preloaded_pt.json1944
-rw-r--r--src/components/application_manager/test/sdl_pt_update.json1722
-rw-r--r--src/components/application_manager/test/smartDeviceLink_test.ini39
-rw-r--r--src/components/application_manager/test/smartDeviceLink_test2.ini28
-rw-r--r--src/components/application_manager/test/state_controller/CMakeLists.txt6
-rw-r--r--src/components/application_manager/test/state_controller/include/application_manager_mock.h80
-rw-r--r--src/components/application_manager/test/state_controller/include/application_mock.h252
-rw-r--r--src/components/application_manager/test/state_controller/include/state_controller_mock.h60
-rw-r--r--src/components/application_manager/test/state_controller/include/statistics_manager_mock.h52
-rw-r--r--src/components/application_manager/test/state_controller/state_controller_test.cc2026
-rw-r--r--src/components/application_manager/test/usage_statistics_test.cc174
-rw-r--r--src/components/application_manager/test/zero_request_amount_test.cc169
-rw-r--r--src/components/config_profile/CMakeLists.txt2
-rw-r--r--src/components/config_profile/include/config_profile/ini_file.h37
-rw-r--r--src/components/config_profile/include/config_profile/profile.h1361
-rw-r--r--src/components/config_profile/src/ini_file.cc142
-rw-r--r--src/components/config_profile/src/profile.cc1029
-rw-r--r--src/components/config_profile/test/CMakeLists.txt4
-rw-r--r--src/components/config_profile/test/ini_file_test.cc279
-rw-r--r--src/components/config_profile/test/profile_test.cc790
-rw-r--r--src/components/connection_handler/CMakeLists.txt4
-rw-r--r--src/components/connection_handler/include/connection_handler/connection.h77
-rw-r--r--src/components/connection_handler/include/connection_handler/connection_handler.h87
-rw-r--r--src/components/connection_handler/include/connection_handler/connection_handler_impl.h294
-rw-r--r--src/components/connection_handler/include/connection_handler/connection_handler_observer.h26
-rw-r--r--src/components/connection_handler/include/connection_handler/device.h6
-rw-r--r--src/components/connection_handler/include/connection_handler/devices_discovery_starter.h5
-rw-r--r--src/components/connection_handler/include/connection_handler/heartbeat_monitor.h55
-rw-r--r--src/components/connection_handler/src/connection.cc128
-rw-r--r--src/components/connection_handler/src/connection_handler_impl.cc569
-rw-r--r--src/components/connection_handler/src/device.cc24
-rw-r--r--src/components/connection_handler/src/heartbeat_monitor.cc104
-rw-r--r--src/components/connection_handler/test/CMakeLists.txt12
-rw-r--r--src/components/connection_handler/test/connection_handler_impl_test.cc906
-rw-r--r--src/components/connection_handler/test/connection_test.cc328
-rw-r--r--src/components/connection_handler/test/device_test.cc4
-rw-r--r--src/components/connection_handler/test/heart_beat_monitor_test.cc126
-rw-r--r--src/components/connection_handler/test/include/connection_handler/connection_handler_observer_mock.h72
-rw-r--r--src/components/connection_handler/test/include/connection_handler_observer_mock.h70
-rw-r--r--src/components/dbus/include/dbus/dbus_adapter.h25
-rw-r--r--src/components/dbus/include/dbus/dbus_message.h35
-rw-r--r--src/components/dbus/include/dbus/dbus_message_inl.h6
-rw-r--r--src/components/dbus/include/dbus/message_descriptions.h6
-rw-r--r--src/components/dbus/include/dbus/schema.h2
-rw-r--r--src/components/dbus/src/dbus_adapter.cc207
-rw-r--r--src/components/dbus/src/dbus_message.cc82
-rw-r--r--src/components/dbus/src/dbus_message_controller.cc26
-rw-r--r--src/components/dbus/src/schema.cc38
-rw-r--r--src/components/dbus/test/test_dbus_adapter.cc8
-rw-r--r--src/components/dbus/test/test_dbus_message_controller.cc17
-rw-r--r--src/components/dbus/test/test_schema.cc5
-rw-r--r--src/components/formatters/CMakeLists.txt9
-rw-r--r--src/components/formatters/include/formatters/CFormatterJsonBase.h119
-rw-r--r--src/components/formatters/include/formatters/CFormatterJsonBase.hpp122
-rw-r--r--src/components/formatters/include/formatters/CFormatterJsonSDLRPCv1.h239
-rw-r--r--src/components/formatters/include/formatters/CFormatterJsonSDLRPCv1.hpp235
-rw-r--r--src/components/formatters/include/formatters/CFormatterJsonSDLRPCv2.h187
-rw-r--r--src/components/formatters/include/formatters/CFormatterJsonSDLRPCv2.hpp176
-rw-r--r--src/components/formatters/include/formatters/CSmartFactory.h410
-rw-r--r--src/components/formatters/include/formatters/CSmartFactory.hpp428
-rw-r--r--src/components/formatters/include/formatters/formatter_json_rpc.h736
-rw-r--r--src/components/formatters/include/formatters/generic_json_formatter.h14
-rw-r--r--src/components/formatters/include/formatters/meta_formatter.h18
-rw-r--r--src/components/formatters/src/CFormatterJsonBase.cc123
-rw-r--r--src/components/formatters/src/CFormatterJsonBase.cpp118
-rw-r--r--src/components/formatters/src/CFormatterJsonSDLRPCv1.cc165
-rw-r--r--src/components/formatters/src/CFormatterJsonSDLRPCv1.cpp157
-rw-r--r--src/components/formatters/src/CFormatterJsonSDLRPCv2.cc108
-rw-r--r--src/components/formatters/src/CFormatterJsonSDLRPCv2.cpp106
-rw-r--r--src/components/formatters/src/CSmartFactory.cc52
-rw-r--r--src/components/formatters/src/CSmartFactory.cpp46
-rw-r--r--src/components/formatters/src/formatter_json_rpc.cc87
-rw-r--r--src/components/formatters/src/generic_json_formatter.cc6
-rw-r--r--src/components/formatters/src/meta_formatter.cc5
-rw-r--r--src/components/formatters/test/CFormatterJsonBase_test.cc62
-rw-r--r--src/components/formatters/test/CMakeLists.txt2
-rw-r--r--src/components/formatters/test/CSmartFactory_test.cc112
-rw-r--r--src/components/formatters/test/cFormatterJsonSDLRPCv1_test.cc34
-rw-r--r--src/components/formatters/test/cFormatterJsonSDLRPCv2_test.cc48
-rw-r--r--src/components/formatters/test/formatter_json_rpc_test.cc333
-rw-r--r--src/components/formatters/test/generic_json_formatter_test.cc74
-rw-r--r--src/components/formatters/test/include/SmartFactoryTestHelper.h167
-rw-r--r--src/components/formatters/test/include/create_smartSchema.h92
-rw-r--r--src/components/formatters/test/include/formatters/SmartFactoryTestHelper.h160
-rw-r--r--src/components/formatters/test/include/formatters/create_smartSchema.h80
-rw-r--r--src/components/formatters/test/include/formatters/meta_formatter_test_helper.h82
-rw-r--r--src/components/formatters/test/include/meta_formatter_test_helper.h83
-rw-r--r--src/components/formatters/test/meta_formatter_test.cc207
-rw-r--r--src/components/formatters/test/src/SmartFactoryTestHelper.cc455
-rw-r--r--src/components/formatters/test/src/create_smartSchema.cc359
-rw-r--r--src/components/formatters/test/src/meta_formatter_test_helper.cc57
-rw-r--r--src/components/hmi_message_handler/CMakeLists.txt9
-rw-r--r--src/components/hmi_message_handler/include/hmi_message_handler/dbus_message_adapter.h13
-rw-r--r--src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_adapter.h29
-rw-r--r--src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_adapter_impl.h70
-rw-r--r--src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_handler.h9
-rw-r--r--src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_handler_impl.h56
-rw-r--r--src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_sender.h3
-rw-r--r--src/components/hmi_message_handler/include/hmi_message_handler/messagebroker_adapter.h16
-rw-r--r--src/components/hmi_message_handler/include/hmi_message_handler/mqueue_adapter.h4
-rw-r--r--src/components/hmi_message_handler/src/dbus_message_adapter.cc80
-rw-r--r--src/components/hmi_message_handler/src/hmi_message_adapter.cc44
-rw-r--r--src/components/hmi_message_handler/src/hmi_message_adapter_impl.cc43
-rw-r--r--src/components/hmi_message_handler/src/hmi_message_handler_impl.cc67
-rw-r--r--src/components/hmi_message_handler/src/messagebroker_adapter.cc57
-rw-r--r--src/components/hmi_message_handler/src/mqueue_adapter.cc36
-rw-r--r--src/components/hmi_message_handler/test/CMakeLists.txt12
-rw-r--r--src/components/hmi_message_handler/test/dbus_message_adapter_test.cc17
-rw-r--r--src/components/hmi_message_handler/test/hmi_message_adapter_test.cc81
-rw-r--r--src/components/hmi_message_handler/test/hmi_message_handler_impl_test.cc136
-rw-r--r--src/components/hmi_message_handler/test/include/hmi_message_handler/mock_dbus_message_controller.h14
-rw-r--r--src/components/hmi_message_handler/test/include/hmi_message_handler/mock_hmi_message_adapter_impl.h60
-rw-r--r--src/components/hmi_message_handler/test/include/hmi_message_handler/mock_hmi_message_observer.h57
-rw-r--r--src/components/hmi_message_handler/test/include/mock_subscriber.h62
-rw-r--r--src/components/hmi_message_handler/test/mock_subscriber.cc23
-rw-r--r--src/components/hmi_message_handler/test/mqueue_adapter_test.cc8
-rw-r--r--src/components/include/application_manager/application_manager_settings.h99
-rw-r--r--src/components/include/application_manager/policies/policy_handler_interface.h390
-rw-r--r--src/components/include/application_manager/request_controller_settings.h48
-rw-r--r--src/components/include/application_manager/state_controller.h96
-rw-r--r--src/components/include/connection_handler/connection_handler_settings.h56
-rw-r--r--src/components/include/hmi_message_handler/hmi_message_handler_settings.h50
-rw-r--r--src/components/include/media_manager/media_manager_settings.h63
-rw-r--r--src/components/include/policy/policy_settings.h42
-rw-r--r--src/components/include/policy/policy_types.h318
-rw-r--r--src/components/include/policy/usage_statistics/statistics_manager.h79
-rw-r--r--src/components/include/protocol/common.h11
-rw-r--r--src/components/include/protocol/message_priority.h5
-rw-r--r--src/components/include/protocol/raw_message.h14
-rw-r--r--src/components/include/protocol/rpc_type.h8
-rw-r--r--src/components/include/protocol/service_type.h8
-rw-r--r--src/components/include/protocol_handler/protocol_handler.h16
-rw-r--r--src/components/include/protocol_handler/protocol_handler_settings.h47
-rw-r--r--src/components/include/protocol_handler/protocol_observer.h6
-rw-r--r--src/components/include/protocol_handler/session_observer.h105
-rw-r--r--src/components/include/security_manager/crypto_manager.h48
-rw-r--r--src/components/include/security_manager/security_manager.h60
-rw-r--r--src/components/include/security_manager/security_manager_listener.h9
-rw-r--r--src/components/include/security_manager/security_manager_settings.h58
-rw-r--r--src/components/include/security_manager/security_query.h194
-rw-r--r--src/components/include/security_manager/ssl_context.h57
-rw-r--r--src/components/include/telemetry_monitor/telemetry_observable.h43
-rw-r--r--src/components/include/test/application_manager/mock_application_manager_settings.h122
-rw-r--r--src/components/include/test/application_manager/mock_request_controller_settings.h63
-rw-r--r--src/components/include/test/application_manager/mock_state_controller.h99
-rw-r--r--src/components/include/test/application_manager/policies/mock_policy_handler_interface.h212
-rw-r--r--src/components/include/test/application_manager/policies/mock_policy_handler_observer.h57
-rw-r--r--src/components/include/test/connection_handler/mock_connection_handler.h103
-rw-r--r--src/components/include/test/connection_handler/mock_connection_handler_settings.h56
-rw-r--r--src/components/include/test/hmi_message_handler/mock_hmi_message_handler.h54
-rw-r--r--src/components/include/test/hmi_message_handler/mock_hmi_message_handler_settings.h52
-rw-r--r--src/components/include/test/media_manager/mock_media_manager_settings.h63
-rw-r--r--src/components/include/test/policy/mock_policy_manager.h185
-rw-r--r--src/components/include/test/policy/mock_policy_settings.h58
-rw-r--r--src/components/include/test/policy/mock_statistics_manager.h63
-rw-r--r--src/components/include/test/policy/usage_statistics/mock_app_stopwatch.h54
-rw-r--r--src/components/include/test/policy/usage_statistics/mock_statistics_manager.h63
-rw-r--r--src/components/include/test/protocol_handler/mock_protocol_handler.h70
-rw-r--r--src/components/include/test/protocol_handler/mock_protocol_handler_settings.h65
-rw-r--r--src/components/include/test/protocol_handler/mock_session_observer.h111
-rw-r--r--src/components/include/test/security_manager/mock_crypto_manager.h61
-rw-r--r--src/components/include/test/security_manager/mock_security_manager.h181
-rw-r--r--src/components/include/test/security_manager/mock_security_manager_listener.h56
-rw-r--r--src/components/include/test/security_manager/mock_security_manager_settings.h60
-rw-r--r--src/components/include/test/security_manager/mock_ssl_context.h76
-rw-r--r--src/components/include/test/telemetry_monitor/mock_telemetry_observable.h55
-rw-r--r--src/components/include/test/telemetry_monitor/mock_telemetry_observer.h54
-rw-r--r--src/components/include/test/transport_manager/mock_transport_manager.h81
-rw-r--r--src/components/include/test/transport_manager/mock_transport_manager_mme_settings.h62
-rw-r--r--src/components/include/test/transport_manager/mock_transport_manager_settings.h68
-rw-r--r--src/components/include/transport_manager/error.h22
-rw-r--r--src/components/include/transport_manager/info.h31
-rw-r--r--src/components/include/transport_manager/transport_adapter/device.h13
-rw-r--r--src/components/include/transport_manager/transport_adapter/transport_adapter.h44
-rw-r--r--src/components/include/transport_manager/transport_adapter/transport_adapter_event.h17
-rw-r--r--src/components/include/transport_manager/transport_manager.h21
-rw-r--r--src/components/include/transport_manager/transport_manager_listener.h43
-rw-r--r--src/components/include/transport_manager/transport_manager_listener_empty.h83
-rw-r--r--src/components/include/transport_manager/transport_manager_mme_settings.h65
-rw-r--r--src/components/include/transport_manager/transport_manager_settings.h56
-rw-r--r--src/components/include/utils/atomic_object.h112
-rw-r--r--src/components/include/utils/auto_trace.h6
-rw-r--r--src/components/include/utils/conditional_variable.h3
-rw-r--r--src/components/include/utils/custom_string.h218
-rw-r--r--src/components/include/utils/data_accessor.h18
-rw-r--r--src/components/include/utils/date_time.h30
-rw-r--r--src/components/include/utils/lock.h49
-rw-r--r--src/components/include/utils/logger.h220
-rw-r--r--src/components/include/utils/macro.h77
-rw-r--r--src/components/include/utils/make_shared.h143
-rw-r--r--src/components/include/utils/message_queue.h222
-rw-r--r--src/components/include/utils/messagemeter.h17
-rw-r--r--src/components/include/utils/prioritized_queue.h23
-rw-r--r--src/components/include/utils/push_log.h21
-rw-r--r--src/components/include/utils/rwlock.h48
-rw-r--r--src/components/include/utils/scope_guard.h326
-rw-r--r--src/components/include/utils/shared_ptr.h409
-rw-r--r--src/components/include/utils/threads/async_runner.h123
-rw-r--r--src/components/include/utils/threads/message_loop_thread.h62
-rw-r--r--src/components/include/utils/threads/thread.h14
-rw-r--r--src/components/include/utils/threads/thread_delegate.h13
-rw-r--r--src/components/include/utils/threads/thread_options.h7
-rw-r--r--src/components/include/utils/timer_thread.h449
-rw-r--r--src/components/interfaces/HMI_API.xml325
-rw-r--r--src/components/interfaces/MOBILE_API.xml242
-rw-r--r--src/components/interfaces/QT_HMI_API.xml236
-rw-r--r--src/components/media_manager/CMakeLists.txt21
-rw-r--r--src/components/media_manager/include/media_manager/audio/a2dp_source_player_adapter.h38
-rw-r--r--src/components/media_manager/include/media_manager/audio/audio_stream_sender_thread.h118
-rw-r--r--src/components/media_manager/include/media_manager/audio/file_audio_streamer_adapter.h49
-rw-r--r--src/components/media_manager/include/media_manager/audio/from_mic_recorder_adapter.h33
-rw-r--r--src/components/media_manager/include/media_manager/audio/from_mic_recorder_listener.h37
-rw-r--r--src/components/media_manager/include/media_manager/audio/from_mic_to_file_recorder_thread.h65
-rw-r--r--src/components/media_manager/include/media_manager/audio/pipe_audio_streamer_adapter.h14
-rw-r--r--src/components/media_manager/include/media_manager/audio/socket_audio_streamer_adapter.h15
-rw-r--r--src/components/media_manager/include/media_manager/file_streamer_adapter.h71
-rw-r--r--src/components/media_manager/include/media_manager/media_adapter.h8
-rw-r--r--src/components/media_manager/include/media_manager/media_adapter_impl.h20
-rw-r--r--src/components/media_manager/include/media_manager/media_adapter_listener.h19
-rw-r--r--src/components/media_manager/include/media_manager/media_manager.h35
-rw-r--r--src/components/media_manager/include/media_manager/media_manager_impl.h86
-rw-r--r--src/components/media_manager/include/media_manager/pipe_streamer_adapter.h97
-rw-r--r--src/components/media_manager/include/media_manager/socket_streamer_adapter.h125
-rw-r--r--src/components/media_manager/include/media_manager/streamer_adapter.h101
-rw-r--r--src/components/media_manager/include/media_manager/streamer_listener.h31
-rw-r--r--src/components/media_manager/include/media_manager/video/file_video_streamer_adapter.h49
-rw-r--r--src/components/media_manager/include/media_manager/video/pipe_video_streamer_adapter.h14
-rw-r--r--src/components/media_manager/include/media_manager/video/socket_video_streamer_adapter.h17
-rw-r--r--src/components/media_manager/include/media_manager/video/video_stream_to_file_adapter.h113
-rw-r--r--src/components/media_manager/src/audio/a2dp_source_player_adapter.cc122
-rw-r--r--src/components/media_manager/src/audio/audio_stream_sender_thread.cc38
-rw-r--r--src/components/media_manager/src/audio/file_audio_streamer_adapter.cc43
-rw-r--r--src/components/media_manager/src/audio/from_mic_recorder_adapter.cc36
-rw-r--r--src/components/media_manager/src/audio/from_mic_recorder_listener.cc39
-rw-r--r--src/components/media_manager/src/audio/from_mic_to_file_recorder_thread.cc82
-rw-r--r--src/components/media_manager/src/audio/pipe_audio_streamer_adapter.cc20
-rw-r--r--src/components/media_manager/src/audio/socket_audio_streamer_adapter.cc28
-rw-r--r--src/components/media_manager/src/file_streamer_adapter.cc102
-rw-r--r--src/components/media_manager/src/media_adapter_impl.cc6
-rw-r--r--src/components/media_manager/src/media_manager_impl.cc161
-rw-r--r--src/components/media_manager/src/pipe_streamer_adapter.cc216
-rw-r--r--src/components/media_manager/src/socket_streamer_adapter.cc312
-rw-r--r--src/components/media_manager/src/streamer_adapter.cc172
-rw-r--r--src/components/media_manager/src/streamer_listener.cc29
-rw-r--r--src/components/media_manager/src/video/file_video_streamer_adapter.cc43
-rw-r--r--src/components/media_manager/src/video/pipe_video_streamer_adapter.cc19
-rw-r--r--src/components/media_manager/src/video/socket_video_streamer_adapter.cc28
-rw-r--r--src/components/media_manager/src/video/video_stream_to_file_adapter.cc50
-rw-r--r--src/components/media_manager/test/CMakeLists.txt12
-rw-r--r--src/components/media_manager/test/include/media_manager/media_adapter_impl_mock.h71
-rw-r--r--src/components/media_manager/test/include/media_manager/media_adapter_listener_mock.h60
-rw-r--r--src/components/media_manager/test/include/media_manager/media_adapter_mock.h61
-rw-r--r--src/components/media_manager/test/media_adapter_impl_test.cc37
-rw-r--r--src/components/media_manager/test/media_manager_impl_test.cc173
-rw-r--r--src/components/policy/CMakeLists.txt84
-rw-r--r--src/components/policy/Readme.txt (renamed from src/components/policy/src/policy/Readme.txt)0
-rw-r--r--src/components/policy/include/policy/cache_manager.h768
-rw-r--r--src/components/policy/include/policy/cache_manager_interface.h631
-rw-r--r--src/components/policy/include/policy/policy_helper.h248
-rw-r--r--src/components/policy/include/policy/policy_listener.h104
-rw-r--r--src/components/policy/include/policy/policy_manager.h481
-rw-r--r--src/components/policy/include/policy/policy_manager_impl.h352
-rw-r--r--src/components/policy/include/policy/policy_table.h (renamed from src/components/policy/src/policy/include/policy/policy_table.h)0
-rw-r--r--src/components/policy/include/policy/policy_table/enums.h113
-rw-r--r--src/components/policy/include/policy/policy_table/functions.h (renamed from src/components/policy/src/policy/policy_table/table_struct/functions.h)0
-rw-r--r--src/components/policy/include/policy/policy_table/types.h441
-rw-r--r--src/components/policy/include/policy/pt_ext_representation.h333
-rw-r--r--src/components/policy/include/policy/pt_representation.h324
-rw-r--r--src/components/policy/include/policy/sql_pt_ext_queries.h (renamed from src/components/policy/src/policy/include/policy/sql_pt_ext_queries.h)0
-rw-r--r--src/components/policy/include/policy/sql_pt_ext_representation.h205
-rw-r--r--src/components/policy/include/policy/sql_pt_queries.h125
-rw-r--r--src/components/policy/include/policy/sql_pt_representation.h203
-rw-r--r--src/components/policy/include/policy/sql_wrapper.h44
-rw-r--r--src/components/policy/include/policy/update_status_manager.h198
-rw-r--r--src/components/policy/include/policy/update_status_manager_interface.h107
-rw-r--r--src/components/policy/include/policy/usage_statistics/app_stopwatch.h50
-rw-r--r--src/components/policy/include/policy/usage_statistics/counter.h107
-rw-r--r--src/components/policy/include/policy/user_consent_manager.h44
-rw-r--r--src/components/policy/policy_table_interface.xml (renamed from src/components/policy/src/policy/policy_table_interface.xml)0
-rw-r--r--src/components/policy/policy_table_interface_ext.xml (renamed from src/components/policy/src/policy/policy_table_interface_ext.xml)0
-rw-r--r--src/components/policy/specification.txt (renamed from src/components/policy/src/policy/specification.txt)0
-rw-r--r--src/components/policy/src/cache_manager.cc1601
-rw-r--r--src/components/policy/src/policy/CMakeLists.txt102
-rw-r--r--src/components/policy/src/policy/include/policy/cache_manager.h652
-rw-r--r--src/components/policy/src/policy/include/policy/cache_manager_interface.h591
-rw-r--r--src/components/policy/src/policy/include/policy/policy_helper.h243
-rw-r--r--src/components/policy/src/policy/include/policy/policy_listener.h99
-rw-r--r--src/components/policy/src/policy/include/policy/policy_manager.h453
-rw-r--r--src/components/policy/src/policy/include/policy/policy_manager_impl.h332
-rw-r--r--src/components/policy/src/policy/include/policy/policy_types.h311
-rw-r--r--src/components/policy/src/policy/include/policy/pt_ext_representation.h336
-rw-r--r--src/components/policy/src/policy/include/policy/pt_representation.h310
-rw-r--r--src/components/policy/src/policy/include/policy/sql_pt_ext_representation.h201
-rw-r--r--src/components/policy/src/policy/include/policy/sql_pt_queries.h120
-rw-r--r--src/components/policy/src/policy/include/policy/sql_pt_representation.h181
-rw-r--r--src/components/policy/src/policy/include/policy/sql_wrapper.h44
-rw-r--r--src/components/policy/src/policy/include/policy/update_status_manager.h196
-rw-r--r--src/components/policy/src/policy/include/policy/update_status_manager_interface.h107
-rw-r--r--src/components/policy/src/policy/include/policy/user_consent_manager.h44
-rw-r--r--src/components/policy/src/policy/policy_table/table_struct/CMakeLists.txt42
-rw-r--r--src/components/policy/src/policy/policy_table/table_struct/enums.cc438
-rw-r--r--src/components/policy/src/policy/policy_table/table_struct/enums.h117
-rw-r--r--src/components/policy/src/policy/policy_table/table_struct/types.cc1126
-rw-r--r--src/components/policy/src/policy/policy_table/table_struct/types.h396
-rw-r--r--src/components/policy/src/policy/policy_table/table_struct/validation.cc199
-rw-r--r--src/components/policy/src/policy/qdb_wrapper/CMakeLists.txt54
-rw-r--r--src/components/policy/src/policy/qdb_wrapper/include/qdb_wrapper/sql_database.h134
-rw-r--r--src/components/policy/src/policy/qdb_wrapper/include/qdb_wrapper/sql_error.h80
-rw-r--r--src/components/policy/src/policy/qdb_wrapper/include/qdb_wrapper/sql_query.h251
-rw-r--r--src/components/policy/src/policy/qdb_wrapper/src/sql_database.cc114
-rw-r--r--src/components/policy/src/policy/qdb_wrapper/src/sql_error.cc66
-rw-r--r--src/components/policy/src/policy/qdb_wrapper/src/sql_query.cc278
-rw-r--r--src/components/policy/src/policy/sqlite_wrapper/CMakeLists.txt44
-rw-r--r--src/components/policy/src/policy/sqlite_wrapper/include/sqlite_wrapper/sql_database.h160
-rw-r--r--src/components/policy/src/policy/sqlite_wrapper/include/sqlite_wrapper/sql_error.h109
-rw-r--r--src/components/policy/src/policy/sqlite_wrapper/include/sqlite_wrapper/sql_query.h219
-rw-r--r--src/components/policy/src/policy/sqlite_wrapper/src/sql_database.cc114
-rw-r--r--src/components/policy/src/policy/sqlite_wrapper/src/sql_error.cc153
-rw-r--r--src/components/policy/src/policy/sqlite_wrapper/src/sql_query.cc157
-rw-r--r--src/components/policy/src/policy/src/cache_manager.cc1227
-rw-r--r--src/components/policy/src/policy/src/policy_helper.cc796
-rw-r--r--src/components/policy/src/policy/src/policy_manager_impl.cc959
-rw-r--r--src/components/policy/src/policy/src/policy_table.cc57
-rw-r--r--src/components/policy/src/policy/src/sql_pt_ext_queries.cc247
-rw-r--r--src/components/policy/src/policy/src/sql_pt_ext_representation.cc1771
-rw-r--r--src/components/policy/src/policy/src/sql_pt_queries.cc695
-rw-r--r--src/components/policy/src/policy/src/sql_pt_representation.cc1612
-rw-r--r--src/components/policy/src/policy/src/update_status_manager.cc268
-rw-r--r--src/components/policy/src/policy/usage_statistics/CMakeLists.txt37
-rw-r--r--src/components/policy/src/policy/usage_statistics/include/usage_statistics/counter.h100
-rw-r--r--src/components/policy/src/policy/usage_statistics/include/usage_statistics/statistics_manager.h84
-rw-r--r--src/components/policy/src/policy/usage_statistics/src/counter.cc125
-rw-r--r--src/components/policy/src/policy_helper.cc805
-rw-r--r--src/components/policy/src/policy_manager_impl.cc1014
-rw-r--r--src/components/policy/src/policy_table.cc52
-rw-r--r--src/components/policy/src/policy_table/enums.cc577
-rw-r--r--src/components/policy/src/policy_table/types.cc1371
-rw-r--r--src/components/policy/src/policy_table/validation.cc197
-rw-r--r--src/components/policy/src/sql_pt_ext_queries.cc268
-rw-r--r--src/components/policy/src/sql_pt_ext_representation.cc1807
-rw-r--r--src/components/policy/src/sql_pt_queries.cc712
-rw-r--r--src/components/policy/src/sql_pt_representation.cc1750
-rw-r--r--src/components/policy/src/update_status_manager.cc270
-rw-r--r--src/components/policy/src/usage_statistics/counter.cc121
-rw-r--r--src/components/policy/test/CMakeLists.txt61
-rw-r--r--src/components/policy/test/PTU.json1949
-rw-r--r--src/components/policy/test/PTU2.json1953
-rw-r--r--src/components/policy/test/PTU3.json1951
-rw-r--r--src/components/policy/test/PTU4.json1954
-rw-r--r--src/components/policy/test/counter_test.cc194
-rw-r--r--src/components/policy/test/generated_code_test.cc10
-rw-r--r--src/components/policy/test/generated_code_with_sqlite_test.cc218
-rw-r--r--src/components/policy/test/include.cmake6
-rw-r--r--src/components/policy/test/include/driver_dbms.h18
-rw-r--r--src/components/policy/test/include/generated_code_with_sqlite_test.h399
-rw-r--r--src/components/policy/test/include/mock_app_stopwatch.h54
-rw-r--r--src/components/policy/test/include/mock_cache_manager.h246
-rw-r--r--src/components/policy/test/include/mock_policy_listener.h42
-rw-r--r--src/components/policy/test/include/mock_policy_manager.h179
-rw-r--r--src/components/policy/test/include/mock_pt_ext_representation.h125
-rw-r--r--src/components/policy/test/include/mock_pt_representation.h93
-rw-r--r--src/components/policy/test/include/mock_statistics_manager.h58
-rw-r--r--src/components/policy/test/include/mock_update_status_manager.h30
-rw-r--r--src/components/policy/test/policy.sql295
-rw-r--r--src/components/policy/test/policy/CMakeLists.txt86
-rw-r--r--src/components/policy/test/policy/qdb_wrapper/CMakeLists.txt29
-rw-r--r--src/components/policy/test/policy/sqlite_wrapper/CMakeLists.txt27
-rw-r--r--src/components/policy/test/policy/usage_statistics/CMakeLists.txt17
-rw-r--r--src/components/policy/test/policy_manager_impl_stress_test.cc289
-rw-r--r--src/components/policy/test/policy_manager_impl_test.cc1407
-rw-r--r--src/components/policy/test/ptu2_requestType.json2615
-rw-r--r--src/components/policy/test/ptu_requestType.json2610
-rw-r--r--src/components/policy/test/qdb_wrapper/sql_database_test.cc139
-rw-r--r--src/components/policy/test/qdb_wrapper/sql_query_test.cc301
-rwxr-xr-xsrc/components/policy/test/qdbserver.sh6
-rw-r--r--src/components/policy/test/sdl_preloaded_pt.json13
-rw-r--r--src/components/policy/test/sdl_pt_first_update.json1744
-rw-r--r--src/components/policy/test/sdl_pt_second_update.json1744
-rw-r--r--src/components/policy/test/sdl_pt_update.json1722
-rw-r--r--src/components/policy/test/shared_library_test.cc17
-rw-r--r--src/components/policy/test/smartDeviceLink2.ini12
-rw-r--r--src/components/policy/test/smartDeviceLink3.ini12
-rw-r--r--src/components/policy/test/sql_pt_ext_representation_test.cc378
-rw-r--r--src/components/policy/test/sql_pt_representation_test.cc1407
-rw-r--r--src/components/policy/test/sqlite_wrapper/sql_database_test.cc229
-rw-r--r--src/components/policy/test/sqlite_wrapper/sql_query_test.cc375
-rw-r--r--src/components/policy/test/test-qdb.ini11
-rw-r--r--src/components/policy/test/update_status_manager_test.cc92
-rw-r--r--src/components/policy/test/usage_statistics_test.cc196
-rw-r--r--src/components/policy/test/valid_sdl_pt_update.json9
-rw-r--r--src/components/protocol/src/message_priority.cc3
-rw-r--r--src/components/protocol/src/raw_message.cc25
-rw-r--r--src/components/protocol/src/rpc_type.cc4
-rw-r--r--src/components/protocol/src/service_type.cc4
-rw-r--r--src/components/protocol_handler/CMakeLists.txt2
-rw-r--r--src/components/protocol_handler/include/protocol_handler/incoming_data_handler.h32
-rw-r--r--src/components/protocol_handler/include/protocol_handler/multiframe_builder.h166
-rw-r--r--src/components/protocol_handler/include/protocol_handler/protocol_handler_impl.h229
-rw-r--r--src/components/protocol_handler/include/protocol_handler/protocol_packet.h90
-rw-r--r--src/components/protocol_handler/include/protocol_handler/protocol_payload.h26
-rw-r--r--src/components/protocol_handler/include/protocol_handler/telemetry_observer.h57
-rw-r--r--src/components/protocol_handler/include/protocol_handler/time_metric_observer.h56
-rw-r--r--src/components/protocol_handler/src/incoming_data_handler.cc101
-rw-r--r--src/components/protocol_handler/src/multiframe_builder.cc284
-rw-r--r--src/components/protocol_handler/src/protocol_handler_impl.cc1329
-rw-r--r--src/components/protocol_handler/src/protocol_packet.cc289
-rw-r--r--src/components/protocol_handler/src/protocol_payload.cc46
-rw-r--r--src/components/protocol_handler/test/CMakeLists.txt20
-rw-r--r--src/components/protocol_handler/test/include/control_message_matcher.h144
-rw-r--r--src/components/protocol_handler/test/include/protocol_handler/control_message_matcher.h207
-rw-r--r--src/components/protocol_handler/test/include/protocol_handler/mock_telemetry_observer.h54
-rw-r--r--src/components/protocol_handler/test/include/protocol_handler/protocol_observer_mock.h57
-rw-r--r--src/components/protocol_handler/test/include/protocol_handler_mock.h234
-rw-r--r--src/components/protocol_handler/test/include/protocol_observer_mock.h57
-rw-r--r--src/components/protocol_handler/test/include/session_observer_mock.h112
-rw-r--r--src/components/protocol_handler/test/incoming_data_handler_test.cc630
-rw-r--r--src/components/protocol_handler/test/multiframe_builder_test.cc540
-rw-r--r--src/components/protocol_handler/test/protocol_handler_tm_test.cc1472
-rw-r--r--src/components/protocol_handler/test/protocol_header_validator_test.cc249
-rw-r--r--src/components/protocol_handler/test/protocol_packet_test.cc185
-rw-r--r--src/components/protocol_handler/test/protocol_payload_test.cc12
-rw-r--r--src/components/qt_hmi/References/Work/bananasnacks/main.cpp15
-rw-r--r--src/components/qt_hmi/References/Work/bananasnacks/qtquick2applicationviewer/qtquick2applicationviewer.cpp66
-rw-r--r--src/components/qt_hmi/References/Work/bananasnacks/qtquick2applicationviewer/qtquick2applicationviewer.h26
-rw-r--r--src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsServer.cpp764
-rw-r--r--src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsServer.h137
-rw-r--r--src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsSocket.cpp1477
-rw-r--r--src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsSocket.h325
-rw-r--r--src/components/qt_hmi/References/Work/fordsdlcore/fordsdlcore_plugin.cpp29
-rw-r--r--src/components/qt_hmi/References/Work/fordsdlcore/fordsdlcore_plugin.h16
-rw-r--r--src/components/qt_hmi/References/Work/fordsdlcore/sdlalert.cpp5
-rw-r--r--src/components/qt_hmi/References/Work/fordsdlcore/sdlalert.h18
-rw-r--r--src/components/qt_hmi/References/Work/fordsdlcore/sdlappslistmodel.cpp6
-rw-r--r--src/components/qt_hmi/References/Work/fordsdlcore/sdlappslistmodel.h74
-rw-r--r--src/components/qt_hmi/References/Work/fordsdlcore/smartdevicelink.cpp497
-rw-r--r--src/components/qt_hmi/References/Work/fordsdlcore/smartdevicelink.h111
-rw-r--r--src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_controller.cc26
-rw-r--r--src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_controller.h8
-rw-r--r--src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_plugin.cc24
-rw-r--r--src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_plugin.h13
-rw-r--r--src/components/qt_hmi/qml_plugins/dbus_adapter/hmi_proxy.cc3
-rw-r--r--src/components/qt_hmi/qml_plugins/dbus_adapter/hmi_proxy.h7
-rw-r--r--src/components/qt_hmi/qml_plugins/dbus_adapter/metatype.h10
-rw-r--r--src/components/qt_hmi/qml_plugins/dbus_adapter/optional_argument.h28
-rw-r--r--src/components/qt_hmi/qml_plugins/dbus_adapter/qml_dbus_common.h135
-rw-r--r--src/components/qt_hmi/qml_plugins/dbus_adapter/qt_version.h11
-rw-r--r--src/components/qt_hmi/qml_plugins/dbus_adapter/stream_qvariant.cc50
-rw-r--r--src/components/qt_hmi/qml_plugins/hw_buttons/attributed_mouse_event.cc4
-rw-r--r--src/components/qt_hmi/qml_plugins/hw_buttons/attributed_mouse_event.h10
-rw-r--r--src/components/qt_hmi/qml_plugins/hw_buttons/hmi_hwbuttons.cc8
-rw-r--r--src/components/qt_hmi/qml_plugins/hw_buttons/hmi_hwbuttons.h7
-rw-r--r--src/components/qt_hmi/qml_plugins/hw_buttons/masked_container.cc110
-rw-r--r--src/components/qt_hmi/qml_plugins/hw_buttons/masked_container.h18
-rw-r--r--src/components/qt_hmi/qml_plugins/hw_buttons/qt_version.h11
-rw-r--r--src/components/qt_hmi/qml_plugins/log4cxx/log4cxx_plugin.cc78
-rw-r--r--src/components/qt_hmi/qml_plugins/log4cxx/log4cxx_plugin.h23
-rw-r--r--src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier.cc9
-rw-r--r--src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier.h6
-rw-r--r--src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier_plugin.cc8
-rw-r--r--src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier_plugin.h4
-rw-r--r--src/components/qt_hmi/qml_plugins/named_pipe_notifier/qt_version.h11
-rw-r--r--src/components/resumption/include/resumption/last_state.h30
-rw-r--r--src/components/resumption/src/last_state.cc51
-rw-r--r--src/components/resumption/test/CMakeLists.txt1
-rw-r--r--src/components/resumption/test/last_state_test.cc72
-rw-r--r--src/components/rpc_base/include/rpc_base/gtest_support.h8
-rw-r--r--src/components/rpc_base/include/rpc_base/rpc_base.h633
-rw-r--r--src/components/rpc_base/include/rpc_base/rpc_base_dbus_inl.h232
-rw-r--r--src/components/rpc_base/include/rpc_base/rpc_base_inl.h334
-rw-r--r--src/components/rpc_base/include/rpc_base/rpc_base_json_inl.h188
-rw-r--r--src/components/rpc_base/include/rpc_base/rpc_message.h28
-rw-r--r--src/components/rpc_base/include/rpc_base/validation_report.h17
-rw-r--r--src/components/rpc_base/src/rpc_base/rpc_base.cc4
-rw-r--r--src/components/rpc_base/test/rpc_base_dbus_test.cc99
-rw-r--r--src/components/rpc_base/test/rpc_base_json_test.cc39
-rw-r--r--src/components/rpc_base/test/rpc_base_test.cc57
-rw-r--r--src/components/rpc_base/test/validation_report_test.cc28
-rw-r--r--src/components/security_manager/CMakeLists.txt4
-rw-r--r--src/components/security_manager/include/security_manager/crypto_manager_impl.h95
-rw-r--r--src/components/security_manager/include/security_manager/crypto_manager_settings_impl.h65
-rw-r--r--src/components/security_manager/include/security_manager/security_manager_impl.h76
-rw-r--r--src/components/security_manager/include/security_manager/security_query.h186
-rw-r--r--src/components/security_manager/src/crypto_manager_impl.cc360
-rw-r--r--src/components/security_manager/src/security_manager_impl.cc250
-rw-r--r--src/components/security_manager/src/security_query.cc97
-rw-r--r--src/components/security_manager/src/ssl_context_impl.cc423
-rw-r--r--src/components/security_manager/test/CMakeLists.txt20
-rw-r--r--src/components/security_manager/test/crypto_manager_impl_test.cc588
-rw-r--r--src/components/security_manager/test/include/security_manager_mock.h311
-rw-r--r--src/components/security_manager/test/mycert.pem22
-rw-r--r--src/components/security_manager/test/mykey.pem27
-rw-r--r--src/components/security_manager/test/security_manager_test.cc774
-rw-r--r--src/components/security_manager/test/security_query_matcher.cc84
-rw-r--r--src/components/security_manager/test/security_query_test.cc101
-rw-r--r--src/components/security_manager/test/ssl_certificate_handshake_test.cc583
-rw-r--r--src/components/security_manager/test/ssl_context_test.cc535
-rw-r--r--src/components/smart_objects/include/smart_objects/always_false_schema_item.h1
-rw-r--r--src/components/smart_objects/include/smart_objects/always_true_schema_item.h1
-rw-r--r--src/components/smart_objects/include/smart_objects/array_schema_item.h9
-rw-r--r--src/components/smart_objects/include/smart_objects/bool_schema_item.h5
-rw-r--r--src/components/smart_objects/include/smart_objects/default_shema_item.h18
-rw-r--r--src/components/smart_objects/include/smart_objects/enum_schema_item.h61
-rw-r--r--src/components/smart_objects/include/smart_objects/errors.h3
-rw-r--r--src/components/smart_objects/include/smart_objects/number_schema_item.h88
-rw-r--r--src/components/smart_objects/include/smart_objects/object_schema_item.h9
-rw-r--r--src/components/smart_objects/include/smart_objects/schema_item.h11
-rw-r--r--src/components/smart_objects/include/smart_objects/schema_item_parameter.h16
-rw-r--r--src/components/smart_objects/include/smart_objects/smart_object.h132
-rw-r--r--src/components/smart_objects/include/smart_objects/string_schema_item.h10
-rw-r--r--src/components/smart_objects/src/always_false_schema_item.cc3
-rw-r--r--src/components/smart_objects/src/always_true_schema_item.cc3
-rw-r--r--src/components/smart_objects/src/array_schema_item.cc13
-rw-r--r--src/components/smart_objects/src/bool_schema_item.cc8
-rw-r--r--src/components/smart_objects/src/number_schema_item.cc12
-rw-r--r--src/components/smart_objects/src/object_schema_item.cc43
-rw-r--r--src/components/smart_objects/src/schema_item.cc10
-rw-r--r--src/components/smart_objects/src/smart_object.cc204
-rw-r--r--src/components/smart_objects/src/smart_schema.cc10
-rw-r--r--src/components/smart_objects/src/string_schema_item.cc12
-rw-r--r--src/components/smart_objects/test/ArraySchemaItem_test.cc19
-rw-r--r--src/components/smart_objects/test/BoolSchemaItem_test.cc19
-rw-r--r--src/components/smart_objects/test/CObjectSchemaItem_test.cc111
-rw-r--r--src/components/smart_objects/test/EnumSchemaItem_test.cc94
-rw-r--r--src/components/smart_objects/test/NumberSchemaItem_test.cc179
-rw-r--r--src/components/smart_objects/test/SmartObjectConvertionTime_test.cc411
-rw-r--r--src/components/smart_objects/test/SmartObjectDraft_test.cc4
-rw-r--r--src/components/smart_objects/test/SmartObjectStress_test.cc131
-rw-r--r--src/components/smart_objects/test/SmartObjectUnit_test.cc135
-rw-r--r--src/components/smart_objects/test/StringSchemaItem_test.cc45
-rw-r--r--src/components/smart_objects/test/map_performance_test.cc2
-rw-r--r--src/components/smart_objects/test/smart_object_performance_test.cc4
-rw-r--r--src/components/telemetry_monitor/CMakeLists.txt69
-rw-r--r--src/components/telemetry_monitor/include/telemetry_monitor/application_manager_metric_wrapper.h52
-rw-r--r--src/components/telemetry_monitor/include/telemetry_monitor/application_manager_observer.h54
-rw-r--r--src/components/telemetry_monitor/include/telemetry_monitor/json_keys.h52
-rw-r--r--src/components/telemetry_monitor/include/telemetry_monitor/metric_wrapper.h60
-rw-r--r--src/components/telemetry_monitor/include/telemetry_monitor/protocol_handler_metric_wrapper.h50
-rw-r--r--src/components/telemetry_monitor/include/telemetry_monitor/protocol_handler_observer.h57
-rw-r--r--src/components/telemetry_monitor/include/telemetry_monitor/telemetry_monitor.h108
-rw-r--r--src/components/telemetry_monitor/include/telemetry_monitor/transport_manager_metric_wrapper.h49
-rw-r--r--src/components/telemetry_monitor/include/telemetry_monitor/transport_manager_observer.h55
-rw-r--r--src/components/telemetry_monitor/src/application_manager_metric_wrapper.cc55
-rw-r--r--src/components/telemetry_monitor/src/application_manager_observer.cc50
-rw-r--r--src/components/telemetry_monitor/src/metric_wrapper.cc75
-rw-r--r--src/components/telemetry_monitor/src/protocol_handler_metric_wrapper.cc51
-rw-r--r--src/components/telemetry_monitor/src/protocol_handler_observer.cc76
-rw-r--r--src/components/telemetry_monitor/src/telemetry_monitor.cc287
-rw-r--r--src/components/telemetry_monitor/src/transport_manager_metric_wrapper.cc51
-rw-r--r--src/components/telemetry_monitor/src/transport_manager_observer.cc67
-rw-r--r--src/components/telemetry_monitor/test/CMakeLists.txt89
-rw-r--r--src/components/telemetry_monitor/test/application_manager_metric_test.cc138
-rw-r--r--src/components/telemetry_monitor/test/application_manager_observer_test.cc60
-rw-r--r--src/components/telemetry_monitor/test/include/telemetry_monitor/mock_telemetry_monitor.h58
-rw-r--r--src/components/telemetry_monitor/test/log4cxx.properties (renamed from src/components/time_tester/test/log4cxx.properties)0
-rw-r--r--src/components/telemetry_monitor/test/metric_wrapper_test.cc82
-rw-r--r--src/components/telemetry_monitor/test/protocol_handler_metric_test.cc125
-rw-r--r--src/components/telemetry_monitor/test/protocol_handler_observer_test.cc81
-rw-r--r--src/components/telemetry_monitor/test/telemetry_monitor_test.cc106
-rw-r--r--src/components/telemetry_monitor/test/transport_manager_metric_test.cc116
-rw-r--r--src/components/telemetry_monitor/test/transport_manager_observer_test.cc59
-rw-r--r--[-rwxr-xr-x]src/components/test_main.cc14
-rw-r--r--src/components/time_tester/CMakeLists.txt69
-rw-r--r--src/components/time_tester/include/time_tester/application_manager_metric.h56
-rw-r--r--src/components/time_tester/include/time_tester/application_manager_observer.h55
-rw-r--r--src/components/time_tester/include/time_tester/json_keys.h52
-rw-r--r--src/components/time_tester/include/time_tester/metric_wrapper.h59
-rw-r--r--src/components/time_tester/include/time_tester/protocol_handler_metric.h51
-rw-r--r--src/components/time_tester/include/time_tester/protocol_handler_observer.h56
-rw-r--r--src/components/time_tester/include/time_tester/time_manager.h98
-rw-r--r--src/components/time_tester/include/time_tester/transport_manager_metric.h49
-rw-r--r--src/components/time_tester/include/time_tester/transport_manager_observer.h54
-rw-r--r--src/components/time_tester/src/application_manager_metric.cc54
-rw-r--r--src/components/time_tester/src/application_manager_observer.cc49
-rw-r--r--src/components/time_tester/src/metric_wrapper.cc46
-rw-r--r--src/components/time_tester/src/protocol_handler_metric.cc51
-rw-r--r--src/components/time_tester/src/protocol_handler_observer.cc72
-rw-r--r--src/components/time_tester/src/time_manager.cc253
-rw-r--r--src/components/time_tester/src/transport_manager_metric.cc51
-rw-r--r--src/components/time_tester/src/transport_manager_observer.cc63
-rw-r--r--src/components/time_tester/test/CMakeLists.txt93
-rw-r--r--src/components/time_tester/test/application_manager_metric_test.cc118
-rw-r--r--src/components/time_tester/test/application_manager_observer_test.cc59
-rw-r--r--src/components/time_tester/test/include/time_manager_mock.h57
-rw-r--r--src/components/time_tester/test/metric_wrapper_test.cc82
-rw-r--r--src/components/time_tester/test/protocol_handler_metric_test.cc119
-rw-r--r--src/components/time_tester/test/protocol_handler_observer_test.cc81
-rw-r--r--src/components/time_tester/test/time_manager_test.cc72
-rw-r--r--src/components/time_tester/test/transport_manager_metric_test.cc110
-rw-r--r--src/components/time_tester/test/transport_manager_observer_test.cc58
-rw-r--r--src/components/transport_manager/CMakeLists.txt10
-rw-r--r--src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_connection_factory.h8
-rw-r--r--src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_device.h10
-rw-r--r--src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_device_scanner.h32
-rw-r--r--src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_socket_connection.h3
-rw-r--r--src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_transport_adapter.h5
-rw-r--r--src/components/transport_manager/include/transport_manager/tcp/dnssd_service_browser.h135
-rw-r--r--src/components/transport_manager/include/transport_manager/tcp/tcp_client_listener.h21
-rw-r--r--src/components/transport_manager/include/transport_manager/tcp/tcp_device.h2
-rw-r--r--src/components/transport_manager/include/transport_manager/tcp/tcp_socket_connection.h7
-rw-r--r--src/components/transport_manager/include/transport_manager/tcp/tcp_transport_adapter.h4
-rw-r--r--src/components/transport_manager/include/transport_manager/telemetry_observer.h55
-rw-r--r--src/components/transport_manager/include/transport_manager/time_metric_observer.h55
-rw-r--r--src/components/transport_manager/include/transport_manager/transport_adapter/client_connection_listener.h8
-rw-r--r--src/components/transport_manager/include/transport_manager/transport_adapter/connection.h5
-rw-r--r--src/components/transport_manager/include/transport_manager/transport_adapter/device_scanner.h3
-rw-r--r--src/components/transport_manager/include/transport_manager/transport_adapter/server_connection_factory.h6
-rw-r--r--src/components/transport_manager/include/transport_manager/transport_adapter/threaded_socket_connection.h1
-rw-r--r--src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_controller.h37
-rw-r--r--src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_impl.h190
-rw-r--r--src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_listener.h92
-rw-r--r--src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_listener_impl.h40
-rw-r--r--src/components/transport_manager/include/transport_manager/transport_manager_default.h17
-rw-r--r--src/components/transport_manager/include/transport_manager/transport_manager_impl.h156
-rw-r--r--src/components/transport_manager/include/transport_manager/usb/common.h39
-rw-r--r--src/components/transport_manager/include/transport_manager/usb/libusb/platform_usb_device.h27
-rw-r--r--src/components/transport_manager/include/transport_manager/usb/libusb/usb_connection.h6
-rw-r--r--src/components/transport_manager/include/transport_manager/usb/libusb/usb_handler.h15
-rw-r--r--src/components/transport_manager/include/transport_manager/usb/qnx/platform_usb_device.h23
-rw-r--r--src/components/transport_manager/include/transport_manager/usb/qnx/usb_connection.h6
-rw-r--r--src/components/transport_manager/include/transport_manager/usb/usb_aoa_adapter.h3
-rw-r--r--src/components/transport_manager/include/transport_manager/usb/usb_control_transfer.h21
-rw-r--r--src/components/transport_manager/include/transport_manager/usb/usb_device.h7
-rw-r--r--src/components/transport_manager/src/bluetooth/bluetooth_connection_factory.cc20
-rw-r--r--src/components/transport_manager/src/bluetooth/bluetooth_device.cc39
-rw-r--r--src/components/transport_manager/src/bluetooth/bluetooth_device_scanner.cc161
-rw-r--r--src/components/transport_manager/src/bluetooth/bluetooth_socket_connection.cc33
-rw-r--r--src/components/transport_manager/src/bluetooth/bluetooth_transport_adapter.cc64
-rw-r--r--src/components/transport_manager/src/tcp/dnssd_service_browser.cc378
-rw-r--r--src/components/transport_manager/src/tcp/tcp_client_listener.cc67
-rw-r--r--src/components/transport_manager/src/tcp/tcp_connection_factory.cc20
-rw-r--r--src/components/transport_manager/src/tcp/tcp_device.cc23
-rw-r--r--src/components/transport_manager/src/tcp/tcp_socket_connection.cc33
-rw-r--r--src/components/transport_manager/src/tcp/tcp_transport_adapter.cc49
-rw-r--r--src/components/transport_manager/src/transport_adapter/threaded_socket_connection.cc72
-rw-r--r--src/components/transport_manager/src/transport_adapter/transport_adapter_impl.cc386
-rw-r--r--src/components/transport_manager/src/transport_adapter/transport_adapter_listener_impl.cc338
-rw-r--r--src/components/transport_manager/src/transport_manager_default.cc69
-rw-r--r--src/components/transport_manager/src/transport_manager_impl.cc589
-rw-r--r--src/components/transport_manager/src/usb/libusb/platform_usb_device.cc30
-rw-r--r--src/components/transport_manager/src/usb/libusb/usb_connection.cc168
-rw-r--r--src/components/transport_manager/src/usb/libusb/usb_handler.cc222
-rw-r--r--src/components/transport_manager/src/usb/qnx/platform_usb_device.cc17
-rw-r--r--src/components/transport_manager/src/usb/qnx/usb_connection.cc148
-rw-r--r--src/components/transport_manager/src/usb/qnx/usb_handler.cc127
-rw-r--r--src/components/transport_manager/src/usb/usb_aoa_adapter.cc26
-rw-r--r--src/components/transport_manager/src/usb/usb_connection_factory.cc32
-rw-r--r--src/components/transport_manager/src/usb/usb_device_scanner.cc49
-rw-r--r--src/components/transport_manager/test/CMakeLists.txt17
-rw-r--r--src/components/transport_manager/test/app_info_storage299
-rw-r--r--src/components/transport_manager/test/dnssd_service_browser_test.cc147
-rw-r--r--src/components/transport_manager/test/include/client_connection_listener_mock.h62
-rw-r--r--src/components/transport_manager/test/include/connection_mock.h56
-rw-r--r--src/components/transport_manager/test/include/device_mock.h70
-rw-r--r--src/components/transport_manager/test/include/device_scanner_mock.h58
-rw-r--r--src/components/transport_manager/test/include/mock_application.h80
-rw-r--r--src/components/transport_manager/test/include/mock_connection.h69
-rw-r--r--src/components/transport_manager/test/include/mock_connection_factory.h69
-rw-r--r--src/components/transport_manager/test/include/mock_device.h82
-rw-r--r--src/components/transport_manager/test/include/mock_device_scanner.h76
-rw-r--r--src/components/transport_manager/test/include/mock_transport_adapter.h62
-rw-r--r--src/components/transport_manager/test/include/mock_transport_adapter_listener.h94
-rw-r--r--src/components/transport_manager/test/include/mock_transport_manager_listener.h103
-rw-r--r--src/components/transport_manager/test/include/raw_message_matcher.h75
-rw-r--r--src/components/transport_manager/test/include/server_connection_factory_mock.h57
-rw-r--r--src/components/transport_manager/test/include/time_metric_observer_mock.h55
-rw-r--r--src/components/transport_manager/test/include/transport_adapter_controller_mock.h92
-rw-r--r--src/components/transport_manager/test/include/transport_adapter_listener_mock.h123
-rw-r--r--src/components/transport_manager/test/include/transport_adapter_mock.h104
-rw-r--r--src/components/transport_manager/test/include/transport_manager/client_connection_listener_mock.h62
-rw-r--r--src/components/transport_manager/test/include/transport_manager/connection_mock.h57
-rw-r--r--src/components/transport_manager/test/include/transport_manager/device_mock.h70
-rw-r--r--src/components/transport_manager/test/include/transport_manager/device_scanner_mock.h58
-rw-r--r--src/components/transport_manager/test/include/transport_manager/mock_telemetry_observer.h53
-rw-r--r--src/components/transport_manager/test/include/transport_manager/mock_transport_adapter_listener.h128
-rw-r--r--src/components/transport_manager/test/include/transport_manager/mock_transport_manager_impl.h71
-rw-r--r--src/components/transport_manager/test/include/transport_manager/raw_message_matcher.h76
-rw-r--r--src/components/transport_manager/test/include/transport_manager/server_connection_factory_mock.h59
-rw-r--r--src/components/transport_manager/test/include/transport_manager/tcp/mock_tcp_transport_adapter.h73
-rw-r--r--src/components/transport_manager/test/include/transport_manager/transport_adapter/mock_transport_adapter_impl.h85
-rw-r--r--src/components/transport_manager/test/include/transport_manager/transport_adapter_controller_mock.h101
-rw-r--r--src/components/transport_manager/test/include/transport_manager/transport_adapter_listener_mock.h133
-rw-r--r--src/components/transport_manager/test/include/transport_manager/transport_adapter_mock.h108
-rw-r--r--src/components/transport_manager/test/include/transport_manager/transport_manager_impl_mock.h54
-rw-r--r--src/components/transport_manager/test/include/transport_manager/transport_manager_listener_mock.h91
-rw-r--r--src/components/transport_manager/test/include/transport_manager_impl_mock.h54
-rw-r--r--src/components/transport_manager/test/include/transport_manager_listener_mock.h89
-rw-r--r--src/components/transport_manager/test/include/transport_manager_mock.h87
-rw-r--r--src/components/transport_manager/test/mock_application.cc147
-rw-r--r--src/components/transport_manager/test/mock_connection.cc78
-rw-r--r--src/components/transport_manager/test/mock_connection_factory.cc63
-rw-r--r--src/components/transport_manager/test/mock_device.cc85
-rw-r--r--src/components/transport_manager/test/mock_device_scanner.cc103
-rw-r--r--src/components/transport_manager/test/mock_transport_adapter.cc57
-rw-r--r--src/components/transport_manager/test/raw_message_matcher.cc12
-rw-r--r--src/components/transport_manager/test/tcp_client_listener_test.cc84
-rw-r--r--src/components/transport_manager/test/tcp_device_test.cc4
-rw-r--r--src/components/transport_manager/test/tcp_transport_adapter_test.cc119
-rw-r--r--src/components/transport_manager/test/transport_adapter_listener_test.cc106
-rw-r--r--src/components/transport_manager/test/transport_adapter_test.cc283
-rw-r--r--src/components/transport_manager/test/transport_manager_default_test.cc45
-rw-r--r--src/components/transport_manager/test/transport_manager_impl_test.cc1090
-rw-r--r--src/components/transport_manager/test/transport_manager_instance_test.cc73
-rw-r--r--src/components/transport_manager/test/transport_manager_test.cc394
-rw-r--r--src/components/utils/CMakeLists.txt14
-rw-r--r--src/components/utils/include/utils/appenders_loader.h1
-rw-r--r--src/components/utils/include/utils/back_trace.h6
-rw-r--r--src/components/utils/include/utils/bitstream.h37
-rw-r--r--src/components/utils/include/utils/convert_utils.h77
-rw-r--r--src/components/utils/include/utils/file_system.h21
-rw-r--r--src/components/utils/include/utils/gen_hash.h30
-rw-r--r--src/components/utils/include/utils/helpers.h115
-rw-r--r--src/components/utils/include/utils/log_message_loop_thread.h17
-rw-r--r--src/components/utils/include/utils/qdb_wrapper/sql_database.h135
-rw-r--r--src/components/utils/include/utils/qdb_wrapper/sql_error.h80
-rw-r--r--src/components/utils/include/utils/qdb_wrapper/sql_query.h265
-rw-r--r--src/components/utils/include/utils/resource_usage.h27
-rw-r--r--src/components/utils/include/utils/signals.h6
-rw-r--r--src/components/utils/include/utils/singleton.h98
-rw-r--r--src/components/utils/include/utils/sqlite_wrapper/sql_database.h167
-rw-r--r--src/components/utils/include/utils/sqlite_wrapper/sql_error.h109
-rw-r--r--src/components/utils/include/utils/sqlite_wrapper/sql_query.h233
-rw-r--r--src/components/utils/include/utils/stl_utils.h27
-rw-r--r--src/components/utils/include/utils/threads/pulse_thread_delegate.h43
-rw-r--r--src/components/utils/include/utils/threads/thread_manager.h7
-rw-r--r--src/components/utils/include/utils/threads/thread_validator.h7
-rw-r--r--src/components/utils/include/utils/timer.h217
-rw-r--r--src/components/utils/include/utils/timer_task.h53
-rw-r--r--src/components/utils/include/utils/timer_task_impl.h79
-rw-r--r--src/components/utils/src/auto_trace.cc20
-rw-r--r--src/components/utils/src/back_trace.cc25
-rw-r--r--src/components/utils/src/bitstream.cc17
-rw-r--r--src/components/utils/src/conditional_variable_posix.cc54
-rw-r--r--src/components/utils/src/convert_utils.cc72
-rw-r--r--src/components/utils/src/custom_string.cc201
-rw-r--r--src/components/utils/src/date_time.cc97
-rw-r--r--src/components/utils/src/file_system.cc133
-rw-r--r--src/components/utils/src/gen_hash.cc62
-rw-r--r--src/components/utils/src/lock_posix.cc71
-rw-r--r--src/components/utils/src/log_message_loop_thread.cc9
-rw-r--r--src/components/utils/src/logger.cc15
-rw-r--r--src/components/utils/src/push_log.cc56
-rw-r--r--src/components/utils/src/qdb_wrapper/CMakeLists.txt54
-rw-r--r--src/components/utils/src/qdb_wrapper/policy.ini (renamed from src/components/policy/src/policy/qdb_wrapper/policy.ini)0
-rwxr-xr-xsrc/components/utils/src/qdb_wrapper/qdbserver.sh (renamed from src/components/policy/src/policy/qdb_wrapper/qdbserver.sh)0
-rw-r--r--src/components/utils/src/qdb_wrapper/sql_database.cc112
-rw-r--r--src/components/utils/src/qdb_wrapper/sql_error.cc63
-rw-r--r--src/components/utils/src/qdb_wrapper/sql_query.cc293
-rw-r--r--src/components/utils/src/resource_usage.cc167
-rw-r--r--src/components/utils/src/signals_linux.cc54
-rw-r--r--src/components/utils/src/sqlite_wrapper/CMakeLists.txt44
-rw-r--r--src/components/utils/src/sqlite_wrapper/sql_database.cc115
-rw-r--r--src/components/utils/src/sqlite_wrapper/sql_error.cc150
-rw-r--r--src/components/utils/src/sqlite_wrapper/sql_query.cc161
-rw-r--r--src/components/utils/src/system.cc26
-rw-r--r--src/components/utils/src/threads/async_runner.cc15
-rw-r--r--src/components/utils/src/threads/posix_thread.cc156
-rw-r--r--src/components/utils/src/threads/pulse_thread_delegate.cc24
-rw-r--r--src/components/utils/src/threads/thread_delegate.cc6
-rw-r--r--src/components/utils/src/threads/thread_manager.cc2
-rw-r--r--src/components/utils/src/threads/thread_validator.cc44
-rw-r--r--src/components/utils/src/timer.cc209
-rw-r--r--src/components/utils/test/CMakeLists.txt41
-rw-r--r--src/components/utils/test/async_runner_test.cc25
-rw-r--r--src/components/utils/test/auto_trace_test.cc121
-rw-r--r--src/components/utils/test/back_trace_test.cc7
-rw-r--r--src/components/utils/test/bitstream_test.cc105
-rw-r--r--src/components/utils/test/conditional_variable_test.cc68
-rw-r--r--src/components/utils/test/custom_string_test.cc319
-rw-r--r--src/components/utils/test/data_accessor_test.cc48
-rw-r--r--src/components/utils/test/date_time_test.cc183
-rw-r--r--src/components/utils/test/file_system_test.cc232
-rw-r--r--src/components/utils/test/generated_code_with_sqlite_test.cc217
-rw-r--r--src/components/utils/test/include/utils/generated_code_with_sqlite_test.h407
-rw-r--r--src/components/utils/test/include/utils/mock_timer_task.h52
-rw-r--r--src/components/utils/test/include/utils/test_handler.h51
-rw-r--r--src/components/utils/test/log_message_loop_thread_test.cc34
-rw-r--r--src/components/utils/test/message_loop_thread_test.cc52
-rw-r--r--src/components/utils/test/message_queue_test.cc55
-rw-r--r--src/components/utils/test/messagemeter_test.cc241
-rw-r--r--src/components/utils/test/posix_thread_test.cc97
-rw-r--r--src/components/utils/test/prioritized_queue_test.cc43
-rw-r--r--src/components/utils/test/qdb_wrapper/sql_database_test.cc139
-rw-r--r--src/components/utils/test/qdb_wrapper/sql_query_test.cc311
-rw-r--r--src/components/utils/test/resource_usage_test.cc16
-rw-r--r--src/components/utils/test/rwlock_posix_test.cc24
-rw-r--r--src/components/utils/test/shared_ptr_test.cc55
-rw-r--r--src/components/utils/test/signals_linux_test.cc55
-rw-r--r--src/components/utils/test/singleton_test.cc72
-rw-r--r--src/components/utils/test/smartDeviceLink.ini19
-rw-r--r--src/components/utils/test/sqlite_wrapper/sql_database_test.cc223
-rw-r--r--src/components/utils/test/sqlite_wrapper/sql_query_test.cc380
-rw-r--r--src/components/utils/test/stl_utils_test.cc19
-rw-r--r--src/components/utils/test/system_test.cc33
-rw-r--r--src/components/utils/test/test_generator/CMakeLists.txt65
-rw-r--r--src/components/utils/test/test_generator/MOBILE_API.xml4999
-rw-r--r--src/components/utils/test/test_generator/generated_msg_version_test.cc77
-rw-r--r--src/components/utils/test/thread_validator_test.cc7
-rw-r--r--src/components/utils/test/timer_test.cc326
-rw-r--r--src/components/utils/test/timer_thread_test.cc153
-rw-r--r--src/plugins/appenders/safe_file_appender.cc6
-rw-r--r--src/plugins/appenders/safe_file_appender.h3
-rw-r--r--src/plugins/appenders/safe_rolling_file_appender.cc6
-rw-r--r--src/plugins/appenders/safe_rolling_file_appender.h3
-rw-r--r--tools/CMakeLists.txt2
-rwxr-xr-xtools/InterfaceGenerator/Generator.py9
-rw-r--r--tools/InterfaceGenerator/MsgVersionGenerate.py85
-rwxr-xr-xtools/InterfaceGenerator/generator/generators/SmartFactoryBase.py4
-rwxr-xr-xtools/InterfaceGenerator/generator/parsers/RPCBase.py3
-rwxr-xr-xtools/Utils/generate_test_certificates.py279
-rwxr-xr-xtools/infrastructure/check_style.sh47
-rwxr-xr-xtools/infrastructure/collect_coverage.sh27
-rw-r--r--tools/infrastructure/format_src.py37
-rwxr-xr-xtools/infrastructure/git-hooks/pre-commit102
-rw-r--r--tools/infrastructure/install_hooks.py40
-rw-r--r--tools/infrastructure/utils.py43
-rw-r--r--tools/policy_table_validator/CMakeLists.txt9
-rw-r--r--tools/policy_table_validator/main.cpp2
2025 files changed, 136961 insertions, 72302 deletions
diff --git a/.clang-format b/.clang-format
new file mode 100644
index 0000000000..8515b05b85
--- /dev/null
+++ b/.clang-format
@@ -0,0 +1,11 @@
+---
+Language: Cpp
+BasedOnStyle: Google
+AllowShortFunctionsOnASingleLine: Empty
+AllowShortIfStatementsOnASingleLine: false
+AllowShortLoopsOnASingleLine: false
+BinPackArguments: false
+BinPackParameters: false
+BreakConstructorInitializersBeforeComma: true
+DerivePointerAlignment: false
+TabWidth: 2
diff --git a/.gitignore b/.gitignore
index 567609b123..6c1cc2cdf2 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1 +1,3 @@
build/
+*.user
+src/appMain/sdl_preloaded_pt.json
diff --git a/.travis.yml b/.travis.yml
index eea4331127..8c2e2d6a5a 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,15 +1,64 @@
language: cpp
+dist: trusty
+sudo: required
+only:
+ - master
+ - develop
+ - \/feature\/.+
+ - \/fix\/.+
+ - \/hotfix\/.+
+ - \/release\/.+
+
addons:
apt:
sources:
- - travis-ci/sqlite3
+ - ubuntu-toolchain-r-test
packages:
- - sqlite3
+ - gcc-4.9
+ - g++-4.9
+ - libssl-dev
+ - libbluetooth3
+ - libbluetooth-dev
+ - libudev-dev
+ - cmake
+ - html2text
+ - clang-format-3.6
before_install:
- sudo apt-get -qq update
- - sudo apt-get install -y libavahi-client-dev libssl-dev libbluetooth3 libbluetooth-dev bluez-tools libudev-dev
- - sudo add-apt-repository ppa:kalakris/cmake -y
- - sudo apt-get update -q
- - sudo apt-get install -y cmake
+ - sudo apt-get -q -y install libavahi-client-dev bluez-tools sqlite3 libsqlite3-dev automake1.11
+ - wget http://archive.ubuntu.com/ubuntu/pool/main/l/lcov/lcov_1.11-3_all.deb
+ - sudo dpkg -i lcov_1.11-3_all.deb
script:
- - mkdir build && cd build && cmake ../ && make && make install \ No newline at end of file
+ - sudo ln -sf /usr/bin/gcov-4.9 /usr/bin/gcov
+ - bash -e tools/infrastructure/check_style.sh
+ - mkdir build && cd build && cmake ../ -DBUILD_TESTS=ON -DENABLE_GCOV=ON && make install
+ - sudo ldconfig
+ - make test
+ - bash -ex ../tools/infrastructure/collect_coverage.sh ./
+env:
+ global:
+ - LC_CTYPE=en_US.UTF-8
+ - CTEST_OUTPUT_ON_FAILURE=TRUE
+ - CMAKE_CXX_COMPILER=g++-4.9
+ - CMAKE_C_COMPILER=gcc-4.9
+ - LD_LIBRARY_PATH=.
+after_success:
+ - pwd ; bash <(curl -s https://codecov.io/bash) -f ./coverage/coverage.info || echo "Codecov did not collect coverage reports"
+deploy:
+ provider: releases
+ api-key: "uw8e4USTAS6c9LFhRMYOvw"
+ file:
+ - "coverage_report.tar.gz"
+ skip_cleanup: true
+ on:
+ tags: true
+notifications:
+ email:
+ - AKutsan@luxoft.com
+ - AByzhynar@luxoft.com
+ - NSnitsar@luxoft.com
+ - RMalynovskyi@luxoft.com
+ - MGhiumiusliu@luxoft.com
+ - AGaliuzov@luxoft.com
+ - ANosach@luxoft.com
+
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 1d63531e75..a4358b5b7e 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -40,16 +40,15 @@ option(EXTENDED_MEDIA_MODE "Turn on and off extended Madia Manager features rela
option(BUILD_SHARED_LIBS "Build all libraries as shared (if ON) or static (if OFF)" OFF)
option(BUILD_BT_SUPPORT "Bluetooth support" ON)
option(BUILD_USB_SUPPORT "libusb support" ON)
-option(BUILD_AVAHI_SUPPORT "libavahi support" ON)
option(BUILD_BACKTRACE_SUPPORT "backtrace support" ON)
option(BUILD_TESTS "Possibility to build and run tests" OFF)
-option(TIME_TESTER "Enable profiling time test util" ON)
+option(TELEMETRY_MONITOR "Enable profiling time test util" ON)
option(ENABLE_LOG "Logging feature" ON)
option(ENABLE_GCOV "gcov code coverage feature" OFF)
option(ENABLE_SANITIZE "Sanitize tool" OFF)
option(ENABLE_SECURITY "Security Ford protocol protection" ON)
option(ENABLE_HMI_PTU_DECRYPTION "Policy table update parsed by hmi" ON)
-option(ENABLE_EXTENDED_POLICY "Turns extended flow which requires embedded system interaction" OFF)
+option(ENABLE_EXTENDED_POLICY "Turns extended flow which requires embedded system interaction" ON)
set(OS_TYPE_OPTION "$ENV{OS_TYPE}")
set(DEBUG_OPTION "$ENV{DEBUG}")
@@ -57,6 +56,7 @@ set(HMI_TYPE_OPTION "$ENV{HMI_TYPE}")
set(TARGET_OPTION "$ENV{TARGET}")
set(MEDIA_MODE_OPTION "$ENV{MEDIA_MODE}")
set(HMI_ADAPTER_OPTION "$ENV{HMI_ADAPTER}")
+set(ENABLE_TESTS_OPTION "$ENV{ENABLE_TESTS}")
set(ENABLE_LOG_OPTION "$ENV{ENABLE_LOG}")
set(ARCH_TYPE_OPTION "$ENV{ARCH_TYPE}")
set(POLICY_OPTION "$ENV{POLICY_TYPE}")
@@ -64,7 +64,8 @@ set(SECURITY_OPTION "$ENV{SECURITY_MODE}")
set(COMPONENTS_DIR ${CMAKE_SOURCE_DIR}/src/components)
set(SNAPSHOT_TAG "$ENV{SNAPSHOT_TAG}")
-
+set(CMAKE_CXX_COMPILER $ENV{CMAKE_CXX_COMPILER})
+set(CMAKE_C_COMPILER $ENV{CMAKE_C_COMPILER})
if (ARCH_TYPE_OPTION)
if (NOT (${ARCH_TYPE_OPTION} STREQUAL "x86") AND NOT (${ARCH_TYPE_OPTION} STREQUAL "armv7"))
@@ -75,19 +76,6 @@ else ()
set(ARCH_TYPE_OPTION "x86")
endif()
-set(objcopy "objcopy")
-if (OS_TYPE_OPTION)
- if (${OS_TYPE_OPTION} STREQUAL "QNX")
- message(STATUS "Jenkins integration: set build process for QNX")
- #do not use include after project() command.
- #Such usecase results in infinite cycle of reinitialization of compiler and other variables
- INCLUDE("./qnx_6.5.0_linux_x86.cmake")
- set(objcopy "nto${ARCH_TYPE_OPTION}-objcopy")
- #tests are not supported yet for QNX build
- set (BUILD_TESTS OFF)
- endif()
-endif()
-
if (HMI_TYPE_OPTION)
if (${HMI_TYPE_OPTION} STREQUAL "HTML5")
message(STATUS "Jenkins integration: select HTML5 HMI")
@@ -135,6 +123,15 @@ if (ENABLE_LOG_OPTION)
endif()
endif()
+if (ENABLE_TESTS_OPTION)
+ if (${ENABLE_TESTS_OPTION} STREQUAL "TESTS_OFF")
+ message(STATUS "Jenkins integration: Unit tests is turned off")
+ set (BUILD_TESTS OFF)
+ elseif(${ENABLE_TESTS_OPTION} STREQUAL "TESTS_ON")
+ message(STATUS "Jenkins integration: Unit tests is turned on")
+ set (BUILD_TESTS ON)
+ endif()
+endif()
if (SECURITY_OPTION)
if (${SECURITY_OPTION} STREQUAL "SEC_OFF")
@@ -143,6 +140,19 @@ if (SECURITY_OPTION)
endif()
endif()
+set(objcopy "objcopy")
+if (OS_TYPE_OPTION)
+ if (${OS_TYPE_OPTION} STREQUAL "QNX")
+ message(STATUS "Jenkins integration: set build process for QNX")
+ #do not use include after project() command.
+ #Such usecase results in infinite cycle of reinitialization of compiler and other variables
+ INCLUDE("./qnx_6.5.0_linux_x86.cmake")
+ set(objcopy "nto${ARCH_TYPE_OPTION}-objcopy")
+ #tests are not supported yet for QNX build
+ set (BUILD_TESTS OFF)
+ endif()
+endif()
+
#Jenkins integration section end
add_custom_target(pasa-tarball
@@ -174,7 +184,7 @@ set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules/")
set(CMAKE_INSTALL_PREFIX ${CMAKE_CURRENT_BINARY_DIR})
set(ARCHIVE_OUTPUT_DIRECTORY ./bin)
-set(CMAKE_CXX_FLAGS "-fPIC -std=gnu++0x -Wall -Werror -Wuninitialized -Wvla")
+set(CMAKE_CXX_FLAGS "-fPIC -std=gnu++0x -Wall -Werror -Wno-deprecated-declarations -Wuninitialized -Wvla")
if(ENABLE_SANITIZE)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address")
@@ -191,7 +201,6 @@ if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
elseif(CMAKE_SYSTEM_NAME STREQUAL "QNX")
add_definitions(-DOS_QNX)
SET(BUILD_BT_SUPPORT OFF)
- SET(BUILD_AVAHI_SUPPORT OFF)
SET(BUILD_BACKTRACE_SUPPORT OFF)
SET(EXTENDED_MEDIA_MODE OFF)
endif()
@@ -208,14 +217,6 @@ if (BUILD_BT_SUPPORT)
message(STATUS "Bluetooth support is enabled")
endif()
-
-if (BUILD_AVAHI_SUPPORT)
- add_definitions(-DAVAHI_SUPPORT)
-# --- Check libavahi-common, libavahi-client availability
- find_package(Libavahi)
- message(STATUS "Avahi support is enabled")
-endif()
-
if (BUILD_BACKTRACE_SUPPORT)
add_definitions(-DBACKTRACE_SUPPORT)
endif()
@@ -225,8 +226,8 @@ if(ENABLE_LOG)
set(install-3rd_party_logger "install-3rd_party_logger")
endif()
-if (TIME_TESTER)
- add_definitions(-DTIME_TESTER)
+if (TELEMETRY_MONITOR)
+ add_definitions(-DTELEMETRY_MONITOR)
endif()
if (ENABLE_EXTENDED_POLICY)
@@ -380,6 +381,9 @@ endif()
include_directories(
${COMPONENTS_DIR}/include
${COMPONENTS_DIR}/protocol/include
+if (BUILD_TESTS)
+ ${COMPONENTS_DIR}/include/test
+endif ()
)
# --- 3rd party libs
@@ -411,23 +415,23 @@ if(ENABLE_LOG)
else()
if(FORCE_3RD_PARTY_LOGGER)
message(STATUS "Force to rebuild logger.")
-
+
#build logger
add_custom_target(3rd_party_logger
- make
+ make
WORKING_DIRECTORY ${3RD_PARTY_BINARY_DIRECTORY}
)
-
+
#install logger
#install either to default place with sudo or non-default plase without sudo.
#to install with sudo to non-default place use manual installation
add_custom_target(install-3rd_party_logger
- COMMAND /bin/bash -c \"USE_DEFAULT_3RD_PARTY_PATH=${USE_DEFAULT_3RD_PARTY_PATH}\;
- if [ \\$$USE_DEFAULT_3RD_PARTY_PATH == "true" ]\; then
- sudo -k \;
- sudo make install\;
- else
- make install\;
+ COMMAND /bin/bash -c \"USE_DEFAULT_3RD_PARTY_PATH=${USE_DEFAULT_3RD_PARTY_PATH}\;
+ if [ \\$$USE_DEFAULT_3RD_PARTY_PATH == "true" ]\; then
+ sudo -k \;
+ sudo make install\;
+ else
+ make install\;
fi\"
DEPENDS 3rd_party_logger
WORKING_DIRECTORY ${3RD_PARTY_BINARY_DIRECTORY}
@@ -435,74 +439,74 @@ if(ENABLE_LOG)
else()
#build logger
add_custom_target(3rd_party_logger
- COMMAND /bin/bash -c \"cd ${CMAKE_CURRENT_SOURCE_DIR} &&
- grep .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/liblog4cxx.so 1>/dev/null 2>&1\;
- if [ \\$$? == 0 ]\; then
- VAR1=\\$$\( readelf -p .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/liblog4cxx.so 2>/dev/null\)\;
- VAR1=\\$$\(echo \\$$VAR1 | awk '{print \\$$NF}'\)\;
+ COMMAND /bin/bash -c \"cd ${CMAKE_CURRENT_SOURCE_DIR} &&
+ grep .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/liblog4cxx.so 1>/dev/null 2>&1\;
+ if [ \\$$? == 0 ]\; then
+ VAR1=\\$$\( readelf -p .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/liblog4cxx.so 2>/dev/null\)\;
+ VAR1=\\$$\(echo \\$$VAR1 | awk '{print \\$$NF}'\)\;
VAR2=-1\;
cd ${CMAKE_CURRENT_SOURCE_DIR}\;
git log . 1>/dev/null 2>&1\;
- if [ \\$$? == 0 ]; then
- VAR2=\\$$\(git log --pretty=\"format:%H\" -1 ${3RD_PARTY_SOURCE_DIRECTORY}/apache-log4cxx-0.10.0\)\;
+ if [ \\$$? == 0 ]; then
+ VAR2=\\$$\(git log --pretty=\"format:%H\" -1 ${3RD_PARTY_SOURCE_DIRECTORY}/apache-log4cxx-0.10.0\)\;
+ fi\;
+ if [ \\$$VAR1 != \\$$VAR2 ]\; then
+ echo " Need to rebuild logger. " \;
+ cd ${3RD_PARTY_BINARY_DIRECTORY}\;
+ make\;
+ else
+ echo " Logger is actual. " \;
fi\;
- if [ \\$$VAR1 != \\$$VAR2 ]\; then
- echo " Need to rebuild logger. " \;
- cd ${3RD_PARTY_BINARY_DIRECTORY}\;
- make\;
- else
- echo " Logger is actual. " \;
- fi\;
- else
- echo " Need to build logger. " \;
- cd ${3RD_PARTY_BINARY_DIRECTORY}\;
- make\;
+ else
+ echo " Need to build logger. " \;
+ cd ${3RD_PARTY_BINARY_DIRECTORY}\;
+ make\;
fi\"
WORKING_DIRECTORY ${3RD_PARTY_BINARY_DIRECTORY}
)
-
+
#install logger
#install either to default place with sudo or non-default plase without sudo.
#to install with sudo to non-default place use manual installation
add_custom_target(install-3rd_party_logger
- COMMAND /bin/bash -c \"cd ${CMAKE_CURRENT_SOURCE_DIR} &&
- grep .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/liblog4cxx.so 1>/dev/null 2>&1\;
- if [ \\$$? == 0 ]\; then
- VAR1=\\$$\( readelf -p .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/liblog4cxx.so 2>/dev/null\)\;
- VAR1=\\$$\(echo \\$$VAR1 | awk '{print \\$$NF}'\)\;
+ COMMAND /bin/bash -c \"cd ${CMAKE_CURRENT_SOURCE_DIR} &&
+ grep .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/liblog4cxx.so 1>/dev/null 2>&1\;
+ if [ \\$$? == 0 ]\; then
+ VAR1=\\$$\( readelf -p .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/liblog4cxx.so 2>/dev/null\)\;
+ VAR1=\\$$\(echo \\$$VAR1 | awk '{print \\$$NF}'\)\;
VAR2=-1\;
cd ${CMAKE_CURRENT_SOURCE_DIR}\;
git log . 1>/dev/null 2>&1\;
- if [ \\$$? == 0 ]; then
- VAR2=\\$$\(git log --pretty=\"format:%H\" -1 ${3RD_PARTY_SOURCE_DIRECTORY}/apache-log4cxx-0.10.0\)\;
+ if [ \\$$? == 0 ]; then
+ VAR2=\\$$\(git log --pretty=\"format:%H\" -1 ${3RD_PARTY_SOURCE_DIRECTORY}/apache-log4cxx-0.10.0\)\;
fi\;
- if [ \\$$VAR1 != \\$$VAR2 ]\; then
- USE_DEFAULT_3RD_PARTY_PATH=${USE_DEFAULT_3RD_PARTY_PATH}\;
- if [ \\$$USE_DEFAULT_3RD_PARTY_PATH == "true" ]\; then
+ if [ \\$$VAR1 != \\$$VAR2 ]\; then
+ USE_DEFAULT_3RD_PARTY_PATH=${USE_DEFAULT_3RD_PARTY_PATH}\;
+ if [ \\$$USE_DEFAULT_3RD_PARTY_PATH == "true" ]\; then
cd ${3RD_PARTY_BINARY_DIRECTORY}\;
- sudo -k \;
- sudo make install\;
- else
+ sudo -k \;
+ sudo make install\;
+ else
cd ${3RD_PARTY_BINARY_DIRECTORY}\;
- make install\;
- fi\;
- fi\;
- else
- USE_DEFAULT_3RD_PARTY_PATH=${USE_DEFAULT_3RD_PARTY_PATH}\;
- if [ \\$$USE_DEFAULT_3RD_PARTY_PATH == "true" ]\; then
+ make install\;
+ fi\;
+ fi\;
+ else
+ USE_DEFAULT_3RD_PARTY_PATH=${USE_DEFAULT_3RD_PARTY_PATH}\;
+ if [ \\$$USE_DEFAULT_3RD_PARTY_PATH == "true" ]\; then
cd ${3RD_PARTY_BINARY_DIRECTORY}\;
- sudo -k \;
- sudo make install\;
- else
+ sudo -k \;
+ sudo make install\;
+ else
cd ${3RD_PARTY_BINARY_DIRECTORY}\;
- make install\;
+ make install\;
fi\;
fi\"
DEPENDS 3rd_party_logger
WORKING_DIRECTORY ${3RD_PARTY_BINARY_DIRECTORY}
)
endif()
-
+
set (install-3rd_party_logger_var "install-3rd_party_logger")
endif()
endif()
@@ -513,23 +517,23 @@ if (HMIADAPTER STREQUAL "dbus")
else()
if(FORCE_3RD_PARTY_DBUS)
message(STATUS "Force to rebuild D-Bus.")
-
+
#build d-bus
add_custom_target(3rd_party_dbus
make
WORKING_DIRECTORY ${3RD_PARTY_BINARY_DIRECTORY}
)
-
+
#install d-bus
#install either to default place with sudo or non-default plase without sudo.
#to install with sudo to non-default place use manual installation
add_custom_target(install-3rd_party_dbus
- COMMAND /bin/bash -c \"USE_DEFAULT_3RD_PARTY_PATH=${USE_DEFAULT_3RD_PARTY_PATH}\;
- if [ \\$$USE_DEFAULT_3RD_PARTY_PATH == "true" ]\; then
- sudo -k \;
- sudo make install\;
- else
- make install\;
+ COMMAND /bin/bash -c \"USE_DEFAULT_3RD_PARTY_PATH=${USE_DEFAULT_3RD_PARTY_PATH}\;
+ if [ \\$$USE_DEFAULT_3RD_PARTY_PATH == "true" ]\; then
+ sudo -k \;
+ sudo make install\;
+ else
+ make install\;
fi\"
DEPENDS 3rd_party_dbus
WORKING_DIRECTORY ${3RD_PARTY_BINARY_DIRECTORY}
@@ -537,72 +541,72 @@ if (HMIADAPTER STREQUAL "dbus")
else()
#build d-bus
add_custom_target(3rd_party_dbus
- COMMAND /bin/bash -c \"grep .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/libdbus-1.so 1>/dev/null 2>&1\;
- if [ \\$$? == 0 ]\; then
- VAR1=\\$$\(readelf -p .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/libdbus-1.so 2>/dev/null\)\;
- VAR1=\\$$\(echo \\$$VAR1 | awk '{print \\$$NF}'\)\;
+ COMMAND /bin/bash -c \"grep .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/libdbus-1.so 1>/dev/null 2>&1\;
+ if [ \\$$? == 0 ]\; then
+ VAR1=\\$$\(readelf -p .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/libdbus-1.so 2>/dev/null\)\;
+ VAR1=\\$$\(echo \\$$VAR1 | awk '{print \\$$NF}'\)\;
VAR2=-1\;
cd ${CMAKE_CURRENT_SOURCE_DIR}\;
git log . 1>/dev/null 2>&1\;
- if [ \\$$? == 0 ]; then
- VAR2=\\$$\(git log --pretty=\"format:%H\" -1 ${3RD_PARTY_SOURCE_DIRECTORY}/dbus-1.7.8\)\;
+ if [ \\$$? == 0 ]; then
+ VAR2=\\$$\(git log --pretty=\"format:%H\" -1 ${3RD_PARTY_SOURCE_DIRECTORY}/dbus-1.7.8\)\;
+ fi\;
+ if [ \\$$VAR1 != \\$$VAR2 ]\; then
+ echo " Need to rebuild D-Bus. " \;
+ cd ${3RD_PARTY_BINARY_DIRECTORY}\;
+ make\;
+ else
+ echo " D-Bus is actual. " \;
fi\;
- if [ \\$$VAR1 != \\$$VAR2 ]\; then
- echo " Need to rebuild D-Bus. " \;
- cd ${3RD_PARTY_BINARY_DIRECTORY}\;
- make\;
- else
- echo " D-Bus is actual. " \;
- fi\;
- else
- echo " Need to build D-Bus. " \;
- cd ${3RD_PARTY_BINARY_DIRECTORY}\;
- make\;
+ else
+ echo " Need to build D-Bus. " \;
+ cd ${3RD_PARTY_BINARY_DIRECTORY}\;
+ make\;
fi\"
WORKING_DIRECTORY ${3RD_PARTY_BINARY_DIRECTORY}
)
-
+
#install d-bus
#install either to default place with sudo or non-default plase without sudo.
#to install with sudo to non-default place use manual installation
add_custom_target(install-3rd_party_dbus
- COMMAND /bin/bash -c \"grep .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/libdbus-1.so 1>/dev/null 2>&1\;
- if [ \\$$? == 0 ]\; then
- VAR1=\\$$\(readelf -p .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/libdbus-1.so 2>/dev/null\)\;
- VAR1=\\$$\(echo \\$$VAR1 | awk '{print \\$$NF}'\)\;
+ COMMAND /bin/bash -c \"grep .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/libdbus-1.so 1>/dev/null 2>&1\;
+ if [ \\$$? == 0 ]\; then
+ VAR1=\\$$\(readelf -p .commit_hash ${3RD_PARTY_INSTALL_PREFIX_ARCH}/lib/libdbus-1.so 2>/dev/null\)\;
+ VAR1=\\$$\(echo \\$$VAR1 | awk '{print \\$$NF}'\)\;
VAR2=-1\;
cd ${CMAKE_CURRENT_SOURCE_DIR}\;
git log . 1>/dev/null 2>&1\;
- if [ \\$$? == 0 ]; then
- VAR2=\\$$\(git log --pretty=\"format:%H\" -1 ${3RD_PARTY_SOURCE_DIRECTORY}/dbus-1.7.8\)\;
+ if [ \\$$? == 0 ]; then
+ VAR2=\\$$\(git log --pretty=\"format:%H\" -1 ${3RD_PARTY_SOURCE_DIRECTORY}/dbus-1.7.8\)\;
fi\;
- if [ \\$$VAR1 != \\$$VAR2 ]\; then
- USE_DEFAULT_3RD_PARTY_PATH=${USE_DEFAULT_3RD_PARTY_PATH}\;
- if [ \\$$USE_DEFAULT_3RD_PARTY_PATH == "true" ]\; then
+ if [ \\$$VAR1 != \\$$VAR2 ]\; then
+ USE_DEFAULT_3RD_PARTY_PATH=${USE_DEFAULT_3RD_PARTY_PATH}\;
+ if [ \\$$USE_DEFAULT_3RD_PARTY_PATH == "true" ]\; then
cd ${3RD_PARTY_BINARY_DIRECTORY}\;
- sudo -k \;
- sudo make install\;
- else
+ sudo -k \;
+ sudo make install\;
+ else
cd ${3RD_PARTY_BINARY_DIRECTORY}\;
- make install\;
- fi\;
- fi\;
- else
- USE_DEFAULT_3RD_PARTY_PATH=${USE_DEFAULT_3RD_PARTY_PATH}\;
- if [ \\$$USE_DEFAULT_3RD_PARTY_PATH == "true" ]\; then
+ make install\;
+ fi\;
+ fi\;
+ else
+ USE_DEFAULT_3RD_PARTY_PATH=${USE_DEFAULT_3RD_PARTY_PATH}\;
+ if [ \\$$USE_DEFAULT_3RD_PARTY_PATH == "true" ]\; then
cd ${3RD_PARTY_BINARY_DIRECTORY}\;
- sudo -k \;
- sudo make install\;
- else
+ sudo -k \;
+ sudo make install\;
+ else
cd ${3RD_PARTY_BINARY_DIRECTORY}\;
- make install\;
- fi\;
+ make install\;
+ fi\;
fi\"
DEPENDS 3rd_party_dbus
WORKING_DIRECTORY ${3RD_PARTY_BINARY_DIRECTORY}
)
endif()
-
+
set (install-3rd_party_dbus_var "install-3rd_party_dbus")
endif()
endif()
@@ -667,8 +671,8 @@ if(BUILD_TESTS)
include(Dart)
#add_subdirectory(./test)
endif()
-
-# Building documentation
+
+# Building documentation
# At first creating directory for generated documentation. Unfortunately doxygen
# cannot generate it byself
diff --git a/COMMITTERS.md b/COMMITTERS.md
index df5fee94df..284351aff1 100644
--- a/COMMITTERS.md
+++ b/COMMITTERS.md
@@ -18,6 +18,11 @@ set in the form of a pull request.
**develop branch** - [The branch](https://github.com/LuxoftSDL/sdl_core/tree/develop) where bug fixes against the latest release or release candidate are merged.
+## Pre-commit hook installation
+* Go to tools/infrastructure/
+* Run install-hooks.py
+* or : Just run "python tools/infrastructure/install-hooks.py"
+
##Pull request checklist
* Add Unit tests.
* All tests pass (see Run all tests section).
diff --git a/README.md b/README.md
index 2384d2cc70..e9aaeade60 100644
--- a/README.md
+++ b/README.md
@@ -2,6 +2,8 @@
[![Build Status](https://travis-ci.org/smartdevicelink/sdl_core.svg?branch=master)](https://travis-ci.org/smartdevicelink/sdl_core)
+ [![codecov.io](https://codecov.io/github/smartdevicelink/sdl_core/coverage.svg?branch=develop)](https://codecov.io/github/smartdevicelink/sdl_core?branch=develop)
+
# SmartDeviceLink (SDL)
SmartDeviceLink (SDL) is a standard set of protocols and messages that connect applications on a smartphone to a vehicle head unit. This messaging enables a consumer to interact with their application using common in-vehicle interfaces such as a touch screen display, embedded voice recognition, steering wheel controls and various vehicle knobs and buttons. There are three main components that make up the SDL ecosystem.
@@ -17,9 +19,7 @@ Pull Requests Welcome!
* [Software Architecture Document](https://app.box.com/s/v5ymu5kathzkwfx8iigxxdpr7d5a2xhh)
* [Transport Manager Programming Guide](https://app.box.com/s/1pjquttvmhf19uujtw4x4fv4t1leqasa)
* [Software Detailed Design](https://app.box.com/s/ohgrvemtx39f8hfea1ab676xxrzvyx1y)
- * [Integration Guidelines](https://app.box.com/s/ohcgjv61cykgkuhycglju6cc4efr0ym3)
-
-<a href="http://www.youtube.com/watch?feature=player_embedded&v=AzdQdSCS24M" target="_blank"><img src="http://i.imgur.com/nm8UujD.png?1" alt="SmartDeviceLink" border="10" /></a>
+ * [Integration Guidelines](https://app.box.com/s/jkj51mkaa5uganbhjxmtv06lbs8hapa9)
## SDL Core
@@ -165,6 +165,26 @@ Take the following steps to launch applications from sdl core.
6. Both applications should show up on the head unit for launching
7. Select the other application, and you should see it launched and brought to the foreground on the phone
+## Test Coverage
+### Used technologies
+ * GCOV - test coverage program.
+ * LCOV - graphical front-end for GCC's coverage testing tool for gcov.
+ * codecov.io - service for assembling code coverage and representing it in a clear for reading form.
+
+### Excluded folders
+_We test only sources written by us and we don`t need to test external sources(open source libraries)._
+ * '/usr/\*' - local libraries shouldn`t be covered by tests.
+ * '\*/test/\*' - we don`t need to cover tests.
+ * '\*/src/3rd\*' - open source libraries shouldn`t be covered by tests.
+
+### Current test coverage
+You can find it in [Coverage report](https://codecov.io/gh/smartdevicelink/sdl_core/branch/develop)
+
+### How to get Test Coverage locally
+ 1. Build project with enabled flag _-DBUILD_TESTS=on_
+ 2. Execute command 'make test'
+ 3. Execute './tools/Utils/collect_coverage.sh <path_to_build_directory>'
+
## Contributions
Conversation regarding the design and development of SmartDeviceLink technology should be directed at the [GENIVI mailing list](https://lists.genivi.org/mailman/listinfo/genivi-smartdevicelink), which anyone can join. Public conference calls regarding the SmartDeviceLink technology will be announced to the GENIVI mailing list, we expect to have conversations every other week. We also encourage interested parties to write issues against our software, and submit pull requests right here in the GitHub repository.
diff --git a/cmake/Modules/FindLibavahi.cmake b/cmake/Modules/FindLibavahi.cmake
deleted file mode 100644
index 2bc9055059..0000000000
--- a/cmake/Modules/FindLibavahi.cmake
+++ /dev/null
@@ -1,29 +0,0 @@
-# --- Check libavahi-common, libavahi-client availability
-
-FIND_LIBRARY(
- LIBAVAHI_CLIENT
- NAMES libavahi-client.so
- PATHS /usr/local/lib /usr/lib /opt/local/include /usr/lib/i386-linux-gnu/
- )
-
-if (NOT LIBAVAHI_CLIENT)
- message(STATUS " libavahi-client is not found")
- message(STATUS " To install it type in the command line:")
- message(STATUS " sudo apt-get install libavahi-client-dev")
-endif (NOT LIBAVAHI_CLIENT)
-
-FIND_LIBRARY(
- LIBAVAHI_COMMON
- NAMES libavahi-common.so
- PATHS /usr/local/lib /usr/lib /opt/local/include /usr/lib/i386-linux-gnu/
- )
-
-if (NOT LIBAVAHI_COMMON)
- message(STATUS " libavahi-common is not found")
- message(STATUS " To install it type in the command line:")
- message(STATUS " sudo apt-get install libavahi-common-dev")
-endif (NOT LIBAVAHI_COMMON)
-
-if (NOT LIBAVAHI_COMMON OR NOT LIBAVAHI_CLIENT)
- message(FATAL_ERROR "One of necesary component of libavahi is not found. Exiting!")
-endif(NOT LIBAVAHI_COMMON OR NOT LIBAVAHI_CLIENT) \ No newline at end of file
diff --git a/src/3rd_party-static/MessageBroker/include/mb_controller.hpp b/src/3rd_party-static/MessageBroker/include/mb_controller.hpp
index 930a53b385..2d196aced2 100644
--- a/src/3rd_party-static/MessageBroker/include/mb_controller.hpp
+++ b/src/3rd_party-static/MessageBroker/include/mb_controller.hpp
@@ -13,6 +13,7 @@
#include "mb_tcpclient.hpp"
#include "utils/lock.h"
+#include "utils/atomic_object.h"
#include <cstring>
@@ -196,7 +197,7 @@ namespace NsMessageBroker
/**
* @brief flag top stop thread
*/
- volatile bool stop;
+ sync_primitives::atomic_bool stop;
private:
/**
@@ -247,12 +248,6 @@ namespace NsMessageBroker
* @brief mutex for mWaitResponseQueue
*/
sync_primitives::Lock queue_lock_;
-
- /*
- * @brief mutex for Mutex for correct finishing of receiving thread
- */
- sync_primitives::Lock receiving_thread_lock_;
-
};
} /* namespace NsMessageBroker */
#endif /* MB_CONTROLLER_H */
diff --git a/src/3rd_party-static/MessageBroker/src/client/mb_controller.cpp b/src/3rd_party-static/MessageBroker/src/client/mb_controller.cpp
index c37a62dbb8..8a4a77cf30 100644
--- a/src/3rd_party-static/MessageBroker/src/client/mb_controller.cpp
+++ b/src/3rd_party-static/MessageBroker/src/client/mb_controller.cpp
@@ -13,6 +13,7 @@ namespace NsMessageBroker
{
CMessageBrokerController::CMessageBrokerController(const std::string& address, uint16_t port, std::string name):
TcpClient(address, port),
+ stop(false),
m_receivingBuffer(""),
mControllersIdStart(-1),
mControllersIdCurrent(0)
@@ -20,7 +21,6 @@ namespace NsMessageBroker
mControllersName = name;
}
-
std::string CMessageBrokerController::getControllersName()
{
return mControllersName;
@@ -272,7 +272,6 @@ namespace NsMessageBroker
void* CMessageBrokerController::MethodForReceiverThread(void * arg)
{
- sync_primitives::AutoLock auto_lock(receiving_thread_lock_);
stop = false;
arg = arg; // to avoid compiler warnings
while(!stop)
diff --git a/src/3rd_party-static/MessageBroker/src/lib_messagebroker/system.cpp b/src/3rd_party-static/MessageBroker/src/lib_messagebroker/system.cpp
index be9b35d611..456362f9d8 100644
--- a/src/3rd_party-static/MessageBroker/src/lib_messagebroker/system.cpp
+++ b/src/3rd_party-static/MessageBroker/src/lib_messagebroker/system.cpp
@@ -23,6 +23,7 @@
*/
#include <time.h>
+#include <signal.h>
#include "system.h"
@@ -91,6 +92,13 @@ bool Thread::Join(void** ret) {
}
void* Thread::Call(void* arg) {
+ // Disable system signals receiving in thread
+ // by setting empty signal mask
+ // (system signals processes only in the main thread)
+ sigset_t set;
+ sigfillset(&set);
+ pthread_sigmask(SIG_SETMASK, &set, NULL);
+
Thread* thread = static_cast<Thread*>(arg);
/* call our specific object method */
diff --git a/src/3rd_party-static/gmock-1.7.0/include/gmock/gmock-spec-builders.h b/src/3rd_party-static/gmock-1.7.0/include/gmock/gmock-spec-builders.h
index 312fbe8705..ec7a9bd000 100644
--- a/src/3rd_party-static/gmock-1.7.0/include/gmock/gmock-spec-builders.h
+++ b/src/3rd_party-static/gmock-1.7.0/include/gmock/gmock-spec-builders.h
@@ -60,6 +60,10 @@
#ifndef GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
#define GMOCK_INCLUDE_GMOCK_GMOCK_SPEC_BUILDERS_H_
+#if defined(OS_POSIX)
+#include <sys/time.h>
+#endif
+
#include <map>
#include <set>
#include <sstream>
@@ -120,6 +124,16 @@ GTEST_API_ GTEST_DECLARE_STATIC_MUTEX_(g_gmock_mutex);
// Untyped base class for ActionResultHolder<R>.
class UntypedActionResultHolderBase;
+// Expectation results enum
+enum ExpectationResult {
+ // Some expectations are not satisfied
+ NotSatisfied,
+ // All expectations are satisfied
+ Satisfied,
+ // Some expectations are over satisfied
+ OverSaturated
+};
+
// Abstract base class of FunctionMockerBase. This is the
// type-agnostic part of the function mocker interface. Its pure
// virtual methods are implemented by FunctionMockerBase.
@@ -134,6 +148,12 @@ class GTEST_API_ UntypedFunctionMockerBase {
bool VerifyAndClearExpectationsLocked()
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
+ // Verifies that all expectations on this mock function have been
+ // satisfied. Does not report failures.
+ // Returns ExpectationResult value.
+ ExpectationResult VerifyExpectationsLocked()
+ GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex);
+
// Clears the ON_CALL()s set on this mock function.
virtual void ClearDefaultActionsLocked()
GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) = 0;
@@ -207,6 +227,11 @@ class GTEST_API_ UntypedFunctionMockerBase {
const char* Name() const
GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
+ // Returns the time of this mock registering. Must be called after
+ // RegisterOwner() has been called.
+ timeval RegisteredTime() const
+ GTEST_LOCK_EXCLUDED_(g_gmock_mutex);
+
// Returns the result of invoking this mock function with the given
// arguments. This function can be safely called from multiple
// threads concurrently. The caller is responsible for deleting the
@@ -234,6 +259,10 @@ class GTEST_API_ UntypedFunctionMockerBase {
// method has been called.
const char* name_; // Protected by g_gmock_mutex.
+ // Time of the function registering.
+ // Only valid after RegisterOwner() has been called.
+ timeval registered_time_; // Protected by g_gmock_mutex.
+
// All default action specs for this function mocker.
UntypedOnCallSpecs untyped_on_call_specs_;
@@ -389,6 +418,12 @@ class GTEST_API_ Mock {
static bool VerifyAndClear(void* mock_obj)
GTEST_LOCK_EXCLUDED_(internal::g_gmock_mutex);
+ // Asynchronously verifies all expectations of all registered mock objects
+ // and clears there default actions and expectations. Returns true if the
+ // verification was successful.
+ static bool AsyncVerifyAndClearExpectations(int timeout)
+ GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
+
private:
friend class internal::UntypedFunctionMockerBase;
@@ -438,6 +473,12 @@ class GTEST_API_ Mock {
static bool VerifyAndClearExpectationsLocked(void* mock_obj)
GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
+ // Asynchronously verifies that all expectations of all registered
+ // mock objects have been satisfied. Reports one or more Google
+ // Test non-fatal failures and returns false if not.
+ static bool AsyncVerifyAndClearExpectationsLocked(int timeout_msec)
+ GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
+
// Clears all ON_CALL()s set on the given mock object.
static void ClearDefaultActionsLocked(void* mock_obj)
GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex);
diff --git a/src/3rd_party-static/gmock-1.7.0/src/gmock-spec-builders.cc b/src/3rd_party-static/gmock-1.7.0/src/gmock-spec-builders.cc
index abaae3ad98..1219a3a3c9 100644
--- a/src/3rd_party-static/gmock-1.7.0/src/gmock-spec-builders.cc
+++ b/src/3rd_party-static/gmock-1.7.0/src/gmock-spec-builders.cc
@@ -64,6 +64,33 @@ GTEST_API_ void LogWithLocation(testing::internal::LogSeverity severity,
Log(severity, s.str(), 0);
}
+// Unlock internal mutex and wait for a while
+void UnlockAndSleep(const long usecs) {
+ g_gmock_mutex.Unlock();
+ Assert(usecs < 60L*1000*1000, __FILE__, __LINE__,
+ "Long sleep makes a bare back");
+ ::std::ostringstream s;
+ s << "Sleeping for " << 0.001 * usecs << "mSecs" << ::std::endl;
+ Log(testing::internal::kInfo, s.str(), 0);
+ usleep(usecs);
+ g_gmock_mutex.Lock();
+}
+
+// Return time structure with the current date/time stamp
+timeval GetCurrentTime() {
+ timeval now;
+ gettimeofday(&now, NULL);
+ return now;
+}
+
+// Unlock internal mutex and wait for a while
+long UsecsElapsed(const timeval start_time) {
+ timeval now = GetCurrentTime();
+ timeval priviously_elapsed;
+ timersub(&now, &start_time, &priviously_elapsed);
+ return priviously_elapsed.tv_sec*1000000L + priviously_elapsed.tv_usec;
+}
+
// Constructs an ExpectationBase object.
ExpectationBase::ExpectationBase(const char* a_file,
int a_line,
@@ -258,7 +285,9 @@ void ReportUninterestingCall(CallReaction reaction, const string& msg) {
}
UntypedFunctionMockerBase::UntypedFunctionMockerBase()
- : mock_obj_(NULL), name_("") {}
+ : mock_obj_(NULL), name_("") {
+ timerclear(&registered_time_);
+}
UntypedFunctionMockerBase::~UntypedFunctionMockerBase() {}
@@ -273,6 +302,7 @@ void UntypedFunctionMockerBase::RegisterOwner(const void* mock_obj)
mock_obj_ = mock_obj;
}
Mock::Register(mock_obj, this);
+ gettimeofday(&registered_time_, NULL);
}
// Sets the mock object this mock method belongs to, and sets the name
@@ -322,6 +352,17 @@ const char* UntypedFunctionMockerBase::Name() const
return name;
}
+// Returns the time of this mock method registering. Must be called
+// after RegisterOwner() has been called.
+timeval UntypedFunctionMockerBase::RegisteredTime() const
+ GTEST_LOCK_EXCLUDED_(g_gmock_mutex) {
+ g_gmock_mutex.AssertHeld();
+ Assert(timerisset(&registered_time_), __FILE__, __LINE__,
+ "RegisteredTime() must not be called before SetOwnerAndName() has "
+ "been called.");
+ return registered_time_;
+}
+
// Calculates the result of invoking this mock function with the given
// arguments, prints it, and returns it. The caller is responsible
// for deleting the result.
@@ -499,6 +540,23 @@ bool UntypedFunctionMockerBase::VerifyAndClearExpectationsLocked()
return expectations_met;
}
+ExpectationResult UntypedFunctionMockerBase::VerifyExpectationsLocked()
+ GTEST_EXCLUSIVE_LOCK_REQUIRED_(g_gmock_mutex) {
+ g_gmock_mutex.AssertHeld();
+ for (UntypedExpectations::const_iterator it =
+ untyped_expectations_.begin();
+ it != untyped_expectations_.end(); ++it) {
+ ExpectationBase* const untyped_expectation = it->get();
+ if (untyped_expectation->IsOverSaturated()) {
+ return OverSaturated;
+ }
+ if (!untyped_expectation->IsSatisfied()) {
+ return NotSatisfied;
+ }
+ }
+ return Satisfied;
+}
+
} // namespace internal
// Class Mock.
@@ -697,6 +755,108 @@ bool Mock::VerifyAndClearExpectationsLocked(void* mock_obj)
return expectations_met;
}
+bool Mock::AsyncVerifyAndClearExpectations(int timeout_msec)
+ GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
+ internal::MutexLock l(&internal::g_gmock_mutex);
+ return AsyncVerifyAndClearExpectationsLocked(timeout_msec);
+}
+
+bool Mock::AsyncVerifyAndClearExpectationsLocked(const int timeout_msec_in)
+ GTEST_EXCLUSIVE_LOCK_REQUIRED_(internal::g_gmock_mutex) {
+ internal::g_gmock_mutex.AssertHeld();
+ MockObjectRegistry::StateMap& state_map = g_mock_object_registry.states();
+ if (state_map.empty()) {
+ // No EXPECT_CALL() was set on the given mock object.
+ return true;
+ }
+
+ // TODO(ezamakhov@gmail.com): refactor the next loops
+ bool expectations_met = true;
+ timeval first_register_time {0, 0};
+ int timeout_msec = timeout_msec_in;
+ for (MockObjectRegistry::StateMap::iterator mock_it = state_map.begin();
+ state_map.end() != mock_it; ++mock_it) {
+ MockObjectState& state = mock_it->second;
+
+ // Verifies the expectations on each mock method in the
+ // given mock object.
+ FunctionMockers& mockers = state.function_mockers;
+ if (mockers.empty()) {
+ internal::Assert(!mockers.empty(), __FILE__, __LINE__,
+ "No functions mocked");
+ return true;
+ }
+
+ for (FunctionMockers::const_iterator it = mockers.begin();
+ it != mockers.end(); ++it) {
+ internal::UntypedFunctionMockerBase* base = *it;
+
+ const timeval register_time = base->RegisteredTime();
+ if (!timerisset(&first_register_time) ||
+ timercmp(&register_time, &first_register_time, <)) {
+ first_register_time = register_time;
+ }
+
+ // Waiting expectations loop
+ do {
+ const internal::ExpectationResult result =
+ base->VerifyExpectationsLocked();
+ if (result == internal::OverSaturated) {
+ expectations_met = false;
+ // break waiting procedure
+ break;
+ }
+ if (result == internal::Satisfied) {
+ // break waiting procedure
+ break;
+ }
+ if (result == internal::NotSatisfied) {
+ // If timeout expared
+ if (timeout_msec <= 0) {
+ expectations_met = false;
+ // break waiting procedure
+ break;
+ }
+ // Unlock callbacks procedures
+ static const int sleep_msec = 10;
+ internal::UnlockAndSleep(sleep_msec * 1000);
+ timeout_msec -= sleep_msec;
+ }
+ } while (true);
+ } // mockers iteration
+
+ if (expectations_met) {
+ const long elapsed_usecs =
+ // first_register_time is empty on no expectations in mocks
+ timerisset(&first_register_time)
+ ? internal::UsecsElapsed(first_register_time)
+ : 100 * 1000;
+ // To avoid waitings very long times.
+ const long max_sleep_time = timeout_msec_in * 10 * 1000;
+ if (max_sleep_time > elapsed_usecs * 2) {
+ // Wait double times
+ internal::UnlockAndSleep(elapsed_usecs * 2);
+ }
+ }
+
+ // Verifies and clears the expectations on each mock method in the
+ // given mock object.
+ for (FunctionMockers::const_iterator it = mockers.begin();
+ it != mockers.end(); ++it) {
+ internal::UntypedFunctionMockerBase* base = *it;
+ // Get finial result and clear expectation
+ const bool final_verification = base->VerifyAndClearExpectationsLocked();
+ if (!final_verification) {
+ expectations_met = false;
+ }
+ }
+ } // state_map iteration
+
+ // We don't clear the content of mockers, as they may still be
+ // needed by ClearDefaultActionsLocked().
+ return expectations_met;
+}
+
// Registers a mock object and a mock method it owns.
void Mock::Register(const void* mock_obj,
internal::UntypedFunctionMockerBase* mocker)
diff --git a/src/appMain/CMakeLists.txt b/src/appMain/CMakeLists.txt
index d27a282c2e..debcfe66c2 100644
--- a/src/appMain/CMakeLists.txt
+++ b/src/appMain/CMakeLists.txt
@@ -51,19 +51,20 @@ set(default_media_inc
)
endif()
-if (TIME_TESTER)
- set(TIME_TESTER_LIB
- TimeTester)
+if (TELEMETRY_MONITOR)
+ set(TELEMETRY_MONITOR_LIB
+ TelemetryMonitor)
endif()
set(LIBRARIES
MediaManager
ApplicationManager
+ MessageHelper
HMI_API
MOBILE_API
v4_protocol_v1_2_no_extra
SmartObjects
- ${TIME_TESTER_LIB}
+ ${TELEMETRY_MONITOR_LIB}
formatters
ProtocolLibrary
ProtocolHandler
@@ -87,9 +88,6 @@ endif()
if (BUILD_BT_SUPPORT)
list(APPEND LIBRARIES bluetooth)
endif()
-if (BUILD_AVAHI_SUPPORT)
- list(APPEND LIBRARIES avahi-client avahi-common)
-endif()
if (BUILD_USB_SUPPORT)
if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
list(APPEND LIBRARIES Libusb-1.0.16)
@@ -120,15 +118,14 @@ include_directories (
${COMPONENTS_DIR}/request_watchdog/include
${COMPONENTS_DIR}/smart_objects/include/
${COMPONENTS_DIR}/media_manager/include/
- ${COMPONENTS_DIR}/time_tester/include
- ${COMPONENTS_DIR}/policy/src/policy/include/
+ ${COMPONENTS_DIR}/telemetry_monitor/include
+ ${COMPONENTS_DIR}/policy/include/
${COMPONENTS_DIR}/resumption/include/
${MESSAGE_BROKER_INCLUDE_DIRECTORY}
${ENCRYPTION_INCLUDE_DIRECTORY}
${COMPONENTS_DIR}
${CMAKE_BINARY_DIR}/src/components/
${COMPONENTS_DIR}/dbus/include/
- ${CMAKE_BINARY_DIR}/src/components/policy/src/policy
${CMAKE_SOURCE_DIR}
${default_media_inc}
${LOG4CXX_INCLUDE_DIRECTORY}
diff --git a/src/appMain/hmi_capabilities.json b/src/appMain/hmi_capabilities.json
index e97a222368..41cf1d3bee 100644..100755
--- a/src/appMain/hmi_capabilities.json
+++ b/src/appMain/hmi_capabilities.json
@@ -1,10 +1,10 @@
{
"UI":
{
- "language":"EN_US",
+ "language":"EN-US",
"languages":[
- "EN_US","ES_MX","FR_CA","DE_DE","ES_ES","EN_GB","RU_RU","TR_TR","PL_PL","FR_FR","IT_IT","SV_SE","PT_PT","NL_NL","ZH_TW",
-"JA_JP","AR_SA","KO_KR","PT_BR","CS_CZ","DA_DK","NO_NO"
+ "EN-US","ES-MX","FR-CA","DE-DE","ES-ES","EN-GB","RU-RU","TR-TR","PL-PL","FR-FR","IT-IT","SV-SE","PT-PT","NL-NL","ZH-TW",
+"JA-JP","AR-SA","KO-KR","PT-BR","CS-CZ","DA-DK","NO-NO"
],
"displayCapabilities":
{
@@ -312,35 +312,43 @@
{
"samplingRate" : "44KHZ",
"bitsPerSample" : "RATE_8_BIT",
- "audioType" : "PCM"
+ "audioType" : "PCM"
+ },
+ "pcmStreamCapabilities":
+ {
+ "samplingRate" : "16KHZ",
+ "bitsPerSample" : "RATE_16_BIT",
+ "audioType" : "PCM"
},
"hmiZoneCapabilities":"FRONT",
"softButtonCapabilities":
- {
- "shortPressAvailable":true,
- "longPressAvailable" :true,
- "upDownAvailable" :true,
- "imageSupported" :true
- }
+ [
+ {
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true,
+ "imageSupported" :true
+ }
+ ]
},
"VR":
{
"capabilities":["TEXT"],
- "language":"EN_US",
+ "language":"EN-US",
"languages":
[
- "EN_US","ES_MX","FR_CA","DE_DE","ES_ES","EN_GB","RU_RU","TR_TR","PL_PL","FR_FR","IT_IT","SV_SE","PT_PT","NL_NL","ZH_TW",
-"JA_JP","AR_SA","KO_KR","PT_BR","CS_CZ","DA_DK","NO_NO"
+ "EN-US","ES-MX","FR-CA","DE-DE","ES-ES","EN-GB","RU-RU","TR-TR","PL-PL","FR-FR","IT-IT","SV-SE","PT-PT","NL-NL","ZH-TW",
+"JA-JP","AR-SA","KO-KR","PT-BR","CS-CZ","DA-DK","NO-NO"
]
},
"TTS":
{
"capabilities":"TEXT",
- "language":"EN_US",
+ "language":"EN-US",
"languages":
[
- "EN_US","ES_MX","FR_CA","DE_DE","ES_ES","EN_GB","RU_RU","TR_TR","PL_PL","FR_FR","IT_IT","SV_SE","PT_PT","NL_NL","ZH_TW",
-"JA_JP","AR_SA","KO_KR","PT_BR","CS_CZ","DA_DK","NO_NO"
+ "EN-US","ES-MX","FR-CA","DE-DE","ES-ES","EN-GB","RU-RU","TR-TR","PL-PL","FR-FR","IT-IT","SV-SE","PT-PT","NL-NL","ZH-TW",
+"JA-JP","AR-SA","KO-KR","PT-BR","CS-CZ","DA-DK","NO-NO"
]
},
"Buttons":
diff --git a/src/appMain/life_cycle.cc b/src/appMain/life_cycle.cc
index ca629e2311..1d8e92210e 100644
--- a/src/appMain/life_cycle.cc
+++ b/src/appMain/life_cycle.cc
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2014, Ford Motor Company
+* Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,145 +30,124 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include "./life_cycle.h"
+#include "life_cycle.h"
#include "utils/signals.h"
+#include "utils/make_shared.h"
#include "config_profile/profile.h"
#include "resumption/last_state.h"
#ifdef ENABLE_SECURITY
#include "security_manager/security_manager_impl.h"
#include "security_manager/crypto_manager_impl.h"
+#include "security_manager/crypto_manager_settings_impl.h"
+#include "application_manager/policies/policy_handler.h"
#endif // ENABLE_SECURITY
#ifdef ENABLE_LOG
#include "utils/log_message_loop_thread.h"
-#endif
+#endif // ENABLE_LOG
using threads::Thread;
namespace main_namespace {
-CREATE_LOGGERPTR_GLOBAL(logger_, "appMain")
+CREATE_LOGGERPTR_GLOBAL(logger_, "SDLMain")
namespace {
void NameMessageBrokerThread(const System::Thread& thread,
const std::string& name) {
Thread::SetNameForId(thread.GetId(), name);
}
+
+void StopThread(System::Thread* thread) {
+ if (thread) {
+ thread->Stop();
+ thread->Join();
+ delete thread;
+ }
+}
} // namespace
-LifeCycle::LifeCycle()
- : transport_manager_(NULL)
- , protocol_handler_(NULL)
- , connection_handler_(NULL)
- , app_manager_(NULL)
+LifeCycle::LifeCycle(const profile::Profile& profile)
+ : transport_manager_(NULL)
+ , protocol_handler_(NULL)
+ , connection_handler_(NULL)
+ , app_manager_(NULL)
#ifdef ENABLE_SECURITY
- , crypto_manager_(NULL)
- , security_manager_(NULL)
+ , crypto_manager_(NULL)
+ , security_manager_(NULL)
#endif // ENABLE_SECURITY
- , hmi_handler_(NULL)
- , hmi_message_adapter_(NULL)
- , media_manager_(NULL)
-#ifdef TIME_TESTER
- , time_tester_(NULL)
-#endif // TIME_TESTER
+ , hmi_handler_(NULL)
+ , hmi_message_adapter_(NULL)
+ , media_manager_(NULL)
+ , last_state_(NULL)
+#ifdef TELEMETRY_MONITOR
+ , telemetry_monitor_(NULL)
+#endif // TELEMETRY_MONITOR
#ifdef DBUS_HMIADAPTER
- , dbus_adapter_(NULL)
- , dbus_adapter_thread_(NULL)
+ , dbus_adapter_(NULL)
+ , dbus_adapter_thread_(NULL)
#endif // DBUS_HMIADAPTER
#ifdef MESSAGEBROKER_HMIADAPTER
- , mb_adapter_(NULL)
- , message_broker_(NULL)
- , message_broker_server_(NULL)
- , mb_thread_(NULL)
- , mb_server_thread_(NULL)
- , mb_adapter_thread_(NULL)
+ , mb_adapter_(NULL)
+ , message_broker_(NULL)
+ , message_broker_server_(NULL)
+ , mb_thread_(NULL)
+ , mb_server_thread_(NULL)
+ , mb_adapter_thread_(NULL)
#endif // MESSAGEBROKER_HMIADAPTER
- , components_started_(false)
-{ }
+ , profile_(profile) {
+}
bool LifeCycle::StartComponents() {
- LOG4CXX_INFO(logger_, "LifeCycle::StartComponents()");
- transport_manager_ =
- transport_manager::TransportManagerDefault::instance();
- DCHECK(transport_manager_ != NULL);
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK(!last_state_);
+ last_state_ = new resumption::LastState(profile_.app_storage_folder(),
+ profile_.app_info_storage());
+ DCHECK(!transport_manager_);
+ transport_manager_ = new transport_manager::TransportManagerDefault(profile_);
+
+ DCHECK(!connection_handler_);
+ connection_handler_ = new connection_handler::ConnectionHandlerImpl(
+ profile_, *transport_manager_);
+
+ DCHECK(!protocol_handler_);
protocol_handler_ =
- new protocol_handler::ProtocolHandlerImpl(transport_manager_,
- profile::Profile::instance()->message_frequency_time(),
- profile::Profile::instance()->message_frequency_count(),
- profile::Profile::instance()->malformed_message_filtering(),
- profile::Profile::instance()->malformed_frequency_time(),
- profile::Profile::instance()->malformed_frequency_count());
- DCHECK(protocol_handler_ != NULL);
-
- connection_handler_ =
- connection_handler::ConnectionHandlerImpl::instance();
- DCHECK(connection_handler_ != NULL);
+ new protocol_handler::ProtocolHandlerImpl(profile_,
+ *connection_handler_,
+ *connection_handler_,
+ *transport_manager_);
+ DCHECK(protocol_handler_);
+ DCHECK(!app_manager_);
app_manager_ =
- application_manager::ApplicationManagerImpl::instance();
- DCHECK(app_manager_ != NULL);
- if (!app_manager_->Init()) {
+ new application_manager::ApplicationManagerImpl(profile_, profile_);
+
+ DCHECK(!hmi_handler_);
+ hmi_handler_ = new hmi_message_handler::HMIMessageHandlerImpl(profile_);
+
+ media_manager_ = new media_manager::MediaManagerImpl(*app_manager_, profile_);
+ if (!app_manager_->Init(*last_state_, media_manager_)) {
LOG4CXX_ERROR(logger_, "Application manager init failed.");
return false;
}
- hmi_handler_ =
- hmi_message_handler::HMIMessageHandlerImpl::instance();
- DCHECK(hmi_handler_ != NULL)
-
#ifdef ENABLE_SECURITY
security_manager_ = new security_manager::SecurityManagerImpl();
+ crypto_manager_ = new security_manager::CryptoManagerImpl(
+ utils::MakeShared<security_manager::CryptoManagerSettingsImpl>(
+ profile_, app_manager_->GetPolicyHandler().RetrieveCertificate()));
+ protocol_handler_->AddProtocolObserver(security_manager_);
+ protocol_handler_->set_security_manager(security_manager_);
- // FIXME(EZamakhov): move to Config or in Sm initialization method
- std::string cert_filename;
- profile::Profile::instance()->ReadStringValue(
- &cert_filename, "",
- security_manager::SecurityManagerImpl::ConfigSection(), "CertificatePath");
-
- std::string ssl_mode;
- profile::Profile::instance()->ReadStringValue(
- &ssl_mode, "CLIENT", security_manager::SecurityManagerImpl::ConfigSection(), "SSLMode");
- crypto_manager_ = new security_manager::CryptoManagerImpl();
-
- std::string key_filename;
- profile::Profile::instance()->ReadStringValue(
- &key_filename, "", security_manager::SecurityManagerImpl::ConfigSection(), "KeyPath");
-
- std::string ciphers_list;
- profile::Profile::instance()->ReadStringValue(
- &ciphers_list, SSL_TXT_ALL, security_manager::SecurityManagerImpl::ConfigSection(), "CipherList");
-
- bool verify_peer;
- profile::Profile::instance()->ReadBoolValue(
- &verify_peer, false, security_manager::SecurityManagerImpl::ConfigSection(), "VerifyPeer");
-
- std::string protocol_name;
- profile::Profile::instance()->ReadStringValue(
- &protocol_name, "TLSv1.2", security_manager::SecurityManagerImpl::ConfigSection(), "Protocol");
-
- security_manager::Protocol protocol;
- if (protocol_name == "TLSv1.0") {
- protocol = security_manager::TLSv1;
- } else if (protocol_name == "TLSv1.1") {
- protocol = security_manager::TLSv1_1;
- } else if (protocol_name == "TLSv1.2") {
- protocol = security_manager::TLSv1_2;
- } else if (protocol_name == "SSLv3") {
- protocol = security_manager::SSLv3;
- } else {
- LOG4CXX_ERROR(logger_, "Unknown protocol: " << protocol_name);
- return false;
- }
+ security_manager_->set_session_observer(connection_handler_);
+ security_manager_->set_protocol_handler(protocol_handler_);
+ security_manager_->set_crypto_manager(crypto_manager_);
+ security_manager_->AddListener(app_manager_);
- if (!crypto_manager_->Init(
- ssl_mode == "SERVER" ? security_manager::SERVER : security_manager::CLIENT,
- protocol,
- cert_filename,
- key_filename,
- ciphers_list,
- verify_peer)) {
+ app_manager_->AddPolicyObserver(crypto_manager_);
+ if (!crypto_manager_->Init()) {
LOG4CXX_ERROR(logger_, "CryptoManager initialization fail.");
return false;
}
@@ -179,60 +158,46 @@ bool LifeCycle::StartComponents() {
hmi_handler_->set_message_observer(app_manager_);
- media_manager_ = media_manager::MediaManagerImpl::instance();
-
- protocol_handler_->set_session_observer(connection_handler_);
protocol_handler_->AddProtocolObserver(media_manager_);
protocol_handler_->AddProtocolObserver(app_manager_);
-#ifdef ENABLE_SECURITY
- protocol_handler_->AddProtocolObserver(security_manager_);
- protocol_handler_->set_security_manager(security_manager_);
-#endif // ENABLE_SECURITY
+
media_manager_->SetProtocolHandler(protocol_handler_);
- connection_handler_->set_transport_manager(transport_manager_);
connection_handler_->set_protocol_handler(protocol_handler_);
connection_handler_->set_connection_handler_observer(app_manager_);
-#ifdef ENABLE_SECURITY
- security_manager_->set_session_observer(connection_handler_);
- security_manager_->set_protocol_handler(protocol_handler_);
- security_manager_->set_crypto_manager(crypto_manager_);
-#endif // ENABLE_SECURITY
-
- // it is important to initialise TimeTester before TM to listen TM Adapters
-#ifdef TIME_TESTER
- time_tester_ = new time_tester::TimeManager();
- time_tester_->Init(protocol_handler_);
-#endif // TIME_TESTER
+// it is important to initialise TelemetryMonitor before TM to listen TM
+// Adapters
+#ifdef TELEMETRY_MONITOR
+ telemetry_monitor_ = new telemetry_monitor::TelemetryMonitor(
+ profile_.server_address(), profile_.time_testing_port());
+ telemetry_monitor_->Start();
+ telemetry_monitor_->Init(protocol_handler_, app_manager_, transport_manager_);
+#endif // TELEMETRY_MONITOR
// It's important to initialise TM after setting up listener chain
// [TM -> CH -> AM], otherwise some events from TM could arrive at nowhere
app_manager_->set_protocol_handler(protocol_handler_);
app_manager_->set_connection_handler(connection_handler_);
app_manager_->set_hmi_message_handler(hmi_handler_);
- transport_manager_->Init();
+ transport_manager_->Init(*last_state_);
// start transport manager
transport_manager_->Visibility(true);
- components_started_ = true;
return true;
}
#ifdef MESSAGEBROKER_HMIADAPTER
bool LifeCycle::InitMessageSystem() {
- message_broker_ =
- NsMessageBroker::CMessageBroker::getInstance();
+ DCHECK(!message_broker_)
+ message_broker_ = NsMessageBroker::CMessageBroker::getInstance();
if (!message_broker_) {
LOG4CXX_FATAL(logger_, " Wrong pMessageBroker pointer!");
return false;
}
- message_broker_server_ =
- new NsMessageBroker::TcpServer(
- profile::Profile::instance()->server_address(),
- profile::Profile::instance()->server_port(),
- message_broker_);
+ message_broker_server_ = new NsMessageBroker::TcpServer(
+ profile_.server_address(), profile_.server_port(), message_broker_);
if (!message_broker_server_) {
LOG4CXX_FATAL(logger_, " Wrong pJSONRPC20Server pointer!");
return false;
@@ -257,46 +222,44 @@ bool LifeCycle::InitMessageSystem() {
LOG4CXX_INFO(logger_, " Message broker server listen successful!");
}
- mb_adapter_ =
- new hmi_message_handler::MessageBrokerAdapter(
- hmi_message_handler::HMIMessageHandlerImpl::instance(),
- profile::Profile::instance()->server_address(),
- profile::Profile::instance()->server_port());
+ mb_adapter_ = new hmi_message_handler::MessageBrokerAdapter(
+ hmi_handler_, profile_.server_address(), profile_.server_port());
- hmi_message_handler::HMIMessageHandlerImpl::instance()->AddHMIMessageAdapter(
- mb_adapter_);
- if (!mb_adapter_->Connect()) {
- LOG4CXX_FATAL(logger_, "Cannot connect to remote peer!");
- return false;
- }
+ hmi_handler_->AddHMIMessageAdapter(mb_adapter_);
+ if (!mb_adapter_->Connect()) {
+ LOG4CXX_FATAL(logger_, "Cannot connect to remote peer!");
+ return false;
+ }
LOG4CXX_INFO(logger_, "Start CMessageBroker thread!");
mb_thread_ = new System::Thread(
- new System::ThreadArgImpl<NsMessageBroker::CMessageBroker>(
- *message_broker_, &NsMessageBroker::CMessageBroker::MethodForThread,
- NULL));
+ new System::ThreadArgImpl<NsMessageBroker::CMessageBroker>(
+ *message_broker_,
+ &NsMessageBroker::CMessageBroker::MethodForThread,
+ NULL));
mb_thread_->Start(false);
// Thread can be named only when started because before that point
// thread doesn't have valid Id to associate name with
NameMessageBrokerThread(*mb_thread_, "MessageBroker");
LOG4CXX_INFO(logger_, "Start MessageBroker TCP server thread!");
- mb_server_thread_ = new System::Thread(
- new System::ThreadArgImpl<NsMessageBroker::TcpServer>(
- *message_broker_server_, &NsMessageBroker::TcpServer::MethodForThread,
- NULL));
+ mb_server_thread_ =
+ new System::Thread(new System::ThreadArgImpl<NsMessageBroker::TcpServer>(
+ *message_broker_server_,
+ &NsMessageBroker::TcpServer::MethodForThread,
+ NULL));
mb_server_thread_->Start(false);
NameMessageBrokerThread(*mb_server_thread_, "MB TCPServer");
LOG4CXX_INFO(logger_, "StartAppMgr JSONRPC 2.0 controller receiver thread!");
- mb_adapter_thread_ = new System::Thread(
- new System::ThreadArgImpl<hmi_message_handler::MessageBrokerAdapter>(
- *mb_adapter_,
- &hmi_message_handler::MessageBrokerAdapter::SubscribeAndBeginReceiverThread,
- NULL));
+ mb_adapter_thread_ = new System::Thread(
+ new System::ThreadArgImpl<hmi_message_handler::MessageBrokerAdapter>(
+ *mb_adapter_,
+ &hmi_message_handler::MessageBrokerAdapter::
+ SubscribeAndBeginReceiverThread,
+ NULL));
mb_adapter_thread_->Start(false);
NameMessageBrokerThread(*mb_adapter_thread_, "MB Adapter");
-
return true;
}
#endif // MESSAGEBROKER_HMIADAPTER
@@ -307,11 +270,9 @@ bool LifeCycle::InitMessageSystem() {
* @return true if success otherwise false.
*/
bool LifeCycle::InitMessageSystem() {
- dbus_adapter_ = new hmi_message_handler::DBusMessageAdapter(
- hmi_message_handler::HMIMessageHandlerImpl::instance());
+ dbus_adapter_ = new hmi_message_handler::DBusMessageAdapter(hmi_handler_);
- hmi_message_handler::HMIMessageHandlerImpl::instance()->AddHMIMessageAdapter(
- dbus_adapter_);
+ hmi_handler_.AddHMIMessageAdapter(dbus_adapter_);
if (!dbus_adapter_->Init()) {
LOG4CXX_FATAL(logger_, "Cannot init DBus service!");
return false;
@@ -321,10 +282,10 @@ bool LifeCycle::InitMessageSystem() {
LOG4CXX_INFO(logger_, "Start DBusMessageAdapter thread!");
dbus_adapter_thread_ = new System::Thread(
- new System::ThreadArgImpl<hmi_message_handler::DBusMessageAdapter>(
- *dbus_adapter_,
- &hmi_message_handler::DBusMessageAdapter::MethodForReceiverThread,
- NULL));
+ new System::ThreadArgImpl<hmi_message_handler::DBusMessageAdapter>(
+ *dbus_adapter_,
+ &hmi_message_handler::DBusMessageAdapter::MethodForReceiverThread,
+ NULL));
dbus_adapter_thread_->Start(false);
return true;
@@ -333,163 +294,166 @@ bool LifeCycle::InitMessageSystem() {
#ifdef MQUEUE_HMIADAPTER
bool LifeCycle::InitMessageSystem() {
- hmi_message_adapter_ = new hmi_message_handler::MqueueAdapter(
- hmi_message_handler::HMIMessageHandlerImpl::instance());
- hmi_message_handler::HMIMessageHandlerImpl::instance()->AddHMIMessageAdapter(
- hmi_message_adapter_);
+ hmi_message_adapter_ = new hmi_message_handler::MqueueAdapter(hmi_handler_);
+ hmi_handler.AddHMIMessageAdapter(hmi_message_adapter_);
return true;
}
#endif // MQUEUE_HMIADAPTER
namespace {
-
- void sig_handler(int sig) {
- // Do nothing
- }
-
- void agony(int sig) {
-// these actions are not signal safe
-// (in case logger is on)
-// but they cannot be moved to a separate thread
-// because the application most probably will crash as soon as this handler returns
-//
-// the application is anyway about to crash
- LOG4CXX_FATAL(logger_, "Stopping application due to segmentation fault");
-#ifdef ENABLE_LOG
- logger::LogMessageLoopThread::destroy();
-#endif
+void sig_handler(int sig) {
+ switch (sig) {
+ case SIGINT:
+ LOG4CXX_DEBUG(logger_, "SIGINT signal has been caught");
+ break;
+ case SIGTERM:
+ LOG4CXX_DEBUG(logger_, "SIGTERM signal has been caught");
+ break;
+ case SIGSEGV:
+ LOG4CXX_DEBUG(logger_, "SIGSEGV signal has been caught");
+ FLUSH_LOGGER();
+ // exit need to prevent endless sending SIGSEGV
+ // http://stackoverflow.com/questions/2663456/how-to-write-a-signal-handler-to-catch-sigsegv
+ abort();
+ default:
+ LOG4CXX_DEBUG(logger_, "Unexpected signal has been caught");
+ exit(EXIT_FAILURE);
}
-
+}
} // namespace
void LifeCycle::Run() {
- // First, register signal handlers
- ::utils::SubscribeToTerminateSignal(&sig_handler);
- ::utils::SubscribeToFaultSignal(&agony);
- // Now wait for any signal
- pause();
+ LOG4CXX_AUTO_TRACE(logger_);
+ // Register signal handlers and wait sys signals
+ // from OS
+ if (!utils::WaitTerminationSignals(&sig_handler)) {
+ LOG4CXX_FATAL(logger_, "Fail to catch system signal!");
+ }
}
-
void LifeCycle::StopComponents() {
- if (!components_started_) {
- LOG4CXX_TRACE(logger_, "exit");
- LOG4CXX_ERROR(logger_, "Components wasn't started");
- return;
- }
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ DCHECK_OR_RETURN_VOID(hmi_handler_);
hmi_handler_->set_message_observer(NULL);
+
+ DCHECK_OR_RETURN_VOID(connection_handler_);
connection_handler_->set_connection_handler_observer(NULL);
+
+ DCHECK_OR_RETURN_VOID(protocol_handler_);
protocol_handler_->RemoveProtocolObserver(app_manager_);
+
+ DCHECK_OR_RETURN_VOID(app_manager_);
app_manager_->Stop();
LOG4CXX_INFO(logger_, "Stopping Protocol Handler");
+ DCHECK_OR_RETURN_VOID(protocol_handler_);
protocol_handler_->RemoveProtocolObserver(media_manager_);
+
#ifdef ENABLE_SECURITY
protocol_handler_->RemoveProtocolObserver(security_manager_);
+ if (security_manager_) {
+ security_manager_->RemoveListener(app_manager_);
+ LOG4CXX_INFO(logger_, "Destroying Crypto Manager");
+ delete crypto_manager_;
+ crypto_manager_ = NULL;
+ LOG4CXX_INFO(logger_, "Destroying Security Manager");
+ delete security_manager_;
+ security_manager_ = NULL;
+ }
#endif // ENABLE_SECURITY
protocol_handler_->Stop();
LOG4CXX_INFO(logger_, "Destroying Media Manager");
+ DCHECK_OR_RETURN_VOID(media_manager_);
media_manager_->SetProtocolHandler(NULL);
- media_manager::MediaManagerImpl::destroy();
+ delete media_manager_;
+ media_manager_ = NULL;
LOG4CXX_INFO(logger_, "Destroying Transport Manager.");
+ DCHECK_OR_RETURN_VOID(transport_manager_);
transport_manager_->Visibility(false);
transport_manager_->Stop();
- transport_manager::TransportManagerDefault::destroy();
+ delete transport_manager_;
+ transport_manager_ = NULL;
LOG4CXX_INFO(logger_, "Stopping Connection Handler.");
- connection_handler::ConnectionHandlerImpl::instance()->Stop();
+ DCHECK_OR_RETURN_VOID(connection_handler_);
+ connection_handler_->Stop();
LOG4CXX_INFO(logger_, "Destroying Protocol Handler");
+ DCHECK(protocol_handler_);
delete protocol_handler_;
+ protocol_handler_ = NULL;
LOG4CXX_INFO(logger_, "Destroying Connection Handler.");
- connection_handler::ConnectionHandlerImpl::destroy();
-
-#ifdef ENABLE_SECURITY
- LOG4CXX_INFO(logger_, "Destroying Crypto Manager");
- crypto_manager_->Finish();
- delete crypto_manager_;
-
- LOG4CXX_INFO(logger_, "Destroying Security Manager");
- delete security_manager_;
-#endif // ENABLE_SECURITY
+ delete connection_handler_;
+ connection_handler_ = NULL;
LOG4CXX_INFO(logger_, "Destroying Last State");
- resumption::LastState::destroy();
+ DCHECK(last_state_);
+ delete last_state_;
+ last_state_ = NULL;
LOG4CXX_INFO(logger_, "Destroying Application Manager.");
- application_manager::ApplicationManagerImpl::destroy();
+ DCHECK(app_manager_);
+ delete app_manager_;
+ app_manager_ = NULL;
LOG4CXX_INFO(logger_, "Destroying HMI Message Handler and MB adapter.");
+
#ifdef DBUS_HMIADAPTER
if (dbus_adapter_) {
- if (hmi_handler_) {
- hmi_handler_->RemoveHMIMessageAdapter(dbus_adapter_);
- hmi_message_handler::HMIMessageHandlerImpl::destroy();
- }
- if (dbus_adapter_thread_) {
- dbus_adapter_thread_->Stop();
- dbus_adapter_thread_->Join();
- delete dbus_adapter_thread_;
- }
+ DCHECK_OR_RETURN_VOID(hmi_handler_);
+ hmi_handler_->RemoveHMIMessageAdapter(dbus_adapter_);
+ dbus_adapter_->exitReceivingThread();
+ StopThread(dbus_adapter_thread_);
delete dbus_adapter_;
+ dbus_adapter_ = NULL;
}
#endif // DBUS_HMIADAPTER
+
#ifdef MESSAGEBROKER_HMIADAPTER
- hmi_handler_->RemoveHMIMessageAdapter(mb_adapter_);
if (mb_adapter_) {
+ DCHECK_OR_RETURN_VOID(hmi_handler_);
+ hmi_handler_->RemoveHMIMessageAdapter(mb_adapter_);
mb_adapter_->unregisterController();
- mb_adapter_->Close();
mb_adapter_->exitReceivingThread();
- if (mb_adapter_thread_) {
- mb_adapter_thread_->Join();
- }
+ StopThread(mb_adapter_thread_);
delete mb_adapter_;
+ mb_adapter_ = NULL;
}
- hmi_message_handler::HMIMessageHandlerImpl::destroy();
- if (mb_adapter_thread_) {
- mb_adapter_thread_->Stop();
- delete mb_adapter_thread_;
- }
-
-#endif // MESSAGEBROKER_HMIADAPTER
+ DCHECK_OR_RETURN_VOID(hmi_handler_);
+ delete hmi_handler_;
+ hmi_handler_ = NULL;
-#ifdef MESSAGEBROKER_HMIADAPTER
LOG4CXX_INFO(logger_, "Destroying Message Broker");
- if (mb_server_thread_) {
- mb_server_thread_->Stop();
- mb_server_thread_->Join();
- delete mb_server_thread_;
+ StopThread(mb_server_thread_);
+ StopThread(mb_thread_);
+
+ if (message_broker_server_) {
+ message_broker_server_->Close();
+ delete message_broker_server_;
+ message_broker_server_ = NULL;
}
- if (mb_thread_) {
- mb_thread_->Stop();
- mb_thread_->Join();
- delete mb_thread_;
+
+ if (message_broker_) {
+ message_broker_->stopMessageBroker();
}
- message_broker_server_->Close();
- delete message_broker_server_;
- message_broker_->stopMessageBroker();
networking::cleanup();
#endif // MESSAGEBROKER_HMIADAPTER
- delete hmi_message_adapter_;
- hmi_message_adapter_ = NULL;
-
-#ifdef TIME_TESTER
+#ifdef TELEMETRY_MONITOR
// It's important to delete tester Obcervers after TM adapters destruction
- if (time_tester_) {
- time_tester_->Stop();
- delete time_tester_;
- time_tester_ = NULL;
+ if (telemetry_monitor_) {
+ telemetry_monitor_->Stop();
+ delete telemetry_monitor_;
+ telemetry_monitor_ = NULL;
}
-#endif // TIME_TESTER
- components_started_ = false;
- LOG4CXX_TRACE(logger_, "exit");
+#endif // TELEMETRY_MONITOR
}
} // namespace main_namespace
diff --git a/src/appMain/life_cycle.h b/src/appMain/life_cycle.h
index d85678047f..2d6e0b938e 100644
--- a/src/appMain/life_cycle.h
+++ b/src/appMain/life_cycle.h
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2014, Ford Motor Company
+* Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -35,15 +35,16 @@
#include "utils/macro.h"
#include "unistd.h"
+#include "config_profile/profile.h"
#include "hmi_message_handler/hmi_message_handler_impl.h"
#ifdef DBUS_HMIADAPTER
-# include "hmi_message_handler/dbus_message_adapter.h"
+#include "hmi_message_handler/dbus_message_adapter.h"
#endif // DBUS_HMIADAPTER
-#if ( defined (MESSAGEBROKER_HMIADAPTER) || defined(PASA_HMI) )
+#if (defined(MESSAGEBROKER_HMIADAPTER) || defined(PASA_HMI))
#include "hmi_message_handler/messagebroker_adapter.h"
#endif // #if ( defined (MESSAGEBROKER_HMIADAPTER) || defined(PASA_HMI) )
#ifdef MQUEUE_HMIADAPTER
-# include "hmi_message_handler/mqueue_adapter.h"
+#include "hmi_message_handler/mqueue_adapter.h"
#endif // MQUEUE_HMIADAPTER
#include "application_manager/application_manager_impl.h"
#include "connection_handler/connection_handler_impl.h"
@@ -51,17 +52,16 @@
#include "transport_manager/transport_manager.h"
#include "transport_manager/transport_manager_default.h"
#include "media_manager/media_manager_impl.h"
-#include "utils/singleton.h"
-#ifdef TIME_TESTER
-#include "time_tester/time_manager.h"
+#ifdef TELEMETRY_MONITOR
+#include "telemetry_monitor/telemetry_monitor.h"
#endif
//#if ( defined (MESSAGEBROKER_HMIADAPTER) || defined(PASA_HMI) )
#ifdef MESSAGEBROKER_HMIADAPTER
#include "CMessageBroker.hpp"
#include "mb_tcpserver.hpp"
-# include "networking.h" // cpplint: Include the directory when naming .h files
-#endif // MESSAGEBROKER_HMIADAPTER
+#include "networking.h" // cpplint: Include the directory when naming .h files
+#endif // MESSAGEBROKER_HMIADAPTER
#include "system.h" // cpplint: Include the directory when naming .h files
#ifdef ENABLE_SECURITY
@@ -72,56 +72,54 @@ class SecurityManagerImpl;
#endif // ENABLE_SECURITY
namespace main_namespace {
-class LifeCycle : public utils::Singleton<LifeCycle> {
- public:
- bool StartComponents();
-
- /**
- * Initialize MessageBroker component
- * @return true if success otherwise false.
- */
- bool InitMessageSystem();
- /**
- * \brief Main loop
- */
- void Run();
- void StopComponents();
+class LifeCycle {
+ public:
+ LifeCycle(const profile::Profile& profile);
+ bool StartComponents();
+ /**
+ * Initialize MessageBroker component
+ * @return true if success otherwise false.
+ */
+ bool InitMessageSystem();
+ /**
+ * \brief Main loop
+ */
+ void Run();
+ void StopComponents();
- private:
- LifeCycle();
- transport_manager::TransportManager* transport_manager_;
- protocol_handler::ProtocolHandlerImpl* protocol_handler_;
- connection_handler::ConnectionHandlerImpl* connection_handler_;
- application_manager::ApplicationManagerImpl* app_manager_;
+ private:
+ transport_manager::TransportManagerImpl* transport_manager_;
+ protocol_handler::ProtocolHandlerImpl* protocol_handler_;
+ connection_handler::ConnectionHandlerImpl* connection_handler_;
+ application_manager::ApplicationManagerImpl* app_manager_;
#ifdef ENABLE_SECURITY
- security_manager::CryptoManager* crypto_manager_;
- security_manager::SecurityManager* security_manager_;
+ security_manager::CryptoManager* crypto_manager_;
+ security_manager::SecurityManager* security_manager_;
#endif // ENABLE_SECURITY
- hmi_message_handler::HMIMessageHandlerImpl* hmi_handler_;
- hmi_message_handler::HMIMessageAdapter* hmi_message_adapter_;
- media_manager::MediaManagerImpl* media_manager_;
-#ifdef TIME_TESTER
- time_tester::TimeManager* time_tester_;
-#endif // TIME_TESTER
+ hmi_message_handler::HMIMessageHandlerImpl* hmi_handler_;
+ hmi_message_handler::HMIMessageAdapter* hmi_message_adapter_;
+ media_manager::MediaManagerImpl* media_manager_;
+ resumption::LastState* last_state_;
+#ifdef TELEMETRY_MONITOR
+ telemetry_monitor::TelemetryMonitor* telemetry_monitor_;
+#endif // TELEMETRY_MONITOR
#ifdef DBUS_HMIADAPTER
- hmi_message_handler::DBusMessageAdapter* dbus_adapter_;
- System::Thread* dbus_adapter_thread_;
+ hmi_message_handler::DBusMessageAdapter* dbus_adapter_;
+ System::Thread* dbus_adapter_thread_;
#endif // DBUS_HMIADAPTER
#ifdef MESSAGEBROKER_HMIADAPTER
- hmi_message_handler::MessageBrokerAdapter* mb_adapter_;
- NsMessageBroker::CMessageBroker* message_broker_;
- NsMessageBroker::TcpServer* message_broker_server_;
- System::Thread* mb_thread_;
- System::Thread* mb_server_thread_;
- System::Thread* mb_adapter_thread_;
+ hmi_message_handler::MessageBrokerAdapter* mb_adapter_;
+ NsMessageBroker::CMessageBroker* message_broker_;
+ NsMessageBroker::TcpServer* message_broker_server_;
+ System::Thread* mb_thread_;
+ System::Thread* mb_server_thread_;
+ System::Thread* mb_adapter_thread_;
#endif // MESSAGEBROKER_HMIADAPTER
-
- bool components_started_;
- FRIEND_BASE_SINGLETON_CLASS(LifeCycle);
- DISALLOW_COPY_AND_ASSIGN(LifeCycle);
+ const profile::Profile& profile_;
+ DISALLOW_COPY_AND_ASSIGN(LifeCycle);
};
} // namespace main_namespace
diff --git a/src/appMain/log4cxx.properties b/src/appMain/log4cxx.properties
index 6a12f8c9b5..2059ee7d3a 100644
--- a/src/appMain/log4cxx.properties
+++ b/src/appMain/log4cxx.properties
@@ -1,52 +1,40 @@
+# Console logging
+log4j.appender.Console=org.apache.log4j.ConsoleAppender
+log4j.appender.Console.ImmediateFlush=true
+log4j.appender.Console.layout=org.apache.log4j.PatternLayout
+log4j.appender.Console.layout.ConversionPattern=%-5p [%d{HH:mm:ss,SSS}][%c] %m%n
+log4j.appender.Console.Threshold=DEBUG
+
# Log for all SmartDeviceLinkCoreSocketHub messages
log4j.appender.SmartDeviceLinkCoreSocketHub=org.apache.log4j.net.SocketHubAppender
log4j.appender.SmartDeviceLinkCoreSocketHub.port=4555
log4j.appender.SmartDeviceLinkCoreSocketHub.locationInfo=true
-# Only ERROR and FATAL messages are logged to console
-log4j.appender.Console=org.apache.log4j.ConsoleAppender
-log4j.appender.Console.ImmediateFlush=true
-log4j.appender.Console.layout=org.apache.log4j.PatternLayout
-log4j.appender.Console.layout.ConversionPattern=%-5p [%d{dd MMM yyyy HH:mm:ss,SSS}][%c] %m%n
-log4j.appender.Console.Threshold=DEBUG
+# Logging via telnet
+log4j.appender.TelnetLogging=org.apache.log4j.TelnetAppender
+log4j.appender.TelnetLogging.port=6676
+log4j.appender.TelnetLogging.layout=org.apache.log4j.PatternLayout
+log4j.appender.TelnetLogging.layout.ConversionPattern=%-5p [%d{dd MMM yyyy HH:mm:ss,SSS}][%t][%c] %F:%L %M: %m%n
-# Log for all SmartDeviceLinkCore messages
+# Log file for all SmartDeviceLinkCore messages
log4j.appender.SmartDeviceLinkCoreLogFile=SafeFileAppender
log4j.appender.SmartDeviceLinkCoreLogFile.File=SmartDeviceLinkCore.log
log4j.appender.SmartDeviceLinkCoreLogFile.append=true
log4j.appender.SmartDeviceLinkCoreLogFile.DatePattern='.' yyyy-MM-dd HH-mm
log4j.appender.SmartDeviceLinkCoreLogFile.ImmediateFlush=true
log4j.appender.SmartDeviceLinkCoreLogFile.layout=org.apache.log4j.PatternLayout
-log4j.appender.SmartDeviceLinkCoreLogFile.layout.ConversionPattern=%-5p [%d{dd MMM yyyy HH:mm:ss,SSS}][%c] %F:%L %M: %m%n
+log4j.appender.SmartDeviceLinkCoreLogFile.layout.ConversionPattern=%-5p [%d{dd MMM yyyy HH:mm:ss,SSS}][%t][%c] %F:%L %M: %m%n
-# Log for all TransportManager messages
+# Log file for all TransportManager messages
log4j.appender.TransportManagerLogFile=SafeFileAppender
log4j.appender.TransportManagerLogFile.File=TransportManager.log
log4j.appender.TransportManagerLogFile.append=false
log4j.appender.TransportManagerLogFile.DatePattern='.' yyyy-MM-dd HH-mm
log4j.appender.TransportManagerLogFile.ImmediateFlush=true
log4j.appender.TransportManagerLogFile.layout=org.apache.log4j.PatternLayout
-log4j.appender.TransportManagerLogFile.layout.ConversionPattern=%-5p [%d{dd MMM yyyy HH:mm:ss,SSS}][%c] %F:%L %M: %m%n
-
-# Log for all DBus plugin messages
-log4j.appender.DBusPluginLogFile=SafeFileAppender
-log4j.appender.DBusPluginLogFile.File=DBusPlugin.log
-log4j.appender.DBusPluginLogFile.append=false
-log4j.appender.DBusPluginLogFile.DatePattern='.' yyyy-MM-dd
-log4j.appender.DBusPluginLogFile.ImmediateFlush=true
-log4j.appender.DBusPluginLogFile.layout=org.apache.log4j.PatternLayout
-log4j.appender.DBusPluginLogFile.layout.ConversionPattern=%-5p [%d{dd MMM yyyy HH:mm:ss,SSS}][%c] %F:%L %M: %m%n
+log4j.appender.TransportManagerLogFile.layout.ConversionPattern=%-5p [%d{dd MMM yyyy HH:mm:ss,SSS}][%t][%c] %F:%L %M: %m%n
-# Log for all HMI Framework plugin
-log4j.appender.HmiFrameworkPluginLogFile=SafeFileAppender
-log4j.appender.HmiFrameworkPluginLogFile.File=HmiFrameworkPlugin.log
-log4j.appender.HmiFrameworkPluginLogFile.append=false
-log4j.appender.HmiFrameworkPluginLogFile.DatePattern='.' yyyy-MM-dd
-log4j.appender.HmiFrameworkPluginLogFile.ImmediateFlush=true
-log4j.appender.HmiFrameworkPluginLogFile.layout=org.apache.log4j.PatternLayout
-log4j.appender.HmiFrameworkPluginLogFile.layout.ConversionPattern=%-5p [%d{dd MMM yyyy HH:mm:ss,SSS}][%c] %F:%L %M: %m%n
-
-# Log for handling Ford protocol info (include ProtocolHandler, ConnectionHandler, SecurityManager, SSLContext)
+# Log for handling Ford protocol info (include ProtocolHandler, ConnectionHandler, SecurityManager)
log4j.appender.ProtocolFordHandlingLogFile=SafeFileAppender
log4j.appender.ProtocolFordHandlingLogFile.File=ProtocolFordHandling.log
log4j.appender.ProtocolFordHandlingLogFile.append=false
@@ -55,24 +43,26 @@ log4j.appender.ProtocolFordHandlingLogFile.ImmediateFlush=true
log4j.appender.ProtocolFordHandlingLogFile.layout=org.apache.log4j.PatternLayout
log4j.appender.ProtocolFordHandlingLogFile.layout.ConversionPattern=%-5p [%d{dd MMM yyyy HH:mm:ss,SSS}][%c] %M: %m%n
-# All SmartDeviceLinkCore logs
-log4j.rootLogger=ALL, Console, SmartDeviceLinkCoreLogFile, SmartDeviceLinkCoreSocketHub
-
-# TransportManager logs
-log4j.logger.TransportManager=ALL, TransportManagerLogFile
-
-# Log for DBus plugin QtHMI
-log4j.logger.DBusPlugin=ALL, DBusPluginLogFile
-
-# Log for HMI Framework plugin
-log4j.logger.HmiFrameworkPlugin=ALL, HmiFrameworkPluginLogFile
-
-# Log by log4cxx plugin
-log4j.logger.Log4cxxPlugin=ALL, HmiFrameworkPluginLogFile
+# Root logging settings
+# Set ALL logging levels to main log file
+log4j.rootLogger=ALL, SmartDeviceLinkCoreLogFile
-# Log by ProtocolHandler
-log4j.logger.ProtocolHandler=ALL, ProtocolFordHandlingLogFile
-# Log by ConnectionHandler
-log4j.logger.ConnectionHandler=ALL, ProtocolFordHandlingLogFile
-# Log by SecurityManager
-log4j.logger.SecurityManager=ALL, ProtocolFordHandlingLogFile
+# Components loggers with own logging levels
+log4j.logger.SDLMain = ALL
+log4j.logger.Utils = ALL
+log4j.logger.Profile = ALL
+log4j.logger.ApplicationManager = ALL
+log4j.logger.Commands = ALL
+log4j.logger.PolicyHandler = ALL
+log4j.logger.Policy = ALL
+log4j.logger.Resumption = ALL
+log4j.logger.HMIMessageHandler = ALL
+log4j.logger.RequestController = ALL
+log4j.logger.StateController = ALL
+log4j.logger.MediaManager = ALL
+log4j.logger.ConnectionHandler = ALL, ProtocolFordHandlingLogFile
+log4j.logger.HeartBeatMonitor = ALL, ProtocolFordHandlingLogFile
+log4j.logger.ProtocolHandler = ALL, ProtocolFordHandlingLogFile
+log4j.logger.SecurityManager = ALL, ProtocolFordHandlingLogFile
+log4j.logger.TelemetryMonitor = ALL
+log4j.logger.TransportManager = ALL, TransportManagerLogFile
diff --git a/src/appMain/main.cc b/src/appMain/main.cc
index 2c14bfa3b6..9507a52e7b 100644
--- a/src/appMain/main.cc
+++ b/src/appMain/main.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -64,8 +64,7 @@
// ----------------------------------------------------------------------------
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "appMain")
+CREATE_LOGGERPTR_GLOBAL(logger_, "SDLMain")
namespace {
@@ -79,14 +78,15 @@ const std::string kLocalHostAddress = "127.0.0.1";
* Initialize HTML based HMI.
* @return true if success otherwise false.
*/
-bool InitHmi() {
- std::string hmi_link = profile::Profile::instance()->link_to_web_hmi();
+bool InitHmi(std::string hmi_link) {
struct stat sb;
if (stat(hmi_link.c_str(), &sb) == -1) {
- LOG4CXX_FATAL(logger_, "HMI index.html doesn't exist!");
+ LOG4CXX_FATAL(logger_, "HMI index file " << hmi_link << " doesn't exist!");
return false;
}
- return utils::System(kBrowser, kBrowserName).Add(kBrowserParams).Add(hmi_link)
+ return utils::System(kBrowser, kBrowserName)
+ .Add(kBrowserParams)
+ .Add(hmi_link)
.Execute();
}
#endif // WEB_HMI
@@ -107,7 +107,6 @@ bool InitHmi() {
return utils::System(kStartHmi).Execute();
}
#endif // QT_HMI
-
}
/**
@@ -117,52 +116,41 @@ bool InitHmi() {
* \return EXIT_SUCCESS or EXIT_FAILURE
*/
int32_t main(int32_t argc, char** argv) {
+ // Unsibscribe once for all threads
+ if (!utils::UnsibscribeFromTermination()) {
+ // Can't use internal logger here
+ exit(EXIT_FAILURE);
+ }
+
+ // --------------------------------------------------------------------------
+ // Components initialization
+ profile::Profile profile_instance;
+ main_namespace::LifeCycle life_cycle(profile_instance);
+ if ((argc > 1) && (0 != argv)) {
+ profile_instance.config_file_name(argv[1]);
+ } else {
+ profile_instance.config_file_name("smartDeviceLink.ini");
+ }
// --------------------------------------------------------------------------
// Logger initialization
- INIT_LOGGER("log4cxx.properties");
-#if defined(__QNXNTO__) and defined(GCOV_ENABLED)
- LOG4CXX_WARN(logger_,
- "Attention! This application was built with unsupported "
- "configuration (gcov + QNX). Use it at your own risk.");
-#endif
+ INIT_LOGGER("log4cxx.properties", profile_instance.logs_enabled());
threads::Thread::SetNameForId(threads::Thread::CurrentId(), "MainThread");
if (!utils::appenders_loader.Loaded()) {
- LOG4CXX_ERROR(logger_, "Appenders plugin not loaded, file logging disabled");
+ LOG4CXX_ERROR(logger_,
+ "Appenders plugin not loaded, file logging disabled");
}
LOG4CXX_INFO(logger_, "Application started!");
- LOG4CXX_INFO(logger_, "SDL version: "
- << profile::Profile::instance()->sdl_version());
-
- // Initialize gstreamer. Needed to activate debug from the command line.
-#if defined(EXTENDED_MEDIA_MODE)
- gst_init(&argc, &argv);
-#endif
+ LOG4CXX_INFO(logger_, "SDL version: " << profile_instance.sdl_version());
// --------------------------------------------------------------------------
// Components initialization
- if ((argc > 1)&&(0 != argv)) {
- profile::Profile::instance()->config_file_name(argv[1]);
- } else {
- profile::Profile::instance()->config_file_name("smartDeviceLink.ini");
- }
-
-#ifdef __QNX__
- if (profile::Profile::instance()->enable_policy()) {
- if (!utils::System("./init_policy.sh").Execute(true)) {
- LOG4CXX_FATAL(logger_, "Failed to init policy database");
- DEINIT_LOGGER();
- exit(EXIT_FAILURE);
- }
- }
-#endif // __QNX__
-
- if (!main_namespace::LifeCycle::instance()->StartComponents()) {
+ if (!life_cycle.StartComponents()) {
LOG4CXX_FATAL(logger_, "Failed to start components");
- main_namespace::LifeCycle::instance()->StopComponents();
+ life_cycle.StopComponents();
DEINIT_LOGGER();
exit(EXIT_FAILURE);
}
@@ -170,20 +158,20 @@ int32_t main(int32_t argc, char** argv) {
// --------------------------------------------------------------------------
// Third-Party components initialization.
- if (!main_namespace::LifeCycle::instance()->InitMessageSystem()) {
+ if (!life_cycle.InitMessageSystem()) {
LOG4CXX_FATAL(logger_, "Failed to init message system");
- main_namespace::LifeCycle::instance()->StopComponents();
+ life_cycle.StopComponents();
DEINIT_LOGGER();
_exit(EXIT_FAILURE);
}
LOG4CXX_INFO(logger_, "InitMessageBroker successful");
- if (profile::Profile::instance()->launch_hmi()) {
- if (profile::Profile::instance()->server_address() == kLocalHostAddress) {
+ if (profile_instance.launch_hmi()) {
+ if (profile_instance.server_address() == kLocalHostAddress) {
LOG4CXX_INFO(logger_, "Start HMI on localhost");
#ifndef NO_HMI
- if (!InitHmi()) {
+ if (!InitHmi(profile_instance.link_to_web_hmi())) {
LOG4CXX_INFO(logger_, "InitHmi successful");
} else {
LOG4CXX_WARN(logger_, "Failed to init HMI");
@@ -193,12 +181,12 @@ int32_t main(int32_t argc, char** argv) {
}
// --------------------------------------------------------------------------
- main_namespace::LifeCycle::instance()->Run();
- LOG4CXX_INFO(logger_, "Stopping application due to signal caught");
+ life_cycle.Run();
+ LOG4CXX_INFO(logger_, "Stop SDL due to caught signal");
- main_namespace::LifeCycle::instance()->StopComponents();
+ life_cycle.StopComponents();
+ LOG4CXX_INFO(logger_, "Application has been stopped successfuly");
- LOG4CXX_INFO(logger_, "Application successfully stopped");
DEINIT_LOGGER();
return EXIT_SUCCESS;
diff --git a/src/appMain/sdl_preloaded_pt.json b/src/appMain/sdl_preloaded_pt.json
index 6968612408..15c0739913 100644
--- a/src/appMain/sdl_preloaded_pt.json
+++ b/src/appMain/sdl_preloaded_pt.json
@@ -1,2323 +1,2273 @@
{
- "policy_table": {
- "module_config": {
- "preloaded_pt": true,
- "exchange_after_x_ignition_cycles": 100,
- "exchange_after_x_kilometers": 1800,
- "exchange_after_x_days": 20,
- "timeout_after_x_seconds": 60,
- "seconds_between_retries": [
- 1,
- 5,
- 25,
- 125,
- 625
- ],
- "endpoints": {
- "0x07": {
- "default": ["https://policies.smartdevicelink.com/api/1/policies"]
- },
- "0x04": {
- "default": ["http://ivsu.software.ford.com/api/getsoftwareupdates"]
- },
- "queryAppsUrl": {
- "default": ["http://sdl.shaid.server"]
- },
- "lock_screen_icon_url": {
- "default": ["http://i.imgur.com/QwZ9uKG.png"]
- }
- },
- "notifications_per_minute_by_priority": {
- "EMERGENCY": 60,
- "NAVIGATION": 15,
- "VOICECOM": 20,
- "COMMUNICATION": 6,
- "NORMAL": 4,
- "NONE": 0
- }
- },
- "functional_groupings": {
- "Base-4": {
- "rpcs": {
- "AddCommand": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "AddSubMenu": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "Alert": {
- "hmi_levels": [
- "FULL",
- "LIMITED"
- ]
- },
- "ChangeRegistration": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "CreateInteractionChoiceSet": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "DeleteCommand": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "DeleteFile": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "DeleteInteractionChoiceSet": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "DeleteSubMenu": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "EncodedSyncPData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "EndAudioPassThru": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "GenericResponse": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "ListFiles": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "OnAppInterfaceUnregistered": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "OnAudioPassThru": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "OnButtonEvent": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "OnButtonPress": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "OnCommand": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "OnDriverDistraction": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "OnEncodedSyncPData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "OnHashChange": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "OnHMIStatus": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "OnLanguageChange": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "OnPermissionsChange": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "OnSystemRequest": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "PerformAudioPassThru": {
- "hmi_levels": [
- "FULL",
- "LIMITED"
- ]
- },
- "PerformInteraction": {
- "hmi_levels": [
- "FULL",
- "LIMITED"
- ]
- },
- "PutFile": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "RegisterAppInterface": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "ResetGlobalProperties": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "ScrollableMessage": {
- "hmi_levels": [
- "FULL"
- ]
- },
- "SetAppIcon": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "SetDisplayLayout": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "SetGlobalProperties": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "SetMediaClockTimer": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "Show": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "Slider": {
- "hmi_levels": [
- "FULL"
- ]
- },
- "Speak": {
- "hmi_levels": [
- "FULL",
- "LIMITED"
- ]
- },
- "SubscribeButton": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "SystemRequest": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "UnregisterAppInterface": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "UnsubscribeButton": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- }
- }
- },
- "Location-1": {
- "user_consent_prompt": "Location",
- "rpcs": {
- "GetVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "gps",
- "speed"
- ]
- },
- "OnVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "gps",
- "speed"
- ]
- },
- "SubscribeVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "gps",
- "speed"
- ]
- },
- "UnsubscribeVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "gps",
- "speed"
- ]
- }
- }
- },
- "Notifications": {
- "user_consent_prompt": "Notifications",
- "rpcs": {
- "Alert": {
- "hmi_levels": [
- "BACKGROUND"
- ]
- }
- }
- },
- "DrivingCharacteristics-3": {
- "user_consent_prompt": "DrivingCharacteristics",
- "rpcs": {
- "GetVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "accPedalPosition",
- "beltStatus",
- "driverBraking",
- "myKey",
- "prndl",
- "rpm",
- "steeringWheelAngle"
- ]
- },
- "OnVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "accPedalPosition",
- "beltStatus",
- "driverBraking",
- "myKey",
- "prndl",
- "rpm",
- "steeringWheelAngle"
- ]
- },
- "SubscribeVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "accPedalPosition",
- "beltStatus",
- "driverBraking",
- "myKey",
- "prndl",
- "rpm",
- "steeringWheelAngle"
- ]
- },
- "UnsubscribeVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "accPedalPosition",
- "beltStatus",
- "driverBraking",
- "myKey",
- "prndl",
- "rpm",
- "steeringWheelAngle"
- ]
- }
- }
- },
- "VehicleInfo-3": {
- "user_consent_prompt": "VehicleInfo",
- "rpcs": {
- "GetVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "bodyInformation",
- "deviceStatus",
- "engineTorque",
- "externalTemperature",
- "fuelLevel",
- "fuelLevel_State",
- "headLampStatus",
- "instantFuelConsumption",
- "odometer",
- "tirePressure",
- "vin",
- "wiperStatus"
- ]
- },
- "OnVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "bodyInformation",
- "deviceStatus",
- "engineTorque",
- "externalTemperature",
- "fuelLevel",
- "fuelLevel_State",
- "headLampStatus",
- "instantFuelConsumption",
- "odometer",
- "tirePressure",
- "vin",
- "wiperStatus"
- ]
- },
- "SubscribeVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "bodyInformation",
- "deviceStatus",
- "engineTorque",
- "externalTemperature",
- "fuelLevel",
- "fuelLevel_State",
- "headLampStatus",
- "instantFuelConsumption",
- "odometer",
- "tirePressure",
- "wiperStatus"
- ]
- },
- "UnsubscribeVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "bodyInformation",
- "deviceStatus",
- "engineTorque",
- "externalTemperature",
- "fuelLevel",
- "fuelLevel_State",
- "headLampStatus",
- "instantFuelConsumption",
- "odometer",
- "tirePressure",
- "wiperStatus"
- ]
- }
- }
- },
- "Emergency-1": {
- "rpcs": {
- "GetVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "airbagStatus",
- "clusterModeStatus",
- "eCallInfo",
- "emergencyEvent"
- ]
- },
- "OnVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "airbagStatus",
- "clusterModeStatus",
- "eCallInfo",
- "emergencyEvent"
- ]
- },
- "SubscribeVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "airbagStatus",
- "clusterModeStatus",
- "eCallInfo",
- "emergencyEvent"
- ]
- },
- "UnsubscribeVehicleData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ],
- "parameters": [
- "airbagStatus",
- "clusterModeStatus",
- "eCallInfo",
- "emergencyEvent"
- ]
- }
- }
- },
- "Navigation-1": {
- "rpcs": {
- "AlertManeuver": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "ShowConstantTBT": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "UpdateTurnList": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- }
- }
- },
- "PropriataryData-1": {
- "rpcs": {
- "DiagnosticMessage": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "GetDTCs": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "ReadDID": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- }
- }
- },
- "ProprietaryData-3": {
- "rpcs": {
- "GetDTCs": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "ReadDID": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- }
- }
- },
- "DataConsent-2": {
- "user_consent_prompt": "DataConsent",
- "rpcs": null
- },
- "PropriataryData-2": {
- "rpcs": {
- "DiagnosticMessage": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "GetDTCs": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- },
- "ReadDID": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- }
- }
- },
- "DiagnosticMessageOnly": {
- "rpcs": {
- "DiagnosticMessage": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- }
- }
- },
- "OnKeyboardInputOnlyGroup": {
- "rpcs": {
- "OnKeyboardInput": {
- "hmi_levels": [
- "FULL"
- ]
- }
- }
- },
- "OnTouchEventOnlyGroup": {
- "rpcs": {
- "OnTouchEvent": {
- "hmi_levels": [
- "FULL"
- ]
- }
- }
- },
- "BaseBeforeDataConsent": {
- "rpcs": {
- "ChangeRegistration": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "DeleteFile": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "EncodedSyncPData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "ListFiles": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "OnAppInterfaceUnregistered": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "OnEncodedSyncPData": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "OnHashChange": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "OnHMIStatus": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "OnLanguageChange": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "OnPermissionsChange": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "OnSystemRequest": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "PutFile": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "RegisterAppInterface": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "ResetGlobalProperties": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "SetAppIcon": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "SetDisplayLayout": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "SetGlobalProperties": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "SystemRequest": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- },
- "UnregisterAppInterface": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED",
- "NONE"
- ]
- }
- }
- },
- "SendLocation": {
- "rpcs": {
- "SendLocation": {
- "hmi_levels": [
- "BACKGROUND",
- "FULL",
- "LIMITED"
- ]
- }
- }
- },
- "BackgroundAPT": {
- "rpcs": {
- "EndAudioPassThru": {
- "hmi_levels": [
- "BACKGROUND"
- ]
- },
- "OnAudioPassThru": {
- "hmi_levels": [
- "BACKGROUND"
- ]
- },
- "PerformAudioPassThru": {
- "hmi_levels": [
- "BACKGROUND"
- ]
- }
- }
- },
- "DialNumberOnly": {
- "rpcs": {
- "DialNumber": {
- "hmi_levels": [
- "FULL",
- "LIMITED"
- ]
- }
- }
- },
- "SendLocationOnly": {
- "rpcs": {
- "SendLocation": {
- "hmi_levels": [
- "FULL",
- "LIMITED"
- ]
- }
- }
- }
- },
- "consumer_friendly_messages": {
- "version": "001.001.023",
- "messages": {
- "AppPermissions": {
- "languages": {
- "de-de": {
- "tts": "%appName% benötigt die folgenden Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Wenn Sie Ja drücken, erklären Sie sich damit einverstanden, dass %vehicleMake% nicht für Schäden oder Verletzungen der Privatsphäre haftet, die im Zusammenhang mit der Nutzung Ihrer Benutzerdaten durch %appName% entstehen. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab.",
- "line1": "Zugriffsanfrage(n)",
- "line2": "erlauben?"
- },
- "en-au": {
- "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
- "line1": "Grant requested",
- "line2": "permission(s)?"
- },
- "en-gb": {
- "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. Please press Yes to allow or No to deny.",
- "line1": "Grant requested",
- "line2": "permission(s)?",
- "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
- },
- "en-ie": {
- "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
- "line1": "Grant requested",
- "line2": "permission(s)?"
- },
- "en-us": {
- "tts": "%appName% is requesting permission to use the following: %functionalGroupLabels%.\r\nTo disable or change these settings at any time visit the SYNC mobile apps settings menu. See App terms of service and privacy policies. Ford is not responsible for App functionality. Avoid distractions and use voice controls where available. Please press yes to allow or no to deny.",
- "line1": "Grant Requested",
- "line2": "Permission(s)?",
- "textBody": "The %appName% App is requesting permission to use the following: %functionalGroupLabels%.\r\n\r\nTo disable or change these settings at any time visit the SYNC mobile apps settings menu. See App terms of service and privacy policies. Ford is not responsible for App functionality. Avoid distractions and use voice controls where available. I agree and consent."
- },
- "es-en": {
- "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
- "line1": "¿Otorgar permiso(s)",
- "line2": "solicitado(s)?",
- "textBody": "La App %appName% solicita permiso para usar: %functionalGroupLabels%. \r\n\r\nPara desactivar o cambiar la configuración, acceda al menú de SYNC® de configuración de apps. Consulte términos de servicio y políticas de privacidad de la App. Ford no es responsable de la funcionalidad de la App. Evite distracciones y use los controles de voz cuando estén disponibles. Estoy de acuerdo y acepto lo anterior."
- },
- "es-es": {
- "tts": "%appName% está solicitando el uso de los siguientes permisos e información del vehículo: %functionalGroupLabels%. Si pulsa sí, acepta que %vehicleMake% no será responsable de los daños o la pérdida de privacidad relacionados con el uso de sus datos por parte de %appName%. Pulse sí para permitir o no para denegar.",
- "line1": "¿Conceder permisos",
- "line2": "solicitados?"
- },
- "es-mx": {
- "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
- "line1": "¿Otorgar permiso(s)",
- "line2": "solicitado(s)?",
- "textBody": "La App %appName% solicita permiso para usar: %functionalGroupLabels%. \r\n\r\nPara desactivar o cambiar la configuración, acceda al menú de SYNC® de configuración de apps. Consulte términos de servicio y políticas de privacidad de la App. Ford no es responsable de la funcionalidad de la App. Evite distracciones y use los controles de voz cuando estén disponibles. Estoy de acuerdo y acepto lo anterior."
- },
- "fr-ca": {
- "tts": "L’application %appName% demande la permission d’utiliser : %functionalGroupLabels%. \r\nPour désactiver ou modifier ces réglages de données à tout moment, consultez le menu de réglages des applications mobiles SYNC. Reportez-vous aux modalités de service et à la politique de confidentialité de l’application. Ford n’est pas responsable de la fonctionnalité de l’application. Évitez les distractions et utilisez les commandes vocales lorsqu’elles sont disponibles. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
- "line1": "Accorder permission(s)",
- "line2": "demandée(s)",
- "textBody": "L’application %appName% demande la permission d’utiliser : %functionalGroupLabels%. \r\n\r\nPour désactiver ou modifier ces réglages de données à tout moment, consultez le menu de réglages des applications mobiles SYNC. Reportez-vous aux modalités de service et à la politique de confidentialité de l’application. Ford n’est pas responsable de la fonctionnalité de l’application. Évitez les distractions et utilisez les commandes vocales lorsqu’elles sont disponibles. J’accepte et je consens."
- },
- "fr-fr": {
- "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
- "line1": "Accorder permission(s)",
- "line2": "demandée(s)"
- },
- "it-it": {
- "tts": "%appName% richiede l'uso delle seguenti informazioni e autorizzazioni sul veicolo: %functionalGroupLabels%. Se si preme Sì, si acconsente che %vehicleMake% non sarà responsabile per danni o perdita di privacy in relazione all'impiego dei dati da parte di %appName%. Premere Sì per consentire e No per negare.",
- "line1": "Concedi autorizzaz.",
- "line2": "richiesta(e)?"
- },
- "nl-nl": {
- "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. Als u op Ja drukt, gaat u ermee akkoord dat %vehicleMake% in geen geval aansprakelijk gesteld kan worden voor schade of verlies van privacy als gevolg van het feit dat %appName% gebruik maakt van uw gegevens. Druk op Ja om dit toe te staan of Nee om te weigeren.",
- "line1": "Aangevraagde",
- "line2": "permissie(s) verlenen?"
- },
- "pl-pl": {
- "tts": "%appName% wymaga następujących informacji o pojeździe oraz pozwoleń: %functionalGroupLabels%. Naciśnięcie TAK oznacza zgodę na fakt, iż %vehicleMake% nie będzie ponosić odpowiedzialności za szkody ani utratę prywatności w związku z wykorzystaniem przez %appName% danych, należących do użytkownika. Naciśnij TAK w celu udzielenia zgody lub NIE w celu odrzucenia żądania.",
- "line1": "Udzielić żądanych",
- "line2": "pozwoleń?"
- },
- "pt-br": {
- "tts": "%appName% está solicitando o uso das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se pressionar sim, você concorda que a %vehicleMake% não será responsável por danos ou perdas de privacidade relacionados ao uso dos seus dados por %appName%. Pressione sim para permitir ou não para negar.",
- "line1": "Conceder permissão",
- "line2": "solicitada?"
- },
- "pt-pt": {
- "tts": "%appName% está a solicitar a utilização das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se premir “Sim”, concorda que %vehicleMake% não será responsável por quaisquer danos ou perda de privacidade relacionada com a utilização dos seus dados por parte de %appName%. Prima “Sim” para permitir ou “Não” para recusar.",
- "line1": "Conceder permiss.",
- "line2": "solicitada(s)?"
- },
- "ru-ru": {
- "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Нажатием \"\"да\"\", Вы соглашаетесь, что %vehicleMake% не будет нести ответственность за какие-либо убытки или потерю прайвеси, связанные с использованием Ваших данных компанией %appName%. Нажмите \"\"Да\"\", если Вы согласны, или \"\"Нет\"\" - если не согласны.",
- "line1": "Предост. заправш.",
- "line2": "разрешения?"
- },
- "sv-se": {
- "tts": "%appName% begär att få tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Om du trycker Ja godkänner du att %vehicleMake% ska hållas skadeslös för alla skador som kan uppstå eller eventuella integritetsintrång som uppstår när %appName% använder dina data. Tryck Ja för att godkänna eller Nej för att neka.",
- "line1": "Vill du ge",
- "line2": "tillstånd?"
- },
- "tr-tr": {
- "tts": "%appName%, şu araç bilgilerini ve izinleri kullanma isteğinde bulunuyor: %functionalGroupLabels%. Evet'e basarsanız, %appName%'in verilerinizi kullanması sonucunda oluşabilecek hasarlardan veya gizlilik kaybından %vehicleMake%'in sorumlu olmayacağını kabul etmiş olacaksınız. Lütfen kabul etmek için Evet'e veya reddetmek için Hayır'a basın.",
- "line1": "İstenen izinler",
- "line2": "verilsin mi?"
- },
- "zh-cn": {
- "tts": "%appName% 正在请求使用下列车辆信息和权限: %functionalGroupLabels%。如果您按“是”,则表示您同意。 %vehicleMake% 将不会对因 %appName% 使用您的数据而引起的任何损毁或隐私损失负责。 请按“是”允许或按“否”拒绝。",
- "line1": "是否允许请求的",
- "line2": "权限?"
- },
- "zh-tw": {
- "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。按「是」,表示您同意,如因 %appName% 使用您的資料導致任何損害或損失,%vehicleMake% 將不負賠償責任。同意請按「是」,拒絕請按「否」。",
- "line1": "允許",
- "line2": "授權請求?"
- }
- }
- },
- "AppPermissionsHelp": {
- "languages": {
- "de-de": {
- "tts": "%appName% fordert folgende Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Im Einstellungsmenü der mobilen Apps können Sie diese Berechtigungen ändern und sich detaillierte Beschreibungen anhören. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
- },
- "en-au": {
- "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
- },
- "en-gb": {
- "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
- },
- "en-ie": {
- "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
- },
- "en-us": {
- "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press yes to grant permissions or no to deny."
- },
- "es-en": {
- "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
- },
- "es-es": {
- "tts": "%appName% está solicitando los siguientes permisos e información del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y escuchar descripciones detalladas en el menú de configuración de la aplicación móvil. Pulse sí para conceder el permiso o no para denegarlo."
- },
- "es-mx": {
- "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
- },
- "fr-ca": {
- "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
- },
- "fr-fr": {
- "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
- },
- "it-it": {
- "tts": "%appName% richiede le seguenti informazioni e autorizzazioni riguardo il veicolo: %functionalGroupLabels%. È possibile modificare tali autorizzazioni e ascoltare descrizioni dettagliate nel menu impostazioni delle app mobili. Premere Sì per concedere le autorizzazioni e No per negarle."
- },
- "nl-nl": {
- "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. U kunt deze toestemmingen wijzigen en gedetailleerde beschrijvingen beluisteren in het instellingenmenu voor mobiele apps. Druk op Ja om permissies te verlenen of op Nee om te weigeren."
- },
- "pl-pl": {
- "tts": "%appName% wymaga następujących informacji o pojeździe oraz zezwoleń: %functionalGroupLabels%. W menu ustawień aplikacji mobilnych można zmienić owe zezwolenia i usłyszeć ich szczegółowy opis. Naciśnij TAK, aby wyrazić zgodę lub NIE w celu odrzucenia żądania."
- },
- "pt-br": {
- "tts": "%appName% está solicitando as seguintes informações e permissões do veículo: %functionalGroupLabels%. Você pode alterar estas permissões e ouvir descrições detalhadas no menu de configurações de aplicativos móveis. Pressione sim para conceder as permissões ou não para negar."
- },
- "pt-pt": {
- "tts": "%appName% está a solicitar as seguintes informações e permissões do veículo: %functionalGroupLabels%. Pode alterar estas permissões e ouvir descrições detalhadas no menu de definições das aplicações móveis. Prima \"\"Sim\"\" para permitir ou \"\"Não\"\" para recusar."
- },
- "ru-ru": {
- "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Вы можете изменить эти разрешения и прослушать подробные их описания в меню настроек мобильного приложения. Нажмите \"\"да\"\", чтобы предоставить разрешения, или \"\"нет\"\", чтобы не предоставлять."
- },
- "sv-se": {
- "tts": "%appName% begär tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Du kan ändra tillstånden och höra detaljerade beskrivningar i menyn för mobilappsinställningar. Tryck Ja för att ge tillstånd eller Nej för att neka."
- },
- "tr-tr": {
- "tts": "%appName%, şu araç bilgilerini ve izinleri istiyor: %functionalGroupLabels%. Bu izinleri değiştirebilir ve mobil uygulamalar ayarlar menüsünden ayrıntılı açıklamaları dinleyebilirsiniz. Lütfen izin vermek için Evet'e veya reddetmek için Hayır'a basın."
- },
- "zh-cn": {
- "tts": "%appName% 正在请求下列车辆信息和权限: %functionalGroupLabels%。您可在移动应用程序设置菜单中更改这些权限,并听取详细说明。请按“是”允许权限或按“否”拒绝。"
- },
- "zh-tw": {
- "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。您可在行動應用程式設定清單中更改這些許可,並聆聽詳細說明。給予許可請按「是」,拒絕請按「否」。"
- }
- }
- },
- "AppPermissionsRevoked": {
- "languages": {
- "de-de": {
- "tts": "Die Autorisierungsdaten der App wurden geändert. %appName% hat keinen Zugriff auf %functionalGroupLabels% mehr. Installieren Sie die neueste Version der App auf Ihrem Gerät.."
- },
- "en-au": {
- "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
- },
- "en-gb": {
- "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
- },
- "en-ie": {
- "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
- },
- "en-us": {
- "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
- },
- "es-en": {
- "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
- },
- "es-es": {
- "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de que tiene la versión más reciente de la aplicación instalada en su dispositivo móvil."
- },
- "es-mx": {
- "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
- },
- "fr-ca": {
- "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
- },
- "fr-fr": {
- "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
- },
- "it-it": {
- "tts": "Le autorizzazioni dell'app sono cambiate. %appName% non è più in grado di accedere a %functionalGroupLabels%. Assicurarsi di avere la versione più recente dell'app installata sul dispositivo mobile."
- },
- "nl-nl": {
- "tts": "De app-autorisaties zijn gewijzigd. %appName% heeft geen toegang meer tot %functionalGroupLabels%. Zorg ervoor dat u de meest recente app-versie op uw mobiele apparaat geïnstalleerd hebt."
- },
- "pl-pl": {
- "tts": "Dane dostępu aplikacji zostały zmienione. %appName% nie ma już dostępu do %functionalGroupLabels%. Sprawdź, czy na telefonie komórkowym zainstalowano najnowszą wersję aplikacji."
- },
- "pt-br": {
- "tts": "As autorizações dos aplicativos foram alteradas. %appName% não pode mais acessar %functionalGroupLabels%. Certifique-se de que a versão mais recente do aplicativo está instalada no seu dispositivo móvel."
- },
- "pt-pt": {
- "tts": "As autorizações das aplicações mudaram. %appName% já não consegue aceder a %functionalGroupLabels%. Certifique-se de que tem a última versão da aplicação no seu dispositivo móvel."
- },
- "ru-ru": {
- "tts": "Авторизации приложения изменены. %appName% больше не имеет доступа к %functionalGroupLabels%. Убедитесь, что на вашем мобильном устройстве установлена самая новая версия приложения."
- },
- "sv-se": {
- "tts": "Appens behörigheter har ändrats. %appName% har inte längre åtkomst till %functionalGroupLabels%. Kontrollera att du har installerat den senaste versionen av appen på mobilenheten."
- },
- "tr-tr": {
- "tts": "Uygulama yetkileri değişti. %appName% artık %functionalGroupLabels%'e erişemeyecek. Lütfen mobil aygıtınızda en son uygulama sürümünün yüklü olduğundan emin olun."
- },
- "zh-cn": {
- "tts": "应用程序授权已变更。 %appName% 将不能再访问 %functionalGroupLabels%。 请确认您的移动设备上安装的应用程序是最新版本。"
- },
- "zh-tw": {
- "tts": "應用程式授權已改變。%appName% 已無法進入 %functionalGroupLabels%。請確認您的行動裝置上安裝了最新版應用程式。"
- }
- }
- },
- "AppUnauthorized": {
- "languages": {
- "de-de": {
- "tts": "Diese Version von %appName% ist nicht autorisiert und wird nicht mit SYNC funktionieren.",
- "line1": "nicht autorisiert"
- },
- "en-au": {
- "tts": "This version of %appName% is not authorized and will not work with SYNC.",
- "line1": "not authorized"
- },
- "en-gb": {
- "tts": "This version of %appName% is not authorized and will not work with SYNC.",
- "line1": "not authorized",
- "textBody": "This version of %appName% is not authorized and will not work with SYNC."
- },
- "en-ie": {
- "tts": "This version of %appName% is not authorized and will not work with SYNC.",
- "line1": "not authorized"
- },
- "en-us": {
- "tts": "This version of %appName% is not authorized and will not work with SYNC.",
- "line1": "Not Authorized",
- "textBody": "This version of %appName% is no longer authorized to work with Mobile Apps. Please update to the latest version of %appName%."
- },
- "es-en": {
- "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
- "line1": "no autorizada",
- "textBody": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
- },
- "es-es": {
- "tts": "Esta versión de %appName% no está autorizada y no funcionará con SYNC.",
- "line1": "No autorizada"
- },
- "es-mx": {
- "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
- "line1": "no autorizada",
- "textBody": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
- },
- "fr-ca": {
- "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
- "line1": "non autorisée",
- "textBody": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
- },
- "fr-fr": {
- "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
- "line1": "non autorisée"
- },
- "it-it": {
- "tts": "Questa versione di %appName% non è autorizzata e non funziona con il SYNC.",
- "line1": "non autorizzata"
- },
- "nl-nl": {
- "tts": "Deze versie van %appName% is niet geautoriseerd en werkt niet met SYNC.",
- "line1": "niet geautoriseerd"
- },
- "pl-pl": {
- "tts": "Niniejsza wersja %appName% nie posiada autoryzacji i nie będzie działać z SYNC.",
- "line1": "brak autoryzacji"
- },
- "pt-br": {
- "tts": "Esta versão do %appName% não tem autorização e não funcionará com o SYNC.",
- "line1": "não autorizado"
- },
- "pt-pt": {
- "tts": "Esta versão de %appName% não está autorizada e não funcionará com o SYNC.",
- "line1": "não autorizada"
- },
- "ru-ru": {
- "tts": "Эта версия %appName% не авторизирована и не будет работать с SYNC.",
- "line1": "не авторизировано"
- },
- "sv-se": {
- "tts": "Den här versionen av %appName% är inte godkänd och fungerar inte med SYNC.",
- "line1": "är ej godkänd"
- },
- "tr-tr": {
- "tts": "Bu %appName% sürümüne izin verilmediğinden SYNC ile çalışamaz.",
- "line1": "için izin yok"
- },
- "zh-cn": {
- "tts": "此版本的%appName% 未得到授权,无法在SYNC上使用。",
- "line1": "未得到授权"
- },
- "zh-tw": {
- "tts": "%appName% 的版本未獲得授權,將無法透過 SYNC 使用。",
- "line1": "無授權"
+ "policy_table": {
+ "module_config": {
+ "preloaded_pt": true,
+ "exchange_after_x_ignition_cycles": 100,
+ "exchange_after_x_kilometers": 1800,
+ "exchange_after_x_days": 30,
+ "timeout_after_x_seconds": 60,
+ "seconds_between_retries": [1,
+ 5,
+ 25,
+ 125,
+ 625],
+ "endpoints": {
+ "0x07": {
+ "default": ["http://policies.telematics.ford.com/api/policies"]
+ },
+ "0x04": {
+ "default": ["http://ivsu.software.ford.com/api/getsoftwareupdates"]
+ },
+ "queryAppsUrl": {
+ "default": ["http://sdl.shaid.server"]
+ },
+ "lock_screen_icon_url": {
+ "default": ["http://i.imgur.com/QwZ9uKG.png"]
+ }
+ },
+ "notifications_per_minute_by_priority": {
+ "EMERGENCY": 60,
+ "NAVIGATION": 15,
+ "VOICECOM": 20,
+ "COMMUNICATION": 6,
+ "NORMAL": 4,
+ "NONE": 0
}
- }
},
- "AppUnsupported": {
- "languages": {
- "de-de": {
- "tts": "Diese Version von %appName% wird von SYNC nicht unterstützt.",
- "line1": "nicht unterstützt"
- },
- "en-au": {
- "tts": "This version of %appName% is not supported by SYNC.",
- "line1": "not supported"
- },
- "en-gb": {
- "tts": "This version of %appName% is not supported by SYNC.",
- "line1": "not supported",
- "textBody": "This version of %appName% is not supported by SYNC."
- },
- "en-ie": {
- "tts": "This version of %appName% is not supported by SYNC.",
- "line1": "not supported"
- },
- "en-us": {
- "tts": "This version of %appName% is not supported by SYNC.",
- "line1": "Not Supported",
- "textBody": "Your version of %appName% is not supported by SYNC."
- },
- "es-en": {
- "tts": "Esta versión de %appName% no es compatible con SYNC.",
- "line1": "no compatible",
- "textBody": "Esta versión de %appName% no es compatible con SYNC."
- },
- "es-es": {
- "tts": "Esta versión de %appName% no es compatible con SYNC.",
- "line1": "No compatible"
- },
- "es-mx": {
- "tts": "Esta versión de %appName% no es compatible con SYNC.",
- "line1": "no compatible",
- "textBody": "Esta versión de %appName% no es compatible con SYNC."
- },
- "fr-ca": {
- "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
- "line1": "incompatible",
- "textBody": "Cette version de %appName% n’est pas prise en charge par SYNC."
- },
- "fr-fr": {
- "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
- "line1": "incompatible"
- },
- "it-it": {
- "tts": "Questa versione di %appName% non è supportata dal SYNC.",
- "line1": "non supportata"
- },
- "nl-nl": {
- "tts": "Deze versie van %appName% wordt niet ondersteund door SYNC.",
- "line1": "niet ondersteund"
- },
- "pl-pl": {
- "tts": "Niniejsza wersja %appName% nie jest obsługiwana przez system SYNC.",
- "line1": "aplikacja nie obsług."
- },
- "pt-br": {
- "tts": "Esta versão do %appName% não é suportada pelo SYNC.",
- "line1": "não suportado"
- },
- "pt-pt": {
- "tts": "Esta versão de %appName% não é suportado pelo SYNC.",
- "line1": "não suportada"
- },
- "ru-ru": {
- "tts": "Эта версия %appName% не поддерживается SYNC.",
- "line1": "не поддерживается"
- },
- "sv-se": {
- "tts": "SYNC har inte stöd för den här versionen av %appName%.",
- "line1": "stöds ej"
- },
- "tr-tr": {
- "tts": "Bu %appName% sürümü SYNC tarafından desteklenmiyor.",
- "line1": "desteklenmiyor"
- },
- "zh-cn": {
- "tts": "SYNC不支持此版本的%appName%。",
- "line1": "不受支持"
- },
- "zh-tw": {
- "tts": "SYNC 不支援此版本的%appName% 。",
- "line1": "不支援"
- }
- }
- },
- "DataConsent": {
- "languages": {
- "en-gb": {
- "textBody": "Would you like to enable Mobile Apps on SYNC? To use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S. \r\n\r\nUpdates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
- },
- "en-us": {
- "line1": "Enable Mobile Apps",
- "line2": "on SYNC? (Uses Data)",
- "textBody": "Would you like to enable Mobile Apps on SYNC?\r\n\r\nIf you enable the use of mobile apps from your mobile device on SYNC, you agree that SYNC can periodically use your device’s data plan to send and receive data that keeps your settings current and enables app functionality. Data sent to Ford U.S. includes your VIN and SYNC module number. Standard rates may apply.\r\n\r\nTo change settings or turn off later, visit the SYNC mobile apps settings menu. See Owner Guide for more information. I agree and consent."
- },
- "es-mx": {
- "textBody": "Si permite el uso de apps de su móvil vía SYNC®, acepta que SYNC® puede utilizar el plan de datos de su equipo para enviar y recibir info para actualizar su configuración y permitir la funcionalidad de la app. Datos enviados a Ford US incluyen VIN y # de módulo de SYNC®. Cargos a su plan de datos pueden aplicar. \r\n\r\nPara cambiar la config. de SYNC® o apagarlo, acceda a Menú de configuración de apps. Vea la Guía del Propietario para más info. Estoy de acuerdo y acepto lo anterior."
- },
- "fr-ca": {
- "textBody": "Si vous activez les applications mobiles sur SYNC, vous acceptez que SYNC utilise votre forfait de données afin de maintenir vos réglages à jour et assurer la pleine fonctionnalité. Parmi les données envoyées à Ford US, notons le NIV et le numéro de module SYNC. Des frais de base peuvent s’appliquer. \r\n\r\nPour modifier les réglages ou désactiver les applications, consultez le menu des réglages des applications de SYNC. Voir le Manuel du propriétaire. J’accepte et je consens."
- }
- }
- },
- "DataConsentHelp": {
- "languages": {
- "en-us": {
- "textBody": "By enabling mobile apps, you consent to allowing SYNC to communicate with Ford at least once per month using your mobile device’s data plan. Disabling will stop all data usage, but you will not be able to use mobile apps on SYNC. See your Owner Guide for more information."
- },
- "es-mx": {
- "textBody": "Las actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario."
- },
- "fr-ca": {
- "textBody": "Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements."
- }
- }
- },
- "DisableApps": {
- "languages": {
- "de-de": {
- "tts": "Ausschalten der automatischen Updates führt zum Ausschalten von SYNC mobile Apps. Sie können Ihre mobilen Apps dann nicht mehr mit SYNC nutzen. Bitte drücken Sie Ja zur Bestätigung oder Nein, um abzubrechen.",
- "line1": "Auto-Update",
- "line2": "und Mobile Apps deaktivieren"
- },
- "en-au": {
- "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
- "line1": "Disable auto-updates",
- "line2": "and Mobile Apps?"
- },
- "en-gb": {
- "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
- "line1": "Disable auto-updates",
- "line2": "and Mobile Apps?",
- "textBody": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
- },
- "en-ie": {
- "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
- "line1": "Disable auto-updates",
- "line2": "and Mobile Apps?"
- },
- "en-us": {
- "tts": "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel.",
- "line1": "Disable Auto-Updates",
- "line2": "and Mobile Apps?",
- "textBody": "If you disable, you will not be able to use any mobile apps with SYNC and your vehicle will stop receiving mobile app permission updates via your device`s data plan. Please press yes to disable mobile apps or no to cancel."
- },
- "es-en": {
- "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
- "line1": "¿Deshab. actualiz.",
- "line2": "autom. y aplic. móv.?",
- "textBody": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
- },
- "es-es": {
- "tts": "Si desactiva las actualizaciones automáticas, también se desactivará la sincronización de las aplicaciones móviles. No podrá utilizar ninguna aplicación móvil con SYNC. Pulse sí para confirmar o no para cancelar.",
- "line1": "¿Desact. actual. auto",
- "line2": "y apl. móviles?"
- },
- "es-mx": {
- "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
- "line1": "¿Deshab. actualiz.",
- "line2": "autom. y aplic. móv.?",
- "textBody": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
- },
- "fr-ca": {
- "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
- "line1": "Désactiver màj autom.",
- "line2": "et app. mobiles?",
- "textBody": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
- },
- "fr-fr": {
- "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
- "line1": "Désactiver màj autom.",
- "line2": "et app. mobiles?"
- },
- "it-it": {
- "tts": "Disabilitando gli aggiornamenti automatici si disattiva anche la sincronizzazione delle app mobili. Non sarà possibile usare app mobili con il SYNC. Premere Sì per confermare e No per cancellare.",
- "line1": "Disabilitare agg. aut.",
- "line2": "e app mobili?"
- },
- "nl-nl": {
- "tts": "Door automatische updates uit te schakelen, schakelt u ook SYNC-mobiele apps uit. U kunt dan geen mobiele apps meer gebruiken met SYNC. Druk op Ja om te bevestigen of op Nee om te annuleren.",
- "line1": "Auto-updates en mob.",
- "line2": "apps uitschakelen?"
- },
- "pl-pl": {
- "tts": "Wyłączenie automatycznych aktualizacji spowoduje także wyłączenie aplikacji mobilnych SYNC. Korzystanie z mobilnych aplikacji za pomocą SYNC będzie niemożliwe. Naciśnij TAK, by potwierdzić lub NIE, by anulować.",
- "line1": "Wył. automat. aktual.",
- "line2": "i aplikacje mobilne?"
- },
- "pt-br": {
- "tts": "Se as atualizações automáticas forem desativadas, os aplicativos também serão desativados. Você não poderá usar nenhum aplicativo com o SYNC. Pressione sim para confirmar ou não para cancelar.",
- "line1": "Desativar atualizações",
- "line2": "autom. e aplicativos?"
- },
- "pt-pt": {
- "tts": "A desactivação das actualizações automáticas desactiva igualmente as aplicações móveis do SYNC. Não poderá utilizar quaisquer aplicações móveis com o SYNC. Prima \"\"Sim\"\" para confirmar ou \"\"Não\"\" para cancelar.",
- "line1": "Desact. actual. autom.",
- "line2": "e aplicações móveis?"
- },
- "ru-ru": {
- "tts": "При отключении автоматических обновлений также будут отключены мобильные приложения sync. Вы не сможете использовать какие-либо мобильные приложения с SYNC. Нажмите \"\"Да\"\" для подтверждения или \"\"Нет\"\" для отмены.",
- "line1": "Откл. автообновления",
- "line2": "и мобил. прилож.?"
- },
- "sv-se": {
- "tts": "Om du avaktiverar automatisk uppdatering avaktiverar du även synkning av mobilappar. Du kommer inte längre att kunna använda dina mobilappar med SYNC. Tryck Ja för att bekräfta eller Nej för att avbryta.",
- "line1": "Avaktiverar autouppdat.",
- "line2": "och mobilappar?"
- },
- "tr-tr": {
- "tts": "Otomatik güncellemeleri devre dışı bırakırsanız sync mobil uygulamalar da devre dışı kalır. SYNC ile mobil uygulama kullanmanız mümkün olmaz. Lütfen onaylamak için Evet'e veya iptal etmek için Hayır'a basın.",
- "line1": "Oto. güncelleme ve",
- "line2": "mobil uygul. kapat?"
- },
- "zh-cn": {
- "tts": "禁用自动更新同时也会禁用SYNC移动应用程序。您将无法在 SYNC 中使用任何移动应用程序。请按“是”确认或按“否”取消。",
- "line1": "是否禁用自动更新和",
- "line2": "移动应用程序?"
- },
- "zh-tw": {
- "tts": "停用自動更新也將停用 sync 行動應用程式。您將無法透過 SYNC 使用任何行動應用程式。確認請按「是」,取消請按「否」。",
- "line1": "停用自動更新",
- "line2": "和行動應用程式?"
+ "functional_groupings": {
+ "Base-4": {
+ "rpcs": {
+ "AddCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "AddSubMenu": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "Alert": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "ChangeRegistration": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "CreateInteractionChoiceSet": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "DeleteInteractionChoiceSet": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteSubMenu": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "EndAudioPassThru": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "GenericResponse": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ListFiles": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAudioPassThru": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnButtonEvent": {
+ "hmi_levels": ["FULL",
+ "LIMITED",
+ "BACKGROUND"]
+ },
+ "OnButtonPress": {
+ "hmi_levels": ["FULL",
+ "LIMITED",
+ "BACKGROUND"]
+ },
+ "OnCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnDriverDistraction": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHashChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "PerformAudioPassThru": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "PerformInteraction": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "PutFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ResetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ScrollableMessage": {
+ "hmi_levels": ["FULL"]
+ },
+ "SetAppIcon": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetMediaClockTimer": {
+ "hmi_levels": ["FULL",
+ "LIMITED",
+ "BACKGROUND"]
+ },
+ "Show": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "Slider": {
+ "hmi_levels": ["FULL"]
+ },
+ "Speak": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "SubscribeButton": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "SystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnsubscribeButton": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "Location-1": {
+ "user_consent_prompt": "Location",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ }
+ }
+ },
+ "Notifications": {
+ "user_consent_prompt": "Notifications",
+ "rpcs": {
+ "Alert": {
+ "hmi_levels": ["BACKGROUND"]
+ }
+ }
+ },
+ "DrivingCharacteristics-3": {
+ "user_consent_prompt": "DrivingCharacteristics",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ }
+ }
+ },
+ "VehicleInfo-3": {
+ "user_consent_prompt": "VehicleInfo",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"]
+ }
+ }
+ },
+ "PropriataryData-1": {
+ "rpcs": {
+ "DiagnosticMessage": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "GetDTCs": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ReadDID": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "PropriataryData-2": {
+ "rpcs": {
+ "DiagnosticMessage": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "GetDTCs": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ReadDID": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "ProprietaryData-3": {
+ "rpcs": {
+ "GetDTCs": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ReadDID": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "Emergency-1": {
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ }
+ }
+ },
+ "Navigation-1": {
+ "rpcs": {
+ "AlertManeuver": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ShowConstantTBT": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "UpdateTurnList": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "Base-6": {
+ "rpcs": {
+ "AddCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "AddSubMenu": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "Alert": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "ChangeRegistration": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "CreateInteractionChoiceSet": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "DeleteInteractionChoiceSet": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteSubMenu": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "EndAudioPassThru": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "GenericResponse": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ListFiles": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAudioPassThru": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnButtonEvent": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "OnButtonPress": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "OnCommand": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "OnDriverDistraction": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnTBTClientState": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "PerformAudioPassThru": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "PerformInteraction": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "PutFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ResetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ScrollableMessage": {
+ "hmi_levels": ["FULL"]
+ },
+ "SetAppIcon": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "SetMediaClockTimer": {
+ "hmi_levels": ["FULL"]
+ },
+ "Show": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "Slider": {
+ "hmi_levels": ["FULL"]
+ },
+ "Speak": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "SubscribeButton": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "SyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnsubscribeButton": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "OnKeyboardInputOnlyGroup": {
+ "rpcs": {
+ "OnKeyboardInput": {
+ "hmi_levels": ["FULL"]
+ }
+ }
+ },
+ "OnTouchEventOnlyGroup": {
+ "rpcs": {
+ "OnTouchEvent": {
+ "hmi_levels": ["FULL"]
+ }
+ }
+ },
+ "DiagnosticMessageOnly": {
+ "rpcs": {
+ "DiagnosticMessage": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "DataConsent-2": {
+ "user_consent_prompt": "DataConsent",
+ "rpcs": null
+ },
+ "BaseBeforeDataConsent": {
+ "rpcs": {
+ "ChangeRegistration": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "DeleteFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ListFiles": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHashChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "PutFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ResetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetAppIcon": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ }
+ }
+ },
+ "SendLocation": {
+ "rpcs": {
+ "SendLocation": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "BackgroundAPT": {
+ "rpcs": {
+ "EndAudioPassThru": {
+ "hmi_levels": ["BACKGROUND"]
+ },
+ "OnAudioPassThru": {
+ "hmi_levels": ["BACKGROUND"]
+ },
+ "PerformAudioPassThru": {
+ "hmi_levels": ["BACKGROUND"]
+ }
+ }
}
- }
},
- "DrivingCharacteristics": {
- "languages": {
- "de-de": {
- "tts": "Eine App hat Zugriff auf die folgenden Fahreigenschaften: Kraftstoffverbrauch, MyKey, Sicherheitsgurtstatus.",
- "label": "Fahreigenschaften"
- },
- "en-au": {
- "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
- "label": "Driving characteristics"
- },
- "en-gb": {
- "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
- "label": "Driving characteristics",
- "textBody": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
- },
- "en-ie": {
- "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
- "label": "Driving characteristics"
- },
- "en-us": {
- "tts": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status, Gear Position, RPM.",
- "label": "Driving Characteristics",
- "textBody": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status, Gear Position, RPM."
- },
- "es-en": {
- "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
- "label": "Características del manejo",
- "textBody": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
- },
- "es-es": {
- "tts": "Una aplicación puede acceder a las siguientes características de conducción: Consumo de combustible, MyKey, Estado cinturones de seguridad.",
- "label": "Características de conducción"
- },
- "es-mx": {
- "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad, RPM del motor, y Posición del cambio.",
- "label": "Características del manejo",
- "textBody": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad, RPM del motor, y Posición del cambio."
- },
- "fr-ca": {
- "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité, régime du moteur, et Position d’embrayage.",
- "label": "Caractéristiques de conduite",
- "textBody": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité, régime du moteur, et Position d’embrayage."
- },
- "fr-fr": {
- "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
- "label": "Caractéristiques de conduite"
- },
- "it-it": {
- "tts": "Un'app può avere accesso alle seguenti caratteristiche di guida: Consumo carburante, MyKey, Stato cinture di sicurezza.",
- "label": "Caratteristiche di guida"
- },
- "nl-nl": {
- "tts": "Een app heeft toegang tot de volgende rijkenmerken: Brandstofverbruik, MyKey, Veiligheidsgordelstatus.",
- "label": "Rijkenmerken"
- },
- "pl-pl": {
- "tts": "Aplikacja może uzyskać dostęp do następujących informacji dotyczących jazdy: Zużycie paliwa, MyKey, Stan pasów bezpieczeństwa.",
- "label": "Informacje dotyczące stylu jazdy"
- },
- "pt-br": {
- "tts": "Um aplicativo pode acessar as seguintes características de condução: Consumo de combustível, MyKey, Estado do cinto de segurança.",
- "label": "Características de condução",
- "line1": "Caract. Condução"
- },
- "pt-pt": {
- "tts": "Uma aplicação consegue aceder às seguintes informações de condução: Consumo de combustível, MyKey, Estado dos cintos de segurança.",
- "label": "Características de condução"
- },
- "ru-ru": {
- "tts": "Приложение имеет доступ к следующим характеристикам движения: Расход топлива, MyKey, Состояние ремней безопасности.",
- "label": "Характеристики движения"
- },
- "sv-se": {
- "tts": "Appen kan komma åt följande köregenskaper: Bränsleförbrukning, MyKey, Bältesstatus.",
- "label": "Köregenskaper"
- },
- "tr-tr": {
- "tts": "Bir uygulama şu sürüş karakteristiklerine erişebilir: Yakıt tüketimi, MyKey, Emniyet kemeri durumu.",
- "label": "Sürüş karakteristikleri"
- },
- "zh-cn": {
- "tts": "移动应用程序可访问下列行驶特性: 油耗, MyKey, 安全带状态",
- "label": "行驶特性"
- },
- "zh-tw": {
- "tts": "應用程式可存取以下駕駛特性: 油耗, MyKey, 安全帶狀態",
- "label": "駕駛特性"
+ "consumer_friendly_messages": {
+ "version": "001.001.021",
+ "messages": {
+ "AppPermissions": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% benötigt die folgenden Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Wenn Sie Ja drücken, erklären Sie sich damit einverstanden, dass %vehicleMake% nicht für Schäden oder Verletzungen der Privatsphäre haftet, die im Zusammenhang mit der Nutzung Ihrer Benutzerdaten durch %appName% entstehen. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab.",
+ "line1": "Zugriffsanfrage(n)",
+ "line2": "erlauben?"
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. Please press yes to allow or no to deny.",
+ "line1": "Grant Requested",
+ "line2": "Permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. \n\nIf you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "es-en": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?",
+ "textBody": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar. \n\n Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando el uso de los siguientes permisos e información del vehículo: %functionalGroupLabels%. Si pulsa sí, acepta que %vehicleMake% no será responsable de los daños o la pérdida de privacidad relacionados con el uso de sus datos por parte de %appName%. Pulse sí para permitir o no para denegar.",
+ "line1": "¿Conceder permisos",
+ "line2": "solicitados?"
+ },
+ "es-mx": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?",
+ "textBody": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. \n\nSi presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles."
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)",
+ "textBody": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)"
+ },
+ "it-it": {
+ "tts": "%appName% richiede l'uso delle seguenti informazioni e autorizzazioni sul veicolo: %functionalGroupLabels%. Se si preme Sì, si acconsente che %vehicleMake% non sarà responsabile per danni o perdita di privacy in relazione all'impiego dei dati da parte di %appName%. Premere Sì per consentire e No per negare.",
+ "line1": "Concedi autorizzaz.",
+ "line2": "richiesta(e)?"
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. Als u op Ja drukt, gaat u ermee akkoord dat %vehicleMake% in geen geval aansprakelijk gesteld kan worden voor schade of verlies van privacy als gevolg van het feit dat %appName% gebruik maakt van uw gegevens. Druk op Ja om dit toe te staan of Nee om te weigeren.",
+ "line1": "Aangevraagde",
+ "line2": "permissie(s) verlenen?"
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz pozwoleń: %functionalGroupLabels%. Naciśnięcie TAK oznacza zgodę na fakt, iż %vehicleMake% nie będzie ponosić odpowiedzialności za szkody ani utratę prywatności w związku z wykorzystaniem przez %appName% danych, należących do użytkownika. Naciśnij TAK w celu udzielenia zgody lub NIE w celu odrzucenia żądania.",
+ "line1": "Udzielić żądanych",
+ "line2": "pozwoleń?"
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando o uso das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se pressionar sim, você concorda que a %vehicleMake% não será responsável por danos ou perdas de privacidade relacionados ao uso dos seus dados por %appName%. Pressione sim para permitir ou não para negar.",
+ "line1": "Conceder permissão",
+ "line2": "solicitada?"
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar a utilização das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se premir “Sim”, concorda que %vehicleMake% não será responsável por quaisquer danos ou perda de privacidade relacionada com a utilização dos seus dados por parte de %appName%. Prima “Sim” para permitir ou “Não” para recusar.",
+ "line1": "Conceder permiss.",
+ "line2": "solicitada(s)?"
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Нажатием \"\"да\"\", Вы соглашаетесь, что %vehicleMake% не будет нести ответственность за какие-либо убытки или потерю прайвеси, связанные с использованием Ваших данных компанией %appName%. Нажмите \"\"Да\"\", если Вы согласны, или \"\"Нет\"\" - если не согласны.",
+ "line1": "Предост. заправш.",
+ "line2": "разрешения?"
+ },
+ "sv-se": {
+ "tts": "%appName% begär att få tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Om du trycker Ja godkänner du att %vehicleMake% ska hållas skadeslös för alla skador som kan uppstå eller eventuella integritetsintrång som uppstår när %appName% använder dina data. Tryck Ja för att godkänna eller Nej för att neka.",
+ "line1": "Vill du ge",
+ "line2": "tillstånd?"
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri kullanma isteğinde bulunuyor: %functionalGroupLabels%. Evet'e basarsanız, %appName%'in verilerinizi kullanması sonucunda oluşabilecek hasarlardan veya gizlilik kaybından %vehicleMake%'in sorumlu olmayacağını kabul etmiş olacaksınız. Lütfen kabul etmek için Evet'e veya reddetmek için Hayır'a basın.",
+ "line1": "İstenen izinler",
+ "line2": "verilsin mi?"
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求使用下列车辆信息和权限: %functionalGroupLabels%。如果您按“是”,则表示您同意。 %vehicleMake% 将不会对因 %appName% 使用您的数据而引起的任何损毁或隐私损失负责。 请按“是”允许或按“否”拒绝。",
+ "line1": "是否允许请求的",
+ "line2": "权限?"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。按「是」,表示您同意,如因 %appName% 使用您的資料導致任何損害或損失,%vehicleMake% 將不負賠償責任。同意請按「是」,拒絕請按「否」。",
+ "line1": "允許",
+ "line2": "授權請求?"
+ }
+ }
+ },
+ "AppPermissionsHelp": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% fordert folgende Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Im Einstellungsmenü der mobilen Apps können Sie diese Berechtigungen ändern und sich detaillierte Beschreibungen anhören. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press yes to grant permissions or no to deny."
+ },
+ "es-en": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando los siguientes permisos e información del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y escuchar descripciones detalladas en el menú de configuración de la aplicación móvil. Pulse sí para conceder el permiso o no para denegarlo."
+ },
+ "es-mx": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "it-it": {
+ "tts": "%appName% richiede le seguenti informazioni e autorizzazioni riguardo il veicolo: %functionalGroupLabels%. È possibile modificare tali autorizzazioni e ascoltare descrizioni dettagliate nel menu impostazioni delle app mobili. Premere Sì per concedere le autorizzazioni e No per negarle."
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. U kunt deze toestemmingen wijzigen en gedetailleerde beschrijvingen beluisteren in het instellingenmenu voor mobiele apps. Druk op Ja om permissies te verlenen of op Nee om te weigeren."
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz zezwoleń: %functionalGroupLabels%. W menu ustawień aplikacji mobilnych można zmienić owe zezwolenia i usłyszeć ich szczegółowy opis. Naciśnij TAK, aby wyrazić zgodę lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando as seguintes informações e permissões do veículo: %functionalGroupLabels%. Você pode alterar estas permissões e ouvir descrições detalhadas no menu de configurações de aplicativos móveis. Pressione sim para conceder as permissões ou não para negar."
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar as seguintes informações e permissões do veículo: %functionalGroupLabels%. Pode alterar estas permissões e ouvir descrições detalhadas no menu de definições das aplicações móveis. Prima \"\"Sim\"\" para permitir ou \"\"Não\"\" para recusar."
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Вы можете изменить эти разрешения и прослушать подробные их описания в меню настроек мобильного приложения. Нажмите \"\"да\"\", чтобы предоставить разрешения, или \"\"нет\"\", чтобы не предоставлять."
+ },
+ "sv-se": {
+ "tts": "%appName% begär tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Du kan ändra tillstånden och höra detaljerade beskrivningar i menyn för mobilappsinställningar. Tryck Ja för att ge tillstånd eller Nej för att neka."
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri istiyor: %functionalGroupLabels%. Bu izinleri değiştirebilir ve mobil uygulamalar ayarlar menüsünden ayrıntılı açıklamaları dinleyebilirsiniz. Lütfen izin vermek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求下列车辆信息和权限: %functionalGroupLabels%。您可在移动应用程序设置菜单中更改这些权限,并听取详细说明。请按“是”允许权限或按“否”拒绝。"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。您可在行動應用程式設定清單中更改這些許可,並聆聽詳細說明。給予許可請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsRevoked": {
+ "languages": {
+ "de-de": {
+ "tts": "Die Autorisierungsdaten der App wurden geändert. %appName% hat keinen Zugriff auf %functionalGroupLabels% mehr. Installieren Sie die neueste Version der App auf Ihrem Gerät.."
+ },
+ "en-au": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-gb": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-ie": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-us": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "es-en": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "es-es": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de que tiene la versión más reciente de la aplicación instalada en su dispositivo móvil."
+ },
+ "es-mx": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "fr-ca": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "fr-fr": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "it-it": {
+ "tts": "Le autorizzazioni dell'app sono cambiate. %appName% non è più in grado di accedere a %functionalGroupLabels%. Assicurarsi di avere la versione più recente dell'app installata sul dispositivo mobile."
+ },
+ "nl-nl": {
+ "tts": "De app-autorisaties zijn gewijzigd. %appName% heeft geen toegang meer tot %functionalGroupLabels%. Zorg ervoor dat u de meest recente app-versie op uw mobiele apparaat geïnstalleerd hebt."
+ },
+ "pl-pl": {
+ "tts": "Dane dostępu aplikacji zostały zmienione. %appName% nie ma już dostępu do %functionalGroupLabels%. Sprawdź, czy na telefonie komórkowym zainstalowano najnowszą wersję aplikacji."
+ },
+ "pt-br": {
+ "tts": "As autorizações dos aplicativos foram alteradas. %appName% não pode mais acessar %functionalGroupLabels%. Certifique-se de que a versão mais recente do aplicativo está instalada no seu dispositivo móvel."
+ },
+ "pt-pt": {
+ "tts": "As autorizações das aplicações mudaram. %appName% já não consegue aceder a %functionalGroupLabels%. Certifique-se de que tem a última versão da aplicação no seu dispositivo móvel."
+ },
+ "ru-ru": {
+ "tts": "Авторизации приложения изменены. %appName% больше не имеет доступа к %functionalGroupLabels%. Убедитесь, что на вашем мобильном устройстве установлена самая новая версия приложения."
+ },
+ "sv-se": {
+ "tts": "Appens behörigheter har ändrats. %appName% har inte längre åtkomst till %functionalGroupLabels%. Kontrollera att du har installerat den senaste versionen av appen på mobilenheten."
+ },
+ "tr-tr": {
+ "tts": "Uygulama yetkileri değişti. %appName% artık %functionalGroupLabels%'e erişemeyecek. Lütfen mobil aygıtınızda en son uygulama sürümünün yüklü olduğundan emin olun."
+ },
+ "zh-cn": {
+ "tts": "应用程序授权已变更。 %appName% 将不能再访问 %functionalGroupLabels%。 请确认您的移动设备上安装的应用程序是最新版本。"
+ },
+ "zh-tw": {
+ "tts": "應用程式授權已改變。%appName% 已無法進入 %functionalGroupLabels%。請確認您的行動裝置上安裝了最新版應用程式。"
+ }
+ }
+ },
+ "AppUnauthorized": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% ist nicht autorisiert und wird nicht mit SYNC funktionieren.",
+ "line1": "nicht autorisiert"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized",
+ "textBody": "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "Not Authorized",
+ "textBody": "This version of %appName% is no longer authorized to work with AppLink. Please update to the latest version of %appName%."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada",
+ "textBody": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no está autorizada y no funcionará con SYNC.",
+ "line1": "No autorizada"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada",
+ "textBody": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée",
+ "textBody": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è autorizzata e non funziona con il SYNC.",
+ "line1": "non autorizzata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% is niet geautoriseerd en werkt niet met SYNC.",
+ "line1": "niet geautoriseerd"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie posiada autoryzacji i nie będzie działać z SYNC.",
+ "line1": "brak autoryzacji"
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não tem autorização e não funcionará com o SYNC.",
+ "line1": "não autorizado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não está autorizada e não funcionará com o SYNC.",
+ "line1": "não autorizada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не авторизирована и не будет работать с SYNC.",
+ "line1": "не авторизировано"
+ },
+ "sv-se": {
+ "tts": "Den här versionen av %appName% är inte godkänd och fungerar inte med SYNC.",
+ "line1": "är ej godkänd"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümüne izin verilmediğinden SYNC ile çalışamaz.",
+ "line1": "için izin yok"
+ },
+ "zh-cn": {
+ "tts": "此版本的%appName% 未得到授权,无法在SYNC上使用。",
+ "line1": "未得到授权"
+ },
+ "zh-tw": {
+ "tts": "%appName% 的版本未獲得授權,將無法透過 SYNC 使用。",
+ "line1": "無授權"
+ }
+ }
+ },
+ "AppUnsupported": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% wird von SYNC nicht unterstützt.",
+ "line1": "nicht unterstützt"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported",
+ "textBody": "This version of %appName% is not supported by SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "Not Supported",
+ "textBody": "Your version of %appName% is not supported by SYNC."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible",
+ "textBody": "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "No compatible"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible",
+ "textBody": "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible",
+ "textBody": "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è supportata dal SYNC.",
+ "line1": "non supportata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% wordt niet ondersteund door SYNC.",
+ "line1": "niet ondersteund"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie jest obsługiwana przez system SYNC.",
+ "line1": "aplikacja nie obsług."
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não é suportada pelo SYNC.",
+ "line1": "não suportado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não é suportado pelo SYNC.",
+ "line1": "não suportada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не поддерживается SYNC.",
+ "line1": "не поддерживается"
+ },
+ "sv-se": {
+ "tts": "SYNC har inte stöd för den här versionen av %appName%.",
+ "line1": "stöds ej"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümü SYNC tarafından desteklenmiyor.",
+ "line1": "desteklenmiyor"
+ },
+ "zh-cn": {
+ "tts": "SYNC不支持此版本的%appName%。",
+ "line1": "不受支持"
+ },
+ "zh-tw": {
+ "tts": "SYNC 不支援此版本的%appName% 。",
+ "line1": "不支援"
+ }
+ }
+ },
+ "DataConsent": {
+ "languages": {
+ "en-gb": {
+ "textBody": "Would you like to enable Mobile Apps on SYNC? To use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S. \r\n\r\nUpdates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "en-us": {
+ "line1": "Enable Mobile Apps",
+ "line2": "on SYNC? (Uses Data)",
+ "textBody": "Would you like to enable Mobile Apps on SYNC?\r\n\r\nTo use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S.\r\n\r\nUpdates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "es-mx": {
+ "textBody": "Para usar aplicaciones móviles con SYNC, este debe comunicarse con Ford al menos una vez al mes a través del plan de datos de su dispositivo móvil. Pueden aplicar tarifas normales. SYNC enviará su VIN y el número de módulo de SYNC a Ford de Estados Unidos de América. \n\nLas actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario. \n\nPresione Sí para permitir y No para denegar."
+ },
+ "fr-ca": {
+ "textBody": "Pour utiliser AppLink, SYNC devra communiquer avec Ford au moins une fois par mois en utilisant le forfait de données de votre appareil mobile. Les tarifs réguliers peuvent s’appliquer. SYNC enverra votre NIV et le numéro de votre module SYNC à Ford États-Unis. Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements.\r\n\r\nVeuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ }
+ }
+ },
+ "DataConsentHelp": {
+ "languages": {
+ "en-us": {
+ "textBody": "By enabling mobile apps, you consent to allowing SYNC to communicate with Ford at least once per month using your mobile device’s data plan. Disabling will stop all data usage, but you will not be able to use mobile apps on SYNC. See your Owner Guide for more information."
+ },
+ "es-mx": {
+ "textBody": "Las actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario."
+ },
+ "fr-ca": {
+ "textBody": "Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements."
+ }
+ }
+ },
+ "DisableApps": {
+ "languages": {
+ "de-de": {
+ "tts": "Ausschalten der automatischen Updates führt zum Ausschalten von SYNC mobile Apps. Sie können Ihre mobilen Apps dann nicht mehr mit SYNC nutzen. Bitte drücken Sie Ja zur Bestätigung oder Nein, um abzubrechen.",
+ "line1": "Auto-Update",
+ "line2": "und Mobile Apps deaktivieren"
+ },
+ "en-au": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-gb": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-ie": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-us": {
+ "tts": "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel.",
+ "line1": "Disable Auto-Updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "If you disable, you will not be able to use any mobile apps with SYNC and your vehicle will stop receiving mobile app permission updates via your device`s data plan. Please press yes to disable mobile apps or no to cancel."
+ },
+ "es-en": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?",
+ "textBody": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "es-es": {
+ "tts": "Si desactiva las actualizaciones automáticas, también se desactivará la sincronización de las aplicaciones móviles. No podrá utilizar ninguna aplicación móvil con SYNC. Pulse sí para confirmar o no para cancelar.",
+ "line1": "¿Desact. actual. auto",
+ "line2": "y apl. móviles?"
+ },
+ "es-mx": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?",
+ "textBody": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "fr-ca": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?",
+ "textBody": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "fr-fr": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?"
+ },
+ "it-it": {
+ "tts": "Disabilitando gli aggiornamenti automatici si disattiva anche la sincronizzazione delle app mobili. Non sarà possibile usare app mobili con il SYNC. Premere Sì per confermare e No per cancellare.",
+ "line1": "Disabilitare agg. aut.",
+ "line2": "e app mobili?"
+ },
+ "nl-nl": {
+ "tts": "Door automatische updates uit te schakelen, schakelt u ook SYNC-mobiele apps uit. U kunt dan geen mobiele apps meer gebruiken met SYNC. Druk op Ja om te bevestigen of op Nee om te annuleren.",
+ "line1": "Auto-updates en mob.",
+ "line2": "apps uitschakelen?"
+ },
+ "pl-pl": {
+ "tts": "Wyłączenie automatycznych aktualizacji spowoduje także wyłączenie aplikacji mobilnych SYNC. Korzystanie z mobilnych aplikacji za pomocą SYNC będzie niemożliwe. Naciśnij TAK, by potwierdzić lub NIE, by anulować.",
+ "line1": "Wył. automat. aktual.",
+ "line2": "i aplikacje mobilne?"
+ },
+ "pt-br": {
+ "tts": "Se as atualizações automáticas forem desativadas, os aplicativos também serão desativados. Você não poderá usar nenhum aplicativo com o SYNC. Pressione sim para confirmar ou não para cancelar.",
+ "line1": "Desativar atualizações",
+ "line2": "autom. e aplicativos?"
+ },
+ "pt-pt": {
+ "tts": "A desactivação das actualizações automáticas desactiva igualmente as aplicações móveis do SYNC. Não poderá utilizar quaisquer aplicações móveis com o SYNC. Prima \"\"Sim\"\" para confirmar ou \"\"Não\"\" para cancelar.",
+ "line1": "Desact. actual. autom.",
+ "line2": "e aplicações móveis?"
+ },
+ "ru-ru": {
+ "tts": "При отключении автоматических обновлений также будут отключены мобильные приложения sync. Вы не сможете использовать какие-либо мобильные приложения с SYNC. Нажмите \"\"Да\"\" для подтверждения или \"\"Нет\"\" для отмены.",
+ "line1": "Откл. автообновления",
+ "line2": "и мобил. прилож.?"
+ },
+ "sv-se": {
+ "tts": "Om du avaktiverar automatisk uppdatering avaktiverar du även synkning av mobilappar. Du kommer inte längre att kunna använda dina mobilappar med SYNC. Tryck Ja för att bekräfta eller Nej för att avbryta.",
+ "line1": "Avaktiverar autouppdat.",
+ "line2": "och mobilappar?"
+ },
+ "tr-tr": {
+ "tts": "Otomatik güncellemeleri devre dışı bırakırsanız sync mobil uygulamalar da devre dışı kalır. SYNC ile mobil uygulama kullanmanız mümkün olmaz. Lütfen onaylamak için Evet'e veya iptal etmek için Hayır'a basın.",
+ "line1": "Oto. güncelleme ve",
+ "line2": "mobil uygul. kapat?"
+ },
+ "zh-cn": {
+ "tts": "禁用自动更新同时也会禁用SYNC移动应用程序。您将无法在 SYNC 中使用任何移动应用程序。请按“是”确认或按“否”取消。",
+ "line1": "是否禁用自动更新和",
+ "line2": "移动应用程序?"
+ },
+ "zh-tw": {
+ "tts": "停用自動更新也將停用 sync 行動應用程式。您將無法透過 SYNC 使用任何行動應用程式。確認請按「是」,取消請按「否」。",
+ "line1": "停用自動更新",
+ "line2": "和行動應用程式?"
+ }
+ }
+ },
+ "DrivingCharacteristics": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahreigenschaften: Kraftstoffverbrauch, MyKey, Sicherheitsgurtstatus.",
+ "label": "Fahreigenschaften"
+ },
+ "en-au": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-gb": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-ie": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-us": {
+ "tts": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status.",
+ "label": "Driving Characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo",
+ "textBody": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a las siguientes características de conducción: Consumo de combustible, MyKey, Estado cinturones de seguridad.",
+ "label": "Características de conducción"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo",
+ "textBody": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite",
+ "textBody": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti caratteristiche di guida: Consumo carburante, MyKey, Stato cinture di sicurezza.",
+ "label": "Caratteristiche di guida"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende rijkenmerken: Brandstofverbruik, MyKey, Veiligheidsgordelstatus.",
+ "label": "Rijkenmerken"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji dotyczących jazdy: Zużycie paliwa, MyKey, Stan pasów bezpieczeństwa.",
+ "label": "Informacje dotyczące stylu jazdy"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes características de condução: Consumo de combustível, MyKey, Estado do cinto de segurança.",
+ "label": "Características de condução"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações de condução: Consumo de combustível, MyKey, Estado dos cintos de segurança.",
+ "label": "Características de condução"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим характеристикам движения: Расход топлива, MyKey, Состояние ремней безопасности.",
+ "label": "Характеристики движения"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande köregenskaper: Bränsleförbrukning, MyKey, Bältesstatus.",
+ "label": "Köregenskaper"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu sürüş karakteristiklerine erişebilir: Yakıt tüketimi, MyKey, Emniyet kemeri durumu.",
+ "label": "Sürüş karakteristikleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列行驶特性: 油耗, MyKey, 安全带状态",
+ "label": "行驶特性"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取以下駕駛特性: 油耗, MyKey, 安全帶狀態",
+ "label": "駕駛特性"
+ }
+ }
+ },
+ "Location": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die GPS-Daten und die Geschwindigkeit des Fahrzeugs.",
+ "label": "GPS und Geschwindigkeit"
+ },
+ "en-au": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-gb": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "en-ie": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-us": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad",
+ "textBody": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder al GPS y la velocidad del vehículo.",
+ "label": "GPS y velocidad"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad",
+ "textBody": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse",
+ "textBody": "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso a GPS e velocità del veicolo.",
+ "label": "GPS e velocità"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot gps en de snelheid van het voertuig.",
+ "label": "Gps en snelheid"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do modułu GPS i prędkości pojazdu.",
+ "label": "GPS i prędkość"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar o GPS e a velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder ao GPS e à velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к GPS и скорости автомобиля.",
+ "label": "GPS и скорость"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt fordonets GPS och hastighetsmätare.",
+ "label": "GPS och hastighet"
+ },
+ "tr-tr": {
+ "tts": "Bu uygulama aracın GPS ve hız bilgilerine erişebilir.",
+ "label": "GPS ve hız"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可以访问车辆 GPS 和车速信息。",
+ "label": "GPS 和车速"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取車輛的GPS和速度。",
+ "label": "GPS和車速"
+ }
+ }
+ },
+ "Notifications": {
+ "languages": {
+ "de-de": {
+ "tts": "Läuft die App im Hintergrund, kann Sie Benachrichtigungen senden.",
+ "label": "Push-Benachrichtigungen"
+ },
+ "en-au": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-gb": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "en-ie": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-us": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push",
+ "textBody": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede enviar notificaciones cuando se está ejecutando en segundo plano.",
+ "label": "Notificaciones push"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push",
+ "textBody": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "fr-ca": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications instantanées",
+ "textBody": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "fr-fr": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications push"
+ },
+ "it-it": {
+ "tts": "Un'app può inviare notifiche se eseguita in background.",
+ "label": "Notifiche push"
+ },
+ "nl-nl": {
+ "tts": "Een app kan meldingen versturen als deze op de achtergrond actief is.",
+ "label": "Push-meldingen"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może wysyłać powiadomienia, działając w tle.",
+ "label": "Powiadomienia Push"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode enviar notificações quando estiver sendo executado em segundo plano.",
+ "label": "Notificações Push"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue enviar notificações quando está activa em segundo plano.",
+ "label": "Notificações push"
+ },
+ "ru-ru": {
+ "tts": "Если приложение работает в фоновом режиме, оно может отправлять оповещения.",
+ "label": "Оповещения о пересылке"
+ },
+ "sv-se": {
+ "tts": "Appen kan skicka meddelanden när den körs i bakgrunden.",
+ "label": "Push-notiser"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama arka planda çalışırken bildirim gönderebilir.",
+ "label": "Anlık bildirimleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序在后台运行时可推送通知。",
+ "label": "推送通知"
+ },
+ "zh-tw": {
+ "tts": "車輛行進時,應用程式可在背景中傳送通知。",
+ "label": "傳送通知"
+ }
+ }
+ },
+ "SettingDisableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Updates deakt."
+ },
+ "en-au": {
+ "line1": "Disable updates"
+ },
+ "en-gb": {
+ "line1": "Disable updates"
+ },
+ "en-ie": {
+ "line1": "Disable updates"
+ },
+ "en-us": {
+ "line1": "Disable Updates",
+ "textBody": "Disable Updates"
+ },
+ "es-en": {
+ "line1": "Deshab. actual.",
+ "textBody": "Deshab. actual."
+ },
+ "es-es": {
+ "line1": "Desact. actual."
+ },
+ "es-mx": {
+ "line1": "Deshab. actual.",
+ "textBody": "Deshab. actual."
+ },
+ "fr-ca": {
+ "line1": "Désactiver MAJ",
+ "textBody": "Désactiver MAJ"
+ },
+ "fr-fr": {
+ "line1": "Désactiver màj"
+ },
+ "it-it": {
+ "line1": "Disabilita agg."
+ },
+ "nl-nl": {
+ "line1": "Upd. uitschak."
+ },
+ "pl-pl": {
+ "line1": "Wyłącz aktual."
+ },
+ "pt-br": {
+ "line1": "Desat. atualiz."
+ },
+ "pt-pt": {
+ "line1": "Desact. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Откл. обновл."
+ },
+ "sv-se": {
+ "line1": "Inaktivera uppd."
+ },
+ "tr-tr": {
+ "line1": "Güncell. Kapat"
+ },
+ "zh-cn": {
+ "line1": "禁用更新"
+ },
+ "zh-tw": {
+ "line1": "停用更新"
+ }
+ }
+ },
+ "SettingEnableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Apps aktivieren"
+ },
+ "en-au": {
+ "line1": "Enable Apps"
+ },
+ "en-gb": {
+ "line1": "Enable Apps"
+ },
+ "en-ie": {
+ "line1": "Enable Apps"
+ },
+ "en-us": {
+ "line1": "Enable Apps"
+ },
+ "es-en": {
+ "line1": "Hab. aplic."
+ },
+ "es-es": {
+ "line1": "Activar apl."
+ },
+ "es-mx": {
+ "line1": "Hab. aplic."
+ },
+ "fr-ca": {
+ "line1": "Activer app.",
+ "textBody": "Activer app."
+ },
+ "fr-fr": {
+ "line1": "Activer app."
+ },
+ "it-it": {
+ "line1": "Abilita app"
+ },
+ "nl-nl": {
+ "line1": "Apps inschak."
+ },
+ "pl-pl": {
+ "line1": "Włącz aplikacje"
+ },
+ "pt-br": {
+ "line1": "Ativar aplic."
+ },
+ "pt-pt": {
+ "line1": "Activar actualiz."
+ },
+ "ru-ru": {
+ "line1": "Вкл. прилож."
+ },
+ "sv-se": {
+ "line1": "Aktivera appar"
+ },
+ "tr-tr": {
+ "line1": "Uygulamaları aç"
+ },
+ "zh-cn": {
+ "line1": "启用应用程序"
+ },
+ "zh-tw": {
+ "line1": "啟用應用程式"
+ }
+ }
+ },
+ "SettingUpdateAuto": {
+ "languages": {
+ "de-de": {
+ "line1": "Update anford."
+ },
+ "en-au": {
+ "line1": "Request update"
+ },
+ "en-gb": {
+ "line1": "Request update"
+ },
+ "en-ie": {
+ "line1": "Request update"
+ },
+ "en-us": {
+ "line1": "Request Update",
+ "textBody": "Select `Update now` to receive app permissions for your SYNC-enabled mobile apps. This may enable additional functionality depending on the app and your settings. If your phone has a working data connection, an update should complete in less than 1 minute."
+ },
+ "es-en": {
+ "line1": "Solicit. actualiz.",
+ "textBody": "Solicit. actualiz."
+ },
+ "es-es": {
+ "line1": "Solicitar actual."
+ },
+ "es-mx": {
+ "line1": "Solicit. actualiz.",
+ "textBody": "Solicit. actualiz."
+ },
+ "fr-ca": {
+ "line1": "Demander MAJ",
+ "textBody": "Demander MAJ"
+ },
+ "fr-fr": {
+ "line1": "Demander màj"
+ },
+ "it-it": {
+ "line1": "Rich. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Upd. aanvragen"
+ },
+ "pl-pl": {
+ "line1": "Zażądaj aktual."
+ },
+ "pt-br": {
+ "line1": "Solicitar atualiz."
+ },
+ "pt-pt": {
+ "line1": "Solicit. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Запрос на обн."
+ },
+ "sv-se": {
+ "line1": "Begär uppdat."
+ },
+ "tr-tr": {
+ "line1": "Güncelleme iste"
+ },
+ "zh-cn": {
+ "line1": "请求更新"
+ },
+ "zh-tw": {
+ "line1": "請求更新"
+ }
+ }
+ },
+ "StatusNeeded": {
+ "languages": {
+ "de-de": {
+ "line1": "Update benötigt"
+ },
+ "en-au": {
+ "line1": "Update needed"
+ },
+ "en-gb": {
+ "line1": "Update needed",
+ "textBody": "Update needed"
+ },
+ "en-ie": {
+ "line1": "Update needed"
+ },
+ "en-us": {
+ "line1": "Update Needed",
+ "textBody": "Update Needed"
+ },
+ "es-en": {
+ "line1": "Actualiz. neces.",
+ "textBody": "Actualiz. neces."
+ },
+ "es-es": {
+ "line1": "Actu. necesaria"
+ },
+ "es-mx": {
+ "line1": "Actualiz. neces.",
+ "textBody": "Actualiz. neces."
+ },
+ "fr-ca": {
+ "line1": "Màj requise",
+ "textBody": "Màj requise"
+ },
+ "fr-fr": {
+ "line1": "Mise à jour requise"
+ },
+ "it-it": {
+ "line1": "Necess. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Update nodig"
+ },
+ "pl-pl": {
+ "line1": "Potrzeba aktual."
+ },
+ "pt-br": {
+ "line1": "Atualiz. necess."
+ },
+ "pt-pt": {
+ "line1": "Actual. necess."
+ },
+ "ru-ru": {
+ "line1": "Необх. обновл."
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs"
+ },
+ "tr-tr": {
+ "line1": "Güncellenmeli"
+ },
+ "zh-cn": {
+ "line1": "需要进行更新"
+ },
+ "zh-tw": {
+ "line1": "需更新"
+ }
+ }
+ },
+ "StatusPending": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktualisieren..."
+ },
+ "en-au": {
+ "line1": "Updating..."
+ },
+ "en-gb": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "en-ie": {
+ "line1": "Updating..."
+ },
+ "en-us": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "es-en": {
+ "line1": "Actualizando...",
+ "textBody": "Actualizando..."
+ },
+ "es-es": {
+ "line1": "Actualizando..."
+ },
+ "es-mx": {
+ "line1": "Actualizando...",
+ "textBody": "Actualizando..."
+ },
+ "fr-ca": {
+ "line1": "MAJ en cours...",
+ "textBody": "MAJ en cours..."
+ },
+ "fr-fr": {
+ "line1": "Màj en cours..."
+ },
+ "it-it": {
+ "line1": "Aggiornamento"
+ },
+ "nl-nl": {
+ "line1": "Updaten..."
+ },
+ "pl-pl": {
+ "line1": "Aktualizowanie"
+ },
+ "pt-br": {
+ "line1": "Atualizando..."
+ },
+ "pt-pt": {
+ "line1": "A actualizar..."
+ },
+ "ru-ru": {
+ "line1": "Обновление..."
+ },
+ "sv-se": {
+ "line1": "Uppdaterar..."
+ },
+ "tr-tr": {
+ "line1": "Güncelleniyor..."
+ },
+ "zh-cn": {
+ "line1": "正在更新......"
+ },
+ "zh-tw": {
+ "line1": "更新中..."
+ }
+ }
+ },
+ "StatusUpToDate": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktuelle Version"
+ },
+ "en-au": {
+ "line1": "Up-to-date"
+ },
+ "en-gb": {
+ "line1": "Up-to-date",
+ "textBody": "Up-to-date"
+ },
+ "en-ie": {
+ "line1": "Up-to-date"
+ },
+ "en-us": {
+ "line1": "Up-To-Date",
+ "textBody": "Up-To-Date"
+ },
+ "es-en": {
+ "line1": "Actualizado",
+ "textBody": "Actualizado"
+ },
+ "es-es": {
+ "line1": "Actualizada"
+ },
+ "es-mx": {
+ "line1": "Actualizado",
+ "textBody": "Actualizado"
+ },
+ "fr-ca": {
+ "line1": "Déjà à jour",
+ "textBody": "Déjà à jour"
+ },
+ "fr-fr": {
+ "line1": "Déjà à jour"
+ },
+ "it-it": {
+ "line1": "più recente"
+ },
+ "nl-nl": {
+ "line1": "Up-to-date"
+ },
+ "pl-pl": {
+ "line1": "Aktualne"
+ },
+ "pt-br": {
+ "line1": "Atualizado"
+ },
+ "pt-pt": {
+ "line1": "Actualizado"
+ },
+ "ru-ru": {
+ "line1": "Обновлено"
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs ej"
+ },
+ "tr-tr": {
+ "line1": "Güncel"
+ },
+ "zh-cn": {
+ "line1": "最新更新"
+ },
+ "zh-tw": {
+ "line1": "更新最新"
+ }
+ }
+ },
+ "VehicleInfo": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahrzeuginformationen: Kraftstoff-Füllstand, Kraftstoffverbrauch, Motordrehzahl, Kilometerzähler, FIN, Außentemperatur, Gangstellung, Reifenluftdruck.",
+ "label": "Fahrzeuginformationen"
+ },
+ "en-au": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-gb": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure."
+ },
+ "en-ie": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-us": {
+ "tts": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo",
+ "textBody": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a la siguiente información del vehículo: Nivel de combustible, Ahorro de combustible, RPM del motor, Cuentakilómetros, VIN, Temperatura aire exterior, Marcha engranada, Presión de neumáticos.",
+ "label": "Información del vehículo"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo",
+ "textBody": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus.",
+ "label": "Renseignements du véhicule",
+ "textBody": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Vitesse de moteur, Compteur kilométrique, NIV, Température extérieure, Position de vitesse, Pression des pneus.",
+ "label": "Renseignements du véhicule"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti informazioni del veicolo: Livello carburante, Consumi carburante, Numero giri motore, Contachilometri, VIN, Temperatura esterna, Posizione marcia, Pressione pneumatici.",
+ "label": "Informazioni sul veicolo"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende voertuiginformatie: Brandstofpeil, Brandstofverbruik, Motortoerental, Kilometerteller, VIN, Buitentemperatuur, Versnellingsstand, Bandenspanning.",
+ "label": "Voertuiginformatie"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji o pojeździe: Poziom paliwa, Zużycie paliwa, Obroty silnika, Licznik przebiegu, Numer VIN, Temperatura zewnętrzna, Aktualny bieg, Ciśnienie opon.",
+ "label": "Informacje o pojeździe"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes informações sobre o veículo: Nível de combustível, Economia de combustível, RPM do motor, Hodômetro, VIN, Temperatura externa, Posição das marchas, Pressão dos pneus.",
+ "label": "Informações sobre o veículo"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações do veículo: Nível de combustível, Poupança de combustível, RPM do motor, Conta-quilómetros, VIN, Temperatura exterior, Posição da mudança de velocidade, Pressão dos pneus.",
+ "label": "Informações do veículo"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим данным автомобиля: Уровень топлива, Економия топлива, Число оборотов двигателя, Одометр, Номер VIN, Температура за бортом, Положение передачи, Давление шин.",
+ "label": "Информация об автомобиле"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande fordonsinformation: Bränslenivå, Bränsleekonomi, Motorns varvtal, Vägmätare, VIN, Utetemperatur, Växelläge, Däcktryck.",
+ "label": "Fordonsinformation"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu araç bilgilerine erişebilir: Yakıt seviyesi, Yakıt ekonomisi, Motor devirleri, Kilometre sayacı, VIN, Dış sıcaklık, Vites konumu, Lastik basıncı.",
+ "label": "Araç bilgisi"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列车辆信息 : 燃油量, 燃油经济性, 发动机转速(RPM), 里程表, VIN, 车外温度, 档位, 胎压.",
+ "label": "车辆信息"
+ },
+ "zh-tw": {
+ "tts": "一個應用程式可存取以下車輛資訊 : 燃油存量, 燃油經濟性, 引擎轉速, 里程表, 車輛識別號碼, 車外溫度, 檔位, 胎壓.",
+ "label": "車輛資訊"
+ }
+ }
+ }
}
- }
},
- "Location": {
- "languages": {
- "de-de": {
- "tts": "Eine App hat Zugriff auf die GPS-Daten und die Geschwindigkeit des Fahrzeugs.",
- "label": "GPS und Geschwindigkeit"
- },
- "en-au": {
- "tts": "An app can access vehicle GPS and speed.",
- "label": "GPS and speed"
- },
- "en-gb": {
- "tts": "An app can access vehicle GPS and speed.",
- "label": "GPS and speed",
- "textBody": "An app can access vehicle GPS and speed."
- },
- "en-ie": {
- "tts": "An app can access vehicle GPS and speed.",
- "label": "GPS and speed"
- },
- "en-us": {
- "tts": "An app can access vehicle GPS and speed.",
- "label": "GPS and Speed",
- "textBody": "An app can access vehicle GPS and speed."
- },
- "es-en": {
- "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
- "label": "GPS y velocidad",
- "textBody": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
- },
- "es-es": {
- "tts": "Una aplicación puede acceder al GPS y la velocidad del vehículo.",
- "label": "GPS y velocidad"
- },
- "es-mx": {
- "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
- "label": "GPS y velocidad",
- "textBody": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
- },
- "fr-ca": {
- "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
- "label": "GPS et Vitesse",
- "textBody": "Une application peut accéder au GPS et à la vitesse du véhicule."
- },
- "fr-fr": {
- "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
- "label": "GPS et vitesse"
- },
- "it-it": {
- "tts": "Un'app può avere accesso a GPS e velocità del veicolo.",
- "label": "GPS e velocità"
- },
- "nl-nl": {
- "tts": "Een app heeft toegang tot gps en de snelheid van het voertuig.",
- "label": "Gps en snelheid"
- },
- "pl-pl": {
- "tts": "Aplikacja może uzyskać dostęp do modułu GPS i prędkości pojazdu.",
- "label": "GPS i prędkość"
- },
- "pt-br": {
- "tts": "Um aplicativo pode acessar o GPS e a velocidade do veículo.",
- "label": "GPS e velocidade"
- },
- "pt-pt": {
- "tts": "Uma aplicação consegue aceder ao GPS e à velocidade do veículo.",
- "label": "GPS e velocidade"
- },
- "ru-ru": {
- "tts": "Приложение имеет доступ к GPS и скорости автомобиля.",
- "label": "GPS и скорость"
- },
- "sv-se": {
- "tts": "Appen kan komma åt fordonets GPS och hastighetsmätare.",
- "label": "GPS och hastighet"
- },
- "tr-tr": {
- "tts": "Bu uygulama aracın GPS ve hız bilgilerine erişebilir.",
- "label": "GPS ve hız"
- },
- "zh-cn": {
- "tts": "移动应用程序可以访问车辆 GPS 和车速信息。",
- "label": "GPS 和车速"
- },
- "zh-tw": {
- "tts": "應用程式可存取車輛的GPS和速度。",
- "label": "GPS和車速"
- }
- }
- },
- "Notifications": {
- "languages": {
- "de-de": {
- "tts": "Läuft die App im Hintergrund, kann Sie Benachrichtigungen senden.",
- "label": "Push-Benachrichtigungen"
- },
- "en-au": {
- "tts": "An app can send notifications when running in the background.",
- "label": "Push notifications"
- },
- "en-gb": {
- "tts": "An app can send notifications when running in the background.",
- "label": "Push notifications",
- "textBody": "An app can send notifications when running in the background."
- },
- "en-ie": {
- "tts": "An app can send notifications when running in the background.",
- "label": "Push notifications"
- },
- "en-us": {
- "tts": "An app can send notifications when running in the background.",
- "label": "Push Notifications",
- "textBody": "An app can send notifications when running in the background."
- },
- "es-en": {
- "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
- "label": "Notificaciones tipo Push",
- "textBody": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
- },
- "es-es": {
- "tts": "Una aplicación puede enviar notificaciones cuando se está ejecutando en segundo plano.",
- "label": "Notificaciones push"
- },
- "es-mx": {
- "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
- "label": "Notificaciones tipo Push",
- "textBody": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
- },
- "fr-ca": {
- "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
- "label": "Notifications Instantanées",
- "textBody": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
- },
- "fr-fr": {
- "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
- "label": "Notifications push"
- },
- "it-it": {
- "tts": "Un'app può inviare notifiche se eseguita in background.",
- "label": "Notifiche push"
- },
- "nl-nl": {
- "tts": "Een app kan meldingen versturen als deze op de achtergrond actief is.",
- "label": "Push-meldingen"
- },
- "pl-pl": {
- "tts": "Aplikacja może wysyłać powiadomienia, działając w tle.",
- "label": "Powiadomienia Push"
- },
- "pt-br": {
- "tts": "Um aplicativo pode enviar notificações quando estiver sendo executado em segundo plano.",
- "label": "Notificações Push",
- "line1": "Notificações"
- },
- "pt-pt": {
- "tts": "Uma aplicação consegue enviar notificações quando está activa em segundo plano.",
- "label": "Notificações push"
- },
- "ru-ru": {
- "tts": "Если приложение работает в фоновом режиме, оно может отправлять оповещения.",
- "label": "Оповещения о пересылке"
- },
- "sv-se": {
- "tts": "Appen kan skicka meddelanden när den körs i bakgrunden.",
- "label": "Push-notiser"
- },
- "tr-tr": {
- "tts": "Bir uygulama arka planda çalışırken bildirim gönderebilir.",
- "label": "Anlık bildirimleri"
- },
- "zh-cn": {
- "tts": "移动应用程序在后台运行时可推送通知。",
- "label": "推送通知"
- },
- "zh-tw": {
- "tts": "車輛行進時,應用程式可在背景中傳送通知。",
- "label": "傳送通知"
- }
- }
- },
- "SettingAppPermissions": {
- "languages": {
- "en-us": {
- "textBody": "Change %AppName%’s functionality and use of data as described below. See App terms of service and privacy policies."
- },
- "es-mx": {
- "textBody": "Para cambiar la funcionalidad de %appName% y usar los datos como se describe más adelante. Consulte los términos de servicio y políticas de privacidad de la App."
- },
- "fr-ca": {
- "textBody": "Pour modifier la fonctionnalité de %appName% et l’usage des données comme décrit ci-dessous. Reportez-vous aux modalités de service et à la politique de confidentialité de l’application."
- }
- }
- },
- "SettingDisableUpdates": {
- "languages": {
- "de-de": {
- "line1": "Updates deakt."
- },
- "en-au": {
- "line1": "Disable updates"
- },
- "en-gb": {
- "line1": "Disable updates"
- },
- "en-ie": {
- "line1": "Disable updates"
- },
- "en-us": {
- "line1": "Disable Updates",
- "textBody": "Disable Updates"
- },
- "es-en": {
- "line1": "Deshab. actual.",
- "textBody": "Deshab. actual."
- },
- "es-es": {
- "line1": "Desact. actual."
- },
- "es-mx": {
- "line1": "Deshab. actual.",
- "textBody": "Deshab. actual."
- },
- "fr-ca": {
- "line1": "Désactiver MAJ",
- "textBody": "Désactiver MAJ"
- },
- "fr-fr": {
- "line1": "Désactiver màj"
- },
- "it-it": {
- "line1": "Disabilita agg."
- },
- "nl-nl": {
- "line1": "Upd. uitschak."
- },
- "pl-pl": {
- "line1": "Wyłącz aktual."
- },
- "pt-br": {
- "line1": "Desat. atualiz."
- },
- "pt-pt": {
- "line1": "Desact. actualiz."
- },
- "ru-ru": {
- "line1": "Откл. обновл."
- },
- "sv-se": {
- "line1": "Inaktivera uppd."
- },
- "tr-tr": {
- "line1": "Güncell. Kapat"
- },
- "zh-cn": {
- "line1": "禁用更新"
- },
- "zh-tw": {
- "line1": "停用更新"
- }
- }
- },
- "SettingEnableUpdates": {
- "languages": {
- "de-de": {
- "line1": "Apps aktivieren"
- },
- "en-au": {
- "line1": "Enable Apps"
- },
- "en-gb": {
- "line1": "Enable Apps"
- },
- "en-ie": {
- "line1": "Enable Apps"
- },
- "en-us": {
- "line1": "Enable Apps"
- },
- "es-en": {
- "line1": "Hab. aplic."
- },
- "es-es": {
- "line1": "Activar apl."
- },
- "es-mx": {
- "line1": "Hab. aplic."
- },
- "fr-ca": {
- "line1": "Activer app.",
- "textBody": "Activer app."
- },
- "fr-fr": {
- "line1": "Activer app."
- },
- "it-it": {
- "line1": "Abilita app"
- },
- "nl-nl": {
- "line1": "Apps inschak."
- },
- "pl-pl": {
- "line1": "Włącz aplikacje"
- },
- "pt-br": {
- "line1": "Ativar aplic."
- },
- "pt-pt": {
- "line1": "Activar actualiz."
- },
- "ru-ru": {
- "line1": "Вкл. прилож."
- },
- "sv-se": {
- "line1": "Aktivera appar"
- },
- "tr-tr": {
- "line1": "Uygulamaları aç"
- },
- "zh-cn": {
- "line1": "启用应用程序"
- },
- "zh-tw": {
- "line1": "啟用應用程式"
- }
- }
- },
- "SettingUpdateAuto": {
- "languages": {
- "de-de": {
- "line1": "Update anford."
- },
- "en-au": {
- "line1": "Request update"
- },
- "en-gb": {
- "line1": "Request update"
- },
- "en-ie": {
- "line1": "Request update"
- },
- "en-us": {
- "line1": "Request Update",
- "textBody": "Select `Update now` to receive app permissions for your SYNC-enabled mobile apps. This may enable additional functionality depending on the app and your settings. If your phone has a working data connection, an update should complete in less than 1 minute."
- },
- "es-en": {
- "line1": "Solicit. actualiz.",
- "textBody": "Solicit. actualiz."
- },
- "es-es": {
- "line1": "Solicitar actual."
- },
- "es-mx": {
- "line1": "Solicit. actualiz.",
- "textBody": "Solicit. actualiz."
- },
- "fr-ca": {
- "line1": "Demander MAJ",
- "textBody": "Demander MAJ"
- },
- "fr-fr": {
- "line1": "Demander màj"
- },
- "it-it": {
- "line1": "Rich. aggiorn."
- },
- "nl-nl": {
- "line1": "Upd. aanvragen"
- },
- "pl-pl": {
- "line1": "Zażądaj aktual."
- },
- "pt-br": {
- "line1": "Solicitar atualiz."
- },
- "pt-pt": {
- "line1": "Solicit. actualiz."
- },
- "ru-ru": {
- "line1": "Запрос на обн."
- },
- "sv-se": {
- "line1": "Begär uppdat."
- },
- "tr-tr": {
- "line1": "Güncelleme iste"
- },
- "zh-cn": {
- "line1": "请求更新"
- },
- "zh-tw": {
- "line1": "請求更新"
- }
- }
- },
- "StatusNeeded": {
- "languages": {
- "de-de": {
- "line1": "Update benötigt"
- },
- "en-au": {
- "line1": "Update needed"
- },
- "en-gb": {
- "line1": "Update needed",
- "textBody": "Update needed"
- },
- "en-ie": {
- "line1": "Update needed"
- },
- "en-us": {
- "line1": "Update Needed",
- "textBody": "Update Needed"
- },
- "es-en": {
- "line1": "Actualiz. neces.",
- "textBody": "Actualiz. neces."
- },
- "es-es": {
- "line1": "Actu. necesaria"
- },
- "es-mx": {
- "line1": "Actualiz. neces.",
- "textBody": "Actualiz. neces."
- },
- "fr-ca": {
- "line1": "Màj requise",
- "textBody": "Màj requise"
- },
- "fr-fr": {
- "line1": "Mise à jour requise"
- },
- "it-it": {
- "line1": "Necess. aggiorn."
- },
- "nl-nl": {
- "line1": "Update nodig"
- },
- "pl-pl": {
- "line1": "Potrzeba aktual."
- },
- "pt-br": {
- "line1": "Atualiz. necess."
- },
- "pt-pt": {
- "line1": "Actual. necess."
- },
- "ru-ru": {
- "line1": "Необх. обновл."
- },
- "sv-se": {
- "line1": "Uppdat. krävs"
- },
- "tr-tr": {
- "line1": "Güncellenmeli"
- },
- "zh-cn": {
- "line1": "需要进行更新"
- },
- "zh-tw": {
- "line1": "需更新"
- }
- }
- },
- "StatusPending": {
- "languages": {
- "de-de": {
- "line1": "Aktualisieren..."
- },
- "en-au": {
- "line1": "Updating..."
- },
- "en-gb": {
- "line1": "Updating...",
- "textBody": "Updating..."
- },
- "en-ie": {
- "line1": "Updating..."
- },
- "en-us": {
- "line1": "Updating...",
- "textBody": "Updating..."
- },
- "es-en": {
- "line1": "Actualizando...",
- "textBody": "Actualizando..."
- },
- "es-es": {
- "line1": "Actualizando..."
- },
- "es-mx": {
- "line1": "Actualizando...",
- "textBody": "Actualizando..."
- },
- "fr-ca": {
- "line1": "MAJ en cours...",
- "textBody": "MAJ en cours..."
- },
- "fr-fr": {
- "line1": "Màj en cours..."
- },
- "it-it": {
- "line1": "Aggiornamento"
- },
- "nl-nl": {
- "line1": "Updaten..."
- },
- "pl-pl": {
- "line1": "Aktualizowanie"
- },
- "pt-br": {
- "line1": "Atualizando..."
- },
- "pt-pt": {
- "line1": "A actualizar..."
- },
- "ru-ru": {
- "line1": "Обновление..."
- },
- "sv-se": {
- "line1": "Uppdaterar..."
- },
- "tr-tr": {
- "line1": "Güncelleniyor..."
- },
- "zh-cn": {
- "line1": "正在更新......"
- },
- "zh-tw": {
- "line1": "更新中..."
- }
- }
- },
- "StatusUpToDate": {
- "languages": {
- "de-de": {
- "line1": "Aktuelle Version"
- },
- "en-au": {
- "line1": "Up-to-date"
- },
- "en-gb": {
- "line1": "Up-to-date",
- "textBody": "Up-to-date"
- },
- "en-ie": {
- "line1": "Up-to-date"
- },
- "en-us": {
- "line1": "Up-To-Date",
- "textBody": "Up-To-Date"
- },
- "es-en": {
- "line1": "Actualizado",
- "textBody": "Actualizado"
- },
- "es-es": {
- "line1": "Actualizada"
- },
- "es-mx": {
- "line1": "Actualizado",
- "textBody": "Actualizado"
- },
- "fr-ca": {
- "line1": "Déjà à jour",
- "textBody": "Déjà à jour"
- },
- "fr-fr": {
- "line1": "Déjà à jour"
- },
- "it-it": {
- "line1": "più recente"
- },
- "nl-nl": {
- "line1": "Up-to-date"
- },
- "pl-pl": {
- "line1": "Aktualne"
- },
- "pt-br": {
- "line1": "Atualizado"
- },
- "pt-pt": {
- "line1": "Actualizado"
- },
- "ru-ru": {
- "line1": "Обновлено"
- },
- "sv-se": {
- "line1": "Uppdat. krävs ej"
- },
- "tr-tr": {
- "line1": "Güncel"
- },
- "zh-cn": {
- "line1": "最新更新"
- },
- "zh-tw": {
- "line1": "更新最新"
- }
- }
- },
- "VehicleInfo": {
- "languages": {
- "de-de": {
- "tts": "Eine App hat Zugriff auf die folgenden Fahrzeuginformationen: Kraftstoff-Füllstand, Kraftstoffverbrauch, Motordrehzahl, Kilometerzähler, FIN, Außentemperatur, Gangstellung, Reifenluftdruck.",
- "label": "Fahrzeuginformationen"
- },
- "en-au": {
- "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
- "label": "Vehicle information"
- },
- "en-gb": {
- "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure.",
- "label": "Vehicle information",
- "textBody": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure."
- },
- "en-ie": {
- "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
- "label": "Vehicle information"
- },
- "en-us": {
- "tts": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Odometer, VIN, External Temperature, Tire Pressure.",
- "label": "Vehicle Information",
- "textBody": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Odometer, VIN, External Temperature, Tire Pressure."
- },
- "es-en": {
- "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
- "label": "Información del vehículo",
- "textBody": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
- },
- "es-es": {
- "tts": "Una aplicación puede acceder a la siguiente información del vehículo: Nivel de combustible, Ahorro de combustible, RPM del motor, Cuentakilómetros, VIN, Temperatura aire exterior, Marcha engranada, Presión de neumáticos.",
- "label": "Información del vehículo"
- },
- "es-mx": {
- "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Presión de los neumáticos.",
- "label": "Información del Vehículo",
- "textBody": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Presión de los neumáticos."
- },
- "fr-ca": {
- "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Odomètre, NIV, Température extérieure, et Pression des pneus.",
- "label": "Renseignements du Véhicule",
- "textBody": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Odomètre, NIV, Température extérieure, et Pression des pneus."
- },
- "fr-fr": {
- "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Vitesse de moteur, Compteur kilométrique, NIV, Température extérieure, Position de vitesse, Pression des pneus.",
- "label": "Renseignements du véhicule"
- },
- "it-it": {
- "tts": "Un'app può avere accesso alle seguenti informazioni del veicolo: Livello carburante, Consumi carburante, Numero giri motore, Contachilometri, VIN, Temperatura esterna, Posizione marcia, Pressione pneumatici.",
- "label": "Informazioni sul veicolo"
- },
- "nl-nl": {
- "tts": "Een app heeft toegang tot de volgende voertuiginformatie: Brandstofpeil, Brandstofverbruik, Motortoerental, Kilometerteller, VIN, Buitentemperatuur, Versnellingsstand, Bandenspanning.",
- "label": "Voertuiginformatie"
- },
- "pl-pl": {
- "tts": "Aplikacja może uzyskać dostęp do następujących informacji o pojeździe: Poziom paliwa, Zużycie paliwa, Obroty silnika, Licznik przebiegu, Numer VIN, Temperatura zewnętrzna, Aktualny bieg, Ciśnienie opon.",
- "label": "Informacje o pojeździe"
- },
- "pt-br": {
- "tts": "Um aplicativo pode acessar as seguintes informações sobre o veículo: Nível de combustível, Economia de combustível, RPM do motor, Hodômetro, VIN, Temperatura externa, Posição das marchas, Pressão dos pneus.",
- "label": "Informações sobre o veículo",
- "line1": "Inform. Veículo"
- },
- "pt-pt": {
- "tts": "Uma aplicação consegue aceder às seguintes informações do veículo: Nível de combustível, Poupança de combustível, RPM do motor, Conta-quilómetros, VIN, Temperatura exterior, Posição da mudança de velocidade, Pressão dos pneus.",
- "label": "Informações do veículo"
- },
- "ru-ru": {
- "tts": "Приложение имеет доступ к следующим данным автомобиля: Уровень топлива, Економия топлива, Число оборотов двигателя, Одометр, Номер VIN, Температура за бортом, Положение передачи, Давление шин.",
- "label": "Информация об автомобиле"
- },
- "sv-se": {
- "tts": "Appen kan komma åt följande fordonsinformation: Bränslenivå, Bränsleekonomi, Motorns varvtal, Vägmätare, VIN, Utetemperatur, Växelläge, Däcktryck.",
- "label": "Fordonsinformation"
- },
- "tr-tr": {
- "tts": "Bir uygulama şu araç bilgilerine erişebilir: Yakıt seviyesi, Yakıt ekonomisi, Motor devirleri, Kilometre sayacı, VIN, Dış sıcaklık, Vites konumu, Lastik basıncı.",
- "label": "Araç bilgisi"
- },
- "zh-cn": {
- "tts": "移动应用程序可访问下列车辆信息 : 燃油量, 燃油经济性, 发动机转速(RPM), 里程表, VIN, 车外温度, 档位, 胎压.",
- "label": "车辆信息"
- },
- "zh-tw": {
- "tts": "一個應用程式可存取以下車輛資訊 : 燃油存量, 燃油經濟性, 引擎轉速, 里程表, 車輛識別號碼, 車外溫度, 檔位, 胎壓.",
- "label": "車輛資訊"
+ "app_policies": {
+ "default": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["Base-4"]
+ },
+ "device": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["DataConsent-2"]
+ },
+ "pre_DataConsent": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["BaseBeforeDataConsent"]
}
- }
}
- }
- },
- "app_policies": {
- "default": {
- "keep_context": false,
- "steal_focus": false,
- "priority": "NONE",
- "default_hmi": "NONE",
- "groups": [
- "Base-4"
- ]
- },
- "device": {
- "keep_context": false,
- "steal_focus": false,
- "priority": "NONE",
- "default_hmi": "NONE",
- "groups": [
- "DataConsent-2"
- ]
- },
- "pre_DataConsent": {
- "keep_context": false,
- "steal_focus": false,
- "priority": "NONE",
- "default_hmi": "NONE",
- "groups": [
- "BaseBeforeDataConsent"
- ]
- }
}
- }
}
+
diff --git a/src/appMain/signal_handlers.cc b/src/appMain/signal_handlers.cc
index 51757358e8..c695467ae2 100644
--- a/src/appMain/signal_handlers.cc
+++ b/src/appMain/signal_handlers.cc
@@ -35,14 +35,6 @@
#include "utils/logger.h"
namespace main_namespace {
-CREATE_LOGGERPTR_GLOBAL(logger_, "SmartDeviceLinkMainApp")
+CREATE_LOGGERPTR_GLOBAL(logger_, "SDLMain")
-void dummy_signal_handler(int32_t signal) {
-}
-
-void legacy_signal_handler(int32_t signal) {
- LOG4CXX_TRACE(logger_, "legacy_signal_handler get signal " << signal);
- LifeCycle::instance()->StopComponents();
-}
-
-} // namespace main_namespace
+} // namespace main_namespace
diff --git a/src/appMain/signal_handlers.h b/src/appMain/signal_handlers.h
index fc5015e6f6..f3adefb929 100644
--- a/src/appMain/signal_handlers.h
+++ b/src/appMain/signal_handlers.h
@@ -35,18 +35,6 @@
#include <stdint.h>
-namespace main_namespace {
-
-// This is dummy signal handler
-// which returns immediately
-// to unblock pause()
-void dummy_signal_handler(int32_t signal);
-
-// This is legacy signal handler
-// used in some tests
-// to stop components
-void legacy_signal_handler(int32_t signal);
-
-} // namespace main_namespace
+namespace main_namespace {} // namespace main_namespace
#endif // SRC_APPMAIN_SIGNAL_HANDLERS_H_
diff --git a/src/appMain/smartDeviceLink.ini b/src/appMain/smartDeviceLink.ini
index 7626b035e2..a9baf8c45a 100644
--- a/src/appMain/smartDeviceLink.ini
+++ b/src/appMain/smartDeviceLink.ini
@@ -1,47 +1,63 @@
- ; The INI-file consists of different chapters.
+; The INI-file consists of different chapters.
; Each chapter begins with the line containing
; the name in square brackets. Syntax:
; [chapter]
; The chapters consists of a set of items with a
-; assinged value. The syntax is:
+; assigned value. The syntax is:
; item=value
; All white spaces an second encounters of chapters
; or items will be ignored.
; Remarks start with semicolon or star as first character.
-; It is alowed for names of chapters and items to
+; It is allowed for names of chapters and items to
; contain semicolon and star. Possible syntax is:
; [ chapter ] ;Remark
; item = value ;Remark
[HMI]
-LaunchHMI = true
-LinkToWebHMI = HMI/index.html
+; Open the $LinkToWebHMI in chromium browser
+LaunchHMI = false
+; Link to index HMTL page
+; correct format is without any quotes and with double forward slash (solidus) separator
+LinkToWebHMI = HMI//index.html
+; WebSocket connection address and port
ServerAddress = 127.0.0.1
ServerPort = 8087
+; Socket ports for video and audio streaming
VideoStreamingPort = 5050
AudioStreamingPort = 5080
[MAIN]
-SDLVersion =
+; SDL source version
+; represents as a git commit hash value
+SDLVersion = {GIT_COMMIT}
+; All logging event could be dropped by setting $LogsEnabled to false
LogsEnabled = true
; Contains .json/.ini files
+; Default value is SDL working directory
AppConfigFolder =
-; Contains output files, e.g. .wav
+; Contains SDL configuration files - .json/.ini
+; Default value is SDL working directory
AppStorageFolder = storage
; Contains resourses, e.g. audio8bit.wav
+; Default value is SDL working directory
AppResourceFolder =
; Standard min stack size
; in Ubuntu : PTHREAD_STACK_MIN = 16384
; in QNX : PTHREAD_STACK_MIN = 256
-;The value of a variable ThreadStackSize used only if its realy needed, other way stack size will be PTHREAD_STACK_MIN
-;
+; The value of a $ThreadStackSize used where its really needed,
+; other way stack size will be PTHREAD_STACK_MIN
ThreadStackSize = 20480
+; Defines if HMI support attenuated mode (able to mix audio sources)
MixingAudioSupported = true
+; In case HMI doesn’t send some capabilities to SDL, the values from the file are used by SDL
HMICapabilities = hmi_capabilities.json
+; Maximum cmdId of VR command which may be registered on SDL
+; Bigger value used for system VR commands processing by SDL
MaxCmdID = 2000000000
-; Default request timeout in milliseconds
+; SDL respond timeout (in milliseconds) in case of HMI has not respond on a mobile request
DefaultTimeout = 10000
-
+; Available disk space in bytes for each application file handling
+; Default value is 100 MiB
AppDirectoryQuota = 104857600
; Allowed requests amount in HMI level NONE during time scale.
; If value is 0 check will be skipped
@@ -53,12 +69,23 @@ AppTimeScaleMaxRequests = 1000
AppRequestsTimeScale = 10
; Allowed pending requests amount. If value is 0 check will be skipped
PendingRequestsAmount = 5000
-HeartBeatTimeout = 7
+PendingRequestsAmount = 0
+; Heart beat timeout used for protocol v3.
+; Timeout must be specified in milliseconds. If timeout is 0 heart beat will be disabled.
+HeartBeatTimeout = 7000
+; The list of diagnostic modes supported on a vehicle.
+; Only the stated values are allowed by SDL in terms of DiagnosticMessage RPC, others are rejected
SupportedDiagModes = 0x01, 0x02, 0x03, 0x05, 0x06, 0x07, 0x09, 0x0A, 0x18, 0x19, 0x22, 0x3E
+; The path to the system file directory for inter-operation between SDL and System (e.g. IVSU files and others).
+; If parameter is empty, SDL uses /tmp/fs/mp/images/ivsu_cache by default
SystemFilesPath = /tmp/fs/mp/images/ivsu_cache
+; To restore the last transport state (name, applications or channels) on SDL on a new device connection and on disconnect
UseLastState = true
+; Port to obtain the performance information about messages processing
TimeTestingPort = 8090
+; Limitation for a number of ReadDID requests (the 1st value) per (the 2nd value) seconds
ReadDIDRequest = 5, 1
+; Limitation for a number of GetVehicleData requests (the 1st value) per (the 2nd value) seconds
GetVehicleDataRequest = 5, 1
[MEDIA MANAGER]
@@ -71,35 +98,34 @@ AudioStreamConsumer = socket
;AudioStreamConsumer = file
;VideoStreamConsumer = pipe
;AudioStreamConsumer = pipe
-;Temp solution: if you change NamedPipePath also change path to pipe in src/components/qt_hmi/qml_model_qtXX/views/SDLNavi.qml
-;Named pipe path will be constructed using AppStorageFolder + name
+; Temp solution: if you change NamedPipePath also change path to pipe in src/components/qt_hmi/qml_model_qtXX/views/SDLNavi.qml
+; Named pipe path will be constructed using AppStorageFolder + name
NamedVideoPipePath = video_stream_pipe
NamedAudioPipePath = audio_stream_pipe
-;File path will be constructed using AppStorageFolder + name
+; File path will be constructed using AppStorageFolder + name
VideoStreamFile = video_stream_file
AudioStreamFile = audio_stream_file
; Recording file source (used for audio pass thru emulation only)
RecordingFileSource = audio.8bit.wav
; Recording file for audio pass thru
RecordingFileName = audio.wav
-; The timeout in seconds for mobile to stop streaming or end up sessions.
-StopStreamingTimeout = 1
-; The timeout in miliseconds to suspend audio data streaming if no data received from mobile
+; The timeout in milliseconds for mobile to stop streaming or end up sessions.
+StopStreamingTimeout = 1000
+; The timeout in milliseconds to suspend audio data streaming if no data received from mobile
AudioDataStoppedTimeout = 1000
-; The timeout in miliseconds to suspend video data streaming if no data received from mobile
+; The timeout in milliseconds to suspend video data streaming if no data received from mobile
VideoDataStoppedTimeout = 1000
-; HelpPromt and TimeOutPrompt is a vector of strings separated by comma
[GLOBAL PROPERTIES]
-
-; Delimiter, which will be appended to each TTS chunck, e.g. helpPrompt/timeoutPrompt
+; HelpPromt and TimeOutPrompt is a vector of strings separated by comma
+; Delimiter, which will be appended to each TTS chunk, e.g. helpPrompt/timeoutPrompt
TTSDelimiter = ,
; Default prompt items, separated by comma
HelpPromt = Please speak one of the following commands,Please say a command
; Default prompt items, separated by comma
TimeOutPromt = Please speak one of the following commands,Please say a command
HelpTitle = Available Vr Commands List
-; In case mobile app didn't send global properties default global properties will be sent after this timeout
+; In case mobile app didn't send global properties default global properties will be sent after this timeout in seconds
; max value TTSGlobalPropertiesTimeout 64K
TTSGlobalPropertiesTimeout = 20
@@ -112,6 +138,7 @@ DeleteFileRequest = 5
ListFilesRequest = 5
[VR COMMANDS]
+; TODO(EZamakhov): delete with APPLINK-15220
HelpCommand = Help
[AppInfo]
@@ -129,17 +156,18 @@ SSLMode = CLIENT
;CipherList = AES256-GCM-SHA384
CipherList = ALL
; Verify Mobile app certificate (could be used in both SSLMode Server and Client)
-VerifyPeer = false
-; If VerifyPeer is enable - terminate handshake if mobile app did not return a certificate
-FialOnNoCert = false
-; If VerifyPeer is enable - do not ask for a mobile app certificate again in case of a renegotiation
-VerifyClientOnce = false
-; Force protected services (could be id's from 0x01 to 0xFF)
+VerifyPeer = true
+; Preloaded CA certificates directory
+CACertificatePath = .
+; Services which can not be started unprotected (could be id's from 0x01 to 0xFF)
;ForceProtectedService = 0x0A, 0x0B
ForceProtectedService = Non
-; Force unprotected services
+; Services which can not be started protected or delayed protected
;ForceUnprotectedService = 0x07
ForceUnprotectedService = Non
+; The PTU will be triggered in case expiration date of certificate
+; then certain hours amount
+UpdateBeforeHours = 24
[Policy]
EnablePolicy = true
@@ -151,18 +179,8 @@ AttemptsToOpenPolicyDB = 5
OpenAttemptTimeoutMs = 500
[TransportManager]
+; Listening port form incoming TCP mobile connection
TCPAdapterPort = 12345
-MMEDatabase = /dev/qdb/mediaservice_db
-EventMQ = /dev/mqueue/ToSDLCoreUSBAdapter
-AckMQ = /dev/mqueue/FromSDLCoreUSBAdapter
-
-[IAP]
-LegacyProtocol = com.ford.sync.prot[0-29]
-HubProtocol = com.smartdevicelink.prot0
-PoolProtocol = com.smartdevicelink.prot[1-29]
-IAPSystemConfig = /fs/mp/etc/mm/ipod.cfg
-IAP2SystemConfig = /fs/mp/etc/mm/iap2.cfg
-IAP2HubConnectAttempts = 3
[ProtocolHandler]
; Packet with payload bigger than next value will be marked as a malformed
@@ -183,11 +201,15 @@ MalformedMessageFiltering = true
; #MalformedFrequencyCount to Zero
MalformedFrequencyCount = 10
MalformedFrequencyTime = 1000
+; Timeout for waiting CONSECUTIVE frames of multiframe
+ExpectedConsecutiveFramesTimeout = 10000
[ApplicationManager]
-ApplicationListUpdateTimeout = 2
-; Max allowed threads for handling mobile requests. Currently max allowed is 2
+; Application list update timeout ms
+ApplicationListUpdateTimeout = 2000
+; Max allowed threads for handling mobile requests. Default value is 2
ThreadPoolSize = 1
+; The max size of hash which is used by OnHashUpdated
HashStringSize = 32
[SDL4]
@@ -201,16 +223,18 @@ AppIconsFolderMaxSize = 104857600
AppIconsAmountToRemove = 1
[Resumption]
-
-# Timeout in seconds for resumption Application HMILevel
-# and resolving conflicts in case if multiple applications initiate resumption
-ApplicationResumingTimeout = 3
-
-# Timeout in seconds for pereodical saving resumption persisten data
-AppSavePersistentDataTimeout = 10 #seconds
-
-# Timeout in seconds to store hmi_level for media app before ign_off
+; Timeout in milliseconds for resumption Application HMILevel
+; and resolving conflicts in case if multiple applications initiate resumption
+ApplicationResumingTimeout = 3000
+; Timeout in milliseconds for periodical saving resumption persistent data
+AppSavePersistentDataTimeout = 10000
+; Timeout in seconds to store hmi_level for media app before ign_off
ResumptionDelayBeforeIgn = 30;
-
-# Timeout in seconds to restore hmi_level for media app after sdl run
+; Timeout in seconds to restore hmi_level for media app after sdl run
ResumptionDelayAfterIgn = 30;
+; Resumption ctrl uses JSON if UseDBForResumption=false for store data otherwise uses DB
+UseDBForResumption = false
+; Number of attempts to open resumption DB
+AttemptsToOpenResumptionDB = 5
+; Timeout between attempts during opening DB in milliseconds
+OpenAttemptTimeoutMsResumptionDB = 500
diff --git a/src/components/CMakeLists.txt b/src/components/CMakeLists.txt
index b6b61d6bd2..d31141b36c 100644
--- a/src/components/CMakeLists.txt
+++ b/src/components/CMakeLists.txt
@@ -80,8 +80,8 @@ add_subdirectory(./config_profile)
# --- AudioManager
add_subdirectory(./media_manager)
-if (TIME_TESTER)
- add_subdirectory(./time_tester)
+if (TELEMETRY_MONITOR)
+ add_subdirectory(./telemetry_monitor)
endif()
diff --git a/src/components/HMI/app/controller/PhoneController.js b/src/components/HMI/app/controller/PhoneController.js
index dd722df80d..c29cae064d 100644
--- a/src/components/HMI/app/controller/PhoneController.js
+++ b/src/components/HMI/app/controller/PhoneController.js
@@ -33,24 +33,50 @@
SDL.PhoneController = Em.Object.create( {
- /** Model binding */
+ /**
+ * Model binding
+ */
modelBinding: "SDL.PhoneModel",
- /** Dialpad delete key press handeler */
+ /**
+ * Dialpad delete key press handeler
+ */
onDelete: function() {
this.model.deleteDialpadNumber();
},
- /** Dial call handeler */
+ /**
+ * Dial call handeler
+ */
onEndCall: function() {
+ FFW.BasicCommunication.OnPhoneCall(false);
this.model.endCall();
},
- /** Dial call handeler */
+ /**
+ * Dial call handeler
+ */
onDialCall: function() {
+ FFW.BasicCommunication.OnPhoneCall(true);
this.model.dialCall();
+ },
+
+ /**
+ * Dialpad key press handler
+ */
+ keyPress: function(element) {
+ this.model.setDialpadNumber(element.text)
+ },
+
+ /**
+ *
+ */
+ incomingCall: function(request) {
+
+ this.model.setDialpadNumber(request.params.number);
+ this.onDialCall();
}
}); \ No newline at end of file
diff --git a/src/components/HMI/app/controller/sdl/RPCController.js b/src/components/HMI/app/controller/sdl/RPCController.js
index 27dd2ec087..44cbd6978e 100644
--- a/src/components/HMI/app/controller/sdl/RPCController.js
+++ b/src/components/HMI/app/controller/sdl/RPCController.js
@@ -114,6 +114,71 @@ SDL.RPCController = Em.Object
},
/**
+ * Validate method for request DialNumber
+ *
+ * @param {Object}
+ * params
+ */
+ DialNumber: function(params) {
+
+ if (params == null) {
+
+ this.resultStruct = {
+ "resultCode": SDL.SDLModel.resultCode["INVALID_DATA"],
+ "resultMessage": "Parameter 'params' does not exists!"
+ };
+
+ return this.resultStruct;
+ }
+
+ if (params.number == null) {
+
+ this.resultStruct = {
+ "resultCode": SDL.SDLModel.resultCode["INVALID_DATA"],
+ "resultMessage": "Parameter 'number' does not exists!"
+ };
+
+ return this.resultStruct;
+ }
+
+ if (typeof params.number != 'string') {
+
+ this.resultStruct = {
+ "resultCode": SDL.SDLModel.resultCode["INVALID_DATA"],
+ "resultMessage": "Wrong type of parameter 'number'!"
+ };
+
+ return this.resultStruct;
+ }
+
+ if (params.appID == null) {
+
+ this.resultStruct = {
+ "resultCode": SDL.SDLModel.resultCode["INVALID_DATA"],
+ "resultMessage": "Parameter 'appID' does not exists!"
+ };
+
+ return this.resultStruct;
+ }
+
+ if (typeof params.appID != 'number') {
+
+ this.resultStruct = {
+ "resultCode": SDL.SDLModel.resultCode["INVALID_DATA"],
+ "resultMessage": "Wrong type of parameter 'appID'!"
+ };
+
+ return this.resultStruct;
+ }
+
+ this.resultStruct = {
+ "resultCode": SDL.SDLModel.resultCode["SUCCESS"]
+ };
+
+ return this.resultStruct;
+ },
+
+ /**
* Validate method for request UpdateDeviceList
*
* @param {Object}
diff --git a/src/components/HMI/app/view/phone/dialpadView.js b/src/components/HMI/app/view/phone/dialpadView.js
index 0290750d0a..06b535bda4 100644
--- a/src/components/HMI/app/view/phone/dialpadView.js
+++ b/src/components/HMI/app/view/phone/dialpadView.js
@@ -79,7 +79,11 @@ SDL.DialpadPhoneView = Em.ContainerView.create( {
classNames: 'left',
- text: '1'
+ text: '1',
+
+ action: "keyPress",
+
+ target: "SDL.PhoneController"
} ),
key2: SDL.Button.extend( {
@@ -87,7 +91,11 @@ SDL.DialpadPhoneView = Em.ContainerView.create( {
classNames: 'center',
- text: '2'
+ text: '2',
+
+ action: "keyPress",
+
+ target: "SDL.PhoneController"
} ),
key3: SDL.Button.extend( {
@@ -95,8 +103,11 @@ SDL.DialpadPhoneView = Em.ContainerView.create( {
classNames: 'right',
- text: '3'
+ text: '3',
+
+ action: "keyPress",
+ target: "SDL.PhoneController"
} ),
key4: SDL.Button.extend( {
@@ -104,7 +115,11 @@ SDL.DialpadPhoneView = Em.ContainerView.create( {
classNames: 'left',
- text: '4'
+ text: '4',
+
+ action: "keyPress",
+
+ target: "SDL.PhoneController"
} ),
key5: SDL.Button.extend( {
@@ -112,7 +127,11 @@ SDL.DialpadPhoneView = Em.ContainerView.create( {
classNames: 'center',
- text: '5'
+ text: '5',
+
+ action: "keyPress",
+
+ target: "SDL.PhoneController"
} ),
key6: SDL.Button.extend( {
@@ -120,7 +139,11 @@ SDL.DialpadPhoneView = Em.ContainerView.create( {
classNames: 'right',
- text: '6'
+ text: '6',
+
+ action: "keyPress",
+
+ target: "SDL.PhoneController"
} ),
key7: SDL.Button.extend( {
@@ -128,7 +151,11 @@ SDL.DialpadPhoneView = Em.ContainerView.create( {
classNames: 'left',
- text: '7'
+ text: '7',
+
+ action: "keyPress",
+
+ target: "SDL.PhoneController"
} ),
key8: SDL.Button.extend( {
@@ -136,7 +163,11 @@ SDL.DialpadPhoneView = Em.ContainerView.create( {
classNames: 'center',
- text: '8'
+ text: '8',
+
+ action: "keyPress",
+
+ target: "SDL.PhoneController"
} ),
key9: SDL.Button.extend( {
@@ -144,7 +175,11 @@ SDL.DialpadPhoneView = Em.ContainerView.create( {
classNames: 'right',
- text: '9'
+ text: '9',
+
+ action: "keyPress",
+
+ target: "SDL.PhoneController"
} ),
key0: SDL.Button.extend( {
@@ -152,7 +187,11 @@ SDL.DialpadPhoneView = Em.ContainerView.create( {
classNames: 'center',
- text: '0'
+ text: '0',
+
+ action: "keyPress",
+
+ target: "SDL.PhoneController"
} ),
keyStar: SDL.Button.extend( {
@@ -160,7 +199,11 @@ SDL.DialpadPhoneView = Em.ContainerView.create( {
classNames: 'left',
- text: '*'
+ text: '*',
+
+ action: "keyPress",
+
+ target: "SDL.PhoneController"
} ),
keyDiez: SDL.Button.extend( {
@@ -168,7 +211,11 @@ SDL.DialpadPhoneView = Em.ContainerView.create( {
classNames: 'right',
- text: '#'
+ text: '#',
+
+ action: "keyPress",
+
+ target: "SDL.PhoneController"
} )
} ),
diff --git a/src/components/HMI/ffw/BasicCommunicationRPC.js b/src/components/HMI/ffw/BasicCommunicationRPC.js
index ed33daef17..6ef3fc60fc 100644
--- a/src/components/HMI/ffw/BasicCommunicationRPC.js
+++ b/src/components/HMI/ffw/BasicCommunicationRPC.js
@@ -485,6 +485,32 @@ FFW.BasicCommunication = FFW.RPCObserver
request.id,
request.method);
}
+ if (request.method == "BasicCommunication.DialNumber") {
+
+ SDL.PopUp.create().appendTo('body').popupActivate(
+ "Would you like to dial " + request.params.number + " ?",
+ function (result) {
+ if (result) {
+
+ FFW.BasicCommunication.sendBCResult(SDL.SDLModel.resultCode["SUCCESS"],
+ request.id,
+ request.method);
+
+ SDL.SDLModel.onDeactivateApp('call', request.params.appID);
+ SDL.States.goToStates('phone.dialpad');
+ SDL.PhoneController.incomingCall(request);
+ } else {
+
+
+ FFW.BasicCommunication.sendError(SDL.SDLModel.resultCode["REJECTED"],
+ request.id,
+ request.method,
+ "No paired device!"
+ );
+ }
+ },
+ false);
+ }
if (request.method == "BasicCommunication.ActivateApp") {
if (!request.params.level || request.params.level == "FULL") {
diff --git a/src/components/application_manager/CMakeLists.txt b/src/components/application_manager/CMakeLists.txt
index e8db4d46c8..d44cf6c69e 100644
--- a/src/components/application_manager/CMakeLists.txt
+++ b/src/components/application_manager/CMakeLists.txt
@@ -33,9 +33,9 @@ set (AM_SOURCE_DIR ${COMPONENTS_DIR}/application_manager)
set (AM_TEST_DIR ${AM_SOURCE_DIR}/test)
set (AM_MOCK_DIR ${AM_TEST_DIR}/mock)
-
include_directories (
include/
+ ${COMPONENTS_DIR}
${COMPONENTS_DIR}/utils/include/
${COMPONENTS_DIR}/formatters/include/
${COMPONENTS_DIR}/protocol_handler/include/
@@ -49,21 +49,36 @@ include_directories (
${COMPONENTS_DIR}/rpc_base/include/
${COMPONENTS_DIR}/interfaces
${CMAKE_BINARY_DIR}/src/components/
- ${COMPONENTS_DIR}/include/
- ${COMPONENTS_DIR}/policy/src/policy/include/
- ${COMPONENTS_DIR}/policy/src/policy/usage_statistics/include/
+ ${COMPONENTS_DIR}/policy/include/
${JSONCPP_INCLUDE_DIRECTORY}
${ENCRYPTION_INCLUDE_DIRECTORY}
${MESSAGE_BROKER_INCLUDE_DIRECTORY}
${LOG4CXX_INCLUDE_DIRECTORY}
)
+if (${CMAKE_SYSTEM_NAME} MATCHES "Linux")
+ include_directories(
+ ${COMPONENTS_DIR}/utils/include/utils/sqlite_wrapper/
+ )
+endif ()
+
+if (${CMAKE_SYSTEM_NAME} MATCHES "QNX")
+ include_directories(
+ ${COMPONENTS_DIR}/utils/include/utils/qdb_wrapper/
+ )
+endif()
+
file (GLOB SOURCES
${AM_SOURCE_DIR}/src/*
)
+set (MESSAGE_HELPER_SOURCES
+ ${AM_SOURCE_DIR}/src/message_helper/message_helper.cc
+)
+
set (POLICIES_MANAGER
${AM_SOURCE_DIR}/src/policies/policy_handler.cc
+${AM_SOURCE_DIR}/src/usage_statistics.cc
${AM_SOURCE_DIR}/src/policies/policy_event_observer.cc
${AM_SOURCE_DIR}/src/policies/delegates/app_permission_delegate.cc
${AM_SOURCE_DIR}/src/policies/delegates/statistics_delegate.cc
@@ -72,11 +87,14 @@ ${AM_SOURCE_DIR}/src/policies/delegates/statistics_delegate.cc
include_directories(
${COMPONENTS_DIR}/policy/src/policy/policy_table/table_struct
)
-
file (GLOB EVENT_ENGINE
${AM_SOURCE_DIR}/src/event_engine/*
)
+file (GLOB RESUMPTION
+ ${AM_SOURCE_DIR}/src/resumption/*
+)
+
file (GLOB MOBILE_COMMANDS_SOURCES
${AM_SOURCE_DIR}/src/commands/*
${AM_SOURCE_DIR}/src/commands/mobile/*
@@ -121,8 +139,8 @@ file (GLOB MOBILE_COMMANDS_SOURCES
${AM_SOURCE_DIR}/src/commands/hmi/on_sdl_persistence_complete_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_exit_all_applications_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_exit_application_notification.cc
+ ${AM_SOURCE_DIR}/src/commands/hmi/on_navi_way_point_change_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_start_device_discovery.cc
- ${AM_SOURCE_DIR}/src/commands/hmi/on_emergency_event_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/close_popup_request.cc
${AM_SOURCE_DIR}/src/commands/hmi/close_popup_response.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_app_activated_notification.cc
@@ -220,6 +238,10 @@ file (GLOB MOBILE_COMMANDS_SOURCES
${AM_SOURCE_DIR}/src/commands/hmi/navi_show_constant_tbt_response.cc
${AM_SOURCE_DIR}/src/commands/hmi/navi_send_location_request.cc
${AM_SOURCE_DIR}/src/commands/hmi/navi_send_location_response.cc
+ ${AM_SOURCE_DIR}/src/commands/hmi/navi_subscribe_way_points_request.cc
+ ${AM_SOURCE_DIR}/src/commands/hmi/navi_subscribe_way_points_response.cc
+ ${AM_SOURCE_DIR}/src/commands/hmi/navi_unsubscribe_way_points_request.cc
+ ${AM_SOURCE_DIR}/src/commands/hmi/navi_unsubscribe_way_points_response.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_ready_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_system_context_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_device_chosen_notification.cc
@@ -232,7 +254,6 @@ file (GLOB MOBILE_COMMANDS_SOURCES
${AM_SOURCE_DIR}/src/commands/hmi/on_ignition_cycle_over_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_system_info_changed_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_file_removed_notification.cc
- ${AM_SOURCE_DIR}/src/commands/hmi/on_play_tone_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_tts_started_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_tts_stopped_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_vr_started_notification.cc
@@ -259,6 +280,8 @@ file (GLOB MOBILE_COMMANDS_SOURCES
${AM_SOURCE_DIR}/src/commands/hmi/navi_audio_start_stream_response.cc
${AM_SOURCE_DIR}/src/commands/hmi/navi_audio_stop_stream_request.cc
${AM_SOURCE_DIR}/src/commands/hmi/navi_audio_stop_stream_response.cc
+ ${AM_SOURCE_DIR}/src/commands/hmi/navi_get_way_points_request.cc
+ ${AM_SOURCE_DIR}/src/commands/hmi/navi_get_way_points_response.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_system_request_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_put_file_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_resume_audio_source_notification.cc
@@ -278,9 +301,9 @@ file (GLOB MOBILE_COMMANDS_SOURCES
${AM_SOURCE_DIR}/src/commands/hmi/get_urls_response.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_device_state_changed_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/on_tts_reset_timeout_notification.cc
- ${AM_SOURCE_DIR}/src/commands/hmi/on_phone_call_notification.cc
${AM_SOURCE_DIR}/src/commands/hmi/dial_number_request.cc
${AM_SOURCE_DIR}/src/commands/hmi/dial_number_response.cc
+ ${AM_SOURCE_DIR}/src/commands/hmi/on_event_changed_notification.cc
)
set (HMI_COMMANDS_SOURCES_JSON
@@ -333,8 +356,13 @@ SET (LIBRARIES
UsageStatistics
dl
formatters
+ dbms
)
+if (CMAKE_SYSTEM_NAME STREQUAL "Linux")
+ list(APPEND LIBRARIES sqlite3)
+endif ()
+
IF(${CMAKE_SYSTEM_NAME} MATCHES "QNX")
list(REMOVE_ITEM LIBRARIES dl)
endif()
@@ -342,16 +370,19 @@ endif()
add_library("AMEventEngine" ${EVENT_ENGINE})
target_link_libraries("AMEventEngine" ${LIBRARIES})
+
add_library("AMPolicyLibrary" ${POLICIES_MANAGER} )
target_link_libraries("AMPolicyLibrary" ${LIBRARIES} AMEventEngine)
add_library("AMHMICommandsLibrary" ${HMI_COMMANDS_SOURCES})
target_link_libraries("AMHMICommandsLibrary" ${LIBRARIES} AMEventEngine)
+add_library("MessageHelper" ${MESSAGE_HELPER_SOURCES})
+
add_library("AMMobileCommandsLibrary" ${MOBILE_COMMANDS_SOURCES} )
target_link_libraries("AMMobileCommandsLibrary" ${LIBRARIES} AMEventEngine)
-add_library("ApplicationManager" ${SOURCES})
+add_library("ApplicationManager" ${SOURCES} ${RESUMPTION})
target_link_libraries("ApplicationManager" ${LIBRARIES} AMHMICommandsLibrary
AMMobileCommandsLibrary
AMEventEngine
@@ -363,4 +394,5 @@ endif()
if(BUILD_TESTS)
add_subdirectory(test)
+ add_subdirectory(test/message_helper)
endif()
diff --git a/src/components/application_manager/include/application_manager/application.h b/src/components/application_manager/include/application_manager/application.h
index 1197bbb813..612db6be03 100644
--- a/src/components/application_manager/include/application_manager/application.h
+++ b/src/components/application_manager/include/application_manager/application.h
@@ -43,6 +43,7 @@
#include "connection_handler/device.h"
#include "application_manager/message.h"
#include "application_manager/hmi_state.h"
+#include "application_manager/application_state.h"
#include "protocol_handler/protocol_handler.h"
namespace NsSmartDeviceLink {
@@ -57,6 +58,9 @@ namespace application_manager {
namespace mobile_api = mobile_apis;
namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+
+namespace custom_str = utils::custom_string;
+
typedef int32_t ErrorCode;
class UsageStatistics;
@@ -70,33 +74,28 @@ enum APIVersion {
kAPIV4 = 4
};
-enum TLimitSource {
- POLICY_TABLE = 0,
- CONFIG_FILE
-};
-
+enum TLimitSource { POLICY_TABLE = 0, CONFIG_FILE };
struct Version {
APIVersion min_supported_api_version;
APIVersion max_supported_api_version;
Version()
- : min_supported_api_version(APIVersion::kUnknownAPI),
- max_supported_api_version(APIVersion::kUnknownAPI) {
- }
+ : min_supported_api_version(APIVersion::kUnknownAPI)
+ , max_supported_api_version(APIVersion::kUnknownAPI) {}
};
struct AppFile {
- // need to use in std::map;
- AppFile() {
- }
- AppFile(const std::string& name, bool persistent, bool download_complete,
+ // need to use in std::map;
+ AppFile() {}
+ AppFile(const std::string& name,
+ bool persistent,
+ bool download_complete,
mobile_apis::FileType::eType type)
- : file_name(name),
- is_persistent(persistent),
- is_download_complete(download_complete),
- file_type(type){
- }
+ : file_name(name)
+ , is_persistent(persistent)
+ , is_download_complete(download_complete)
+ , file_type(type) {}
std::string file_name;
bool is_persistent;
bool is_download_complete;
@@ -104,26 +103,26 @@ struct AppFile {
};
typedef std::map<std::string, AppFile> AppFilesMap;
class InitialApplicationData {
- public:
- virtual ~InitialApplicationData() {
- }
-
- virtual const smart_objects::SmartObject* app_types() const = 0;
- virtual const smart_objects::SmartObject* vr_synonyms() const = 0;
- virtual std::string mobile_app_id() const = 0;
- virtual const smart_objects::SmartObject* tts_name() const = 0;
- virtual const smart_objects::SmartObject* ngn_media_screen_name() const = 0;
- virtual const mobile_api::Language::eType& language() const = 0;
- virtual const mobile_api::Language::eType& ui_language() const = 0;
- virtual void set_app_types(const smart_objects::SmartObject& app_types) = 0;
- virtual void set_vr_synonyms(
+ public:
+ virtual ~InitialApplicationData() {}
+
+ virtual const smart_objects::SmartObject* app_types() const = 0;
+ virtual const smart_objects::SmartObject* vr_synonyms() const = 0;
+ virtual const std::string& mac_address() const = 0;
+ virtual std::string policy_app_id() const = 0;
+ virtual const smart_objects::SmartObject* tts_name() const = 0;
+ virtual const smart_objects::SmartObject* ngn_media_screen_name() const = 0;
+ virtual const mobile_api::Language::eType& language() const = 0;
+ virtual const mobile_api::Language::eType& ui_language() const = 0;
+ virtual void set_app_types(const smart_objects::SmartObject& app_types) = 0;
+ virtual void set_vr_synonyms(
const smart_objects::SmartObject& vr_synonyms) = 0;
- virtual void set_mobile_app_id(const std::string& mobile_app_id) = 0;
- virtual void set_tts_name(const smart_objects::SmartObject& tts_name) = 0;
- virtual void set_ngn_media_screen_name(
+ virtual void set_mobile_app_id(const std::string& policy_app_id) = 0;
+ virtual void set_tts_name(const smart_objects::SmartObject& tts_name) = 0;
+ virtual void set_ngn_media_screen_name(
const smart_objects::SmartObject& ngn_name) = 0;
- virtual void set_language(const mobile_api::Language::eType& language) = 0;
- virtual void set_ui_language(
+ virtual void set_language(const mobile_api::Language::eType& language) = 0;
+ virtual void set_ui_language(
const mobile_api::Language::eType& ui_language) = 0;
};
@@ -161,554 +160,626 @@ typedef std::map<uint32_t, PerformChoice> PerformChoiceSetMap;
*/
typedef std::set<uint32_t> SoftButtonID;
+/**
+ * @brief Defines set of vehicle info types
+ */
+typedef std::set<uint32_t> VehicleInfoSubscriptions;
+
+/**
+ * @brief Defines set of buttons subscription
+ */
+typedef std::set<mobile_apis::ButtonName::eType> ButtonSubscriptions;
+
class DynamicApplicationData {
- public:
- virtual ~DynamicApplicationData() {
- }
- virtual const smart_objects::SmartObject* help_prompt() const = 0;
- virtual const smart_objects::SmartObject* timeout_prompt() const = 0;
- virtual const smart_objects::SmartObject* vr_help_title() const = 0;
- virtual const smart_objects::SmartObject* vr_help() const = 0;
- virtual const mobile_api::TBTState::eType& tbt_state() const = 0;
- virtual const smart_objects::SmartObject* show_command() const = 0;
- virtual const smart_objects::SmartObject* tbt_show_command() const = 0;
- virtual const std::set<mobile_apis::ButtonName::eType>& SubscribedButtons() const = 0;
- virtual const std::set<uint32_t>& SubscribesIVI() const = 0;
- virtual const smart_objects::SmartObject* keyboard_props() const = 0;
- virtual const smart_objects::SmartObject* menu_title() const = 0;
- virtual const smart_objects::SmartObject* menu_icon() const = 0;
-
- virtual void load_global_properties(const smart_objects::SmartObject& so) = 0;
- virtual void set_help_prompt(
+ public:
+ virtual ~DynamicApplicationData() {}
+ virtual const smart_objects::SmartObject* help_prompt() const = 0;
+ virtual const smart_objects::SmartObject* timeout_prompt() const = 0;
+ virtual const smart_objects::SmartObject* vr_help_title() const = 0;
+ virtual const smart_objects::SmartObject* vr_help() const = 0;
+ virtual const mobile_api::TBTState::eType& tbt_state() const = 0;
+ virtual const smart_objects::SmartObject* show_command() const = 0;
+ virtual const smart_objects::SmartObject* tbt_show_command() const = 0;
+ virtual DataAccessor<ButtonSubscriptions> SubscribedButtons() const = 0;
+ virtual DataAccessor<VehicleInfoSubscriptions> SubscribedIVI() const = 0;
+ virtual const smart_objects::SmartObject* keyboard_props() const = 0;
+ virtual const smart_objects::SmartObject* menu_title() const = 0;
+ virtual const smart_objects::SmartObject* menu_icon() const = 0;
+
+ virtual void load_global_properties(const smart_objects::SmartObject& so) = 0;
+ virtual void set_help_prompt(
const smart_objects::SmartObject& help_prompt) = 0;
- virtual void set_timeout_prompt(
+ virtual void set_timeout_prompt(
const smart_objects::SmartObject& timeout_prompt) = 0;
- virtual void set_vr_help_title(
+ virtual void set_vr_help_title(
const smart_objects::SmartObject& vr_help_title) = 0;
- virtual void reset_vr_help_title() = 0;
- virtual void set_vr_help(const smart_objects::SmartObject& vr_help) = 0;
- virtual void reset_vr_help() = 0;
- virtual void set_tbt_state(const mobile_api::TBTState::eType& tbt_state) = 0;
- virtual void set_show_command(
+ virtual void reset_vr_help_title() = 0;
+ virtual void set_vr_help(const smart_objects::SmartObject& vr_help) = 0;
+ virtual void reset_vr_help() = 0;
+ virtual void set_tbt_state(const mobile_api::TBTState::eType& tbt_state) = 0;
+ virtual void set_show_command(
const smart_objects::SmartObject& show_command) = 0;
- virtual void set_tbt_show_command(
+ virtual void set_tbt_show_command(
const smart_objects::SmartObject& tbt_show) = 0;
- virtual void set_keyboard_props(
- const smart_objects::SmartObject& keyboard_props) = 0;
- virtual void set_menu_title(
- const smart_objects::SmartObject& menu_title) = 0;
- virtual void set_menu_icon(
- const smart_objects::SmartObject& menu_icon) = 0;
-
- virtual uint32_t audio_stream_retry_number() const = 0;
-
- virtual void set_audio_stream_retry_number(
- const uint32_t& audio_stream_retry_number) = 0;
-
- virtual uint32_t video_stream_retry_number() const = 0;
-
- virtual void set_video_stream_retry_number(
- const uint32_t& video_stream_retry_number) = 0;
-
- /*
- * @brief Adds a command to the in application menu
- */
- virtual void AddCommand(uint32_t cmd_id,
- const smart_objects::SmartObject& command) = 0;
-
- /*
- * @brief Deletes all commands from the application
- * menu with the specified command id
- */
- virtual void RemoveCommand(uint32_t cmd_id) = 0;
-
- /*
- * @brief Finds command with the specified command id
- */
- virtual smart_objects::SmartObject* FindCommand(uint32_t cmd_id) = 0;
-
- /*
- * @brief Adds a menu to the application
- */
- virtual void AddSubMenu(uint32_t menu_id,
- const smart_objects::SmartObject& menu) = 0;
-
- /*
- * @brief Deletes menu from the application menu
- */
- virtual void RemoveSubMenu(uint32_t menu_id) = 0;
-
- /*
- * @brief Finds menu with the specified id
- */
- virtual smart_objects::SmartObject* FindSubMenu(
- uint32_t menu_id) const = 0;
-
- /*
- * @brief Returns true if sub menu with such name already exist
- */
- virtual bool IsSubMenuNameAlreadyExist(const std::string& name) = 0;
-
- /*
- * @brief Adds a interaction choice set to the application
- *
- * @param choice_set_id Unique ID used for this interaction choice set
- * @param choice_set SmartObject that represent choice set
- */
- virtual void AddChoiceSet(uint32_t choice_set_id,
- const smart_objects::SmartObject& choice_set) = 0;
-
- /*
- * @brief Deletes choice set from the application
- *
- * @param choice_set_id Unique ID of the interaction choice set
- */
- virtual void RemoveChoiceSet(uint32_t choice_set_id) = 0;
-
- /*
- * @brief Finds choice set with the specified choice_set_id id
- *
- * @param choice_set_id Unique ID of the interaction choice set
- */
- virtual smart_objects::SmartObject* FindChoiceSet(
- uint32_t choice_set_id) = 0;
-
- /*
- * @brief Adds perform interaction choice set to the application
- *
- * @param correlation_id Unique ID of the request that added this choice set
- * @param choice_set_id Unique ID used for this interaction choice set
- * @param choice_set SmartObject that represents choice set
- */
- virtual void AddPerformInteractionChoiceSet(
- uint32_t correlation_id, uint32_t choice_set_id,
+ virtual void set_keyboard_props(
+ const smart_objects::SmartObject& keyboard_props) = 0;
+ virtual void set_menu_title(const smart_objects::SmartObject& menu_title) = 0;
+ virtual void set_menu_icon(const smart_objects::SmartObject& menu_icon) = 0;
+
+ virtual uint32_t audio_stream_retry_number() const = 0;
+
+ virtual void set_audio_stream_retry_number(
+ const uint32_t& audio_stream_retry_number) = 0;
+
+ virtual uint32_t video_stream_retry_number() const = 0;
+
+ virtual void set_video_stream_retry_number(
+ const uint32_t& video_stream_retry_number) = 0;
+
+ /*
+ * @brief Adds a command to the in application menu
+ */
+ virtual void AddCommand(uint32_t cmd_id,
+ const smart_objects::SmartObject& command) = 0;
+
+ /*
+ * @brief Deletes all commands from the application
+ * menu with the specified command id
+ */
+ virtual void RemoveCommand(uint32_t cmd_id) = 0;
+
+ /*
+ * @brief Finds command with the specified command id
+ */
+ virtual smart_objects::SmartObject* FindCommand(uint32_t cmd_id) = 0;
+
+ /*
+ * @brief Adds a menu to the application
+ */
+ virtual void AddSubMenu(uint32_t menu_id,
+ const smart_objects::SmartObject& menu) = 0;
+
+ /*
+ * @brief Deletes menu from the application menu
+ */
+ virtual void RemoveSubMenu(uint32_t menu_id) = 0;
+
+ /*
+ * @brief Finds menu with the specified id
+ */
+ virtual smart_objects::SmartObject* FindSubMenu(uint32_t menu_id) const = 0;
+
+ /*
+ * @brief Returns true if sub menu with such name already exist
+ */
+ virtual bool IsSubMenuNameAlreadyExist(const std::string& name) = 0;
+
+ /*
+ * @brief Adds a interaction choice set to the application
+ *
+ * @param choice_set_id Unique ID used for this interaction choice set
+ * @param choice_set SmartObject that represent choice set
+ */
+ virtual void AddChoiceSet(uint32_t choice_set_id,
+ const smart_objects::SmartObject& choice_set) = 0;
+
+ /*
+ * @brief Deletes choice set from the application
+ *
+ * @param choice_set_id Unique ID of the interaction choice set
+ */
+ virtual void RemoveChoiceSet(uint32_t choice_set_id) = 0;
+
+ /*
+ * @brief Finds choice set with the specified choice_set_id id
+ *
+ * @param choice_set_id Unique ID of the interaction choice set
+ */
+ virtual smart_objects::SmartObject* FindChoiceSet(uint32_t choice_set_id) = 0;
+
+ /*
+ * @brief Adds perform interaction choice set to the application
+ *
+ * @param correlation_id Unique ID of the request that added this choice set
+ * @param choice_set_id Unique ID used for this interaction choice set
+ * @param choice_set SmartObject that represents choice set
+ */
+ virtual void AddPerformInteractionChoiceSet(
+ uint32_t correlation_id,
+ uint32_t choice_set_id,
const smart_objects::SmartObject& choice_set) = 0;
- /*
- * @brief Deletes entirely perform interaction choice set for request
- * @param correlation_id Unique ID of the request that added this choice set
- *
- */
- virtual void DeletePerformInteractionChoiceSet(uint32_t correlation_id) = 0;
-
- /*
- * @brief Retrieves entirely ChoiceSet - VR commands map
- *
- * @return ChoiceSet map that is currently in use
- */
- virtual DataAccessor<PerformChoiceSetMap>
- performinteraction_choice_set_map() const = 0;
-
- /*
- * @brief Retrieve application commands
- */
- virtual DataAccessor<CommandsMap> commands_map() const = 0;
-
- /*
- * @brief Retrieve application sub menus
- */
- virtual DataAccessor<SubMenuMap> sub_menu_map() const = 0;
-
- /*
- * @brief Retrieve application choice set map
- */
- virtual DataAccessor<ChoiceSetMap> choice_set_map() const = 0;
-
- /*
- * @brief Sets perform interaction state
- *
- * @param active Current state of the perform interaction
- */
- virtual void set_perform_interaction_active(uint32_t active) = 0;
-
- /*
- * @brief Retrieves perform interaction state
- *
- * @return TRUE if perform interaction active, otherwise FALSE
- */
- virtual uint32_t is_perform_interaction_active() const = 0;
-
- /*
+ /*
+ * @brief Deletes entirely perform interaction choice set for request
+ * @param correlation_id Unique ID of the request that added this choice set
+ *
+ */
+ virtual void DeletePerformInteractionChoiceSet(uint32_t correlation_id) = 0;
+
+ /*
+ * @brief Retrieves entirely ChoiceSet - VR commands map
+ *
+ * @return ChoiceSet map that is currently in use
+ */
+ virtual DataAccessor<PerformChoiceSetMap> performinteraction_choice_set_map()
+ const = 0;
+
+ /*
+ * @brief Retrieve application commands
+ */
+ virtual DataAccessor<CommandsMap> commands_map() const = 0;
+
+ /*
+ * @brief Retrieve application sub menus
+ */
+ virtual DataAccessor<SubMenuMap> sub_menu_map() const = 0;
+
+ /*
+ * @brief Retrieve application choice set map
+ */
+ virtual DataAccessor<ChoiceSetMap> choice_set_map() const = 0;
+
+ /*
+ * @brief Sets perform interaction state
+ *
+ * @param active Current state of the perform interaction
+ */
+ virtual void set_perform_interaction_active(uint32_t active) = 0;
+
+ /*
+ * @brief Retrieves perform interaction state
+ *
+ * @return TRUE if perform interaction active, otherwise FALSE
+ */
+ virtual uint32_t is_perform_interaction_active() const = 0;
+
+ /*
+ * @brief Set perform interaction layout
+ *
+ * @param Current Interaction layout of the perform interaction
+ */
+ virtual void set_perform_interaction_layout(
+ mobile_api::LayoutMode::eType layout) = 0;
+
+ /*
+ * @brief Retrieve perform interaction layout
+ */
+ virtual mobile_api::LayoutMode::eType perform_interaction_layout() const = 0;
+
+ /*
* @brief Sets the mode for perform interaction: UI/VR/BOTH
*
* @param mode Mode that was selected (MENU; VR; BOTH)
*/
- virtual void set_perform_interaction_mode(int32_t mode) = 0;
-
- /*
- * @brief Retrieve the mode that was PerformInteraction sent in
- *
- * @return mode of PerformInteraction
- */
- virtual int32_t perform_interaction_mode() const = 0;
-
- /*
- * @brief Sets reset global properties state
- *
- * @param active Current state of the reset global properties
- */
- virtual void set_reset_global_properties_active(bool active) = 0;
-
- /*
- * @brief Retrieves reset global properties state
- *
- * @return TRUE if perform interaction active, otherwise FALSE
- */
- virtual bool is_reset_global_properties_active() const = 0;
+ virtual void set_perform_interaction_mode(int32_t mode) = 0;
+
+ /*
+ * @brief Retrieve the mode that was PerformInteraction sent in
+ *
+ * @return mode of PerformInteraction
+ */
+ virtual int32_t perform_interaction_mode() const = 0;
+
+ /*
+ * @brief Sets reset global properties state
+ *
+ * @param active Current state of the reset global properties
+ */
+ virtual void set_reset_global_properties_active(bool active) = 0;
+
+ /*
+ * @brief Retrieves reset global properties state
+ *
+ * @return TRUE if perform interaction active, otherwise FALSE
+ */
+ virtual bool is_reset_global_properties_active() const = 0;
};
class Application : public virtual InitialApplicationData,
- public virtual DynamicApplicationData {
-
- public:
- enum ApplicationState {
- kRegistered = 0,
- kWaitingForRegistration
- };
-
- public:
- Application() :
- is_greyed_out_(false) {
- }
-
- virtual ~Application() {
- }
-
- /**
- * @brief Returns message belonging to the application
- * that is currently executed (i.e. on HMI).
- * @return smart_objects::SmartObject * Active message
- */
- virtual const smart_objects::SmartObject* active_message() const = 0;
-
- /**
- * @brief returns current hash value
- * @return current hash value
- */
- virtual const std::string& curHash() const = 0;
-
- /**
- * @brief Change Hash for current application
- * and send notification to mobile
- * @return updated_hash
- */
- virtual void UpdateHash() = 0;
-
- virtual void CloseActiveMessage() = 0;
- virtual bool IsFullscreen() const = 0;
- virtual void ChangeSupportingAppHMIType() = 0;
-
- virtual bool is_navi() const = 0;
- virtual void set_is_navi(bool allow) = 0;
-
- virtual bool video_streaming_approved() const = 0;
- virtual void set_video_streaming_approved(bool state) = 0;
- virtual bool audio_streaming_approved() const = 0;
- virtual void set_audio_streaming_approved(bool state) = 0;
-
- virtual bool video_streaming_allowed() const = 0;
- virtual void set_video_streaming_allowed(bool state) = 0;
- virtual bool audio_streaming_allowed() const = 0;
- virtual void set_audio_streaming_allowed(bool state) = 0;
-
- /**
- * @brief Starts streaming service for application
- * @param service_type Type of streaming service
- */
- virtual void StartStreaming(
- protocol_handler::ServiceType service_type) = 0;
-
- /**
- * @brief Stops streaming service for application
- * @param service_type Type of streaming service
- */
- virtual void StopStreaming(
- protocol_handler::ServiceType service_type) = 0;
-
- /**
- * @brief Suspends streaming process for application
- * @param service_type Type of streaming service
- */
- virtual void SuspendStreaming(
- protocol_handler::ServiceType service_type) = 0;
-
- /**
- * @brief Wakes up streaming process for application
- * @param service_type Type of streaming service
- */
- virtual void WakeUpStreaming(
- protocol_handler::ServiceType service_type) = 0;
-
- virtual bool is_voice_communication_supported() const = 0;
- virtual void set_voice_communication_supported(
- bool is_voice_communication_supported) = 0;
- virtual bool app_allowed() const = 0;
- virtual bool has_been_activated() const = 0;
- virtual bool set_activated(bool is_active) = 0;
-
- virtual const Version& version() const = 0;
- virtual void set_hmi_application_id(uint32_t hmi_app_id) = 0;
- virtual uint32_t hmi_app_id() const = 0;
- virtual uint32_t app_id() const = 0;
- virtual const std::string& name() const = 0;
- virtual const std::string folder_name() const = 0;
- virtual bool is_media_application() const = 0;
- virtual bool is_foreground() const = 0;
- virtual void set_foreground(bool is_foreground) = 0;
- virtual const mobile_api::HMILevel::eType hmi_level() const = 0;
- virtual const uint32_t put_file_in_none_count() const = 0;
- virtual const uint32_t delete_file_in_none_count() const = 0;
- virtual const uint32_t list_files_in_none_count() const = 0;
- virtual const mobile_api::SystemContext::eType system_context() const = 0;
- virtual const mobile_api::AudioStreamingState::eType
- audio_streaming_state() const = 0;
- virtual const std::string& app_icon_path() const = 0;
- virtual connection_handler::DeviceHandle device() const = 0;
- virtual bool tts_speak_state() = 0;
-
- /**
- * @brief Active states of application
- */
- DataAccessor<HmiStateList> GetHmiStateListAccessor() {
- DataAccessor<HmiStateList> hmi_states_da =
- DataAccessor<HmiStateList>(hmi_states_, hmi_states_lock_);
- return hmi_states_da;
- }
-
- /**
- * @brief Current hmi state
- */
- virtual const HmiStatePtr CurrentHmiState() const = 0;
-
-
- /**
- * @brief RegularHmiState of application without active events VR, TTS etc ...
- * @return HmiState of application
- */
- virtual const HmiStatePtr RegularHmiState() const = 0;
-
- /**
- * @brief sets true if application has sent TTS GlobalProperties
- * request with empty array help_prompt to HMI with level
- * NONE BACKGROUND
- * @param active contains state of sending TTS GlobalProperties
- */
- virtual void set_tts_properties_in_none(bool active) = 0;
- /**
- * @brief returns true if application has sent TTS GlobalProperties
- * otherwise return false
- * @return flag tts_properties_in_none
- */
- virtual bool tts_properties_in_none() = 0;
- /**
- * @brief sets true if application has sent TTS GlobalProperties
- * request with default array help_prompt to HMI with level
- * FULL LIMITED
- * @param active contains state of sending TTS GlobalProperties
- */
- virtual void set_tts_properties_in_full(
- bool active) = 0;
- /**
- * @brief returns true if application has sent TTS GlobalProperties
- * otherwise return false
- * @return flag tts_properties_in_full
- */
- virtual bool tts_properties_in_full() = 0;
- virtual void set_version(const Version& version) = 0;
- virtual void set_name(const std::string& name) = 0;
- virtual void set_is_media_application(bool is_media) = 0;
- virtual void increment_put_file_in_none_count() = 0;
- virtual void increment_delete_file_in_none_count() = 0;
- virtual void increment_list_files_in_none_count() = 0;
- virtual bool set_app_icon_path(const std::string& file_name) = 0;
- virtual void set_app_allowed(const bool& allowed) = 0;
- virtual void set_device(connection_handler::DeviceHandle device) = 0;
- virtual uint32_t get_grammar_id() const = 0 ;
- virtual void set_grammar_id(uint32_t value) = 0;
-
- virtual void set_protocol_version(
- const ProtocolVersion& protocol_version) = 0;
- virtual ProtocolVersion protocol_version() const = 0;
-
- virtual bool AddFile(AppFile& file) = 0;
- virtual const AppFilesMap& getAppFiles() const = 0;
-
- /**
- * @brief Updates fields of existing file
- * @param file_name File name, that need to update
- * @param is_persistent Bollean describes is file persistent?
- * @param is_download_complete Bollean describes is file downloaded fully on need to finish downloading?
- * @return TRUE if file exist and updated sucsesfuly, othervise return false
- */
- virtual bool UpdateFile(AppFile& file) = 0;
- virtual bool DeleteFile(const std::string& file_name) = 0;
- virtual const AppFile* GetFile(const std::string& file_name) = 0;
-
- virtual bool SubscribeToButton(mobile_apis::ButtonName::eType btn_name) = 0;
- virtual bool IsSubscribedToButton(mobile_apis::ButtonName::eType btn_name) = 0;
- virtual bool UnsubscribeFromButton(mobile_apis::ButtonName::eType btn_name) = 0;
-
- virtual bool SubscribeToIVI(uint32_t vehicle_info_type_) = 0;
- virtual bool IsSubscribedToIVI(uint32_t vehicle_info_type_) = 0;
- virtual bool UnsubscribeFromIVI(uint32_t vehicle_info_type_) = 0;
-
- /**
- * @brief ResetDataInNone reset data counters in NONE
- */
- virtual void ResetDataInNone() = 0;
-
- /**
- * @brief Check, if limits for command number per time is exceeded
- * @param cmd_id Unique command id from mobile API
- * @param source Limits source, e.g. policy table, config file etc.
- * @return true, if - excedeed, otherwise - false
- */
- virtual bool IsCommandLimitsExceeded(mobile_apis::FunctionID::eType cmd_id,
- TLimitSource source) = 0;
-
- /**
- * Returns object for recording statistics
- * @return object for recording statistics
- */
- virtual UsageStatistics& usage_report() = 0;
-
- /**
- * @brief SetRegularState set permanent state of application
- * @param state state to setup
- */
- virtual void SetRegularState(HmiStatePtr state) = 0;
-
- /**
- * @brief AddHMIState the function that will change application's
- * hmi state.
- *
- * @param app_id id of the application whose hmi level should be changed.
- *
- * @param state new hmi state for certain application.
- */
- virtual void AddHMIState(HmiStatePtr state) = 0;
-
- /**
- * @brief RemoveHMIState the function that will turn back hmi_level after end
- * of some event
- *
- * @param app_id id of the application whose hmi level should be changed.
- *
- * @param state_id that should be removed
- */
- virtual void RemoveHMIState(HmiState::StateID state_id) = 0;
-
- /**
- * @brief Keeps id of softbuttons which is created in commands:
- * Alert, Show, ScrollableMessage, ShowConstantTBT, AlertManeuver, UpdateTurnList
- * @param cmd_id Unique command id from mobile API
- * @param list of softbuttons were created by command.
- */
- virtual void SubscribeToSoftButtons(int32_t cmd_id,
- const SoftButtonID& softbuttons_id) = 0;
-
- /**
- * @brief Determine the existence of softbutton
- * @param Softbutton_id contains id of softbutton
- * @return Returns true if application contains softbutton id otherwise returns false.
- */
- virtual bool IsSubscribedToSoftButton(const uint32_t softbutton_id) = 0;
-
- /**
- * @brief Removes list of softbuttons which is created in commands
- * @param cmd_id Unique command id from mobile API
- */
- virtual void UnsubscribeFromSoftButtons(int32_t cmd_id) = 0;
-
- /**
- * @brief Check's if it is media, voice communication or navigation application
- *
- * @return true if application is media, voice communication or navigation
- */
- virtual bool IsAudioApplication() const = 0;
-
- /**
- * @brief IsRegistered allows to distinguish if this
- * application has been registered.
- *
- * @return true if registered, false otherwise.
- */
- bool IsRegistered() const { return app_state_ == kRegistered;}
-
- /**
- * @brief MarkRegistered allows to mark application as registered.
- */
- void MarkRegistered() {app_state_ = kRegistered;}
-
- /**
- * @brief MarkUnregistered allows to mark application as unregistered.
- */
- void MarkUnregistered() {app_state_ = kWaitingForRegistration;}
-
- /**
- * @brief schemaUrl contains application's url (for 4th protocol version)
- *
- * @return application's url.
- */
- std::string SchemaUrl() const {return url_;}
+ public virtual DynamicApplicationData {
+ public:
+ enum ApplicationRegisterState { kRegistered = 0, kWaitingForRegistration };
+
+ public:
+ Application() : is_greyed_out_(false) {}
+ virtual ~Application() {}
+
+ /**
+ * @brief Returns message belonging to the application
+ * that is currently executed (i.e. on HMI).
+ * @return smart_objects::SmartObject * Active message
+ */
+ virtual const smart_objects::SmartObject* active_message() const = 0;
+
+ /**
+ * @brief returns current hash value
+ * @return current hash value
+ */
+ virtual const std::string& curHash() const = 0;
+
+ /**
+ * @brief Change Hash for current application
+ * and send notification to mobile
+ * @return updated_hash
+ */
+ virtual void UpdateHash() = 0;
+
+ /**
+ * @brief method is called when SDL is saving application data for resumption
+ * @return TRUE if data of application need to save for resumption, otherwise
+ * return FALSE
+ */
+ virtual bool is_application_data_changed() const = 0;
+
+ /**
+ * @brief method is called after SDL saved application data for resumption
+ * @param state_application_data contains FALSE after saving data
+ */
+ virtual void set_is_application_data_changed(bool state_application_data) = 0;
+
+ virtual void CloseActiveMessage() = 0;
+ virtual bool IsFullscreen() const = 0;
+ virtual void ChangeSupportingAppHMIType() = 0;
+
+ virtual bool is_navi() const = 0;
+ virtual void set_is_navi(bool allow) = 0;
+
+ virtual bool video_streaming_approved() const = 0;
+ virtual void set_video_streaming_approved(bool state) = 0;
+ virtual bool audio_streaming_approved() const = 0;
+ virtual void set_audio_streaming_approved(bool state) = 0;
+
+ virtual bool video_streaming_allowed() const = 0;
+ virtual void set_video_streaming_allowed(bool state) = 0;
+ virtual bool audio_streaming_allowed() const = 0;
+ virtual void set_audio_streaming_allowed(bool state) = 0;
+
+ /**
+ * @brief Starts streaming service for application
+ * @param service_type Type of streaming service
+ */
+ virtual void StartStreaming(protocol_handler::ServiceType service_type) = 0;
+
+ /**
+ * @brief Stops streaming service for application
+ * @param service_type Type of streaming service
+ */
+ virtual void StopStreaming(protocol_handler::ServiceType service_type) = 0;
+
+ /**
+ * @brief Stops streaming for application whether it is allowed or not HMI
+ * @param service_type video or audio
+ */
+ virtual void StopStreamingForce(
+ protocol_handler::ServiceType service_type) = 0;
+
+ /**
+ * @brief Suspends streaming process for application
+ * @param service_type Type of streaming service
+ */
+ virtual void SuspendStreaming(protocol_handler::ServiceType service_type) = 0;
+
+ /**
+ * @brief Wakes up streaming process for application
+ * @param service_type Type of streaming service
+ */
+ virtual void WakeUpStreaming(protocol_handler::ServiceType service_type) = 0;
+
+ virtual bool is_voice_communication_supported() const = 0;
+ virtual void set_voice_communication_supported(
+ bool is_voice_communication_supported) = 0;
+ virtual bool app_allowed() const = 0;
+ virtual bool has_been_activated() const = 0;
+ virtual bool set_activated(bool is_active) = 0;
+
+ virtual const Version& version() const = 0;
+ virtual void set_hmi_application_id(uint32_t hmi_app_id) = 0;
+ virtual uint32_t hmi_app_id() const = 0;
+ virtual uint32_t app_id() const = 0;
+ virtual const custom_str::CustomString& name() const = 0;
+ /**
+ * @brief Sets application folder name, which is used for storing of related
+ * files, e.g. icons
+ * @param folder_name Name of folder
+ */
+ virtual void set_folder_name(const std::string& folder_name) = 0;
+ virtual const std::string folder_name() const = 0;
+ virtual bool is_media_application() const = 0;
+ virtual bool is_foreground() const = 0;
+ virtual void set_foreground(const bool is_foreground) = 0;
+ virtual const mobile_api::HMILevel::eType hmi_level() const = 0;
+ virtual const uint32_t put_file_in_none_count() const = 0;
+ virtual const uint32_t delete_file_in_none_count() const = 0;
+ virtual const uint32_t list_files_in_none_count() const = 0;
+ virtual const mobile_api::SystemContext::eType system_context() const = 0;
+ virtual const mobile_api::AudioStreamingState::eType audio_streaming_state()
+ const = 0;
+ virtual const std::string& app_icon_path() const = 0;
+ virtual connection_handler::DeviceHandle device() const = 0;
+
+ /**
+ * @brief sets true if application has sent TTS GlobalProperties
+ * request with empty array help_prompt to HMI with level
+ * NONE BACKGROUND
+ * @param active contains state of sending TTS GlobalProperties
+ */
+ virtual void set_tts_properties_in_none(bool active) = 0;
+ /**
+ * @brief returns true if application has sent TTS GlobalProperties
+ * otherwise return false
+ * @return flag tts_properties_in_none
+ */
+ virtual bool tts_properties_in_none() = 0;
+ /**
+ * @brief sets true if application has sent TTS GlobalProperties
+ * request with default array help_prompt to HMI with level
+ * FULL LIMITED
+ * @param active contains state of sending TTS GlobalProperties
+ */
+ virtual void set_tts_properties_in_full(bool active) = 0;
+ /**
+ * @brief returns true if application has sent TTS GlobalProperties
+ * otherwise return false
+ * @return flag tts_properties_in_full
+ */
+ virtual bool tts_properties_in_full() = 0;
+ virtual void set_version(const Version& version) = 0;
+ virtual void set_name(const custom_str::CustomString& name) = 0;
+ virtual void set_is_media_application(bool is_media) = 0;
+ virtual void increment_put_file_in_none_count() = 0;
+ virtual void increment_delete_file_in_none_count() = 0;
+ virtual void increment_list_files_in_none_count() = 0;
+ virtual bool set_app_icon_path(const std::string& file_name) = 0;
+ virtual void set_app_allowed(const bool allowed) = 0;
+ virtual void set_device(connection_handler::DeviceHandle device) = 0;
+ virtual uint32_t get_grammar_id() const = 0;
+ virtual void set_grammar_id(uint32_t value) = 0;
+
+ virtual void set_protocol_version(
+ const ProtocolVersion& protocol_version) = 0;
+ virtual ProtocolVersion protocol_version() const = 0;
+
+ virtual void set_is_resuming(bool is_resuming) = 0;
+ virtual bool is_resuming() const = 0;
+
+ virtual bool AddFile(const AppFile& file) = 0;
+ virtual const AppFilesMap& getAppFiles() const = 0;
+
+ /**
+ * @brief Updates fields of existing file
+ * @param file_name File name, that need to update
+ * @param is_persistent Bollean describes is file persistent?
+ * @param is_download_complete Bollean describes is file downloaded fully on
+ * need to finish downloading?
+ * @return TRUE if file exist and updated sucsesfuly, othervise return false
+ */
+ virtual bool UpdateFile(const AppFile& file) = 0;
+ virtual bool DeleteFile(const std::string& file_name) = 0;
+ virtual const AppFile* GetFile(const std::string& file_name) = 0;
+
+ virtual bool SubscribeToButton(mobile_apis::ButtonName::eType btn_name) = 0;
+ virtual bool IsSubscribedToButton(
+ mobile_apis::ButtonName::eType btn_name) = 0;
+ virtual bool UnsubscribeFromButton(
+ mobile_apis::ButtonName::eType btn_name) = 0;
+
+ virtual bool SubscribeToIVI(uint32_t vehicle_info_type) = 0;
+ virtual bool IsSubscribedToIVI(uint32_t vehicle_info_type) const = 0;
+ virtual bool UnsubscribeFromIVI(uint32_t vehicle_info_type) = 0;
+
+ /**
+ * @brief ResetDataInNone reset data counters in NONE
+ */
+ virtual void ResetDataInNone() = 0;
+
+ /**
+ * @brief Check, if limits for command number per time is exceeded
+ * @param cmd_id Unique command id from mobile API
+ * @param source Limits source, e.g. policy table, config file etc.
+ * @return true, if - excedeed, otherwise - false
+ */
+ virtual bool IsCommandLimitsExceeded(mobile_apis::FunctionID::eType cmd_id,
+ TLimitSource source) = 0;
+
+ /**
+ * Returns object for recording statistics
+ * @return object for recording statistics
+ */
+ virtual UsageStatistics& usage_report() = 0;
+
+ /**
+ * @brief SetRegularState set permanent state of application
+ *
+ * @param state state to setup
+ */
+ virtual void SetRegularState(HmiStatePtr state) = 0;
+
+ /**
+ * @brief SetPostponedState sets postponed state to application.
+ * This state could be set as regular later
+ *
+ * @param state state to setup
+ */
+ virtual void SetPostponedState(HmiStatePtr state) = 0;
+
+ virtual void RemovePostponedState() = 0;
+
+ /**
+ * @brief AddHMIState the function that will change application's
+ * hmi state.
+ *
+ * @param app_id id of the application whose hmi level should be changed.
+ *
+ * @param state new hmi state for certain application.
+ */
+ virtual void AddHMIState(HmiStatePtr state) = 0;
+
+ /**
+ * @brief RemoveHMIState the function that will turn back hmi_level after end
+ * of some event
+ *
+ * @param app_id id of the application whose hmi level should be changed.
+ *
+ * @param state_id that should be removed
+ */
+ virtual void RemoveHMIState(HmiState::StateID state_id) = 0;
+
+ /**
+ * @brief HmiState of application within active events PhoneCall, TTS< etc ...
+ * @return Active HmiState of application
+ */
+ virtual const HmiStatePtr CurrentHmiState() const = 0;
+
+ /**
+ * @brief RegularHmiState of application without active events VR, TTS etc ...
+ * @return HmiState of application
+ */
+ virtual const HmiStatePtr RegularHmiState() const = 0;
+
+ /**
+ * @brief PostponedHmiState returns postponed hmi state of application
+ * if it's present
+ *
+ * @return Postponed hmi state of application
+ */
+ virtual const HmiStatePtr PostponedHmiState() const = 0;
+
+ /**
+ * @brief Keeps id of softbuttons which is created in commands:
+ * Alert, Show, ScrollableMessage, ShowConstantTBT, AlertManeuver,
+ * UpdateTurnList
+ * @param cmd_id Unique command id from mobile API
+ * @param list of softbuttons were created by command.
+ */
+ virtual void SubscribeToSoftButtons(int32_t cmd_id,
+ const SoftButtonID& softbuttons_id) = 0;
+
+ /**
+ * @brief Determine the existence of softbutton
+ * @param Softbutton_id contains id of softbutton
+ * @return Returns true if application contains softbutton id otherwise
+ * returns false.
+ */
+ virtual bool IsSubscribedToSoftButton(const uint32_t softbutton_id) = 0;
+
+ /**
+ * @brief Removes list of softbuttons which is created in commands
+ * @param cmd_id Unique command id from mobile API
+ */
+ virtual void UnsubscribeFromSoftButtons(int32_t cmd_id) = 0;
+
+ /**
+ * @brief Check's if it is media, voice communication or navigation
+ * application
+ *
+ * @return true if application is media, voice communication or navigation
+ */
+ virtual bool IsAudioApplication() const = 0;
+
+ /**
+ * @brief IsRegistered allows to distinguish if this
+ * application has been registered.
+ *
+ * @return true if registered, false otherwise.
+ */
+ virtual bool IsRegistered() const = 0;
+ /**
+ * @brief MarkRegistered allows to mark application as registered.
+ */
+ void MarkRegistered() {
+ app_state_ = kRegistered;
+ }
- /**
- * @brief SetShemaUrl allows to store schema url for application.
- *
- * @param url url to store.
- */
- void SetShemaUrl(const std::string& url) {url_ = url;}
+ /**
+ * @brief MarkUnregistered allows to mark application as unregistered.
+ */
+ void MarkUnregistered() {
+ app_state_ = kWaitingForRegistration;
+ }
- /**
- * @brief packagName allows to obtain application's package name.
- *
- * @return pakage name.
- */
- std::string PackageName() const {return package_name_;}
+ /**
+ * @brief schemaUrl contains application's url (for 4th protocol version)
+ *
+ * @return application's url.
+ */
+ std::string SchemaUrl() const {
+ return url_;
+ }
- /**
- * @brief SetPackageName allows to store package name for application.
- *
- * @param packageName package name to store.
- */
- void SetPackageName(const std::string& packageName) {
- package_name_ = packageName;
- }
+ /**
+ * @brief SetShemaUrl allows to store schema url for application.
+ *
+ * @param url url to store.
+ */
+ void SetShemaUrl(const std::string& url) {
+ url_ = url;
+ }
- /**
- * @brief GetDeviceId allows to obtain device id which posseses
- * by this application.
- *
- * @return device the device id.
- */
- std::string GetDeviceId() const {return device_id_;}
+ /**
+ * @brief packagName allows to obtain application's package name.
+ *
+ * @return pakage name.
+ */
+ std::string PackageName() const {
+ return package_name_;
+ }
- /**
- * @brief Returns is application should be greyed out on HMI
- */
- bool is_greyed_out() const {return is_greyed_out_;}
+ /**
+ * @brief SetPackageName allows to store package name for application.
+ *
+ * @param packageName package name to store.
+ */
+ void SetPackageName(const std::string& packageName) {
+ package_name_ = packageName;
+ }
- /**
- * @brief Sets application as should be greyed out on HMI
- * @param is_greyed_out True, if should be greyed out on HMI,
- * otherwise - false
- */
- void set_greyed_out(bool is_greyed_out) {is_greyed_out_ = is_greyed_out;}
+ /**
+ * @brief GetDeviceId allows to obtain device id which posseses
+ * by this application.
+ *
+ * @return device the device id.
+ */
+ std::string GetDeviceId() const {
+ return device_id_;
+ }
- protected:
+ /**
+ * @brief Returns is application should be greyed out on HMI
+ */
+ bool is_greyed_out() const {
+ return is_greyed_out_;
+ }
- /**
- * @brief Active states of application
- */
- HmiStateList hmi_states_;
- mutable sync_primitives::Lock hmi_states_lock_;
-
- ApplicationState app_state_;
- std::string url_;
- std::string package_name_;
- std::string device_id_;
- ssize_t connection_id_;
- bool is_greyed_out_;
+ /**
+ * @brief Sets application as should be greyed out on HMI
+ * @param is_greyed_out True, if should be greyed out on HMI,
+ * otherwise - false
+ */
+ void set_greyed_out(bool is_greyed_out) {
+ is_greyed_out_ = is_greyed_out;
+ }
+ /**
+ * @brief Load persistent files from application folder.
+ */
+ virtual void LoadPersistentFiles() = 0;
+
+ /**
+ * @brief Get available app space
+ * @param name of the app folder(make + mobile app id)
+ * @return free app space.
+ */
+ virtual uint32_t GetAvailableDiskSpace() = 0;
+
+ protected:
+ mutable sync_primitives::Lock hmi_states_lock_;
+
+ ApplicationRegisterState app_state_;
+ ApplicationState state_;
+ std::string url_;
+ std::string package_name_;
+ std::string device_id_;
+ ssize_t connection_id_;
+ bool is_greyed_out_;
};
typedef utils::SharedPtr<Application> ApplicationSharedPtr;
diff --git a/src/components/application_manager/include/application_manager/application_data_impl.h b/src/components/application_manager/include/application_manager/application_data_impl.h
index 62d3d1c8c7..465e4e010a 100644
--- a/src/components/application_manager/include/application_manager/application_data_impl.h
+++ b/src/components/application_manager/include/application_manager/application_data_impl.h
@@ -44,235 +44,244 @@ namespace application_manager {
namespace mobile_api = mobile_apis;
class InitialApplicationDataImpl : public virtual Application {
- public:
- InitialApplicationDataImpl();
- ~InitialApplicationDataImpl();
-
- const smart_objects::SmartObject* app_types() const;
- const smart_objects::SmartObject* vr_synonyms() const;
- virtual std::string mobile_app_id() const;
- const smart_objects::SmartObject* tts_name() const;
- const smart_objects::SmartObject* ngn_media_screen_name() const;
- const mobile_api::Language::eType& language() const;
- const mobile_api::Language::eType& ui_language() const;
- void set_app_types(const smart_objects::SmartObject& app_types);
- void set_vr_synonyms(const smart_objects::SmartObject& vr_synonyms);
- void set_mobile_app_id(const std::string& mobile_app_id);
- void set_tts_name(const smart_objects::SmartObject& tts_name);
- void set_ngn_media_screen_name(const smart_objects::SmartObject& ngn_name);
- void set_language(const mobile_api::Language::eType& language);
- void set_ui_language(const mobile_api::Language::eType& ui_language);
-
- protected:
- smart_objects::SmartObject* app_types_;
- smart_objects::SmartObject* vr_synonyms_;
- std::string mobile_app_id_;
- smart_objects::SmartObject* tts_name_;
- smart_objects::SmartObject* ngn_media_screen_name_;
- mobile_api::Language::eType language_;
- mobile_api::Language::eType ui_language_;
- private:
- DISALLOW_COPY_AND_ASSIGN(InitialApplicationDataImpl);
+ public:
+ InitialApplicationDataImpl();
+ ~InitialApplicationDataImpl();
+
+ const smart_objects::SmartObject* app_types() const;
+ const smart_objects::SmartObject* vr_synonyms() const;
+ virtual std::string policy_app_id() const;
+ const smart_objects::SmartObject* tts_name() const;
+ const smart_objects::SmartObject* ngn_media_screen_name() const;
+ const mobile_api::Language::eType& language() const;
+ const mobile_api::Language::eType& ui_language() const;
+ void set_app_types(const smart_objects::SmartObject& app_types);
+ void set_vr_synonyms(const smart_objects::SmartObject& vr_synonyms);
+ void set_mobile_app_id(const std::string& policy_app_id);
+ void set_tts_name(const smart_objects::SmartObject& tts_name);
+ void set_ngn_media_screen_name(const smart_objects::SmartObject& ngn_name);
+ void set_language(const mobile_api::Language::eType& language);
+ void set_ui_language(const mobile_api::Language::eType& ui_language);
+
+ void set_perform_interaction_layout(
+ mobile_api::LayoutMode::eType layout) OVERRIDE;
+ mobile_api::LayoutMode::eType perform_interaction_layout() const OVERRIDE;
+
+ protected:
+ smart_objects::SmartObject* app_types_;
+ smart_objects::SmartObject* vr_synonyms_;
+ std::string mobile_app_id_;
+ smart_objects::SmartObject* tts_name_;
+ smart_objects::SmartObject* ngn_media_screen_name_;
+ mobile_api::Language::eType language_;
+ mobile_api::Language::eType ui_language_;
+ mobile_apis::LayoutMode::eType perform_interaction_layout_;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(InitialApplicationDataImpl);
};
class DynamicApplicationDataImpl : public virtual Application {
- public:
- DynamicApplicationDataImpl();
- ~DynamicApplicationDataImpl();
- const smart_objects::SmartObject* help_prompt() const;
- const smart_objects::SmartObject* timeout_prompt() const;
- const smart_objects::SmartObject* vr_help_title() const;
- const smart_objects::SmartObject* vr_help() const;
- const mobile_api::TBTState::eType& tbt_state() const;
- const smart_objects::SmartObject* show_command() const;
- const smart_objects::SmartObject* tbt_show_command() const;
- const smart_objects::SmartObject* keyboard_props() const;
- const smart_objects::SmartObject* menu_title() const;
- const smart_objects::SmartObject* menu_icon() const;
-
- void load_global_properties(const smart_objects::SmartObject& properties_so);
- void set_help_prompt(const smart_objects::SmartObject& help_prompt);
- void set_timeout_prompt(const smart_objects::SmartObject& timeout_prompt);
- void set_vr_help_title(const smart_objects::SmartObject& vr_help_title);
- void reset_vr_help_title();
- void set_vr_help(const smart_objects::SmartObject& vr_help);
- void reset_vr_help();
- void set_tbt_state(const mobile_api::TBTState::eType& tbt_state);
- void set_show_command(const smart_objects::SmartObject& show_command);
- void set_tbt_show_command(const smart_objects::SmartObject& tbt_show);
- void set_keyboard_props(const smart_objects::SmartObject& keyboard_props);
- void set_menu_title(const smart_objects::SmartObject& menu_title);
- void set_menu_icon(const smart_objects::SmartObject& menu_icon);
- /*
- * @brief Adds a command to the in application menu
- */
- void AddCommand(uint32_t cmd_id,
- const smart_objects::SmartObject& command);
-
- /*
- * @brief Deletes all commands from the application menu with the specified command id
- */
- void RemoveCommand(uint32_t cmd_id);
-
- /*
- * @brief Finds command with the specified command id
- */
- smart_objects::SmartObject* FindCommand(uint32_t cmd_id);
-
- /*
- * @brief Adds a menu to the application
- */
- void AddSubMenu(uint32_t menu_id, const smart_objects::SmartObject& menu);
-
- /*
- * @brief Deletes menu from the application menu
- */
- void RemoveSubMenu(uint32_t menu_id);
-
- /*
- * @brief Finds menu with the specified id
- */
- smart_objects::SmartObject* FindSubMenu(uint32_t menu_id) const;
-
- /*
- * @brief Returns true if sub menu with such name already exist
- */
- bool IsSubMenuNameAlreadyExist(const std::string& name);
-
- /*
- * @brief Adds a interaction choice set to the application
- *
- * @param choice_set_id Unique ID used for this interaction choice set
- * @param choice_set SmartObject that represent choice set
- */
- void AddChoiceSet(uint32_t choice_set_id,
- const smart_objects::SmartObject& choice_set);
-
- /*
- * @brief Deletes choice set from the application
- *
- * @param choice_set_id Unique ID of the interaction choice set
- */
- void RemoveChoiceSet(uint32_t choice_set_id);
-
- /*
- * @brief Finds choice set with the specified choice_set_id id
- *
- * @param choice_set_id Unique ID of the interaction choice set
- */
- smart_objects::SmartObject* FindChoiceSet(uint32_t choice_set_id);
-
- /*
- * @brief Adds perform interaction choice set to the application
- *
- * @param correlation_id Unique ID of the request that added this choice set
- * @param choice_set_id Unique ID used for this interaction choice set
- * @param choice_set SmartObject that represents choice set
- */
- void AddPerformInteractionChoiceSet(uint32_t correlation_id,
- uint32_t choice_set_id, const smart_objects::SmartObject& choice_set);
-
- /*
- * @brief Deletes entirely perform interaction choice set map
- * @param correlation_id Unique ID of the request that added this choice set
- *
- */
- void DeletePerformInteractionChoiceSet(uint32_t correlation_id);
-
- /*
- * @brief Retrieves entirely ChoiceSet - VR commands map
- *
- * @return ChoiceSet map that is currently in use
- */
- inline DataAccessor<PerformChoiceSetMap> performinteraction_choice_set_map() const;
-
- /*
- * @brief Retrieve application commands
- */
- inline DataAccessor<CommandsMap> commands_map() const;
-
- /*
- * @brief Retrieve application sub menus
- */
- inline DataAccessor<SubMenuMap> sub_menu_map() const;
-
- /*
- * @brief Retrieve application choice set map
- */
- inline DataAccessor<ChoiceSetMap> choice_set_map() const;
-
- /*
- * @brief Sets perform interaction state
- *
- * @param active Current state of the perform interaction
- */
- void set_perform_interaction_active(uint32_t active);
-
- /*
- * @brief Retrieves perform interaction state
- *
- * @return TRUE if perform interaction active, otherwise FALSE
- */
- inline uint32_t is_perform_interaction_active() const;
-
- /*
- * @brief Sets the mode for perform interaction: UI/VR/BOTH
- *
- * @param mode Mode that was selected (MENU; VR; BOTH)
- */
- void set_perform_interaction_mode(int32_t mode);
-
- /*
- * @brief Retrieve the mode that was PerformInteraction sent in
- *
- * @return mode of PerformInteraction
- */
- inline int32_t perform_interaction_mode() const;
-
- /*
- * @brief Sets reset global properties state
- *
- * @param active Current state of the reset global properties
- */
- void set_reset_global_properties_active(bool active);
-
- /*
- * @brief Retrieves reset global properties state
- *
- * @return TRUE if perform interaction active, otherwise FALSE
- */
- inline bool is_reset_global_properties_active() const;
-
-protected:
- smart_objects::SmartObject* help_prompt_;
- smart_objects::SmartObject* timeout_prompt_;
- smart_objects::SmartObject* vr_help_title_;
- smart_objects::SmartObject* vr_help_;
- mobile_api::TBTState::eType tbt_state_;
- smart_objects::SmartObject* show_command_;
- smart_objects::SmartObject* keyboard_props_;
- smart_objects::SmartObject* menu_title_;
- smart_objects::SmartObject* menu_icon_;
- smart_objects::SmartObject* tbt_show_command_;
-
-
- CommandsMap commands_;
- mutable sync_primitives::Lock commands_lock_;
- SubMenuMap sub_menu_;
- mutable sync_primitives::Lock sub_menu_lock_;
- ChoiceSetMap choice_set_map_;
- mutable sync_primitives::Lock choice_set_map_lock_;
- PerformChoiceSetMap performinteraction_choice_set_map_;
- mutable sync_primitives::Lock performinteraction_choice_set_lock_;
- uint32_t is_perform_interaction_active_;
- bool is_reset_global_properties_active_;
- int32_t perform_interaction_mode_;
-
-private:
- void SetGlobalProperties(const smart_objects::SmartObject& param,
- void (DynamicApplicationData::*callback)(
- const NsSmartDeviceLink::NsSmartObjects::SmartObject&));
- DISALLOW_COPY_AND_ASSIGN(DynamicApplicationDataImpl);
+ public:
+ DynamicApplicationDataImpl();
+ ~DynamicApplicationDataImpl();
+ const smart_objects::SmartObject* help_prompt() const;
+ const smart_objects::SmartObject* timeout_prompt() const;
+ const smart_objects::SmartObject* vr_help_title() const;
+ const smart_objects::SmartObject* vr_help() const;
+ const mobile_api::TBTState::eType& tbt_state() const;
+ const smart_objects::SmartObject* show_command() const;
+ const smart_objects::SmartObject* tbt_show_command() const;
+ const smart_objects::SmartObject* keyboard_props() const;
+ const smart_objects::SmartObject* menu_title() const;
+ const smart_objects::SmartObject* menu_icon() const;
+
+ void load_global_properties(const smart_objects::SmartObject& properties_so);
+ void set_help_prompt(const smart_objects::SmartObject& help_prompt);
+ void set_timeout_prompt(const smart_objects::SmartObject& timeout_prompt);
+ void set_vr_help_title(const smart_objects::SmartObject& vr_help_title);
+ void reset_vr_help_title();
+ void set_vr_help(const smart_objects::SmartObject& vr_help);
+ void reset_vr_help();
+ void set_tbt_state(const mobile_api::TBTState::eType& tbt_state);
+ void set_show_command(const smart_objects::SmartObject& show_command);
+ void set_tbt_show_command(const smart_objects::SmartObject& tbt_show);
+ void set_keyboard_props(const smart_objects::SmartObject& keyboard_props);
+ void set_menu_title(const smart_objects::SmartObject& menu_title);
+ void set_menu_icon(const smart_objects::SmartObject& menu_icon);
+ /*
+ * @brief Adds a command to the in application menu
+ */
+ void AddCommand(uint32_t cmd_id, const smart_objects::SmartObject& command);
+
+ /*
+ * @brief Deletes all commands from the application menu with the specified
+ * command id
+ */
+ void RemoveCommand(uint32_t cmd_id);
+
+ /*
+ * @brief Finds command with the specified command id
+ */
+ smart_objects::SmartObject* FindCommand(uint32_t cmd_id);
+
+ /*
+ * @brief Adds a menu to the application
+ */
+ void AddSubMenu(uint32_t menu_id, const smart_objects::SmartObject& menu);
+
+ /*
+ * @brief Deletes menu from the application menu
+ */
+ void RemoveSubMenu(uint32_t menu_id);
+
+ /*
+ * @brief Finds menu with the specified id
+ */
+ smart_objects::SmartObject* FindSubMenu(uint32_t menu_id) const;
+
+ /*
+ * @brief Returns true if sub menu with such name already exist
+ */
+ bool IsSubMenuNameAlreadyExist(const std::string& name);
+
+ /*
+ * @brief Adds a interaction choice set to the application
+ *
+ * @param choice_set_id Unique ID used for this interaction choice set
+ * @param choice_set SmartObject that represent choice set
+ */
+ void AddChoiceSet(uint32_t choice_set_id,
+ const smart_objects::SmartObject& choice_set);
+
+ /*
+ * @brief Deletes choice set from the application
+ *
+ * @param choice_set_id Unique ID of the interaction choice set
+ */
+ void RemoveChoiceSet(uint32_t choice_set_id);
+
+ /*
+ * @brief Finds choice set with the specified choice_set_id id
+ *
+ * @param choice_set_id Unique ID of the interaction choice set
+ */
+ smart_objects::SmartObject* FindChoiceSet(uint32_t choice_set_id);
+
+ /*
+ * @brief Adds perform interaction choice set to the application
+ *
+ * @param correlation_id Unique ID of the request that added this choice set
+ * @param choice_set_id Unique ID used for this interaction choice set
+ * @param choice_set SmartObject that represents choice set
+ */
+ void AddPerformInteractionChoiceSet(
+ uint32_t correlation_id,
+ uint32_t choice_set_id,
+ const smart_objects::SmartObject& choice_set);
+
+ /*
+ * @brief Deletes entirely perform interaction choice set map
+ * @param correlation_id Unique ID of the request that added this choice set
+ *
+ */
+ void DeletePerformInteractionChoiceSet(uint32_t correlation_id);
+
+ /*
+ * @brief Retrieves entirely ChoiceSet - VR commands map
+ *
+ * @return ChoiceSet map that is currently in use
+ */
+ inline DataAccessor<PerformChoiceSetMap> performinteraction_choice_set_map()
+ const;
+
+ /*
+ * @brief Retrieve application commands
+ */
+ inline DataAccessor<CommandsMap> commands_map() const;
+
+ /*
+ * @brief Retrieve application sub menus
+ */
+ inline DataAccessor<SubMenuMap> sub_menu_map() const;
+
+ /*
+ * @brief Retrieve application choice set map
+ */
+ inline DataAccessor<ChoiceSetMap> choice_set_map() const;
+
+ /*
+ * @brief Sets perform interaction state
+ *
+ * @param active Current state of the perform interaction
+ */
+ void set_perform_interaction_active(uint32_t active);
+
+ /*
+ * @brief Retrieves perform interaction state
+ *
+ * @return TRUE if perform interaction active, otherwise FALSE
+ */
+ inline uint32_t is_perform_interaction_active() const;
+
+ /*
+ * @brief Sets the mode for perform interaction: UI/VR/BOTH
+ *
+ * @param mode Mode that was selected (MENU; VR; BOTH)
+ */
+ void set_perform_interaction_mode(int32_t mode);
+
+ /*
+ * @brief Retrieve the mode that was PerformInteraction sent in
+ *
+ * @return mode of PerformInteraction
+ */
+ inline int32_t perform_interaction_mode() const;
+
+ /*
+ * @brief Sets reset global properties state
+ *
+ * @param active Current state of the reset global properties
+ */
+ void set_reset_global_properties_active(bool active);
+
+ /*
+ * @brief Retrieves reset global properties state
+ *
+ * @return TRUE if perform interaction active, otherwise FALSE
+ */
+ inline bool is_reset_global_properties_active() const;
+
+ protected:
+ smart_objects::SmartObject* help_prompt_;
+ smart_objects::SmartObject* timeout_prompt_;
+ smart_objects::SmartObject* vr_help_title_;
+ smart_objects::SmartObject* vr_help_;
+ mobile_api::TBTState::eType tbt_state_;
+ smart_objects::SmartObject* show_command_;
+ smart_objects::SmartObject* keyboard_props_;
+ smart_objects::SmartObject* menu_title_;
+ smart_objects::SmartObject* menu_icon_;
+ smart_objects::SmartObject* tbt_show_command_;
+
+ CommandsMap commands_;
+ mutable sync_primitives::Lock commands_lock_;
+ SubMenuMap sub_menu_;
+ mutable sync_primitives::Lock sub_menu_lock_;
+ ChoiceSetMap choice_set_map_;
+ mutable sync_primitives::Lock choice_set_map_lock_;
+ PerformChoiceSetMap performinteraction_choice_set_map_;
+ mutable sync_primitives::Lock performinteraction_choice_set_lock_;
+ uint32_t is_perform_interaction_active_;
+ bool is_reset_global_properties_active_;
+ int32_t perform_interaction_mode_;
+
+ private:
+ void SetGlobalProperties(
+ const smart_objects::SmartObject& param,
+ void (DynamicApplicationData::*callback)(
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject&));
+ DISALLOW_COPY_AND_ASSIGN(DynamicApplicationDataImpl);
};
DataAccessor<CommandsMap> DynamicApplicationDataImpl::commands_map() const {
@@ -289,9 +298,8 @@ DataAccessor<ChoiceSetMap> DynamicApplicationDataImpl::choice_set_map() const {
DataAccessor<PerformChoiceSetMap>
DynamicApplicationDataImpl::performinteraction_choice_set_map() const {
- return DataAccessor<PerformChoiceSetMap>(
- performinteraction_choice_set_map_,
- performinteraction_choice_set_lock_);
+ return DataAccessor<PerformChoiceSetMap>(performinteraction_choice_set_map_,
+ performinteraction_choice_set_lock_);
}
uint32_t DynamicApplicationDataImpl::is_perform_interaction_active() const {
diff --git a/src/components/application_manager/include/application_manager/application_impl.h b/src/components/application_manager/include/application_manager/application_impl.h
index f23b53632f..75496b2761 100644
--- a/src/components/application_manager/include/application_manager/application_impl.h
+++ b/src/components/application_manager/include/application_manager/application_impl.h
@@ -38,6 +38,7 @@
#include <vector>
#include <utility>
#include <list>
+#include <stdint.h>
#include "utils/date_time.h"
#include "application_manager/application_data_impl.h"
@@ -46,8 +47,10 @@
#include "protocol_handler/protocol_handler.h"
#include "connection_handler/device.h"
-#include "utils/timer_thread.h"
#include "utils/lock.h"
+#include "utils/atomic_object.h"
+#include "utils/custom_string.h"
+#include "utils/timer.h"
namespace usage_statistics {
@@ -59,14 +62,18 @@ using namespace utils;
using namespace timer;
namespace mobile_api = mobile_apis;
+namespace custom_str = custom_string;
class ApplicationImpl : public virtual InitialApplicationDataImpl,
- public virtual DynamicApplicationDataImpl {
+ public virtual DynamicApplicationDataImpl {
public:
- ApplicationImpl(uint32_t application_id,
- const std::string& mobile_app_id,
- const std::string& app_name,
- utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager);
+ ApplicationImpl(
+ uint32_t application_id,
+ const std::string& policy_app_id,
+ const std::string& mac_address,
+ const custom_str::CustomString& app_name,
+ utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager,
+ ApplicationManager& application_manager);
~ApplicationImpl();
@@ -84,7 +91,9 @@ class ApplicationImpl : public virtual InitialApplicationDataImpl,
*/
virtual void ChangeSupportingAppHMIType();
- inline bool is_navi() const { return is_navi_; }
+ inline bool is_navi() const {
+ return is_navi_;
+ }
void set_is_navi(bool allow);
bool video_streaming_approved() const;
@@ -97,15 +106,11 @@ class ApplicationImpl : public virtual InitialApplicationDataImpl,
bool audio_streaming_allowed() const;
void set_audio_streaming_allowed(bool state);
- void StartStreaming(
- protocol_handler::ServiceType service_type);
- void StopStreaming(
- protocol_handler::ServiceType service_type);
-
- void SuspendStreaming(
- protocol_handler::ServiceType service_type);
- void WakeUpStreaming(
- protocol_handler::ServiceType service_type);
+ void StartStreaming(protocol_handler::ServiceType service_type);
+ void StopStreamingForce(protocol_handler::ServiceType service_type);
+ void StopStreaming(protocol_handler::ServiceType service_type);
+ void SuspendStreaming(protocol_handler::ServiceType service_type);
+ void WakeUpStreaming(protocol_handler::ServiceType service_type);
virtual bool is_voice_communication_supported() const;
virtual void set_voice_communication_supported(
@@ -118,43 +123,46 @@ class ApplicationImpl : public virtual InitialApplicationDataImpl,
void set_hmi_application_id(uint32_t hmi_app_id);
inline uint32_t hmi_app_id() const;
inline uint32_t app_id() const;
- const std::string& name() const;
+ const custom_str::CustomString& name() const;
+ void set_folder_name(const std::string& folder_name) OVERRIDE;
const std::string folder_name() const;
bool is_media_application() const;
- virtual bool is_foreground() const;
- virtual void set_foreground(bool is_foreground);
- virtual const mobile_api::HMILevel::eType hmi_level() const;
+ bool is_foreground() const OVERRIDE;
+ void set_foreground(const bool is_foreground) OVERRIDE;
+ const mobile_apis::HMILevel::eType hmi_level() const;
const uint32_t put_file_in_none_count() const;
const uint32_t delete_file_in_none_count() const;
const uint32_t list_files_in_none_count() const;
const mobile_api::SystemContext::eType system_context() const;
- inline const mobile_apis::AudioStreamingState::eType audio_streaming_state() const;
+ inline const mobile_apis::AudioStreamingState::eType audio_streaming_state()
+ const;
const std::string& app_icon_path() const;
connection_handler::DeviceHandle device() const;
- bool tts_speak_state();
+ const std::string& mac_address() const OVERRIDE;
void set_tts_properties_in_none(bool active);
bool tts_properties_in_none();
void set_tts_properties_in_full(bool active);
bool tts_properties_in_full();
void set_version(const Version& ver);
- void set_name(const std::string& name);
+ void set_name(const custom_str::CustomString& name);
void set_is_media_application(bool is_media);
void increment_put_file_in_none_count();
void increment_delete_file_in_none_count();
void increment_list_files_in_none_count();
bool set_app_icon_path(const std::string& path);
- void set_app_allowed(const bool& allowed);
+ void set_app_allowed(const bool allowed);
void set_device(connection_handler::DeviceHandle device);
virtual uint32_t get_grammar_id() const;
virtual void set_grammar_id(uint32_t value);
-
virtual void set_protocol_version(const ProtocolVersion& protocol_version);
virtual ProtocolVersion protocol_version() const;
- bool AddFile(AppFile& file);
- bool UpdateFile(AppFile& file);
+ virtual void set_is_resuming(bool is_resuming);
+ virtual bool is_resuming() const;
+ bool AddFile(const AppFile& file);
+ bool UpdateFile(const AppFile& file);
bool DeleteFile(const std::string& file_name);
virtual const AppFilesMap& getAppFiles() const;
@@ -164,24 +172,29 @@ class ApplicationImpl : public virtual InitialApplicationDataImpl,
bool IsSubscribedToButton(mobile_apis::ButtonName::eType btn_name);
bool UnsubscribeFromButton(mobile_apis::ButtonName::eType btn_name);
- bool SubscribeToIVI(uint32_t vehicle_info_type_);
- bool IsSubscribedToIVI(uint32_t vehicle_info_type_);
- bool UnsubscribeFromIVI(uint32_t vehicle_info_type_);
+ bool SubscribeToIVI(uint32_t vehicle_info_type) OVERRIDE;
+ bool IsSubscribedToIVI(uint32_t vehicle_info_type) const OVERRIDE;
+ bool UnsubscribeFromIVI(uint32_t vehicle_info_type) OVERRIDE;
+ DataAccessor<VehicleInfoSubscriptions> SubscribedIVI() const OVERRIDE;
+ inline bool IsRegistered() const OVERRIDE;
/**
* @brief ResetDataInNone reset data counters in NONE
*/
virtual void ResetDataInNone();
- virtual const std::set<mobile_apis::ButtonName::eType>& SubscribedButtons() const;
- virtual const std::set<uint32_t>& SubscribesIVI() const;
+ virtual DataAccessor<ButtonSubscriptions> SubscribedButtons() const OVERRIDE;
virtual const std::string& curHash() const;
- /**
- * @brief Change Hash for current application
- * and send notification to mobile
- * @return updated_hash
- */
+#ifdef CUSTOMER_PASA
+ virtual bool flag_sending_hash_change_after_awake() const;
+ virtual void set_flag_sending_hash_change_after_awake(bool flag);
+#endif // CUSTOMER_PASA
+ /**
+ * @brief Change Hash for current application
+ * and send notification to mobile
+ * @return updated_hash
+ */
virtual void UpdateHash();
UsageStatistics& usage_report();
@@ -194,20 +207,36 @@ class ApplicationImpl : public virtual InitialApplicationDataImpl,
virtual void UnsubscribeFromSoftButtons(int32_t cmd_id);
+ virtual bool is_application_data_changed() const;
+
+ virtual void set_is_application_data_changed(bool state_application_data);
+
/**
- * @brief Check's if it is media, voice communication or navigation application
+ * @brief Check's if it is media, voice communication or navigation
+ * application
*
* @return true if application is media, voice communication or navigation
*/
virtual bool IsAudioApplication() const;
- /*
+ /**
* @brief SetRegularState set permanent state of application
+ *
* @param state state to setup
*/
virtual void SetRegularState(HmiStatePtr state);
/**
+ * @brief SetPostponedState sets postponed state to application.
+ * This state could be set as regular later
+ *
+ * @param state state to setup
+ */
+ virtual void SetPostponedState(HmiStatePtr state);
+
+ virtual void RemovePostponedState();
+
+ /**
* @brief AddHMIState the function that will change application's
* hmi state.
*
@@ -239,6 +268,14 @@ class ApplicationImpl : public virtual InitialApplicationDataImpl,
*/
virtual const HmiStatePtr RegularHmiState() const;
+ /**
+ * @brief PostponedHmiState returns postponed hmi state of application
+ * if it's present
+ *
+ * @return Postponed hmi state of application
+ */
+ virtual const HmiStatePtr PostponedHmiState() const;
+
uint32_t audio_stream_retry_number() const;
void set_audio_stream_retry_number(const uint32_t& audio_stream_retry_number);
@@ -247,21 +284,25 @@ class ApplicationImpl : public virtual InitialApplicationDataImpl,
void set_video_stream_retry_number(const uint32_t& video_stream_retry_number);
- protected:
+ /**
+ * @brief Load persistent files from application folder.
+ */
+ void LoadPersistentFiles() OVERRIDE;
/**
- * @brief Clean up application folder. Persistent files will stay
+ * @brief Get available app space
+ * @param name of the app folder(make + mobile app id)
+ * @return free app space.
*/
- void CleanupFiles();
+ uint32_t GetAvailableDiskSpace() OVERRIDE;
+ protected:
/**
- * @brief Load persistent files from application folder.
+ * @brief Clean up application folder. Persistent files will stay
*/
- void LoadPersistentFiles();
+ void CleanupFiles();
private:
- typedef SharedPtr<TimerThread<ApplicationImpl>> ApplicationTimerPtr;
-
/**
* @brief Callback for video streaming suspend timer.
* Suspends video streaming process for application
@@ -269,55 +310,68 @@ class ApplicationImpl : public virtual InitialApplicationDataImpl,
void OnVideoStreamSuspend();
/**
+ * @brief Stops video streaming for application
+ */
+ inline void StopNaviStreaming();
+
+ /**
+ * @brief Stops audio streaming for application
+ */
+ inline void StopAudioStreaming();
+
+ /**
* @brief Callback for audio streaming suspend timer.
* Suspends audio streaming process for application
*/
void OnAudioStreamSuspend();
- std::string hash_val_;
- uint32_t grammar_id_;
+ std::string hash_val_;
+ uint32_t grammar_id_;
Version version_;
- std::string app_name_;
- uint32_t hmi_app_id_;
- uint32_t app_id_;
- smart_objects::SmartObject* active_message_;
- bool is_media_;
- bool is_navi_;
-
- bool video_streaming_approved_;
- bool audio_streaming_approved_;
- bool video_streaming_allowed_;
- bool audio_streaming_allowed_;
- bool video_streaming_suspended_;
- bool audio_streaming_suspended_;
- sync_primitives::Lock video_streaming_suspended_lock_;
- sync_primitives::Lock audio_streaming_suspended_lock_;
-
- bool is_app_allowed_;
- bool has_been_activated_;
- bool tts_properties_in_none_;
- bool tts_properties_in_full_;
- bool is_foreground_;
- uint32_t put_file_in_none_count_;
- uint32_t delete_file_in_none_count_;
- uint32_t list_files_in_none_count_;
- std::string app_icon_path_;
- connection_handler::DeviceHandle device_;
-
- AppFilesMap app_files_;
+ custom_str::CustomString app_name_;
+ uint32_t hmi_app_id_;
+ uint32_t app_id_;
+ smart_objects::SmartObject* active_message_;
+ bool is_media_;
+ bool is_navi_;
+
+ bool video_streaming_approved_;
+ bool audio_streaming_approved_;
+ bool video_streaming_allowed_;
+ bool audio_streaming_allowed_;
+ bool video_streaming_suspended_;
+ bool audio_streaming_suspended_;
+ sync_primitives::Lock video_streaming_suspended_lock_;
+ sync_primitives::Lock audio_streaming_suspended_lock_;
+
+ bool is_app_allowed_;
+ bool has_been_activated_;
+ bool tts_properties_in_none_;
+ bool tts_properties_in_full_;
+ bool is_foreground_;
+ bool is_application_data_changed_;
+ uint32_t put_file_in_none_count_;
+ uint32_t delete_file_in_none_count_;
+ uint32_t list_files_in_none_count_;
+ std::string app_icon_path_;
+ connection_handler::DeviceHandle device_;
+ const std::string mac_address_;
+
+ AppFilesMap app_files_;
std::set<mobile_apis::ButtonName::eType> subscribed_buttons_;
- std::set<uint32_t> subscribed_vehicle_info_;
- UsageStatistics usage_report_;
- ProtocolVersion protocol_version_;
- bool is_voice_communication_application_;
-
- uint32_t video_stream_retry_number_;
- uint32_t audio_stream_retry_number_;
- uint32_t video_stream_suspend_timeout_;
- uint32_t audio_stream_suspend_timeout_;
- ApplicationTimerPtr video_stream_suspend_timer_;
- ApplicationTimerPtr audio_stream_suspend_timer_;
+ VehicleInfoSubscriptions subscribed_vehicle_info_;
+ UsageStatistics usage_report_;
+ ProtocolVersion protocol_version_;
+ bool is_voice_communication_application_;
+ sync_primitives::atomic_bool is_resuming_;
+
+ uint32_t video_stream_retry_number_;
+ uint32_t audio_stream_retry_number_;
+ uint32_t video_stream_suspend_timeout_;
+ uint32_t audio_stream_suspend_timeout_;
+ Timer video_stream_suspend_timer_;
+ Timer audio_stream_suspend_timer_;
/**
* @brief Defines number per time in seconds limits
@@ -328,17 +382,20 @@ class ApplicationImpl : public virtual InitialApplicationDataImpl,
* @brief Defines specific command number per time in seconds limits
*/
typedef std::map<mobile_apis::FunctionID::eType, TimeToNumberLimit>
- CommandNumberTimeLimit;
+ CommandNumberTimeLimit;
/**
* @brief Defines id of SoftButton which is related from name of command
*/
- typedef std::map<int32_t, SoftButtonID>
- CommandSoftButtonID;
+ typedef std::map<int32_t, SoftButtonID> CommandSoftButtonID;
CommandNumberTimeLimit cmd_number_to_time_limits_;
CommandSoftButtonID cmd_softbuttonid_;
// Lock for command soft button id
sync_primitives::Lock cmd_softbuttonid_lock_;
+ mutable sync_primitives::Lock vi_lock_;
+ sync_primitives::Lock button_lock_;
+ std::string folder_name_;
+ ApplicationManager& application_manager_;
DISALLOW_COPY_AND_ASSIGN(ApplicationImpl);
};
@@ -354,14 +411,18 @@ const mobile_api::AudioStreamingState::eType
ApplicationImpl::audio_streaming_state() const {
using namespace mobile_apis;
const HmiStatePtr hmi_state = CurrentHmiState();
- return hmi_state ? hmi_state->audio_streaming_state() :
- AudioStreamingState::INVALID_ENUM;
+ return hmi_state ? hmi_state->audio_streaming_state()
+ : AudioStreamingState::INVALID_ENUM;
}
bool ApplicationImpl::app_allowed() const {
return is_app_allowed_;
}
+bool ApplicationImpl::IsRegistered() const {
+ return app_state_ == kRegistered;
+}
+
} // namespace application_manager
#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_APPLICATION_IMPL_H_
diff --git a/src/components/application_manager/include/application_manager/application_manager.h b/src/components/application_manager/include/application_manager/application_manager.h
index b535b5b63d..97c38cd134 100644
--- a/src/components/application_manager/include/application_manager/application_manager.h
+++ b/src/components/application_manager/include/application_manager/application_manager.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -33,7 +33,28 @@
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_APPLICATION_MANAGER_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_APPLICATION_MANAGER_H_
+#include <string>
+#include <vector>
+#include <set>
+#include "vehicle_info_data.h"
#include "application_manager/application.h"
+#include "application_manager/hmi_capabilities.h"
+#include "application_manager/commands/command.h"
+#include "connection_handler/connection_handler.h"
+#include "utils/data_accessor.h"
+#include "utils/shared_ptr.h"
+#include "telemetry_monitor/telemetry_observable.h"
+#include "application_manager/policies/policy_handler_interface.h"
+#include "application_manager/application_manager_settings.h"
+#include "application_manager/state_controller.h"
+
+namespace resumption {
+class LastState;
+}
+
+namespace media_manager {
+class MediaManager;
+}
// Other compomnents class declaration
namespace hmi_message_handler {
@@ -45,19 +66,58 @@ class ProtocolHandler;
namespace connection_handler {
class ConnectionHandler;
}
+namespace resumption {
+class ResumeCtrl;
+}
namespace application_manager {
+namespace event_engine {
+class EventDispatcher;
+}
+
class Application;
+class StateControllerImpl;
+struct CommandParametersPermissions;
+typedef std::vector<std::string> RPCParams;
+
+struct ApplicationsAppIdSorter {
+ bool operator()(const ApplicationSharedPtr lhs,
+ const ApplicationSharedPtr rhs) const {
+ return lhs->app_id() < rhs->app_id();
+ }
+};
+
+struct ApplicationsPolicyAppIdSorter {
+ bool operator()(const ApplicationSharedPtr lhs,
+ const ApplicationSharedPtr rhs) {
+ if (lhs->policy_app_id() == rhs->policy_app_id()) {
+ return lhs->device() < rhs->device();
+ }
+ return lhs->policy_app_id() < rhs->policy_app_id();
+ }
+};
+
+typedef std::set<ApplicationSharedPtr, ApplicationsAppIdSorter> ApplicationSet;
+
+typedef std::set<ApplicationSharedPtr, ApplicationsPolicyAppIdSorter>
+ AppsWaitRegistrationSet;
+
+// typedef for Applications list iterator
+typedef ApplicationSet::iterator ApplicationSetIt;
+
+// typedef for Applications list const iterator
+typedef ApplicationSet::const_iterator ApplicationSetConstIt;
class ApplicationManager {
-public:
+ public:
virtual ~ApplicationManager() {}
/**
* Inits application manager
*/
- virtual bool Init() = 0;
+ virtual bool Init(resumption::LastState& last_state,
+ media_manager::MediaManager* media_manager) = 0;
/**
* @brief Stop work.
@@ -66,12 +126,164 @@ public:
**/
virtual bool Stop() = 0;
- virtual void
- set_hmi_message_handler(hmi_message_handler::HMIMessageHandler *handler) = 0;
- virtual void
- set_protocol_handler(protocol_handler::ProtocolHandler *handler) = 0;
- virtual void
- set_connection_handler(connection_handler::ConnectionHandler *handler) = 0;
+ virtual void set_hmi_message_handler(
+ hmi_message_handler::HMIMessageHandler* handler) = 0;
+ virtual void set_protocol_handler(
+ protocol_handler::ProtocolHandler* handler) = 0;
+ virtual void set_connection_handler(
+ connection_handler::ConnectionHandler* handler) = 0;
+
+ virtual DataAccessor<ApplicationSet> applications() const = 0;
+
+ virtual ApplicationSharedPtr application(uint32_t app_id) const = 0;
+ virtual ApplicationSharedPtr active_application() const = 0;
+
+ /**
+ * Function used only by HMI request/response/notification base classes
+ * to change HMI app id to Mobile app id and vice versa.
+ * Don't use it inside Core
+ */
+ virtual ApplicationSharedPtr application_by_hmi_app(
+ uint32_t hmi_app_id) const = 0;
+
+ virtual ApplicationSharedPtr application_by_policy_id(
+ const std::string& policy_app_id) const = 0;
+
+ virtual std::vector<ApplicationSharedPtr> applications_by_button(
+ uint32_t button) = 0;
+ virtual std::vector<ApplicationSharedPtr> applications_with_navi() = 0;
+
+ /**
+ * @brief Returns media application with LIMITED HMI Level if exists
+ *
+ * @return Shared pointer to application if application does not
+ * exist returns empty shared pointer.
+ */
+ virtual ApplicationSharedPtr get_limited_media_application() const = 0;
+
+ /**
+ * @brief Returns navigation application with LIMITED HMI Level if exists
+ *
+ * @return Shared pointer to application if application does not
+ * exist returns empty shared pointer
+ */
+ virtual ApplicationSharedPtr get_limited_navi_application() const = 0;
+
+ /**
+ * @brief Returns voice communication application with
+ * LIMITED HMI Level if exists
+ *
+ * @return Shared pointer to application if application does not
+ * exist returns empty shared pointer
+ */
+ virtual ApplicationSharedPtr get_limited_voice_application() const = 0;
+
+ /**
+ * @brief Retrieves application id associated with correlation id
+ *
+ * @param correlation_id Correlation ID of the HMI request
+ *
+ * @return application id associated with correlation id
+ */
+ virtual uint32_t application_id(const int32_t correlation_id) = 0;
+
+ /**
+ * @brief Sets application id correlation id
+ *
+ * @param correlation_id Correlation ID of the HMI request
+ * @param app_id Application ID
+ */
+ virtual void set_application_id(const int32_t correlation_id,
+ const uint32_t app_id) = 0;
+
+ /**
+ * @brief OnHMILevelChanged the callback that allows SDL to react when
+ * application's HMI level has been changed.
+ *
+ * @param app_id application identifier for which HMILevel has been chaned.
+ *
+ * @param from previous HMILevel.
+ * @param to current HMILevel.
+ */
+ virtual void OnHMILevelChanged(uint32_t app_id,
+ mobile_apis::HMILevel::eType from,
+ mobile_apis::HMILevel::eType to) = 0;
+
+ /**
+ * @brief Sends HMI status notification to mobile
+ *
+ * @param application_impl application with changed HMI status
+ *
+ **/
+ virtual void SendHMIStatusNotification(
+ const utils::SharedPtr<Application> app) = 0;
+
+ /**
+ * @brief Checks if Application is subscribed for way points
+ * @param Application AppID
+ * @return true if Application is subscribed for way points
+ * otherwise false
+ */
+ virtual bool IsAppSubscribedForWayPoints(const uint32_t app_id) const = 0;
+
+ /**
+ * @brief Subscribe Application for way points
+ * @param Application AppID
+ */
+ virtual void SubscribeAppForWayPoints(const uint32_t app_id) = 0;
+
+ /**
+ * @brief Unsubscribe Application for way points
+ * @param Application AppID
+ */
+ virtual void UnsubscribeAppFromWayPoints(const uint32_t app_id) = 0;
+
+ /**
+ * @brief Is Any Application is subscribed for way points
+ * @return true if some app is subscribed otherwise false
+ */
+ virtual bool IsAnyAppSubscribedForWayPoints() const = 0;
+
+ /**
+ * @brief Get subscribed for way points
+ * @return reference to set of subscribed apps for way points
+ */
+ virtual const std::set<int32_t> GetAppsSubscribedForWayPoints() const = 0;
+
+ virtual void SendMessageToMobile(const commands::MessageSharedPtr message,
+ bool final_message = false) = 0;
+
+ virtual void SendMessageToHMI(const commands::MessageSharedPtr message) = 0;
+
+ virtual bool ManageHMICommand(const commands::MessageSharedPtr message) = 0;
+ virtual bool ManageMobileCommand(const commands::MessageSharedPtr message,
+ commands::Command::CommandOrigin origin) = 0;
+ virtual mobile_api::HMILevel::eType GetDefaultHmiLevel(
+ ApplicationConstSharedPtr application) const = 0;
+ /**
+ * @brief hmi_capabilities return capabilities of hmi
+ * @return capabilities of hmi
+ */
+ virtual HMICapabilities& hmi_capabilities() = 0;
+
+ virtual const HMICapabilities& hmi_capabilities() const = 0;
+
+ virtual void ProcessQueryApp(const smart_objects::SmartObject& sm_object,
+ const uint32_t connection_key) = 0;
+
+ virtual bool is_attenuated_supported() const = 0;
+
+ /**
+ * @brief Checks if application with the same HMI type
+ * (media, voice communication or navi) exists
+ * in HMI_FULL or HMI_LIMITED level.
+ *
+ * @param app Pointer to application to compare with
+ *
+ * @return true if exist otherwise false
+ */
+ virtual bool IsAppTypeExistsInFullOrLimited(
+ ApplicationConstSharedPtr app) const = 0;
/**
* @brief Sets default HMI level and configure application after its
@@ -79,8 +291,290 @@ public:
* @param app Application
*/
virtual void OnApplicationRegistered(ApplicationSharedPtr app) = 0;
+
+ virtual connection_handler::ConnectionHandler& connection_handler() const = 0;
+ virtual protocol_handler::ProtocolHandler& protocol_handler() const = 0;
+ virtual policy::PolicyHandlerInterface& GetPolicyHandler() = 0;
+
+ virtual uint32_t GetNextHMICorrelationID() = 0;
+ virtual uint32_t GenerateNewHMIAppID() = 0;
+
+ /**
+ * @brief Ends opened navi services (audio/video) for application
+ * @param app_id Application id
+ */
+ virtual void EndNaviServices(uint32_t app_id) = 0;
+
+ /* @brief Starts audio passthru process
+ *
+ * @return true on success, false if passthru is already in process
+ */
+ virtual bool BeginAudioPassThrough() = 0;
+
+ /*
+ * @brief Finishes already started audio passthru process
+ *
+ * @return true on success, false if passthru is not active
+ */
+ virtual bool EndAudioPassThrough() = 0;
+
+ virtual void ConnectToDevice(const std::string& device_mac) = 0;
+
+ virtual void OnHMIStartedCooperation() = 0;
+
+ virtual bool IsHMICooperating() const = 0;
+ /**
+ * @brief Notifies all components interested in Vehicle Data update
+ * i.e. new value of odometer etc and returns list of applications
+ * subscribed for event.
+ * @param vehicle_info Enum value of type of vehicle data
+ * @param new value (for integer values currently) of vehicle data
+ */
+ virtual std::vector<ApplicationSharedPtr> IviInfoUpdated(
+ VehicleDataType vehicle_info, int value) = 0;
+
+ virtual ApplicationSharedPtr RegisterApplication(const utils::SharedPtr<
+ smart_objects::SmartObject>& request_for_registration) = 0;
+
+ virtual void SendUpdateAppList() = 0;
+
+ virtual void MarkAppsGreyOut(const connection_handler::DeviceHandle handle,
+ bool is_greyed_out) = 0;
+
+ /**
+ * @brief Returns pointer to application-to-be-registered (from QUERY_APP
+ * list)
+ * @param hmi_id HMI application id
+ * @return Pointer to application or uninitialized shared pointer
+ */
+ virtual ApplicationConstSharedPtr WaitingApplicationByID(
+ const uint32_t hmi_id) const = 0;
+
+ /**
+ * @brief Returns list of applications-to-be-registered (QUERY_APP list)
+ * @return Locked list of applications
+ */
+ virtual DataAccessor<AppsWaitRegistrationSet> AppsWaitingForRegistration()
+ const = 0;
+
+ virtual bool IsAppsQueriedFrom(
+ const connection_handler::DeviceHandle handle) const = 0;
+
+ virtual bool IsStopping() const = 0;
+
+ virtual void RemoveAppFromTTSGlobalPropertiesList(const uint32_t app_id) = 0;
+
+ virtual mobile_apis::Result::eType SaveBinary(
+ const std::vector<uint8_t>& binary_data,
+ const std::string& file_path,
+ const std::string& file_name,
+ const int64_t offset) = 0;
+ /*
+ * @brief Sets SDL access to all mobile apps
+ *
+ * @param allowed SDL access to all mobile apps
+ */
+ virtual void SetAllAppsAllowed(const bool allowed) = 0;
+
+ /*
+ * @brief Sets state for driver distraction
+ *
+ * @param state New state to be set
+ */
+ virtual void set_driver_distraction(bool is_distracting) = 0;
+
+ /*
+ * @brief Starts audio pass thru thread
+ *
+ * @param session_key Session key of connection for Mobile side
+ * @param correlation_id Correlation id for response for Mobile side
+ * @param max_duration Max duration of audio recording in milliseconds
+ * @param sampling_rate Value for rate(8, 16, 22, 44 kHz)
+ * @param bits_per_sample The quality the audio is recorded.
+ * @param audio_type Type of audio data
+ */
+ virtual void StartAudioPassThruThread(int32_t session_key,
+ int32_t correlation_id,
+ int32_t max_duration,
+ int32_t sampling_rate,
+ int32_t bits_per_sample,
+ int32_t audio_type) = 0;
+
+ virtual void StartDevicesDiscovery() = 0;
+
+ virtual void StopAudioPassThru(int32_t application_key) = 0;
+
+ /**
+ * @brief TerminateRequest forces termination of request
+ * @param connection_key - application id of request
+ * @param corr_id correlation id of request
+ */
+ virtual void TerminateRequest(uint32_t connection_key, uint32_t corr_id) = 0;
+
+ /*
+ * @brief Closes application by id
+ *
+ * @param app_id Application id
+ * @param reason reason of unregistering application
+ * @param is_resuming describes - is this unregister
+ * is normal or need to be resumed\
+ * @param is_unexpected_disconnect
+ * Indicates if connection was unexpectedly lost(TM layer, HB)
+ */
+ virtual void UnregisterApplication(const uint32_t& app_id,
+ mobile_apis::Result::eType reason,
+ bool is_resuming = false,
+ bool is_unexpected_disconnect = false) = 0;
+
+ /**
+ * @ Updates request timeout
+ *
+ * @param connection_key Connection key of application
+ * @param mobile_correlation_id Correlation ID of the mobile request
+ * @param new_timeout_value New timeout in milliseconds to be set
+ */
+ virtual void updateRequestTimeout(uint32_t connection_key,
+ uint32_t mobile_correlation_id,
+ uint32_t new_timeout_value) = 0;
+
+ virtual StateController& state_controller() = 0;
+
+ virtual void SetUnregisterAllApplicationsReason(
+ mobile_api::AppInterfaceUnregisteredReason::eType reason) = 0;
+
+ /*
+ * @brief Called on Master_reset or Factory_defaults
+ * when User chooses to reset HU.
+ * Resets Policy Table if applicable.
+ */
+ virtual void HeadUnitReset(
+ mobile_api::AppInterfaceUnregisteredReason::eType reason) = 0;
+
+ /**
+ * @brief Checks HMI level and returns true if streaming is allowed
+ * @param app_id Application id
+ * @param service_type Service type to check
+ * @return True if streaming is allowed, false in other case
+ */
+ virtual bool HMILevelAllowsStreaming(
+ uint32_t app_id, protocol_handler::ServiceType service_type) const = 0;
+
+ /**
+ * @brief Checks, if given RPC is allowed at current HMI level for specific
+ * application in policy table
+ * @param policy_app_id Application id
+ * @param hmi_level Current HMI level of application
+ * @param function_id FunctionID of RPC
+ * @param params_permissions Permissions for RPC parameters (e.g.
+ * SubscribeVehicleData) defined in policy table
+ * @return SUCCESS, if allowed, otherwise result code of check
+ */
+ virtual mobile_apis::Result::eType CheckPolicyPermissions(
+ const std::string& policy_app_id,
+ mobile_apis::HMILevel::eType hmi_level,
+ mobile_apis::FunctionID::eType function_id,
+ const RPCParams& rpc_params,
+ CommandParametersPermissions* params_permissions = NULL) = 0;
+
+ /**
+ * @brief IsApplicationForbidden allows to distinguish if application is
+ * not allowed to register, because of spamming.
+ *
+ * @param connection_key the connection key ofthe required application
+ *
+ * @param policy_app_id application's mobile(policy) identifier.
+ *
+ * @return true in case application is allowed to register, false otherwise.
+ */
+ virtual bool IsApplicationForbidden(
+ uint32_t connection_key, const std::string& policy_app_id) const = 0;
+
+ virtual resumption::ResumeCtrl& resume_controller() = 0;
+ /*
+ * @brief Converts connection string transport type representation
+ * to HMI Common_TransportType
+ *
+ * @param transport_type String representing connection type
+ *
+ * @return Corresponding HMI TransporType value
+ */
+ virtual hmi_apis::Common_TransportType::eType GetDeviceTransportType(
+ const std::string& transport_type) = 0;
+
+ /**
+ * @brief method adds application
+ * to tts_global_properties_app_list_
+ * @param app_id contains application which will
+ * send TTS global properties after timeout
+ */
+ virtual void AddAppToTTSGlobalPropertiesList(const uint32_t app_id) = 0;
+
+ /**
+ * Generate grammar ID
+ *
+ * @return New grammar ID
+ */
+ virtual uint32_t GenerateGrammarID() = 0;
+
+ virtual policy::DeviceConsent GetUserConsentForDevice(
+ const std::string& device_id) const = 0;
+
+ /**
+ * @brief Handle sequence for unauthorized application
+ * @param app_id Application id
+ */
+ virtual void OnAppUnauthorized(const uint32_t& app_id) = 0;
+
+ virtual bool ActivateApplication(ApplicationSharedPtr app) = 0;
+
+ /**
+ * @brief Callback calls when application starts/stops data streaming
+ * @param app_id Streaming application id
+ * @param service_type Streaming service type
+ * @param state Shows if streaming started or stopped
+ */
+ virtual void OnAppStreaming(uint32_t app_id,
+ protocol_handler::ServiceType service_type,
+ bool state) = 0;
+
+ /**
+ * @brief CreateRegularState create regular HMI state for application
+ * @param app_id
+ * @param hmi_level of returned state
+ * @param audio_state of returned state
+ * @param system_context of returned state
+ * @return new regular HMI state
+ */
+ virtual HmiStatePtr CreateRegularState(
+ uint32_t app_id,
+ mobile_apis::HMILevel::eType hmi_level,
+ mobile_apis::AudioStreamingState::eType audio_state,
+ mobile_apis::SystemContext::eType system_context) const = 0;
+
+ virtual void SendAudioPassThroughNotification(
+ uint32_t session_key, std::vector<uint8_t>& binary_data) = 0;
+
+ /**
+ * @brief Checks if application can stream (streaming service is started and
+ * streaming is enabled in application)
+ * @param app_id Application id
+ * @param service_type Service type to check
+ * @return True if streaming is allowed, false in other case
+ */
+ virtual bool CanAppStream(
+ uint32_t app_id, protocol_handler::ServiceType service_type) const = 0;
+
+ /**
+ * @brief ForbidStreaming forbid the stream over the certain application.
+ * @param app_id the application's id which should stop streaming.
+ */
+ virtual void ForbidStreaming(uint32_t app_id) = 0;
+
+ virtual const ApplicationManagerSettings& get_settings() const = 0;
+
+ virtual event_engine::EventDispatcher& event_dispatcher() = 0;
};
-} // namespace application_manager
+} // namespace application_manager
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_APPLICATION_MANAGER_H_
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_APPLICATION_MANAGER_H_
diff --git a/src/components/application_manager/include/application_manager/application_manager_impl.h b/src/components/application_manager/include/application_manager/application_manager_impl.h
index a5b9833954..dda192f8b0 100644
--- a/src/components/application_manager/include/application_manager/application_manager_impl.h
+++ b/src/components/application_manager/include/application_manager/application_manager_impl.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -46,19 +46,22 @@
#include "application_manager/message.h"
#include "application_manager/message_helper.h"
#include "application_manager/request_controller.h"
-#include "application_manager/resume_ctrl.h"
+#include "application_manager/resumption/resume_ctrl.h"
#include "application_manager/vehicle_info_data.h"
-#include "application_manager/state_controller.h"
+#include "application_manager/state_controller_impl.h"
+#include "application_manager/application_manager_settings.h"
+#include "application_manager/event_engine/event_dispatcher_impl.h"
+
#include "protocol_handler/protocol_observer.h"
#include "protocol_handler/protocol_handler.h"
#include "hmi_message_handler/hmi_message_observer.h"
#include "hmi_message_handler/hmi_message_sender.h"
#include "application_manager/policies/policy_handler_observer.h"
-#include "media_manager/media_manager_impl.h"
#include "connection_handler/connection_handler.h"
#include "connection_handler/connection_handler_observer.h"
#include "connection_handler/device.h"
-#include "formatters/CSmartFactory.hpp"
+#include "formatters/CSmartFactory.h"
+#include "policies/policy_handler.h"
#include "interfaces/HMI_API.h"
#include "interfaces/HMI_API_schema.h"
@@ -66,9 +69,15 @@
#include "interfaces/v4_protocol_v1_2_no_extra.h"
#include "interfaces/v4_protocol_v1_2_no_extra_schema.h"
-#ifdef TIME_TESTER
-#include "time_metric_observer.h"
-#endif // TIME_TESTER
+
+#ifdef ENABLE_SECURITY
+#include "security_manager/security_manager_listener.h"
+#include "security_manager/ssl_context.h"
+#endif // ENABLE_SECURITY
+
+#ifdef TELEMETRY_MONITOR
+#include "telemetry_observer.h"
+#endif // TELEMETRY_MONITOR
#include "utils/macro.h"
#include "utils/shared_ptr.h"
@@ -77,8 +86,8 @@
#include "utils/threads/thread.h"
#include "utils/threads/message_loop_thread.h"
#include "utils/lock.h"
-#include "utils/singleton.h"
#include "utils/data_accessor.h"
+#include "utils/timer.h"
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
@@ -96,12 +105,15 @@ namespace application_manager {
namespace mobile_api = mobile_apis;
using namespace utils;
using namespace timer;
+namespace custom_str = custom_string;
class ApplicationManagerImpl;
enum VRTTSSessionChanging { kVRSessionChanging = 0, kTTSSessionChanging };
struct CommandParametersPermissions;
+typedef std::map<std::string, hmi_apis::Common_TransportType::eType>
+ DeviceTypes;
namespace impl {
using namespace threads;
@@ -117,44 +129,56 @@ using namespace threads;
* when we have them.
*/
struct MessageFromMobile : public utils::SharedPtr<Message> {
- explicit MessageFromMobile(const utils::SharedPtr<Message> &message)
+ MessageFromMobile() {}
+ explicit MessageFromMobile(const utils::SharedPtr<Message>& message)
: utils::SharedPtr<Message>(message) {}
// PrioritizedQueue requres this method to decide which priority to assign
- size_t PriorityOrder() const { return (*this)->Priority().OrderingValue(); }
+ size_t PriorityOrder() const {
+ return (*this)->Priority().OrderingValue();
+ }
};
struct MessageToMobile : public utils::SharedPtr<Message> {
- explicit MessageToMobile(const utils::SharedPtr<Message> &message,
+ MessageToMobile() : is_final(false) {}
+ explicit MessageToMobile(const utils::SharedPtr<Message>& message,
bool final_message)
: utils::SharedPtr<Message>(message), is_final(final_message) {}
// PrioritizedQueue requres this method to decide which priority to assign
- size_t PriorityOrder() const { return (*this)->Priority().OrderingValue(); }
+ size_t PriorityOrder() const {
+ return (*this)->Priority().OrderingValue();
+ }
// Signals if connection to mobile must be closed after sending this message
bool is_final;
};
struct MessageFromHmi : public utils::SharedPtr<Message> {
- explicit MessageFromHmi(const utils::SharedPtr<Message> &message)
+ MessageFromHmi() {}
+ explicit MessageFromHmi(const utils::SharedPtr<Message>& message)
: utils::SharedPtr<Message>(message) {}
// PrioritizedQueue requres this method to decide which priority to assign
- size_t PriorityOrder() const { return (*this)->Priority().OrderingValue(); }
+ size_t PriorityOrder() const {
+ return (*this)->Priority().OrderingValue();
+ }
};
struct MessageToHmi : public utils::SharedPtr<Message> {
- explicit MessageToHmi(const utils::SharedPtr<Message> &message)
+ MessageToHmi() {}
+ explicit MessageToHmi(const utils::SharedPtr<Message>& message)
: utils::SharedPtr<Message>(message) {}
// PrioritizedQueue requres this method to decide which priority to assign
- size_t PriorityOrder() const { return (*this)->Priority().OrderingValue(); }
+ size_t PriorityOrder() const {
+ return (*this)->Priority().OrderingValue();
+ }
};
// Short type names for prioritized message queues
-typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageFromMobile>>
+typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageFromMobile> >
FromMobileQueue;
-typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageToMobile>>
+typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageToMobile> >
ToMobileQueue;
-typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageFromHmi>>
+typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageFromHmi> >
FromHmiQueue;
-typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageToHmi>>
+typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageToHmi> >
ToHmiQueue;
// AudioPassThru
@@ -165,8 +189,9 @@ typedef struct {
typedef std::queue<AudioData> RawAudioDataQueue;
typedef threads::MessageLoopThread<RawAudioDataQueue> AudioPassThruQueue;
}
-
+CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationManager")
typedef std::vector<std::string> RPCParams;
+typedef utils::SharedPtr<timer::Timer> TimerSPtr;
class ApplicationManagerImpl
: public ApplicationManager,
@@ -174,66 +199,69 @@ class ApplicationManagerImpl
public protocol_handler::ProtocolObserver,
public connection_handler::ConnectionHandlerObserver,
public policy::PolicyHandlerObserver,
+#ifdef ENABLE_SECURITY
+ public security_manager::SecurityManagerListener,
+#endif // ENABLE_SECURITY
public impl::FromMobileQueue::Handler,
public impl::ToMobileQueue::Handler,
public impl::FromHmiQueue::Handler,
public impl::ToHmiQueue::Handler,
- public impl::AudioPassThruQueue::Handler,
- public utils::Singleton<ApplicationManagerImpl> {
+ public impl::AudioPassThruQueue::Handler
+#ifdef TELEMETRY_MONITOR
+ ,
+ public telemetry_monitor::TelemetryObservable<AMTelemetryObserver>
+#endif // TELEMETRY_MONITOR
+ {
friend class ResumeCtrl;
friend class CommandImpl;
-public:
+ public:
+ ApplicationManagerImpl(const ApplicationManagerSettings& am_settings,
+ const policy::PolicySettings& policy_settings);
~ApplicationManagerImpl();
/**
* Inits application manager
*/
- virtual bool Init();
+ bool Init(resumption::LastState& last_state,
+ media_manager::MediaManager* media_manager) OVERRIDE;
/**
* @brief Stop work.
*
* @return TRUE on success otherwise FALSE.
**/
- virtual bool Stop();
+ bool Stop() OVERRIDE;
- /////////////////////////////////////////////////////
+ DataAccessor<ApplicationSet> applications() const OVERRIDE;
+ ApplicationSharedPtr application(uint32_t app_id) const OVERRIDE;
- ApplicationSharedPtr application(uint32_t app_id) const;
- ApplicationSharedPtr
- application_by_policy_id(const std::string &policy_app_id) const;
- ApplicationSharedPtr active_application() const;
- std::vector<ApplicationSharedPtr> applications_by_button(uint32_t button);
- std::vector<ApplicationSharedPtr> applications_by_ivi(uint32_t vehicle_info);
- std::vector<ApplicationSharedPtr> applications_with_navi();
+ ApplicationSharedPtr active_application() const OVERRIDE;
- /**
- * @brief Returns media application with LIMITED HMI Level if exist.
- *
- * @return Shared pointer to application if application does not
- * exist returns empty shared pointer.
- */
- ApplicationSharedPtr get_limited_media_application() const;
+ ApplicationSharedPtr application_by_hmi_app(
+ uint32_t hmi_app_id) const OVERRIDE;
+ ApplicationSharedPtr application_by_policy_id(
+ const std::string& policy_app_id) const OVERRIDE;
- /**
- * @brief Returns navigation application with LIMITED HMI Level if exist.
- *
- * @return Shared pointer to application if application does not
- * exist returns empty shared pointer
- */
- ApplicationSharedPtr get_limited_navi_application() const;
+ std::vector<ApplicationSharedPtr> applications_by_button(
+ uint32_t button) OVERRIDE;
+ std::vector<ApplicationSharedPtr> applications_with_navi() OVERRIDE;
- /**
- * @brief Returns voice communication application with LIMITED HMI Level if
- *exist.
- *
- * @return Shared pointer to application if application does not
- * exist returns empty shared pointer
- */
- ApplicationSharedPtr get_limited_voice_application() const;
+ ApplicationSharedPtr get_limited_media_application() const OVERRIDE;
+ ApplicationSharedPtr get_limited_navi_application() const OVERRIDE;
+ ApplicationSharedPtr get_limited_voice_application() const OVERRIDE;
+
+ uint32_t application_id(const int32_t correlation_id) OVERRIDE;
+ void set_application_id(const int32_t correlation_id,
+ const uint32_t app_id) OVERRIDE;
+ void OnHMILevelChanged(uint32_t app_id,
+ mobile_apis::HMILevel::eType from,
+ mobile_apis::HMILevel::eType to) OVERRIDE;
+
+ void SendHMIStatusNotification(
+ const utils::SharedPtr<Application> app) OVERRIDE;
/**
* @brief Checks if application with the same HMI type
* (media, voice communication or navi) exists
@@ -243,7 +271,39 @@ public:
*
* @return true if exist otherwise false
*/
- bool IsAppTypeExistsInFullOrLimited(ApplicationSharedPtr app) const;
+ bool IsAppTypeExistsInFullOrLimited(ApplicationConstSharedPtr app) const;
+
+ /**
+ * @brief Checks if Application is subscribed for way points
+ * @param Application AppID
+ * @return true if Application is subscribed for way points
+ * otherwise false
+ */
+ bool IsAppSubscribedForWayPoints(const uint32_t app_id) const OVERRIDE;
+
+ /**
+ * @brief Subscribe Application for way points
+ * @param Application AppID
+ */
+ void SubscribeAppForWayPoints(const uint32_t app_id) OVERRIDE;
+
+ /**
+ * @brief Unsubscribe Application for way points
+ * @param Application AppID
+ */
+ void UnsubscribeAppFromWayPoints(const uint32_t app_id) OVERRIDE;
+
+ /**
+ * @brief Is Any Application is subscribed for way points
+ * @return true if some app is subscribed otherwise false
+ */
+ bool IsAnyAppSubscribedForWayPoints() const OVERRIDE;
+
+ /**
+ * @brief Get subscribed for way points
+ * @return reference to set of subscribed apps for way points
+ */
+ const std::set<int32_t> GetAppsSubscribedForWayPoints() const OVERRIDE;
/**
* @brief Notifies all components interested in Vehicle Data update
@@ -253,13 +313,12 @@ public:
* @param new value (for integer values currently) of vehicle data
*/
std::vector<ApplicationSharedPtr> IviInfoUpdated(VehicleDataType vehicle_info,
- int value);
+ int value) OVERRIDE;
void OnApplicationRegistered(ApplicationSharedPtr app) OVERRIDE;
- /////////////////////////////////////////////////////
-
- HMICapabilities &hmi_capabilities();
+ HMICapabilities& hmi_capabilities();
+ const HMICapabilities& hmi_capabilities() const;
/**
* @brief ProcessQueryApp executes logic related to QUERY_APP system request.
@@ -268,21 +327,22 @@ public:
* system request.
* @param connection_key connection key for app, which sent system request
*/
- void ProcessQueryApp(const smart_objects::SmartObject &sm_object,
- const uint32_t connection_key);
+ void ProcessQueryApp(const smart_objects::SmartObject& sm_object,
+ const uint32_t connection_key) OVERRIDE;
-#ifdef TIME_TESTER
+ bool is_attenuated_supported() const OVERRIDE;
+
+#ifdef TELEMETRY_MONITOR
/**
* @brief Setup observer for time metric.
*
* @param observer - pointer to observer
*/
- void SetTimeMetricObserver(AMMetricObserver *observer);
-#endif // TIME_TESTER
+ void SetTelemetryObserver(AMTelemetryObserver* observer) OVERRIDE;
+#endif // TELEMETRY_MONITOR
- ApplicationSharedPtr
- RegisterApplication(const utils::SharedPtr<smart_objects::SmartObject> &
- request_for_registration);
+ ApplicationSharedPtr RegisterApplication(const utils::SharedPtr<
+ smart_objects::SmartObject>& request_for_registration) OVERRIDE;
/*
* @brief Closes application by id
*
@@ -293,16 +353,16 @@ public:
* @param is_unexpected_disconnect
* Indicates if connection was unexpectedly lost(TM layer, HB)
*/
- void UnregisterApplication(const uint32_t &app_id,
+ void UnregisterApplication(const uint32_t& app_id,
mobile_apis::Result::eType reason,
bool is_resuming = false,
- bool is_unexpected_disconnect = false);
+ bool is_unexpected_disconnect = false) OVERRIDE;
/**
* @brief Handle sequence for unauthorized application
* @param app_id Application id
*/
- void OnAppUnauthorized(const uint32_t &app_id);
+ void OnAppUnauthorized(const uint32_t& app_id) OVERRIDE;
/*
* @brief Sets unregister reason for closing all registered applications
@@ -311,14 +371,15 @@ public:
* @param reason Describes the reason for HU switching off
*/
void SetUnregisterAllApplicationsReason(
- mobile_api::AppInterfaceUnregisteredReason::eType reason);
+ mobile_api::AppInterfaceUnregisteredReason::eType reason) OVERRIDE;
/*
* @brief Called on Master_reset or Factory_defaults
* when User chooses to reset HU.
* Resets Policy Table if applicable.
*/
- void HeadUnitReset(mobile_api::AppInterfaceUnregisteredReason::eType reason);
+ void HeadUnitReset(
+ mobile_api::AppInterfaceUnregisteredReason::eType reason) OVERRIDE;
/*
* @brief Closes all registered applications
@@ -327,7 +388,7 @@ public:
bool RemoveAppDataFromHMI(ApplicationSharedPtr app);
bool LoadAppDataToHMI(ApplicationSharedPtr app);
- bool ActivateApplication(ApplicationSharedPtr app);
+ bool ActivateApplication(ApplicationSharedPtr app) OVERRIDE;
/**
* @brief Put application in FULL HMI Level if possible,
@@ -338,28 +399,28 @@ public:
*/
mobile_api::HMILevel::eType IsHmiLevelFullAllowed(ApplicationSharedPtr app);
- void ConnectToDevice(const std::string &device_mac);
- void OnHMIStartedCooperation();
+ void ConnectToDevice(const std::string& device_mac) OVERRIDE;
+ void OnHMIStartedCooperation() OVERRIDE;
/*
* @brief Returns unique correlation ID for HMI request
*
* @return Unique correlation ID
*/
- uint32_t GetNextHMICorrelationID();
+ uint32_t GetNextHMICorrelationID() OVERRIDE;
/* @brief Starts audio passthru process
*
* @return true on success, false if passthru is already in process
*/
- bool begin_audio_pass_thru();
+ bool BeginAudioPassThrough() OVERRIDE;
/*
* @brief Finishes already started audio passthru process
*
* @return true on success, false if passthru is not active
*/
- bool end_audio_pass_thru();
+ bool EndAudioPassThrough() OVERRIDE;
/*
* @brief Retrieves driver distraction state
@@ -373,7 +434,7 @@ public:
*
* @param state New state to be set
*/
- void set_driver_distraction(bool is_distracting);
+ void set_driver_distraction(const bool is_distracting) OVERRIDE;
/*
* @brief Retrieves if VR session has started
@@ -387,7 +448,7 @@ public:
*
* @param state Current HMI VR session state
*/
- void set_vr_session_started(const bool &state);
+ void set_vr_session_started(const bool state);
/*
* @brief Retrieves SDL access to all mobile apps
@@ -401,7 +462,7 @@ public:
*
* @param allowed SDL access to all mobile apps
*/
- void set_all_apps_allowed(const bool &allowed);
+ void SetAllAppsAllowed(const bool allowed) OVERRIDE;
/**
* @brief CreateRegularState create regular HMI state for application
@@ -411,10 +472,11 @@ public:
* @param system_context of returned state
* @return new regular HMI state
*/
- HmiStatePtr
- CreateRegularState(uint32_t app_id, mobile_apis::HMILevel::eType hmi_level,
- mobile_apis::AudioStreamingState::eType audio_state,
- mobile_apis::SystemContext::eType system_context) const;
+ HmiStatePtr CreateRegularState(
+ uint32_t app_id,
+ mobile_apis::HMILevel::eType hmi_level,
+ mobile_apis::AudioStreamingState::eType audio_state,
+ mobile_apis::SystemContext::eType system_context) const OVERRIDE;
/**
* @brief SetState set regular audio state
@@ -425,15 +487,15 @@ public:
mobile_apis::AudioStreamingState::eType audio_state) {
ApplicationSharedPtr app = application(app_id);
if (!app) {
- LOG4CXX_ERROR(logger_, "Application with appID=" << app_id
- << " does not exist");
+ LOG4CXX_ERROR(logger_,
+ "Application with appID=" << app_id << " does not exist");
return;
}
state_ctrl_.SetRegularState(app, audio_state);
}
/**
- * @brief SetState setup regular hmi state, tha will appear if no
+ * @brief SetState setup regular hmi state, that will appear if no
* specific events are active
* @param app appication to setup regular State
* @param state state of new regular state
@@ -442,11 +504,11 @@ public:
void SetState(uint32_t app_id, HmiStatePtr new_state) {
ApplicationSharedPtr app = application(app_id);
if (!app) {
- LOG4CXX_ERROR(logger_, "Application with appID=" << app_id
- << " does not exist");
+ LOG4CXX_ERROR(logger_,
+ "Application with appID=" << app_id << " does not exist");
return;
}
- state_ctrl_.SetRegularState<SendActivateApp>(app, new_state);
+ state_ctrl_.SetRegularState(app, new_state, SendActivateApp);
}
/**
@@ -458,11 +520,11 @@ public:
void SetState(uint32_t app_id, mobile_apis::HMILevel::eType hmi_level) {
ApplicationSharedPtr app = application(app_id);
if (!app) {
- LOG4CXX_ERROR(logger_, "Application with appID=" << app_id
- << " does not exist");
+ LOG4CXX_ERROR(logger_,
+ "Application with appID=" << app_id << " does not exist");
return;
}
- state_ctrl_.SetRegularState<SendActivateApp>(app, hmi_level);
+ state_ctrl_.SetRegularState(app, hmi_level, SendActivateApp);
}
/**
@@ -473,15 +535,16 @@ public:
* @param SendActivateApp: if true, ActivateAppRequest will be sent on HMI
*/
template <bool SendActivateApp>
- void SetState(uint32_t app_id, mobile_apis::HMILevel::eType hmi_level,
+ void SetState(uint32_t app_id,
+ mobile_apis::HMILevel::eType hmi_level,
mobile_apis::AudioStreamingState::eType audio_state) {
ApplicationSharedPtr app = application(app_id);
if (!app) {
- LOG4CXX_ERROR(logger_, "Application with appID=" << app_id
- << " does not exist");
+ LOG4CXX_ERROR(logger_,
+ "Application with appID=" << app_id << " does not exist");
return;
}
- state_ctrl_.SetRegularState<SendActivateApp>(app, hmi_level, audio_state);
+ state_ctrl_.SetRegularState(app, hmi_level, audio_state, SendActivateApp);
}
/**
@@ -492,17 +555,18 @@ public:
* @param SendActivateApp: if true, ActivateAppRequest will be sent on HMI
*/
template <bool SendActivateApp>
- void SetState(uint32_t app_id, mobile_apis::HMILevel::eType hmi_level,
+ void SetState(uint32_t app_id,
+ mobile_apis::HMILevel::eType hmi_level,
mobile_apis::AudioStreamingState::eType audio_state,
mobile_apis::SystemContext::eType system_context) {
ApplicationSharedPtr app = application(app_id);
if (!app) {
- LOG4CXX_ERROR(logger_, "Application with appID=" << app_id
- << " does not exist");
+ LOG4CXX_ERROR(logger_,
+ "Application with appID=" << app_id << " does not exist");
return;
}
- state_ctrl_.SetRegularState<SendActivateApp>(app, hmi_level, audio_state,
- system_context);
+ state_ctrl_.SetRegularState(
+ app, hmi_level, audio_state, system_context, SendActivateApp);
}
/**
@@ -514,14 +578,51 @@ public:
mobile_apis::SystemContext::eType system_context) {
ApplicationSharedPtr app = application(app_id);
if (!app) {
- LOG4CXX_ERROR(logger_, "Application with appID=" << app_id
- << " does not exist");
+ LOG4CXX_ERROR(logger_,
+ "Application with appID=" << app_id << " does not exist");
return;
}
state_ctrl_.SetRegularState(app, system_context);
}
/**
+ * @brief SetState Change regular hmi level
+ * @param app appication to setup regular State
+ * @param hmi_level hmi level of new regular state
+ */
+ void SetHmiState(uint32_t app_id, mobile_apis::HMILevel::eType hmi_level) {
+ ApplicationSharedPtr app = application(app_id);
+ if (!app) {
+ LOG4CXX_ERROR(logger_,
+ "Application with appID=" << app_id << " does not exist");
+ return;
+ }
+ state_ctrl_.SetRegularState(app, hmi_level);
+ }
+
+ /**
+ * @brief SetState Change regular hmi state
+ * @param app appication to setup regular State
+ * @param state new regular hmi state
+ */
+ void SetState(uint32_t app_id, HmiStatePtr state) {
+ ApplicationSharedPtr app = application(app_id);
+ if (!app) {
+ LOG4CXX_ERROR(logger_,
+ "Application with appID=" << app_id << " does not exist");
+ return;
+ }
+ state_ctrl_.SetRegularState(app, state);
+ }
+
+ /**
+ * @brief Checks, if particular state is active
+ * @param state_id State
+ * @return True, if state is active, otherwise - false
+ */
+ bool IsStateActive(HmiState::StateID state_id) const;
+
+ /**
* @brief Notification from PolicyHandler about PTU.
* Compares AppHMIType between saved in app and received from PTU. If they are
* different method sends:
@@ -533,8 +634,8 @@ public:
* UI_ChangeRegistration with list new AppHMIType
* for app with HMI level BACKGROUND.
*/
- virtual void OnUpdateHMIAppType(
- std::map<std::string, std::vector<std::string>> app_hmi_types);
+ void OnUpdateHMIAppType(
+ std::map<std::string, std::vector<std::string> > app_hmi_types) OVERRIDE;
/*
* @brief Starts audio pass thru thread
@@ -546,16 +647,19 @@ public:
* @param bits_per_sample The quality the audio is recorded.
* @param audio_type Type of audio data
*/
- void StartAudioPassThruThread(int32_t session_key, int32_t correlation_id,
- int32_t max_duration, int32_t sampling_rate,
- int32_t bits_per_sample, int32_t audio_type);
+ void StartAudioPassThruThread(int32_t session_key,
+ int32_t correlation_id,
+ int32_t max_duration,
+ int32_t sampling_rate,
+ int32_t bits_per_sample,
+ int32_t audio_type) OVERRIDE;
/*
* @brief Terminates audio pass thru thread
* @param application_key Id of application for which
* audio pass thru should be stopped
*/
- void StopAudioPassThru(int32_t application_key);
+ void StopAudioPassThru(int32_t application_key) OVERRIDE;
/*
* @brief Creates AudioPassThru data chunk and inserts it
@@ -566,8 +670,8 @@ public:
*
* @param binary_data AudioPassThru data chunk
*/
- void SendAudioPassThroughNotification(uint32_t session_key,
- std::vector<uint8_t> &binary_data);
+ void SendAudioPassThroughNotification(
+ uint32_t session_key, std::vector<uint8_t>& binary_data) OVERRIDE;
std::string GetDeviceName(connection_handler::DeviceHandle handle);
@@ -579,16 +683,12 @@ public:
*
* @return Corresponding HMI TransporType value
*/
- hmi_apis::Common_TransportType::eType
- GetDeviceTransportType(const std::string &transport_type);
-
- /////////////////////////////////////////////////////
-
- void set_hmi_message_handler(hmi_message_handler::HMIMessageHandler *handler);
- void set_connection_handler(connection_handler::ConnectionHandler *handler);
- void set_protocol_handler(protocol_handler::ProtocolHandler *handler);
+ hmi_apis::Common_TransportType::eType GetDeviceTransportType(
+ const std::string& transport_type);
- ///////////////////////////////////////////////////////
+ void set_hmi_message_handler(hmi_message_handler::HMIMessageHandler* handler);
+ void set_connection_handler(connection_handler::ConnectionHandler* handler);
+ void set_protocol_handler(protocol_handler::ProtocolHandler* handler);
void StartDevicesDiscovery();
@@ -596,48 +696,58 @@ public:
// if |final_message| parameter is set connection to mobile will be closed
// after processing this message
void SendMessageToMobile(const commands::MessageSharedPtr message,
- bool final_message = false);
+ bool final_message = false) OVERRIDE;
+
+ void SendMessageToHMI(const commands::MessageSharedPtr message) OVERRIDE;
+
+ bool ManageMobileCommand(const commands::MessageSharedPtr message,
+ commands::Command::CommandOrigin origin) OVERRIDE;
+ bool ManageHMICommand(const commands::MessageSharedPtr message) OVERRIDE;
/**
* @brief TerminateRequest forces termination of request
* @param connection_key - application id of request
* @param corr_id correlation id of request
*/
- void TerminateRequest(uint32_t connection_key, uint32_t corr_id);
-
- bool ManageMobileCommand(
- const commands::MessageSharedPtr message,
- commands::Command::CommandOrigin origin = commands::Command::ORIGIN_SDL);
- void SendMessageToHMI(const commands::MessageSharedPtr message);
- bool ManageHMICommand(const commands::MessageSharedPtr message);
-
- /////////////////////////////////////////////////////////
+ void TerminateRequest(uint32_t connection_key, uint32_t corr_id) OVERRIDE;
// Overriden ProtocolObserver method
- virtual void
- OnMessageReceived(const ::protocol_handler::RawMessagePtr message) OVERRIDE;
- virtual void
- OnMobileMessageSent(const ::protocol_handler::RawMessagePtr message) OVERRIDE;
+ void OnMessageReceived(
+ const ::protocol_handler::RawMessagePtr message) OVERRIDE;
+ void OnMobileMessageSent(
+ const ::protocol_handler::RawMessagePtr message) OVERRIDE;
// Overriden HMIMessageObserver method
- void
- OnMessageReceived(hmi_message_handler::MessageSharedPointer message) OVERRIDE;
- void
- OnErrorSending(hmi_message_handler::MessageSharedPointer message) OVERRIDE;
+ void OnMessageReceived(
+ hmi_message_handler::MessageSharedPointer message) OVERRIDE;
+ void OnErrorSending(
+ hmi_message_handler::MessageSharedPointer message) OVERRIDE;
// Overriden ConnectionHandlerObserver method
void OnDeviceListUpdated(
- const connection_handler::DeviceMap &device_list) OVERRIDE;
- // TODO (EZamakhov): fix all indentations in this file
+ const connection_handler::DeviceMap& device_list) OVERRIDE;
void OnFindNewApplicationsRequest() OVERRIDE;
- void
- RemoveDevice(const connection_handler::DeviceHandle &device_handle) OVERRIDE;
+ void RemoveDevice(
+ const connection_handler::DeviceHandle& device_handle) OVERRIDE;
bool OnServiceStartedCallback(
- const connection_handler::DeviceHandle &device_handle,
- const int32_t &session_key,
- const protocol_handler::ServiceType &type) OVERRIDE;
+ const connection_handler::DeviceHandle& device_handle,
+ const int32_t& session_key,
+ const protocol_handler::ServiceType& type) OVERRIDE;
void OnServiceEndedCallback(
- const int32_t &session_key, const protocol_handler::ServiceType &type,
- const connection_handler::CloseSessionReason &close_reason) OVERRIDE;
+ const int32_t& session_key,
+ const protocol_handler::ServiceType& type,
+ const connection_handler::CloseSessionReason& close_reason) OVERRIDE;
+
+#ifdef ENABLE_SECURITY
+ // Overriden SecurityManagerListener method
+ bool OnHandshakeDone(
+ uint32_t connection_key,
+ security_manager::SSLContext::HandshakeResult result) OVERRIDE FINAL;
+
+ void OnCertificateUpdateRequired() OVERRIDE FINAL;
+
+ security_manager::SSLContext::HandshakeContext GetHandshakeContext(
+ uint32_t key) const OVERRIDE FINAL;
+#endif // ENABLE_SECURITY
/**
* @ Add notification to collection
@@ -651,7 +761,7 @@ public:
*
* @param ptr Reference to shared pointer that point on hmi notification
*/
- void removeNotification(const commands::Command *notification);
+ void removeNotification(const commands::Command* notification);
/**
* @ Updates request timeout
@@ -662,24 +772,7 @@ public:
*/
void updateRequestTimeout(uint32_t connection_key,
uint32_t mobile_correlation_id,
- uint32_t new_timeout_value);
-
- /*
- * @brief Retrieves application id associated whith correlation id
- *
- * @param correlation_id Correlation ID of the HMI request
- *
- * @return application id associated whith correlation id
- */
- const uint32_t application_id(const int32_t correlation_id);
-
- /*
- * @brief Sets application id correlation id
- *
- * @param correlation_id Correlation ID of the HMI request
- * @param app_id Application ID
- */
- void set_application_id(const int32_t correlation_id, const uint32_t app_id);
+ uint32_t new_timeout_value) OVERRIDE;
/**
* @brief AddPolicyObserver allows to subscribe needed component to events
@@ -687,14 +780,14 @@ public:
*
* @param listener the component to subscribe.
*/
- void AddPolicyObserver(PolicyHandlerObserver *listener);
+ void AddPolicyObserver(PolicyHandlerObserver* listener);
/**
* @brief RemovePolicyObserver allows to remove observer from collection.
*
* @param listener observer to remove.
*/
- void RemovePolicyObserver(PolicyHandlerObserver *listener);
+ void RemovePolicyObserver(PolicyHandlerObserver* listener);
/**
* @brief Checks HMI level and returns true if streaming is allowed
@@ -702,9 +795,9 @@ public:
* @param service_type Service type to check
* @return True if streaming is allowed, false in other case
*/
- bool
- HMILevelAllowsStreaming(uint32_t app_id,
- protocol_handler::ServiceType service_type) const;
+ bool HMILevelAllowsStreaming(
+ uint32_t app_id,
+ protocol_handler::ServiceType service_type) const OVERRIDE;
/**
* @brief Checks if application can stream (streaming service is started and
@@ -714,19 +807,19 @@ public:
* @return True if streaming is allowed, false in other case
*/
bool CanAppStream(uint32_t app_id,
- protocol_handler::ServiceType service_type) const;
+ protocol_handler::ServiceType service_type) const OVERRIDE;
/**
* @brief Ends opened navi services (audio/video) for application
* @param app_id Application id
*/
- void EndNaviServices(uint32_t app_id);
+ void EndNaviServices(uint32_t app_id) OVERRIDE;
/**
* @brief ForbidStreaming forbid the stream over the certain application.
* @param app_id the application's id which should stop streaming.
*/
- void ForbidStreaming(uint32_t app_id);
+ void ForbidStreaming(uint32_t app_id) OVERRIDE;
/**
* @brief Callback calls when application starts/stops data streaming
@@ -735,56 +828,47 @@ public:
* @param state Shows if streaming started or stopped
*/
void OnAppStreaming(uint32_t app_id,
- protocol_handler::ServiceType service_type, bool state);
+ protocol_handler::ServiceType service_type,
+ bool state) OVERRIDE;
- /**
- * @brief OnHMILevelChanged the callback that allows SDL to react when
- * application's HMILeval has been changed.
- *
- * @param app_id application identifier for which HMILevel has been chaned.
- *
- * @param from previous HMILevel.
- * @param to current HMILevel.
- */
- void OnHMILevelChanged(uint32_t app_id, mobile_apis::HMILevel::eType from,
- mobile_apis::HMILevel::eType to);
-
- mobile_api::HMILevel::eType
- GetDefaultHmiLevel(ApplicationSharedPtr application) const;
+ mobile_api::HMILevel::eType GetDefaultHmiLevel(
+ ApplicationConstSharedPtr application) const;
/**
- * Getter for resume_controller
- * @return Resume Controller
- */
- ResumeCtrl &resume_controller() { return resume_ctrl_; }
+ * Getter for resume_controller
+ * @return Resume Controller
+ */
+ resumption::ResumeCtrl& resume_controller() OVERRIDE {
+ return resume_ctrl_;
+ }
/**
* Generate grammar ID
*
* @return New grammar ID
*/
- uint32_t GenerateGrammarID();
+ uint32_t GenerateGrammarID() OVERRIDE;
/**
* Generate new HMI application ID
*
* @return New HMI application ID
*/
- uint32_t GenerateNewHMIAppID();
+ uint32_t GenerateNewHMIAppID() OVERRIDE;
/**
* @brief Parse smartObject and replace mobile app Id by HMI app ID
*
* @param message Smartobject to be parsed
*/
- void ReplaceMobileByHMIAppId(smart_objects::SmartObject &message);
+ void ReplaceMobileByHMIAppId(smart_objects::SmartObject& message);
/**
* @brief Parse smartObject and replace HMI app ID by mobile app Id
*
* @param message Smartobject to be parsed
*/
- void ReplaceHMIByMobileAppId(smart_objects::SmartObject &message);
+ void ReplaceHMIByMobileAppId(smart_objects::SmartObject& message);
/*
* @brief Save binary data to specified directory
@@ -798,22 +882,22 @@ public:
*
* @return SUCCESS if file was saved, other code otherwise
*/
- mobile_apis::Result::eType SaveBinary(const std::vector<uint8_t> &binary_data,
- const std::string &file_path,
- const std::string &file_name,
- const int64_t offset);
+ mobile_apis::Result::eType SaveBinary(const std::vector<uint8_t>& binary_data,
+ const std::string& file_path,
+ const std::string& file_name,
+ const int64_t offset) OVERRIDE;
/**
* @brief Get available app space
* @param name of the app folder(make + mobile app id)
* @return free app space.
*/
- uint32_t GetAvailableSpaceForApp(const std::string &folder_name);
+ uint32_t GetAvailableSpaceForApp(const std::string& folder_name);
/*
* @brief returns true if HMI is cooperating
*/
- bool IsHMICooperating() const;
+ bool IsHMICooperating() const OVERRIDE;
/**
* @brief Method used to send default app tts globalProperties
@@ -827,7 +911,7 @@ public:
* @param app_id contains application which will
* send TTS global properties after timeout
*/
- void AddAppToTTSGlobalPropertiesList(const uint32_t app_id);
+ void AddAppToTTSGlobalPropertiesList(const uint32_t app_id) OVERRIDE;
/**
* @brief method removes application
@@ -835,7 +919,7 @@ public:
* @param app_id contains application which will
* send TTS global properties after timeout
*/
- void RemoveAppFromTTSGlobalPropertiesList(const uint32_t app_id);
+ void RemoveAppFromTTSGlobalPropertiesList(const uint32_t app_id) OVERRIDE;
/**
* @brief method adds application in FULL and LIMITED state
@@ -851,16 +935,13 @@ public:
*/
void ResetPhoneCallAppList();
- /**
- * Function used only by HMI request/response/notification base classes
- * to change HMI app id to Mobile app id and vice versa.
- * Dot use it inside Core
- */
- ApplicationSharedPtr application_by_hmi_app(uint32_t hmi_app_id) const;
-
// TODO(AOleynik): Temporary added, to fix build. Should be reworked.
- connection_handler::ConnectionHandler *connection_handler();
+ connection_handler::ConnectionHandler& connection_handler() const OVERRIDE;
+ protocol_handler::ProtocolHandler& protocol_handler() const OVERRIDE;
+ virtual policy::PolicyHandlerInterface& GetPolicyHandler() OVERRIDE {
+ return policy_handler_;
+ }
/**
* @brief Checks, if given RPC is allowed at current HMI level for specific
* application in policy table
@@ -872,9 +953,11 @@ public:
* @return SUCCESS, if allowed, otherwise result code of check
*/
mobile_apis::Result::eType CheckPolicyPermissions(
- const std::string &policy_app_id, mobile_apis::HMILevel::eType hmi_level,
- mobile_apis::FunctionID::eType function_id, const RPCParams &rpc_params,
- CommandParametersPermissions *params_permissions = NULL);
+ const std::string& policy_app_id,
+ mobile_apis::HMILevel::eType hmi_level,
+ mobile_apis::FunctionID::eType function_id,
+ const RPCParams& rpc_params,
+ CommandParametersPermissions* params_permissions = NULL) OVERRIDE;
/*
* @brief Function Should be called when Low Voltage is occured
*/
@@ -885,6 +968,22 @@ public:
*/
void OnWakeUp();
+ /**
+ * @brief IsApplicationForbidden allows to distinguish if application is
+ * not allowed to register, because of spamming.
+ *
+ * @param connection_key the connection key ofthe required application
+ *
+ * @param policy_app_id application's mobile(policy) identifier.
+ *
+ * @return true in case application is allowed to register, false otherwise.
+ */
+ bool IsApplicationForbidden(uint32_t connection_key,
+ const std::string& policy_app_id) const OVERRIDE;
+
+ policy::DeviceConsent GetUserConsentForDevice(
+ const std::string& device_id) const OVERRIDE;
+
struct ApplicationsAppIdSorter {
bool operator()(const ApplicationSharedPtr lhs,
const ApplicationSharedPtr rhs) {
@@ -892,95 +991,8 @@ public:
}
};
- struct ApplicationsMobileAppIdSorter {
- bool operator()(const ApplicationSharedPtr lhs,
- const ApplicationSharedPtr rhs) {
-
- if (lhs->mobile_app_id() == rhs->mobile_app_id()) {
- return lhs->device() < rhs->device();
- }
- return lhs->mobile_app_id() < rhs->mobile_app_id();
- }
- };
-
// typedef for Applications list
- typedef std::set<ApplicationSharedPtr, ApplicationsAppIdSorter> ApplictionSet;
-
- typedef std::multiset<ApplicationSharedPtr, ApplicationsMobileAppIdSorter>
- AppsWaitRegistrationSet;
-
- // typedef for Applications list iterator
- typedef ApplictionSet::iterator ApplictionSetIt;
-
- // typedef for Applications list const iterator
- typedef ApplictionSet::const_iterator ApplictionSetConstIt;
-
- DataAccessor<AppsWaitRegistrationSet> apps_waiting_for_registration() const;
- ApplicationConstSharedPtr waiting_app(const uint32_t hmi_id) const;
-
- /**
- * Class for thread-safe access to applications list
- */
- class ApplicationListAccessor : public DataAccessor<ApplictionSet> {
- public:
- /**
- * @brief ApplicationListAccessor class constructor
- */
- ApplicationListAccessor()
- : DataAccessor<ApplictionSet>(
- ApplicationManagerImpl::instance()->applications_,
- ApplicationManagerImpl::instance()->applications_list_lock_) {}
-
- ~ApplicationListAccessor();
-
- /**
- * @brief thread-safe getter for applications
- * @return applications list
- */
- const ApplictionSet &applications() const { return GetData(); }
-
- ApplictionSetConstIt begin() { return applications().begin(); }
-
- ApplictionSetConstIt end() { return applications().end(); }
-
- template <class UnaryPredicate>
- ApplicationSharedPtr Find(UnaryPredicate finder) {
- ApplicationSharedPtr result;
- ApplictionSetConstIt it = std::find_if(begin(), end(), finder);
- if (it != end()) {
- result = *it;
- }
- return result;
- }
-
- template <class UnaryPredicate>
- std::vector<ApplicationSharedPtr> FindAll(UnaryPredicate finder) {
- std::vector<ApplicationSharedPtr> result;
- ApplictionSetConstIt it = std::find_if(begin(), end(), finder);
- while (it != end()) {
- result.push_back(*it);
- it = std::find_if(++it, end(), finder);
- }
- return result;
- }
-
- void Erase(ApplicationSharedPtr app_to_remove) {
- ApplicationManagerImpl::instance()->applications_.erase(app_to_remove);
- }
-
- void Insert(ApplicationSharedPtr app_to_insert) {
- ApplicationManagerImpl::instance()->applications_.insert(app_to_insert);
- }
-
- bool Empty() {
- return ApplicationManagerImpl::instance()->applications_.empty();
- }
-
- private:
- DISALLOW_COPY_AND_ASSIGN(ApplicationListAccessor);
- };
-
- friend class ApplicationListAccessor;
+ typedef std::set<std::string> ForbiddenApps;
struct AppIdPredicate {
uint32_t app_id_;
@@ -998,12 +1010,12 @@ public:
}
};
- struct MobileAppIdPredicate {
+ struct PolicyAppIdPredicate {
std::string policy_app_id_;
- MobileAppIdPredicate(const std::string &policy_app_id)
+ PolicyAppIdPredicate(const std::string& policy_app_id)
: policy_app_id_(policy_app_id) {}
bool operator()(const ApplicationSharedPtr app) const {
- return app ? policy_app_id_ == app->mobile_app_id() : false;
+ return app ? policy_app_id_ == app->policy_app_id() : false;
}
};
@@ -1046,10 +1058,18 @@ public:
}
};
+ struct GrammarIdPredicate {
+ uint32_t grammar_id_;
+ GrammarIdPredicate(uint32_t grammar_id) : grammar_id_(grammar_id) {}
+ bool operator()(const ApplicationSharedPtr app) const {
+ return app ? grammar_id_ == app->get_grammar_id() : false;
+ }
+ };
+
/**
* @brief Sends UpdateAppList notification to HMI
*/
- void SendUpdateAppList();
+ void SendUpdateAppList() OVERRIDE;
/**
* @brief Marks applications received through QueryApps as should be
@@ -1058,18 +1078,31 @@ public:
* @param handle, device handle
*/
void MarkAppsGreyOut(const connection_handler::DeviceHandle handle,
- bool is_greyed_out);
+ bool is_greyed_out) OVERRIDE;
+
+ ApplicationConstSharedPtr WaitingApplicationByID(
+ const uint32_t hmi_id) const OVERRIDE;
+
+ DataAccessor<AppsWaitRegistrationSet> AppsWaitingForRegistration()
+ const OVERRIDE;
/**
* @brief Checks, if apps list had been queried already from certain device
* @param handle, Device handle
* @return true, if list had been queried already, otherwise - false
*/
- bool IsAppsQueriedFrom(const connection_handler::DeviceHandle handle) const;
+ bool IsAppsQueriedFrom(
+ const connection_handler::DeviceHandle handle) const OVERRIDE;
- bool IsStopping() const { return is_stopping_; }
+ bool IsStopping() const OVERRIDE {
+ return is_stopping_;
+ }
+
+ StateController& state_controller() OVERRIDE;
+ const ApplicationManagerSettings& get_settings() const OVERRIDE;
+ virtual event_engine::EventDispatcher& event_dispatcher() OVERRIDE;
-private:
+ private:
/**
* @brief PullLanguagesInfo allows to pull information about languages.
*
@@ -1078,11 +1111,9 @@ private:
* @param ttsName tts name that should be filled.
* @param vrSynonym vr synonymus that should be filled.
*/
- void PullLanguagesInfo(const smart_objects::SmartObject &app_data,
- smart_objects::SmartObject &ttsName,
- smart_objects::SmartObject &vrSynonym);
-
- ApplicationManagerImpl();
+ void PullLanguagesInfo(const smart_objects::SmartObject& app_data,
+ smart_objects::SmartObject& ttsName,
+ smart_objects::SmartObject& vrSynonym);
/**
* @brief Method transforms string to AppHMIType
@@ -1097,18 +1128,18 @@ private:
* @param from_application contains app HMI type from application
* @return return TRUE if arrays of appHMIType equal, otherwise return FALSE
*/
- bool CompareAppHMIType(const smart_objects::SmartObject &from_policy,
- const smart_objects::SmartObject &from_application);
+ bool CompareAppHMIType(const smart_objects::SmartObject& from_policy,
+ const smart_objects::SmartObject& from_application);
- hmi_apis::HMI_API &hmi_so_factory();
- mobile_apis::MOBILE_API &mobile_so_factory();
+ hmi_apis::HMI_API& hmi_so_factory();
+ mobile_apis::MOBILE_API& mobile_so_factory();
- bool ConvertMessageToSO(const Message &message,
- smart_objects::SmartObject &output);
- bool ConvertSOtoMessage(const smart_objects::SmartObject &message,
- Message &output);
- utils::SharedPtr<Message>
- ConvertRawMsgToMessage(const ::protocol_handler::RawMessagePtr message);
+ bool ConvertMessageToSO(const Message& message,
+ smart_objects::SmartObject& output);
+ bool ConvertSOtoMessage(const smart_objects::SmartObject& message,
+ Message& output);
+ utils::SharedPtr<Message> ConvertRawMsgToMessage(
+ const ::protocol_handler::RawMessagePtr message);
void ProcessMessageFromMobile(const utils::SharedPtr<Message> message);
void ProcessMessageFromHMI(const utils::SharedPtr<Message> message);
@@ -1119,26 +1150,27 @@ private:
* of messages. Beware, each is called on different thread!
*/
// CALLED ON messages_from_mobile_ thread!
- virtual void Handle(const impl::MessageFromMobile message) OVERRIDE;
+ void Handle(const impl::MessageFromMobile message) OVERRIDE;
// CALLED ON messages_to_mobile_ thread!
- virtual void Handle(const impl::MessageToMobile message) OVERRIDE;
+ void Handle(const impl::MessageToMobile message) OVERRIDE;
// CALLED ON messages_from_hmi_ thread!
- virtual void Handle(const impl::MessageFromHmi message) OVERRIDE;
+ void Handle(const impl::MessageFromHmi message) OVERRIDE;
// CALLED ON messages_to_hmi_ thread!
- virtual void Handle(const impl::MessageToHmi message) OVERRIDE;
+ void Handle(const impl::MessageToHmi message) OVERRIDE;
// CALLED ON audio_pass_thru_messages_ thread!
- virtual void Handle(const impl::AudioData message) OVERRIDE;
+ void Handle(const impl::AudioData message) OVERRIDE;
template <typename ApplicationList>
void PrepareApplicationListSO(ApplicationList app_list,
- smart_objects::SmartObject &applications) {
- CREATE_LOGGERPTR_LOCAL(logger_, "ApplicatinManagerImpl");
+ smart_objects::SmartObject& applications,
+ ApplicationManager& app_mngr) {
+ CREATE_LOGGERPTR_LOCAL(logger_, "ApplicationManager");
- smart_objects::SmartArray *app_array = applications.asArray();
+ smart_objects::SmartArray* app_array = applications.asArray();
uint32_t app_count = NULL == app_array ? 0 : app_array->size();
typename ApplicationList::const_iterator it;
for (it = app_list.begin(); it != app_list.end(); ++it) {
@@ -1148,8 +1180,13 @@ private:
}
smart_objects::SmartObject hmi_application(smart_objects::SmartType_Map);
- ;
- if (MessageHelper::CreateHMIApplicationStruct(*it, hmi_application)) {
+ const protocol_handler::SessionObserver& session_observer =
+ connection_handler().get_session_observer();
+ if (MessageHelper::CreateHMIApplicationStruct(*it,
+ session_observer,
+ GetPolicyHandler(),
+ &hmi_application,
+ app_mngr)) {
applications[app_count++] = hmi_application;
} else {
LOG4CXX_DEBUG(logger_, "Can't CreateHMIApplicationStruct ");
@@ -1172,7 +1209,7 @@ private:
* @param connection_key connection key of app, which provided app list to
* be created
*/
- void CreateApplications(smart_objects::SmartArray &obj_array,
+ void CreateApplications(smart_objects::SmartArray& obj_array,
const uint32_t connection_key);
/*
@@ -1186,17 +1223,28 @@ private:
*/
bool IsLowVoltage();
-private:
+ private:
/*
* NaviServiceStatusMap shows which navi service (audio/video) is opened
* for specified application. Two bool values in std::pair mean:
* 1st value - is video service opened or not
* 2nd value - is audio service opened or not
*/
- typedef std::map<uint32_t, std::pair<bool, bool>> NaviServiceStatusMap;
+ typedef std::map<uint32_t, std::pair<bool, bool> > NaviServiceStatusMap;
- typedef SharedPtr<TimerThread<ApplicationManagerImpl>>
- ApplicationManagerTimerPtr;
+ /**
+ * @brief GetHashedAppID allows to obtain unique application id as a string.
+ * It concatenates device mac and application id to obtain unique id.
+ *
+ * @param connection_key connection key for which need to obtain device mac;
+ *
+ * @param policy_app_id mobile(policy) application id on particular device.
+ * This parameter will be concatenated with device id.
+ *
+ * @return unique aplication identifier.
+ */
+ std::string GetHashedAppID(uint32_t connection_key,
+ const std::string& policy_app_id) const;
/**
* @brief Removes suspended and stopped timers from timer pool
@@ -1275,7 +1323,7 @@ private:
* @param type Directory type
* @return true, if succedeed, otherwise - false
*/
- bool InitDirectory(const std::string &path, DirectoryType type) const;
+ bool InitDirectory(const std::string& path, DirectoryType type) const;
/**
* @brief Checks, whether r/w permissions are present for particular path
@@ -1283,7 +1331,7 @@ private:
* @param type Directory type
* @return true, if allowed, otherwise - false
*/
- bool IsReadWriteAllowed(const std::string &path, DirectoryType type) const;
+ bool IsReadWriteAllowed(const std::string& path, DirectoryType type) const;
/**
* @brief Removes apps, waiting for registration related to
@@ -1293,21 +1341,21 @@ private:
void RemoveAppsWaitingForRegistration(
const connection_handler::DeviceHandle handle);
- /**
- * @brief Clears TTS global properties list of apps
- */
void ClearTTSGlobalPropertiesList();
-private:
+ private:
+ const ApplicationManagerSettings& settings_;
/**
* @brief List of applications
*/
- ApplictionSet applications_;
+ ApplicationSet applications_;
AppsWaitRegistrationSet apps_to_register_;
+ ForbiddenApps forbidden_applications;
// Lock for applications list
mutable sync_primitives::Lock applications_list_lock_;
mutable sync_primitives::Lock apps_to_register_list_lock_;
+ mutable sync_primitives::Lock subscribed_way_points_apps_lock_;
/**
* @brief Map of correlation id and associated application id.
@@ -1315,6 +1363,11 @@ private:
std::map<const int32_t, const uint32_t> appID_list_;
/**
+ * @brief Set AppIDs of subscribed apps for way points
+ */
+ std::set<int32_t> subscribed_way_points_apps_list_;
+
+ /**
* @brief Map contains applications which
* will send TTS global properties to HMI after timeout
*/
@@ -1327,15 +1380,18 @@ private:
bool is_vr_session_strated_;
bool hmi_cooperating_;
bool is_all_apps_allowed_;
- media_manager::MediaManager *media_manager_;
- hmi_message_handler::HMIMessageHandler *hmi_handler_;
- connection_handler::ConnectionHandler *connection_handler_;
- protocol_handler::ProtocolHandler *protocol_handler_;
+ event_engine::EventDispatcherImpl event_dispatcher_;
+ media_manager::MediaManager* media_manager_;
+
+ hmi_message_handler::HMIMessageHandler* hmi_handler_;
+ connection_handler::ConnectionHandler* connection_handler_;
+ policy::PolicyHandler policy_handler_;
+ protocol_handler::ProtocolHandler* protocol_handler_;
request_controller::RequestController request_ctrl_;
- hmi_apis::HMI_API *hmi_so_factory_;
- mobile_apis::MOBILE_API *mobile_so_factory_;
+ hmi_apis::HMI_API* hmi_so_factory_;
+ mobile_apis::MOBILE_API* mobile_so_factory_;
static uint32_t corelation_id_;
static const uint32_t max_corelation_id_;
@@ -1362,7 +1418,7 @@ private:
* about persistent application data on disk, and save session ID for resuming
* application in case INGITION_OFF or MASTER_RESSET
*/
- ResumeCtrl resume_ctrl_;
+ resumption::ResumeCtrl resume_ctrl_;
NaviServiceStatusMap navi_service_status_;
std::deque<uint32_t> navi_app_to_stop_;
@@ -1370,36 +1426,24 @@ private:
uint32_t navi_close_app_timeout_;
uint32_t navi_end_stream_timeout_;
- std::vector<ApplicationManagerTimerPtr> timer_pool_;
+ std::vector<TimerSPtr> timer_pool_;
sync_primitives::Lock timer_pool_lock_;
- sync_primitives::Lock stopping_flag_lock_;
+ sync_primitives::Lock stopping_application_mng_lock_;
+ StateControllerImpl state_ctrl_;
- StateController state_ctrl_;
+#ifdef TELEMETRY_MONITOR
+ AMTelemetryObserver* metric_observer_;
+#endif // TELEMETRY_MONITOR
-#ifdef TIME_TESTER
- AMMetricObserver *metric_observer_;
-#endif // TIME_TESTER
+ Timer application_list_update_timer_;
- class ApplicationListUpdateTimer
- : public timer::TimerThread<ApplicationManagerImpl> {
- public:
- ApplicationListUpdateTimer(ApplicationManagerImpl *callee)
- : timer::TimerThread<ApplicationManagerImpl>(
- "AM ListUpdater", callee,
- &ApplicationManagerImpl::OnApplicationListUpdateTimer) {}
- };
- typedef utils::SharedPtr<ApplicationListUpdateTimer>
- ApplicationListUpdateTimerSptr;
- ApplicationListUpdateTimerSptr application_list_update_timer_;
-
- timer::TimerThread<ApplicationManagerImpl> tts_global_properties_timer_;
+ Timer tts_global_properties_timer_;
bool is_low_voltage_;
+
volatile bool is_stopping_;
DISALLOW_COPY_AND_ASSIGN(ApplicationManagerImpl);
-
- FRIEND_BASE_SINGLETON_CLASS(ApplicationManagerImpl);
};
bool ApplicationManagerImpl::vr_session_started() const {
@@ -1413,6 +1457,7 @@ bool ApplicationManagerImpl::driver_distraction() const {
inline bool ApplicationManagerImpl::all_apps_allowed() const {
return is_all_apps_allowed_;
}
-} // namespace application_manager
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_H_
+} // namespace application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_H_
diff --git a/src/components/application_manager/include/application_manager/application_state.h b/src/components/application_manager/include/application_manager/application_state.h
new file mode 100644
index 0000000000..bf894eaf94
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/application_state.h
@@ -0,0 +1,159 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_APPLICATION_STATE_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_APPLICATION_STATE_H_
+#include <vector>
+#include "utils/lock.h"
+#include "utils/macro.h"
+#include "application_manager/hmi_state.h"
+
+namespace application_manager {
+
+typedef std::vector<HmiStatePtr> HmiStates;
+
+/*
+ * Class represents application state, i.e. current HMI level, audio streaming
+ * state and context
+ * Current implementation:
+ * - has regular state, which is default or base state
+ * - temporary states can be applied on top of regular state
+ * - on temporary state end it is being removed from states list
+ * - current state is the consolidated state of all the states, since different
+ * temporary state can affect one or more parameters (HMI state, audio, context)
+ * - can have postponed state (comes from resumption process), which is
+ * not applied on top, but is being added before base and can replace base later
+ * on
+ */
+class ApplicationState {
+ public:
+ /**
+ * @brief ApplicationState constructor
+ */
+ ApplicationState();
+
+ /**
+ * @brief Init state
+ * @param state Initial state
+ */
+ void InitState(HmiStatePtr state);
+
+ /**
+ * @brief Adds state to states storage
+ * @param state State of application
+ */
+ void AddState(HmiStatePtr state);
+
+ /**
+ * @brief Removes state from states storage
+ * @param state State of application
+ */
+ void RemoveState(HmiState::StateID state);
+
+ /**
+ * @brief Gets state by state id
+ * @param state_id State id
+ * @return Pointer to application state
+ */
+ HmiStatePtr GetState(HmiState::StateID state_id) const;
+
+ private:
+ /**
+ * @brief AddHMIState the function that will change application's
+ * hmi state.
+ *
+ * @param app_id id of the application whose hmi level should be changed.
+ *
+ * @param state new hmi state for certain application.
+ */
+ void AddHMIState(HmiStatePtr state);
+
+ /**
+ * @brief RemoveHMIState the function that will turn back hmi_level after end
+ * of some event
+ *
+ * @param app_id id of the application whose hmi level should be changed.
+ *
+ * @param state_id that should be removed
+ */
+ void RemoveHMIState(HmiState::StateID state_id);
+
+ /**
+ * @brief Removes postponed state
+ */
+ void RemovePostponedState();
+
+ /**
+ * @brief Sets regular state of application
+ * @param state State of application
+ */
+ void SetRegularState(HmiStatePtr state);
+
+ /**
+ * @brief Sets postponed state of application.
+ * This state could be set as regular later on
+ *
+ * @param state state to setup
+ */
+ void SetPostponedState(HmiStatePtr state);
+
+ /**
+ * @brief HmiState of application within active events PhoneCall, TTS< etc ...
+ * @return Active HmiState of application
+ */
+ HmiStatePtr CurrentHmiState() const;
+
+ /**
+ * @brief RegularHmiState of application without active events VR, TTS etc ...
+ * @return HmiState of application
+ */
+ HmiStatePtr RegularHmiState() const;
+
+ /**
+ * @brief PostponedHmiState returns postponed hmi state of application
+ * if it's present
+ *
+ * @return Postponed hmi state of application
+ */
+ HmiStatePtr PostponedHmiState() const;
+
+ /**
+ * @brief Active states of application
+ */
+ HmiStates hmi_states_;
+ mutable sync_primitives::Lock hmi_states_lock_;
+
+ DISALLOW_COPY_AND_ASSIGN(ApplicationState);
+};
+}
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_APPLICATION_STATE_H_
diff --git a/src/components/application_manager/include/application_manager/commands/command.h b/src/components/application_manager/include/application_manager/commands/command.h
index 238e0b71c7..fb2bc6d78f 100644
--- a/src/components/application_manager/include/application_manager/commands/command.h
+++ b/src/components/application_manager/include/application_manager/commands/command.h
@@ -32,17 +32,11 @@
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_COMMAND_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_COMMAND_H_
-
-#include "utils/shared_ptr.h"
+#include <stdint.h>
#include "smart_objects/smart_object.h"
-#include "application_manager/event_engine/event_observer.h"
-#include "application_manager/smart_object_keys.h"
+#include "utils/shared_ptr.h"
namespace application_manager {
-/**
- * @brief SmartObject type
- **/
-
namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
namespace commands {
@@ -114,21 +108,16 @@ class Command {
*/
virtual bool AllowedToTerminate() = 0;
- /**
- * @brief SetAllowedToTerminate set up allowed to terminate flag.
- * If true, request controller will terminate request on response
- */
- virtual void SetAllowedToTerminate(bool allowed) = 0;
-
+ /**
+ * @brief SetAllowedToTerminate set up allowed to terminate flag.
+ * If true, request controller will terminate request on response
+ */
+ virtual void SetAllowedToTerminate(const bool allowed) = 0;
- enum CommandOrigin {
- ORIGIN_SDL,
- ORIGIN_MOBILE
- };
+ enum CommandOrigin { ORIGIN_SDL, ORIGIN_MOBILE };
};
typedef smart_objects::SmartObjectSPtr MessageSharedPtr;
-
} // namespace commands
} // namespace application_manager
diff --git a/src/components/application_manager/include/application_manager/commands/command_impl.h b/src/components/application_manager/include/application_manager/commands/command_impl.h
index 6cc8f82330..439b1756ef 100644
--- a/src/components/application_manager/include/application_manager/commands/command_impl.h
+++ b/src/components/application_manager/include/application_manager/commands/command_impl.h
@@ -34,6 +34,9 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_COMMAND_IMPL_H_
#include "application_manager/commands/command.h"
+#include "application_manager/event_engine/event_observer.h"
+#include "application_manager/application_manager.h"
+#include "application_manager/smart_object_keys.h"
#include "utils/logger.h"
namespace application_manager {
@@ -49,7 +52,6 @@ struct CommandParametersPermissions {
};
namespace commands {
-
/**
* @brief Class is intended to encapsulate RPC as an object
**/
@@ -60,7 +62,8 @@ class CommandImpl : public Command {
*
* @param message Incoming SmartObject message
**/
- explicit CommandImpl(const MessageSharedPtr& message);
+ CommandImpl(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief CommandImpl class destructor
@@ -71,52 +74,51 @@ class CommandImpl : public Command {
/**
* @brief Checks command permissions according to policy table
*/
- virtual bool CheckPermissions();
+ bool CheckPermissions() OVERRIDE;
/**
* @brief Init required by command resources
**/
- virtual bool Init();
+ bool Init() OVERRIDE;
/**
* @brief Cleanup all resources used by command
**/
- virtual bool CleanUp();
+ bool CleanUp() OVERRIDE;
/**
* @brief Execute corresponding command by calling the action on reciever
**/
- virtual void Run();
-
+ void Run() OVERRIDE;
/**
* @brief Retrieves request default timeout.
* If request has a custom timeout, request_timeout_ should be reassign to it
*
* @return Request default timeout
*/
- virtual uint32_t default_timeout() const;
+ uint32_t default_timeout() const OVERRIDE;
/*
* @brief Retrieves correlation ID
*/
- virtual uint32_t correlation_id() const;
+ uint32_t correlation_id() const OVERRIDE;
/*
* @brief Retrieves connection key
*/
- virtual uint32_t connection_key() const;
+ uint32_t connection_key() const OVERRIDE;
/*
* @brief Retrieves request ID
*/
- virtual int32_t function_id() const;
+ int32_t function_id() const OVERRIDE;
/*
* @brief Function is called by RequestController when request execution time
* has exceed it's limit
*
*/
- virtual void onTimeOut();
+ void onTimeOut() OVERRIDE;
/**
* @brief AllowedToTerminate tells request Controller if it can terminate this
@@ -125,30 +127,42 @@ class CommandImpl : public Command {
* If request need to terminate itself, it should override this function false
* @return allowed_to_terminate_ value
*/
- virtual bool AllowedToTerminate() {
- return allowed_to_terminate_;
- }
+ bool AllowedToTerminate() OVERRIDE;
/**
* @brief SetAllowedToTerminate set up allowed to terminate flag.
* If true, request controller will terminate request on response
*/
- virtual void SetAllowedToTerminate(bool allowed) {
- allowed_to_terminate_ = allowed;
- }
+ void SetAllowedToTerminate(const bool allowed) OVERRIDE;
// members
static const int32_t hmi_protocol_type_;
static const int32_t mobile_protocol_type_;
- static const int32_t protocol_version_;
+ static const int32_t protocol_version_;
protected:
+ /**
+ * @brief Parse smartObject and replace mobile app Id by HMI app ID
+ *
+ * @param message Smartobject to be parsed
+ */
+ void ReplaceMobileByHMIAppId(smart_objects::SmartObject& message);
+
+ /**
+ * @brief Parse smartObject and replace HMI app ID by mobile app Id
+ *
+ * @param message Smartobject to be parsed
+ */
+ void ReplaceHMIByMobileAppId(smart_objects::SmartObject& message);
+
MessageSharedPtr message_;
uint32_t default_timeout_;
bool allowed_to_terminate_;
+ ApplicationManager& application_manager_;
+
#ifdef ENABLE_LOG
static log4cxx::LoggerPtr logger_;
-#endif // ENABLE_LOG
+#endif // ENABLE_LOG
private:
DISALLOW_COPY_AND_ASSIGN(CommandImpl);
diff --git a/src/components/application_manager/include/application_manager/commands/command_notification_from_mobile_impl.h b/src/components/application_manager/include/application_manager/commands/command_notification_from_mobile_impl.h
index 9f95a52850..2f3b809274 100644
--- a/src/components/application_manager/include/application_manager/commands/command_notification_from_mobile_impl.h
+++ b/src/components/application_manager/include/application_manager/commands/command_notification_from_mobile_impl.h
@@ -47,12 +47,14 @@ namespace commands {
class CommandNotificationFromMobileImpl : public CommandImpl {
public:
- explicit CommandNotificationFromMobileImpl(const MessageSharedPtr& message);
+ CommandNotificationFromMobileImpl(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
virtual ~CommandNotificationFromMobileImpl();
virtual bool Init();
virtual bool CleanUp();
virtual void Run();
void SendNotification();
+
private:
DISALLOW_COPY_AND_ASSIGN(CommandNotificationFromMobileImpl);
};
diff --git a/src/components/application_manager/include/application_manager/commands/command_notification_impl.h b/src/components/application_manager/include/application_manager/commands/command_notification_impl.h
index 7d0d11af89..25a2a18aca 100644
--- a/src/components/application_manager/include/application_manager/commands/command_notification_impl.h
+++ b/src/components/application_manager/include/application_manager/commands/command_notification_impl.h
@@ -47,12 +47,14 @@ namespace commands {
class CommandNotificationImpl : public CommandImpl {
public:
- explicit CommandNotificationImpl(const MessageSharedPtr& message);
+ CommandNotificationImpl(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
virtual ~CommandNotificationImpl();
virtual bool Init();
virtual bool CleanUp();
virtual void Run();
void SendNotification();
+
private:
DISALLOW_COPY_AND_ASSIGN(CommandNotificationImpl);
};
diff --git a/src/components/application_manager/include/application_manager/commands/command_request_impl.h b/src/components/application_manager/include/application_manager/commands/command_request_impl.h
index 0401a3bf46..c5f45e2095 100644
--- a/src/components/application_manager/include/application_manager/commands/command_request_impl.h
+++ b/src/components/application_manager/include/application_manager/commands/command_request_impl.h
@@ -50,19 +50,15 @@ namespace commands {
namespace NsSmart = NsSmartDeviceLink::NsSmartObjects;
class CommandRequestImpl : public CommandImpl,
- public event_engine::EventObserver {
+ public event_engine::EventObserver {
public:
+ enum RequestState { kAwaitingHMIResponse = 0, kTimedOut, kCompleted };
- enum RequestState {
- kAwaitingHMIResponse = 0,
- kTimedOut,
- kCompleted
- };
-
- explicit CommandRequestImpl(const MessageSharedPtr& message);
+ CommandRequestImpl(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
virtual ~CommandRequestImpl();
virtual bool CheckPermissions();
- virtual bool Init();
+ virtual bool Init();
virtual bool CleanUp();
virtual void Run();
@@ -99,7 +95,7 @@ class CommandRequestImpl : public CommandImpl,
* @param allow_empty_string if true methods allow empty sting
* @return true if success otherwise return false
*/
- bool CheckSyntax(std::string str, bool allow_empty_line = false);
+ bool CheckSyntax(const std::string& str, bool allow_empty_line = false);
/*
* @brief Sends HMI request
@@ -110,8 +106,8 @@ class CommandRequestImpl : public CommandImpl,
* @return hmi correlation id
*/
uint32_t SendHMIRequest(const hmi_apis::FunctionID::eType& function_id,
- const smart_objects::SmartObject* msg_params = NULL,
- bool use_events = false);
+ const smart_objects::SmartObject* msg_params = NULL,
+ bool use_events = false);
/*
* @brief Creates HMI request
@@ -131,8 +127,7 @@ class CommandRequestImpl : public CommandImpl,
mobile_apis::Result::eType GetMobileResultCode(
const hmi_apis::Common_Result::eType& hmi_code) const;
-protected:
-
+ protected:
/**
* @brief Checks message permissions and parameters according to policy table
* permissions
@@ -141,10 +136,8 @@ protected:
/**
* @brief Remove from current message parameters disallowed by policy table
- * @param params_permissions Parameters permissions from policy table
*/
- void RemoveDisallowedParameters(
- const CommandParametersPermissions& params_permissions);
+ void RemoveDisallowedParameters();
/**
* @brief Adds disallowed parameters back to response with appropriate
@@ -161,14 +154,20 @@ protected:
bool HasDisallowedParams() const;
protected:
- RequestState current_state_;
- sync_primitives::Lock state_lock_;
- CommandParametersPermissions parameters_permissions_;
+ /**
+ * @brief Returns policy parameters permissions
+ * @return Parameters permissions struct reference
+ */
+ const CommandParametersPermissions& parameters_permissions() const;
+
+ RequestState current_state_;
+ sync_primitives::Lock state_lock_;
+ CommandParametersPermissions parameters_permissions_;
+ CommandParametersPermissions removed_parameters_permissions_;
private:
DISALLOW_COPY_AND_ASSIGN(CommandRequestImpl);
-
/**
* @brief Adds param to disallowed parameters enumeration
* @param info string with disallowed params enumeration
@@ -181,7 +180,8 @@ protected:
* @brief Adds disallowed parameters to response info
* @param response Response message, which info should be extended
*/
- void AddDisallowedParametersToInfo(smart_objects::SmartObject& response) const;
+ void AddDisallowedParametersToInfo(
+ smart_objects::SmartObject& response) const;
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/command_response_impl.h b/src/components/application_manager/include/application_manager/commands/command_response_impl.h
index 0c93bf54d4..2b52ea5a58 100644
--- a/src/components/application_manager/include/application_manager/commands/command_response_impl.h
+++ b/src/components/application_manager/include/application_manager/commands/command_response_impl.h
@@ -48,7 +48,8 @@ namespace commands {
class CommandResponseImpl : public CommandImpl {
public:
- explicit CommandResponseImpl(const MessageSharedPtr& message);
+ CommandResponseImpl(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
virtual ~CommandResponseImpl();
virtual bool Init();
virtual bool CleanUp();
@@ -57,6 +58,7 @@ class CommandResponseImpl : public CommandImpl {
const mobile_apis::Result::eType& result_code =
mobile_apis::Result::INVALID_ENUM,
bool final_message = false);
+
private:
DISALLOW_COPY_AND_ASSIGN(CommandResponseImpl);
};
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/activate_app_request.h b/src/components/application_manager/include/application_manager/commands/hmi/activate_app_request.h
index 5122a0856b..090a77b9ed 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/activate_app_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/activate_app_request.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief ActivateAppRequest command class
**/
class ActivateAppRequest : public RequestToHMI {
- public:
- /**
- * @brief ActivateAppRequest class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit ActivateAppRequest(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief ActivateAppRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ ActivateAppRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief ActivateAppRequest class destructor
- **/
- virtual ~ActivateAppRequest();
+ /**
+ * @brief ActivateAppRequest class destructor
+ **/
+ virtual ~ActivateAppRequest();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(ActivateAppRequest);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(ActivateAppRequest);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/activate_app_response.h b/src/components/application_manager/include/application_manager/commands/hmi/activate_app_response.h
index a15d317077..471de1135e 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/activate_app_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/activate_app_response.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief ActivateAppResponse command class
**/
class ActivateAppResponse : public ResponseFromHMI {
- public:
- /**
- * @brief ActivateAppResponse class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit ActivateAppResponse(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief ActivateAppResponse class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ ActivateAppResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief ActivateAppResponse class destructor
- **/
- virtual ~ActivateAppResponse();
+ /**
+ * @brief ActivateAppResponse class destructor
+ **/
+ virtual ~ActivateAppResponse();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(ActivateAppResponse);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(ActivateAppResponse);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/add_statistics_info_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/add_statistics_info_notification.h
index 1aa3b7a512..3e0f81f167 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/add_statistics_info_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/add_statistics_info_notification.h
@@ -49,7 +49,8 @@ class AddStatisticsInfoNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit AddStatisticsInfoNotification(const MessageSharedPtr& message);
+ AddStatisticsInfoNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief AddStatisticsInfoNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/allow_all_apps_request.h b/src/components/application_manager/include/application_manager/commands/hmi/allow_all_apps_request.h
index 3d42b6d5a6..c1c5b36e5b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/allow_all_apps_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/allow_all_apps_request.h
@@ -49,7 +49,8 @@ class AllowAllAppsRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit AllowAllAppsRequest(const MessageSharedPtr& message);
+ AllowAllAppsRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief AllowAllAppsRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/allow_all_apps_response.h b/src/components/application_manager/include/application_manager/commands/hmi/allow_all_apps_response.h
index ccc8d5ae7d..711825cfab 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/allow_all_apps_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/allow_all_apps_response.h
@@ -49,7 +49,8 @@ class AllowAllAppsResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit AllowAllAppsResponse(const MessageSharedPtr& message);
+ AllowAllAppsResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief AllowAllAppsResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/allow_app_request.h b/src/components/application_manager/include/application_manager/commands/hmi/allow_app_request.h
index e90576a7df..10424a2661 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/allow_app_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/allow_app_request.h
@@ -49,7 +49,8 @@ class AllowAppRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit AllowAppRequest(const MessageSharedPtr& message);
+ AllowAppRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief AllowAppRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/allow_app_response.h b/src/components/application_manager/include/application_manager/commands/hmi/allow_app_response.h
index 6bedf30a38..4f2642f550 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/allow_app_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/allow_app_response.h
@@ -49,7 +49,8 @@ class AllowAppResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit AllowAppResponse(const MessageSharedPtr& message);
+ AllowAppResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief AllowAppResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/basic_communication_system_request.h b/src/components/application_manager/include/application_manager/commands/hmi/basic_communication_system_request.h
index 867596f189..d9aaff7797 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/basic_communication_system_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/basic_communication_system_request.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief BasicCommunicationSystemRequest command class
**/
class BasicCommunicationSystemRequest : public RequestToHMI {
- public:
- /**
- * @brief BasicCommunicationSystemRequest class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit BasicCommunicationSystemRequest(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief BasicCommunicationSystemRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ BasicCommunicationSystemRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief BasicCommunicationSystemRequest class destructor
- **/
- virtual ~BasicCommunicationSystemRequest();
+ /**
+ * @brief BasicCommunicationSystemRequest class destructor
+ **/
+ virtual ~BasicCommunicationSystemRequest();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(BasicCommunicationSystemRequest);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(BasicCommunicationSystemRequest);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/basic_communication_system_response.h b/src/components/application_manager/include/application_manager/commands/hmi/basic_communication_system_response.h
index 5c174eac85..b7d4f8f689 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/basic_communication_system_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/basic_communication_system_response.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief BasicCommunicationSystemResponse command class
**/
class BasicCommunicationSystemResponse : public ResponseFromHMI {
- public:
- /**
- * @brief BasicCommunicationSystemResponse class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit BasicCommunicationSystemResponse(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief BasicCommunicationSystemResponse class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ BasicCommunicationSystemResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief BasicCommunicationSystemResponse class destructor
- **/
- virtual ~BasicCommunicationSystemResponse();
+ /**
+ * @brief BasicCommunicationSystemResponse class destructor
+ **/
+ virtual ~BasicCommunicationSystemResponse();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(BasicCommunicationSystemResponse);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(BasicCommunicationSystemResponse);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/button_get_capabilities_request.h b/src/components/application_manager/include/application_manager/commands/hmi/button_get_capabilities_request.h
index 639800a047..45dc690c6c 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/button_get_capabilities_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/button_get_capabilities_request.h
@@ -49,7 +49,8 @@ class ButtonGetCapabilitiesRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit ButtonGetCapabilitiesRequest(const MessageSharedPtr& message);
+ ButtonGetCapabilitiesRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief ButtonGetCapabilitiesRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/button_get_capabilities_response.h b/src/components/application_manager/include/application_manager/commands/hmi/button_get_capabilities_response.h
index 7cd174477b..4efa576079 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/button_get_capabilities_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/button_get_capabilities_response.h
@@ -49,7 +49,8 @@ class ButtonGetCapabilitiesResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit ButtonGetCapabilitiesResponse(const MessageSharedPtr& message);
+ ButtonGetCapabilitiesResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief ButtonGetCapabilitiesResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/close_popup_request.h b/src/components/application_manager/include/application_manager/commands/hmi/close_popup_request.h
index 34722bc4f1..d7d4d18d97 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/close_popup_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/close_popup_request.h
@@ -49,7 +49,8 @@ class ClosePopupRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit ClosePopupRequest(const MessageSharedPtr& message);
+ ClosePopupRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief ClosePopupRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/close_popup_response.h b/src/components/application_manager/include/application_manager/commands/hmi/close_popup_response.h
index ce3a6d2936..6dccad7b57 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/close_popup_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/close_popup_response.h
@@ -49,7 +49,8 @@ class ClosePopupResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit ClosePopupResponse(const MessageSharedPtr& message);
+ ClosePopupResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief ClosePopupResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/dial_number_request.h b/src/components/application_manager/include/application_manager/commands/hmi/dial_number_request.h
index 7d59abdadd..2b002c31dd 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/dial_number_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/dial_number_request.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016, Ford Motor Company
+ * Copyright (c) 2013, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -50,23 +50,24 @@ class DialNumberRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit DialNumberRequest(const MessageSharedPtr& message);
+ DialNumberRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief DialNumberRequest class destructor
**/
- ~DialNumberRequest() OVERRIDE;
+ virtual ~DialNumberRequest();
/**
* @brief Execute command
**/
- void Run() OVERRIDE;
+ virtual void Run();
private:
DISALLOW_COPY_AND_ASSIGN(DialNumberRequest);
};
-} // namespace hmi
+} // namespace hmi
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/dial_number_response.h b/src/components/application_manager/include/application_manager/commands/hmi/dial_number_response.h
index 93a2e06c5f..1fbef15307 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/dial_number_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/dial_number_response.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016, Ford Motor Company
+ * Copyright (c) 2013, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -51,23 +51,24 @@ class DialNumberResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit DialNumberResponse(const MessageSharedPtr& message);
+ DialNumberResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief DialNumberResponse class destructor
**/
- ~DialNumberResponse() OVERRIDE;
+ virtual ~DialNumberResponse();
/**
* @brief Execute command
**/
- void Run() OVERRIDE;
+ virtual void Run();
private:
DISALLOW_COPY_AND_ASSIGN(DialNumberResponse);
};
-} // namespace hmi
+} // namespace hmi
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/get_system_info_request.h b/src/components/application_manager/include/application_manager/commands/hmi/get_system_info_request.h
index 8262dbb6fa..f4e421473c 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/get_system_info_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/get_system_info_request.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief GetSystemInfoRequest command class
**/
class GetSystemInfoRequest : public RequestToHMI {
- public:
- /**
- * @brief GetSystemInfoRequest class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit GetSystemInfoRequest(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief GetSystemInfoRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ GetSystemInfoRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief GetSystemInfoRequest class destructor
- **/
- virtual ~GetSystemInfoRequest();
+ /**
+ * @brief GetSystemInfoRequest class destructor
+ **/
+ virtual ~GetSystemInfoRequest();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(GetSystemInfoRequest);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(GetSystemInfoRequest);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/get_system_info_response.h b/src/components/application_manager/include/application_manager/commands/hmi/get_system_info_response.h
index 70983d3ce3..766a2869d9 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/get_system_info_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/get_system_info_response.h
@@ -34,35 +34,46 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_GET_SYSTEM_INFO_RESPONSE_H_
#include "application_manager/commands/hmi/response_from_hmi.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
+struct SystemInfo {
+ std::string ccpu_version;
+ std::string wers_country_code;
+ std::string language;
+};
+
/**
* @brief GetSystemInfoResponse command class
**/
class GetSystemInfoResponse : public ResponseFromHMI {
- public:
- /**
- * @brief GetSystemInfoResponse class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit GetSystemInfoResponse(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief GetSystemInfoResponse class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ GetSystemInfoResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+
+ /**
+ * @brief GetSystemInfoResponse class destructor
+ **/
+ virtual ~GetSystemInfoResponse();
- /**
- * @brief GetSystemInfoResponse class destructor
- **/
- virtual ~GetSystemInfoResponse();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ private:
+ const SystemInfo GetSystemInfo(
+ const hmi_apis::Common_Result::eType code) const;
- private:
- DISALLOW_COPY_AND_ASSIGN(GetSystemInfoResponse);
+ DISALLOW_COPY_AND_ASSIGN(GetSystemInfoResponse);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/get_urls.h b/src/components/application_manager/include/application_manager/commands/hmi/get_urls.h
index ac7cf80ac2..5f75f42d5c 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/get_urls.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/get_urls.h
@@ -38,51 +38,60 @@
namespace application_manager {
namespace commands {
-
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
/**
* @brief GetUrls command class
**/
class GetUrls : public RequestFromHMI {
- public:
- /**
- * @brief GetUrls class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit GetUrls(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief GetUrls class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ GetUrls(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief GetUrls class destructor
- **/
- virtual ~GetUrls();
+ /**
+ * @brief GetUrls class destructor
+ **/
+ virtual ~GetUrls();
- /**
- * @brief Execute command
- **/
- void Run() OVERRIDE;
+ /**
+ * @brief Execute command
+ **/
+ void Run() OVERRIDE;
- private:
+ private:
#ifdef EXTENDED_POLICY
- /**
- * @brief Processes URLs collecting for policy service
- * @param endpoints Endpoints section of policy table
- */
- void ProcessPolicyServiceURLs(const policy::EndpointUrls& endpoints);
+ /**
+ * @brief Processes URLs collecting for policy service
+ * @param endpoints Endpoints section of policy table
+ */
+ void ProcessPolicyServiceURLs(const policy::EndpointUrls& endpoints);
#endif
- /**
- * @brief Process URLs collecting for service
- * @param endpoints Endpoints section of policy table
- */
- void ProcessServiceURLs(const policy::EndpointUrls& endpoints);
+ /**
+ * @brief Process URLs collecting for service
+ * @param endpoints Endpoints section of policy table
+ */
+ void ProcessServiceURLs(const policy::EndpointUrls& endpoints);
+
+ /**
+ * @brief Sends response to HMI
+ * @param result Result code
+ */
+ void SendResponseToHMI(hmi_apis::Common_Result::eType result);
- /**
- * @brief Sends response to HMI
- * @param result Result code
- */
- void SendResponseToHMI(hmi_apis::Common_Result::eType result);
+ /**
+ * @brief fills structure for sending to HMI with default urls
+ * @param urls structure for filling
+ * @param endpoints Endpoints section of policy table
+ */
+ void FillSODefaultUrls(smart_objects::SmartObject& urls,
+ const policy::EndpointUrls& endpoints);
- DISALLOW_COPY_AND_ASSIGN(GetUrls);
+ DISALLOW_COPY_AND_ASSIGN(GetUrls);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/get_urls_response.h b/src/components/application_manager/include/application_manager/commands/hmi/get_urls_response.h
index 956e5a788e..1ca9ba93db 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/get_urls_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/get_urls_response.h
@@ -39,26 +39,27 @@ namespace application_manager {
namespace commands {
class GetUrlsResponse : public ResponseToHMI {
- public:
- /**
- * @brief GetUrlsResponse class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit GetUrlsResponse(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief GetUrlsResponse class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ GetUrlsResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief GetUrlsResponse class destructor
- **/
- virtual ~GetUrlsResponse();
+ /**
+ * @brief GetUrlsResponse class destructor
+ **/
+ virtual ~GetUrlsResponse();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(GetUrlsResponse);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(GetUrlsResponse);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/mixing_audio_supported_request.h b/src/components/application_manager/include/application_manager/commands/hmi/mixing_audio_supported_request.h
index 2957693c9e..4989208f7a 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/mixing_audio_supported_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/mixing_audio_supported_request.h
@@ -49,7 +49,8 @@ class MixingAudioSupportedRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit MixingAudioSupportedRequest(const MessageSharedPtr& message);
+ MixingAudioSupportedRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief MixingAudioSupportedRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/mixing_audio_supported_response.h b/src/components/application_manager/include/application_manager/commands/hmi/mixing_audio_supported_response.h
index e2b5affe34..a0cf89f558 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/mixing_audio_supported_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/mixing_audio_supported_response.h
@@ -49,7 +49,8 @@ class MixingAudioSupportedResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit MixingAudioSupportedResponse(const MessageSharedPtr& message);
+ MixingAudioSupportedResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief MixingAudioSupportedResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_alert_maneuver_request.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_alert_maneuver_request.h
index 58f85f829a..123c0ab0d6 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_alert_maneuver_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_alert_maneuver_request.h
@@ -49,7 +49,8 @@ class NaviAlertManeuverRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit NaviAlertManeuverRequest(const MessageSharedPtr& message);
+ NaviAlertManeuverRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief NaviAlertManeuverRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_alert_maneuver_response.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_alert_maneuver_response.h
index 11f46d5da8..d4a57e9e2f 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_alert_maneuver_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_alert_maneuver_response.h
@@ -49,7 +49,8 @@ class NaviAlertManeuverResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit NaviAlertManeuverResponse(const MessageSharedPtr& message);
+ NaviAlertManeuverResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief NaviAlertManeuverResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_start_stream_request.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_start_stream_request.h
index 3e95c6b16b..d6f4fd36e2 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_start_stream_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_start_stream_request.h
@@ -50,19 +50,19 @@ class AudioStartStreamRequest : public RequestToHMI,
*
* @param message Incoming SmartObject message
**/
- explicit AudioStartStreamRequest(const MessageSharedPtr& message);
+ AudioStartStreamRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnNaviStartStreamRequest class destructor
**/
virtual ~AudioStartStreamRequest();
- /**
- * @brief onTimeOut from requrst Controller
- */
+ /**
+ * @brief onTimeOut from requrst Controller
+ */
virtual void onTimeOut();
-
/**
* @brief Execute command
**/
@@ -73,13 +73,13 @@ class AudioStartStreamRequest : public RequestToHMI,
**/
virtual void on_event(const event_engine::Event& event);
- /**
- * @brief RetryStartSession resend HMI startSession request if needed.
- * If limit expired, set audio_stream_retry_number counter to 0
- */
+ /**
+ * @brief RetryStartSession resend HMI startSession request if needed.
+ * If limit expired, set audio_stream_retry_number counter to 0
+ */
void RetryStartSession();
- private:
+ private:
uint32_t retry_number_;
DISALLOW_COPY_AND_ASSIGN(AudioStartStreamRequest);
};
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_start_stream_response.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_start_stream_response.h
index 01992eb3b7..485b510bf2 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_start_stream_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_start_stream_response.h
@@ -48,7 +48,8 @@ class AudioStartStreamResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit AudioStartStreamResponse(const MessageSharedPtr& message);
+ AudioStartStreamResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief AudioStartStreamResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_stop_stream_request.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_stop_stream_request.h
index 04bba8b752..3a21e3e827 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_stop_stream_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_stop_stream_request.h
@@ -48,7 +48,8 @@ class AudioStopStreamRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit AudioStopStreamRequest(const MessageSharedPtr& message);
+ AudioStopStreamRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief NaviStopStreamRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_stop_stream_response.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_stop_stream_response.h
index 7275ac34d8..ce32d5b627 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_stop_stream_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_audio_stop_stream_response.h
@@ -48,7 +48,8 @@ class AudioStopStreamResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit AudioStopStreamResponse(const MessageSharedPtr& message);
+ AudioStopStreamResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnNaviStopStreamResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_get_way_points_request.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_get_way_points_request.h
new file mode 100644
index 0000000000..33c5dfe2db
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_get_way_points_request.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_GET_WAY_POINTS_REQUEST_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_GET_WAY_POINTS_REQUEST_H_
+
+#include "application_manager/commands/hmi/request_to_hmi.h"
+
+namespace application_manager {
+
+namespace commands {
+
+/**
+ * @brief NaviGetWayPointsRequest command class
+ **/
+class NaviGetWayPointsRequest : public RequestToHMI {
+ public:
+ /**
+ * @brief NaviGetWayPointsRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ NaviGetWayPointsRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+ /**
+ * @brief NaviGetWayPointsRequest class destructor
+ **/
+ virtual ~NaviGetWayPointsRequest();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run() OVERRIDE;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(NaviGetWayPointsRequest);
+};
+
+} // namespace commands
+
+} // namespace application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_GET_WAY_POINTS_REQUEST_H_
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_get_way_points_response.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_get_way_points_response.h
new file mode 100644
index 0000000000..633d927715
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_get_way_points_response.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_GET_WAY_POINTS_RESPONSE_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_GET_WAY_POINTS_RESPONSE_H_
+
+#include "application_manager/commands/hmi/response_from_hmi.h"
+
+namespace application_manager {
+
+namespace commands {
+
+/**
+ * @brief NaviGetWaypoints command class
+ **/
+class NaviGetWayPointsResponse : public ResponseFromHMI {
+ public:
+ /**
+ * @brief NaviGetWaypoints class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ NaviGetWayPointsResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+
+ /**
+ * @brief NaviGetWaypoints class destructor
+ **/
+ virtual ~NaviGetWayPointsResponse();
+
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run() OVERRIDE;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(NaviGetWayPointsResponse);
+};
+
+} // namespace commands
+
+} // namespace application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_GET_WAY_POINTS_RESPONSE_H_
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_is_ready_request.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_is_ready_request.h
index e779ecb699..9f1adaeee0 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_is_ready_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_is_ready_request.h
@@ -49,7 +49,8 @@ class NaviIsReadyRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit NaviIsReadyRequest(const MessageSharedPtr& message);
+ NaviIsReadyRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief NaviIsReadyRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_is_ready_response.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_is_ready_response.h
index 3da6933bc3..72c001b863 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_is_ready_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_is_ready_response.h
@@ -49,7 +49,8 @@ class NaviIsReadyResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit NaviIsReadyResponse(const MessageSharedPtr& message);
+ NaviIsReadyResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief NaviIsReadyResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_send_location_request.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_send_location_request.h
index 45474b532a..56a9594c0b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_send_location_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_send_location_request.h
@@ -49,7 +49,8 @@ class NaviSendLocationRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
*/
- explicit NaviSendLocationRequest(const MessageSharedPtr& message);
+ NaviSendLocationRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief NaviSendLocationRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_send_location_response.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_send_location_response.h
index ef9a605c36..ec3392642a 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_send_location_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_send_location_response.h
@@ -49,7 +49,8 @@ class NaviSendLocationResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
*/
- explicit NaviSendLocationResponse(const MessageSharedPtr& message);
+ NaviSendLocationResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief NaviSendLocationResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_show_constant_tbt_request.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_show_constant_tbt_request.h
index b866ce3e1f..4cb8ddd7f7 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_show_constant_tbt_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_show_constant_tbt_request.h
@@ -49,7 +49,8 @@ class NaviShowConstantTBTRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit NaviShowConstantTBTRequest(const MessageSharedPtr& message);
+ NaviShowConstantTBTRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief NaviShowConstantTBTRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_show_constant_tbt_response.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_show_constant_tbt_response.h
index 3f212985f9..d9e7b1d234 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_show_constant_tbt_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_show_constant_tbt_response.h
@@ -49,7 +49,8 @@ class NaviShowConstantTBTResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit NaviShowConstantTBTResponse(const MessageSharedPtr& message);
+ NaviShowConstantTBTResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief NaviShowConstantTBTResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_start_stream_request.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_start_stream_request.h
index 0e8cd39cc9..6fcb3f3267 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_start_stream_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_start_stream_request.h
@@ -44,44 +44,44 @@ namespace commands {
**/
class NaviStartStreamRequest : public RequestToHMI,
public event_engine::EventObserver {
- public:
- /**
- * @brief NaviStartStreamRequest class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit NaviStartStreamRequest(const MessageSharedPtr& message);
-
- /**
- * @brief OnNaviStartStreamRequest class destructor
- **/
- virtual ~NaviStartStreamRequest();
-
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ public:
+ /**
+ * @brief NaviStartStreamRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ NaviStartStreamRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief On event callback
- **/
- virtual void on_event(const event_engine::Event& event);
+ /**
+ * @brief OnNaviStartStreamRequest class destructor
+ **/
+ virtual ~NaviStartStreamRequest();
- /**
- * @brief onTimeOut from requrst Controller
- */
- virtual void onTimeOut();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
+ /**
+ * @brief On event callback
+ **/
+ virtual void on_event(const event_engine::Event& event);
- /**
- * @brief RetryStartSession resend HMI startSession request if needed.
- * If limit expired, set video_stream_retry_number counter to 0
+ /**
+ * @brief onTimeOut from requrst Controller
*/
- void RetryStartSession();
+ virtual void onTimeOut();
+
+ /**
+ * @brief RetryStartSession resend HMI startSession request if needed.
+ * If limit expired, set video_stream_retry_number counter to 0
+ */
+ void RetryStartSession();
- private:
- uint32_t retry_number_;
- DISALLOW_COPY_AND_ASSIGN(NaviStartStreamRequest);
+ private:
+ uint32_t retry_number_;
+ DISALLOW_COPY_AND_ASSIGN(NaviStartStreamRequest);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_start_stream_response.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_start_stream_response.h
index c94b6f219c..3e18767194 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_start_stream_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_start_stream_response.h
@@ -48,7 +48,8 @@ class NaviStartStreamResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit NaviStartStreamResponse(const MessageSharedPtr& message);
+ NaviStartStreamResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief NaviStartStreamResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_stop_stream_request.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_stop_stream_request.h
index 86b0981c22..d6952d0305 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_stop_stream_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_stop_stream_request.h
@@ -48,7 +48,8 @@ class NaviStopStreamRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit NaviStopStreamRequest(const MessageSharedPtr& message);
+ NaviStopStreamRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief NaviStopStreamRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_stop_stream_response.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_stop_stream_response.h
index 6f4986e4c7..b3107b5e61 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_stop_stream_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_stop_stream_response.h
@@ -48,7 +48,8 @@ class NaviStopStreamResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit NaviStopStreamResponse(const MessageSharedPtr& message);
+ NaviStopStreamResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnNaviStopStreamResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_subscribe_way_points_request.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_subscribe_way_points_request.h
new file mode 100644
index 0000000000..33a2077918
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_subscribe_way_points_request.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_SUBSCRIBE_WAY_POINTS_REQUEST_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_SUBSCRIBE_WAY_POINTS_REQUEST_H_
+
+#include "application_manager/commands/hmi/request_to_hmi.h"
+
+namespace application_manager {
+
+namespace commands {
+
+/**
+ * @brief NaviSubscribeWayPointsRequest command class
+ **/
+class NaviSubscribeWayPointsRequest : public RequestToHMI {
+ public:
+ /**
+ * @brief NaviSubscribeWayPointsRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ NaviSubscribeWayPointsRequest(const MessageSharedPtr& messag,
+ ApplicationManager& application_manager);
+ /**
+ * @brief NaviSubscribeWayPointsRequest class destructor
+ **/
+ virtual ~NaviSubscribeWayPointsRequest();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run() OVERRIDE;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(NaviSubscribeWayPointsRequest);
+};
+
+} // namespace commands
+
+} // namespace application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_SUBSCRIBE_WAY_POINTS_REQUEST_H_
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_subscribe_way_points_response.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_subscribe_way_points_response.h
new file mode 100644
index 0000000000..eff2b281f2
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_subscribe_way_points_response.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_SUBSCRIBE_WAY_POINTS_RESPONSE_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_SUBSCRIBE_WAY_POINTS_RESPONSE_H_
+
+#include "application_manager/commands/hmi/response_from_hmi.h"
+
+namespace application_manager {
+
+namespace commands {
+
+/**
+ * @brief NaviSubscribeWaypoints command class
+ **/
+class NaviSubscribeWayPointsResponse : public ResponseFromHMI {
+ public:
+ /**
+ * @brief NaviSubscribeWaypoints class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ NaviSubscribeWayPointsResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+
+ /**
+ * @brief NaviSubscribeWaypoints class destructor
+ **/
+ virtual ~NaviSubscribeWayPointsResponse();
+
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run() OVERRIDE;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(NaviSubscribeWayPointsResponse);
+};
+
+} // namespace commands
+
+} // namespace application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_SUBSCRIBE_WAY_POINTS_RESPONSE_H_
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_unsubscribe_way_points_request.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_unsubscribe_way_points_request.h
new file mode 100644
index 0000000000..607bb1ef26
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_unsubscribe_way_points_request.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_UNSUBSCRIBE_WAY_POINTS_REQUEST_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_UNSUBSCRIBE_WAY_POINTS_REQUEST_H_
+
+#include "application_manager/commands/hmi/request_to_hmi.h"
+
+namespace application_manager {
+
+namespace commands {
+
+/**
+ * @brief NaviSubscribeWayPointsRequest command class
+ **/
+class NaviUnSubscribeWayPointsRequest : public RequestToHMI {
+ public:
+ /**
+ * @brief NaviUnSubscribeWayPointsRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ NaviUnSubscribeWayPointsRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+ /**
+ * @brief NaviUnSubscribeWayPointsRequest class destructor
+ **/
+ virtual ~NaviUnSubscribeWayPointsRequest();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run() OVERRIDE;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(NaviUnSubscribeWayPointsRequest);
+};
+
+} // namespace commands
+
+} // namespace application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_UNSUBSCRIBE_WAY_POINTS_REQUEST_H_
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_unsubscribe_way_points_response.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_unsubscribe_way_points_response.h
new file mode 100644
index 0000000000..936814f2fe
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_unsubscribe_way_points_response.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_UNSUBSCRIBE_WAY_POINTS_RESPONSE_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_UNSUBSCRIBE_WAY_POINTS_RESPONSE_H_
+
+#include "application_manager/commands/hmi/response_from_hmi.h"
+
+namespace application_manager {
+
+namespace commands {
+
+/**
+ * @brief NaviUnSubscribeWaypoints command class
+ **/
+class NaviUnsubscribeWayPointsResponse : public ResponseFromHMI {
+ public:
+ /**
+ * @brief NaviUnSubscribeWaypoints class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ NaviUnsubscribeWayPointsResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+
+ /**
+ * @brief NaviUnSubscribeWaypoints class destructor
+ **/
+ virtual ~NaviUnsubscribeWayPointsResponse();
+
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run() OVERRIDE;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(NaviUnsubscribeWayPointsResponse);
+};
+
+} // namespace commands
+
+} // namespace application_manager
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_NAVI_UNSUBSCRIBE_WAY_POINTS_RESPONSE_H_
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_update_turn_list_request.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_update_turn_list_request.h
index a5e2f8bf37..830e9358ec 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_update_turn_list_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_update_turn_list_request.h
@@ -49,7 +49,8 @@ class NaviUpdateTurnListRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit NaviUpdateTurnListRequest(const MessageSharedPtr& message);
+ NaviUpdateTurnListRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief NaviUpdateTurnListRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/navi_update_turn_list_response.h b/src/components/application_manager/include/application_manager/commands/hmi/navi_update_turn_list_response.h
index 0e15a9175c..93c714b4f4 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/navi_update_turn_list_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/navi_update_turn_list_response.h
@@ -49,7 +49,8 @@ class NaviUpdateTurnListResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit NaviUpdateTurnListResponse(const MessageSharedPtr& message);
+ NaviUpdateTurnListResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief NaviUpdateTurnListResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/notification_from_hmi.h b/src/components/application_manager/include/application_manager/commands/hmi/notification_from_hmi.h
index 1dcae4366d..c74108ccf0 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/notification_from_hmi.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/notification_from_hmi.h
@@ -50,14 +50,16 @@ namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
class NotificationFromHMI : public CommandImpl {
public:
- explicit NotificationFromHMI(const MessageSharedPtr& message);
+ NotificationFromHMI(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
virtual ~NotificationFromHMI();
virtual bool Init();
virtual bool CleanUp();
virtual void Run();
void SendNotificationToMobile(const MessageSharedPtr& message);
void CreateHMIRequest(const hmi_apis::FunctionID::eType& function_id,
- const smart_objects::SmartObject& msg_params) const;
+ const smart_objects::SmartObject& msg_params) const;
+
private:
DISALLOW_COPY_AND_ASSIGN(NotificationFromHMI);
};
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/notification_to_hmi.h b/src/components/application_manager/include/application_manager/commands/hmi/notification_to_hmi.h
index 2372754b63..dd2db8804a 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/notification_to_hmi.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/notification_to_hmi.h
@@ -41,12 +41,14 @@ namespace commands {
class NotificationToHMI : public CommandImpl {
public:
- explicit NotificationToHMI(const MessageSharedPtr& message);
+ NotificationToHMI(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
virtual ~NotificationToHMI();
virtual bool Init();
virtual bool CleanUp();
virtual void Run();
void SendNotification();
+
private:
DISALLOW_COPY_AND_ASSIGN(NotificationToHMI);
};
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_allow_sdl_functionality_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_allow_sdl_functionality_notification.h
index 6ec14e35b0..ee7d22b859 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_allow_sdl_functionality_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_allow_sdl_functionality_notification.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief OnAllowSDLFunctionalityNotification command class
**/
class OnAllowSDLFunctionalityNotification : public NotificationFromHMI {
- public:
- /**
- * @brief OnAllowSDLFunctionalityNotification class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnAllowSDLFunctionalityNotification(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief OnAllowSDLFunctionalityNotification class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnAllowSDLFunctionalityNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief OnAllowSDLFunctionalityNotification class destructor
- **/
- virtual ~OnAllowSDLFunctionalityNotification();
+ /**
+ * @brief OnAllowSDLFunctionalityNotification class destructor
+ **/
+ virtual ~OnAllowSDLFunctionalityNotification();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(OnAllowSDLFunctionalityNotification);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnAllowSDLFunctionalityNotification);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_app_activated_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_app_activated_notification.h
index 011df3832c..a1de12b4d6 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_app_activated_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_app_activated_notification.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief OnAppActivatedNotification command class
**/
class OnAppActivatedNotification : public NotificationFromHMI {
- public:
- /**
- * @brief OnAppActivatedNotification class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnAppActivatedNotification(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief OnAppActivatedNotification class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnAppActivatedNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief OnAppActivatedNotification class destructor
- **/
- virtual ~OnAppActivatedNotification();
+ /**
+ * @brief OnAppActivatedNotification class destructor
+ **/
+ virtual ~OnAppActivatedNotification();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(OnAppActivatedNotification);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnAppActivatedNotification);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_app_deactivated_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_app_deactivated_notification.h
index 8731fc43f1..687d492a01 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_app_deactivated_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_app_deactivated_notification.h
@@ -49,7 +49,8 @@ class OnAppDeactivatedNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnAppDeactivatedNotification(const MessageSharedPtr& message);
+ OnAppDeactivatedNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnAppDeactivatedNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_app_permission_changed_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_app_permission_changed_notification.h
index c6ea82a15c..bdaf6d1119 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_app_permission_changed_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_app_permission_changed_notification.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief OnAppPermissionChangedNotification command class
**/
class OnAppPermissionChangedNotification : public NotificationToHMI {
- public:
- /**
- * @brief OnAppPermissionChangedNotification class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnAppPermissionChangedNotification(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief OnAppPermissionChangedNotification class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnAppPermissionChangedNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief OnAppPermissionChangedNotification class destructor
- **/
- virtual ~OnAppPermissionChangedNotification();
+ /**
+ * @brief OnAppPermissionChangedNotification class destructor
+ **/
+ virtual ~OnAppPermissionChangedNotification();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(OnAppPermissionChangedNotification);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnAppPermissionChangedNotification);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_app_permission_consent_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_app_permission_consent_notification.h
index ea36d55b39..5cafe0c1b5 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_app_permission_consent_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_app_permission_consent_notification.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief OnAppPermissionConsentNotification command class
**/
class OnAppPermissionConsentNotification : public NotificationFromHMI {
- public:
- /**
- * @brief OnAppPermissionConsentNotification class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnAppPermissionConsentNotification(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief OnAppPermissionConsentNotification class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnAppPermissionConsentNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief OnAppPermissionConsentNotification class destructor
- **/
- virtual ~OnAppPermissionConsentNotification();
+ /**
+ * @brief OnAppPermissionConsentNotification class destructor
+ **/
+ virtual ~OnAppPermissionConsentNotification();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(OnAppPermissionConsentNotification);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnAppPermissionConsentNotification);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_app_registered_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_app_registered_notification.h
index 1ebbfcd483..58e92a977a 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_app_registered_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_app_registered_notification.h
@@ -49,7 +49,8 @@ class OnAppRegisteredNotification : public NotificationToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnAppRegisteredNotification(const MessageSharedPtr& message);
+ OnAppRegisteredNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnAppRegisteredNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_app_unregistered_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_app_unregistered_notification.h
index 96fd19e9bc..980e558d6f 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_app_unregistered_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_app_unregistered_notification.h
@@ -49,7 +49,8 @@ class OnAppUnregisteredNotification : public NotificationToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnAppUnregisteredNotification(const MessageSharedPtr& message);
+ OnAppUnregisteredNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnAppUnregisteredNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_audio_data_streaming_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_audio_data_streaming_notification.h
index 97a979065e..121367ed90 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_audio_data_streaming_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_audio_data_streaming_notification.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief OnAudioDataStreamingNotification command class
**/
class OnAudioDataStreamingNotification : public NotificationToHMI {
- public:
- /**
- * @brief OnAudioDataStreamingNotification class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnAudioDataStreamingNotification(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief OnAudioDataStreamingNotification class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnAudioDataStreamingNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief OnAudioDataStreamingNotification class destructor
- **/
- virtual ~OnAudioDataStreamingNotification();
+ /**
+ * @brief OnAudioDataStreamingNotification class destructor
+ **/
+ virtual ~OnAudioDataStreamingNotification();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(OnAudioDataStreamingNotification);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnAudioDataStreamingNotification);
};
} // namespace commands
@@ -70,4 +71,3 @@ class OnAudioDataStreamingNotification : public NotificationToHMI {
} // namespace application_manager
#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_AUDIO_DATA_STREAMING_NOTIFICATION_H_
-
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_button_event_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_button_event_notification.h
index 0a56d7d924..f294bce2c8 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_button_event_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_button_event_notification.h
@@ -53,7 +53,8 @@ class OnButtonEventNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnButtonEventNotification(const MessageSharedPtr& message);
+ OnButtonEventNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief Execute command
@@ -64,7 +65,7 @@ class OnButtonEventNotification : public NotificationFromHMI {
DISALLOW_COPY_AND_ASSIGN(OnButtonEventNotification);
};
-} // namespace hmi
+} // namespace hmi
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_button_press_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_button_press_notification.h
index ce5f1de8f1..8936ed8a0f 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_button_press_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_button_press_notification.h
@@ -53,7 +53,8 @@ class OnButtonPressNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnButtonPressNotification(const MessageSharedPtr& message);
+ OnButtonPressNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief Execute command
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_button_subscription_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_button_subscription_notification.h
index c046380cd7..d98ba3a90b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_button_subscription_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_button_subscription_notification.h
@@ -51,7 +51,8 @@ class OnButtonSubscriptionNotification : public NotificationToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnButtonSubscriptionNotification(const MessageSharedPtr& message);
+ OnButtonSubscriptionNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnButtonSubscriptionNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_device_chosen_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_device_chosen_notification.h
index 17ba26b7f7..5345135583 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_device_chosen_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_device_chosen_notification.h
@@ -49,7 +49,8 @@ class OnDeviceChosenNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnDeviceChosenNotification(const MessageSharedPtr& message);
+ OnDeviceChosenNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnDeviceChosenNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_device_state_changed_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_device_state_changed_notification.h
index b87a6e2d9f..62a87f4599 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_device_state_changed_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_device_state_changed_notification.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief OnDeviceStateChangedNotification command class
**/
class OnDeviceStateChangedNotification : public NotificationFromHMI {
- public:
- /**
- * @brief OnDeviceStateChangedNotification class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnDeviceStateChangedNotification(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief OnDeviceStateChangedNotification class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnDeviceStateChangedNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief OnDeviceStateChangedNotification class destructor
- **/
- virtual ~OnDeviceStateChangedNotification();
+ /**
+ * @brief OnDeviceStateChangedNotification class destructor
+ **/
+ virtual ~OnDeviceStateChangedNotification();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(OnDeviceStateChangedNotification);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnDeviceStateChangedNotification);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_driver_distraction_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_driver_distraction_notification.h
index 01a87aae05..69d1707bf7 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_driver_distraction_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_driver_distraction_notification.h
@@ -53,7 +53,8 @@ class OnDriverDistractionNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnDriverDistractionNotification(const MessageSharedPtr& message);
+ OnDriverDistractionNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnDriverDistractionNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_emergency_event_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_emergency_event_notification.h
deleted file mode 100644
index aa82de4d89..0000000000
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_emergency_event_notification.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_EMERGENCY_EVENT_NOTIFICATION_H_
-#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_EMERGENCY_EVENT_NOTIFICATION_H_
-
-#include "application_manager/commands/hmi/notification_from_hmi.h"
-
-namespace application_manager {
-
-namespace commands {
-
-/**
- * @brief OnEmergencyEventNotification command class
- **/
-class OnEmergencyEventNotification : public NotificationFromHMI {
- public:
- /**
- * @brief OnEmergencyEventNotification class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnEmergencyEventNotification(const MessageSharedPtr& message);
-
- /**
- * @brief OnEmergencyEventNotification class destructor
- **/
- virtual ~OnEmergencyEventNotification();
-
- /**
- * @brief Execute command
- **/
- virtual void Run();
-
- private:
- DISALLOW_COPY_AND_ASSIGN(OnEmergencyEventNotification);
-};
-
-} // namespace commands
-
-} // namespace application_manager
-
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_EMERGENCY_EVENT_NOTIFICATION_H_
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_event_changed_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_event_changed_notification.h
new file mode 100644
index 0000000000..e066332d4c
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_event_changed_notification.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2013, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_EVENT_CHANGED_NOTIFICATION_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_EVENT_CHANGED_NOTIFICATION_H_
+
+#include "application_manager/commands/hmi/notification_from_hmi.h"
+
+namespace application_manager {
+
+namespace commands {
+
+/**
+ * @brief OnEventChangedNotification command class
+ **/
+class OnEventChangedNotification : public NotificationFromHMI {
+ public:
+ /**
+ * @brief OnEventChangedNotification class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnEventChangedNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+
+ /**
+ * @brief OnEventChangedNotification class destructor
+ **/
+ virtual ~OnEventChangedNotification();
+
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnEventChangedNotification);
+};
+
+} // namespace commands
+
+} // namespace application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_EVENT_CHANGED_NOTIFICATION_H_
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_exit_all_applications_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_exit_all_applications_notification.h
index 65d78f60c6..ad10a58bff 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_exit_all_applications_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_exit_all_applications_notification.h
@@ -49,7 +49,8 @@ class OnExitAllApplicationsNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnExitAllApplicationsNotification(const MessageSharedPtr& message);
+ OnExitAllApplicationsNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnExitAllApplicationsNotification class destructor
@@ -62,7 +63,6 @@ class OnExitAllApplicationsNotification : public NotificationFromHMI {
virtual void Run();
private:
-
/**
* @brief Notify's HMI that SDL stored all data required for resumption
**/
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_exit_application_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_exit_application_notification.h
index 479dd3a09c..275b266b98 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_exit_application_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_exit_application_notification.h
@@ -49,7 +49,8 @@ class OnExitApplicationNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnExitApplicationNotification(const MessageSharedPtr& message);
+ OnExitApplicationNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnExitApplicationNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_file_removed_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_file_removed_notification.h
index cc47705c82..3f1ac17fc4 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_file_removed_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_file_removed_notification.h
@@ -49,7 +49,8 @@ class OnFileRemovedNotification : public NotificationToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnFileRemovedNotification(const MessageSharedPtr& message);
+ OnFileRemovedNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnFileRemovedNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_find_applications.h b/src/components/application_manager/include/application_manager/commands/hmi/on_find_applications.h
index f9fb9cdb21..32db73c2f5 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_find_applications.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_find_applications.h
@@ -49,7 +49,8 @@ class OnFindApplications : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnFindApplications(const MessageSharedPtr& message);
+ OnFindApplications(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnFindApplications class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_ignition_cycle_over_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_ignition_cycle_over_notification.h
index f8fccdc382..acb1ff31ac 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_ignition_cycle_over_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_ignition_cycle_over_notification.h
@@ -50,7 +50,8 @@ class OnIgnitionCycleOverNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnIgnitionCycleOverNotification(const MessageSharedPtr& message);
+ OnIgnitionCycleOverNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnIgnitionCycleOverNotification class destructor
@@ -63,7 +64,6 @@ class OnIgnitionCycleOverNotification : public NotificationFromHMI {
virtual void Run();
private:
-
DISALLOW_COPY_AND_ASSIGN(OnIgnitionCycleOverNotification);
};
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_navi_tbt_client_state_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_navi_tbt_client_state_notification.h
index a657ffcc68..0150853546 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_navi_tbt_client_state_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_navi_tbt_client_state_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_NAVI_TBT_CLIENT_STATE_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnNaviTBTClientStateNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnNaviTBTClientStateNotification(const MessageSharedPtr& message);
+ OnNaviTBTClientStateNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnNaviTBTClientStateNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_navi_way_point_change_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_navi_way_point_change_notification.h
new file mode 100644
index 0000000000..d304685008
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_navi_way_point_change_notification.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_NAVI_WAY_POINT_CHANGE_NOTIFICATION_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_NAVI_WAY_POINT_CHANGE_NOTIFICATION_H_
+
+#include "application_manager/commands/hmi/notification_from_hmi.h"
+#include "application_manager/application_manager.h"
+
+namespace application_manager {
+
+namespace commands {
+
+/**
+ * @brief OnNaviWayPointChangeNotification command class
+ **/
+class OnNaviWayPointChangeNotification : public NotificationFromHMI {
+ public:
+ /**
+ * @brief OnNaviWayPointChangeNotification class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnNaviWayPointChangeNotification(const MessageSharedPtr& message,
+ ApplicationManager& app_man);
+
+ /**
+ * @brief OnNaviWayPointChangeNotification class destructor
+ **/
+ virtual ~OnNaviWayPointChangeNotification();
+
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run() OVERRIDE;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnNaviWayPointChangeNotification);
+};
+
+} // namespace commands
+
+} // namespace application_manager
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_NAVI_WAY_POINT_CHANGE_NOTIFICATION_H_
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_phone_call_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_phone_call_notification.h
deleted file mode 100644
index 45d831eb03..0000000000
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_phone_call_notification.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_PHONE_CALL_NOTIFICATION_H_
-#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_PHONE_CALL_NOTIFICATION_H_
-
-#include "application_manager/commands/hmi/notification_from_hmi.h"
-
-namespace application_manager {
-
-namespace commands {
-
-namespace hmi {
-
-
-/**
- * @brief OnPhoneCallNotification command class
- **/
-class OnPhoneCallNotification : public NotificationFromHMI {
- public:
- /**
- * @brief OnPhoneCallNotification class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnPhoneCallNotification(const MessageSharedPtr& message);
-
- /**
- * @brief OnPhoneCallNotification class destructor
- **/
- virtual ~OnPhoneCallNotification();
-
- /**
- * @brief Execute command
- **/
- virtual void Run();
-
- private:
- DISALLOW_COPY_AND_ASSIGN(OnPhoneCallNotification);
-};
-
-} // namespace hmi
-
-} // namespace commands
-
-} // namespace application_manager
-
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_PHONE_CALL_NOTIFICATION_H_
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_play_tone_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_play_tone_notification.h
deleted file mode 100644
index ceba0528fa..0000000000
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_play_tone_notification.h
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_PLAY_TONE_NOTIFICATION_H_
-#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_PLAY_TONE_NOTIFICATION_H_
-
-#include "application_manager/commands/hmi/notification_to_hmi.h"
-
-namespace application_manager {
-
-namespace commands {
-
-/**
- * @brief OnPlayToneNotification command class
- **/
-class OnPlayToneNotification : public NotificationToHMI {
- public:
- /**
- * @brief OnPlayToneNotification class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnPlayToneNotification(const MessageSharedPtr& message);
-
- /**
- * @brief OnPlayToneNotification class destructor
- **/
- virtual ~OnPlayToneNotification();
-
- /**
- * @brief Execute command
- **/
- virtual void Run();
-
- private:
- DISALLOW_COPY_AND_ASSIGN(OnPlayToneNotification);
-};
-
-} // namespace commands
-
-} // namespace application_manager
-
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_PLAY_TONE_NOTIFICATION_H_
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_policy_update.h b/src/components/application_manager/include/application_manager/commands/hmi/on_policy_update.h
index 81278fb75a..d4380048ee 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_policy_update.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_policy_update.h
@@ -39,26 +39,27 @@ namespace application_manager {
namespace commands {
class OnPolicyUpdate : public NotificationFromHMI {
- public:
- /**
- * @brief OnPolicyUpdate class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnPolicyUpdate(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief OnPolicyUpdate class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnPolicyUpdate(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief OnPolicyUpdate class destructor
- **/
- virtual ~OnPolicyUpdate();
+ /**
+ * @brief OnPolicyUpdate class destructor
+ **/
+ virtual ~OnPolicyUpdate();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(OnPolicyUpdate);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnPolicyUpdate);
};
} // namespace commands
} // namespace application_manager
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_put_file_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_put_file_notification.h
index bc60284309..809623fda0 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_put_file_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_put_file_notification.h
@@ -50,7 +50,8 @@ class OnPutFileNotification : public NotificationToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnPutFileNotification(const MessageSharedPtr& message);
+ OnPutFileNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnPutFileNotification class destructor
@@ -63,7 +64,6 @@ class OnPutFileNotification : public NotificationToHMI {
virtual void Run();
private:
-
DISALLOW_COPY_AND_ASSIGN(OnPutFileNotification);
};
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_ready_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_ready_notification.h
index 24fc52deac..7df1bf5ac0 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_ready_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_ready_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_READY_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnReadyNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnReadyNotification(const MessageSharedPtr& message);
+ OnReadyNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnReadyNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_received_policy_update.h b/src/components/application_manager/include/application_manager/commands/hmi/on_received_policy_update.h
index 4b61deef4f..4c2eacdae3 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_received_policy_update.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_received_policy_update.h
@@ -46,7 +46,8 @@ class OnReceivedPolicyUpdate : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnReceivedPolicyUpdate(const MessageSharedPtr& message);
+ OnReceivedPolicyUpdate(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnReceivedPolicyUpdate class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_record_start_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_record_start_notification.h
index 67cccdd816..fbb8a0522a 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_record_start_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_record_start_notification.h
@@ -49,7 +49,8 @@ class OnRecordStartdNotification : public NotificationToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnRecordStartdNotification(const MessageSharedPtr& message);
+ OnRecordStartdNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnRecordStartdNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_resume_audio_source_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_resume_audio_source_notification.h
index 03f84d0907..764ee6d180 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_resume_audio_source_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_resume_audio_source_notification.h
@@ -50,7 +50,8 @@ class OnResumeAudioSourceNotification : public NotificationToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnResumeAudioSourceNotification(const MessageSharedPtr& message);
+ OnResumeAudioSourceNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnResumeAudioSourceNotification class destructor
@@ -63,7 +64,6 @@ class OnResumeAudioSourceNotification : public NotificationToHMI {
virtual void Run();
private:
-
DISALLOW_COPY_AND_ASSIGN(OnResumeAudioSourceNotification);
};
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_sdl_close_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_sdl_close_notification.h
index 5b9ac04e8f..ef1d289ca7 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_sdl_close_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_sdl_close_notification.h
@@ -49,7 +49,8 @@ class OnSDLCloseNotification : public NotificationToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnSDLCloseNotification(const MessageSharedPtr& message);
+ OnSDLCloseNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnSdlCloseNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_sdl_consent_needed_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_sdl_consent_needed_notification.h
index 4f30873e4e..e54daab96f 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_sdl_consent_needed_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_sdl_consent_needed_notification.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief OnSDLConsentNeededNotification command class
**/
class OnSDLConsentNeededNotification : public NotificationToHMI {
- public:
- /**
- * @brief OnSDLConsentNeededNotification class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnSDLConsentNeededNotification(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief OnSDLConsentNeededNotification class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnSDLConsentNeededNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief OnSDLConsentNeededNotification class destructor
- **/
- virtual ~OnSDLConsentNeededNotification();
+ /**
+ * @brief OnSDLConsentNeededNotification class destructor
+ **/
+ virtual ~OnSDLConsentNeededNotification();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(OnSDLConsentNeededNotification);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnSDLConsentNeededNotification);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_sdl_persistence_complete_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_sdl_persistence_complete_notification.h
index 6f8f3a6e1a..6ac04b488b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_sdl_persistence_complete_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_sdl_persistence_complete_notification.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief OnSDLPersistenceCompleteNotification command class
**/
class OnSDLPersistenceCompleteNotification : public NotificationToHMI {
- public:
- /**
- * @brief OnSDLPersistenceCompleteNotification class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnSDLPersistenceCompleteNotification(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief OnSDLPersistenceCompleteNotification class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnSDLPersistenceCompleteNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief OnSDLPersistenceCompleteNotification class destructor
- **/
- virtual ~OnSDLPersistenceCompleteNotification();
+ /**
+ * @brief OnSDLPersistenceCompleteNotification class destructor
+ **/
+ virtual ~OnSDLPersistenceCompleteNotification();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(OnSDLPersistenceCompleteNotification);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnSDLPersistenceCompleteNotification);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_start_device_discovery.h b/src/components/application_manager/include/application_manager/commands/hmi/on_start_device_discovery.h
index bfa14f67fc..dc40c1a614 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_start_device_discovery.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_start_device_discovery.h
@@ -49,7 +49,8 @@ class OnStartDeviceDiscovery : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnStartDeviceDiscovery(const MessageSharedPtr& message);
+ OnStartDeviceDiscovery(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnStartDeviceDiscovery class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_status_update_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_status_update_notification.h
index c123826886..62ee38c473 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_status_update_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_status_update_notification.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief OnGetStatusUpdateNotification command class
**/
class OnStatusUpdateNotification : public NotificationToHMI {
- public:
- /**
- * @brief OnGetStatusUpdateNotification class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnStatusUpdateNotification(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief OnGetStatusUpdateNotification class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnStatusUpdateNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief OnGetStatusUpdateNotification class destructor
- **/
- virtual ~OnStatusUpdateNotification();
+ /**
+ * @brief OnGetStatusUpdateNotification class destructor
+ **/
+ virtual ~OnStatusUpdateNotification();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(OnStatusUpdateNotification);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnStatusUpdateNotification);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_system_context_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_system_context_notification.h
index 35d6f49daa..9008a20cc9 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_system_context_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_system_context_notification.h
@@ -51,7 +51,8 @@ class OnSystemContextNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnSystemContextNotification(const MessageSharedPtr& message);
+ OnSystemContextNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnSystemContextNotification class destructor
@@ -64,9 +65,6 @@ class OnSystemContextNotification : public NotificationFromHMI {
virtual void Run();
private:
- void SendSystemContextNotification(ApplicationSharedPtr app,
- mobile_api::SystemContext::eType system_context);
-
DISALLOW_COPY_AND_ASSIGN(OnSystemContextNotification);
};
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_system_error_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_system_error_notification.h
index ee7df7acd6..1e65b15c20 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_system_error_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_system_error_notification.h
@@ -49,7 +49,8 @@ class OnSystemErrorNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnSystemErrorNotification(const MessageSharedPtr& message);
+ OnSystemErrorNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnSystemErrorNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_system_info_changed_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_system_info_changed_notification.h
index 9b6c62782c..d709a5267c 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_system_info_changed_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_system_info_changed_notification.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief OnSystemInfoChangedNotification command class
**/
class OnSystemInfoChangedNotification : public NotificationFromHMI {
- public:
- /**
- * @brief OnSystemInfoChangedNotification class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnSystemInfoChangedNotification(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief OnSystemInfoChangedNotification class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnSystemInfoChangedNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief OnSystemInfoChangedNotification class destructor
- **/
- virtual ~OnSystemInfoChangedNotification();
+ /**
+ * @brief OnSystemInfoChangedNotification class destructor
+ **/
+ virtual ~OnSystemInfoChangedNotification();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(OnSystemInfoChangedNotification);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnSystemInfoChangedNotification);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_system_request_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_system_request_notification.h
index f1d25e24a4..8e4db24822 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_system_request_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_system_request_notification.h
@@ -50,7 +50,8 @@ class OnSystemRequestNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnSystemRequestNotification(const MessageSharedPtr& message);
+ OnSystemRequestNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnSystemRequestNotification class destructor
@@ -63,7 +64,6 @@ class OnSystemRequestNotification : public NotificationFromHMI {
virtual void Run();
private:
-
DISALLOW_COPY_AND_ASSIGN(OnSystemRequestNotification);
};
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_tts_language_change_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_tts_language_change_notification.h
index 79ae9b496e..245dc32386 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_tts_language_change_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_tts_language_change_notification.h
@@ -49,7 +49,8 @@ class OnTTSLanguageChangeNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnTTSLanguageChangeNotification(const MessageSharedPtr& message);
+ OnTTSLanguageChangeNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnTTSLanguageChangeNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_tts_reset_timeout_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_tts_reset_timeout_notification.h
index 11cb755544..be84a93215 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_tts_reset_timeout_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_tts_reset_timeout_notification.h
@@ -51,7 +51,8 @@ class OnTTSResetTimeoutNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnTTSResetTimeoutNotification(const MessageSharedPtr& message);
+ OnTTSResetTimeoutNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnTTSResetTimeoutNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_tts_started_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_tts_started_notification.h
index c7e88ac558..234d8036eb 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_tts_started_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_tts_started_notification.h
@@ -49,7 +49,8 @@ class OnTTSStartedNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnTTSStartedNotification(const MessageSharedPtr& message);
+ OnTTSStartedNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnTTSStartedNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_tts_stopped_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_tts_stopped_notification.h
index bf5dc7fb9e..4e058fde64 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_tts_stopped_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_tts_stopped_notification.h
@@ -49,7 +49,8 @@ class OnTTSStoppedNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject OnTTSStartedNotificationmessage
**/
- explicit OnTTSStoppedNotification(const MessageSharedPtr& message);
+ OnTTSStoppedNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnTTSStoppedNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_ui_command_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_ui_command_notification.h
index b4a0228c78..618bc13017 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_ui_command_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_ui_command_notification.h
@@ -49,7 +49,8 @@ class OnUICommandNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnUICommandNotification(const MessageSharedPtr& message);
+ OnUICommandNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnUICommandNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_ui_keyboard_input_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_ui_keyboard_input_notification.h
index 77b771065b..6e881dc94a 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_ui_keyboard_input_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_ui_keyboard_input_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_UI_KEYBOARD_INPUT_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -52,7 +52,8 @@ class OnUIKeyBoardInputNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnUIKeyBoardInputNotification(const MessageSharedPtr& message);
+ OnUIKeyBoardInputNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnUIKeyBoardInputNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_ui_language_change_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_ui_language_change_notification.h
index bcb661c89d..cc8cd1eb0e 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_ui_language_change_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_ui_language_change_notification.h
@@ -49,7 +49,8 @@ class OnUILanguageChangeNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnUILanguageChangeNotification(const MessageSharedPtr& message);
+ OnUILanguageChangeNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnUILanguageChangeNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_ui_reset_timeout_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_ui_reset_timeout_notification.h
index f97c8768b5..f5dd173998 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_ui_reset_timeout_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_ui_reset_timeout_notification.h
@@ -51,7 +51,8 @@ class OnUIResetTimeoutNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnUIResetTimeoutNotification(const MessageSharedPtr& message);
+ OnUIResetTimeoutNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnUIResetTimeoutNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_ui_touch_event_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_ui_touch_event_notification.h
index 6d8005e12f..9e9384fffe 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_ui_touch_event_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_ui_touch_event_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_UI_TOUCH_EVENT_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -52,7 +52,8 @@ class OnUITouchEventNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnUITouchEventNotification(const MessageSharedPtr& message);
+ OnUITouchEventNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnUITouchEventNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_update_device_list.h b/src/components/application_manager/include/application_manager/commands/hmi/on_update_device_list.h
index f56d01a5cc..ee53445606 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_update_device_list.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_update_device_list.h
@@ -49,7 +49,8 @@ class OnUpdateDeviceList : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnUpdateDeviceList(const MessageSharedPtr& message);
+ OnUpdateDeviceList(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnUpdateDeviceList class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_acc_pedal_position_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_acc_pedal_position_notification.h
index d591ab2be6..9c5a8cd955 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_acc_pedal_position_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_acc_pedal_position_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_ACC_PEDAL_POSITION_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIAccPedalPositionNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIAccPedalPositionNotification(const MessageSharedPtr& message);
+ OnVIAccPedalPositionNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIAccPedalPositionNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_belt_status_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_belt_status_notification.h
index f901462fdf..c4f92269bb 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_belt_status_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_belt_status_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_BELT_STATUS_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIBeltStatusNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIBeltStatusNotification(const MessageSharedPtr& message);
+ OnVIBeltStatusNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIBeltStatusNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_body_information_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_body_information_notification.h
index a0bc31778a..9d9854c50b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_body_information_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_body_information_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_BODY_INFORMATION_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIBodyInformationNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIBodyInformationNotification(const MessageSharedPtr& message);
+ OnVIBodyInformationNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIBodyInformationNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_device_status_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_device_status_notification.h
index 0e24616f3e..c31ee1f209 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_device_status_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_device_status_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_DEVICE_STATUS_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIDeviceStatusNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIDeviceStatusNotification(const MessageSharedPtr& message);
+ OnVIDeviceStatusNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIDeviceStatusNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_driver_braking_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_driver_braking_notification.h
index 0290388756..108f02b5a4 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_driver_braking_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_driver_braking_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_DRIVER_BRAKING_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIDriverBrakingNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIDriverBrakingNotification(const MessageSharedPtr& message);
+ OnVIDriverBrakingNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIDriverBrakingNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_engine_torque_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_engine_torque_notification.h
index 8307e5359e..bbd13963aa 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_engine_torque_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_engine_torque_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_ENGINE_TORQUE_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIEngineTorqueNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIEngineTorqueNotification(const MessageSharedPtr& message);
+ OnVIEngineTorqueNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIEngineTorqueNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_external_temperature_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_external_temperature_notification.h
index be5b086853..b996febacf 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_external_temperature_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_external_temperature_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_EXTERNAL_TEMPERATURE_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIExternalTemperatureNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIExternalTemperatureNotification(const MessageSharedPtr& message);
+ OnVIExternalTemperatureNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIExternalTemperatureNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_fuel_level_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_fuel_level_notification.h
index 83e6f845e0..9c30b6c32c 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_fuel_level_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_fuel_level_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_FUEL_LEVEL_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIFuelLevelNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIFuelLevelNotification(const MessageSharedPtr& message);
+ OnVIFuelLevelNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIFuelLevelNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_fuel_level_state_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_fuel_level_state_notification.h
index 42a6b8e0d9..53b6ea209f 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_fuel_level_state_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_fuel_level_state_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_FUEL_LEVEL_STATE_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIFuelLevelStateNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIFuelLevelStateNotification(const MessageSharedPtr& message);
+ OnVIFuelLevelStateNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIFuelLevelStateNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_gps_data_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_gps_data_notification.h
index 01c2cf60b6..579344b538 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_gps_data_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_gps_data_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_GPS_DATA_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIGpsDataNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIGpsDataNotification(const MessageSharedPtr& message);
+ OnVIGpsDataNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIGpsDataNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_head_lamp_status_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_head_lamp_status_notification.h
index dc80b33ddd..5fd3be85a4 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_head_lamp_status_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_head_lamp_status_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_HEAD_LAMP_STATUS_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIHeadLampStatusNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIHeadLampStatusNotification(const MessageSharedPtr& message);
+ OnVIHeadLampStatusNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIHeadLampStatusNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_instant_fuel_consumption_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_instant_fuel_consumption_notification.h
index c4e5accead..ee82b1397f 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_instant_fuel_consumption_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_instant_fuel_consumption_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_INSTANT_FUEL_CONSUMPTION_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIInstantFuelConsumptionNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIInstantFuelConsumptionNotification(const MessageSharedPtr& message);
+ OnVIInstantFuelConsumptionNotification(
+ const MessageSharedPtr& message, ApplicationManager& application_manager);
/**
* @brief OnVIInstantFuelConsumptionNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_my_key_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_my_key_notification.h
index e2d9d91ae1..364e42081c 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_my_key_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_my_key_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_MY_KEY_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIMyKeyNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIMyKeyNotification(const MessageSharedPtr& message);
+ OnVIMyKeyNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIMyKeyNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_odometer_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_odometer_notification.h
index 7c1c691ac5..7d93530f04 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_odometer_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_odometer_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_ODOMETER_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIOdometerNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIOdometerNotification(const MessageSharedPtr& message);
+ OnVIOdometerNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIOdometerNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_prndl_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_prndl_notification.h
index bf2ca83f8f..c09220d2a6 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_prndl_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_prndl_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_PRNDL_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIPrndlNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIPrndlNotification(const MessageSharedPtr& message);
+ OnVIPrndlNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIPrndlNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_rpm_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_rpm_notification.h
index ebcfe3a86c..d05e1221df 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_rpm_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_rpm_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_RPM_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIRpmNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIRpmNotification(const MessageSharedPtr& message);
+ OnVIRpmNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIRpmNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_speed_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_speed_notification.h
index 37bf66e4d0..b1908cde28 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_speed_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_speed_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_SPEED_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVISpeedNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVISpeedNotification(const MessageSharedPtr& message);
+ OnVISpeedNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVISpeedNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_steering_wheel_angle_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_steering_wheel_angle_notification.h
index bf01b2bf76..28f78ac4d5 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_steering_wheel_angle_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_steering_wheel_angle_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_STEERING_WHEEL_ANGLE_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVISteeringWheelAngleNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVISteeringWheelAngleNotification(const MessageSharedPtr& message);
+ OnVISteeringWheelAngleNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVISteeringWheelAngleNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_tire_pressure_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_tire_pressure_notification.h
index 1c1e00d893..eef4f0e4a4 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_tire_pressure_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_tire_pressure_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_TIRE_PRESSURE_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVITirePressureNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVITirePressureNotification(const MessageSharedPtr& message);
+ OnVITirePressureNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVITirePressureNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_vehicle_data_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_vehicle_data_notification.h
index 59da271a04..2422c47813 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_vehicle_data_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_vehicle_data_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_VEHICLE_DATA_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -51,7 +51,8 @@ class OnVIVehicleDataNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIVehicleDataNotification(const MessageSharedPtr& message);
+ OnVIVehicleDataNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIVehicleDataNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_vin_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_vin_notification.h
index 06b73c508d..4ea04fbb0d 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_vin_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_vin_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_VIN_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIVinNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIVinNotification(const MessageSharedPtr& message);
+ OnVIVinNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIVinNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_wiper_status_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_wiper_status_notification.h
index 399b38112e..2b57ef1dd3 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vi_wiper_status_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vi_wiper_status_notification.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VI_WIPER_STATUS_NOTIFICATION_H_
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -50,7 +50,8 @@ class OnVIWiperStatusNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVIWiperStatusNotification(const MessageSharedPtr& message);
+ OnVIWiperStatusNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVIWiperStatusNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_video_data_streaming_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_video_data_streaming_notification.h
index 38749ba8f8..02c65df4e9 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_video_data_streaming_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_video_data_streaming_notification.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief OnVideoDataStreamingNotification command class
**/
class OnVideoDataStreamingNotification : public NotificationToHMI {
- public:
- /**
- * @brief OnVideoDataStreamingNotification class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit OnVideoDataStreamingNotification(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief OnVideoDataStreamingNotification class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnVideoDataStreamingNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief OnVideoDataStreamingNotification class destructor
- **/
- virtual ~OnVideoDataStreamingNotification();
+ /**
+ * @brief OnVideoDataStreamingNotification class destructor
+ **/
+ virtual ~OnVideoDataStreamingNotification();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(OnVideoDataStreamingNotification);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnVideoDataStreamingNotification);
};
} // namespace commands
@@ -70,4 +71,3 @@ class OnVideoDataStreamingNotification : public NotificationToHMI {
} // namespace application_manager
#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_ON_VIDEO_DATA_STREAMING_NOTIFICATION_H_
-
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vr_command_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vr_command_notification.h
index 37bc2556f8..fa85ba8468 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vr_command_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vr_command_notification.h
@@ -50,7 +50,8 @@ class OnVRCommandNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVRCommandNotification(const MessageSharedPtr& message);
+ OnVRCommandNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVRCommandNotification class destructor
@@ -63,7 +64,6 @@ class OnVRCommandNotification : public NotificationFromHMI {
virtual void Run();
private:
-
DISALLOW_COPY_AND_ASSIGN(OnVRCommandNotification);
};
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vr_language_change_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vr_language_change_notification.h
index be408f0aa0..d0f86e5f83 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vr_language_change_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vr_language_change_notification.h
@@ -49,7 +49,8 @@ class OnVRLanguageChangeNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVRLanguageChangeNotification(const MessageSharedPtr& message);
+ OnVRLanguageChangeNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVRLanguageChangeNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vr_started_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vr_started_notification.h
index 5ae5ace27b..f142fcc25c 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vr_started_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vr_started_notification.h
@@ -49,7 +49,8 @@ class OnVRStartedNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVRStartedNotification(const MessageSharedPtr& message);
+ OnVRStartedNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVRStartedNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/on_vr_stopped_notification.h b/src/components/application_manager/include/application_manager/commands/hmi/on_vr_stopped_notification.h
index 311ee8acde..d1dbcc91cd 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/on_vr_stopped_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/on_vr_stopped_notification.h
@@ -49,7 +49,8 @@ class OnVRStoppedNotification : public NotificationFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit OnVRStoppedNotification(const MessageSharedPtr& message);
+ OnVRStoppedNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVRStoppedNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/request_from_hmi.h b/src/components/application_manager/include/application_manager/commands/hmi/request_from_hmi.h
index 9cb5a9f99d..c435c41c47 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/request_from_hmi.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/request_from_hmi.h
@@ -1,75 +1,82 @@
- /*
- Copyright (c) 2014, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
+/*
+ Copyright (c) 2014, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_REQUEST_FROM_HMI_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_REQUEST_FROM_HMI_H_
+
+#include "application_manager/commands/command_impl.h"
+#include "interfaces/HMI_API.h"
+
+namespace NsSmartDeviceLink {
+namespace NsSmartObjects {
+class SmartObject;
+}
+}
+
+namespace application_manager {
+
+namespace commands {
+
+namespace NsSmart = NsSmartDeviceLink::NsSmartObjects;
+
+class RequestFromHMI : public CommandImpl, public event_engine::EventObserver {
+ public:
+ RequestFromHMI(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+ virtual ~RequestFromHMI();
+ virtual bool Init();
+ virtual bool CleanUp();
+ virtual void Run();
+ virtual void on_event(const event_engine::Event& event);
+ /**
+ * @brief SendResponse allows to send response to hmi
+ * @param correlation_id the correlation id for the rfesponse.
+ * @param function_id the function id for which response will be sent
+ * @param result_code the result code.
*/
+ void SendResponse(const bool success,
+ const uint32_t correlation_id,
+ const hmi_apis::FunctionID::eType function_id,
+ const hmi_apis::Common_Result::eType result_code);
+
+ void FillCommonParametersOfSO(smart_objects::SmartObject* message,
+ uint32_t correlation_id,
+ hmi_apis::FunctionID::eType function_id);
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(RequestFromHMI);
+};
+
+} // namespace commands
+} // namespace application_manager
- #ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_REQUEST_FROM_HMI_H_
- #define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_REQUEST_FROM_HMI_H_
-
- #include "application_manager/commands/command_impl.h"
- #include "interfaces/HMI_API.h"
-
- namespace NsSmartDeviceLink {
- namespace NsSmartObjects {
- class SmartObject;
- }
- }
-
- namespace application_manager {
-
- namespace commands {
-
- namespace NsSmart = NsSmartDeviceLink::NsSmartObjects;
-
- class RequestFromHMI : public CommandImpl, public event_engine::EventObserver {
- public:
- explicit RequestFromHMI(const MessageSharedPtr& message);
- virtual ~RequestFromHMI();
- virtual bool Init();
- virtual bool CleanUp();
- virtual void Run();
- virtual void on_event(const event_engine::Event& event);
- /**
- * @brief SendResponse allows to send response to hmi
- * @param correlation_id the correlation id for the rfesponse.
- * @param function_id the function id for which response will be sent
- * @param result_code the result code.
- */
- void SendResponse(uint32_t correlation_id,
- hmi_apis::FunctionID::eType function_id,
- hmi_apis::Common_Result::eType result_code);
- private:
- DISALLOW_COPY_AND_ASSIGN(RequestFromHMI);
- };
-
- } // namespace commands
- } // namespace application_manager
-
- #endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_REQUEST_FROM_HMI_H_
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_REQUEST_FROM_HMI_H_
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/request_to_hmi.h b/src/components/application_manager/include/application_manager/commands/hmi/request_to_hmi.h
index fe359182dd..e512279e79 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/request_to_hmi.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/request_to_hmi.h
@@ -34,15 +34,16 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_REQUEST_TO_HMI_H_
#include "application_manager/commands/command_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
-
class RequestToHMI : public CommandImpl {
public:
- explicit RequestToHMI(const MessageSharedPtr& message);
+ RequestToHMI(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
virtual ~RequestToHMI();
virtual bool Init();
virtual bool CleanUp();
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/response_from_hmi.h b/src/components/application_manager/include/application_manager/commands/hmi/response_from_hmi.h
index 7769caa0a7..a5d41252f5 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/response_from_hmi.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/response_from_hmi.h
@@ -34,6 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_RESPONSE_FROM_HMI_H_
#include "application_manager/commands/command_impl.h"
+#include "application_manager/application_manager.h"
#include "interfaces/HMI_API.h"
namespace NsSmartDeviceLink {
@@ -50,12 +51,14 @@ namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
class ResponseFromHMI : public CommandImpl {
public:
- explicit ResponseFromHMI(const MessageSharedPtr& message);
+ ResponseFromHMI(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
virtual ~ResponseFromHMI();
virtual bool Init();
virtual bool CleanUp();
virtual void Run();
- void SendResponseToMobile(const MessageSharedPtr& message);
+ void SendResponseToMobile(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/*
* @brief Creates HMI request
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/response_to_hmi.h b/src/components/application_manager/include/application_manager/commands/hmi/response_to_hmi.h
index ce9e9469d0..f00e57ff3a 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/response_to_hmi.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/response_to_hmi.h
@@ -51,7 +51,8 @@ namespace NsSmart = NsSmartDeviceLink::NsSmartObjects;
class ResponseToHMI : public CommandImpl {
public:
- explicit ResponseToHMI(const MessageSharedPtr& message);
+ ResponseToHMI(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
virtual ~ResponseToHMI();
virtual bool Init();
virtual bool CleanUp();
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/sdl_activate_app_request.h b/src/components/application_manager/include/application_manager/commands/hmi/sdl_activate_app_request.h
index 58a7e9ecda..0dff904955 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/sdl_activate_app_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/sdl_activate_app_request.h
@@ -34,54 +34,74 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_SDL_ACTIVATE_APP_REQUEST_H_
#include "application_manager/commands/hmi/request_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
- typedef std::pair<ApplicationSharedPtr, std::vector<ApplicationSharedPtr> > DevicesApps;
/**
* @brief SDLActivateAppRequest command class
**/
class SDLActivateAppRequest : public RequestFromHMI {
- public:
- /**
- * @brief SDLActivateAppRequest class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit SDLActivateAppRequest(const MessageSharedPtr& message);
-
- /**
- * @brief SDLActivateAppRequest class destructor
- **/
- virtual ~SDLActivateAppRequest();
-
- /**
- * @brief Execute command
- **/
- virtual void Run();
-
- /**
- * @brief onTimeOut allows to process case when timeout has appeared
- * during request execution.
- */
- virtual void onTimeOut();
-
- /**
- * @brief on_event allows to handle events
- *
- * @param event event type that current request subscribed on.
- */
- virtual void on_event(const event_engine::Event& event);
- private:
- uint32_t app_id() const;
- uint32_t hmi_app_id(const smart_objects::SmartObject& so) const;
-
- DevicesApps FindAllAppOnParticularDevice(
- const connection_handler::DeviceHandle handle);
- DISALLOW_COPY_AND_ASSIGN(SDLActivateAppRequest);
+ public:
+ /**
+ * @brief Applications registered over protocol v4
+ */
+ typedef std::vector<application_manager::ApplicationSharedPtr> V4ProtoApps;
+
+ /**
+ * @brief SDLActivateAppRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ SDLActivateAppRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+
+ /**
+ * @brief SDLActivateAppRequest class destructor
+ **/
+ ~SDLActivateAppRequest() OVERRIDE;
+
+ /**
+ * @brief Execute command
+ **/
+ void Run() OVERRIDE;
+
+ /**
+ * @brief onTimeOut allows to process case when timeout has appeared
+ * during request execution.
+ */
+ void onTimeOut() OVERRIDE;
+
+ /**
+ * @brief on_event allows to handle events
+ *
+ * @param event event type that current request subscribed on.
+ */
+ void on_event(const event_engine::Event& event) OVERRIDE;
+
+ private:
+ uint32_t app_id() const;
+ uint32_t hmi_app_id(const smart_objects::SmartObject& so) const;
+
+ /**
+ * @brief Retrieves all v4 protocol applications for particular device
+ * @param handle Device handle
+ * @return List of applications registered over v4 protocol
+ */
+ V4ProtoApps get_v4_proto_apps(
+ const connection_handler::DeviceHandle handle) const;
+
+ /**
+ * @brief Get v4 protocol application reported as forgrounded on device
+ * @param handle Device
+ * @return Pointer to application or empty pointer
+ */
+ ApplicationSharedPtr get_foreground_app(
+ const connection_handler::DeviceHandle handle) const;
+
+ DISALLOW_COPY_AND_ASSIGN(SDLActivateAppRequest);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/sdl_activate_app_response.h b/src/components/application_manager/include/application_manager/commands/hmi/sdl_activate_app_response.h
index bf0789e60e..f35a295581 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/sdl_activate_app_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/sdl_activate_app_response.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief SDLActivateAppResponse command class
**/
class SDLActivateAppResponse : public ResponseToHMI {
- public:
- /**
- * @brief SDLActivateAppResponse class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit SDLActivateAppResponse(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief SDLActivateAppResponse class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ SDLActivateAppResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief SDLActivateAppResponse class destructor
- **/
- virtual ~SDLActivateAppResponse();
+ /**
+ * @brief SDLActivateAppResponse class destructor
+ **/
+ virtual ~SDLActivateAppResponse();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(SDLActivateAppResponse);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(SDLActivateAppResponse);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_list_of_permissions_request.h b/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_list_of_permissions_request.h
index 7c8f10529b..4f8d598322 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_list_of_permissions_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_list_of_permissions_request.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief SDLGetListOfPermissionsRequest command class
**/
class SDLGetListOfPermissionsRequest : public RequestFromHMI {
- public:
- /**
- * @brief SDLGetListOfPermissionsRequest class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit SDLGetListOfPermissionsRequest(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief SDLGetListOfPermissionsRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ SDLGetListOfPermissionsRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief SDLGetListOfPermissionsRequest class destructor
- **/
- virtual ~SDLGetListOfPermissionsRequest();
+ /**
+ * @brief SDLGetListOfPermissionsRequest class destructor
+ **/
+ virtual ~SDLGetListOfPermissionsRequest();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(SDLGetListOfPermissionsRequest);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(SDLGetListOfPermissionsRequest);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_list_of_permissions_response.h b/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_list_of_permissions_response.h
index 452784d92c..e00e613e70 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_list_of_permissions_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_list_of_permissions_response.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief SDLGetListOfPermissionsResponse command class
**/
class SDLGetListOfPermissionsResponse : public ResponseToHMI {
- public:
- /**
- * @brief SDLGetListOfPermissionsResponse class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit SDLGetListOfPermissionsResponse(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief SDLGetListOfPermissionsResponse class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ SDLGetListOfPermissionsResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief SDLGetListOfPermissionsResponse class destructor
- **/
- virtual ~SDLGetListOfPermissionsResponse();
+ /**
+ * @brief SDLGetListOfPermissionsResponse class destructor
+ **/
+ virtual ~SDLGetListOfPermissionsResponse();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(SDLGetListOfPermissionsResponse);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(SDLGetListOfPermissionsResponse);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_status_update_request.h b/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_status_update_request.h
index cb7d37d336..cfc0d55b54 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_status_update_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_status_update_request.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief SDLGetStatusUpdateRequest command class
**/
class SDLGetStatusUpdateRequest : public RequestFromHMI {
- public:
- /**
- * @brief SDLGetStatusUpdateRequest class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit SDLGetStatusUpdateRequest(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief SDLGetStatusUpdateRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ SDLGetStatusUpdateRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief SDLGetStatusUpdateRequest class destructor
- **/
- virtual ~SDLGetStatusUpdateRequest();
+ /**
+ * @brief SDLGetStatusUpdateRequest class destructor
+ **/
+ virtual ~SDLGetStatusUpdateRequest();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(SDLGetStatusUpdateRequest);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(SDLGetStatusUpdateRequest);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_status_update_response.h b/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_status_update_response.h
index a3fc0862b5..c25008bd90 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_status_update_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_status_update_response.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief SDLGetStatusUpdateResponse command class
**/
class SDLGetStatusUpdateResponse : public ResponseToHMI {
- public:
- /**
- * @brief SDLGetStatusUpdateResponse class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit SDLGetStatusUpdateResponse(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief SDLGetStatusUpdateResponse class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ SDLGetStatusUpdateResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief SDLGetStatusUpdateResponse class destructor
- **/
- virtual ~SDLGetStatusUpdateResponse();
+ /**
+ * @brief SDLGetStatusUpdateResponse class destructor
+ **/
+ virtual ~SDLGetStatusUpdateResponse();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(SDLGetStatusUpdateResponse);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(SDLGetStatusUpdateResponse);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_user_friendly_message_request.h b/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_user_friendly_message_request.h
index 96f46cfa3d..7d9fec337c 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_user_friendly_message_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_user_friendly_message_request.h
@@ -34,6 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_GET_USER_FRIENDLY_MESSAGE_REQUEST_H_
#include "application_manager/commands/hmi/request_from_hmi.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -43,26 +44,27 @@ namespace commands {
* @brief SDLGetUserFriendlyMessageRequest command class
**/
class SDLGetUserFriendlyMessageRequest : public RequestFromHMI {
- public:
- /**
- * @brief SDLGetUserFriendlyMessageRequest class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit SDLGetUserFriendlyMessageRequest(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief SDLGetUserFriendlyMessageRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ SDLGetUserFriendlyMessageRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief SDLGetUserFriendlyMessageRequest class destructor
- **/
- virtual ~SDLGetUserFriendlyMessageRequest();
+ /**
+ * @brief SDLGetUserFriendlyMessageRequest class destructor
+ **/
+ virtual ~SDLGetUserFriendlyMessageRequest();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(SDLGetUserFriendlyMessageRequest);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(SDLGetUserFriendlyMessageRequest);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_user_friendly_message_response.h b/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_user_friendly_message_response.h
index 4cf7be56c9..43c440c277 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_user_friendly_message_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/sdl_get_user_friendly_message_response.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief SDLGetUserFriendlyMessageResponse command class
**/
class SDLGetUserFriendlyMessageResponse : public ResponseToHMI {
- public:
- /**
- * @brief SDLGetUserFriendlyMessageResponse class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit SDLGetUserFriendlyMessageResponse(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief SDLGetUserFriendlyMessageResponse class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ SDLGetUserFriendlyMessageResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief SDLGetUserFriendlyMessageResponse class destructor
- **/
- virtual ~SDLGetUserFriendlyMessageResponse();
+ /**
+ * @brief SDLGetUserFriendlyMessageResponse class destructor
+ **/
+ virtual ~SDLGetUserFriendlyMessageResponse();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(SDLGetUserFriendlyMessageResponse);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(SDLGetUserFriendlyMessageResponse);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/sdl_policy_update.h b/src/components/application_manager/include/application_manager/commands/hmi/sdl_policy_update.h
index 9cffc8644d..6cf4646163 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/sdl_policy_update.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/sdl_policy_update.h
@@ -46,7 +46,8 @@ class SDLPolicyUpdate : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit SDLPolicyUpdate(const MessageSharedPtr& message);
+ SDLPolicyUpdate(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
~SDLPolicyUpdate() OVERRIDE;
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/sdl_policy_update_response.h b/src/components/application_manager/include/application_manager/commands/hmi/sdl_policy_update_response.h
index d3f7105523..53e9e796bf 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/sdl_policy_update_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/sdl_policy_update_response.h
@@ -40,26 +40,27 @@ namespace application_manager {
namespace commands {
class SDLPolicyUpdateResponse : public ResponseFromHMI {
- public:
- /**
- * @brief SDLPolicyUpdateResponse class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit SDLPolicyUpdateResponse(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief SDLPolicyUpdateResponse class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ SDLPolicyUpdateResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief SDLPolicyUpdateResponse class destructor
- **/
- virtual ~SDLPolicyUpdateResponse();
+ /**
+ * @brief SDLPolicyUpdateResponse class destructor
+ **/
+ virtual ~SDLPolicyUpdateResponse();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(SDLPolicyUpdateResponse);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(SDLPolicyUpdateResponse);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_change_registration_request.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_change_registration_request.h
index a25309e5d5..0f36e82b44 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_change_registration_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_change_registration_request.h
@@ -49,7 +49,8 @@ class TTSChangeRegistrationRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit TTSChangeRegistrationRequest(const MessageSharedPtr& message);
+ TTSChangeRegistrationRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSChangeRegistrationRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_change_registration_response.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_change_registration_response.h
index 73ad180286..ca9c114156 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_change_registration_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_change_registration_response.h
@@ -49,7 +49,8 @@ class TTSChangeRegistratioResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit TTSChangeRegistratioResponse(const MessageSharedPtr& message);
+ TTSChangeRegistratioResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSChangeRegistratioResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_get_capabilities_request.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_get_capabilities_request.h
index 543945e8ef..bea41b7371 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_get_capabilities_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_get_capabilities_request.h
@@ -49,7 +49,8 @@ class TTSGetCapabilitiesRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit TTSGetCapabilitiesRequest(const MessageSharedPtr& message);
+ TTSGetCapabilitiesRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSGetCapabilitiesRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_get_capabilities_response.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_get_capabilities_response.h
index 2fc16d1a40..a70ee2b33b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_get_capabilities_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_get_capabilities_response.h
@@ -49,7 +49,8 @@ class TTSGetCapabilitiesResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit TTSGetCapabilitiesResponse(const MessageSharedPtr& message);
+ TTSGetCapabilitiesResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSGetCapabilitiesResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_get_language_request.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_get_language_request.h
index e0ae0da0c4..627cf3da06 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_get_language_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_get_language_request.h
@@ -49,7 +49,8 @@ class TTSGetLanguageRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit TTSGetLanguageRequest(const MessageSharedPtr& message);
+ TTSGetLanguageRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSGetLanguageRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_get_language_response.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_get_language_response.h
index 0d9df07ae6..f44492a6ed 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_get_language_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_get_language_response.h
@@ -49,7 +49,8 @@ class TTSGetLanguageResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit TTSGetLanguageResponse(const MessageSharedPtr& message);
+ TTSGetLanguageResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSGetLanguageResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_get_supported_languages_request.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_get_supported_languages_request.h
index 136edbb5f4..9500d54eea 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_get_supported_languages_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_get_supported_languages_request.h
@@ -49,7 +49,8 @@ class TTSGetSupportedLanguagesRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit TTSGetSupportedLanguagesRequest(const MessageSharedPtr& message);
+ TTSGetSupportedLanguagesRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSGetSupportedLanguagesRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_get_supported_languages_response.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_get_supported_languages_response.h
index 38e3c673bb..1bc569ebb8 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_get_supported_languages_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_get_supported_languages_response.h
@@ -49,7 +49,8 @@ class TTSGetSupportedLanguagesResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit TTSGetSupportedLanguagesResponse(const MessageSharedPtr& message);
+ TTSGetSupportedLanguagesResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSGetSupportedLanguagesResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_is_ready_request.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_is_ready_request.h
index 676faabc01..81bd8eb27b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_is_ready_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_is_ready_request.h
@@ -49,7 +49,8 @@ class TTSIsReadyRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit TTSIsReadyRequest(const MessageSharedPtr& message);
+ TTSIsReadyRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSIsReadyRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_is_ready_response.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_is_ready_response.h
index 12bb3bb870..833d3d0a82 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_is_ready_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_is_ready_response.h
@@ -49,7 +49,8 @@ class TTSIsReadyResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit TTSIsReadyResponse(const MessageSharedPtr& message);
+ TTSIsReadyResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSIsReadyResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_set_global_properties_request.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_set_global_properties_request.h
index 92a260d77f..b18e372b3e 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_set_global_properties_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_set_global_properties_request.h
@@ -49,7 +49,8 @@ class TTSSetGlobalPropertiesRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit TTSSetGlobalPropertiesRequest(const MessageSharedPtr& message);
+ TTSSetGlobalPropertiesRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSSetGlobalPropertiesRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_set_global_properties_response.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_set_global_properties_response.h
index 0766decf9f..aa7c85eece 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_set_global_properties_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_set_global_properties_response.h
@@ -49,7 +49,8 @@ class TTSSetGlobalPropertiesResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit TTSSetGlobalPropertiesResponse(const MessageSharedPtr& message);
+ TTSSetGlobalPropertiesResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSSetGlobalPropertiesResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_speak_request.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_speak_request.h
index f5555f6495..87384beedf 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_speak_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_speak_request.h
@@ -42,15 +42,15 @@ namespace commands {
/**
* @brief TTSSpeakRequest command class
**/
-class TTSSpeakRequest
- : public RequestToHMI {
+class TTSSpeakRequest : public RequestToHMI {
public:
/**
* @brief TTSSpeakRequest class constructor
*
* @param message Incoming SmartObject message
**/
- explicit TTSSpeakRequest(const MessageSharedPtr& message);
+ TTSSpeakRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSSpeakRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_speak_response.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_speak_response.h
index 541ea0d2ab..9f15afb33b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_speak_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_speak_response.h
@@ -42,15 +42,15 @@ namespace commands {
/**
* @brief TTSSpeakResponse command class
**/
-class TTSSpeakResponse
- : public ResponseFromHMI {
+class TTSSpeakResponse : public ResponseFromHMI {
public:
/**
* @brief TTSSpeakResponse class constructor
*
* @param message Incoming SmartObject message
**/
- explicit TTSSpeakResponse(const MessageSharedPtr& message);
+ TTSSpeakResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSSpeakResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_stop_speaking_request.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_stop_speaking_request.h
index 46c464425d..c51daee84d 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_stop_speaking_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_stop_speaking_request.h
@@ -49,7 +49,8 @@ class TTSStopSpeakingRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit TTSStopSpeakingRequest(const MessageSharedPtr& message);
+ TTSStopSpeakingRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSStopSpeakingRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/tts_stop_speaking_response.h b/src/components/application_manager/include/application_manager/commands/hmi/tts_stop_speaking_response.h
index aab8ca8c5b..a23889a733 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/tts_stop_speaking_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/tts_stop_speaking_response.h
@@ -49,7 +49,8 @@ class TTSStopSpeakingResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit TTSStopSpeakingResponse(const MessageSharedPtr& message);
+ TTSStopSpeakingResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSStopSpeakingResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_add_command_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_add_command_request.h
index 6b857818e7..294fd11912 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_add_command_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_add_command_request.h
@@ -49,7 +49,8 @@ class UIAddCommandRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIAddCommandRequest(const MessageSharedPtr& message);
+ UIAddCommandRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIAddCommandRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_add_command_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_add_command_response.h
index c6a02fdd03..ed48e13322 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_add_command_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_add_command_response.h
@@ -49,7 +49,8 @@ class UIAddCommandResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIAddCommandResponse(const MessageSharedPtr& message);
+ UIAddCommandResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIAddCommandResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_add_submenu_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_add_submenu_request.h
index bba9a4c47e..96fa0557ae 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_add_submenu_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_add_submenu_request.h
@@ -49,7 +49,8 @@ class UIAddSubmenuRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIAddSubmenuRequest(const MessageSharedPtr& message);
+ UIAddSubmenuRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIAddSubmenuRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_add_submenu_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_add_submenu_response.h
index 0c4afc2fa3..62abf10b60 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_add_submenu_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_add_submenu_response.h
@@ -49,7 +49,8 @@ class UIAddSubmenuResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIAddSubmenuResponse(const MessageSharedPtr& message);
+ UIAddSubmenuResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIAddSubmenuResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_alert_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_alert_request.h
index 72cd733eb5..123246e596 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_alert_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_alert_request.h
@@ -49,7 +49,8 @@ class UIAlertRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIAlertRequest(const MessageSharedPtr& message);
+ UIAlertRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIAlertRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_alert_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_alert_response.h
index 97eb2ba94b..db48699a23 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_alert_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_alert_response.h
@@ -49,7 +49,8 @@ class UIAlertResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIAlertResponse(const MessageSharedPtr& message);
+ UIAlertResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIAlertResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_change_registration_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_change_registration_request.h
index 8e68dee2ec..744ed82cad 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_change_registration_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_change_registration_request.h
@@ -49,7 +49,8 @@ class UIChangeRegistrationRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIChangeRegistrationRequest(const MessageSharedPtr& message);
+ UIChangeRegistrationRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIChangeRegistrationRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_change_registration_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_change_registration_response.h
index 50b092639b..57814b9acf 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_change_registration_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_change_registration_response.h
@@ -49,7 +49,8 @@ class UIChangeRegistratioResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIChangeRegistratioResponse(const MessageSharedPtr& message);
+ UIChangeRegistratioResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIChangeRegistratioResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_command_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_command_request.h
index 9eceb2eb6f..21a4c6dd42 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_command_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_command_request.h
@@ -49,7 +49,8 @@ class UIDeleteCommandRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIDeleteCommandRequest(const MessageSharedPtr& message);
+ UIDeleteCommandRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIDeleteCommandRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_command_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_command_response.h
index c4d7ab6cac..c9baba728f 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_command_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_command_response.h
@@ -49,7 +49,8 @@ class UIDeleteCommandResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIDeleteCommandResponse(const MessageSharedPtr& message);
+ UIDeleteCommandResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIDeleteCommandResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_submenu_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_submenu_request.h
index 24bf5878ff..d238e39a10 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_submenu_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_submenu_request.h
@@ -49,7 +49,8 @@ class UIDeleteSubmenuRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIDeleteSubmenuRequest(const MessageSharedPtr& message);
+ UIDeleteSubmenuRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIDeleteSubmenuRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_submenu_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_submenu_response.h
index 05d77c82d7..36d7bee528 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_submenu_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_delete_submenu_response.h
@@ -49,7 +49,8 @@ class UIDeleteSubmenuResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIDeleteSubmenuResponse(const MessageSharedPtr& message);
+ UIDeleteSubmenuResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIDeleteSubmenuResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_end_audio_pass_thru_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_end_audio_pass_thru_request.h
index 06637fc8d4..d8bd10a9ca 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_end_audio_pass_thru_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_end_audio_pass_thru_request.h
@@ -50,7 +50,8 @@ class UIEndAudioPassThruRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIEndAudioPassThruRequest(const MessageSharedPtr& message);
+ UIEndAudioPassThruRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIEndAudioPassThruRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_end_audio_pass_thru_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_end_audio_pass_thru_response.h
index 6d5594f69f..c2a373d8c0 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_end_audio_pass_thru_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_end_audio_pass_thru_response.h
@@ -49,7 +49,8 @@ class UIEndAudioPassThruResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIEndAudioPassThruResponse(const MessageSharedPtr& message);
+ UIEndAudioPassThruResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIEndAudioPassThruResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_get_capabilities_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_get_capabilities_request.h
index ad9a566078..cffba5ca42 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_get_capabilities_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_get_capabilities_request.h
@@ -49,7 +49,8 @@ class UIGetCapabilitiesRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIGetCapabilitiesRequest(const MessageSharedPtr& message);
+ UIGetCapabilitiesRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIGetCapabilitiesRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_get_capabilities_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_get_capabilities_response.h
index ce6ad6f7ef..525dd7ad9d 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_get_capabilities_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_get_capabilities_response.h
@@ -49,7 +49,8 @@ class UIGetCapabilitiesResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIGetCapabilitiesResponse(const MessageSharedPtr& message);
+ UIGetCapabilitiesResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIGetCapabilitiesResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_get_language_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_get_language_request.h
index 7371cd1031..4bf8e11d7e 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_get_language_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_get_language_request.h
@@ -49,7 +49,8 @@ class UIGetLanguageRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIGetLanguageRequest(const MessageSharedPtr& message);
+ UIGetLanguageRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIGetLanguageRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_get_language_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_get_language_response.h
index f6536452ce..29bbba85ff 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_get_language_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_get_language_response.h
@@ -49,7 +49,8 @@ class UIGetLanguageResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIGetLanguageResponse(const MessageSharedPtr& message);
+ UIGetLanguageResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIGetLanguageResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_get_supported_languages_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_get_supported_languages_request.h
index d0975e68da..94c197b7bc 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_get_supported_languages_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_get_supported_languages_request.h
@@ -49,7 +49,8 @@ class UIGetSupportedLanguagesRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIGetSupportedLanguagesRequest(const MessageSharedPtr& message);
+ UIGetSupportedLanguagesRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIGetSupportedLanguagesRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_get_supported_languages_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_get_supported_languages_response.h
index c888c7b208..8962b77833 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_get_supported_languages_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_get_supported_languages_response.h
@@ -49,7 +49,8 @@ class UIGetSupportedLanguagesResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIGetSupportedLanguagesResponse(const MessageSharedPtr& message);
+ UIGetSupportedLanguagesResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIGetSupportedLanguagesResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_is_ready_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_is_ready_request.h
index 7cb4287244..a505df6de4 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_is_ready_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_is_ready_request.h
@@ -49,7 +49,8 @@ class UIIsReadyRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIIsReadyRequest(const MessageSharedPtr& message);
+ UIIsReadyRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIIsReadyRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_is_ready_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_is_ready_response.h
index 64106654e9..93b2d9a569 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_is_ready_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_is_ready_response.h
@@ -49,7 +49,8 @@ class UIIsReadyResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIIsReadyResponse(const MessageSharedPtr& message);
+ UIIsReadyResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIIsReadyResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_request.h
index 69566324f2..4cec5a5600 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_request.h
@@ -49,7 +49,8 @@ class UIPerformAudioPassThruRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIPerformAudioPassThruRequest(const MessageSharedPtr& message);
+ UIPerformAudioPassThruRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIPerformAudioPassThruRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_response.h
index c3283101f9..9fb502233f 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_response.h
@@ -49,7 +49,8 @@ class UIPerformAudioPassThruResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIPerformAudioPassThruResponse(const MessageSharedPtr& message);
+ UIPerformAudioPassThruResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIPerformAudioPassThruResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_interaction_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_interaction_request.h
index d8e2f6c682..d9ae72a319 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_interaction_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_interaction_request.h
@@ -49,7 +49,8 @@ class UIPerformInteractionRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIPerformInteractionRequest(const MessageSharedPtr& message);
+ UIPerformInteractionRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIPerformInteractionRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_interaction_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_interaction_response.h
index 04286897a3..4db471bbae 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_interaction_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_perform_interaction_response.h
@@ -49,7 +49,8 @@ class UIPerformInteractionResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIPerformInteractionResponse(const MessageSharedPtr& message);
+ UIPerformInteractionResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIPerformInteractionResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_scrollable_message_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_scrollable_message_request.h
index 06bfadbae7..8ba828a25e 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_scrollable_message_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_scrollable_message_request.h
@@ -49,7 +49,8 @@ class UIScrollableMessageRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIScrollableMessageRequest(const MessageSharedPtr& message);
+ UIScrollableMessageRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIScrollableMessageRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_scrollable_message_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_scrollable_message_response.h
index 6d6d09c313..4ae432d658 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_scrollable_message_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_scrollable_message_response.h
@@ -49,7 +49,8 @@ class UIScrollableMessageResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIScrollableMessageResponse(const MessageSharedPtr& message);
+ UIScrollableMessageResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIScrollableMessageResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_app_icon_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_app_icon_request.h
index 96f91d0f82..c016cf7cda 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_app_icon_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_app_icon_request.h
@@ -49,7 +49,8 @@ class UISetAppIconRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UISetAppIconRequest(const MessageSharedPtr& message);
+ UISetAppIconRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UISetIconRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_app_icon_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_app_icon_response.h
index b323a91c36..640e43c9f4 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_app_icon_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_app_icon_response.h
@@ -49,7 +49,8 @@ class UISetAppIconResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UISetAppIconResponse(const MessageSharedPtr& message);
+ UISetAppIconResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UISetIconResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_display_layout_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_display_layout_request.h
index 7e67912f53..573e9351b1 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_display_layout_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_display_layout_request.h
@@ -42,26 +42,27 @@ namespace commands {
* @brief UiSetDisplayLayoutRequest command class
**/
class UiSetDisplayLayoutRequest : public RequestToHMI {
- public:
- /**
- * @brief UiSetDisplayLayoutRequest class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit UiSetDisplayLayoutRequest(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief UiSetDisplayLayoutRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ UiSetDisplayLayoutRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief UiSetDisplayLayoutRequest class destructor
- **/
- virtual ~UiSetDisplayLayoutRequest();
+ /**
+ * @brief UiSetDisplayLayoutRequest class destructor
+ **/
+ virtual ~UiSetDisplayLayoutRequest();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(UiSetDisplayLayoutRequest);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(UiSetDisplayLayoutRequest);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_display_layout_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_display_layout_response.h
index 3e7a898af0..7b8098fdf5 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_display_layout_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_display_layout_response.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief UiSetDisplayLayoutResponse command class
**/
class UiSetDisplayLayoutResponse : public ResponseFromHMI {
- public:
- /**
- * @brief UiSetDisplayLayoutResponse class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit UiSetDisplayLayoutResponse(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief UiSetDisplayLayoutResponse class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ UiSetDisplayLayoutResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief UiSetDisplayLayoutResponse class destructor
- **/
- virtual ~UiSetDisplayLayoutResponse();
+ /**
+ * @brief UiSetDisplayLayoutResponse class destructor
+ **/
+ virtual ~UiSetDisplayLayoutResponse();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(UiSetDisplayLayoutResponse);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(UiSetDisplayLayoutResponse);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_global_properties_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_global_properties_request.h
index 8b54e85332..83bf11e2e1 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_global_properties_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_global_properties_request.h
@@ -49,7 +49,8 @@ class UISetGlobalPropertiesRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UISetGlobalPropertiesRequest(const MessageSharedPtr& message);
+ UISetGlobalPropertiesRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIShowRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_global_properties_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_global_properties_response.h
index b3cb38d49f..91de5e6df7 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_global_properties_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_global_properties_response.h
@@ -49,7 +49,8 @@ class UISetGlobalPropertiesResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UISetGlobalPropertiesResponse(const MessageSharedPtr& message);
+ UISetGlobalPropertiesResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UISetGlobalPropertiesResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_icon_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_icon_request.h
index 1541aada6b..34bef8a989 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_icon_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_icon_request.h
@@ -1,5 +1,5 @@
-/**
- * Copyright (c) 2013, Ford Motor Company
+/*
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -49,7 +49,7 @@ class UISetIconRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UISetIconRequest(const MessageSharedPtr& message);
+ UISetIconRequest(const MessageSharedPtr& message);
/**
* @brief UISetIconRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_icon_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_icon_response.h
index f125f64282..a9739bc802 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_icon_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_icon_response.h
@@ -1,5 +1,5 @@
-/**
- * Copyright (c) 2013, Ford Motor Company
+/*
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -49,7 +49,7 @@ class UISetIconResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UISetIconResponse(const MessageSharedPtr& message);
+ UISetIconResponse(const MessageSharedPtr& message);
/**
* @brief UISetIconResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_media_clock_timer_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_media_clock_timer_request.h
index 443fc8d1a7..92565e6f02 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_media_clock_timer_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_media_clock_timer_request.h
@@ -49,7 +49,8 @@ class UISetMediaClockTimerRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UISetMediaClockTimerRequest(const MessageSharedPtr& message);
+ UISetMediaClockTimerRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UISetMediaClockTimerRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_media_clock_timer_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_media_clock_timer_response.h
index 9358707117..0d71ff00f0 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_set_media_clock_timer_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_set_media_clock_timer_response.h
@@ -49,7 +49,8 @@ class UISetMediaClockTimerResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UISetMediaClockTimerResponse(const MessageSharedPtr& message);
+ UISetMediaClockTimerResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UISetMediaClockTimerResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_show_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_show_request.h
index 136a99622b..80348de63b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_show_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_show_request.h
@@ -49,7 +49,8 @@ class UIShowRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIShowRequest(const MessageSharedPtr& message);
+ UIShowRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIShowRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_show_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_show_response.h
index 4a9b49253e..d696d2b9f8 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_show_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_show_response.h
@@ -49,7 +49,8 @@ class UIShowResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UIShowResponse(const MessageSharedPtr& message);
+ UIShowResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UIShowResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_slider_request.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_slider_request.h
index 8a3b37bfef..583f52084d 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_slider_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_slider_request.h
@@ -49,7 +49,8 @@ class UISliderRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UISliderRequest(const MessageSharedPtr& message);
+ UISliderRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UISliderRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/ui_slider_response.h b/src/components/application_manager/include/application_manager/commands/hmi/ui_slider_response.h
index 2384f248aa..cabb54f6cb 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/ui_slider_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/ui_slider_response.h
@@ -49,7 +49,8 @@ class UISliderResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UISliderResponse(const MessageSharedPtr& message);
+ UISliderResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UISliderResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/update_app_list_request.h b/src/components/application_manager/include/application_manager/commands/hmi/update_app_list_request.h
index b606134409..61be04d04f 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/update_app_list_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/update_app_list_request.h
@@ -49,7 +49,8 @@ class UpdateAppListRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UpdateAppListRequest(const MessageSharedPtr& message);
+ UpdateAppListRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UpdateAppListRequest class destructor
@@ -70,4 +71,3 @@ class UpdateAppListRequest : public RequestToHMI {
} // namespace application_manager
#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_UPDATE_APP_LIST_REQUEST_H_
-
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/update_app_list_response.h b/src/components/application_manager/include/application_manager/commands/hmi/update_app_list_response.h
index 135481cb0b..5ff8948393 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/update_app_list_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/update_app_list_response.h
@@ -49,7 +49,8 @@ class UpdateAppListResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UpdateAppListResponse(const MessageSharedPtr& message);
+ UpdateAppListResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UpdateAppListResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/update_device_list_request.h b/src/components/application_manager/include/application_manager/commands/hmi/update_device_list_request.h
index f645d312c5..c52ec96075 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/update_device_list_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/update_device_list_request.h
@@ -53,7 +53,8 @@ class UpdateDeviceListRequest : public RequestToHMI,
*
* @param message Incoming SmartObject message
**/
- explicit UpdateDeviceListRequest(const MessageSharedPtr& message);
+ UpdateDeviceListRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UpdateDeviceListRequest class destructor
@@ -73,14 +74,14 @@ class UpdateDeviceListRequest : public RequestToHMI,
*/
virtual void on_event(const event_engine::Event& event);
- /**
- * @brief Need to stop execution StopMethod if HMI did not started
- */
+ /**
+ * @brief Need to stop execution StopMethod if HMI did not started
+ */
virtual bool CleanUp();
private:
- sync_primitives::Lock wait_hmi_lock;
- sync_primitives::ConditionalVariable termination_condition_;
+ sync_primitives::Lock wait_hmi_lock;
+ sync_primitives::ConditionalVariable termination_condition_;
DISALLOW_COPY_AND_ASSIGN(UpdateDeviceListRequest);
};
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/update_device_list_response.h b/src/components/application_manager/include/application_manager/commands/hmi/update_device_list_response.h
index 6ea2c1e528..1928b81207 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/update_device_list_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/update_device_list_response.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief UpdateDeviceListResponse command class
**/
class UpdateDeviceListResponse : public ResponseFromHMI {
- public:
- /**
- * @brief UpdateDeviceListResponse class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit UpdateDeviceListResponse(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief UpdateDeviceListResponse class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ UpdateDeviceListResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief UpdateDeviceListResponse class destructor
- **/
- virtual ~UpdateDeviceListResponse();
+ /**
+ * @brief UpdateDeviceListResponse class destructor
+ **/
+ virtual ~UpdateDeviceListResponse();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(UpdateDeviceListResponse);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(UpdateDeviceListResponse);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/update_sdl_request.h b/src/components/application_manager/include/application_manager/commands/hmi/update_sdl_request.h
index f84f93f2ed..d8be10da2e 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/update_sdl_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/update_sdl_request.h
@@ -34,6 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_UPDATE_SDL_REQUEST_H_
#include "application_manager/commands/hmi/request_to_hmi.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -49,7 +50,8 @@ class UpdateSDLRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UpdateSDLRequest(const MessageSharedPtr& message);
+ UpdateSDLRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UpdateSDLRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/update_sdl_response.h b/src/components/application_manager/include/application_manager/commands/hmi/update_sdl_response.h
index b0d370ecfd..bc0375d5fa 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/update_sdl_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/update_sdl_response.h
@@ -49,7 +49,8 @@ class UpdateSDLResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit UpdateSDLResponse(const MessageSharedPtr& message);
+ UpdateSDLResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UpdateSDLResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_diagnostic_message_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_diagnostic_message_request.h
index c60533d2ea..099f27b734 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_diagnostic_message_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_diagnostic_message_request.h
@@ -49,7 +49,8 @@ class VIDiagnosticMessageRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIDiagnosticMessageRequest(const MessageSharedPtr& message);
+ VIDiagnosticMessageRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VIDiagnosticMessageRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_diagnostic_message_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_diagnostic_message_response.h
index 027e007e42..f0ae76ccb7 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_diagnostic_message_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_diagnostic_message_response.h
@@ -49,7 +49,8 @@ class VIDiagnosticMessageResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIDiagnosticMessageResponse(const MessageSharedPtr& message);
+ VIDiagnosticMessageResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VIDiagnosticMessageResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_dtcs_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_dtcs_request.h
index 170eb895fd..3b7e502a57 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_dtcs_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_dtcs_request.h
@@ -49,7 +49,8 @@ class VIGetDTCsRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIGetDTCsRequest(const MessageSharedPtr& message);
+ VIGetDTCsRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VIGetDTCsRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_dtcs_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_dtcs_response.h
index 3ba4656d5b..7b7dab567b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_dtcs_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_dtcs_response.h
@@ -49,7 +49,8 @@ class VIGetDTCsResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIGetDTCsResponse(const MessageSharedPtr& message);
+ VIGetDTCsResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VIGetDTCsResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_request.h
index 7413b6bf3b..006f18e864 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_request.h
@@ -49,7 +49,8 @@ class VIGetVehicleDataRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIGetVehicleDataRequest(const MessageSharedPtr& message);
+ VIGetVehicleDataRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VIGetVehicleDataRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_request_template.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_request_template.h
index af991186fd..a11c763021 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_request_template.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_request_template.h
@@ -44,7 +44,7 @@ namespace commands {
*
* Template class for sending 1 subscribe thin request
**/
-template<event_engine::Event::EventID eventID>
+template <event_engine::Event::EventID eventID>
class VIGetVehicleDataRequestTemplate : public RequestToHMI {
public:
/**
@@ -52,15 +52,15 @@ class VIGetVehicleDataRequestTemplate : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIGetVehicleDataRequestTemplate(const MessageSharedPtr& message)
- : RequestToHMI(message) {
- }
+ VIGetVehicleDataRequestTemplate(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
/**
* @brief Execute command with sending DBus thin request to HMI
**/
virtual void Run() {
- LOG4CXX_INFO(logger_, "VIGetVehicleDataRequestTemplate::Run");
+ LOG4CXX_AUTO_TRACE(logger_);
SendRequest();
}
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_response.h
index 1f9736b56a..ef19072bb0 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_response.h
@@ -34,6 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_VI_GET_VEHICLE_DATA_RESPONSE_H_
#include "application_manager/commands/hmi/response_from_hmi.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -49,7 +50,8 @@ class VIGetVehicleDataResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIGetVehicleDataResponse(const MessageSharedPtr& message);
+ VIGetVehicleDataResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VIGetVehicleDataResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_response_template.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_response_template.h
index 156664cac3..a1c143baed 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_response_template.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_data_response_template.h
@@ -35,6 +35,7 @@
#include "application_manager/event_engine/event.h"
#include "application_manager/commands/hmi/response_from_hmi.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
@@ -42,7 +43,7 @@ namespace commands {
/**
* @brief VIGetVehicleDataResponseTemplate command class
**/
-template<event_engine::Event::EventID eventID>
+template <event_engine::Event::EventID eventID>
class VIGetVehicleDataResponseTemplate : public ResponseFromHMI {
public:
/**
@@ -50,18 +51,18 @@ class VIGetVehicleDataResponseTemplate : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIGetVehicleDataResponseTemplate(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
- }
+ VIGetVehicleDataResponseTemplate(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
/**
* @brief Execute command
**/
virtual void Run() {
- LOG4CXX_INFO(logger_, "VIGetVehicleDataResponseTemplate::Run");
+ LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(eventID);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
private:
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_type_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_type_request.h
index 67d8ae046c..cd70c3349b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_type_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_type_request.h
@@ -49,7 +49,8 @@ class VIGetVehicleTypeRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIGetVehicleTypeRequest(const MessageSharedPtr& message);
+ VIGetVehicleTypeRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VIGetVehicleTypeRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_type_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_type_response.h
index b36b193418..0ef35dd7fc 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_type_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_get_vehicle_type_response.h
@@ -49,7 +49,8 @@ class VIGetVehicleTypeResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIGetVehicleTypeResponse(const MessageSharedPtr& message);
+ VIGetVehicleTypeResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VIGetVehicleTypeResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_is_ready_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_is_ready_request.h
index 061681029a..9049db4d24 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_is_ready_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_is_ready_request.h
@@ -49,7 +49,8 @@ class VIIsReadyRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIIsReadyRequest(const MessageSharedPtr& message);
+ VIIsReadyRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VIIsReadyRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_is_ready_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_is_ready_response.h
index 52e00f85da..a7866a1e73 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_is_ready_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_is_ready_response.h
@@ -34,6 +34,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_HMI_VI_IS_READY_RESPONSE_H_
#include "application_manager/commands/hmi/response_from_hmi.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -49,7 +50,8 @@ class VIIsReadyResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIIsReadyResponse(const MessageSharedPtr& message);
+ VIIsReadyResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VIIsReadyResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_read_did_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_read_did_request.h
index 6520db5e7d..cdbdb45a8b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_read_did_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_read_did_request.h
@@ -49,7 +49,8 @@ class VIReadDIDRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIReadDIDRequest(const MessageSharedPtr& message);
+ VIReadDIDRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VIReadDIDRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_read_did_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_read_did_response.h
index 0855be454b..acb8760c5b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_read_did_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_read_did_response.h
@@ -49,7 +49,8 @@ class VIReadDIDResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIReadDIDResponse(const MessageSharedPtr& message);
+ VIReadDIDResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VIReadDIDResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request.h
index 1eb06c6217..58d4984f8d 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request.h
@@ -49,7 +49,8 @@ class VISubscribeVehicleDataRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VISubscribeVehicleDataRequest(const MessageSharedPtr& message);
+ VISubscribeVehicleDataRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VISubscribeVehicleDataRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request_template.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request_template.h
index fc9b7dd2ea..7fefe0dbe2 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request_template.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request_template.h
@@ -44,7 +44,7 @@ namespace commands {
*
* Template class for sending 1 subscribe thin request
**/
-template<event_engine::Event::EventID eventID>
+template <event_engine::Event::EventID eventID>
class VISubscribeVehicleDataRequestTemplate : public RequestToHMI {
public:
/**
@@ -52,16 +52,15 @@ class VISubscribeVehicleDataRequestTemplate : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VISubscribeVehicleDataRequestTemplate(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
- }
+ VISubscribeVehicleDataRequestTemplate(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
/**
* @brief Execute command with sending DBus thin request to HMI
**/
virtual void Run() {
- LOG4CXX_INFO(logger_, "VISubscriveVehicleDataRequestTemplate::Run");
+ LOG4CXX_AUTO_TRACE(logger_);
SendRequest();
}
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response.h
index b5e2788f32..8f038bf941 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response.h
@@ -49,7 +49,8 @@ class VISubscribeVehicleDataResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VISubscribeVehicleDataResponse(const MessageSharedPtr& message);
+ VISubscribeVehicleDataResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VISubscribeVehicleDataResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response_template.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response_template.h
index 64f3c51cbc..7790c57092 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response_template.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response_template.h
@@ -35,13 +35,14 @@
#include "application_manager/event_engine/event.h"
#include "application_manager/commands/hmi/response_from_hmi.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
/**
* @brief VISubscriveVehicleDataResponseTemplate command class
**/
-template<event_engine::Event::EventID eventID>
+template <event_engine::Event::EventID eventID>
class VISubscribeVehicleDataResponseTemplate : public ResponseFromHMI {
public:
/**
@@ -49,20 +50,20 @@ class VISubscribeVehicleDataResponseTemplate : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VISubscribeVehicleDataResponseTemplate(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
- }
+ VISubscribeVehicleDataResponseTemplate(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
/**
* @brief Execute command
**/
virtual void Run() {
- LOG4CXX_INFO(logger_, "VISubscribeVehicleDataResponse::Run");
+ LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(eventID);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
+
private:
DISALLOW_COPY_AND_ASSIGN(VISubscribeVehicleDataResponseTemplate<eventID>);
};
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request.h
index 1320ae477a..b99eee47e7 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request.h
@@ -49,7 +49,8 @@ class VIUnsubscribeVehicleDataRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIUnsubscribeVehicleDataRequest(const MessageSharedPtr& message);
+ VIUnsubscribeVehicleDataRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VIUnsubscribeVehicleDataRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request_template.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request_template.h
index 9aa529d407..b9367a372e 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request_template.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request_template.h
@@ -44,7 +44,7 @@ namespace commands {
*
* Template class for sending 1 unsubscribe thin request
**/
-template<event_engine::Event::EventID eventID>
+template <event_engine::Event::EventID eventID>
class VIUnsubscribeVehicleDataRequestTemplate : public RequestToHMI {
public:
/**
@@ -52,16 +52,15 @@ class VIUnsubscribeVehicleDataRequestTemplate : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIUnsubscribeVehicleDataRequestTemplate(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
- }
+ VIUnsubscribeVehicleDataRequestTemplate(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
/**
* @brief Execute command with sending DBus thin request to HMI
**/
virtual void Run() {
- LOG4CXX_INFO(logger_, "VIUnsubscriveVehicleDataRequestTemplate::Run");
+ LOG4CXX_AUTO_TRACE(logger_);
SendRequest();
}
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response.h
index 8818709afe..3f930b5a5b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response.h
@@ -49,7 +49,8 @@ class VIUnsubscribeVehicleDataResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIUnsubscribeVehicleDataResponse(const MessageSharedPtr& message);
+ VIUnsubscribeVehicleDataResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VIUnsubscribeVehicleDataResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response_template.h b/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response_template.h
index 3dfcc763cb..9d943b838d 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response_template.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response_template.h
@@ -35,6 +35,7 @@
#include "application_manager/event_engine/event.h"
#include "application_manager/commands/hmi/response_from_hmi.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
@@ -42,7 +43,7 @@ namespace commands {
/**
* @brief VIUnsubscriveVehicleDataResponseTemplate command class
**/
-template<event_engine::Event::EventID eventID>
+template <event_engine::Event::EventID eventID>
class VIUnsubscribeVehicleDataResponseTemplate : public ResponseFromHMI {
public:
/**
@@ -50,20 +51,20 @@ class VIUnsubscribeVehicleDataResponseTemplate : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VIUnsubscribeVehicleDataResponseTemplate(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
- }
+ VIUnsubscribeVehicleDataResponseTemplate(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
/**
* @brief Execute command
**/
virtual void Run() {
- LOG4CXX_INFO(logger_, "VIUnsubscriveVehicleDataResponseTemplate::Run");
+ LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(eventID);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
+
private:
DISALLOW_COPY_AND_ASSIGN(VIUnsubscribeVehicleDataResponseTemplate<eventID>);
};
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_add_command_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_add_command_request.h
index 9fdc3f776f..1ef4125c89 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_add_command_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_add_command_request.h
@@ -49,7 +49,8 @@ class VRAddCommandRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VRAddCommandRequest(const MessageSharedPtr& message);
+ VRAddCommandRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VRAddCommandRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_add_command_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_add_command_response.h
index 7418ed5865..1b419ed6ec 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_add_command_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_add_command_response.h
@@ -49,7 +49,8 @@ class VRAddCommandResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VRAddCommandResponse(const MessageSharedPtr& message);
+ VRAddCommandResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VRAddCommandResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_change_registration_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_change_registration_request.h
index 53584ee970..642319e8d6 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_change_registration_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_change_registration_request.h
@@ -49,7 +49,8 @@ class VRChangeRegistrationRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VRChangeRegistrationRequest(const MessageSharedPtr& message);
+ VRChangeRegistrationRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VRChangeRegistrationRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_change_registration_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_change_registration_response.h
index d71a14da34..8dc5e96729 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_change_registration_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_change_registration_response.h
@@ -49,7 +49,8 @@ class VRChangeRegistrationResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VRChangeRegistrationResponse(const MessageSharedPtr& message);
+ VRChangeRegistrationResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VRChangeRegistrationResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_delete_command_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_delete_command_request.h
index 91a5dc7d99..bc5c24a350 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_delete_command_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_delete_command_request.h
@@ -49,7 +49,8 @@ class VRDeleteCommandRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VRDeleteCommandRequest(const MessageSharedPtr& message);
+ VRDeleteCommandRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VRDeleteCommandRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_delete_command_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_delete_command_response.h
index ad8c82e38c..526c296321 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_delete_command_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_delete_command_response.h
@@ -49,7 +49,8 @@ class VRDeleteCommandResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VRDeleteCommandResponse(const MessageSharedPtr& message);
+ VRDeleteCommandResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VRDeleteCommandResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_get_capabilities_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_get_capabilities_request.h
index 676967083f..8dcc240e9b 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_get_capabilities_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_get_capabilities_request.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief VRGetCapabilitiesRequest command class
**/
class VRGetCapabilitiesRequest : public RequestToHMI {
- public:
- /**
- * @brief VRGetCapabilitiesRequest class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit VRGetCapabilitiesRequest(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief VRGetCapabilitiesRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ VRGetCapabilitiesRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief VRGetCapabilitiesRequest class destructor
- **/
- virtual ~VRGetCapabilitiesRequest();
+ /**
+ * @brief VRGetCapabilitiesRequest class destructor
+ **/
+ virtual ~VRGetCapabilitiesRequest();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(VRGetCapabilitiesRequest);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(VRGetCapabilitiesRequest);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_get_capabilities_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_get_capabilities_response.h
index 8b88eb4e3b..b6c8e081f5 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_get_capabilities_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_get_capabilities_response.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief VRGetCapabilitiesResponse command class
**/
class VRGetCapabilitiesResponse : public ResponseFromHMI {
- public:
- /**
- * @brief VRGetCapabilitiesResponse class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit VRGetCapabilitiesResponse(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief VRGetCapabilitiesResponse class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ VRGetCapabilitiesResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief VRGetCapabilitiesResponse class destructor
- **/
- virtual ~VRGetCapabilitiesResponse();
+ /**
+ * @brief VRGetCapabilitiesResponse class destructor
+ **/
+ virtual ~VRGetCapabilitiesResponse();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(VRGetCapabilitiesResponse);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(VRGetCapabilitiesResponse);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_get_language_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_get_language_request.h
index 9dd9133ffd..05373784f3 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_get_language_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_get_language_request.h
@@ -49,7 +49,8 @@ class VRGetLanguageRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VRGetLanguageRequest(const MessageSharedPtr& message);
+ VRGetLanguageRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VRGetLanguageRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_get_language_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_get_language_response.h
index d9c4fc2126..fad2f219df 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_get_language_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_get_language_response.h
@@ -49,7 +49,8 @@ class VRGetLanguageResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VRGetLanguageResponse(const MessageSharedPtr& message);
+ VRGetLanguageResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VRGetLanguageResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_get_supported_languages_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_get_supported_languages_request.h
index 0a010cdfec..6ed56ebd32 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_get_supported_languages_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_get_supported_languages_request.h
@@ -49,7 +49,8 @@ class VRGetSupportedLanguagesRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VRGetSupportedLanguagesRequest(const MessageSharedPtr& message);
+ VRGetSupportedLanguagesRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VRGetSupportedLanguagesRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_get_supported_languages_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_get_supported_languages_response.h
index dbbe57ba36..c4e742ecd0 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_get_supported_languages_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_get_supported_languages_response.h
@@ -49,7 +49,8 @@ class VRGetSupportedLanguagesResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VRGetSupportedLanguagesResponse(const MessageSharedPtr& message);
+ VRGetSupportedLanguagesResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VRGetSupportedLanguagesResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_is_ready_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_is_ready_request.h
index e66c9c36a5..9fc4ccd2f3 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_is_ready_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_is_ready_request.h
@@ -49,7 +49,8 @@ class VRIsReadyRequest : public RequestToHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VRIsReadyRequest(const MessageSharedPtr& message);
+ VRIsReadyRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VRIsReadyRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_is_ready_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_is_ready_response.h
index a9b1a68455..474b3373a3 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_is_ready_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_is_ready_response.h
@@ -49,7 +49,8 @@ class VRIsReadyResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VRIsReadyResponse(const MessageSharedPtr& message);
+ VRIsReadyResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief VRIsReadyResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_perform_interaction_request.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_perform_interaction_request.h
index b819fdb927..35a7e80b06 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_perform_interaction_request.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_perform_interaction_request.h
@@ -43,26 +43,27 @@ namespace commands {
* @brief VRPerformInteractionRequest command class
**/
class VRPerformInteractionRequest : public RequestToHMI {
- public:
- /**
- * @brief VRPerformInteractionRequest class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit VRPerformInteractionRequest(const MessageSharedPtr& message);
+ public:
+ /**
+ * @brief VRPerformInteractionRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ VRPerformInteractionRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
- /**
- * @brief VRPerformInteractionRequest class destructor
- **/
- virtual ~VRPerformInteractionRequest();
+ /**
+ * @brief VRPerformInteractionRequest class destructor
+ **/
+ virtual ~VRPerformInteractionRequest();
- /**
- * @brief Execute command
- **/
- virtual void Run();
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
- private:
- DISALLOW_COPY_AND_ASSIGN(VRPerformInteractionRequest);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(VRPerformInteractionRequest);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/hmi/vr_perform_interaction_response.h b/src/components/application_manager/include/application_manager/commands/hmi/vr_perform_interaction_response.h
index ffbbd613e2..7c445416ce 100644
--- a/src/components/application_manager/include/application_manager/commands/hmi/vr_perform_interaction_response.h
+++ b/src/components/application_manager/include/application_manager/commands/hmi/vr_perform_interaction_response.h
@@ -49,7 +49,8 @@ class VRPerformInteractionResponse : public ResponseFromHMI {
*
* @param message Incoming SmartObject message
**/
- explicit VRPerformInteractionResponse(const MessageSharedPtr& message);
+ VRPerformInteractionResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief TTSPerformInteractionResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/add_command_request.h b/src/components/application_manager/include/application_manager/commands/mobile/add_command_request.h
index 2c36d8425e..22a0c7e85f 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/add_command_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/add_command_request.h
@@ -52,7 +52,8 @@ class AddCommandRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit AddCommandRequest(const MessageSharedPtr& message);
+ AddCommandRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief AddCommandRequest class destructor
@@ -72,7 +73,6 @@ class AddCommandRequest : public CommandRequestImpl {
void on_event(const event_engine::Event& event);
private:
-
/*
* @brief Check if command name doesn't exist in application
* Please see SDLAQ-CRS-407 for more information
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/add_command_response.h b/src/components/application_manager/include/application_manager/commands/mobile/add_command_response.h
index 67a49a8e17..84bcdebc31 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/add_command_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/add_command_response.h
@@ -51,7 +51,8 @@ class AddCommandResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit AddCommandResponse(const MessageSharedPtr& message);
+ AddCommandResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief AddCommandResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/add_sub_menu_request.h b/src/components/application_manager/include/application_manager/commands/mobile/add_sub_menu_request.h
index befeb76d9f..1f12523953 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/add_sub_menu_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/add_sub_menu_request.h
@@ -51,7 +51,8 @@ class AddSubMenuRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit AddSubMenuRequest(const MessageSharedPtr& message);
+ AddSubMenuRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief AddSubMenuRequest class destructor
@@ -71,7 +72,6 @@ class AddSubMenuRequest : public CommandRequestImpl {
void on_event(const event_engine::Event& event);
private:
-
/*
* @brief Check if submenu name is valid
*
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/add_sub_menu_response.h b/src/components/application_manager/include/application_manager/commands/mobile/add_sub_menu_response.h
index 62c404951a..4d71e5f017 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/add_sub_menu_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/add_sub_menu_response.h
@@ -51,7 +51,8 @@ class AddSubMenuResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit AddSubMenuResponse(const MessageSharedPtr& message);
+ AddSubMenuResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief AddSubMenuResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/alert_maneuver_request.h b/src/components/application_manager/include/application_manager/commands/mobile/alert_maneuver_request.h
index 02423f0630..472ff45551 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/alert_maneuver_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/alert_maneuver_request.h
@@ -53,7 +53,8 @@ class AlertManeuverRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit AlertManeuverRequest(const MessageSharedPtr& message);
+ AlertManeuverRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief AlertManeuverRequest class destructor
@@ -81,8 +82,10 @@ class AlertManeuverRequest : public CommandRequestImpl {
*/
bool IsWhiteSpaceExist();
- mobile_apis::Result::eType tts_speak_result_code_;
- mobile_apis::Result::eType navi_alert_maneuver_result_code_;
+ mobile_apis::Result::eType tts_speak_result_code_;
+ mobile_apis::Result::eType navi_alert_maneuver_result_code_;
+ std::string info_navi_;
+ std::string info_tts_;
Pending pending_requests_;
DISALLOW_COPY_AND_ASSIGN(AlertManeuverRequest);
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/alert_maneuver_response.h b/src/components/application_manager/include/application_manager/commands/mobile/alert_maneuver_response.h
index 5f0827699b..c02322e298 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/alert_maneuver_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/alert_maneuver_response.h
@@ -51,7 +51,8 @@ class AlertManeuverResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit AlertManeuverResponse(const MessageSharedPtr& message);
+ AlertManeuverResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief AlertManeuverResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/alert_request.h b/src/components/application_manager/include/application_manager/commands/mobile/alert_request.h
index 705a1d1454..bc99665d82 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/alert_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/alert_request.h
@@ -52,7 +52,8 @@ class AlertRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit AlertRequest(const MessageSharedPtr& message);
+ AlertRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief AlertRequest class destructor
@@ -71,7 +72,8 @@ class AlertRequest : public CommandRequestImpl {
/*
* @brief Will caled by request controller, when default will be expired.
- * If Alert request has soft buttons, timeout response should not be sent to mobile
+ * If Alert request has soft buttons, timeout response should not be sent to
+ * mobile
*/
virtual void onTimeOut();
@@ -83,7 +85,6 @@ class AlertRequest : public CommandRequestImpl {
void on_event(const event_engine::Event& event);
protected:
-
private:
/*
* @brief Checks if request parameters are valid
@@ -102,15 +103,16 @@ class AlertRequest : public CommandRequestImpl {
* @brief Sends TTS Speak request
*
* @param app_id Id of application requested this RPC
- */
- void SendSpeakRequest(int32_t app_id);
-
- /*
- * @brief Sends Basic communication playtone notification
*
- * @param app_id Id of application requested this RPC
+ * @param tts_chunks_exists if tts chunks exists in
+ * message contains true, otherwise contains false
+ *
+ * @param length_tts_chunks contains length of array
+ * tts chunks.
*/
- void SendPlayToneNotification(int32_t app_id);
+ void SendSpeakRequest(int32_t app_id,
+ bool tts_chunks_exists,
+ size_t length_tts_chunks);
/*
* @brief Tells if there are sent requests without responses
@@ -124,14 +126,14 @@ class AlertRequest : public CommandRequestImpl {
*/
bool CheckStringsOfAlertRequest();
- bool awaiting_ui_alert_response_;
- bool awaiting_tts_speak_response_;
- bool awaiting_tts_stop_speaking_response_;
- bool response_success_;
- bool flag_other_component_sent_;
- mobile_apis::Result::eType response_result_;
- smart_objects::SmartObject response_params_;
- mobile_apis::Result::eType tts_speak_response_;
+ bool awaiting_ui_alert_response_;
+ bool awaiting_tts_speak_response_;
+ bool awaiting_tts_stop_speaking_response_;
+ bool is_alert_succeeded_;
+ bool is_ui_alert_sent_;
+ mobile_apis::Result::eType alert_result_;
+ smart_objects::SmartObject alert_response_params_;
+ mobile_apis::Result::eType tts_speak_result_;
DISALLOW_COPY_AND_ASSIGN(AlertRequest);
};
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/alert_response.h b/src/components/application_manager/include/application_manager/commands/mobile/alert_response.h
index 59b38933a7..acac21d738 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/alert_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/alert_response.h
@@ -51,7 +51,8 @@ class AlertResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit AlertResponse(const MessageSharedPtr& message);
+ AlertResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief AlertResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/change_registration_request.h b/src/components/application_manager/include/application_manager/commands/mobile/change_registration_request.h
index d36f16a976..c81ed0b5d3 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/change_registration_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/change_registration_request.h
@@ -39,22 +39,26 @@
#include "application_manager/commands/command_request_impl.h"
#include "application_manager/commands/pending.h"
#include "utils/macro.h"
+#include "utils/custom_string.h"
namespace application_manager {
namespace commands {
+namespace custom_str = utils::custom_string;
+
/**
* @brief ChangeRegistrationRequest command class
**/
-class ChangeRegistrationRequest : public CommandRequestImpl {
+class ChangeRegistrationRequest : public CommandRequestImpl {
public:
/**
* @brief ChangeRegistrationRequest class constructor
*
* @param message Incoming SmartObject message
**/
- explicit ChangeRegistrationRequest(const MessageSharedPtr& message);
+ ChangeRegistrationRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief ChangeRegistrationRequest class destructor
@@ -107,9 +111,9 @@ class ChangeRegistrationRequest : public CommandRequestImpl {
*
* @return true if all of result codes is success
*/
- bool AllHmiResponsesSuccess(const hmi_apis::Common_Result::eType ui,
- const hmi_apis::Common_Result::eType vr,
- const hmi_apis::Common_Result::eType tts);
+ bool AllHmiResponsesSuccess(const hmi_apis::Common_Result::eType ui,
+ const hmi_apis::Common_Result::eType vr,
+ const hmi_apis::Common_Result::eType tts);
/**
* @brief Checks change_registration params(ttsName, appname,
@@ -118,42 +122,49 @@ class ChangeRegistrationRequest : public CommandRequestImpl {
* @return true if command contains \t\n \\t \\n of whitespace otherwise
* returns false.
*/
- bool IsWhiteSpaceExist();
-
- /**
- * @brief Check parameters (name, vr) for
- * coincidence with already known parameters of registered applications
- *
- * @return SUCCESS if there is no coincidence of app.name/VR synonyms,
- * otherwise appropriate error code returns
- */
- mobile_apis::Result::eType CheckCoincidence();
-
- /**
- * @brief Predicate for using with CheckCoincidence method to compare with VR synonym SO
- *
- * @return TRUE if there is coincidence of VR, otherwise FALSE
- */
- struct CoincidencePredicateVR {
- explicit CoincidencePredicateVR(const std::string &newItem)
- :newItem_(newItem)
- {};
-
- bool operator()(smart_objects::SmartObject obj) {
- const std::string vr_synonym = obj.asString();
- return !(strcasecmp(vr_synonym.c_str(), newItem_.c_str()));
- };
-
- const std::string &newItem_;
- };
-
- Pending pending_requests_;
-
- hmi_apis::Common_Result::eType ui_result_;
- hmi_apis::Common_Result::eType vr_result_;
- hmi_apis::Common_Result::eType tts_result_;
-
- DISALLOW_COPY_AND_ASSIGN(ChangeRegistrationRequest);
+ bool IsWhiteSpaceExist();
+
+ /**
+ * @brief Check parameters (name, vr) for
+ * coincidence with already known parameters of registered applications
+ *
+ * @return SUCCESS if there is no coincidence of app.name/VR synonyms,
+ * otherwise appropriate error code returns
+ */
+ mobile_apis::Result::eType CheckCoincidence();
+
+ /**
+ * @brief Checks if requested name is allowed by policy
+ * @param app_name Application name
+ * @return true, if allowed, otherwise - false
+ */
+ bool IsNicknameAllowed(const custom_str::CustomString& app_name) const;
+
+ /**
+ * @brief Predicate for using with CheckCoincidence method to compare with VR
+ * synonym SO
+ *
+ * @return TRUE if there is coincidence of VR, otherwise FALSE
+ */
+ struct CoincidencePredicateVR {
+ CoincidencePredicateVR(const custom_str::CustomString& newItem)
+ : newItem_(newItem){};
+
+ bool operator()(const smart_objects::SmartObject& obj) const {
+ const custom_str::CustomString& vr_synonym = obj.asCustomString();
+ return newItem_.CompareIgnoreCase(vr_synonym);
+ };
+
+ const custom_str::CustomString& newItem_;
+ };
+
+ Pending pending_requests_;
+
+ hmi_apis::Common_Result::eType ui_result_;
+ hmi_apis::Common_Result::eType vr_result_;
+ hmi_apis::Common_Result::eType tts_result_;
+
+ DISALLOW_COPY_AND_ASSIGN(ChangeRegistrationRequest);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/change_registration_response.h b/src/components/application_manager/include/application_manager/commands/mobile/change_registration_response.h
index 2cac5f2d58..6ff3fd9a4a 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/change_registration_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/change_registration_response.h
@@ -51,7 +51,8 @@ class ChangeRegistrationResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit ChangeRegistrationResponse(const MessageSharedPtr& message);
+ ChangeRegistrationResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief ChangeRegistrationResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/create_interaction_choice_set_request.h b/src/components/application_manager/include/application_manager/commands/mobile/create_interaction_choice_set_request.h
index 615416fac5..2a6e55f312 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/create_interaction_choice_set_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/create_interaction_choice_set_request.h
@@ -53,186 +53,185 @@ namespace commands {
**/
class CreateInteractionChoiceSetRequest : public CommandRequestImpl {
public:
- /**
- * @brief CreateInteractionChoiceSetRequest class constructor
- *
- * @param message Incoming SmartObject message
- **/
- explicit CreateInteractionChoiceSetRequest(const MessageSharedPtr& message);
-
- /**
- * @brief CreateInteractionChoiceSetRequest class destructor
- **/
- virtual ~CreateInteractionChoiceSetRequest();
-
- /**
- * @brief Execute command
- **/
- virtual void Run();
-
+ /**
+ * @brief CreateInteractionChoiceSetRequest class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ CreateInteractionChoiceSetRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+
+ /**
+ * @brief CreateInteractionChoiceSetRequest class destructor
+ **/
+ virtual ~CreateInteractionChoiceSetRequest();
+
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run();
private:
- /**
- * @brief Interface method that is called whenever new event received
- *
- * @param event The received event
- */
- virtual void on_event(const event_engine::Event& event);
-
- /**
- * @brief Function is called by RequestController when request execution time
- * has exceed it's limit
- */
- virtual void onTimeOut();
- /**
- * @brief DeleteChoices allows to walk through the sent commands collection
- * in order to sent appropriate DeleteCommand request.
- */
- void DeleteChoices();
-
- /**
- * @brief Calls after all responses from HMI were received.
- * Terminates request and sends successful response to mobile
- * if all responses were SUCCESS or calls DeleteChoices in other case.
- */
- void OnAllHMIResponsesReceived();
-
- /**
- * @brief The VRCommand struct
- * Collect minimum information about sent VR commands, for correctly
- * processing deleting sent commands if error from HMI received
- */
- struct VRCommandInfo {
- VRCommandInfo() {}
- explicit VRCommandInfo(uint32_t cmd_id):
- cmd_id_(cmd_id),
- succesful_response_received_(false) {}
- uint32_t cmd_id_;
- bool succesful_response_received_;
- };
-
- typedef std::map<uint32_t, VRCommandInfo> SentCommandsMap;
- SentCommandsMap sent_commands_map_;
-
- int32_t choice_set_id_;
- size_t expected_chs_count_;
- size_t received_chs_count_;
-
- /**
- * @brief Flag for stop sending VR commands to HMI, in case one of responses
- * failed
- */
- volatile bool error_from_hmi_;
- sync_primitives::Lock error_from_hmi_lock_;
-
- /**
- * @brief Flag shows if request already was expired by timeout
- */
- volatile bool is_timed_out_;
- sync_primitives::Lock is_timed_out_lock_;
-
- sync_primitives::Lock vr_commands_lock_;
- /*
- * @brief Sends VR AddCommand request to HMI
- *
- * @param app_id Application ID
- *
- */
- void SendVRAddCommandRequests(ApplicationSharedPtr const app);
-
- /*
- * @brief Checks incoming choiseSet params.
- * @param app Registred mobile application
- *
- * @return Mobile result code
- */
- mobile_apis::Result::eType CheckChoiceSet(ApplicationConstSharedPtr app);
-
- /*
- * @brief Predicate for using with CheckChoiceSet method to compare choice ID param
- *
- * return TRUE if there is coincidence of choice ID, otherwise FALSE
- */
- struct CoincidencePredicateChoiceID {
- explicit CoincidencePredicateChoiceID(const uint32_t newItem)
- : newItem_(newItem)
- {}
-
- bool operator()(smart_objects::SmartObject obj) {
- return obj[strings::choice_id].asUInt() == newItem_;
- }
-
- const uint32_t newItem_;
- };
-
- /*
- * @brief Predicate for using with CheckChoiceSet method to compare menu name param
- *
- * return TRUE if there is coincidence of menu name, otherwise FALSE
- */
- struct CoincidencePredicateMenuName {
- explicit CoincidencePredicateMenuName(const std::string& newItem)
- : newItem_(newItem)
- {};
-
- bool operator()(smart_objects::SmartObject obj) {
- return obj[strings::menu_name].asString() == newItem_;
- }
-
- const std::string& newItem_;
- };
-
- /*
- * @brief Predicate for using with CheckChoiceSet method to compare VR commands param
- *
- * return TRUE if there is coincidence of VR commands, otherwise FALSE
- */
- struct CoincidencePredicateVRCommands {
- explicit CoincidencePredicateVRCommands(
- const smart_objects::SmartObject& newItem): newItem_(newItem) {}
-
- bool operator()(smart_objects::SmartObject obj) {
- return compareStr(obj, newItem_);
- }
-
- const smart_objects::SmartObject& newItem_;
- };
-
- /*
- * @brief Checks if incoming choice set doesn't has similar VR synonyms.
- *
- * @param choice1 Choice to compare
- * @param choice2 Choice to compare
- *
- * return Return TRUE if there are similar VR synonyms in choice set,
- * otherwise FALSE
- */
- bool compareSynonyms(
+ /**
+ * @brief Interface method that is called whenever new event received
+ *
+ * @param event The received event
+ */
+ virtual void on_event(const event_engine::Event& event);
+
+ /**
+ * @brief Function is called by RequestController when request execution time
+ * has exceed it's limit
+ */
+ virtual void onTimeOut();
+ /**
+ * @brief DeleteChoices allows to walk through the sent commands collection
+ * in order to sent appropriate DeleteCommand request.
+ */
+ void DeleteChoices();
+
+ /**
+ * @brief Calls after all responses from HMI were received.
+ * Terminates request and sends successful response to mobile
+ * if all responses were SUCCESS or calls DeleteChoices in other case.
+ */
+ void OnAllHMIResponsesReceived();
+
+ /**
+ * @brief The VRCommand struct
+ * Collect minimum information about sent VR commands, for correctly
+ * processing deleting sent commands if error from HMI received
+ */
+ struct VRCommandInfo {
+ VRCommandInfo() {}
+ VRCommandInfo(uint32_t cmd_id)
+ : cmd_id_(cmd_id), succesful_response_received_(false) {}
+ uint32_t cmd_id_;
+ bool succesful_response_received_;
+ };
+
+ typedef std::map<uint32_t, VRCommandInfo> SentCommandsMap;
+ SentCommandsMap sent_commands_map_;
+
+ int32_t choice_set_id_;
+ size_t expected_chs_count_;
+ size_t received_chs_count_;
+
+ /**
+ * @brief Flag for stop sending VR commands to HMI, in case one of responses
+ * failed
+ */
+ volatile bool error_from_hmi_;
+ sync_primitives::Lock error_from_hmi_lock_;
+
+ /**
+ * @brief Flag shows if request already was expired by timeout
+ */
+ volatile bool is_timed_out_;
+ sync_primitives::Lock is_timed_out_lock_;
+
+ sync_primitives::Lock vr_commands_lock_;
+ /*
+ * @brief Sends VR AddCommand request to HMI
+ *
+ * @param app_id Application ID
+ *
+ */
+ void SendVRAddCommandRequests(ApplicationSharedPtr const app);
+
+ /*
+ * @brief Checks incoming choiseSet params.
+ * @param app Registred mobile application
+ *
+ * @return Mobile result code
+ */
+ mobile_apis::Result::eType CheckChoiceSet(ApplicationConstSharedPtr app);
+
+ /*
+ * @brief Predicate for using with CheckChoiceSet method to compare choice ID
+ *param
+ *
+ * return TRUE if there is coincidence of choice ID, otherwise FALSE
+ */
+ struct CoincidencePredicateChoiceID {
+ CoincidencePredicateChoiceID(const uint32_t newItem) : newItem_(newItem) {}
+
+ bool operator()(smart_objects::SmartObject obj) {
+ return obj[strings::choice_id].asUInt() == newItem_;
+ }
+
+ const uint32_t newItem_;
+ };
+
+ /*
+ * @brief Predicate for using with CheckChoiceSet method to compare menu name
+ *param
+ *
+ * return TRUE if there is coincidence of menu name, otherwise FALSE
+ */
+ struct CoincidencePredicateMenuName {
+ CoincidencePredicateMenuName(const std::string& newItem)
+ : newItem_(newItem){};
+
+ bool operator()(smart_objects::SmartObject obj) {
+ return obj[strings::menu_name].asString() == newItem_;
+ }
+
+ const std::string& newItem_;
+ };
+
+ /*
+ * @brief Predicate for using with CheckChoiceSet method to compare VR commands
+ *param
+ *
+ * return TRUE if there is coincidence of VR commands, otherwise FALSE
+ */
+ struct CoincidencePredicateVRCommands {
+ CoincidencePredicateVRCommands(const smart_objects::SmartObject& newItem)
+ : newItem_(newItem) {}
+
+ bool operator()(smart_objects::SmartObject obj) {
+ return compareStr(obj, newItem_);
+ }
+
+ const smart_objects::SmartObject& newItem_;
+ };
+
+ /*
+ * @brief Checks if incoming choice set doesn't has similar VR synonyms.
+ *
+ * @param choice1 Choice to compare
+ * @param choice2 Choice to compare
+ *
+ * return Return TRUE if there are similar VR synonyms in choice set,
+ * otherwise FALSE
+ */
+ bool compareSynonyms(
const NsSmartDeviceLink::NsSmartObjects::SmartObject& choice1,
const NsSmartDeviceLink::NsSmartObjects::SmartObject& choice2);
- /*
- * @brief Checks VR synonyms ignoring differences in case.
- *
- * @param str1 VR synonym to compare
- * @param str2 VR synonym to compare
- *
- * return Return TRUE if there are similar VR synonyms in choice set,
- * otherwise FALSE
- */
- static bool compareStr(
+ /*
+ * @brief Checks VR synonyms ignoring differences in case.
+ *
+ * @param str1 VR synonym to compare
+ * @param str2 VR synonym to compare
+ *
+ * return Return TRUE if there are similar VR synonyms in choice set,
+ * otherwise FALSE
+ */
+ static bool compareStr(
const NsSmartDeviceLink::NsSmartObjects::SmartObject& str1,
const NsSmartDeviceLink::NsSmartObjects::SmartObject& str2);
- /**
- * @brief Checks choice set params(menuName, tertiaryText, ...)
- * When type is String there is a check on the contents \t\n \\t \\n
- * @param choice_set which must check
- * @return if choice_set contains \t\n \\t \\n return TRUE, FALSE otherwise
- */
- bool IsWhiteSpaceExist(const smart_objects::SmartObject& choice_set);
+ /**
+ * @brief Checks choice set params(menuName, tertiaryText, ...)
+ * When type is String there is a check on the contents \t\n \\t \\n
+ * @param choice_set which must check
+ * @return if choice_set contains \t\n \\t \\n return TRUE, FALSE otherwise
+ */
+ bool IsWhiteSpaceExist(const smart_objects::SmartObject& choice_set);
- DISALLOW_COPY_AND_ASSIGN(CreateInteractionChoiceSetRequest);
+ DISALLOW_COPY_AND_ASSIGN(CreateInteractionChoiceSetRequest);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/create_interaction_choice_set_response.h b/src/components/application_manager/include/application_manager/commands/mobile/create_interaction_choice_set_response.h
index 965573f4a4..6a7faf705c 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/create_interaction_choice_set_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/create_interaction_choice_set_response.h
@@ -51,7 +51,8 @@ class CreateInteractionChoiceSetResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit CreateInteractionChoiceSetResponse(const MessageSharedPtr& message);
+ CreateInteractionChoiceSetResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief CreateInteractionChoiceSetResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/delete_command_request.h b/src/components/application_manager/include/application_manager/commands/mobile/delete_command_request.h
index bae0fedd54..6a19014c96 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/delete_command_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/delete_command_request.h
@@ -51,7 +51,8 @@ class DeleteCommandRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit DeleteCommandRequest(const MessageSharedPtr& message);
+ DeleteCommandRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief DeleteCommandRequest class destructor
@@ -71,7 +72,6 @@ class DeleteCommandRequest : public CommandRequestImpl {
void on_event(const event_engine::Event& event);
private:
-
DISALLOW_COPY_AND_ASSIGN(DeleteCommandRequest);
/*
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/delete_command_response.h b/src/components/application_manager/include/application_manager/commands/mobile/delete_command_response.h
index 0fe0f0959b..b61035ca1b 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/delete_command_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/delete_command_response.h
@@ -51,7 +51,8 @@ class DeleteCommandResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit DeleteCommandResponse(const MessageSharedPtr& message);
+ DeleteCommandResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief DeleteCommandResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/delete_file_request.h b/src/components/application_manager/include/application_manager/commands/mobile/delete_file_request.h
index 4927227465..adaf2686bc 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/delete_file_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/delete_file_request.h
@@ -53,7 +53,8 @@ class DeleteFileRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit DeleteFileRequest(const MessageSharedPtr& message);
+ DeleteFileRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief DeleteFileRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/delete_file_response.h b/src/components/application_manager/include/application_manager/commands/mobile/delete_file_response.h
index cfe6aaa4fa..e001e46a22 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/delete_file_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/delete_file_response.h
@@ -51,7 +51,8 @@ class DeleteFileResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit DeleteFileResponse(const MessageSharedPtr& message);
+ DeleteFileResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief DeleteFileResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/delete_interaction_choice_set_request.h b/src/components/application_manager/include/application_manager/commands/mobile/delete_interaction_choice_set_request.h
index 283b882fad..716a1d82de 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/delete_interaction_choice_set_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/delete_interaction_choice_set_request.h
@@ -52,7 +52,8 @@ class DeleteInteractionChoiceSetRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit DeleteInteractionChoiceSetRequest(const MessageSharedPtr& message);
+ DeleteInteractionChoiceSetRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief DeleteInteractionChoiceSetRequest class destructor
@@ -65,7 +66,6 @@ class DeleteInteractionChoiceSetRequest : public CommandRequestImpl {
virtual void Run();
private:
-
/*
* @brief Check if requested choice set ID in use by perform interaction
*
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/delete_interaction_choice_set_response.h b/src/components/application_manager/include/application_manager/commands/mobile/delete_interaction_choice_set_response.h
index 1f641e15b3..86e20bc6d4 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/delete_interaction_choice_set_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/delete_interaction_choice_set_response.h
@@ -51,7 +51,8 @@ class DeleteInteractionChoiceSetResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit DeleteInteractionChoiceSetResponse(const MessageSharedPtr& message);
+ DeleteInteractionChoiceSetResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief DeleteInteractionChoiceSetResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/delete_sub_menu_request.h b/src/components/application_manager/include/application_manager/commands/mobile/delete_sub_menu_request.h
index 6687218051..7c48de5d8e 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/delete_sub_menu_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/delete_sub_menu_request.h
@@ -52,7 +52,8 @@ class DeleteSubMenuRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit DeleteSubMenuRequest(const MessageSharedPtr& message);
+ DeleteSubMenuRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief DeleteSubMenuRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/delete_sub_menu_response.h b/src/components/application_manager/include/application_manager/commands/mobile/delete_sub_menu_response.h
index 0bb080e93e..76232aee4b 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/delete_sub_menu_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/delete_sub_menu_response.h
@@ -51,7 +51,8 @@ class DeleteSubMenuResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit DeleteSubMenuResponse(const MessageSharedPtr& message);
+ DeleteSubMenuResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief DeleteSubMenuResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/diagnostic_message_request.h b/src/components/application_manager/include/application_manager/commands/mobile/diagnostic_message_request.h
index 4cda040b42..34c8b0e872 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/diagnostic_message_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/diagnostic_message_request.h
@@ -51,7 +51,8 @@ class DiagnosticMessageRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit DiagnosticMessageRequest(const MessageSharedPtr& message);
+ DiagnosticMessageRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief DiagnosticMessageRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/diagnostic_message_response.h b/src/components/application_manager/include/application_manager/commands/mobile/diagnostic_message_response.h
index 1b6a6024f4..439f11a57e 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/diagnostic_message_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/diagnostic_message_response.h
@@ -51,7 +51,8 @@ class DiagnosticMessageResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit DiagnosticMessageResponse(const MessageSharedPtr& message);
+ DiagnosticMessageResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief DiagnosticMessageResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/dial_number_request.h b/src/components/application_manager/include/application_manager/commands/mobile/dial_number_request.h
index ea8556f6e0..1b945fc5fb 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/dial_number_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/dial_number_request.h
@@ -48,7 +48,8 @@ class DialNumberRequest : public CommandRequestImpl {
/**
* \brief DialNumberRequest class constructor
**/
- explicit DialNumberRequest(const MessageSharedPtr& message);
+ DialNumberRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* \brief DialNumberRequest class destructor
@@ -58,11 +59,11 @@ class DialNumberRequest : public CommandRequestImpl {
/**
* @brief Initialize request params
**/
- bool Init() OVERRIDE;
+ bool Init() OVERRIDE;
/**
- * @brief Execute command
- **/
+ * @brief Execute command
+ **/
void Run() OVERRIDE;
/**
@@ -73,13 +74,12 @@ class DialNumberRequest : public CommandRequestImpl {
void on_event(const event_engine::Event& event);
private:
-
/**
* @brief Removes from number param all characters
* except the + character and digits.
*
*/
- void StripNumberParam(std::string &number);
+ void StripNumberParam(std::string& number);
DISALLOW_COPY_AND_ASSIGN(DialNumberRequest);
};
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/dial_number_response.h b/src/components/application_manager/include/application_manager/commands/mobile/dial_number_response.h
index 0cdeb9eb90..4a6980bd04 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/dial_number_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/dial_number_response.h
@@ -1,5 +1,6 @@
/*
- Copyright (c) 2016, Ford Motor Company
+
+ Copyright (c) 2013, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -50,17 +51,18 @@ class DialNumberResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit DialNumberResponse(const MessageSharedPtr& message);
+ DialNumberResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief DialNumberResponse class destructor
**/
- ~DialNumberResponse() OVERRIDE;
+ virtual ~DialNumberResponse();
/**
* @brief Execute command
**/
- void Run() OVERRIDE;
+ virtual void Run();
private:
DISALLOW_COPY_AND_ASSIGN(DialNumberResponse);
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/end_audio_pass_thru_request.h b/src/components/application_manager/include/application_manager/commands/mobile/end_audio_pass_thru_request.h
index f291f7a748..add6d2497e 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/end_audio_pass_thru_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/end_audio_pass_thru_request.h
@@ -51,7 +51,8 @@ class EndAudioPassThruRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit EndAudioPassThruRequest(const MessageSharedPtr& message);
+ EndAudioPassThruRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief EndAudioPassThruRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/end_audio_pass_thru_response.h b/src/components/application_manager/include/application_manager/commands/mobile/end_audio_pass_thru_response.h
index 5ad5f85e6e..381a397fbd 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/end_audio_pass_thru_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/end_audio_pass_thru_response.h
@@ -51,7 +51,8 @@ class EndAudioPassThruResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit EndAudioPassThruResponse(const MessageSharedPtr& message);
+ EndAudioPassThruResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief EndAudioPassThruResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/generic_response.h b/src/components/application_manager/include/application_manager/commands/mobile/generic_response.h
index 1fb931d508..9ccef12152 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/generic_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/generic_response.h
@@ -45,15 +45,14 @@ class GenericResponse : public CommandResponseImpl {
/**
* \brief GenericResponse class constructor
**/
- explicit GenericResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
- }
+ GenericResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
/**
* \brief GenericResponse class destructor
**/
- virtual ~GenericResponse() {
- }
+ virtual ~GenericResponse() {}
/**
* @brief Execute command
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/get_dtcs_request.h b/src/components/application_manager/include/application_manager/commands/mobile/get_dtcs_request.h
index d76ac253bc..d962937e39 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/get_dtcs_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/get_dtcs_request.h
@@ -51,7 +51,8 @@ class GetDTCsRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit GetDTCsRequest(const MessageSharedPtr& message);
+ GetDTCsRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief GetDTCsRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/get_dtcs_response.h b/src/components/application_manager/include/application_manager/commands/mobile/get_dtcs_response.h
index 69ff1fca59..abe970d60f 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/get_dtcs_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/get_dtcs_response.h
@@ -51,7 +51,8 @@ class GetDTCsResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit GetDTCsResponse(const MessageSharedPtr& message);
+ GetDTCsResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief GetDTCsResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/get_vehicle_data_request.h b/src/components/application_manager/include/application_manager/commands/mobile/get_vehicle_data_request.h
index db9db7b0a7..eda77e59b0 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/get_vehicle_data_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/get_vehicle_data_request.h
@@ -53,7 +53,8 @@ class GetVehicleDataRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit GetVehicleDataRequest(const MessageSharedPtr& message);
+ GetVehicleDataRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief GetVehicleDataRequest class destructor
@@ -65,7 +66,6 @@ class GetVehicleDataRequest : public CommandRequestImpl {
**/
virtual void Run();
-
protected:
virtual void on_event(const event_engine::Event& event);
@@ -83,7 +83,7 @@ class GetVehicleDataRequest : public CommandRequestImpl {
typedef std::vector<HmiRequest> HmiRequests;
HmiRequests hmi_requests_;
-#endif // #ifdef HMI_DBUS_API
+#endif // #ifdef HMI_DBUS_API
DISALLOW_COPY_AND_ASSIGN(GetVehicleDataRequest);
};
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/get_vehicle_data_response.h b/src/components/application_manager/include/application_manager/commands/mobile/get_vehicle_data_response.h
index f0306df6aa..4fadaf2b01 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/get_vehicle_data_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/get_vehicle_data_response.h
@@ -51,7 +51,8 @@ class GetVehicleDataResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit GetVehicleDataResponse(const MessageSharedPtr& message);
+ GetVehicleDataResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief GetVehicleDataResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/get_way_points_request.h b/src/components/application_manager/include/application_manager/commands/mobile/get_way_points_request.h
new file mode 100644
index 0000000000..bf23121177
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/mobile/get_way_points_request.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_GET_WAY_POINTS_REQUEST_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_GET_WAY_POINTS_REQUEST_H_
+
+#include "application_manager/commands/command_request_impl.h"
+
+namespace application_manager {
+
+namespace commands {
+
+/**
+ * @brief GetWayPointsRequest command class
+ **/
+class GetWayPointsRequest : public CommandRequestImpl {
+ public:
+ /**
+ * \brief GetWayPointsRequest class constructor
+ **/
+ GetWayPointsRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+
+ /**
+ * \brief GetWayPointsRequest class destructor
+ **/
+ virtual ~GetWayPointsRequest();
+
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run() OVERRIDE;
+ /**
+ * @brief Interface method that is called whenever new event received
+ *
+ * @param event The received event
+ */
+ virtual void on_event(const event_engine::Event& event);
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(GetWayPointsRequest);
+};
+
+} // namespace commands
+
+} // namespace application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_GET_WAY_POINTS_REQUEST_H_
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/get_way_points_response.h b/src/components/application_manager/include/application_manager/commands/mobile/get_way_points_response.h
new file mode 100644
index 0000000000..cb4f840763
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/mobile/get_way_points_response.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_GET_WAY_POINTS_RESPONSE_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_GET_WAY_POINTS_RESPONSE_H_
+
+#include "application_manager/commands/command_response_impl.h"
+#include "utils/macro.h"
+
+namespace application_manager {
+
+namespace commands {
+
+/**
+ * @brief GetWayPointsResponse command class
+ **/
+class GetWayPointsResponse : public CommandResponseImpl {
+ public:
+ /**
+ * \brief GetWayPointsResponse class constructor
+ **/
+ GetWayPointsResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+
+ /**
+ * \brief GetWayPointsResponse class destructor
+ **/
+ virtual ~GetWayPointsResponse();
+
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run() OVERRIDE;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(GetWayPointsResponse);
+};
+
+} // namespace commands
+
+} // namespace application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_GET_WAY_POINTS_RESPONSE_H_
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/list_files_request.h b/src/components/application_manager/include/application_manager/commands/mobile/list_files_request.h
index 86171f1ff8..d8d28b7e9d 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/list_files_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/list_files_request.h
@@ -51,7 +51,8 @@ class ListFilesRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit ListFilesRequest(const MessageSharedPtr& message);
+ ListFilesRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief ListFilesRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/list_files_response.h b/src/components/application_manager/include/application_manager/commands/mobile/list_files_response.h
index 6f8e80bae2..a211ee5968 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/list_files_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/list_files_response.h
@@ -51,7 +51,8 @@ class ListFilesResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit ListFilesResponse(const MessageSharedPtr& message);
+ ListFilesResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief ListFilesResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_app_interface_unregistered_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_app_interface_unregistered_notification.h
index 8753660470..7ef2e7e5d2 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_app_interface_unregistered_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_app_interface_unregistered_notification.h
@@ -51,8 +51,8 @@ class OnAppInterfaceUnregisteredNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnAppInterfaceUnregisteredNotification(
- const MessageSharedPtr& message);
+ OnAppInterfaceUnregisteredNotification(
+ const MessageSharedPtr& message, ApplicationManager& application_manager);
/**
* @brief OnAppInterfaceUnregisteredNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_audio_pass_thru_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_audio_pass_thru_notification.h
index 67bc319771..b74d8fbe41 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_audio_pass_thru_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_audio_pass_thru_notification.h
@@ -42,7 +42,8 @@ namespace application_manager {
namespace commands {
/**
- * @brief OnAudioPassThruNotification class used to send notification with binary data written from
+ * @brief OnAudioPassThruNotification class used to send notification with
+ *binary data written from
* microphone to mobile device while PerformAudioPassThru is active.
**/
class OnAudioPassThruNotification : public CommandNotificationImpl {
@@ -52,7 +53,8 @@ class OnAudioPassThruNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnAudioPassThruNotification(const MessageSharedPtr& message);
+ OnAudioPassThruNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnAudioPassThruNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_button_event_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_button_event_notification.h
index d1297ba980..80355993e1 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_button_event_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_button_event_notification.h
@@ -55,7 +55,8 @@ class OnButtonEventNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnButtonEventNotification(const MessageSharedPtr& message);
+ OnButtonEventNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnButtonEventNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_button_press_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_button_press_notification.h
index 0ebdb6d7c6..1443e58a70 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_button_press_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_button_press_notification.h
@@ -55,7 +55,8 @@ class OnButtonPressNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnButtonPressNotification(const MessageSharedPtr& message);
+ OnButtonPressNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnButtonEventCommand class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_command_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_command_notification.h
index 751b1e7dd2..3f9a0ad6c2 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_command_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_command_notification.h
@@ -54,7 +54,8 @@ class OnCommandNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnCommandNotification(const MessageSharedPtr& message);
+ OnCommandNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnCommandNotification class destructor
@@ -65,6 +66,7 @@ class OnCommandNotification : public CommandNotificationImpl {
* @brief Execute command
**/
virtual void Run();
+
private:
DISALLOW_COPY_AND_ASSIGN(OnCommandNotification);
};
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_driver_distraction_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_driver_distraction_notification.h
index 2f2a3c81fc..ee3c19c707 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_driver_distraction_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_driver_distraction_notification.h
@@ -53,7 +53,8 @@ class OnDriverDistractionNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnDriverDistractionNotification(const MessageSharedPtr& message);
+ OnDriverDistractionNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnDriverDistractionNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_hash_change_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_hash_change_notification.h
index be83047863..9f9fad16d4 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_hash_change_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_hash_change_notification.h
@@ -52,7 +52,8 @@ class OnHashChangeNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnHashChangeNotification(const MessageSharedPtr& message);
+ OnHashChangeNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnHashChangeNotification class destructor
@@ -68,7 +69,7 @@ class OnHashChangeNotification : public CommandNotificationImpl {
DISALLOW_COPY_AND_ASSIGN(OnHashChangeNotification);
};
-} // namespace mobile
+} // namespace mobile
} // namespace commands
} // namespace application_manager
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_hmi_status_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_hmi_status_notification.h
index 11d82925ec..a82182eea0 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_hmi_status_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_hmi_status_notification.h
@@ -51,7 +51,8 @@ class OnHMIStatusNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnHMIStatusNotification(const MessageSharedPtr& message);
+ OnHMIStatusNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnHMIStatusNotification class destructor
@@ -63,7 +64,7 @@ class OnHMIStatusNotification : public CommandNotificationImpl {
**/
virtual void Run();
-private:
+ private:
DISALLOW_COPY_AND_ASSIGN(OnHMIStatusNotification);
};
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_hmi_status_notification_from_mobile.h b/src/components/application_manager/include/application_manager/commands/mobile/on_hmi_status_notification_from_mobile.h
index 70a8bf745b..878f4fa720 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_hmi_status_notification_from_mobile.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_hmi_status_notification_from_mobile.h
@@ -35,6 +35,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_ON_HMI_STATUS_NOTIFICATION_FROM_MOBILE_H_
#include "application_manager/commands/command_notification_from_mobile_impl.h"
+#include "application_manager/application_manager.h"
#include "interfaces/MOBILE_API.h"
#include "utils/macro.h"
@@ -45,15 +46,16 @@ namespace commands {
/**
* @brief OnHMIStatusNotificationFromMobile class
**/
-class OnHMIStatusNotificationFromMobile :
- public CommandNotificationFromMobileImpl {
+class OnHMIStatusNotificationFromMobile
+ : public CommandNotificationFromMobileImpl {
public:
/**
* @brief OnHMIStatusNotificationFromMobile class constructor
*
* @param message Incoming SmartObject message
**/
- explicit OnHMIStatusNotificationFromMobile(const MessageSharedPtr& message);
+ OnHMIStatusNotificationFromMobile(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnHMIStatusNotificationFromMobile class destructor
@@ -65,7 +67,7 @@ class OnHMIStatusNotificationFromMobile :
**/
virtual void Run();
-private:
+ private:
DISALLOW_COPY_AND_ASSIGN(OnHMIStatusNotificationFromMobile);
};
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_keyboard_input_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_keyboard_input_notification.h
index e0d6a258e9..911ca70cdf 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_keyboard_input_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_keyboard_input_notification.h
@@ -53,7 +53,8 @@ class OnKeyBoardInputNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnKeyBoardInputNotification(const MessageSharedPtr& message);
+ OnKeyBoardInputNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnKeyBoardInputNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_language_change_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_language_change_notification.h
index d163114890..c62652ff67 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_language_change_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_language_change_notification.h
@@ -51,7 +51,8 @@ class OnLanguageChangeNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnLanguageChangeNotification(const MessageSharedPtr& message);
+ OnLanguageChangeNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnLanguageChangeNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_permissions_change_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_permissions_change_notification.h
index 3cffe8ff49..d5f7aa96b8 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_permissions_change_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_permissions_change_notification.h
@@ -51,7 +51,8 @@ class OnPermissionsChangeNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnPermissionsChangeNotification(const MessageSharedPtr& message);
+ OnPermissionsChangeNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnPermissionsChangeNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_system_request_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_system_request_notification.h
index cba6c4ed99..143b076033 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_system_request_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_system_request_notification.h
@@ -53,7 +53,8 @@ class OnSystemRequestNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnSystemRequestNotification(const MessageSharedPtr& message);
+ OnSystemRequestNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnSystemRequestNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_tbt_client_state_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_tbt_client_state_notification.h
index 5c34caba36..e7b895dceb 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_tbt_client_state_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_tbt_client_state_notification.h
@@ -51,7 +51,8 @@ class OnTBTClientStateNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnTBTClientStateNotification(const MessageSharedPtr& message);
+ OnTBTClientStateNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnTBTClientStateNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_touch_event_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_touch_event_notification.h
index 1aba3087dd..abbf6787db 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_touch_event_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_touch_event_notification.h
@@ -53,7 +53,8 @@ class OnTouchEventNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnTouchEventNotification(const MessageSharedPtr& message);
+ OnTouchEventNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnTouchEventNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_vehicle_data_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_vehicle_data_notification.h
index 7e64f19639..de6172de64 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/on_vehicle_data_notification.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_vehicle_data_notification.h
@@ -53,7 +53,8 @@ class OnVehicleDataNotification : public CommandNotificationImpl {
*
* @param message Incoming SmartObject message
**/
- explicit OnVehicleDataNotification(const MessageSharedPtr& message);
+ OnVehicleDataNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief OnVehicleDataNotification class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/on_way_point_change_notification.h b/src/components/application_manager/include/application_manager/commands/mobile/on_way_point_change_notification.h
new file mode 100644
index 0000000000..c204e1669c
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/mobile/on_way_point_change_notification.h
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_ON_WAY_POINT_CHANGE_NOTIFICATION_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_ON_WAY_POINT_CHANGE_NOTIFICATION_H_
+
+#include "application_manager/commands/command_notification_impl.h"
+#include "utils/macro.h"
+
+namespace application_manager {
+
+namespace commands {
+
+class OnWayPointChangeNotification : public CommandNotificationImpl {
+ public:
+ /**
+ * @brief OnWayPointChangeNotification class constructor
+ *
+ * @param message Incoming SmartObject message
+ **/
+ OnWayPointChangeNotification(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+
+ /**
+ * @brief OnWayPointChangeNotification class destructor
+ **/
+ virtual ~OnWayPointChangeNotification();
+
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run() OVERRIDE;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(OnWayPointChangeNotification);
+};
+
+} // namespace commands
+} // namespace application_manager
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_ON_WAY_POINT_CHANGE_NOTIFICATION_H_
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/perform_audio_pass_thru_request.h b/src/components/application_manager/include/application_manager/commands/mobile/perform_audio_pass_thru_request.h
index 62ca1257bb..b69cb969e1 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/perform_audio_pass_thru_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/perform_audio_pass_thru_request.h
@@ -52,7 +52,8 @@ class PerformAudioPassThruRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit PerformAudioPassThruRequest(const MessageSharedPtr& message);
+ PerformAudioPassThruRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief PerformAudioPassThruRequest class destructor
@@ -114,12 +115,19 @@ class PerformAudioPassThruRequest : public CommandRequestImpl {
bool IsWhiteSpaceExist();
/**
+ * @brief Waiting for TTS.Speak response, after default timeout send
+ * GENERIC_ERROR response
+ * @return if receive TTS.Speak return TRUE, FALSE otherwise
+ */
+ bool WaitTTSSpeak();
+
+ /**
* @brief If is_active_tts_speak_ TRUE - set up to FALSE and send request
* TTS_StopSpeaking to HMI
*/
void FinishTTSSpeak();
- //flag display state of speak during perform audio pass thru
+ // flag display state of speak during perform audio pass thru
bool is_active_tts_speak_;
mobile_apis::Result::eType result_tts_speak_;
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/perform_audio_pass_thru_response.h b/src/components/application_manager/include/application_manager/commands/mobile/perform_audio_pass_thru_response.h
index d659e59be0..d227c4fef3 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/perform_audio_pass_thru_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/perform_audio_pass_thru_response.h
@@ -51,7 +51,8 @@ class PerformAudioPassThruResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit PerformAudioPassThruResponse(const MessageSharedPtr& message);
+ PerformAudioPassThruResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief PerformAudioPassThruResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/perform_interaction_request.h b/src/components/application_manager/include/application_manager/commands/mobile/perform_interaction_request.h
index 02575c1126..f64b2ab334 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/perform_interaction_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/perform_interaction_request.h
@@ -36,7 +36,6 @@
#include "application_manager/commands/command_request_impl.h"
#include "application_manager/application.h"
-#include "utils/timer_thread.h"
#include "utils/macro.h"
namespace application_manager {
@@ -48,15 +47,15 @@ namespace commands {
/**
* @brief PerformInteractionRequest command class
**/
-class PerformInteractionRequest : public CommandRequestImpl {
-
+class PerformInteractionRequest : public CommandRequestImpl {
public:
/**
* @brief PerformInteractionRequest class constructor
*
* @param message Incoming SmartObject message
**/
- explicit PerformInteractionRequest(const MessageSharedPtr& message);
+ PerformInteractionRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief PerformInteractionRequest class destructor
@@ -86,7 +85,7 @@ class PerformInteractionRequest : public CommandRequestImpl {
* has exceed it's limit
*
*/
- virtual void onTimeOut();
+ virtual void onTimeOut();
/*
* @brief Function will be called when VR_OnCommand event
@@ -95,7 +94,8 @@ class PerformInteractionRequest : public CommandRequestImpl {
* @param message which should send to mobile side
*
*/
- void ProcessVRResponse(const smart_objects::SmartObject& message);
+ void ProcessVRResponse(const smart_objects::SmartObject& message,
+ smart_objects::SmartObject& msg_params);
/*
* @brief Sends PerformInteraction response to mobile side
@@ -103,9 +103,9 @@ class PerformInteractionRequest : public CommandRequestImpl {
* @param message which should send to mobile side
*
*/
- void ProcessPerformInteractionResponse
- (const smart_objects::SmartObject& message);
-
+ void ProcessPerformInteractionResponse(
+ const smart_objects::SmartObject& message,
+ smart_objects::SmartObject& msg_params);
/*
* @brief Sends UI PerformInteraction request to HMI
@@ -132,12 +132,6 @@ class PerformInteractionRequest : public CommandRequestImpl {
*/
void SendUIShowVRHelpRequest(ApplicationSharedPtr const app);
- /**
- * @brief Creates and Sends Perform interaction to UI.
- */
- void CreateUIPerformInteraction(const smart_objects::SmartObject& msg_params,
- application_manager::ApplicationSharedPtr const app);
-
/*
* @brief Checks if incoming choice set doesn't has similar menu names.
*
@@ -146,7 +140,8 @@ class PerformInteractionRequest : public CommandRequestImpl {
* return Return TRUE if there are no similar menu names in choice set,
* otherwise FALSE
*/
- bool CheckChoiceSetMenuNames(application_manager::ApplicationSharedPtr const app);
+ bool CheckChoiceSetMenuNames(
+ application_manager::ApplicationSharedPtr const app);
/*
* @brief Checks if incoming choice set doesn't has similar VR synonyms.
@@ -156,7 +151,8 @@ class PerformInteractionRequest : public CommandRequestImpl {
* return Return TRUE if there are no similar VR synonyms in choice set,
* otherwise FALSE
*/
- bool CheckChoiceSetVRSynonyms(application_manager::ApplicationSharedPtr const app);
+ bool CheckChoiceSetVRSynonyms(
+ application_manager::ApplicationSharedPtr const app);
/*
* @brief Checks if request with non-sequential positions of vrHelpItems
@@ -167,7 +163,8 @@ class PerformInteractionRequest : public CommandRequestImpl {
* @return TRUE if vrHelpItems positions are sequential,
* otherwise FALSE
*/
- bool CheckVrHelpItemPositions(application_manager::ApplicationSharedPtr const app);
+ bool CheckVrHelpItemPositions(
+ application_manager::ApplicationSharedPtr const app);
/*
* @brief Disable PerformInteraction state in application and
@@ -197,13 +194,50 @@ class PerformInteractionRequest : public CommandRequestImpl {
*/
bool CheckChoiceIDFromResponse(ApplicationSharedPtr app, int32_t choice_id);
- // members
- mobile_apis::Result::eType vr_perform_interaction_code_;
+ /**
+ * @brief Checks for a match of choice ID, in
+ * choice sets.
+ * @param app contains pointer to application.
+ * @param choice_set_id_list_length contains amount
+ * of choice set ids.
+ * @param choice_set_id_list array of choice set ids
+ * @return If request contains several choice sets with
+ * same choice id returns false, otherwise returns
+ * true.
+ */
+ bool CheckChoiceIDFromRequest(
+ ApplicationSharedPtr app,
+ const size_t choice_set_id_list_length,
+ const smart_objects::SmartObject& choice_set_id_list) const;
+
+ /**
+ * @brief Tells if there are sent requests without responses
+ * @return If there is request without response method returns TRUE
+ * otherwise returns FALSE
+ */
+ const bool HasHMIResponsesToWait() const;
+
+ /**
+ * @brief Check VR response result code, in case GENERIC_ERROR, REJECTED,
+ * send resultCode FALSE, in case WARNINGS send resultCode TRUE
+ */
+ void CheckResponseResultCode();
+
+ /**
+ * @brief Check UI & VR result codes, send response to mobile
+ * @param msg_param Message params to send
+ */
+ void SendBothModeResponse(const smart_objects::SmartObject& msg_param);
+
mobile_apis::InteractionMode::eType interaction_mode_;
- bool ui_response_recived_;
- bool vr_response_recived_;
- bool app_pi_was_active_before_;
- static uint32_t pi_requests_count_;
+ bool ui_response_recived_;
+ bool vr_response_recived_;
+ bool ui_result_;
+ bool vr_result_;
+ bool app_pi_was_active_before_;
+ static uint32_t pi_requests_count_;
+ mobile_apis::Result::eType vr_resultCode_;
+ mobile_apis::Result::eType ui_resultCode_;
DISALLOW_COPY_AND_ASSIGN(PerformInteractionRequest);
};
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/perform_interaction_response.h b/src/components/application_manager/include/application_manager/commands/mobile/perform_interaction_response.h
index 4ecc149fb4..1274996747 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/perform_interaction_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/perform_interaction_response.h
@@ -51,7 +51,8 @@ class PerformInteractionResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit PerformInteractionResponse(const MessageSharedPtr& message);
+ PerformInteractionResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief PerformInteractionResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/put_file_request.h b/src/components/application_manager/include/application_manager/commands/mobile/put_file_request.h
index 8a94a708a1..e3af8ac69b 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/put_file_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/put_file_request.h
@@ -36,7 +36,7 @@
#include "application_manager/commands/command_request_impl.h"
#include "utils/macro.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
@@ -52,7 +52,8 @@ class PutFileRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit PutFileRequest(const MessageSharedPtr& message);
+ PutFileRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief PutFileRequest class destructor
@@ -65,13 +66,13 @@ class PutFileRequest : public CommandRequestImpl {
virtual void Run();
private:
- int64_t offset_;
- std::string sync_file_name_;
- int64_t length_;
- mobile_apis::FileType::eType file_type_;
- bool is_persistent_file_;
+ int64_t offset_;
+ std::string sync_file_name_;
+ int64_t length_;
+ mobile_apis::FileType::eType file_type_;
+ bool is_persistent_file_;
- void SendOnPutFileNotification();
+ void SendOnPutFileNotification();
DISALLOW_COPY_AND_ASSIGN(PutFileRequest);
};
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/put_file_response.h b/src/components/application_manager/include/application_manager/commands/mobile/put_file_response.h
index 89ff6ad08f..f561f9fdbc 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/put_file_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/put_file_response.h
@@ -51,7 +51,8 @@ class PutFileResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit PutFileResponse(const MessageSharedPtr& message);
+ PutFileResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief PutFileResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/read_did_request.h b/src/components/application_manager/include/application_manager/commands/mobile/read_did_request.h
index e2e5dbf3da..c88f16dab0 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/read_did_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/read_did_request.h
@@ -51,7 +51,8 @@ class ReadDIDRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit ReadDIDRequest(const MessageSharedPtr& message);
+ ReadDIDRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief ReadDIDRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/read_did_response.h b/src/components/application_manager/include/application_manager/commands/mobile/read_did_response.h
index 80b9b5ea48..2e493fa0ec 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/read_did_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/read_did_response.h
@@ -51,7 +51,8 @@ class ReadDIDResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit ReadDIDResponse(const MessageSharedPtr& message);
+ ReadDIDResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief ReadDIDResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/register_app_interface_request.h b/src/components/application_manager/include/application_manager/commands/mobile/register_app_interface_request.h
index e5bcf40da9..b0a2ee05d1 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/register_app_interface_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/register_app_interface_request.h
@@ -34,9 +34,10 @@
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_REGISTER_APP_INTERFACE_REQUEST_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_REGISTER_APP_INTERFACE_REQUEST_H_
-#include <string.h>
#include "application_manager/commands/command_request_impl.h"
+#include "application_manager/policies/policy_handler_interface.h"
#include "utils/macro.h"
+#include "utils/custom_string.h"
namespace policy {
struct DeviceInfo;
@@ -48,6 +49,8 @@ class Application;
namespace commands {
+namespace custom_str = utils::custom_string;
+
/**
* @brief Register app interface request command class
**/
@@ -56,7 +59,8 @@ class RegisterAppInterfaceRequest : public CommandRequestImpl {
/**
* \brief RegisterAppInterfaceRequest class constructor
**/
- explicit RegisterAppInterfaceRequest(const MessageSharedPtr& message);
+ RegisterAppInterfaceRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief RegisterAppInterfaceRequest class destructor
@@ -79,10 +83,22 @@ class RegisterAppInterfaceRequest : public CommandRequestImpl {
*@param application_impl application
*
**/
- void SendRegisterAppInterfaceResponseToMobile(
- mobile_apis::Result::eType result = mobile_apis::Result::SUCCESS);
+ void SendRegisterAppInterfaceResponseToMobile();
private:
+ smart_objects::SmartObjectSPtr GetLockScreenIconUrlNotification(
+ const uint32_t connection_key,
+ ApplicationSharedPtr app);
+
+ /**
+ * @brief Sends OnAppRegistered notification to HMI
+ *
+ *@param application_impl application with changed HMI status
+ *
+ **/
+ void SendOnAppRegisteredNotificationToHMI(const Application& application_impl,
+ bool resumption = false,
+ bool need_restore_vr = false);
/*
* @brief Check new ID along with known mobile application ID
*
@@ -100,22 +116,21 @@ class RegisterAppInterfaceRequest : public CommandRequestImpl {
mobile_apis::Result::eType CheckCoincidence();
/*
- * @brief Predicate for using with CheckCoincidence method to compare with VR synonym SO
+ * @brief Predicate for using with CheckCoincidence method to compare with VR
+ * synonym SO
*
* return TRUE if there is coincidence of VR, otherwise FALSE
*/
struct CoincidencePredicateVR {
- explicit CoincidencePredicateVR(const std::string &newItem)
- :newItem_(newItem)
- {};
-
- bool operator()(smart_objects::SmartObject obj) {
- const std::string vr_synonym = obj.asString();
- return !(strcasecmp(vr_synonym.c_str(), newItem_.c_str()));
- };
+ CoincidencePredicateVR(const custom_str::CustomString& newItem)
+ : newItem_(newItem) {}
- const std::string &newItem_;
- };
+ bool operator()(const smart_objects::SmartObject& obj) {
+ const custom_str::CustomString& vr_synonym = obj.asCustomString();
+ return newItem_.CompareIgnoreCase(vr_synonym);
+ }
+ const custom_str::CustomString& newItem_;
+ };
/**
* @brief Check request parameters against policy table data
@@ -153,11 +168,11 @@ class RegisterAppInterfaceRequest : public CommandRequestImpl {
*/
void SendSubscribeCustomButtonNotification();
-private:
+ private:
std::string response_info_;
mobile_apis::Result::eType result_checking_app_hmi_type_;
-
+ policy::PolicyHandlerInterface& GetPolicyHandler();
DISALLOW_COPY_AND_ASSIGN(RegisterAppInterfaceRequest);
};
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/register_app_interface_response.h b/src/components/application_manager/include/application_manager/commands/mobile/register_app_interface_response.h
index 1244cb65f8..b125cc7c55 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/register_app_interface_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/register_app_interface_response.h
@@ -47,15 +47,14 @@ class RegisterAppInterfaceResponse : public CommandResponseImpl {
/**
* \brief RegisterAppInterfaceResponse class constructor
**/
- explicit RegisterAppInterfaceResponse(const MessageSharedPtr& response)
- : CommandResponseImpl(response) {
- }
+ RegisterAppInterfaceResponse(const MessageSharedPtr& response,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(response, application_manager) {}
/**
* \brief RegisterAppInterfaceResponse class destructor
**/
- virtual ~RegisterAppInterfaceResponse() {
- }
+ virtual ~RegisterAppInterfaceResponse() {}
/**
* @brief Execute command
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/reset_global_properties_request.h b/src/components/application_manager/include/application_manager/commands/mobile/reset_global_properties_request.h
index d7abe38c11..0053c14f3c 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/reset_global_properties_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/reset_global_properties_request.h
@@ -52,7 +52,8 @@ class ResetGlobalPropertiesRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit ResetGlobalPropertiesRequest(const MessageSharedPtr& message);
+ ResetGlobalPropertiesRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief ResetGlobalPropertiesRequest class destructor
@@ -103,7 +104,8 @@ class ResetGlobalPropertiesRequest : public CommandRequestImpl {
*
* @return TRUE on success, otherwise FALSE
*/
- bool ResetVrHelpTitleItems(application_manager::ApplicationSharedPtr const app);
+ bool ResetVrHelpTitleItems(
+ application_manager::ApplicationSharedPtr const app);
/*
* @brief Check if there some not delivered hmi responses exist
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/reset_global_properties_response.h b/src/components/application_manager/include/application_manager/commands/mobile/reset_global_properties_response.h
index 7c0b8eb00b..39e28486d4 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/reset_global_properties_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/reset_global_properties_response.h
@@ -51,7 +51,8 @@ class ResetGlobalPropertiesResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit ResetGlobalPropertiesResponse(const MessageSharedPtr& message);
+ ResetGlobalPropertiesResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief ResetGlobalPropertiesResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/scrollable_message_request.h b/src/components/application_manager/include/application_manager/commands/mobile/scrollable_message_request.h
index a810f4eb2d..b3058c9a26 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/scrollable_message_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/scrollable_message_request.h
@@ -50,7 +50,8 @@ class ScrollableMessageRequest : public CommandRequestImpl {
/**
* @brief ScrollableMessageRequest class constructor
**/
- explicit ScrollableMessageRequest(const MessageSharedPtr& message);
+ ScrollableMessageRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SliderCommand class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/scrollable_message_response.h b/src/components/application_manager/include/application_manager/commands/mobile/scrollable_message_response.h
index f0c0ea8f7a..aa0ac01e9d 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/scrollable_message_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/scrollable_message_response.h
@@ -45,13 +45,13 @@ class ScrollableMessageResponse : public CommandResponseImpl {
/**
* \brief ScrollableMessageResponse class constructor
**/
- explicit ScrollableMessageResponse(const MessageSharedPtr& message);
+ ScrollableMessageResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* \brief SpeakResponseCommand class destructor
**/
- virtual ~ScrollableMessageResponse() {
- }
+ virtual ~ScrollableMessageResponse() {}
/**
* @brief Execute command
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/send_location_request.h b/src/components/application_manager/include/application_manager/commands/mobile/send_location_request.h
index 581c779aa5..570e70d007 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/send_location_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/send_location_request.h
@@ -34,6 +34,7 @@
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SEND_LOCATION_REQUEST_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SEND_LOCATION_REQUEST_H_
+#include <list>
#include "application_manager/commands/command_request_impl.h"
namespace application_manager {
@@ -48,7 +49,8 @@ class SendLocationRequest : public CommandRequestImpl {
/**
* @brief SendLocationRquest class constructor
*/
- explicit SendLocationRequest(const MessageSharedPtr& message);
+ SendLocationRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SendLocationRquest class destructor
@@ -67,8 +69,13 @@ class SendLocationRequest : public CommandRequestImpl {
*/
virtual void on_event(const event_engine::Event& event);
-
private:
+ /**
+ * @brief CheckFieldsCompatibility checks if fields are compatible with each
+ * other.
+ * @return true if compatible, otherwise return false
+ */
+ bool CheckFieldsCompatibility();
/**
* @brief Checks sendlocation params(locationName, locationDescription, ...).
@@ -77,7 +84,8 @@ class SendLocationRequest : public CommandRequestImpl {
*/
bool IsWhiteSpaceExist();
- bool CheckHMICapabilities(std::list<hmi_apis::Common_TextFieldName::eType>& fields_names);
+ bool CheckHMICapabilities(
+ std::vector<hmi_apis::Common_TextFieldName::eType>& fields_names);
DISALLOW_COPY_AND_ASSIGN(SendLocationRequest);
};
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/send_location_response.h b/src/components/application_manager/include/application_manager/commands/mobile/send_location_response.h
index fe88a2af29..0be0be8ca3 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/send_location_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/send_location_response.h
@@ -36,7 +36,6 @@
#include "application_manager/commands/command_response_impl.h"
#include "application_manager/message.h"
-
namespace application_manager {
namespace commands {
@@ -45,7 +44,8 @@ class SendLocationResponse : public CommandResponseImpl {
/**
* @brief SendLocationResponse class constructor
*/
- explicit SendLocationResponse(const MessageSharedPtr& message);
+ SendLocationResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SendLocationResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/set_app_icon_request.h b/src/components/application_manager/include/application_manager/commands/mobile/set_app_icon_request.h
index da21decd81..42eedad19b 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/set_app_icon_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/set_app_icon_request.h
@@ -49,17 +49,15 @@ class SetAppIconRequest : public CommandRequestImpl {
/**
* @brief Contains information about the type of image
*/
- typedef enum {
- STATIC = 0,
- DYNAMIC
- } ImageType;
+ typedef enum { STATIC = 0, DYNAMIC } ImageType;
/**
* @brief SetIconRequest class constructor
*
* @param message Incoming SmartObject message
**/
- explicit SetAppIconRequest(const MessageSharedPtr& message);
+ SetAppIconRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SetIconRequest class destructor
@@ -101,11 +99,11 @@ class SetAppIconRequest : public CommandRequestImpl {
bool IsEnoughSpaceForIcon(const uint64_t icon_size) const;
DISALLOW_COPY_AND_ASSIGN(SetAppIconRequest);
-private:
+ private:
/**
* @brief Checks, if icons saving to configured folder is enabled
*/
- static int8_t is_icons_saving_enabled_;
+ bool is_icons_saving_enabled_;
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/set_app_icon_response.h b/src/components/application_manager/include/application_manager/commands/mobile/set_app_icon_response.h
index 02be7fe37e..6061cf5702 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/set_app_icon_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/set_app_icon_response.h
@@ -51,7 +51,8 @@ class SetAppIconResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit SetAppIconResponse(const MessageSharedPtr& message);
+ SetAppIconResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SetIconResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/set_display_layout_request.h b/src/components/application_manager/include/application_manager/commands/mobile/set_display_layout_request.h
index 925a1cd67f..06e8d70f79 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/set_display_layout_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/set_display_layout_request.h
@@ -51,7 +51,8 @@ class SetDisplayLayoutRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit SetDisplayLayoutRequest(const MessageSharedPtr& message);
+ SetDisplayLayoutRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SetDisplayLayoutRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/set_display_layout_response.h b/src/components/application_manager/include/application_manager/commands/mobile/set_display_layout_response.h
index dbf3de8d88..a2040307b0 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/set_display_layout_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/set_display_layout_response.h
@@ -51,7 +51,8 @@ class SetDisplayLayoutResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit SetDisplayLayoutResponse(const MessageSharedPtr& message);
+ SetDisplayLayoutResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SetDisplayLayoutResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/set_global_properties_request.h b/src/components/application_manager/include/application_manager/commands/mobile/set_global_properties_request.h
index d9e18dd76f..aa26a70393 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/set_global_properties_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/set_global_properties_request.h
@@ -1,6 +1,5 @@
/*
-
- Copyright (c) 2013, Ford Motor Company
+ Copyright (c) 2015, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -36,6 +35,7 @@
#include "application_manager/commands/command_request_impl.h"
#include "utils/macro.h"
+#include "application_manager/application.h"
namespace application_manager {
@@ -51,7 +51,8 @@ class SetGlobalPropertiesRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit SetGlobalPropertiesRequest(const MessageSharedPtr& message);
+ SetGlobalPropertiesRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SetGlobalPropertiesRequest class destructor
@@ -71,21 +72,42 @@ class SetGlobalPropertiesRequest : public CommandRequestImpl {
void on_event(const event_engine::Event& event);
private:
- /*
- * @brief Chec if HelpItems order is correct
- *
- * @return TRUE on success, otherwise FALSE
- */
- bool CheckVrHelpItemsOrder();
+ // Verify correctness VrHelptitle value
+ static bool ValidateVRHelpTitle(
+ const smart_objects::SmartObject* const vr_help_so_ptr);
+
+ // prepare UI sending data (VrHelps, Menus, Keyboard) to SmartObject
+ static void PrepareUIRequestVRHelpData(
+ const ApplicationSharedPtr app,
+ const smart_objects::SmartObject& msg_params,
+ smart_objects::SmartObject& out_params);
+
+ static bool PrepareUIRequestDefaultVRHelpData(
+ const ApplicationSharedPtr app, smart_objects::SmartObject& out_params);
+
+ static void PrepareUIRequestMenuAndKeyboardData(
+ const ApplicationSharedPtr app,
+ const smart_objects::SmartObject& msg_params,
+ smart_objects::SmartObject& out_params);
+
+ // Send TTS request to HMI
+ void SendTTSRequest(const smart_objects::SmartObject& params,
+ bool use_events);
+
+ // Send UI request to HMI
+ void SendUIRequest(const smart_objects::SmartObject& params, bool use_events);
- /*
+ // VRHelp shall contain sequential positions and start from 1
+ static bool CheckVrHelpItemsOrder(const smart_objects::SmartObject& vr_help);
+
+ /**
* @brief Check if there some not delivered hmi responses exist
*
* @return true if all responses received
*/
bool IsPendingResponseExist();
- /*
+ /**
* @brief Checks if request has at least one parameter
*
* @param params request parameters
@@ -103,8 +125,6 @@ class SetGlobalPropertiesRequest : public CommandRequestImpl {
*/
bool IsWhiteSpaceExist();
- DISALLOW_COPY_AND_ASSIGN(SetGlobalPropertiesRequest);
-
bool is_ui_send_;
bool is_tts_send_;
@@ -113,6 +133,8 @@ class SetGlobalPropertiesRequest : public CommandRequestImpl {
hmi_apis::Common_Result::eType ui_result_;
hmi_apis::Common_Result::eType tts_result_;
+
+ DISALLOW_COPY_AND_ASSIGN(SetGlobalPropertiesRequest);
};
} // namespace commands
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/set_global_properties_response.h b/src/components/application_manager/include/application_manager/commands/mobile/set_global_properties_response.h
index dd80e738e3..c5beda084d 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/set_global_properties_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/set_global_properties_response.h
@@ -51,7 +51,8 @@ class SetGlobalPropertiesResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit SetGlobalPropertiesResponse(const MessageSharedPtr& message);
+ SetGlobalPropertiesResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SetGlobalPropertiesResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/set_icon_request.h b/src/components/application_manager/include/application_manager/commands/mobile/set_icon_request.h
index d46094032a..96d4ac6f1e 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/set_icon_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/set_icon_request.h
@@ -35,6 +35,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SET_ICON_REQUEST_H_
#include "application_manager/commands/command_request_impl.h"
+#include "application_manager/application_manager.h"
#include "utils/macro.h"
namespace application_manager {
@@ -49,17 +50,15 @@ class SetIconRequest : public CommandRequestImpl {
/**
* @brief Contains information about the type of image
*/
- typedef enum {
- STATIC = 0,
- DYNAMIC
- } ImageType;
+ typedef enum { STATIC = 0, DYNAMIC } ImageType;
/**
* @brief SetIconRequest class constructor
*
* @param message Incoming SmartObject message
**/
- explicit SetIconRequest(const MessageSharedPtr& message);
+ SetIconRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SetIconRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/set_icon_response.h b/src/components/application_manager/include/application_manager/commands/mobile/set_icon_response.h
index 88dceaf5a2..83be0d4a4b 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/set_icon_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/set_icon_response.h
@@ -35,6 +35,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SET_ICON_RESPONSE_H_
#include "application_manager/commands/command_response_impl.h"
+#include "application_manager/application_manager.h"
#include "utils/macro.h"
namespace application_manager {
@@ -51,7 +52,7 @@ class SetIconResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit SetIconResponse(const MessageSharedPtr& message);
+ SetIconResponse(const MessageSharedPtr& message, ApplicationManager& app_man);
/**
* @brief SetIconResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/set_media_clock_timer_request.h b/src/components/application_manager/include/application_manager/commands/mobile/set_media_clock_timer_request.h
index e4fae5c0b3..283dd41622 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/set_media_clock_timer_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/set_media_clock_timer_request.h
@@ -49,7 +49,8 @@ class SetMediaClockRequest : public CommandRequestImpl {
/**
* \brief SetMediaClockRequest class constructor
**/
- explicit SetMediaClockRequest(const MessageSharedPtr& message);
+ SetMediaClockRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* \brief ShowCommand class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/set_media_clock_timer_response.h b/src/components/application_manager/include/application_manager/commands/mobile/set_media_clock_timer_response.h
index 46844bd2f3..3f41ae2dab 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/set_media_clock_timer_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/set_media_clock_timer_response.h
@@ -45,7 +45,8 @@ class SetMediaClockTimerResponse : public CommandResponseImpl {
/**
* \brief SetMediaClockTimerResponse class constructor
**/
- explicit SetMediaClockTimerResponse(const MessageSharedPtr& message);
+ SetMediaClockTimerResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* \brief SetMediaClockTimerResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/show_constant_tbt_request.h b/src/components/application_manager/include/application_manager/commands/mobile/show_constant_tbt_request.h
index a22ee9852a..f015d740df 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/show_constant_tbt_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/show_constant_tbt_request.h
@@ -52,7 +52,8 @@ class ShowConstantTBTRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit ShowConstantTBTRequest(const MessageSharedPtr& message);
+ ShowConstantTBTRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief ShowConstantTBTRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/show_constant_tbt_response.h b/src/components/application_manager/include/application_manager/commands/mobile/show_constant_tbt_response.h
index 6a102b1984..73aad5de89 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/show_constant_tbt_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/show_constant_tbt_response.h
@@ -51,7 +51,8 @@ class ShowConstantTBTResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit ShowConstantTBTResponse(const MessageSharedPtr& message);
+ ShowConstantTBTResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief ShowConstantTBTResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/show_request.h b/src/components/application_manager/include/application_manager/commands/mobile/show_request.h
index 091cab3bfd..cbe2ca396a 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/show_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/show_request.h
@@ -50,7 +50,8 @@ class ShowRequest : public CommandRequestImpl {
/**
* \brief ShowRequest class constructor
**/
- explicit ShowRequest(const MessageSharedPtr& message);
+ ShowRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* \brief ShowRequest class destructor
@@ -70,7 +71,6 @@ class ShowRequest : public CommandRequestImpl {
virtual void on_event(const event_engine::Event& event);
private:
-
/*
* @brief Check if all strings have valid syntax in request
*
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/show_response.h b/src/components/application_manager/include/application_manager/commands/mobile/show_response.h
index c327bc3b3a..0a54fb9cde 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/show_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/show_response.h
@@ -45,7 +45,8 @@ class ShowResponse : public CommandResponseImpl {
/**
* \brief ShowResponse class constructor
**/
- explicit ShowResponse(const MessageSharedPtr& message);
+ ShowResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* \brief ShowResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/slider_request.h b/src/components/application_manager/include/application_manager/commands/mobile/slider_request.h
index de24438ddd..2446c9ff20 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/slider_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/slider_request.h
@@ -49,7 +49,8 @@ class SliderRequest : public CommandRequestImpl {
/**
* \brief SliderRequest class constructor
**/
- explicit SliderRequest(const MessageSharedPtr& message);
+ SliderRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* \brief SliderRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/slider_response.h b/src/components/application_manager/include/application_manager/commands/mobile/slider_response.h
index 1888388e7c..bc0efaadd0 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/slider_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/slider_response.h
@@ -45,7 +45,8 @@ class SliderResponse : public CommandResponseImpl {
/**
* \brief SliderResponse class constructor
**/
- explicit SliderResponse(const MessageSharedPtr& message);
+ SliderResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* \brief SpeakResponseCommand class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/speak_request.h b/src/components/application_manager/include/application_manager/commands/mobile/speak_request.h
index 7d3b2096af..dc22652b27 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/speak_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/speak_request.h
@@ -49,7 +49,8 @@ class SpeakRequest : public CommandRequestImpl {
/**
* \brief SpeakRequest class constructor
**/
- explicit SpeakRequest(const MessageSharedPtr& message);
+ SpeakRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* \brief SpeakRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/speak_response.h b/src/components/application_manager/include/application_manager/commands/mobile/speak_response.h
index cbf1ec40de..2808526603 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/speak_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/speak_response.h
@@ -45,7 +45,8 @@ class SpeakResponse : public CommandResponseImpl {
/**
* \brief SpeakResponse class constructor
**/
- explicit SpeakResponse(const MessageSharedPtr& message);
+ SpeakResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* \brief SpeakResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/subscribe_button_request.h b/src/components/application_manager/include/application_manager/commands/mobile/subscribe_button_request.h
index 12168e2473..b5a22d40a9 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/subscribe_button_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/subscribe_button_request.h
@@ -52,7 +52,8 @@ class SubscribeButtonRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit SubscribeButtonRequest(const MessageSharedPtr& message);
+ SubscribeButtonRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SubscribeButtonRequest class destructor
@@ -65,7 +66,6 @@ class SubscribeButtonRequest : public CommandRequestImpl {
virtual void Run();
private:
-
/**
* @brief Checks if button subscription allowed. In case non-media
* application trying to subscribe on buttons(tune, seek) negative result will
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/subscribe_button_response.h b/src/components/application_manager/include/application_manager/commands/mobile/subscribe_button_response.h
index 8366884540..38e0dd2dc6 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/subscribe_button_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/subscribe_button_response.h
@@ -51,7 +51,8 @@ class SubscribeButtonResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit SubscribeButtonResponse(const MessageSharedPtr& message);
+ SubscribeButtonResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SubscribeButtonResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/subscribe_vehicle_data_request.h b/src/components/application_manager/include/application_manager/commands/mobile/subscribe_vehicle_data_request.h
index 288500e7e8..6b2c2bb616 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/subscribe_vehicle_data_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/subscribe_vehicle_data_request.h
@@ -35,6 +35,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SUBSCRIBE_VEHICLE_DATA_REQUEST_H_
#include "application_manager/commands/command_request_impl.h"
+#include "application_manager/application.h"
#include "utils/macro.h"
namespace application_manager {
@@ -51,7 +52,8 @@ class SubscribeVehicleDataRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit SubscribeVehicleDataRequest(const MessageSharedPtr& message);
+ SubscribeVehicleDataRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SubscribeButtonCommandRequest class destructor
@@ -82,12 +84,45 @@ class SubscribeVehicleDataRequest : public CommandRequestImpl {
typedef std::vector<HmiRequest> HmiRequests;
HmiRequests hmi_requests_;
-#endif // #ifdef HMI_DBUS_API
+#endif // #ifdef HMI_DBUS_API
private:
- bool IsAnythingAlreadySubscribed(
+ /**
+ * @brief Checks, if any app is subscribed for particular VI parameter
+ * @param param_id VI parameter id
+ * @return true, if there are registered apps subscribed for VI parameter,
+ * otherwise - false
+ */
+ bool IsSomeoneSubscribedFor(const uint32_t param_id) const;
+
+ /**
+ * @brief Adds VI parameters being subscribed by another or the same app to
+ * response with appropriate results
+ * @param msg_params 'message_params' response section reference
+ */
+ void AddAlreadySubscribedVI(smart_objects::SmartObject& msg_params) const;
+
+ /**
+ * @brief Removes subscription for VI parameters which subsription attempt
+ * returned an error
+ * @param app Pointer to application sent subscribe request
+ * @param msg_params 'message_parameters' response section reference
+ */
+ void UnsubscribeFailedSubscriptions(
+ ApplicationSharedPtr app,
const smart_objects::SmartObject& msg_params) const;
+ /**
+ * @brief VI parameters which had been already subscribed by another apps
+ * befor particular app subscribed for these parameters
+ */
+ VehicleInfoSubscriptions vi_already_subscribed_by_another_apps_;
+
+ /**
+ * @brief VI parameters which had been subscribed already by particular app
+ */
+ VehicleInfoSubscriptions vi_already_subscribed_by_this_app_;
+
DISALLOW_COPY_AND_ASSIGN(SubscribeVehicleDataRequest);
};
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/subscribe_vehicle_data_response.h b/src/components/application_manager/include/application_manager/commands/mobile/subscribe_vehicle_data_response.h
index d2771c0712..7e3cffc387 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/subscribe_vehicle_data_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/subscribe_vehicle_data_response.h
@@ -51,7 +51,8 @@ class SubscribeVehicleDataResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit SubscribeVehicleDataResponse(const MessageSharedPtr& message);
+ SubscribeVehicleDataResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UnsubscribeVehicleDataCommandRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/subscribe_way_points_request.h b/src/components/application_manager/include/application_manager/commands/mobile/subscribe_way_points_request.h
new file mode 100644
index 0000000000..50b3a6f2cb
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/mobile/subscribe_way_points_request.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SUBSCRIBE_WAY_POINTS_REQUEST_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SUBSCRIBE_WAY_POINTS_REQUEST_H_
+
+#include "application_manager/commands/command_request_impl.h"
+
+namespace application_manager {
+
+namespace commands {
+
+/**
+ * @brief SubsribeWayPointsRequest command class
+ **/
+class SubscribeWayPointsRequest : public CommandRequestImpl {
+ public:
+ /**
+ * \brief SubscribeWayPointsRequest class constructor
+ **/
+ SubscribeWayPointsRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+
+ /**
+ * \brief SubscribeWayPointsRequest class destructor
+ **/
+ virtual ~SubscribeWayPointsRequest();
+
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run() OVERRIDE;
+ /**
+ * @brief Interface method that is called whenever new event received
+ *
+ * @param event The received event
+ */
+ virtual void on_event(const event_engine::Event& event);
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(SubscribeWayPointsRequest);
+};
+
+} // commands
+
+} // application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SUBSCRIBE_WAY_POINTS_REQUEST_H_
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/subscribe_way_points_response.h b/src/components/application_manager/include/application_manager/commands/mobile/subscribe_way_points_response.h
new file mode 100644
index 0000000000..cfdc0eede7
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/mobile/subscribe_way_points_response.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SUBSCRIBE_WAY_POINTS_RESPONSE_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SUBSCRIBE_WAY_POINTS_RESPONSE_H_
+
+#include "application_manager/commands/command_response_impl.h"
+#include "utils/macro.h"
+
+namespace application_manager {
+
+namespace commands {
+
+/**
+ * @brief SubscribeWayPointsResponse command class
+ **/
+class SubscribeWayPointsResponse : public CommandResponseImpl {
+ public:
+ /**
+ * \brief SubscribeWayPointsResponse class constructor
+ **/
+ SubscribeWayPointsResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+
+ /**
+ * \brief SubscribeWayPointsResponse class destructor
+ **/
+ virtual ~SubscribeWayPointsResponse();
+
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run() OVERRIDE;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(SubscribeWayPointsResponse);
+};
+
+} // commands
+
+} // application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_SUBSCRIBE_WAY_POINTS_RESPONSE_H_
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/system_request.h b/src/components/application_manager/include/application_manager/commands/mobile/system_request.h
index 25accb1db2..de87512e92 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/system_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/system_request.h
@@ -36,6 +36,9 @@
#include <string>
#include "application_manager/commands/command_request_impl.h"
+#include "application_manager/application_manager.h"
+#include "application_manager/event_engine/event.h"
+#include "smart_objects/smart_object.h"
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
@@ -57,7 +60,8 @@ class SystemRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit SystemRequest(const MessageSharedPtr& message);
+ SystemRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SystemRequest class destructor
@@ -76,17 +80,17 @@ class SystemRequest : public CommandRequestImpl {
*/
virtual void on_event(const event_engine::Event& event);
-private:
+ private:
/**
* @brief Validates data coming within QueryApps response
* @param data Data
* @return true, if data is valid, otherwise - false
*/
- bool ValidateQueryAppData(const smart_objects::SmartObject& data) const;
+ bool ValidateQueryAppData(smart_objects::SmartObject& data) const;
private:
static uint32_t index;
- std::string processing_file_;
+ std::string processing_file_;
DISALLOW_COPY_AND_ASSIGN(SystemRequest);
};
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/system_response.h b/src/components/application_manager/include/application_manager/commands/mobile/system_response.h
index ca2fb99970..3f48db7f0e 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/system_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/system_response.h
@@ -36,7 +36,6 @@
#include "application_manager/commands/command_response_impl.h"
-
namespace application_manager {
namespace commands {
@@ -51,7 +50,8 @@ class SystemResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit SystemResponse(const MessageSharedPtr& message);
+ SystemResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief SystemResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/unregister_app_interface_request.h b/src/components/application_manager/include/application_manager/commands/mobile/unregister_app_interface_request.h
index a5a53736e2..acc7374e18 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/unregister_app_interface_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/unregister_app_interface_request.h
@@ -49,15 +49,14 @@ class UnregisterAppInterfaceRequest : public CommandRequestImpl {
/**
* \brief UnregisterAppInterfaceRequest class constructor
**/
- explicit UnregisterAppInterfaceRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
- }
+ UnregisterAppInterfaceRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
/**
* \brief UnregisterAppInterfaceRequest class destructor
**/
- virtual ~UnregisterAppInterfaceRequest() {
- }
+ virtual ~UnregisterAppInterfaceRequest() {}
/**
* @brief Execute command
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/unregister_app_interface_response.h b/src/components/application_manager/include/application_manager/commands/mobile/unregister_app_interface_response.h
index 5c8928a6c8..1a459e109c 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/unregister_app_interface_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/unregister_app_interface_response.h
@@ -47,15 +47,14 @@ class UnregisterAppInterfaceResponse : public CommandResponseImpl {
/**
* \brief UnregisterAppInterfaceResponse class constructor
**/
- explicit UnregisterAppInterfaceResponse(const MessageSharedPtr& response)
- : CommandResponseImpl(response) {
- }
+ UnregisterAppInterfaceResponse(const MessageSharedPtr& response,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(response, application_manager) {}
/**
* \brief UnregisterAppInterfaceResponse class destructor
**/
- virtual ~UnregisterAppInterfaceResponse() {
- }
+ virtual ~UnregisterAppInterfaceResponse() {}
/**
* @brief Execute command
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_button_request.h b/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_button_request.h
index 58c9dc8de9..62600d51d7 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_button_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_button_request.h
@@ -51,7 +51,8 @@ class UnsubscribeButtonRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit UnsubscribeButtonRequest(const MessageSharedPtr& message);
+ UnsubscribeButtonRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UnsubscribeButtonRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_button_response.h b/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_button_response.h
index 972da48065..06dbe84578 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_button_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_button_response.h
@@ -51,7 +51,8 @@ class UnsubscribeButtonResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit UnsubscribeButtonResponse(const MessageSharedPtr& message);
+ UnsubscribeButtonResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UnsubscribeButtonResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_vehicle_data_request.h b/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_vehicle_data_request.h
index dd52a77224..a6bade2fd6 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_vehicle_data_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_vehicle_data_request.h
@@ -35,6 +35,7 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_UNSUBSCRIBE_VEHICLE_DATA_REQUEST_H_
#include "application_manager/commands/command_request_impl.h"
+#include "application_manager/application.h"
#include "utils/macro.h"
namespace application_manager {
@@ -51,7 +52,8 @@ class UnsubscribeVehicleDataRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit UnsubscribeVehicleDataRequest(const MessageSharedPtr& message);
+ UnsubscribeVehicleDataRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UnsubscribeVehicleDataRequest class destructor
@@ -82,11 +84,40 @@ class UnsubscribeVehicleDataRequest : public CommandRequestImpl {
typedef std::vector<HmiRequest> HmiRequests;
HmiRequests hmi_requests_;
-#endif // #ifdef HMI_DBUS_API
+#endif // #ifdef HMI_DBUS_API
private:
- bool IsAnythingAlreadyUnsubscribed(
- const smart_objects::SmartObject& msg_params) const;
+ /**
+ * @brief Checks, if any app is subscribed for particular VI parameter
+ * @param param_id VI parameter id
+ * @return true, if there are registered apps subscribed for VI parameter,
+ * otherwise - false
+ */
+ bool IsSomeoneSubscribedFor(const uint32_t param_id) const;
+
+ /**
+ * @brief Adds VI parameters being unsubscribed by another or the same app to
+ * response with appropriate results
+ * @param msg_params 'message_params' response section reference
+ */
+ void AddAlreadyUnsubscribedVI(smart_objects::SmartObject& response) const;
+
+ /**
+ * @brief Allows to update hash after sending response to mobile.
+ */
+ void UpdateHash() const;
+
+ /**
+ * @brief VI parameters which still being subscribed by another apps after
+ * particular app had been unsubscribed from these parameters
+ */
+ VehicleInfoSubscriptions vi_still_subscribed_by_another_apps_;
+
+ /**
+ * @brief VI parameters which had been unsubscribed already by particular app
+ */
+ VehicleInfoSubscriptions vi_already_unsubscribed_by_this_app_;
+
DISALLOW_COPY_AND_ASSIGN(UnsubscribeVehicleDataRequest);
};
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_vehicle_data_response.h b/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_vehicle_data_response.h
index 3fb932ecf3..a34a36688c 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_vehicle_data_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_vehicle_data_response.h
@@ -51,7 +51,8 @@ class UnsubscribeVehicleDataResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit UnsubscribeVehicleDataResponse(const MessageSharedPtr& message);
+ UnsubscribeVehicleDataResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UnsubscribeVehicleDataResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_way_points_request.h b/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_way_points_request.h
new file mode 100644
index 0000000000..2831551667
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_way_points_request.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_UNSUBSCRIBE_WAY_POINTS_REQUEST_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_UNSUBSCRIBE_WAY_POINTS_REQUEST_H_
+
+#include "application_manager/commands/command_request_impl.h"
+
+namespace application_manager {
+
+namespace commands {
+
+class UnSubscribeWayPointsRequest : public CommandRequestImpl {
+ public:
+ /**
+ * \brief UnSubscribeWayPointsRequest class constructor
+ **/
+ UnSubscribeWayPointsRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+
+ /**
+ * \brief UnSubscribeWayPointsRequest class destructor
+ **/
+ virtual ~UnSubscribeWayPointsRequest();
+
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run() OVERRIDE;
+ /**
+ * @brief Interface method that is called whenever new event received
+ *
+ * @param event The received event
+ */
+ virtual void on_event(const event_engine::Event& event);
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(UnSubscribeWayPointsRequest);
+};
+
+} // commands
+
+} // application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_UNSUBSCRIBE_WAY_POINTS_REQUEST_H_
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_way_points_response.h b/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_way_points_response.h
new file mode 100644
index 0000000000..70211330a9
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/commands/mobile/unsubscribe_way_points_response.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_UNSUBSCRIBE_WAY_POINTS_RESPONSE_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_UNSUBSCRIBE_WAY_POINTS_RESPONSE_H_
+
+#include "application_manager/commands/command_response_impl.h"
+#include "utils/macro.h"
+
+namespace application_manager {
+
+namespace commands {
+
+/**
+ * @brief UnsubscribeWayPointsResponse command class
+ **/
+class UnsubscribeWayPointsResponse : public CommandResponseImpl {
+ public:
+ /**
+ * \brief UnsubscribeWayPointsResponse class constructor
+ **/
+ UnsubscribeWayPointsResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
+
+ /**
+ * \brief UnsubscribeWayPointsResponse class destructor
+ **/
+ virtual ~UnsubscribeWayPointsResponse();
+
+ /**
+ * @brief Execute command
+ **/
+ virtual void Run() OVERRIDE;
+
+ private:
+ DISALLOW_COPY_AND_ASSIGN(UnsubscribeWayPointsResponse);
+};
+
+} // commands
+
+} // application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_MOBILE_UNSUBSCRIBE_WAY_POINTS_RESPONSE_H_
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/update_turn_list_request.h b/src/components/application_manager/include/application_manager/commands/mobile/update_turn_list_request.h
index c65c2bc534..e15e81caf5 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/update_turn_list_request.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/update_turn_list_request.h
@@ -52,7 +52,8 @@ class UpdateTurnListRequest : public CommandRequestImpl {
*
* @param message Incoming SmartObject message
**/
- explicit UpdateTurnListRequest(const MessageSharedPtr& message);
+ UpdateTurnListRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UpdateTurnListRequest class destructor
diff --git a/src/components/application_manager/include/application_manager/commands/mobile/update_turn_list_response.h b/src/components/application_manager/include/application_manager/commands/mobile/update_turn_list_response.h
index fdbf64826c..481ad9f219 100644
--- a/src/components/application_manager/include/application_manager/commands/mobile/update_turn_list_response.h
+++ b/src/components/application_manager/include/application_manager/commands/mobile/update_turn_list_response.h
@@ -51,7 +51,8 @@ class UpdateTurnListResponse : public CommandResponseImpl {
*
* @param message Incoming SmartObject message
**/
- explicit UpdateTurnListResponse(const MessageSharedPtr& message);
+ UpdateTurnListResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager);
/**
* @brief UpdateTurnListResponse class destructor
diff --git a/src/components/application_manager/include/application_manager/event_engine/event.h b/src/components/application_manager/include/application_manager/event_engine/event.h
index 55f5cd1320..4b8a4088bf 100644
--- a/src/components/application_manager/include/application_manager/event_engine/event.h
+++ b/src/components/application_manager/include/application_manager/event_engine/event.h
@@ -41,11 +41,12 @@
namespace application_manager {
namespace event_engine {
+class EventDispatcher;
+
namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
class Event {
public:
-
// Typedef for possible Event ID's from mobile_apis functionID enum
typedef hmi_apis::FunctionID::eType EventID;
@@ -65,7 +66,7 @@ class Event {
* @brief Sends synchronously event to all subscribers.
*
*/
- void raise();
+ void raise(EventDispatcher& event_dispatcher);
/*
* @brief Provides event ID
@@ -102,11 +103,9 @@ class Event {
inline int32_t smart_object_type() const;
protected:
-
private:
-
- EventID id_;
- smart_objects::SmartObject response_so_;
+ EventID id_;
+ smart_objects::SmartObject response_so_;
/*
* @brief Default constructor
@@ -127,21 +126,24 @@ const smart_objects::SmartObject& Event::smart_object() const {
}
int32_t Event::smart_object_function_id() const {
- return response_so_.getElement(
- strings::params).getElement(strings::function_id).asInt();
+ return response_so_.getElement(strings::params)
+ .getElement(strings::function_id)
+ .asInt();
}
int32_t Event::smart_object_correlation_id() const {
- return response_so_.getElement(
- strings::params).getElement(strings::correlation_id).asInt();
+ return response_so_.getElement(strings::params)
+ .getElement(strings::correlation_id)
+ .asInt();
}
int32_t Event::smart_object_type() const {
- return response_so_.getElement(
- strings::params).getElement(strings::message_type).asInt();
+ return response_so_.getElement(strings::params)
+ .getElement(strings::message_type)
+ .asInt();
}
-}
-}
+} // namespace event_engine
+} // namespace application_manager
#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_EVENT_H_
diff --git a/src/components/application_manager/include/application_manager/event_engine/event_dispatcher.h b/src/components/application_manager/include/application_manager/event_engine/event_dispatcher.h
index ff21b01c58..3d236b9c0f 100644
--- a/src/components/application_manager/include/application_manager/event_engine/event_dispatcher.h
+++ b/src/components/application_manager/include/application_manager/event_engine/event_dispatcher.h
@@ -1,5 +1,5 @@
/*
- Copyright (c) 2013, Ford Motor Company
+ Copyright (c) 2016, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -34,11 +34,6 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_EVENT_DISPATCHER_H_
#include <list>
-#include <map>
-
-#include "utils/lock.h"
-#include "utils/singleton.h"
-
#include "application_manager/event_engine/event.h"
namespace application_manager {
@@ -46,15 +41,14 @@ namespace event_engine {
class EventObserver;
-class EventDispatcher : public utils::Singleton<EventDispatcher> {
+class EventDispatcher {
public:
-
/*
* @brief Delivers the event to all subscribers
*
* @param event Received event
*/
- void raise_event(const Event& event);
+ virtual void raise_event(const Event& event) = 0;
/*
* @brief Subscribe the observer to event
@@ -63,9 +57,9 @@ class EventDispatcher : public utils::Singleton<EventDispatcher> {
* @param hmi_correlation_id The event HMI correlation ID
* @param observer The observer to subscribe for event
*/
- void add_observer(const Event::EventID& event_id,
- int32_t hmi_correlation_id,
- EventObserver* const observer);
+ virtual void add_observer(const Event::EventID& event_id,
+ int32_t hmi_correlation_id,
+ EventObserver& observer) = 0;
/*
* @brief Unsubscribes the observer from specific event
@@ -73,55 +67,23 @@ class EventDispatcher : public utils::Singleton<EventDispatcher> {
* @param event_id The event ID to unsubscribe from
* @param observer The observer to be unsubscribed
*/
- void remove_observer(const Event::EventID& event_id,
- EventObserver* const observer);
+ virtual void remove_observer(const Event::EventID& event_id,
+ EventObserver& observer) = 0;
/*
* @brief Unsubscribes the observer from all events
*
* @param observer The observer to be unsubscribed
*/
- void remove_observer(EventObserver* const observer);
-
- protected:
-
- private:
-
- /*
- * @brief Default constructor
- */
- EventDispatcher();
+ virtual void remove_observer(EventObserver& observer) = 0;
/*
* @brief Destructor
*/
- virtual ~EventDispatcher();
-
- /*
- * @brief removes observer
- * when occurs unsubscribe from event
- * @param observer to be removed
- */
- void remove_observer_from_list(EventObserver* const observer);
-
- DISALLOW_COPY_AND_ASSIGN(EventDispatcher);
-
- FRIEND_BASE_SINGLETON_CLASS(EventDispatcher);
-
- // Data types section
- typedef std::list<EventObserver*> ObserverList;
- typedef std::map<int32_t, ObserverList> ObserversMap;
- typedef std::map<Event::EventID, ObserversMap> EventObserverMap;
-
- // Members section
- sync_primitives::Lock state_lock_;
- sync_primitives::Lock observer_list_lock_;
- EventObserverMap observers_;
- ObserverList observers_list_;
-
+ virtual ~EventDispatcher(){};
};
-}
-}
+} // namespace event_engine
+} // namespace application_manager
#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_EVENT_DISPATCHER_H_
diff --git a/src/components/application_manager/include/application_manager/event_engine/event_dispatcher_impl.h b/src/components/application_manager/include/application_manager/event_engine/event_dispatcher_impl.h
new file mode 100644
index 0000000000..9a13ad608b
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/event_engine/event_dispatcher_impl.h
@@ -0,0 +1,129 @@
+/*
+ Copyright (c) 2016, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_EVENT_DISPATCHER_IMPL_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_EVENT_DISPATCHER_IMPL_H_
+
+#include <vector>
+#include <map>
+
+#include "utils/lock.h"
+
+#include "application_manager/event_engine/event.h"
+#include "application_manager/event_engine/event_dispatcher.h"
+
+namespace application_manager {
+namespace event_engine {
+
+class EventObserver;
+
+class EventDispatcherImpl : public EventDispatcher {
+ public:
+ // Data types section
+ typedef std::vector<EventObserver*> ObserverVector;
+ typedef std::map<int32_t, ObserverVector> ObserversMap;
+ typedef std::map<Event::EventID, ObserversMap> EventObserverMap;
+ /*
+ * @brief Destructor
+ */
+ virtual ~EventDispatcherImpl();
+
+ /*
+ * @brief Default constructor
+ */
+ EventDispatcherImpl();
+
+#ifdef BUILD_TESTS
+ EventObserverMap get_observers() const {
+ return observers_event_;
+ }
+ ObserverVector get_observers_list() const {
+ return observers_;
+ }
+#endif // BUILD_TESTS
+
+ /*
+ * @brief Delivers the event to all subscribers
+ *
+ * @param event Received event
+ */
+ void raise_event(const Event& event) OVERRIDE;
+
+ /*
+ * @brief Subscribe the observer to event
+ *
+ * @param event_id The event ID to subscribe for
+ * @param hmi_correlation_id The event HMI correlation ID
+ * @param observer The observer to subscribe for event
+ */
+ void add_observer(const Event::EventID& event_id,
+ int32_t hmi_correlation_id,
+ EventObserver& observer) OVERRIDE;
+
+ /*
+ * @brief Unsubscribes the observer from specific event
+ *
+ * @param event_id The event ID to unsubscribe from
+ * @param observer The observer to be unsubscribed
+ */
+ void remove_observer(const Event::EventID& event_id,
+ EventObserver& observer) OVERRIDE;
+
+ /*
+ * @brief Unsubscribes the observer from all events
+ *
+ * @param observer The observer to be unsubscribed
+ */
+ void remove_observer(EventObserver& observer) OVERRIDE;
+
+ private:
+ /*
+ * @brief removes observer
+ * when occurs unsubscribe from event
+ * @param observer to be removed
+ */
+ void remove_observer_from_vector(EventObserver& observer);
+
+ DISALLOW_COPY_AND_ASSIGN(EventDispatcherImpl);
+
+ private:
+ // Members section
+ sync_primitives::Lock state_lock_;
+ sync_primitives::Lock observer_lock_;
+ EventObserverMap observers_event_;
+ ObserverVector observers_;
+};
+
+} // namespace event_engine
+} // namespace application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_EVENT_DISPATCHER_IMPL_H_
diff --git a/src/components/application_manager/include/application_manager/event_engine/event_observer.h b/src/components/application_manager/include/application_manager/event_engine/event_observer.h
index 8631203290..3e910edfa9 100644
--- a/src/components/application_manager/include/application_manager/event_engine/event_observer.h
+++ b/src/components/application_manager/include/application_manager/event_engine/event_observer.h
@@ -1,5 +1,5 @@
/*
- Copyright (c) 2013, Ford Motor Company
+ Copyright (c) 2016, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -35,15 +35,13 @@
#include <string>
#include "application_manager/event_engine/event.h"
-#include "application_manager/event_engine/event_dispatcher.h"
namespace application_manager {
namespace event_engine {
-class EventObserver
-{
+class EventDispatcher;
+class EventObserver {
public:
-
friend class EventDispatcher;
// Typedef for possible Observer ID's from mobile_apis functionID enum
@@ -53,7 +51,7 @@ class EventObserver
* @brief Constructor
*
*/
- EventObserver();
+ EventObserver(EventDispatcher& event_dispatcher);
/*
* @brief Destructor
@@ -75,7 +73,6 @@ class EventObserver
virtual void on_event(const Event& event) = 0;
protected:
-
/*
* @brief Subscribe to an event
*
@@ -83,8 +80,8 @@ class EventObserver
* @param hmi_correlation_id The event HMI correlation ID.
* If param is omitted, it means subscription for HMI notification
*/
- void subscribe_on_event(
- const Event::EventID& event_id, int32_t hmi_correlation_id = 0);
+ void subscribe_on_event(const Event::EventID& event_id,
+ int32_t hmi_correlation_id = 0);
/*
* @brief Unsubscribes the observer from specific event
@@ -100,8 +97,8 @@ class EventObserver
void unsubscribe_from_all_events();
private:
-
ObserverID id_;
+ EventDispatcher& event_dispatcher_;
DISALLOW_COPY_AND_ASSIGN(EventObserver);
};
@@ -110,7 +107,7 @@ const EventObserver::ObserverID& EventObserver::id() const {
return id_;
}
-}
-}
+} // namespace event_engine
+} // namespace application_manager
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_EVENT_OBSERVER_H_
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_EVENT_OBSERVER_H_
diff --git a/src/components/application_manager/include/application_manager/hmi_capabilities.h b/src/components/application_manager/include/application_manager/hmi_capabilities.h
index 277455ff4e..f94c8125c8 100644
--- a/src/components/application_manager/include/application_manager/hmi_capabilities.h
+++ b/src/components/application_manager/include/application_manager/hmi_capabilities.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -28,7 +28,7 @@
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
- */
+*/
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_HMI_CAPABILITIES_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_HMI_CAPABILITIES_H_
@@ -37,28 +37,30 @@
#include "interfaces/MOBILE_API.h"
#include "json/json.h"
#include "utils/macro.h"
+#include "application_manager/hmi_language_handler.h"
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
class SmartObject;
}
}
+namespace resumption {
+class LastState;
+}
namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
namespace application_manager {
-class ApplicationManagerImpl;
+class ApplicationManager;
class HMICapabilities {
-
public:
-
/*
* @ Class constructor
*
* @param app_mngr Application manager pointer
*/
- explicit HMICapabilities(ApplicationManagerImpl* const app_mngr);
+ explicit HMICapabilities(ApplicationManager& app_mngr);
/*
* @brief Class destructor
@@ -121,8 +123,7 @@ class HMICapabilities {
*
* @return Currently active UI language
*/
- inline const hmi_apis::Common_Language::eType&
- active_ui_language() const;
+ const hmi_apis::Common_Language::eType active_ui_language() const;
/*
* @brief Sets currently active UI language
@@ -136,8 +137,7 @@ class HMICapabilities {
*
* @return Currently supported UI languages
*/
- inline const smart_objects::SmartObject*
- ui_supported_languages() const;
+ inline const smart_objects::SmartObject* ui_supported_languages() const;
/*
* @brief Sets supported UI languages
@@ -152,8 +152,7 @@ class HMICapabilities {
*
* @return Currently active VR language
*/
- inline const hmi_apis::Common_Language::eType&
- active_vr_language() const;
+ const hmi_apis::Common_Language::eType active_vr_language() const;
/*
* @brief Sets currently active VR language
@@ -167,8 +166,7 @@ class HMICapabilities {
*
* @return Currently supported VR languages
*/
- inline const smart_objects::SmartObject*
- vr_supported_languages() const;
+ inline const smart_objects::SmartObject* vr_supported_languages() const;
/*
* @brief Sets supported VR languages
@@ -183,8 +181,7 @@ class HMICapabilities {
*
* @return Currently active TTS language
*/
- inline const hmi_apis::Common_Language::eType&
- active_tts_language() const;
+ const hmi_apis::Common_Language::eType active_tts_language() const;
/*
* @brief Sets currently active TTS language
@@ -192,15 +189,14 @@ class HMICapabilities {
* @param language Currently active TTS language
*/
void set_active_tts_language(
- const hmi_apis::Common_Language::eType& language);
+ const hmi_apis::Common_Language::eType& language);
/*
* @brief Retrieves TTS supported languages
*
* @return Currently supported TTS languages
*/
- inline const smart_objects::SmartObject*
- tts_supported_languages() const;
+ inline const smart_objects::SmartObject* tts_supported_languages() const;
/*
* @brief Sets supported TTS languages
@@ -215,8 +211,7 @@ class HMICapabilities {
*
* @return Currently supported display capabilities
*/
- inline const smart_objects::SmartObject*
- display_capabilities() const;
+ inline const smart_objects::SmartObject* display_capabilities() const;
/*
* @brief Sets supported display capabilities
@@ -231,8 +226,7 @@ class HMICapabilities {
*
* @return Currently supported HMI zone capabilities
*/
- inline const smart_objects::SmartObject*
- hmi_zone_capabilities() const;
+ inline const smart_objects::SmartObject* hmi_zone_capabilities() const;
/*
* @brief Sets supported HMI zone capabilities
@@ -247,8 +241,7 @@ class HMICapabilities {
*
* @return Currently supported SoftButton's capabilities
*/
- inline const smart_objects::SmartObject*
- soft_button_capabilities() const;
+ inline const smart_objects::SmartObject* soft_button_capabilities() const;
/*
* @brief Sets supported SoftButton's capabilities
@@ -311,12 +304,26 @@ class HMICapabilities {
const smart_objects::SmartObject& audio_pass_thru_capabilities);
/*
+ * @brief Sets supported pcm_stream capabilities
+ *
+ * @param supported pcm stream capabilities
+ */
+ void set_pcm_stream_capabilities(
+ const smart_objects::SmartObject& pcm_stream_capabilities);
+
+ /*
* @brief Retrieves information about the audio_pass_thru capabilities
*
* @return Currently supported audio_pass_thru capabilities
*/
- inline const smart_objects::SmartObject*
- audio_pass_thru_capabilities() const;
+ inline const smart_objects::SmartObject* audio_pass_thru_capabilities() const;
+
+ /*
+ * @brief Retrieves information about the pcm_stream capabilities
+ *
+ * @return Currently supported pcm_streaming capabilities
+ */
+ inline const smart_objects::SmartObject* pcm_stream_capabilities() const;
/*
* @brief Retrieves information about the preset bank capabilities
@@ -360,7 +367,7 @@ class HMICapabilities {
* @param prerecorded_speech supported prerecorded speech
*/
void set_prerecorded_speech(
- const smart_objects::SmartObject& prerecorded_speech);
+ const smart_objects::SmartObject& prerecorded_speech);
/*
* @brief Interface used to store information if navigation
@@ -393,7 +400,8 @@ class HMICapabilities {
inline bool phone_call_supported() const;
/*
- * @brief Interface used to store information about software version of the target
+ * @brief Interface used to store information about software version of the
+ *target
*
* @param ccpu_version Received system/hmi software version
*/
@@ -406,8 +414,18 @@ class HMICapabilities {
*/
inline const std::string& ccpu_version() const;
- protected:
+ void Init(resumption::LastState* last_state);
+ /**
+ * @brief return component which follows for correctness of
+ * languages
+ * @return HMI language handler
+ */
+ HMILanguageHandler& get_hmi_language_handler() {
+ return hmi_language_handler_;
+ }
+
+ protected:
/*
* @brief Loads capabilities from local file in case SDL was launched
* without HMI
@@ -426,8 +444,8 @@ class HMICapabilities {
* @returns TRUE if member exists and returns FALSE if
* member does not exist.
*/
- bool check_existing_json_member(
- const Json::Value& json_member, const char* name_of_member);
+ bool check_existing_json_member(const Json::Value& json_member,
+ const char* name_of_member);
/*
* @brief function converts json object "languages" to smart object
@@ -440,41 +458,43 @@ class HMICapabilities {
smart_objects::SmartObject& languages);
private:
- bool is_vr_cooperating_;
- bool is_tts_cooperating_;
- bool is_ui_cooperating_;
- bool is_navi_cooperating_;
- bool is_ivi_cooperating_;
+ bool is_vr_cooperating_;
+ bool is_tts_cooperating_;
+ bool is_ui_cooperating_;
+ bool is_navi_cooperating_;
+ bool is_ivi_cooperating_;
// to check if IsReady response for corresponding interface received
- bool is_vr_ready_response_recieved_;
- bool is_tts_ready_response_recieved_;
- bool is_ui_ready_response_recieved_;
- bool is_navi_ready_response_recieved_;
- bool is_ivi_ready_response_recieved_;
+ bool is_vr_ready_response_recieved_;
+ bool is_tts_ready_response_recieved_;
+ bool is_ui_ready_response_recieved_;
+ bool is_navi_ready_response_recieved_;
+ bool is_ivi_ready_response_recieved_;
- bool attenuated_supported_;
+ bool attenuated_supported_;
hmi_apis::Common_Language::eType ui_language_;
hmi_apis::Common_Language::eType vr_language_;
hmi_apis::Common_Language::eType tts_language_;
- smart_objects::SmartObject* vehicle_type_;
- smart_objects::SmartObject* ui_supported_languages_;
- smart_objects::SmartObject* tts_supported_languages_;
- smart_objects::SmartObject* vr_supported_languages_;
- smart_objects::SmartObject* display_capabilities_;
- smart_objects::SmartObject* hmi_zone_capabilities_;
- smart_objects::SmartObject* soft_buttons_capabilities_;
- smart_objects::SmartObject* button_capabilities_;
- smart_objects::SmartObject* preset_bank_capabilities_;
- smart_objects::SmartObject* vr_capabilities_;
- smart_objects::SmartObject* speech_capabilities_;
- smart_objects::SmartObject* audio_pass_thru_capabilities_;
- smart_objects::SmartObject* prerecorded_speech_;
- bool is_navigation_supported_;
- bool is_phone_call_supported_;
- std::string ccpu_version_;
-
- ApplicationManagerImpl* app_mngr_;
+ smart_objects::SmartObject* vehicle_type_;
+ smart_objects::SmartObject* ui_supported_languages_;
+ smart_objects::SmartObject* tts_supported_languages_;
+ smart_objects::SmartObject* vr_supported_languages_;
+ smart_objects::SmartObject* display_capabilities_;
+ smart_objects::SmartObject* hmi_zone_capabilities_;
+ smart_objects::SmartObject* soft_buttons_capabilities_;
+ smart_objects::SmartObject* button_capabilities_;
+ smart_objects::SmartObject* preset_bank_capabilities_;
+ smart_objects::SmartObject* vr_capabilities_;
+ smart_objects::SmartObject* speech_capabilities_;
+ smart_objects::SmartObject* audio_pass_thru_capabilities_;
+ smart_objects::SmartObject* pcm_stream_capabilities_;
+ smart_objects::SmartObject* prerecorded_speech_;
+ std::string ccpu_version_;
+ bool is_navigation_supported_;
+ bool is_phone_call_supported_;
+
+ ApplicationManager& app_mngr_;
+ HMILanguageHandler hmi_language_handler_;
DISALLOW_COPY_AND_ASSIGN(HMICapabilities);
};
@@ -499,48 +519,33 @@ bool HMICapabilities::is_ivi_cooperating() const {
return is_ivi_cooperating_;
}
-const hmi_apis::Common_Language::eType&
-HMICapabilities::active_ui_language() const {
- return ui_language_;
-}
-
-const smart_objects::SmartObject*
-HMICapabilities::ui_supported_languages() const {
+const smart_objects::SmartObject* HMICapabilities::ui_supported_languages()
+ const {
return ui_supported_languages_;
}
-const hmi_apis::Common_Language::eType&
-HMICapabilities::active_vr_language() const {
- return vr_language_;
-}
-
-const smart_objects::SmartObject*
-HMICapabilities::vr_supported_languages() const {
+const smart_objects::SmartObject* HMICapabilities::vr_supported_languages()
+ const {
return vr_supported_languages_;
}
-const hmi_apis::Common_Language::eType&
-HMICapabilities::active_tts_language() const {
- return tts_language_;
-}
-
-const smart_objects::SmartObject*
-HMICapabilities::tts_supported_languages() const {
+const smart_objects::SmartObject* HMICapabilities::tts_supported_languages()
+ const {
return tts_supported_languages_;
}
-const smart_objects::SmartObject*
-HMICapabilities::display_capabilities() const {
+const smart_objects::SmartObject* HMICapabilities::display_capabilities()
+ const {
return display_capabilities_;
}
-const smart_objects::SmartObject*
-HMICapabilities::hmi_zone_capabilities() const {
+const smart_objects::SmartObject* HMICapabilities::hmi_zone_capabilities()
+ const {
return hmi_zone_capabilities_;
}
-const smart_objects::SmartObject*
-HMICapabilities::soft_button_capabilities() const {
+const smart_objects::SmartObject* HMICapabilities::soft_button_capabilities()
+ const {
return soft_buttons_capabilities_;
}
@@ -548,8 +553,7 @@ const smart_objects::SmartObject* HMICapabilities::button_capabilities() const {
return button_capabilities_;
}
-const smart_objects::SmartObject*
-HMICapabilities::speech_capabilities() const {
+const smart_objects::SmartObject* HMICapabilities::speech_capabilities() const {
return speech_capabilities_;
}
@@ -562,8 +566,13 @@ HMICapabilities::audio_pass_thru_capabilities() const {
return audio_pass_thru_capabilities_;
}
-const smart_objects::SmartObject*
-HMICapabilities::preset_bank_capabilities() const {
+const smart_objects::SmartObject* HMICapabilities::pcm_stream_capabilities()
+ const {
+ return pcm_stream_capabilities_;
+}
+
+const smart_objects::SmartObject* HMICapabilities::preset_bank_capabilities()
+ const {
return preset_bank_capabilities_;
}
@@ -575,11 +584,14 @@ const smart_objects::SmartObject* HMICapabilities::vehicle_type() const {
return vehicle_type_;
}
-const smart_objects::SmartObject*
-HMICapabilities::prerecorded_speech() const {
+const smart_objects::SmartObject* HMICapabilities::prerecorded_speech() const {
return prerecorded_speech_;
}
+const std::string& HMICapabilities::ccpu_version() const {
+ return ccpu_version_;
+}
+
bool HMICapabilities::navigation_supported() const {
return is_navigation_supported_;
}
@@ -588,10 +600,6 @@ bool HMICapabilities::phone_call_supported() const {
return is_phone_call_supported_;
}
-const std::string& HMICapabilities::ccpu_version() const {
- return ccpu_version_;
-}
-
} // namespace application_manager
#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_HMI_CAPABILITIES_H_
diff --git a/src/components/application_manager/include/application_manager/hmi_command_factory.h b/src/components/application_manager/include/application_manager/hmi_command_factory.h
index 89936e4ca6..6603563c6d 100644
--- a/src/components/application_manager/include/application_manager/hmi_command_factory.h
+++ b/src/components/application_manager/include/application_manager/hmi_command_factory.h
@@ -37,9 +37,8 @@
#include "utils/macro.h"
namespace application_manager {
-
typedef utils::SharedPtr<commands::Command> CommandSharedPtr;
-
+class ApplicationManager;
/**
* @brief Factory class for command creation
**/
@@ -51,7 +50,9 @@ class HMICommandFactory {
* @param smartObject SmartObject shared pointer.
* @return Pointer to created command object.
**/
- static CommandSharedPtr CreateCommand(const commands::MessageSharedPtr& message);
+ static CommandSharedPtr CreateCommand(
+ const commands::MessageSharedPtr& message,
+ ApplicationManager& application_manager);
private:
HMICommandFactory();
diff --git a/src/components/application_manager/include/application_manager/hmi_language_handler.h b/src/components/application_manager/include/application_manager/hmi_language_handler.h
new file mode 100644
index 0000000000..e8af02c189
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/hmi_language_handler.h
@@ -0,0 +1,187 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_HMI_LANGUAGE_HANDLER_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_HMI_LANGUAGE_HANDLER_H_
+
+#include "application_manager/event_engine/event_observer.h"
+#include "utils/lock.h"
+#include "interfaces/HMI_API.h"
+namespace resumption {
+class LastState;
+}
+namespace application_manager {
+
+class ApplicationManager;
+/**
+ * Class is used to handle edge case with slow HMI responses for current
+ * languages. Main idea is to cache values within some persistent storage and
+ * respond to applications with these values. In case app registered before
+ * responses are gotten and after responses were received their language(s)
+ * mismatch to current on HMI - apps have to be unregistered.
+ **/
+class HMILanguageHandler : public event_engine::EventObserver {
+ public:
+ typedef std::map<uint32_t, bool> Apps;
+
+ /**
+ * @brief System interfaces
+ */
+ enum Interface { INTERFACE_UI, INTERFACE_VR, INTERFACE_TTS };
+
+ /**
+ * @brief Class constructor
+ */
+ HMILanguageHandler(ApplicationManager& application_manager);
+
+ /**
+ * @brief Sets language for interface
+ * @param interface Interface
+ * @param language Language
+ */
+ void set_language_for(Interface interface,
+ hmi_apis::Common_Language::eType language);
+
+ /**
+ * @brief Gets language for interface
+ * @param interface Interface
+ * @return Language
+ */
+ hmi_apis::Common_Language::eType get_language_for(Interface interface) const;
+
+ void on_event(const event_engine::Event& event) OVERRIDE;
+
+ /**
+ * @brief Trigger waiting for response
+ * @param request Request object
+ */
+ void set_handle_response_for(
+ const event_engine::smart_objects::SmartObject& request);
+
+ /**
+ * @brief Sets default languages from HMI capabilities
+ * @param ui UI language
+ * @param vr VR language
+ * @param tts TTS language
+ */
+ void set_default_capabilities_languages(hmi_apis::Common_Language::eType ui,
+ hmi_apis::Common_Language::eType vr,
+ hmi_apis::Common_Language::eType tts);
+ void Init(resumption::LastState* value);
+
+ /**
+ * @brief Removes application from container after
+ * removing application from core
+ * @param app_id id application for removing
+ */
+ void OnUnregisterApplication(uint32_t app_id);
+
+ private:
+ void SendOnLanguageChangeToMobile(uint32_t connection_key);
+
+ /**
+ * @brief Verifies languages gotten from HMI with persisted languages
+ */
+ void VerifyWithPersistedLanguages();
+
+ /**
+ * @brief Handles applications registered before actual HMI languages
+ * have been received
+ * @param app_id Application id
+ */
+ void HandleWrongLanguageApp(const Apps::value_type& app_id);
+
+ /**
+ * @brief Checks if application needs to be handled because of language(s)
+ * mismatch
+ * @param app Application
+ */
+ void CheckApplication(const Apps::value_type app);
+
+ sync_primitives::Lock apps_lock_;
+
+ /**
+ * @brief Applications, which needs to be handled
+ */
+ Apps apps_;
+
+ /**
+ * @brief UI language persisted from previous ignition cycle
+ */
+ hmi_apis::Common_Language::eType persisted_ui_language_;
+
+ /**
+ * @brief VR language persisted from previous ignition cycle
+ */
+ hmi_apis::Common_Language::eType persisted_vr_language_;
+
+ /**
+ * @brief TTS language persisted from previous ignition cycle
+ */
+ hmi_apis::Common_Language::eType persisted_tts_language_;
+
+ /**
+ * @brief Default UI language from HMI capabilitites
+ */
+ hmi_apis::Common_Language::eType capabilities_ui_language_;
+
+ /**
+ * @brief Default VR language from HMI capabilitites
+ */
+ hmi_apis::Common_Language::eType capabilities_vr_language_;
+
+ /**
+ * @brief Default TTS language from HMI capabilitites
+ */
+ hmi_apis::Common_Language::eType capabilities_tts_language_;
+
+ /**
+ * @brief Indicates if current UI language has been received from HMI
+ */
+ bool is_ui_language_received_;
+
+ /**
+ * @brief Indicates if current VR language has been received from HMI
+ */
+ bool is_vr_language_received_;
+
+ /**
+ * @brief Indicates if current TTS language has been received from HMI
+ */
+ bool is_tts_language_received_;
+ resumption::LastState* last_state_;
+ ApplicationManager& application_manager_;
+};
+
+} // namespace application_manager
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_HMI_LANGUAGE_HANDLER_H_
diff --git a/src/components/application_manager/include/application_manager/hmi_state.h b/src/components/application_manager/include/application_manager/hmi_state.h
index 4451fb6857..31da7647fa 100644
--- a/src/components/application_manager/include/application_manager/hmi_state.h
+++ b/src/components/application_manager/include/application_manager/hmi_state.h
@@ -1,186 +1,304 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_HMISTATE_H
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_HMISTATE_H
#include <list>
#include "interfaces/MOBILE_API.h"
#include "utils/shared_ptr.h"
-#include "application_manager/state_context.h"
namespace application_manager {
class HmiState;
+class ApplicationManager;
+
typedef utils::SharedPtr<HmiState> HmiStatePtr;
-typedef std::list<HmiStatePtr> HmiStateList;
- /**
- * @brief The HmiState class
- * Handle Hmi state of application (hmi level,
- * audio streaming state, system context)
- *
- */
+/**
+* @brief The HmiState class
+* Handle Hmi state of application (hmi level,
+* audio streaming state, system context)
+*
+*/
class HmiState {
+ public:
+ /**
+ * @brief The StateID enum describes state of application
+ * If no events occured STATE_ID_DEFAULT shuld be presented
+ */
+ enum StateID {
+ STATE_ID_CURRENT,
+ STATE_ID_REGULAR,
+ STATE_ID_POSTPONED,
+ STATE_ID_PHONE_CALL,
+ STATE_ID_SAFETY_MODE,
+ STATE_ID_VR_SESSION,
+ STATE_ID_TTS_SESSION,
+ STATE_ID_NAVI_STREAMING,
+ STATE_ID_DEACTIVATE_HMI,
+ STATE_ID_AUDIO_SOURCE,
+ STATE_ID_EMBEDDED_NAVI
+ };
- public:
- /**
- * @brief The StateID enum describes state of application
- * If no events occured STATE_ID_DEFAULT shuld be presented
- */
- enum StateID {
- STATE_ID_REGULAR,
- STATE_ID_PHONE_CALL,
- STATE_ID_SAFETY_MODE,
- STATE_ID_VR_SESSION,
- STATE_ID_TTS_SESSION,
- STATE_ID_NAVI_STREAMING,
- };
-
- HmiState(uint32_t app_id, const StateContext& state_context_);
- HmiState(uint32_t app_id, const StateContext& state_context_,
- StateID state_id);
-
-
- virtual ~HmiState() {}
-
- /**
- * @brief setParent setup parent state
- * @param parent state to setup
- */
- void set_parent(HmiStatePtr parent);
-
- /**
- * @brief parent get parent state
- * @return parent state
- */
- const HmiStatePtr parent() const {
- return parent_;
- }
+ HmiState(uint32_t app_id, const ApplicationManager& app_mngr);
+ HmiState(uint32_t app_id,
+ const ApplicationManager& app_mngr,
+ StateID state_id);
- /**
- * @brief hmi_level
- * @return return hmi level member
- */
- virtual mobile_apis::HMILevel::eType hmi_level() const {
- if (parent_) {
- return parent_->hmi_level();
- }
- return hmi_level_;
- }
- /**
- * @brief set_hmi_level set hmi_level member
- * @param hmi_level hmi level to setup
- */
- void set_hmi_level(mobile_apis::HMILevel::eType hmi_level) {
- hmi_level_ = hmi_level;
- }
+ virtual ~HmiState() {}
- /**
- * @brief audio_streaming_state
- * @return return audio streaming state member
- */
- virtual mobile_apis::AudioStreamingState::eType
- audio_streaming_state() const {
- if (parent_) {
- return parent_->audio_streaming_state();
- }
- return audio_streaming_state_;
- }
- /**
- * @brief set_audio_streaming_state set audio_streaming_state member
- * @param audio_state audio_state to setup
- */
- virtual void set_audio_streaming_state(
- mobile_apis::AudioStreamingState::eType audio_state) {
- audio_streaming_state_ = audio_state;
- }
+ /**
+ * @brief setParent setup parent state
+ * @param parent state to setup
+ */
+ void set_parent(HmiStatePtr parent);
+
+ /**
+ * @brief parent get parent state
+ * @return parent state
+ */
+ const HmiStatePtr parent() const {
+ return parent_;
+ }
- /**
- * @brief system_context
- * @return return system context member
- */
- virtual mobile_apis::SystemContext::eType system_context() const {
- if (parent_) {
- return parent_->system_context();
- }
- return system_context_;
+ /**
+ * @brief hmi_level
+ * @return return hmi level member
+ */
+ virtual mobile_apis::HMILevel::eType hmi_level() const {
+ if (parent_) {
+ return parent_->hmi_level();
}
+ return hmi_level_;
+ }
+ /**
+ * @brief set_hmi_level set hmi_level member
+ * @param hmi_level hmi level to setup
+ */
+ void set_hmi_level(mobile_apis::HMILevel::eType hmi_level) {
+ hmi_level_ = hmi_level;
+ }
- /**
- * @brief set_system_context set system_context member
- * @param system_context system_context to setup
- */
- virtual void set_system_context(
- mobile_apis::SystemContext::eType system_context){
- system_context_ = system_context;
+ /**
+ * @brief audio_streaming_state
+ * @return return audio streaming state member
+ */
+ virtual mobile_apis::AudioStreamingState::eType audio_streaming_state()
+ const {
+ if (parent_) {
+ return parent_->audio_streaming_state();
}
+ return audio_streaming_state_;
+ }
+ /**
+ * @brief set_audio_streaming_state set audio_streaming_state member
+ * @param audio_state audio_state to setup
+ */
+ virtual void set_audio_streaming_state(
+ mobile_apis::AudioStreamingState::eType audio_state) {
+ audio_streaming_state_ = audio_state;
+ }
- /**
- * @brief state_id state type
- * @return reutrn state type
- */
- StateID state_id() const {
- return state_id_;
+ /**
+ * @brief system_context
+ * @return return system context member
+ */
+ virtual mobile_apis::SystemContext::eType system_context() const {
+ if (parent_) {
+ return parent_->system_context();
}
- protected:
- uint32_t app_id_;
- StateID state_id_;
- const StateContext& state_context_;
- HmiStatePtr parent_;
- mobile_apis::HMILevel::eType hmi_level_;
- mobile_apis::AudioStreamingState::eType audio_streaming_state_;
- mobile_apis::SystemContext::eType system_context_;
- private:
- void operator=(const HmiState&);
+ return system_context_;
+ }
+
+ /**
+ * @brief set_system_context set system_context member
+ * @param system_context system_context to setup
+ */
+ virtual void set_system_context(
+ mobile_apis::SystemContext::eType system_context) {
+ system_context_ = system_context;
+ }
+
+ /**
+ * @brief state_id state type
+ * @return return state type
+ */
+ StateID state_id() const {
+ return state_id_;
+ }
+
+ /**
+ * @brief set_state_id sets state id
+ * @param state_id state id to setup
+ */
+ virtual void set_state_id(StateID state_id) {
+ state_id_ = state_id;
+ }
+
+ protected:
+ uint32_t app_id_;
+ StateID state_id_;
+ const ApplicationManager& app_mngr_;
+ HmiStatePtr parent_;
+ mobile_apis::HMILevel::eType hmi_level_;
+ mobile_apis::AudioStreamingState::eType audio_streaming_state_;
+ mobile_apis::SystemContext::eType system_context_;
+
+ protected:
+ /**
+ * @brief is_navi_app check if app is navi
+ * @param app_id application id
+ * @return true if app is navi, otherwise return false
+ */
+ bool is_navi_app(const uint32_t app_id) const;
+
+ /**
+ * @brief is_media_app check if app is media
+ * @param app_id application id
+ * @return true if media_app, otherwise return false
+ */
+ bool is_media_app(const uint32_t app_id) const;
+
+ /**
+ * @brief is_voice_communicationn_app check if app is voice comunication
+ * @param app_id application id
+ * @return true if voice_communicationn_app, otherwise return false
+ */
+ bool is_voice_communication_app(const uint32_t app_id) const;
+
+ private:
+ void operator=(const HmiState&);
};
/**
- * @brief The VRHmiState class impement logic of VR temporary state
+ * @brief The VRHmiState class implements logic of VR temporary state
*/
class VRHmiState : public HmiState {
- public:
- virtual mobile_apis::AudioStreamingState::eType audio_streaming_state() const;
- VRHmiState(uint32_t app_id, StateContext& state_context);
+ public:
+ virtual mobile_apis::AudioStreamingState::eType audio_streaming_state()
+ const OVERRIDE;
+ VRHmiState(uint32_t app_id, const ApplicationManager& app_mngr);
};
/**
- * @brief The TTSHmiState class impement logic of TTS temporary state
+ * @brief The TTSHmiState class implements logic of TTS temporary state
*/
class TTSHmiState : public HmiState {
- public:
- TTSHmiState(uint32_t app_id, StateContext& state_context);
- virtual mobile_apis::AudioStreamingState::eType audio_streaming_state() const;
+ public:
+ TTSHmiState(uint32_t app_id, const ApplicationManager& app_mngr);
+ virtual mobile_apis::AudioStreamingState::eType audio_streaming_state()
+ const OVERRIDE;
};
/**
- * @brief The NaviStreamingState class impement logic of NaviStreaming temporary state
+ * @brief The NaviStreamingState class implements logic of NaviStreaming
+ * temporary state
*/
class NaviStreamingHmiState : public HmiState {
- public:
- NaviStreamingHmiState(uint32_t app_id, StateContext& state_context);
- virtual mobile_apis::AudioStreamingState::eType audio_streaming_state() const;
+ public:
+ NaviStreamingHmiState(uint32_t app_id, const ApplicationManager& app_mngr);
+ mobile_apis::AudioStreamingState::eType audio_streaming_state()
+ const OVERRIDE;
};
/**
- * @brief The PhoneCallHmiState class impement logic of PhoneCall temporary state
+ * @brief The PhoneCallHmiState class implements logic of PhoneCall temporary
+ * state
*/
class PhoneCallHmiState : public HmiState {
- public:
- PhoneCallHmiState(uint32_t app_id, StateContext& state_context);
- virtual mobile_apis::HMILevel::eType hmi_level() const;
- virtual mobile_apis::AudioStreamingState::eType audio_streaming_state() const {
- return mobile_apis::AudioStreamingState::NOT_AUDIBLE;
- }
+ public:
+ PhoneCallHmiState(uint32_t app_id, const ApplicationManager& app_mngr);
+ mobile_apis::HMILevel::eType hmi_level() const OVERRIDE;
+ mobile_apis::AudioStreamingState::eType audio_streaming_state()
+ const OVERRIDE {
+ return mobile_apis::AudioStreamingState::NOT_AUDIBLE;
+ }
};
/**
- * @brief The SafetyModeHmiState class impement logic of SafetyMode temporary state
+ * @brief The SafetyModeHmiState class implements logic of SafetyMode temporary
+ * state
*/
class SafetyModeHmiState : public HmiState {
- public:
- SafetyModeHmiState(uint32_t app_id, StateContext& state_context);
- virtual mobile_apis::AudioStreamingState::eType audio_streaming_state() const {
- return mobile_apis::AudioStreamingState::NOT_AUDIBLE;
- }
+ public:
+ SafetyModeHmiState(uint32_t app_id, const ApplicationManager& app_mngr);
+ mobile_apis::AudioStreamingState::eType audio_streaming_state()
+ const OVERRIDE {
+ return mobile_apis::AudioStreamingState::NOT_AUDIBLE;
+ }
};
+/**
+ * @brief The DeactivateHMI class implements logic of DeactivateHMI temporary
+ * state
+ */
+class DeactivateHMI : public HmiState {
+ public:
+ DeactivateHMI(uint32_t app_id, const ApplicationManager& app_mngr);
+ mobile_apis::HMILevel::eType hmi_level() const OVERRIDE;
+ mobile_apis::AudioStreamingState::eType audio_streaming_state()
+ const OVERRIDE {
+ return mobile_apis::AudioStreamingState::NOT_AUDIBLE;
+ }
+};
+
+/**
+ * @brief The AudioSource class implements logic of OnEventChanged(AUDIO_SOURCE)
+ * temporary state
+ */
+class AudioSource : public HmiState {
+ public:
+ AudioSource(uint32_t app_id, const ApplicationManager& app_mngr);
+ mobile_apis::HMILevel::eType hmi_level() const OVERRIDE;
+ mobile_apis::AudioStreamingState::eType audio_streaming_state()
+ const OVERRIDE {
+ return mobile_apis::AudioStreamingState::NOT_AUDIBLE;
+ }
+};
+
+/**
+ * @brief The EmbeddedNavi class implements logic of
+ * OnEventChanged(EMBEDDED_NAVI)
+ * temporary state
+ */
+class EmbeddedNavi : public HmiState {
+ public:
+ EmbeddedNavi(uint32_t app_id, const ApplicationManager& app_mngr);
+ mobile_apis::HMILevel::eType hmi_level() const OVERRIDE;
+ mobile_apis::AudioStreamingState::eType audio_streaming_state()
+ const OVERRIDE {
+ return mobile_apis::AudioStreamingState::NOT_AUDIBLE;
+ }
+};
}
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_HMISTATE_H
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_HMISTATE_H
diff --git a/src/components/application_manager/include/application_manager/message.h b/src/components/application_manager/include/application_manager/message.h
index 5a2c8bdc18..521e0baca5 100644
--- a/src/components/application_manager/include/application_manager/message.h
+++ b/src/components/application_manager/include/application_manager/message.h
@@ -53,7 +53,7 @@ enum MessageType {
kRequest = 0,
kResponse = 1,
kNotification = 2,
- kErrorResponse = 3 // Error Response HMI ONLY
+ kErrorResponse = 3 // Error Response HMI ONLY
};
// Map PrcType to corresponding MessageType
@@ -103,12 +103,14 @@ class Message {
void set_data_size(size_t data_size);
void set_payload_size(size_t payload_size);
- protocol_handler::MessagePriority Priority() const { return priority_; }
+ protocol_handler::MessagePriority Priority() const {
+ return priority_;
+ }
private:
- int32_t function_id_; // @remark protocol V2.
+ int32_t function_id_; // @remark protocol V2.
int32_t correlation_id_; // @remark protocol V2.
- MessageType type_; // @remark protocol V2.
+ MessageType type_; // @remark protocol V2.
// Pre-calculated message priority, higher priority messages are
// Processed first
diff --git a/src/components/application_manager/include/application_manager/message_helper.h b/src/components/application_manager/include/application_manager/message_helper.h
index cfd3d4c72f..ab89883ad2 100644
--- a/src/components/application_manager/include/application_manager/message_helper.h
+++ b/src/components/application_manager/include/application_manager/message_helper.h
@@ -1,5 +1,5 @@
/*
- Copyright (c) 2013, Ford Motor Company
+ Copyright (c) 2015, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -34,8 +34,9 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_MESSAGE_HELPER_H_
#include <map>
+#include <vector>
#include <string>
-#include <string.h>
+
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
#include "utils/macro.h"
@@ -43,6 +44,8 @@
#include "application_manager/application.h"
#include "application_manager/vehicle_info_data.h"
#include "policy/policy_types.h"
+#include "protocol_handler/session_observer.h"
+#include "application_manager/policies/policy_handler_interface.h"
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
@@ -50,6 +53,10 @@ class SmartObject;
}
}
+namespace policy {
+class PolicyHandlerInterface;
+}
+
namespace application_manager {
namespace mobile_api = mobile_apis;
namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
@@ -66,508 +73,629 @@ typedef std::map<std::string, VehicleDataType> VehicleData;
* @brief MessageHelper class
**/
class MessageHelper {
- public:
- /**
- * @brief Creates request for different interfaces(JSON, DBUS)
- * @param correlation_id unique ID
- * @param params Vector of arguments that we need in GetVehicleData request (e.g. gps, odometer, fuel_level)
- */
- static void CreateGetVehicleDataRequest(uint32_t correlation_id, const std::vector<std::string>& params);
-
- /**
- * @brief Sends HMI status notification to mobile
- *
- *@param application_impl application with changed HMI status
- *
- **/
- static void SendHMIStatusNotification(const Application& application_impl);
-
- /**
- * @brief Sends OnAppRegistered notification to HMI
- *
- *@param application_impl application with changed HMI status
- *
- **/
- static void SendOnAppRegisteredNotificationToHMI(
- const Application& application_impl,
- bool resumption = false,
- bool need_restore_vr = false);
-
- /**
- * @brief Create mobile HashUpdateNotification
- */
- static smart_objects::SmartObjectSPtr GetHashUpdateNotification(const uint32_t app_id);
-
- /**
- * @brief Create OnSystemRequest notification for lock screen icon url
- */
- static smart_objects::SmartObject* GetLockScreenIconUrlNotification(const uint32_t connection_key);
-
- /**
- * @brief Send the OnSystemRequest notification for lock screen icon url to the mobile device
- */
- static void SendLockScreenIconUrlNotification(const uint32_t connection_key);
-
- /**
- * @brief Sends to mobile HashUpdateNotification
- */
- static void SendHashUpdateNotification(const uint32_t app_id);
-
- /**
- * @brief Sends OnAppInterfaceUnregistered notification to mobile
- *
- *@param connection_key Connection key
- *@param reason Reason
- *
- **/
- static void SendOnAppInterfaceUnregisteredNotificationToMobile(
- int32_t connection_key,
- mobile_apis::AppInterfaceUnregisteredReason::eType reason);
-
- /*
- * @brief Retrieve vehicle data map for param name in mobile request
- * to VehicleDataType
- *
- * @return VehicleData reference
- */
- static const VehicleData& vehicle_data();
-
- /**
- * @brief Convert string to HMI level, if possible
- * @param hmi_level Stringified HMI level
- * @return Appropriate enum from HMI level, or INVALID_ENUM, if conversiion
- * is not possible
- */
- static mobile_api::HMILevel::eType StringToHMILevel(
+ public:
+ /**
+ * @brief Creates request for different interfaces(JSON, DBUS)
+ * @param correlation_id unique ID
+ * @param params Vector of arguments that we need in GetVehicleData request
+ * (e.g. gps, odometer, fuel_level)
+ */
+ static void CreateGetVehicleDataRequest(
+ const uint32_t correlation_id,
+ const std::vector<std::string>& params,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief Create mobile HashUpdateNotification
+ */
+ static smart_objects::SmartObjectSPtr CreateHashUpdateNotification(
+ const uint32_t app_id);
+
+ /**
+ * @brief Sends to mobile HashUpdateNotification
+ */
+ static void SendHashUpdateNotification(const uint32_t app_id,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief Sends OnLanguageChange notification to application
+ * @param connection_key Connection key of application
+ */
+ static void SendOnLanguageChangeToMobile(uint32_t connection_key);
+
+ /*
+ * @brief Retrieve vehicle data map for param name in mobile request
+ * to VehicleDataType
+ *
+ * @return VehicleData reference
+ */
+ static const VehicleData& vehicle_data();
+
+ /**
+ * @brief Converts HMI Result enum value to string
+ * @param hmi_result HMI Result enum value
+ * @return stringified value for enum if succedeed, otherwise - empty string
+ */
+ static std::string HMIResultToString(
+ hmi_apis::Common_Result::eType hmi_result);
+
+ /**
+ * @brief Converts string to HMI Result enum value
+ * @param hmi_result stringified value
+ * @return HMI Result enum value if succedeed, otherwise - INVALID_ENUM
+ * value
+ */
+ static hmi_apis::Common_Result::eType HMIResultFromString(
+ const std::string& hmi_result);
+
+ /**
+ * @brief Converts mobile Result enum value to string
+ * @param mobile_result mobile Result enum value
+ * @return stringified value for enum if succedeed, otherwise - empty string
+ */
+ static std::string MobileResultToString(
+ mobile_apis::Result::eType mobile_result);
+
+ /**
+ * @brief Converts string to mobile Result enum value
+ * @param mobile_result stringified value
+ * @return mobile Result enum value if succedeed, otherwise - INVALID_ENUM
+ * value
+ */
+ static mobile_api::Result::eType MobileResultFromString(
+ const std::string& mobile_result);
+
+ /**
+ * @brief Converts HMI Result enum value to mobile Result enum value
+ * @param hmi_result HMI Result enum value
+ * @return mobile Result enum value if succedeed, otherwise - INVALID_ENUM
+ * value
+ */
+ static mobile_api::Result::eType HMIToMobileResult(
+ const hmi_apis::Common_Result::eType hmi_result);
+
+ /**
+ * @brief Converts mobile Result enum value to HMI Result enum value
+ * @param mobile_result mobile Result enum value
+ * @return HMI Result enum value
+ */
+ static hmi_apis::Common_Result::eType MobileToHMIResult(
+ const mobile_api::Result::eType mobile_result);
+
+ /**
+ * @brief Convert string to HMI level, if possible
+ * @param hmi_level Stringified HMI level
+ * @return Appropriate enum from HMI level, or INVALID_ENUM, if conversiion
+ * is not possible
+ */
+ static mobile_api::HMILevel::eType StringToHMILevel(
const std::string& hmi_level);
- /*
- * @brief Used to obtain string representation of app's
- * HMI Level.
- * @param hmi_level Desired HMI Level
- */
- static std::string StringifiedHMILevel(
+ /*
+ * @brief Used to obtain string representation of app's
+ * HMI Level.
+ * @param hmi_level Desired HMI Level
+ */
+ static std::string StringifiedHMILevel(
mobile_apis::HMILevel::eType hmi_level);
- /*
- * @brief Used to obtain function name by its id
- * @param function_id Function ID
- */
- static std::string StringifiedFunctionID(
+ /*
+ * @brief Used to obtain function name by its id
+ * @param function_id Function ID
+ */
+ static std::string StringifiedFunctionID(
mobile_apis::FunctionID::eType function_id);
- static smart_objects::SmartObjectSPtr CreateBlockedByPoliciesResponse(
+ static smart_objects::SmartObjectSPtr CreateBlockedByPoliciesResponse(
mobile_apis::FunctionID::eType function_id,
- mobile_apis::Result::eType result, uint32_t correlation_id,
+ mobile_apis::Result::eType result,
+ const uint32_t correlation_id,
uint32_t connection_key);
- /*
- * @brief Prepare GetDeviceListResponse
- *
- *
- * @param devices Devices list
- *
- */
- static smart_objects::SmartObjectSPtr CreateDeviceListSO(
- const connection_handler::DeviceMap& devices);
-
- static smart_objects::SmartObjectSPtr CreateModuleInfoSO(
- uint32_t function_id);
-
- static smart_objects::SmartObjectSPtr CreateSetAppIcon(
- const std::string& path_to_icon, uint32_t app_id);
-
- /**
- * @brief Sends IVI subscription requests
- */
- static bool SendIVISubscribtions(const uint32_t app_id);
-
- /**
- * @brief Returns IVI subscription requests
- */
- static smart_objects::SmartObjectList GetIVISubscriptionRequests(ApplicationSharedPtr app);
-
- /**
- * @brief Sends button subscription notification
- */
- static void SendOnButtonSubscriptionNotification(
- uint32_t app_id, hmi_apis::Common_ButtonName::eType button, bool is_subscribed);
-
- /**
- * @brief Sends button subscription notifications for all buttons
- * that application is subscribed on
- */
- static void SendAllOnButtonSubscriptionNotificationsForApp(
- ApplicationConstSharedPtr app);
-
- static void SendAppDataToHMI(ApplicationConstSharedPtr app);
- static void SendGlobalPropertiesToHMI(ApplicationConstSharedPtr app);
- static smart_objects::SmartObjectList CreateGlobalPropertiesRequestsToHMI(ApplicationConstSharedPtr app);
-
- static smart_objects::SmartObjectSPtr CreateAppVrHelp(
- ApplicationConstSharedPtr app);
-
- static smart_objects::SmartObjectList CreateShowRequestToHMI(ApplicationConstSharedPtr app);
- static void SendShowRequestToHMI(ApplicationConstSharedPtr app);
- static void SendShowConstantTBTRequestToHMI(ApplicationConstSharedPtr app);
- static void SendAddCommandRequestToHMI(ApplicationConstSharedPtr app);
- static smart_objects::SmartObjectList CreateAddCommandRequestToHMI(ApplicationConstSharedPtr app);
-
- /**
- * @brief Sends UI_ChangeRegistration to HMI with list of AppHMIType
- * @param app applicaton instace
- */
- static void SendUIChangeRegistrationRequestToHMI(ApplicationConstSharedPtr app);
- static void SendChangeRegistrationRequestToHMI(ApplicationConstSharedPtr app);
- static void SendAddVRCommandToHMI(
- uint32_t cmd_id, const smart_objects::SmartObject& vr_commands,
- uint32_t app_id);
-
- static smart_objects::SmartObjectSPtr CreateAddVRCommandToHMI(
- uint32_t cmd_id, const smart_objects::SmartObject& vr_commands,
- uint32_t app_id);
-
- /*
- * @brief Create Common.HMIApplication struct application instance
- * @param app : applicaton instace
- * @param output smart object to store Common.HMIApplication struct
- * @return true on succes, otherwise return false;
- */
- static bool CreateHMIApplicationStruct(ApplicationConstSharedPtr app,
- smart_objects::SmartObject& output);
-
- static void SendAddSubMenuRequestToHMI(ApplicationConstSharedPtr app);
- static smart_objects::SmartObjectList CreateAddSubMenuRequestToHMI(ApplicationConstSharedPtr app);
-
- /*
- * @brief Creates BasicCommunication.OnAppUnregistered notification
- * @param app Application instance
- * @param is_unexpected_disconnect
- * Indicates if connection was unexpectedly lost by TM or HB
- */
- static void SendOnAppUnregNotificationToHMI(ApplicationConstSharedPtr app,
- bool is_unexpected_disconnect = false);
- static uint32_t SendActivateAppToHMI(
- uint32_t const app_id,
- hmi_apis::Common_HMILevel::eType level = hmi_apis::Common_HMILevel::FULL,
- bool send_policy_priority = true);
-
- static void SendOnResumeAudioSourceToHMI(const uint32_t app_id);
-
- static std::string GetDeviceMacAddressForHandle(
- const uint32_t device_handle);
-
- static void GetDeviceInfoForHandle(const uint32_t device_handle,
- policy::DeviceParams* device_info);
- static void GetDeviceInfoForApp(uint32_t connection_key,
- policy::DeviceParams* device_info);
-
- /**
- * @brief Send SDL_ActivateApp response to HMI
- * @param permissions response parameters
- */
- static void SendSDLActivateAppResponse(policy::AppPermissions& permissions,
- uint32_t correlation_id);
+ /*
+ * @brief Prepare GetDeviceListResponse
+ *
+ *
+ * @param devices Devices list
+ *
+ */
+ static smart_objects::SmartObjectSPtr CreateDeviceListSO(
+ const connection_handler::DeviceMap& devices,
+ const policy::PolicyHandlerInterface& policy_handler,
+ ApplicationManager& app_mngr);
+
+ static smart_objects::SmartObjectSPtr CreateModuleInfoSO(
+ uint32_t function_id, ApplicationManager& app_mngr);
+
+ static smart_objects::SmartObjectSPtr CreateSetAppIcon(
+ const std::string& path_to_icon, uint32_t app_id);
+
+ /**
+ * @brief Sends IVI subscription requests
+ */
+ static bool SendIVISubscribtions(const uint32_t app_id,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief Returns IVI subscription requests
+ */
+ static smart_objects::SmartObjectList GetIVISubscriptionRequests(
+ ApplicationSharedPtr app, ApplicationManager& app_mngr);
+
+ /**
+ * @brief Sends button subscription notification
+ */
+ static void SendOnButtonSubscriptionNotification(
+ const uint32_t app_id,
+ const hmi_apis::Common_ButtonName::eType button,
+ const bool is_subscribed,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief Sends button subscription notifications for all buttons
+ * that application is subscribed on
+ */
+ static void SendAllOnButtonSubscriptionNotificationsForApp(
+ ApplicationConstSharedPtr app, ApplicationManager& app_mngr);
+
+ static void SendAppDataToHMI(ApplicationConstSharedPtr app,
+ ApplicationManager& app_man);
+ static void SendGlobalPropertiesToHMI(ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr);
+ static smart_objects::SmartObjectList CreateGlobalPropertiesRequestsToHMI(
+ ApplicationConstSharedPtr app, const uint32_t correlation_id);
+
+ static smart_objects::SmartObjectSPtr CreateAppVrHelp(
+ ApplicationConstSharedPtr app);
- /**
- * @brief Send OnSDLConsentNeeded to HMI for device data consent by user
- * @param device_info Device info, e.g. mac, handle, name
+ static smart_objects::SmartObjectList CreateShowRequestToHMI(
+ ApplicationConstSharedPtr app, const uint32_t correlation_id);
+ static void SendShowRequestToHMI(ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr);
+ static void SendShowConstantTBTRequestToHMI(ApplicationConstSharedPtr app,
+ ApplicationManager& app_man);
+ static void SendAddCommandRequestToHMI(ApplicationConstSharedPtr app,
+ ApplicationManager& app_man);
+ static smart_objects::SmartObjectList CreateAddCommandRequestToHMI(
+ ApplicationConstSharedPtr app, ApplicationManager& app_mngr);
+
+ static smart_objects::SmartObjectList
+ CreateAddVRCommandRequestFromChoiceToHMI(ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief Sends UI_ChangeRegistration to HMI with list of AppHMIType
+ * @param app applicaton instace
+ */
+ static void SendUIChangeRegistrationRequestToHMI(
+ ApplicationConstSharedPtr app, ApplicationManager& app_mngr);
+ static void SendChangeRegistrationRequestToHMI(ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr);
+ static void SendAddVRCommandToHMI(
+ uint32_t cmd_id,
+ const smart_objects::SmartObject& vr_commands,
+ const uint32_t app_id,
+ ApplicationManager& app_mngr);
+
+ static smart_objects::SmartObjectSPtr CreateAddVRCommandToHMI(
+ uint32_t cmd_id,
+ const smart_objects::SmartObject& vr_commands,
+ const uint32_t app_id,
+ ApplicationManager& app_mngr);
+
+ /*
+ * @brief Create Common.HMIApplication struct application instance
+ * @param app : applicaton instace
+ * @param output smart object to store Common.HMIApplication struct
+ * @return true on succes, otherwise return false;
+ */
+ static bool CreateHMIApplicationStruct(
+ ApplicationConstSharedPtr app,
+ const protocol_handler::SessionObserver& session_observer,
+ const policy::PolicyHandlerInterface& policy_handler,
+ smart_objects::SmartObject* output,
+ ApplicationManager& app_mngr);
+
+ static void SendAddSubMenuRequestToHMI(ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr);
+ static smart_objects::SmartObjectList CreateAddSubMenuRequestToHMI(
+ ApplicationConstSharedPtr app, const uint32_t correlation_id);
+
+ /*
+ * @brief Creates BasicCommunication.OnAppUnregistered notification
+ * @param app Application instance
+ * @param is_unexpected_disconnect
+ * Indicates if connection was unexpectedly lost by TM or HB
+ */
+ static void SendOnAppUnregNotificationToHMI(ApplicationConstSharedPtr app,
+ bool is_unexpected_disconnect,
+ ApplicationManager& app_mngr);
+
+ static NsSmartDeviceLink::NsSmartObjects::SmartObjectSPtr
+ GetBCActivateAppRequestToHMI(
+ ApplicationConstSharedPtr app,
+ const protocol_handler::SessionObserver& session_observer,
+ const policy::PolicyHandlerInterface& policy_handler,
+ hmi_apis::Common_HMILevel::eType level,
+ bool send_policy_priority,
+ ApplicationManager& app_mngr);
+
+ static void SendOnResumeAudioSourceToHMI(const uint32_t app_id,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief Send SDL_ActivateApp response to HMI
+ * @param permissions response parameters
+ */
+ static void SendSDLActivateAppResponse(policy::AppPermissions& permissions,
+ uint32_t correlation_id,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief Send OnSDLConsentNeeded to HMI for device data consent by user
+ * @param device_info Device info, e.g. mac, handle, name
+ */
+ static void SendOnSDLConsentNeeded(const policy::DeviceParams& device_info,
+ ApplicationManager& app_man);
+
+ /**
+ * @brief Send request to SyncP process to read file and send
+ * Policy Table Snapshot using Retry Strategy
+ * @param file_path Path to file with PTS
+ * @param timeout Timeout to wait for PTU
+ * @param retries Seconds between retries
*/
- static void SendOnSDLConsentNeeded(const policy::DeviceParams& device_info);
-
- /**
- * @brief Send request to SyncP process to read file and send
- * Policy Table Snapshot using Retry Strategy
- * @param file_path Path to file with PTS
- * @param timeout Timeout to wait for PTU
- * @param retries Seconds between retries
- */
- static void SendPolicyUpdate(const std::string& file_path,
- int timeout,
- const std::vector<int>& retries);
-
- /**
- * @brief Send GetUserFriendlyMessage response to HMI
- * @param msg Appopriate messages params
- * @param correlation_id Correlation id of request
- */
- static void SendGetUserFriendlyMessageResponse(
+ static void SendPolicyUpdate(const std::string& file_path,
+ int timeout,
+ const std::vector<int>& retries,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief Send GetUserFriendlyMessage response to HMI
+ * @param msg Appopriate messages params
+ * @param correlation_id Correlation id of request
+ */
+ static void SendGetUserFriendlyMessageResponse(
const std::vector<policy::UserFriendlyMessage>& msg,
- uint32_t correlation_id);
-
- /**
- * @brief Send GetListOfPermissions response to HMI
- * @param permissions Array of groups permissions
- * @param correlation_id Correlation id of request
- */
- static void SendGetListOfPermissionsResponse(
+ uint32_t correlation_id,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief Send GetListOfPermissions response to HMI
+ * @param permissions Array of groups permissions
+ * @param correlation_id Correlation id of request
+ */
+ static void SendGetListOfPermissionsResponse(
const std::vector<policy::FunctionalGroupPermission>& permissions,
- uint32_t correlation_id);
-
- /*
- * @brief Sends notification to HMI to start video streaming
- *
- * @param connection_key Application connection key
- *
- */
- static void SendNaviStartStream(int32_t connection_key);
-
- /*
- * @brief Sends notification to HMI to stop video streaming
- *
- * @param connection_key Application connection key
- *
- */
- static void SendNaviStopStream(int32_t connection_key);
-
- /*
- * @brief Send notification for Update of Policy Table
- * with PT Snapshot.
- * @param connection_key Id of application to send message to
- * @param policy_data PT Snapshot
- * @param url If empty string, no URL is provided
- * @param timeout If -1 no timeout is provdied
- */
- static void SendPolicySnapshotNotification(
- unsigned int connection_key, const std::vector<uint8_t>& policy_data,
- const std::string& url = "", int timeout = -1);
-
- static void SendSystemRequestNotification(
- uint32_t connection_key,
- NsSmartDeviceLink::NsSmartObjects::SmartObject& content);
-
- /**
- * @brief SendLaunchApp allows to send OnSystemRequest with LAUNCH_UP.
- *
- * @param connection_key application id.
- *
- * @param urlSchema application's url schema.
- *
- * @param packageName application's package name.
- */
- static void SendLaunchApp(uint32_t connection_key,
- const std::string& urlSchema,
- const std::string& packageName);
-
- /**
- * @brief Sends OnSystemRequest which queries remote apps list
- * @param connection_key application id, which is used for sending out
- */
- static void SendQueryApps(uint32_t connection_key);
-
- /*
- * @brief Send notification to mobile on application permissions update
- * @param connection_key Id of application to send message to
- * @param permissions updated permissions for application
- */
- static void SendOnPermissionsChangeNotification(
- uint32_t connection_key, const policy::Permissions& permissions);
-
- /*
- * @brief Send notification to HMI on application permissions update
- * @param connection_key Id of application to send message to
- * @param permissions updated permissions for application
- */
- static void SendOnAppPermissionsChangedNotification(
- uint32_t connection_key, const policy::AppPermissions& permissions);
-
- /**
- * @brief Send GetStatusUpdate response to HMI with current policy update
- * status
- * @param status Update status
- * @param correlation_id Correlation id from request
- */
- static void SendGetStatusUpdateResponse(const std::string& status,
- uint32_t correlation_id);
-
- /**
- * @brief Send UpdateSDL response to HMI with policy update result
- * @param result Update result
- * @param correlation_id Correlation id from request
- */
- static void SendUpdateSDLResponse(const std::string& result,
- uint32_t correlation_id);
-
- /**
- * @brief Send OnStatusUpdate to HMI on policy update status change
- * @param status Policy table update status
- */
- static void SendOnStatusUpdate(const std::string& status);
-
- /**
- * @brief Send GetSystemInfo request to HMI
- */
- static void SendGetSystemInfoRequest();
-
- /*
- * @brief Sends notification to HMI to start audio streaming
- *
- * @param connection_key Application connection key
- *
- */
- static void SendAudioStartStream(int32_t connection_key);
-
- /*
- * @brief Sends notification to HMI to stop audio streaming
- *
- * @param connection_key Application connection key
- *
- */
- static void SendAudioStopStream(int32_t connection_key);
-
- static void SendOnDataStreaming(protocol_handler::ServiceType service,
- bool available);
-
- /*
- * @brief Sends notification to HMI to stop audioPathThru
- *
- * @param connection_key Application connection key
- *
- * @return TRUE on SUCCES otherwise return FALSE
- */
- static bool SendStopAudioPathThru();
-
- static smart_objects::SmartObjectSPtr CreateNegativeResponse(
- uint32_t connection_key, int32_t function_id, uint32_t correlation_id,
- int32_t result_code);
-
- /*
- * @brief Verify image and add image file full path
- *
- * @param SmartObject with image
- *
- * @param app current application
- *
- * @return verification result
- *
- */
- static mobile_apis::Result::eType VerifyImage(smart_objects::SmartObject& image,
- ApplicationConstSharedPtr app);
-
- /*
- * @brief Finds "Image" structure in request and verify image file presence
- * in Core.
- *
- * @param message SmartObject with request
- *
- * @param app current application
- *
- * @return verification result
- *
- */
- static mobile_apis::Result::eType VerifyImageFiles(
- smart_objects::SmartObject& message, ApplicationConstSharedPtr app);
-
- static mobile_apis::Result::eType VerifyImageVrHelpItems(
- smart_objects::SmartObject& message, ApplicationConstSharedPtr app);
-
- /**
- * @brief Checks string if it contains incorrect character \t\n \\t \\n
- * or string contains only whitespace
- * @param parameter str contains string which must be checked
- * @return returns FALSE if string contains incorrect character or
- * string is empty otherwise returns TRUE
- */
- static bool VerifySoftButtonString(const std::string& str);
-
- static mobile_apis::Result::eType ProcessSoftButtons(
+ uint32_t correlation_id,
+ ApplicationManager& app_mngr);
+
+ /*
+ * @brief Sends notification to HMI to start video streaming
+ *
+ * @param connection_key Application connection key
+ *
+ */
+ static void SendNaviStartStream(int32_t app_id, ApplicationManager& app_mngr);
+
+ /*
+ * @brief Sends notification to HMI to stop video streaming
+ *
+ * @param connection_key Application connection key
+ *
+ */
+ static void SendNaviStopStream(int32_t app_id, ApplicationManager& app_mngr);
+
+ /*
+ * @brief Send notification for Update of Policy Table
+ * with PT Snapshot.
+ * @param connection_key Id of application to send message to
+ * @param policy_data PT Snapshot
+ * @param url If empty string, no URL is provided
+ * @param timeout If -1 no timeout is provdied
+ */
+ static void SendPolicySnapshotNotification(
+ uint32_t connection_key,
+ const std::vector<uint8_t>& policy_data,
+ const std::string& url,
+ ApplicationManager& app_mngr);
+
+ static void SendSystemRequestNotification(
+ uint32_t connection_key,
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& content,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief SendLaunchApp allows to send OnSystemRequest with LAUNCH_UP.
+ *
+ * @param connection_key application id.
+ *
+ * @param urlSchema application's url schema.
+ *
+ * @param packageName application's package name.
+ */
+ static void SendLaunchApp(const uint32_t connection_key,
+ const std::string& urlSchema,
+ const std::string& packageName,
+ ApplicationManager& app_man);
+
+ /**
+ * @brief Sends OnSystemRequest which queries remote apps list
+ * @param connection_key application id, which is used for sending out
+ */
+ static void SendQueryApps(const uint32_t connection_key,
+ ApplicationManager& app_man);
+
+ /*
+ * @brief Send notification to mobile on application permissions update
+ * @param connection_key Id of application to send message to
+ * @param permissions updated permissions for application
+ */
+ static void SendOnPermissionsChangeNotification(
+ uint32_t connection_key,
+ const policy::Permissions& permissions,
+ ApplicationManager& app_mngr);
+
+ /*
+ * @brief Send notification to HMI on application permissions update
+ * @param connection_key Id of application to send message to
+ * @param permissions updated permissions for application
+ */
+ static void SendOnAppPermissionsChangedNotification(
+ uint32_t connection_key,
+ const policy::AppPermissions& permissions,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief Send GetStatusUpdate response to HMI with current policy update
+ * status
+ * @param status Update status
+ * @param correlation_id Correlation id from request
+ */
+ static void SendGetStatusUpdateResponse(const std::string& status,
+ const uint32_t correlation_id,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief Send UpdateSDL response to HMI with policy update result
+ * @param result Update result
+ * @param correlation_id Correlation id from request
+ */
+ static void SendUpdateSDLResponse(const std::string& result,
+ const uint32_t correlation_id,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief Send OnStatusUpdate to HMI on policy update status change
+ * @param status Policy table update status
+ */
+ static void SendOnStatusUpdate(const std::string& status,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief Send GetSystemInfo request to HMI
+ */
+ static void SendGetSystemInfoRequest(ApplicationManager& app_mngr);
+
+ /*
+ * @brief Sends notification to HMI to start audio streaming
+ *
+ * @param connection_key Application connection key
+ *
+ */
+ static void SendAudioStartStream(int32_t app_id,
+ ApplicationManager& app_mngr);
+
+ /*
+ * @brief Sends notification to HMI to stop audio streaming
+ *
+ * @param connection_key Application connection key
+ *
+ */
+ static void SendAudioStopStream(int32_t connection_key,
+ ApplicationManager& app_mngr);
+
+ static void SendOnDataStreaming(protocol_handler::ServiceType service,
+ bool available,
+ ApplicationManager& app_mngr);
+
+ /*
+ * @brief Sends notification to HMI to stop audioPathThru
+ *
+ * @param connection_key Application connection key
+ *
+ * @return TRUE on SUCCES otherwise return FALSE
+ */
+ static bool SendStopAudioPathThru(ApplicationManager& app_mngr);
+
+ /**
+ * @brief Sends UnsubscribeWayPoints request
+ * @return true if UnSubscribedWayPoints is send otherwise false
+ */
+ static bool SendUnsubscribedWayPoints(ApplicationManager& app_mngr);
+
+ static smart_objects::SmartObjectSPtr CreateNegativeResponse(
+ uint32_t connection_key,
+ int32_t function_id,
+ const uint32_t correlation_id,
+ int32_t result_code);
+
+ /*
+ * @brief Verify image and add image file full path
+ *
+ * @param SmartObject with image
+ *
+ * @param app current application
+ *
+ * @return verification result
+ *
+ */
+ static mobile_apis::Result::eType VerifyImage(
+ smart_objects::SmartObject& image,
+ ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr);
+
+ /*
+ * @brief Finds "Image" structure in request and verify image file presence
+ * in Core.
+ *
+ * @param message SmartObject with request
+ *
+ * @param app current application
+ *
+ * @return verification result
+ *
+ */
+ static mobile_apis::Result::eType VerifyImageFiles(
+ smart_objects::SmartObject& message,
+ ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr);
+
+ static mobile_apis::Result::eType VerifyImageVrHelpItems(
+ smart_objects::SmartObject& message,
+ ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr);
+
+ /**
+ * @brief Checks string if it contains incorrect character \t\n \\t \\n
+ * or string contains only whitespace
+ * @param parameter str contains string which must be checked
+ * @return returns FALSE if string contains incorrect character or
+ * string is empty otherwise returns TRUE
+ */
+ static bool VerifySoftButtonString(const std::string& str);
+
+ static mobile_apis::Result::eType ProcessSoftButtons(
smart_objects::SmartObject& message_params,
- ApplicationConstSharedPtr app);
-
- /**
- * @brief checkWithPolicy allows to check soft button's parameters
- * according to the current policy
- * @param system_action system action
- * @param app_mobile_id policy application id
- * @return
- */
- static bool CheckWithPolicy(mobile_apis::SystemAction::eType system_action,
- const std::string& app_mobile_id);
-
- /*
- * @brief subscribe application to softbutton
- *
- * @param message_params contains data of request
- *
- * @param app current application
- *
- * @param function_id Unique command id from mobile API
- */
- static void SubscribeApplicationToSoftButton(
- smart_objects::SmartObject& message_params,
- ApplicationSharedPtr app,
- int32_t function_id);
-
- static bool PrintSmartObject(const smart_objects::SmartObject& object);
-
- template<typename From, typename To>
- static To ConvertEnumAPINoCheck(const From& input) {
- return static_cast<To>(input);
- }
-
- /**
- * @brief Convert common language to string representation
- * @param language Common language
- * @return Common language string representation
- */
- static std::string CommonLanguageToString(
+ ApplicationConstSharedPtr app,
+ const policy::PolicyHandlerInterface& policy_handler,
+ ApplicationManager& app_mngr);
+
+ /*
+ * @brief subscribe application to softbutton
+ *
+ * @param message_params contains data of request
+ *
+ * @param app current application
+ *
+ * @param function_id Unique command id from mobile API
+ */
+ static void SubscribeApplicationToSoftButton(
+ smart_objects::SmartObject& message_params,
+ ApplicationSharedPtr app,
+ int32_t function_id);
+
+ static bool PrintSmartObject(const smart_objects::SmartObject& object);
+
+ template <typename From, typename To>
+ static To ConvertEnumAPINoCheck(const From& input) {
+ return static_cast<To>(input);
+ }
+
+ static const uint32_t GetPriorityCode(const std::string& priority);
+ /**
+ * @brief Convert common language to string representation
+ * @param language Common language
+ * @return Common language string representation
+ */
+ static std::string CommonLanguageToString(
hmi_apis::Common_Language::eType language);
- /**
- * @brief Converts string to common language enum value
- * @param language language as string
- * @return Common language enum value
- */
- static hmi_apis::Common_Language::eType CommonLanguageFromString(
- const std::string& language);
-
- /**
- * @brief Gets command limit number per minute for specific application
- * @param policy_app_id Unique application id
- * @return Limit for number of command per minute
- */
- static uint32_t GetAppCommandLimit(const std::string& policy_app_id);
-
- /**
- * @brief Creates TTS.SetGlobalProperties request and sends
- * to HMI for VCA module.
- * @param app contains application which sends TTS GlobalProperties to HMI
- * after timeout or first time when application register with level NONE or
- * BACKGROUND
- * @param default_help_prompt
- * if default_help_prompt=TRUE->TTSGlobalProperties request will be created with
- * default helpPrompt array, otherwise TTSGlobalProperties request will be created
- * with empty helpPrompt array.
- */
- static void SendTTSGlobalProperties(
- ApplicationSharedPtr app, bool default_help_prompt);
-
- /**
- * @brief SendSetAppIcon allows to send SetAppIcon request.
- *
- * @param app_id application for which icon request should be sent.
- *
- * @param icon_path path to the icon.
- */
- static void SendSetAppIcon(uint32_t app_id,
- const std::string& icon_path);
- private:
- /**
- * @brief Allows to fill SO according to the current permissions.
- * @param permissions application permissions.
- * @param message which should be filled.
- */
- static void FillAppRevokedPermissions(const policy::AppPermissions& permissions,
- smart_objects::SmartObject& message);
-
- static smart_objects::SmartObjectSPtr CreateChangeRegistration(
- int32_t function_id, int32_t language, uint32_t app_id,
- const smart_objects::SmartObject* app_types = NULL);
-
- MessageHelper();
-
- static const VehicleData vehicle_data_;
- DISALLOW_COPY_AND_ASSIGN(MessageHelper);
+ /**
+ * @brief Converts string to mobile language enum value
+ * @param language language as string
+ * @return Mobile language enum value
+ */
+ static mobile_apis::Language::eType MobileLanguageFromString(
+ const std::string& language);
+
+ /**
+ * @brief Converts mobile language enum to HMI language enum
+ * @param language Mobile language enum
+ * @return HMI language enum
+ */
+ static hmi_apis::Common_Language::eType MobileToCommonLanguage(
+ const mobile_apis::Language::eType language);
+
+ /**
+ * @brief Converts HMI language enum to mobile language enum
+ * @param language HMI language enum
+ * @return Mobile language enum
+ */
+ static mobile_apis::Language::eType CommonToMobileLanguage(
+ const hmi_apis::Common_Language::eType language);
+
+ /**
+ * @brief Gets command limit number per minute for specific application
+ * @param policy_app_id Unique application id
+ * @return Limit for number of command per minute
+ */
+ static uint32_t GetAppCommandLimit(const std::string& policy_app_id);
+
+ /**
+ * @brief Creates TTS.SetGlobalProperties request and sends
+ * to HMI for VCA module.
+ * @param app contains application which sends TTS GlobalProperties to HMI
+ * after timeout or first time when application register with level NONE or
+ * BACKGROUND
+ * @param default_help_prompt
+ * if default_help_prompt=TRUE->TTSGlobalProperties request will be created
+ * with
+ * default helpPrompt array, otherwise TTSGlobalProperties request will be
+ * created
+ * with empty helpPrompt array.
+ */
+ static void SendTTSGlobalProperties(ApplicationSharedPtr app,
+ const bool default_help_prompt,
+ ApplicationManager& app_man);
+
+ /**
+ * @brief SendSetAppIcon allows to send SetAppIcon request.
+ *
+ * @param app_id application for which icon request should be sent.
+ *
+ * @param icon_path path to the icon.
+ */
+ static void SendSetAppIcon(const uint32_t app_id,
+ const std::string& icon_path,
+ ApplicationManager& application_manager);
+
+ static hmi_apis::Common_Language::eType CommonLanguageFromString(
+ const std::string& language);
+
+ static smart_objects::SmartObjectSPtr
+ GetOnAppInterfaceUnregisteredNotificationToMobile(
+ int32_t connection_key,
+ mobile_api::AppInterfaceUnregisteredReason::eType reason);
+
+ private:
+ /**
+ * @brief Creates new request object and fill its header
+ * @return New request object
+ */
+ static smart_objects::SmartObjectSPtr CreateRequestObject(
+ const uint32_t correlation_id);
+
+ /**
+ * @brief Allows to fill SO according to the current permissions.
+ * @param permissions application permissions.
+ * @param message which should be filled.
+ */
+ static void FillAppRevokedPermissions(
+ const policy::AppPermissions& permissions,
+ smart_objects::SmartObject& message);
+
+ static smart_objects::SmartObjectSPtr CreateChangeRegistration(
+ const int32_t function_id,
+ const int32_t language,
+ const uint32_t app_id,
+ const smart_objects::SmartObject* app_types,
+ ApplicationManager& app_mngr);
+
+ MessageHelper();
+
+ static const VehicleData vehicle_data_;
+ DISALLOW_COPY_AND_ASSIGN(MessageHelper);
};
} // namespace application_manager
diff --git a/src/components/application_manager/include/application_manager/mobile_command_factory.h b/src/components/application_manager/include/application_manager/mobile_command_factory.h
index b28e0abb34..1f270b28db 100644
--- a/src/components/application_manager/include/application_manager/mobile_command_factory.h
+++ b/src/components/application_manager/include/application_manager/mobile_command_factory.h
@@ -39,6 +39,7 @@
namespace application_manager {
typedef utils::SharedPtr<commands::Command> CommandSharedPtr;
+class ApplicationManager;
/**
* @brief Factory class for command creation
@@ -51,9 +52,10 @@ class MobileCommandFactory {
* @param smartObject SmartObject shared pointer.
* @return Pointer to created command object.
**/
- static commands::Command* CreateCommand(
- const commands::MessageSharedPtr& message,
- commands::Command::CommandOrigin origin);
+ static CommandSharedPtr CreateCommand(
+ const commands::MessageSharedPtr& message,
+ commands::Command::CommandOrigin origin,
+ ApplicationManager& application_manager);
private:
MobileCommandFactory();
diff --git a/src/components/application_manager/include/application_manager/mobile_message_handler.h b/src/components/application_manager/include/application_manager/mobile_message_handler.h
index 5e8d551aee..6b62258b23 100644
--- a/src/components/application_manager/include/application_manager/mobile_message_handler.h
+++ b/src/components/application_manager/include/application_manager/mobile_message_handler.h
@@ -40,29 +40,29 @@
namespace application_manager {
typedef utils::SharedPtr<application_manager::Message> MobileMessage;
class MobileMessageHandler {
- public:
- static application_manager::Message* HandleIncomingMessageProtocol(
+ public:
+ static application_manager::Message* HandleIncomingMessageProtocol(
const protocol_handler::RawMessagePtr message);
- static protocol_handler::RawMessage* HandleOutgoingMessageProtocol(
+ static protocol_handler::RawMessage* HandleOutgoingMessageProtocol(
const MobileMessage& message);
- //! -------------------------------------------------------------
- private:
- static application_manager::Message* HandleIncomingMessageProtocolV1(
+ //! -------------------------------------------------------------
+ private:
+ static application_manager::Message* HandleIncomingMessageProtocolV1(
const protocol_handler::RawMessagePtr message);
- static application_manager::Message* HandleIncomingMessageProtocolV2(
+ static application_manager::Message* HandleIncomingMessageProtocolV2(
const protocol_handler::RawMessagePtr message);
- //! -------------------------------------------------------------
+ //! -------------------------------------------------------------
- static protocol_handler::RawMessage* HandleOutgoingMessageProtocolV1(
+ static protocol_handler::RawMessage* HandleOutgoingMessageProtocolV1(
const MobileMessage& message);
- static protocol_handler::RawMessage* HandleOutgoingMessageProtocolV2(
+ static protocol_handler::RawMessage* HandleOutgoingMessageProtocolV2(
const MobileMessage& message);
- DISALLOW_COPY_AND_ASSIGN(MobileMessageHandler);
+ DISALLOW_COPY_AND_ASSIGN(MobileMessageHandler);
};
} // namespace application_manager
diff --git a/src/components/application_manager/include/application_manager/policies/delegates/app_permission_delegate.h b/src/components/application_manager/include/application_manager/policies/delegates/app_permission_delegate.h
index 55a4f146c2..6913f5038e 100644
--- a/src/components/application_manager/include/application_manager/policies/delegates/app_permission_delegate.h
+++ b/src/components/application_manager/include/application_manager/policies/delegates/app_permission_delegate.h
@@ -33,49 +33,50 @@
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_DELEGATES_APP_PERMISSION_DELEGATE_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_DELEGATES_APP_PERMISSION_DELEGATE_H_
-
#include "utils/threads/thread.h"
#include "utils/threads/thread_delegate.h"
#include "utils/conditional_variable.h"
#include "policy/policy_types.h"
+#include "application_manager/policies/policy_handler_interface.h"
namespace policy {
-
+/**
+*@brief The AppPermissionDelegate class allows to call OnAppPermissionConsent
+*in async way.
+*/
+class AppPermissionDelegate : public threads::ThreadDelegate {
+ public:
/**
- * @brief The AppPermissionDelegate class allows to call OnAppPermissionConsent
- * in async way.
- */
-class AppPermissionDelegate: public threads::ThreadDelegate {
- public:
- /**
- * @brief AppPermissionDelegate constructor, contains parameters
- * which will be pass to the called function.
- *
- * @param connection_key connection key.
- *
- * @param permissions new permissions
- */
- AppPermissionDelegate(const uint32_t connection_key,
- const PermissionConsent &permissions);
+ * @brief AppPermissionDelegate constructor, contains parameters
+ * which will be pass to the called function.
+ *
+ * @param connection_key connection key.
+ *
+ * @param permissions new permissions
+ */
+ AppPermissionDelegate(const uint32_t connection_key,
+ const PermissionConsent& permissions,
+ policy::PolicyHandlerInterface& policy_handler);
- /**
- * @brief threadMain run the needed function.
- */
- virtual void threadMain();
-
- /**
- * @brief exitThreadMain do some stuff before exit from thread
- *
- * @return true in case when thread has been finished properly
- */
- virtual void exitThreadMain();
+ /**
+ * @brief threadMain run the needed function.
+ */
+ virtual void threadMain();
- private:
- uint32_t connection_key_;
- PermissionConsent permissions_;
+ /**
+ * @brief exitThreadMain do some stuff before exit from thread
+ *
+ * @return true in case when thread has been finished properly
+ */
+ virtual void exitThreadMain();
+
+ private:
+ uint32_t connection_key_;
+ PermissionConsent permissions_;
+ policy::PolicyHandlerInterface& policy_handler_;
};
-} // namespace policy
+} // namespace policy
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_DELEGATES_APP_PERMISSION_DELEGATE_H_
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_DELEGATES_APP_PERMISSION_DELEGATE_H_
diff --git a/src/components/application_manager/include/application_manager/policies/delegates/statistics_delegate.h b/src/components/application_manager/include/application_manager/policies/delegates/statistics_delegate.h
index 9044a3fd33..3dc9ad925c 100644
--- a/src/components/application_manager/include/application_manager/policies/delegates/statistics_delegate.h
+++ b/src/components/application_manager/include/application_manager/policies/delegates/statistics_delegate.h
@@ -42,41 +42,45 @@
namespace policy {
- class StatisticsDelegate: public threads::ThreadDelegate {
- enum StatisticType{
- INCREMENT_GLOBAL,
- INCREMENT_APP,
- SET,
- ADD
- };
- public:
- explicit StatisticsDelegate(usage_statistics::GlobalCounterId type);
-
- StatisticsDelegate(const std::string& app_id,
- usage_statistics::AppCounterId type);
-
- StatisticsDelegate(const std::string& app_id,
- usage_statistics::AppInfoId type,
- const std::string& value);
-
- StatisticsDelegate(const std::string& app_id,
- usage_statistics::AppStopwatchId type,
- int32_t timespan_seconds);
-
- virtual void threadMain();
-
- virtual void exitThreadMain();
- private:
- StatisticType type_;
- usage_statistics::GlobalCounterId global_counter_;
- usage_statistics::AppCounterId app_counter_;
- usage_statistics::AppInfoId app_info_;
- usage_statistics::AppStopwatchId stop_watch_;
-
- std::string app_id_;
- std::string value_;
- int32_t timespan_seconds_;
- };
-} // namespace policy
-
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_DELEGATES_STATISTICS_DELEGATE_H_
+class PolicyHandler;
+
+class StatisticsDelegate : public threads::ThreadDelegate {
+ enum StatisticType { INCREMENT_GLOBAL, INCREMENT_APP, SET, ADD };
+
+ public:
+ StatisticsDelegate(PolicyHandler& policy_handler,
+ usage_statistics::GlobalCounterId type);
+
+ StatisticsDelegate(PolicyHandler& policy_handler,
+ const std::string& app_id,
+ usage_statistics::AppCounterId type);
+
+ StatisticsDelegate(PolicyHandler& policy_handler,
+ const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value);
+
+ StatisticsDelegate(PolicyHandler& policy_handler,
+ const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int32_t timespan_seconds);
+
+ virtual void threadMain();
+
+ virtual void exitThreadMain();
+
+ private:
+ StatisticType type_;
+ usage_statistics::GlobalCounterId global_counter_;
+ usage_statistics::AppCounterId app_counter_;
+ usage_statistics::AppInfoId app_info_;
+ usage_statistics::AppStopwatchId stop_watch_;
+
+ std::string app_id_;
+ std::string value_;
+ int32_t timespan_seconds_;
+ PolicyHandler& policy_handler_;
+};
+} // namespace policy
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_DELEGATES_STATISTICS_DELEGATE_H_
diff --git a/src/components/application_manager/include/application_manager/policies/policy_event_observer.h b/src/components/application_manager/include/application_manager/policies/policy_event_observer.h
index e251170fec..13f070a1ec 100644
--- a/src/components/application_manager/include/application_manager/policies/policy_event_observer.h
+++ b/src/components/application_manager/include/application_manager/policies/policy_event_observer.h
@@ -30,30 +30,34 @@
POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_POLICY_EVENT_OBSERVER_H_
-#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_POLICY_EVENT_OBSERVER_H_
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_POLICIES_POLICY_EVENT_OBSERVER_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_POLICIES_POLICY_EVENT_OBSERVER_H_
#include "application_manager/event_engine/event_observer.h"
+#include "utils/lock.h"
namespace policy {
namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
-class PolicyHandler;
+class PolicyHandlerInterface;
-class PolicyEventObserver :
- public application_manager::event_engine::EventObserver {
+class PolicyEventObserver
+ : public application_manager::event_engine::EventObserver {
public:
- explicit PolicyEventObserver(policy::PolicyHandler* const policy_handler);
- void set_policy_handler(policy::PolicyHandler* const policy_handler);
+ PolicyEventObserver(
+ policy::PolicyHandlerInterface* const policy_handler,
+ application_manager::event_engine::EventDispatcher& event_dispatcher);
+ void set_policy_handler(policy::PolicyHandlerInterface* const policy_handler);
void on_event(const application_manager::event_engine::Event& event);
void subscribe_on_event(
const application_manager::event_engine::Event::EventID& event_id,
int32_t hmi_correlation_id = 0);
+
private:
sync_primitives::Lock policy_handler_lock_;
- PolicyHandler* policy_handler_;
+ PolicyHandlerInterface* policy_handler_;
void ProcessOdometerEvent(const smart_objects::SmartObject& message);
};
} // namespace policy
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_POLICY_EVENT_OBSERVER_H_
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_POLICIES_POLICY_EVENT_OBSERVER_H_
diff --git a/src/components/application_manager/include/application_manager/policies/policy_handler.h b/src/components/application_manager/include/application_manager/policies/policy_handler.h
index 1fb7d68d25..6f36408444 100644
--- a/src/components/application_manager/include/application_manager/policies/policy_handler.h
+++ b/src/components/application_manager/include/application_manager/policies/policy_handler.h
@@ -37,80 +37,93 @@
#include <map>
#include <set>
#include <vector>
-#include <cstdint>
+#include <list>
+#include <stdint.h>
+
#include "policy/policy_manager.h"
+#include "application_manager/policies/policy_handler_interface.h"
#include "application_manager/policies/policy_event_observer.h"
#include "application_manager/policies/delegates/statistics_delegate.h"
+#include "application_manager/policies/policy_handler_observer.h"
#include "utils/logger.h"
-#include "utils/singleton.h"
#include "utils/threads/thread.h"
#include "utils/threads/thread_delegate.h"
#include "utils/conditional_variable.h"
#include "utils/rwlock.h"
-#include "usage_statistics/statistics_manager.h"
-#include "application_manager/policies/policy_handler_observer.h"
+#include "utils/custom_string.h"
+#include "policy/usage_statistics/statistics_manager.h"
#include "utils/threads/async_runner.h"
-#include "application_manager/application_manager_impl.h"
+#include "policy/policy_settings.h"
namespace Json {
class Value;
}
+namespace application_manager {
+class ApplicationManager;
+}
+
namespace policy {
typedef std::vector<uint32_t> AppIds;
typedef std::vector<uint32_t> DeviceHandles;
-
-class PolicyHandler
- : public utils::Singleton<PolicyHandler,
- utils::deleters::Deleter<PolicyHandler>>,
- public PolicyListener,
- public threads::AsyncRunner {
-public:
+namespace custom_str = utils::custom_string;
+
+class PolicyHandler : public PolicyHandlerInterface,
+ public PolicyListener,
+ public threads::AsyncRunner {
+ public:
+ PolicyHandler(const policy::PolicySettings& get_settings,
+ application_manager::ApplicationManager& application_manager);
virtual ~PolicyHandler();
- bool LoadPolicyLibrary();
- bool PolicyEnabled();
- bool InitPolicyTable();
- bool ResetPolicyTable();
- bool ClearUserConsent();
- bool SendMessageToSDK(const BinaryMessage &pt_string, const std::string &url);
- bool ReceiveMessageFromSDK(const std::string &file,
- const BinaryMessage &pt_string);
- bool UnloadPolicyLibrary();
- virtual void OnPermissionsUpdated(const std::string &policy_app_id,
- const Permissions &permissions,
- const HMILevel &default_hmi);
-
- virtual void OnPermissionsUpdated(const std::string &policy_app_id,
- const Permissions &permissions);
-
- void OnSnapshotCreated(const BinaryMessage &pt_string) OVERRIDE;
-
- bool GetPriority(const std::string &policy_app_id, std::string *priority);
- void CheckPermissions(const PTString &app_id, const PTString &hmi_level,
- const PTString &rpc, const RPCParams &rpc_params,
- CheckPermissionResult &result);
-
- uint32_t GetNotificationsNumber(const std::string &priority);
- DeviceConsent GetUserConsentForDevice(const std::string &device_id);
- bool GetDefaultHmi(const std::string &policy_app_id,
- std::string *default_hmi);
- bool GetInitialAppData(const std::string &application_id,
- StringArray *nicknames = NULL,
- StringArray *app_hmi_types = NULL);
- void GetServiceUrls(const std::string &service_type,
- EndpointUrls &end_points);
-
- std::string GetLockScreenIconUrl() const;
- void ResetRetrySequence();
- uint32_t NextRetryTimeout();
- int TimeoutExchange();
- void OnExceededTimeout();
- void OnSystemReady();
- void PTUpdatedAt(int kilometers, int days_after_epoch);
- void add_listener(PolicyHandlerObserver *listener);
- void remove_listener(PolicyHandlerObserver *listener);
-
- utils::SharedPtr<usage_statistics::StatisticsManager> GetStatisticManager();
+ bool LoadPolicyLibrary() OVERRIDE;
+ bool PolicyEnabled() const OVERRIDE;
+ bool InitPolicyTable() OVERRIDE;
+ bool ResetPolicyTable() OVERRIDE;
+ bool ClearUserConsent() OVERRIDE;
+ bool SendMessageToSDK(const BinaryMessage& pt_string,
+ const std::string& url) OVERRIDE;
+ bool ReceiveMessageFromSDK(const std::string& file,
+ const BinaryMessage& pt_string) OVERRIDE;
+ bool UnloadPolicyLibrary() OVERRIDE;
+ virtual void OnPermissionsUpdated(const std::string& policy_app_id,
+ const Permissions& permissions,
+ const HMILevel& default_hmi) OVERRIDE;
+
+ virtual void OnPermissionsUpdated(const std::string& policy_app_id,
+ const Permissions& permissions) OVERRIDE;
+
+ virtual void OnSnapshotCreated(const BinaryMessage& pt_string) OVERRIDE;
+
+ virtual bool GetPriority(const std::string& policy_app_id,
+ std::string* priority) const OVERRIDE;
+ void CheckPermissions(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ const RPCParams& rpc_params,
+ CheckPermissionResult& result) OVERRIDE;
+
+ uint32_t GetNotificationsNumber(const std::string& priority) const OVERRIDE;
+ virtual DeviceConsent GetUserConsentForDevice(
+ const std::string& device_id) const OVERRIDE;
+ bool GetDefaultHmi(const std::string& policy_app_id,
+ std::string* default_hmi) const OVERRIDE;
+ bool GetInitialAppData(const std::string& application_id,
+ StringArray* nicknames = NULL,
+ StringArray* app_hmi_types = NULL) OVERRIDE;
+ void GetServiceUrls(const std::string& service_type,
+ EndpointUrls& end_points) OVERRIDE;
+ virtual std::string GetLockScreenIconUrl() const OVERRIDE;
+ void ResetRetrySequence() OVERRIDE;
+ uint32_t NextRetryTimeout() OVERRIDE;
+ int TimeoutExchange() OVERRIDE;
+ void OnExceededTimeout() OVERRIDE;
+ void OnSystemReady() OVERRIDE;
+ void PTUpdatedAt(Counters counter, int value) OVERRIDE;
+ void add_listener(PolicyHandlerObserver* listener) OVERRIDE;
+ void remove_listener(PolicyHandlerObserver* listener) OVERRIDE;
+
+ utils::SharedPtr<usage_statistics::StatisticsManager> GetStatisticManager()
+ const OVERRIDE;
/**
* @brief CheckSystemAction allows to check whether certain system
@@ -121,47 +134,56 @@ public:
* @return true if specified system action is enabled, false otherwise.
*/
bool CheckSystemAction(mobile_apis::SystemAction::eType system_action,
- const std::string &policy_app_id);
+ const std::string& policy_app_id) const OVERRIDE;
/**
* Lets client to notify PolicyHandler that more kilometers expired
* @param kms New value of odometer
*/
- void KmsChanged(int kms);
+ void KmsChanged(int kms) OVERRIDE;
/**
* @brief Gather information for application and sends it to HMI
* @param connection_key Connection key for application
*/
- void OnActivateApp(uint32_t connection_key, uint32_t correlation_id);
+ void OnActivateApp(uint32_t connection_key, uint32_t correlation_id) OVERRIDE;
/**
* @brief Process user consent on mobile data connection access
- * @param Device id or 0, if concern to all SDL functionality
+ * @param Device id or empty string, if concern to all SDL functionality
* @param User consent from response
*/
- void OnAllowSDLFunctionalityNotification(bool is_allowed,
- uint32_t device_id = 0);
+ void OnAllowSDLFunctionalityNotification(
+ bool is_allowed, const std::string& device_id) OVERRIDE;
/**
* @brief Increment counter for ignition cycles
*/
- void OnIgnitionCycleOver();
+ void OnIgnitionCycleOver() OVERRIDE;
- void OnPendingPermissionChange(const std::string &policy_app_id);
+ void OnPendingPermissionChange(const std::string& policy_app_id) OVERRIDE;
/**
* Initializes PT exchange at user request
* @param correlation_id correlation id of request
*/
- void PTExchangeAtUserRequest(uint32_t correlation_id);
+ void PTExchangeAtUserRequest(uint32_t correlation_id) OVERRIDE;
+
+ /**
+ * @brief Add's device to policy table
+ * @param device_id Device mac address
+ * @param connection_type Device connection type
+ */
+ void AddDevice(const std::string& device_id,
+ const std::string& connection_type) OVERRIDE;
/**
* @brief Save device info for specific device to policy table
* @param device_id Device mac address
* @param device_info Device params
*/
- void SetDeviceInfo(std::string &device_id, const DeviceInfo &device_info);
+ void SetDeviceInfo(const std::string& device_id,
+ const DeviceInfo& device_info) OVERRIDE;
/**
* @brief Store user-changed permissions consent to DB
@@ -170,7 +192,7 @@ public:
* @param permissions User-changed group permissions consent
*/
void OnAppPermissionConsent(const uint32_t connection_key,
- const PermissionConsent &permissions);
+ const PermissionConsent& permissions) OVERRIDE;
/**
* @brief Get appropriate message parameters and send them with response
@@ -179,9 +201,9 @@ public:
* @param language Language
* @param correlation_id correlation id of request
*/
- void OnGetUserFriendlyMessage(const std::vector<std::string> &message_codes,
- const std::string &language,
- uint32_t correlation_id);
+ void OnGetUserFriendlyMessage(const std::vector<std::string>& message_codes,
+ const std::string& language,
+ uint32_t correlation_id) OVERRIDE;
/**
* @brief Get list of permissions for application/device binded to
@@ -191,32 +213,33 @@ public:
* @param correlation_id Correlation id from request
*/
void OnGetListOfPermissions(const uint32_t connection_key,
- const uint32_t correlation_id);
+ const uint32_t correlation_id) OVERRIDE;
/**
* @brief Get current policy table update state and send response
* @param correlation_id Correlation id from request
*/
- void OnGetStatusUpdate(const uint32_t correlation_id);
+ void OnGetStatusUpdate(const uint32_t correlation_id) OVERRIDE;
/**
* @brief Send notification to HMI with changed policy update status
* @param status Current policy update state
*/
- void OnUpdateStatusChanged(const std::string &status);
+ void OnUpdateStatusChanged(const std::string& status) OVERRIDE;
/**
* @brief Update currently used device id in policies manager for given
* application
* @param policy_app_id Application id
*/
- std::string OnCurrentDeviceIdUpdateRequired(const std::string &policy_app_id);
+ std::string OnCurrentDeviceIdUpdateRequired(
+ const std::string& policy_app_id) OVERRIDE;
/**
* @brief Set parameters from OnSystemInfoChanged to policy table
* @param language System language
*/
- void OnSystemInfoChanged(const std::string &language);
+ void OnSystemInfoChanged(const std::string& language) OVERRIDE;
/**
* @brief Save data from GetSystemInfo request to policy table
@@ -224,116 +247,114 @@ public:
* @param wers_country_code WERS country code
* @param language System language
*/
- void OnGetSystemInfo(const std::string &ccpu_version,
- const std::string &wers_country_code,
- const std::string &language);
+ void OnGetSystemInfo(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language) OVERRIDE;
/**
* @brief Send request to HMI to get update on system parameters
*/
- void OnSystemInfoUpdateRequired() OVERRIDE;
+ virtual void OnSystemInfoUpdateRequired() OVERRIDE;
/**
* @brief Sends GetVehicleData request in case when Vechicle info is ready.
*/
- virtual void OnVIIsReady();
+ virtual void OnVIIsReady() OVERRIDE;
/**
* @brief Allows to update vechicle data info.
* @param SmartObject which contains all needed information.
*/
- virtual void OnVehicleDataUpdated(const smart_objects::SmartObject &message);
+ virtual void OnVehicleDataUpdated(
+ const smart_objects::SmartObject& message) OVERRIDE;
/**
* Removes device
* @param device_id id of device
*/
- void RemoveDevice(const std::string &device_id);
+ void RemoveDevice(const std::string& device_id) OVERRIDE;
/**
* Adds statistics info
* @param type type of info
*/
- void AddStatisticsInfo(int type);
+ void AddStatisticsInfo(int type) OVERRIDE;
/**
* Handles system error
* @param code code of error
*/
- void OnSystemError(int code);
+ void OnSystemError(int code) OVERRIDE;
/**
* @brief Choose application id to be used for snapshot sending
* @return Application id or 0, if there are no applications registered
*/
- uint32_t GetAppIdForSending();
+ uint32_t GetAppIdForSending() const OVERRIDE;
- std::string GetAppName(const std::string &policy_app_id);
+ custom_str::CustomString GetAppName(
+ const std::string& policy_app_id) OVERRIDE;
- void
- OnUpdateHMIAppType(std::map<std::string, StringArray> app_hmi_types) OVERRIDE;
+ virtual void OnUpdateHMIAppType(
+ std::map<std::string, StringArray> app_hmi_types) OVERRIDE;
- void OnCertificateUpdated(const std::string &certificate_data) OVERRIDE;
+ virtual void OnCertificateUpdated(
+ const std::string& certificate_data) OVERRIDE;
- bool CanUpdate() OVERRIDE;
+ virtual bool CanUpdate() OVERRIDE;
- void OnDeviceConsentChanged(const std::string &device_id,
- bool is_allowed) OVERRIDE;
+ virtual void OnDeviceConsentChanged(const std::string& device_id,
+ const bool is_allowed) OVERRIDE;
- virtual void OnPTExchangeNeeded();
+ virtual void SendOnAppPermissionsChanged(
+ const AppPermissions& permissions,
+ const std::string& policy_app_id) const OVERRIDE;
- void GetAvailableApps(std::queue<std::string> &apps) OVERRIDE;
+ virtual void OnPTExchangeNeeded() OVERRIDE;
+
+ virtual void GetAvailableApps(std::queue<std::string>& apps) OVERRIDE;
/**
* @brief Allows to add new or update existed application during
* registration process
* @param application_id The policy aplication id.
*/
- void AddApplication(const std::string &application_id);
+ void AddApplication(const std::string& application_id) OVERRIDE;
/**
* Checks whether application is revoked
* @param app_id id application
* @return true if application is revoked
*/
- bool IsApplicationRevoked(const std::string &app_id);
+ bool IsApplicationRevoked(const std::string& app_id) OVERRIDE;
/**
* @brief Notifies policy manager, that PTS was sent out
*/
- void OnUpdateRequestSentToMobile();
+ void OnUpdateRequestSentToMobile() OVERRIDE;
/**
* Returns heart beat timeout
* @param app_id application id
- * @return if timeout was set then value in seconds greater zero
+ * @return if timeout was set then value in milliseconds greater zero
* otherwise heart beat for specific application isn't set
*/
- uint16_t HeartBeatTimeout(const std::string &app_id) const;
+ uint32_t HeartBeatTimeout(const std::string& app_id) const OVERRIDE;
/**
* @brief Returns URL for querying list of remote apps
*/
- const std::string RemoteAppsUrl() const;
+ const std::string RemoteAppsUrl() const OVERRIDE;
/**
* @brief Handler on applications search started
*/
- void OnAppsSearchStarted();
+ void OnAppsSearchStarted() OVERRIDE;
/**
* @brief Handler on applications search completed
*/
- void OnAppsSearchCompleted();
-
- /**
- * @brief OnAppRegisteredOnMobile alows to handle event when application were
- * succesfully registered on mobile device.
- * It will send OnAppPermissionSend notification and will try to start PTU.
- *
- * @param application_id registered application.
- */
- void OnAppRegisteredOnMobile(const std::string &application_id);
+ void OnAppsSearchCompleted() OVERRIDE;
/**
* @brief Checks if certain request type is allowed for application
@@ -341,34 +362,63 @@ public:
* @param type Request type
* @return true, if allowed, otherwise - false
*/
- bool IsRequestTypeAllowed(const std::string &policy_app_id,
- mobile_apis::RequestType::eType type) const;
+ bool IsRequestTypeAllowed(
+ const std::string& policy_app_id,
+ mobile_apis::RequestType::eType type) const OVERRIDE;
/**
* @brief Gets application request types
* @param policy_app_id Unique application id
* @return request types
*/
- const std::vector<std::string>
- GetAppRequestTypes(const std::string &policy_app_id) const;
+ const std::vector<std::string> GetAppRequestTypes(
+ const std::string& policy_app_id) const OVERRIDE;
+
+ /**
+ * @brief Gets vehicle information
+ * @return Structure with vehicle information
+ */
+ const VehicleInfo GetVehicleInfo() const OVERRIDE;
+
+ /**
+ * @brief OnAppRegisteredOnMobile allows to handle event when application were
+ * succesfully registered on mobile device.
+ * It will send OnAppPermissionSend notification and will try to start PTU.
+ *
+ * @param application_id registered application.
+ */
+ void OnAppRegisteredOnMobile(const std::string& application_id) OVERRIDE;
// TODO(AKutsan) REMOVE THIS UGLY HOTFIX
- virtual void Increment(usage_statistics::GlobalCounterId type);
- virtual void Increment(const std::string &app_id,
- usage_statistics::AppCounterId type);
- virtual void Set(const std::string &app_id, usage_statistics::AppInfoId type,
- const std::string &value);
- virtual void Add(const std::string &app_id,
+ virtual void Increment(usage_statistics::GlobalCounterId type) OVERRIDE;
+ virtual void Increment(const std::string& app_id,
+ usage_statistics::AppCounterId type) OVERRIDE;
+ virtual void Set(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value) OVERRIDE;
+ virtual void Add(const std::string& app_id,
usage_statistics::AppStopwatchId type,
- int32_t timespan_seconds);
+ int32_t timespan_seconds) OVERRIDE;
+
+#ifdef BUILD_TESTS
+ void SetPolicyManager(utils::SharedPtr<PolicyManager> pm) {
+ policy_manager_ = pm;
+ }
+#endif // BUILD_TESTS
+
+#ifdef ENABLE_SECURITY
+ std::string RetrieveCertificate() const OVERRIDE;
+#endif // ENABLE_SECURITY
-protected:
+ const PolicySettings& get_settings() const OVERRIDE;
+
+ protected:
/**
* Starts next retry exchange policy table
*/
void StartNextRetry();
-private:
+ private:
/**
* Checks system action of application for permission of keep context
* @param system_action system action (see mobile api)
@@ -377,7 +427,7 @@ private:
* policy
* otherwise true
*/
- bool CheckKeepContext(const std::string &policy_app_id);
+ bool CheckKeepContext(const std::string& policy_app_id) const;
/**
* Checks system action of application for permission of steal focus
@@ -387,7 +437,7 @@ private:
* policy
* otherwise true
*/
- bool CheckStealFocus(const std::string &policy_app_id);
+ bool CheckStealFocus(const std::string& policy_app_id) const;
/**
* @brief OnAppPermissionConsentInternal reacts on permission changing
@@ -397,47 +447,54 @@ private:
* @param permissions new permissions.
*/
void OnAppPermissionConsentInternal(const uint32_t connection_key,
- PermissionConsent &permissions);
+ PermissionConsent& permissions) OVERRIDE;
+
+ /**
+ * @brief Sets days after epoch on successful policy update
+ */
+ void SetDaysAfterEpoch();
-private:
+ private:
class StatisticManagerImpl : public usage_statistics::StatisticsManager {
+ public:
+ StatisticManagerImpl(PolicyHandler* policy_handler)
+ : policy_handler_(policy_handler) {
+ DCHECK(policy_handler_);
+ }
// TODO(AKutsan) REMOVE THIS UGLY HOTFIX
virtual void Increment(usage_statistics::GlobalCounterId type) {
-
- PolicyHandler::instance()->AsyncRun(new StatisticsDelegate(type));
+ policy_handler_->AsyncRun(new StatisticsDelegate(*policy_handler_, type));
}
- virtual void Increment(const std::string &app_id,
- usage_statistics::AppCounterId type) {
-
- PolicyHandler::instance()->AsyncRun(new StatisticsDelegate(app_id, type));
+ void Increment(const std::string& app_id,
+ usage_statistics::AppCounterId type) {
+ policy_handler_->AsyncRun(
+ new StatisticsDelegate(*policy_handler_, app_id, type));
}
- virtual void Set(const std::string &app_id,
- usage_statistics::AppInfoId type,
- const std::string &value) {
-
- PolicyHandler::instance()->AsyncRun(
- new StatisticsDelegate(app_id, type, value));
+ void Set(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value) {
+ policy_handler_->AsyncRun(
+ new StatisticsDelegate(*policy_handler_, app_id, type, value));
}
- virtual void Add(const std::string &app_id,
- usage_statistics::AppStopwatchId type,
- int32_t timespan_seconds) {
-
- PolicyHandler::instance()->AsyncRun(
- new StatisticsDelegate(app_id, type, timespan_seconds));
+ void Add(const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int32_t timespan_seconds) {
+ policy_handler_->AsyncRun(new StatisticsDelegate(
+ *policy_handler_, app_id, type, timespan_seconds));
}
+
+ private:
+ PolicyHandler* policy_handler_;
};
- // TODO(AKutsan) REMOVE THIS UGLY HOTFIX
- PolicyHandler();
- bool SaveSnapshot(const BinaryMessage &pt_string, std::string &snap_path);
- static PolicyHandler *instance_;
+ bool SaveSnapshot(const BinaryMessage& pt_string, std::string& snap_path);
static const std::string kLibrary;
mutable sync_primitives::RWLock policy_manager_lock_;
utils::SharedPtr<PolicyManager> policy_manager_;
- void *dl_handle_;
+ void* dl_handle_;
AppIds last_used_app_ids_;
utils::SharedPtr<PolicyEventObserver> event_observer_;
uint32_t last_activated_app_id_;
@@ -449,7 +506,7 @@ private:
inline bool CreateManager();
- typedef std::list<PolicyHandlerObserver *> HandlersCollection;
+ typedef std::list<PolicyHandlerObserver*> HandlersCollection;
HandlersCollection listeners_;
sync_primitives::Lock listeners_lock_;
@@ -463,15 +520,13 @@ private:
sync_primitives::Lock app_to_device_link_lock_;
utils::SharedPtr<StatisticManagerImpl> statistic_manager_impl_;
-
+ const PolicySettings& settings_;
+ application_manager::ApplicationManager& application_manager_;
friend class AppPermissionDelegate;
DISALLOW_COPY_AND_ASSIGN(PolicyHandler);
- FRIEND_BASE_SINGLETON_CLASS_WITH_DELETER(
- PolicyHandler, utils::deleters::Deleter<PolicyHandler>);
- FRIEND_DELETER_DESTRUCTOR(PolicyHandler);
};
-} // namespace policy
+} // namespace policy
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_POLICY_HANDLER_H_
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_POLICY_HANDLER_H_
diff --git a/src/components/application_manager/include/application_manager/policies/policy_handler_observer.h b/src/components/application_manager/include/application_manager/policies/policy_handler_observer.h
index c9b32b7e17..794da0cdfb 100644
--- a/src/components/application_manager/include/application_manager/policies/policy_handler_observer.h
+++ b/src/components/application_manager/include/application_manager/policies/policy_handler_observer.h
@@ -33,12 +33,19 @@
#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_POLICY_HANDLER_OBSERVER_H_
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_POLICY_HANDLER_OBSERVER_H_
+#include <vector>
+#include <string>
+#include <map>
+
namespace policy {
-class PolicyHandlerObserver{
- public:
- virtual void OnUpdateHMIAppType(std::map<std::string, std::vector<std::string> > app_hmi_types) = 0;
- virtual void OnCertificateUpdated(const std::string& certificate_data) {}
+class PolicyHandlerObserver {
+ public:
+ virtual void OnUpdateHMIAppType(
+ std::map<std::string, std::vector<std::string> > app_hmi_types) {}
+ virtual bool OnCertificateUpdated(const std::string& certificate_data) {
+ return false;
+ }
virtual ~PolicyHandlerObserver() {}
};
} // namespace policy
diff --git a/src/components/application_manager/include/application_manager/policies/pt_exchange_handler.h b/src/components/application_manager/include/application_manager/policies/pt_exchange_handler.h
index 31f7ded507..4e543eae96 100644
--- a/src/components/application_manager/include/application_manager/policies/pt_exchange_handler.h
+++ b/src/components/application_manager/include/application_manager/policies/pt_exchange_handler.h
@@ -37,10 +37,10 @@
namespace policy {
class PTExchangeHandler {
- public:
- virtual ~PTExchangeHandler() {};
- virtual void Start() = 0;
- virtual void Stop() = 0;
+ public:
+ virtual ~PTExchangeHandler(){};
+ virtual void Start() = 0;
+ virtual void Stop() = 0;
};
} // namespace policy
diff --git a/src/components/application_manager/include/application_manager/request_controller.h b/src/components/application_manager/include/application_manager/request_controller.h
index cddcd72337..237d9f5d8a 100644
--- a/src/components/application_manager/include/application_manager/request_controller.h
+++ b/src/components/application_manager/include/application_manager/request_controller.h
@@ -42,13 +42,13 @@
#include "utils/threads/thread.h"
#include "utils/conditional_variable.h"
#include "utils/threads/thread_delegate.h"
+#include "utils/timer.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
#include "application_manager/request_info.h"
-#include "utils/timer_thread.h"
-
+#include "application_manager/request_controller_settings.h"
namespace application_manager {
@@ -59,233 +59,231 @@ namespace request_controller {
* requests.
*/
class RequestController {
- public:
- /**
- * @brief Result code for addRequest
- */
- enum TResult {
- SUCCESS = 0,
- TOO_MANY_REQUESTS,
- TOO_MANY_PENDING_REQUESTS,
- NONE_HMI_LEVEL_MANY_REQUESTS,
- INVALID_DATA
- };
-
- /**
- * @brief Thread pool state
- */
- enum TPoolState {
- UNDEFINED = 0,
- STARTED,
- STOPPED,
- };
-
- // Methods
-
- /**
- * @brief Class constructor
- *
- */
- RequestController();
-
- /**
- * @brief Class destructor
- *
- */
- virtual ~RequestController();
-
- /**
- * @brief Initialize thread pool
- *
- */
- void InitializeThreadpool();
-
- /**
- * @brief Destroy thread pool
- *
- */
- void DestroyThreadpool();
-
- /**
- * @brief Check if max request amount wasn't exceed and adds request to queue.
- *
- * @param request Active mobile request
- * @param hmi_level Current application hmi_level
- *
- * @return Result code
- *
- */
- TResult addMobileRequest(const RequestPtr request,
- const mobile_apis::HMILevel::eType& hmi_level);
-
-
- /**
- * @brief Store HMI request until response or timeout won't remove it
- *
- * @param request Active hmi request
- * @return Result code
- *
- */
- TResult addHMIRequest(const RequestPtr request);
-
- /**
- * @ Add notification to collection
- *
- * @param ptr Reference to shared pointer that point on hmi notification
- */
- void addNotification(const RequestPtr ptr);
-
-
- /**
- * @brief Removes request from queue
- *
- * @param correlation_id Active request correlation ID,
- * @param connection_key Active request connection key (0 for HMI requersts)
- * @param force_terminate if true, request controller will terminate
- * even if not allowed by request
- */
- void terminateRequest(const uint32_t& correlation_id,
- const uint32_t& connection_key,
- bool force_terminate = false);
-
- /**
- * @brief Removes request from queue
- *
- * @param mobile_correlation_id Active mobile request correlation ID
- *
- */
- void OnMobileResponse(const uint32_t& mobile_correlation_id,
- const uint32_t& connection_key);
-
-
- /**
- * @brief Removes request from queue
- *
- * @param mobile_correlation_id Active mobile request correlation ID
- *
- */
- void OnHMIResponse(const uint32_t& correlation_id);
-
- /**
- * @ Add notification to collection
- *
- * @param ptr Reference to shared pointer that point on hmi notification
- */
- void removeNotification(const commands::Command* notification);
-
- /**
- * @brief Removes all requests from queue for specified application
- *
- * @param app_id Mobile application ID (app_id)
- *
- */
- void terminateAppRequests(const uint32_t& app_id);
-
- /**
- * @brief Terminates all requests from HMI
- */
- void terminateAllHMIRequests();
-
-
- /**
- * @brief Terminates all requests from Mobile
- */
- void terminateAllMobileRequests();
-
- /**
- * @brief Updates request timeout
- *
- * @param app_id Connection key of application
- * @param mobile_correlation_id Correlation ID of the mobile request
- * @param new_timeout_value New timeout to be set in milliseconds
- */
- void updateRequestTimeout(const uint32_t& app_id,
- const uint32_t& mobile_correlation_id,
- const uint32_t& new_timeout);
-
- /*
- * @brief Function Should be called when Low Voltage is occured
- */
- void OnLowVoltage();
-
- /*
- * @brief Function Should be called when Low Voltage is occured
- */
- void OnWakeUp();
-
- bool IsLowVoltage();
-
- protected:
- /**
- * @brief Timer Callback
- */
- void onTimer();
-
- /**
- * @brief Update timout for next OnTimer
- * Not thread safe
- */
- void UpdateTimer();
-
- void terminateWaitingForExecutionAppRequests(const uint32_t& app_id);
- void terminateWaitingForResponseAppRequests(const uint32_t& app_id);
-
- /**
- * @brief Check Posibility to add new requests, or limits was exceeded
- * @param request - request to check possipility to Add
- * @return True if new request could be added, false otherwise
- */
- TResult CheckPosibilitytoAdd(const RequestPtr request);
-
- /**
- * @brief Check Posibility to add new requests, or limits was exceeded
- * @param pending_requests_amount - maximum count of request that should be allowed for all applications
- * @return True if new request could be added, false otherwise
- */
- bool CheckPendingRequestsAmount(const uint32_t& pending_requests_amount);
-
- private:
- class Worker : public threads::ThreadDelegate {
- public:
- explicit Worker(RequestController* requestController);
- virtual ~Worker();
- virtual void threadMain();
- virtual void exitThreadMain();
- protected:
- private:
- RequestController* request_controller_;
- sync_primitives::Lock thread_lock_;
- volatile bool stop_flag_;
- };
-
- std::vector<threads::Thread*> pool_;
- volatile TPoolState pool_state_;
- uint32_t pool_size_;
- sync_primitives::ConditionalVariable cond_var_;
-
- std::list<RequestInfoPtr> mobile_request_info_list_;
- sync_primitives::Lock mobile_request_info_list_lock_;
-
- /*
- * Requests, that are waiting for responses
- * RequestInfoSet provides correct processing of requests with thre same
- * app_id and corr_id
- */
- RequestInfoSet waiting_for_response_;
-
- /**
- * @brief Set of HMI notifications with timeout.
- */
- std::list<RequestPtr> notification_list_;
-
- /*
- * timer for checking requests timeout
- */
- timer::TimerThread<RequestController> timer_;
- static const uint32_t dafault_sleep_time_ = UINT_MAX;
-
- bool is_low_voltage_;
- DISALLOW_COPY_AND_ASSIGN(RequestController);
+ public:
+ /**
+ * @brief Result code for addRequest
+ */
+ enum TResult {
+ SUCCESS = 0,
+ TOO_MANY_REQUESTS,
+ TOO_MANY_PENDING_REQUESTS,
+ NONE_HMI_LEVEL_MANY_REQUESTS,
+ INVALID_DATA
+ };
+
+ /**
+ * @brief Thread pool state
+ */
+ enum TPoolState {
+ UNDEFINED = 0,
+ STARTED,
+ STOPPED,
+ };
+
+ // Methods
+
+ /**
+ * @brief Class constructor
+ *
+ */
+ RequestController(const RequestControlerSettings& settings);
+
+ /**
+ * @brief Class destructor
+ *
+ */
+ virtual ~RequestController();
+
+ /**
+ * @brief Initialize thread pool
+ *
+ */
+ void InitializeThreadpool();
+
+ /**
+ * @brief Destroy thread pool
+ *
+ */
+ void DestroyThreadpool();
+
+ /**
+ * @brief Check if max request amount wasn't exceed and adds request to queue.
+ *
+ * @param request Active mobile request
+ * @param hmi_level Current application hmi_level
+ *
+ * @return Result code
+ *
+ */
+ TResult addMobileRequest(const RequestPtr request,
+ const mobile_apis::HMILevel::eType& hmi_level);
+
+ /**
+ * @brief Store HMI request until response or timeout won't remove it
+ *
+ * @param request Active hmi request
+ * @return Result code
+ *
+ */
+ TResult addHMIRequest(const RequestPtr request);
+
+ /**
+ * @ Add notification to collection
+ *
+ * @param ptr Reference to shared pointer that point on hmi notification
+ */
+ void addNotification(const RequestPtr ptr);
+
+ /**
+ * @brief Removes request from queue
+ *
+ * @param correlation_id Active request correlation ID,
+ * @param connection_key Active request connection key (0 for HMI requersts)
+ * @param force_terminate if true, request controller will terminate
+ * even if not allowed by request
+ */
+ void terminateRequest(const uint32_t& correlation_id,
+ const uint32_t& connection_key,
+ bool force_terminate = false);
+
+ /**
+ * @brief Removes request from queue
+ *
+ * @param mobile_correlation_id Active mobile request correlation ID
+ *
+ */
+ void OnMobileResponse(const uint32_t& mobile_correlation_id,
+ const uint32_t& connection_key);
+
+ /**
+ * @brief Removes request from queue
+ *
+ * @param mobile_correlation_id Active mobile request correlation ID
+ *
+ */
+ void OnHMIResponse(const uint32_t& correlation_id);
+
+ /**
+ * @ Add notification to collection
+ *
+ * @param ptr Reference to shared pointer that point on hmi notification
+ */
+ void removeNotification(const commands::Command* notification);
+
+ /**
+ * @brief Removes all requests from queue for specified application
+ *
+ * @param app_id Mobile application ID (app_id)
+ *
+ */
+ void terminateAppRequests(const uint32_t& app_id);
+
+ /**
+ * @brief Terminates all requests from HMI
+ */
+ void terminateAllHMIRequests();
+
+ /**
+ * @brief Terminates all requests from Mobile
+ */
+ void terminateAllMobileRequests();
+
+ /**
+ * @brief Updates request timeout
+ *
+ * @param app_id Connection key of application
+ * @param mobile_correlation_id Correlation ID of the mobile request
+ * @param new_timeout_value New timeout to be set in milliseconds
+ */
+ void updateRequestTimeout(const uint32_t& app_id,
+ const uint32_t& mobile_correlation_id,
+ const uint32_t& new_timeout);
+
+ /*
+ * @brief Function Should be called when Low Voltage is occured
+ */
+ void OnLowVoltage();
+
+ /*
+ * @brief Function Should be called when Low Voltage is occured
+ */
+ void OnWakeUp();
+
+ bool IsLowVoltage();
+
+ protected:
+ /**
+ * @brief Timer Callback
+ */
+ void onTimer();
+
+ /**
+ * @brief Update timout for next OnTimer
+ * Not thread safe
+ */
+ void UpdateTimer();
+
+ void terminateWaitingForExecutionAppRequests(const uint32_t& app_id);
+ void terminateWaitingForResponseAppRequests(const uint32_t& app_id);
+
+ /**
+ * @brief Check Posibility to add new requests, or limits was exceeded
+ * @param request - request to check possipility to Add
+ * @return True if new request could be added, false otherwise
+ */
+ TResult CheckPosibilitytoAdd(const RequestPtr request);
+
+ /**
+ * @brief Check Posibility to add new requests, or limits was exceeded
+ * @param pending_requests_amount - maximum count of request that should be
+ * allowed for all applications
+ * @return True if new request could be added, false otherwise
+ */
+ bool CheckPendingRequestsAmount(const uint32_t& pending_requests_amount);
+
+ private:
+ class Worker : public threads::ThreadDelegate {
+ public:
+ explicit Worker(RequestController* requestController);
+ virtual ~Worker();
+ virtual void threadMain();
+ virtual void exitThreadMain();
+
+ protected:
+ private:
+ RequestController* request_controller_;
+ sync_primitives::Lock thread_lock_;
+ volatile bool stop_flag_;
+ };
+
+ std::vector<threads::Thread*> pool_;
+ volatile TPoolState pool_state_;
+ uint32_t pool_size_;
+ sync_primitives::ConditionalVariable cond_var_;
+
+ std::list<RequestPtr> mobile_request_list_;
+ sync_primitives::Lock mobile_request_list_lock_;
+
+ /*
+ * Requests, that are waiting for responses
+ * RequestInfoSet provides correct processing of requests with thre same
+ * app_id and corr_id
+ */
+ RequestInfoSet waiting_for_response_;
+
+ /**
+ * @brief Set of HMI notifications with timeout.
+ */
+ std::list<RequestPtr> notification_list_;
+
+ /*
+ * timer for checking requests timeout
+ */
+ timer::Timer timer_;
+
+ bool is_low_voltage_;
+ const RequestControlerSettings& settings_;
+ DISALLOW_COPY_AND_ASSIGN(RequestController);
};
} // namespace request_controller
diff --git a/src/components/application_manager/include/application_manager/request_info.h b/src/components/application_manager/include/application_manager/request_info.h
index 3b48d78d48..193699be78 100644
--- a/src/components/application_manager/include/application_manager/request_info.h
+++ b/src/components/application_manager/include/application_manager/request_info.h
@@ -48,333 +48,327 @@ namespace application_manager {
namespace request_controller {
+/*
+ * @brief Typedef for active mobile request
+ *
+ */
+typedef utils::SharedPtr<commands::Command> RequestPtr;
+
+struct RequestInfo {
+ enum RequestType { MobileRequest, HMIRequest };
+
+ RequestInfo() {}
+ virtual ~RequestInfo() {}
+
+ RequestInfo(RequestPtr request,
+ const RequestType requst_type,
+ const uint64_t timeout_msec)
+ : request_(request)
+ , timeout_msec_(timeout_msec)
+ , hmi_level_(mobile_apis::HMILevel::INVALID_ENUM) {
+ start_time_ = date_time::DateTime::getCurrentTime();
+ updateEndTime();
+ requst_type_ = requst_type;
+ }
+
+ RequestInfo(RequestPtr request,
+ const RequestType requst_type,
+ const TimevalStruct& start_time,
+ const uint64_t timeout_msec);
+
+ void updateEndTime();
+
+ void updateTimeOut(const uint64_t& timeout_msec);
+
+ bool isExpired();
+
+ TimevalStruct start_time() {
+ return start_time_;
+ }
+
+ void update_start_time(TimevalStruct start_time) {
+ start_time_ = start_time;
+ }
+
+ uint64_t timeout_msec() {
+ return timeout_msec_;
+ }
+
+ void set_timeout_msec(uint64_t timeout) {
+ timeout_msec_ = timeout;
+ }
+
+ TimevalStruct end_time() {
+ return end_time_;
+ }
+
+ uint32_t app_id() {
+ return app_id_;
+ }
+
+ mobile_apis::HMILevel::eType hmi_level() {
+ return hmi_level_;
+ }
+
+ void set_hmi_level(const mobile_apis::HMILevel::eType& level) {
+ hmi_level_ = level;
+ }
+
+ RequestType requst_type() const {
+ return requst_type_;
+ }
+
+ uint32_t requestId() {
+ return correlation_id_;
+ }
+
+ commands::Command* request() {
+ return request_.get();
+ }
+ uint64_t hash();
+ static uint64_t GenerateHash(uint32_t var1, uint32_t var2);
+ static uint32_t HmiConnectoinKey;
+
+ protected:
+ RequestPtr request_;
+ TimevalStruct start_time_;
+ uint64_t timeout_msec_;
+ TimevalStruct end_time_;
+ uint32_t app_id_;
+ mobile_apis::HMILevel::eType hmi_level_;
+ RequestType requst_type_;
+ uint32_t correlation_id_;
+};
+
+typedef utils::SharedPtr<RequestInfo> RequestInfoPtr;
+
+struct MobileRequestInfo : public RequestInfo {
+ MobileRequestInfo(RequestPtr request, const uint64_t timeout_msec);
+ MobileRequestInfo(RequestPtr request,
+ const TimevalStruct& start_time,
+ const uint64_t timeout_msec);
+};
+
+struct HMIRequestInfo : public RequestInfo {
+ HMIRequestInfo(RequestPtr request, const uint64_t timeout_msec);
+ HMIRequestInfo(RequestPtr request,
+ const TimevalStruct& start_time,
+ const uint64_t timeout_msec);
+};
+
+// Request info, for searching in request info set by log_n time
+// Returns correct hash by app_id and corr_id
+struct FakeRequestInfo : public RequestInfo {
+ FakeRequestInfo(uint32_t app_id, uint32_t correaltion_id);
+};
+
+struct RequestInfoTimeComparator {
+ bool operator()(const RequestInfoPtr lhs, const RequestInfoPtr rhs) const;
+};
+
+struct RequestInfoHashComparator {
+ bool operator()(const RequestInfoPtr lhs, const RequestInfoPtr rhs) const;
+};
+
+typedef std::set<RequestInfoPtr, RequestInfoTimeComparator>
+ TimeSortedRequestInfoSet;
+typedef std::set<RequestInfoPtr, RequestInfoHashComparator>
+ HashSortedRequestInfoSet;
+
+/*
+ * @brief RequestInfoSet provides uniue requests bu corralation_id and app_id
+ *
+ */
+class RequestInfoSet {
+ public:
/*
- * @brief Typedef for active mobile request
- *
+ * @brief Add requests into colletion by log(n) time
+ * @param request_info - request to add
+ * @return false is request with the same app_id and correlation_id exist
*/
- typedef utils::SharedPtr<commands::Command> RequestPtr;
+ bool Add(RequestInfoPtr request_info);
- struct RequestInfo {
- enum RequestType {MobileRequest, HMIRequest};
+ /*
+ * @brief Find requests int colletion by log(n) time
+ * @param connection_key - connection_key of request
+ * @param correlation_id - correlation_id of request
+ * @return founded request or shared_ptr with NULL
+ */
+ RequestInfoPtr Find(const uint32_t connection_key,
+ const uint32_t correlation_id);
- RequestInfo() {}
- virtual ~RequestInfo() {}
+ /*
+ * @brief Get request with smalest end_time_
+ * @return founded request or shared_ptr with NULL
+ */
+ RequestInfoPtr Front();
- RequestInfo(RequestPtr request,
- const RequestType requst_type,
- const uint64_t timeout_sec)
- : request_(request),
- timeout_sec_(timeout_sec) {
- start_time_ = date_time::DateTime::getCurrentTime();
- updateEndTime();
- requst_type_ = requst_type;
- }
+ /*
+ * @brief Get request with smalest end_time_ != 0
+ * @return founded request or shared_ptr with NULL
+ */
+ RequestInfoPtr FrontWithNotNullTimeout();
- RequestInfo(RequestPtr request, const RequestType requst_type,
- const TimevalStruct& start_time, const uint64_t timeout_sec);
+ /*
+ * @brief Erase request from colletion by log(n) time
+ * @param request_info - request to erase
+ * @return true if Erase succes, otherwise return false
+ */
+ bool RemoveRequest(const RequestInfoPtr request_info);
- void updateEndTime();
+ /*
+ * @brief Erase request from colletion by connection_key
+ * @param connection_key - connection_key of requests to erase
+ * @return count of erased requests
+ */
+ uint32_t RemoveByConnectionKey(uint32_t connection_key);
- void updateTimeOut(const uint64_t& timeout_sec);
+ /*
+ * @brief Erase all mobile requests from controller
+ * @return count of erased requests
+ */
+ uint32_t RemoveMobileRequests();
- bool isExpired();
+ /*
+ * @return count of requestd in collections
+ */
+ const size_t Size();
- TimevalStruct start_time() {
- return start_time_;
- }
+ /**
+ * @brief Check if this app is able to add new requests,
+ * or limits was exceeded
+ * @param app_id - application id
+ * @param app_time_scale - time scale (seconds)
+ * @param max_request_per_time_scale - maximum count of request
+ * that should be allowed for app_time_scale seconds
+ * @return True if new request could be added, false otherwise
+ */
+ bool CheckTimeScaleMaxRequest(uint32_t app_id,
+ uint32_t app_time_scale,
+ uint32_t max_request_per_time_scale);
- void update_start_time(TimevalStruct start_time) {
- start_time_ = start_time;
- }
+ /**
+ * @brief Check if this app is able to add new requests
+ * in current hmi_level, or limits was exceeded
+ * @param hmi_level - hmi level
+ * @param app_id - application id
+ * @param app_time_scale - time scale (seconds)
+ * @param max_request_per_time_scale - maximum count of request
+ * that should be allowed for app_time_scale seconds
+ * @return True if new request could be added, false otherwise
+ */
+ bool CheckHMILevelTimeScaleMaxRequest(mobile_apis::HMILevel::eType hmi_level,
+ uint32_t app_id,
+ uint32_t app_time_scale,
+ uint32_t max_request_per_time_scale);
- uint64_t timeout_sec() {
- return timeout_sec_;
- }
+ private:
+ /*
+ * @brief Comparator of connection key for std::find_if function
+ */
+ struct AppIdCompararator {
+ enum CompareType { Equal, NotEqual };
+ AppIdCompararator(CompareType compare_type, uint32_t app_id)
+ : app_id_(app_id), compare_type_(compare_type) {}
+ bool operator()(const RequestInfoPtr value_compare) const;
+
+ private:
+ uint32_t app_id_;
+ CompareType compare_type_;
+ };
- void set_timeout_sec(uint64_t timeout) {
- timeout_sec_ = timeout;
- }
+ bool Erase(const RequestInfoPtr request_info);
- TimevalStruct end_time() {
- return end_time_;
- }
+ /*
+ * @brief Erase requests from collection if filter allows
+ * @param filter - filtering predicate
+ * @return count of erased requests
+ */
+ uint32_t RemoveRequests(const RequestInfoSet::AppIdCompararator& filter);
- uint32_t app_id() {
- return app_id_;
- }
+ /*
+ * @brief Debug function, will raise assert if set sizes are noit equal
+ */
+ inline void CheckSetSizes();
+ TimeSortedRequestInfoSet time_sorted_pending_requests_;
+ HashSortedRequestInfoSet hash_sorted_pending_requests_;
- mobile_apis::HMILevel::eType hmi_level() {
- return hmi_level_;
- }
+ // the lock caled this_lock_, since the class represent collection by itself.
+ sync_primitives::Lock this_lock_;
+};
- void set_hmi_level(const mobile_apis::HMILevel::eType& level) {
- hmi_level_ = level;
+/**
+* @brief Structure used in std algorithms to determine amount of request
+* during time scale
+*/
+struct TimeScale {
+ TimeScale(const TimevalStruct& start,
+ const TimevalStruct& end,
+ const uint32_t& app_id)
+ : start_(start), end_(end), app_id_(app_id) {}
+
+ bool operator()(RequestInfoPtr setEntry) {
+ if (!setEntry.valid()) {
+ return false;
}
- RequestType requst_type() const {
- return requst_type_;
- }
-
- uint32_t requestId() {
- return correlation_id_;
+ if (setEntry->app_id() != app_id_) {
+ return false;
}
- commands::Command* request() {
- return request_.get();
+ if ((setEntry->start_time() < start_) || (end_ < setEntry->start_time())) {
+ return false;
}
- uint64_t hash();
- static uint64_t GenerateHash(uint32_t var1, uint32_t var2);
- static uint32_t HmiConnectoinKey;
- protected:
- RequestPtr request_;
- TimevalStruct start_time_;
- uint64_t timeout_sec_;
- TimevalStruct end_time_;
- uint32_t app_id_;
- mobile_apis::HMILevel::eType hmi_level_;
- RequestType requst_type_;
- uint32_t correlation_id_;
- };
- typedef utils::SharedPtr<RequestInfo> RequestInfoPtr;
+ return true;
+ }
- struct MobileRequestInfo: public RequestInfo {
- MobileRequestInfo(RequestPtr request,
- const uint64_t timeout_sec);
- MobileRequestInfo(RequestPtr request,
- const TimevalStruct& start_time,
- const uint64_t timeout_sec);
- };
-
- struct HMIRequestInfo: public RequestInfo {
- HMIRequestInfo(RequestPtr request, const uint64_t timeout_sec);
- HMIRequestInfo(RequestPtr request, const TimevalStruct& start_time,
- const uint64_t timeout_sec);
- };
-
- // Request info, for searching in request info set by log_n time
- // Returns correct hash by app_id and corr_id
- struct FakeRequestInfo :public RequestInfo {
- FakeRequestInfo(uint32_t app_id, uint32_t correaltion_id);
- };
-
- struct RequestInfoTimeComparator {
- bool operator() (const RequestInfoPtr lhs,
- const RequestInfoPtr rhs) const;
- };
-
- struct RequestInfoHashComparator {
- bool operator() (const RequestInfoPtr lhs,
- const RequestInfoPtr rhs) const;
- };
-
-
- typedef std::set<RequestInfoPtr, RequestInfoTimeComparator> TimeSortedRequestInfoSet;
- typedef std::set<RequestInfoPtr, RequestInfoHashComparator> HashSortedRequestInfoSet;
-
- /*
- * @brief RequestInfoSet provides uniue requests bu corralation_id and app_id
- *
- */
- class RequestInfoSet {
- public:
- /*
- * @brief Add requests into colletion by log(n) time
- * @param request_info - request to add
- * @return false is request with the same app_id and correlation_id exist
- */
- bool Add(RequestInfoPtr request_info);
-
- /*
- * @brief Find requests int colletion by log(n) time
- * @param connection_key - connection_key of request
- * @param correlation_id - correlation_id of request
- * @return founded request or shared_ptr with NULL
- */
- RequestInfoPtr Find(const uint32_t connection_key,
- const uint32_t correlation_id);
-
- /*
- * @brief Get request with smalest end_time_
- * @return founded request or shared_ptr with NULL
- */
- RequestInfoPtr Front();
-
- /*
- * @brief Get request with smalest end_time_ != 0
- * @return founded request or shared_ptr with NULL
- */
- RequestInfoPtr FrontWithNotNullTimeout();
-
- /*
- * @brief Erase request from colletion by log(n) time
- * @param request_info - request to erase
- * @return true if Erase succes, otherwise return false
- */
- bool RemoveRequest(const RequestInfoPtr request_info);
-
- /*
- * @brief Erase request from colletion by connection_key
- * @param connection_key - connection_key of requests to erase
- * @return count of erased requests
- */
- uint32_t RemoveByConnectionKey(uint32_t connection_key);
-
- /*
- * @brief Erase all mobile requests from controller
- * @return count of erased requests
- */
- uint32_t RemoveMobileRequests();
-
- /*
- * @return count of requestd in collections
- */
- const size_t Size();
-
- /**
- * @brief Check if this app is able to add new requests,
- * or limits was exceeded
- * @param app_id - application id
- * @param app_time_scale - time scale (seconds)
- * @param max_request_per_time_scale - maximum count of request
- * that should be allowed for app_time_scale seconds
- * @return True if new request could be added, false otherwise
- */
- bool CheckTimeScaleMaxRequest(uint32_t app_id,
- uint32_t app_time_scale,
- uint32_t max_request_per_time_scale);
-
- /**
- * @brief Check if this app is able to add new requests
- * in current hmi_level, or limits was exceeded
- * @param hmi_level - hmi level
- * @param app_id - application id
- * @param app_time_scale - time scale (seconds)
- * @param max_request_per_time_scale - maximum count of request
- * that should be allowed for app_time_scale seconds
- * @return True if new request could be added, false otherwise
- */
- bool CheckHMILevelTimeScaleMaxRequest(mobile_apis::HMILevel::eType hmi_level,
- uint32_t app_id,
- uint32_t app_time_scale,
- uint32_t max_request_per_time_scale);
- private:
- /*
- * @brief Comparator of connection key for std::find_if function
- */
- struct AppIdCompararator {
- enum CompareType {Equal, NotEqual};
- AppIdCompararator(CompareType compare_type, uint32_t app_id):
- app_id_(app_id),
- compare_type_(compare_type) {}
- bool operator()(const RequestInfoPtr value_compare) const;
-
- private:
- uint32_t app_id_;
- CompareType compare_type_;
- };
-
- bool Erase(const RequestInfoPtr request_info);
-
- /*
- * @brief Erase requests from collection if filter allows
- * @param filter - filtering predicate
- * @return count of erased requests
- */
- uint32_t RemoveRequests(const RequestInfoSet::AppIdCompararator& filter);
-
- /*
- * @brief Debug function, will raise assert if set sizes are noit equal
- */
- inline void CheckSetSizes();
- TimeSortedRequestInfoSet time_sorted_pending_requests_;
- HashSortedRequestInfoSet hash_sorted_pending_requests_;
-
- // the lock caled this_lock_, since the class represent collection by itself.
- sync_primitives::Lock this_lock_;
- };
+ private:
+ TimevalStruct start_;
+ TimevalStruct end_;
+ uint32_t app_id_;
+};
+/**
+* @brief Structure used in std algorithms to determine amount of request
+* during time scale for application in defined hmi level
+*/
+struct HMILevelTimeScale {
+ HMILevelTimeScale(const TimevalStruct& start,
+ const TimevalStruct& end,
+ const uint32_t& app_id,
+ const mobile_apis::HMILevel::eType& hmi_level)
+ : start_(start), end_(end), app_id_(app_id), hmi_level_(hmi_level) {}
+
+ bool operator()(RequestInfoPtr setEntry) {
+ if (!setEntry.valid()) {
+ return false;
+ }
- /**
- * @brief Structure used in std algorithms to determine amount of request
- * during time scale
- */
- struct TimeScale {
- TimeScale(const TimevalStruct& start,
- const TimevalStruct& end,
- const uint32_t& app_id)
- : start_(start),
- end_(end),
- app_id_(app_id) {}
-
- bool operator()(RequestInfoPtr setEntry) {
- if (!setEntry.valid()) {
- return false;
- }
-
- if (setEntry->app_id() != app_id_) {
- return false;
- }
-
- if (date_time::DateTime::getmSecs(setEntry->start_time())
- < date_time::DateTime::getmSecs(start_) ||
- date_time::DateTime::getmSecs(setEntry->start_time())
- > date_time::DateTime::getmSecs(end_)) {
- return false;
- }
-
- return true;
+ if (setEntry->app_id() != app_id_) {
+ return false;
}
- private:
- TimevalStruct start_;
- TimevalStruct end_;
- uint32_t app_id_;
- };
+ if (setEntry->hmi_level() != hmi_level_) {
+ return false;
+ }
- /**
- * @brief Structure used in std algorithms to determine amount of request
- * during time scale for application in defined hmi level
- */
- struct HMILevelTimeScale {
- HMILevelTimeScale(const TimevalStruct& start,
- const TimevalStruct& end,
- const uint32_t& app_id,
- const mobile_apis::HMILevel::eType& hmi_level)
- : start_(start),
- end_(end),
- app_id_(app_id),
- hmi_level_(hmi_level) {}
-
- bool operator()(RequestInfoPtr setEntry) {
- if (!setEntry.valid()) {
- return false;
- }
-
- if (setEntry->app_id() != app_id_) {
- return false;
- }
-
- if (setEntry->hmi_level() != hmi_level_) {
- return false;
- }
-
- if (date_time::DateTime::getSecs(setEntry->start_time())
- < date_time::DateTime::getSecs(start_) ||
- date_time::DateTime::getSecs(setEntry->start_time())
- > date_time::DateTime::getSecs(end_)) {
- return false;
- }
-
- return true;
+ if (date_time::DateTime::getSecs(setEntry->start_time()) <
+ date_time::DateTime::getSecs(start_) ||
+ date_time::DateTime::getSecs(setEntry->start_time()) >
+ date_time::DateTime::getSecs(end_)) {
+ return false;
}
- private:
- TimevalStruct start_;
- TimevalStruct end_;
- uint32_t app_id_;
- mobile_apis::HMILevel::eType hmi_level_;
- };
+ return true;
+ }
+
+ private:
+ TimevalStruct start_;
+ TimevalStruct end_;
+ uint32_t app_id_;
+ mobile_apis::HMILevel::eType hmi_level_;
+};
} // namespace request_controller
diff --git a/src/components/application_manager/include/application_manager/resume_ctrl.h b/src/components/application_manager/include/application_manager/resume_ctrl.h
deleted file mode 100644
index 4d90316365..0000000000
--- a/src/components/application_manager/include/application_manager/resume_ctrl.h
+++ /dev/null
@@ -1,525 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_RESUME_CTRL_H
-#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_RESUME_CTRL_H
-
-#include <stdint.h>
-#include <vector>
-#include <map>
-#include <set>
-#include <list>
-
-#include "json/json.h"
-#include "interfaces/HMI_API.h"
-#include "interfaces/HMI_API_schema.h"
-#include "interfaces/MOBILE_API_schema.h"
-#include "connection_handler/connection_handler_observer.h"
-#include "connection_handler/device.h"
-#include "application_manager/event_engine/event_observer.h"
-#include "smart_objects/smart_object.h"
-#include "application_manager/application.h"
-#include "utils/timer_thread.h"
-
-namespace application_manager {
-
-namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
-
-class ApplicationManagerImpl;
-class Application;
-class ResumeCtrl: public event_engine::EventObserver {
-
- public:
-
- /**
- * @brief Constructor
- * @param app_mngr ApplicationManager pointer
- */
- explicit ResumeCtrl(ApplicationManagerImpl* app_mngr);
-
- /**
- * @brief Event, that raised if application get resumption response from HMI
- * @param event : event object, that contains smart_object with HMI message
- */
- virtual void on_event(const event_engine::Event& event);
-
- /**
- * @brief Save all applications info to the file system
- */
- void SaveAllApplications();
-
- /**
- * @brief Save application persistent info for future resuming
- * @param application is application witch need to be saved
- */
- void SaveApplication(ApplicationConstSharedPtr application);
-
- /**
- * @brief Set application HMI Level as saved
- * @param application is application witch HMI Level is need to restore
- * @return true if success, otherwise return false
- */
- bool RestoreAppHMIState(ApplicationSharedPtr application);
-
- /**
- * @brief Set application HMI Level as stored in policy
- * @param application is application witch HMI Level is need to setup
- * @return true if success, otherwise return false
- */
- bool SetupDefaultHMILevel(ApplicationSharedPtr application);
-
- /**
- * @brief Setup HmiLevel for application
- * Do routine of setting up hmi_level
- * @param application is application witch HMI Level is need to setup
- * @param hmi_level HMI Level is needed to setup
- * @param hmi_level AudioStreamingState is needed to setup
- * @param check_policy indicate if policy data consent must be verified
- * @return true if success, otherwise return false
- */
- bool SetAppHMIState(ApplicationSharedPtr application,
- const mobile_apis::HMILevel::eType hmi_level,
- bool check_policy = true);
-
- /**
- * @brief Set application HMI Level as saved
- * @param application is application witch HMI Level is need to restore
- * @return true if success, otherwise return false
- */
- bool RestoreApplicationData(ApplicationSharedPtr application);
-
- /**
- * @brief Check if Resume controller have saved instance of application
- * @param application is application witch need to be checked
- * @return true if exist, false otherwise
- */
- bool ApplicationIsSaved(ApplicationConstSharedPtr application);
-
- /**
- * @brief Remove application from list of saved applications
- * @param mobile_app_id application witch need to be removed
- * @return return true, if success, otherwise return false
- */
- bool RemoveApplicationFromSaved(const std::string& mobile_app_id);
-
- /**
- * @brief Increments ignition counter for all registered applications
- * and remember ign_off time stamp
- */
- void Suspend();
-
- /**
- * @brief Increments ignition counter for all registered applications
- * and remember ign_off time stamp
- */
- void OnAwake();
-
- /**
- * @brief Method starts timer "RsmCtrlPercist" when SDL receives onAwakeSDL notification
- */
- void StartSavePersistentDataTimer();
-
- /**
- * @brief Method stops timer "RsmCtrlPercist" when SDL receives OnExitAllApplication notification
- * with reason "SUSPEND"
- */
- void StopSavePersistentDataTimer();
-
- /**
- * @brief Method stops restore_hmi_level_timer_ "RsmCtrlRstore" in Suspend()
- */
- void StopRestoreHmiLevelTimer();
-
- /**
- * @brief Start timer for resumption applications
- * Restore D1-D5 data
- * @param application that is need to be restored
- * @return true if it was saved, otherwise return false
- */
- bool StartResumption(ApplicationSharedPtr application, const std::string& hash);
-
- /**
- * @brief Start timer for resumption applications
- * Does not restore D1-D5 data
- * @param application that is need to be restored
- * @return true if it was saved, otherwise return false
- */
- bool StartResumptionOnlyHMILevel(ApplicationSharedPtr application);
-
- /**
- * @brief Check if there are all files need for resumption
- * @param application that is need to be restored
- * @return true if it all files exist, otherwise return false
- */
- bool CheckPersistenceFilesForResumption(ApplicationSharedPtr application);
-
- /**
- * @brief Check application hash
- * @param application that is need to be restored
- * @return true if it was saved, otherwise return false
- */
- bool CheckApplicationHash(ApplicationSharedPtr application, const std::string& hash);
-
- /**
- * @brief Check if Resume controller have saved application with hmi app id
- * @param hmi_app_id - hmi application id
- * @return true if exist, false otherwise
- */
- bool IsHMIApplicationIdExist(uint32_t hmi_app_id);
-
- /**
- * @brief Check if Resume controller have saved instance of application
- * @param mobile_app_id - mobile application id
- * @return true if exist, false otherwise
- */
- bool IsApplicationSaved(const std::string& mobile_app_id);
-
- /**
- * @brief Function is used for application resume. HMI app ID must be
- * the same(PASA VCA module use it for stored app info).
- * Retrieves HMI app ID for the given mobile app ID from stored information.
- *
- * @param mobile_app_id - mobile application id
- * @return HMI app ID
- */
- uint32_t GetHMIApplicationID(const std::string& mobile_app_id);
-
- /**
- * @brief SaveDataOnTimer :
- * Timer callback for persisting ResumptionData each N seconds
- * N gets from property
- */
- void SaveDataOnTimer();
-
- void ClearResumptionInfo();
-
- void ApplicationsDataUpdated() {
- is_data_saved = false;
- }
-
- /**
- * @brief Resume HMI Level and audio streaming state if needed
- * @param application - application to restore hmi level
- * and audio streaming state
- */
- void StartAppHmiStateResumption(ApplicationSharedPtr application);
- /**
- * @brief Update launch_time_ to current
- */
- void ResetLaunchTime();
-
- private:
-
-
- typedef std::pair<uint32_t, uint32_t> application_timestamp;
-
- std::set<ApplicationSharedPtr> retrieve_application();
-
- /**
- * @brief This struct need to map
- * timestamp and application from correlationID
- */
- struct ResumingApp {
- uint32_t old_session_key; // session key is the same as app_id
- ApplicationSharedPtr app;
- };
-
- struct TimeStampComparator {
- bool operator() (const application_timestamp& lhs,
- const application_timestamp& rhs) const{
- return lhs.second < rhs.second;
- }
- };
-
- /**
- * @brief geter for launch_time_
- * @return value of launch_time_
- */
- time_t launch_time() const;
-
- /**
- * @brief Check device MAC address
- *
- * @param application that is need to be restored
- * @param saved_device_mac Saved device MAC address
- *
- * @return TRUE on success, otherwise FALSE
- */
- bool IsDeviceMacAddressEqual(ApplicationSharedPtr application,
- const std::string& saved_device_mac);
- /**
- * @brief Get Resumption section of LastState
- * @return Resumption section of LastState in Json
- */
- Json::Value& GetResumptionData();
-
- /**
- * @brief Get applications for resumption of LastState
- * @return applications for resumption of LastState
- */
- Json::Value& GetSavedApplications();
-
- /**
- * @brief Get the last ignition off time from LastState
- * @return the last ignition off time from LastState
- */
- time_t GetIgnOffTime();
-
- /**
- * @brief Setup IgnOff time to LastState
- * @param ign_off_time - igition off time
- */
- void SetLastIgnOffTime(time_t ign_off_time);
-
- /**
- * @brief Set applications for resumption to LastState
- * @parems apps_json applications to write in LastState
- */
- void SetSavedApplication(Json::Value& apps_json);
-
- Json::Value GetApplicationCommands(
- ApplicationConstSharedPtr application);
- Json::Value GetApplicationSubMenus(
- ApplicationConstSharedPtr application);
- Json::Value GetApplicationInteractionChoiseSets(
- ApplicationConstSharedPtr application);
- Json::Value GetApplicationGlobalProperties(
- ApplicationConstSharedPtr application);
- Json::Value GetApplicationSubscriptions(
- ApplicationConstSharedPtr application);
- Json::Value GetApplicationFiles(
- ApplicationConstSharedPtr application);
- Json::Value GetApplicationShow(
- ApplicationConstSharedPtr application);
-
- Json::Value JsonFromSO(const smart_objects::SmartObject *so);
-
- uint32_t SendHMIRequest(const hmi_apis::FunctionID::eType& function_id,
- const smart_objects::SmartObject* msg_params = NULL,
- bool use_events = false);
-
- bool ProcessHMIRequest(
- smart_objects::SmartObjectSPtr request = NULL,
- bool use_events = false);
-
- void InsertToTimerQueue(uint32_t app_id, uint32_t time_stamp);
-
- /**
- * @brief AddFiles allows to add files for the application
- * which should be resumed
- *
- * @param application application which will be resumed
- *
- * @param saved_app application specific section from backup file
- */
- void AddFiles(ApplicationSharedPtr application, const Json::Value& saved_app);
-
- /**
- * @brief AddSubmenues allows to add sub menues for the application
- * which should be resumed
- *
- * @param application application which will be resumed
- *
- * @param saved_app application specific section from backup file
- */
- void AddSubmenues(ApplicationSharedPtr application, const Json::Value& saved_app);
-
- /**
- * @brief AddCommands allows to add commands for the application
- * which should be resumed
- *
- * @param application application which will be resumed
- *
- * @param saved_app application specific section from backup file
- */
- void AddCommands(ApplicationSharedPtr application, const Json::Value& saved_app);
-
- /**
- * @brief AddChoicesets allows to add choice sets for the application
- * which should be resumed
- *
- * @param application application which will be resumed
- *
- * @param saved_app application specific section from backup file
- */
- void AddChoicesets(ApplicationSharedPtr application, const Json::Value& saved_app);
-
- /**
- * @brief SetGlobalProperties allows to restore global properties.
- *
- * @param application application which will be resumed
- *
- * @param saved_app application specific section from backup file
- */
- void SetGlobalProperties(ApplicationSharedPtr application, const Json::Value& saved_app);
-
- /**
- * @brief AddSubscriptions allows to restore subscriptions
- *
- * @param application application which will be resumed
- *
- * @param saved_app application specific section from backup file
- */
- void AddSubscriptions(ApplicationSharedPtr application, const Json::Value& saved_app);
-
- /**
- * @brief ProcessHMIRequests allows to process obtained requests.
- *
- * @param requests request that should be processed.
- */
- void ProcessHMIRequests(const smart_objects::SmartObjectList& requests);
-
- /**
- * @brief CheckIcons allows to check application icons
- *
- * @param application application under resumtion application
- *
- * @param json_object
- *
- * @return true in case icons exists, false otherwise
- */
- bool CheckIcons(ApplicationSharedPtr application, const Json::Value& json_object);
-
- /**
- * @brief GetFromSavedOrAppend allows to get existed record about application
- * or adds the new one.
- *
- * @param mobile_app_id application id.
- *
- * @return the reference to the record in applications array.
- */
- Json::Value& GetFromSavedOrAppend(const std::string& mobile_app_id);
-
- /**
- * @brief CheckIgnCycleRestrictions checks if is needed to resume HMI state
- * by ign cycle restrictions
- * @param json_app - saved application
- * @return true if resumptions allowed, otherwise return false
- */
- bool CheckIgnCycleRestrictions(const Json::Value& json_app);
-
- /**
- * @brief DisconnectedInLastIgnCycle should check if was connected in prev ign cycle
- * @param json_app - saved applicationa
- * @return true if app connected in frep ign_cycle otherwise return false
- */
- bool DisconnectedInLastIgnCycle(const Json::Value& json_app);
-
- /**
- * @brief DisconnectedJustBeforeIgnOff should check if application
- * was dissconnected in N secconds delay before ign off.
- * N will be readed from profile
- * @param json_app - saved applicationa
- * @return was dissconnected in N secconds delay before ign off
- * otherwise return false
- */
- bool DisconnectedJustBeforeIgnOff(const Json::Value& json_app);
-
- /**
- * @brief CheckDelayAfterIgnOn should check if SDL was started less
- * then N secconds ago. N will be readed from profile.
- * @return true if SDL started N secconds ago, otherwise return false
- */
- bool CheckDelayAfterIgnOn();
-
- /**
- * @brief CheckAppRestrictions checks if is needed to resume HMI state
- * by application type and saved app_level
- * @param json_app - saved application
- * @return true if resumptions allowed, otherwise return false
- */
- bool CheckAppRestrictions(ApplicationSharedPtr application,
- const Json::Value& json_app);
- /**
- * @brief GetObjectIndex allows to obtain specified obbject index from
- * applications arrays.
- *
- * @param mobile_app_id application id that should be found.
- *
- * @return application's index of or -1 if it doesn't exists
- */
- int GetObjectIndex(const std::string& mobile_app_id);
-
- /**
- * @brief Timer callback for restoring HMI Level
- *
- */
- void ApplicationResumptiOnTimer();
-
- /*
- * @brief Loads data on start up
- */
- void LoadResumeData();
-
- /*
- * @brief Return true if application resumption data is valid,
- * otherwise false
- *
- * @param index application index in the resumption list
- */
- bool IsResumptionDataValid(uint32_t index);
-
- template<typename Iterator>
- Json::Value Append(Iterator first,
- Iterator last,
- const std::string& key,
- Json::Value& result) {
- while (first != last) {
- result[key].append(*first);
- ++first;
- }
- return result;
- }
-
- /**
- * @brief times of IGN_OFF that zombie application have to be saved.
- */
- static const uint32_t kApplicationLifes = 3;
-
- /**
- *@brief Mapping applications to time_stamps
- * wait for timer to resume HMI Level
- *
- */
- mutable sync_primitives::Lock queue_lock_;
- sync_primitives::Lock resumtion_lock_;
- ApplicationManagerImpl* app_mngr_;
- timer::TimerThread<ResumeCtrl> save_persistent_data_timer_;
- timer::TimerThread<ResumeCtrl> restore_hmi_level_timer_;
- std::vector<uint32_t> waiting_for_timer_;
- bool is_resumption_active_;
- bool is_data_saved;
- time_t launch_time_;
-};
-
-} // namespace application_manager
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_RESUME_CTRL_H
diff --git a/src/components/application_manager/include/application_manager/resumption/resume_ctrl.h b/src/components/application_manager/include/application_manager/resumption/resume_ctrl.h
new file mode 100644
index 0000000000..853f91ff23
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/resumption/resume_ctrl.h
@@ -0,0 +1,506 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_RESUME_CTRL_H
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_RESUME_CTRL_H
+
+#include <stdint.h>
+#include <vector>
+#include <map>
+#include <set>
+#include <list>
+
+#include "interfaces/HMI_API.h"
+#include "interfaces/HMI_API_schema.h"
+#include "interfaces/MOBILE_API_schema.h"
+#include "application_manager/event_engine/event_observer.h"
+#include "smart_objects/smart_object.h"
+#include "application_manager/application.h"
+#include "application_manager/resumption/resumption_data.h"
+#include "utils/timer.h"
+
+namespace application_manager {
+class ApplicationManager;
+class Application;
+}
+
+namespace resumption {
+
+class LastState;
+
+/**
+ * @brief Contains logic for storage/restore data of applications.
+ */
+
+class ResumeCtrl : public application_manager::event_engine::EventObserver {
+ public:
+ /**
+ * @brief allows to create ResumeCtrl object
+ */
+ ResumeCtrl(application_manager::ApplicationManager& application_manager);
+
+ /**
+ * @brief allows to destroy ResumeCtrl object
+ */
+ ~ResumeCtrl();
+
+ /**
+ * @brief Event, that raised if application get resumption response from HMI
+ * @param event : event object, that contains smart_object with HMI message
+ */
+ virtual void on_event(const application_manager::event_engine::Event& event);
+
+ /**
+ * @brief Save all applications info to the file system
+ */
+ void SaveAllApplications();
+
+ /**
+ * @brief Save application persistent info for future resuming
+ * @param application is application witch need to be saved
+ */
+ void SaveApplication(application_manager::ApplicationSharedPtr application);
+
+ /**
+ * @brief Set application HMI Level and ausio_state as saved
+ * @param application is application witch HMI Level is need to restore
+ * @return true if success, otherwise return false
+ */
+ bool RestoreAppHMIState(
+ application_manager::ApplicationSharedPtr application);
+
+ /**
+ * @brief Set application HMI Level as stored in policy
+ * @param application is application witch HMI Level is need to setup
+ * @return true if success, otherwise return false
+ */
+ bool SetupDefaultHMILevel(
+ application_manager::ApplicationSharedPtr application);
+
+ /**
+ * @brief Setup HmiLevel for application
+ * Do routine of setting up hmi_level
+ * @param application is application witch HMI Level is need to setup
+ * @param hmi_level HMI Level is needed to setup
+ * @param hmi_level AudioStreamingState is needed to setup
+ * @param check_policy indicate if policy data consent must be verified
+ * @return true if success, otherwise return false
+ */
+ bool SetAppHMIState(application_manager::ApplicationSharedPtr application,
+ const mobile_apis::HMILevel::eType hmi_level,
+ bool check_policy = true);
+
+ /**
+ * @brief Check if Resume controller have saved instance of application
+ * @param application is application witch need to be checked
+ * @return true if exist, false otherwise
+ */
+ bool ApplicationIsSaved(
+ application_manager::ApplicationConstSharedPtr application);
+
+ /**
+ * @brief Remove application from list of saved applications
+ * @param application is application which need to be removed
+ * @return return true, if success, otherwise return false
+ */
+ bool RemoveApplicationFromSaved(
+ application_manager::ApplicationConstSharedPtr application);
+
+ /**
+ * @brief Increments ignition counter for all registered applications
+ * and remember ign_off time stamp
+ */
+ void OnSuspend();
+
+ /**
+ * @brief Increments ignition counter for all registered applications
+ * and remember ign_off time stamp
+ */
+ void OnAwake();
+
+ /**
+ * @brief Method starts timer "RsmCtrlPercist" when
+ * SDL receives onAwakeSDL notification
+ */
+ void StartSavePersistentDataTimer();
+
+ /**
+ * @brief Method stops timer "RsmCtrlPercist" when SDL
+ * receives OnExitAllApplication notification
+ * with reason "SUSPEND"
+ */
+ void StopSavePersistentDataTimer();
+
+ /**
+ * @brief Method stops restore_hmi_level_timer_ "RsmCtrlRstore" in OnSuspend()
+ */
+ void StopRestoreHmiLevelTimer();
+
+ /**
+ * @brief Start timer for resumption applications
+ * Restore D1-D5 data
+ * @param application that is need to be restored
+ * @return true if it was saved, otherwise return false
+ */
+ bool StartResumption(application_manager::ApplicationSharedPtr application,
+ const std::string& hash);
+
+ /**
+ * @brief Start timer for resumption applications
+ * Does not restore D1-D5 data
+ * @param application that is need to be restored
+ * @return true if it was saved, otherwise return false
+ */
+ bool StartResumptionOnlyHMILevel(
+ application_manager::ApplicationSharedPtr application);
+
+ /**
+ * @brief Check if there are all files need for resumption
+ * @param application that is need to be restored
+ * @return true if it all files exist, otherwise return false
+ */
+ bool CheckPersistenceFilesForResumption(
+ application_manager::ApplicationSharedPtr application);
+
+ /**
+ * @brief Check application hash
+ * @param application that is need to be restored
+ * @return true if it was saved, otherwise return false
+ */
+ bool CheckApplicationHash(
+ application_manager::ApplicationSharedPtr application,
+ const std::string& hash);
+
+ /**
+ * @brief Checks if Resume controller have saved application with hmi app id
+ * @param hmi_app_id - hmi application id
+ * @return true if exist, false otherwise
+ */
+ bool IsHMIApplicationIdExist(uint32_t hmi_app_id);
+
+ /**
+ * @brief Check if Resume controller have saved instance of application
+ * @param policy_app_id - mobile application id
+ * @param device_id - id of device where application is run
+ * @return true if exist, false otherwise
+ */
+ bool IsApplicationSaved(const std::string& policy_app_id,
+ const std::string& device_id);
+
+ /**
+ * @brief Function is used for application resume. HMI app ID must be
+ * the same(PASA VCA module use it for stored app info).
+ * Retrieves HMI app ID for the given policy app ID from stored information.
+ * @param policy_app_id - mobile application id
+ * @param device_id - id of device where application is run
+ * @return HMI app ID
+ */
+ uint32_t GetHMIApplicationID(const std::string& policy_app_id,
+ const std::string& device_id) const;
+ /**
+ * @brief SaveDataOnTimer :
+ * Timer callback for persisting ResumptionData each N seconds
+ * N gets from property
+ */
+ void SaveDataOnTimer();
+
+ /**
+ * @brief Updates flag for saving application data
+ */
+ void ApplicationsDataUpdated() {
+ is_data_saved_ = false;
+ }
+
+ /**
+ * @brief Resume HMI Level and audio streaming state if needed
+ * @param application - application to restore hmi level
+ * and audio streaming state
+ */
+ void StartAppHmiStateResumption(
+ application_manager::ApplicationSharedPtr application);
+
+ /**
+ * @brief Update launch_time_ to current
+ */
+ void ResetLaunchTime();
+
+ /**
+ * @brief Timer callback for restoring HMI Level
+ *
+ */
+ void ApplicationResumptiOnTimer();
+
+ /**
+ * @brief Removes activated application from resumption list
+ *
+ * @param application application witch need to be removed from resumption
+ */
+ void OnAppActivated(application_manager::ApplicationSharedPtr application);
+
+ /**
+ * @brief Removes app from resumption list
+ *
+ * app_id Application to remove
+ */
+ void RemoveFromResumption(uint32_t app_id);
+
+ /**
+ * @brief Initialization data for Resume controller
+ * @return true if initialization is success otherwise
+ * returns false
+ */
+ bool Init(LastState& last_state);
+
+ /**
+ * @brief Notify resume controller about new application
+ * @param policy_app_id - mobile application id
+ * @param device_id - id of device where application is run
+ */
+ void OnAppRegistrationStart(const std::string& policy_app_id,
+ const std::string& device_id);
+
+ /**
+ * @brief Notify resume controller about delete new application
+ */
+ void OnAppRegistrationEnd();
+
+#ifdef BUILD_TESTS
+ void set_resumption_storage(utils::SharedPtr<ResumptionData> mock_storage);
+#endif // BUILD_TESTS
+ private:
+ /**
+ * @brief restores saved data of application
+ * @param application contains application for which restores data
+ * @return true if success, otherwise return false
+ */
+ bool RestoreApplicationData(
+ application_manager::ApplicationSharedPtr application);
+
+ /**
+ * @brief AddFiles allows to add files for the application
+ * which should be resumed
+ * @param application application which will be resumed
+ * @param saved_app application specific section from backup file
+ */
+ void AddFiles(application_manager::ApplicationSharedPtr application,
+ const smart_objects::SmartObject& saved_app);
+
+ /**
+ * @brief AddSubmenues allows to add sub menues for the application
+ * which should be resumed
+ * @param application application which will be resumed
+ * @param saved_app application specific section from backup file
+ */
+ void AddSubmenues(application_manager::ApplicationSharedPtr application,
+ const smart_objects::SmartObject& saved_app);
+
+ /**
+ * @brief AddCommands allows to add commands for the application
+ * which should be resumed
+ * @param application application which will be resumed
+ * @param saved_app application specific section from backup file
+ */
+ void AddCommands(application_manager::ApplicationSharedPtr application,
+ const smart_objects::SmartObject& saved_app);
+
+ /**
+ * @brief AddChoicesets allows to add choice sets for the application
+ * which should be resumed
+ * @param application application which will be resumed
+ * @param saved_app application specific section from backup file
+ */
+ void AddChoicesets(application_manager::ApplicationSharedPtr application,
+ const smart_objects::SmartObject& saved_app);
+
+ /**
+ * @brief SetGlobalProperties allows to restore global properties.
+ * @param application application which will be resumed
+ * @param saved_app application specific section from backup file
+ */
+ void SetGlobalProperties(
+ application_manager::ApplicationSharedPtr application,
+ const smart_objects::SmartObject& saved_app);
+
+ /**
+ * @brief AddSubscriptions allows to restore subscriptions
+ * @param application application which will be resumed
+ * @param saved_app application specific section from backup file
+ */
+ void AddSubscriptions(application_manager::ApplicationSharedPtr application,
+ const smart_objects::SmartObject& saved_app);
+
+ /**
+ * @brief AddWayPointsSubscription allows to restore subscription
+ * for WayPoints
+ * @param application application which will be resumed
+ * @param saved_app application specific section from backup file
+ */
+ void AddWayPointsSubscription(
+ application_manager::ApplicationSharedPtr application,
+ const smart_objects::SmartObject& saved_app);
+
+ bool CheckIgnCycleRestrictions(const smart_objects::SmartObject& saved_app);
+
+ bool DisconnectedJustBeforeIgnOff(
+ const smart_objects::SmartObject& saved_app);
+
+ bool CheckAppRestrictions(
+ application_manager::ApplicationConstSharedPtr application,
+ const smart_objects::SmartObject& saved_app);
+
+ /**
+ * @brief CheckIcons allows to check application icons
+ * @param application application under resumtion application
+ * @param json_object
+ * @return true in case icons exists, false otherwise
+ */
+ bool CheckIcons(application_manager::ApplicationSharedPtr application,
+ smart_objects::SmartObject& obj);
+
+ /**
+ * @brief CheckDelayAfterIgnOn should check if SDL was started less
+ * then N secconds ago. N will be readed from profile.
+ * @return true if SDL started N secconds ago, otherwise return false
+ */
+ bool CheckDelayAfterIgnOn();
+
+ typedef std::pair<uint32_t, uint32_t> ApplicationTimestamp;
+
+ std::set<application_manager::ApplicationSharedPtr> retrieve_application();
+
+ /**
+ * @brief This struct need to map
+ * timestamp and application from correlationID
+ */
+ struct ResumingApp {
+ uint32_t old_session_key; // session key is the same as app_id
+ application_manager::ApplicationSharedPtr app;
+ };
+
+ struct TimeStampComparator {
+ bool operator()(const ApplicationTimestamp& lhs,
+ const ApplicationTimestamp& rhs) const {
+ return lhs.second < rhs.second;
+ }
+ };
+
+ /**
+ * @brief geter for launch_time_
+ * @return value of launch_time_
+ */
+ time_t launch_time() const;
+
+ /**
+ * @brief Check device MAC address
+ * @param application that is need to be restored
+ * @param saved_device_mac Saved device MAC address
+ * @return TRUE on success, otherwise FALSE
+ */
+ bool IsDeviceMacAddressEqual(
+ application_manager::ApplicationSharedPtr application,
+ const std::string& saved_device_mac);
+
+ /**
+ * @brief Get the last ignition off time from LastState
+ * @return the last ignition off time from LastState
+ */
+ time_t GetIgnOffTime();
+
+ /**
+ * @brief Setup IgnOff time to LastState
+ * @param ign_off_time - igition off time
+ */
+ void SetLastIgnOffTime(time_t ign_off_time);
+
+ /**
+ * @brief Process specified HMI request
+ * @param request Request to process
+ * @param use_events Process request events or not flag
+ * @return TRUE on success, otherwise FALSE
+ */
+ bool ProcessHMIRequest(smart_objects::SmartObjectSPtr request = NULL,
+ bool use_events = false);
+
+ /**
+ * @brief Process list of HMI requests using ProcessHMIRequest method
+ * @param requests List of requests to process
+ */
+ void ProcessHMIRequests(const smart_objects::SmartObjectList& requests);
+
+ void InsertToTimerQueue(uint32_t app_id, uint32_t time_stamp);
+
+ void AddToResumptionTimerQueue(const uint32_t app_id);
+
+ void LoadResumeData();
+
+ /**
+ * @brief Checks, if application data needs to be resumed
+ * @param application Application data from storage
+ * @return true, if data resumption must be skipped, otherwise - false
+ */
+ bool IsAppDataResumptionExpired(
+ const smart_objects::SmartObject& application) const;
+ /**
+ * @brief Checks from resume data, if application has been disconnected
+ * unexpectedly
+ * @param app Application section from resume data
+ * @return true, if it has been unexpectedly disconnected, otherwise - false
+ */
+ bool IsUnexpectedlyDisconnected(const smart_objects::SmartObject& app) const;
+
+ /**
+ * @brief Checks, if application can be resumed
+ * @param application Application
+ * @return true, if no restrictions currently, otherwise - false
+ */
+ bool IsResumeAllowed(
+ const application_manager::ApplicationSharedPtr application) const;
+
+ /**
+ *@brief Mapping applications to time_stamps
+ * wait for timer to resume HMI Level
+ *
+ */
+ mutable sync_primitives::Lock queue_lock_;
+ timer::Timer restore_hmi_level_timer_;
+ timer::Timer save_persistent_data_timer_;
+ typedef std::list<uint32_t> WaitingForTimerList;
+ WaitingForTimerList waiting_for_timer_;
+ bool is_resumption_active_;
+ bool is_data_saved_;
+ time_t launch_time_;
+ utils::SharedPtr<ResumptionData> resumption_storage_;
+ application_manager::ApplicationManager& application_manager_;
+};
+
+} // namespace resumption
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_RESUME_CTRL_H
diff --git a/src/components/application_manager/include/application_manager/resumption/resumption_data.h b/src/components/application_manager/include/application_manager/resumption/resumption_data.h
new file mode 100644
index 0000000000..469be2c902
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/resumption/resumption_data.h
@@ -0,0 +1,274 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_RESUMPTION_RESUMPTION_DATA_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_RESUMPTION_RESUMPTION_DATA_H_
+
+#include "smart_objects/smart_object.h"
+#include "application_manager/application.h"
+#include "application_manager/application_manager.h"
+
+namespace application_manager {
+class ApplicationManagerSettings;
+}
+
+namespace resumption {
+
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+namespace app_mngr = application_manager;
+
+/**
+ * @brief Abstract class which provides an interface for storage/restore
+ * application data. Contains methods for receiving application data
+ * from application.
+ */
+
+class ResumptionData {
+ public:
+ /**
+ * @brief Constructor of ResumptionData
+ */
+ ResumptionData(
+ const application_manager::ApplicationManager& application_manager);
+
+ /**
+ * @brief Destructor of ResumptionData
+ */
+ virtual ~ResumptionData() {}
+
+ /**
+ * @brief Save application persistent info for future resuming
+ * @param application is application witch need to be saved
+ */
+ virtual void SaveApplication(app_mngr::ApplicationSharedPtr application) = 0;
+
+ /**
+ * @brief Checks if saved data of applications have hmi app id
+ * @param hmi_app_id - hmi application id
+ * @return true if exist, false otherwise
+ */
+ virtual bool IsHMIApplicationIdExist(uint32_t hmi_app_id) const = 0;
+
+ /**
+ * @brief Retrieves HMI app ID for the given mobile app ID
+ * and device ID from stored information.
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return HMI app ID
+ */
+ virtual uint32_t GetHMIApplicationID(const std::string& policy_app_id,
+ const std::string& device_id) const = 0;
+
+ /**
+ * @brief Increments ignition counter for all registered applications
+ * and remember ign_off time stamp
+ */
+ virtual void OnSuspend() = 0;
+
+ /**
+ * @brief Retrieves hash ID for the given mobile app ID
+ * and device ID from stored information.
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param hash_id - parameter which will contain HASH id from saved
+ * application
+ * @return TRUE if application will be found in saved data otherwise
+ * returns FALSE
+ */
+ virtual bool GetHashId(const std::string& policy_app_id,
+ const std::string& device_id,
+ std::string& hash_id) const = 0;
+
+ /**
+ * @brief Increments ignition counter for all registered applications
+ * and remember ign_off time stamp
+ */
+ virtual void OnAwake() = 0;
+
+ /**
+ * @brief Retrieves data of saved application for the given mobile app ID
+ * and device ID
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param saved_app - parameter which will contain data of saved application
+ * @return TRUE if application will be found in saved data otherwise
+ * returns FALSE
+ */
+ virtual bool GetSavedApplication(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const = 0;
+
+ /**
+ * @brief Remove application from list of saved applications
+ * @param policy_app_id application which need to be removed
+ * @param device_id - contains id of device on which is running application
+ * @return return true, if success, otherwise return false
+ */
+ virtual bool RemoveApplicationFromSaved(const std::string& policy_app_id,
+ const std::string& device_id) = 0;
+
+ /**
+ * @brief Get the last ignition off time from LastState
+ * @return the last ignition off time from LastState
+ */
+ virtual uint32_t GetIgnOffTime() const = 0;
+
+ /**
+ * @brief Checks if saved data have application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return index if data of application exists, otherwise returns -1
+ */
+ virtual ssize_t IsApplicationSaved(const std::string& policy_app_id,
+ const std::string& device_id) const = 0;
+
+ /**
+ * @brief Retrieves data from saved application
+ * @param saved_data - will be contain data for resume_ctrl
+ */
+ virtual void GetDataForLoadResumeData(
+ smart_objects::SmartObject& saved_data) const = 0;
+
+ /**
+ * @brief Updates HMI level of saved application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param hmi_level - contains hmi level for saved application
+ */
+ virtual void UpdateHmiLevel(const std::string& policy_app_id,
+ const std::string& device_id,
+ mobile_apis::HMILevel::eType hmi_level) = 0;
+
+ /**
+ * @brief Init storage
+ */
+ virtual bool Init() = 0;
+
+ /**
+ * @brief Drops data related to applicaton data resumption
+ * @param device_id Device ID
+ * @param app_id Application ID
+ * @return true, if dropped successfully, otherwise - false
+ */
+ virtual bool DropAppDataResumption(const std::string& device_id,
+ const std::string& app_id) = 0;
+
+ /**
+ * @brief Persist saves resumption data on file system
+ */
+ virtual void Persist() = 0;
+
+ protected:
+ /**
+ * @brief Retrieves of commands from application
+ * @param application contains application of which selection commands
+ * @return list of commands
+ */
+ smart_objects::SmartObject GetApplicationCommands(
+ app_mngr::ApplicationConstSharedPtr application) const;
+
+ /**
+ * @brief Retrieves of submenues from application
+ * @param application contains application of which selection submenues
+ * @return list of submenues
+ */
+ smart_objects::SmartObject GetApplicationSubMenus(
+ app_mngr::ApplicationConstSharedPtr application) const;
+
+ /**
+ * @brief Retrieves of interactionChoiceSet from application
+ * @param application contains application of which selection
+ * interactionChoiceSet
+ * @return list of interaction choice set
+ */
+ smart_objects::SmartObject GetApplicationInteractionChoiseSets(
+ app_mngr::ApplicationConstSharedPtr application) const;
+
+ /**
+ * @brief Retrieves of global properties from application
+ * @param application contains application of which selection global
+ * properties
+ * @return global properties of application
+ */
+ smart_objects::SmartObject GetApplicationGlobalProperties(
+ app_mngr::ApplicationConstSharedPtr application) const;
+
+ /**
+ * @brief Retrieves of subscriptions from application
+ * @param application contains application of which selection subscriptions
+ * @return subscriptions of application
+ */
+ smart_objects::SmartObject GetApplicationSubscriptions(
+ app_mngr::ApplicationConstSharedPtr application) const;
+
+ /**
+ * @brief Retrieves of files from application
+ * @param application contains application of which selection files
+ * @return files of application
+ */
+ smart_objects::SmartObject GetApplicationFiles(
+ app_mngr::ApplicationConstSharedPtr application) const;
+
+ /**
+ * @brief checks pointer that it is not equal NULL
+ * @param ptr - contains pointer which need to check
+ * @return smartObject from pointer
+ */
+ smart_objects::SmartObject PointerToSmartObj(
+ const smart_objects::SmartObject* ptr) const;
+
+ /**
+ * @brief Creates smart array from received data
+ * @param first - iterator points to beginning of the data
+ * @param last - iterator points to ending of the data
+ * @param key - contains smart array's name
+ * @param result - will contain created array
+ */
+ template <typename Iterator>
+ void Append(Iterator first,
+ Iterator last,
+ const std::string& key,
+ smart_objects::SmartObject& result) const {
+ int i = 0;
+ result[key] = smart_objects::SmartObject(smart_objects::SmartType_Array);
+ while (first != last) {
+ result[key][i++] = *first;
+ ++first;
+ }
+ }
+ mutable sync_primitives::Lock resumption_lock_;
+ const application_manager::ApplicationManager& application_manager_;
+};
+} // namespace resumption
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_RESUMPTION_RESUMPTION_DATA_H_
diff --git a/src/components/application_manager/include/application_manager/resumption/resumption_data_db.h b/src/components/application_manager/include/application_manager/resumption/resumption_data_db.h
new file mode 100644
index 0000000000..d08ecc2ae1
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/resumption/resumption_data_db.h
@@ -0,0 +1,838 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_RESUMPTION_RESUMPTION_DATA_DB_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_RESUMPTION_RESUMPTION_DATA_DB_H_
+#include "application_manager/resumption/resumption_data.h"
+
+#include "sql_database.h"
+#include "sql_query.h"
+
+namespace resumption {
+
+/**
+ * @brief Points what structure contains vr commands
+ */
+enum AccessoryVRCommand { kVRCommandFromChoice = 0, kVRCommandFromCommand };
+
+struct ApplicationParams {
+ ApplicationParams(const smart_objects::SmartObject& application);
+ ApplicationParams(app_mngr::ApplicationSharedPtr application);
+
+ std::string m_hash;
+ int64_t m_grammar_id;
+ int64_t m_connection_key;
+ int64_t m_hmi_app_id;
+ mobile_apis::HMILevel::eType m_hmi_level;
+ bool m_is_media_application;
+ bool m_is_valid;
+};
+
+/**
+ * @brief Show should database be saved in a disk file or in memory
+ */
+enum DbStorage { In_Memory_Storage = 0, In_File_Storage };
+
+/**
+ * @brief class contains logic for representation application data in
+ * data base
+ */
+class ResumptionDataDB : public ResumptionData {
+ public:
+ /**
+ * @brief Constructor of ResumptionDataDB
+ * @param db_storage show database should be saved in a disk file or in memory
+ */
+ ResumptionDataDB(
+ DbStorage db_storage,
+ const application_manager::ApplicationManager& application_manager);
+
+ /**
+ * @brief allows to destroy ResumptionDataDB object
+ */
+ virtual ~ResumptionDataDB();
+
+ /**
+ * @brief Creates or opens DB and initialize it
+ * @return false if DB doesn't initialize
+ * otherwise returns true
+ */
+ virtual bool Init();
+
+ /**
+ * @brief Save application persistent info for future resuming to db
+ * @param application is application which need to be saved
+ */
+ void SaveApplication(app_mngr::ApplicationSharedPtr application) OVERRIDE;
+ /**
+ * @brief Checks if saved data of applications have hmi app id
+ * @param hmi_app_id - hmi application id
+ * @return true if exist, otherwise false
+ */
+ virtual bool IsHMIApplicationIdExist(uint32_t hmi_app_id) const;
+ /**
+ * @brief Retrieves HMI app ID for the given mobile app ID
+ * and device ID from stored data.
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return HMI app ID
+ */
+ virtual uint32_t GetHMIApplicationID(const std::string& policy_app_id,
+ const std::string& device_id) const;
+
+ /**
+ * @brief Increments ignition counter for all registered applications
+ * and remember ign_off time stamp
+ */
+ virtual void OnSuspend();
+
+ /**
+ * @brief Retrieves hash ID for the given mobile app ID
+ * and device ID from stored information.
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param hash_id - parameter which will contain HASH id from saved
+ * application
+ * @return TRUE if application will be found in saved data otherwise
+ * returns FALSE
+ */
+ virtual bool GetHashId(const std::string& policy_app_id,
+ const std::string& device_id,
+ std::string& hash_id) const;
+
+ /**
+ * @brief Decrements ignition counter for all registered applications
+ * and remember ign_off time stamp
+ */
+ virtual void OnAwake();
+
+ /**
+ * @brief Retrieves data of saved application for the given mobile app ID
+ * and device ID
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param saved_app - parameter which will contain data of saved application
+ * @return TRUE if application will be found in saved data otherwise
+ * returns FALSE
+ */
+ virtual bool GetSavedApplication(const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const;
+
+ /**
+ * @brief Remove application from list of saved applications
+ * @param policy_app_id application witch need to be removed
+ * @param device_id - contains id of device on which is running application
+ * @return return true, if success, otherwise return false
+ */
+ virtual bool RemoveApplicationFromSaved(const std::string& policy_app_id,
+ const std::string& device_id);
+
+ /**
+ * @brief Get the last ignition off time from LastState
+ * @return the last ignition off time from LastState
+ */
+ virtual uint32_t GetIgnOffTime() const;
+
+ /**
+ * @brief Checks if saved data have application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return 0 if saved data contains application otherwise returns -1
+ */
+ virtual ssize_t IsApplicationSaved(const std::string& policy_app_id,
+ const std::string& device_id) const;
+
+ /**
+ * @brief Retrieves data from saved application
+ * @param will contain data for resume_ctrl
+ */
+ virtual void GetDataForLoadResumeData(
+ smart_objects::SmartObject& saved_data) const;
+
+ /**
+ * @brief Updates HMI level of saved application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param hmi_level - contains hmi level for saved application
+ */
+ virtual void UpdateHmiLevel(const std::string& policy_app_id,
+ const std::string& device_id,
+ mobile_apis::HMILevel::eType hmi_level);
+
+ /**
+ * @brief Re-creates and re-init DB
+ * @return true if success, otherwise - false
+ */
+ bool RefreshDB() const;
+
+ /**
+ * @brief Gets all the data from DB to memory
+ * @param data Object which holds resumption data
+ * @return true if success, otherwise - false
+ */
+ bool GetAllData(smart_objects::SmartObject& data) const;
+
+ /**
+ * @brief Saves all the data to DB
+ * @param data Object, which holds resumption data
+ * @return true if success, otherwise - false
+ */
+ bool SaveAllData(const smart_objects::SmartObject& data);
+
+ /**
+ * @brief Checks, if DB version is actual to current schema
+ * @return true if success, otherwise - false
+ */
+ bool IsDBVersionActual() const;
+
+ /**
+ * @brief Updates DB version accordingly to current schema
+ * @return true if success, otherwise - false
+ */
+ bool UpdateDBVersion() const;
+
+ bool DropAppDataResumption(const std::string& device_id,
+ const std::string& app_id) OVERRIDE;
+ /**
+ * @brief Write json resumption info to file system
+ */
+ void Persist() OVERRIDE;
+
+ protected:
+ /**
+ * @brief returns pointer to data base
+ */
+ utils::dbms::SQLDatabase* db() const;
+
+ private:
+ /**
+ * @brief Calculates DB version from current schema
+ * @return version
+ */
+ const int32_t GetDBVersion() const;
+
+ /**
+ * @brief Retrieves hmi level from db
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param hmi_level - will contains hmi level for saved application
+ * @return true if application with mobile id and device id has hmi level
+ * otherwise returns false
+ */
+ bool SelectHMILevel(const std::string& policy_app_id,
+ const std::string& device_id,
+ int& hmi_level) const;
+ /**
+ * @brief Checks existence HMI id in DB
+ * @param hmi_app_id - HMI id
+ * return true if hmiID is same with saved hmiID otherwise returns false
+ */
+ bool CheckExistenceHMIId(uint32_t hmi_app_id) const;
+
+ /**
+ * @brief Select HMI id from saved application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param hmi_id - will contains hmi id from saved application
+ */
+ void SelectHMIId(const std::string& policy_app_id,
+ const std::string& device_id,
+ uint32_t& hmi_id) const;
+
+ /**
+ * @brief Select hash id from saved application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param hash_id - will contains hash id from saved application
+ */
+ bool SelectHashId(const std::string& policy_app_id,
+ const std::string& device_id,
+ std::string& hash_id) const;
+
+ /**
+ * @brief Select Ign off time
+ * @return Ign off time from saved data
+ */
+ uint32_t SelectIgnOffTime() const;
+
+ /**
+ * @brief Checks existence application in DB
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param application_exist will contain true if restored data contain
+ * application
+ * otherwise will contain false
+ * return if we have problem with access to DB returns FALSE otherwise
+ * returns TRUE
+ */
+ bool CheckExistenceApplication(const std::string& policy_app_id,
+ const std::string& device_id,
+ bool& application_exist) const;
+
+ /**
+ * @brief Retrieves data from saved application
+ * @param will contain data for resume_ctrl
+ */
+ void SelectDataForLoadResumeData(
+ smart_objects::SmartObject& saved_data) const;
+
+ /**
+ * @brief Deletes saved application from db
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return true if application data was deleted otherwise returns
+ * false
+ */
+ bool DeleteSavedApplication(const std::string& policy_app_id,
+ const std::string& device_id);
+
+ /**
+ * @brief Deletes file from saved application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return true if data was deleted otherwise returns
+ * false
+ */
+ bool DeleteSavedFiles(const std::string& policy_app_id,
+ const std::string& device_id);
+
+ /**
+ * @brief Deletes submenu from saved application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return true if data was deleted otherwise returns
+ * false
+ */
+ bool DeleteSavedSubMenu(const std::string& policy_app_id,
+ const std::string& device_id);
+
+ /**
+ * @brief Deletes subscriptions from saved application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return true if data was deleted otherwise returns
+ * false
+ */
+ bool DeleteSavedSubscriptions(const std::string& policy_app_id,
+ const std::string& device_id);
+
+ /**
+ * @brief Deletes commands from saved application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return true if data was deleted otherwise returns
+ * false
+ */
+ bool DeleteSavedCommands(const std::string& policy_app_id,
+ const std::string& device_id);
+
+ /**
+ * @brief Deletes choice set from saved application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return true if data was deleted otherwise returns
+ * false
+ */
+ bool DeleteSavedChoiceSet(const std::string& policy_app_id,
+ const std::string& device_id);
+
+ /**
+ * @brief Deletes global properties from saved application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return true if data was deleted otherwise returns
+ * false
+ */
+ bool DeleteSavedGlobalProperties(const std::string& policy_app_id,
+ const std::string& device_id);
+ /**
+ * @brief Deletes data from application table
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return true if data was deleted otherwise returns
+ * false
+ */
+ bool DeleteDataFromApplicationTable(const std::string& policy_app_id,
+ const std::string& device_id);
+
+ /**
+ * @brief Saves files data to DB
+ * @param files contains data for saving
+ * @param application_primary_key - primary key from DB table application
+ * @return true if data was saved successfully otherwise returns
+ * false
+ */
+ bool InsertFilesData(const smart_objects::SmartObject& files,
+ int64_t application_primary_key) const;
+
+ /**
+ * @brief Saves submenu data to DB
+ * @param submenus contains data for saving
+ * @param application_primary_key - primary key from DB table application
+ * @return true if data was saved successfully otherwise returns
+ * false
+ */
+ bool InsertSubMenuData(const smart_objects::SmartObject& submenus,
+ int64_t application_primary_key) const;
+
+ /**
+ * @brief Saves commands data to DB
+ * @param commands contains data for saving
+ * @param application_primary_key - primary key from DB table application
+ * @return true if data was saved successfully otherwise returns
+ * false
+ */
+ bool InsertCommandsData(const smart_objects::SmartObject& commands,
+ int64_t application_primary_key) const;
+
+ /**
+ * @brief Saves subscriptions data to DB
+ * @param subscriptions contains data for saving
+ * @param application_primary_key - primary key from DB table application
+ * @return true if data was saved successfully otherwise returns
+ * false
+ */
+ bool InsertSubscriptionsData(const smart_objects::SmartObject& subscriptions,
+ int64_t application_primary_key) const;
+
+ /**
+ * @brief Saves choice set data to DB
+ * @param choicesets contains data for saving
+ * @param application_primary_key - primary key from DB table application
+ * @return true if data was saved successfully otherwise returns
+ * false
+ */
+ bool InsertChoiceSetData(const smart_objects::SmartObject& choicesets,
+ int64_t application_primary_key) const;
+
+ /**
+ * @brief Saves globalProperties data to DB
+ * @param global_properties contains data for saving
+ * @param global_properties_key - will contain primary key from global
+ * properties table
+ * @return true if data was saved successfully otherwise returns
+ * false
+ */
+ bool InsertGlobalPropertiesData(
+ const smart_objects::SmartObject& global_properties,
+ int64_t& global_properties_key) const;
+
+ /**
+ * @brief Saves application data to DB
+ * @param application contains data for saving
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return true if application data was saved successfully
+ * otherwise returns false
+ */
+ bool SaveApplicationToDB(app_mngr::ApplicationSharedPtr application,
+ const std::string& policy_app_id,
+ const std::string& device_id) const;
+
+ bool SaveApplicationToDB(const smart_objects::SmartObject& application,
+ const std::string& policy_app_id,
+ const std::string& device_id) const;
+
+ /**
+ * @brief Updates ignition of count on saved applications after onAwake
+ * notification
+ */
+ void UpdateDataOnAwake();
+
+ /**
+ * @brief Execute query for delete data of application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param text_query - contains text of query
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool ExecQueryToDeleteData(const std::string& policy_app_id,
+ const std::string& device_id,
+ const std::string& text_query);
+
+ /**
+ * @brief Execute union query for delete data of application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param text_query - contains text of query
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool ExecUnionQueryToDeleteData(const std::string& policy_app_id,
+ const std::string& device_id,
+ const std::string& text_query);
+
+ /**
+ * @brief Execute query in order to insert image to DB
+ * @param image_primary_key - will contain primary key from image table
+ * @param image contains data for saving to DB
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool ExecInsertImage(int64_t& image_primary_key,
+ const smart_objects::SmartObject& image) const;
+
+ /**
+ * @brief Execute query in order to insert choice to DB
+ * @param choice_set_key - contain primary key from
+ * applicationChoiceSet table
+ * @param choice_array contains data for saving to DB
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool ExecInsertChoice(int64_t choice_set_key,
+ const smart_objects::SmartObject& choice_array) const;
+
+ /**
+ * @brief Execute query in order to insert vr commands to DB
+ * @param primary_key - will contain primary key from command table or
+ * choice table
+ * @param vr_commands_array contains data for saving to DB
+ * @param value indicates which structure contains vrcommands
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool ExecInsertVrCommands(const int64_t primary_key,
+ const smart_objects::SmartObject& vr_commands_array,
+ AccessoryVRCommand value) const;
+
+ /**
+ * @brief Execute query in order to insert choice set data to DB
+ * @param choice_set_primary_key - will contain primary key from
+ * applicationChoiceSet table
+ * @param choiceset contains data for saving to DB
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool ExecInsertApplicationChoiceSet(
+ int64_t& choice_set_primary_key,
+ const smart_objects::SmartObject& choiceset) const;
+
+ /**
+ * @brief combines primary key from several table to new table
+ * @param first_primary_key - will contain primary key from first DB table
+ * @param second_primary_key - will contain primary key from second DB table
+ * @param text_query - contains text of query
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool ExecInsertDataToArray(int64_t first_primary_key,
+ int64_t second_primary_key,
+ const std::string& text_query) const;
+
+ /**
+ * @brief Execute query in order to insert characters array to DB
+ * @param global_properties_key contains primary key from globalproperties
+ * table
+ * @param characters_array contains data for saving to DB
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool ExecInsertLimitedCharacters(
+ int64_t global_properties_key,
+ const smart_objects::SmartObject& characters_array) const;
+
+ /**
+ * @brief Execute query in order to insert vr help item array to DB
+ * @param global_properties_key contains primary key from globalproperties
+ * table
+ * @param vrhelp_array contains data for saving to DB
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool ExecInsertVRHelpItem(
+ int64_t global_properties_key,
+ const smart_objects::SmartObject& vrhelp_array) const;
+
+ /**
+ * @brief Execute query in order to insert data to ttsChunk table
+ * @param tts_chunk contains data for saving to DB
+ * @param tts_chunk_key will contain primary key from ttsChunk table
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool ExecInsertTTSChunks(const smart_objects::SmartObject& tts_chunk,
+ int64_t& tts_chunk_key) const;
+
+ /**
+ * @brief Execute query in order to insert data to helpTimeoutPromptArray
+ * @param global_properties contains data for saving to DB
+ * @param global_properties_key contains primary key from globalproperties
+ * table
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool ExecInsertHelpTimeoutArray(
+ const smart_objects::SmartObject& global_properties,
+ int64_t global_properties_key) const;
+
+ /**
+ * @brief Execute query in order to insert or update data in application table
+ * @param application contains data for saving to DB
+ * @param policy_app_id contains mobile application id of application
+ * @param device_id contains id of device on which is running application
+ * @param application_primary_key will contain primary key from application
+ * table
+ * @param global_properties_key contains primary key from globalproperties
+ * table
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool InsertApplicationData(const ApplicationParams& application,
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ int64_t* application_primary_key,
+ int64_t global_properties_key) const;
+
+ /**
+ * @brief Calls InsertApplicationData method
+ * @param application contains data for saving to DB
+ * @param policy_app_id contains mobile application id of application
+ * @param device_id contains id of device on which is running application
+ * @return true if InsertApplicationData works successfully, otherwise
+ * returns false;
+ */
+ bool InsertApplicationData(app_mngr::ApplicationSharedPtr application,
+ const std::string& policy_app_id,
+ const std::string& device_id);
+
+ /**
+ * @brief Delete application data where ign_off_count >= application_lifes
+ * @param application_lifes contains amount ign off
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool DeleteAppWithIgnCount(const int application_lifes);
+
+ /**
+ * @brief Selects data from file table
+ * @param policy_app_id contains mobile application id of application
+ * @param device_id contains id of device on which is running application
+ * @param saved_app will contain data from file table
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool SelectFilesData(const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const;
+
+ /**
+ * @brief Selects data from subMenu table
+ * @param policy_app_id contains mobile application id of application
+ * @param device_id contains id of device on which is running application
+ * @param saved_app will contain data from subMenu table
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool SelectSubmenuData(const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const;
+
+ /**
+ * @brief Selects data from commands table
+ * @param policy_app_id contains mobile application id of application
+ * @param device_id contains id of device on which is running application
+ * @param saved_app will contain commands
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool SelectCommandData(const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const;
+
+ /**
+ * @brief Selects data from applicationSubscribtionsArray table
+ * @param policy_app_id contains mobile application id of application
+ * @param device_id contains id of device on which is running application
+ * @param saved_app will contain subscriptions
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool SelectSubscriptionsData(const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const;
+
+ /**
+ * @brief Selects choice set data from DB
+ * @param policy_app_id contains mobile application id of application
+ * @param device_id contains id of device on which is running application
+ * @param saved_app will contain choiceSets
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool SelectChoiceSetData(const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const;
+
+ /**
+ * @brief Selects global properties data from DB
+ * @param policy_app_id contains mobile application id of application
+ * @param device_id contains id of device on which is running application
+ * @param saved_app will contain global properties
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool SelectGlobalPropertiesData(const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const;
+
+ /**
+ * @brief Selects image data from DB
+ * @param image_key primary key from image table
+ * @param image will contain image data from DB
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool SelectImageData(int64_t image_key,
+ smart_objects::SmartObject& image) const;
+
+ /**
+ * @brief Selects ttsChunk data from DB
+ * @param tts_chunk_key primary key from ttsChunk table
+ * @param tts_chunk will contain ttsChunk data from DB
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool SelectTTSChunkData(int64_t tts_chunk_key,
+ smart_objects::SmartObject& tts_chunk) const;
+
+ /**
+ * @brief Selects VR help items data from DB
+ * @param global_properties_key primary key from global properties table
+ * @param global_properties will contain VR help items
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool SelectVrHelpItemsData(
+ int64_t global_properties_key,
+ smart_objects::SmartObject& global_properties) const;
+
+ /**
+ * @brief Selects table limited character data from DB
+ * @param global_properties_key primary key from global properties table
+ * @param keyboard_properties will contain table limited character
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool SelectCharactersData(
+ int64_t global_properties_key,
+ smart_objects::SmartObject& keyboard_properties) const;
+
+ /**
+ * @brief Selects data from application table of DB
+ * @param policy_app_id contains mobile application id of application
+ * @param device_id contains id of device on which is running application
+ * @param saved_app will contain data from application table
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool SelectDataFromAppTable(const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const;
+
+ /**
+ * @brief Selects count from array table
+ * @param count_item will contain amount item in table
+ * @param text_query - contains text of query
+ * @param policy_app_id contains mobile application id of application
+ * @param device_id contains id of device on which is running application
+ * @return true if query was run successfully otherwise returns
+ * false
+ */
+ bool SelectCountFromArray(uint32_t& count_item,
+ const std::string& text_query,
+ const std::string& policy_app_id,
+ const std::string& device_id) const;
+
+ /**
+ * @brief Binds data from smart object with query
+ * @param key contains key from smart object
+ * @param so contains data which needs to bind with query
+ * @param query object of query for DB
+ * @param pos contains position for binding query
+ */
+ void CustomBind(const std::string& key,
+ const smart_objects::SmartObject& so,
+ utils::dbms::SQLQuery& query,
+ const int pos) const;
+
+ /**
+ * @brief prepare and bind the same type query
+ * @param query object of query for DB
+ * @param policy_app_id contains mobile application id of application
+ * @param device_id contains id of device on which is running application
+ * @param text_query - contains text of query
+ * @return true if query was binded successfully otherwise returns
+ * false
+ */
+ bool PrepareSelectQuery(utils::dbms::SQLQuery& query,
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ const std::string& text_query) const;
+
+ /**
+ * @brief Updates HMI level and time stamp in application table
+ * @param application contains data for saving
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return true if application data were updated successfully
+ * otherwise returns false
+ */
+ bool UpdateApplicationData(app_mngr::ApplicationConstSharedPtr application,
+ const std::string& policy_app_id,
+ const std::string& device_id);
+
+ /**
+ * @brief Writes data to DB after update
+ */
+ void WriteDb();
+
+ /**
+ * @brief Updates grammarID for application
+ * @param policy_app_id Application ID
+ * @param device_id Device ID
+ * @param grammar_id GrammarID
+ * @return true if succedeed, otherwise - false
+ */
+ bool UpdateGrammarID(const std::string& policy_app_id,
+ const std::string& device_id,
+ const uint32_t grammar_id);
+
+ DISALLOW_COPY_AND_ASSIGN(ResumptionDataDB);
+
+ utils::dbms::SQLDatabase* db_;
+};
+} // namespace resumption
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_RESUMPTION_RESUMPTION_DATA_DB_H_
diff --git a/src/components/application_manager/include/application_manager/resumption/resumption_data_json.h b/src/components/application_manager/include/application_manager/resumption/resumption_data_json.h
new file mode 100644
index 0000000000..0be6d64db2
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/resumption/resumption_data_json.h
@@ -0,0 +1,235 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_RESUMPTION_RESUMPTION_DATA_JSON_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_RESUMPTION_RESUMPTION_DATA_JSON_H_
+
+#include "application_manager/resumption/resumption_data.h"
+#include "json/json.h"
+#include "resumption/last_state.h"
+
+namespace resumption {
+
+/**
+ * @brief class contains logic for representation application data in
+ * json file
+ */
+class ResumptionDataJson : public ResumptionData {
+ public:
+ /**
+ * @brief Constructor of ResumptionDataJson
+ */
+ ResumptionDataJson(
+ LastState& last_state,
+ const application_manager::ApplicationManager& application_manager);
+
+ /**
+ * @brief allows to destroy ResumptionDataJson object
+ */
+ virtual ~ResumptionDataJson();
+
+ /**
+ * @brief Save application persistent info for future resuming on json format
+ * @param application is application witch need to be saved
+ */
+ virtual void SaveApplication(
+ app_mngr::ApplicationSharedPtr application) OVERRIDE;
+
+ /**
+ * @brief Checks if saved data of applications have hmi app id
+ * @param hmi_app_id - hmi application id
+ * @return true if exist, false otherwise
+ */
+ virtual bool IsHMIApplicationIdExist(uint32_t hmi_app_id) const;
+
+ /**
+ * @brief Retrieves HMI app ID for the given mobile app ID
+ * and device ID from stored information.
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return HMI app ID
+ */
+ virtual uint32_t GetHMIApplicationID(const std::string& policy_app_id,
+ const std::string& device_id) const;
+
+ /**
+ * @brief Increments ignition counter for all registered applications
+ * and remember ign_off time stamp
+ */
+ virtual void OnSuspend();
+
+ /**
+ * @brief Increments ignition counter for all registered applications
+ * and remember ign_off time stamp
+ */
+ virtual void OnAwake();
+
+ /**
+ * @brief Retrieves hash ID for the given mobile app ID
+ * and device ID from stored information.
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param hash_id - parameter which will contain HASH id from saved
+ * application
+ * @return TRUE if application will be found in saved data otherwise
+ * returns FALSE
+ */
+ virtual bool GetHashId(const std::string& policy_app_id,
+ const std::string& device_id,
+ std::string& hash_id) const;
+
+ /**
+ * @brief Retrieves data of saved application for the given mobile app ID
+ * and device ID
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param saved_app - parameter which will contain data of saved application
+ * @return TRUE if application will be found in saved data otherwise
+ * returns FALSE
+ */
+ virtual bool GetSavedApplication(const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const;
+
+ /**
+ * @brief Remove application from list of saved applications
+ * @param policy_app_id application witch need to be removed
+ * @param device_id - contains id of device on which is running application
+ * @return return true, if success, otherwise return false
+ */
+ virtual bool RemoveApplicationFromSaved(const std::string& policy_app_id,
+ const std::string& device_id);
+
+ /**
+ * @brief Get the last ignition off time from LastState
+ * @return the last ignition off time from LastState
+ */
+ virtual uint32_t GetIgnOffTime() const;
+
+ /**
+ * @brief Checks if saved data have application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @return index if data of application exists, otherwise returns -1
+ */
+ virtual ssize_t IsApplicationSaved(const std::string& policy_app_id,
+ const std::string& device_id) const;
+
+ /**
+ * @brief Retrieves data from saved application
+ * @param will be contain data for resume_ctrl
+ */
+ virtual void GetDataForLoadResumeData(
+ smart_objects::SmartObject& saved_data) const;
+
+ /**
+ * @brief Updates HMI level of saved application
+ * @param policy_app_id - mobile application id
+ * @param device_id - contains id of device on which is running application
+ * @param hmi_level - contains hmi level for saved application
+ */
+ virtual void UpdateHmiLevel(const std::string& policy_app_id,
+ const std::string& device_id,
+ mobile_apis::HMILevel::eType hmi_level);
+
+ virtual bool Init();
+
+ bool DropAppDataResumption(const std::string& device_id,
+ const std::string& app_id) OVERRIDE;
+
+ /**
+ * @brief Write json resumption info to file system
+ */
+ void Persist() OVERRIDE;
+
+ resumption::LastState& last_state() const {
+ return last_state_;
+ }
+
+ private:
+ /**
+ * @brief GetFromSavedOrAppend allows to get existed record about application
+ * or adds the new one.
+ * @param policy_app_id application id.
+ * @param device_id unique id of device.
+ * @return the reference to the record in applications array.
+ */
+ Json::Value& GetFromSavedOrAppend(const std::string& policy_app_id,
+ const std::string& device_id) const;
+
+ /**
+ * @brief Get applications for resumption of LastState
+ * @return applications for resumption of LastState
+ */
+ Json::Value& GetSavedApplications() const;
+
+ /**
+ * @brief Get Resumption section of LastState
+ * @return Resumption section of LastState in Json
+ */
+ Json::Value& GetResumptionData() const;
+
+ /**
+ * @brief GetObjectIndex allows to obtain specified object index from
+ * applications arrays.
+ * @param policy_app_id application id that should be found.
+ * @param device_id unique id of device.
+ * @return application's index of or -1 if it doesn't exists
+ */
+ ssize_t GetObjectIndex(const std::string& policy_app_id,
+ const std::string& device_id) const;
+
+ /**
+ * @brief Set applications for resumption to LastState
+ * @parems apps_json applications to write in LastState
+ */
+ void SetSavedApplication(Json::Value& apps_json);
+
+ /**
+ * @brief Setup IgnOff time to LastState
+ * @param ign_off_time - igition off time
+ */
+ void SetLastIgnOffTime(time_t ign_off_time);
+
+ /*
+ * @brief Return true if application resumption data is valid,
+ * otherwise false
+ * @param index application index in the resumption list
+ */
+ bool IsResumptionDataValid(uint32_t index) const;
+
+ LastState& last_state_;
+ DISALLOW_COPY_AND_ASSIGN(ResumptionDataJson);
+};
+} // namespace resumption
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_RESUMPTION_RESUMPTION_DATA_JSON_H_
diff --git a/src/components/application_manager/include/application_manager/resumption/resumption_sql_queries.h b/src/components/application_manager/include/application_manager/resumption/resumption_sql_queries.h
new file mode 100644
index 0000000000..3f8ca3a416
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/resumption/resumption_sql_queries.h
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2013, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_RESUMPTION_RESUMPTION_SQL_QUERY_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_RESUMPTION_RESUMPTION_SQL_QUERY_H_
+
+#include <string>
+
+namespace resumption {
+
+extern const std::string kCreateSchema;
+extern const std::string kDropSchema;
+extern const std::string kInsertInitData;
+extern const std::string kChecksResumptionData;
+extern const std::string kSelectCountHMILevel;
+extern const std::string kSelectHMILevel;
+extern const std::string kCheckHMIId;
+extern const std::string kSelectHMIId;
+extern const std::string kSelectCountHMIId;
+extern const std::string kCountHashId;
+extern const std::string kSelectHashId;
+extern const std::string kSelectIgnOffTime;
+extern const std::string kCheckApplication;
+extern const std::string kCountApplications;
+extern const std::string kSelectDataForLoadResumeData;
+extern const std::string kUpdateHMILevel;
+extern const std::string kUpdateIgnOffCount;
+extern const std::string kCountApplicationsIgnOff;
+extern const std::string kSelectApplicationsIgnOffCount;
+extern const std::string kUpdateSuspendData;
+extern const std::string KUpdateLastIgnOffTime;
+extern const std::string kDeleteFile;
+extern const std::string kDeleteApplicationFilesArray;
+extern const std::string kDeleteSubMenu;
+extern const std::string kDeleteApplicationSubMenuArray;
+extern const std::string kDeleteApplicationSubscribtionsArray;
+extern const std::string kDeleteImageFromCommands;
+extern const std::string kDeleteVrCommands;
+extern const std::string kDeleteCommands;
+extern const std::string kDeleteApplicationCommandsArray;
+extern const std::string kDeleteImageFromChoiceSet;
+extern const std::string kDeleteVrCommandsFromChoiceSet;
+extern const std::string kDeleteChoice;
+extern const std::string kDeleteChoiceArray;
+extern const std::string kDeleteApplicationChoiceSet;
+extern const std::string kDeleteApplicationChoiceSetArray;
+extern const std::string kDeleteImageFromGlobalProperties;
+extern const std::string kDeletevrHelpItem;
+extern const std::string kDeletevrHelpItemArray;
+extern const std::string kDeleteTableLimitedCharacterList;
+extern const std::string kDeleteCharacterArray;
+extern const std::string kDeleteTTSChunk;
+extern const std::string kDeleteFromApplicationTable;
+extern const std::string kDeleteHelpTimeoutPromptArray;
+extern const std::string kDeleteGlobalProperties;
+extern const std::string kSelectCountImage;
+extern const std::string kSelectPrimaryKeyImage;
+extern const std::string kInsertImage;
+extern const std::string kInsertToFile;
+extern const std::string kInsertToApplicationFilesArray;
+extern const std::string kInsertToSubMenu;
+extern const std::string kInsertToApplicationSubMenuArray;
+extern const std::string kInsertToVrCommandsArray;
+extern const std::string kInsertToCommand;
+extern const std::string kInsertApplicationCommandArray;
+extern const std::string kInsertVrCommand;
+extern const std::string kInsertSubscriptions;
+extern const std::string kInsertChoice;
+extern const std::string kInsertApplicationChoiceSet;
+extern const std::string kInsertChoiceArray;
+extern const std::string kInsertApplicationChoiceSetArray;
+extern const std::string kInsertGlobalProperties;
+extern const std::string kInsertTableLimitedCharacter;
+extern const std::string kInsertCharacterArray;
+extern const std::string kInsertVRHelpItem;
+extern const std::string kInsertVRHelpItemArray;
+extern const std::string kInsertHelpTimeoutPromptArray;
+extern const std::string kInsertTTSChunk;
+extern const std::string kInsertApplication;
+extern const std::string kSelectCountFiles;
+extern const std::string kSelectFiles;
+extern const std::string kSelectCountSubMenu;
+extern const std::string kSelectSubMenu;
+extern const std::string kSelectCountCommands;
+extern const std::string kSelectCommands;
+extern const std::string kSelectCountSubscriptions;
+extern const std::string kSelectSubscriptions;
+extern const std::string kSelectCountChoiceSet;
+extern const std::string kSelectChoiceSets;
+extern const std::string kSelectImage;
+extern const std::string kSelectCountGlobalProperties;
+extern const std::string kSelectGlobalProperties;
+extern const std::string kChecksVrHelpItem;
+extern const std::string kSelectVrHelpItem;
+extern const std::string kChecksCharacter;
+extern const std::string kSelectCharacter;
+extern const std::string kSelectTTSChunk;
+extern const std::string kSelectAppTable;
+extern const std::string kSelectAllApps;
+extern const std::string kUpdateApplicationData;
+extern const std::string kSelectDBVersion;
+extern const std::string kUpdateDBVersion;
+extern const std::string kUpdateGrammarID;
+extern const std::string kInsertSubscribedForWayPoints;
+extern const std::string kSelectSubscribedForWayPoints;
+extern const std::string kDeleteSubscribedForWayPoints;
+} // namespace resumption
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_RESUMPTION_RESUMPTION_SQL_QUERY_H_
diff --git a/src/components/application_manager/include/application_manager/smart_object_keys.h b/src/components/application_manager/include/application_manager/smart_object_keys.h
index cebac3fef3..1fda170c34 100644
--- a/src/components/application_manager/include/application_manager/smart_object_keys.h
+++ b/src/components/application_manager/include/application_manager/smart_object_keys.h
@@ -37,381 +37,400 @@ namespace application_manager {
namespace strings {
-const char params[] = "params";
-const char message_type[] = "message_type";
-const char correlation_id[] = "correlation_id";
-const char function_id[] = "function_id";
-const char protocol_version[] = "protocol_version";
-const char protocol_type[] = "protocol_type";
-const char connection_key[] = "connection_key";
-const char error[] = "error";
-const char error_msg[] = "message";
-const char default_app_id[] = "default";
-const char msg_params[] = "msg_params";
-const char method_name[] = "methodName";
-const char info[] = "info";
-const char app_id[] = "appID";
-const char hmi_app_id[] = "hmiAppID";
-const char device_mac[] = "deviceMAC";
-const char url[] = "url";
-const char urlScheme[] = "urlScheme";
-const char packageName[] = "packageName";
-const char cmd_icon[] = "cmdIcon";
-const char result_code[] = "resultCode";
-const char success[] = "success";
-const char sync_msg_version[] = "syncMsgVersion";
-const char major_version[] = "majorVersion";
-const char minor_version[] = "minorVersion";
-const char app_name[] = "appName";
-const char ngn_media_screen_app_name[] = "ngnMediaScreenAppName";
-const char vr_synonyms[] = "vrSynonyms";
-const char uses_vehicle_data[] = "usesVehicleData";
-const char is_media_application[] = "isMediaApplication";
-const char greyOut[] = "greyOut";
-const char language_desired[] = "languageDesired";
-const char auto_activated_id[] = "autoActivateID";
-const char app_type[] = "appType";
-const char app_hmi_type[] = "appHMIType";
-const char tts_name[] = "ttsName";
-const char binary_data[] = "binary_data";
-const char timeout_prompt[] = "timeoutPrompt";
-const char timeout[] = "timeout";
-const char vr_help_title[] = "vrHelpTitle";
-const char vr_help[] = "vrHelp";
-const char main_field_1[] = "mainField1";
-const char main_field_2[] = "mainField2";
-const char main_field_3[] = "mainField3";
-const char main_field_4[] = "mainField4";
-const char eta[] = "eta";
-const char time_to_destination[] = "timeToDestination";
-const char total_distance[] = "totalDistance";
-const char alignment[] = "alignment";
-const char graphic[] = "graphic";
-const char secondary_graphic[] = "secondaryGraphic";
-const char status_bar[] = "statusBar";
-const char media_clock[] = "mediaClock";
-const char media_track[] = "mediaTrack";
-const char properties[] = "properties";
-const char cmd_id[] = "cmdID";
-const char menu_params[] = "menuParams";
-const char menu_title[] = "menuTitle";
-const char menu_icon[] = "menuIcon";
-const char keyboard_properties[] = "keyboardProperties";
-const char vr_commands[] = "vrCommands";
-const char position[] = "position";
-const char num_ticks[] = "numTicks";
-const char slider_footer[] = "sliderFooter";
-const char menu_id[] = "menuID";
-const char menu_name[] = "menuName";
-const char interaction_choice_set_id[] = "interactionChoiceSetID";
-const char interaction_choice_set_id_list[] = "interactionChoiceSetIDList";
-const char choice_set[] = "choiceSet";
-const char choice_id[] = "choiceID";
-const char grammar_id[] = "grammarID";
-const char navigation_text_1[] = "navigationText1";
-const char navigation_text_2[] = "navigationText2";
-const char alert_text1[] = "alertText1";
-const char alert_text2[] = "alertText2";
-const char alert_text3[] = "alertText3";
-const char tts_chunks[] = "ttsChunks";
-const char initial_prompt[] = "initialPrompt";
-const char initial_text[] = "initialText";
-const char duration[] = "duration";
-const char progress_indicator[] = "progressIndicator";
-const char alert_type[] = "alertType";
-const char play_tone[] = "playTone";
-const char soft_buttons[] = "softButtons";
-const char soft_button_id[] = "softButtonID";
-const char custom_presets[] = "customPresets";
-const char audio_pass_display_text1[] = "audioPassThruDisplayText1";
-const char audio_pass_display_text2[] = "audioPassThruDisplayText2";
-const char max_duration[] = "maxDuration";
-const char sampling_rate[] = "samplingRate";
-const char bits_per_sample[] = "bitsPerSample";
-const char audio_type[] = "audioType";
-const char mute_audio[] = "muteAudio";
-const char button_name[] = "buttonName";
-const char button_event_mode[] = "buttonEventMode";
-const char button_press_mode[] = "buttonPressMode";
-const char custom_button_id[] = "customButtonID";
-const char data_type[] = "dataType";
-const char turn_list[] = "turnList";
-const char turn_icon[] = "turnIcon";
-const char next_turn_icon[] = "nextTurnIcon";
-const char value[] = "value";
-const char hmi_display_language[] = "hmiDisplayLanguage";
-const char language[] = "language";
-const char data[] = "data";
-const char start_time[] = "startTime";
-const char end_time[] = "endTime";
-const char hours[] = "hours";
-const char minutes[] = "minutes";
-const char seconds [] = "seconds";
-const char update_mode[] = "updateMode";
-const char trigger_source[] = "triggerSource";
-const char hmi_level[] = "hmiLevel";
-const char activate_app_hmi_level[] = "level";
-const char audio_streaming_state[] = "audioStreamingState";
-const char system_context[] = "systemContext";
-const char speech_capabilities[] = "speechCapabilities";
-const char vr_capabilities[] = "vrCapabilities";
-const char audio_pass_thru_capabilities[] = "audioPassThruCapabilities";
+extern const char* params;
+extern const char* message_type;
+extern const char* correlation_id;
+extern const char* function_id;
+extern const char* protocol_version;
+extern const char* protocol_type;
+extern const char* connection_key;
+extern const char* error;
+extern const char* error_msg;
+extern const char* default_app_id;
+extern const char* msg_params;
+extern const char* method_name;
+extern const char* info;
+extern const char* app_id;
+extern const char* hmi_app_id;
+extern const char* device_id;
+extern const char* subscribed_for_way_points;
+extern const char* url;
+extern const char* urlScheme;
+extern const char* packageName;
+extern const char* cmd_icon;
+extern const char* result_code;
+extern const char* success;
+extern const char* sync_msg_version;
+extern const char* major_version;
+extern const char* minor_version;
+extern const char* app_name;
+extern const char* ngn_media_screen_app_name;
+extern const char* vr_synonyms;
+extern const char* uses_vehicle_data;
+extern const char* is_media_application;
+extern const char* greyOut;
+extern const char* language_desired;
+extern const char* auto_activated_id;
+extern const char* app_type;
+extern const char* app_hmi_type;
+extern const char* tts_name;
+extern const char* binary_data;
+extern const char* timeout_prompt;
+extern const char* timeout;
+extern const char* vr_help_title;
+extern const char* vr_help;
+extern const char* main_field_1;
+extern const char* main_field_2;
+extern const char* main_field_3;
+extern const char* main_field_4;
+extern const char* eta;
+extern const char* time_to_destination;
+extern const char* total_distance;
+extern const char* alignment;
+extern const char* graphic;
+extern const char* secondary_graphic;
+extern const char* status_bar;
+extern const char* media_clock;
+extern const char* media_track;
+extern const char* properties;
+extern const char* cmd_id;
+extern const char* menu_params;
+extern const char* menu_title;
+extern const char* menu_icon;
+extern const char* keyboard_properties;
+extern const char* vr_commands;
+extern const char* position;
+extern const char* num_ticks;
+extern const char* slider_footer;
+extern const char* menu_id;
+extern const char* menu_name;
+extern const char* interaction_choice_set_id;
+extern const char* interaction_choice_set_id_list;
+extern const char* choice_set;
+extern const char* choice_id;
+extern const char* grammar_id;
+extern const char* navigation_text_1;
+extern const char* navigation_text_2;
+extern const char* alert_text1;
+extern const char* alert_text2;
+extern const char* alert_text3;
+extern const char* tts_chunks;
+extern const char* initial_prompt;
+extern const char* initial_text;
+extern const char* duration;
+extern const char* progress_indicator;
+extern const char* alert_type;
+extern const char* play_tone;
+extern const char* soft_buttons;
+extern const char* soft_button_id;
+extern const char* custom_presets;
+extern const char* audio_pass_display_text1;
+extern const char* audio_pass_display_text2;
+extern const char* max_duration;
+extern const char* sampling_rate;
+extern const char* bits_per_sample;
+extern const char* audio_type;
+extern const char* mute_audio;
+extern const char* button_name;
+extern const char* button_event_mode;
+extern const char* button_press_mode;
+extern const char* custom_button_id;
+extern const char* data_type;
+extern const char* turn_list;
+extern const char* turn_icon;
+extern const char* next_turn_icon;
+extern const char* value;
+extern const char* hmi_display_language;
+extern const char* language;
+extern const char* data;
+extern const char* start_time;
+extern const char* end_time;
+extern const char* hours;
+extern const char* minutes;
+extern const char* seconds;
+extern const char* update_mode;
+extern const char* trigger_source;
+extern const char* hmi_level;
+extern const char* activate_app_hmi_level;
+extern const char* audio_streaming_state;
+extern const char* system_context;
+extern const char* speech_capabilities;
+extern const char* vr_capabilities;
+extern const char* audio_pass_thru_capabilities;
+extern const char* pcm_stream_capabilities;
+
// PutFile
-const char sync_file_name[] = "syncFileName";
-const char file_name[] = "fileName";
-const char file_type[] = "fileType";
-const char file_size[] = "fileSize";
-const char request_type[] = "requestType";
-const char persistent_file[] = "persistentFile";
-const char file_data[] = "fileData";
-const char space_available[] = "spaceAvailable";
-const char image_type[] = "imageType";
-const char image[] = "image";
-const char type[] = "type";
-const char system_file[] = "systemFile";
-const char offset[] = "offset";
-const char length[] = "length";
-const char secondary_image[] = "secondaryImage";
-const char filenames[] = "filenames";
+extern const char* sync_file_name;
+extern const char* file_name;
+extern const char* file_type;
+extern const char* file_size;
+extern const char* request_type;
+extern const char* persistent_file;
+extern const char* file_data;
+extern const char* space_available;
+extern const char* image_type;
+extern const char* image;
+extern const char* type;
+extern const char* system_file;
+extern const char* offset;
+extern const char* length;
+extern const char* secondary_image;
+extern const char* filenames;
-const char hmi_display_language_desired[] = "hmiDisplayLanguageDesired";
-const char ecu_name[] = "ecuName";
-const char dtc_mask[] = "dtcMask";
-const char did_location[] = "didLocation";
-const char app_list[] = "appList";
-const char device_list[] = "deviceList";
-const char device_info[] = "deviceInfo";
-const char name[] = "name";
-const char id[] = "id";
-const char isSDLAllowed[] = "isSDLAllowed";
-const char transport_type[] = "transportType";
-const char application[] = "application";
-const char applications[] = "applications";
-const char icon[] = "icon";
-const char device_name[] = "deviceName";
-const char reason[] = "reason";
-const char available[] = "available";
-const char text[] = "text";
-const char character_set[] = "characterSet";
-const char secondary_text[] = "secondaryText";
-const char tertiary_text[] = "tertiaryText";
-const char hardware[] = "hardware";
-const char firmware_rev[] = "firmwareRev";
-const char os[] = "os";
-const char os_version[] = "osVersion";
-const char carrier[] = "carrier";
-const char slider_header[] = "sliderHeader";
+extern const char* hmi_display_language_desired;
+extern const char* ecu_name;
+extern const char* dtc_mask;
+extern const char* did_location;
+extern const char* app_list;
+extern const char* device_list;
+extern const char* device_info;
+extern const char* name;
+extern const char* id;
+extern const char* isSDLAllowed;
+extern const char* transport_type;
+extern const char* application;
+extern const char* applications;
+extern const char* icon;
+extern const char* device_name;
+extern const char* reason;
+extern const char* available;
+extern const char* text;
+extern const char* character_set;
+extern const char* secondary_text;
+extern const char* tertiary_text;
+extern const char* hardware;
+extern const char* firmware_rev;
+extern const char* os;
+extern const char* os_version;
+extern const char* carrier;
+extern const char* slider_header;
+extern const char* key_press_mode;
// duplicate names from hmi_request
-const char limited_character_list[] = "limitedCharacterList";
-const char auto_complete_text[] = "autoCompleteText";
-const char navigation_text[] = "navigationText";
+extern const char* limited_character_list;
+extern const char* auto_complete_text;
+extern const char* navigation_text;
// vehicle info
-const char gps[] = "gps";
-const char speed[] = "speed";
-const char rpm[] = "rpm";
-const char fuel_level[] = "fuelLevel";
-const char fuel_level_state[] = "fuelLevel_State";
-const char instant_fuel_consumption[] = "instantFuelConsumption";
-const char external_temp[] = "externalTemperature";
-const char vin[] = "vin";
-const char prndl[] = "prndl";
-const char tire_pressure[] = "tirePressure";
-const char odometer[] = "odometer";
-const char belt_status[] = "beltStatus";
-const char body_information[] = "bodyInformation";
-const char device_status[] = "deviceStatus";
-const char driver_braking[] = "driverBraking";
-const char wiper_status[] = "wiperStatus";
-const char head_lamp_status[] = "headLampStatus";
-const char engine_torque[] = "engineTorque";
-const char acc_pedal_pos[] = "accPedalPosition";
-const char steering_wheel_angle[] = "steeringWheelAngle";
-const char e_call_info[] = "eCallInfo";
-const char airbag_status[] = "airbagStatus";
-const char emergency_event[] = "emergencyEvent";
-const char cluster_mode_status[] = "clusterModeStatus";
-const char my_key[] = "myKey";
-const char help_prompt[] = "helpPrompt";
-const char scroll_message_body[] = "scrollableMessageBody";
-const char data_result[] = "dataResult";
-const char dtc_list[] = "dtcList";
-const char interaction_mode[] = "interactionMode";
-const char slider_position[] = "sliderPosition";
-const char system_action[] = "systemAction";
-const char prerecorded_speech[] = "prerecordedSpeech";
-const char supported_diag_modes[] = "supportedDiagModes";
-const char hmi_capabilities[] = "hmiCapabilities";
-const char navigation[] = "navigation";
-const char phone_call[] = "phoneCall";
-const char sdl_version[] = "sdlVersion";
-const char system_software_version[] = "systemSoftwareVersion";
-const char priority[] = "priority";
+extern const char* gps;
+extern const char* speed;
+extern const char* rpm;
+extern const char* fuel_level;
+extern const char* fuel_level_state;
+extern const char* instant_fuel_consumption;
+extern const char* external_temp;
+extern const char* vin;
+extern const char* prndl;
+extern const char* tire_pressure;
+extern const char* odometer;
+extern const char* belt_status;
+extern const char* body_information;
+extern const char* device_status;
+extern const char* driver_braking;
+extern const char* wiper_status;
+extern const char* head_lamp_status;
+extern const char* engine_torque;
+extern const char* acc_pedal_pos;
+extern const char* steering_wheel_angle;
+extern const char* e_call_info;
+extern const char* airbag_status;
+extern const char* emergency_event;
+extern const char* cluster_mode_status;
+extern const char* my_key;
+extern const char* help_prompt;
+extern const char* scroll_message_body;
+extern const char* data_result;
+extern const char* dtc_list;
+extern const char* interaction_mode;
+extern const char* slider_position;
+extern const char* system_action;
+extern const char* prerecorded_speech;
+extern const char* supported_diag_modes;
+extern const char* hmi_capabilities;
+extern const char* navigation;
+extern const char* phone_call;
+extern const char* sdl_version;
+extern const char* system_software_version;
+extern const char* priority;
+
+// resuming
+extern const char* application_commands;
+extern const char* application_submenus;
+extern const char* application_choice_sets;
+extern const char* application_global_properties;
+extern const char* application_vehicle_info;
+extern const char* application_buttons;
+extern const char* application_subscribtions;
+extern const char* application_files;
+extern const char* application_show;
+extern const char* resumption;
+extern const char* resume_app_list;
+extern const char* last_ign_off_time;
+
+extern const char* resume_vr_grammars;
-//resuming
-const char application_commands[] = "applicationCommands";
-const char application_submenus[] = "applicationSubMenus";
-const char application_choise_sets[] = "applicationChoiceSets";
-const char application_global_properties[] = "globalProperties";
-const char application_vehicle_info[] = "vehicleInfo";
-const char application_buttons[] = "buttons";
-const char application_subscribtions[] = "subscribtions";
-const char application_files[] = "applicationFiles";
-const char application_show[] = "applicationShow";
-const char resumption[] = "resumption";
-const char resume_app_list[] = "resume_app_list";
-const char last_ign_off_time[] = "last_ign_off_time";
+extern const char* ign_off_count;
-const char resume_vr_grammars[] = "resumeVrGrammars";
+extern const char* connection_info;
+extern const char* is_download_complete;
-const char ign_off_count[] = "ign_off_count";
-const char suspend_count[] = "suspend_count";
+extern const char* longitude_degrees;
+extern const char* latitude_degrees;
+extern const char* address;
+extern const char* country_name;
+extern const char* country_code;
+extern const char* postal_code;
+extern const char* administrative_area;
+extern const char* locality;
+extern const char* sub_locality;
+extern const char* thoroughfare;
+extern const char* sub_thoroughfare;
-const char connection_info[] = "connection_info";
-const char is_download_complete[] = "is_download_complete";
+extern const char* hash_id;
+extern const char* time_stamp;
+extern const char* manual_text_entry;
+extern const char* image_type_supported;
+extern const char* unexpected_disconnect;
+extern const char* location_name;
+extern const char* location_description;
+extern const char* address_lines;
+extern const char* phone_number;
+extern const char* number;
+extern const char* location_image;
+extern const char* is_suscribed;
+extern const char* message_data;
-const char hash_id[] = "hashID";
-const char time_stamp[] = "timeStamp";
-const char manual_text_entry[] = "manualTextEntry";
-const char image_type_supported[] = "imageTypeSupported";
-const char unexpected_disconnect[] = "unexpectedDisconnect";
-const char location_name[] = "locationName";
-const char location_description[] = "locationDescription";
-const char address_lines[] = "addressLines";
-const char phone_number[] = "phoneNumber";
-const char number[] = "number";
-const char location_image[] = "locationImage";
-const char is_suscribed[] = "isSubscribed";
-const char message_data[] = "messageData";
+extern const char* delivery_mode;
} // namespace strings
namespace json {
-const char appId[] = "appId";
-const char name[] = "name";
-const char ios[] = "ios";
-const char android[] = "android";
-const char appHmiType[] = "appHmiType";
-const char urlScheme[] = "urlScheme";
-const char packageName[] = "packageName";
-const char response[] = "response";
-const char is_media_application[] = "isMediaApplication";
-const char default_[] = "default";
-const char languages[] = "languages";
-const char ttsName[] = "ttsName";
-const char vrSynonyms[] = "vrSynonyms";
-} // namespace json
+extern const char* appId;
+extern const char* name;
+extern const char* ios;
+extern const char* android;
+extern const char* appHmiType;
+extern const char* urlScheme;
+extern const char* packageName;
+extern const char* response;
+extern const char* is_media_application;
+extern const char* default_;
+extern const char* languages;
+extern const char* ttsName;
+extern const char* vrSynonyms;
+} // namespace json
namespace http_request {
-const char httpRequest[] = "HTTPRequest";
-const char headers[] = "headers";
-const char content_type[] = "ContentType";
-const char connect_timeout[] = "ConnectTimout";
-const char do_output[] = "DoOutput";
-const char do_input[] = "DoInput";
-const char use_caches[] = "UseCaches";
-const char request_method[] = "RequestMethod";
-const char read_timeout[] = "ReadTimeout";
-const char instance_follow_redirect[] = "InstanceFollowRedirect";
-const char charset[] = "charset";
-const char content_lenght[] = "Content_Lenght";
-const char GET[] = "GET";
-} // http_request
+extern const char* httpRequest;
+extern const char* headers;
+extern const char* content_type;
+extern const char* connect_timeout;
+extern const char* do_output;
+extern const char* do_input;
+extern const char* use_caches;
+extern const char* request_method;
+extern const char* read_timeout;
+extern const char* instance_follow_redirect;
+extern const char* charset;
+extern const char* content_lenght;
+extern const char* GET;
+} // http_request
namespace mobile_notification {
-const char state[] = "state";
-const char syncp_timeout[] = "Timeout";
-const char syncp_url[] = "URL";
+extern const char* state;
+extern const char* syncp_timeout;
+extern const char* syncp_url;
} // namespace mobile_notification
namespace hmi_levels {
-const char kFull[] = "FULL";
-const char kLimited[] = "LIMITED";
-const char kBackground[] = "BACKGROUND";
-const char kNone[] = "NONE";
+extern const char* kFull;
+extern const char* kLimited;
+extern const char* kBackground;
+extern const char* kNone;
}
namespace hmi_request {
-const char parent_id[] = "parentID";
-const char field_name[] = "fieldName";
-const char field_text[] = "fieldText";
-const char alert_strings[] = "alertStrings";
-const char duration[] = "duration";
-const char soft_buttons[] = "softButtons";
-const char tts_chunks[] = "ttsChunks";
-const char speak_type[] = "speakType";
-const char audio_pass_display_texts[] = "audioPassThruDisplayTexts";
-const char max_duration[] = "maxDuration";
-const char reason[] = "reason";
-const char message_text[] = "messageText";
-const char initial_text[] = "initialText";
-const char navi_texts[] = "navigationTexts";
-const char navi_text[] = "navigationText";
-const char show_strings[] = "showStrings";
-const char interaction_layout[] = "interactionLayout";
-const char menu_title[] = "menuTitle";
-const char menu_icon[] = "menuIcon";
-const char keyboard_properties[] = "keyboardProperties";
-const char method_name[] = "methodName";
-const char keyboard_layout[] = "keyboardLayout";
-const char limited_character_list[] = "limitedCharacterList";
-const char auto_complete_text[] = "autoCompleteText";
-const char file[] = "file";
-const char retry[] = "retry";
-const char service[] = "service";
+extern const char* parent_id;
+extern const char* field_name;
+extern const char* field_text;
+extern const char* alert_strings;
+extern const char* duration;
+extern const char* soft_buttons;
+extern const char* tts_chunks;
+extern const char* speak_type;
+extern const char* audio_pass_display_texts;
+extern const char* max_duration;
+extern const char* reason;
+extern const char* message_text;
+extern const char* initial_text;
+extern const char* navi_texts;
+extern const char* navi_text;
+extern const char* show_strings;
+extern const char* interaction_layout;
+extern const char* menu_title;
+extern const char* menu_icon;
+extern const char* keyboard_properties;
+extern const char* method_name;
+extern const char* keyboard_layout;
+extern const char* limited_character_list;
+extern const char* auto_complete_text;
+extern const char* file;
+extern const char* retry;
+extern const char* service;
} // namespace hmi_request
namespace hmi_response {
-const char code[] = "code";
-const char message[] = "message";
-const char method[] = "method";
-const char try_again_time[] = "tryAgainTime";
-const char custom_button_id[] = "customButtonID";
-const char button_name[] = "name";
-const char button_mode[] = "mode";
-const char attenuated_supported[] = "attenuatedSupported";
-const char languages[] = "languages";
-const char language[] = "language";
-const char display_capabilities[] = "displayCapabilities";
-const char hmi_zone_capabilities[] = "hmiZoneCapabilities";
-const char soft_button_capabilities[] = "softButtonCapabilities";
-const char image_supported[] = "imageSupported";
-const char button_capabilities[] = "buttonCapabilities";
-const char capabilities[] = "capabilities";
-const char speech_capabilities[] = "speechCapabilities";
-const char prerecorded_speech_capabilities[] = "prerecordedSpeechCapabilities";
-const char preset_bank_capabilities[] = "presetBankCapabilities";
-const char allowed[] = "allowed";
-const char vehicle_type[] = "vehicleType";
-const char did_result[] = "didResult";
-const char result_code[] = "resultCode";
-const char dtc[] = "dtc";
-const char ecu_header[] = "ecuHeader";
-const char image_capabilities[] = "imageCapabilities";
-const char display_type[] = "displayType";
-const char text_fields[] = "textFields";
-const char media_clock_formats[] = "mediaClockFormats";
-const char graphic_supported[] = "graphicSupported";
-const char image_fields[] = "imageFields";
-const char templates_available[] = "templatesAvailable";
-const char screen_params[] = "screenParams";
-const char num_custom_presets_available[] = "numCustomPresetsAvailable";
-const char urls[] = "urls";
-const char policy_app_id[] = "policyAppID";
-const char enabled[] = "enabled";
+extern const char* code;
+extern const char* message;
+extern const char* method;
+extern const char* try_again_time;
+extern const char* custom_button_id;
+extern const char* button_name;
+extern const char* button_mode;
+extern const char* attenuated_supported;
+extern const char* languages;
+extern const char* language;
+extern const char* display_capabilities;
+extern const char* hmi_zone_capabilities;
+extern const char* soft_button_capabilities;
+extern const char* image_supported;
+extern const char* button_capabilities;
+extern const char* capabilities;
+extern const char* speech_capabilities;
+extern const char* prerecorded_speech_capabilities;
+extern const char* preset_bank_capabilities;
+extern const char* allowed;
+extern const char* vehicle_type;
+extern const char* did_result;
+extern const char* result_code;
+extern const char* dtc;
+extern const char* ecu_header;
+extern const char* image_capabilities;
+extern const char* display_type;
+extern const char* text_fields;
+extern const char* media_clock_formats;
+extern const char* graphic_supported;
+extern const char* image_fields;
+extern const char* templates_available;
+extern const char* screen_params;
+extern const char* num_custom_presets_available;
+extern const char* urls;
+extern const char* policy_app_id;
+extern const char* enabled;
} // namespace hmi_response
namespace hmi_notification {
-const char prndl[] = "prndl";
-const char file_name[] = "file_name";
-const char system_context[] = "systemContext";
-const char state[] = "state";
-const char result[] = "result";
-const char statistic_type[] = "statisticType";
-const char error[] = "error";
-const char policyfile[] = "policyfile";
-const char is_active[] = "isActive";
+extern const char* prndl;
+extern const char* file_name;
+extern const char* system_context;
+extern const char* state;
+extern const char* result;
+extern const char* statistic_type;
+extern const char* error;
+extern const char* policyfile;
+extern const char* is_active;
+extern const char* is_deactivated;
+extern const char* event_name;
} // namespace hmi_notification
diff --git a/src/components/application_manager/include/application_manager/state_context.h b/src/components/application_manager/include/application_manager/state_context.h
deleted file mode 100644
index 94962c23b4..0000000000
--- a/src/components/application_manager/include/application_manager/state_context.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_STATE_CONTEXT_H_
-#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_STATE_CONTEXT_H_
-
-#include <inttypes.h>
-
-namespace application_manager {
-/**
-* @brief The StateContext implement acessing to data, that is required by HmiState
-*/
-class StateContext {
- public:
-
- /**
- * @brief is_navi_app check if app is navi
- * @param app_id application id
- * @return true if app is navi, otherwise return false
- */
- bool is_navi_app(const uint32_t app_id) const;
-
- /**
- * @brief is_meida_app check if app is is meida
- * @param app_id application id
- * @return @return true if meida_app, otherwise return false
- */
- bool is_meida_app(const uint32_t app_id) const;
-
- /**
- * @brief is_voice_comunication_app check if app is voice comunication
- * @param app_id application id
- * @return @return true if voice_comunication_app, otherwise return false
- */
- bool is_voice_comunication_app(const uint32_t app_id) const;
-
- /**
- * @brief is_attenuated_supported check if HMI support attenuated mode
- * @return true if supported, otherwise return false
- */
- bool is_attenuated_supported() const;
-};
-
-}
-#endif // STATE_CONTEXT_H
-
diff --git a/src/components/application_manager/include/application_manager/state_controller.h b/src/components/application_manager/include/application_manager/state_controller.h
deleted file mode 100644
index a09d11f18e..0000000000
--- a/src/components/application_manager/include/application_manager/state_controller.h
+++ /dev/null
@@ -1,408 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_STATE_CONTROLLER_H_
-#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_STATE_CONTROLLER_H_
-#include <list>
-
-#include "application_manager/hmi_state.h"
-#include "application_manager/application.h"
-#include "event_engine/event_observer.h"
-#include "application_manager/message_helper.h"
-#include "interfaces/MOBILE_API.h"
-#include "application_manager/state_context.h"
-#include "utils/lock.h"
-
-namespace application_manager {
-class ApplicationManagerImpl;
-class StateController : public event_engine::EventObserver {
-public:
- StateController();
-
- /**
- * @brief SetRegularState setup regular hmi state, tha will appear if no
- * specific events are active
- * @param app appication to setup regular State
- * @param state state of new regular state
- */
- template <bool SendActivateApp>
- void SetRegularState(ApplicationSharedPtr app, HmiStatePtr state) {
- if (!app) {
- return;
- }
- DCHECK_OR_RETURN_VOID(state);
- DCHECK_OR_RETURN_VOID(state->state_id() == HmiState::STATE_ID_REGULAR);
-
- if (SendActivateApp) {
- uint32_t corr_id = MessageHelper::SendActivateAppToHMI(app->app_id());
- subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_ActivateApp,
- corr_id);
- waiting_for_activate[app->app_id()] = state;
- } else {
- ApplyRegularState(app, state);
- }
- }
-
- /**
- * @brief SetRegularState Change regular audio state
- * @param app appication to setup regular State
- * @param audio_state of new regular state
- */
- void
- SetRegularState(ApplicationSharedPtr app,
- const mobile_apis::AudioStreamingState::eType audio_state);
-
- /**
- * @brief SetRegularState Change regular hmi level and audio state
- * @param app appication to setup regular State
- * @param hmi_level of new regular state
- * @param audio_state of new regular state
- * @param SendActivateApp: if true, ActivateAppRequest will be sent on HMI */
- template <bool SendActivateApp>
- void
- SetRegularState(ApplicationSharedPtr app,
- const mobile_apis::HMILevel::eType hmi_level,
- const mobile_apis::AudioStreamingState::eType audio_state) {
- if (!app) {
- return;
- }
- HmiStatePtr prev_regular = app->RegularHmiState();
- DCHECK_OR_RETURN_VOID(prev_regular);
- HmiStatePtr hmi_state =
- CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
- DCHECK_OR_RETURN_VOID(hmi_state);
- hmi_state->set_hmi_level(hmi_level);
- hmi_state->set_audio_streaming_state(audio_state);
- hmi_state->set_system_context(prev_regular->system_context());
- SetRegularState<SendActivateApp>(app, hmi_state);
- }
-
- /**
- * @brief SetRegularState Change regular hmi level
- * @param app appication to setup regular State
- * @param hmi_level of new regular state
- * @param SendActivateApp: if true, ActivateAppRequest will be sent on HMI */
- template <bool SendActivateApp>
- void SetRegularState(ApplicationSharedPtr app,
- const mobile_apis::HMILevel::eType hmi_level) {
- if (!app) {
- return;
- }
- HmiStatePtr prev_regular = app->RegularHmiState();
- DCHECK_OR_RETURN_VOID(prev_regular);
- HmiStatePtr hmi_state =
- CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
- DCHECK_OR_RETURN_VOID(hmi_state);
- hmi_state->set_hmi_level(hmi_level);
- hmi_state->set_audio_streaming_state(prev_regular->audio_streaming_state());
- hmi_state->set_system_context(prev_regular->system_context());
- SetRegularState<SendActivateApp>(app, hmi_state);
- }
-
- /**
- * @brief SetRegularState Change regular hmi level, audio state and system
- * context
- * @param app appication to setup regular State
- * @param hmi_level of new regular state
- * @param audio_state of new regular state
- * @param system_context of new regular state
- * @param SendActivateApp: if true, ActivateAppRequest will be sent on HMI */
- template <bool SendActivateApp>
- void
- SetRegularState(ApplicationSharedPtr app,
- const mobile_apis::HMILevel::eType hmi_level,
- const mobile_apis::AudioStreamingState::eType audio_state,
- const mobile_apis::SystemContext::eType system_context) {
- if (!app) {
- return;
- }
-
- HmiStatePtr hmi_state =
- CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
- DCHECK_OR_RETURN_VOID(hmi_state);
- hmi_state->set_hmi_level(hmi_level);
- hmi_state->set_audio_streaming_state(audio_state);
- hmi_state->set_system_context(system_context);
- SetRegularState<SendActivateApp>(app, hmi_state);
- }
-
- /**
- * @brief SetRegularState Change regular system context
- * @param app appication to setup regular State
- * @param system_context of new regular state
- */
- void SetRegularState(ApplicationSharedPtr app,
- const mobile_apis::SystemContext::eType system_context) {
- if (!app) {
- return;
- }
- HmiStatePtr prev_regular = app->RegularHmiState();
- DCHECK_OR_RETURN_VOID(prev_regular);
- HmiStatePtr hmi_state =
- CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
- DCHECK_OR_RETURN_VOID(hmi_state);
- hmi_state->set_hmi_level(prev_regular->hmi_level());
- hmi_state->set_audio_streaming_state(prev_regular->audio_streaming_state());
- hmi_state->set_system_context(system_context);
- SetRegularState<false>(app, hmi_state);
- }
-
- // EventObserver interface
- void on_event(const event_engine::Event &event);
-
- /**
- * @brief Sets default application state and apply currently active HMI states
- * on application registration
- * @param app application to apply states
- * @param default_level default HMI level
- */
- virtual void
- OnApplicationRegistered(ApplicationSharedPtr app,
- const mobile_apis::HMILevel::eType default_level);
-
- /**
- * @brief OnStateChanged send HMIStatusNotification if neded
- * @param app application
- * @param old_state state before change
- * @param new_state state after change
- */
- void OnStateChanged(ApplicationSharedPtr app, HmiStatePtr old_state,
- HmiStatePtr new_state);
- /**
- * @brief state_context getter for state_context
- * @return
- */
- const StateContext &state_context() const { return state_context_; }
-
- /**
- * @brief OnNaviStreamingStarted process Navi streaming started
- */
- void OnNaviStreamingStarted();
-
- /**
- * @brief OnNaviStreamingStopped process Navi streaming stopped
- */
- void OnNaviStreamingStopped();
-
-private:
- /**
- * Execute Unary punction for each application
- */
- template <typename UnaryFunction,
- typename ContextAcessor = ApplicationManagerImpl>
- void ForEachApplication(UnaryFunction func) {
- using namespace utils;
- typename ContextAcessor::ApplicationListAccessor accessor;
- typedef typename ContextAcessor::ApplictionSetConstIt Iter;
- for (Iter it = accessor.begin(); it != accessor.end(); ++it) {
- if (it->valid()) {
- ApplicationConstSharedPtr const_app = *it;
- func(ContextAcessor::instance()->application(const_app->app_id()));
- }
- }
- }
-
- /**
- * @brief The HmiLevelConflictResolver struct
- * Move other application to HmiStates if applied moved to FULL or LIMITED
- */
- struct HmiLevelConflictResolver {
- ApplicationSharedPtr applied_;
- HmiStatePtr state_;
- StateController *state_ctrl_;
- HmiLevelConflictResolver(ApplicationSharedPtr app, HmiStatePtr state,
- StateController *state_ctrl)
- : applied_(app), state_(state) {}
- void operator()(ApplicationSharedPtr to_resolve);
- };
-
- /**
- * Function to add new temporary HmiState for application
- */
- template <HmiState::StateID ID>
- void HMIStateStarted(ApplicationSharedPtr app) {
- DCHECK_OR_RETURN_VOID(app);
- HmiStatePtr old_hmi_state = app->CurrentHmiState();
- HmiStatePtr new_hmi_state = CreateHmiState(app->app_id(), ID);
- DCHECK_OR_RETURN_VOID(new_hmi_state);
- DCHECK_OR_RETURN_VOID(new_hmi_state->state_id() !=
- HmiState::STATE_ID_REGULAR);
- new_hmi_state->set_parent(old_hmi_state);
- app->AddHMIState(new_hmi_state);
- OnStateChanged(app, old_hmi_state, new_hmi_state);
- }
-
- /**
- * @brief TempStateStarted add HMI State ID in StateController collection
- * @param ID state identifier
- */
- void TempStateStarted(HmiState::StateID ID);
-
- /**
- * @brief TempStateStopped remove HMI State ID from StateController collection
- * @param ID state identifier
- */
- void TempStateStopped(HmiState::StateID ID);
-
- /**
- * Function to remove temporary HmiState for application
- */
- template <HmiState::StateID ID>
- void HMIStateStopped(ApplicationSharedPtr app) {
- DCHECK_OR_RETURN_VOID(app);
- HmiStatePtr cur = app->CurrentHmiState();
- HmiStatePtr old_hmi_state =
- CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
- DCHECK_OR_RETURN_VOID(old_hmi_state);
- old_hmi_state->set_hmi_level(cur->hmi_level());
- old_hmi_state->set_audio_streaming_state(cur->audio_streaming_state());
- old_hmi_state->set_system_context(cur->system_context());
- app->RemoveHMIState(ID);
- HmiStatePtr new_hmi_state = app->CurrentHmiState();
- OnStateChanged(app, old_hmi_state, new_hmi_state);
- }
-
- /**
- * @brief ApplyRegularState setup regular hmi state, that will appear if no
- * specific events are active, without sending ActivateApp
- * @param app appication to setup default State
- * @param state state of new defailt state
- */
- void ApplyRegularState(ApplicationSharedPtr app, HmiStatePtr state);
-
- /**
- * @brief SetupRegularHmiState set regular HMI State without
- * resolwing conflicts and ActivateApp request
- * @param app application
- * @param state hmi_state to setup
- */
- void SetupRegularHmiState(ApplicationSharedPtr app, HmiStatePtr state);
-
- /**
- * @brief IsSameAppType checkis if apps has same types
- * @param app1
- * @param app2
- * @return true if aps have same types, otherwise return false
- */
- bool IsSameAppType(ApplicationConstSharedPtr app1,
- ApplicationConstSharedPtr app2);
-
- /**
- * @brief SetupRegularHmiState set regular HMI State without
- * resolwing conflicts and ActivateApp request
- * @param app application
- * @param hmi_level of new regular state
- * @param audio_state of new regular state
- * @param system_context of new regular state
- */
- void SetupRegularHmiState(
- ApplicationSharedPtr app, const mobile_apis::HMILevel::eType hmi_level,
- const mobile_apis::AudioStreamingState::eType audio_state,
- const mobile_apis::SystemContext::eType system_context);
-
- /**
- * @brief SetupRegularHmiState set regular HMI State without
- * resolwing conflicts and ActivateApp request
- * @param app application
- * @param hmi_level of new regular state
- * @param audio_state of new regular state
- */
- void SetupRegularHmiState(
- ApplicationSharedPtr app, const mobile_apis::HMILevel::eType hmi_level,
- const mobile_apis::AudioStreamingState::eType audio_state);
-
- /**
- * @brief OnActivateAppResponse calback for activate app response
- * @param message Smart Object
- */
- void OnActivateAppResponse(const smart_objects::SmartObject &message);
-
- /**
- * @brief OnPhoneCallStarted process Phone Call Started event
- */
- void OnPhoneCallStarted();
-
- /**
- * @brief OnPhoneCallEnded process Phone Call Ended event
- */
- void OnPhoneCallEnded();
-
- /**
- * @brief OnSafetyModeEnabled process Safety Mode Enable event
- */
- void OnSafetyModeEnabled();
-
- /**
- * @brief OnSafetyModeDisabled process Safety Mode Disable event
- */
- void OnSafetyModeDisabled();
-
- /**
- * @brief OnVRStarted process VR session started
- */
- void OnVRStarted();
-
- /**
- * @brief OnVREnded process VR session ended
- */
- void OnVREnded();
- /**
- * @brief OnTTSStarted process TTS session started
- */
- void OnTTSStarted();
-
- /**
- * @brief OnTTSEnded process TTS session ended
- */
- void OnTTSStopped();
-
- /**
- * @brief CreateHmiState creates Hmi state according to state_id
- * @param app_id application ID
- * @param state_id state id
- * @return
- */
- HmiStatePtr CreateHmiState(uint32_t app_id, HmiState::StateID state_id);
-
- mobile_apis::AudioStreamingState::eType
- CalcAudioState(ApplicationSharedPtr app,
- const mobile_apis::HMILevel::eType hmi_level) const;
-
- typedef std::list<HmiState::StateID> StateIDList;
- StateIDList active_states_;
- sync_primitives::Lock active_states_lock_;
- std::map<uint32_t, HmiStatePtr> waiting_for_activate;
- StateContext state_context_;
-};
-}
-
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_STATE_CONTROLLER_H_
diff --git a/src/components/application_manager/include/application_manager/state_controller_impl.h b/src/components/application_manager/include/application_manager/state_controller_impl.h
new file mode 100644
index 0000000000..f2f9fb39a4
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/state_controller_impl.h
@@ -0,0 +1,448 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_STATE_CONTROLLER_IMPL_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_STATE_CONTROLLER_IMPL_H_
+#include <list>
+
+#include "application_manager/hmi_state.h"
+#include "application_manager/application.h"
+#include "application_manager/application_manager.h"
+#include "event_engine/event_observer.h"
+#include "application_manager/state_controller.h"
+#include "application_manager/message_helper.h"
+#include "interfaces/MOBILE_API.h"
+#include "utils/lock.h"
+#include "utils/helpers.h"
+
+namespace application_manager {
+
+class StateControllerImpl : public event_engine::EventObserver,
+ public StateController {
+ public:
+ explicit StateControllerImpl(ApplicationManager& app_mngr);
+
+ /**
+ * @brief SetRegularState setup regular hmi state, that will appear if
+ * no specific events are active
+ * @param app appication to setup regular State
+ * @param state state of new regular state
+ */
+
+ virtual void SetRegularState(ApplicationSharedPtr app,
+ HmiStatePtr state,
+ const bool SendActivateApp);
+
+ /**
+ * @brief SetRegularState Change regular hmi level and audio state
+ * @param app appication to setup regular State
+ * @param hmi_level of new regular state
+ * @param audio_state of new regular state
+ * @param SendActivateApp: if true, ActivateAppRequest will be sent on HMI */
+
+ virtual void SetRegularState(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const mobile_apis::AudioStreamingState::eType audio_state,
+ const bool SendActivateApp);
+
+ /**
+ * @brief SetRegularState Change regular hmi level
+ * @param app appication to setup regular State
+ * @param hmi_level of new regular state
+ * @param SendActivateApp: if true, ActivateAppRequest will be sent on HMI
+ */
+ virtual void SetRegularState(ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const bool SendActivateApp);
+
+ /**
+ * @brief SetRegularState Change regular hmi level, audio state and system
+ * context
+ * @param app appication to setup regular State
+ * @param hmi_level of new regular state
+ * @param audio_state of new regular state
+ * @param system_context of new regular state
+ * @param SendActivateApp: if true, ActivateAppRequest will be sent on HMI */
+
+ virtual void SetRegularState(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const mobile_apis::AudioStreamingState::eType audio_state,
+ const mobile_apis::SystemContext::eType system_context,
+ const bool SendActivateApp);
+
+ /**
+ * @brief SetRegularState Sets regular state with new hmi level
+ * to application
+ * @param app appication to setup regular state
+ * @param hmi_level new hmi level for application
+ */
+ virtual void SetRegularState(ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level);
+
+ /**
+ * @brief SetRegularState Change regular audio state
+ * @param app appication to setup regular State
+ * @param audio_state of new regular state
+ */
+ virtual void SetRegularState(
+ ApplicationSharedPtr app,
+ const mobile_apis::AudioStreamingState::eType audio_state);
+
+ /**
+ * @brief SetRegularState Change regular system context
+ * @param app appication to setup regular State
+ * @param system_context of new regular state
+ */
+ virtual void SetRegularState(
+ ApplicationSharedPtr app,
+ const mobile_apis::SystemContext::eType system_context);
+
+ /**
+ * @brief SetRegularState Sets new regular state to application
+ * @param app appication to setup regular state
+ * @param state new hmi state for application
+ */
+ virtual void SetRegularState(ApplicationSharedPtr app, HmiStatePtr state);
+
+ // EventObserver interface
+ void on_event(const event_engine::Event& event);
+
+ /**
+ * @brief Sets default application state and apply currently active HMI states
+ * on application registration
+ * @param app application to apply states
+ * @param default_level default HMI level
+ */
+ virtual void OnApplicationRegistered(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType default_level);
+
+ /**
+ * @brief OnNaviStreamingStarted process Navi streaming started
+ */
+ virtual void OnNaviStreamingStarted();
+
+ /**
+ * @brief OnNaviStreamingStopped process Navi streaming stopped
+ */
+ virtual void OnNaviStreamingStopped();
+
+ /**
+ * @brief OnStateChanged send HMIStatusNotification if neded
+ * @param app application
+ * @param old_state state before change
+ * @param new_state state after change
+ */
+ virtual void OnStateChanged(ApplicationSharedPtr app,
+ HmiStatePtr old_state,
+ HmiStatePtr new_state);
+
+ /**
+ * @brief Checks activity of Deactivate HMI state.
+ * @return Returns TRUE if deactivate HMI state is active, otherwise returns
+ * FALSE.
+ */
+ virtual bool IsStateActive(HmiState::StateID state_id) const;
+
+ private:
+ int64_t SendBCActivateApp(ApplicationConstSharedPtr app,
+ hmi_apis::Common_HMILevel::eType level,
+ bool send_policy_priority);
+ /**
+ * @brief The HmiLevelConflictResolver struct
+ * Move other application to HmiStates if applied moved to FULL or LIMITED
+ */
+ struct HmiLevelConflictResolver {
+ ApplicationSharedPtr applied_;
+ HmiStatePtr state_;
+ StateControllerImpl* state_ctrl_;
+ HmiLevelConflictResolver(ApplicationSharedPtr app,
+ HmiStatePtr state,
+ StateControllerImpl* state_ctrl)
+ : applied_(app), state_(state), state_ctrl_(state_ctrl) {}
+ void operator()(ApplicationSharedPtr to_resolve);
+ };
+
+ template <typename UnaryFunction>
+ void ForEachApplication(UnaryFunction func) const {
+ DataAccessor<ApplicationSet> accessor = app_mngr_.applications();
+ ApplicationSet::iterator it = accessor.GetData().begin();
+ for (; it != accessor.GetData().end(); ++it) {
+ ApplicationConstSharedPtr const_app = *it;
+ if (const_app) {
+ func(app_mngr_.application(const_app->app_id()));
+ }
+ }
+ }
+
+ /**
+ * @brief ResolveHmiState Checks if requested hmi state is
+ * allowed by current states context and correct it if it possible
+ *
+ * @param app application to apply state
+ *
+ * @param state state to be checked
+ *
+ * @return Resolved hmi state or empty pointer in case requested
+ * hmi state is not allowed
+ */
+ HmiStatePtr ResolveHmiState(ApplicationSharedPtr app,
+ HmiStatePtr state) const;
+
+ /**
+ * @brief IsResumptionAllowed checks, if app is allowed to be resumed in
+ * current state
+ * @param app Application
+ * @param state State to be checked
+ * @return true, if app is allowed to be resumed, otherwise - false
+ */
+ bool IsResumptionAllowed(ApplicationSharedPtr app, HmiStatePtr state) const;
+
+ /**
+ * @brief GetAvailableHmiLevel Returns closest to requested
+ * available hmi level for application
+ *
+ * @param app application to apply state
+ *
+ * @param hmi_level requested hmi level
+ *
+ * @return Resolved hmi state or empty pointer in case requested
+ * hmi state is not allowed
+ */
+ mobile_apis::HMILevel::eType GetAvailableHmiLevel(
+ ApplicationSharedPtr app, mobile_apis::HMILevel::eType hmi_level) const;
+
+ /**
+ * @brief IsStateAvailable Checks if hmi state is available
+ * to apply for specified application
+ *
+ * @param app application to apply state
+ *
+ * @param state state to be checked
+ *
+ * @return true if state is available, false otherwise
+ */
+ bool IsStateAvailable(ApplicationSharedPtr app, HmiStatePtr state) const;
+
+ /**
+ * @brief IsStateAvailableForResumption Checks if hmi state is available
+ * to apply for specified application during resumption
+ *
+ * @param app application to apply state
+ *
+ * @param state state to be checked
+ *
+ * @return true if state is available, false otherwise
+ */
+ bool IsStateAvailableForResumption(ApplicationSharedPtr app,
+ HmiStatePtr state) const;
+
+ /**
+ * @brief ApplyPostponedStateForApp tries to apply postponed state
+ * to application if it's allowed by current active states
+ */
+ void ApplyPostponedStateForApp(ApplicationSharedPtr app);
+
+ /**
+ * @brief IsTempStateActive Checks if specified temp state
+ * is currently active
+ *
+ * @return true if state is active, false otherwise
+ */
+ bool IsTempStateActive(HmiState::StateID ID) const;
+
+ /**
+ * Function to add new temporary HmiState for application
+ */
+ template <HmiState::StateID ID>
+ void HMIStateStarted(ApplicationSharedPtr app) {
+ DCHECK_OR_RETURN_VOID(app);
+ HmiStatePtr old_hmi_state = app->CurrentHmiState();
+ HmiStatePtr new_hmi_state = CreateHmiState(app->app_id(), ID);
+ DCHECK_OR_RETURN_VOID(new_hmi_state);
+ DCHECK_OR_RETURN_VOID(new_hmi_state->state_id() !=
+ HmiState::STATE_ID_REGULAR);
+ new_hmi_state->set_parent(old_hmi_state);
+ app->AddHMIState(new_hmi_state);
+ OnStateChanged(app, old_hmi_state, new_hmi_state);
+ }
+
+ /**
+ * @brief TempStateStarted add HMI State ID in StateControllerImpl collection
+ * @param ID state identifier
+ */
+ void TempStateStarted(HmiState::StateID ID);
+
+ /**
+ * @brief TempStateStopped remove HMI State ID from StateControllerImpl
+ * collection
+ * @param ID state identifier
+ */
+ void TempStateStopped(HmiState::StateID ID);
+
+ /**
+ * @brief Sets BACKGROUND or LIMITED hmi level to application
+ * depends on application type
+ * @param app Application to deactivate
+ */
+ void DeactivateApp(ApplicationSharedPtr app);
+
+ /**
+ * Function to remove temporary HmiState for application
+ */
+ template <HmiState::StateID ID>
+ void HMIStateStopped(ApplicationSharedPtr app) {
+ DCHECK_OR_RETURN_VOID(app);
+ HmiStatePtr cur = app->CurrentHmiState();
+ HmiStatePtr old_hmi_state =
+ CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
+ DCHECK_OR_RETURN_VOID(old_hmi_state);
+ old_hmi_state->set_hmi_level(cur->hmi_level());
+ old_hmi_state->set_audio_streaming_state(cur->audio_streaming_state());
+ old_hmi_state->set_system_context(cur->system_context());
+ app->RemoveHMIState(ID);
+ HmiStatePtr new_hmi_state = app->CurrentHmiState();
+ OnStateChanged(app, old_hmi_state, new_hmi_state);
+ }
+
+ /**
+ * @brief ApplyRegularState setup regular hmi state, that will appear if no
+ * specific events are active, without sending ActivateApp
+ * @param app appication to setup default State
+ * @param state state of new defailt state
+ */
+ void ApplyRegularState(ApplicationSharedPtr app, HmiStatePtr state);
+
+ /**
+ * @brief SetupRegularHmiState set regular HMI State without
+ * resolving conflicts and ActivateApp request
+ * @param app application
+ * @param state hmi_state to setup
+ */
+ void SetupRegularHmiState(ApplicationSharedPtr app, HmiStatePtr state);
+
+ /**
+ * @brief IsSameAppType checks if apps has same types
+ * @param app1
+ * @param app2
+ * @return true if aps have same types, otherwise return false
+ */
+ bool IsSameAppType(ApplicationConstSharedPtr app1,
+ ApplicationConstSharedPtr app2);
+
+ /**
+ * @brief SetupRegularHmiState set regular HMI State without
+ * resolving conflicts and ActivateApp request
+ * @param app application
+ * @param hmi_level of new regular state
+ * @param audio_state of new regular state
+ * @param system_context of new regular state
+ */
+ void SetupRegularHmiState(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const mobile_apis::AudioStreamingState::eType audio_state,
+ const mobile_apis::SystemContext::eType system_context);
+
+ /**
+ * @brief SetupRegularHmiState set regular HMI State without
+ * resolving conflicts and ActivateApp request
+ * @param app application
+ * @param hmi_level of new regular state
+ * @param audio_state of new regular state
+ */
+ void SetupRegularHmiState(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const mobile_apis::AudioStreamingState::eType audio_state);
+
+ /**
+ * @brief OnActivateAppResponse calback for activate app response
+ * @param message Smart Object
+ */
+ void OnActivateAppResponse(const smart_objects::SmartObject& message);
+
+ /**
+ * @brief OnAppDeactivated callback for OnAppDeactivated notification
+ * @param message Smart Object
+ */
+ void OnAppDeactivated(const smart_objects::SmartObject& message);
+
+ /**
+ * @brief OnAppActivated callback for OnAppActivated notification
+ * @param message Smart Object
+ */
+ void OnAppActivated(const smart_objects::SmartObject& message);
+
+ /**
+ * @brief Apply temporary state
+ */
+ template <HmiState::StateID ID>
+ void ApplyTempState() {
+ ForEachApplication(std::bind1st(
+ std::mem_fun(&StateControllerImpl::HMIStateStarted<ID>), this));
+ TempStateStarted(ID);
+ }
+
+ /**
+ * @brief Cancel temporary state
+ */
+ template <HmiState::StateID ID>
+ void CancelTempState() {
+ ForEachApplication(std::bind1st(
+ std::mem_fun(&StateControllerImpl::HMIStateStopped<ID>), this));
+ TempStateStopped(ID);
+ }
+
+ /**
+ * @brief CreateHmiState creates Hmi state according to state_id
+ * @param app_id application ID
+ * @param state_id state id
+ * @return
+ */
+ HmiStatePtr CreateHmiState(uint32_t app_id, HmiState::StateID state_id) const;
+
+ mobile_apis::AudioStreamingState::eType CalcAudioState(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level) const;
+
+ typedef std::list<HmiState::StateID> StateIDList;
+ StateIDList active_states_;
+ mutable sync_primitives::Lock active_states_lock_;
+ std::map<uint32_t, HmiStatePtr> waiting_for_activate;
+ ApplicationManager& app_mngr_;
+};
+}
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_STATE_CONTROLLER_IMPL_H_
diff --git a/src/components/application_manager/include/application_manager/telemetry_observer.h b/src/components/application_manager/include/application_manager/telemetry_observer.h
new file mode 100644
index 0000000000..ab995fcf91
--- /dev/null
+++ b/src/components/application_manager/include/application_manager/telemetry_observer.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_TIME_METRIC_OBSERVER_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_TIME_METRIC_OBSERVER_H_
+
+#include "smart_objects/smart_object.h"
+#include "application_manager/smart_object_keys.h"
+#include "json/json.h"
+#include "utils/shared_ptr.h"
+#include "utils/date_time.h"
+
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+namespace application_manager {
+
+class AMTelemetryObserver {
+ public:
+ struct MessageMetric {
+ TimevalStruct begin;
+ TimevalStruct end;
+ utils::SharedPtr<smart_objects::SmartObject> message;
+ };
+ typedef utils::SharedPtr<MessageMetric> MessageMetricSharedPtr;
+
+ virtual void OnMessage(MessageMetricSharedPtr) = 0;
+ virtual ~AMTelemetryObserver() {}
+};
+} // application_manager
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_USAGE_STATISTICS_H_
diff --git a/src/components/application_manager/include/application_manager/time_metric_observer.h b/src/components/application_manager/include/application_manager/time_metric_observer.h
deleted file mode 100644
index de3deb8372..0000000000
--- a/src/components/application_manager/include/application_manager/time_metric_observer.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_TIME_METRIC_OBSERVER_H_
-#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_TIME_METRIC_OBSERVER_H_
-
-
-#include "smart_objects/smart_object.h"
-#include "application_manager/smart_object_keys.h"
-#include "json/json.h"
-#include "utils/shared_ptr.h"
-#include "utils/date_time.h"
-
-namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
-namespace application_manager {
-
-class AMMetricObserver {
- public:
- struct MessageMetric {
- TimevalStruct begin;
- TimevalStruct end;
- utils::SharedPtr<smart_objects::SmartObject> message;
- };
- typedef utils::SharedPtr<MessageMetric> MessageMetricSharedPtr;
-
- virtual void OnMessage(MessageMetricSharedPtr) = 0;
- virtual ~AMMetricObserver(){}
-};
-} // application_manager
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_USAGE_STATISTICS_H_
diff --git a/src/components/application_manager/include/application_manager/usage_statistics.h b/src/components/application_manager/include/application_manager/usage_statistics.h
index d6ff1f2c49..b84c820a60 100644
--- a/src/components/application_manager/include/application_manager/usage_statistics.h
+++ b/src/components/application_manager/include/application_manager/usage_statistics.h
@@ -34,16 +34,24 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_USAGE_STATISTICS_H_
#include <string>
-#include "usage_statistics/counter.h"
+#include <memory>
+#include "policy/usage_statistics/counter.h"
+#include "policy/usage_statistics/app_stopwatch.h"
+#include "utils/macro.h"
+#include "utils/shared_ptr.h"
#include "interfaces/MOBILE_API.h"
namespace application_manager {
class UsageStatistics {
public:
- UsageStatistics(const std::string& app_id,
- utils::SharedPtr<usage_statistics::StatisticsManager>
- statistics_manager);
+ UsageStatistics(
+ const std::string& app_id,
+ utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager);
+ UsageStatistics(
+ const std::string& app_id,
+ utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager,
+ usage_statistics::AppStopwatch* time_in_hmi_state_ptr);
void RecordHmiStateChanged(mobile_apis::HMILevel::eType new_hmi_level);
void RecordAppRegistrationGuiLanguage(
mobile_apis::Language::eType gui_language);
@@ -54,9 +62,10 @@ class UsageStatistics {
void RecordAppUserSelection();
void RecordRunAttemptsWhileRevoked();
void RecordRemovalsForBadBehavior();
+ void RecordTLSError();
private:
- usage_statistics::AppStopwatch time_in_hmi_state_;
+ std::auto_ptr<usage_statistics::AppStopwatch> time_in_hmi_state_sptr_;
usage_statistics::AppInfo app_registration_language_gui_;
usage_statistics::AppInfo app_registration_language_vui_;
usage_statistics::AppCounter count_of_rejected_rpc_calls_;
@@ -64,6 +73,8 @@ class UsageStatistics {
usage_statistics::AppCounter count_of_user_selections_;
usage_statistics::AppCounter count_of_run_attempts_while_revoked_;
usage_statistics::AppCounter count_of_removals_for_bad_behavior_;
+ usage_statistics::AppCounter count_of_tls_error_;
+ DISALLOW_COPY_AND_ASSIGN(UsageStatistics);
};
} // namespace application_manager
diff --git a/src/components/application_manager/include/application_manager/vehicle_info_data.h b/src/components/application_manager/include/application_manager/vehicle_info_data.h
index 0cac4fd8f9..390a1707c8 100644
--- a/src/components/application_manager/include/application_manager/vehicle_info_data.h
+++ b/src/components/application_manager/include/application_manager/vehicle_info_data.h
@@ -34,10 +34,10 @@
#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_VEHICLE_INFO_DATA_H_
namespace application_manager {
- /*
- * @brief Typedef for the vehicle data types that can
- * be published and subscribed to
- */
+/*
+*@brief Typedef for the vehicle data types that can
+*be published and subscribed to
+*/
enum VehicleDataType {
GPS = 0,
SPEED,
diff --git a/src/components/application_manager/src/application_data_impl.cc b/src/components/application_manager/src/application_data_impl.cc
index bfdbadfc8f..a81540708c 100644
--- a/src/components/application_manager/src/application_data_impl.cc
+++ b/src/components/application_manager/src/application_data_impl.cc
@@ -37,16 +37,15 @@
#include "utils/logger.h"
namespace application_manager {
-CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationDataImpl")
+CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationManager")
InitialApplicationDataImpl::InitialApplicationDataImpl()
- : app_types_(NULL),
- vr_synonyms_(NULL),
- tts_name_(NULL),
- ngn_media_screen_name_(NULL),
- language_(mobile_api::Language::INVALID_ENUM),
- ui_language_(mobile_api::Language::INVALID_ENUM) {
-}
+ : app_types_(NULL)
+ , vr_synonyms_(NULL)
+ , tts_name_(NULL)
+ , ngn_media_screen_name_(NULL)
+ , language_(mobile_api::Language::INVALID_ENUM)
+ , ui_language_(mobile_api::Language::INVALID_ENUM) {}
InitialApplicationDataImpl::~InitialApplicationDataImpl() {
if (app_types_) {
@@ -70,17 +69,17 @@ InitialApplicationDataImpl::~InitialApplicationDataImpl() {
}
}
-const smart_objects::SmartObject*
-InitialApplicationDataImpl::app_types() const {
+const smart_objects::SmartObject* InitialApplicationDataImpl::app_types()
+ const {
return app_types_;
}
-const smart_objects::SmartObject*
-InitialApplicationDataImpl::vr_synonyms() const {
+const smart_objects::SmartObject* InitialApplicationDataImpl::vr_synonyms()
+ const {
return vr_synonyms_;
}
-std::string InitialApplicationDataImpl::mobile_app_id() const {
+std::string InitialApplicationDataImpl::policy_app_id() const {
return mobile_app_id_;
}
@@ -93,13 +92,13 @@ InitialApplicationDataImpl::ngn_media_screen_name() const {
return ngn_media_screen_name_;
}
-const mobile_api::Language::eType&
-InitialApplicationDataImpl::language() const {
+const mobile_api::Language::eType& InitialApplicationDataImpl::language()
+ const {
return language_;
}
-const mobile_api::Language::eType&
-InitialApplicationDataImpl::ui_language() const {
+const mobile_api::Language::eType& InitialApplicationDataImpl::ui_language()
+ const {
return ui_language_;
}
@@ -153,28 +152,37 @@ void InitialApplicationDataImpl::set_ui_language(
ui_language_ = ui_language;
}
-DynamicApplicationDataImpl::DynamicApplicationDataImpl()
- : help_prompt_(NULL),
- timeout_prompt_(NULL),
- vr_help_title_(NULL),
- vr_help_(NULL),
- tbt_state_(mobile_api::TBTState::INVALID_ENUM),
- show_command_(NULL),
- keyboard_props_(NULL),
- menu_title_(NULL),
- menu_icon_(NULL),
- tbt_show_command_(NULL),
- commands_(),
- commands_lock_(true),
- sub_menu_(),
- choice_set_map_(),
- performinteraction_choice_set_map_(),
- performinteraction_choice_set_lock_(true),
- is_perform_interaction_active_(false),
- is_reset_global_properties_active_(false),
- perform_interaction_mode_(-1) {
+void InitialApplicationDataImpl::set_perform_interaction_layout(
+ mobile_apis::LayoutMode::eType layout) {
+ perform_interaction_layout_ = layout;
}
+mobile_apis::LayoutMode::eType
+InitialApplicationDataImpl::perform_interaction_layout() const {
+ return perform_interaction_layout_;
+}
+
+DynamicApplicationDataImpl::DynamicApplicationDataImpl()
+ : help_prompt_(NULL)
+ , timeout_prompt_(NULL)
+ , vr_help_title_(NULL)
+ , vr_help_(NULL)
+ , tbt_state_(mobile_api::TBTState::INVALID_ENUM)
+ , show_command_(NULL)
+ , keyboard_props_(NULL)
+ , menu_title_(NULL)
+ , menu_icon_(NULL)
+ , tbt_show_command_(NULL)
+ , commands_()
+ , commands_lock_(true)
+ , sub_menu_()
+ , choice_set_map_()
+ , performinteraction_choice_set_map_()
+ , performinteraction_choice_set_lock_(true)
+ , is_perform_interaction_active_(false)
+ , is_reset_global_properties_active_(false)
+ , perform_interaction_mode_(-1) {}
+
DynamicApplicationDataImpl::~DynamicApplicationDataImpl() {
if (help_prompt_) {
delete help_prompt_;
@@ -207,82 +215,88 @@ DynamicApplicationDataImpl::~DynamicApplicationDataImpl() {
}
for (CommandsMap::iterator command_it = commands_.begin();
- commands_.end() != command_it; ++command_it) {
+ commands_.end() != command_it;
+ ++command_it) {
delete command_it->second;
}
commands_.clear();
for (SubMenuMap::iterator sub_menu_it = sub_menu_.begin();
- sub_menu_.end() != sub_menu_it; ++sub_menu_it) {
+ sub_menu_.end() != sub_menu_it;
+ ++sub_menu_it) {
delete sub_menu_it->second;
}
sub_menu_.clear();
PerformChoiceSetMap::iterator it = performinteraction_choice_set_map_.begin();
for (; performinteraction_choice_set_map_.end() != it; ++it) {
- PerformChoice::iterator choice_it = performinteraction_choice_set_map_[it->first].begin();
- for (; performinteraction_choice_set_map_[it->first].end() != choice_it; ++choice_it) {
- delete choice_it->second;
+ PerformChoice::iterator choice_it =
+ performinteraction_choice_set_map_[it->first].begin();
+ for (; performinteraction_choice_set_map_[it->first].end() != choice_it;
+ ++choice_it) {
+ delete choice_it->second;
}
performinteraction_choice_set_map_[it->first].clear();
}
performinteraction_choice_set_map_.clear();
}
-const smart_objects::SmartObject*
-DynamicApplicationDataImpl::help_prompt() const {
+const smart_objects::SmartObject* DynamicApplicationDataImpl::help_prompt()
+ const {
return help_prompt_;
}
-const smart_objects::SmartObject*
-DynamicApplicationDataImpl::timeout_prompt() const {
+const smart_objects::SmartObject* DynamicApplicationDataImpl::timeout_prompt()
+ const {
return timeout_prompt_;
}
-const smart_objects::SmartObject*
-DynamicApplicationDataImpl::vr_help_title() const {
+const smart_objects::SmartObject* DynamicApplicationDataImpl::vr_help_title()
+ const {
return vr_help_title_;
}
-const smart_objects::SmartObject*
-DynamicApplicationDataImpl::vr_help() const {
+const smart_objects::SmartObject* DynamicApplicationDataImpl::vr_help() const {
return vr_help_;
}
-const mobile_api::TBTState::eType&
-DynamicApplicationDataImpl::tbt_state() const {
+const mobile_api::TBTState::eType& DynamicApplicationDataImpl::tbt_state()
+ const {
return tbt_state_;
}
-const smart_objects::SmartObject*
-DynamicApplicationDataImpl::show_command() const {
+const smart_objects::SmartObject* DynamicApplicationDataImpl::show_command()
+ const {
return show_command_;
}
-const smart_objects::SmartObject*
-DynamicApplicationDataImpl::tbt_show_command() const {
+const smart_objects::SmartObject* DynamicApplicationDataImpl::tbt_show_command()
+ const {
return tbt_show_command_;
}
-const smart_objects::SmartObject* DynamicApplicationDataImpl::keyboard_props() const {
+const smart_objects::SmartObject* DynamicApplicationDataImpl::keyboard_props()
+ const {
return keyboard_props_;
}
-const smart_objects::SmartObject* DynamicApplicationDataImpl::menu_title() const {
+const smart_objects::SmartObject* DynamicApplicationDataImpl::menu_title()
+ const {
return menu_title_;
}
-const smart_objects::SmartObject* DynamicApplicationDataImpl::menu_icon() const {
+const smart_objects::SmartObject* DynamicApplicationDataImpl::menu_icon()
+ const {
return menu_icon_;
}
void DynamicApplicationDataImpl::load_global_properties(
const smart_objects::SmartObject& properties_so) {
SetGlobalProperties(properties_so.getElement(strings::vr_help_title),
- &DynamicApplicationData::set_vr_help_title);
+ &DynamicApplicationData::set_vr_help_title);
SetGlobalProperties(properties_so.getElement(strings::vr_help),
- &DynamicApplicationData::set_vr_help);
+ &DynamicApplicationData::set_vr_help);
SetGlobalProperties(properties_so.getElement(strings::timeout_prompt),
&DynamicApplicationData::set_timeout_prompt);
@@ -388,16 +402,15 @@ void DynamicApplicationDataImpl::set_menu_icon(
if (menu_icon_) {
delete menu_icon_;
}
- menu_icon_= new smart_objects::SmartObject(menu_icon);
+ menu_icon_ = new smart_objects::SmartObject(menu_icon);
}
void DynamicApplicationDataImpl::SetGlobalProperties(
const smart_objects::SmartObject& param,
void (DynamicApplicationData::*callback)(
- const NsSmartDeviceLink::NsSmartObjects::SmartObject&)) {
-
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject&)) {
smart_objects::SmartType so_type = param.getType();
- if (so_type != smart_objects::SmartType::SmartType_Invalid &&
+ if (so_type != smart_objects::SmartType::SmartType_Invalid &&
so_type != smart_objects::SmartType::SmartType_Null) {
if (callback) {
(this->*callback)(param);
@@ -408,7 +421,7 @@ void DynamicApplicationDataImpl::SetGlobalProperties(
}
void DynamicApplicationDataImpl::AddCommand(
- uint32_t cmd_id, const smart_objects::SmartObject& command) {
+ uint32_t cmd_id, const smart_objects::SmartObject& command) {
sync_primitives::AutoLock lock(commands_lock_);
CommandsMap::const_iterator it = commands_.find(cmd_id);
if (commands_.end() == it) {
@@ -438,7 +451,7 @@ smart_objects::SmartObject* DynamicApplicationDataImpl::FindCommand(
// TODO(VS): Create common functions for processing collections
void DynamicApplicationDataImpl::AddSubMenu(
- uint32_t menu_id, const smart_objects::SmartObject& menu) {
+ uint32_t menu_id, const smart_objects::SmartObject& menu) {
sync_primitives::AutoLock lock(sub_menu_lock_);
SubMenuMap::const_iterator it = sub_menu_.find(menu_id);
if (sub_menu_.end() == it) {
@@ -470,8 +483,7 @@ smart_objects::SmartObject* DynamicApplicationDataImpl::FindSubMenu(
bool DynamicApplicationDataImpl::IsSubMenuNameAlreadyExist(
const std::string& name) {
sync_primitives::AutoLock lock(sub_menu_lock_);
- for (SubMenuMap::iterator it = sub_menu_.begin();
- sub_menu_.end() != it;
+ for (SubMenuMap::iterator it = sub_menu_.begin(); sub_menu_.end() != it;
++it) {
smart_objects::SmartObject* menu = it->second;
if ((*menu)[strings::menu_name] == name) {
@@ -482,7 +494,7 @@ bool DynamicApplicationDataImpl::IsSubMenuNameAlreadyExist(
}
void DynamicApplicationDataImpl::AddChoiceSet(
- uint32_t choice_set_id, const smart_objects::SmartObject& choice_set) {
+ uint32_t choice_set_id, const smart_objects::SmartObject& choice_set) {
sync_primitives::AutoLock lock(choice_set_map_lock_);
ChoiceSetMap::const_iterator it = choice_set_map_.find(choice_set_id);
if (choice_set_map_.end() == it) {
@@ -512,15 +524,16 @@ smart_objects::SmartObject* DynamicApplicationDataImpl::FindChoiceSet(
}
void DynamicApplicationDataImpl::AddPerformInteractionChoiceSet(
- uint32_t correlation_id, uint32_t choice_set_id,
- const smart_objects::SmartObject& vr_commands) {
+ uint32_t correlation_id,
+ uint32_t choice_set_id,
+ const smart_objects::SmartObject& vr_commands) {
sync_primitives::AutoLock lock(performinteraction_choice_set_lock_);
- performinteraction_choice_set_map_[correlation_id].insert(
- std::make_pair(choice_set_id, new smart_objects::SmartObject(vr_commands)));
+ performinteraction_choice_set_map_[correlation_id].insert(std::make_pair(
+ choice_set_id, new smart_objects::SmartObject(vr_commands)));
}
void DynamicApplicationDataImpl::DeletePerformInteractionChoiceSet(
- uint32_t correlation_id) {
+ uint32_t correlation_id) {
sync_primitives::AutoLock lock(performinteraction_choice_set_lock_);
PerformChoice::iterator it =
performinteraction_choice_set_map_[correlation_id].begin();
diff --git a/src/components/application_manager/src/application_impl.cc b/src/components/application_manager/src/application_impl.cc
index 59b3830447..61451e3602 100644
--- a/src/components/application_manager/src/application_impl.cc
+++ b/src/components/application_manager/src/application_impl.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,17 +30,20 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
+#include "application_manager/application_impl.h"
#include <string>
#include <strings.h>
-#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
-#include "application_manager/application_manager_impl.h"
#include "protocol_handler/protocol_handler.h"
+#include "application_manager/application_manager.h"
#include "config_profile/profile.h"
#include "interfaces/MOBILE_API.h"
#include "utils/file_system.h"
#include "utils/logger.h"
#include "utils/gen_hash.h"
+#include "utils/make_shared.h"
+#include "utils/timer_task_impl.h"
+#include "application_manager/policies/policy_handler_interface.h"
namespace {
@@ -55,14 +58,10 @@ mobile_apis::FileType::eType StringToFileType(const char* str) {
return mobile_apis::FileType::GRAPHIC_PNG;
} else if (0 == strcasecmp(str, "wave")) {
return mobile_apis::FileType::AUDIO_WAVE;
- } else if ((0 == strcasecmp(str, "m4a")) ||
- (0 == strcasecmp(str, "m4b")) ||
- (0 == strcasecmp(str, "m4p")) ||
- (0 == strcasecmp(str, "m4v")) ||
- (0 == strcasecmp(str, "m4r")) ||
- (0 == strcasecmp(str, "3gp")) ||
- (0 == strcasecmp(str, "mp4")) ||
- (0 == strcasecmp(str, "aac"))) {
+ } else if ((0 == strcasecmp(str, "m4a")) || (0 == strcasecmp(str, "m4b")) ||
+ (0 == strcasecmp(str, "m4p")) || (0 == strcasecmp(str, "m4v")) ||
+ (0 == strcasecmp(str, "m4r")) || (0 == strcasecmp(str, "3gp")) ||
+ (0 == strcasecmp(str, "mp4")) || (0 == strcasecmp(str, "aac"))) {
return mobile_apis::FileType::AUDIO_AAC;
} else if (0 == strcasecmp(str, "mp3")) {
return mobile_apis::FileType::AUDIO_MP3;
@@ -72,44 +71,59 @@ mobile_apis::FileType::eType StringToFileType(const char* str) {
}
}
-namespace application_manager {
-
CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationManager")
-ApplicationImpl::ApplicationImpl(uint32_t application_id,
+namespace application_manager {
+
+ApplicationImpl::ApplicationImpl(
+ uint32_t application_id,
const std::string& mobile_app_id,
- const std::string& app_name,
- utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager)
- : grammar_id_(0),
- hmi_app_id_(0),
- app_id_(application_id),
- active_message_(NULL),
- is_media_(false),
- is_navi_(false),
- video_streaming_approved_(false),
- audio_streaming_approved_(false),
- video_streaming_allowed_(false),
- audio_streaming_allowed_(false),
- video_streaming_suspended_(true),
- audio_streaming_suspended_(true),
- is_app_allowed_(true),
- has_been_activated_(false),
- tts_properties_in_none_(false),
- tts_properties_in_full_(false),
- put_file_in_none_count_(0),
- delete_file_in_none_count_(0),
- list_files_in_none_count_(0),
- device_(0),
- usage_report_(mobile_app_id, statistics_manager),
- protocol_version_(ProtocolVersion::kV3),
- is_voice_communication_application_(false),
- video_stream_retry_number_(0),
- audio_stream_retry_number_(0) {
-
- cmd_number_to_time_limits_[mobile_apis::FunctionID::ReadDIDID] =
- {date_time::DateTime::getCurrentTime(), 0};
- cmd_number_to_time_limits_[mobile_apis::FunctionID::GetVehicleDataID] =
- {date_time::DateTime::getCurrentTime(), 0};
+ const std::string& mac_address,
+ const custom_str::CustomString& app_name,
+ utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager,
+ ApplicationManager& application_manager)
+ : grammar_id_(0)
+ , hmi_app_id_(0)
+ , app_id_(application_id)
+ , active_message_(NULL)
+ , is_media_(false)
+ , is_navi_(false)
+ , video_streaming_approved_(false)
+ , audio_streaming_approved_(false)
+ , video_streaming_allowed_(false)
+ , audio_streaming_allowed_(false)
+ , video_streaming_suspended_(true)
+ , audio_streaming_suspended_(true)
+ , is_app_allowed_(true)
+ , has_been_activated_(false)
+ , tts_properties_in_none_(false)
+ , tts_properties_in_full_(false)
+ , is_foreground_(false)
+ , is_application_data_changed_(false)
+ , put_file_in_none_count_(0)
+ , delete_file_in_none_count_(0)
+ , list_files_in_none_count_(0)
+ , device_(0)
+ , mac_address_(mac_address)
+ , usage_report_(mobile_app_id, statistics_manager)
+ , protocol_version_(ProtocolVersion::kV3)
+ , is_voice_communication_application_(false)
+ , is_resuming_(false)
+ , video_stream_retry_number_(0)
+ , audio_stream_retry_number_(0)
+ , video_stream_suspend_timer_(
+ "VideoStreamSuspend",
+ new ::timer::TimerTaskImpl<ApplicationImpl>(
+ this, &ApplicationImpl::OnVideoStreamSuspend))
+ , audio_stream_suspend_timer_(
+ "AudioStreamSuspend",
+ new ::timer::TimerTaskImpl<ApplicationImpl>(
+ this, &ApplicationImpl::OnAudioStreamSuspend))
+ , application_manager_(application_manager) {
+ cmd_number_to_time_limits_[mobile_apis::FunctionID::ReadDIDID] = {
+ date_time::DateTime::getCurrentTime(), 0};
+ cmd_number_to_time_limits_[mobile_apis::FunctionID::GetVehicleDataID] = {
+ date_time::DateTime::getCurrentTime(), 0};
set_mobile_app_id(mobile_app_id);
set_name(app_name);
@@ -117,29 +131,19 @@ ApplicationImpl::ApplicationImpl(uint32_t application_id,
MarkUnregistered();
// subscribe application to custom button by default
SubscribeToButton(mobile_apis::ButtonName::CUSTOM_BUTTON);
-
// load persistent files
LoadPersistentFiles();
- HmiStatePtr initial_state =
- ApplicationManagerImpl::instance()->CreateRegularState(app_id(),
- mobile_apis::HMILevel::INVALID_ENUM,
- mobile_apis::AudioStreamingState::INVALID_ENUM,
- mobile_api::SystemContext::SYSCTXT_MAIN);
- hmi_states_.push_back(initial_state);
+ HmiStatePtr initial_state = application_manager_.CreateRegularState(
+ app_id(),
+ mobile_apis::HMILevel::INVALID_ENUM,
+ mobile_apis::AudioStreamingState::INVALID_ENUM,
+ mobile_api::SystemContext::SYSCTXT_MAIN);
+ state_.InitState(initial_state);
video_stream_suspend_timeout_ =
- profile::Profile::instance()->video_data_stopped_timeout() / 1000;
+ application_manager_.get_settings().video_data_stopped_timeout();
audio_stream_suspend_timeout_ =
- profile::Profile::instance()->audio_data_stopped_timeout() / 1000;
-
- video_stream_suspend_timer_ = ApplicationTimerPtr(
- new timer::TimerThread<ApplicationImpl>(
- "VideoStreamSuspend", this,
- &ApplicationImpl::OnVideoStreamSuspend, true));
- audio_stream_suspend_timer_ = ApplicationTimerPtr(
- new timer::TimerThread<ApplicationImpl>(
- "AudioStreamSuspend", this,
- &ApplicationImpl::OnAudioStreamSuspend, true));
+ application_manager_.get_settings().audio_data_stopped_timeout();
}
ApplicationImpl::~ApplicationImpl() {
@@ -187,7 +191,6 @@ void ApplicationImpl::ChangeSupportingAppHMIType() {
}
}
-
void ApplicationImpl::set_is_navi(bool allow) {
is_navi_ = allow;
}
@@ -202,74 +205,52 @@ void ApplicationImpl::set_voice_communication_supported(
}
bool ApplicationImpl::IsAudioApplication() const {
- return is_media_ ||
- is_voice_communication_application_ ||
- is_navi_;
+ return is_media_ || is_voice_communication_application_ || is_navi_;
}
void ApplicationImpl::SetRegularState(HmiStatePtr state) {
- DCHECK_OR_RETURN_VOID(state);
- sync_primitives::AutoLock auto_lock(hmi_states_lock_);
- DCHECK_OR_RETURN_VOID(!hmi_states_.empty());
- hmi_states_.erase(hmi_states_.begin());
- if (hmi_states_.begin() != hmi_states_.end()) {
- HmiStatePtr first_temp = hmi_states_.front();
- DCHECK_OR_RETURN_VOID(first_temp);
- first_temp->set_parent(state);
- }
- hmi_states_.push_front(state);
+ LOG4CXX_AUTO_TRACE(logger_);
+ state_.AddState(state);
}
-void ApplicationImpl::AddHMIState(HmiStatePtr state) {
- DCHECK_OR_RETURN_VOID(state);
- sync_primitives::AutoLock auto_lock(hmi_states_lock_);
- hmi_states_.push_back(state);
+void ApplicationImpl::RemovePostponedState() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ state_.RemoveState(HmiState::STATE_ID_POSTPONED);
}
-struct StateIdFindPredicate {
- HmiState::StateID state_id_;
- StateIdFindPredicate(HmiState::StateID state_id):
- state_id_(state_id) {}
- bool operator ()(const HmiStatePtr cur) {
- return cur->state_id() == state_id_;
- }
+void ApplicationImpl::SetPostponedState(HmiStatePtr state) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ state_.AddState(state);
+}
+
+struct StateIDComparator {
+ HmiState::StateID state_id_;
+ StateIDComparator(HmiState::StateID state_id) : state_id_(state_id) {}
+ bool operator()(const HmiStatePtr cur) {
+ return cur->state_id() == state_id_;
+ }
};
+void ApplicationImpl::AddHMIState(HmiStatePtr state) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ state_.AddState(state);
+}
+
void ApplicationImpl::RemoveHMIState(HmiState::StateID state_id) {
LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock auto_lock(hmi_states_lock_);
- HmiStateList::iterator it =
- std::find_if(hmi_states_.begin(), hmi_states_.end(),
- StateIdFindPredicate(state_id));
- if (it != hmi_states_.end()) {
- // unable to remove regular state
- DCHECK_OR_RETURN_VOID(it != hmi_states_.begin());
- HmiStateList::iterator next = it;
- HmiStateList::iterator prev = it;
- next++;
- prev--;
- if (next != hmi_states_.end()) {
- HmiStatePtr next_state = *next;
- HmiStatePtr prev_state = *prev;
- next_state->set_parent(prev_state);
- }
- hmi_states_.erase(it);
- } else {
- LOG4CXX_ERROR(logger_, "Unsuccesfull remove HmiState: " << state_id);
- }
+ state_.RemoveState(state_id);
}
const HmiStatePtr ApplicationImpl::CurrentHmiState() const {
- sync_primitives::AutoLock auto_lock(hmi_states_lock_);
- DCHECK_OR_RETURN(!hmi_states_.empty(), HmiStatePtr());
- //TODO(APPLINK-11448) Need implement
- return hmi_states_.back();
+ return state_.GetState(HmiState::STATE_ID_CURRENT);
}
-const HmiStatePtr ApplicationImpl::RegularHmiState() const{
- //sync_primitives::AutoLock auto_lock(hmi_states_lock_);
- DCHECK_OR_RETURN(!hmi_states_.empty(), HmiStatePtr());
- return hmi_states_.front();
+const HmiStatePtr ApplicationImpl::RegularHmiState() const {
+ return state_.GetState(HmiState::STATE_ID_REGULAR);
+}
+
+const HmiStatePtr ApplicationImpl::PostponedHmiState() const {
+ return state_.GetState(HmiState::STATE_ID_POSTPONED);
}
const smart_objects::SmartObject* ApplicationImpl::active_message() const {
@@ -284,12 +265,16 @@ void ApplicationImpl::set_hmi_application_id(uint32_t hmi_app_id) {
hmi_app_id_ = hmi_app_id;
}
-const std::string& ApplicationImpl::name() const {
+const custom_str::CustomString& ApplicationImpl::name() const {
return app_name_;
}
+void ApplicationImpl::set_folder_name(const std::string& folder_name) {
+ folder_name_ = folder_name;
+}
+
const std::string ApplicationImpl::folder_name() const {
- return name() + mobile_app_id();
+ return folder_name_;
}
bool ApplicationImpl::is_media_application() const {
@@ -302,11 +287,11 @@ const mobile_api::HMILevel::eType ApplicationImpl::hmi_level() const {
return hmi_state ? hmi_state->hmi_level() : HMILevel::INVALID_ENUM;
}
-bool application_manager::ApplicationImpl::is_foreground() const {
+bool ApplicationImpl::is_foreground() const {
return is_foreground_;
}
-void application_manager::ApplicationImpl::set_foreground(bool is_foreground) {
+void ApplicationImpl::set_foreground(const bool is_foreground) {
is_foreground_ = is_foreground;
}
@@ -322,12 +307,11 @@ const uint32_t ApplicationImpl::list_files_in_none_count() const {
return list_files_in_none_count_;
}
-const mobile_api::SystemContext::eType
-ApplicationImpl::system_context() const {
+const mobile_api::SystemContext::eType ApplicationImpl::system_context() const {
using namespace mobile_apis;
const HmiStatePtr hmi_state = CurrentHmiState();
- return hmi_state ? hmi_state->system_context() :
- SystemContext::INVALID_ENUM;;
+ return hmi_state ? hmi_state->system_context() : SystemContext::INVALID_ENUM;
+ ;
}
const std::string& ApplicationImpl::app_icon_path() const {
@@ -338,11 +322,15 @@ connection_handler::DeviceHandle ApplicationImpl::device() const {
return device_;
}
+const std::string& ApplicationImpl::mac_address() const {
+ return mac_address_;
+}
+
void ApplicationImpl::set_version(const Version& ver) {
version_ = ver;
}
-void ApplicationImpl::set_name(const std::string& name) {
+void ApplicationImpl::set_name(const custom_str::CustomString& name) {
app_name_ = name;
}
@@ -351,18 +339,10 @@ void ApplicationImpl::set_is_media_application(bool is_media) {
}
bool IsTTSState(const HmiStatePtr state) {
- return state->state_id() == HmiState::STATE_ID_TTS_SESSION ;
+ return state->state_id() == HmiState::STATE_ID_TTS_SESSION;
}
-bool ApplicationImpl::tts_speak_state() {
- sync_primitives::AutoLock autolock(hmi_states_lock_);
- HmiStateList::const_iterator it =
- std::find_if(hmi_states_.begin(), hmi_states_.end(), IsTTSState);
- return it != hmi_states_.end();
-}
-
-void ApplicationImpl::set_tts_properties_in_none(
- bool active) {
+void ApplicationImpl::set_tts_properties_in_none(bool active) {
tts_properties_in_none_ = active;
}
@@ -370,8 +350,7 @@ bool ApplicationImpl::tts_properties_in_none() {
return tts_properties_in_none_;
}
-void ApplicationImpl::set_tts_properties_in_full(
- bool active) {
+void ApplicationImpl::set_tts_properties_in_full(bool active) {
tts_properties_in_full_ = active;
}
@@ -417,18 +396,36 @@ void ApplicationImpl::StartStreaming(
LOG4CXX_AUTO_TRACE(logger_);
if (ServiceType::kMobileNav == service_type) {
+ LOG4CXX_TRACE(logger_, "ServiceType = Video");
if (!video_streaming_approved()) {
- MessageHelper::SendNaviStartStream(app_id());
+ LOG4CXX_TRACE(logger_, "Video streaming not approved");
+ MessageHelper::SendNaviStartStream(app_id(), application_manager_);
set_video_stream_retry_number(0);
}
} else if (ServiceType::kAudio == service_type) {
+ LOG4CXX_TRACE(logger_, "ServiceType = Audio");
if (!audio_streaming_approved()) {
- MessageHelper::SendAudioStartStream(app_id());
- set_video_stream_retry_number(0);
+ LOG4CXX_TRACE(logger_, "Audio streaming not approved");
+ MessageHelper::SendAudioStartStream(app_id(), application_manager_);
+ set_audio_stream_retry_number(0);
}
}
}
+void ApplicationImpl::StopStreamingForce(
+ protocol_handler::ServiceType service_type) {
+ using namespace protocol_handler;
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ SuspendStreaming(service_type);
+
+ if (service_type == ServiceType::kMobileNav) {
+ StopNaviStreaming();
+ } else if (service_type == ServiceType::kAudio) {
+ StopAudioStreaming();
+ }
+}
+
void ApplicationImpl::StopStreaming(
protocol_handler::ServiceType service_type) {
using namespace protocol_handler;
@@ -436,40 +433,47 @@ void ApplicationImpl::StopStreaming(
SuspendStreaming(service_type);
- if (ServiceType::kMobileNav == service_type) {
- if (video_streaming_approved()) {
- video_stream_suspend_timer_->stop();
- MessageHelper::SendNaviStopStream(app_id());
- set_video_streaming_approved(false);
- }
- } else if (ServiceType::kAudio == service_type) {
- if (audio_streaming_approved()) {
- audio_stream_suspend_timer_->stop();
- MessageHelper::SendAudioStopStream(app_id());
- set_audio_streaming_approved(false);
- }
+ if (service_type == ServiceType::kMobileNav && video_streaming_approved()) {
+ StopNaviStreaming();
+ } else if (service_type == ServiceType::kAudio &&
+ audio_streaming_approved()) {
+ StopAudioStreaming();
}
}
+void ApplicationImpl::StopNaviStreaming() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ video_stream_suspend_timer_.Stop();
+ MessageHelper::SendNaviStopStream(app_id(), application_manager_);
+ set_video_streaming_approved(false);
+ set_video_stream_retry_number(0);
+}
+
+void ApplicationImpl::StopAudioStreaming() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ audio_stream_suspend_timer_.Stop();
+ MessageHelper::SendAudioStopStream(app_id(), application_manager_);
+ set_audio_streaming_approved(false);
+ set_audio_stream_retry_number(0);
+}
+
void ApplicationImpl::SuspendStreaming(
protocol_handler::ServiceType service_type) {
using namespace protocol_handler;
LOG4CXX_AUTO_TRACE(logger_);
if (ServiceType::kMobileNav == service_type) {
- video_stream_suspend_timer_->suspend();
- ApplicationManagerImpl::instance()->OnAppStreaming(
- app_id(), service_type, false);
+ video_stream_suspend_timer_.Stop();
+ application_manager_.OnAppStreaming(app_id(), service_type, false);
sync_primitives::AutoLock lock(video_streaming_suspended_lock_);
video_streaming_suspended_ = true;
} else if (ServiceType::kAudio == service_type) {
- audio_stream_suspend_timer_->suspend();
- ApplicationManagerImpl::instance()->OnAppStreaming(
- app_id(), service_type, false);
+ audio_stream_suspend_timer_.Stop();
+ application_manager_.OnAppStreaming(app_id(), service_type, false);
sync_primitives::AutoLock lock(audio_streaming_suspended_lock_);
audio_streaming_suspended_ = true;
}
- MessageHelper::SendOnDataStreaming(service_type, false);
+ MessageHelper::SendOnDataStreaming(service_type, false, application_manager_);
}
void ApplicationImpl::WakeUpStreaming(
@@ -480,21 +484,21 @@ void ApplicationImpl::WakeUpStreaming(
if (ServiceType::kMobileNav == service_type) {
sync_primitives::AutoLock lock(video_streaming_suspended_lock_);
if (video_streaming_suspended_) {
- ApplicationManagerImpl::instance()->OnAppStreaming(
- app_id(), service_type, true);
- MessageHelper::SendOnDataStreaming(ServiceType::kMobileNav, true);
+ application_manager_.OnAppStreaming(app_id(), service_type, true);
+ MessageHelper::SendOnDataStreaming(
+ ServiceType::kMobileNav, true, application_manager_);
video_streaming_suspended_ = false;
}
- video_stream_suspend_timer_->start(video_stream_suspend_timeout_);
+ video_stream_suspend_timer_.Start(video_stream_suspend_timeout_, false);
} else if (ServiceType::kAudio == service_type) {
sync_primitives::AutoLock lock(audio_streaming_suspended_lock_);
if (audio_streaming_suspended_) {
- ApplicationManagerImpl::instance()->OnAppStreaming(
- app_id(), service_type, true);
- MessageHelper::SendOnDataStreaming(ServiceType::kAudio, true);
+ application_manager_.OnAppStreaming(app_id(), service_type, true);
+ MessageHelper::SendOnDataStreaming(
+ ServiceType::kAudio, true, application_manager_);
audio_streaming_suspended_ = false;
}
- audio_stream_suspend_timer_->start(audio_stream_suspend_timeout_);
+ audio_stream_suspend_timer_.Start(audio_stream_suspend_timeout_, false);
}
}
@@ -550,7 +554,7 @@ bool ApplicationImpl::set_app_icon_path(const std::string& path) {
return false;
}
-void ApplicationImpl::set_app_allowed(const bool& allowed) {
+void ApplicationImpl::set_app_allowed(const bool allowed) {
is_app_allowed_ = allowed;
}
@@ -567,9 +571,9 @@ void ApplicationImpl::set_grammar_id(uint32_t value) {
}
void ApplicationImpl::ResetDataInNone() {
- put_file_in_none_count_ = 0;
- delete_file_in_none_count_ = 0;
- list_files_in_none_count_ = 0;
+ put_file_in_none_count_ = 0;
+ delete_file_in_none_count_ = 0;
+ list_files_in_none_count_ = 0;
}
bool ApplicationImpl::has_been_activated() const {
@@ -590,20 +594,30 @@ ProtocolVersion ApplicationImpl::protocol_version() const {
return protocol_version_;
}
-bool ApplicationImpl::AddFile(AppFile& file) {
+void ApplicationImpl::set_is_resuming(bool is_resuming) {
+ is_resuming_ = is_resuming;
+}
+
+bool ApplicationImpl::is_resuming() const {
+ return is_resuming_;
+}
+
+bool ApplicationImpl::AddFile(const AppFile& file) {
if (app_files_.count(file.file_name) == 0) {
- LOG4CXX_INFO(logger_, "AddFile file " << file.file_name
- << " File type is " << file.file_type);
+ LOG4CXX_INFO(logger_,
+ "AddFile file " << file.file_name << " File type is "
+ << file.file_type);
app_files_[file.file_name] = file;
return true;
}
return false;
}
-bool ApplicationImpl::UpdateFile(AppFile& file) {
+bool ApplicationImpl::UpdateFile(const AppFile& file) {
if (app_files_.count(file.file_name) != 0) {
- LOG4CXX_INFO(logger_, "UpdateFile file " << file.file_name
- << " File type is " << file.file_type);
+ LOG4CXX_INFO(logger_,
+ "UpdateFile file " << file.file_name << " File type is "
+ << file.file_type);
app_files_[file.file_name] = file;
return true;
}
@@ -613,8 +627,9 @@ bool ApplicationImpl::UpdateFile(AppFile& file) {
bool ApplicationImpl::DeleteFile(const std::string& file_name) {
AppFilesMap::iterator it = app_files_.find(file_name);
if (it != app_files_.end()) {
- LOG4CXX_INFO(logger_, "DeleteFile file " << it->second.file_name
- << " File type is " << it->second.file_type);
+ LOG4CXX_INFO(logger_,
+ "DeleteFile file " << it->second.file_name << " File type is "
+ << it->second.file_type);
app_files_.erase(it);
return true;
}
@@ -626,45 +641,47 @@ const AppFilesMap& ApplicationImpl::getAppFiles() const {
}
const AppFile* ApplicationImpl::GetFile(const std::string& file_name) {
- if (app_files_.find(file_name) != app_files_.end()) {
- return &(app_files_[file_name]);
- }
- return NULL;
+ if (app_files_.find(file_name) != app_files_.end()) {
+ return &(app_files_[file_name]);
+ }
+ return NULL;
}
-bool ApplicationImpl::SubscribeToButton(mobile_apis::ButtonName::eType btn_name) {
- size_t old_size = subscribed_buttons_.size();
- subscribed_buttons_.insert(btn_name);
- return (subscribed_buttons_.size() == old_size + 1);
+bool ApplicationImpl::SubscribeToButton(
+ mobile_apis::ButtonName::eType btn_name) {
+ sync_primitives::AutoLock lock(button_lock_);
+ return subscribed_buttons_.insert(btn_name).second;
}
-bool ApplicationImpl::IsSubscribedToButton(mobile_apis::ButtonName::eType btn_name) {
- std::set<mobile_apis::ButtonName::eType>::iterator it = subscribed_buttons_.find(btn_name);
+bool ApplicationImpl::IsSubscribedToButton(
+ mobile_apis::ButtonName::eType btn_name) {
+ sync_primitives::AutoLock lock(button_lock_);
+ std::set<mobile_apis::ButtonName::eType>::iterator it =
+ subscribed_buttons_.find(btn_name);
return (subscribed_buttons_.end() != it);
}
-bool ApplicationImpl::UnsubscribeFromButton(mobile_apis::ButtonName::eType btn_name) {
- size_t old_size = subscribed_buttons_.size();
- subscribed_buttons_.erase(btn_name);
- return (subscribed_buttons_.size() == old_size - 1);
+bool ApplicationImpl::UnsubscribeFromButton(
+ mobile_apis::ButtonName::eType btn_name) {
+ sync_primitives::AutoLock lock(button_lock_);
+ return subscribed_buttons_.erase(btn_name);
}
-bool ApplicationImpl::SubscribeToIVI(uint32_t vehicle_info_type_) {
- size_t old_size = subscribed_vehicle_info_.size();
- subscribed_vehicle_info_.insert(vehicle_info_type_);
- return (subscribed_vehicle_info_.size() == old_size + 1);
+bool ApplicationImpl::SubscribeToIVI(uint32_t vehicle_info_type) {
+ sync_primitives::AutoLock lock(vi_lock_);
+ return subscribed_vehicle_info_.insert(vehicle_info_type).second;
}
-bool ApplicationImpl::IsSubscribedToIVI(uint32_t vehicle_info_type_) {
- std::set<uint32_t>::iterator it = subscribed_vehicle_info_.find(
- vehicle_info_type_);
+bool ApplicationImpl::IsSubscribedToIVI(uint32_t vehicle_info_type) const {
+ sync_primitives::AutoLock lock(vi_lock_);
+ VehicleInfoSubscriptions::const_iterator it =
+ subscribed_vehicle_info_.find(vehicle_info_type);
return (subscribed_vehicle_info_.end() != it);
}
-bool ApplicationImpl::UnsubscribeFromIVI(uint32_t vehicle_info_type_) {
- size_t old_size = subscribed_vehicle_info_.size();
- subscribed_vehicle_info_.erase(vehicle_info_type_);
- return (subscribed_vehicle_info_.size() == old_size - 1);
+bool ApplicationImpl::UnsubscribeFromIVI(uint32_t vehicle_info_type) {
+ sync_primitives::AutoLock lock(vi_lock_);
+ return subscribed_vehicle_info_.erase(vehicle_info_type);
}
UsageStatistics& ApplicationImpl::usage_report() {
@@ -672,127 +689,144 @@ UsageStatistics& ApplicationImpl::usage_report() {
}
bool ApplicationImpl::IsCommandLimitsExceeded(
- mobile_apis::FunctionID::eType cmd_id,
- TLimitSource source) {
+ mobile_apis::FunctionID::eType cmd_id, TLimitSource source) {
TimevalStruct current = date_time::DateTime::getCurrentTime();
switch (source) {
- // In case of config file values there is COMMON limitations for number of
- // commands per certain time in seconds, i.e. 5 requests per 10 seconds with
- // any interval between them
- case CONFIG_FILE: {
- CommandNumberTimeLimit::iterator it =
- cmd_number_to_time_limits_.find(cmd_id);
- if (cmd_number_to_time_limits_.end() == it) {
- LOG4CXX_WARN(logger_, "Limits for command id " << cmd_id
- << "had not been set.");
- return true;
- }
+ // In case of config file values there is COMMON limitations for number of
+ // commands per certain time in seconds, i.e. 5 requests per 10 seconds with
+ // any interval between them
+ case CONFIG_FILE: {
+ CommandNumberTimeLimit::iterator it =
+ cmd_number_to_time_limits_.find(cmd_id);
+ if (cmd_number_to_time_limits_.end() == it) {
+ LOG4CXX_WARN(logger_,
+ "Limits for command id " << cmd_id << "had not been set.");
+ return true;
+ }
- TimeToNumberLimit& limit = it->second;
+ TimeToNumberLimit& limit = it->second;
- std::pair<uint32_t, int32_t> frequency_restrictions;
+ std::pair<uint32_t, int32_t> frequency_restrictions;
- if (mobile_apis::FunctionID::ReadDIDID == cmd_id) {
- frequency_restrictions =
- profile::Profile::instance()->read_did_frequency();
+ if (mobile_apis::FunctionID::ReadDIDID == cmd_id) {
+ frequency_restrictions =
+ application_manager_.get_settings().read_did_frequency();
- } else if (mobile_apis::FunctionID::GetVehicleDataID == cmd_id) {
- frequency_restrictions =
- profile::Profile::instance()->get_vehicle_data_frequency();
- } else {
- LOG4CXX_INFO(logger_, "No restrictions for request");
- return false;
- }
-
- LOG4CXX_INFO(logger_, "Time Info: " <<
- "\n Current: " << current.tv_sec <<
- "\n Limit: (" << limit.first.tv_sec << "," << limit.second << ")"
- "\n frequency_restrictions: (" << frequency_restrictions.first << "," << frequency_restrictions.second << ")"
- );
- if (current.tv_sec < limit.first.tv_sec + frequency_restrictions.second) {
- if (limit.second < frequency_restrictions.first) {
- ++limit.second;
+ } else if (mobile_apis::FunctionID::GetVehicleDataID == cmd_id) {
+ frequency_restrictions =
+ application_manager_.get_settings().get_vehicle_data_frequency();
+ } else {
+ LOG4CXX_INFO(logger_, "No restrictions for request");
return false;
}
- return true;
- }
- limit.first = current;
- limit.second = 1;
+ LOG4CXX_INFO(logger_,
+ "Time Info: "
+ << "\n Current: " << current.tv_sec << "\n Limit: ("
+ << limit.first.tv_sec << "," << limit.second
+ << ")"
+ "\n frequency_restrictions: ("
+ << frequency_restrictions.first << ","
+ << frequency_restrictions.second << ")");
+ if (current.tv_sec < limit.first.tv_sec + frequency_restrictions.second) {
+ if (limit.second < frequency_restrictions.first) {
+ ++limit.second;
+ return false;
+ }
+ return true;
+ }
- return false;
+ limit.first = current;
+ limit.second = 1;
- break;
- }
- // In case of policy table values, there is EVEN limitation for number of
- // commands per minute, e.g. 10 command per minute i.e. 1 command per 6 sec
- case POLICY_TABLE: {
- uint32_t cmd_limit = application_manager::MessageHelper::GetAppCommandLimit(
- mobile_app_id_);
+ return false;
- if (0 == cmd_limit) {
- return true;
+ break;
}
+ // In case of policy table values, there is EVEN limitation for number of
+ // commands per minute, e.g. 10 command per minute i.e. 1 command per 6 sec
+ case POLICY_TABLE: {
+ const policy::PolicyHandlerInterface& policy_handler =
+ application_manager_.GetPolicyHandler();
+ std::string priority;
+ policy_handler.GetPriority(policy_app_id(), &priority);
+ uint32_t cmd_limit = policy_handler.GetNotificationsNumber(priority);
+
+ if (0 == cmd_limit) {
+ return true;
+ }
- const uint32_t dummy_limit = 1;
- CommandNumberTimeLimit::iterator it =
- cmd_number_to_time_limits_.find(cmd_id);
- // If no command with cmd_id had been executed yet, just add to limits
- if (cmd_number_to_time_limits_.end() == it) {
- cmd_number_to_time_limits_[cmd_id] = {current, dummy_limit};
- return false;
- }
+ const uint32_t dummy_limit = 1;
+ CommandNumberTimeLimit::iterator it =
+ cmd_number_to_time_limits_.find(cmd_id);
+ // If no command with cmd_id had been executed yet, just add to limits
+ if (cmd_number_to_time_limits_.end() == it) {
+ cmd_number_to_time_limits_[cmd_id] = {current, dummy_limit};
+ return false;
+ }
- const uint32_t minute = 60;
+ const uint32_t minute = 60;
- TimeToNumberLimit& limit = it->second;
+ TimeToNumberLimit& limit = it->second;
- // Checking even limitation for command
- if (static_cast<uint32_t>(current.tv_sec - limit.first.tv_sec) <
- minute/cmd_limit) {
- return true;
- }
+ // Checking even limitation for command
+ if (static_cast<uint32_t>(current.tv_sec - limit.first.tv_sec) <
+ minute / cmd_limit) {
+ return true;
+ }
- cmd_number_to_time_limits_[cmd_id] = {current, dummy_limit};
+ cmd_number_to_time_limits_[cmd_id] = {current, dummy_limit};
- return false;
- break;
- }
- default: {
- LOG4CXX_WARN(logger_, "Limit source is not implemented.");
- break;
- }
+ return false;
+ break;
+ }
+ default: {
+ LOG4CXX_WARN(logger_, "Limit source is not implemented.");
+ break;
+ }
}
return true;
}
-const std::set<mobile_apis::ButtonName::eType>& ApplicationImpl::SubscribedButtons() const {
- return subscribed_buttons_;
+DataAccessor<ButtonSubscriptions> ApplicationImpl::SubscribedButtons() const {
+ return DataAccessor<ButtonSubscriptions>(subscribed_buttons_, button_lock_);
}
-const std::set<uint32_t>& ApplicationImpl::SubscribesIVI() const {
- return subscribed_vehicle_info_;
+DataAccessor<VehicleInfoSubscriptions> ApplicationImpl::SubscribedIVI() const {
+ return DataAccessor<VehicleInfoSubscriptions>(subscribed_vehicle_info_,
+ vi_lock_);
}
const std::string& ApplicationImpl::curHash() const {
return hash_val_;
}
+bool ApplicationImpl::is_application_data_changed() const {
+ return is_application_data_changed_;
+}
+
+void ApplicationImpl::set_is_application_data_changed(
+ bool state_application_data) {
+ is_application_data_changed_ = state_application_data;
+}
+
void ApplicationImpl::UpdateHash() {
LOG4CXX_AUTO_TRACE(logger_);
- hash_val_ = utils::gen_hash(profile::Profile::instance()->hash_string_size());
- MessageHelper::SendHashUpdateNotification(app_id());
+ hash_val_ =
+ utils::gen_hash(application_manager_.get_settings().hash_string_size());
+ set_is_application_data_changed(true);
+
+ MessageHelper::SendHashUpdateNotification(app_id(), application_manager_);
}
void ApplicationImpl::CleanupFiles() {
std::string directory_name =
- profile::Profile::instance()->app_storage_folder();
+ application_manager_.get_settings().app_storage_folder();
directory_name += "/" + folder_name();
if (file_system::DirectoryExists(directory_name)) {
- std::vector<std::string> files = file_system::ListFiles(
- directory_name);
+ std::vector<std::string> files = file_system::ListFiles(directory_name);
AppFilesMap::const_iterator app_files_it;
std::vector<std::string>::const_iterator it = files.begin();
@@ -804,7 +838,7 @@ void ApplicationImpl::CleanupFiles() {
if ((app_files_it == app_files_.end()) ||
(!app_files_it->second.is_persistent)) {
LOG4CXX_INFO(logger_, "DeleteFile file " << file_name);
- file_system::DeleteFile(file_name);
+ file_system::DeleteFile(file_name);
}
}
@@ -817,7 +851,8 @@ void ApplicationImpl::LoadPersistentFiles() {
using namespace profile;
if (kWaitingForRegistration == app_state_) {
- const std::string app_icon_dir(Profile::instance()->app_icons_folder());
+ const std::string app_icon_dir(
+ application_manager_.get_settings().app_icons_folder());
const std::string full_icon_path(app_icon_dir + "/" + mobile_app_id_);
if (file_system::FileExists(full_icon_path)) {
AppFile file;
@@ -830,7 +865,8 @@ void ApplicationImpl::LoadPersistentFiles() {
return;
}
- std::string directory_name = Profile::instance()->app_storage_folder();
+ std::string directory_name =
+ application_manager_.get_settings().app_storage_folder();
directory_name += "/" + folder_name();
if (file_system::DirectoryExists(directory_name)) {
@@ -853,17 +889,46 @@ void ApplicationImpl::LoadPersistentFiles() {
file.file_type = StringToFileType(file_type.c_str());
}
- LOG4CXX_INFO(logger_, "Loaded persistent file " << file.file_name
- << " File type is " << file.file_type);
+ LOG4CXX_INFO(logger_,
+ "Loaded persistent file "
+ << file.file_name << " File type is " << file.file_type);
AddFile(file);
}
}
}
-void ApplicationImpl::SubscribeToSoftButtons(int32_t cmd_id,
- const SoftButtonID& softbuttons_id) {
+uint32_t ApplicationImpl::GetAvailableDiskSpace() {
+ const uint32_t app_quota =
+ application_manager_.get_settings().app_dir_quota();
+ std::string app_storage_path =
+ application_manager_.get_settings().app_storage_folder();
+
+ app_storage_path += "/";
+ app_storage_path += folder_name();
+
+ if (file_system::DirectoryExists(app_storage_path)) {
+ size_t size_of_directory = file_system::DirectorySize(app_storage_path);
+ if (app_quota < size_of_directory) {
+ return 0;
+ }
+
+ uint32_t current_app_quota = app_quota - size_of_directory;
+ uint32_t available_disk_space =
+ file_system::GetAvailableDiskSpace(app_storage_path);
+
+ if (current_app_quota > available_disk_space) {
+ return available_disk_space;
+ }
+ return current_app_quota;
+ }
+ return app_quota;
+}
+
+void ApplicationImpl::SubscribeToSoftButtons(
+ int32_t cmd_id, const SoftButtonID& softbuttons_id) {
sync_primitives::AutoLock lock(cmd_softbuttonid_lock_);
- if (static_cast<int32_t>(mobile_apis::FunctionID::ScrollableMessageID) == cmd_id) {
+ if (static_cast<int32_t>(mobile_apis::FunctionID::ScrollableMessageID) ==
+ cmd_id) {
CommandSoftButtonID::iterator it = cmd_softbuttonid_.find(cmd_id);
if (cmd_softbuttonid_.end() == it) {
cmd_softbuttonid_[cmd_id] = softbuttons_id;
@@ -877,7 +942,7 @@ bool ApplicationImpl::IsSubscribedToSoftButton(const uint32_t softbutton_id) {
sync_primitives::AutoLock lock(cmd_softbuttonid_lock_);
CommandSoftButtonID::iterator it = cmd_softbuttonid_.begin();
for (; it != cmd_softbuttonid_.end(); ++it) {
- if((it->second).find(softbutton_id) != (it->second).end()) {
+ if ((it->second).find(softbutton_id) != (it->second).end()) {
return true;
}
}
@@ -887,7 +952,7 @@ bool ApplicationImpl::IsSubscribedToSoftButton(const uint32_t softbutton_id) {
void ApplicationImpl::UnsubscribeFromSoftButtons(int32_t cmd_id) {
sync_primitives::AutoLock lock(cmd_softbuttonid_lock_);
CommandSoftButtonID::iterator it = cmd_softbuttonid_.find(cmd_id);
- if(it != cmd_softbuttonid_.end()) {
+ if (it != cmd_softbuttonid_.end()) {
cmd_softbuttonid_.erase(it);
}
}
diff --git a/src/components/application_manager/src/application_manager_impl.cc b/src/components/application_manager/src/application_manager_impl.cc
index 2aba14ec30..249fd04def 100644
--- a/src/components/application_manager/src/application_manager_impl.cc
+++ b/src/components/application_manager/src/application_manager_impl.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,7 +30,7 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include <stdlib.h> // for rand()
+#include <stdlib.h> // for rand()
#include <climits>
#include <string>
@@ -48,16 +48,20 @@
#include "hmi_message_handler/hmi_message_handler.h"
#include "connection_handler/connection_handler_impl.h"
#include "formatters/formatter_json_rpc.h"
-#include "formatters/CFormatterJsonSDLRPCv2.hpp"
-#include "formatters/CFormatterJsonSDLRPCv1.hpp"
-#include "config_profile/profile.h"
+#include "formatters/CFormatterJsonSDLRPCv2.h"
+#include "formatters/CFormatterJsonSDLRPCv1.h"
+
#include "utils/threads/thread.h"
#include "utils/file_system.h"
#include "utils/helpers.h"
+#include "utils/make_shared.h"
+#include "utils/timer_task_impl.h"
#include "smart_objects/enum_schema_item.h"
#include "interfaces/HMI_API_schema.h"
#include "application_manager/application_impl.h"
-#include "usage_statistics/counter.h"
+#include "media_manager/media_manager.h"
+#include "policy/usage_statistics/counter.h"
+#include "utils/custom_string.h"
#include <time.h>
namespace {
@@ -68,7 +72,16 @@ int get_rand_from_range(uint32_t from = 0, int to = RAND_MAX) {
namespace application_manager {
-CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationManager")
+namespace {
+DeviceTypes devicesType = {
+ std::make_pair(std::string("USB_AOA"),
+ hmi_apis::Common_TransportType::USB_AOA),
+ std::make_pair(std::string("USB_IOS"),
+ hmi_apis::Common_TransportType::USB_IOS),
+ std::make_pair(std::string("BLUETOOTH"),
+ hmi_apis::Common_TransportType::BLUETOOTH),
+ std::make_pair(std::string("WIFI"), hmi_apis::Common_TransportType::WIFI)};
+}
uint32_t ApplicationManagerImpl::corelation_id_ = 0;
const uint32_t ApplicationManagerImpl::max_corelation_id_ = UINT_MAX;
@@ -78,34 +91,50 @@ namespace jhs = NsSmartDeviceLink::NsJSONHandler::strings;
using namespace NsSmartDeviceLink::NsSmartObjects;
-ApplicationManagerImpl::ApplicationManagerImpl()
- : applications_list_lock_(true), audio_pass_thru_active_(false),
- is_distracting_driver_(false), is_vr_session_strated_(false),
- hmi_cooperating_(false), is_all_apps_allowed_(true), media_manager_(NULL),
- hmi_handler_(NULL), connection_handler_(NULL), protocol_handler_(NULL),
- request_ctrl_(), hmi_so_factory_(NULL), mobile_so_factory_(NULL),
- messages_from_mobile_("AM FromMobile", this),
- messages_to_mobile_("AM ToMobile", this),
- messages_from_hmi_("AM FromHMI", this),
- messages_to_hmi_("AM ToHMI", this),
- audio_pass_thru_messages_("AudioPassThru", this), hmi_capabilities_(this),
- unregister_reason_(
- mobile_api::AppInterfaceUnregisteredReason::INVALID_ENUM),
- resume_ctrl_(this),
- navi_close_app_timeout_(
- profile::Profile::instance()->stop_streaming_timeout()),
- navi_end_stream_timeout_(
- profile::Profile::instance()->stop_streaming_timeout()),
- stopping_flag_lock_(true),
-#ifdef TIME_TESTER
- metric_observer_(NULL),
-#endif // TIME_TESTER
- application_list_update_timer_(new ApplicationListUpdateTimer(this)),
- tts_global_properties_timer_(
- "TTSGLPRTimer", this,
- &ApplicationManagerImpl::OnTimerSendTTSGlobalProperties, true),
- is_low_voltage_(false), is_stopping_(false) {
-
+ApplicationManagerImpl::ApplicationManagerImpl(
+ const ApplicationManagerSettings& am_settings,
+ const policy::PolicySettings& policy_settings)
+ : settings_(am_settings)
+ , applications_list_lock_(true)
+ , audio_pass_thru_active_(false)
+ , is_distracting_driver_(false)
+ , is_vr_session_strated_(false)
+ , hmi_cooperating_(false)
+ , is_all_apps_allowed_(true)
+ , media_manager_(NULL)
+ , hmi_handler_(NULL)
+ , connection_handler_(NULL)
+ , policy_handler_(policy_settings, *this)
+ , protocol_handler_(NULL)
+ , request_ctrl_(am_settings)
+ , hmi_so_factory_(NULL)
+ , mobile_so_factory_(NULL)
+ , messages_from_mobile_("AM FromMobile", this)
+ , messages_to_mobile_("AM ToMobile", this)
+ , messages_from_hmi_("AM FromHMI", this)
+ , messages_to_hmi_("AM ToHMI", this)
+ , audio_pass_thru_messages_("AudioPassThru", this)
+ , hmi_capabilities_(*this)
+ , unregister_reason_(
+ mobile_api::AppInterfaceUnregisteredReason::INVALID_ENUM)
+ , resume_ctrl_(*this)
+ , navi_close_app_timeout_(am_settings.stop_streaming_timeout())
+ , navi_end_stream_timeout_(am_settings.stop_streaming_timeout())
+ , stopping_application_mng_lock_(true)
+ , state_ctrl_(*this)
+#ifdef TELEMETRY_MONITOR
+ , metric_observer_(NULL)
+#endif // TELEMETRY_MONITOR
+ , application_list_update_timer_(
+ "AM ListUpdater",
+ new TimerTaskImpl<ApplicationManagerImpl>(
+ this, &ApplicationManagerImpl::OnApplicationListUpdateTimer))
+ , tts_global_properties_timer_(
+ "AM TTSGLPRTimer",
+ new TimerTaskImpl<ApplicationManagerImpl>(
+ this, &ApplicationManagerImpl::OnTimerSendTTSGlobalProperties))
+ , is_low_voltage_(false)
+ , is_stopping_(false) {
std::srand(std::time(0));
AddPolicyObserver(this);
@@ -114,16 +143,17 @@ ApplicationManagerImpl::ApplicationManagerImpl()
{TYPE_ICONS, "Icons"}};
sync_primitives::AutoLock lock(timer_pool_lock_);
- ApplicationManagerTimerPtr clearTimerPoolTimer(
- new TimerThread<ApplicationManagerImpl>(
- "ClearTimerPoolTimer", this, &ApplicationManagerImpl::ClearTimerPool,
- true));
- clearTimerPoolTimer->start(10);
- timer_pool_.push_back(clearTimerPoolTimer);
+ TimerSPtr clearing_timer(utils::MakeShared<timer::Timer>(
+ "ClearTimerPoolTimer",
+ new TimerTaskImpl<ApplicationManagerImpl>(
+ this, &ApplicationManagerImpl::ClearTimerPool)));
+ const uint32_t timeout_ms = 10000u;
+ clearing_timer->Start(timeout_ms, false);
+ timer_pool_.push_back(clearing_timer);
}
ApplicationManagerImpl::~ApplicationManagerImpl() {
- LOG4CXX_INFO(logger_, "Destructing ApplicationManager.");
+ LOG4CXX_AUTO_TRACE(logger_);
is_stopping_ = true;
SendOnSDLClose();
@@ -139,10 +169,8 @@ ApplicationManagerImpl::~ApplicationManagerImpl() {
mobile_so_factory_ = NULL;
}
protocol_handler_ = NULL;
- media_manager_ = NULL;
- LOG4CXX_INFO(logger_, "Destroying Policy Handler");
+ LOG4CXX_DEBUG(logger_, "Destroying Policy Handler");
RemovePolicyObserver(this);
- policy::PolicyHandler::destroy();
sync_primitives::AutoLock lock(timer_pool_lock_);
timer_pool_.clear();
@@ -151,54 +179,57 @@ ApplicationManagerImpl::~ApplicationManagerImpl() {
navi_app_to_end_stream_.clear();
}
-bool ApplicationManagerImpl::Stop() {
- LOG4CXX_INFO(logger_, "Stop ApplicationManager.");
- stopping_flag_lock_.Acquire();
- is_stopping_ = true;
- stopping_flag_lock_.Release();
- application_list_update_timer_->stop();
- try {
- UnregisterAllApplications();
- } catch (...) {
- LOG4CXX_ERROR(logger_,
- "An error occurred during unregistering applications.");
+template <class UnaryPredicate>
+ApplicationSharedPtr FindApp(DataAccessor<ApplicationSet> accessor,
+ UnaryPredicate finder) {
+ ApplicationSet::iterator it = std::find_if(
+ accessor.GetData().begin(), accessor.GetData().end(), finder);
+ if (accessor.GetData().end() == it) {
+ LOG4CXX_DEBUG(logger_, "Unable to find application");
+ return ApplicationSharedPtr();
}
+ ApplicationSharedPtr app = *it;
+ LOG4CXX_DEBUG(logger_, " Found Application app_id = " << app->app_id());
+ return app;
+}
- request_ctrl_.DestroyThreadpool();
-
- // for PASA customer policy backup should happen :AllApp(SUSPEND)
- LOG4CXX_INFO(logger_, "Unloading policy library.");
- policy::PolicyHandler::instance()->UnloadPolicyLibrary();
+template <class UnaryPredicate>
+std::vector<ApplicationSharedPtr> FindAllApps(
+ DataAccessor<ApplicationSet> accessor, UnaryPredicate finder) {
+ std::vector<ApplicationSharedPtr> result;
+ ApplicationSetConstIt it = std::find_if(
+ accessor.GetData().begin(), accessor.GetData().end(), finder);
+ while (it != accessor.GetData().end()) {
+ result.push_back(*it);
+ it = std::find_if(++it, accessor.GetData().end(), finder);
+ }
+ return result;
+}
- return true;
+DataAccessor<ApplicationSet> ApplicationManagerImpl::applications() const {
+ DataAccessor<ApplicationSet> accessor(applications_, applications_list_lock_);
+ return accessor;
}
-ApplicationSharedPtr
-ApplicationManagerImpl::application(uint32_t app_id) const {
+ApplicationSharedPtr ApplicationManagerImpl::application(
+ uint32_t app_id) const {
AppIdPredicate finder(app_id);
- ApplicationListAccessor accessor;
- ApplicationSharedPtr app = accessor.Find(finder);
- LOG4CXX_DEBUG(logger_, " app_id << " << app_id << "Found = " << app);
- return app;
+ DataAccessor<ApplicationSet> accessor = applications();
+ return FindApp(accessor, finder);
}
-ApplicationSharedPtr
-ApplicationManagerImpl::application_by_hmi_app(uint32_t hmi_app_id) const {
+ApplicationSharedPtr ApplicationManagerImpl::application_by_hmi_app(
+ uint32_t hmi_app_id) const {
HmiAppIdPredicate finder(hmi_app_id);
- ApplicationListAccessor accessor;
- ApplicationSharedPtr app = accessor.Find(finder);
- LOG4CXX_DEBUG(logger_, " hmi_app_id << " << hmi_app_id << "Found = " << app);
- return app;
+ DataAccessor<ApplicationSet> accessor = applications();
+ return FindApp(accessor, finder);
}
ApplicationSharedPtr ApplicationManagerImpl::application_by_policy_id(
- const std::string &policy_app_id) const {
- MobileAppIdPredicate finder(policy_app_id);
- ApplicationListAccessor accessor;
- ApplicationSharedPtr app = accessor.Find(finder);
- LOG4CXX_DEBUG(logger_, " policy_app_id << " << policy_app_id
- << "Found = " << app);
- return app;
+ const std::string& policy_app_id) const {
+ PolicyAppIdPredicate finder(policy_app_id);
+ DataAccessor<ApplicationSet> accessor = applications();
+ return FindApp(accessor, finder);
}
bool ActiveAppPredicate(const ApplicationSharedPtr app) {
@@ -207,22 +238,18 @@ bool ActiveAppPredicate(const ApplicationSharedPtr app) {
ApplicationSharedPtr ApplicationManagerImpl::active_application() const {
// TODO(DK) : check driver distraction
- ApplicationListAccessor accessor;
- ApplicationSharedPtr app = accessor.Find(ActiveAppPredicate);
- LOG4CXX_DEBUG(logger_, " Found = " << app);
- return app;
+ DataAccessor<ApplicationSet> accessor = applications();
+ return FindApp(accessor, ActiveAppPredicate);
}
bool LimitedAppPredicate(const ApplicationSharedPtr app) {
return app ? app->hmi_level() == mobile_api::HMILevel::HMI_LIMITED : false;
}
-ApplicationSharedPtr
-ApplicationManagerImpl::get_limited_media_application() const {
- ApplicationListAccessor accessor;
- ApplicationSharedPtr app = accessor.Find(LimitedAppPredicate);
- LOG4CXX_DEBUG(logger_, " Found = " << app);
- return app;
+ApplicationSharedPtr ApplicationManagerImpl::get_limited_media_application()
+ const {
+ DataAccessor<ApplicationSet> accessor = applications();
+ return FindApp(accessor, LimitedAppPredicate);
}
bool LimitedNaviAppPredicate(const ApplicationSharedPtr app) {
@@ -231,12 +258,10 @@ bool LimitedNaviAppPredicate(const ApplicationSharedPtr app) {
: false;
}
-ApplicationSharedPtr
-ApplicationManagerImpl::get_limited_navi_application() const {
- ApplicationListAccessor accessor;
- ApplicationSharedPtr app = accessor.Find(LimitedNaviAppPredicate);
- LOG4CXX_DEBUG(logger_, " Found = " << app);
- return app;
+ApplicationSharedPtr ApplicationManagerImpl::get_limited_navi_application()
+ const {
+ DataAccessor<ApplicationSet> accessor = applications();
+ return FindApp(accessor, LimitedNaviAppPredicate);
}
bool LimitedVoiceAppPredicate(const ApplicationSharedPtr app) {
@@ -245,12 +270,10 @@ bool LimitedVoiceAppPredicate(const ApplicationSharedPtr app) {
: false;
}
-ApplicationSharedPtr
-ApplicationManagerImpl::get_limited_voice_application() const {
- ApplicationListAccessor accessor;
- ApplicationSharedPtr app = accessor.Find(LimitedVoiceAppPredicate);
- LOG4CXX_DEBUG(logger_, " Found = " << app);
- return app;
+ApplicationSharedPtr ApplicationManagerImpl::get_limited_voice_application()
+ const {
+ DataAccessor<ApplicationSet> accessor = applications();
+ return FindApp(accessor, LimitedVoiceAppPredicate);
}
bool NaviAppPredicate(const ApplicationSharedPtr app) {
@@ -259,52 +282,68 @@ bool NaviAppPredicate(const ApplicationSharedPtr app) {
std::vector<ApplicationSharedPtr>
ApplicationManagerImpl::applications_with_navi() {
- ApplicationListAccessor accessor;
- std::vector<ApplicationSharedPtr> apps = accessor.FindAll(NaviAppPredicate);
- LOG4CXX_DEBUG(logger_, " Found count: " << apps.size());
- return apps;
+ DataAccessor<ApplicationSet> accessor = applications();
+ return FindAllApps(accessor, NaviAppPredicate);
}
std::vector<ApplicationSharedPtr>
ApplicationManagerImpl::applications_by_button(uint32_t button) {
SubscribedToButtonPredicate finder(
static_cast<mobile_apis::ButtonName::eType>(button));
- ApplicationListAccessor accessor;
- std::vector<ApplicationSharedPtr> apps = accessor.FindAll(finder);
- LOG4CXX_DEBUG(logger_, " Found count: " << apps.size());
- return apps;
+ DataAccessor<ApplicationSet> accessor = applications();
+ return FindAllApps(accessor, finder);
}
-std::vector<ApplicationSharedPtr>
-ApplicationManagerImpl::IviInfoUpdated(VehicleDataType vehicle_info,
- int value) {
+struct SubscribedToIVIPredicate {
+ int32_t vehicle_info_;
+ SubscribedToIVIPredicate(int32_t vehicle_info)
+ : vehicle_info_(vehicle_info) {}
+ bool operator()(const ApplicationSharedPtr app) const {
+ return app ? app->IsSubscribedToIVI(vehicle_info_) : false;
+ }
+};
+std::vector<ApplicationSharedPtr> ApplicationManagerImpl::IviInfoUpdated(
+ VehicleDataType vehicle_info, int value) {
// Notify Policy Manager if available about info it's interested in,
// i.e. odometer etc
switch (vehicle_info) {
- case ODOMETER:
- policy::PolicyHandler::instance()->KmsChanged(value);
- break;
- default:
- break;
+ case ODOMETER:
+ GetPolicyHandler().KmsChanged(value);
+ break;
+ default:
+ break;
}
SubscribedToIVIPredicate finder(static_cast<int32_t>(vehicle_info));
- ApplicationListAccessor accessor;
- std::vector<ApplicationSharedPtr> apps = accessor.FindAll(finder);
- LOG4CXX_DEBUG(logger_, " vehicle_info << " << vehicle_info
- << "Found count: " << apps.size());
- return apps;
+ DataAccessor<ApplicationSet> accessor = applications();
+ return FindAllApps(accessor, finder);
}
void ApplicationManagerImpl::OnApplicationRegistered(ApplicationSharedPtr app) {
+ LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN_VOID(app);
sync_primitives::AutoLock lock(applications_list_lock_);
const mobile_apis::HMILevel::eType default_level = GetDefaultHmiLevel(app);
state_ctrl_.OnApplicationRegistered(app, default_level);
+
+ // TODO(AOleynik): Is neccessary to be able to know that registration process
+ // has been completed and default HMI level is set, otherwise policy will
+ // block all the requests/notifications to mobile
+ // APPLINK-20764 - introduce usage of internal events or re-implement
+ event_engine::Event event(
+ hmi_apis::FunctionID::BasicCommunication_OnAppRegistered);
+
+ smart_objects::SmartObject msg;
+ msg[strings::params][strings::message_type] =
+ hmi_apis::messageType::notification;
+ msg[strings::params][strings::app_id] = app->app_id();
+
+ event.set_smart_object(msg);
+ event.raise(event_dispatcher());
}
bool ApplicationManagerImpl::IsAppTypeExistsInFullOrLimited(
- ApplicationSharedPtr app) const {
+ ApplicationConstSharedPtr app) const {
bool voice_state = app->is_voice_communication_supported();
bool media_state = app->is_media_application();
bool navi_state = app->is_navi();
@@ -357,85 +396,95 @@ bool ApplicationManagerImpl::IsAppTypeExistsInFullOrLimited(
}
ApplicationSharedPtr ApplicationManagerImpl::RegisterApplication(
- const utils::SharedPtr<smart_objects::SmartObject> &
+ const utils::SharedPtr<smart_objects::SmartObject>&
request_for_registration) {
+ LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(logger_, "Restarting application list update timer");
- policy::PolicyHandler::instance()->OnAppsSearchStarted();
- uint32_t timeout =
- profile::Profile::instance()->application_list_update_timeout();
- application_list_update_timer_->start(timeout);
-
- smart_objects::SmartObject &message = *request_for_registration;
+ smart_objects::SmartObject& message = *request_for_registration;
uint32_t connection_key =
message[strings::params][strings::connection_key].asInt();
- if (false == is_all_apps_allowed_) {
- LOG4CXX_INFO(logger_,
- "RegisterApplication: access to app's disabled by user");
- utils::SharedPtr<smart_objects::SmartObject> response(
- MessageHelper::CreateNegativeResponse(
- connection_key, mobile_apis::FunctionID::RegisterAppInterfaceID,
- message[strings::params][strings::correlation_id].asUInt(),
- mobile_apis::Result::DISALLOWED));
- ManageMobileCommand(response);
- return ApplicationSharedPtr();
- }
-
// app_id is SDL "internal" ID
- // original app_id can be gotten via ApplicationImpl::mobile_app_id()
+ // original app_id can be received via ApplicationImpl::mobile_app_id()
uint32_t app_id = 0;
std::list<int32_t> sessions_list;
uint32_t device_id = 0;
- if (connection_handler_) {
- connection_handler::ConnectionHandlerImpl *con_handler_impl =
- static_cast<connection_handler::ConnectionHandlerImpl *>(
- connection_handler_);
-
- if (con_handler_impl->GetDataOnSessionKey(
- connection_key, &app_id, &sessions_list, &device_id) == -1) {
- LOG4CXX_ERROR(logger_,
- "Failed to create application: no connection info.");
- utils::SharedPtr<smart_objects::SmartObject> response(
- MessageHelper::CreateNegativeResponse(
- connection_key, mobile_apis::FunctionID::RegisterAppInterfaceID,
- message[strings::params][strings::correlation_id].asUInt(),
- mobile_apis::Result::GENERIC_ERROR));
- ManageMobileCommand(response);
- return ApplicationSharedPtr();
- }
+ DCHECK_OR_RETURN(connection_handler_, ApplicationSharedPtr());
+ if (connection_handler().GetDataOnSessionKey(
+ connection_key, &app_id, &sessions_list, &device_id) == -1) {
+ LOG4CXX_ERROR(logger_, "Failed to create application: no connection info.");
+ utils::SharedPtr<smart_objects::SmartObject> response(
+ MessageHelper::CreateNegativeResponse(
+ connection_key,
+ mobile_apis::FunctionID::RegisterAppInterfaceID,
+ message[strings::params][strings::correlation_id].asUInt(),
+ mobile_apis::Result::GENERIC_ERROR));
+ ManageMobileCommand(response, commands::Command::ORIGIN_SDL);
+ return ApplicationSharedPtr();
}
- smart_objects::SmartObject &params = message[strings::msg_params];
-
- const std::string &mobile_app_id = params[strings::app_id].asString();
- const std::string &app_name =
- message[strings::msg_params][strings::app_name].asString();
+ LOG4CXX_DEBUG(logger_, "Restarting application list update timer");
+ GetPolicyHandler().OnAppsSearchStarted();
+ uint32_t timeout = get_settings().application_list_update_timeout();
+ application_list_update_timer_.Start(timeout, true);
- LOG4CXX_DEBUG(logger_, "App with connection key: "
- << connection_key
- << " registered from handle: " << device_id);
+ if (!is_all_apps_allowed_) {
+ LOG4CXX_WARN(logger_,
+ "RegisterApplication: access to app's disabled by user");
+ utils::SharedPtr<smart_objects::SmartObject> response(
+ MessageHelper::CreateNegativeResponse(
+ connection_key,
+ mobile_apis::FunctionID::RegisterAppInterfaceID,
+ message[strings::params][strings::correlation_id].asUInt(),
+ mobile_apis::Result::DISALLOWED));
+ ManageMobileCommand(response, commands::Command::ORIGIN_SDL);
+ return ApplicationSharedPtr();
+ }
- ApplicationSharedPtr application(new ApplicationImpl(
- app_id, mobile_app_id, app_name,
- policy::PolicyHandler::instance()->GetStatisticManager()));
+ smart_objects::SmartObject& params = message[strings::msg_params];
+ const std::string& policy_app_id = params[strings::app_id].asString();
+ const custom_str::CustomString& app_name =
+ message[strings::msg_params][strings::app_name].asCustomString();
+ std::string device_mac = "";
+ if (connection_handler().get_session_observer().GetDataOnDeviceID(
+ device_id, NULL, NULL, &device_mac, NULL) == -1) {
+ LOG4CXX_ERROR(logger_, "Failed to extract device mac for id " << device_id);
+ } else {
+ LOG4CXX_DEBUG(logger_,
+ "Device mac for id" << device_id << " is " << device_mac);
+ }
+ ApplicationSharedPtr application(
+ new ApplicationImpl(app_id,
+ policy_app_id,
+ device_mac,
+ app_name,
+ GetPolicyHandler().GetStatisticManager(),
+ *this));
if (!application) {
usage_statistics::AppCounter count_of_rejections_sync_out_of_memory(
- policy::PolicyHandler::instance()->GetStatisticManager(), mobile_app_id,
+ GetPolicyHandler().GetStatisticManager(),
+ policy_app_id,
usage_statistics::REJECTIONS_SYNC_OUT_OF_MEMORY);
++count_of_rejections_sync_out_of_memory;
utils::SharedPtr<smart_objects::SmartObject> response(
MessageHelper::CreateNegativeResponse(
- connection_key, mobile_apis::FunctionID::RegisterAppInterfaceID,
+ connection_key,
+ mobile_apis::FunctionID::RegisterAppInterfaceID,
message[strings::params][strings::correlation_id].asUInt(),
mobile_apis::Result::OUT_OF_MEMORY));
- ManageMobileCommand(response);
+ ManageMobileCommand(response, commands::Command::ORIGIN_SDL);
return ApplicationSharedPtr();
}
+ application->set_folder_name(policy_app_id + "_" +
+ application->mac_address());
+ // To load persistent files, app folder name must be known first, which is now
+ // depends on device_id and mobile_app_id
+ application->LoadPersistentFiles();
application->set_device(device_id);
+
application->set_grammar_id(GenerateGrammarID());
mobile_api::Language::eType launguage_desired =
static_cast<mobile_api::Language::eType>(
@@ -465,15 +514,13 @@ ApplicationSharedPtr ApplicationManagerImpl::RegisterApplication(
message[strings::params][strings::protocol_version].asInt());
application->set_protocol_version(protocol_version);
- if (connection_handler_) {
- if (ProtocolVersion::kUnknownProtocol != protocol_version) {
- connection_handler_->BindProtocolVersionWithSession(
- connection_key, static_cast<uint8_t>(protocol_version));
- }
- if (protocol_version >= ProtocolVersion::kV3 &&
- profile::Profile::instance()->heart_beat_timeout() > 0) {
- connection_handler_->StartSessionHeartBeat(connection_key);
- }
+ if (ProtocolVersion::kUnknownProtocol != protocol_version) {
+ connection_handler().BindProtocolVersionWithSession(
+ connection_key, static_cast<uint8_t>(protocol_version));
+ }
+ if ((protocol_version == ProtocolVersion::kV3) &&
+ (get_settings().heart_beat_timeout() != 0)) {
+ connection_handler().StartSessionHeartBeat(connection_key);
}
// Keep HMI add id in case app is present in "waiting for registration" list
@@ -486,12 +533,17 @@ ApplicationSharedPtr ApplicationManagerImpl::RegisterApplication(
apps_to_register_list_lock_.Release();
if (!application->hmi_app_id()) {
- const bool is_saved = resume_ctrl_.IsApplicationSaved(mobile_app_id);
+ const bool is_saved =
+ resume_ctrl_.IsApplicationSaved(policy_app_id, device_mac);
application->set_hmi_application_id(
- is_saved ? resume_ctrl_.GetHMIApplicationID(mobile_app_id)
+ is_saved ? resume_ctrl_.GetHMIApplicationID(policy_app_id, device_mac)
: GenerateNewHMIAppID());
}
+ // Stops timer of saving data to resumption in order to
+ // doesn't erase data from resumption storage.
+ // Timer will be started after hmi level resumption.
+ resume_ctrl_.OnAppRegistrationStart(policy_app_id, device_mac);
// Add application to registered app list and set appropriate mark.
// Lock has to be released before adding app to policy DB to avoid possible
// deadlock with simultaneous PTU processing
@@ -500,8 +552,7 @@ ApplicationSharedPtr ApplicationManagerImpl::RegisterApplication(
applications_.insert(application);
applications_list_lock_.Release();
- policy::PolicyHandler::instance()->AddApplication(
- application->mobile_app_id());
+ GetPolicyHandler().AddApplication(application->policy_app_id());
return application;
}
@@ -519,17 +570,18 @@ bool ApplicationManagerImpl::ActivateApplication(ApplicationSharedPtr app) {
LOG4CXX_AUTO_TRACE(logger_);
DCHECK_OR_RETURN(app, false);
+ // remove from resumption if app was activated by user
+ resume_controller().OnAppActivated(app);
HMILevel::eType hmi_level = HMILevel::HMI_FULL;
AudioStreamingState::eType audio_state;
app->IsAudioApplication() ? audio_state = AudioStreamingState::AUDIBLE
: audio_state = AudioStreamingState::NOT_AUDIBLE;
-
- state_ctrl_.SetRegularState<false>(app, hmi_level, audio_state);
+ state_ctrl_.SetRegularState(app, hmi_level, audio_state, false);
return true;
}
-mobile_api::HMILevel::eType
-ApplicationManagerImpl::IsHmiLevelFullAllowed(ApplicationSharedPtr app) {
+mobile_api::HMILevel::eType ApplicationManagerImpl::IsHmiLevelFullAllowed(
+ ApplicationSharedPtr app) {
LOG4CXX_AUTO_TRACE(logger_);
if (!app) {
LOG4CXX_ERROR(logger_, "Application pointer invalid");
@@ -549,16 +601,17 @@ ApplicationManagerImpl::IsHmiLevelFullAllowed(ApplicationSharedPtr app) {
} else if (is_active_app_exist && (!is_audio_app)) {
result = GetDefaultHmiLevel(app);
}
- LOG4CXX_ERROR(logger_, "is_audio_app : "
- << is_audio_app
- << "; does_audio_app_with_same_type_exist : "
- << does_audio_app_with_same_type_exist
- << "; is_active_app_exist : "
- << is_active_app_exist << "; result : " << result);
+ LOG4CXX_ERROR(
+ logger_,
+ "is_audio_app : " << is_audio_app
+ << "; does_audio_app_with_same_type_exist : "
+ << does_audio_app_with_same_type_exist
+ << "; is_active_app_exist : " << is_active_app_exist
+ << "; result : " << result);
return result;
}
-void ApplicationManagerImpl::ConnectToDevice(const std::string &device_mac) {
+void ApplicationManagerImpl::ConnectToDevice(const std::string& device_mac) {
// TODO(VS): Call function from ConnectionHandler
if (!connection_handler_) {
LOG4CXX_WARN(logger_, "Connection handler is not set.");
@@ -566,51 +619,54 @@ void ApplicationManagerImpl::ConnectToDevice(const std::string &device_mac) {
}
connection_handler::DeviceHandle handle;
- if (!connection_handler_->GetDeviceID(device_mac, &handle)) {
- LOG4CXX_ERROR(logger_, "Attempt to connect to invalid device with mac:"
- << device_mac);
+ if (!connection_handler().GetDeviceID(device_mac, &handle)) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Attempt to connect to invalid device with mac:" << device_mac);
return;
}
- connection_handler_->ConnectToDevice(handle);
+ connection_handler().ConnectToDevice(handle);
}
void ApplicationManagerImpl::OnHMIStartedCooperation() {
+ LOG4CXX_AUTO_TRACE(logger_);
hmi_cooperating_ = true;
- LOG4CXX_INFO(logger_, "ApplicationManagerImpl::OnHMIStartedCooperation()");
-
- MessageHelper::SendGetSystemInfoRequest();
+ MessageHelper::SendGetSystemInfoRequest(*this);
utils::SharedPtr<smart_objects::SmartObject> is_vr_ready(
- MessageHelper::CreateModuleInfoSO(
- static_cast<uint32_t>(hmi_apis::FunctionID::VR_IsReady)));
+ MessageHelper::CreateModuleInfoSO(hmi_apis::FunctionID::VR_IsReady,
+ *this));
ManageHMICommand(is_vr_ready);
utils::SharedPtr<smart_objects::SmartObject> is_tts_ready(
- MessageHelper::CreateModuleInfoSO(hmi_apis::FunctionID::TTS_IsReady));
+ MessageHelper::CreateModuleInfoSO(hmi_apis::FunctionID::TTS_IsReady,
+ *this));
ManageHMICommand(is_tts_ready);
utils::SharedPtr<smart_objects::SmartObject> is_ui_ready(
- MessageHelper::CreateModuleInfoSO(hmi_apis::FunctionID::UI_IsReady));
+ MessageHelper::CreateModuleInfoSO(hmi_apis::FunctionID::UI_IsReady,
+ *this));
ManageHMICommand(is_ui_ready);
utils::SharedPtr<smart_objects::SmartObject> is_navi_ready(
MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::Navigation_IsReady));
+ hmi_apis::FunctionID::Navigation_IsReady, *this));
ManageHMICommand(is_navi_ready);
utils::SharedPtr<smart_objects::SmartObject> is_ivi_ready(
MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::VehicleInfo_IsReady));
+ hmi_apis::FunctionID::VehicleInfo_IsReady, *this));
ManageHMICommand(is_ivi_ready);
utils::SharedPtr<smart_objects::SmartObject> button_capabilities(
MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::Buttons_GetCapabilities));
+ hmi_apis::FunctionID::Buttons_GetCapabilities, *this));
ManageHMICommand(button_capabilities);
utils::SharedPtr<smart_objects::SmartObject> mixing_audio_supported_request(
MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::BasicCommunication_MixingAudioSupported));
+ hmi_apis::FunctionID::BasicCommunication_MixingAudioSupported,
+ *this));
ManageHMICommand(mixing_audio_supported_request);
resume_controller().ResetLaunchTime();
}
@@ -625,7 +681,7 @@ uint32_t ApplicationManagerImpl::GetNextHMICorrelationID() {
return corelation_id_;
}
-bool ApplicationManagerImpl::begin_audio_pass_thru() {
+bool ApplicationManagerImpl::BeginAudioPassThrough() {
sync_primitives::AutoLock lock(audio_pass_thru_lock_);
if (audio_pass_thru_active_) {
return false;
@@ -635,7 +691,7 @@ bool ApplicationManagerImpl::begin_audio_pass_thru() {
}
}
-bool ApplicationManagerImpl::end_audio_pass_thru() {
+bool ApplicationManagerImpl::EndAudioPassThrough() {
sync_primitives::AutoLock lock(audio_pass_thru_lock_);
if (audio_pass_thru_active_) {
audio_pass_thru_active_ = false;
@@ -645,47 +701,57 @@ bool ApplicationManagerImpl::end_audio_pass_thru() {
}
}
-void ApplicationManagerImpl::set_driver_distraction(bool is_distracting) {
+void ApplicationManagerImpl::set_driver_distraction(const bool is_distracting) {
is_distracting_driver_ = is_distracting;
}
-void ApplicationManagerImpl::set_vr_session_started(const bool &state) {
+void ApplicationManagerImpl::set_vr_session_started(const bool state) {
is_vr_session_strated_ = state;
}
-void ApplicationManagerImpl::set_all_apps_allowed(const bool &allowed) {
+void ApplicationManagerImpl::SetAllAppsAllowed(const bool allowed) {
is_all_apps_allowed_ = allowed;
}
HmiStatePtr ApplicationManagerImpl::CreateRegularState(
- uint32_t app_id, mobile_apis::HMILevel::eType hmi_level,
+ uint32_t app_id,
+ mobile_apis::HMILevel::eType hmi_level,
mobile_apis::AudioStreamingState::eType audio_state,
mobile_apis::SystemContext::eType system_context) const {
- HmiStatePtr state(new HmiState(app_id, state_ctrl_.state_context()));
+ HmiStatePtr state(new HmiState(app_id, *this));
state->set_hmi_level(hmi_level);
state->set_audio_streaming_state(audio_state);
state->set_system_context(system_context);
return state;
}
-void ApplicationManagerImpl::StartAudioPassThruThread(
- int32_t session_key, int32_t correlation_id, int32_t max_duration,
- int32_t sampling_rate, int32_t bits_per_sample, int32_t audio_type) {
+bool ApplicationManagerImpl::IsStateActive(HmiState::StateID state_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_, "Checking for active state id " << state_id);
+ return state_ctrl_.IsStateActive(state_id);
+}
+
+void ApplicationManagerImpl::StartAudioPassThruThread(int32_t session_key,
+ int32_t correlation_id,
+ int32_t max_duration,
+ int32_t sampling_rate,
+ int32_t bits_per_sample,
+ int32_t audio_type) {
+ LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_INFO(logger_, "START MICROPHONE RECORDER");
- if (NULL != media_manager_) {
- media_manager_->StartMicrophoneRecording(
- session_key, profile::Profile::instance()->recording_file_name(),
- max_duration);
- }
+ DCHECK_OR_RETURN_VOID(media_manager_);
+ media_manager_->StartMicrophoneRecording(
+ session_key, get_settings().recording_file_name(), max_duration);
}
void ApplicationManagerImpl::SendAudioPassThroughNotification(
- uint32_t session_key, std::vector<uint8_t> &binary_data) {
+ uint32_t session_key, std::vector<uint8_t>& binary_data) {
LOG4CXX_AUTO_TRACE(logger_);
if (!audio_pass_thru_active_) {
- LOG4CXX_ERROR(logger_, "Trying to send PassThroughNotification"
- " when PassThrough is not active");
+ LOG4CXX_ERROR(logger_,
+ "Trying to send PassThroughNotification"
+ " when PassThrough is not active");
return;
}
@@ -698,23 +764,19 @@ void ApplicationManagerImpl::SendAudioPassThroughNotification(
void ApplicationManagerImpl::StopAudioPassThru(int32_t application_key) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(audio_pass_thru_lock_);
- if (NULL != media_manager_) {
- media_manager_->StopMicrophoneRecording(application_key);
- }
+ DCHECK_OR_RETURN_VOID(media_manager_);
+ media_manager_->StopMicrophoneRecording(application_key);
}
-std::string
-ApplicationManagerImpl::GetDeviceName(connection_handler::DeviceHandle handle) {
- DCHECK(connection_handler_ != 0);
-
+std::string ApplicationManagerImpl::GetDeviceName(
+ connection_handler::DeviceHandle handle) {
+ DCHECK(connection_handler_);
std::string device_name = "";
- connection_handler::ConnectionHandlerImpl *con_handler_impl =
- static_cast<connection_handler::ConnectionHandlerImpl *>(
- connection_handler_);
- if (con_handler_impl->GetDataOnDeviceID(handle, &device_name, NULL) == -1) {
+ if (connection_handler().get_session_observer().GetDataOnDeviceID(
+ handle, &device_name, NULL, NULL, NULL) == -1) {
LOG4CXX_ERROR(logger_, "Failed to extract device name for id " << handle);
} else {
- LOG4CXX_INFO(logger_, "\t\t\t\t\tDevice name is " << device_name);
+ LOG4CXX_DEBUG(logger_, "\t\t\t\t\tDevice name is " << device_name);
}
return device_name;
@@ -722,16 +784,13 @@ ApplicationManagerImpl::GetDeviceName(connection_handler::DeviceHandle handle) {
hmi_apis::Common_TransportType::eType
ApplicationManagerImpl::GetDeviceTransportType(
- const std::string &transport_type) {
+ const std::string& transport_type) {
hmi_apis::Common_TransportType::eType result =
hmi_apis::Common_TransportType::INVALID_ENUM;
- if ("BLUETOOTH" == transport_type) {
- result = hmi_apis::Common_TransportType::BLUETOOTH;
- } else if ("WIFI" == transport_type) {
- result = hmi_apis::Common_TransportType::WIFI;
- } else if ("USB" == transport_type) {
- result = hmi_apis::Common_TransportType::USB;
+ DeviceTypes::const_iterator it = devicesType.find(transport_type);
+ if (it != devicesType.end()) {
+ return devicesType[transport_type];
} else {
LOG4CXX_ERROR(logger_, "Unknown transport type " << transport_type);
}
@@ -752,6 +811,7 @@ void ApplicationManagerImpl::OnMessageReceived(
utils::SharedPtr<Message> outgoing_message = ConvertRawMsgToMessage(message);
if (outgoing_message) {
+ LOG4CXX_DEBUG(logger_, "Posting new Message");
messages_from_mobile_.PostMessage(
impl::MessageFromMobile(outgoing_message));
}
@@ -775,26 +835,25 @@ void ApplicationManagerImpl::OnMessageReceived(
messages_from_hmi_.PostMessage(impl::MessageFromHmi(message));
}
-ApplicationConstSharedPtr
-ApplicationManagerImpl::waiting_app(const uint32_t hmi_id) const {
- AppsWaitRegistrationSet app_list = apps_waiting_for_registration().GetData();
+ApplicationConstSharedPtr ApplicationManagerImpl::WaitingApplicationByID(
+ const uint32_t hmi_id) const {
+ AppsWaitRegistrationSet app_list = AppsWaitingForRegistration().GetData();
AppsWaitRegistrationSet::const_iterator it_end = app_list.end();
HmiAppIdPredicate finder(hmi_id);
ApplicationSharedPtr result;
- ApplictionSetConstIt it_app = std::find_if(app_list.begin(), it_end, finder);
+ ApplicationSetConstIt it_app = std::find_if(app_list.begin(), it_end, finder);
if (it_app != it_end) {
result = *it_app;
}
return result;
}
-DataAccessor<ApplicationManagerImpl::AppsWaitRegistrationSet>
-ApplicationManagerImpl::apps_waiting_for_registration() const {
- return DataAccessor<AppsWaitRegistrationSet>(
- ApplicationManagerImpl::instance()->apps_to_register_,
- ApplicationManagerImpl::instance()->apps_to_register_list_lock_);
+DataAccessor<AppsWaitRegistrationSet>
+ApplicationManagerImpl::AppsWaitingForRegistration() const {
+ return DataAccessor<AppsWaitRegistrationSet>(apps_to_register_,
+ apps_to_register_list_lock_);
}
bool ApplicationManagerImpl::IsAppsQueriedFrom(
@@ -810,6 +869,14 @@ bool ApplicationManagerImpl::IsAppsQueriedFrom(
return false;
}
+StateController& ApplicationManagerImpl::state_controller() {
+ return state_ctrl_;
+}
+
+const ApplicationManagerSettings& ApplicationManagerImpl::get_settings() const {
+ return settings_;
+}
+
void application_manager::ApplicationManagerImpl::MarkAppsGreyOut(
const connection_handler::DeviceHandle handle, bool is_greyed_out) {
sync_primitives::AutoLock lock(apps_to_register_list_lock_);
@@ -821,24 +888,42 @@ void application_manager::ApplicationManagerImpl::MarkAppsGreyOut(
}
}
}
-
void ApplicationManagerImpl::OnErrorSending(
hmi_message_handler::MessageSharedPointer message) {
return;
}
void ApplicationManagerImpl::OnDeviceListUpdated(
- const connection_handler::DeviceMap &device_list) {
+ const connection_handler::DeviceMap& device_list) {
LOG4CXX_AUTO_TRACE(logger_);
+
+ // add device to policy DB
+ connection_handler::DeviceMap::const_iterator it = device_list.begin();
+ for (; device_list.end() != it; ++it) {
+ policy::DeviceParams dev_params;
+ connection_handler().get_session_observer().GetDataOnDeviceID(
+ it->second.device_handle(),
+ &dev_params.device_name,
+ NULL,
+ &dev_params.device_mac_address,
+ &dev_params.device_connection_type);
+
+ policy::DeviceInfo device_info;
+ device_info.AdoptDeviceType(dev_params.device_connection_type);
+
+ GetPolicyHandler().AddDevice(dev_params.device_mac_address,
+ device_info.connection_type);
+ }
+
smart_objects::SmartObjectSPtr msg_params =
- MessageHelper::CreateDeviceListSO(device_list);
+ MessageHelper::CreateDeviceListSO(device_list, GetPolicyHandler(), *this);
if (!msg_params) {
LOG4CXX_WARN(logger_, "Failed to create sub-smart object.");
return;
}
smart_objects::SmartObjectSPtr update_list = new smart_objects::SmartObject;
- smart_objects::SmartObject &so_to_send = *update_list;
+ smart_objects::SmartObject& so_to_send = *update_list;
so_to_send[jhs::S_PARAMS][jhs::S_FUNCTION_ID] =
hmi_apis::FunctionID::BasicCommunication_UpdateDeviceList;
so_to_send[jhs::S_PARAMS][jhs::S_MESSAGE_TYPE] =
@@ -851,12 +936,11 @@ void ApplicationManagerImpl::OnDeviceListUpdated(
}
void ApplicationManagerImpl::OnFindNewApplicationsRequest() {
- connection_handler_->ConnectToAllDevices();
+ connection_handler().ConnectToAllDevices();
LOG4CXX_DEBUG(logger_, "Starting application list update timer");
- uint32_t timeout =
- profile::Profile::instance()->application_list_update_timeout();
- application_list_update_timer_->start(timeout);
- policy::PolicyHandler::instance()->OnAppsSearchStarted();
+ uint32_t timeout = get_settings().application_list_update_timeout();
+ application_list_update_timer_.Start(timeout, true);
+ GetPolicyHandler().OnAppsSearchStarted();
}
void ApplicationManagerImpl::SendUpdateAppList() {
@@ -866,36 +950,35 @@ void ApplicationManagerImpl::SendUpdateAppList() {
using namespace hmi_apis;
SmartObjectSPtr request = MessageHelper::CreateModuleInfoSO(
- FunctionID::BasicCommunication_UpdateAppList);
+ FunctionID::BasicCommunication_UpdateAppList, *this);
(*request)[strings::msg_params][strings::applications] =
SmartObject(SmartType_Array);
- SmartObject &applications =
+ SmartObject& applications =
(*request)[strings::msg_params][strings::applications];
- PrepareApplicationListSO(applications_, applications);
- PrepareApplicationListSO(apps_to_register_, applications);
+ PrepareApplicationListSO(applications_, applications, *this);
+ PrepareApplicationListSO(apps_to_register_, applications, *this);
ManageHMICommand(request);
}
void ApplicationManagerImpl::RemoveDevice(
- const connection_handler::DeviceHandle &device_handle) {
- LOG4CXX_INFO(logger_, "device_handle " << device_handle);
+ const connection_handler::DeviceHandle& device_handle) {
+ LOG4CXX_DEBUG(logger_, "device_handle " << device_handle);
}
mobile_apis::HMILevel::eType ApplicationManagerImpl::GetDefaultHmiLevel(
- ApplicationSharedPtr application) const {
+ ApplicationConstSharedPtr application) const {
using namespace mobile_apis;
LOG4CXX_AUTO_TRACE(logger_);
HMILevel::eType default_hmi = HMILevel::HMI_NONE;
- if (policy::PolicyHandler::instance()->PolicyEnabled()) {
- const std::string policy_app_id = application->mobile_app_id();
+ if (policy_handler_.PolicyEnabled()) {
+ const std::string policy_app_id = application->policy_app_id();
std::string default_hmi_string = "";
- if (policy::PolicyHandler::instance()->GetDefaultHmi(policy_app_id,
- &default_hmi_string)) {
+ if (policy_handler_.GetDefaultHmi(policy_app_id, &default_hmi_string)) {
if ("BACKGROUND" == default_hmi_string) {
default_hmi = HMILevel::HMI_BACKGROUND;
} else if ("FULL" == default_hmi_string) {
@@ -905,21 +988,24 @@ mobile_apis::HMILevel::eType ApplicationManagerImpl::GetDefaultHmiLevel(
} else if ("NONE" == default_hmi_string) {
default_hmi = HMILevel::HMI_NONE;
} else {
- LOG4CXX_ERROR(logger_, "Unable to convert " + default_hmi_string +
- " to HMILevel");
+ LOG4CXX_ERROR(
+ logger_,
+ "Unable to convert " + default_hmi_string + " to HMILevel");
}
} else {
- LOG4CXX_ERROR(logger_, "Unable to get default hmi_level for "
- << policy_app_id);
+ LOG4CXX_ERROR(logger_,
+ "Unable to get default hmi_level for " << policy_app_id);
}
}
return default_hmi;
}
-uint32_t ApplicationManagerImpl::GenerateGrammarID() { return rand(); }
+uint32_t ApplicationManagerImpl::GenerateGrammarID() {
+ return rand();
+}
uint32_t ApplicationManagerImpl::GenerateNewHMIAppID() {
- LOG4CXX_TRACE(logger_, "ENTER");
+ LOG4CXX_AUTO_TRACE(logger_);
uint32_t hmi_app_id = get_rand_from_range(1);
LOG4CXX_DEBUG(logger_, "GenerateNewHMIAppID value is: " << hmi_app_id);
@@ -929,79 +1015,78 @@ uint32_t ApplicationManagerImpl::GenerateNewHMIAppID() {
LOG4CXX_DEBUG(logger_, "Trying new value: " << hmi_app_id);
}
- LOG4CXX_TRACE(logger_, "EXIT");
return hmi_app_id;
}
void ApplicationManagerImpl::ReplaceMobileByHMIAppId(
- smart_objects::SmartObject &message) {
+ smart_objects::SmartObject& message) {
MessageHelper::PrintSmartObject(message);
if (message.keyExists(strings::app_id)) {
- ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(
- message[strings::app_id].asUInt());
- if (application.valid()) {
- LOG4CXX_INFO(logger_, "ReplaceMobileByHMIAppId from "
- << message[strings::app_id].asInt() << " to "
- << application->hmi_app_id());
- message[strings::app_id] = application->hmi_app_id();
+ ApplicationSharedPtr application_ptr =
+ application(message[strings::app_id].asUInt());
+ if (application_ptr.valid()) {
+ LOG4CXX_DEBUG(logger_,
+ "ReplaceMobileByHMIAppId from "
+ << message[strings::app_id].asInt() << " to "
+ << application_ptr->hmi_app_id());
+ message[strings::app_id] = application_ptr->hmi_app_id();
}
} else {
switch (message.getType()) {
- case smart_objects::SmartType::SmartType_Array: {
- smart_objects::SmartArray *message_array = message.asArray();
- smart_objects::SmartArray::iterator it = message_array->begin();
- for (; it != message_array->end(); ++it) {
- ReplaceMobileByHMIAppId(*it);
+ case smart_objects::SmartType::SmartType_Array: {
+ smart_objects::SmartArray* message_array = message.asArray();
+ smart_objects::SmartArray::iterator it = message_array->begin();
+ for (; it != message_array->end(); ++it) {
+ ReplaceMobileByHMIAppId(*it);
+ }
+ break;
}
- break;
- }
- case smart_objects::SmartType::SmartType_Map: {
- std::set<std::string> keys = message.enumerate();
- std::set<std::string>::const_iterator key = keys.begin();
- for (; key != keys.end(); ++key) {
- std::string k = *key;
- ReplaceMobileByHMIAppId(message[*key]);
+ case smart_objects::SmartType::SmartType_Map: {
+ std::set<std::string> keys = message.enumerate();
+ std::set<std::string>::const_iterator key = keys.begin();
+ for (; key != keys.end(); ++key) {
+ std::string k = *key;
+ ReplaceMobileByHMIAppId(message[*key]);
+ }
+ break;
}
- break;
- }
- default: { break; }
+ default: { break; }
}
}
}
void ApplicationManagerImpl::ReplaceHMIByMobileAppId(
- smart_objects::SmartObject &message) {
+ smart_objects::SmartObject& message) {
if (message.keyExists(strings::app_id)) {
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application_by_hmi_app(
- message[strings::app_id].asUInt());
+ application_by_hmi_app(message[strings::app_id].asUInt());
if (application.valid()) {
- LOG4CXX_INFO(logger_, "ReplaceHMIByMobileAppId from "
- << message[strings::app_id].asInt() << " to "
- << application->app_id());
+ LOG4CXX_DEBUG(logger_,
+ "ReplaceHMIByMobileAppId from "
+ << message[strings::app_id].asInt() << " to "
+ << application->app_id());
message[strings::app_id] = application->app_id();
}
} else {
switch (message.getType()) {
- case smart_objects::SmartType::SmartType_Array: {
- smart_objects::SmartArray *message_array = message.asArray();
- smart_objects::SmartArray::iterator it = message_array->begin();
- for (; it != message_array->end(); ++it) {
- ReplaceHMIByMobileAppId(*it);
+ case smart_objects::SmartType::SmartType_Array: {
+ smart_objects::SmartArray* message_array = message.asArray();
+ smart_objects::SmartArray::iterator it = message_array->begin();
+ for (; it != message_array->end(); ++it) {
+ ReplaceHMIByMobileAppId(*it);
+ }
+ break;
}
- break;
- }
- case smart_objects::SmartType::SmartType_Map: {
- std::set<std::string> keys = message.enumerate();
- std::set<std::string>::const_iterator key = keys.begin();
- for (; key != keys.end(); ++key) {
- ReplaceHMIByMobileAppId(message[*key]);
+ case smart_objects::SmartType::SmartType_Map: {
+ std::set<std::string> keys = message.enumerate();
+ std::set<std::string>::const_iterator key = keys.begin();
+ for (; key != keys.end(); ++key) {
+ ReplaceHMIByMobileAppId(message[*key]);
+ }
+ break;
}
- break;
- }
- default: { break; }
+ default: { break; }
}
}
}
@@ -1016,9 +1101,10 @@ bool ApplicationManagerImpl::StartNaviService(
if (navi_service_status_.end() == it) {
std::pair<NaviServiceStatusMap::iterator, bool> res =
navi_service_status_.insert(
- std::pair<uint32_t, std::pair<bool, bool>>(
+ std::pair<uint32_t, std::pair<bool, bool> >(
app_id, std::make_pair(false, false)));
if (!res.second) {
+ LOG4CXX_WARN(logger_, "Navi service refused");
return false;
}
it = res.first;
@@ -1031,6 +1117,8 @@ bool ApplicationManagerImpl::StartNaviService(
application(app_id)->StartStreaming(service_type);
return true;
+ } else {
+ LOG4CXX_WARN(logger_, "Refused navi service by HMI level");
}
return false;
}
@@ -1056,50 +1144,59 @@ void ApplicationManagerImpl::StopNaviService(
LOG4CXX_WARN(logger_, "An application is not registered.");
return;
}
+
app->StopStreaming(service_type);
}
bool ApplicationManagerImpl::OnServiceStartedCallback(
- const connection_handler::DeviceHandle &device_handle,
- const int32_t &session_key, const protocol_handler::ServiceType &type) {
+ const connection_handler::DeviceHandle& device_handle,
+ const int32_t& session_key,
+ const protocol_handler::ServiceType& type) {
using namespace helpers;
using namespace protocol_handler;
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_,
+ "ServiceType = " << type << ". Session = " << std::hex
+ << session_key);
- LOG4CXX_DEBUG(logger_, "OnServiceStartedCallback " << type << " in session 0x"
- << std::hex
- << session_key);
if (type == kRpc) {
- LOG4CXX_INFO(logger_, "RPC service is about to be started.");
+ LOG4CXX_DEBUG(logger_, "RPC service is about to be started.");
return true;
}
ApplicationSharedPtr app = application(session_key);
if (!app) {
- LOG4CXX_DEBUG(logger_, "The application with id:" << session_key
- << " doesn't exists.");
+ LOG4CXX_WARN(logger_,
+ "The application with id:" << session_key
+ << " doesn't exists.");
return false;
}
- if (Compare<ServiceType, EQ, ONE>(type, ServiceType::kMobileNav,
- ServiceType::kAudio)) {
+ if (Compare<ServiceType, EQ, ONE>(
+ type, ServiceType::kMobileNav, ServiceType::kAudio)) {
if (app->is_navi()) {
return StartNaviService(session_key, type);
+ } else {
+ LOG4CXX_WARN(logger_, "Refuse not navi application");
}
+ } else {
+ LOG4CXX_WARN(logger_, "Refuse unknown service");
}
return false;
}
void ApplicationManagerImpl::OnServiceEndedCallback(
- const int32_t &session_key, const protocol_handler::ServiceType &type,
- const connection_handler::CloseSessionReason &close_reason) {
+ const int32_t& session_key,
+ const protocol_handler::ServiceType& type,
+ const connection_handler::CloseSessionReason& close_reason) {
using namespace helpers;
using namespace protocol_handler;
- using namespace mobile_apis;
using namespace connection_handler;
using namespace mobile_apis;
- LOG4CXX_DEBUG(logger_, "OnServiceEndedCallback for service "
- << type << " with reason " << close_reason
- << " in session 0x" << std::hex << session_key);
+ LOG4CXX_DEBUG(logger_,
+ "OnServiceEndedCallback for service "
+ << type << " with reason " << close_reason
+ << " in session 0x" << std::hex << session_key);
if (type == kRpc) {
LOG4CXX_INFO(logger_, "Remove application.");
@@ -1114,68 +1211,115 @@ void ApplicationManagerImpl::OnServiceEndedCallback(
bool is_resuming;
bool is_unexpected_disconnect;
switch (close_reason) {
- case CloseSessionReason::kFlood: {
- reason = Result::TOO_MANY_PENDING_REQUESTS;
- is_resuming = true;
- is_unexpected_disconnect = false;
-
- MessageHelper::SendOnAppInterfaceUnregisteredNotificationToMobile(
- session_key, AppInterfaceUnregisteredReason::TOO_MANY_REQUESTS);
- break;
- }
- case CloseSessionReason::kMalformed: {
- reason = Result::INVALID_ENUM;
- is_resuming = true;
- is_unexpected_disconnect = false;
- break;
- }
- case CloseSessionReason::kUnauthorizedApp: {
- reason = Result::INVALID_ENUM;
- is_resuming = true;
- is_unexpected_disconnect = false;
- break;
- }
- default: {
- reason = Result::INVALID_ENUM;
- is_resuming = true;
- is_unexpected_disconnect = true;
- break;
- }
+ case CloseSessionReason::kFlood: {
+ reason = Result::TOO_MANY_PENDING_REQUESTS;
+ is_resuming = true;
+ is_unexpected_disconnect = false;
+
+ ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ session_key, AppInterfaceUnregisteredReason::TOO_MANY_REQUESTS),
+ commands::Command::ORIGIN_SDL);
+ break;
+ }
+ case CloseSessionReason::kMalformed: {
+ reason = Result::INVALID_ENUM;
+ is_resuming = false;
+ is_unexpected_disconnect = false;
+ break;
+ }
+ case CloseSessionReason::kUnauthorizedApp: {
+ reason = Result::INVALID_ENUM;
+ is_resuming = true;
+ is_unexpected_disconnect = false;
+ break;
+ }
+ default: {
+ reason = Result::INVALID_ENUM;
+ is_resuming = true;
+ is_unexpected_disconnect = true;
+ break;
+ }
}
- UnregisterApplication(session_key, reason, is_resuming,
- is_unexpected_disconnect);
+ UnregisterApplication(
+ session_key, reason, is_resuming, is_unexpected_disconnect);
return;
}
- if (Compare<ServiceType, EQ, ONE>(type, ServiceType::kMobileNav,
- ServiceType::kAudio)) {
+ if (Compare<ServiceType, EQ, ONE>(
+ type, ServiceType::kMobileNav, ServiceType::kAudio)) {
StopNaviService(session_key, type);
}
}
+#ifdef ENABLE_SECURITY
+bool ApplicationManagerImpl::OnHandshakeDone(
+ uint32_t connection_key,
+ security_manager::SSLContext::HandshakeResult result) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ using security_manager::SSLContext;
+ using namespace helpers;
+
+ ApplicationSharedPtr app = application(connection_key);
+ DCHECK_OR_RETURN(app, false);
+ if (Compare<SSLContext::HandshakeResult, EQ, ONE>(
+ result,
+ SSLContext::Handshake_Result_CertExpired,
+ SSLContext::Handshake_Result_CertNotSigned,
+ SSLContext::Handshake_Result_AppIDMismatch,
+ SSLContext::Handshake_Result_AppNameMismatch,
+ SSLContext::Handshake_Result_NotYetValid)) {
+ app->usage_report().RecordTLSError();
+ }
+ return false;
+}
+
+void ApplicationManagerImpl::OnCertificateUpdateRequired() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ GetPolicyHandler().OnPTExchangeNeeded();
+}
+
+security_manager::SSLContext::HandshakeContext
+ApplicationManagerImpl::GetHandshakeContext(uint32_t key) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using security_manager::SSLContext;
+ ApplicationConstSharedPtr app = application(key);
+ if (app) {
+ return SSLContext::HandshakeContext(
+ custom_str::CustomString(app->policy_app_id()), app->name());
+ }
+ return SSLContext::HandshakeContext();
+}
+#endif // ENABLE_SECURITY
+
void ApplicationManagerImpl::set_hmi_message_handler(
- hmi_message_handler::HMIMessageHandler *handler) {
+ hmi_message_handler::HMIMessageHandler* handler) {
hmi_handler_ = handler;
}
void ApplicationManagerImpl::set_connection_handler(
- connection_handler::ConnectionHandler *handler) {
+ connection_handler::ConnectionHandler* handler) {
connection_handler_ = handler;
}
-connection_handler::ConnectionHandler *
-ApplicationManagerImpl::connection_handler() {
- return connection_handler_;
+connection_handler::ConnectionHandler&
+ApplicationManagerImpl::connection_handler() const {
+ return *connection_handler_;
+}
+
+protocol_handler::ProtocolHandler& ApplicationManagerImpl::protocol_handler()
+ const {
+ return *protocol_handler_;
}
void ApplicationManagerImpl::set_protocol_handler(
- protocol_handler::ProtocolHandler *handler) {
+ protocol_handler::ProtocolHandler* handler) {
protocol_handler_ = handler;
}
void ApplicationManagerImpl::StartDevicesDiscovery() {
- connection_handler::ConnectionHandlerImpl::instance()
- ->StartDevicesDiscovery();
+ connection_handler().get_device_discovery_starter().StartDevicesDiscovery();
}
void ApplicationManagerImpl::SendMessageToMobile(
@@ -1197,7 +1341,7 @@ void ApplicationManagerImpl::SendMessageToMobile(
(*message)[strings::params][strings::connection_key].asUInt());
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "No application associated with connection key");
+ LOG4CXX_ERROR(logger_, "No application associated with connection key");
if ((*message)[strings::msg_params].keyExists(strings::result_code) &&
((*message)[strings::msg_params][strings::result_code] ==
NsSmartDeviceLinkRPC::V1::Result::UNSUPPORTED_VERSION)) {
@@ -1213,8 +1357,9 @@ void ApplicationManagerImpl::SendMessageToMobile(
}
mobile_so_factory().attachSchema(*message, false);
- LOG4CXX_INFO(logger_, "Attached schema to message, result if valid: "
- << message->isValid());
+ LOG4CXX_DEBUG(
+ logger_,
+ "Attached schema to message, result if valid: " << message->isValid());
// Messages to mobile are not yet prioritized so use default priority value
utils::SharedPtr<Message> message_to_send(
@@ -1224,7 +1369,7 @@ void ApplicationManagerImpl::SendMessageToMobile(
return;
}
- smart_objects::SmartObject &msg_to_mobile = *message;
+ smart_objects::SmartObject& msg_to_mobile = *message;
// If correlation_id is not present, it is from-HMI message which should be
// checked against policy permissions
if (msg_to_mobile[strings::params].keyExists(strings::correlation_id)) {
@@ -1237,7 +1382,7 @@ void ApplicationManagerImpl::SendMessageToMobile(
(*message)[strings::params][strings::function_id].asUInt());
RPCParams params;
- const smart_objects::SmartObject &s_map = (*message)[strings::msg_params];
+ const smart_objects::SmartObject& s_map = (*message)[strings::msg_params];
if (smart_objects::SmartType_Map == s_map.getType()) {
smart_objects::SmartMap::iterator iter = s_map.map_begin();
smart_objects::SmartMap::iterator iter_end = s_map.map_end();
@@ -1250,13 +1395,13 @@ void ApplicationManagerImpl::SendMessageToMobile(
}
}
const mobile_apis::Result::eType check_result = CheckPolicyPermissions(
- app->mobile_app_id(), app->hmi_level(), function_id, params);
+ app->policy_app_id(), app->hmi_level(), function_id, params);
if (mobile_apis::Result::SUCCESS != check_result) {
const std::string string_functionID =
MessageHelper::StringifiedFunctionID(function_id);
- LOG4CXX_WARN(logger_, "Function \"" << string_functionID << "\" (#"
- << function_id
- << ") not allowed by policy");
+ LOG4CXX_WARN(logger_,
+ "Function \"" << string_functionID << "\" (#" << function_id
+ << ") not allowed by policy");
return;
}
@@ -1266,14 +1411,15 @@ void ApplicationManagerImpl::SendMessageToMobile(
(*message)[strings::msg_params][strings::request_type].asUInt());
if (mobile_apis::RequestType::PROPRIETARY == request_type ||
mobile_apis::RequestType::HTTP == request_type) {
- policy::PolicyHandler::instance()->OnUpdateRequestSentToMobile();
+ GetPolicyHandler().OnUpdateRequestSentToMobile();
}
}
}
if (message_to_send->binary_data()) {
- LOG4CXX_DEBUG(logger_, "Binary data size: "
- << message_to_send->binary_data()->size());
+ LOG4CXX_DEBUG(
+ logger_,
+ "Binary data size: " << message_to_send->binary_data()->size());
}
messages_to_mobile_.PostMessage(
impl::MessageToMobile(message_to_send, final_message));
@@ -1290,7 +1436,7 @@ bool ApplicationManagerImpl::ManageMobileCommand(
LOG4CXX_AUTO_TRACE(logger_);
if (!message) {
- LOG4CXX_WARN(logger_, "RET Null-pointer message received.");
+ LOG4CXX_WARN(logger_, "Null-pointer message received.");
return false;
}
@@ -1302,9 +1448,9 @@ bool ApplicationManagerImpl::ManageMobileCommand(
MessageHelper::PrintSmartObject(*message);
#endif
- LOG4CXX_INFO(logger_, "Trying to create message in mobile factory.");
+ LOG4CXX_DEBUG(logger_, "Trying to create message in mobile factory.");
utils::SharedPtr<commands::Command> command(
- MobileCommandFactory::CreateCommand(message, origin));
+ MobileCommandFactory::CreateCommand(message, origin, *this));
if (!command) {
LOG4CXX_WARN(logger_,
@@ -1335,12 +1481,14 @@ bool ApplicationManagerImpl::ManageMobileCommand(
if (((mobile_apis::FunctionID::RegisterAppInterfaceID != function_id) &&
(protocol_type == commands::CommandImpl::mobile_protocol_type_)) &&
(mobile_apis::FunctionID::UnregisterAppInterfaceID != function_id)) {
- app = ApplicationManagerImpl::instance()->application(connection_key);
+ app = application(connection_key);
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "RET APPLICATION_NOT_REGISTERED");
+ LOG4CXX_ERROR(logger_, "RET APPLICATION_NOT_REGISTERED");
smart_objects::SmartObjectSPtr response =
MessageHelper::CreateNegativeResponse(
- connection_key, static_cast<int32_t>(function_id), correlation_id,
+ connection_key,
+ static_cast<int32_t>(function_id),
+ correlation_id,
static_cast<int32_t>(
mobile_apis::Result::APPLICATION_NOT_REGISTERED));
@@ -1372,7 +1520,6 @@ bool ApplicationManagerImpl::ManageMobileCommand(
}
if (message_type == mobile_apis::messageType::request) {
-
// commands will be launched from requesr_ctrl
mobile_apis::HMILevel::eType app_hmi_level =
mobile_apis::HMILevel::INVALID_ENUM;
@@ -1386,52 +1533,69 @@ bool ApplicationManagerImpl::ManageMobileCommand(
request_ctrl_.addMobileRequest(command, app_hmi_level);
if (result == request_controller::RequestController::SUCCESS) {
- LOG4CXX_INFO(logger_, "Perform request");
+ LOG4CXX_DEBUG(logger_, "Perform request");
} else if (result == request_controller::RequestController::
TOO_MANY_PENDING_REQUESTS) {
- LOG4CXX_ERROR_EXT(logger_, "RET Unable top perform request: "
- << "TOO_MANY_PENDING_REQUESTS");
+ LOG4CXX_ERROR(logger_,
+ "RET Unable top perform request: "
+ << "TOO_MANY_PENDING_REQUESTS");
smart_objects::SmartObjectSPtr response =
MessageHelper::CreateNegativeResponse(
- connection_key, static_cast<int32_t>(function_id), correlation_id,
+ connection_key,
+ static_cast<int32_t>(function_id),
+ correlation_id,
static_cast<int32_t>(
mobile_apis::Result::TOO_MANY_PENDING_REQUESTS));
+ ApplicationSharedPtr app_ptr = application(connection_key);
+ if (app_ptr) {
+ app_ptr->usage_report().RecordRemovalsForBadBehavior();
+ }
SendMessageToMobile(response);
return false;
} else if (result ==
request_controller::RequestController::TOO_MANY_REQUESTS) {
- LOG4CXX_ERROR_EXT(logger_, "RET Unable to perform request: "
- << "TOO_MANY_REQUESTS");
+ LOG4CXX_ERROR(logger_,
+ "RET Unable to perform request: "
+ << "TOO_MANY_REQUESTS");
- MessageHelper::SendOnAppInterfaceUnregisteredNotificationToMobile(
- connection_key,
- mobile_api::AppInterfaceUnregisteredReason::TOO_MANY_REQUESTS);
+ ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ connection_key,
+ mobile_api::AppInterfaceUnregisteredReason::TOO_MANY_REQUESTS),
+ commands::Command::ORIGIN_SDL);
UnregisterApplication(connection_key,
mobile_apis::Result::TOO_MANY_PENDING_REQUESTS,
false);
+ ApplicationSharedPtr app_ptr = application(connection_key);
+ if (app_ptr) {
+ app_ptr->usage_report().RecordRemovalsForBadBehavior();
+ }
return false;
} else if (result == request_controller::RequestController::
NONE_HMI_LEVEL_MANY_REQUESTS) {
- LOG4CXX_ERROR_EXT(logger_, "RET Unable to perform request: "
- << "REQUEST_WHILE_IN_NONE_HMI_LEVEL");
+ LOG4CXX_ERROR(logger_,
+ "RET Unable to perform request: "
+ << "REQUEST_WHILE_IN_NONE_HMI_LEVEL");
- MessageHelper::SendOnAppInterfaceUnregisteredNotificationToMobile(
- connection_key, mobile_api::AppInterfaceUnregisteredReason::
- REQUEST_WHILE_IN_NONE_HMI_LEVEL);
+ ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ connection_key,
+ mobile_api::AppInterfaceUnregisteredReason::
+ REQUEST_WHILE_IN_NONE_HMI_LEVEL),
+ commands::Command::ORIGIN_SDL);
ApplicationSharedPtr app_ptr = application(connection_key);
if (app_ptr) {
app_ptr->usage_report().RecordRemovalsForBadBehavior();
}
- UnregisterApplication(connection_key, mobile_apis::Result::INVALID_ENUM,
- false);
+ UnregisterApplication(
+ connection_key, mobile_apis::Result::INVALID_ENUM, false);
return false;
} else {
- LOG4CXX_ERROR_EXT(logger_,
- "RET Unable to perform request: Unknown case");
+ LOG4CXX_ERROR(logger_, "RET Unable to perform request: Unknown case");
return false;
}
return true;
@@ -1465,8 +1629,9 @@ void ApplicationManagerImpl::SendMessageToHMI(
}
hmi_so_factory().attachSchema(*message, false);
- LOG4CXX_INFO(logger_, "Attached schema to message, result if valid: "
- << message->isValid());
+ LOG4CXX_INFO(
+ logger_,
+ "Attached schema to message, result if valid: " << message->isValid());
#ifdef HMI_DBUS_API
message_to_send->set_smart_object(*message);
@@ -1476,7 +1641,7 @@ void ApplicationManagerImpl::SendMessageToHMI(
"Cannot send message to HMI: failed to create string");
return;
}
-#endif // HMI_DBUS_API
+#endif // HMI_DBUS_API
messages_to_hmi_.PostMessage(impl::MessageToHmi(message_to_send));
}
@@ -1497,7 +1662,7 @@ bool ApplicationManagerImpl::ManageHMICommand(
MessageHelper::PrintSmartObject(*message);
- CommandSharedPtr command = HMICommandFactory::CreateCommand(message);
+ CommandSharedPtr command = HMICommandFactory::CreateCommand(message, *this);
if (!command) {
LOG4CXX_WARN(logger_, "Failed to create command from smart object");
return false;
@@ -1506,15 +1671,15 @@ bool ApplicationManagerImpl::ManageHMICommand(
int32_t message_type =
(*(message.get()))[strings::params][strings::message_type].asInt();
- // Init before adding to request controller to be able to set request timeout
+ if (kRequest == message_type) {
+ LOG4CXX_DEBUG(logger_, "ManageHMICommand");
+ request_ctrl_.addHMIRequest(command);
+ }
+
if (command->Init()) {
- if (kRequest == message_type) {
- LOG4CXX_DEBUG(logger_, "ManageHMICommand");
- request_ctrl_.addHMIRequest(command);
- }
command->Run();
if (kResponse == message_type) {
- int32_t correlation_id =
+ const uint32_t correlation_id =
(*(message.get()))[strings::params][strings::correlation_id].asInt();
request_ctrl_.OnHMIResponse(correlation_id);
}
@@ -1523,39 +1688,47 @@ bool ApplicationManagerImpl::ManageHMICommand(
return false;
}
-bool ApplicationManagerImpl::Init() {
+bool ApplicationManagerImpl::Init(resumption::LastState& last_state,
+ media_manager::MediaManager* media_manager) {
LOG4CXX_TRACE(logger_, "Init application manager");
- const std::string app_storage_folder =
- profile::Profile::instance()->app_storage_folder();
+ const std::string app_storage_folder = get_settings().app_storage_folder();
if (!InitDirectory(app_storage_folder, TYPE_STORAGE) ||
!IsReadWriteAllowed(app_storage_folder, TYPE_STORAGE)) {
return false;
}
+ if (!resume_ctrl_.Init(last_state)) {
+ LOG4CXX_ERROR(logger_, "Problem with initialization of resume controller");
+ return false;
+ }
+ hmi_capabilities_.Init(&last_state);
- const std::string system_files_path =
- profile::Profile::instance()->system_files_path();
+ if (!(file_system::IsWritingAllowed(app_storage_folder) &&
+ file_system::IsReadingAllowed(app_storage_folder))) {
+ LOG4CXX_ERROR(logger_,
+ "Storage directory doesn't have read/write permissions");
+ return false;
+ }
+
+ const std::string system_files_path = get_settings().system_files_path();
if (!InitDirectory(system_files_path, TYPE_SYSTEM) ||
!IsReadWriteAllowed(system_files_path, TYPE_SYSTEM)) {
return false;
}
-
- const std::string app_icons_folder =
- profile::Profile::instance()->app_icons_folder();
+ const std::string app_icons_folder = get_settings().app_icons_folder();
if (!InitDirectory(app_icons_folder, TYPE_ICONS)) {
return false;
}
// In case there is no R/W permissions for this location, SDL just has to
// log this and proceed
IsReadWriteAllowed(app_icons_folder, TYPE_ICONS);
-
- if (policy::PolicyHandler::instance()->PolicyEnabled()) {
- if (!policy::PolicyHandler::instance()->LoadPolicyLibrary()) {
+ if (GetPolicyHandler().PolicyEnabled()) {
+ if (!GetPolicyHandler().LoadPolicyLibrary()) {
LOG4CXX_ERROR(logger_,
"Policy library is not loaded. Check LD_LIBRARY_PATH");
return false;
}
LOG4CXX_INFO(logger_, "Policy library is loaded, now initing PT");
- if (!policy::PolicyHandler::instance()->InitPolicyTable()) {
+ if (!GetPolicyHandler().InitPolicyTable()) {
LOG4CXX_ERROR(logger_, "Policy table is not initialized.");
return false;
}
@@ -1563,150 +1736,185 @@ bool ApplicationManagerImpl::Init() {
LOG4CXX_WARN(logger_,
"System is configured to work without policy functionality.");
}
- media_manager_ = media_manager::MediaManagerImpl::instance();
+ media_manager_ = media_manager;
+ return true;
+}
+
+bool ApplicationManagerImpl::Stop() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ stopping_application_mng_lock_.Acquire();
+ is_stopping_ = true;
+ stopping_application_mng_lock_.Release();
+ application_list_update_timer_.Stop();
+ try {
+ UnregisterAllApplications();
+ } catch (...) {
+ LOG4CXX_ERROR(logger_,
+ "An error occurred during unregistering applications.");
+ }
+ request_ctrl_.DestroyThreadpool();
+
+ // for PASA customer policy backup should happen :AllApp(SUSPEND)
+ LOG4CXX_DEBUG(logger_, "Unloading policy library.");
+ GetPolicyHandler().UnloadPolicyLibrary();
+
return true;
}
bool ApplicationManagerImpl::ConvertMessageToSO(
- const Message &message, smart_objects::SmartObject &output) {
- LOG4CXX_INFO(logger_, "\t\t\tMessage to convert: protocol "
- << message.protocol_version() << "; json "
- << message.json_message());
+ const Message& message, smart_objects::SmartObject& output) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_,
+ "\t\t\tMessage to convert: protocol "
+ << message.protocol_version() << "; json "
+ << message.json_message());
switch (message.protocol_version()) {
- case ProtocolVersion::kV4:
- case ProtocolVersion::kV3:
- case ProtocolVersion::kV2: {
- const bool conversion_result =
- formatters::CFormatterJsonSDLRPCv2::fromString(
- message.json_message(), output, message.function_id(),
- message.type(), message.correlation_id());
- if (!conversion_result || !mobile_so_factory().attachSchema(output, true) ||
- ((output.validate() != smart_objects::Errors::OK))) {
- LOG4CXX_WARN(logger_, "Failed to parse string to smart object :"
- << message.json_message());
- utils::SharedPtr<smart_objects::SmartObject> response(
- MessageHelper::CreateNegativeResponse(
- message.connection_key(), message.function_id(),
- message.correlation_id(), mobile_apis::Result::INVALID_DATA));
- ManageMobileCommand(response, commands::Command::ORIGIN_SDL);
- return false;
- }
- LOG4CXX_INFO(logger_,
- "Convertion result for sdl object is true"
- << " function_id "
- << output[jhs::S_PARAMS][jhs::S_FUNCTION_ID].asInt());
- output[strings::params][strings::connection_key] = message.connection_key();
- output[strings::params][strings::protocol_version] =
- message.protocol_version();
- if (message.binary_data()) {
- if (message.payload_size() < message.data_size()) {
- LOG4CXX_ERROR(
- logger_, "Incomplete binary"
- << " binary size should be " << message.data_size()
- << " payload data size is " << message.payload_size());
+ case ProtocolVersion::kV4:
+ case ProtocolVersion::kV3:
+ case ProtocolVersion::kV2: {
+ const bool conversion_result =
+ formatters::CFormatterJsonSDLRPCv2::fromString(
+ message.json_message(),
+ output,
+ message.function_id(),
+ message.type(),
+ message.correlation_id());
+ if (!conversion_result ||
+ !mobile_so_factory().attachSchema(output, true) ||
+ ((output.validate() != smart_objects::Errors::OK))) {
+ LOG4CXX_WARN(logger_,
+ "Failed to parse string to smart object :"
+ << message.json_message());
utils::SharedPtr<smart_objects::SmartObject> response(
MessageHelper::CreateNegativeResponse(
- message.connection_key(), message.function_id(),
- message.correlation_id(), mobile_apis::Result::INVALID_DATA));
- ManageMobileCommand(response);
+ message.connection_key(),
+ message.function_id(),
+ message.correlation_id(),
+ mobile_apis::Result::INVALID_DATA));
+ ManageMobileCommand(response, commands::Command::ORIGIN_SDL);
return false;
}
- output[strings::params][strings::binary_data] = *(message.binary_data());
+ LOG4CXX_DEBUG(logger_,
+ "Convertion result for sdl object is true function_id "
+ << output[jhs::S_PARAMS][jhs::S_FUNCTION_ID].asInt());
+
+ output[strings::params][strings::connection_key] =
+ message.connection_key();
+ output[strings::params][strings::protocol_version] =
+ message.protocol_version();
+ if (message.binary_data()) {
+ if (message.payload_size() < message.data_size()) {
+ LOG4CXX_ERROR(logger_,
+ "Incomplete binary"
+ << " binary size should be " << message.data_size()
+ << " payload data size is "
+ << message.payload_size());
+ utils::SharedPtr<smart_objects::SmartObject> response(
+ MessageHelper::CreateNegativeResponse(
+ message.connection_key(),
+ message.function_id(),
+ message.correlation_id(),
+ mobile_apis::Result::INVALID_DATA));
+ ManageMobileCommand(response, commands::Command::ORIGIN_SDL);
+ return false;
+ }
+ output[strings::params][strings::binary_data] =
+ *(message.binary_data());
+ }
+ break;
}
- break;
- }
- case ProtocolVersion::kHMI: {
+ case ProtocolVersion::kHMI: {
#ifdef ENABLE_LOG
- int32_t result =
+ int32_t result =
#endif
- formatters::FormatterJsonRpc::FromString<hmi_apis::FunctionID::eType,
- hmi_apis::messageType::eType>(
- message.json_message(), output);
- LOG4CXX_INFO(logger_,
- "Convertion result: "
- << result << " function id "
- << output[jhs::S_PARAMS][jhs::S_FUNCTION_ID].asInt());
- if (!hmi_so_factory().attachSchema(output, false)) {
- LOG4CXX_WARN(logger_, "Failed to attach schema to object.");
- return false;
- }
- if (output.validate() != smart_objects::Errors::OK) {
- LOG4CXX_ERROR(logger_, "Incorrect parameter from HMI");
-
- if (application_manager::MessageType::kNotification ==
- output[strings::params][strings::message_type].asInt()) {
- LOG4CXX_ERROR(logger_, "Ignore wrong HMI notification");
- return false;
- }
-
- if (application_manager::MessageType::kRequest ==
- output[strings::params][strings::message_type].asInt()) {
- LOG4CXX_ERROR(logger_, "Ignore wrong HMI request");
+ formatters::FormatterJsonRpc::FromString<
+ hmi_apis::FunctionID::eType,
+ hmi_apis::messageType::eType>(message.json_message(), output);
+ LOG4CXX_DEBUG(logger_,
+ "Convertion result: "
+ << result << " function id "
+ << output[jhs::S_PARAMS][jhs::S_FUNCTION_ID].asInt());
+ if (!hmi_so_factory().attachSchema(output, false)) {
+ LOG4CXX_WARN(logger_, "Failed to attach schema to object.");
return false;
}
+ if (output.validate() != smart_objects::Errors::OK) {
+ LOG4CXX_ERROR(logger_, "Incorrect parameter from HMI");
- output.erase(strings::msg_params);
- output[strings::params][hmi_response::code] =
- hmi_apis::Common_Result::INVALID_DATA;
- output[strings::msg_params][strings::info] =
- std::string("Received invalid data on HMI response");
- }
- break;
- }
- case ProtocolVersion::kV1: {
- static NsSmartDeviceLinkRPC::V1::v4_protocol_v1_2_no_extra v1_shema;
-
- if (message.function_id() == 0 || message.type() == kUnknownType) {
- LOG4CXX_ERROR(logger_, "Message received: UNSUPPORTED_VERSION");
-
- int32_t conversation_result =
- formatters::CFormatterJsonSDLRPCv1::fromString<
- NsSmartDeviceLinkRPC::V1::FunctionID::eType,
- NsSmartDeviceLinkRPC::V1::messageType::eType>(
- message.json_message(), output);
-
- if (formatters::CFormatterJsonSDLRPCv1::kSuccess == conversation_result) {
-
- smart_objects::SmartObject params =
- smart_objects::SmartObject(smart_objects::SmartType::SmartType_Map);
-
- output[strings::params][strings::message_type] =
- NsSmartDeviceLinkRPC::V1::messageType::response;
- output[strings::params][strings::connection_key] =
- message.connection_key();
+ if (application_manager::MessageType::kNotification ==
+ output[strings::params][strings::message_type].asInt()) {
+ LOG4CXX_ERROR(logger_, "Ignore wrong HMI notification");
+ return false;
+ }
- output[strings::msg_params] =
- smart_objects::SmartObject(smart_objects::SmartType::SmartType_Map);
- output[strings::msg_params][strings::success] = false;
- output[strings::msg_params][strings::result_code] =
- NsSmartDeviceLinkRPC::V1::Result::UNSUPPORTED_VERSION;
+ if (application_manager::MessageType::kRequest ==
+ output[strings::params][strings::message_type].asInt()) {
+ LOG4CXX_ERROR(logger_, "Ignore wrong HMI request");
+ return false;
+ }
- smart_objects::SmartObjectSPtr msg_to_send =
- new smart_objects::SmartObject(output);
- v1_shema.attachSchema(*msg_to_send, false);
- SendMessageToMobile(msg_to_send);
- return false;
+ output.erase(strings::msg_params);
+ output[strings::params][hmi_response::code] =
+ hmi_apis::Common_Result::INVALID_DATA;
+ output[strings::msg_params][strings::info] =
+ std::string("Received invalid data on HMI response");
}
+ break;
}
-
- break;
- }
- default:
- // TODO(PV):
- // removed NOTREACHED() because some app can still have vesion 1.
- LOG4CXX_WARN(logger_, "Application used unsupported protocol :"
- << message.protocol_version() << ".");
- return false;
+ case ProtocolVersion::kV1: {
+ static NsSmartDeviceLinkRPC::V1::v4_protocol_v1_2_no_extra v1_shema;
+
+ if (message.function_id() == 0 || message.type() == kUnknownType) {
+ LOG4CXX_ERROR(logger_, "Message received: UNSUPPORTED_VERSION");
+
+ int32_t conversation_result =
+ formatters::CFormatterJsonSDLRPCv1::fromString<
+ NsSmartDeviceLinkRPC::V1::FunctionID::eType,
+ NsSmartDeviceLinkRPC::V1::messageType::eType>(
+ message.json_message(), output);
+
+ if (formatters::CFormatterJsonSDLRPCv1::kSuccess ==
+ conversation_result) {
+ smart_objects::SmartObject params = smart_objects::SmartObject(
+ smart_objects::SmartType::SmartType_Map);
+
+ output[strings::params][strings::message_type] =
+ NsSmartDeviceLinkRPC::V1::messageType::response;
+ output[strings::params][strings::connection_key] =
+ message.connection_key();
+
+ output[strings::msg_params] = smart_objects::SmartObject(
+ smart_objects::SmartType::SmartType_Map);
+ output[strings::msg_params][strings::success] = false;
+ output[strings::msg_params][strings::result_code] =
+ NsSmartDeviceLinkRPC::V1::Result::UNSUPPORTED_VERSION;
+
+ smart_objects::SmartObjectSPtr msg_to_send =
+ new smart_objects::SmartObject(output);
+ v1_shema.attachSchema(*msg_to_send, false);
+ SendMessageToMobile(msg_to_send);
+ return false;
+ }
+ }
+ break;
+ }
+ default:
+ // TODO(PV):
+ // removed NOTREACHED() because some app can still have vesion 1.
+ LOG4CXX_WARN(logger_,
+ "Application used unsupported protocol :"
+ << message.protocol_version() << ".");
+ return false;
}
- LOG4CXX_INFO(logger_, "Successfully parsed message into smart object");
+ LOG4CXX_DEBUG(logger_, "Successfully parsed message into smart object");
return true;
}
bool ApplicationManagerImpl::ConvertSOtoMessage(
- const smart_objects::SmartObject &message, Message &output) {
- LOG4CXX_INFO(logger_, "Message to convert");
+ const smart_objects::SmartObject& message, Message& output) {
+ LOG4CXX_AUTO_TRACE(logger_);
if (smart_objects::SmartType_Null == message.getType() ||
smart_objects::SmartType_Invalid == message.getType()) {
@@ -1714,53 +1922,54 @@ bool ApplicationManagerImpl::ConvertSOtoMessage(
return false;
}
- LOG4CXX_INFO(logger_, "Message with protocol: "
- << message.getElement(jhs::S_PARAMS)
- .getElement(jhs::S_PROTOCOL_TYPE)
- .asInt());
+ LOG4CXX_DEBUG(
+ logger_,
+ "Message with protocol: " << message.getElement(jhs::S_PARAMS)
+ .getElement(jhs::S_PROTOCOL_TYPE)
+ .asInt());
std::string output_string;
- switch (message.getElement(jhs::S_PARAMS)
- .getElement(jhs::S_PROTOCOL_TYPE)
- .asInt()) {
- case 0: {
- if (message.getElement(jhs::S_PARAMS)
- .getElement(jhs::S_PROTOCOL_VERSION)
- .asInt() == 1) {
- if (!formatters::CFormatterJsonSDLRPCv1::toString(message,
- output_string)) {
- LOG4CXX_WARN(logger_, "Failed to serialize smart object");
- return false;
+ const int64_t protocol_type = message.getElement(jhs::S_PARAMS)
+ .getElement(jhs::S_PROTOCOL_TYPE)
+ .asInt();
+ const int64_t protocol_version = message.getElement(jhs::S_PARAMS)
+ .getElement(jhs::S_PROTOCOL_VERSION)
+ .asInt();
+ switch (protocol_type) {
+ case 0: {
+ if (protocol_version == 1) {
+ if (!formatters::CFormatterJsonSDLRPCv1::toString(message,
+ output_string)) {
+ LOG4CXX_WARN(logger_, "Failed to serialize smart object");
+ return false;
+ }
+ output.set_protocol_version(application_manager::kV1);
+ } else {
+ if (!formatters::CFormatterJsonSDLRPCv2::toString(message,
+ output_string)) {
+ LOG4CXX_WARN(logger_, "Failed to serialize smart object");
+ return false;
+ }
+ output.set_protocol_version(
+ static_cast<ProtocolVersion>(protocol_version));
}
- output.set_protocol_version(application_manager::kV1);
- } else {
- if (!formatters::CFormatterJsonSDLRPCv2::toString(message,
- output_string)) {
+
+ break;
+ }
+ case 1: {
+ if (!formatters::FormatterJsonRpc::ToString(message, output_string)) {
LOG4CXX_WARN(logger_, "Failed to serialize smart object");
return false;
}
- output.set_protocol_version(
- static_cast<ProtocolVersion>(message.getElement(jhs::S_PARAMS)
- .getElement(jhs::S_PROTOCOL_VERSION)
- .asUInt()));
+ output.set_protocol_version(application_manager::kHMI);
+ break;
}
-
- break;
- }
- case 1: {
- if (!formatters::FormatterJsonRpc::ToString(message, output_string)) {
- LOG4CXX_WARN(logger_, "Failed to serialize smart object");
+ default:
+ NOTREACHED();
return false;
- }
- output.set_protocol_version(application_manager::kHMI);
- break;
- }
- default:
- NOTREACHED();
- return false;
}
- LOG4CXX_INFO(logger_, "Convertion result: " << output_string);
+ LOG4CXX_DEBUG(logger_, "Convertion result: " << output_string);
output.set_connection_key(message.getElement(jhs::S_PARAMS)
.getElement(strings::connection_key)
@@ -1787,7 +1996,7 @@ bool ApplicationManagerImpl::ConvertSOtoMessage(
}
if (message.getElement(jhs::S_PARAMS).keyExists(strings::binary_data)) {
- application_manager::BinaryData *binaryData =
+ application_manager::BinaryData* binaryData =
new application_manager::BinaryData(
message.getElement(jhs::S_PARAMS)
.getElement(strings::binary_data)
@@ -1800,17 +2009,17 @@ bool ApplicationManagerImpl::ConvertSOtoMessage(
output.set_binary_data(binaryData);
}
- LOG4CXX_INFO(logger_, "Successfully parsed smart object into message");
+ LOG4CXX_DEBUG(logger_, "Successfully parsed smart object into message");
return true;
}
utils::SharedPtr<Message> ApplicationManagerImpl::ConvertRawMsgToMessage(
const ::protocol_handler::RawMessagePtr message) {
+ LOG4CXX_AUTO_TRACE(logger_);
DCHECK(message);
utils::SharedPtr<Message> outgoing_message;
- LOG4CXX_INFO(logger_, "Service type." << message->service_type());
-
+ LOG4CXX_DEBUG(logger_, "Service type." << message->service_type());
if (message->service_type() != protocol_handler::kRpc &&
message->service_type() != protocol_handler::kBulk) {
// skip this message, not under handling of ApplicationManager
@@ -1818,7 +2027,7 @@ utils::SharedPtr<Message> ApplicationManagerImpl::ConvertRawMsgToMessage(
return outgoing_message;
}
- Message *convertion_result =
+ Message* convertion_result =
MobileMessageHandler::HandleIncomingMessageProtocol(message);
if (convertion_result) {
@@ -1831,14 +2040,16 @@ utils::SharedPtr<Message> ApplicationManagerImpl::ConvertRawMsgToMessage(
void ApplicationManagerImpl::ProcessMessageFromMobile(
const utils::SharedPtr<Message> message) {
- LOG4CXX_INFO(logger_, "ApplicationManagerImpl::ProcessMessageFromMobile()");
-#ifdef TIME_TESTER
- AMMetricObserver::MessageMetricSharedPtr metric(
- new AMMetricObserver::MessageMetric());
+ LOG4CXX_AUTO_TRACE(logger_);
+#ifdef TELEMETRY_MONITOR
+ AMTelemetryObserver::MessageMetricSharedPtr metric(
+ new AMTelemetryObserver::MessageMetric());
metric->begin = date_time::DateTime::getCurrentTime();
-#endif // TIME_TESTER
- smart_objects::SmartObjectSPtr so_from_mobile(new smart_objects::SmartObject);
+#endif // TELEMETRY_MONITOR
+ smart_objects::SmartObjectSPtr so_from_mobile =
+ utils::MakeShared<smart_objects::SmartObject>();
+ DCHECK_OR_RETURN_VOID(so_from_mobile);
if (!so_from_mobile) {
LOG4CXX_ERROR(logger_, "Null pointer");
return;
@@ -1848,24 +2059,24 @@ void ApplicationManagerImpl::ProcessMessageFromMobile(
LOG4CXX_ERROR(logger_, "Cannot create smart object from message");
return;
}
-#ifdef TIME_TESTER
+#ifdef TELEMETRY_MONITOR
metric->message = so_from_mobile;
-#endif // TIME_TESTER
+#endif // TELEMETRY_MONITOR
if (!ManageMobileCommand(so_from_mobile, commands::Command::ORIGIN_MOBILE)) {
LOG4CXX_ERROR(logger_, "Received command didn't run successfully");
}
-#ifdef TIME_TESTER
+#ifdef TELEMETRY_MONITOR
metric->end = date_time::DateTime::getCurrentTime();
if (metric_observer_) {
metric_observer_->OnMessage(metric);
}
-#endif // TIME_TESTER
+#endif // TELEMETRY_MONITOR
}
void ApplicationManagerImpl::ProcessMessageFromHMI(
const utils::SharedPtr<Message> message) {
- LOG4CXX_INFO(logger_, "ApplicationManagerImpl::ProcessMessageFromHMI()");
+ LOG4CXX_AUTO_TRACE(logger_);
smart_objects::SmartObjectSPtr smart_object(new smart_objects::SmartObject);
if (!smart_object) {
@@ -1880,15 +2091,15 @@ void ApplicationManagerImpl::ProcessMessageFromHMI(
LOG4CXX_ERROR(logger_, "Cannot create smart object from message");
return;
}
-#endif // HMI_DBUS_API
+#endif // HMI_DBUS_API
- LOG4CXX_INFO(logger_, "Converted message, trying to create hmi command");
+ LOG4CXX_DEBUG(logger_, "Converted message, trying to create hmi command");
if (!ManageHMICommand(smart_object)) {
LOG4CXX_ERROR(logger_, "Received command didn't run successfully");
}
}
-hmi_apis::HMI_API &ApplicationManagerImpl::hmi_so_factory() {
+hmi_apis::HMI_API& ApplicationManagerImpl::hmi_so_factory() {
if (!hmi_so_factory_) {
hmi_so_factory_ = new hmi_apis::HMI_API;
if (!hmi_so_factory_) {
@@ -1899,7 +2110,7 @@ hmi_apis::HMI_API &ApplicationManagerImpl::hmi_so_factory() {
return *hmi_so_factory_;
}
-mobile_apis::MOBILE_API &ApplicationManagerImpl::mobile_so_factory() {
+mobile_apis::MOBILE_API& ApplicationManagerImpl::mobile_so_factory() {
if (!mobile_so_factory_) {
mobile_so_factory_ = new mobile_apis::MOBILE_API;
if (!mobile_so_factory_) {
@@ -1910,71 +2121,93 @@ mobile_apis::MOBILE_API &ApplicationManagerImpl::mobile_so_factory() {
return *mobile_so_factory_;
}
-HMICapabilities &ApplicationManagerImpl::hmi_capabilities() {
+HMICapabilities& ApplicationManagerImpl::hmi_capabilities() {
+ return hmi_capabilities_;
+}
+
+const HMICapabilities& ApplicationManagerImpl::hmi_capabilities() const {
return hmi_capabilities_;
}
-void ApplicationManagerImpl::PullLanguagesInfo(const SmartObject &app_data,
- SmartObject &ttsName,
- SmartObject &vrSynonym) {
+void ApplicationManagerImpl::PullLanguagesInfo(const SmartObject& app_data,
+ SmartObject& ttsName,
+ SmartObject& vrSynonym) {
LOG4CXX_AUTO_TRACE(logger_);
- if (app_data.keyExists(json::languages)) {
+ if (!app_data.keyExists(json::languages)) {
+ LOG4CXX_WARN(logger_, "\"languages\" not exists");
+ return;
+ }
- const HMICapabilities &hmi_cap = hmi_capabilities();
- std::string vr(
- MessageHelper::CommonLanguageToString(hmi_cap.active_vr_language()));
- const SmartObject &arr = app_data[json::languages];
+ const HMICapabilities& hmi_cap = hmi_capabilities();
+ std::string cur_vr_lang(
+ MessageHelper::CommonLanguageToString(hmi_cap.active_vr_language()));
+ const SmartObject& languages = app_data[json::languages];
- std::transform(vr.begin(), vr.end(), vr.begin(), ::toupper);
+ std::transform(
+ cur_vr_lang.begin(), cur_vr_lang.end(), cur_vr_lang.begin(), ::toupper);
- ssize_t default_idx = -1;
- ssize_t specific_idx = -1;
+ ssize_t default_idx = -1;
+ ssize_t specific_idx = -1;
- const size_t size = arr.length();
- for (size_t idx = 0; idx < size; ++idx) {
- if (arr[idx].keyExists(vr)) {
- specific_idx = idx;
- break;
- } else if (arr[idx].keyExists(json::default_)) {
- default_idx = idx;
- } else {
- LOG4CXX_DEBUG(logger_, "Unknown key was specified.");
- }
+ const size_t size = languages.length();
+ for (size_t idx = 0; idx < size; ++idx) {
+ if (languages[idx].keyExists(cur_vr_lang)) {
+ LOG4CXX_DEBUG(logger_, "Found active HMI language " << cur_vr_lang);
+ specific_idx = idx;
+ } else if (languages[idx].keyExists(json::default_)) {
+ LOG4CXX_DEBUG(logger_, "Found default language");
+ default_idx = idx;
}
+ }
- const ssize_t regular_id = specific_idx != -1 ? specific_idx : default_idx;
+ if ((-1 == specific_idx) && (-1 == default_idx)) {
+ LOG4CXX_DEBUG(logger_, "No suitable language found");
+ return;
+ }
- if (regular_id != -1 &&
- app_data[json::languages][regular_id][vr].keyExists(json::ttsName) &&
- app_data[json::languages][regular_id][vr].keyExists(json::vrSynonyms)) {
- ttsName = app_data[json::languages][regular_id][vr][json::ttsName];
- vrSynonym = app_data[json::languages][regular_id][vr][json::vrSynonyms];
- }
+ if (app_data[json::languages][specific_idx][cur_vr_lang].keyExists(
+ json::ttsName)) {
+ LOG4CXX_DEBUG(logger_, "Get ttsName from " << cur_vr_lang << " language");
+ ttsName =
+ app_data[json::languages][specific_idx][cur_vr_lang][json::ttsName];
+ } else {
+ LOG4CXX_DEBUG(logger_,
+ "No data for ttsName for " << cur_vr_lang << " language");
+ }
+
+ if (app_data[json::languages][specific_idx][cur_vr_lang].keyExists(
+ json::vrSynonyms)) {
+ LOG4CXX_DEBUG(logger_,
+ "Get vrSynonyms from " << cur_vr_lang << " language");
+ vrSynonym =
+ app_data[json::languages][specific_idx][cur_vr_lang][json::vrSynonyms];
+ } else {
+ LOG4CXX_DEBUG(logger_,
+ "No data for vrSynonyms for " << cur_vr_lang << " language");
}
}
-void ApplicationManagerImpl::CreateApplications(SmartArray &obj_array,
+void ApplicationManagerImpl::CreateApplications(SmartArray& obj_array,
const uint32_t connection_key) {
LOG4CXX_AUTO_TRACE(logger_);
using namespace policy;
- using namespace profile;
const std::size_t arr_size(obj_array.size());
for (std::size_t idx = 0; idx < arr_size; ++idx) {
- const SmartObject &app_data = obj_array[idx];
+ const SmartObject& app_data = obj_array[idx];
if (!(app_data.keyExists(json::name) && app_data.keyExists(json::appId))) {
LOG4CXX_DEBUG(logger_, "The entry in query apps json is not valid");
continue;
}
- const std::string mobile_app_id(app_data[json::appId].asString());
+ const std::string policy_app_id(app_data[json::appId].asString());
ApplicationSharedPtr registered_app =
- ApplicationManagerImpl::instance()->application_by_policy_id(
- mobile_app_id);
+ application_by_policy_id(policy_app_id);
if (registered_app) {
- LOG4CXX_DEBUG(logger_, "Application with the same id: "
- << mobile_app_id << " is registered already.");
+ LOG4CXX_DEBUG(logger_,
+ "Application with the same id: "
+ << policy_app_id << " is registered already.");
continue;
}
@@ -1984,7 +2217,8 @@ void ApplicationManagerImpl::CreateApplications(SmartArray &obj_array,
SmartObject vrSynonym;
SmartObject ttsName;
- const std::string appName(app_data[json::name].asString());
+ const custom_str::CustomString appName(
+ app_data[json::name].asCustomString());
if (app_data.keyExists(json::ios)) {
os_type = json::ios;
@@ -1996,40 +2230,46 @@ void ApplicationManagerImpl::CreateApplications(SmartArray &obj_array,
PullLanguagesInfo(app_data[os_type], ttsName, vrSynonym);
- if (ttsName.empty() || vrSynonym.empty()) {
+ if (ttsName.empty()) {
ttsName = SmartObject(SmartType_Array);
- vrSynonym = SmartObject(SmartType_Array);
-
ttsName[0] = appName;
+ }
+ if (vrSynonym.empty()) {
+ vrSynonym = SmartObject(SmartType_Array);
vrSynonym[0] = appName;
}
- const uint32_t hmi_app_id =
- resume_ctrl_.IsApplicationSaved(mobile_app_id)
- ? resume_ctrl_.GetHMIApplicationID(mobile_app_id)
- : GenerateNewHMIAppID();
-
- const std::string app_icon_dir(Profile::instance()->app_icons_folder());
- const std::string full_icon_path(app_icon_dir + "/" + mobile_app_id);
+ const std::string app_icon_dir(settings_.app_icons_folder());
+ const std::string full_icon_path(app_icon_dir + "/" + policy_app_id);
uint32_t device_id = 0;
- connection_handler::ConnectionHandlerImpl *con_handler_impl =
- static_cast<connection_handler::ConnectionHandlerImpl *>(
- connection_handler_);
if (-1 ==
- con_handler_impl->GetDataOnSessionKey(connection_key, NULL, NULL,
- &device_id)) {
+ connection_handler().GetDataOnSessionKey(
+ connection_key, NULL, NULL, &device_id)) {
LOG4CXX_ERROR(logger_,
"Failed to create application: no connection info.");
continue;
}
+ std::string device_mac;
+ connection_handler().get_session_observer().GetDataOnDeviceID(
+ device_id, NULL, NULL, &device_mac, NULL);
+
+ const uint32_t hmi_app_id =
+ resume_ctrl_.IsApplicationSaved(policy_app_id, device_mac)
+ ? resume_ctrl_.GetHMIApplicationID(policy_app_id, device_mac)
+ : GenerateNewHMIAppID();
+
// AppId = 0 because this is query_app(provided by hmi for download, but not
// yet registered)
ApplicationSharedPtr app(
- new ApplicationImpl(0, mobile_app_id, appName,
- PolicyHandler::instance()->GetStatisticManager()));
+ new ApplicationImpl(0,
+ policy_app_id,
+ device_mac,
+ appName,
+ GetPolicyHandler().GetStatisticManager(),
+ *this));
DCHECK_OR_RETURN_VOID(app);
app->SetShemaUrl(url_scheme);
app->SetPackageName(package_name);
@@ -2050,7 +2290,7 @@ void ApplicationManagerImpl::CreateApplications(SmartArray &obj_array,
}
void ApplicationManagerImpl::ProcessQueryApp(
- const smart_objects::SmartObject &sm_object,
+ const smart_objects::SmartObject& sm_object,
const uint32_t connection_key) {
LOG4CXX_AUTO_TRACE(logger_);
using namespace policy;
@@ -2060,47 +2300,53 @@ void ApplicationManagerImpl::ProcessQueryApp(
return;
}
- SmartArray *obj_array = sm_object[json::response].asArray();
+ SmartArray* obj_array = sm_object[json::response].asArray();
if (NULL != obj_array) {
CreateApplications(*obj_array, connection_key);
SendUpdateAppList();
AppsWaitRegistrationSet::const_iterator it = apps_to_register_.begin();
for (; it != apps_to_register_.end(); ++it) {
-
const std::string full_icon_path((*it)->app_icon_path());
if (file_system::FileExists(full_icon_path)) {
- MessageHelper::SendSetAppIcon((*it)->hmi_app_id(), full_icon_path);
+ MessageHelper::SendSetAppIcon(
+ (*it)->hmi_app_id(), full_icon_path, *this);
}
}
}
}
-#ifdef TIME_TESTER
-void ApplicationManagerImpl::SetTimeMetricObserver(AMMetricObserver *observer) {
+bool ApplicationManagerImpl::is_attenuated_supported() const {
+ return hmi_capabilities().attenuated_supported() &&
+ get_settings().is_mixing_audio_supported();
+}
+
+#ifdef TELEMETRY_MONITOR
+void ApplicationManagerImpl::SetTelemetryObserver(
+ AMTelemetryObserver* observer) {
metric_observer_ = observer;
}
-#endif // TIME_TESTER
+#endif // TELEMETRY_MONITOR
void ApplicationManagerImpl::addNotification(const CommandSharedPtr ptr) {
request_ctrl_.addNotification(ptr);
}
void ApplicationManagerImpl::removeNotification(
- const commands::Command *notification) {
+ const commands::Command* notification) {
request_ctrl_.removeNotification(notification);
}
void ApplicationManagerImpl::updateRequestTimeout(
- uint32_t connection_key, uint32_t mobile_correlation_id,
+ uint32_t connection_key,
+ uint32_t mobile_correlation_id,
uint32_t new_timeout_value) {
LOG4CXX_AUTO_TRACE(logger_);
- request_ctrl_.updateRequestTimeout(connection_key, mobile_correlation_id,
- new_timeout_value);
+ request_ctrl_.updateRequestTimeout(
+ connection_key, mobile_correlation_id, new_timeout_value);
}
-const uint32_t
-ApplicationManagerImpl::application_id(const int32_t correlation_id) {
+uint32_t ApplicationManagerImpl::application_id(const int32_t correlation_id) {
// ykazakov: there is no erase for const iterator for QNX
std::map<const int32_t, const uint32_t>::iterator it =
appID_list_.find(correlation_id);
@@ -2120,13 +2366,13 @@ void ApplicationManagerImpl::set_application_id(const int32_t correlation_id,
}
void ApplicationManagerImpl::AddPolicyObserver(
- policy::PolicyHandlerObserver *listener) {
- policy::PolicyHandler::instance()->add_listener(listener);
+ policy::PolicyHandlerObserver* listener) {
+ GetPolicyHandler().add_listener(listener);
}
void ApplicationManagerImpl::RemovePolicyObserver(
- policy::PolicyHandlerObserver *listener) {
- policy::PolicyHandler::instance()->remove_listener(listener);
+ policy::PolicyHandlerObserver* listener) {
+ GetPolicyHandler().remove_listener(listener);
}
void ApplicationManagerImpl::SetUnregisterAllApplicationsReason(
@@ -2137,28 +2383,32 @@ void ApplicationManagerImpl::SetUnregisterAllApplicationsReason(
void ApplicationManagerImpl::HeadUnitReset(
mobile_api::AppInterfaceUnregisteredReason::eType reason) {
- stopping_flag_lock_.Acquire();
+ stopping_application_mng_lock_.Acquire();
is_stopping_ = true;
- stopping_flag_lock_.Release();
+ stopping_application_mng_lock_.Release();
switch (reason) {
- case mobile_api::AppInterfaceUnregisteredReason::MASTER_RESET: {
- UnregisterAllApplications();
- policy::PolicyHandler::instance()->ResetPolicyTable();
- policy::PolicyHandler::instance()->UnloadPolicyLibrary();
+ case mobile_api::AppInterfaceUnregisteredReason::MASTER_RESET: {
+ UnregisterAllApplications();
+ GetPolicyHandler().ResetPolicyTable();
+ GetPolicyHandler().UnloadPolicyLibrary();
+
+ resume_controller().StopSavePersistentDataTimer();
+ file_system::remove_directory_content(
+ get_settings().app_storage_folder());
+ break;
+ }
+ case mobile_api::AppInterfaceUnregisteredReason::FACTORY_DEFAULTS: {
+ GetPolicyHandler().ClearUserConsent();
- resume_controller().StopSavePersistentDataTimer();
- file_system::remove_directory_content(
- profile::Profile::instance()->app_storage_folder());
- break;
- }
- case mobile_api::AppInterfaceUnregisteredReason::FACTORY_DEFAULTS: {
- policy::PolicyHandler::instance()->ClearUserConsent();
- break;
- }
- default: {
- LOG4CXX_ERROR(logger_, "Bad AppInterfaceUnregisteredReason");
- return;
- }
+ resume_controller().StopSavePersistentDataTimer();
+ file_system::remove_directory_content(
+ get_settings().app_storage_folder());
+ break;
+ }
+ default: {
+ LOG4CXX_ERROR(logger_, "Bad AppInterfaceUnregisteredReason");
+ return;
+ }
}
}
@@ -2188,8 +2438,9 @@ void ApplicationManagerImpl::SendOnSDLClose() {
new Message(protocol_handler::MessagePriority::kDefault));
hmi_so_factory().attachSchema(*msg, false);
- LOG4CXX_DEBUG(logger_, "Attached schema to message, result if valid: "
- << msg->isValid());
+ LOG4CXX_DEBUG(
+ logger_,
+ "Attached schema to message, result if valid: " << msg->isValid());
#ifdef HMI_DBUS_API
message_to_send->set_smart_object(*msg);
@@ -2199,7 +2450,7 @@ void ApplicationManagerImpl::SendOnSDLClose() {
"Cannot send message to HMI: failed to create string");
return;
}
-#endif // HMI_DBUS_API
+#endif // HMI_DBUS_API
if (!hmi_handler_) {
LOG4CXX_WARN(logger_, "No HMI Handler set");
@@ -2225,32 +2476,26 @@ void ApplicationManagerImpl::UnregisterAllApplications() {
ClearTTSGlobalPropertiesList();
- { // A local scope to limit accessor's lifetime and release app list lock.
- ApplicationListAccessor accessor;
- ApplictionSetConstIt it = accessor.begin();
- while (it != accessor.end()) {
+ { // A local scope to limit accessor's lifetime and release app list lock.
+ DataAccessor<ApplicationSet> accessor = applications();
+ ApplicationSetConstIt it = accessor.GetData().begin();
+ while (it != accessor.GetData().end()) {
ApplicationSharedPtr app_to_remove = *it;
-
-#ifdef CUSTOMER_PASA
- if (!is_ignition_off) {
-#endif // CUSTOMER_PASA
- MessageHelper::SendOnAppInterfaceUnregisteredNotificationToMobile(
- app_to_remove->app_id(), unregister_reason_);
-#ifdef CUSTOMER_PASA
- }
-#endif // CUSTOMER_PASA
-
+ ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ app_to_remove->app_id(), unregister_reason_),
+ commands::Command::ORIGIN_SDL);
UnregisterApplication(app_to_remove->app_id(),
- mobile_apis::Result::INVALID_ENUM, is_ignition_off,
+ mobile_apis::Result::INVALID_ENUM,
+ is_ignition_off,
is_unexpected_disconnect);
- connection_handler_->CloseSession(app_to_remove->app_id(),
+ connection_handler().CloseSession(app_to_remove->app_id(),
connection_handler::kCommon);
- it = accessor.begin();
+ it = accessor.GetData().begin();
}
}
-
- if (is_ignition_off) { // Move this block before unregistering apps?
- resume_controller().Suspend();
+ if (is_ignition_off) {
+ resume_controller().OnSuspend();
}
request_ctrl_.terminateAllHMIRequests();
}
@@ -2263,23 +2508,39 @@ void ApplicationManagerImpl::RemoveAppsWaitingForRegistration(
apps_to_register_.begin(), apps_to_register_.end(), device_finder);
while (apps_to_register_.end() != it_app) {
- LOG4CXX_DEBUG(logger_, "Waiting app: " << (*it_app)->name()
- << " is removed.");
+ LOG4CXX_DEBUG(logger_,
+ "Waiting app: " << (*it_app)->name().c_str()
+ << " is removed.");
apps_to_register_.erase(it_app);
- it_app = std::find_if(apps_to_register_.begin(), apps_to_register_.end(),
- device_finder);
+ it_app = std::find_if(
+ apps_to_register_.begin(), apps_to_register_.end(), device_finder);
}
apps_to_register_list_lock_.Release();
}
void ApplicationManagerImpl::UnregisterApplication(
- const uint32_t &app_id, mobile_apis::Result::eType reason, bool is_resuming,
+ const uint32_t& app_id,
+ mobile_apis::Result::eType reason,
+ bool is_resuming,
bool is_unexpected_disconnect) {
- LOG4CXX_INFO(logger_, "app_id = " << app_id << "; reason = " << reason
- << "; is_resuming = " << is_resuming
- << "; is_unexpected_disconnect = "
- << is_unexpected_disconnect);
+ LOG4CXX_DEBUG(logger_,
+ "app_id = " << app_id << "; reason = " << reason
+ << "; is_resuming = " << is_resuming
+ << "; is_unexpected_disconnect = "
+ << is_unexpected_disconnect);
+ size_t subscribed_for_way_points_app_count = 0;
+
+ // SDL sends UnsubscribeWayPoints only for last application
+ {
+ sync_primitives::AutoLock lock(subscribed_way_points_apps_lock_);
+ subscribed_for_way_points_app_count =
+ subscribed_way_points_apps_list_.size();
+ }
+ if (1 == subscribed_for_way_points_app_count) {
+ LOG4CXX_ERROR(logger_, "Send UnsubscribeWayPoints");
+ MessageHelper::SendUnsubscribedWayPoints(*this);
+ }
NaviServiceStatusMap::iterator it = navi_service_status_.find(app_id);
if (navi_service_status_.end() != it) {
@@ -2290,35 +2551,41 @@ void ApplicationManagerImpl::UnregisterApplication(
RemoveAppFromTTSGlobalPropertiesList(app_id);
switch (reason) {
- case mobile_apis::Result::SUCCESS:
- break;
- case mobile_apis::Result::DISALLOWED:
- break;
- case mobile_apis::Result::USER_DISALLOWED:
- break;
- case mobile_apis::Result::INVALID_CERT:
- break;
- case mobile_apis::Result::EXPIRED_CERT:
- break;
- case mobile_apis::Result::TOO_MANY_PENDING_REQUESTS: {
- ApplicationSharedPtr app_ptr = application(app_id);
- if (app_ptr) {
- app_ptr->usage_report().RecordRemovalsForBadBehavior();
+ case mobile_apis::Result::SUCCESS:
+ break;
+ case mobile_apis::Result::DISALLOWED:
+ break;
+ case mobile_apis::Result::USER_DISALLOWED:
+ break;
+ case mobile_apis::Result::INVALID_CERT:
+ break;
+ case mobile_apis::Result::EXPIRED_CERT:
+ break;
+ case mobile_apis::Result::TOO_MANY_PENDING_REQUESTS: {
+ ApplicationSharedPtr app_ptr = application(app_id);
+ if (app_ptr) {
+ app_ptr->usage_report().RecordRemovalsForBadBehavior();
+ if (reason == mobile_apis::Result::TOO_MANY_PENDING_REQUESTS) {
+ LOG4CXX_DEBUG(
+ logger_,
+ "INSERT: " << GetHashedAppID(app_id, app_ptr->policy_app_id()));
+ forbidden_applications.insert(
+ GetHashedAppID(app_id, app_ptr->policy_app_id()));
+ }
+ }
+ break;
+ }
+ default: {
+ LOG4CXX_ERROR(logger_, "Unknown unregister reason " << reason);
+ break;
}
- break;
- }
- default: {
- LOG4CXX_ERROR(logger_, "Unknown unregister reason " << reason);
- break;
- }
}
-
ApplicationSharedPtr app_to_remove;
connection_handler::DeviceHandle handle = 0;
{
- ApplicationListAccessor accessor;
- ApplictionSetConstIt it = accessor.begin();
- for (; it != accessor.end(); ++it) {
+ DataAccessor<ApplicationSet> accessor(applications());
+ ApplicationSetConstIt it = accessor.GetData().begin();
+ for (; it != accessor.GetData().end(); ++it) {
if ((*it)->app_id() == app_id) {
app_to_remove = *it;
handle = app_to_remove->device();
@@ -2327,12 +2594,24 @@ void ApplicationManagerImpl::UnregisterApplication(
}
if (!app_to_remove) {
LOG4CXX_ERROR(logger_, "Cant find application with app_id = " << app_id);
+
+ // Just to terminate RAI in case of connection is dropped (rare case)
+ // App won't be unregistered since RAI has not been started yet
+ LOG4CXX_DEBUG(logger_, "Trying to terminate possible RAI request.");
+ request_ctrl_.terminateAppRequests(app_id);
+
return;
}
- accessor.Erase(app_to_remove);
-
+ if (is_resuming) {
+ resume_ctrl_.SaveApplication(app_to_remove);
+ } else {
+ resume_ctrl_.RemoveApplicationFromSaved(app_to_remove);
+ }
+ applications_.erase(app_to_remove);
+ (hmi_capabilities_.get_hmi_language_handler())
+ .OnUnregisterApplication(app_id);
AppV4DevicePredicate finder(handle);
- ApplicationSharedPtr app = accessor.Find(finder);
+ ApplicationSharedPtr app = FindApp(accessor, finder);
if (!app) {
LOG4CXX_DEBUG(
logger_, "There is no more SDL4 apps with device handle: " << handle);
@@ -2341,40 +2620,32 @@ void ApplicationManagerImpl::UnregisterApplication(
SendUpdateAppList();
}
}
-
- if (is_resuming) {
- resume_ctrl_.SaveApplication(app_to_remove);
- } else {
- resume_ctrl_.RemoveApplicationFromSaved(app_to_remove->mobile_app_id());
- }
-
if (audio_pass_thru_active_) {
// May be better to put this code in MessageHelper?
- end_audio_pass_thru();
+ EndAudioPassThrough();
StopAudioPassThru(app_id);
- MessageHelper::SendStopAudioPathThru();
+ MessageHelper::SendStopAudioPathThru(*this);
}
- MessageHelper::SendOnAppUnregNotificationToHMI(app_to_remove,
- is_unexpected_disconnect);
+ MessageHelper::SendOnAppUnregNotificationToHMI(
+ app_to_remove, is_unexpected_disconnect, *this);
request_ctrl_.terminateAppRequests(app_id);
return;
}
-void ApplicationManagerImpl::OnAppUnauthorized(const uint32_t &app_id) {
- connection_handler_->CloseSession(app_id,
+void ApplicationManagerImpl::OnAppUnauthorized(const uint32_t& app_id) {
+ connection_handler().CloseSession(app_id,
connection_handler::kUnauthorizedApp);
}
void ApplicationManagerImpl::Handle(const impl::MessageFromMobile message) {
- LOG4CXX_INFO(logger_, "Received message from Mobile side");
+ LOG4CXX_AUTO_TRACE(logger_);
if (!message) {
LOG4CXX_ERROR(logger_, "Null-pointer message received.");
return;
}
-
- sync_primitives::AutoLock lock(stopping_flag_lock_);
+ sync_primitives::AutoLock lock(stopping_application_mng_lock_);
if (is_stopping_) {
LOG4CXX_INFO(logger_, "Application manager is stopping");
return;
@@ -2400,7 +2671,7 @@ void ApplicationManagerImpl::Handle(const impl::MessageToMobile message) {
bool is_final = message.is_final;
bool close_session = false;
if (is_final) {
- if (1 < connection_handler_->GetConnectionSessionsCount(
+ if (1 < connection_handler().GetConnectionSessionsCount(
message->connection_key())) {
is_final = false;
close_session = true;
@@ -2411,13 +2682,13 @@ void ApplicationManagerImpl::Handle(const impl::MessageToMobile message) {
LOG4CXX_INFO(logger_, "Message for mobile given away");
if (close_session) {
- connection_handler_->CloseSession(message->connection_key(),
+ connection_handler().CloseSession(message->connection_key(),
connection_handler::kCommon);
}
}
void ApplicationManagerImpl::Handle(const impl::MessageFromHmi message) {
- LOG4CXX_INFO(logger_, "Received message from hmi");
+ LOG4CXX_AUTO_TRACE(logger_);
if (!message) {
LOG4CXX_ERROR(logger_, "Null-pointer message received.");
@@ -2428,27 +2699,27 @@ void ApplicationManagerImpl::Handle(const impl::MessageFromHmi message) {
}
void ApplicationManagerImpl::Handle(const impl::MessageToHmi message) {
- LOG4CXX_INFO(logger_, "Received message to hmi");
+ LOG4CXX_AUTO_TRACE(logger_);
if (!hmi_handler_) {
LOG4CXX_ERROR(logger_, "Observer is not set for HMIMessageHandler");
return;
}
hmi_handler_->SendMessageToHMI(message);
- LOG4CXX_INFO(logger_, "Message to hmi given away.");
+ LOG4CXX_INFO(logger_, "Message for HMI given away");
}
void ApplicationManagerImpl::Handle(const impl::AudioData message) {
- LOG4CXX_INFO(logger_, "Send AudioPassThru notification");
+ LOG4CXX_AUTO_TRACE(logger_);
smart_objects::SmartObjectSPtr on_audio_pass =
new smart_objects::SmartObject();
if (!on_audio_pass) {
- LOG4CXX_ERROR_EXT(logger_, "OnAudioPassThru NULL pointer");
+ LOG4CXX_ERROR(logger_, "OnAudioPassThru NULL pointer");
return;
}
- LOG4CXX_INFO_EXT(logger_, "Fill smart object");
+ LOG4CXX_DEBUG(logger_, "Fill smart object");
(*on_audio_pass)[strings::params][strings::message_type] =
application_manager::MessageType::kNotification;
@@ -2458,29 +2729,35 @@ void ApplicationManagerImpl::Handle(const impl::AudioData message) {
(*on_audio_pass)[strings::params][strings::function_id] =
mobile_apis::FunctionID::OnAudioPassThruID;
- LOG4CXX_INFO_EXT(logger_, "Fill binary data");
+ LOG4CXX_DEBUG(logger_, "Fill binary data");
// binary data
(*on_audio_pass)[strings::params][strings::binary_data] =
smart_objects::SmartObject(message.binary_data);
- LOG4CXX_INFO_EXT(logger_, "After fill binary data");
-
- LOG4CXX_INFO_EXT(logger_, "Send data");
+ LOG4CXX_DEBUG(logger_, "After fill binary data");
+ LOG4CXX_DEBUG(logger_, "Send data");
CommandSharedPtr command(MobileCommandFactory::CreateCommand(
- on_audio_pass, commands::Command::ORIGIN_SDL));
+ on_audio_pass, commands::Command::ORIGIN_SDL, *this));
+ if (!command) {
+ LOG4CXX_WARN(logger_, "Failed to create mobile command from smart object");
+ return;
+ }
+
command->Init();
command->Run();
command->CleanUp();
}
mobile_apis::Result::eType ApplicationManagerImpl::CheckPolicyPermissions(
- const std::string &policy_app_id, mobile_apis::HMILevel::eType hmi_level,
- mobile_apis::FunctionID::eType function_id, const RPCParams &rpc_params,
- CommandParametersPermissions *params_permissions) {
- LOG4CXX_INFO(logger_, "CheckPolicyPermissions");
+ const std::string& policy_app_id,
+ mobile_apis::HMILevel::eType hmi_level,
+ mobile_apis::FunctionID::eType function_id,
+ const RPCParams& rpc_params,
+ CommandParametersPermissions* params_permissions) {
+ LOG4CXX_AUTO_TRACE(logger_);
// TODO(AOleynik): Remove check of policy_enable, when this flag will be
// unused in config file
- if (!policy::PolicyHandler::instance()->PolicyEnabled()) {
+ if (!GetPolicyHandler().PolicyEnabled()) {
return mobile_apis::Result::SUCCESS;
}
@@ -2488,13 +2765,16 @@ mobile_apis::Result::eType ApplicationManagerImpl::CheckPolicyPermissions(
MessageHelper::StringifiedFunctionID(function_id);
const std::string stringified_hmi_level =
MessageHelper::StringifiedHMILevel(hmi_level);
- LOG4CXX_INFO(logger_, "Checking permissions for "
- << policy_app_id << " in " << stringified_hmi_level
- << " rpc " << stringified_functionID);
+ LOG4CXX_DEBUG(logger_,
+ "Checking permissions for " << policy_app_id << " in "
+ << stringified_hmi_level << " rpc "
+ << stringified_functionID);
policy::CheckPermissionResult result;
- policy::PolicyHandler::instance()->CheckPermissions(
- policy_app_id, stringified_hmi_level, stringified_functionID, rpc_params,
- result);
+ GetPolicyHandler().CheckPermissions(policy_app_id,
+ stringified_hmi_level,
+ stringified_functionID,
+ rpc_params,
+ result);
if (NULL != params_permissions) {
params_permissions->allowed_params = result.list_of_allowed_params;
@@ -2529,15 +2809,15 @@ mobile_apis::Result::eType ApplicationManagerImpl::CheckPolicyPermissions(
app->usage_report().RecordPolicyRejectedRpcCall();
switch (result.hmi_level_permitted) {
- case policy::kRpcDisallowed:
- return mobile_apis::Result::DISALLOWED;
- case policy::kRpcUserDisallowed:
- return mobile_apis::Result::USER_DISALLOWED;
- default:
- return mobile_apis::Result::INVALID_ENUM;
+ case policy::kRpcDisallowed:
+ return mobile_apis::Result::DISALLOWED;
+ case policy::kRpcUserDisallowed:
+ return mobile_apis::Result::USER_DISALLOWED;
+ default:
+ return mobile_apis::Result::INVALID_ENUM;
}
}
- LOG4CXX_INFO(logger_, "Request is allowed by policies. " + log_msg);
+ LOG4CXX_DEBUG(logger_, "Request is allowed by policies. " << log_msg);
return mobile_api::Result::SUCCESS;
}
@@ -2552,6 +2832,17 @@ bool ApplicationManagerImpl::IsLowVoltage() {
return is_low_voltage_;
}
+std::string ApplicationManagerImpl::GetHashedAppID(
+ uint32_t connection_key, const std::string& mobile_app_id) const {
+ uint32_t device_id = 0;
+ connection_handler().GetDataOnSessionKey(connection_key, 0, NULL, &device_id);
+ std::string device_name;
+ connection_handler().get_session_observer().GetDataOnDeviceID(
+ device_id, &device_name, NULL, NULL, NULL);
+
+ return mobile_app_id + device_name;
+}
+
bool ApplicationManagerImpl::HMILevelAllowsStreaming(
uint32_t app_id, protocol_handler::ServiceType service_type) const {
LOG4CXX_AUTO_TRACE(logger_);
@@ -2585,6 +2876,7 @@ bool ApplicationManagerImpl::CanAppStream(
} else {
LOG4CXX_WARN(logger_, "Unsupported service_type " << service_type);
}
+
return HMILevelAllowsStreaming(app_id, service_type) && is_allowed;
}
@@ -2601,18 +2893,22 @@ void ApplicationManagerImpl::ForbidStreaming(uint32_t app_id) {
}
if (navi_app_to_stop_.end() != std::find(navi_app_to_stop_.begin(),
- navi_app_to_stop_.end(), app_id) ||
+ navi_app_to_stop_.end(),
+ app_id) ||
navi_app_to_end_stream_.end() !=
std::find(navi_app_to_end_stream_.begin(),
- navi_app_to_end_stream_.end(), app_id)) {
+ navi_app_to_end_stream_.end(),
+ app_id)) {
return;
}
NaviServiceStatusMap::iterator it = navi_service_status_.find(app_id);
if (navi_service_status_.end() == it ||
(!it->second.first && !it->second.second)) {
- MessageHelper::SendOnAppInterfaceUnregisteredNotificationToMobile(
- app_id, PROTOCOL_VIOLATION);
+ ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ app_id, PROTOCOL_VIOLATION),
+ commands::Command::ORIGIN_SDL);
UnregisterApplication(app_id, ABORTED);
return;
}
@@ -2652,41 +2948,46 @@ void ApplicationManagerImpl::EndNaviServices(uint32_t app_id) {
NaviServiceStatusMap::iterator it = navi_service_status_.find(app_id);
if (navi_service_status_.end() == it) {
+ LOG4CXX_ERROR(logger_, "No info about navi servicies for app");
return;
}
if (connection_handler_) {
if (it->second.first) {
LOG4CXX_DEBUG(logger_, "Going to end video service");
- connection_handler_->SendEndService(app_id, ServiceType::kMobileNav);
- app->set_video_streaming_approved(false);
- app->set_video_streaming_allowed(false);
+ connection_handler().SendEndService(app_id, ServiceType::kMobileNav);
+ app->StopStreamingForce(ServiceType::kMobileNav);
}
if (it->second.second) {
LOG4CXX_DEBUG(logger_, "Going to end audio service");
- connection_handler_->SendEndService(app_id, ServiceType::kAudio);
- app->set_audio_streaming_approved(false);
- app->set_audio_streaming_allowed(false);
+ connection_handler().SendEndService(app_id, ServiceType::kAudio);
+ app->StopStreamingForce(ServiceType::kAudio);
}
+ DisallowStreaming(app_id);
+
navi_app_to_stop_.push_back(app_id);
- ApplicationManagerTimerPtr closeTimer(
- new TimerThread<ApplicationManagerImpl>(
- "CloseAppTimer", this, &ApplicationManagerImpl::CloseNaviApp));
- closeTimer->start(navi_close_app_timeout_);
+ TimerSPtr close_timer(utils::MakeShared<timer::Timer>(
+ "CloseNaviAppTimer",
+ new TimerTaskImpl<ApplicationManagerImpl>(
+ this, &ApplicationManagerImpl::CloseNaviApp)));
+ close_timer->Start(navi_close_app_timeout_, true);
sync_primitives::AutoLock lock(timer_pool_lock_);
- timer_pool_.push_back(closeTimer);
+ timer_pool_.push_back(close_timer);
}
}
void ApplicationManagerImpl::OnHMILevelChanged(
- uint32_t app_id, mobile_apis::HMILevel::eType from,
+ uint32_t app_id,
+ mobile_apis::HMILevel::eType from,
mobile_apis::HMILevel::eType to) {
+ LOG4CXX_AUTO_TRACE(logger_);
using namespace mobile_apis::HMILevel;
using namespace helpers;
if (from == to) {
+ LOG4CXX_TRACE(logger_, "HMILevel from = to");
return;
}
@@ -2697,39 +2998,72 @@ void ApplicationManagerImpl::OnHMILevelChanged(
}
if (to == HMI_FULL || to == HMI_LIMITED) {
+ LOG4CXX_TRACE(logger_, "HMILevel to FULL or LIMITED");
if (from == HMI_BACKGROUND) {
+ LOG4CXX_TRACE(logger_, "HMILevel from BACKGROUND");
AllowStreaming(app_id);
}
} else if (to == HMI_BACKGROUND) {
+ LOG4CXX_TRACE(logger_, "HMILevel to BACKGROUND");
if (from == HMI_FULL || from == HMI_LIMITED) {
+ LOG4CXX_TRACE(logger_, "HMILevel from FULL or LIMITED");
navi_app_to_end_stream_.push_back(app_id);
-
- ApplicationManagerTimerPtr endStreamTimer(
- new TimerThread<ApplicationManagerImpl>(
- "EndStreamTimer", this,
- &ApplicationManagerImpl::EndNaviStreaming));
- endStreamTimer->start(navi_end_stream_timeout_);
+ TimerSPtr end_stream_timer(utils::MakeShared<timer::Timer>(
+ "AppShouldFinishStreaming",
+ new TimerTaskImpl<ApplicationManagerImpl>(
+ this, &ApplicationManagerImpl::EndNaviStreaming)));
+ end_stream_timer->Start(navi_end_stream_timeout_, true);
sync_primitives::AutoLock lock(timer_pool_lock_);
- timer_pool_.push_back(endStreamTimer);
+ timer_pool_.push_back(end_stream_timer);
}
} else if (to == HMI_NONE) {
+ LOG4CXX_TRACE(logger_, "HMILevel to NONE");
if (from == HMI_FULL || from == HMI_LIMITED || from == HMI_BACKGROUND) {
EndNaviServices(app_id);
}
}
}
+void ApplicationManagerImpl::SendHMIStatusNotification(
+ const utils::SharedPtr<Application> app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(app);
+ smart_objects::SmartObjectSPtr notification =
+ utils::MakeShared<smart_objects::SmartObject>();
+ smart_objects::SmartObject& message = *notification;
+
+ message[strings::params][strings::function_id] =
+ static_cast<int32_t>(mobile_api::FunctionID::OnHMIStatusID);
+
+ message[strings::params][strings::message_type] =
+ static_cast<int32_t>(application_manager::MessageType::kNotification);
+
+ message[strings::params][strings::connection_key] =
+ static_cast<int32_t>(app->app_id());
+
+ message[strings::msg_params][strings::hmi_level] =
+ static_cast<int32_t>(app->hmi_level());
+
+ message[strings::msg_params][strings::audio_streaming_state] =
+ static_cast<int32_t>(app->audio_streaming_state());
+
+ message[strings::msg_params][strings::system_context] =
+ static_cast<int32_t>(app->system_context());
+
+ ManageMobileCommand(notification, commands::Command::ORIGIN_SDL);
+}
+
void ApplicationManagerImpl::ClearTimerPool() {
LOG4CXX_AUTO_TRACE(logger_);
- std::vector<ApplicationManagerTimerPtr> new_timer_pool;
+ std::vector<TimerSPtr> new_timer_pool;
sync_primitives::AutoLock lock(timer_pool_lock_);
new_timer_pool.push_back(timer_pool_[0]);
- for (size_t i = 1; i < timer_pool_.size(); i++) {
- if (timer_pool_[i]->isRunning()) {
+ for (size_t i = 1; i < timer_pool_.size(); ++i) {
+ if (timer_pool_[i]->is_running()) {
new_timer_pool.push_back(timer_pool_[i]);
}
}
@@ -2749,8 +3083,12 @@ void ApplicationManagerImpl::CloseNaviApp() {
NaviServiceStatusMap::iterator it = navi_service_status_.find(app_id);
if (navi_service_status_.end() != it) {
if (it->second.first || it->second.second) {
- MessageHelper::SendOnAppInterfaceUnregisteredNotificationToMobile(
- app_id, PROTOCOL_VIOLATION);
+ LOG4CXX_INFO(logger_,
+ "App haven't answered for EndService. Unregister it.");
+ ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ app_id, PROTOCOL_VIOLATION),
+ commands::Command::ORIGIN_SDL);
UnregisterApplication(app_id, ABORTED);
}
}
@@ -2812,6 +3150,17 @@ void ApplicationManagerImpl::AllowStreaming(uint32_t app_id) {
}
}
+bool ApplicationManagerImpl::IsApplicationForbidden(
+ uint32_t connection_key, const std::string& mobile_app_id) const {
+ const std::string name = GetHashedAppID(connection_key, mobile_app_id);
+ return forbidden_applications.find(name) != forbidden_applications.end();
+}
+
+policy::DeviceConsent ApplicationManagerImpl::GetUserConsentForDevice(
+ const std::string& device_id) const {
+ return policy_handler_.GetUserConsentForDevice(device_id);
+}
+
void ApplicationManagerImpl::OnWakeUp() {
LOG4CXX_AUTO_TRACE(logger_);
is_low_voltage_ = false;
@@ -2819,10 +3168,13 @@ void ApplicationManagerImpl::OnWakeUp() {
}
mobile_apis::Result::eType ApplicationManagerImpl::SaveBinary(
- const std::vector<uint8_t> &binary_data, const std::string &file_path,
- const std::string &file_name, const int64_t offset) {
- LOG4CXX_INFO(logger_, "SaveBinaryWithOffset binary_size = "
- << binary_data.size() << " offset = " << offset);
+ const std::vector<uint8_t>& binary_data,
+ const std::string& file_path,
+ const std::string& file_name,
+ const int64_t offset) {
+ LOG4CXX_DEBUG(logger_,
+ "SaveBinaryWithOffset binary_size = "
+ << binary_data.size() << " offset = " << offset);
if (binary_data.size() > file_system::GetAvailableDiskSpace(file_path)) {
LOG4CXX_ERROR(logger_, "Out of free disc space.");
@@ -2830,40 +3182,43 @@ mobile_apis::Result::eType ApplicationManagerImpl::SaveBinary(
}
const std::string full_file_path = file_path + "/" + file_name;
- int64_t file_size = file_system::FileSize(full_file_path);
- std::ofstream *file_stream;
+ const int64_t file_size = file_system::FileSize(full_file_path);
+ std::ofstream* file_stream;
if (offset != 0) {
if (file_size != offset) {
- LOG4CXX_INFO(logger_,
- "ApplicationManagerImpl::SaveBinaryWithOffset offset"
- << " does'n match existing file size");
+ LOG4CXX_DEBUG(logger_,
+ "ApplicationManagerImpl::SaveBinaryWithOffset offset"
+ << " does'n match existing file size");
return mobile_apis::Result::INVALID_DATA;
}
file_stream = file_system::Open(full_file_path, std::ios_base::app);
} else {
- LOG4CXX_INFO(
+ LOG4CXX_DEBUG(
logger_,
"ApplicationManagerImpl::SaveBinaryWithOffset offset is 0, rewrite");
// if offset == 0: rewrite file
file_stream = file_system::Open(full_file_path, std::ios_base::out);
}
- if (!file_system::Write(file_stream, binary_data.data(),
- binary_data.size())) {
+ if (!file_system::Write(
+ file_stream, binary_data.data(), binary_data.size())) {
file_system::Close(file_stream);
+ delete file_stream;
+ file_stream = NULL;
return mobile_apis::Result::GENERIC_ERROR;
}
file_system::Close(file_stream);
+ delete file_stream;
+ file_stream = NULL;
LOG4CXX_INFO(logger_, "Successfully write data to file");
return mobile_apis::Result::SUCCESS;
}
uint32_t ApplicationManagerImpl::GetAvailableSpaceForApp(
- const std::string &folder_name) {
- const uint32_t app_quota = profile::Profile::instance()->app_dir_quota();
- std::string app_storage_path =
- profile::Profile::instance()->app_storage_folder();
+ const std::string& folder_name) {
+ const uint32_t app_quota = settings_.app_dir_quota();
+ std::string app_storage_path = settings_.app_storage_folder();
app_storage_path += "/";
app_storage_path += folder_name;
@@ -2895,7 +3250,7 @@ bool ApplicationManagerImpl::IsHMICooperating() const {
void ApplicationManagerImpl::OnApplicationListUpdateTimer() {
LOG4CXX_DEBUG(logger_, "Application list update timer finished");
SendUpdateAppList();
- policy::PolicyHandler::instance()->OnAppsSearchCompleted();
+ GetPolicyHandler().OnAppsSearchCompleted();
}
void ApplicationManagerImpl::OnTimerSendTTSGlobalProperties() {
@@ -2919,7 +3274,8 @@ void ApplicationManagerImpl::OnTimerSendTTSGlobalProperties() {
for (uint32_t i = 0; i < app_list.size(); ++i) {
LOG4CXX_INFO(logger_,
"Send TTS GlobalProperties to HMI with default helpPrompt");
- MessageHelper::SendTTSGlobalProperties(application(app_list[i]), true);
+ MessageHelper::SendTTSGlobalProperties(
+ application(app_list[i]), true, *this);
RemoveAppFromTTSGlobalPropertiesList(app_list[i]);
}
}
@@ -2928,8 +3284,7 @@ void ApplicationManagerImpl::OnTimerSendTTSGlobalProperties() {
void ApplicationManagerImpl::AddAppToTTSGlobalPropertiesList(
const uint32_t app_id) {
LOG4CXX_AUTO_TRACE(logger_);
- uint16_t timeout =
- profile::Profile::instance()->tts_global_properties_timeout();
+ uint16_t timeout = get_settings().tts_global_properties_timeout();
TimevalStruct current_time = date_time::DateTime::getCurrentTime();
current_time.tv_sec += timeout;
// please avoid AutoLock usage to avoid deadlock
@@ -2942,7 +3297,8 @@ void ApplicationManagerImpl::AddAppToTTSGlobalPropertiesList(
if (1 == tts_global_properties_app_list_.size()) {
LOG4CXX_INFO(logger_, "Start tts_global_properties_timer_");
tts_global_properties_app_list_lock_.Release();
- tts_global_properties_timer_.start(1);
+ const uint32_t timeout_ms = 1000;
+ tts_global_properties_timer_.Start(timeout_ms, false);
return;
}
tts_global_properties_app_list_lock_.Release();
@@ -2958,18 +3314,18 @@ void ApplicationManagerImpl::RemoveAppFromTTSGlobalPropertiesList(
if (tts_global_properties_app_list_.end() != it) {
tts_global_properties_app_list_.erase(it);
if (tts_global_properties_app_list_.empty()) {
- LOG4CXX_INFO(logger_, "Stop tts_global_properties_timer_");
+ LOG4CXX_DEBUG(logger_, "Stop tts_global_properties_timer_");
// if container is empty need to stop timer
tts_global_properties_app_list_lock_.Release();
- tts_global_properties_timer_.suspend();
+ tts_global_properties_timer_.Stop();
return;
}
}
tts_global_properties_app_list_lock_.Release();
}
-mobile_apis::AppHMIType::eType
-ApplicationManagerImpl::StringToAppHMIType(std::string str) {
+mobile_apis::AppHMIType::eType ApplicationManagerImpl::StringToAppHMIType(
+ std::string str) {
LOG4CXX_AUTO_TRACE(logger_);
if ("DEFAULT" == str) {
return mobile_apis::AppHMIType::DEFAULT;
@@ -2997,8 +3353,8 @@ ApplicationManagerImpl::StringToAppHMIType(std::string str) {
}
bool ApplicationManagerImpl::CompareAppHMIType(
- const smart_objects::SmartObject &from_policy,
- const smart_objects::SmartObject &from_application) {
+ const smart_objects::SmartObject& from_policy,
+ const smart_objects::SmartObject& from_application) {
LOG4CXX_AUTO_TRACE(logger_);
bool equal = false;
uint32_t lenght_policy_app_types = from_policy.length();
@@ -3020,19 +3376,20 @@ bool ApplicationManagerImpl::CompareAppHMIType(
}
void ApplicationManagerImpl::OnUpdateHMIAppType(
- std::map<std::string, std::vector<std::string>> app_hmi_types) {
+ std::map<std::string, std::vector<std::string> > app_hmi_types) {
LOG4CXX_AUTO_TRACE(logger_);
- std::map<std::string, std::vector<std::string>>::iterator
+ std::map<std::string, std::vector<std::string> >::iterator
it_app_hmi_types_from_policy;
std::vector<std::string> hmi_types_from_policy;
smart_objects::SmartObject transform_app_hmi_types(
smart_objects::SmartType_Array);
bool flag_diffirence_app_hmi_type = false;
- ApplicationListAccessor accessor;
- for (ApplictionSetIt it = accessor.begin(); it != accessor.end(); ++it) {
-
- it_app_hmi_types_from_policy = app_hmi_types.find(((*it)->mobile_app_id()));
+ DataAccessor<ApplicationSet> accessor(applications());
+ for (ApplicationSetIt it = accessor.GetData().begin();
+ it != accessor.GetData().end();
+ ++it) {
+ it_app_hmi_types_from_policy = app_hmi_types.find(((*it)->policy_app_id()));
if (it_app_hmi_types_from_policy != app_hmi_types.end() &&
((it_app_hmi_types_from_policy->second).size())) {
@@ -3050,7 +3407,7 @@ void ApplicationManagerImpl::OnUpdateHMIAppType(
}
ApplicationConstSharedPtr app = *it;
- const smart_objects::SmartObject *save_application_hmi_type =
+ const smart_objects::SmartObject* save_application_hmi_type =
app->app_types();
if (save_application_hmi_type == NULL ||
@@ -3066,14 +3423,12 @@ void ApplicationManagerImpl::OnUpdateHMIAppType(
(*it)->set_app_types(transform_app_hmi_types);
(*it)->ChangeSupportingAppHMIType();
if ((*it)->hmi_level() == mobile_api::HMILevel::HMI_BACKGROUND) {
-
- MessageHelper::SendUIChangeRegistrationRequestToHMI(*it);
+ MessageHelper::SendUIChangeRegistrationRequestToHMI(*it, *this);
} else if (((*it)->hmi_level() == mobile_api::HMILevel::HMI_FULL) ||
((*it)->hmi_level() == mobile_api::HMILevel::HMI_LIMITED)) {
-
- MessageHelper::SendUIChangeRegistrationRequestToHMI(*it);
- ApplicationManagerImpl::instance()->SetState<true>(
- (*it)->app_id(), mobile_apis::HMILevel::HMI_BACKGROUND);
+ MessageHelper::SendUIChangeRegistrationRequestToHMI(*it, *this);
+ state_controller().SetRegularState(
+ *it, mobile_apis::HMILevel::HMI_BACKGROUND, true);
}
}
}
@@ -3082,25 +3437,28 @@ void ApplicationManagerImpl::OnUpdateHMIAppType(
ProtocolVersion ApplicationManagerImpl::SupportedSDLVersion() const {
LOG4CXX_AUTO_TRACE(logger_);
- bool heart_beat_support = profile::Profile::instance()->heart_beat_timeout();
- bool sdl4_support = profile::Profile::instance()->enable_protocol_4();
+ bool heart_beat_support = get_settings().heart_beat_timeout();
+ bool sdl4_support = protocol_handler_->get_settings().enable_protocol_4();
if (sdl4_support) {
- LOG4CXX_DEBUG(logger_, "SDL Supported protocol version "
- << ProtocolVersion::kV4);
+ LOG4CXX_DEBUG(logger_,
+ "SDL Supported protocol version " << ProtocolVersion::kV4);
return ProtocolVersion::kV4;
}
if (heart_beat_support) {
- LOG4CXX_DEBUG(logger_, "SDL Supported protocol version "
- << ProtocolVersion::kV3);
+ LOG4CXX_DEBUG(logger_,
+ "SDL Supported protocol version " << ProtocolVersion::kV3);
return ProtocolVersion::kV3;
}
-
- LOG4CXX_DEBUG(logger_, "SDL Supported protocol version "
- << ProtocolVersion::kV2);
+ LOG4CXX_DEBUG(logger_,
+ "SDL Supported protocol version " << ProtocolVersion::kV2);
return ProtocolVersion::kV2;
}
+event_engine::EventDispatcher& ApplicationManagerImpl::event_dispatcher() {
+ return event_dispatcher_;
+}
+
const std::string ApplicationManagerImpl::DirectoryTypeToString(
ApplicationManagerImpl::DirectoryType type) const {
DirectoryTypeMap::const_iterator it = dir_type_to_string_map_.find(type);
@@ -3111,24 +3469,25 @@ const std::string ApplicationManagerImpl::DirectoryTypeToString(
}
bool ApplicationManagerImpl::InitDirectory(
- const std::string &path, ApplicationManagerImpl::DirectoryType type) const {
+ const std::string& path, ApplicationManagerImpl::DirectoryType type) const {
const std::string directory_type = DirectoryTypeToString(type);
if (!file_system::DirectoryExists(path)) {
LOG4CXX_WARN(logger_, directory_type << " directory doesn't exist.");
// if storage directory doesn't exist try to create it
if (!file_system::CreateDirectoryRecursively(path)) {
- LOG4CXX_ERROR(logger_, "Unable to create " << directory_type
- << " directory " << path);
+ LOG4CXX_ERROR(logger_,
+ "Unable to create " << directory_type << " directory "
+ << path);
return false;
}
- LOG4CXX_DEBUG(logger_, directory_type
- << " directory has been created: " << path);
+ LOG4CXX_DEBUG(logger_,
+ directory_type << " directory has been created: " << path);
}
return true;
}
-bool ApplicationManagerImpl::IsReadWriteAllowed(const std::string &path,
+bool ApplicationManagerImpl::IsReadWriteAllowed(const std::string& path,
DirectoryType type) const {
const std::string directory_type = DirectoryTypeToString(type);
if (!(file_system::IsWritingAllowed(path) &&
@@ -3139,8 +3498,8 @@ bool ApplicationManagerImpl::IsReadWriteAllowed(const std::string &path,
return false;
}
- LOG4CXX_DEBUG(logger_, directory_type
- << " directory has read/write permissions.");
+ LOG4CXX_DEBUG(logger_,
+ directory_type << " directory has read/write permissions.");
return true;
}
@@ -3151,6 +3510,41 @@ void ApplicationManagerImpl::ClearTTSGlobalPropertiesList() {
tts_global_properties_app_list_.clear();
}
-ApplicationManagerImpl::ApplicationListAccessor::~ApplicationListAccessor() {}
+bool ApplicationManagerImpl::IsAppSubscribedForWayPoints(
+ const uint32_t app_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(subscribed_way_points_apps_lock_);
+ if (subscribed_way_points_apps_list_.find(app_id) ==
+ subscribed_way_points_apps_list_.end()) {
+ return false;
+ }
+ return true;
+}
+
+void ApplicationManagerImpl::SubscribeAppForWayPoints(const uint32_t app_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(subscribed_way_points_apps_lock_);
+ subscribed_way_points_apps_list_.insert(app_id);
+}
+
+void ApplicationManagerImpl::UnsubscribeAppFromWayPoints(
+ const uint32_t app_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(subscribed_way_points_apps_lock_);
+ subscribed_way_points_apps_list_.erase(app_id);
+}
+
+bool ApplicationManagerImpl::IsAnyAppSubscribedForWayPoints() const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(subscribed_way_points_apps_lock_);
+ return !subscribed_way_points_apps_list_.empty();
+}
+
+const std::set<int32_t> ApplicationManagerImpl::GetAppsSubscribedForWayPoints()
+ const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(subscribed_way_points_apps_lock_);
+ return subscribed_way_points_apps_list_;
+}
-} // namespace application_manager
+} // namespace application_manager
diff --git a/src/components/application_manager/src/application_state.cc b/src/components/application_manager/src/application_state.cc
new file mode 100644
index 0000000000..101a565a8e
--- /dev/null
+++ b/src/components/application_manager/src/application_state.cc
@@ -0,0 +1,249 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/application_state.h"
+#include <algorithm>
+#include "utils/logger.h"
+#include "utils/macro.h"
+
+namespace {
+
+struct StateIDComparator {
+ application_manager::HmiState::StateID state_id_;
+ StateIDComparator(application_manager::HmiState::StateID state_id)
+ : state_id_(state_id) {}
+ bool operator()(const application_manager::HmiStatePtr cur) const {
+ return cur->state_id() == state_id_;
+ }
+};
+}
+
+namespace application_manager {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationManager")
+
+ApplicationState::ApplicationState() {}
+
+void ApplicationState::InitState(HmiStatePtr state) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(state);
+ sync_primitives::AutoLock auto_lock(hmi_states_lock_);
+ hmi_states_.clear();
+ hmi_states_.push_back(state);
+}
+
+void ApplicationState::AddState(HmiStatePtr state) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(state);
+ switch (state->state_id()) {
+ case HmiState::StateID::STATE_ID_REGULAR:
+ SetRegularState(state);
+ return;
+ case HmiState::StateID::STATE_ID_POSTPONED:
+ SetPostponedState(state);
+ return;
+ case HmiState::StateID::STATE_ID_CURRENT:
+ LOG4CXX_ERROR(logger_, "State of type '" << state << "' can't be added.");
+ return;
+ default:
+ AddHMIState(state);
+ break;
+ }
+
+ return;
+}
+
+void ApplicationState::RemoveState(HmiState::StateID state) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(state);
+ switch (state) {
+ case HmiState::StateID::STATE_ID_CURRENT:
+ case HmiState::StateID::STATE_ID_REGULAR:
+ LOG4CXX_ERROR(logger_,
+ "State of type '" << state << "'can't be removed.");
+ break;
+ case HmiState::StateID::STATE_ID_POSTPONED:
+ RemovePostponedState();
+ break;
+ default:
+ RemoveHMIState(state);
+ break;
+ }
+}
+
+HmiStatePtr ApplicationState::GetState(HmiState::StateID state_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ switch (state_id) {
+ case HmiState::StateID::STATE_ID_REGULAR:
+ LOG4CXX_DEBUG(logger_, "Getting regular state.");
+ return RegularHmiState();
+ case HmiState::StateID::STATE_ID_POSTPONED:
+ LOG4CXX_DEBUG(logger_, "Getting postponed state.");
+ return PostponedHmiState();
+ default:
+ LOG4CXX_DEBUG(logger_, "Getting current state.");
+ return CurrentHmiState();
+ }
+}
+
+void ApplicationState::AddHMIState(HmiStatePtr state) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(state);
+ sync_primitives::AutoLock auto_lock(hmi_states_lock_);
+ HmiStates::iterator it = std::find_if(hmi_states_.begin(),
+ hmi_states_.end(),
+ StateIDComparator(state->state_id()));
+ if (hmi_states_.end() != it) {
+ LOG4CXX_WARN(
+ logger_,
+ "Hmi state with ID "
+ << state->state_id()
+ << "has been already applied to this application. Ignoring");
+ return;
+ }
+
+ hmi_states_.push_back(state);
+}
+
+void ApplicationState::RemoveHMIState(HmiState::StateID state_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock auto_lock(hmi_states_lock_);
+ HmiStates::iterator it = std::find_if(
+ hmi_states_.begin(), hmi_states_.end(), StateIDComparator(state_id));
+ if (it == hmi_states_.end()) {
+ LOG4CXX_ERROR(logger_, "Unsuccesful remove HmiState: " << state_id);
+ return;
+ }
+
+ // unable to remove regular state
+ DCHECK_OR_RETURN_VOID(it != hmi_states_.begin());
+ HmiStates::iterator next = it;
+ HmiStates::iterator prev = it;
+ next++;
+ prev--;
+ if (next != hmi_states_.end()) {
+ HmiStatePtr next_state = *next;
+ HmiStatePtr prev_state = *prev;
+ next_state->set_parent(prev_state);
+ }
+ hmi_states_.erase(it);
+}
+
+void ApplicationState::RemovePostponedState() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock auto_lock(hmi_states_lock_);
+ DCHECK_OR_RETURN_VOID(!hmi_states_.empty());
+
+ StateIDComparator finder(HmiState::StateID::STATE_ID_POSTPONED);
+
+ HmiStates::iterator postponed_state =
+ std::find_if(hmi_states_.begin(), hmi_states_.end(), finder);
+
+ if (hmi_states_.end() == postponed_state) {
+ LOG4CXX_ERROR(logger_, "No postponed state is set for app.");
+ return;
+ }
+ hmi_states_.erase(postponed_state);
+}
+
+void ApplicationState::SetRegularState(HmiStatePtr state) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(state);
+ DCHECK_OR_RETURN_VOID(state->state_id() ==
+ HmiState::StateID::STATE_ID_REGULAR);
+ sync_primitives::AutoLock auto_lock(hmi_states_lock_);
+ DCHECK_OR_RETURN_VOID(!hmi_states_.empty());
+
+ HmiStatePtr front_state = hmi_states_.front();
+ HmiState::StateID front_state_id = front_state->state_id();
+ if (HmiState::StateID::STATE_ID_POSTPONED == front_state_id) {
+ // Drop postponed state
+ hmi_states_.erase(hmi_states_.begin());
+ }
+
+ // Drop regular state
+ hmi_states_.erase(hmi_states_.begin());
+
+ if (!hmi_states_.empty()) {
+ HmiStatePtr front_state = hmi_states_.front();
+ front_state->set_parent(state);
+ }
+ hmi_states_.insert(hmi_states_.begin(), state);
+ if (HmiState::StateID::STATE_ID_POSTPONED == front_state_id) {
+ hmi_states_.insert(hmi_states_.begin(), front_state);
+ }
+}
+
+void ApplicationState::SetPostponedState(HmiStatePtr state) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(state);
+ DCHECK_OR_RETURN_VOID(state->state_id() ==
+ HmiState::StateID::STATE_ID_POSTPONED);
+ sync_primitives::AutoLock auto_lock(hmi_states_lock_);
+ DCHECK_OR_RETURN_VOID(!hmi_states_.empty());
+ HmiStatePtr front_state = hmi_states_.front();
+ if (front_state->state_id() == HmiState::StateID::STATE_ID_POSTPONED) {
+ hmi_states_.erase(hmi_states_.begin());
+ }
+ hmi_states_.insert(hmi_states_.begin(), state);
+}
+
+HmiStatePtr ApplicationState::CurrentHmiState() const {
+ sync_primitives::AutoLock auto_lock(hmi_states_lock_);
+ DCHECK_OR_RETURN(!hmi_states_.empty(), HmiStatePtr());
+ HmiStatePtr back_state = hmi_states_.back();
+ DCHECK_OR_RETURN(
+ back_state->state_id() != HmiState::StateID::STATE_ID_POSTPONED,
+ HmiStatePtr());
+ return back_state;
+}
+
+HmiStatePtr ApplicationState::RegularHmiState() const {
+ sync_primitives::AutoLock auto_lock(hmi_states_lock_);
+ DCHECK_OR_RETURN(!hmi_states_.empty(), HmiStatePtr());
+ HmiStates::const_iterator front_itr = hmi_states_.begin();
+ if ((*front_itr)->state_id() == HmiState::StateID::STATE_ID_POSTPONED) {
+ ++front_itr;
+ }
+ return *front_itr;
+}
+
+HmiStatePtr ApplicationState::PostponedHmiState() const {
+ sync_primitives::AutoLock auto_lock(hmi_states_lock_);
+ DCHECK_OR_RETURN(!hmi_states_.empty(), HmiStatePtr());
+ HmiStatePtr front_state = hmi_states_.front();
+ return front_state->state_id() == HmiState::StateID::STATE_ID_POSTPONED
+ ? front_state
+ : HmiStatePtr();
+}
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/command_impl.cc b/src/components/application_manager/src/commands/command_impl.cc
index 5fd3449165..0a3e65a790 100644
--- a/src/components/application_manager/src/commands/command_impl.cc
+++ b/src/components/application_manager/src/commands/command_impl.cc
@@ -31,7 +31,8 @@
*/
#include "application_manager/commands/command_impl.h"
-#include "config_profile/profile.h"
+#include "application_manager/application_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
@@ -42,17 +43,18 @@ const int32_t CommandImpl::hmi_protocol_type_ = 1;
const int32_t CommandImpl::mobile_protocol_type_ = 0;
const int32_t CommandImpl::protocol_version_ = 3;
-CommandImpl::CommandImpl(const MessageSharedPtr& message)
- : message_(message),
- default_timeout_(profile::Profile::instance()->default_timeout()),
- allowed_to_terminate_(true) {
-}
+CommandImpl::CommandImpl(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : message_(message)
+ , default_timeout_(application_manager.get_settings().default_timeout())
+ , allowed_to_terminate_(true)
+ , application_manager_(application_manager) {}
CommandImpl::~CommandImpl() {
CleanUp();
}
-bool CommandImpl::CheckPermissions(){
+bool CommandImpl::CheckPermissions() {
return true;
}
@@ -64,8 +66,7 @@ bool CommandImpl::CleanUp() {
return true;
}
-void CommandImpl::Run() {
-}
+void CommandImpl::Run() {}
uint32_t CommandImpl::default_timeout() const {
return default_timeout_;
@@ -83,8 +84,87 @@ uint32_t CommandImpl::connection_key() const {
return (*message_)[strings::params][strings::connection_key].asUInt();
}
-void CommandImpl::onTimeOut() {
+void CommandImpl::onTimeOut() {}
+
+bool CommandImpl::AllowedToTerminate() {
+ return allowed_to_terminate_;
+}
+
+void CommandImpl::SetAllowedToTerminate(const bool allowed) {
+ allowed_to_terminate_ = allowed;
+}
+
+void CommandImpl::ReplaceMobileByHMIAppId(
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& message) {
+ if (message.keyExists(strings::app_id)) {
+ ApplicationSharedPtr application =
+ application_manager_.application(message[strings::app_id].asUInt());
+ if (application.valid()) {
+ LOG4CXX_DEBUG(logger_,
+ "ReplaceMobileByHMIAppId from "
+ << message[strings::app_id].asInt() << " to "
+ << application->hmi_app_id());
+ message[strings::app_id] = application->hmi_app_id();
+ }
+ } else {
+ switch (message.getType()) {
+ case smart_objects::SmartType::SmartType_Array: {
+ smart_objects::SmartArray* message_array = message.asArray();
+ smart_objects::SmartArray::iterator it = message_array->begin();
+ for (; it != message_array->end(); ++it) {
+ ReplaceMobileByHMIAppId(*it);
+ }
+ break;
+ }
+ case smart_objects::SmartType::SmartType_Map: {
+ std::set<std::string> keys = message.enumerate();
+ std::set<std::string>::const_iterator key = keys.begin();
+ for (; key != keys.end(); ++key) {
+ std::string k = *key;
+ ReplaceMobileByHMIAppId(message[*key]);
+ }
+ break;
+ }
+ default: { break; }
+ }
+ }
+}
+void CommandImpl::ReplaceHMIByMobileAppId(
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& message) {
+ if (message.keyExists(strings::app_id)) {
+ ApplicationSharedPtr application =
+ application_manager_.application_by_hmi_app(
+ message[strings::app_id].asUInt());
+
+ if (application.valid()) {
+ LOG4CXX_DEBUG(logger_,
+ "ReplaceHMIByMobileAppId from "
+ << message[strings::app_id].asInt() << " to "
+ << application->app_id());
+ message[strings::app_id] = application->app_id();
+ }
+ } else {
+ switch (message.getType()) {
+ case smart_objects::SmartType::SmartType_Array: {
+ smart_objects::SmartArray* message_array = message.asArray();
+ smart_objects::SmartArray::iterator it = message_array->begin();
+ for (; it != message_array->end(); ++it) {
+ ReplaceHMIByMobileAppId(*it);
+ }
+ break;
+ }
+ case smart_objects::SmartType::SmartType_Map: {
+ std::set<std::string> keys = message.enumerate();
+ std::set<std::string>::const_iterator key = keys.begin();
+ for (; key != keys.end(); ++key) {
+ ReplaceHMIByMobileAppId(message[*key]);
+ }
+ break;
+ }
+ default: { break; }
+ }
+ }
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/command_notification_from_mobile_impl.cc b/src/components/application_manager/src/commands/command_notification_from_mobile_impl.cc
index ee7afaddf9..5b44abeec9 100644
--- a/src/components/application_manager/src/commands/command_notification_from_mobile_impl.cc
+++ b/src/components/application_manager/src/commands/command_notification_from_mobile_impl.cc
@@ -31,7 +31,7 @@
*/
#include "application_manager/commands/command_notification_from_mobile_impl.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
#include "application_manager/message_helper.h"
namespace application_manager {
@@ -39,12 +39,10 @@ namespace application_manager {
namespace commands {
CommandNotificationFromMobileImpl::CommandNotificationFromMobileImpl(
- const MessageSharedPtr& message)
- : CommandImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandImpl(message, application_manager) {}
-CommandNotificationFromMobileImpl::~CommandNotificationFromMobileImpl() {
-}
+CommandNotificationFromMobileImpl::~CommandNotificationFromMobileImpl() {}
bool CommandNotificationFromMobileImpl::Init() {
return true;
@@ -54,8 +52,7 @@ bool CommandNotificationFromMobileImpl::CleanUp() {
return true;
}
-void CommandNotificationFromMobileImpl::Run() {
-}
+void CommandNotificationFromMobileImpl::Run() {}
void CommandNotificationFromMobileImpl::SendNotification() {
(*message_)[strings::params][strings::protocol_type] = mobile_protocol_type_;
@@ -66,7 +63,7 @@ void CommandNotificationFromMobileImpl::SendNotification() {
LOG4CXX_INFO(logger_, "SendNotification");
MessageHelper::PrintSmartObject(*message_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/command_notification_impl.cc b/src/components/application_manager/src/commands/command_notification_impl.cc
index c99f2d9086..b6b0e7d500 100644
--- a/src/components/application_manager/src/commands/command_notification_impl.cc
+++ b/src/components/application_manager/src/commands/command_notification_impl.cc
@@ -31,7 +31,7 @@
*/
#include "application_manager/commands/command_notification_impl.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
#include "application_manager/message_helper.h"
namespace application_manager {
@@ -39,12 +39,10 @@ namespace application_manager {
namespace commands {
CommandNotificationImpl::CommandNotificationImpl(
- const MessageSharedPtr& message)
- : CommandImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandImpl(message, application_manager) {}
-CommandNotificationImpl::~CommandNotificationImpl() {
-}
+CommandNotificationImpl::~CommandNotificationImpl() {}
bool CommandNotificationImpl::Init() {
return true;
@@ -54,8 +52,7 @@ bool CommandNotificationImpl::CleanUp() {
return true;
}
-void CommandNotificationImpl::Run() {
-}
+void CommandNotificationImpl::Run() {}
void CommandNotificationImpl::SendNotification() {
(*message_)[strings::params][strings::protocol_type] = mobile_protocol_type_;
@@ -66,7 +63,7 @@ void CommandNotificationImpl::SendNotification() {
LOG4CXX_INFO(logger_, "SendNotification");
MessageHelper::PrintSmartObject(*message_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/command_request_impl.cc b/src/components/application_manager/src/commands/command_request_impl.cc
index 544b12a290..b3b463328f 100644
--- a/src/components/application_manager/src/commands/command_request_impl.cc
+++ b/src/components/application_manager/src/commands/command_request_impl.cc
@@ -33,7 +33,7 @@
#include <algorithm>
#include <string>
#include "application_manager/commands/command_request_impl.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
#include "application_manager/message_helper.h"
#include "smart_objects/smart_object.h"
@@ -44,9 +44,7 @@ namespace commands {
struct DisallowedParamsInserter {
DisallowedParamsInserter(smart_objects::SmartObject& response,
mobile_apis::VehicleDataResultCode::eType code)
- : response_(response),
- code_(code) {
- }
+ : response_(response), code_(code) {}
bool operator()(const std::string& param) {
const VehicleData& vehicle_data =
@@ -62,18 +60,19 @@ struct DisallowedParamsInserter {
}
return false;
}
-private:
+
+ private:
smart_objects::SmartObject& response_;
mobile_apis::VehicleDataResultCode::eType code_;
};
-CommandRequestImpl::CommandRequestImpl(const MessageSharedPtr& message)
- : CommandImpl(message),
- current_state_(kAwaitingHMIResponse) {
-}
+CommandRequestImpl::CommandRequestImpl(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandImpl(message, application_manager)
+ , EventObserver(application_manager.event_dispatcher())
+ , current_state_(kAwaitingHMIResponse) {}
-CommandRequestImpl::~CommandRequestImpl() {
-}
+CommandRequestImpl::~CommandRequestImpl() {}
bool CommandRequestImpl::Init() {
return true;
@@ -87,8 +86,7 @@ bool CommandRequestImpl::CleanUp() {
return true;
}
-void CommandRequestImpl::Run() {
-}
+void CommandRequestImpl::Run() {}
void CommandRequestImpl::onTimeOut() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -107,19 +105,21 @@ void CommandRequestImpl::onTimeOut() {
}
smart_objects::SmartObjectSPtr response =
- MessageHelper::CreateNegativeResponse(connection_key(), function_id(),
- correlation_id(), mobile_api::Result::GENERIC_ERROR);
+ MessageHelper::CreateNegativeResponse(connection_key(),
+ function_id(),
+ correlation_id(),
+ mobile_api::Result::GENERIC_ERROR);
- ApplicationManagerImpl::instance()->ManageMobileCommand(response);
+ application_manager_.ManageMobileCommand(response, ORIGIN_SDL);
}
-void CommandRequestImpl::on_event(const event_engine::Event& event) {
-}
+void CommandRequestImpl::on_event(const event_engine::Event& event) {}
void CommandRequestImpl::SendResponse(
- const bool success, const mobile_apis::Result::eType& result_code,
- const char* info, const smart_objects::SmartObject* response_params) {
-
+ const bool success,
+ const mobile_apis::Result::eType& result_code,
+ const char* info,
+ const smart_objects::SmartObject* response_params) {
{
sync_primitives::AutoLock auto_lock(state_lock_);
if (kTimedOut == current_state_) {
@@ -154,12 +154,13 @@ void CommandRequestImpl::SendResponse(
response[strings::msg_params][strings::info] = std::string(info);
}
- // Add disallowed parameters and info from request back to response with appropriate
+ // Add disallowed parameters and info from request back to response with
+ // appropriate
// reasons (VehicleData result codes)
if (result_code != mobile_apis::Result::APPLICATION_NOT_REGISTERED) {
const mobile_apis::FunctionID::eType& id =
static_cast<mobile_apis::FunctionID::eType>(function_id());
- if ((id == mobile_apis::FunctionID::SubscribeVehicleDataID) ||
+ if ((id == mobile_apis::FunctionID::SubscribeVehicleDataID) ||
(id == mobile_apis::FunctionID::UnsubscribeVehicleDataID)) {
AddDisallowedParameters(response);
AddDisallowedParametersToInfo(response);
@@ -171,10 +172,11 @@ void CommandRequestImpl::SendResponse(
response[strings::msg_params][strings::success] = success;
response[strings::msg_params][strings::result_code] = result_code;
- ApplicationManagerImpl::instance()->ManageMobileCommand(result);
+ application_manager_.ManageMobileCommand(result, ORIGIN_SDL);
}
-bool CommandRequestImpl::CheckSyntax(std::string str, bool allow_empty_line) {
+bool CommandRequestImpl::CheckSyntax(const std::string& str,
+ bool allow_empty_line) {
if (std::string::npos != str.find_first_of("\t\n")) {
LOG4CXX_ERROR(logger_, "CheckSyntax failed! :" << str);
return false;
@@ -194,14 +196,16 @@ bool CommandRequestImpl::CheckSyntax(std::string str, bool allow_empty_line) {
uint32_t CommandRequestImpl::SendHMIRequest(
const hmi_apis::FunctionID::eType& function_id,
- const smart_objects::SmartObject* msg_params, bool use_events) {
-
+ const smart_objects::SmartObject* msg_params,
+ bool use_events) {
smart_objects::SmartObjectSPtr result = new smart_objects::SmartObject;
const uint32_t hmi_correlation_id =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
+ application_manager_.GetNextHMICorrelationID();
if (use_events) {
- LOG4CXX_DEBUG(logger_, "subscribe_on_event " << function_id << " " << hmi_correlation_id);
+ LOG4CXX_DEBUG(logger_,
+ "subscribe_on_event " << function_id << " "
+ << hmi_correlation_id);
subscribe_on_event(function_id, hmi_correlation_id);
}
@@ -218,7 +222,7 @@ uint32_t CommandRequestImpl::SendHMIRequest(
request[strings::msg_params] = *msg_params;
}
- if (!ApplicationManagerImpl::instance()->ManageHMICommand(result)) {
+ if (!application_manager_.ManageHMICommand(result)) {
LOG4CXX_ERROR(logger_, "Unable to send request");
SendResponse(false, mobile_apis::Result::OUT_OF_MEMORY);
}
@@ -228,7 +232,6 @@ uint32_t CommandRequestImpl::SendHMIRequest(
void CommandRequestImpl::CreateHMINotification(
const hmi_apis::FunctionID::eType& function_id,
const NsSmart::SmartObject& msg_params) const {
-
smart_objects::SmartObjectSPtr result = new smart_objects::SmartObject;
if (!result) {
LOG4CXX_ERROR(logger_, "Memory allocation failed.");
@@ -245,14 +248,13 @@ void CommandRequestImpl::CreateHMINotification(
notify[strings::params][strings::function_id] = function_id;
notify[strings::msg_params] = msg_params;
- if (!ApplicationManagerImpl::instance()->ManageHMICommand(result)) {
+ if (!application_manager_.ManageHMICommand(result)) {
LOG4CXX_ERROR(logger_, "Unable to send HMI notification");
}
}
mobile_apis::Result::eType CommandRequestImpl::GetMobileResultCode(
const hmi_apis::Common_Result::eType& hmi_code) const {
-
mobile_apis::Result::eType mobile_result = mobile_apis::Result::GENERIC_ERROR;
switch (hmi_code) {
case hmi_apis::Common_Result::SUCCESS: {
@@ -351,6 +353,10 @@ mobile_apis::Result::eType CommandRequestImpl::GetMobileResultCode(
mobile_result = mobile_apis::Result::USER_DISALLOWED;
break;
}
+ case hmi_apis::Common_Result::SAVED: {
+ mobile_result = mobile_apis::Result::SAVED;
+ break;
+ }
default: {
LOG4CXX_ERROR(logger_, "Unknown HMI result code " << hmi_code);
break;
@@ -361,7 +367,7 @@ mobile_apis::Result::eType CommandRequestImpl::GetMobileResultCode(
}
bool CommandRequestImpl::CheckAllowedParameters() {
- LOG4CXX_INFO(logger_, "CheckAllowedParameters");
+ LOG4CXX_AUTO_TRACE(logger_);
// RegisterAppInterface should always be allowed
if (mobile_apis::FunctionID::RegisterAppInterfaceID ==
@@ -369,97 +375,96 @@ bool CommandRequestImpl::CheckAllowedParameters() {
return true;
}
- ApplicationManagerImpl::ApplicationListAccessor accessor;
- ApplicationManagerImpl::ApplictionSetConstIt it_app_list =
- accessor.begin();
- ApplicationManagerImpl::ApplictionSetConstIt it_app_list_end =
- accessor.end();
+ const ApplicationSet& accessor =
+ application_manager_.applications().GetData();
+ ApplicationSetConstIt it_app_list = accessor.begin();
+ ApplicationSetConstIt it_app_list_end = accessor.end();
for (; it_app_list != it_app_list_end; ++it_app_list) {
if (connection_key() == (*it_app_list).get()->app_id()) {
-
RPCParams params;
- const smart_objects::SmartObject& s_map = (*message_)[strings::msg_params];
+ const smart_objects::SmartObject& s_map =
+ (*message_)[strings::msg_params];
if (smart_objects::SmartType_Map == s_map.getType()) {
smart_objects::SmartMap::iterator iter = s_map.map_begin();
smart_objects::SmartMap::iterator iter_end = s_map.map_end();
for (; iter != iter_end; ++iter) {
if (true == iter->second.asBool()) {
- LOG4CXX_INFO(logger_, "Request's param: " << iter->first);
+ LOG4CXX_DEBUG(logger_, "Request's param: " << iter->first);
params.push_back(iter->first);
}
}
}
- CommandParametersPermissions params_permissions;
mobile_apis::Result::eType check_result =
- application_manager::ApplicationManagerImpl::instance()->
- CheckPolicyPermissions(
- (*it_app_list).get()->mobile_app_id(),
- (*it_app_list).get()->hmi_level(),
- static_cast<mobile_api::FunctionID::eType>(function_id()),
- params,
- &params_permissions);
+ application_manager_.CheckPolicyPermissions(
+ (*it_app_list).get()->policy_app_id(),
+ (*it_app_list).get()->hmi_level(),
+ static_cast<mobile_api::FunctionID::eType>(function_id()),
+ params,
+ &parameters_permissions_);
// Check, if RPC is allowed by policy
if (mobile_apis::Result::SUCCESS != check_result) {
smart_objects::SmartObjectSPtr response =
- MessageHelper::CreateBlockedByPoliciesResponse(
- static_cast<mobile_api::FunctionID::eType>(function_id()),
- check_result, correlation_id(), (*it_app_list)->app_id());
+ MessageHelper::CreateBlockedByPoliciesResponse(
+ static_cast<mobile_api::FunctionID::eType>(function_id()),
+ check_result,
+ correlation_id(),
+ (*it_app_list)->app_id());
- ApplicationManagerImpl::instance()->SendMessageToMobile(response);
+ application_manager_.SendMessageToMobile(response);
return false;
}
// If no parameters specified in policy table, no restriction will be
// applied for parameters
- if (params_permissions.allowed_params.empty() &&
- params_permissions.disallowed_params.empty() &&
- params_permissions.undefined_params.empty()) {
+ if (parameters_permissions_.allowed_params.empty() &&
+ parameters_permissions_.disallowed_params.empty() &&
+ parameters_permissions_.undefined_params.empty()) {
return true;
}
- RemoveDisallowedParameters(params_permissions);
+ RemoveDisallowedParameters();
}
}
return true;
}
-void CommandRequestImpl::RemoveDisallowedParameters(
- const CommandParametersPermissions& params_permissions) {
- LOG4CXX_INFO(logger_, "RemoveDisallowedParameters");
+void CommandRequestImpl::RemoveDisallowedParameters() {
+ LOG4CXX_AUTO_TRACE(logger_);
smart_objects::SmartObject& params = (*message_)[strings::msg_params];
// Remove from request all disallowed parameters
std::vector<std::string>::const_iterator it_disallowed =
- params_permissions.disallowed_params.begin();
+ parameters_permissions_.disallowed_params.begin();
std::vector<std::string>::const_iterator it_disallowed_end =
- params_permissions.disallowed_params.end();
- for (;it_disallowed != it_disallowed_end; ++it_disallowed) {
+ parameters_permissions_.disallowed_params.end();
+ for (; it_disallowed != it_disallowed_end; ++it_disallowed) {
if (params.keyExists(*it_disallowed)) {
params.erase(*it_disallowed);
- parameters_permissions_.disallowed_params.push_back(
- *it_disallowed);
- LOG4CXX_INFO(logger_, "Following parameter is disallowed by user: "
- << *it_disallowed);
+ removed_parameters_permissions_.disallowed_params.push_back(
+ *it_disallowed);
+ LOG4CXX_INFO(
+ logger_,
+ "Following parameter is disallowed by user: " << *it_disallowed);
}
}
// Remove from request all undefined yet parameters
std::vector<std::string>::const_iterator it_undefined =
- params_permissions.undefined_params.begin();
+ parameters_permissions_.undefined_params.begin();
std::vector<std::string>::const_iterator it_undefined_end =
- params_permissions.undefined_params.end();
- for (;it_undefined != it_undefined_end; ++it_undefined) {
+ parameters_permissions_.undefined_params.end();
+ for (; it_undefined != it_undefined_end; ++it_undefined) {
if (params.keyExists(*it_undefined)) {
params.erase(*it_undefined);
- parameters_permissions_.undefined_params.push_back(
- *it_undefined);
- LOG4CXX_INFO(logger_, "Following parameter is disallowed by policy: "
- << *it_undefined);
+ removed_parameters_permissions_.undefined_params.push_back(*it_undefined);
+ LOG4CXX_INFO(
+ logger_,
+ "Following parameter is disallowed by policy: " << *it_undefined);
}
}
@@ -469,19 +474,18 @@ void CommandRequestImpl::RemoveDisallowedParameters(
VehicleData::const_iterator it_vehicle_data = vehicle_data.begin();
VehicleData::const_iterator it_vehicle_data_end = vehicle_data.end();
- for (;it_vehicle_data != it_vehicle_data_end; ++it_vehicle_data) {
+ for (; it_vehicle_data != it_vehicle_data_end; ++it_vehicle_data) {
const std::string key = it_vehicle_data->first;
if (params.keyExists(key) &&
- params_permissions.allowed_params.end() ==
- std::find(params_permissions.allowed_params.begin(),
- params_permissions.allowed_params.end(),
- key)) {
+ parameters_permissions_.allowed_params.end() ==
+ std::find(parameters_permissions_.allowed_params.begin(),
+ parameters_permissions_.allowed_params.end(),
+ key)) {
params.erase(key);
- parameters_permissions_.undefined_params.push_back(key);
+ removed_parameters_permissions_.undefined_params.push_back(key);
LOG4CXX_INFO(logger_,
"Following parameter is not found among allowed parameters '"
- << key
- << "' and will be treated as disallowed.");
+ << key << "' and will be treated as disallowed.");
}
}
}
@@ -501,13 +505,13 @@ void CommandRequestImpl::AddDisallowedParametersToInfo(
std::string info;
std::vector<std::string>::const_iterator it =
- parameters_permissions_.disallowed_params.begin();
- for (; it != parameters_permissions_.disallowed_params.end(); ++it) {
+ removed_parameters_permissions_.disallowed_params.begin();
+ for (; it != removed_parameters_permissions_.disallowed_params.end(); ++it) {
AddDissalowedParameterToInfoString(info, (*it));
}
- it = parameters_permissions_.undefined_params.begin();
- for (; it != parameters_permissions_.undefined_params.end(); ++it) {
+ it = removed_parameters_permissions_.undefined_params.begin();
+ for (; it != removed_parameters_permissions_.undefined_params.end(); ++it) {
AddDissalowedParameterToInfoString(info, (*it));
}
@@ -527,23 +531,26 @@ void CommandRequestImpl::AddDisallowedParametersToInfo(
void CommandRequestImpl::AddDisallowedParameters(
smart_objects::SmartObject& response) {
DisallowedParamsInserter disallowed_inserter(
- response,
- mobile_apis::VehicleDataResultCode::VDRC_USER_DISALLOWED);
- std::for_each(parameters_permissions_.disallowed_params.begin(),
- parameters_permissions_.disallowed_params.end(),
+ response, mobile_apis::VehicleDataResultCode::VDRC_USER_DISALLOWED);
+ std::for_each(removed_parameters_permissions_.disallowed_params.begin(),
+ removed_parameters_permissions_.disallowed_params.end(),
disallowed_inserter);
DisallowedParamsInserter undefined_inserter(
- response,
- mobile_apis::VehicleDataResultCode::VDRC_DISALLOWED);
- std::for_each(parameters_permissions_.undefined_params.begin(),
- parameters_permissions_.undefined_params.end(),
+ response, mobile_apis::VehicleDataResultCode::VDRC_DISALLOWED);
+ std::for_each(removed_parameters_permissions_.undefined_params.begin(),
+ removed_parameters_permissions_.undefined_params.end(),
undefined_inserter);
}
bool CommandRequestImpl::HasDisallowedParams() const {
- return ((!parameters_permissions_.disallowed_params.empty()) ||
- (!parameters_permissions_.undefined_params.empty()));
+ return ((!removed_parameters_permissions_.disallowed_params.empty()) ||
+ (!removed_parameters_permissions_.undefined_params.empty()));
+}
+
+const CommandParametersPermissions& CommandRequestImpl::parameters_permissions()
+ const {
+ return parameters_permissions_;
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/command_response_impl.cc b/src/components/application_manager/src/commands/command_response_impl.cc
index d7bd9133bf..c3265230a8 100644
--- a/src/components/application_manager/src/commands/command_response_impl.cc
+++ b/src/components/application_manager/src/commands/command_response_impl.cc
@@ -31,18 +31,17 @@
*/
#include "application_manager/commands/command_response_impl.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
-CommandResponseImpl::CommandResponseImpl(const MessageSharedPtr& message)
- : CommandImpl(message) {
-}
+CommandResponseImpl::CommandResponseImpl(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandImpl(message, application_manager) {}
-CommandResponseImpl::~CommandResponseImpl() {
-}
+CommandResponseImpl::~CommandResponseImpl() {}
bool CommandResponseImpl::Init() {
return true;
@@ -52,11 +51,12 @@ bool CommandResponseImpl::CleanUp() {
return true;
}
-void CommandResponseImpl::Run() {
-}
+void CommandResponseImpl::Run() {}
void CommandResponseImpl::SendResponse(
- bool success, const mobile_apis::Result::eType& result_code, bool final_message) {
+ bool success,
+ const mobile_apis::Result::eType& result_code,
+ bool final_message) {
LOG4CXX_INFO(logger_, "Trying to send response");
(*message_)[strings::params][strings::protocol_type] = mobile_protocol_type_;
@@ -80,7 +80,7 @@ void CommandResponseImpl::SendResponse(
}
}
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_, final_message);
+ application_manager_.SendMessageToMobile(message_, final_message);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/activate_app_request.cc b/src/components/application_manager/src/commands/hmi/activate_app_request.cc
index c8258bd74a..ea36cd2b0a 100644
--- a/src/components/application_manager/src/commands/hmi/activate_app_request.cc
+++ b/src/components/application_manager/src/commands/hmi/activate_app_request.cc
@@ -31,41 +31,39 @@
*/
#include "application_manager/commands/hmi/activate_app_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/message_helper.h"
namespace application_manager {
- namespace commands {
-
- ActivateAppRequest::ActivateAppRequest(
- const MessageSharedPtr& message): RequestToHMI(message) {
- }
+namespace commands {
+ActivateAppRequest::ActivateAppRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
- ActivateAppRequest::~ActivateAppRequest() {
- LOG4CXX_TRACE(logger_, "~ActivateAppRequest");
- }
+ActivateAppRequest::~ActivateAppRequest() {
+ LOG4CXX_TRACE(logger_, "~ActivateAppRequest");
+}
- void ActivateAppRequest::Run() {
- LOG4CXX_TRACE(logger_, "enter " << correlation_id());
- uint32_t app_id = RequestToHMI::application_id();
- ApplicationManagerImpl::instance()->set_application_id(correlation_id(), app_id);
+void ActivateAppRequest::Run() {
+ LOG4CXX_TRACE(logger_, "enter " << correlation_id());
+ uint32_t app_id = RequestToHMI::application_id();
+ application_manager_.set_application_id(correlation_id(), app_id);
#ifdef ENABLE_LOG
- if ((*message_)[strings::msg_params].keyExists(
- strings::activate_app_hmi_level)) {
- mobile_apis::HMILevel::eType requested_hmi_level =
- static_cast<mobile_apis::HMILevel::eType>(
- (*message_)[strings::msg_params][strings::activate_app_hmi_level].asInt());
- LOG4CXX_TRACE(logger_, "requested_hmi_level = "
- << requested_hmi_level);
- }
+ if ((*message_)[strings::msg_params].keyExists(
+ strings::activate_app_hmi_level)) {
+ mobile_apis::HMILevel::eType requested_hmi_level =
+ static_cast<mobile_apis::HMILevel::eType>(
+ (*message_)[strings::msg_params][strings::activate_app_hmi_level]
+ .asInt());
+ LOG4CXX_TRACE(logger_, "requested_hmi_level = " << requested_hmi_level);
+ }
#endif
- SendRequest();
- LOG4CXX_TRACE(logger_, "exit");
- }
+ SendRequest();
+ LOG4CXX_TRACE(logger_, "exit");
+}
- } // namespace commands
+} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/activate_app_response.cc b/src/components/application_manager/src/commands/hmi/activate_app_response.cc
index 2f63198d82..55e704b6c4 100644
--- a/src/components/application_manager/src/commands/hmi/activate_app_response.cc
+++ b/src/components/application_manager/src/commands/hmi/activate_app_response.cc
@@ -30,7 +30,7 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/activate_app_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/message_helper.h"
namespace application_manager {
@@ -38,17 +38,17 @@ namespace application_manager {
namespace commands {
ActivateAppResponse::ActivateAppResponse(
- const MessageSharedPtr& message): ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-ActivateAppResponse::~ActivateAppResponse() {
-}
+ActivateAppResponse::~ActivateAppResponse() {}
void ActivateAppResponse::Run() {
LOG4CXX_TRACE(logger_, "enter");
- event_engine::Event event(hmi_apis::FunctionID::BasicCommunication_ActivateApp);
+ event_engine::Event event(
+ hmi_apis::FunctionID::BasicCommunication_ActivateApp);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
LOG4CXX_TRACE(logger_, "exit");
}
diff --git a/src/components/application_manager/src/commands/hmi/add_statistics_info_notification.cc b/src/components/application_manager/src/commands/hmi/add_statistics_info_notification.cc
index 73c9a49def..ef75eba1e2 100644
--- a/src/components/application_manager/src/commands/hmi/add_statistics_info_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/add_statistics_info_notification.cc
@@ -39,23 +39,20 @@ namespace application_manager {
namespace commands {
AddStatisticsInfoNotification::AddStatisticsInfoNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-AddStatisticsInfoNotification::~AddStatisticsInfoNotification() {
-}
+AddStatisticsInfoNotification::~AddStatisticsInfoNotification() {}
void AddStatisticsInfoNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
int type = (*message_)[strings::msg_params][hmi_notification::statistic_type]
- .asInt();
+ .asInt();
- policy::PolicyHandler::instance()->AddStatisticsInfo(type);
+ application_manager_.GetPolicyHandler().AddStatisticsInfo(type);
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/allow_all_apps_request.cc b/src/components/application_manager/src/commands/hmi/allow_all_apps_request.cc
index 548238f00f..4e096a2cda 100644
--- a/src/components/application_manager/src/commands/hmi/allow_all_apps_request.cc
+++ b/src/components/application_manager/src/commands/hmi/allow_all_apps_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-AllowAllAppsRequest::AllowAllAppsRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+AllowAllAppsRequest::AllowAllAppsRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-AllowAllAppsRequest::~AllowAllAppsRequest() {
-}
+AllowAllAppsRequest::~AllowAllAppsRequest() {}
void AllowAllAppsRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void AllowAllAppsRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/allow_all_apps_response.cc b/src/components/application_manager/src/commands/hmi/allow_all_apps_response.cc
index eca9363254..ed05c3ba83 100644
--- a/src/components/application_manager/src/commands/hmi/allow_all_apps_response.cc
+++ b/src/components/application_manager/src/commands/hmi/allow_all_apps_response.cc
@@ -30,23 +30,21 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/allow_all_apps_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-AllowAllAppsResponse::AllowAllAppsResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+AllowAllAppsResponse::AllowAllAppsResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-AllowAllAppsResponse::~AllowAllAppsResponse() {
-}
+AllowAllAppsResponse::~AllowAllAppsResponse() {}
void AllowAllAppsResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->set_all_apps_allowed(
+ application_manager_.SetAllAppsAllowed(
(*message_)[strings::msg_params][hmi_response::allowed].asBool());
}
diff --git a/src/components/application_manager/src/commands/hmi/allow_app_request.cc b/src/components/application_manager/src/commands/hmi/allow_app_request.cc
index 2f0d4bcc98..5176b3b4fe 100644
--- a/src/components/application_manager/src/commands/hmi/allow_app_request.cc
+++ b/src/components/application_manager/src/commands/hmi/allow_app_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-AllowAppRequest::AllowAppRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+AllowAppRequest::AllowAppRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-AllowAppRequest::~AllowAppRequest() {
-}
+AllowAppRequest::~AllowAppRequest() {}
void AllowAppRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void AllowAppRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/allow_app_response.cc b/src/components/application_manager/src/commands/hmi/allow_app_response.cc
index 7a7f3dd560..5fd9c702b4 100644
--- a/src/components/application_manager/src/commands/hmi/allow_app_response.cc
+++ b/src/components/application_manager/src/commands/hmi/allow_app_response.cc
@@ -30,34 +30,33 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/allow_app_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
namespace application_manager {
namespace commands {
-AllowAppResponse::AllowAppResponse(
- const MessageSharedPtr& message): ResponseFromHMI(message) {
-}
+AllowAppResponse::AllowAppResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-AllowAppResponse::~AllowAppResponse() {
-}
+AllowAppResponse::~AllowAppResponse() {}
void AllowAppResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
uint32_t connection_key =
- (*message_)[strings::params][strings::connection_key].asInt();
+ (*message_)[strings::params][strings::connection_key].asInt();
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->
- application(connection_key);
+ ApplicationSharedPtr app = application_manager_.application(connection_key);
if (!app) {
LOG4CXX_ERROR(logger_, "NULL pointer");
return;
}
- app->set_app_allowed((*message_)[strings::msg_params][hmi_response::allowed].asBool());
+ app->set_app_allowed(
+ (*message_)[strings::msg_params][hmi_response::allowed].asBool());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/basic_communication_on_awake_sdl.cc b/src/components/application_manager/src/commands/hmi/basic_communication_on_awake_sdl.cc
index b34752a00f..80b1edb5bb 100644
--- a/src/components/application_manager/src/commands/hmi/basic_communication_on_awake_sdl.cc
+++ b/src/components/application_manager/src/commands/hmi/basic_communication_on_awake_sdl.cc
@@ -29,5 +29,3 @@
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
-
-
diff --git a/src/components/application_manager/src/commands/hmi/basic_communication_system_request.cc b/src/components/application_manager/src/commands/hmi/basic_communication_system_request.cc
index d0251a7276..2499c21680 100644
--- a/src/components/application_manager/src/commands/hmi/basic_communication_system_request.cc
+++ b/src/components/application_manager/src/commands/hmi/basic_communication_system_request.cc
@@ -31,18 +31,16 @@
*/
#include "application_manager/commands/hmi/basic_communication_system_request.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
BasicCommunicationSystemRequest::BasicCommunicationSystemRequest(
- const MessageSharedPtr& message): RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-BasicCommunicationSystemRequest::~BasicCommunicationSystemRequest() {
-}
+BasicCommunicationSystemRequest::~BasicCommunicationSystemRequest() {}
void BasicCommunicationSystemRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +50,3 @@ void BasicCommunicationSystemRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/basic_communication_system_response.cc b/src/components/application_manager/src/commands/hmi/basic_communication_system_response.cc
index 6106266d19..16afce92e0 100644
--- a/src/components/application_manager/src/commands/hmi/basic_communication_system_response.cc
+++ b/src/components/application_manager/src/commands/hmi/basic_communication_system_response.cc
@@ -31,6 +31,7 @@
*/
#include "application_manager/commands/hmi/basic_communication_system_response.h"
#include "application_manager/event_engine/event.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
@@ -38,17 +39,17 @@ namespace application_manager {
namespace commands {
BasicCommunicationSystemResponse::BasicCommunicationSystemResponse(
- const MessageSharedPtr& message): ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-BasicCommunicationSystemResponse::~BasicCommunicationSystemResponse() {
-}
+BasicCommunicationSystemResponse::~BasicCommunicationSystemResponse() {}
void BasicCommunicationSystemResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- event_engine::Event event(hmi_apis::FunctionID::BasicCommunication_SystemRequest);
+ event_engine::Event event(
+ hmi_apis::FunctionID::BasicCommunication_SystemRequest);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/button_get_capabilities_request.cc b/src/components/application_manager/src/commands/hmi/button_get_capabilities_request.cc
index 87cf1aa783..e6b73879e5 100644
--- a/src/components/application_manager/src/commands/hmi/button_get_capabilities_request.cc
+++ b/src/components/application_manager/src/commands/hmi/button_get_capabilities_request.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
ButtonGetCapabilitiesRequest::ButtonGetCapabilitiesRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-ButtonGetCapabilitiesRequest::~ButtonGetCapabilitiesRequest() {
-}
+ButtonGetCapabilitiesRequest::~ButtonGetCapabilitiesRequest() {}
void ButtonGetCapabilitiesRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -54,4 +52,3 @@ void ButtonGetCapabilitiesRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/button_get_capabilities_response.cc b/src/components/application_manager/src/commands/hmi/button_get_capabilities_response.cc
index bb04636aba..a947fb7ba9 100644
--- a/src/components/application_manager/src/commands/hmi/button_get_capabilities_response.cc
+++ b/src/components/application_manager/src/commands/hmi/button_get_capabilities_response.cc
@@ -30,7 +30,7 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/button_get_capabilities_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "utils/logger.h"
namespace application_manager {
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
ButtonGetCapabilitiesResponse::ButtonGetCapabilitiesResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-ButtonGetCapabilitiesResponse::~ButtonGetCapabilitiesResponse() {
-}
+ButtonGetCapabilitiesResponse::~ButtonGetCapabilitiesResponse() {}
void ButtonGetCapabilitiesResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -56,8 +54,7 @@ void ButtonGetCapabilitiesResponse::Run() {
return;
}
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
hmi_capabilities.set_button_capabilities(
(*message_)[strings::msg_params][hmi_response::capabilities]);
diff --git a/src/components/application_manager/src/commands/hmi/close_popup_request.cc b/src/components/application_manager/src/commands/hmi/close_popup_request.cc
index 352a281348..b0ab48dd96 100644
--- a/src/components/application_manager/src/commands/hmi/close_popup_request.cc
+++ b/src/components/application_manager/src/commands/hmi/close_popup_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-ClosePopupRequest::ClosePopupRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ClosePopupRequest::ClosePopupRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-ClosePopupRequest::~ClosePopupRequest() {
-}
+ClosePopupRequest::~ClosePopupRequest() {}
void ClosePopupRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void ClosePopupRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/close_popup_response.cc b/src/components/application_manager/src/commands/hmi/close_popup_response.cc
index 078d24ef2d..15adb2ee32 100644
--- a/src/components/application_manager/src/commands/hmi/close_popup_response.cc
+++ b/src/components/application_manager/src/commands/hmi/close_popup_response.cc
@@ -35,12 +35,11 @@ namespace application_manager {
namespace commands {
-ClosePopupResponse::ClosePopupResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ClosePopupResponse::ClosePopupResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-ClosePopupResponse::~ClosePopupResponse() {
-}
+ClosePopupResponse::~ClosePopupResponse() {}
void ClosePopupResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/hmi/dial_number_request.cc b/src/components/application_manager/src/commands/hmi/dial_number_request.cc
index 0e8e359e7e..b26541cb01 100644
--- a/src/components/application_manager/src/commands/hmi/dial_number_request.cc
+++ b/src/components/application_manager/src/commands/hmi/dial_number_request.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016, Ford Motor Company
+ * Copyright (c) 2013, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -38,20 +38,18 @@ namespace commands {
namespace hmi {
-DialNumberRequest::DialNumberRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+DialNumberRequest::DialNumberRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-DialNumberRequest::~DialNumberRequest() {
-}
+DialNumberRequest::~DialNumberRequest() {}
void DialNumberRequest::Run() {
SendRequest();
}
-} // namespace hmi
+} // namespace hmi
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/dial_number_response.cc b/src/components/application_manager/src/commands/hmi/dial_number_response.cc
index 3f616bf47f..5511fa98f8 100644
--- a/src/components/application_manager/src/commands/hmi/dial_number_response.cc
+++ b/src/components/application_manager/src/commands/hmi/dial_number_response.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2016, Ford Motor Company
+ * Copyright (c) 2013, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -37,20 +37,20 @@ namespace commands {
namespace hmi {
-DialNumberResponse::DialNumberResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+DialNumberResponse::DialNumberResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-DialNumberResponse::~DialNumberResponse() {
-}
+DialNumberResponse::~DialNumberResponse() {}
void DialNumberResponse::Run() {
- event_engine::Event event(hmi_apis::FunctionID::BasicCommunication_DialNumber);
+ event_engine::Event event(
+ hmi_apis::FunctionID::BasicCommunication_DialNumber);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
-} // namespace hmi
+} // namespace hmi
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/get_system_info_request.cc b/src/components/application_manager/src/commands/hmi/get_system_info_request.cc
index 9024331462..379027c43a 100644
--- a/src/components/application_manager/src/commands/hmi/get_system_info_request.cc
+++ b/src/components/application_manager/src/commands/hmi/get_system_info_request.cc
@@ -31,29 +31,25 @@
*/
#include "application_manager/commands/hmi/get_system_info_request.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
GetSystemInfoRequest::GetSystemInfoRequest(
- const MessageSharedPtr& message): RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-GetSystemInfoRequest::~GetSystemInfoRequest() {
-}
+GetSystemInfoRequest::~GetSystemInfoRequest() {}
void GetSystemInfoRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
uint32_t correlation_id = RequestToHMI::correlation_id();
uint32_t app_id = RequestToHMI::application_id();
- ApplicationManagerImpl::instance()->set_application_id(correlation_id, app_id);
+ application_manager_.set_application_id(correlation_id, app_id);
SendRequest();
}
} // namespace commands
} // namespace application_manager
-
-
diff --git a/src/components/application_manager/src/commands/hmi/get_system_info_response.cc b/src/components/application_manager/src/commands/hmi/get_system_info_response.cc
index 5b1ec94e9d..be6dabb292 100644
--- a/src/components/application_manager/src/commands/hmi/get_system_info_response.cc
+++ b/src/components/application_manager/src/commands/hmi/get_system_info_response.cc
@@ -30,20 +30,16 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/get_system_info_response.h"
-#include "application_manager/application_manager_impl.h"
-#include "application_manager/policies/policy_handler.h"
#include "application_manager/message_helper.h"
namespace application_manager {
-
namespace commands {
GetSystemInfoResponse::GetSystemInfoResponse(
- const MessageSharedPtr& message): ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-GetSystemInfoResponse::~GetSystemInfoResponse() {
-}
+GetSystemInfoResponse::~GetSystemInfoResponse() {}
void GetSystemInfoResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -51,39 +47,36 @@ void GetSystemInfoResponse::Run() {
static_cast<hmi_apis::Common_Result::eType>(
(*message_)[strings::params][hmi_response::code].asInt());
- std::string ccpu_version;
- std::string wers_country_code;
- std::string language;
+ const SystemInfo& info = GetSystemInfo(code);
- if (hmi_apis::Common_Result::SUCCESS == code) {
- ccpu_version =
- (*message_)[strings::msg_params]["ccpu_version"].asString();
- wers_country_code =
- (*message_)[strings::msg_params]["wersCountryCode"].asString();
- uint32_t lang_code = (*message_)[strings::msg_params]["language"].asUInt();
- language = application_manager::MessageHelper::CommonLanguageToString(
- static_cast<hmi_apis::Common_Language::eType>(lang_code));
+ // We have to set preloaded flag as false in policy table on any response
+ // of GetSystemInfo (SDLAQ-CRS-2365)
+ application_manager_.GetPolicyHandler().OnGetSystemInfo(
+ info.ccpu_version, info.wers_country_code, info.language);
+}
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
- hmi_capabilities.set_ccpu_version(ccpu_version);
- } else {
- LOG4CXX_WARN(logger_, "GetSystemError returns an error code " << code);
+const SystemInfo GetSystemInfoResponse::GetSystemInfo(
+ const hmi_apis::Common_Result::eType code) const {
+ SystemInfo info;
- // We have to set preloaded flag as false in policy table on any response
- // of GetSystemInfo (SDLAQ-CRS-2365)
- const std::string empty_value;
- policy::PolicyHandler::instance()->OnGetSystemInfo(empty_value,
- empty_value,
- empty_value);
- return;
+ if (hmi_apis::Common_Result::SUCCESS != code) {
+ LOG4CXX_WARN(logger_, "GetSystemError returns an error code " << code);
+ return info;
}
+ info.ccpu_version =
+ (*message_)[strings::msg_params]["ccpu_version"].asString();
- // We have to set preloaded flag as false in policy table on any response
- // of GetSystemInfo (SDLAQ-CRS-2365)
- policy::PolicyHandler::instance()->OnGetSystemInfo(ccpu_version,
- wers_country_code,
- language);
+ info.wers_country_code =
+ (*message_)[strings::msg_params]["wersCountryCode"].asString();
+
+ const uint32_t lang_code =
+ (*message_)[strings::msg_params]["language"].asUInt();
+ info.language = application_manager::MessageHelper::CommonLanguageToString(
+ static_cast<hmi_apis::Common_Language::eType>(lang_code));
+
+ application_manager_.hmi_capabilities().set_ccpu_version(info.ccpu_version);
+
+ return info;
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/get_urls.cc b/src/components/application_manager/src/commands/hmi/get_urls.cc
index 1c7d9f57c1..af220051d4 100644
--- a/src/components/application_manager/src/commands/hmi/get_urls.cc
+++ b/src/components/application_manager/src/commands/hmi/get_urls.cc
@@ -32,13 +32,27 @@
#include "application_manager/commands/hmi/get_urls.h"
#include "application_manager/message.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
#include "application_manager/policies/policy_handler.h"
+namespace {
+struct PolicyAppIdComparator {
+ PolicyAppIdComparator(const std::string& policy_app_id)
+ : policy_app_id_(policy_app_id) {}
+
+ bool operator()(const policy::EndpointData& data) {
+ return data.app_id == policy_app_id_;
+ }
+ std::string policy_app_id_;
+};
+}
+
namespace application_manager {
namespace commands {
-GetUrls::GetUrls(const MessageSharedPtr& message) : RequestFromHMI(message) {}
+GetUrls::GetUrls(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestFromHMI(message, application_manager) {}
GetUrls::~GetUrls() {}
@@ -49,7 +63,7 @@ void GetUrls::Run() {
using namespace strings;
using namespace hmi_apis;
- if (!policy::PolicyHandler::instance()->PolicyEnabled()) {
+ if (!application_manager_.GetPolicyHandler().PolicyEnabled()) {
SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
return;
}
@@ -59,9 +73,8 @@ void GetUrls::Run() {
object[msg_params][hmi_request::service].asString();
policy::EndpointUrls endpoints;
- policy::PolicyHandler::instance()->GetServiceUrls(
- object[strings::msg_params][hmi_request::service].asString(),
- endpoints);
+ application_manager_.GetPolicyHandler().GetServiceUrls(
+ object[strings::msg_params][hmi_request::service].asString(), endpoints);
if (endpoints.empty()) {
LOG4CXX_ERROR(logger_, "No URLs for service " << service_to_check);
SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
@@ -88,22 +101,29 @@ void GetUrls::ProcessPolicyServiceURLs(const policy::EndpointUrls& endpoints) {
using namespace hmi_apis;
const uint32_t app_id_to_send_to =
- policy::PolicyHandler::instance()->GetAppIdForSending();
+ application_manager_.GetPolicyHandler().GetAppIdForSending();
if (!app_id_to_send_to) {
LOG4CXX_ERROR(logger_,
"There are no available applications for processing.");
- ApplicationManagerImpl::instance()->ManageHMICommand(message_);
+ SmartObject urls(SmartType_Array);
+ FillSODefaultUrls(urls, endpoints);
+ if (!urls.empty()) {
+ (*message_)[msg_params][hmi_response::urls] = urls;
+ }
+ (*message_).erase(hmi_request::service);
+ SendResponseToHMI(Common_Result::SUCCESS);
return;
}
ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(app_id_to_send_to);
+ application_manager_.application(app_id_to_send_to);
if (!app.valid()) {
LOG4CXX_WARN(logger_,
"There is no registered application with "
- "connection key '" << app_id_to_send_to << "'");
+ "connection key '"
+ << app_id_to_send_to << "'");
SendResponseToHMI(Common_Result::DATA_NOT_AVAILABLE);
return;
}
@@ -111,10 +131,8 @@ void GetUrls::ProcessPolicyServiceURLs(const policy::EndpointUrls& endpoints) {
SmartObject& object = *message_;
object[msg_params].erase(hmi_request::service);
object[msg_params][hmi_response::urls] = SmartObject(SmartType_Array);
-
SmartObject& urls = object[msg_params][hmi_response::urls];
-
- const std::string mobile_app_id = app->mobile_app_id();
+ const std::string mobile_app_id = app->policy_app_id();
std::string default_url = "URL is not found";
// Will use only one URL for particular application if it will be found
@@ -122,7 +140,6 @@ void GetUrls::ProcessPolicyServiceURLs(const policy::EndpointUrls& endpoints) {
SmartObject service_info = SmartObject(SmartType_Map);
for (size_t e = 0; e < endpoints.size(); ++e) {
-
if (mobile_app_id == endpoints[e].app_id) {
if (endpoints[e].url.size()) {
service_info[url] = endpoints[e].url[0];
@@ -175,10 +192,27 @@ void GetUrls::ProcessServiceURLs(const policy::EndpointUrls& endpoints) {
SendResponseToHMI(Common_Result::SUCCESS);
}
+void GetUrls::FillSODefaultUrls(smart_objects::SmartObject& urls,
+ const policy::EndpointUrls& endpoints) {
+ using namespace smart_objects;
+ LOG4CXX_AUTO_TRACE(logger_);
+ PolicyAppIdComparator comparator(policy::kDefaultId);
+ policy::EndpointUrls::const_iterator it =
+ std::find_if(endpoints.begin(), endpoints.end(), comparator);
+ if (it == endpoints.end()) {
+ return;
+ }
+ SmartObject service_info = SmartObject(SmartType_Map);
+ for (size_t i = 0; i < (*it).url.size(); ++i) {
+ service_info[strings::url] = (*it).url[i];
+ urls[i] = service_info;
+ }
+}
+
void GetUrls::SendResponseToHMI(hmi_apis::Common_Result::eType result) {
(*message_)[strings::params][strings::message_type] = MessageType::kResponse;
(*message_)[strings::params][hmi_response::code] = result;
- ApplicationManagerImpl::instance()->ManageHMICommand(message_);
+ application_manager_.ManageHMICommand(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/get_urls_response.cc b/src/components/application_manager/src/commands/hmi/get_urls_response.cc
index b446f088bf..dd9686fbce 100644
--- a/src/components/application_manager/src/commands/hmi/get_urls_response.cc
+++ b/src/components/application_manager/src/commands/hmi/get_urls_response.cc
@@ -31,24 +31,22 @@
*/
#include "application_manager/commands/hmi/get_urls_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-GetUrlsResponse::GetUrlsResponse(
- const MessageSharedPtr& message): ResponseToHMI(message) {
-}
+GetUrlsResponse::GetUrlsResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseToHMI(message, application_manager) {}
-GetUrlsResponse::~GetUrlsResponse() {
-}
+GetUrlsResponse::~GetUrlsResponse() {}
void GetUrlsResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
(*message_)[strings::params][strings::protocol_type] = hmi_protocol_type_;
(*message_)[strings::params][strings::protocol_version] = protocol_version_;
- ApplicationManagerImpl::instance()->SendMessageToHMI(message_);
+ application_manager_.SendMessageToHMI(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/mixing_audio_supported_request.cc b/src/components/application_manager/src/commands/hmi/mixing_audio_supported_request.cc
index 059843355c..e38d1fc088 100644
--- a/src/components/application_manager/src/commands/hmi/mixing_audio_supported_request.cc
+++ b/src/components/application_manager/src/commands/hmi/mixing_audio_supported_request.cc
@@ -37,11 +37,10 @@ namespace application_manager {
namespace commands {
MixingAudioSupportedRequest::MixingAudioSupportedRequest(
- const MessageSharedPtr& message) : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-MixingAudioSupportedRequest::~MixingAudioSupportedRequest() {
-}
+MixingAudioSupportedRequest::~MixingAudioSupportedRequest() {}
void MixingAudioSupportedRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void MixingAudioSupportedRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/mixing_audio_supported_response.cc b/src/components/application_manager/src/commands/hmi/mixing_audio_supported_response.cc
index 2da8bdc453..f8b58e6f35 100644
--- a/src/components/application_manager/src/commands/hmi/mixing_audio_supported_response.cc
+++ b/src/components/application_manager/src/commands/hmi/mixing_audio_supported_response.cc
@@ -30,26 +30,24 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/mixing_audio_supported_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
MixingAudioSupportedResponse::MixingAudioSupportedResponse(
- const MessageSharedPtr& message) : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-MixingAudioSupportedResponse::~MixingAudioSupportedResponse() {
-}
+MixingAudioSupportedResponse::~MixingAudioSupportedResponse() {}
void MixingAudioSupportedResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
- hmi_capabilities.set_attenuated_supported((*message_)
- [strings::msg_params][hmi_response::attenuated_supported].asBool());
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
+ hmi_capabilities.set_attenuated_supported(
+ (*message_)[strings::msg_params][hmi_response::attenuated_supported]
+ .asBool());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/navi_alert_maneuver_request.cc b/src/components/application_manager/src/commands/hmi/navi_alert_maneuver_request.cc
index 77b3701904..582caaa8f3 100644
--- a/src/components/application_manager/src/commands/hmi/navi_alert_maneuver_request.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_alert_maneuver_request.cc
@@ -37,11 +37,10 @@ namespace application_manager {
namespace commands {
NaviAlertManeuverRequest::NaviAlertManeuverRequest(
- const MessageSharedPtr& message) : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-NaviAlertManeuverRequest::~NaviAlertManeuverRequest() {
-}
+NaviAlertManeuverRequest::~NaviAlertManeuverRequest() {}
void NaviAlertManeuverRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void NaviAlertManeuverRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/navi_alert_maneuver_response.cc b/src/components/application_manager/src/commands/hmi/navi_alert_maneuver_response.cc
index 49d659777b..5f0422bf6a 100644
--- a/src/components/application_manager/src/commands/hmi/navi_alert_maneuver_response.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_alert_maneuver_response.cc
@@ -31,6 +31,7 @@
*/
#include "application_manager/commands/hmi/navi_alert_maneuver_response.h"
#include "application_manager/event_engine/event.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
@@ -38,18 +39,17 @@ namespace application_manager {
namespace commands {
NaviAlertManeuverResponse::NaviAlertManeuverResponse(
- const MessageSharedPtr& message) : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-NaviAlertManeuverResponse::~NaviAlertManeuverResponse() {
-}
+NaviAlertManeuverResponse::~NaviAlertManeuverResponse() {}
void NaviAlertManeuverResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::Navigation_AlertManeuver);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/navi_audio_start_stream_request.cc b/src/components/application_manager/src/commands/hmi/navi_audio_start_stream_request.cc
index 4a637341c1..920c6fbdf9 100644
--- a/src/components/application_manager/src/commands/hmi/navi_audio_start_stream_request.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_audio_start_stream_request.cc
@@ -31,67 +31,30 @@
*/
#include "application_manager/commands/hmi/navi_audio_start_stream_request.h"
-#include "application_manager/application_manager_impl.h"
+
+#include "application_manager/message_helper.h"
#include "protocol_handler/protocol_handler.h"
-#include "config_profile/profile.h"
namespace application_manager {
namespace commands {
AudioStartStreamRequest::AudioStartStreamRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message),
- retry_number_(0) {
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager)
+ , EventObserver(application_manager.event_dispatcher())
+ , retry_number_(0) {
LOG4CXX_AUTO_TRACE(logger_);
std::pair<uint32_t, int32_t> stream_retry =
- profile::Profile::instance()->start_stream_retry_amount();
+ application_manager_.get_settings().start_stream_retry_amount();
default_timeout_ = stream_retry.second;
retry_number_ = stream_retry.first;
- LOG4CXX_DEBUG(logger_, "default_timeout_ = " << default_timeout_
- <<"; retry_number_ = " << retry_number_);
-}
-
-AudioStartStreamRequest::~AudioStartStreamRequest() {
-}
-
-void AudioStartStreamRequest::RetryStartSession() {
- LOG4CXX_AUTO_TRACE(logger_);
-
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->
- application_by_hmi_app(application_id());
- if (!app) {
- LOG4CXX_ERROR(logger_,
- "StartAudioStreamRequest aborted. Application not found");
- return;
- }
- if (app->audio_streaming_approved()) {
- LOG4CXX_DEBUG(logger_, "AudioStartStream retry sequence stopped. "
- << "SUCCESS received");
- app->set_audio_stream_retry_number(0);
- return;
- }
-
- uint32_t curr_retry_number = app->audio_stream_retry_number();
- if (curr_retry_number < retry_number_ - 1) {
- LOG4CXX_DEBUG(logger_, "Send AudioStartStream retry. retry_number = "
- << curr_retry_number);
- MessageHelper::SendAudioStartStream(app->app_id());
- app->set_audio_stream_retry_number(++curr_retry_number);
- } else {
- LOG4CXX_DEBUG(logger_, "Audio start stream retry sequence stopped. "
- << "Attempts expired.");
- app->set_audio_stream_retry_number(0);
- ApplicationManagerImpl::instance()->EndNaviServices(app->app_id());
- }
+ LOG4CXX_DEBUG(logger_,
+ "default_timeout_ = " << default_timeout_
+ << "; retry_number_ = " << retry_number_);
}
-void AudioStartStreamRequest::onTimeOut() {
- RetryStartSession();
-
- ApplicationManagerImpl::instance()->TerminateRequest(
- connection_key(), correlation_id());
-}
+AudioStartStreamRequest::~AudioStartStreamRequest() {}
void AudioStartStreamRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -100,14 +63,15 @@ void AudioStartStreamRequest::Run() {
subscribe_on_event(hmi_apis::FunctionID::Navigation_StartAudioStream,
correlation_id());
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->
- application_by_hmi_app(application_id());
+ ApplicationSharedPtr app =
+ application_manager_.application_by_hmi_app(application_id());
if (app) {
app->set_audio_streaming_allowed(true);
SendRequest();
} else {
- LOG4CXX_ERROR(logger_, "Applcation with hmi_app_id "
- << application_id() << " does not exist");
+ LOG4CXX_ERROR(logger_,
+ "Applcation with hmi_app_id " << application_id()
+ << " does not exist");
}
}
@@ -115,11 +79,11 @@ void AudioStartStreamRequest::on_event(const event_engine::Event& event) {
using namespace protocol_handler;
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->
- application_by_hmi_app(application_id());
+ ApplicationSharedPtr app =
+ application_manager_.application_by_hmi_app(application_id());
if (!app) {
LOG4CXX_ERROR(logger_,
- "StartAudioStreamRequest aborted. Application not found");
+ "StartAudioStreamRequest aborted. Application not found");
return;
}
@@ -133,24 +97,76 @@ void AudioStartStreamRequest::on_event(const event_engine::Event& event) {
message[strings::params][hmi_response::code].asInt());
if (hmi_apis::Common_Result::SUCCESS == code) {
- LOG4CXX_DEBUG(logger_, "StartAudioStreamResponse SUCCESS");
- if (ApplicationManagerImpl::instance()->
- HMILevelAllowsStreaming(app->app_id(), ServiceType::kAudio)) {
+ LOG4CXX_INFO(logger_, "StartAudioStream response SUCCESS");
+ if (application_manager_.HMILevelAllowsStreaming(app->app_id(),
+ ServiceType::kAudio)) {
app->set_audio_streaming_approved(true);
} else {
- LOG4CXX_DEBUG(logger_,
- "StartAudioStreamRequest aborted. Application can not stream");
+ LOG4CXX_WARN(
+ logger_,
+ "StartAudioStreamRequest aborted. Application can not stream");
}
+ break;
+ }
+ if (hmi_apis::Common_Result::REJECTED == code) {
+ LOG4CXX_INFO(logger_, "StartAudioStream response REJECTED");
+ RetryStartSession();
+ break;
}
- break;
}
default: {
- LOG4CXX_ERROR(logger_,"Received unknown event" << event.id());
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
return;
}
}
}
+void AudioStartStreamRequest::onTimeOut() {
+ RetryStartSession();
+
+ application_manager_.TerminateRequest(connection_key(), correlation_id());
+}
+
+void AudioStartStreamRequest::RetryStartSession() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ ApplicationSharedPtr app =
+ application_manager_.application_by_hmi_app(application_id());
+ if (!app) {
+ LOG4CXX_ERROR(logger_,
+ "StartAudioStreamRequest aborted. Application not found");
+ return;
+ }
+
+ if (!app->audio_streaming_allowed()) {
+ LOG4CXX_WARN(logger_, "Audio streaming not allowed");
+ return;
+ }
+
+ if (app->audio_streaming_approved()) {
+ LOG4CXX_INFO(logger_,
+ "AudioStartStream retry sequence stopped. "
+ << "SUCCESS received");
+ app->set_audio_stream_retry_number(0);
+ return;
+ }
+
+ uint32_t curr_retry_number = app->audio_stream_retry_number();
+ if (curr_retry_number < retry_number_ - 1) {
+ LOG4CXX_DEBUG(
+ logger_,
+ "Send AudioStartStream retry. retry_number = " << curr_retry_number);
+ MessageHelper::SendAudioStartStream(app->app_id(), application_manager_);
+ app->set_audio_stream_retry_number(++curr_retry_number);
+ } else {
+ LOG4CXX_DEBUG(logger_,
+ "Audio start stream retry sequence stopped. "
+ << "Attempts expired.");
+
+ application_manager_.EndNaviServices(app->app_id());
+ }
+}
+
} // namespace commands
} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/hmi/navi_audio_start_stream_response.cc b/src/components/application_manager/src/commands/hmi/navi_audio_start_stream_response.cc
index 5547057a1f..c7fc7365e7 100644
--- a/src/components/application_manager/src/commands/hmi/navi_audio_start_stream_response.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_audio_start_stream_response.cc
@@ -35,19 +35,18 @@ namespace application_manager {
namespace commands {
-AudioStartStreamResponse::AudioStartStreamResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+AudioStartStreamResponse::AudioStartStreamResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-AudioStartStreamResponse::~AudioStartStreamResponse() {
-}
+AudioStartStreamResponse::~AudioStartStreamResponse() {}
void AudioStartStreamResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::Navigation_StartAudioStream);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/navi_audio_stop_stream_request.cc b/src/components/application_manager/src/commands/hmi/navi_audio_stop_stream_request.cc
index ea00d5bc3b..d0f1a96282 100644
--- a/src/components/application_manager/src/commands/hmi/navi_audio_stop_stream_request.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_audio_stop_stream_request.cc
@@ -36,12 +36,10 @@ namespace application_manager {
namespace commands {
AudioStopStreamRequest::AudioStopStreamRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-AudioStopStreamRequest::~AudioStopStreamRequest() {
-}
+AudioStopStreamRequest::~AudioStopStreamRequest() {}
void AudioStopStreamRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/hmi/navi_audio_stop_stream_response.cc b/src/components/application_manager/src/commands/hmi/navi_audio_stop_stream_response.cc
index 29e6708e19..c669d399f9 100644
--- a/src/components/application_manager/src/commands/hmi/navi_audio_stop_stream_response.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_audio_stop_stream_response.cc
@@ -35,16 +35,14 @@ namespace application_manager {
namespace commands {
-AudioStopStreamResponse::AudioStopStreamResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+AudioStopStreamResponse::AudioStopStreamResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-AudioStopStreamResponse::~AudioStopStreamResponse() {
-}
+AudioStopStreamResponse::~AudioStopStreamResponse() {}
void AudioStopStreamResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
-
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/navi_get_way_points_request.cc b/src/components/application_manager/src/commands/hmi/navi_get_way_points_request.cc
new file mode 100644
index 0000000000..51f862c957
--- /dev/null
+++ b/src/components/application_manager/src/commands/hmi/navi_get_way_points_request.cc
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/commands/hmi/navi_get_way_points_request.h"
+
+namespace application_manager {
+
+namespace commands {
+
+NaviGetWayPointsRequest::NaviGetWayPointsRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
+
+NaviGetWayPointsRequest::~NaviGetWayPointsRequest() {}
+
+void NaviGetWayPointsRequest::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ SendRequest();
+}
+
+} // namespace commands
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/hmi/navi_get_way_points_response.cc b/src/components/application_manager/src/commands/hmi/navi_get_way_points_response.cc
new file mode 100644
index 0000000000..f295845b24
--- /dev/null
+++ b/src/components/application_manager/src/commands/hmi/navi_get_way_points_response.cc
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/commands/hmi/navi_get_way_points_response.h"
+#include "application_manager/event_engine/event.h"
+#include "interfaces/HMI_API.h"
+
+namespace application_manager {
+
+namespace commands {
+
+NaviGetWayPointsResponse::NaviGetWayPointsResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
+
+NaviGetWayPointsResponse::~NaviGetWayPointsResponse() {}
+
+void NaviGetWayPointsResponse::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ event_engine::Event event(hmi_apis::FunctionID::Navigation_GetWayPoints);
+ event.set_smart_object(*message_);
+ event.raise(application_manager_.event_dispatcher());
+}
+
+} // namespace commands
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/hmi/navi_is_ready_request.cc b/src/components/application_manager/src/commands/hmi/navi_is_ready_request.cc
index 4c00908781..92e972e8f4 100644
--- a/src/components/application_manager/src/commands/hmi/navi_is_ready_request.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_is_ready_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-NaviIsReadyRequest::NaviIsReadyRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+NaviIsReadyRequest::NaviIsReadyRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-NaviIsReadyRequest::~NaviIsReadyRequest() {
-}
+NaviIsReadyRequest::~NaviIsReadyRequest() {}
void NaviIsReadyRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void NaviIsReadyRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/navi_is_ready_response.cc b/src/components/application_manager/src/commands/hmi/navi_is_ready_response.cc
index a3387aec33..129900c60f 100644
--- a/src/components/application_manager/src/commands/hmi/navi_is_ready_response.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_is_ready_response.cc
@@ -30,18 +30,16 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/navi_is_ready_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-NaviIsReadyResponse::NaviIsReadyResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+NaviIsReadyResponse::NaviIsReadyResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-NaviIsReadyResponse::~NaviIsReadyResponse() {
-}
+NaviIsReadyResponse::~NaviIsReadyResponse() {}
void NaviIsReadyResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,8 +50,7 @@ void NaviIsReadyResponse::Run() {
is_available = object[strings::msg_params][strings::available].asBool();
}
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
hmi_capabilities.set_is_navi_cooperating(is_available);
}
diff --git a/src/components/application_manager/src/commands/hmi/navi_send_location_request.cc b/src/components/application_manager/src/commands/hmi/navi_send_location_request.cc
index 94d569c4ef..ad878033ca 100644
--- a/src/components/application_manager/src/commands/hmi/navi_send_location_request.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_send_location_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-NaviSendLocationRequest::NaviSendLocationRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+NaviSendLocationRequest::NaviSendLocationRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-NaviSendLocationRequest::~NaviSendLocationRequest() {
-}
+NaviSendLocationRequest::~NaviSendLocationRequest() {}
void NaviSendLocationRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void NaviSendLocationRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/navi_send_location_response.cc b/src/components/application_manager/src/commands/hmi/navi_send_location_response.cc
index 7ec5a5907d..a3d9f4c9e5 100644
--- a/src/components/application_manager/src/commands/hmi/navi_send_location_response.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_send_location_response.cc
@@ -36,19 +36,18 @@ namespace application_manager {
namespace commands {
-NaviSendLocationResponse::NaviSendLocationResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+NaviSendLocationResponse::NaviSendLocationResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-NaviSendLocationResponse::~NaviSendLocationResponse() {
-}
+NaviSendLocationResponse::~NaviSendLocationResponse() {}
void NaviSendLocationResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::Navigation_SendLocation);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/navi_show_constant_tbt_request.cc b/src/components/application_manager/src/commands/hmi/navi_show_constant_tbt_request.cc
index b477dc8dab..a92ef07d12 100644
--- a/src/components/application_manager/src/commands/hmi/navi_show_constant_tbt_request.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_show_constant_tbt_request.cc
@@ -37,11 +37,10 @@ namespace application_manager {
namespace commands {
NaviShowConstantTBTRequest::NaviShowConstantTBTRequest(
- const MessageSharedPtr& message) : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-NaviShowConstantTBTRequest::~NaviShowConstantTBTRequest() {
-}
+NaviShowConstantTBTRequest::~NaviShowConstantTBTRequest() {}
void NaviShowConstantTBTRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void NaviShowConstantTBTRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/navi_show_constant_tbt_response.cc b/src/components/application_manager/src/commands/hmi/navi_show_constant_tbt_response.cc
index 58878a3c0c..ede3272e8e 100644
--- a/src/components/application_manager/src/commands/hmi/navi_show_constant_tbt_response.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_show_constant_tbt_response.cc
@@ -31,6 +31,7 @@
*/
#include "application_manager/commands/hmi/navi_show_constant_tbt_response.h"
#include "application_manager/event_engine/event.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
@@ -38,18 +39,17 @@ namespace application_manager {
namespace commands {
NaviShowConstantTBTResponse::NaviShowConstantTBTResponse(
- const MessageSharedPtr& message) : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-NaviShowConstantTBTResponse::~NaviShowConstantTBTResponse() {
-}
+NaviShowConstantTBTResponse::~NaviShowConstantTBTResponse() {}
void NaviShowConstantTBTResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::Navigation_ShowConstantTBT);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/navi_start_stream_request.cc b/src/components/application_manager/src/commands/hmi/navi_start_stream_request.cc
index 1ff7916b9a..f0104cbaee 100644
--- a/src/components/application_manager/src/commands/hmi/navi_start_stream_request.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_start_stream_request.cc
@@ -31,29 +31,30 @@
*/
#include "application_manager/commands/hmi/navi_start_stream_request.h"
-#include "application_manager/application_manager_impl.h"
+
+#include "application_manager/message_helper.h"
#include "protocol_handler/protocol_handler.h"
-#include "config_profile/profile.h"
namespace application_manager {
namespace commands {
NaviStartStreamRequest::NaviStartStreamRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message),
- retry_number_(0) {
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager)
+ , EventObserver(application_manager.event_dispatcher())
+ , retry_number_(0) {
LOG4CXX_AUTO_TRACE(logger_);
std::pair<uint32_t, int32_t> stream_retry =
- profile::Profile::instance()->start_stream_retry_amount();
+ application_manager_.get_settings().start_stream_retry_amount();
default_timeout_ = stream_retry.second;
retry_number_ = stream_retry.first;
- LOG4CXX_DEBUG(logger_, "default_timeout_ = " << default_timeout_
- <<"; retry_number_ = " << retry_number_);
+ LOG4CXX_DEBUG(logger_,
+ "default_timeout_ = " << default_timeout_
+ << "; retry_number_ = " << retry_number_);
}
-NaviStartStreamRequest::~NaviStartStreamRequest() {
-}
+NaviStartStreamRequest::~NaviStartStreamRequest() {}
void NaviStartStreamRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -62,14 +63,15 @@ void NaviStartStreamRequest::Run() {
subscribe_on_event(hmi_apis::FunctionID::Navigation_StartStream,
correlation_id());
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->
- application_by_hmi_app(application_id());
+ ApplicationSharedPtr app =
+ application_manager_.application_by_hmi_app(application_id());
if (app) {
app->set_video_streaming_allowed(true);
SendRequest();
} else {
- LOG4CXX_ERROR(logger_, "Applcation with hmi_app_id "
- << application_id() << "does not exist");
+ LOG4CXX_ERROR(logger_,
+ "Applcation with hmi_app_id " << application_id()
+ << "does not exist");
}
}
@@ -77,11 +79,11 @@ void NaviStartStreamRequest::on_event(const event_engine::Event& event) {
using namespace protocol_handler;
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->
- application_by_hmi_app(application_id());
+ ApplicationSharedPtr app =
+ application_manager_.application_by_hmi_app(application_id());
if (!app) {
LOG4CXX_ERROR(logger_,
- "NaviStartStreamRequest aborted. Application not found");
+ "NaviStartStreamRequest aborted. Application not found");
return;
}
@@ -95,19 +97,25 @@ void NaviStartStreamRequest::on_event(const event_engine::Event& event) {
message[strings::params][hmi_response::code].asInt());
if (hmi_apis::Common_Result::SUCCESS == code) {
- LOG4CXX_DEBUG(logger_, "NaviStartStreamResponse SUCCESS");
- if (ApplicationManagerImpl::instance()->
- HMILevelAllowsStreaming(app->app_id(), ServiceType::kMobileNav)) {
+ LOG4CXX_INFO(logger_, "NaviStartStreamResponse SUCCESS");
+ if (application_manager_.HMILevelAllowsStreaming(
+ app->app_id(), ServiceType::kMobileNav)) {
app->set_video_streaming_approved(true);
} else {
- LOG4CXX_DEBUG(logger_,
- "NaviStartStreamRequest aborted. Application can not stream");
+ LOG4CXX_DEBUG(
+ logger_,
+ "NaviStartStreamRequest aborted. Application can not stream");
}
+ break;
+ }
+ if (hmi_apis::Common_Result::REJECTED == code) {
+ LOG4CXX_INFO(logger_, "StartStream response REJECTED ");
+ SendRequest();
+ break;
}
- break;
}
default: {
- LOG4CXX_ERROR(logger_,"Received unknown event" << event.id());
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
return;
}
}
@@ -116,38 +124,46 @@ void NaviStartStreamRequest::on_event(const event_engine::Event& event) {
void NaviStartStreamRequest::onTimeOut() {
RetryStartSession();
- ApplicationManagerImpl::instance()->TerminateRequest(
- connection_key(), correlation_id());
+ application_manager_.TerminateRequest(connection_key(), correlation_id());
}
void NaviStartStreamRequest::RetryStartSession() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->
- application_by_hmi_app(application_id());
+ ApplicationSharedPtr app =
+ application_manager_.application_by_hmi_app(application_id());
if (!app) {
LOG4CXX_ERROR(logger_,
- "NaviStartStreamRequest aborted. Application not found");
+ "NaviStartStreamRequest aborted. Application not found");
+ return;
+ }
+
+ if (!app->video_streaming_allowed()) {
+ LOG4CXX_WARN(logger_, "Video streaming not allowed");
return;
}
+
if (app->video_streaming_approved()) {
- LOG4CXX_DEBUG(logger_, "NaviStartStream retry sequence stopped. "
- << "SUCCESS received");
+ LOG4CXX_INFO(logger_,
+ "NaviStartStream retry sequence stopped. "
+ << "SUCCESS received");
app->set_video_stream_retry_number(0);
return;
}
uint32_t curr_retry_number = app->video_stream_retry_number();
if (curr_retry_number < retry_number_ - 1) {
- LOG4CXX_DEBUG(logger_, "Send NaviStartStream retry. retry_number = "
- << curr_retry_number);
- MessageHelper::SendNaviStartStream(app->app_id());
+ LOG4CXX_DEBUG(
+ logger_,
+ "Send NaviStartStream retry. retry_number = " << curr_retry_number);
+ MessageHelper::SendNaviStartStream(app->app_id(), application_manager_);
app->set_video_stream_retry_number(++curr_retry_number);
} else {
- LOG4CXX_DEBUG(logger_, "NaviStartStream retry sequence stopped. "
- << "Attempts expired");
- app->set_video_stream_retry_number(0);
- ApplicationManagerImpl::instance()->EndNaviServices(app->app_id());
+ LOG4CXX_DEBUG(logger_,
+ "NaviStartStream retry sequence stopped. "
+ << "Attempts expired");
+
+ application_manager_.EndNaviServices(app->app_id());
}
}
diff --git a/src/components/application_manager/src/commands/hmi/navi_start_stream_response.cc b/src/components/application_manager/src/commands/hmi/navi_start_stream_response.cc
index a283891054..b0b9e672c3 100644
--- a/src/components/application_manager/src/commands/hmi/navi_start_stream_response.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_start_stream_response.cc
@@ -35,19 +35,18 @@ namespace application_manager {
namespace commands {
-NaviStartStreamResponse::NaviStartStreamResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+NaviStartStreamResponse::NaviStartStreamResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-NaviStartStreamResponse::~NaviStartStreamResponse() {
-}
+NaviStartStreamResponse::~NaviStartStreamResponse() {}
void NaviStartStreamResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::Navigation_StartStream);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/navi_stop_stream_request.cc b/src/components/application_manager/src/commands/hmi/navi_stop_stream_request.cc
index 3d74c27535..4b72ff28b4 100644
--- a/src/components/application_manager/src/commands/hmi/navi_stop_stream_request.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_stop_stream_request.cc
@@ -5,12 +5,10 @@ namespace application_manager {
namespace commands {
NaviStopStreamRequest::NaviStopStreamRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-NaviStopStreamRequest::~NaviStopStreamRequest() {
-}
+NaviStopStreamRequest::~NaviStopStreamRequest() {}
void NaviStopStreamRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/hmi/navi_stop_stream_response.cc b/src/components/application_manager/src/commands/hmi/navi_stop_stream_response.cc
index 0603df6a65..3a7fc75260 100644
--- a/src/components/application_manager/src/commands/hmi/navi_stop_stream_response.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_stop_stream_response.cc
@@ -35,16 +35,14 @@ namespace application_manager {
namespace commands {
-NaviStopStreamResponse::NaviStopStreamResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+NaviStopStreamResponse::NaviStopStreamResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-NaviStopStreamResponse::~NaviStopStreamResponse() {
-}
+NaviStopStreamResponse::~NaviStopStreamResponse() {}
void NaviStopStreamResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
-
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/navi_subscribe_way_points_request.cc b/src/components/application_manager/src/commands/hmi/navi_subscribe_way_points_request.cc
new file mode 100644
index 0000000000..f2106c8724
--- /dev/null
+++ b/src/components/application_manager/src/commands/hmi/navi_subscribe_way_points_request.cc
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/commands/hmi/navi_subscribe_way_points_request.h"
+
+namespace application_manager {
+
+namespace commands {
+
+NaviSubscribeWayPointsRequest::NaviSubscribeWayPointsRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
+
+NaviSubscribeWayPointsRequest::~NaviSubscribeWayPointsRequest() {}
+
+void NaviSubscribeWayPointsRequest::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ SendRequest();
+}
+
+} // namespace commands
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/hmi/navi_subscribe_way_points_response.cc b/src/components/application_manager/src/commands/hmi/navi_subscribe_way_points_response.cc
new file mode 100644
index 0000000000..f641051560
--- /dev/null
+++ b/src/components/application_manager/src/commands/hmi/navi_subscribe_way_points_response.cc
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/commands/hmi/navi_subscribe_way_points_response.h"
+#include "application_manager/event_engine/event.h"
+#include "interfaces/HMI_API.h"
+
+namespace application_manager {
+
+namespace commands {
+
+NaviSubscribeWayPointsResponse::NaviSubscribeWayPointsResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
+
+NaviSubscribeWayPointsResponse::~NaviSubscribeWayPointsResponse() {}
+
+void NaviSubscribeWayPointsResponse::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ event_engine::Event event(
+ hmi_apis::FunctionID::Navigation_SubscribeWayPoints);
+ event.set_smart_object(*message_);
+ event.raise(application_manager_.event_dispatcher());
+}
+
+} // namespace commands
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/hmi/navi_unsubscribe_way_points_request.cc b/src/components/application_manager/src/commands/hmi/navi_unsubscribe_way_points_request.cc
new file mode 100644
index 0000000000..e66069feef
--- /dev/null
+++ b/src/components/application_manager/src/commands/hmi/navi_unsubscribe_way_points_request.cc
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/commands/hmi/navi_unsubscribe_way_points_request.h"
+
+namespace application_manager {
+
+namespace commands {
+
+NaviUnSubscribeWayPointsRequest::NaviUnSubscribeWayPointsRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
+
+NaviUnSubscribeWayPointsRequest::~NaviUnSubscribeWayPointsRequest() {}
+
+void NaviUnSubscribeWayPointsRequest::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ SendRequest();
+}
+
+} // namespace commands
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/hmi/navi_unsubscribe_way_points_response.cc b/src/components/application_manager/src/commands/hmi/navi_unsubscribe_way_points_response.cc
new file mode 100644
index 0000000000..61216321e8
--- /dev/null
+++ b/src/components/application_manager/src/commands/hmi/navi_unsubscribe_way_points_response.cc
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/commands/hmi/navi_unsubscribe_way_points_response.h"
+#include "application_manager/event_engine/event.h"
+#include "interfaces/MOBILE_API.h"
+#include "interfaces/HMI_API.h"
+
+namespace application_manager {
+
+namespace commands {
+
+NaviUnsubscribeWayPointsResponse::NaviUnsubscribeWayPointsResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
+
+NaviUnsubscribeWayPointsResponse::~NaviUnsubscribeWayPointsResponse() {}
+
+void NaviUnsubscribeWayPointsResponse::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ event_engine::Event event(
+ hmi_apis::FunctionID::Navigation_UnsubscribeWayPoints);
+ event.set_smart_object(*message_);
+ event.raise(application_manager_.event_dispatcher());
+}
+
+} // namespace commands
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/hmi/navi_update_turn_list_request.cc b/src/components/application_manager/src/commands/hmi/navi_update_turn_list_request.cc
index 37037245fa..c37c3d12f9 100644
--- a/src/components/application_manager/src/commands/hmi/navi_update_turn_list_request.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_update_turn_list_request.cc
@@ -37,11 +37,10 @@ namespace application_manager {
namespace commands {
NaviUpdateTurnListRequest::NaviUpdateTurnListRequest(
- const MessageSharedPtr& message) : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-NaviUpdateTurnListRequest::~NaviUpdateTurnListRequest() {
-}
+NaviUpdateTurnListRequest::~NaviUpdateTurnListRequest() {}
void NaviUpdateTurnListRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void NaviUpdateTurnListRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/navi_update_turn_list_response.cc b/src/components/application_manager/src/commands/hmi/navi_update_turn_list_response.cc
index d196db93e9..faf5719d05 100644
--- a/src/components/application_manager/src/commands/hmi/navi_update_turn_list_response.cc
+++ b/src/components/application_manager/src/commands/hmi/navi_update_turn_list_response.cc
@@ -31,6 +31,7 @@
*/
#include "application_manager/commands/hmi/navi_update_turn_list_response.h"
#include "application_manager/event_engine/event.h"
+
#include "interfaces/MOBILE_API.h"
namespace application_manager {
@@ -38,18 +39,17 @@ namespace application_manager {
namespace commands {
NaviUpdateTurnListResponse::NaviUpdateTurnListResponse(
- const MessageSharedPtr& message) : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-NaviUpdateTurnListResponse::~NaviUpdateTurnListResponse() {
-}
+NaviUpdateTurnListResponse::~NaviUpdateTurnListResponse() {}
void NaviUpdateTurnListResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::Navigation_UpdateTurnList);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/notification_from_hmi.cc b/src/components/application_manager/src/commands/hmi/notification_from_hmi.cc
index 9c483459e1..64eb63fde8 100644
--- a/src/components/application_manager/src/commands/hmi/notification_from_hmi.cc
+++ b/src/components/application_manager/src/commands/hmi/notification_from_hmi.cc
@@ -31,22 +31,21 @@
*/
#include "application_manager/commands/hmi/notification_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
#include "smart_objects/smart_object.h"
namespace application_manager {
namespace commands {
-NotificationFromHMI::NotificationFromHMI(const MessageSharedPtr& message)
- : CommandImpl(message) {
-
+NotificationFromHMI::NotificationFromHMI(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandImpl(message, application_manager) {
// Replace HMI app id with Mobile connection id
- ApplicationManagerImpl::instance()->ReplaceHMIByMobileAppId(*message);
+ ReplaceHMIByMobileAppId(*message);
}
-NotificationFromHMI::~NotificationFromHMI() {
-}
+NotificationFromHMI::~NotificationFromHMI() {}
bool NotificationFromHMI::Init() {
return true;
@@ -56,21 +55,18 @@ bool NotificationFromHMI::CleanUp() {
return true;
}
-void NotificationFromHMI::Run() {
-}
+void NotificationFromHMI::Run() {}
void NotificationFromHMI::SendNotificationToMobile(
const MessageSharedPtr& message) {
-
(*message)[strings::params][strings::message_type] =
static_cast<int32_t>(application_manager::MessageType::kNotification);
- ApplicationManagerImpl::instance()->ManageMobileCommand(message);
+ application_manager_.ManageMobileCommand(message, ORIGIN_SDL);
}
void NotificationFromHMI::CreateHMIRequest(
const hmi_apis::FunctionID::eType& function_id,
const smart_objects::SmartObject& msg_params) const {
-
smart_objects::SmartObjectSPtr result = new smart_objects::SmartObject;
if (!result) {
LOG4CXX_ERROR(logger_, "Memory allocation failed.");
@@ -78,8 +74,8 @@ void NotificationFromHMI::CreateHMIRequest(
}
// get hmi correlation id for chaining further request from this object
- const uint32_t hmi_correlation_id_ = ApplicationManagerImpl::instance()
- ->GetNextHMICorrelationID();
+ const uint32_t hmi_correlation_id_ =
+ application_manager_.GetNextHMICorrelationID();
NsSmartDeviceLink::NsSmartObjects::SmartObject& request = *result;
request[strings::params][strings::message_type] =
@@ -94,7 +90,7 @@ void NotificationFromHMI::CreateHMIRequest(
request[strings::msg_params] = msg_params;
- if (!ApplicationManagerImpl::instance()->ManageHMICommand(result)) {
+ if (!application_manager_.ManageHMICommand(result)) {
LOG4CXX_ERROR(logger_, "Unable to send request");
return;
}
diff --git a/src/components/application_manager/src/commands/hmi/notification_to_hmi.cc b/src/components/application_manager/src/commands/hmi/notification_to_hmi.cc
index e4f8920ec9..f1e933b7ef 100644
--- a/src/components/application_manager/src/commands/hmi/notification_to_hmi.cc
+++ b/src/components/application_manager/src/commands/hmi/notification_to_hmi.cc
@@ -31,21 +31,20 @@
*/
#include "application_manager/commands/hmi/notification_to_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
-NotificationToHMI::NotificationToHMI(const MessageSharedPtr& message)
- : CommandImpl(message) {
-
+NotificationToHMI::NotificationToHMI(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandImpl(message, application_manager) {
// Replace Mobile connection id with HMI app id
- ApplicationManagerImpl::instance()->ReplaceMobileByHMIAppId(*(message.get()));
+ ReplaceMobileByHMIAppId(*(message.get()));
}
-NotificationToHMI::~NotificationToHMI() {
-}
+NotificationToHMI::~NotificationToHMI() {}
bool NotificationToHMI::Init() {
return true;
@@ -55,13 +54,12 @@ bool NotificationToHMI::CleanUp() {
return true;
}
-void NotificationToHMI::Run() {
-}
+void NotificationToHMI::Run() {}
void NotificationToHMI::SendNotification() {
(*message_)[strings::params][strings::protocol_type] = hmi_protocol_type_;
(*message_)[strings::params][strings::protocol_version] = protocol_version_;
- ApplicationManagerImpl::instance()->SendMessageToHMI(message_);
+ application_manager_.SendMessageToHMI(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/on_allow_sdl_functionality_notification.cc b/src/components/application_manager/src/commands/hmi/on_allow_sdl_functionality_notification.cc
index 506413ce1e..70e5e7cefd 100644
--- a/src/components/application_manager/src/commands/hmi/on_allow_sdl_functionality_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_allow_sdl_functionality_notification.cc
@@ -31,6 +31,7 @@
*/
#include "application_manager/commands/hmi/on_allow_sdl_functionality_notification.h"
+#include "application_manager/application_manager.h"
#include "application_manager/policies/policy_handler.h"
namespace application_manager {
@@ -38,20 +39,18 @@ namespace application_manager {
namespace commands {
OnAllowSDLFunctionalityNotification::OnAllowSDLFunctionalityNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnAllowSDLFunctionalityNotification::~OnAllowSDLFunctionalityNotification() {
-}
+OnAllowSDLFunctionalityNotification::~OnAllowSDLFunctionalityNotification() {}
void OnAllowSDLFunctionalityNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- uint32_t device_id = 0;
+ std::string device_id;
if ((*message_)[strings::msg_params].keyExists("device")) {
- device_id = (*message_)[strings::msg_params]["device"]["id"].asUInt();
+ device_id = (*message_)[strings::msg_params]["device"]["id"].asString();
}
- policy::PolicyHandler::instance()->OnAllowSDLFunctionalityNotification(
+ application_manager_.GetPolicyHandler().OnAllowSDLFunctionalityNotification(
(*message_)[strings::msg_params][hmi_response::allowed].asBool(),
device_id);
}
@@ -59,4 +58,3 @@ void OnAllowSDLFunctionalityNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_app_activated_notification.cc b/src/components/application_manager/src/commands/hmi/on_app_activated_notification.cc
index 0ff76a45f5..76252a50fd 100644
--- a/src/components/application_manager/src/commands/hmi/on_app_activated_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_app_activated_notification.cc
@@ -31,7 +31,7 @@
*/
#include "application_manager/commands/hmi/on_app_activated_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/message_helper.h"
#include "interfaces/HMI_API.h"
@@ -40,22 +40,19 @@ namespace application_manager {
namespace commands {
OnAppActivatedNotification::OnAppActivatedNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnAppActivatedNotification::~OnAppActivatedNotification() {
-}
+OnAppActivatedNotification::~OnAppActivatedNotification() {}
void OnAppActivatedNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- uint32_t app_id = ((*message_)[strings::msg_params][strings::app_id]).asUInt();
- ApplicationManagerImpl::instance()->SetState<true>(app_id,
- mobile_apis::HMILevel::HMI_FULL
- );
+ event_engine::Event event(
+ hmi_apis::FunctionID::BasicCommunication_OnAppActivated);
+ event.set_smart_object(*message_);
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_app_deactivated_notification.cc b/src/components/application_manager/src/commands/hmi/on_app_deactivated_notification.cc
index 3df1c566d9..86ce6a830c 100644
--- a/src/components/application_manager/src/commands/hmi/on_app_deactivated_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_app_deactivated_notification.cc
@@ -31,10 +31,10 @@
*/
#include "application_manager/commands/hmi/on_app_deactivated_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
-#include "config_profile/profile.h"
+
#include "utils/helpers.h"
namespace application_manager {
@@ -42,77 +42,19 @@ namespace application_manager {
namespace commands {
OnAppDeactivatedNotification::OnAppDeactivatedNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnAppDeactivatedNotification::~OnAppDeactivatedNotification() {
-}
+OnAppDeactivatedNotification::~OnAppDeactivatedNotification() {}
void OnAppDeactivatedNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
-
- uint32_t app_id = (*message_)[strings::msg_params][strings::app_id].asUInt();
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(app_id);
-
- if (!app.valid()) {
- LOG4CXX_ERROR(logger_, "Application with id " << app_id << " not found");
- return;
- }
-
- using namespace hmi_apis;
- using namespace mobile_apis;
- using namespace helpers;
-
- Common_DeactivateReason::eType deactivate_reason =
- static_cast<Common_DeactivateReason::eType>
- ((*message_)[strings::msg_params][hmi_request::reason].asInt());
-
- if (!((Common_DeactivateReason::AUDIO == deactivate_reason ||
- Common_DeactivateReason::PHONECALL == deactivate_reason) &&
- HMILevel::HMI_LIMITED == app->hmi_level())) {
- app = ApplicationManagerImpl::instance()->active_application();
-
- if (!app.valid()) {
- LOG4CXX_ERROR_EXT(logger_, "No active application");
- return;
- }
- if (app_id != app->app_id()) {
- LOG4CXX_ERROR_EXT(logger_, "Wrong application id");
- return;
- }
- }
-
- if (HMILevel::HMI_NONE == app->hmi_level()) {
- return;
- }
- HmiStatePtr regular = app->RegularHmiState();
- DCHECK_OR_RETURN_VOID(regular);
- HmiStatePtr new_regular(new HmiState(*regular));
-
- switch ((*message_)[strings::msg_params][hmi_request::reason].asInt()) {
- case hmi_apis::Common_DeactivateReason::AUDIO: {
- new_regular->set_audio_streaming_state(mobile_api::AudioStreamingState::NOT_AUDIBLE);
- new_regular->set_hmi_level(mobile_api::HMILevel::HMI_BACKGROUND);
- break;
- }
- case hmi_apis::Common_DeactivateReason::NAVIGATIONMAP:
- case hmi_apis::Common_DeactivateReason::PHONEMENU:
- case hmi_apis::Common_DeactivateReason::SYNCSETTINGS:
- case hmi_apis::Common_DeactivateReason::GENERAL: {
- if (app->IsAudioApplication()) {
- new_regular->set_hmi_level(mobile_api::HMILevel::HMI_LIMITED);
- } else {
- new_regular->set_hmi_level(mobile_api::HMILevel::HMI_BACKGROUND);
- }
- }
- }
- ApplicationManagerImpl::instance()->SetState<false>(app->app_id(), new_regular);
-
+ event_engine::Event event(
+ hmi_apis::FunctionID::BasicCommunication_OnAppDeactivated);
+ event.set_smart_object(*message_);
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_app_permission_changed_notification.cc b/src/components/application_manager/src/commands/hmi/on_app_permission_changed_notification.cc
index c786b486f4..fa7293513a 100644
--- a/src/components/application_manager/src/commands/hmi/on_app_permission_changed_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_app_permission_changed_notification.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
OnAppPermissionChangedNotification::OnAppPermissionChangedNotification(
- const MessageSharedPtr& message)
- : NotificationToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationToHMI(message, application_manager) {}
-OnAppPermissionChangedNotification::~OnAppPermissionChangedNotification() {
-}
+OnAppPermissionChangedNotification::~OnAppPermissionChangedNotification() {}
void OnAppPermissionChangedNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/hmi/on_app_permission_consent_notification.cc b/src/components/application_manager/src/commands/hmi/on_app_permission_consent_notification.cc
index 69a18200fa..0efc1aee8a 100644
--- a/src/components/application_manager/src/commands/hmi/on_app_permission_consent_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_app_permission_consent_notification.cc
@@ -32,20 +32,19 @@
*/
#include "application_manager/commands/hmi/on_app_permission_consent_notification.h"
-#include "application_manager/application_manager_impl.h"
-#include "application_manager/message_helper.h"
+#include "application_manager/application_manager.h"
#include "application_manager/policies/policy_handler.h"
+#include "application_manager/message_helper.h"
namespace application_manager {
namespace commands {
-OnAppPermissionConsentNotification::OnAppPermissionConsentNotification(const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+OnAppPermissionConsentNotification::OnAppPermissionConsentNotification(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnAppPermissionConsentNotification::~OnAppPermissionConsentNotification() {
-}
+OnAppPermissionConsentNotification::~OnAppPermissionConsentNotification() {}
void OnAppPermissionConsentNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -62,28 +61,29 @@ void OnAppPermissionConsentNotification::Run() {
if (msg_params.keyExists("consentedFunctions")) {
smart_objects::SmartArray* user_consent =
- msg_params["consentedFunctions"].asArray();
-
- smart_objects::SmartArray::const_iterator it = user_consent->begin();
- smart_objects::SmartArray::const_iterator it_end = user_consent->end();
- for (; it != it_end; ++it) {
- policy::FunctionalGroupPermission permissions;
- permissions.group_id = (*it)["id"].asInt();
- permissions.group_alias = (*it)["name"].asString();
- if ((*it).keyExists("allowed")) {
- permissions.state = (*it)["allowed"].asBool() ? policy::kGroupAllowed :
- policy::kGroupDisallowed;
- } else {
- permissions.state = policy::kGroupUndefined;
- }
+ msg_params["consentedFunctions"].asArray();
+
+ smart_objects::SmartArray::const_iterator it = user_consent->begin();
+ smart_objects::SmartArray::const_iterator it_end = user_consent->end();
+ for (; it != it_end; ++it) {
+ policy::FunctionalGroupPermission permissions;
+ permissions.group_id = (*it)["id"].asInt();
+ permissions.group_alias = (*it)["name"].asString();
+ if ((*it).keyExists("allowed")) {
+ permissions.state = (*it)["allowed"].asBool()
+ ? policy::kGroupAllowed
+ : policy::kGroupDisallowed;
+ } else {
+ permissions.state = policy::kGroupUndefined;
+ }
permission_consent.group_permissions.push_back(permissions);
}
permission_consent.consent_source = msg_params["source"].asString();
- policy::PolicyHandler::instance()->OnAppPermissionConsent(connection_key,
- permission_consent);
+ application_manager_.GetPolicyHandler().OnAppPermissionConsent(
+ connection_key, permission_consent);
}
}
diff --git a/src/components/application_manager/src/commands/hmi/on_app_registered_notification.cc b/src/components/application_manager/src/commands/hmi/on_app_registered_notification.cc
index af3f45fed0..a97e19b556 100644
--- a/src/components/application_manager/src/commands/hmi/on_app_registered_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_app_registered_notification.cc
@@ -31,30 +31,28 @@
*/
#include "application_manager/commands/hmi/on_app_registered_notification.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
OnAppRegisteredNotification::OnAppRegisteredNotification(
- const MessageSharedPtr& message) : NotificationToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationToHMI(message, application_manager) {}
-OnAppRegisteredNotification::~OnAppRegisteredNotification() {
-}
+OnAppRegisteredNotification::~OnAppRegisteredNotification() {}
void OnAppRegisteredNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
// SDL must notify system about app registration before any dependent actions
// will be started
SendNotification();
- event_engine::Event event(hmi_apis::FunctionID::BasicCommunication_OnAppRegistered);
+ event_engine::Event event(
+ hmi_apis::FunctionID::BasicCommunication_OnAppRegistered);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_app_unregistered_notification.cc b/src/components/application_manager/src/commands/hmi/on_app_unregistered_notification.cc
index 571c6f381c..10ea1ea303 100644
--- a/src/components/application_manager/src/commands/hmi/on_app_unregistered_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_app_unregistered_notification.cc
@@ -31,7 +31,7 @@
*/
#include "application_manager/commands/hmi/on_app_unregistered_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/event_engine/event.h"
namespace application_manager {
@@ -39,19 +39,19 @@ namespace application_manager {
namespace commands {
OnAppUnregisteredNotification::OnAppUnregisteredNotification(
- const MessageSharedPtr& message) : NotificationToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationToHMI(message, application_manager) {}
-OnAppUnregisteredNotification::~OnAppUnregisteredNotification() {
-}
+OnAppUnregisteredNotification::~OnAppUnregisteredNotification() {}
void OnAppUnregisteredNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- //sending event for delete VRCommand on PerformInteraction
- event_engine::Event event(hmi_apis::FunctionID::BasicCommunication_OnAppUnregistered);
+ // sending event for delete VRCommand on PerformInteraction
+ event_engine::Event event(
+ hmi_apis::FunctionID::BasicCommunication_OnAppUnregistered);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
SendNotification();
}
@@ -59,4 +59,3 @@ void OnAppUnregisteredNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_audio_data_streaming_notification.cc b/src/components/application_manager/src/commands/hmi/on_audio_data_streaming_notification.cc
index d94d298509..c3e81bdc30 100644
--- a/src/components/application_manager/src/commands/hmi/on_audio_data_streaming_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_audio_data_streaming_notification.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
OnAudioDataStreamingNotification::OnAudioDataStreamingNotification(
- const MessageSharedPtr& message)
- : NotificationToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationToHMI(message, application_manager) {}
-OnAudioDataStreamingNotification::~OnAudioDataStreamingNotification() {
-}
+OnAudioDataStreamingNotification::~OnAudioDataStreamingNotification() {}
void OnAudioDataStreamingNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +50,3 @@ void OnAudioDataStreamingNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_button_event_notification.cc b/src/components/application_manager/src/commands/hmi/on_button_event_notification.cc
index 2beffc2bdd..fc8d5989a1 100644
--- a/src/components/application_manager/src/commands/hmi/on_button_event_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_button_event_notification.cc
@@ -31,7 +31,7 @@
*/
#include "application_manager/commands/hmi/on_button_event_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "utils/logger.h"
@@ -42,8 +42,8 @@ namespace commands {
namespace hmi {
OnButtonEventNotification::OnButtonEventNotification(
- const MessageSharedPtr& message) : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
void OnButtonEventNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -59,4 +59,3 @@ void OnButtonEventNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_button_press_notification.cc b/src/components/application_manager/src/commands/hmi/on_button_press_notification.cc
index 261aa68ee7..abff87c962 100644
--- a/src/components/application_manager/src/commands/hmi/on_button_press_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_button_press_notification.cc
@@ -31,7 +31,7 @@
*/
#include "application_manager/commands/hmi/on_button_press_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "utils/logger.h"
#include "application_manager/event_engine/event.h"
@@ -43,14 +43,14 @@ namespace commands {
namespace hmi {
OnButtonPressNotification::OnButtonPressNotification(
- const MessageSharedPtr& message) : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
void OnButtonPressNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::Buttons_OnButtonPress);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
(*message_)[strings::params][strings::function_id] =
static_cast<int>(mobile_apis::FunctionID::eType::OnButtonPressID);
SendNotificationToMobile(message_);
@@ -61,4 +61,3 @@ void OnButtonPressNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_button_subscription_notification.cc b/src/components/application_manager/src/commands/hmi/on_button_subscription_notification.cc
index 3c31de054e..aae994ea34 100644
--- a/src/components/application_manager/src/commands/hmi/on_button_subscription_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_button_subscription_notification.cc
@@ -39,11 +39,10 @@ namespace commands {
namespace hmi {
OnButtonSubscriptionNotification::OnButtonSubscriptionNotification(
- const MessageSharedPtr& message) : NotificationToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationToHMI(message, application_manager) {}
-OnButtonSubscriptionNotification::~OnButtonSubscriptionNotification() {
-}
+OnButtonSubscriptionNotification::~OnButtonSubscriptionNotification() {}
void OnButtonSubscriptionNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -56,4 +55,3 @@ void OnButtonSubscriptionNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_device_chosen_notification.cc b/src/components/application_manager/src/commands/hmi/on_device_chosen_notification.cc
index 441538bee2..83ec785a9d 100644
--- a/src/components/application_manager/src/commands/hmi/on_device_chosen_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_device_chosen_notification.cc
@@ -31,24 +31,22 @@
*/
#include "application_manager/commands/hmi/on_device_chosen_notification.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
OnDeviceChosenNotification::OnDeviceChosenNotification(
- const MessageSharedPtr& message) : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnDeviceChosenNotification::~OnDeviceChosenNotification() {
-}
+OnDeviceChosenNotification::~OnDeviceChosenNotification() {}
void OnDeviceChosenNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
if ((*message_)[strings::msg_params].keyExists(strings::device_info)) {
- ApplicationManagerImpl::instance()->ConnectToDevice(
+ application_manager_.ConnectToDevice(
(*message_)[strings::msg_params][strings::device_info][strings::id]
.asString());
}
@@ -57,4 +55,3 @@ void OnDeviceChosenNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_device_state_changed_notification.cc b/src/components/application_manager/src/commands/hmi/on_device_state_changed_notification.cc
index b41eb6b861..346c05032b 100644
--- a/src/components/application_manager/src/commands/hmi/on_device_state_changed_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_device_state_changed_notification.cc
@@ -32,44 +32,46 @@
#include <algorithm>
#include "application_manager/commands/hmi/on_device_state_changed_notification.h"
-#include "application_manager/policies/policy_handler.h"
+#include "application_manager/application_manager.h"
#include "application_manager/message_helper.h"
#include "interfaces/HMI_API.h"
#include "encryption/hashing.h"
namespace {
- // TODO(AOleynik) : replace this !!!
- void check_zero(const char& a, const char& b, std::string& bt_mac) {
- if ('0' != a && '0' == b) {
- bt_mac.push_back(a);
- bt_mac.push_back(b);
- } else if ('0' == a) {
- bt_mac.push_back(b);
- } else {
- bt_mac.push_back(a);
- bt_mac.push_back(b);
- }
- }
-
- std::string convert_to_bt_mac(std::string& deviceInternalId) {
- std::transform(deviceInternalId.begin(), deviceInternalId.end(),deviceInternalId.begin(), ::tolower);
+// TODO(AOleynik) : replace this !!!
+void check_zero(const char& a, const char& b, std::string& bt_mac) {
+ if ('0' != a && '0' == b) {
+ bt_mac.push_back(a);
+ bt_mac.push_back(b);
+ } else if ('0' == a) {
+ bt_mac.push_back(b);
+ } else {
+ bt_mac.push_back(a);
+ bt_mac.push_back(b);
+ }
+}
- std::string bt_mac;
- check_zero(deviceInternalId[10], deviceInternalId[11], bt_mac);
- bt_mac.push_back(':');
- check_zero(deviceInternalId[8], deviceInternalId[9], bt_mac);
- bt_mac.push_back(':');
- check_zero(deviceInternalId[6], deviceInternalId[7], bt_mac);
- bt_mac.push_back(':');
- check_zero(deviceInternalId[4], deviceInternalId[5], bt_mac);
- bt_mac.push_back(':');
- check_zero(deviceInternalId[2], deviceInternalId[3], bt_mac);
- bt_mac.push_back(':');
- check_zero(deviceInternalId[0], deviceInternalId[1], bt_mac);
+std::string convert_to_bt_mac(std::string& deviceInternalId) {
+ std::transform(deviceInternalId.begin(),
+ deviceInternalId.end(),
+ deviceInternalId.begin(),
+ ::tolower);
- return bt_mac;
- }
+ std::string bt_mac;
+ check_zero(deviceInternalId[10], deviceInternalId[11], bt_mac);
+ bt_mac.push_back(':');
+ check_zero(deviceInternalId[8], deviceInternalId[9], bt_mac);
+ bt_mac.push_back(':');
+ check_zero(deviceInternalId[6], deviceInternalId[7], bt_mac);
+ bt_mac.push_back(':');
+ check_zero(deviceInternalId[4], deviceInternalId[5], bt_mac);
+ bt_mac.push_back(':');
+ check_zero(deviceInternalId[2], deviceInternalId[3], bt_mac);
+ bt_mac.push_back(':');
+ check_zero(deviceInternalId[0], deviceInternalId[1], bt_mac);
+ return bt_mac;
+}
}
namespace application_manager {
@@ -77,35 +79,34 @@ namespace application_manager {
namespace commands {
OnDeviceStateChangedNotification::OnDeviceStateChangedNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnDeviceStateChangedNotification::~OnDeviceStateChangedNotification() {
-}
+OnDeviceStateChangedNotification::~OnDeviceStateChangedNotification() {}
void OnDeviceStateChangedNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- if ((*message_)[strings::msg_params]["deviceState"]
- == hmi_apis::Common_DeviceState::UNPAIRED) {
- // It is expected, that "deviceInternalId" is the device MAC address in
- // form XXXXXXXXXX
- std::string device_id = (*message_)[strings::msg_params]["deviceInternalId"]
- .asString();
+ if ((*message_)[strings::msg_params]["deviceState"] ==
+ hmi_apis::Common_DeviceState::UNPAIRED) {
+ // It is expected, that "deviceInternalId" is the device MAC address in
+ // form XXXXXXXXXX
+ std::string device_id =
+ (*message_)[strings::msg_params]["deviceInternalId"].asString();
if (device_id.empty()) {
if ((*message_)[strings::msg_params].keyExists("deviceId")) {
- device_id = (*message_)[strings::msg_params]["deviceId"]["id"].asString();
+ device_id =
+ (*message_)[strings::msg_params]["deviceId"]["id"].asString();
}
} else {
- // Policy uses hashed MAC address as device_id
- LOG4CXX_DEBUG(logger_,"Device_id from HMI: " << device_id);
- std::string bt_mac = convert_to_bt_mac(device_id);
- LOG4CXX_DEBUG(logger_,"Device_id as BT MAC: " << bt_mac);
- device_id = encryption::MakeHash(bt_mac);
- LOG4CXX_DEBUG(logger_,"Device_id hashed as BT MAC : " << device_id);
+ // Policy uses hashed MAC address as device_id
+ LOG4CXX_DEBUG(logger_, "Device_id from HMI: " << device_id);
+ std::string bt_mac = convert_to_bt_mac(device_id);
+ LOG4CXX_DEBUG(logger_, "Device_id as BT MAC: " << bt_mac);
+ device_id = encryption::MakeHash(bt_mac);
+ LOG4CXX_DEBUG(logger_, "Device_id hashed as BT MAC : " << device_id);
}
- policy::PolicyHandler::instance()->RemoveDevice(device_id);
+ application_manager_.GetPolicyHandler().RemoveDevice(device_id);
}
}
diff --git a/src/components/application_manager/src/commands/hmi/on_driver_distraction_notification.cc b/src/components/application_manager/src/commands/hmi/on_driver_distraction_notification.cc
index ceb6e1b586..4c322c456f 100644
--- a/src/components/application_manager/src/commands/hmi/on_driver_distraction_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_driver_distraction_notification.cc
@@ -32,7 +32,7 @@
#include <set>
#include "application_manager/commands/hmi/on_driver_distraction_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
@@ -44,27 +44,24 @@ namespace commands {
namespace hmi {
OnDriverDistractionNotification::OnDriverDistractionNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnDriverDistractionNotification::~OnDriverDistractionNotification() {
-}
+OnDriverDistractionNotification::~OnDriverDistractionNotification() {}
void OnDriverDistractionNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
const hmi_apis::Common_DriverDistractionState::eType state =
static_cast<hmi_apis::Common_DriverDistractionState::eType>(
- (*message_)[strings::msg_params][hmi_notification::state]
- .asInt());
- ApplicationManagerImpl::instance()->set_driver_distraction(state);
+ (*message_)[strings::msg_params][hmi_notification::state].asInt());
+ application_manager_.set_driver_distraction(state);
smart_objects::SmartObjectSPtr on_driver_distraction =
new smart_objects::SmartObject();
if (!on_driver_distraction) {
- LOG4CXX_ERROR_EXT(logger_, "NULL pointer");
+ LOG4CXX_ERROR(logger_, "NULL pointer");
return;
}
@@ -74,15 +71,15 @@ void OnDriverDistractionNotification::Run() {
(*on_driver_distraction)[strings::msg_params][mobile_notification::state] =
state;
- ApplicationManagerImpl::ApplicationListAccessor accessor;
- const ApplicationManagerImpl::ApplictionSet applications = accessor.applications();
+ const ApplicationSet applications =
+ application_manager_.applications().GetData();
- ApplicationManagerImpl::ApplictionSetConstIt it = applications.begin();
+ ApplicationSetConstIt it = applications.begin();
for (; applications.end() != it; ++it) {
const ApplicationSharedPtr app = *it;
if (app) {
- (*on_driver_distraction)[strings::params]
- [strings::connection_key] = app->app_id();
+ (*on_driver_distraction)[strings::params][strings::connection_key] =
+ app->app_id();
SendNotificationToMobile(on_driver_distraction);
}
}
@@ -93,4 +90,3 @@ void OnDriverDistractionNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_emergency_event_notification.cc b/src/components/application_manager/src/commands/hmi/on_emergency_event_notification.cc
deleted file mode 100644
index 47b80a1d2b..0000000000
--- a/src/components/application_manager/src/commands/hmi/on_emergency_event_notification.cc
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "application_manager/commands/hmi/on_emergency_event_notification.h"
-#include "application_manager/application_manager_impl.h"
-
-namespace application_manager {
-
-namespace commands {
-
-OnEmergencyEventNotification::OnEmergencyEventNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
-
-OnEmergencyEventNotification::~OnEmergencyEventNotification() {
-}
-
-void OnEmergencyEventNotification::Run() {
- LOG4CXX_AUTO_TRACE(logger_);
- event_engine::Event event(hmi_apis::FunctionID::BasicCommunication_OnEmergencyEvent);
- event.set_smart_object(*message_);
- event.raise();
-}
-
-} // namespace commands
-
-} // namespace application_manager
-
-
diff --git a/src/components/application_manager/src/commands/hmi/on_event_changed_notification.cc b/src/components/application_manager/src/commands/hmi/on_event_changed_notification.cc
new file mode 100644
index 0000000000..c211ffde50
--- /dev/null
+++ b/src/components/application_manager/src/commands/hmi/on_event_changed_notification.cc
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/commands/hmi/on_event_changed_notification.h"
+
+namespace application_manager {
+
+namespace commands {
+
+OnEventChangedNotification::OnEventChangedNotification(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
+
+OnEventChangedNotification::~OnEventChangedNotification() {}
+
+void OnEventChangedNotification::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ event_engine::Event event(
+ hmi_apis::FunctionID::BasicCommunication_OnEventChanged);
+ event.set_smart_object(*message_);
+ event.raise(application_manager_.event_dispatcher());
+}
+
+} // namespace commands
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/hmi/on_exit_all_applications_notification.cc b/src/components/application_manager/src/commands/hmi/on_exit_all_applications_notification.cc
index 7c09800d21..682093cef9 100644
--- a/src/components/application_manager/src/commands/hmi/on_exit_all_applications_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_exit_all_applications_notification.cc
@@ -36,20 +36,19 @@
#include <unistd.h>
#include <signal.h>
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
+#include "application_manager/resumption/resume_ctrl.h"
#include "interfaces/HMI_API.h"
-
namespace application_manager {
namespace commands {
OnExitAllApplicationsNotification::OnExitAllApplicationsNotification(
- const MessageSharedPtr& message) : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnExitAllApplicationsNotification::~OnExitAllApplicationsNotification() {
-}
+OnExitAllApplicationsNotification::~OnExitAllApplicationsNotification() {}
void OnExitAllApplicationsNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -62,8 +61,6 @@ void OnExitAllApplicationsNotification::Run() {
mobile_api::AppInterfaceUnregisteredReason::eType mob_reason =
mobile_api::AppInterfaceUnregisteredReason::INVALID_ENUM;
- ApplicationManagerImpl* app_manager = ApplicationManagerImpl::instance();
-
switch (reason) {
case hmi_apis::Common_ApplicationsCloseReason::IGNITION_OFF: {
mob_reason = mobile_api::AppInterfaceUnregisteredReason::IGNITION_OFF;
@@ -81,17 +78,18 @@ void OnExitAllApplicationsNotification::Run() {
SendOnSDLPersistenceComplete();
return;
}
- default : {
+ default: {
LOG4CXX_ERROR(logger_, "Unknown Application close reason" << reason);
return;
}
}
- app_manager->SetUnregisterAllApplicationsReason(mob_reason);
+ application_manager_.SetUnregisterAllApplicationsReason(mob_reason);
if (mobile_api::AppInterfaceUnregisteredReason::MASTER_RESET == mob_reason ||
- mobile_api::AppInterfaceUnregisteredReason::FACTORY_DEFAULTS == mob_reason) {
- app_manager->HeadUnitReset(mob_reason);
+ mobile_api::AppInterfaceUnregisteredReason::FACTORY_DEFAULTS ==
+ mob_reason) {
+ application_manager_.HeadUnitReset(mob_reason);
}
kill(getpid(), SIGINT);
}
@@ -103,14 +101,14 @@ void OnExitAllApplicationsNotification::SendOnSDLPersistenceComplete() {
new smart_objects::SmartObject(smart_objects::SmartType_Map);
(*message)[strings::params][strings::function_id] =
hmi_apis::FunctionID::BasicCommunication_OnSDLPersistenceComplete;
- (*message)[strings::params][strings::message_type] = MessageType::kNotification;
+ (*message)[strings::params][strings::message_type] =
+ MessageType::kNotification;
(*message)[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
+ application_manager_.GetNextHMICorrelationID();
- ApplicationManagerImpl::instance()->ManageHMICommand(message);
+ application_manager_.ManageHMICommand(message);
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_exit_application_notification.cc b/src/components/application_manager/src/commands/hmi/on_exit_application_notification.cc
index d64ba3adf9..a7b6b9a2cd 100644
--- a/src/components/application_manager/src/commands/hmi/on_exit_application_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_exit_application_notification.cc
@@ -31,8 +31,9 @@
*/
#include "application_manager/commands/hmi/on_exit_application_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
+#include "application_manager/state_controller.h"
#include "application_manager/message_helper.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
@@ -42,39 +43,70 @@ namespace application_manager {
namespace commands {
OnExitApplicationNotification::OnExitApplicationNotification(
- const MessageSharedPtr& message) : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnExitApplicationNotification::~OnExitApplicationNotification() {
-}
+OnExitApplicationNotification::~OnExitApplicationNotification() {}
void OnExitApplicationNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl* app_mgr = ApplicationManagerImpl::instance();
- ApplicationSharedPtr app_impl = app_mgr->application(
- (*message_)[strings::msg_params][strings::app_id].asUInt());
+ using namespace mobile_apis;
+ using namespace hmi_apis;
+
+ uint32_t app_id = (*message_)[strings::msg_params][strings::app_id].asUInt();
+ ApplicationSharedPtr app_impl = application_manager_.application(app_id);
+
if (!(app_impl.valid())) {
LOG4CXX_ERROR(logger_, "Application does not exist");
return;
}
- hmi_apis::Common_ApplicationToNONEReason::eType reason;
- reason = static_cast<hmi_apis::Common_ApplicationToNONEReason::eType>
- ((*message_)[strings::msg_params][strings::reason].asInt());
+
+ Common_ApplicationExitReason::eType reason;
+ reason = static_cast<Common_ApplicationExitReason::eType>(
+ (*message_)[strings::msg_params][strings::reason].asInt());
+
switch (reason) {
- case hmi_apis::Common_ApplicationToNONEReason::USER_EXIT : {
+ case Common_ApplicationExitReason::DRIVER_DISTRACTION_VIOLATION: {
+ application_manager_.ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ app_id,
+ AppInterfaceUnregisteredReason::DRIVER_DISTRACTION_VIOLATION),
+ commands::Command::ORIGIN_SDL);
break;
}
- default : {
- LOG4CXX_WARN(logger_, "Unhandled reason");
+ case Common_ApplicationExitReason::USER_EXIT: {
break;
}
+ case Common_ApplicationExitReason::UNAUTHORIZED_TRANSPORT_REGISTRATION: {
+ application_manager_.ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ app_id, AppInterfaceUnregisteredReason::APP_UNAUTHORIZED),
+ commands::Command::ORIGIN_SDL);
+ // HMI rejects registration for navi application
+ application_manager_.UnregisterApplication(app_id, Result::SUCCESS);
+ return;
+ }
+ case Common_ApplicationExitReason::UNSUPPORTED_HMI_RESOURCE: {
+ application_manager_.ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ app_id, AppInterfaceUnregisteredReason::UNSUPPORTED_HMI_RESOURCE),
+ commands::Command::ORIGIN_SDL);
+ application_manager_.UnregisterApplication(app_id, Result::SUCCESS);
+ return;
+ }
+ default: {
+ LOG4CXX_WARN(logger_, "Unhandled reason");
+ return;
+ }
+ }
+ ApplicationSharedPtr app = application_manager_.application(app_id);
+ if (app) {
+ application_manager_.state_controller().SetRegularState(
+ app, HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE, false);
+ } else {
+ LOG4CXX_ERROR(logger_, "Unable to find appication " << app_id);
}
- using namespace mobile_apis;
- ApplicationManagerImpl::instance()->SetState<false>(app_impl->app_id(),
- HMILevel::HMI_NONE,
- AudioStreamingState::NOT_AUDIBLE,
- SystemContext::SYSCTXT_MAIN);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/on_file_removed_notification.cc b/src/components/application_manager/src/commands/hmi/on_file_removed_notification.cc
index 83c3e61a0c..e69d111d2c 100644
--- a/src/components/application_manager/src/commands/hmi/on_file_removed_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_file_removed_notification.cc
@@ -31,18 +31,16 @@
*/
#include "application_manager/commands/hmi/on_file_removed_notification.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
OnFileRemovedNotification::OnFileRemovedNotification(
- const MessageSharedPtr& message) : NotificationToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationToHMI(message, application_manager) {}
-OnFileRemovedNotification::~OnFileRemovedNotification() {
-}
+OnFileRemovedNotification::~OnFileRemovedNotification() {}
void OnFileRemovedNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void OnFileRemovedNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_find_applications.cc b/src/components/application_manager/src/commands/hmi/on_find_applications.cc
index fc1b72c73a..9d3633ba6d 100644
--- a/src/components/application_manager/src/commands/hmi/on_find_applications.cc
+++ b/src/components/application_manager/src/commands/hmi/on_find_applications.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-OnFindApplications::OnFindApplications(const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+OnFindApplications::OnFindApplications(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnFindApplications::~OnFindApplications() {
-}
+OnFindApplications::~OnFindApplications() {}
void OnFindApplications::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void OnFindApplications::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_ignition_cycle_over_notification.cc b/src/components/application_manager/src/commands/hmi/on_ignition_cycle_over_notification.cc
index 32babf05cc..8c772d6dcd 100644
--- a/src/components/application_manager/src/commands/hmi/on_ignition_cycle_over_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_ignition_cycle_over_notification.cc
@@ -31,26 +31,23 @@
*/
#include "application_manager/commands/hmi/on_ignition_cycle_over_notification.h"
-#include "application_manager/policies/policy_handler.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
OnIgnitionCycleOverNotification::OnIgnitionCycleOverNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnIgnitionCycleOverNotification::~OnIgnitionCycleOverNotification() {
-}
+OnIgnitionCycleOverNotification::~OnIgnitionCycleOverNotification() {}
void OnIgnitionCycleOverNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- policy::PolicyHandler::instance()->OnIgnitionCycleOver();
+ application_manager_.GetPolicyHandler().OnIgnitionCycleOver();
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_navi_tbt_client_state_notification.cc b/src/components/application_manager/src/commands/hmi/on_navi_tbt_client_state_notification.cc
index 87db5d4a38..e25de1f3a9 100644
--- a/src/components/application_manager/src/commands/hmi/on_navi_tbt_client_state_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_navi_tbt_client_state_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnNaviTBTClientStateNotification::OnNaviTBTClientStateNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnNaviTBTClientStateNotification::~OnNaviTBTClientStateNotification() {
-}
+OnNaviTBTClientStateNotification::~OnNaviTBTClientStateNotification() {}
void OnNaviTBTClientStateNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnNaviTBTClientStateNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_navi_way_point_change_notification.cc b/src/components/application_manager/src/commands/hmi/on_navi_way_point_change_notification.cc
new file mode 100644
index 0000000000..17d1b420be
--- /dev/null
+++ b/src/components/application_manager/src/commands/hmi/on_navi_way_point_change_notification.cc
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/commands/hmi/on_navi_way_point_change_notification.h"
+
+namespace application_manager {
+
+namespace commands {
+
+OnNaviWayPointChangeNotification::OnNaviWayPointChangeNotification(
+ const MessageSharedPtr& message, ApplicationManager& app_man)
+ : NotificationFromHMI(message, app_man) {}
+
+OnNaviWayPointChangeNotification::~OnNaviWayPointChangeNotification() {}
+
+void OnNaviWayPointChangeNotification::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ // prepare SmartObject for mobile factory
+ (*message_)[strings::params][strings::function_id] =
+ static_cast<int32_t>(mobile_apis::FunctionID::OnWayPointChangeID);
+
+ SendNotificationToMobile(message_);
+}
+
+} // namespace commands
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/hmi/on_phone_call_notification.cc b/src/components/application_manager/src/commands/hmi/on_phone_call_notification.cc
deleted file mode 100644
index 5f47c2908a..0000000000
--- a/src/components/application_manager/src/commands/hmi/on_phone_call_notification.cc
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "application_manager/commands/hmi/on_phone_call_notification.h"
-#include "application_manager/application_manager_impl.h"
-#include "application_manager/application_impl.h"
-#include "application_manager/message_helper.h"
-
-namespace application_manager {
-
-namespace commands {
-
-namespace hmi {
-
-OnPhoneCallNotification::OnPhoneCallNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
-
-OnPhoneCallNotification::~OnPhoneCallNotification() {
-}
-
-void OnPhoneCallNotification::Run() {
- LOG4CXX_AUTO_TRACE(logger_);
- event_engine::Event event(hmi_apis::FunctionID::BasicCommunication_OnPhoneCall);
- event.set_smart_object(*message_);
- event.raise();
-}
-
-} // namespace hmi
-
-} // namespace commands
-
-} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_play_tone_notification.cc b/src/components/application_manager/src/commands/hmi/on_play_tone_notification.cc
deleted file mode 100644
index 9820bb02ad..0000000000
--- a/src/components/application_manager/src/commands/hmi/on_play_tone_notification.cc
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "application_manager/commands/hmi/on_play_tone_notification.h"
-
-namespace application_manager {
-
-namespace commands {
-
-OnPlayToneNotification::OnPlayToneNotification(const MessageSharedPtr& message)
- : NotificationToHMI(message) {
-}
-
-OnPlayToneNotification::~OnPlayToneNotification() {
-}
-
-void OnPlayToneNotification::Run() {
- LOG4CXX_AUTO_TRACE(logger_);
-
- SendNotification();
-}
-
-} // namespace commands
-
-} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_policy_update.cc b/src/components/application_manager/src/commands/hmi/on_policy_update.cc
index 56c544888a..39b179f967 100644
--- a/src/components/application_manager/src/commands/hmi/on_policy_update.cc
+++ b/src/components/application_manager/src/commands/hmi/on_policy_update.cc
@@ -31,21 +31,20 @@
*/
#include "application_manager/commands/hmi/on_policy_update.h"
-#include "application_manager/policies/policy_handler.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
-OnPolicyUpdate::OnPolicyUpdate(const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+OnPolicyUpdate::OnPolicyUpdate(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnPolicyUpdate::~OnPolicyUpdate() {
-}
+OnPolicyUpdate::~OnPolicyUpdate() {}
void OnPolicyUpdate::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- policy::PolicyHandler::instance()->OnPTExchangeNeeded();
+ application_manager_.GetPolicyHandler().OnPTExchangeNeeded();
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/on_put_file_notification.cc b/src/components/application_manager/src/commands/hmi/on_put_file_notification.cc
index cf0297df01..596b7d4549 100644
--- a/src/components/application_manager/src/commands/hmi/on_put_file_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_put_file_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnPutFileNotification::OnPutFileNotification(
- const MessageSharedPtr& message)
- : NotificationToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationToHMI(message, application_manager) {}
-OnPutFileNotification::~OnPutFileNotification() {
-}
+OnPutFileNotification::~OnPutFileNotification() {}
void OnPutFileNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void OnPutFileNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_ready_notification.cc b/src/components/application_manager/src/commands/hmi/on_ready_notification.cc
index f1ac8b6d3c..3a45e0f934 100644
--- a/src/components/application_manager/src/commands/hmi/on_ready_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_ready_notification.cc
@@ -31,29 +31,26 @@
*/
#include "application_manager/commands/hmi/on_ready_notification.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-OnReadyNotification::OnReadyNotification(const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+OnReadyNotification::OnReadyNotification(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnReadyNotification::~OnReadyNotification() {
-}
+OnReadyNotification::~OnReadyNotification() {}
void OnReadyNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->OnHMIStartedCooperation();
+ application_manager_.OnHMIStartedCooperation();
event_engine::Event event(hmi_apis::FunctionID::BasicCommunication_OnReady);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_received_policy_update.cc b/src/components/application_manager/src/commands/hmi/on_received_policy_update.cc
index f739c762c7..03c0bc7378 100644
--- a/src/components/application_manager/src/commands/hmi/on_received_policy_update.cc
+++ b/src/components/application_manager/src/commands/hmi/on_received_policy_update.cc
@@ -32,32 +32,31 @@
#include <string>
#include "application_manager/commands/hmi/on_received_policy_update.h"
-#include "application_manager/policies/policy_handler.h"
+#include "application_manager/application_manager.h"
#include "utils/file_system.h"
namespace application_manager {
namespace commands {
-OnReceivedPolicyUpdate::OnReceivedPolicyUpdate(const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+OnReceivedPolicyUpdate::OnReceivedPolicyUpdate(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnReceivedPolicyUpdate::~OnReceivedPolicyUpdate() {
-}
+OnReceivedPolicyUpdate::~OnReceivedPolicyUpdate() {}
void OnReceivedPolicyUpdate::Run() {
LOG4CXX_AUTO_TRACE(logger_);
#ifdef EXTENDED_POLICY
const std::string& file_path =
- (*message_)[strings::msg_params][hmi_notification::policyfile].asString();
+ (*message_)[strings::msg_params][hmi_notification::policyfile].asString();
policy::BinaryMessage file_content;
if (!file_system::ReadBinaryFile(file_path, file_content)) {
LOG4CXX_ERROR(logger_, "Failed to read Update file.");
return;
}
- policy::PolicyHandler::instance()->ReceiveMessageFromSDK(file_path,
- file_content);
+ application_manager_.GetPolicyHandler().ReceiveMessageFromSDK(file_path,
+ file_content);
#else
LOG4CXX_WARN(logger_,
"This RPC is part of extended policy flow."
diff --git a/src/components/application_manager/src/commands/hmi/on_record_start_notification.cc b/src/components/application_manager/src/commands/hmi/on_record_start_notification.cc
index 163b525628..4d126ac67d 100644
--- a/src/components/application_manager/src/commands/hmi/on_record_start_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_record_start_notification.cc
@@ -31,18 +31,16 @@
*/
#include "application_manager/commands/hmi/on_record_start_notification.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
OnRecordStartdNotification::OnRecordStartdNotification(
- const MessageSharedPtr& message) : NotificationToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationToHMI(message, application_manager) {}
-OnRecordStartdNotification::~OnRecordStartdNotification() {
-}
+OnRecordStartdNotification::~OnRecordStartdNotification() {}
void OnRecordStartdNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void OnRecordStartdNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_resume_audio_source_notification.cc b/src/components/application_manager/src/commands/hmi/on_resume_audio_source_notification.cc
index 8e00c3447c..ce3c371cf8 100644
--- a/src/components/application_manager/src/commands/hmi/on_resume_audio_source_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_resume_audio_source_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnResumeAudioSourceNotification::OnResumeAudioSourceNotification(
- const MessageSharedPtr& message)
- : NotificationToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationToHMI(message, application_manager) {}
-OnResumeAudioSourceNotification::~OnResumeAudioSourceNotification() {
-}
+OnResumeAudioSourceNotification::~OnResumeAudioSourceNotification() {}
void OnResumeAudioSourceNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void OnResumeAudioSourceNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_sdl_close_notification.cc b/src/components/application_manager/src/commands/hmi/on_sdl_close_notification.cc
index c393219134..0517ea8d24 100644
--- a/src/components/application_manager/src/commands/hmi/on_sdl_close_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_sdl_close_notification.cc
@@ -37,14 +37,13 @@ namespace application_manager {
namespace commands {
OnSDLCloseNotification::OnSDLCloseNotification(
- const MessageSharedPtr& message) : NotificationToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationToHMI(message, application_manager) {}
-OnSDLCloseNotification::~OnSDLCloseNotification() {
-}
+OnSDLCloseNotification::~OnSDLCloseNotification() {}
void OnSDLCloseNotification::Run() {
- LOG4CXX_INFO(logger_, "OnSdlCloseNotification::Run");
+ LOG4CXX_AUTO_TRACE(logger_);
SendNotification();
}
@@ -52,4 +51,3 @@ void OnSDLCloseNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_sdl_consent_needed_notification.cc b/src/components/application_manager/src/commands/hmi/on_sdl_consent_needed_notification.cc
index 20010111fd..a9c36813f6 100644
--- a/src/components/application_manager/src/commands/hmi/on_sdl_consent_needed_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_sdl_consent_needed_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnSDLConsentNeededNotification::OnSDLConsentNeededNotification(
- const MessageSharedPtr& message)
- : NotificationToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationToHMI(message, application_manager) {}
-OnSDLConsentNeededNotification::~OnSDLConsentNeededNotification() {
-}
+OnSDLConsentNeededNotification::~OnSDLConsentNeededNotification() {}
void OnSDLConsentNeededNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void OnSDLConsentNeededNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_sdl_persistence_complete_notification.cc b/src/components/application_manager/src/commands/hmi/on_sdl_persistence_complete_notification.cc
index afe0ffeabc..e30a0fb902 100644
--- a/src/components/application_manager/src/commands/hmi/on_sdl_persistence_complete_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_sdl_persistence_complete_notification.cc
@@ -37,15 +37,13 @@ namespace application_manager {
namespace commands {
OnSDLPersistenceCompleteNotification::OnSDLPersistenceCompleteNotification(
- const MessageSharedPtr& message)
- : NotificationToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationToHMI(message, application_manager) {}
-OnSDLPersistenceCompleteNotification::~OnSDLPersistenceCompleteNotification() {
-}
+OnSDLPersistenceCompleteNotification::~OnSDLPersistenceCompleteNotification() {}
void OnSDLPersistenceCompleteNotification::Run() {
- LOG4CXX_INFO(logger_, "OnSDLpersistenceCompleteNotification::Run");
+ LOG4CXX_AUTO_TRACE(logger_);
SendNotification();
}
diff --git a/src/components/application_manager/src/commands/hmi/on_start_device_discovery.cc b/src/components/application_manager/src/commands/hmi/on_start_device_discovery.cc
index 6f867adbcd..8e94b2b004 100644
--- a/src/components/application_manager/src/commands/hmi/on_start_device_discovery.cc
+++ b/src/components/application_manager/src/commands/hmi/on_start_device_discovery.cc
@@ -31,26 +31,23 @@
*/
#include "application_manager/commands/hmi/on_start_device_discovery.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-OnStartDeviceDiscovery::OnStartDeviceDiscovery(const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+OnStartDeviceDiscovery::OnStartDeviceDiscovery(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnStartDeviceDiscovery::~OnStartDeviceDiscovery() {
-}
+OnStartDeviceDiscovery::~OnStartDeviceDiscovery() {}
void OnStartDeviceDiscovery::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->StartDevicesDiscovery();
+ application_manager_.StartDevicesDiscovery();
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_status_update_notification.cc b/src/components/application_manager/src/commands/hmi/on_status_update_notification.cc
index 7db0053e2d..78a6b68324 100644
--- a/src/components/application_manager/src/commands/hmi/on_status_update_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_status_update_notification.cc
@@ -37,19 +37,16 @@ namespace application_manager {
namespace commands {
OnStatusUpdateNotification::OnStatusUpdateNotification(
- const MessageSharedPtr& message)
- : NotificationToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationToHMI(message, application_manager) {}
-OnStatusUpdateNotification::~OnStatusUpdateNotification() {
-}
+OnStatusUpdateNotification::~OnStatusUpdateNotification() {}
void OnStatusUpdateNotification::Run() {
- LOG4CXX_INFO(logger_, "OnGetStatusUpdateNotification::Run");
+ LOG4CXX_AUTO_TRACE(logger_);
SendNotification();
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_system_context_notification.cc b/src/components/application_manager/src/commands/hmi/on_system_context_notification.cc
index aa334d8259..887aacf5b9 100644
--- a/src/components/application_manager/src/commands/hmi/on_system_context_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_system_context_notification.cc
@@ -31,57 +31,49 @@
*/
#include "application_manager/commands/hmi/on_system_context_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
+#include "application_manager/state_controller.h"
#include "application_manager/message_helper.h"
namespace application_manager {
namespace commands {
OnSystemContextNotification::OnSystemContextNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnSystemContextNotification::~OnSystemContextNotification() {
-}
+OnSystemContextNotification::~OnSystemContextNotification() {}
void OnSystemContextNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
mobile_api::SystemContext::eType system_context =
- static_cast<mobile_api::SystemContext::eType>(
- (*message_)[strings::msg_params][hmi_notification::system_context].asInt());
+ static_cast<mobile_api::SystemContext::eType>(
+ (*message_)[strings::msg_params][hmi_notification::system_context]
+ .asInt());
ApplicationSharedPtr app;
-
if ((mobile_api::SystemContext::SYSCTXT_VRSESSION == system_context) ||
(mobile_api::SystemContext::SYSCTXT_MENU == system_context) ||
(mobile_api::SystemContext::SYSCTXT_HMI_OBSCURED == system_context)) {
- app = ApplicationManagerImpl::instance()->active_application();
+ app = application_manager_.active_application();
} else if ((mobile_api::SystemContext::SYSCTXT_ALERT == system_context) ||
(mobile_api::SystemContext::SYSCTXT_MAIN == system_context)) {
if ((*message_)[strings::msg_params].keyExists(strings::app_id)) {
- app = ApplicationManagerImpl::instance()->
- application((*message_)[strings::msg_params][strings::app_id].asUInt());
+ app = application_manager_.application(
+ (*message_)[strings::msg_params][strings::app_id].asUInt());
}
}
- if (app.valid() && (system_context != app->system_context()) &&
- (system_context != mobile_api::SystemContext::INVALID_ENUM)) {
- SendSystemContextNotification(app, system_context);
+ if (app && mobile_api::SystemContext::INVALID_ENUM != system_context) {
+ application_manager_.state_controller().SetRegularState(app,
+ system_context);
} else {
- LOG4CXX_ERROR(logger_, "Ignored wrong SystemContext notification!");
+ LOG4CXX_ERROR(logger_, "Application does not exist");
}
}
-void OnSystemContextNotification::SendSystemContextNotification(ApplicationSharedPtr app,
- mobile_api::SystemContext::eType system_context) {
- ApplicationManagerImpl::instance()->SetState(app->app_id(),
- system_context);
-}
-
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_system_error_notification.cc b/src/components/application_manager/src/commands/hmi/on_system_error_notification.cc
index 09a96cc797..4885420f1c 100644
--- a/src/components/application_manager/src/commands/hmi/on_system_error_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_system_error_notification.cc
@@ -31,7 +31,7 @@
*/
#include "application_manager/commands/hmi/on_system_error_notification.h"
-#include "application_manager/policies/policy_handler.h"
+#include "application_manager/application_manager.h"
#include "interfaces/HMI_API.h"
namespace application_manager {
@@ -39,23 +39,20 @@ namespace application_manager {
namespace commands {
OnSystemErrorNotification::OnSystemErrorNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnSystemErrorNotification::~OnSystemErrorNotification() {
-}
+OnSystemErrorNotification::~OnSystemErrorNotification() {}
void OnSystemErrorNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- int code = (*message_)[strings::msg_params][hmi_notification::error]
- .asInt();
+ const int code =
+ (*message_)[strings::msg_params][hmi_notification::error].asInt();
- policy::PolicyHandler::instance()->OnSystemError(code);
+ application_manager_.GetPolicyHandler().OnSystemError(code);
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_system_info_changed_notification.cc b/src/components/application_manager/src/commands/hmi/on_system_info_changed_notification.cc
index fb5a9abc43..00b3649284 100644
--- a/src/components/application_manager/src/commands/hmi/on_system_info_changed_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_system_info_changed_notification.cc
@@ -31,7 +31,7 @@
*/
#include "application_manager/commands/hmi/on_system_info_changed_notification.h"
-#include "application_manager/policies/policy_handler.h"
+#include "application_manager/application_manager.h"
#include "application_manager/message_helper.h"
namespace application_manager {
@@ -39,12 +39,10 @@ namespace application_manager {
namespace commands {
OnSystemInfoChangedNotification::OnSystemInfoChangedNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnSystemInfoChangedNotification::~OnSystemInfoChangedNotification() {
-}
+OnSystemInfoChangedNotification::~OnSystemInfoChangedNotification() {}
void OnSystemInfoChangedNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,13 +50,11 @@ void OnSystemInfoChangedNotification::Run() {
(*message_)[strings::msg_params][strings::language].asUInt();
const std::string language =
application_manager::MessageHelper::CommonLanguageToString(
- static_cast<hmi_apis::Common_Language::eType>(lang_code));
+ static_cast<hmi_apis::Common_Language::eType>(lang_code));
- policy::PolicyHandler::instance()->OnSystemInfoChanged(language);
+ application_manager_.GetPolicyHandler().OnSystemInfoChanged(language);
}
} // namespace commands
} // namespace application_manager
-
-
diff --git a/src/components/application_manager/src/commands/hmi/on_system_request_notification.cc b/src/components/application_manager/src/commands/hmi/on_system_request_notification.cc
index e464037136..b74f1b6799 100644
--- a/src/components/application_manager/src/commands/hmi/on_system_request_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_system_request_notification.cc
@@ -31,25 +31,23 @@
*/
#include "application_manager/application_impl.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/commands/hmi/on_system_request_notification.h"
-#include "application_manager/policies/policy_handler.h"
+#include "application_manager/policies/policy_handler_interface.h"
#include "interfaces/MOBILE_API.h"
#include "utils/macro.h"
-using policy::PolicyHandler;
+using policy::PolicyHandlerInterface;
namespace application_manager {
namespace commands {
OnSystemRequestNotification::OnSystemRequestNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnSystemRequestNotification::~OnSystemRequestNotification() {
-}
+OnSystemRequestNotification::~OnSystemRequestNotification() {}
void OnSystemRequestNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,26 +56,31 @@ void OnSystemRequestNotification::Run() {
smart_objects::SmartObject& msg_params = (*message_)[strings::msg_params];
params[strings::function_id] =
- static_cast<int32_t>(mobile_apis::FunctionID::eType::OnSystemRequestID);
+ static_cast<int32_t>(mobile_apis::FunctionID::eType::OnSystemRequestID);
+ // According to HMI API, this should be HMI unique id, but during processing
+ // messages from HMI this param is replaced by connection key, so below it
+ // will be treated as connection key
ApplicationSharedPtr app;
- if (!msg_params.keyExists(strings::app_id)) {
+ if (msg_params.keyExists(strings::app_id)) {
+ const uint32_t app_id = msg_params[strings::app_id].asUInt();
+ LOG4CXX_DEBUG(logger_, "Received OnSystemRequest for appID " << app_id);
+ LOG4CXX_DEBUG(logger_, "Searching app to send OnSystemRequest by appID.");
+ app = application_manager_.application(app_id);
+ } else {
LOG4CXX_DEBUG(logger_,
- "No application specified, trying to choose automatically.");
- PolicyHandler* policy_handler = PolicyHandler::instance();
- uint32_t selected_app_id = policy_handler->GetAppIdForSending();
+ "Received OnSystemRequest without appID."
+ " One of registered apps will be used.");
+ LOG4CXX_DEBUG(logger_, "Searching registered app to send OnSystemRequest.");
+ const PolicyHandlerInterface& policy_handler =
+ application_manager_.GetPolicyHandler();
+ const uint32_t selected_app_id = policy_handler.GetAppIdForSending();
if (0 == selected_app_id) {
LOG4CXX_WARN(logger_,
"Can't select application to forward OnSystemRequest.");
return;
}
- ApplicationManagerImpl* app_mgr = ApplicationManagerImpl::instance();
- app = app_mgr->application(selected_app_id);
- } else {
- const uint32_t app_id = msg_params[strings::app_id].asUInt();
- LOG4CXX_WARN(logger_, "Looking for application with connection key "
- << app_id);
- app = ApplicationManagerImpl::instance()->application(app_id);
+ app = application_manager_.application(selected_app_id);
}
if (!app.valid()) {
@@ -87,7 +90,7 @@ void OnSystemRequestNotification::Run() {
}
LOG4CXX_DEBUG(logger_,
- "Sending request with application id " << app->mobile_app_id());
+ "Sending request with application id " << app->policy_app_id());
params[strings::connection_key] = app->app_id();
SendNotificationToMobile(message_);
@@ -96,4 +99,3 @@ void OnSystemRequestNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_tts_language_change_notification.cc b/src/components/application_manager/src/commands/hmi/on_tts_language_change_notification.cc
index daa307d627..bd152c2af0 100644
--- a/src/components/application_manager/src/commands/hmi/on_tts_language_change_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_tts_language_change_notification.cc
@@ -31,7 +31,7 @@
*/
#include "application_manager/commands/hmi/on_tts_language_change_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
#include "interfaces/MOBILE_API.h"
@@ -41,18 +41,15 @@ namespace application_manager {
namespace commands {
OnTTSLanguageChangeNotification::OnTTSLanguageChangeNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnTTSLanguageChangeNotification::~OnTTSLanguageChangeNotification() {
-}
+OnTTSLanguageChangeNotification::~OnTTSLanguageChangeNotification() {}
void OnTTSLanguageChangeNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
hmi_capabilities.set_active_tts_language(
static_cast<hmi_apis::Common_Language::eType>(
@@ -70,20 +67,22 @@ void OnTTSLanguageChangeNotification::Run() {
(*message_)[strings::params][strings::function_id] =
static_cast<int32_t>(mobile_apis::FunctionID::OnLanguageChangeID);
- ApplicationManagerImpl::ApplicationListAccessor accessor;
-
- ApplicationManagerImpl::ApplictionSetIt it = accessor.begin();
+ const ApplicationSet& accessor =
+ application_manager_.applications().GetData();
+ ApplicationSetIt it = accessor.begin();
for (; accessor.end() != it;) {
ApplicationSharedPtr app = *it++;
(*message_)[strings::params][strings::connection_key] = app->app_id();
SendNotificationToMobile(message_);
- if (static_cast<int>(app->language())
- != (*message_)[strings::msg_params][strings::language].asInt()) {
- MessageHelper::SendOnAppInterfaceUnregisteredNotificationToMobile(
- app->app_id(),
- mobile_api::AppInterfaceUnregisteredReason::LANGUAGE_CHANGE);
- ApplicationManagerImpl::instance()->UnregisterApplication(
+ if (static_cast<int>(app->language()) !=
+ (*message_)[strings::msg_params][strings::language].asInt()) {
+ application_manager_.ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ app->app_id(),
+ mobile_api::AppInterfaceUnregisteredReason::LANGUAGE_CHANGE),
+ commands::Command::ORIGIN_SDL);
+ application_manager_.UnregisterApplication(
app->app_id(), mobile_apis::Result::SUCCESS, false);
}
}
@@ -92,4 +91,3 @@ void OnTTSLanguageChangeNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_tts_reset_timeout_notification.cc b/src/components/application_manager/src/commands/hmi/on_tts_reset_timeout_notification.cc
index 96089384c4..283e2056ba 100644
--- a/src/components/application_manager/src/commands/hmi/on_tts_reset_timeout_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_tts_reset_timeout_notification.cc
@@ -9,18 +9,17 @@ namespace commands {
namespace hmi {
OnTTSResetTimeoutNotification::OnTTSResetTimeoutNotification(
- const MessageSharedPtr& message) : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnTTSResetTimeoutNotification::~OnTTSResetTimeoutNotification() {
-}
+OnTTSResetTimeoutNotification::~OnTTSResetTimeoutNotification() {}
void OnTTSResetTimeoutNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::TTS_OnResetTimeout);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace hmi
@@ -28,4 +27,3 @@ void OnTTSResetTimeoutNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_tts_started_notification.cc b/src/components/application_manager/src/commands/hmi/on_tts_started_notification.cc
index dc69246d5c..317465f354 100644
--- a/src/components/application_manager/src/commands/hmi/on_tts_started_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_tts_started_notification.cc
@@ -31,28 +31,24 @@
*/
#include "application_manager/commands/hmi/on_tts_started_notification.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
OnTTSStartedNotification::OnTTSStartedNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnTTSStartedNotification::~OnTTSStartedNotification() {
-}
+OnTTSStartedNotification::~OnTTSStartedNotification() {}
void OnTTSStartedNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::TTS_Started);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_tts_stopped_notification.cc b/src/components/application_manager/src/commands/hmi/on_tts_stopped_notification.cc
index 8d429ed179..7f763d8598 100644
--- a/src/components/application_manager/src/commands/hmi/on_tts_stopped_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_tts_stopped_notification.cc
@@ -31,7 +31,7 @@
*/
#include "application_manager/commands/hmi/on_tts_stopped_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/event_engine/event.h"
namespace application_manager {
@@ -39,22 +39,19 @@ namespace application_manager {
namespace commands {
OnTTSStoppedNotification::OnTTSStoppedNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnTTSStoppedNotification::~OnTTSStoppedNotification() {
-}
+OnTTSStoppedNotification::~OnTTSStoppedNotification() {}
void OnTTSStoppedNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::TTS_Stopped);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_ui_command_notification.cc b/src/components/application_manager/src/commands/hmi/on_ui_command_notification.cc
index d8fe1ebdea..9f91d99a85 100644
--- a/src/components/application_manager/src/commands/hmi/on_ui_command_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_ui_command_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnUICommandNotification::OnUICommandNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnUICommandNotification::~OnUICommandNotification() {
-}
+OnUICommandNotification::~OnUICommandNotification() {}
void OnUICommandNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -59,4 +57,3 @@ void OnUICommandNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_ui_keyboard_input_notification.cc b/src/components/application_manager/src/commands/hmi/on_ui_keyboard_input_notification.cc
index 9dcfe01e60..117fec5741 100644
--- a/src/components/application_manager/src/commands/hmi/on_ui_keyboard_input_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_ui_keyboard_input_notification.cc
@@ -40,18 +40,17 @@ namespace commands {
namespace hmi {
OnUIKeyBoardInputNotification::OnUIKeyBoardInputNotification(
- const MessageSharedPtr& message) : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnUIKeyBoardInputNotification::~OnUIKeyBoardInputNotification() {
-}
+OnUIKeyBoardInputNotification::~OnUIKeyBoardInputNotification() {}
void OnUIKeyBoardInputNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- //prepare SmartObject for mobile factory
+ // prepare SmartObject for mobile factory
(*message_)[strings::params][strings::function_id] =
- mobile_apis::FunctionID::OnKeyboardInputID;
+ mobile_apis::FunctionID::OnKeyboardInputID;
SendNotificationToMobile(message_);
}
@@ -60,4 +59,3 @@ void OnUIKeyBoardInputNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_ui_language_change_notification.cc b/src/components/application_manager/src/commands/hmi/on_ui_language_change_notification.cc
index 7e54099994..6e8e38f757 100644
--- a/src/components/application_manager/src/commands/hmi/on_ui_language_change_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_ui_language_change_notification.cc
@@ -31,7 +31,7 @@
*/
#include "application_manager/commands/hmi/on_ui_language_change_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
#include "interfaces/MOBILE_API.h"
@@ -41,18 +41,15 @@ namespace application_manager {
namespace commands {
OnUILanguageChangeNotification::OnUILanguageChangeNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnUILanguageChangeNotification::~OnUILanguageChangeNotification() {
-}
+OnUILanguageChangeNotification::~OnUILanguageChangeNotification() {}
void OnUILanguageChangeNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
hmi_capabilities.set_active_ui_language(
static_cast<hmi_apis::Common_Language::eType>(
@@ -67,21 +64,24 @@ void OnUILanguageChangeNotification::Run() {
(*message_)[strings::params][strings::function_id] =
static_cast<int32_t>(mobile_apis::FunctionID::OnLanguageChangeID);
- ApplicationManagerImpl::ApplicationListAccessor accessor;
+ const ApplicationSet& accessor =
+ application_manager_.applications().GetData();
- ApplicationManagerImpl::ApplictionSetIt it = accessor.begin();
+ ApplicationSetConstIt it = accessor.begin();
for (; accessor.end() != it;) {
ApplicationSharedPtr app = *it++;
(*message_)[strings::params][strings::connection_key] = app->app_id();
SendNotificationToMobile(message_);
- if (app->ui_language() != (*message_)[strings::msg_params]
- [strings::hmi_display_language].asInt()) {
-
- MessageHelper::SendOnAppInterfaceUnregisteredNotificationToMobile(
- app->app_id(),
- mobile_api::AppInterfaceUnregisteredReason::LANGUAGE_CHANGE);
- ApplicationManagerImpl::instance()->UnregisterApplication(
+ if (app->ui_language() !=
+ (*message_)[strings::msg_params][strings::hmi_display_language]
+ .asInt()) {
+ application_manager_.ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ app->app_id(),
+ mobile_api::AppInterfaceUnregisteredReason::LANGUAGE_CHANGE),
+ commands::Command::ORIGIN_SDL);
+ application_manager_.UnregisterApplication(
app->app_id(), mobile_apis::Result::SUCCESS, false);
}
}
@@ -90,4 +90,3 @@ void OnUILanguageChangeNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_ui_reset_timeout_notification.cc b/src/components/application_manager/src/commands/hmi/on_ui_reset_timeout_notification.cc
index 96f65839c1..a5fea7bf8d 100644
--- a/src/components/application_manager/src/commands/hmi/on_ui_reset_timeout_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_ui_reset_timeout_notification.cc
@@ -41,18 +41,17 @@ namespace commands {
namespace hmi {
OnUIResetTimeoutNotification::OnUIResetTimeoutNotification(
- const MessageSharedPtr& message) : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnUIResetTimeoutNotification::~OnUIResetTimeoutNotification() {
-}
+OnUIResetTimeoutNotification::~OnUIResetTimeoutNotification() {}
void OnUIResetTimeoutNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_OnResetTimeout);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace hmi
@@ -60,4 +59,3 @@ void OnUIResetTimeoutNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_ui_touch_event_notification.cc b/src/components/application_manager/src/commands/hmi/on_ui_touch_event_notification.cc
index 00e0e4d2c6..7709af8720 100644
--- a/src/components/application_manager/src/commands/hmi/on_ui_touch_event_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_ui_touch_event_notification.cc
@@ -40,18 +40,17 @@ namespace commands {
namespace hmi {
OnUITouchEventNotification::OnUITouchEventNotification(
- const MessageSharedPtr& message) : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnUITouchEventNotification::~OnUITouchEventNotification() {
-}
+OnUITouchEventNotification::~OnUITouchEventNotification() {}
void OnUITouchEventNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- //prepare SmartObject for mobile factory
+ // prepare SmartObject for mobile factory
(*message_)[strings::params][strings::function_id] =
- mobile_apis::FunctionID::OnTouchEventID;
+ mobile_apis::FunctionID::OnTouchEventID;
SendNotificationToMobile(message_);
}
@@ -60,4 +59,3 @@ void OnUITouchEventNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_update_device_list.cc b/src/components/application_manager/src/commands/hmi/on_update_device_list.cc
index 8716fb4165..b245ea21aa 100644
--- a/src/components/application_manager/src/commands/hmi/on_update_device_list.cc
+++ b/src/components/application_manager/src/commands/hmi/on_update_device_list.cc
@@ -30,18 +30,16 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/on_update_device_list.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-OnUpdateDeviceList::OnUpdateDeviceList(const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+OnUpdateDeviceList::OnUpdateDeviceList(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnUpdateDeviceList::~OnUpdateDeviceList() {
-}
+OnUpdateDeviceList::~OnUpdateDeviceList() {}
void OnUpdateDeviceList::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -50,4 +48,3 @@ void OnUpdateDeviceList::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_acc_pedal_position_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_acc_pedal_position_notification.cc
index f1e515e2f2..9b10055e2c 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_acc_pedal_position_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_acc_pedal_position_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIAccPedalPositionNotification::OnVIAccPedalPositionNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIAccPedalPositionNotification::~OnVIAccPedalPositionNotification() {
-}
+OnVIAccPedalPositionNotification::~OnVIAccPedalPositionNotification() {}
void OnVIAccPedalPositionNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIAccPedalPositionNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_belt_status_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_belt_status_notification.cc
index 0dd5361f74..58f9add514 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_belt_status_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_belt_status_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIBeltStatusNotification::OnVIBeltStatusNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIBeltStatusNotification::~OnVIBeltStatusNotification() {
-}
+OnVIBeltStatusNotification::~OnVIBeltStatusNotification() {}
void OnVIBeltStatusNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIBeltStatusNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_body_information_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_body_information_notification.cc
index 27c902c880..33f2944c38 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_body_information_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_body_information_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIBodyInformationNotification::OnVIBodyInformationNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIBodyInformationNotification::~OnVIBodyInformationNotification() {
-}
+OnVIBodyInformationNotification::~OnVIBodyInformationNotification() {}
void OnVIBodyInformationNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIBodyInformationNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_device_status_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_device_status_notification.cc
index 07b96f1011..9cbf612be1 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_device_status_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_device_status_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIDeviceStatusNotification::OnVIDeviceStatusNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIDeviceStatusNotification::~OnVIDeviceStatusNotification() {
-}
+OnVIDeviceStatusNotification::~OnVIDeviceStatusNotification() {}
void OnVIDeviceStatusNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIDeviceStatusNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_driver_braking_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_driver_braking_notification.cc
index 57a8f9c6ef..e521ac3a37 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_driver_braking_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_driver_braking_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIDriverBrakingNotification::OnVIDriverBrakingNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIDriverBrakingNotification::~OnVIDriverBrakingNotification() {
-}
+OnVIDriverBrakingNotification::~OnVIDriverBrakingNotification() {}
void OnVIDriverBrakingNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIDriverBrakingNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_engine_torque_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_engine_torque_notification.cc
index 7509884497..ebed955270 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_engine_torque_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_engine_torque_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIEngineTorqueNotification::OnVIEngineTorqueNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIEngineTorqueNotification::~OnVIEngineTorqueNotification() {
-}
+OnVIEngineTorqueNotification::~OnVIEngineTorqueNotification() {}
void OnVIEngineTorqueNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIEngineTorqueNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_external_temperature_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_external_temperature_notification.cc
index 64dd411bdd..9f0696fdc6 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_external_temperature_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_external_temperature_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIExternalTemperatureNotification::OnVIExternalTemperatureNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIExternalTemperatureNotification::~OnVIExternalTemperatureNotification() {
-}
+OnVIExternalTemperatureNotification::~OnVIExternalTemperatureNotification() {}
void OnVIExternalTemperatureNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIExternalTemperatureNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_fuel_level_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_fuel_level_notification.cc
index 59ecab0abc..ef650a9f99 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_fuel_level_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_fuel_level_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIFuelLevelNotification::OnVIFuelLevelNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIFuelLevelNotification::~OnVIFuelLevelNotification() {
-}
+OnVIFuelLevelNotification::~OnVIFuelLevelNotification() {}
void OnVIFuelLevelNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIFuelLevelNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_fuel_level_state_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_fuel_level_state_notification.cc
index faa8a0522a..a5267d8dac 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_fuel_level_state_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_fuel_level_state_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIFuelLevelStateNotification::OnVIFuelLevelStateNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIFuelLevelStateNotification::~OnVIFuelLevelStateNotification() {
-}
+OnVIFuelLevelStateNotification::~OnVIFuelLevelStateNotification() {}
void OnVIFuelLevelStateNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIFuelLevelStateNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_gps_data_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_gps_data_notification.cc
index df582418cb..63b95bf6dc 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_gps_data_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_gps_data_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIGpsDataNotification::OnVIGpsDataNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIGpsDataNotification::~OnVIGpsDataNotification() {
-}
+OnVIGpsDataNotification::~OnVIGpsDataNotification() {}
void OnVIGpsDataNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIGpsDataNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_head_lamp_status_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_head_lamp_status_notification.cc
index 01a0a725ef..7d494f02d3 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_head_lamp_status_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_head_lamp_status_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIHeadLampStatusNotification::OnVIHeadLampStatusNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIHeadLampStatusNotification::~OnVIHeadLampStatusNotification() {
-}
+OnVIHeadLampStatusNotification::~OnVIHeadLampStatusNotification() {}
void OnVIHeadLampStatusNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIHeadLampStatusNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_instant_fuel_consumption_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_instant_fuel_consumption_notification.cc
index b13d50fc1c..a62f4cacea 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_instant_fuel_consumption_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_instant_fuel_consumption_notification.cc
@@ -38,12 +38,11 @@ namespace application_manager {
namespace commands {
OnVIInstantFuelConsumptionNotification::OnVIInstantFuelConsumptionNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIInstantFuelConsumptionNotification::~OnVIInstantFuelConsumptionNotification() {
-}
+OnVIInstantFuelConsumptionNotification::
+ ~OnVIInstantFuelConsumptionNotification() {}
void OnVIInstantFuelConsumptionNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +57,3 @@ void OnVIInstantFuelConsumptionNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_my_key_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_my_key_notification.cc
index 71870522ce..229d50667b 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_my_key_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_my_key_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIMyKeyNotification::OnVIMyKeyNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIMyKeyNotification::~OnVIMyKeyNotification() {
-}
+OnVIMyKeyNotification::~OnVIMyKeyNotification() {}
void OnVIMyKeyNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIMyKeyNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_odometer_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_odometer_notification.cc
index 5db3ef3bb3..10f236539c 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_odometer_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_odometer_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIOdometerNotification::OnVIOdometerNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIOdometerNotification::~OnVIOdometerNotification() {
-}
+OnVIOdometerNotification::~OnVIOdometerNotification() {}
void OnVIOdometerNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIOdometerNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_prndl_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_prndl_notification.cc
index 1739f4809b..81585eabca 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_prndl_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_prndl_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIPrndlNotification::OnVIPrndlNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIPrndlNotification::~OnVIPrndlNotification() {
-}
+OnVIPrndlNotification::~OnVIPrndlNotification() {}
void OnVIPrndlNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIPrndlNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_rpm_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_rpm_notification.cc
index 336847ced0..b5c0703917 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_rpm_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_rpm_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIRpmNotification::OnVIRpmNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIRpmNotification::~OnVIRpmNotification() {
-}
+OnVIRpmNotification::~OnVIRpmNotification() {}
void OnVIRpmNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIRpmNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_speed_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_speed_notification.cc
index ad38bf50a5..aacafb71c9 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_speed_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_speed_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVISpeedNotification::OnVISpeedNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVISpeedNotification::~OnVISpeedNotification() {
-}
+OnVISpeedNotification::~OnVISpeedNotification() {}
void OnVISpeedNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVISpeedNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_steering_wheel_angle_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_steering_wheel_angle_notification.cc
index 4fd70bf169..af102ea926 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_steering_wheel_angle_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_steering_wheel_angle_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVISteeringWheelAngleNotification::OnVISteeringWheelAngleNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVISteeringWheelAngleNotification::~OnVISteeringWheelAngleNotification() {
-}
+OnVISteeringWheelAngleNotification::~OnVISteeringWheelAngleNotification() {}
void OnVISteeringWheelAngleNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVISteeringWheelAngleNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_tire_pressure_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_tire_pressure_notification.cc
index fda6e6e28d..99506e6171 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_tire_pressure_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_tire_pressure_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVITirePressureNotification::OnVITirePressureNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVITirePressureNotification::~OnVITirePressureNotification() {
-}
+OnVITirePressureNotification::~OnVITirePressureNotification() {}
void OnVITirePressureNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVITirePressureNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_vehicle_data_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_vehicle_data_notification.cc
index 15ccf940b8..5f8109ccab 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_vehicle_data_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_vehicle_data_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIVehicleDataNotification::OnVIVehicleDataNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIVehicleDataNotification::~OnVIVehicleDataNotification() {
-}
+OnVIVehicleDataNotification::~OnVIVehicleDataNotification() {}
void OnVIVehicleDataNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIVehicleDataNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_vin_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_vin_notification.cc
index aa1683c5fb..c360e41dff 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_vin_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_vin_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIVinNotification::OnVIVinNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIVinNotification::~OnVIVinNotification() {
-}
+OnVIVinNotification::~OnVIVinNotification() {}
void OnVIVinNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIVinNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vi_wiper_status_notification.cc b/src/components/application_manager/src/commands/hmi/on_vi_wiper_status_notification.cc
index 0d27f42388..08fb3f31d4 100644
--- a/src/components/application_manager/src/commands/hmi/on_vi_wiper_status_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vi_wiper_status_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVIWiperStatusNotification::OnVIWiperStatusNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVIWiperStatusNotification::~OnVIWiperStatusNotification() {
-}
+OnVIWiperStatusNotification::~OnVIWiperStatusNotification() {}
void OnVIWiperStatusNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -58,4 +56,3 @@ void OnVIWiperStatusNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_video_data_streaming_notification.cc b/src/components/application_manager/src/commands/hmi/on_video_data_streaming_notification.cc
index 12642a75f2..ee0a91f5ef 100644
--- a/src/components/application_manager/src/commands/hmi/on_video_data_streaming_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_video_data_streaming_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnVideoDataStreamingNotification::OnVideoDataStreamingNotification(
- const MessageSharedPtr& message)
- : NotificationToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationToHMI(message, application_manager) {}
-OnVideoDataStreamingNotification::~OnVideoDataStreamingNotification() {
-}
+OnVideoDataStreamingNotification::~OnVideoDataStreamingNotification() {}
void OnVideoDataStreamingNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/hmi/on_vr_command_notification.cc b/src/components/application_manager/src/commands/hmi/on_vr_command_notification.cc
index f8f9b4dfad..c609e2dc0a 100644
--- a/src/components/application_manager/src/commands/hmi/on_vr_command_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vr_command_notification.cc
@@ -31,9 +31,11 @@
*/
#include "application_manager/commands/hmi/on_vr_command_notification.h"
-#include "application_manager/application_manager_impl.h"
+
+#include "application_manager/policies/policy_handler.h"
#include "application_manager/message_helper.h"
-#include "config_profile/profile.h"
+#include "application_manager/state_controller.h"
+
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
#include "application_manager/event_engine/event.h"
@@ -43,29 +45,28 @@ namespace application_manager {
namespace commands {
OnVRCommandNotification::OnVRCommandNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVRCommandNotification::~OnVRCommandNotification() {
-}
+OnVRCommandNotification::~OnVRCommandNotification() {}
void OnVRCommandNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
-
- ApplicationSharedPtr active_app = ApplicationManagerImpl::instance()
- ->active_application();
- const uint32_t cmd_id = (*message_)[strings::msg_params][strings::cmd_id]
- .asUInt();
- uint32_t max_cmd_id = profile::Profile::instance()->max_cmd_id();
+ const uint32_t cmd_id =
+ (*message_)[strings::msg_params][strings::cmd_id].asUInt();
+ uint32_t max_cmd_id = application_manager_.get_settings().max_cmd_id();
// Check if this is one of standart VR commands (i.e. "Help")
if (cmd_id > max_cmd_id + 1) {
LOG4CXX_INFO(logger_, "Switched App");
const uint32_t app_id = cmd_id - max_cmd_id;
- ApplicationManagerImpl::instance()->SetState<true>(app_id,
- mobile_apis::HMILevel::HMI_FULL
- );
+ ApplicationSharedPtr app = application_manager_.application(app_id);
+ if (app) {
+ application_manager_.state_controller().SetRegularState(
+ app, mobile_apis::HMILevel::HMI_FULL, true);
+ } else {
+ LOG4CXX_ERROR(logger_, "Unable to find appication " << app_id);
+ }
return;
}
@@ -73,9 +74,9 @@ void OnVRCommandNotification::Run() {
if (cmd_id == max_cmd_id + 1) {
return;
}
- const uint32_t app_id = (*message_)[strings::msg_params][strings::app_id]
- .asUInt();
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(app_id);
+ const uint32_t app_id =
+ (*message_)[strings::msg_params][strings::app_id].asUInt();
+ ApplicationSharedPtr app = application_manager_.application(app_id);
if (!app) {
LOG4CXX_ERROR(logger_, "NULL pointer");
return;
@@ -87,7 +88,7 @@ void OnVRCommandNotification::Run() {
if (0 != app->is_perform_interaction_active()) {
event_engine::Event event(hmi_apis::FunctionID::VR_OnCommand);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
} else {
(*message_)[strings::params][strings::function_id] =
static_cast<int32_t>(mobile_apis::FunctionID::eType::OnCommandID);
@@ -101,4 +102,3 @@ void OnVRCommandNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vr_language_change_notification.cc b/src/components/application_manager/src/commands/hmi/on_vr_language_change_notification.cc
index 9a146c19e7..bbdb55cde6 100644
--- a/src/components/application_manager/src/commands/hmi/on_vr_language_change_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vr_language_change_notification.cc
@@ -31,8 +31,9 @@
*/
#include "application_manager/commands/hmi/on_vr_language_change_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
+#include "application_manager/state_controller.h"
#include "application_manager/message_helper.h"
#include "interfaces/MOBILE_API.h"
@@ -41,18 +42,15 @@ namespace application_manager {
namespace commands {
OnVRLanguageChangeNotification::OnVRLanguageChangeNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVRLanguageChangeNotification::~OnVRLanguageChangeNotification() {
-}
+OnVRLanguageChangeNotification::~OnVRLanguageChangeNotification() {}
void OnVRLanguageChangeNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
hmi_capabilities.set_active_vr_language(
static_cast<hmi_apis::Common_Language::eType>(
@@ -64,23 +62,25 @@ void OnVRLanguageChangeNotification::Run() {
(*message_)[strings::params][strings::function_id] =
static_cast<int32_t>(mobile_apis::FunctionID::OnLanguageChangeID);
- ApplicationManagerImpl::ApplicationListAccessor accessor;
+ const ApplicationSet& accessor =
+ application_manager_.applications().GetData();
- ApplicationManagerImpl::ApplictionSetIt it = accessor.begin();
+ ApplicationSetConstIt it = accessor.begin();
for (; accessor.end() != it;) {
ApplicationSharedPtr app = *it++;
(*message_)[strings::params][strings::connection_key] = app->app_id();
SendNotificationToMobile(message_);
- if (static_cast<int32_t>(app->language())
- != (*message_)[strings::msg_params][strings::language].asInt()) {
-
- ApplicationManagerImpl::instance()->SetState<false>(app->app_id(),
- mobile_api::HMILevel::HMI_NONE);
-
- MessageHelper::SendOnAppInterfaceUnregisteredNotificationToMobile(
- app->app_id(),
- mobile_api::AppInterfaceUnregisteredReason::LANGUAGE_CHANGE);
- ApplicationManagerImpl::instance()->UnregisterApplication(
+ if (static_cast<int32_t>(app->language()) !=
+ (*message_)[strings::msg_params][strings::language].asInt()) {
+ application_manager_.state_controller().SetRegularState(
+ app, mobile_api::HMILevel::HMI_NONE, false);
+
+ application_manager_.ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ app->app_id(),
+ mobile_api::AppInterfaceUnregisteredReason::LANGUAGE_CHANGE),
+ commands::Command::ORIGIN_SDL);
+ application_manager_.UnregisterApplication(
app->app_id(), mobile_apis::Result::SUCCESS, false);
}
}
@@ -89,4 +89,3 @@ void OnVRLanguageChangeNotification::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vr_started_notification.cc b/src/components/application_manager/src/commands/hmi/on_vr_started_notification.cc
index 85994ad80e..68942fcf01 100644
--- a/src/components/application_manager/src/commands/hmi/on_vr_started_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vr_started_notification.cc
@@ -31,29 +31,25 @@
*/
#include "application_manager/commands/hmi/on_vr_started_notification.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
OnVRStartedNotification::OnVRStartedNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVRStartedNotification::~OnVRStartedNotification() {
-}
+OnVRStartedNotification::~OnVRStartedNotification() {}
void OnVRStartedNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::VR_Started);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/on_vr_stopped_notification.cc b/src/components/application_manager/src/commands/hmi/on_vr_stopped_notification.cc
index 89bdc18eb3..e8f9fab847 100644
--- a/src/components/application_manager/src/commands/hmi/on_vr_stopped_notification.cc
+++ b/src/components/application_manager/src/commands/hmi/on_vr_stopped_notification.cc
@@ -31,29 +31,25 @@
*/
#include "application_manager/commands/hmi/on_vr_stopped_notification.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
OnVRStoppedNotification::OnVRStoppedNotification(
- const MessageSharedPtr& message)
- : NotificationFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : NotificationFromHMI(message, application_manager) {}
-OnVRStoppedNotification::~OnVRStoppedNotification() {
-}
+OnVRStoppedNotification::~OnVRStoppedNotification() {}
void OnVRStoppedNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::VR_Stopped);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/request_from_hmi.cc b/src/components/application_manager/src/commands/hmi/request_from_hmi.cc
index 5713cf2a15..be3cd6314c 100644
--- a/src/components/application_manager/src/commands/hmi/request_from_hmi.cc
+++ b/src/components/application_manager/src/commands/hmi/request_from_hmi.cc
@@ -31,21 +31,22 @@
*/
#include "application_manager/commands/hmi/request_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
+#include "utils/make_shared.h"
namespace application_manager {
namespace commands {
-RequestFromHMI::RequestFromHMI(const MessageSharedPtr& message)
- : CommandImpl(message) {
-
+RequestFromHMI::RequestFromHMI(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandImpl(message, application_manager)
+ , EventObserver(application_manager.event_dispatcher()) {
// Replace HMI app id with Mobile connection id
- ApplicationManagerImpl::instance()->ReplaceHMIByMobileAppId(*(message.get()));
+ ReplaceHMIByMobileAppId(*(message.get()));
}
-RequestFromHMI::~RequestFromHMI() {
-}
+RequestFromHMI::~RequestFromHMI() {}
bool RequestFromHMI::Init() {
return true;
@@ -55,27 +56,51 @@ bool RequestFromHMI::CleanUp() {
return true;
}
-void RequestFromHMI::Run() {
-}
-
-void RequestFromHMI::on_event(const event_engine::Event& event) {
-}
+void RequestFromHMI::Run() {}
-void RequestFromHMI::SendResponse(uint32_t correlation_id,
- hmi_apis::FunctionID::eType function_id,
- hmi_apis::Common_Result::eType result_code) {
- smart_objects::SmartObject* message = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+void RequestFromHMI::on_event(const event_engine::Event& event) {}
- (*message)[strings::params][strings::function_id] = function_id;
+void RequestFromHMI::SendResponse(
+ const bool success,
+ const uint32_t correlation_id,
+ const hmi_apis::FunctionID::eType function_id,
+ const hmi_apis::Common_Result::eType result_code) {
+ smart_objects::SmartObject* message =
+ new smart_objects::SmartObject(smart_objects::SmartType_Map);
+ FillCommonParametersOfSO(message, correlation_id, function_id);
(*message)[strings::params][strings::message_type] = MessageType::kResponse;
- (*message)[strings::params][strings::correlation_id] = correlation_id;
- (*message)[strings::params][hmi_response::code] = result_code;
+ (*message)[strings::params][hmi_response::code] = 0;
+ (*message)[strings::msg_params][strings::success] = success;
+ (*message)[strings::msg_params][strings::result_code] = result_code;
- ApplicationManagerImpl::instance()->ManageHMICommand(message);
+ application_manager_.ManageHMICommand(message);
}
+// void RequestFromHMI::SendErrorResponse(uint32_t correlation_id,
+// hmi_apis::FunctionID::eType
+// function_id,
+// hmi_apis::Common_Result::eType
+// result_code) {
+// smart_objects::SmartObject* message = new smart_objects::SmartObject(
+// smart_objects::SmartType_Map);
+// FillCommonParametersOfSO(message, correlation_id, function_id);
+// (*message)[strings::params][strings::message_type] =
+// MessageType::kErrorResponse;
+// (*message)[strings::params][hmi_response::code] = result_code;
+// (*message)[strings::params][strings::error_msg] = "HMIDeactivate is active";
+
+// application_manager_.ManageHMICommand(message);
+//}
+
+void RequestFromHMI::FillCommonParametersOfSO(
+ smart_objects::SmartObject* message,
+ uint32_t correlation_id,
+ hmi_apis::FunctionID::eType function_id) {
+ (*message)[strings::params][strings::function_id] = function_id;
+ (*message)[strings::params][strings::protocol_type] = hmi_protocol_type_;
+ (*message)[strings::params][strings::protocol_version] = protocol_version_;
+ (*message)[strings::params][strings::correlation_id] = correlation_id;
+}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/request_to_hmi.cc b/src/components/application_manager/src/commands/hmi/request_to_hmi.cc
index 82b36be0f0..2e7d7e9df1 100644
--- a/src/components/application_manager/src/commands/hmi/request_to_hmi.cc
+++ b/src/components/application_manager/src/commands/hmi/request_to_hmi.cc
@@ -31,21 +31,19 @@
*/
#include "application_manager/commands/hmi/request_to_hmi.h"
-#include "application_manager/application_manager_impl.h"
-#include "config_profile/profile.h"
namespace application_manager {
namespace commands {
-RequestToHMI::RequestToHMI(const MessageSharedPtr& message)
- : CommandImpl(message) {
+RequestToHMI::RequestToHMI(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandImpl(message, application_manager) {
// Replace Mobile connection id with HMI app id
- ApplicationManagerImpl::instance()->ReplaceMobileByHMIAppId(*(message.get()));
+ ReplaceMobileByHMIAppId(*(message.get()));
}
-RequestToHMI::~RequestToHMI() {
-}
+RequestToHMI::~RequestToHMI() {}
bool RequestToHMI::Init() {
return true;
@@ -55,14 +53,13 @@ bool RequestToHMI::CleanUp() {
return true;
}
-void RequestToHMI::Run() {
-}
+void RequestToHMI::Run() {}
void RequestToHMI::SendRequest() {
(*message_)[strings::params][strings::protocol_type] = hmi_protocol_type_;
(*message_)[strings::params][strings::protocol_version] = protocol_version_;
- ApplicationManagerImpl::instance()->SendMessageToHMI(message_);
+ application_manager_.SendMessageToHMI(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/response_from_hmi.cc b/src/components/application_manager/src/commands/hmi/response_from_hmi.cc
index 9f6ced5974..23d8e6e229 100644
--- a/src/components/application_manager/src/commands/hmi/response_from_hmi.cc
+++ b/src/components/application_manager/src/commands/hmi/response_from_hmi.cc
@@ -31,27 +31,27 @@
*/
#include "application_manager/commands/hmi/response_from_hmi.h"
-#include "application_manager/application_manager_impl.h"
+
#include "smart_objects/smart_object.h"
namespace application_manager {
namespace commands {
-ResponseFromHMI::ResponseFromHMI(const MessageSharedPtr& message)
- : CommandImpl(message) {
- //If it is error response, shift info
+ResponseFromHMI::ResponseFromHMI(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandImpl(message, application_manager) {
+ // If it is error response, shift info
if ((*message)[strings::params].keyExists(hmi_response::message)) {
(*message)[strings::msg_params][strings::info] =
(*message)[strings::params][hmi_response::message];
}
// Replace HMI app id with Mobile connection id
- ApplicationManagerImpl::instance()->ReplaceHMIByMobileAppId(*(message.get()));
+ ReplaceHMIByMobileAppId(*(message.get()));
}
-ResponseFromHMI::~ResponseFromHMI() {
-}
+ResponseFromHMI::~ResponseFromHMI() {}
bool ResponseFromHMI::Init() {
return true;
@@ -61,19 +61,18 @@ bool ResponseFromHMI::CleanUp() {
return true;
}
-void ResponseFromHMI::Run() {
-}
+void ResponseFromHMI::Run() {}
-void ResponseFromHMI::SendResponseToMobile(const MessageSharedPtr& message) {
+void ResponseFromHMI::SendResponseToMobile(
+ const MessageSharedPtr& message, ApplicationManager& application_manager) {
(*message)[strings::params][strings::message_type] = MessageType::kResponse;
- ApplicationManagerImpl::instance()->ManageMobileCommand(message);
+ application_manager_.ManageMobileCommand(message, ORIGIN_SDL);
}
void ResponseFromHMI::CreateHMIRequest(
const hmi_apis::FunctionID::eType& function_id,
const smart_objects::SmartObject& msg_params) const {
-
smart_objects::SmartObjectSPtr result = new smart_objects::SmartObject;
if (!result) {
@@ -82,8 +81,8 @@ void ResponseFromHMI::CreateHMIRequest(
}
// get hmi correlation id for chaining further request from this object
- const uint32_t hmi_correlation_id_ = ApplicationManagerImpl::instance()
- ->GetNextHMICorrelationID();
+ const uint32_t hmi_correlation_id_ =
+ application_manager_.GetNextHMICorrelationID();
NsSmartDeviceLink::NsSmartObjects::SmartObject& request = *result;
request[strings::params][strings::message_type] = MessageType::kRequest;
@@ -96,7 +95,7 @@ void ResponseFromHMI::CreateHMIRequest(
request[strings::msg_params] = msg_params;
- if (!ApplicationManagerImpl::instance()->ManageHMICommand(result)) {
+ if (!application_manager_.ManageHMICommand(result)) {
LOG4CXX_ERROR(logger_, "Unable to send request");
return;
}
diff --git a/src/components/application_manager/src/commands/hmi/response_to_hmi.cc b/src/components/application_manager/src/commands/hmi/response_to_hmi.cc
index d18987428e..e6f64047ba 100644
--- a/src/components/application_manager/src/commands/hmi/response_to_hmi.cc
+++ b/src/components/application_manager/src/commands/hmi/response_to_hmi.cc
@@ -31,20 +31,20 @@
*/
#include "application_manager/commands/hmi/response_to_hmi.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
-ResponseToHMI::ResponseToHMI(const MessageSharedPtr& message)
- : CommandImpl(message) {
+ResponseToHMI::ResponseToHMI(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandImpl(message, application_manager) {
// Replace Mobile connection id with HMI app id
- ApplicationManagerImpl::instance()->ReplaceMobileByHMIAppId(*(message.get()));
+ ReplaceMobileByHMIAppId(*(message.get()));
}
-ResponseToHMI::~ResponseToHMI() {
-}
+ResponseToHMI::~ResponseToHMI() {}
bool ResponseToHMI::Init() {
return true;
@@ -58,9 +58,8 @@ void ResponseToHMI::Run() {
(*message_)[strings::params][strings::protocol_type] = hmi_protocol_type_;
(*message_)[strings::params][strings::protocol_version] = protocol_version_;
- ApplicationManagerImpl::instance()->SendMessageToHMI(message_);
+ application_manager_.SendMessageToHMI(message_);
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/sdl_activate_app_request.cc b/src/components/application_manager/src/commands/hmi/sdl_activate_app_request.cc
index af55040ad1..30ea41e0b0 100644
--- a/src/components/application_manager/src/commands/hmi/sdl_activate_app_request.cc
+++ b/src/components/application_manager/src/commands/hmi/sdl_activate_app_request.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -31,19 +31,58 @@
*/
#include "application_manager/commands/hmi/sdl_activate_app_request.h"
-#include "application_manager/policies/policy_handler.h"
+#include "application_manager/state_controller.h"
#include "application_manager/message_helper.h"
namespace application_manager {
namespace commands {
-SDLActivateAppRequest::SDLActivateAppRequest(const MessageSharedPtr& message)
- : RequestFromHMI(message) {
+namespace {
+struct ProtoV4AppsOnDevice : std::unary_function<ApplicationSharedPtr, bool> {
+ connection_handler::DeviceHandle handle_;
+ ProtoV4AppsOnDevice(const connection_handler::DeviceHandle handle)
+ : handle_(handle) {}
+ bool operator()(const ApplicationSharedPtr app) const {
+ return app
+ ? handle_ == app->device() &&
+ ProtocolVersion::kV4 == app->protocol_version()
+ : false;
+ }
+};
+
+struct ForegroundApp
+ : std::unary_function<SDLActivateAppRequest::V4ProtoApps::value_type,
+ bool> {
+ bool operator()(
+ const SDLActivateAppRequest::V4ProtoApps::value_type ptr) const {
+ return ptr ? ptr->is_foreground() : false;
+ }
+};
+
+struct SendLaunchApp
+ : std::unary_function<SDLActivateAppRequest::V4ProtoApps::value_type,
+ void> {
+ ApplicationConstSharedPtr app_to_launch_;
+ ApplicationManager& application_manager_;
+ SendLaunchApp(ApplicationConstSharedPtr app_to_launch, ApplicationManager& am)
+ : app_to_launch_(app_to_launch), application_manager_(am) {}
+ void operator()(
+ const SDLActivateAppRequest::V4ProtoApps::value_type ptr) const {
+ MessageHelper::SendLaunchApp((*ptr).app_id(),
+ app_to_launch_->SchemaUrl(),
+ app_to_launch_->PackageName(),
+ application_manager_);
+ return;
+ }
+};
}
-SDLActivateAppRequest::~SDLActivateAppRequest() {
-}
+SDLActivateAppRequest::SDLActivateAppRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestFromHMI(message, application_manager) {}
+
+SDLActivateAppRequest::~SDLActivateAppRequest() {}
void SDLActivateAppRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,49 +91,73 @@ void SDLActivateAppRequest::Run() {
const uint32_t application_id = app_id();
- ApplicationConstSharedPtr app =
- ApplicationManagerImpl::instance()->application(application_id);
+ ApplicationConstSharedPtr app_to_activate =
+ application_manager_.application(application_id);
+
+ if (!app_to_activate) {
+ LOG4CXX_WARN(
+ logger_,
+ "Can't find application within regular apps: " << application_id);
+
+ // Here is the hack - in fact SDL gets hmi_app_id in appID field and
+ // replaces it with connection_key only for normally registered apps, but
+ // for apps_to_be_registered (waiting) it keeps original value (hmi_app_id)
+ // so method does lookup for hmi_app_id
+ app_to_activate =
+ application_manager_.WaitingApplicationByID(application_id);
+
+ if (!app_to_activate) {
+ LOG4CXX_WARN(
+ logger_,
+ "Can't find application within waiting apps: " << application_id);
+ return;
+ }
+ }
+
+ LOG4CXX_DEBUG(logger_,
+ "Found application to activate. Application id is "
+ << app_to_activate->app_id());
- if (!app) {
- LOG4CXX_WARN(logger_, "Can't find application within regular apps: "
- << application_id);
+ if (app_to_activate->IsRegistered()) {
+ LOG4CXX_DEBUG(logger_, "Application is registered. Activating.");
+ application_manager_.GetPolicyHandler().OnActivateApp(application_id,
+ correlation_id());
+ return;
+ }
- app = ApplicationManagerImpl::instance()->waiting_app(application_id);
+ connection_handler::DeviceHandle device_handle = app_to_activate->device();
+ ApplicationSharedPtr foreground_v4_app = get_foreground_app(device_handle);
+ V4ProtoApps v4_proto_apps = get_v4_proto_apps(device_handle);
- if (!app) {
- LOG4CXX_WARN(logger_, "Can't find application within waiting apps: "
- << application_id);
- return;
- }
+ if (!foreground_v4_app && v4_proto_apps.empty()) {
+ LOG4CXX_ERROR(logger_,
+ "Can't find regular foreground app with the same "
+ "connection id:"
+ << device_handle);
+ SendResponse(false, correlation_id(), SDL_ActivateApp, NO_APPS_REGISTERED);
+ return;
}
- if (!app->IsRegistered()) {
- DevicesApps devices_apps =
- FindAllAppOnParticularDevice(app->device());
- if (!devices_apps.first && devices_apps.second.empty()) {
- LOG4CXX_ERROR(logger_, "Can't find regular foreground app with the same "
- "connection id:" << app->device());
- SendResponse(correlation_id(),
- SDL_ActivateApp, NO_APPS_REGISTERED);
- return;
- }
- if (devices_apps.first) {
- MessageHelper::SendLaunchApp(devices_apps.first->app_id(),
- app->SchemaUrl(),
- app->PackageName());
- } else {
- std::vector<ApplicationSharedPtr>::const_iterator it = devices_apps.second.begin();
- for (; it != devices_apps.second.end(); ++it) {
- MessageHelper::SendLaunchApp((*it)->app_id(),
- app->SchemaUrl(),
- app->PackageName());
- }
- }
- subscribe_on_event(BasicCommunication_OnAppRegistered);
+ LOG4CXX_DEBUG(logger_,
+ "Application is not registered yet. "
+ "Sending launch request.");
+
+ if (foreground_v4_app) {
+ LOG4CXX_DEBUG(logger_, "Sending request to foreground application.");
+ MessageHelper::SendLaunchApp(foreground_v4_app->app_id(),
+ app_to_activate->SchemaUrl(),
+ app_to_activate->PackageName(),
+ application_manager_);
} else {
- policy::PolicyHandler::instance()->OnActivateApp(application_id,
- correlation_id());
+ LOG4CXX_DEBUG(logger_,
+ "No preffered (foreground) application is found. "
+ "Sending request to all v4 applications.");
+ std::for_each(v4_proto_apps.begin(),
+ v4_proto_apps.end(),
+ SendLaunchApp(app_to_activate, application_manager_));
}
+
+ subscribe_on_event(BasicCommunication_OnAppRegistered);
}
void SDLActivateAppRequest::onTimeOut() {
@@ -102,8 +165,8 @@ void SDLActivateAppRequest::onTimeOut() {
using namespace hmi_apis::Common_Result;
using namespace application_manager;
unsubscribe_from_event(BasicCommunication_OnAppRegistered);
- SendResponse(correlation_id(),
- SDL_ActivateApp, APPLICATION_NOT_REGISTERED);
+ SendResponse(
+ false, correlation_id(), SDL_ActivateApp, APPLICATION_NOT_REGISTERED);
}
void SDLActivateAppRequest::on_event(const event_engine::Event& event) {
@@ -119,64 +182,68 @@ void SDLActivateAppRequest::on_event(const event_engine::Event& event) {
const uint32_t hmi_application_id = hmi_app_id(event.smart_object());
ApplicationSharedPtr app =
- application_manager::ApplicationManagerImpl::instance()->
- application_by_hmi_app(hmi_application_id);
+ application_manager_.application_by_hmi_app(hmi_application_id);
if (!app) {
- LOG4CXX_ERROR(logger_, "Application not found by HMI app id: "
- << hmi_application_id);
+ LOG4CXX_ERROR(
+ logger_, "Application not found by HMI app id: " << hmi_application_id);
return;
}
- policy::PolicyHandler::instance()->OnActivateApp(app->app_id(),
- correlation_id());
+ application_manager_.GetPolicyHandler().OnActivateApp(app->app_id(),
+ correlation_id());
}
uint32_t SDLActivateAppRequest::app_id() const {
- if ((*message_).keyExists(strings::msg_params)) {
- if ((*message_)[strings::msg_params].keyExists(strings::app_id)){
- return (*message_)[strings::msg_params][strings::app_id].asUInt();
- }
+ using namespace strings;
+ if (!(*message_).keyExists(msg_params)) {
+ LOG4CXX_DEBUG(logger_, msg_params << " section is absent in the message.");
+ return 0;
}
- LOG4CXX_DEBUG(logger_, "app_id section is absent in the message.");
- return 0;
+ if (!(*message_)[msg_params].keyExists(strings::app_id)) {
+ LOG4CXX_DEBUG(logger_,
+ strings::app_id << " section is absent in the message.");
+ return 0;
+ }
+ return (*message_)[msg_params][strings::app_id].asUInt();
}
uint32_t SDLActivateAppRequest::hmi_app_id(
const smart_objects::SmartObject& so) const {
- if (so.keyExists(strings::params)) {
- if (so[strings::msg_params].keyExists(strings::application)){
- if (so[strings::msg_params][strings::application].
- keyExists(strings::app_id)) {
- return so[strings::msg_params][strings::application]
- [strings::app_id].asUInt();
- }
- }
+ using namespace strings;
+ if (!so.keyExists(params)) {
+ LOG4CXX_DEBUG(logger_, params << " section is absent in the message.");
+ return 0;
}
- LOG4CXX_DEBUG(logger_, "Can't find app_id section is absent in the message.");
- return 0;
+ if (!so[msg_params].keyExists(application)) {
+ LOG4CXX_DEBUG(logger_, application << " section is absent in the message.");
+ return 0;
+ }
+ if (so[msg_params][application].keyExists(strings::app_id)) {
+ LOG4CXX_DEBUG(logger_,
+ strings::app_id << " section is absent in the message.");
+ return 0;
+ }
+ return so[msg_params][application][strings::app_id].asUInt();
}
-DevicesApps
-SDLActivateAppRequest::FindAllAppOnParticularDevice(
- const connection_handler::DeviceHandle handle) {
- DevicesApps apps;
-
- ApplicationManagerImpl::ApplicationListAccessor accessor;
- ApplicationManagerImpl::ApplictionSet app_list = accessor.GetData();
-
- ApplicationManagerImpl::ApplictionSetIt it = app_list.begin();
- ApplicationManagerImpl::ApplictionSetIt it_end = app_list.end();
+SDLActivateAppRequest::V4ProtoApps SDLActivateAppRequest::get_v4_proto_apps(
+ const connection_handler::DeviceHandle handle) const {
+ const ApplicationSet app_list = application_manager_.applications().GetData();
+ V4ProtoApps v4_proto_apps;
+ std::copy_if(app_list.begin(),
+ app_list.end(),
+ std::back_inserter(v4_proto_apps),
+ ProtoV4AppsOnDevice(handle));
+ return v4_proto_apps;
+}
- for (;it != it_end; ++it) {
- if (handle == (*it)->device()) {
- if ((*it)->is_foreground()) {
- apps.first = *it;
- }
- apps.second.push_back(*it);
- }
- }
- return apps;
+ApplicationSharedPtr SDLActivateAppRequest::get_foreground_app(
+ const connection_handler::DeviceHandle handle) const {
+ V4ProtoApps v4_proto_apps = get_v4_proto_apps(handle);
+ V4ProtoApps::iterator foreground_app =
+ std::find_if(v4_proto_apps.begin(), v4_proto_apps.end(), ForegroundApp());
+ return foreground_app != v4_proto_apps.end() ? *foreground_app
+ : ApplicationSharedPtr();
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/sdl_activate_app_response.cc b/src/components/application_manager/src/commands/hmi/sdl_activate_app_response.cc
index 6c7a0b5355..75a8c0b241 100644
--- a/src/components/application_manager/src/commands/hmi/sdl_activate_app_response.cc
+++ b/src/components/application_manager/src/commands/hmi/sdl_activate_app_response.cc
@@ -31,28 +31,24 @@
*/
#include "application_manager/commands/hmi/sdl_activate_app_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
SDLActivateAppResponse::SDLActivateAppResponse(
- const MessageSharedPtr& message): ResponseToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseToHMI(message, application_manager) {}
-SDLActivateAppResponse::~SDLActivateAppResponse() {
-}
+SDLActivateAppResponse::~SDLActivateAppResponse() {}
void SDLActivateAppResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
(*message_)[strings::params][strings::protocol_type] = hmi_protocol_type_;
(*message_)[strings::params][strings::protocol_version] = protocol_version_;
- ApplicationManagerImpl::instance()->SendMessageToHMI(message_);
+ application_manager_.SendMessageToHMI(message_);
}
} // namespace commands
} // namespace application_manager
-
-
diff --git a/src/components/application_manager/src/commands/hmi/sdl_get_list_of_permissions_request.cc b/src/components/application_manager/src/commands/hmi/sdl_get_list_of_permissions_request.cc
index a6649b2579..4b150cda60 100644
--- a/src/components/application_manager/src/commands/hmi/sdl_get_list_of_permissions_request.cc
+++ b/src/components/application_manager/src/commands/hmi/sdl_get_list_of_permissions_request.cc
@@ -31,19 +31,17 @@
*/
#include "application_manager/commands/hmi/sdl_get_list_of_permissions_request.h"
-#include "application_manager/policies/policy_handler.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
SDLGetListOfPermissionsRequest::SDLGetListOfPermissionsRequest(
- const MessageSharedPtr& message)
- : RequestFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestFromHMI(message, application_manager) {}
-SDLGetListOfPermissionsRequest::~SDLGetListOfPermissionsRequest() {
-}
+SDLGetListOfPermissionsRequest::~SDLGetListOfPermissionsRequest() {}
void SDLGetListOfPermissionsRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -51,12 +49,10 @@ void SDLGetListOfPermissionsRequest::Run() {
if ((*message_)[strings::msg_params].keyExists(strings::app_id)) {
connection_key = (*message_)[strings::msg_params][strings::app_id].asUInt();
}
- policy::PolicyHandler::instance()->OnGetListOfPermissions(
- connection_key,
- (*message_)[strings::params][strings::correlation_id].asUInt());
+ application_manager_.GetPolicyHandler().OnGetListOfPermissions(
+ connection_key,
+ (*message_)[strings::params][strings::correlation_id].asUInt());
}
} // namespace commands
} // namespace application_manager
-
-
diff --git a/src/components/application_manager/src/commands/hmi/sdl_get_list_of_permissions_response.cc b/src/components/application_manager/src/commands/hmi/sdl_get_list_of_permissions_response.cc
index 5d5e75e5c7..521b59a0ec 100644
--- a/src/components/application_manager/src/commands/hmi/sdl_get_list_of_permissions_response.cc
+++ b/src/components/application_manager/src/commands/hmi/sdl_get_list_of_permissions_response.cc
@@ -31,28 +31,24 @@
*/
#include "application_manager/commands/hmi/sdl_get_list_of_permissions_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
SDLGetListOfPermissionsResponse::SDLGetListOfPermissionsResponse(
- const MessageSharedPtr& message): ResponseToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseToHMI(message, application_manager) {}
-SDLGetListOfPermissionsResponse::~SDLGetListOfPermissionsResponse() {
-}
+SDLGetListOfPermissionsResponse::~SDLGetListOfPermissionsResponse() {}
void SDLGetListOfPermissionsResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
(*message_)[strings::params][strings::protocol_type] = hmi_protocol_type_;
(*message_)[strings::params][strings::protocol_version] = protocol_version_;
- ApplicationManagerImpl::instance()->SendMessageToHMI(message_);
+ application_manager_.SendMessageToHMI(message_);
}
} // namespace commands
} // namespace application_manager
-
-
diff --git a/src/components/application_manager/src/commands/hmi/sdl_get_status_update_request.cc b/src/components/application_manager/src/commands/hmi/sdl_get_status_update_request.cc
index dd977d99f0..afa7569746 100644
--- a/src/components/application_manager/src/commands/hmi/sdl_get_status_update_request.cc
+++ b/src/components/application_manager/src/commands/hmi/sdl_get_status_update_request.cc
@@ -31,26 +31,23 @@
*/
#include "application_manager/commands/hmi/sdl_get_status_update_request.h"
-#include "application_manager/policies/policy_handler.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
-SDLGetStatusUpdateRequest::SDLGetStatusUpdateRequest(const MessageSharedPtr& message)
- : RequestFromHMI(message) {
-}
+SDLGetStatusUpdateRequest::SDLGetStatusUpdateRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestFromHMI(message, application_manager) {}
-SDLGetStatusUpdateRequest::~SDLGetStatusUpdateRequest() {
-}
+SDLGetStatusUpdateRequest::~SDLGetStatusUpdateRequest() {}
void SDLGetStatusUpdateRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- policy::PolicyHandler::instance()->OnGetStatusUpdate(
- (*message_)[strings::params][strings::correlation_id].asUInt());
+ application_manager_.GetPolicyHandler().OnGetStatusUpdate(
+ (*message_)[strings::params][strings::correlation_id].asUInt());
}
} // namespace commands
} // namespace application_manager
-
-
diff --git a/src/components/application_manager/src/commands/hmi/sdl_get_status_update_response.cc b/src/components/application_manager/src/commands/hmi/sdl_get_status_update_response.cc
index ab1c57e9af..0af7e0217a 100644
--- a/src/components/application_manager/src/commands/hmi/sdl_get_status_update_response.cc
+++ b/src/components/application_manager/src/commands/hmi/sdl_get_status_update_response.cc
@@ -31,29 +31,24 @@
*/
#include "application_manager/commands/hmi/sdl_get_status_update_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
SDLGetStatusUpdateResponse::SDLGetStatusUpdateResponse(
- const MessageSharedPtr& message): ResponseToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseToHMI(message, application_manager) {}
-SDLGetStatusUpdateResponse::~SDLGetStatusUpdateResponse() {
-}
+SDLGetStatusUpdateResponse::~SDLGetStatusUpdateResponse() {}
void SDLGetStatusUpdateResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
(*message_)[strings::params][strings::protocol_type] = hmi_protocol_type_;
(*message_)[strings::params][strings::protocol_version] = protocol_version_;
- ApplicationManagerImpl::instance()->SendMessageToHMI(message_);
+ application_manager_.SendMessageToHMI(message_);
}
} // namespace commands
} // namespace application_manager
-
-
-
diff --git a/src/components/application_manager/src/commands/hmi/sdl_get_user_friendly_message_request.cc b/src/components/application_manager/src/commands/hmi/sdl_get_user_friendly_message_request.cc
index cdd5c16ed0..ea959389ef 100644
--- a/src/components/application_manager/src/commands/hmi/sdl_get_user_friendly_message_request.cc
+++ b/src/components/application_manager/src/commands/hmi/sdl_get_user_friendly_message_request.cc
@@ -31,28 +31,24 @@
*/
#include "application_manager/commands/hmi/sdl_get_user_friendly_message_request.h"
-#include "application_manager/application_manager_impl.h"
#include "application_manager/message_helper.h"
-#include "application_manager/policies/policy_handler.h"
namespace application_manager {
namespace commands {
SDLGetUserFriendlyMessageRequest::SDLGetUserFriendlyMessageRequest(
- const MessageSharedPtr& message)
- : RequestFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestFromHMI(message, application_manager) {}
-SDLGetUserFriendlyMessageRequest::~SDLGetUserFriendlyMessageRequest() {
-}
+SDLGetUserFriendlyMessageRequest::~SDLGetUserFriendlyMessageRequest() {}
void SDLGetUserFriendlyMessageRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
const std::string messageCodes = "messageCodes";
if (!(*message_)[strings::msg_params].keyExists(messageCodes)) {
LOG4CXX_WARN(logger_,
- "Mandatory parameter '"+messageCodes+"'' is missing");
+ "Mandatory parameter '" + messageCodes + "'' is missing");
return;
}
smart_objects::SmartArray* msg =
@@ -68,26 +64,24 @@ void SDLGetUserFriendlyMessageRequest::Run() {
std::string required_language;
if ((*message_)[strings::msg_params].keyExists(strings::language)) {
- uint32_t lang_code = (*message_)[strings::msg_params][strings::language]
- .asUInt();
+ uint32_t lang_code =
+ (*message_)[strings::msg_params][strings::language].asUInt();
required_language =
application_manager::MessageHelper::CommonLanguageToString(
- static_cast<hmi_apis::Common_Language::eType>(lang_code));
+ static_cast<hmi_apis::Common_Language::eType>(lang_code));
} else {
hmi_apis::Common_Language::eType ui_language =
- application_manager::ApplicationManagerImpl::instance()
- ->hmi_capabilities().active_ui_language();
+ application_manager_.hmi_capabilities().active_ui_language();
required_language =
application_manager::MessageHelper::CommonLanguageToString(ui_language);
}
- policy::PolicyHandler::instance()->OnGetUserFriendlyMessage(
- msg_codes, required_language,
- (*message_)[strings::params][strings::correlation_id].asInt());
+ application_manager_.GetPolicyHandler().OnGetUserFriendlyMessage(
+ msg_codes,
+ required_language,
+ (*message_)[strings::params][strings::correlation_id].asInt());
}
} // namespace commands
} // namespace application_manager
-
-
diff --git a/src/components/application_manager/src/commands/hmi/sdl_get_user_friendly_message_response.cc b/src/components/application_manager/src/commands/hmi/sdl_get_user_friendly_message_response.cc
index 8cc1b2d629..c693625dbb 100644
--- a/src/components/application_manager/src/commands/hmi/sdl_get_user_friendly_message_response.cc
+++ b/src/components/application_manager/src/commands/hmi/sdl_get_user_friendly_message_response.cc
@@ -31,28 +31,24 @@
*/
#include "application_manager/commands/hmi/sdl_get_user_friendly_message_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
SDLGetUserFriendlyMessageResponse::SDLGetUserFriendlyMessageResponse(
- const MessageSharedPtr& message): ResponseToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseToHMI(message, application_manager) {}
-SDLGetUserFriendlyMessageResponse::~SDLGetUserFriendlyMessageResponse() {
-}
+SDLGetUserFriendlyMessageResponse::~SDLGetUserFriendlyMessageResponse() {}
void SDLGetUserFriendlyMessageResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
(*message_)[strings::params][strings::protocol_type] = hmi_protocol_type_;
(*message_)[strings::params][strings::protocol_version] = protocol_version_;
- ApplicationManagerImpl::instance()->SendMessageToHMI(message_);
+ application_manager_.SendMessageToHMI(message_);
}
} // namespace commands
} // namespace application_manager
-
-
diff --git a/src/components/application_manager/src/commands/hmi/sdl_policy_update.cc b/src/components/application_manager/src/commands/hmi/sdl_policy_update.cc
index e1fe835224..e79bca14de 100644
--- a/src/components/application_manager/src/commands/hmi/sdl_policy_update.cc
+++ b/src/components/application_manager/src/commands/hmi/sdl_policy_update.cc
@@ -36,8 +36,9 @@ namespace application_manager {
namespace commands {
-SDLPolicyUpdate::SDLPolicyUpdate(const MessageSharedPtr& message)
- : RequestToHMI(message) {}
+SDLPolicyUpdate::SDLPolicyUpdate(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
SDLPolicyUpdate::~SDLPolicyUpdate() {}
diff --git a/src/components/application_manager/src/commands/hmi/sdl_policy_update_response.cc b/src/components/application_manager/src/commands/hmi/sdl_policy_update_response.cc
index bc7c6e0d74..38b57a5b9f 100644
--- a/src/components/application_manager/src/commands/hmi/sdl_policy_update_response.cc
+++ b/src/components/application_manager/src/commands/hmi/sdl_policy_update_response.cc
@@ -36,11 +36,10 @@ namespace application_manager {
namespace commands {
SDLPolicyUpdateResponse::SDLPolicyUpdateResponse(
- const MessageSharedPtr& message): ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-SDLPolicyUpdateResponse::~SDLPolicyUpdateResponse() {
-}
+SDLPolicyUpdateResponse::~SDLPolicyUpdateResponse() {}
void SDLPolicyUpdateResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/hmi/tts_change_registration_request.cc b/src/components/application_manager/src/commands/hmi/tts_change_registration_request.cc
index dd127ec43f..bb1f29d889 100644
--- a/src/components/application_manager/src/commands/hmi/tts_change_registration_request.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_change_registration_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
TTSChangeRegistrationRequest::TTSChangeRegistrationRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-TTSChangeRegistrationRequest::~TTSChangeRegistrationRequest() {
-}
+TTSChangeRegistrationRequest::~TTSChangeRegistrationRequest() {}
void TTSChangeRegistrationRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void TTSChangeRegistrationRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/tts_change_registration_response.cc b/src/components/application_manager/src/commands/hmi/tts_change_registration_response.cc
index 03b51e5db7..e63ee5f74d 100644
--- a/src/components/application_manager/src/commands/hmi/tts_change_registration_response.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_change_registration_response.cc
@@ -31,6 +31,7 @@
*/
#include "application_manager/commands/hmi/tts_change_registration_response.h"
#include "application_manager/event_engine/event.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
@@ -38,19 +39,17 @@ namespace application_manager {
namespace commands {
TTSChangeRegistratioResponse::TTSChangeRegistratioResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-TTSChangeRegistratioResponse::~TTSChangeRegistratioResponse() {
-}
+TTSChangeRegistratioResponse::~TTSChangeRegistratioResponse() {}
void TTSChangeRegistratioResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::TTS_ChangeRegistration);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/tts_get_capabilities_request.cc b/src/components/application_manager/src/commands/hmi/tts_get_capabilities_request.cc
index fb3dedc1c0..4dbf5e8ee7 100644
--- a/src/components/application_manager/src/commands/hmi/tts_get_capabilities_request.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_get_capabilities_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
TTSGetCapabilitiesRequest::TTSGetCapabilitiesRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-TTSGetCapabilitiesRequest::~TTSGetCapabilitiesRequest() {
-}
+TTSGetCapabilitiesRequest::~TTSGetCapabilitiesRequest() {}
void TTSGetCapabilitiesRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void TTSGetCapabilitiesRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/tts_get_capabilities_response.cc b/src/components/application_manager/src/commands/hmi/tts_get_capabilities_response.cc
index 53a1bd3916..ce629b36d7 100644
--- a/src/components/application_manager/src/commands/hmi/tts_get_capabilities_response.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_get_capabilities_response.cc
@@ -30,36 +30,32 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/tts_get_capabilities_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
TTSGetCapabilitiesResponse::TTSGetCapabilitiesResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-TTSGetCapabilitiesResponse::~TTSGetCapabilitiesResponse() {
-}
+TTSGetCapabilitiesResponse::~TTSGetCapabilitiesResponse() {}
void TTSGetCapabilitiesResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
- if ((*message_)[strings::msg_params].keyExists(hmi_response::speech_capabilities)) {
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
+ if ((*message_)[strings::msg_params].keyExists(
+ hmi_response::speech_capabilities)) {
hmi_capabilities.set_speech_capabilities(
- (*message_)[strings::msg_params][hmi_response::speech_capabilities]);
+ (*message_)[strings::msg_params][hmi_response::speech_capabilities]);
}
if ((*message_)[strings::msg_params].keyExists(
- hmi_response::prerecorded_speech_capabilities)) {
+ hmi_response::prerecorded_speech_capabilities)) {
hmi_capabilities.set_prerecorded_speech(
(*message_)[strings::msg_params]
- [hmi_response::prerecorded_speech_capabilities]);
+ [hmi_response::prerecorded_speech_capabilities]);
}
-
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/tts_get_language_request.cc b/src/components/application_manager/src/commands/hmi/tts_get_language_request.cc
index 6d4e4f465a..c44667a223 100644
--- a/src/components/application_manager/src/commands/hmi/tts_get_language_request.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_get_language_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-TTSGetLanguageRequest::TTSGetLanguageRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+TTSGetLanguageRequest::TTSGetLanguageRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-TTSGetLanguageRequest::~TTSGetLanguageRequest() {
-}
+TTSGetLanguageRequest::~TTSGetLanguageRequest() {}
void TTSGetLanguageRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void TTSGetLanguageRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/tts_get_language_response.cc b/src/components/application_manager/src/commands/hmi/tts_get_language_response.cc
index 6c2122557b..37aed2c6cb 100644
--- a/src/components/application_manager/src/commands/hmi/tts_get_language_response.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_get_language_response.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,28 +30,40 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/tts_get_language_response.h"
-#include "application_manager/application_manager_impl.h"
+
+#include "application_manager/event_engine/event.h"
namespace application_manager {
namespace commands {
-TTSGetLanguageResponse::TTSGetLanguageResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+TTSGetLanguageResponse::TTSGetLanguageResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-TTSGetLanguageResponse::~TTSGetLanguageResponse() {
-}
+TTSGetLanguageResponse::~TTSGetLanguageResponse() {}
void TTSGetLanguageResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace hmi_apis;
+
+ Common_Language::eType language = Common_Language::INVALID_ENUM;
+
+ if ((*message_).keyExists(strings::msg_params) &&
+ (*message_)[strings::msg_params].keyExists(hmi_response::language)) {
+ language = static_cast<Common_Language::eType>(
+ (*message_)[strings::msg_params][hmi_response::language].asInt());
+ }
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ application_manager_.hmi_capabilities().set_active_tts_language(language);
- hmi_capabilities.set_active_tts_language(
- static_cast<hmi_apis::Common_Language::eType>(
- (*message_)[strings::msg_params][hmi_response::language].asInt()));
+ LOG4CXX_DEBUG(logger_,
+ "Raising event for function_id " << function_id()
+ << " and correlation_id "
+ << correlation_id());
+ event_engine::Event event(FunctionID::TTS_GetLanguage);
+ event.set_smart_object(*message_);
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/tts_get_supported_languages_request.cc b/src/components/application_manager/src/commands/hmi/tts_get_supported_languages_request.cc
index 5251832bc1..941adca01d 100644
--- a/src/components/application_manager/src/commands/hmi/tts_get_supported_languages_request.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_get_supported_languages_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
TTSGetSupportedLanguagesRequest::TTSGetSupportedLanguagesRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-TTSGetSupportedLanguagesRequest::~TTSGetSupportedLanguagesRequest() {
-}
+TTSGetSupportedLanguagesRequest::~TTSGetSupportedLanguagesRequest() {}
void TTSGetSupportedLanguagesRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void TTSGetSupportedLanguagesRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/tts_get_supported_languages_response.cc b/src/components/application_manager/src/commands/hmi/tts_get_supported_languages_response.cc
index a5d022a6cb..79af1d3cc2 100644
--- a/src/components/application_manager/src/commands/hmi/tts_get_supported_languages_response.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_get_supported_languages_response.cc
@@ -30,7 +30,7 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/tts_get_supported_languages_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
TTSGetSupportedLanguagesResponse::TTSGetSupportedLanguagesResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-TTSGetSupportedLanguagesResponse::~TTSGetSupportedLanguagesResponse() {
-}
+TTSGetSupportedLanguagesResponse::~TTSGetSupportedLanguagesResponse() {}
void TTSGetSupportedLanguagesResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,8 +51,7 @@ void TTSGetSupportedLanguagesResponse::Run() {
(*message_)[strings::params][hmi_response::code].asInt());
if (hmi_apis::Common_Result::SUCCESS == code) {
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
hmi_capabilities.set_tts_supported_languages(
(*message_)[strings::msg_params][hmi_response::languages]);
diff --git a/src/components/application_manager/src/commands/hmi/tts_is_ready_request.cc b/src/components/application_manager/src/commands/hmi/tts_is_ready_request.cc
index 3a50cfef90..e7fd335808 100644
--- a/src/components/application_manager/src/commands/hmi/tts_is_ready_request.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_is_ready_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-TTSIsReadyRequest::TTSIsReadyRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+TTSIsReadyRequest::TTSIsReadyRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-TTSIsReadyRequest::~TTSIsReadyRequest() {
-}
+TTSIsReadyRequest::~TTSIsReadyRequest() {}
void TTSIsReadyRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void TTSIsReadyRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/tts_is_ready_response.cc b/src/components/application_manager/src/commands/hmi/tts_is_ready_response.cc
index dd8eab7534..91efb293c9 100644
--- a/src/components/application_manager/src/commands/hmi/tts_is_ready_response.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_is_ready_response.cc
@@ -30,18 +30,16 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/tts_is_ready_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-TTSIsReadyResponse::TTSIsReadyResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+TTSIsReadyResponse::TTSIsReadyResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-TTSIsReadyResponse::~TTSIsReadyResponse() {
-}
+TTSIsReadyResponse::~TTSIsReadyResponse() {}
void TTSIsReadyResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,8 +50,7 @@ void TTSIsReadyResponse::Run() {
is_available = object[strings::msg_params][strings::available].asBool();
}
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
hmi_capabilities.set_is_tts_cooperating(is_available);
}
diff --git a/src/components/application_manager/src/commands/hmi/tts_set_global_properties_request.cc b/src/components/application_manager/src/commands/hmi/tts_set_global_properties_request.cc
index ce330c355f..bf035ffe23 100644
--- a/src/components/application_manager/src/commands/hmi/tts_set_global_properties_request.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_set_global_properties_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
TTSSetGlobalPropertiesRequest::TTSSetGlobalPropertiesRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-TTSSetGlobalPropertiesRequest::~TTSSetGlobalPropertiesRequest() {
-}
+TTSSetGlobalPropertiesRequest::~TTSSetGlobalPropertiesRequest() {}
void TTSSetGlobalPropertiesRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void TTSSetGlobalPropertiesRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/tts_set_global_properties_response.cc b/src/components/application_manager/src/commands/hmi/tts_set_global_properties_response.cc
index 70dc46d6a6..f494fb1a8e 100644
--- a/src/components/application_manager/src/commands/hmi/tts_set_global_properties_response.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_set_global_properties_response.cc
@@ -31,6 +31,7 @@
*/
#include "application_manager/commands/hmi/tts_set_global_properties_response.h"
#include "application_manager/event_engine/event.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
@@ -38,19 +39,17 @@ namespace application_manager {
namespace commands {
TTSSetGlobalPropertiesResponse::TTSSetGlobalPropertiesResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-TTSSetGlobalPropertiesResponse::~TTSSetGlobalPropertiesResponse() {
-}
+TTSSetGlobalPropertiesResponse::~TTSSetGlobalPropertiesResponse() {}
void TTSSetGlobalPropertiesResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::TTS_SetGlobalProperties);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/tts_speak_request.cc b/src/components/application_manager/src/commands/hmi/tts_speak_request.cc
index 79fbde2c4f..2e386449d0 100644
--- a/src/components/application_manager/src/commands/hmi/tts_speak_request.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_speak_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-TTSSpeakRequest::TTSSpeakRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+TTSSpeakRequest::TTSSpeakRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-TTSSpeakRequest::~TTSSpeakRequest() {
-}
+TTSSpeakRequest::~TTSSpeakRequest() {}
void TTSSpeakRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void TTSSpeakRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/tts_speak_response.cc b/src/components/application_manager/src/commands/hmi/tts_speak_response.cc
index ff60115e70..5cffdccf34 100644
--- a/src/components/application_manager/src/commands/hmi/tts_speak_response.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_speak_response.cc
@@ -31,6 +31,7 @@
*/
#include "application_manager/commands/hmi/tts_speak_response.h"
#include "application_manager/event_engine/event.h"
+
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
@@ -38,19 +39,18 @@ namespace application_manager {
namespace commands {
-TTSSpeakResponse::TTSSpeakResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+TTSSpeakResponse::TTSSpeakResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-TTSSpeakResponse::~TTSSpeakResponse() {
-}
+TTSSpeakResponse::~TTSSpeakResponse() {}
void TTSSpeakResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::TTS_Speak);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/tts_stop_speaking_request.cc b/src/components/application_manager/src/commands/hmi/tts_stop_speaking_request.cc
index 32aaec27e7..c2275dda72 100644
--- a/src/components/application_manager/src/commands/hmi/tts_stop_speaking_request.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_stop_speaking_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-TTSStopSpeakingRequest::TTSStopSpeakingRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+TTSStopSpeakingRequest::TTSStopSpeakingRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-TTSStopSpeakingRequest::~TTSStopSpeakingRequest() {
-}
+TTSStopSpeakingRequest::~TTSStopSpeakingRequest() {}
void TTSStopSpeakingRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void TTSStopSpeakingRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/tts_stop_speaking_response.cc b/src/components/application_manager/src/commands/hmi/tts_stop_speaking_response.cc
index b32cf52bb5..67d747f464 100644
--- a/src/components/application_manager/src/commands/hmi/tts_stop_speaking_response.cc
+++ b/src/components/application_manager/src/commands/hmi/tts_stop_speaking_response.cc
@@ -38,19 +38,17 @@ namespace application_manager {
namespace commands {
TTSStopSpeakingResponse::TTSStopSpeakingResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-TTSStopSpeakingResponse::~TTSStopSpeakingResponse() {
-}
+TTSStopSpeakingResponse::~TTSStopSpeakingResponse() {}
void TTSStopSpeakingResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::TTS_StopSpeaking);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_add_command_request.cc b/src/components/application_manager/src/commands/hmi/ui_add_command_request.cc
index ed9f7979a1..c0edad3f80 100644
--- a/src/components/application_manager/src/commands/hmi/ui_add_command_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_add_command_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-UIAddCommandRequest::UIAddCommandRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+UIAddCommandRequest::UIAddCommandRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIAddCommandRequest::~UIAddCommandRequest() {
-}
+UIAddCommandRequest::~UIAddCommandRequest() {}
void UIAddCommandRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void UIAddCommandRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_add_command_response.cc b/src/components/application_manager/src/commands/hmi/ui_add_command_response.cc
index 13b2ab1b2b..a7eaabc91e 100644
--- a/src/components/application_manager/src/commands/hmi/ui_add_command_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_add_command_response.cc
@@ -37,19 +37,18 @@ namespace application_manager {
namespace commands {
-UIAddCommandResponse::UIAddCommandResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+UIAddCommandResponse::UIAddCommandResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIAddCommandResponse::~UIAddCommandResponse() {
-}
+UIAddCommandResponse::~UIAddCommandResponse() {}
void UIAddCommandResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_AddCommand);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_add_submenu_request.cc b/src/components/application_manager/src/commands/hmi/ui_add_submenu_request.cc
index 667499584f..f0a233853c 100644
--- a/src/components/application_manager/src/commands/hmi/ui_add_submenu_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_add_submenu_request.cc
@@ -36,15 +36,14 @@ namespace application_manager {
namespace commands {
-UIAddSubmenuRequest::UIAddSubmenuRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+UIAddSubmenuRequest::UIAddSubmenuRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIAddSubmenuRequest::~UIAddSubmenuRequest() {
-}
+UIAddSubmenuRequest::~UIAddSubmenuRequest() {}
void UIAddSubmenuRequest::Run() {
- LOG4CXX_INFO(logger_, "UIAddCommandRequest::Run");
+ LOG4CXX_AUTO_TRACE(logger_);
SendRequest();
}
@@ -52,4 +51,3 @@ void UIAddSubmenuRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_add_submenu_response.cc b/src/components/application_manager/src/commands/hmi/ui_add_submenu_response.cc
index 54247dbbce..6c6c18cbad 100644
--- a/src/components/application_manager/src/commands/hmi/ui_add_submenu_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_add_submenu_response.cc
@@ -31,25 +31,25 @@
*/
#include "application_manager/commands/hmi/ui_add_submenu_response.h"
#include "application_manager/event_engine/event.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
namespace commands {
-UIAddSubmenuResponse::UIAddSubmenuResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+UIAddSubmenuResponse::UIAddSubmenuResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIAddSubmenuResponse::~UIAddSubmenuResponse() {
-}
+UIAddSubmenuResponse::~UIAddSubmenuResponse() {}
void UIAddSubmenuResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_AddSubMenu);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_alert_request.cc b/src/components/application_manager/src/commands/hmi/ui_alert_request.cc
index c706d5fdba..44673d4981 100644
--- a/src/components/application_manager/src/commands/hmi/ui_alert_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_alert_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-UIAlertRequest::UIAlertRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+UIAlertRequest::UIAlertRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIAlertRequest::~UIAlertRequest() {
-}
+UIAlertRequest::~UIAlertRequest() {}
void UIAlertRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void UIAlertRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_alert_response.cc b/src/components/application_manager/src/commands/hmi/ui_alert_response.cc
index 8c9ddef7ac..6d552a1eb7 100644
--- a/src/components/application_manager/src/commands/hmi/ui_alert_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_alert_response.cc
@@ -31,25 +31,25 @@
*/
#include "application_manager/commands/hmi/ui_alert_response.h"
#include "application_manager/event_engine/event.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
namespace commands {
-UIAlertResponse::UIAlertResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+UIAlertResponse::UIAlertResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIAlertResponse::~UIAlertResponse() {
-}
+UIAlertResponse::~UIAlertResponse() {}
void UIAlertResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_Alert);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_change_registration_request.cc b/src/components/application_manager/src/commands/hmi/ui_change_registration_request.cc
index 67c9be6cb5..dcc88125fc 100644
--- a/src/components/application_manager/src/commands/hmi/ui_change_registration_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_change_registration_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
UIChangeRegistrationRequest::UIChangeRegistrationRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIChangeRegistrationRequest::~UIChangeRegistrationRequest() {
-}
+UIChangeRegistrationRequest::~UIChangeRegistrationRequest() {}
void UIChangeRegistrationRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void UIChangeRegistrationRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_change_registration_response.cc b/src/components/application_manager/src/commands/hmi/ui_change_registration_response.cc
index 1d59d66d74..52805a93c8 100644
--- a/src/components/application_manager/src/commands/hmi/ui_change_registration_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_change_registration_response.cc
@@ -31,6 +31,7 @@
*/
#include "application_manager/commands/hmi/ui_change_registration_response.h"
#include "application_manager/event_engine/event.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
@@ -38,19 +39,17 @@ namespace application_manager {
namespace commands {
UIChangeRegistratioResponse::UIChangeRegistratioResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIChangeRegistratioResponse::~UIChangeRegistratioResponse() {
-}
+UIChangeRegistratioResponse::~UIChangeRegistratioResponse() {}
void UIChangeRegistratioResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_ChangeRegistration);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_delete_command_request.cc b/src/components/application_manager/src/commands/hmi/ui_delete_command_request.cc
index 7d5532f30f..7bd529e8dc 100644
--- a/src/components/application_manager/src/commands/hmi/ui_delete_command_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_delete_command_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-UIDeleteCommandRequest::UIDeleteCommandRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+UIDeleteCommandRequest::UIDeleteCommandRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIDeleteCommandRequest::~UIDeleteCommandRequest() {
-}
+UIDeleteCommandRequest::~UIDeleteCommandRequest() {}
void UIDeleteCommandRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void UIDeleteCommandRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_delete_command_response.cc b/src/components/application_manager/src/commands/hmi/ui_delete_command_response.cc
index 2fb94a63a3..74a1bd64c2 100644
--- a/src/components/application_manager/src/commands/hmi/ui_delete_command_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_delete_command_response.cc
@@ -31,6 +31,7 @@
*/
#include "application_manager/commands/hmi/ui_delete_command_response.h"
#include "application_manager/event_engine/event.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
@@ -38,19 +39,17 @@ namespace application_manager {
namespace commands {
UIDeleteCommandResponse::UIDeleteCommandResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIDeleteCommandResponse::~UIDeleteCommandResponse() {
-}
+UIDeleteCommandResponse::~UIDeleteCommandResponse() {}
void UIDeleteCommandResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_DeleteCommand);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_delete_submenu_request.cc b/src/components/application_manager/src/commands/hmi/ui_delete_submenu_request.cc
index e945139639..335d97eee4 100644
--- a/src/components/application_manager/src/commands/hmi/ui_delete_submenu_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_delete_submenu_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-UIDeleteSubmenuRequest::UIDeleteSubmenuRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+UIDeleteSubmenuRequest::UIDeleteSubmenuRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIDeleteSubmenuRequest::~UIDeleteSubmenuRequest() {
-}
+UIDeleteSubmenuRequest::~UIDeleteSubmenuRequest() {}
void UIDeleteSubmenuRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void UIDeleteSubmenuRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_delete_submenu_response.cc b/src/components/application_manager/src/commands/hmi/ui_delete_submenu_response.cc
index 89a5a19a0b..302343da5e 100644
--- a/src/components/application_manager/src/commands/hmi/ui_delete_submenu_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_delete_submenu_response.cc
@@ -31,6 +31,7 @@
*/
#include "application_manager/commands/hmi/ui_delete_submenu_response.h"
#include "application_manager/event_engine/event.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
@@ -38,19 +39,17 @@ namespace application_manager {
namespace commands {
UIDeleteSubmenuResponse::UIDeleteSubmenuResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIDeleteSubmenuResponse::~UIDeleteSubmenuResponse() {
-}
+UIDeleteSubmenuResponse::~UIDeleteSubmenuResponse() {}
void UIDeleteSubmenuResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_DeleteSubMenu);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_end_audio_pass_thru_request.cc b/src/components/application_manager/src/commands/hmi/ui_end_audio_pass_thru_request.cc
index b87e1d89b8..e1cd11f922 100644
--- a/src/components/application_manager/src/commands/hmi/ui_end_audio_pass_thru_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_end_audio_pass_thru_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
UIEndAudioPassThruRequest::UIEndAudioPassThruRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIEndAudioPassThruRequest::~UIEndAudioPassThruRequest() {
-}
+UIEndAudioPassThruRequest::~UIEndAudioPassThruRequest() {}
void UIEndAudioPassThruRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void UIEndAudioPassThruRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_end_audio_pass_thru_response.cc b/src/components/application_manager/src/commands/hmi/ui_end_audio_pass_thru_response.cc
index 8f5d92b78f..e9eb596b85 100644
--- a/src/components/application_manager/src/commands/hmi/ui_end_audio_pass_thru_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_end_audio_pass_thru_response.cc
@@ -31,6 +31,7 @@
*/
#include "application_manager/commands/hmi/ui_end_audio_pass_thru_response.h"
#include "application_manager/event_engine/event.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
@@ -38,19 +39,17 @@ namespace application_manager {
namespace commands {
UIEndAudioPassThruResponse::UIEndAudioPassThruResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIEndAudioPassThruResponse::~UIEndAudioPassThruResponse() {
-}
+UIEndAudioPassThruResponse::~UIEndAudioPassThruResponse() {}
void UIEndAudioPassThruResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_EndAudioPassThru);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_get_capabilities_request.cc b/src/components/application_manager/src/commands/hmi/ui_get_capabilities_request.cc
index 74ee67e884..0ae4258d6b 100644
--- a/src/components/application_manager/src/commands/hmi/ui_get_capabilities_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_get_capabilities_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
UIGetCapabilitiesRequest::UIGetCapabilitiesRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIGetCapabilitiesRequest::~UIGetCapabilitiesRequest() {
-}
+UIGetCapabilitiesRequest::~UIGetCapabilitiesRequest() {}
void UIGetCapabilitiesRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void UIGetCapabilitiesRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_get_capabilities_response.cc b/src/components/application_manager/src/commands/hmi/ui_get_capabilities_response.cc
index b62f24cc51..de0a2f2157 100644
--- a/src/components/application_manager/src/commands/hmi/ui_get_capabilities_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_get_capabilities_response.cc
@@ -30,25 +30,21 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/ui_get_capabilities_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
UIGetCapabilitiesResponse::UIGetCapabilitiesResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIGetCapabilitiesResponse::~UIGetCapabilitiesResponse() {
-}
+UIGetCapabilitiesResponse::~UIGetCapabilitiesResponse() {}
void UIGetCapabilitiesResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
const smart_objects::SmartObject& msg_params =
(*message_)[strings::msg_params];
@@ -83,7 +79,6 @@ void UIGetCapabilitiesResponse::Run() {
msg_params[strings::hmi_capabilities][strings::phone_call].asBool());
}
}
-
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_get_language_request.cc b/src/components/application_manager/src/commands/hmi/ui_get_language_request.cc
index 1b22a9b58f..59d9eef6e3 100644
--- a/src/components/application_manager/src/commands/hmi/ui_get_language_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_get_language_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-UIGetLanguageRequest::UIGetLanguageRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+UIGetLanguageRequest::UIGetLanguageRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIGetLanguageRequest::~UIGetLanguageRequest() {
-}
+UIGetLanguageRequest::~UIGetLanguageRequest() {}
void UIGetLanguageRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void UIGetLanguageRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_get_language_response.cc b/src/components/application_manager/src/commands/hmi/ui_get_language_response.cc
index cba85d91e7..dfbdb89804 100644
--- a/src/components/application_manager/src/commands/hmi/ui_get_language_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_get_language_response.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,29 +30,41 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/ui_get_language_response.h"
-#include "application_manager/application_manager_impl.h"
+
+#include "application_manager/event_engine/event.h"
#include "interfaces/HMI_API.h"
namespace application_manager {
namespace commands {
-UIGetLanguageResponse::UIGetLanguageResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+UIGetLanguageResponse::UIGetLanguageResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIGetLanguageResponse::~UIGetLanguageResponse() {
-}
+UIGetLanguageResponse::~UIGetLanguageResponse() {}
void UIGetLanguageResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace hmi_apis;
+
+ Common_Language::eType language = Common_Language::INVALID_ENUM;
+
+ if ((*message_).keyExists(strings::msg_params) &&
+ (*message_)[strings::msg_params].keyExists(hmi_response::language)) {
+ language = static_cast<Common_Language::eType>(
+ (*message_)[strings::msg_params][hmi_response::language].asInt());
+ }
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ application_manager_.hmi_capabilities().set_active_ui_language(language);
- hmi_capabilities.set_active_ui_language(
- static_cast<hmi_apis::Common_Language::eType>(
- (*message_)[strings::msg_params][hmi_response::language].asInt()));
+ LOG4CXX_DEBUG(logger_,
+ "Raising event for function_id " << function_id()
+ << " and correlation_id "
+ << correlation_id());
+ event_engine::Event event(FunctionID::UI_GetLanguage);
+ event.set_smart_object(*message_);
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_get_supported_languages_request.cc b/src/components/application_manager/src/commands/hmi/ui_get_supported_languages_request.cc
index 5cd0c09e65..598ff39f79 100644
--- a/src/components/application_manager/src/commands/hmi/ui_get_supported_languages_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_get_supported_languages_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
UIGetSupportedLanguagesRequest::UIGetSupportedLanguagesRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIGetSupportedLanguagesRequest::~UIGetSupportedLanguagesRequest() {
-}
+UIGetSupportedLanguagesRequest::~UIGetSupportedLanguagesRequest() {}
void UIGetSupportedLanguagesRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void UIGetSupportedLanguagesRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_get_supported_languages_response.cc b/src/components/application_manager/src/commands/hmi/ui_get_supported_languages_response.cc
index 2057f3cbb2..e5849f5f63 100644
--- a/src/components/application_manager/src/commands/hmi/ui_get_supported_languages_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_get_supported_languages_response.cc
@@ -30,7 +30,7 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/ui_get_supported_languages_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
UIGetSupportedLanguagesResponse::UIGetSupportedLanguagesResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIGetSupportedLanguagesResponse::~UIGetSupportedLanguagesResponse() {
-}
+UIGetSupportedLanguagesResponse::~UIGetSupportedLanguagesResponse() {}
void UIGetSupportedLanguagesResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,8 +51,7 @@ void UIGetSupportedLanguagesResponse::Run() {
(*message_)[strings::params][hmi_response::code].asInt());
if (hmi_apis::Common_Result::SUCCESS == code) {
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
hmi_capabilities.set_ui_supported_languages(
(*message_)[strings::msg_params][hmi_response::languages]);
diff --git a/src/components/application_manager/src/commands/hmi/ui_is_ready_request.cc b/src/components/application_manager/src/commands/hmi/ui_is_ready_request.cc
index 94df3cec7d..463ae9d41d 100644
--- a/src/components/application_manager/src/commands/hmi/ui_is_ready_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_is_ready_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-UIIsReadyRequest::UIIsReadyRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+UIIsReadyRequest::UIIsReadyRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIIsReadyRequest::~UIIsReadyRequest() {
-}
+UIIsReadyRequest::~UIIsReadyRequest() {}
void UIIsReadyRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void UIIsReadyRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_is_ready_response.cc b/src/components/application_manager/src/commands/hmi/ui_is_ready_response.cc
index 9edf77080e..e7fca943bc 100644
--- a/src/components/application_manager/src/commands/hmi/ui_is_ready_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_is_ready_response.cc
@@ -30,18 +30,16 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/ui_is_ready_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-UIIsReadyResponse::UIIsReadyResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+UIIsReadyResponse::UIIsReadyResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIIsReadyResponse::~UIIsReadyResponse() {
-}
+UIIsReadyResponse::~UIIsReadyResponse() {}
void UIIsReadyResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,8 +50,7 @@ void UIIsReadyResponse::Run() {
is_available = object[strings::msg_params][strings::available].asBool();
}
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
hmi_capabilities.set_is_ui_cooperating(is_available);
}
diff --git a/src/components/application_manager/src/commands/hmi/ui_perform_audio_pass_thru_request.cc b/src/components/application_manager/src/commands/hmi/ui_perform_audio_pass_thru_request.cc
index 3cf7722b24..a88719d303 100644
--- a/src/components/application_manager/src/commands/hmi/ui_perform_audio_pass_thru_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_perform_audio_pass_thru_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
UIPerformAudioPassThruRequest::UIPerformAudioPassThruRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIPerformAudioPassThruRequest::~UIPerformAudioPassThruRequest() {
-}
+UIPerformAudioPassThruRequest::~UIPerformAudioPassThruRequest() {}
void UIPerformAudioPassThruRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void UIPerformAudioPassThruRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_perform_audio_pass_thru_response.cc b/src/components/application_manager/src/commands/hmi/ui_perform_audio_pass_thru_response.cc
index c8a488e44d..0736cca526 100644
--- a/src/components/application_manager/src/commands/hmi/ui_perform_audio_pass_thru_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_perform_audio_pass_thru_response.cc
@@ -38,19 +38,17 @@ namespace application_manager {
namespace commands {
UIPerformAudioPassThruResponse::UIPerformAudioPassThruResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIPerformAudioPassThruResponse::~UIPerformAudioPassThruResponse() {
-}
+UIPerformAudioPassThruResponse::~UIPerformAudioPassThruResponse() {}
void UIPerformAudioPassThruResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_PerformAudioPassThru);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_perform_interaction_request.cc b/src/components/application_manager/src/commands/hmi/ui_perform_interaction_request.cc
index 2b1f5ce484..82a900f1ae 100644
--- a/src/components/application_manager/src/commands/hmi/ui_perform_interaction_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_perform_interaction_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
UIPerformInteractionRequest::UIPerformInteractionRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIPerformInteractionRequest::~UIPerformInteractionRequest() {
-}
+UIPerformInteractionRequest::~UIPerformInteractionRequest() {}
void UIPerformInteractionRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void UIPerformInteractionRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_perform_interaction_response.cc b/src/components/application_manager/src/commands/hmi/ui_perform_interaction_response.cc
index 25237525da..ea78c0cd66 100644
--- a/src/components/application_manager/src/commands/hmi/ui_perform_interaction_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_perform_interaction_response.cc
@@ -38,18 +38,16 @@ namespace application_manager {
namespace commands {
UIPerformInteractionResponse::UIPerformInteractionResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIPerformInteractionResponse::~UIPerformInteractionResponse() {
-}
+UIPerformInteractionResponse::~UIPerformInteractionResponse() {}
void UIPerformInteractionResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_PerformInteraction);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_scrollable_message_request.cc b/src/components/application_manager/src/commands/hmi/ui_scrollable_message_request.cc
index 911c840ce4..006944d404 100644
--- a/src/components/application_manager/src/commands/hmi/ui_scrollable_message_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_scrollable_message_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
UIScrollableMessageRequest::UIScrollableMessageRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIScrollableMessageRequest::~UIScrollableMessageRequest() {
-}
+UIScrollableMessageRequest::~UIScrollableMessageRequest() {}
void UIScrollableMessageRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void UIScrollableMessageRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_scrollable_message_response.cc b/src/components/application_manager/src/commands/hmi/ui_scrollable_message_response.cc
index 58c793c3b6..c39a99fc61 100644
--- a/src/components/application_manager/src/commands/hmi/ui_scrollable_message_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_scrollable_message_response.cc
@@ -38,19 +38,17 @@ namespace application_manager {
namespace commands {
UIScrollableMessageResponse::UIScrollableMessageResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIScrollableMessageResponse::~UIScrollableMessageResponse() {
-}
+UIScrollableMessageResponse::~UIScrollableMessageResponse() {}
void UIScrollableMessageResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_ScrollableMessage);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_set_app_icon_request.cc b/src/components/application_manager/src/commands/hmi/ui_set_app_icon_request.cc
index c4a3b3b3af..2666eedfc8 100644
--- a/src/components/application_manager/src/commands/hmi/ui_set_app_icon_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_set_app_icon_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-UISetAppIconRequest::UISetAppIconRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+UISetAppIconRequest::UISetAppIconRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UISetAppIconRequest::~UISetAppIconRequest() {
-}
+UISetAppIconRequest::~UISetAppIconRequest() {}
void UISetAppIconRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void UISetAppIconRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_set_app_icon_response.cc b/src/components/application_manager/src/commands/hmi/ui_set_app_icon_response.cc
index 46c10e8f22..18fc5a5761 100644
--- a/src/components/application_manager/src/commands/hmi/ui_set_app_icon_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_set_app_icon_response.cc
@@ -37,19 +37,18 @@ namespace application_manager {
namespace commands {
-UISetAppIconResponse::UISetAppIconResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+UISetAppIconResponse::UISetAppIconResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UISetAppIconResponse::~UISetAppIconResponse() {
-}
+UISetAppIconResponse::~UISetAppIconResponse() {}
void UISetAppIconResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_SetAppIcon);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_set_display_layout_request.cc b/src/components/application_manager/src/commands/hmi/ui_set_display_layout_request.cc
index df9f6cf2a6..cd69c9c8e6 100644
--- a/src/components/application_manager/src/commands/hmi/ui_set_display_layout_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_set_display_layout_request.cc
@@ -37,11 +37,10 @@ namespace application_manager {
namespace commands {
UiSetDisplayLayoutRequest::UiSetDisplayLayoutRequest(
- const MessageSharedPtr& message): RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UiSetDisplayLayoutRequest::~UiSetDisplayLayoutRequest() {
-}
+UiSetDisplayLayoutRequest::~UiSetDisplayLayoutRequest() {}
void UiSetDisplayLayoutRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -51,4 +50,3 @@ void UiSetDisplayLayoutRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_set_display_layout_response.cc b/src/components/application_manager/src/commands/hmi/ui_set_display_layout_response.cc
index f23cc92642..c5a439636f 100644
--- a/src/components/application_manager/src/commands/hmi/ui_set_display_layout_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_set_display_layout_response.cc
@@ -39,18 +39,17 @@ namespace application_manager {
namespace commands {
UiSetDisplayLayoutResponse::UiSetDisplayLayoutResponse(
- const MessageSharedPtr& message): ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UiSetDisplayLayoutResponse::~UiSetDisplayLayoutResponse() {
-}
+UiSetDisplayLayoutResponse::~UiSetDisplayLayoutResponse() {}
void UiSetDisplayLayoutResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_SetDisplayLayout);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_set_global_properties_request.cc b/src/components/application_manager/src/commands/hmi/ui_set_global_properties_request.cc
index 39a0e865df..8658a043b0 100644
--- a/src/components/application_manager/src/commands/hmi/ui_set_global_properties_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_set_global_properties_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
UISetGlobalPropertiesRequest::UISetGlobalPropertiesRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UISetGlobalPropertiesRequest::~UISetGlobalPropertiesRequest() {
-}
+UISetGlobalPropertiesRequest::~UISetGlobalPropertiesRequest() {}
void UISetGlobalPropertiesRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void UISetGlobalPropertiesRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_set_global_properties_response.cc b/src/components/application_manager/src/commands/hmi/ui_set_global_properties_response.cc
index 23173961fb..d10c206a7c 100644
--- a/src/components/application_manager/src/commands/hmi/ui_set_global_properties_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_set_global_properties_response.cc
@@ -38,19 +38,17 @@ namespace application_manager {
namespace commands {
UISetGlobalPropertiesResponse::UISetGlobalPropertiesResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UISetGlobalPropertiesResponse::~UISetGlobalPropertiesResponse() {
-}
+UISetGlobalPropertiesResponse::~UISetGlobalPropertiesResponse() {}
void UISetGlobalPropertiesResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_SetGlobalProperties);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_set_icon_request.cc b/src/components/application_manager/src/commands/hmi/ui_set_icon_request.cc
index b587a3028e..c98b7ec028 100644
--- a/src/components/application_manager/src/commands/hmi/ui_set_icon_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_set_icon_request.cc
@@ -37,14 +37,12 @@ namespace application_manager {
namespace commands {
UISetIconRequest::UISetIconRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ : RequestToHMI(message) {}
-UISetIconRequest::~UISetIconRequest() {
-}
+UISetIconRequest::~UISetIconRequest() {}
void UISetIconRequest::Run() {
- LOG4CXX_INFO(logger_, "UISetIconRequest::Run");
+ LOG4CXX_AUTO_TRACE(logger_);
SendRequest();
}
@@ -52,4 +50,3 @@ void UISetIconRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_set_icon_response.cc b/src/components/application_manager/src/commands/hmi/ui_set_icon_response.cc
deleted file mode 100644
index f4565baaf1..0000000000
--- a/src/components/application_manager/src/commands/hmi/ui_set_icon_response.cc
+++ /dev/null
@@ -1,57 +0,0 @@
-/**
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-#include "application_manager/commands/hmi/ui_set_icon_response.h"
-#include "application_manager/event_engine/event.h"
-#include "interfaces/HMI_API.h"
-
-namespace application_manager {
-
-namespace commands {
-
-UISetIconResponse::UISetIconResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
-
-UISetIconResponse::~UISetIconResponse() {
-}
-
-void UISetIconResponse::Run() {
- LOG4CXX_INFO(logger_, "UISetIconResponse::Run");
-
- event_engine::Event event(hmi_apis::FunctionID::UI_SetAppIcon);
- event.set_smart_object(*message_);
- event.raise();
-}
-
-} // namespace commands
-
-} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/hmi/ui_set_media_clock_timer_request.cc b/src/components/application_manager/src/commands/hmi/ui_set_media_clock_timer_request.cc
index 272ff561aa..955cb1d57b 100644
--- a/src/components/application_manager/src/commands/hmi/ui_set_media_clock_timer_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_set_media_clock_timer_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
UISetMediaClockTimerRequest::UISetMediaClockTimerRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UISetMediaClockTimerRequest::~UISetMediaClockTimerRequest() {
-}
+UISetMediaClockTimerRequest::~UISetMediaClockTimerRequest() {}
void UISetMediaClockTimerRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void UISetMediaClockTimerRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_set_media_clock_timer_response.cc b/src/components/application_manager/src/commands/hmi/ui_set_media_clock_timer_response.cc
index ae878bd694..32acef4994 100644
--- a/src/components/application_manager/src/commands/hmi/ui_set_media_clock_timer_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_set_media_clock_timer_response.cc
@@ -38,19 +38,17 @@ namespace application_manager {
namespace commands {
UISetMediaClockTimerResponse::UISetMediaClockTimerResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UISetMediaClockTimerResponse::~UISetMediaClockTimerResponse() {
-}
+UISetMediaClockTimerResponse::~UISetMediaClockTimerResponse() {}
void UISetMediaClockTimerResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_SetMediaClockTimer);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_show_request.cc b/src/components/application_manager/src/commands/hmi/ui_show_request.cc
index 65b9894902..9c0e90feff 100644
--- a/src/components/application_manager/src/commands/hmi/ui_show_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_show_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-UIShowRequest::UIShowRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+UIShowRequest::UIShowRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UIShowRequest::~UIShowRequest() {
-}
+UIShowRequest::~UIShowRequest() {}
void UIShowRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void UIShowRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_show_response.cc b/src/components/application_manager/src/commands/hmi/ui_show_response.cc
index 8d348e6086..333d9e96c5 100644
--- a/src/components/application_manager/src/commands/hmi/ui_show_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_show_response.cc
@@ -36,19 +36,18 @@ namespace application_manager {
namespace commands {
-UIShowResponse::UIShowResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+UIShowResponse::UIShowResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UIShowResponse::~UIShowResponse() {
-}
+UIShowResponse::~UIShowResponse() {}
void UIShowResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_Show);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/ui_slider_request.cc b/src/components/application_manager/src/commands/hmi/ui_slider_request.cc
index c8d3242d98..26e6ed76b0 100644
--- a/src/components/application_manager/src/commands/hmi/ui_slider_request.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_slider_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-UISliderRequest::UISliderRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+UISliderRequest::UISliderRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UISliderRequest::~UISliderRequest() {
-}
+UISliderRequest::~UISliderRequest() {}
void UISliderRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void UISliderRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/ui_slider_response.cc b/src/components/application_manager/src/commands/hmi/ui_slider_response.cc
index 7837117ebd..091eb50e0d 100644
--- a/src/components/application_manager/src/commands/hmi/ui_slider_response.cc
+++ b/src/components/application_manager/src/commands/hmi/ui_slider_response.cc
@@ -37,19 +37,18 @@ namespace application_manager {
namespace commands {
-UISliderResponse::UISliderResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+UISliderResponse::UISliderResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UISliderResponse::~UISliderResponse() {
-}
+UISliderResponse::~UISliderResponse() {}
void UISliderResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::UI_Slider);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/update_app_list_request.cc b/src/components/application_manager/src/commands/hmi/update_app_list_request.cc
index 72f65d1a2e..286d269727 100644
--- a/src/components/application_manager/src/commands/hmi/update_app_list_request.cc
+++ b/src/components/application_manager/src/commands/hmi/update_app_list_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-UpdateAppListRequest::UpdateAppListRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+UpdateAppListRequest::UpdateAppListRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UpdateAppListRequest::~UpdateAppListRequest() {
-}
+UpdateAppListRequest::~UpdateAppListRequest() {}
void UpdateAppListRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,5 +51,3 @@ void UpdateAppListRequest::Run() {
} // namespace commands
} // namespace application_manager
-
-
diff --git a/src/components/application_manager/src/commands/hmi/update_app_list_response.cc b/src/components/application_manager/src/commands/hmi/update_app_list_response.cc
index 308bce3ad2..6546d03805 100644
--- a/src/components/application_manager/src/commands/hmi/update_app_list_response.cc
+++ b/src/components/application_manager/src/commands/hmi/update_app_list_response.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-UpdateAppListResponse::UpdateAppListResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+UpdateAppListResponse::UpdateAppListResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UpdateAppListResponse::~UpdateAppListResponse() {
-}
+UpdateAppListResponse::~UpdateAppListResponse() {}
void UpdateAppListResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,5 +51,3 @@ void UpdateAppListResponse::Run() {
} // namespace commands
} // namespace application_manager
-
-
diff --git a/src/components/application_manager/src/commands/hmi/update_device_list_request.cc b/src/components/application_manager/src/commands/hmi/update_device_list_request.cc
index 696e2f85c4..74d104b36d 100644
--- a/src/components/application_manager/src/commands/hmi/update_device_list_request.cc
+++ b/src/components/application_manager/src/commands/hmi/update_device_list_request.cc
@@ -31,8 +31,7 @@
*/
#include "application_manager/commands/hmi/update_device_list_request.h"
-#include "application_manager/application_manager_impl.h"
-#include "config_profile/profile.h"
+
#include "interfaces/HMI_API.h"
#include <unistd.h>
@@ -42,21 +41,21 @@ namespace application_manager {
namespace commands {
UpdateDeviceListRequest::UpdateDeviceListRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager)
+ , EventObserver(application_manager_.event_dispatcher()) {}
-UpdateDeviceListRequest::~UpdateDeviceListRequest() {
-}
+UpdateDeviceListRequest::~UpdateDeviceListRequest() {}
void UpdateDeviceListRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock auto_lock(wait_hmi_lock);
// Fix problem with SDL and HMI HTML. This problem is not actual for HMI PASA.
- // Flag conditional compilation for specific customer is used in order to exclude
+ // Flag conditional compilation for specific customer is used in order to
+ // exclude
// hit code to RTC
- if (true == profile::Profile::instance()->launch_hmi()) {
- if (!ApplicationManagerImpl::instance()->IsHMICooperating()) {
+ if (true == application_manager_.get_settings().launch_hmi()) {
+ if (!application_manager_.IsHMICooperating()) {
LOG4CXX_INFO(logger_, "Wait for HMI Cooperation");
subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_OnReady);
termination_condition_.Wait(auto_lock);
@@ -71,13 +70,13 @@ void UpdateDeviceListRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock auto_lock(wait_hmi_lock);
switch (event.id()) {
- case hmi_apis::FunctionID::BasicCommunication_OnReady : {
+ case hmi_apis::FunctionID::BasicCommunication_OnReady: {
LOG4CXX_INFO(logger_, "received OnReady");
unsubscribe_from_event(hmi_apis::FunctionID::BasicCommunication_OnReady);
termination_condition_.Broadcast();
break;
};
- default : {
+ default: {
LOG4CXX_ERROR(logger_, "Unknown event ");
break;
};
@@ -93,4 +92,3 @@ bool UpdateDeviceListRequest::CleanUp() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/update_device_list_response.cc b/src/components/application_manager/src/commands/hmi/update_device_list_response.cc
index b3e0f9a309..6d9dec92f8 100644
--- a/src/components/application_manager/src/commands/hmi/update_device_list_response.cc
+++ b/src/components/application_manager/src/commands/hmi/update_device_list_response.cc
@@ -36,12 +36,10 @@ namespace application_manager {
namespace commands {
UpdateDeviceListResponse::UpdateDeviceListResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UpdateDeviceListResponse::~UpdateDeviceListResponse() {
-}
+UpdateDeviceListResponse::~UpdateDeviceListResponse() {}
void UpdateDeviceListResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/hmi/update_sdl_request.cc b/src/components/application_manager/src/commands/hmi/update_sdl_request.cc
index b03e595e9c..44f7547964 100644
--- a/src/components/application_manager/src/commands/hmi/update_sdl_request.cc
+++ b/src/components/application_manager/src/commands/hmi/update_sdl_request.cc
@@ -32,27 +32,24 @@
*/
#include "application_manager/commands/hmi/update_sdl_request.h"
-#include "application_manager/policies/policy_handler.h"
namespace application_manager {
namespace commands {
-UpdateSDLRequest::UpdateSDLRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+UpdateSDLRequest::UpdateSDLRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-UpdateSDLRequest::~UpdateSDLRequest() {
-}
+UpdateSDLRequest::~UpdateSDLRequest() {}
void UpdateSDLRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- policy::PolicyHandler::instance()->PTExchangeAtUserRequest(
+ application_manager_.GetPolicyHandler().PTExchangeAtUserRequest(
(*message_)[strings::params][strings::correlation_id].asInt());
}
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/update_sdl_response.cc b/src/components/application_manager/src/commands/hmi/update_sdl_response.cc
index d9c8b6102f..0e8978fe89 100644
--- a/src/components/application_manager/src/commands/hmi/update_sdl_response.cc
+++ b/src/components/application_manager/src/commands/hmi/update_sdl_response.cc
@@ -30,25 +30,23 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/update_sdl_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-UpdateSDLResponse::UpdateSDLResponse(
- const MessageSharedPtr& message): ResponseFromHMI(message) {
-}
+UpdateSDLResponse::UpdateSDLResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-UpdateSDLResponse::~UpdateSDLResponse() {
-}
+UpdateSDLResponse::~UpdateSDLResponse() {}
void UpdateSDLResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
(*message_)[strings::params][strings::protocol_type] = hmi_protocol_type_;
(*message_)[strings::params][strings::protocol_version] = protocol_version_;
- ApplicationManagerImpl::instance()->SendMessageToHMI(message_);
+ application_manager_.SendMessageToHMI(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/vi_diagnostic_message_request.cc b/src/components/application_manager/src/commands/hmi/vi_diagnostic_message_request.cc
index eb9a9841be..5fe81fcbd8 100644
--- a/src/components/application_manager/src/commands/hmi/vi_diagnostic_message_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_diagnostic_message_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-VIDiagnosticMessageRequest::VIDiagnosticMessageRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+VIDiagnosticMessageRequest::VIDiagnosticMessageRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VIDiagnosticMessageRequest::~VIDiagnosticMessageRequest() {
-}
+VIDiagnosticMessageRequest::~VIDiagnosticMessageRequest() {}
void VIDiagnosticMessageRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void VIDiagnosticMessageRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vi_diagnostic_message_response.cc b/src/components/application_manager/src/commands/hmi/vi_diagnostic_message_response.cc
index 4183395e99..e19af75b54 100644
--- a/src/components/application_manager/src/commands/hmi/vi_diagnostic_message_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_diagnostic_message_response.cc
@@ -37,19 +37,19 @@ namespace application_manager {
namespace commands {
-VIDiagnosticMessageResponse::VIDiagnosticMessageResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+VIDiagnosticMessageResponse::VIDiagnosticMessageResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VIDiagnosticMessageResponse::~VIDiagnosticMessageResponse() {
-}
+VIDiagnosticMessageResponse::~VIDiagnosticMessageResponse() {}
void VIDiagnosticMessageResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- event_engine::Event event(hmi_apis::FunctionID::VehicleInfo_DiagnosticMessage);
+ event_engine::Event event(
+ hmi_apis::FunctionID::VehicleInfo_DiagnosticMessage);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/vi_get_dtcs_request.cc b/src/components/application_manager/src/commands/hmi/vi_get_dtcs_request.cc
index a89252ada2..b373471c43 100644
--- a/src/components/application_manager/src/commands/hmi/vi_get_dtcs_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_get_dtcs_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-VIGetDTCsRequest::VIGetDTCsRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+VIGetDTCsRequest::VIGetDTCsRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VIGetDTCsRequest::~VIGetDTCsRequest() {
-}
+VIGetDTCsRequest::~VIGetDTCsRequest() {}
void VIGetDTCsRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void VIGetDTCsRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vi_get_dtcs_response.cc b/src/components/application_manager/src/commands/hmi/vi_get_dtcs_response.cc
index c44f5213d2..3e720f9dbc 100644
--- a/src/components/application_manager/src/commands/hmi/vi_get_dtcs_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_get_dtcs_response.cc
@@ -37,19 +37,18 @@ namespace application_manager {
namespace commands {
-VIGetDTCsResponse::VIGetDTCsResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+VIGetDTCsResponse::VIGetDTCsResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VIGetDTCsResponse::~VIGetDTCsResponse() {
-}
+VIGetDTCsResponse::~VIGetDTCsResponse() {}
void VIGetDTCsResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::VehicleInfo_GetDTCs);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/vi_get_vehicle_data_request.cc b/src/components/application_manager/src/commands/hmi/vi_get_vehicle_data_request.cc
index 37d5ede4b0..05424c4967 100644
--- a/src/components/application_manager/src/commands/hmi/vi_get_vehicle_data_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_get_vehicle_data_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
VIGetVehicleDataRequest::VIGetVehicleDataRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VIGetVehicleDataRequest::~VIGetVehicleDataRequest() {
-}
+VIGetVehicleDataRequest::~VIGetVehicleDataRequest() {}
void VIGetVehicleDataRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void VIGetVehicleDataRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vi_get_vehicle_data_response.cc b/src/components/application_manager/src/commands/hmi/vi_get_vehicle_data_response.cc
index 0ed0f7f515..2794f6eddd 100644
--- a/src/components/application_manager/src/commands/hmi/vi_get_vehicle_data_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_get_vehicle_data_response.cc
@@ -31,27 +31,24 @@
*/
#include "application_manager/commands/hmi/vi_get_vehicle_data_response.h"
#include "application_manager/event_engine/event.h"
-#include "application_manager/policies/policy_handler.h"
#include "interfaces/HMI_API.h"
namespace application_manager {
namespace commands {
VIGetVehicleDataResponse::VIGetVehicleDataResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VIGetVehicleDataResponse::~VIGetVehicleDataResponse() {
-}
+VIGetVehicleDataResponse::~VIGetVehicleDataResponse() {}
void VIGetVehicleDataResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::VehicleInfo_GetVehicleData);
- if ((*message_)[strings::params][strings::message_type]
- == static_cast<int32_t>(hmi_apis::messageType::error_response)) {
+ if ((*message_)[strings::params][strings::message_type] ==
+ static_cast<int32_t>(hmi_apis::messageType::error_response)) {
smart_objects::SmartObject result(smart_objects::SmartType_Map);
if ((*message_)[strings::params].keyExists(strings::data)) {
@@ -73,10 +70,10 @@ void VIGetVehicleDataResponse::Run() {
event.set_smart_object(result);
} else {
event.set_smart_object(*message_);
- policy::PolicyHandler::instance()->OnVehicleDataUpdated(*message_);
+ application_manager_.GetPolicyHandler().OnVehicleDataUpdated(*message_);
}
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/vi_get_vehicle_type_request.cc b/src/components/application_manager/src/commands/hmi/vi_get_vehicle_type_request.cc
index 11dd26dfad..64a3831e1c 100644
--- a/src/components/application_manager/src/commands/hmi/vi_get_vehicle_type_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_get_vehicle_type_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
VIGetVehicleTypeRequest::VIGetVehicleTypeRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VIGetVehicleTypeRequest::~VIGetVehicleTypeRequest() {
-}
+VIGetVehicleTypeRequest::~VIGetVehicleTypeRequest() {}
void VIGetVehicleTypeRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void VIGetVehicleTypeRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vi_get_vehicle_type_response.cc b/src/components/application_manager/src/commands/hmi/vi_get_vehicle_type_response.cc
index 2b5f6b96be..2369eb7eee 100644
--- a/src/components/application_manager/src/commands/hmi/vi_get_vehicle_type_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_get_vehicle_type_response.cc
@@ -30,25 +30,21 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/vi_get_vehicle_type_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
VIGetVehicleTypeResponse::VIGetVehicleTypeResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VIGetVehicleTypeResponse::~VIGetVehicleTypeResponse() {
-}
+VIGetVehicleTypeResponse::~VIGetVehicleTypeResponse() {}
void VIGetVehicleTypeResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
hmi_capabilities.set_vehicle_type(
(*message_)[strings::msg_params][hmi_response::vehicle_type]);
diff --git a/src/components/application_manager/src/commands/hmi/vi_is_ready_request.cc b/src/components/application_manager/src/commands/hmi/vi_is_ready_request.cc
index aae05e0fcc..3ecc2ffe90 100644
--- a/src/components/application_manager/src/commands/hmi/vi_is_ready_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_is_ready_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-VIIsReadyRequest::VIIsReadyRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+VIIsReadyRequest::VIIsReadyRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VIIsReadyRequest::~VIIsReadyRequest() {
-}
+VIIsReadyRequest::~VIIsReadyRequest() {}
void VIIsReadyRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void VIIsReadyRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vi_is_ready_response.cc b/src/components/application_manager/src/commands/hmi/vi_is_ready_response.cc
index 4a79a6d9b9..91dae226b6 100644
--- a/src/components/application_manager/src/commands/hmi/vi_is_ready_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_is_ready_response.cc
@@ -30,19 +30,16 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/vi_is_ready_response.h"
-#include "application_manager/application_manager_impl.h"
-#include "application_manager/policies/policy_handler.h"
namespace application_manager {
namespace commands {
-VIIsReadyResponse::VIIsReadyResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+VIIsReadyResponse::VIIsReadyResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VIIsReadyResponse::~VIIsReadyResponse() {
-}
+VIIsReadyResponse::~VIIsReadyResponse() {}
void VIIsReadyResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,11 +50,10 @@ void VIIsReadyResponse::Run() {
is_available = object[strings::msg_params][strings::available].asBool();
}
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
hmi_capabilities.set_is_ivi_cooperating(is_available);
- policy::PolicyHandler::instance()->OnVIIsReady();
+ application_manager_.GetPolicyHandler().OnVIIsReady();
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/vi_read_did_request.cc b/src/components/application_manager/src/commands/hmi/vi_read_did_request.cc
index 92a105dde4..d72fcb8157 100644
--- a/src/components/application_manager/src/commands/hmi/vi_read_did_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_read_did_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-VIReadDIDRequest::VIReadDIDRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+VIReadDIDRequest::VIReadDIDRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VIReadDIDRequest::~VIReadDIDRequest() {
-}
+VIReadDIDRequest::~VIReadDIDRequest() {}
void VIReadDIDRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void VIReadDIDRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vi_read_did_response.cc b/src/components/application_manager/src/commands/hmi/vi_read_did_response.cc
index 675b944272..568a573f88 100644
--- a/src/components/application_manager/src/commands/hmi/vi_read_did_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_read_did_response.cc
@@ -31,26 +31,23 @@
*/
#include "application_manager/commands/hmi/vi_read_did_response.h"
#include "application_manager/event_engine/event.h"
-#include "application_manager/application_manager_impl.h"
-
namespace application_manager {
namespace commands {
-VIReadDIDResponse::VIReadDIDResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+VIReadDIDResponse::VIReadDIDResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VIReadDIDResponse::~VIReadDIDResponse() {
-}
+VIReadDIDResponse::~VIReadDIDResponse() {}
void VIReadDIDResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::VehicleInfo_ReadDID);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/vi_subscribe_vehicle_data_request.cc b/src/components/application_manager/src/commands/hmi/vi_subscribe_vehicle_data_request.cc
index 5ad4daea94..5c953334bb 100644
--- a/src/components/application_manager/src/commands/hmi/vi_subscribe_vehicle_data_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_subscribe_vehicle_data_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
VISubscribeVehicleDataRequest::VISubscribeVehicleDataRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VISubscribeVehicleDataRequest::~VISubscribeVehicleDataRequest() {
-}
+VISubscribeVehicleDataRequest::~VISubscribeVehicleDataRequest() {}
void VISubscribeVehicleDataRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void VISubscribeVehicleDataRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vi_subscribe_vehicle_data_response.cc b/src/components/application_manager/src/commands/hmi/vi_subscribe_vehicle_data_response.cc
index 91d9c85382..4df2d9190a 100644
--- a/src/components/application_manager/src/commands/hmi/vi_subscribe_vehicle_data_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_subscribe_vehicle_data_response.cc
@@ -37,20 +37,17 @@ namespace application_manager {
namespace commands {
VISubscribeVehicleDataResponse::VISubscribeVehicleDataResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VISubscribeVehicleDataResponse::~VISubscribeVehicleDataResponse() {
-}
+VISubscribeVehicleDataResponse::~VISubscribeVehicleDataResponse() {}
void VISubscribeVehicleDataResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(
- hmi_apis::FunctionID::VehicleInfo_SubscribeVehicleData
- );
+ hmi_apis::FunctionID::VehicleInfo_SubscribeVehicleData);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/vi_unsubscribe_vehicle_data_request.cc b/src/components/application_manager/src/commands/hmi/vi_unsubscribe_vehicle_data_request.cc
index 7c12cbe6f1..2211cde19c 100644
--- a/src/components/application_manager/src/commands/hmi/vi_unsubscribe_vehicle_data_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_unsubscribe_vehicle_data_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
VIUnsubscribeVehicleDataRequest::VIUnsubscribeVehicleDataRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VIUnsubscribeVehicleDataRequest::~VIUnsubscribeVehicleDataRequest() {
-}
+VIUnsubscribeVehicleDataRequest::~VIUnsubscribeVehicleDataRequest() {}
void VIUnsubscribeVehicleDataRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void VIUnsubscribeVehicleDataRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vi_unsubscribe_vehicle_data_response.cc b/src/components/application_manager/src/commands/hmi/vi_unsubscribe_vehicle_data_response.cc
index 124b7dacbd..5044f0ef43 100644
--- a/src/components/application_manager/src/commands/hmi/vi_unsubscribe_vehicle_data_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vi_unsubscribe_vehicle_data_response.cc
@@ -37,20 +37,17 @@ namespace application_manager {
namespace commands {
VIUnsubscribeVehicleDataResponse::VIUnsubscribeVehicleDataResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VIUnsubscribeVehicleDataResponse::~VIUnsubscribeVehicleDataResponse() {
-}
+VIUnsubscribeVehicleDataResponse::~VIUnsubscribeVehicleDataResponse() {}
void VIUnsubscribeVehicleDataResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeVehicleData
- );
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeVehicleData);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/vr_add_command_request.cc b/src/components/application_manager/src/commands/hmi/vr_add_command_request.cc
index c900df1678..04af05d4e7 100644
--- a/src/components/application_manager/src/commands/hmi/vr_add_command_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_add_command_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-VRAddCommandRequest::VRAddCommandRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+VRAddCommandRequest::VRAddCommandRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VRAddCommandRequest::~VRAddCommandRequest() {
-}
+VRAddCommandRequest::~VRAddCommandRequest() {}
void VRAddCommandRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void VRAddCommandRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vr_add_command_response.cc b/src/components/application_manager/src/commands/hmi/vr_add_command_response.cc
index 3d34b5c65a..496bd47605 100644
--- a/src/components/application_manager/src/commands/hmi/vr_add_command_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_add_command_response.cc
@@ -31,25 +31,25 @@
*/
#include "application_manager/commands/hmi/vr_add_command_response.h"
#include "application_manager/event_engine/event.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
namespace commands {
-VRAddCommandResponse::VRAddCommandResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+VRAddCommandResponse::VRAddCommandResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VRAddCommandResponse::~VRAddCommandResponse() {
-}
+VRAddCommandResponse::~VRAddCommandResponse() {}
void VRAddCommandResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::VR_AddCommand);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/vr_change_registration_request.cc b/src/components/application_manager/src/commands/hmi/vr_change_registration_request.cc
index fe8ee69021..e64e7cc388 100644
--- a/src/components/application_manager/src/commands/hmi/vr_change_registration_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_change_registration_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
VRChangeRegistrationRequest::VRChangeRegistrationRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VRChangeRegistrationRequest::~VRChangeRegistrationRequest() {
-}
+VRChangeRegistrationRequest::~VRChangeRegistrationRequest() {}
void VRChangeRegistrationRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void VRChangeRegistrationRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vr_change_registration_response.cc b/src/components/application_manager/src/commands/hmi/vr_change_registration_response.cc
index 5bd2fb853a..8084688c15 100644
--- a/src/components/application_manager/src/commands/hmi/vr_change_registration_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_change_registration_response.cc
@@ -38,19 +38,17 @@ namespace application_manager {
namespace commands {
VRChangeRegistrationResponse::VRChangeRegistrationResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VRChangeRegistrationResponse::~VRChangeRegistrationResponse() {
-}
+VRChangeRegistrationResponse::~VRChangeRegistrationResponse() {}
void VRChangeRegistrationResponse::Run() {
- LOG4CXX_INFO(logger_, "VRChangeRegistratioResponse::Run");
+ LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::VR_ChangeRegistration);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/vr_delete_command_request.cc b/src/components/application_manager/src/commands/hmi/vr_delete_command_request.cc
index e3052ae208..1db85529da 100644
--- a/src/components/application_manager/src/commands/hmi/vr_delete_command_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_delete_command_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-VRDeleteCommandRequest::VRDeleteCommandRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+VRDeleteCommandRequest::VRDeleteCommandRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VRDeleteCommandRequest::~VRDeleteCommandRequest() {
-}
+VRDeleteCommandRequest::~VRDeleteCommandRequest() {}
void VRDeleteCommandRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void VRDeleteCommandRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vr_delete_command_response.cc b/src/components/application_manager/src/commands/hmi/vr_delete_command_response.cc
index 8954b1d1b9..08711be2c8 100644
--- a/src/components/application_manager/src/commands/hmi/vr_delete_command_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_delete_command_response.cc
@@ -38,19 +38,17 @@ namespace application_manager {
namespace commands {
VRDeleteCommandResponse::VRDeleteCommandResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VRDeleteCommandResponse::~VRDeleteCommandResponse() {
-}
+VRDeleteCommandResponse::~VRDeleteCommandResponse() {}
void VRDeleteCommandResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::VR_DeleteCommand);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/vr_get_capabilities_request.cc b/src/components/application_manager/src/commands/hmi/vr_get_capabilities_request.cc
index 58d0a4b3e4..3159380c17 100644
--- a/src/components/application_manager/src/commands/hmi/vr_get_capabilities_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_get_capabilities_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
VRGetCapabilitiesRequest::VRGetCapabilitiesRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VRGetCapabilitiesRequest::~VRGetCapabilitiesRequest() {
-}
+VRGetCapabilitiesRequest::~VRGetCapabilitiesRequest() {}
void VRGetCapabilitiesRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void VRGetCapabilitiesRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vr_get_capabilities_response.cc b/src/components/application_manager/src/commands/hmi/vr_get_capabilities_response.cc
index 5ca1d86190..9aa0fc6668 100644
--- a/src/components/application_manager/src/commands/hmi/vr_get_capabilities_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_get_capabilities_response.cc
@@ -30,28 +30,24 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/vr_get_capabilities_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
VRGetCapabilitiesResponse::VRGetCapabilitiesResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VRGetCapabilitiesResponse::~VRGetCapabilitiesResponse() {
-}
+VRGetCapabilitiesResponse::~VRGetCapabilitiesResponse() {}
void VRGetCapabilitiesResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
hmi_capabilities.set_vr_capabilities(
- (*message_)[strings::msg_params][strings::vr_capabilities]);
+ (*message_)[strings::msg_params][strings::vr_capabilities]);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/vr_get_language_request.cc b/src/components/application_manager/src/commands/hmi/vr_get_language_request.cc
index 0b98979418..baf34c8017 100644
--- a/src/components/application_manager/src/commands/hmi/vr_get_language_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_get_language_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-VRGetLanguageRequest::VRGetLanguageRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+VRGetLanguageRequest::VRGetLanguageRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VRGetLanguageRequest::~VRGetLanguageRequest() {
-}
+VRGetLanguageRequest::~VRGetLanguageRequest() {}
void VRGetLanguageRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void VRGetLanguageRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vr_get_language_response.cc b/src/components/application_manager/src/commands/hmi/vr_get_language_response.cc
index 62127bdf9b..a55dca44a3 100644
--- a/src/components/application_manager/src/commands/hmi/vr_get_language_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_get_language_response.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,28 +30,41 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/vr_get_language_response.h"
-#include "application_manager/application_manager_impl.h"
+
+#include "application_manager/event_engine/event.h"
#include "interfaces/HMI_API.h"
namespace application_manager {
namespace commands {
-VRGetLanguageResponse::VRGetLanguageResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+VRGetLanguageResponse::VRGetLanguageResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VRGetLanguageResponse::~VRGetLanguageResponse() {
-}
+VRGetLanguageResponse::~VRGetLanguageResponse() {}
void VRGetLanguageResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace hmi_apis;
+
+ Common_Language::eType language = Common_Language::INVALID_ENUM;
+
+ if ((*message_).keyExists(strings::msg_params) &&
+ (*message_)[strings::msg_params].keyExists(hmi_response::language)) {
+ language = static_cast<Common_Language::eType>(
+ (*message_)[strings::msg_params][hmi_response::language].asInt());
+ }
+
+ application_manager_.hmi_capabilities().set_active_vr_language(language);
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
- hmi_capabilities.set_active_vr_language(
- static_cast<hmi_apis::Common_Language::eType>(
- (*message_)[strings::msg_params][hmi_response::language].asInt()));
+ LOG4CXX_DEBUG(logger_,
+ "Raising event for function_id " << function_id()
+ << " and correlation_id "
+ << correlation_id());
+ event_engine::Event event(FunctionID::VR_GetLanguage);
+ event.set_smart_object(*message_);
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/hmi/vr_get_supported_languages_request.cc b/src/components/application_manager/src/commands/hmi/vr_get_supported_languages_request.cc
index aea97da02d..def4a64699 100644
--- a/src/components/application_manager/src/commands/hmi/vr_get_supported_languages_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_get_supported_languages_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
VRGetSupportedLanguagesRequest::VRGetSupportedLanguagesRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VRGetSupportedLanguagesRequest::~VRGetSupportedLanguagesRequest() {
-}
+VRGetSupportedLanguagesRequest::~VRGetSupportedLanguagesRequest() {}
void VRGetSupportedLanguagesRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void VRGetSupportedLanguagesRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vr_get_supported_languages_response.cc b/src/components/application_manager/src/commands/hmi/vr_get_supported_languages_response.cc
index b1ea89a460..e5a6ed0b86 100644
--- a/src/components/application_manager/src/commands/hmi/vr_get_supported_languages_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_get_supported_languages_response.cc
@@ -30,7 +30,7 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/vr_get_supported_languages_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
@@ -39,12 +39,10 @@ namespace application_manager {
namespace commands {
VRGetSupportedLanguagesResponse::VRGetSupportedLanguagesResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VRGetSupportedLanguagesResponse::~VRGetSupportedLanguagesResponse() {
-}
+VRGetSupportedLanguagesResponse::~VRGetSupportedLanguagesResponse() {}
void VRGetSupportedLanguagesResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -54,8 +52,7 @@ void VRGetSupportedLanguagesResponse::Run() {
(*message_)[strings::params][hmi_response::code].asInt());
if (hmi_apis::Common_Result::SUCCESS == code) {
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
hmi_capabilities.set_vr_supported_languages(
(*message_)[strings::msg_params][hmi_response::languages]);
}
diff --git a/src/components/application_manager/src/commands/hmi/vr_is_ready_request.cc b/src/components/application_manager/src/commands/hmi/vr_is_ready_request.cc
index a5a3a2b62e..8c5e8bd49b 100644
--- a/src/components/application_manager/src/commands/hmi/vr_is_ready_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_is_ready_request.cc
@@ -36,12 +36,11 @@ namespace application_manager {
namespace commands {
-VRIsReadyRequest::VRIsReadyRequest(const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+VRIsReadyRequest::VRIsReadyRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VRIsReadyRequest::~VRIsReadyRequest() {
-}
+VRIsReadyRequest::~VRIsReadyRequest() {}
void VRIsReadyRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,4 +51,3 @@ void VRIsReadyRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vr_is_ready_response.cc b/src/components/application_manager/src/commands/hmi/vr_is_ready_response.cc
index a0de7ae33a..617742a28c 100644
--- a/src/components/application_manager/src/commands/hmi/vr_is_ready_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_is_ready_response.cc
@@ -30,18 +30,16 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "application_manager/commands/hmi/vr_is_ready_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-VRIsReadyResponse::VRIsReadyResponse(const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+VRIsReadyResponse::VRIsReadyResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VRIsReadyResponse::~VRIsReadyResponse() {
-}
+VRIsReadyResponse::~VRIsReadyResponse() {}
void VRIsReadyResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -52,8 +50,7 @@ void VRIsReadyResponse::Run() {
is_available = object[strings::msg_params][strings::available].asBool();
}
- HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
hmi_capabilities.set_is_vr_cooperating(is_available);
}
diff --git a/src/components/application_manager/src/commands/hmi/vr_perform_interaction_request.cc b/src/components/application_manager/src/commands/hmi/vr_perform_interaction_request.cc
index 1791bab57a..c4646e59f4 100644
--- a/src/components/application_manager/src/commands/hmi/vr_perform_interaction_request.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_perform_interaction_request.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
VRPerformInteractionRequest::VRPerformInteractionRequest(
- const MessageSharedPtr& message)
- : RequestToHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : RequestToHMI(message, application_manager) {}
-VRPerformInteractionRequest::~VRPerformInteractionRequest() {
-}
+VRPerformInteractionRequest::~VRPerformInteractionRequest() {}
void VRPerformInteractionRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -53,4 +51,3 @@ void VRPerformInteractionRequest::Run() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/hmi/vr_perform_interaction_response.cc b/src/components/application_manager/src/commands/hmi/vr_perform_interaction_response.cc
index 8fc22ce872..bb5ceb3755 100644
--- a/src/components/application_manager/src/commands/hmi/vr_perform_interaction_response.cc
+++ b/src/components/application_manager/src/commands/hmi/vr_perform_interaction_response.cc
@@ -37,18 +37,16 @@ namespace application_manager {
namespace commands {
VRPerformInteractionResponse::VRPerformInteractionResponse(
- const MessageSharedPtr& message)
- : ResponseFromHMI(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : ResponseFromHMI(message, application_manager) {}
-VRPerformInteractionResponse::~VRPerformInteractionResponse() {
-}
+VRPerformInteractionResponse::~VRPerformInteractionResponse() {}
void VRPerformInteractionResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
event_engine::Event event(hmi_apis::FunctionID::VR_PerformInteraction);
event.set_smart_object(*message_);
- event.raise();
+ event.raise(application_manager_.event_dispatcher());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/add_command_request.cc b/src/components/application_manager/src/commands/mobile/add_command_request.cc
index da44d0e7c4..03bdfadd66 100644
--- a/src/components/application_manager/src/commands/mobile/add_command_request.cc
+++ b/src/components/application_manager/src/commands/mobile/add_command_request.cc
@@ -33,27 +33,30 @@
#include <string>
#include "application_manager/commands/mobile/add_command_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application.h"
#include "application_manager/message_helper.h"
#include "utils/file_system.h"
+#include "utils/helpers.h"
+#include "utils/custom_string.h"
namespace application_manager {
namespace commands {
-AddCommandRequest::AddCommandRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message),
- send_ui_(false),
- send_vr_(false),
- is_ui_received_(false),
- is_vr_received_(false),
- ui_result_(hmi_apis::Common_Result::INVALID_ENUM),
- vr_result_(hmi_apis::Common_Result::INVALID_ENUM) {
-}
+namespace custom_str = utils::custom_string;
-AddCommandRequest::~AddCommandRequest() {
-}
+AddCommandRequest::AddCommandRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager)
+ , send_ui_(false)
+ , send_vr_(false)
+ , is_ui_received_(false)
+ , is_vr_received_(false)
+ , ui_result_(hmi_apis::Common_Result::INVALID_ENUM)
+ , vr_result_(hmi_apis::Common_Result::INVALID_ENUM) {}
+
+AddCommandRequest::~AddCommandRequest() {}
void AddCommandRequest::onTimeOut() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -64,43 +67,43 @@ void AddCommandRequest::onTimeOut() {
void AddCommandRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
+ ApplicationSharedPtr app = application_manager_.application(
(*message_)[strings::params][strings::connection_key].asUInt());
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "No application associated with session key");
+ LOG4CXX_ERROR(logger_, "No application associated with session key");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
if ((*message_)[strings::msg_params].keyExists(strings::cmd_icon)) {
- mobile_apis::Result::eType verification_result =
- MessageHelper::VerifyImage((*message_)[strings::msg_params]
- [strings::cmd_icon], app);
+ mobile_apis::Result::eType verification_result = MessageHelper::VerifyImage(
+ (*message_)[strings::msg_params][strings::cmd_icon],
+ app,
+ application_manager_);
if (mobile_apis::Result::SUCCESS != verification_result) {
- LOG4CXX_ERROR_EXT(
- logger_,
- "MessageHelper::VerifyImage return " << verification_result);
+ LOG4CXX_ERROR(
+ logger_, "MessageHelper::VerifyImage return " << verification_result);
SendResponse(false, verification_result);
return;
}
}
if (!((*message_)[strings::msg_params].keyExists(strings::cmd_id))) {
- LOG4CXX_ERROR_EXT(logger_, "INVALID_DATA");
+ LOG4CXX_ERROR(logger_, "INVALID_DATA");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
if (app->FindCommand(
- (*message_)[strings::msg_params][strings::cmd_id].asUInt())) {
- LOG4CXX_ERROR_EXT(logger_, "INVALID_ID");
+ (*message_)[strings::msg_params][strings::cmd_id].asUInt())) {
+ LOG4CXX_ERROR(logger_, "INVALID_ID");
SendResponse(false, mobile_apis::Result::INVALID_ID);
return;
}
- bool data_exist = false;
+ bool data_exist = false;
if ((*message_)[strings::msg_params].keyExists(strings::menu_params)) {
if (!CheckCommandName(app)) {
@@ -108,21 +111,21 @@ void AddCommandRequest::Run() {
return;
}
if (((*message_)[strings::msg_params][strings::menu_params].keyExists(
- hmi_request::parent_id)) && (0 != (*message_)[strings::msg_params]
- [strings::menu_params][hmi_request::parent_id].asUInt())) {
+ hmi_request::parent_id)) &&
+ (0 !=
+ (*message_)[strings::msg_params][strings::menu_params]
+ [hmi_request::parent_id].asUInt())) {
if (!CheckCommandParentId(app)) {
- SendResponse(false, mobile_apis::Result::INVALID_ID,
- "Parent ID doesn't exist");
+ SendResponse(
+ false, mobile_apis::Result::INVALID_ID, "Parent ID doesn't exist");
return;
}
}
data_exist = true;
}
- if (((*message_)[strings::msg_params].keyExists(strings::vr_commands))
- && ((*message_)[strings::msg_params]
- [strings::vr_commands].length() > 0)) {
-
+ if (((*message_)[strings::msg_params].keyExists(strings::vr_commands)) &&
+ ((*message_)[strings::msg_params][strings::vr_commands].length() > 0)) {
if (!CheckCommandVRSynonym(app)) {
SendResponse(false, mobile_apis::Result::DUPLICATE_NAME);
return;
@@ -132,24 +135,22 @@ void AddCommandRequest::Run() {
}
if (!data_exist) {
- LOG4CXX_ERROR_EXT(logger_, "INVALID_DATA");
+ LOG4CXX_ERROR(logger_, "INVALID_DATA");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
if (IsWhiteSpaceExist()) {
- LOG4CXX_ERROR(logger_,
- "Incoming add command has contains \t\n \\t \\n");
+ LOG4CXX_ERROR(logger_, "Incoming add command has contains \t\n \\t \\n");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
- app->AddCommand((*message_)[strings::msg_params]
- [strings::cmd_id].asUInt(),
- (*message_)[strings::msg_params]);
+ app->AddCommand((*message_)[strings::msg_params][strings::cmd_id].asUInt(),
+ (*message_)[strings::msg_params]);
- smart_objects::SmartObject ui_msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject ui_msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
if ((*message_)[strings::msg_params].keyExists(strings::menu_params)) {
ui_msg_params[strings::cmd_id] =
(*message_)[strings::msg_params][strings::cmd_id];
@@ -158,10 +159,11 @@ void AddCommandRequest::Run() {
ui_msg_params[strings::app_id] = app->app_id();
- if ( ((*message_)[strings::msg_params].keyExists(strings::cmd_icon))
- && ((*message_)[strings::msg_params][strings::cmd_icon].keyExists(strings::value))
- && (0 < (*message_)[strings::msg_params][strings::cmd_icon]
- [strings::value].length())) {
+ if (((*message_)[strings::msg_params].keyExists(strings::cmd_icon)) &&
+ ((*message_)[strings::msg_params][strings::cmd_icon].keyExists(
+ strings::value)) &&
+ (0 < (*message_)[strings::msg_params][strings::cmd_icon][strings::value]
+ .length())) {
ui_msg_params[strings::cmd_icon] =
(*message_)[strings::msg_params][strings::cmd_icon];
}
@@ -169,8 +171,8 @@ void AddCommandRequest::Run() {
send_ui_ = true;
}
- smart_objects::SmartObject vr_msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject vr_msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
if ((*message_)[strings::msg_params].keyExists(strings::vr_commands)) {
vr_msg_params[strings::cmd_id] =
(*message_)[strings::msg_params][strings::cmd_id];
@@ -203,27 +205,28 @@ bool AddCommandRequest::CheckCommandName(ApplicationConstSharedPtr app) {
CommandsMap::const_iterator i = commands.begin();
uint32_t saved_parent_id = 0;
uint32_t parent_id = 0;
- if ((*message_)[strings::msg_params]
- [strings::menu_params].keyExists(hmi_request::parent_id)) {
- parent_id = (*message_)[strings::msg_params]
- [strings::menu_params][hmi_request::parent_id].asUInt();
+ if ((*message_)[strings::msg_params][strings::menu_params].keyExists(
+ hmi_request::parent_id)) {
+ parent_id = (*message_)[strings::msg_params][strings::menu_params]
+ [hmi_request::parent_id].asUInt();
}
for (; commands.end() != i; ++i) {
-
if (!(*i->second).keyExists(strings::menu_params)) {
continue;
}
saved_parent_id = 0;
if ((*i->second)[strings::menu_params].keyExists(hmi_request::parent_id)) {
- saved_parent_id = (*i->second)[strings::menu_params][hmi_request::parent_id].asUInt();
+ saved_parent_id =
+ (*i->second)[strings::menu_params][hmi_request::parent_id].asUInt();
}
- if (((*i->second)[strings::menu_params][strings::menu_name].asString()
- == (*message_)[strings::msg_params][strings::menu_params]
- [strings::menu_name].asString()) &&
+ if (((*i->second)[strings::menu_params][strings::menu_name].asString() ==
+ (*message_)[strings::msg_params][strings::menu_params]
+ [strings::menu_name].asString()) &&
(saved_parent_id == parent_id)) {
- LOG4CXX_INFO(logger_, "AddCommandRequest::CheckCommandName received"
+ LOG4CXX_INFO(logger_,
+ "AddCommandRequest::CheckCommandName received"
" command name already exist in same level menu");
return false;
}
@@ -241,23 +244,23 @@ bool AddCommandRequest::CheckCommandVRSynonym(ApplicationConstSharedPtr app) {
CommandsMap::const_iterator it = commands.begin();
for (; commands.end() != it; ++it) {
-
- if(!(*it->second).keyExists(strings::vr_commands)) {
+ if (!(*it->second).keyExists(strings::vr_commands)) {
continue;
}
for (size_t i = 0; i < (*it->second)[strings::vr_commands].length(); ++i) {
for (size_t j = 0;
- j < (*message_)[strings::msg_params][strings::vr_commands].length();
- ++j) {
- std::string vr_cmd_i =
- (*it->second)[strings::vr_commands][i].asString();
- std::string vr_cmd_j =
- (*message_)[strings::msg_params]
- [strings::vr_commands][j].asString();
-
- if (0 == strcasecmp(vr_cmd_i.c_str(), vr_cmd_j.c_str())) {
- LOG4CXX_INFO(logger_, "AddCommandRequest::CheckCommandVRSynonym"
+ j < (*message_)[strings::msg_params][strings::vr_commands].length();
+ ++j) {
+ const custom_str::CustomString& vr_cmd_i =
+ (*it->second)[strings::vr_commands][i].asCustomString();
+ const custom_str::CustomString& vr_cmd_j =
+ (*message_)[strings::msg_params][strings::vr_commands][j]
+ .asCustomString();
+
+ if (vr_cmd_i.CompareIgnoreCase(vr_cmd_j)) {
+ LOG4CXX_INFO(logger_,
+ "AddCommandRequest::CheckCommandVRSynonym"
" received command vr synonym already exist");
return false;
}
@@ -274,11 +277,12 @@ bool AddCommandRequest::CheckCommandParentId(ApplicationConstSharedPtr app) {
const int32_t parent_id =
(*message_)[strings::msg_params][strings::menu_params]
- [hmi_request::parent_id].asInt();
+ [hmi_request::parent_id].asInt();
smart_objects::SmartObject* parent = app->FindSubMenu(parent_id);
if (!parent) {
- LOG4CXX_INFO(logger_, "AddCommandRequest::CheckCommandParentId received"
+ LOG4CXX_INFO(logger_,
+ "AddCommandRequest::CheckCommandParentId received"
" submenu doesn't exist");
return false;
}
@@ -287,11 +291,12 @@ bool AddCommandRequest::CheckCommandParentId(ApplicationConstSharedPtr app) {
void AddCommandRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
const smart_objects::SmartObject& message = event.smart_object();
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "NULL pointer");
@@ -299,7 +304,8 @@ void AddCommandRequest::on_event(const event_engine::Event& event) {
}
smart_objects::SmartObject msg_param(smart_objects::SmartType_Map);
- msg_param[strings::cmd_id] = (*message_)[strings::msg_params][strings::cmd_id];
+ msg_param[strings::cmd_id] =
+ (*message_)[strings::msg_params][strings::cmd_id];
msg_param[strings::app_id] = application->app_id();
switch (event.id()) {
@@ -326,79 +332,104 @@ void AddCommandRequest::on_event(const event_engine::Event& event) {
break;
}
default: {
- LOG4CXX_ERROR(logger_,"Received unknown event" << event.id());
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
return;
}
}
- if (!IsPendingResponseExist()) {
-
- ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ if (IsPendingResponseExist()) {
+ return;
+ }
- if (hmi_apis::Common_Result::REJECTED == ui_result_) {
- RemoveCommand();
- }
+ if (hmi_apis::Common_Result::REJECTED == ui_result_) {
+ RemoveCommand();
+ }
- smart_objects::SmartObject msg_params(smart_objects::SmartType_Map);
- msg_params[strings::cmd_id] = (*message_)[strings::msg_params][strings::cmd_id];
- msg_params[strings::app_id] = application->app_id();
-
- mobile_apis::Result::eType result_code = mobile_apis::Result::INVALID_ENUM;
-
- bool result = ((hmi_apis::Common_Result::SUCCESS == ui_result_) &&
- (hmi_apis::Common_Result::SUCCESS == vr_result_)) ||
- ((hmi_apis::Common_Result::SUCCESS == ui_result_) &&
- (hmi_apis::Common_Result::INVALID_ENUM == vr_result_ ||
- hmi_apis::Common_Result::UNSUPPORTED_RESOURCE == vr_result_)) ||
- ((hmi_apis::Common_Result::INVALID_ENUM == ui_result_ ||
- hmi_apis::Common_Result::UNSUPPORTED_RESOURCE == ui_result_ ) &&
- (hmi_apis::Common_Result::SUCCESS == vr_result_));
-
- if (!result && (hmi_apis::Common_Result::REJECTED == ui_result_)) {
- result_code = static_cast<mobile_apis::Result::eType>(ui_result_);
- } else {
- result_code = static_cast<mobile_apis::Result::eType>(
- std::max(ui_result_, vr_result_));
- }
+ smart_objects::SmartObject msg_params(smart_objects::SmartType_Map);
+ msg_params[strings::cmd_id] =
+ (*message_)[strings::msg_params][strings::cmd_id];
+ msg_params[strings::app_id] = application->app_id();
+
+ mobile_apis::Result::eType result_code = mobile_apis::Result::INVALID_ENUM;
+
+ const bool is_vr_invalid_unsupported =
+ Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ vr_result_,
+ hmi_apis::Common_Result::INVALID_ENUM,
+ hmi_apis::Common_Result::UNSUPPORTED_RESOURCE);
+
+ const bool is_ui_ivalid_unsupported =
+ Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ ui_result_,
+ hmi_apis::Common_Result::INVALID_ENUM,
+ hmi_apis::Common_Result::UNSUPPORTED_RESOURCE);
+
+ const bool is_no_ui_error = Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ ui_result_,
+ hmi_apis::Common_Result::SUCCESS,
+ hmi_apis::Common_Result::WARNINGS);
+
+ const bool is_no_vr_error = Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ vr_result_,
+ hmi_apis::Common_Result::SUCCESS,
+ hmi_apis::Common_Result::WARNINGS);
+
+ bool result = (is_no_ui_error && is_no_vr_error) ||
+ (is_no_ui_error && is_vr_invalid_unsupported) ||
+ (is_no_vr_error && is_ui_ivalid_unsupported);
+
+ const bool is_vr_or_ui_warning =
+ Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ hmi_apis::Common_Result::WARNINGS, ui_result_, vr_result_);
+
+ if (!result && hmi_apis::Common_Result::REJECTED == ui_result_) {
+ result_code = MessageHelper::HMIToMobileResult(ui_result_);
+ } else if (is_vr_or_ui_warning) {
+ result_code = mobile_apis::Result::WARNINGS;
+ } else {
+ result_code =
+ MessageHelper::HMIToMobileResult(std::max(ui_result_, vr_result_));
+ }
- if (BothSend() && hmi_apis::Common_Result::SUCCESS == vr_result_) {
- if (hmi_apis::Common_Result::SUCCESS != ui_result_ &&
- hmi_apis::Common_Result::WARNINGS != ui_result_ &&
- hmi_apis::Common_Result::UNSUPPORTED_RESOURCE != ui_result_) {
+ if (BothSend() && hmi_apis::Common_Result::SUCCESS == vr_result_) {
+ const bool is_ui_not_ok = Compare<hmi_apis::Common_Result::eType, NEQ, ALL>(
+ ui_result_,
+ hmi_apis::Common_Result::SUCCESS,
+ hmi_apis::Common_Result::WARNINGS,
+ hmi_apis::Common_Result::UNSUPPORTED_RESOURCE);
- result_code =
- (ui_result_ == hmi_apis::Common_Result::REJECTED) ?
- mobile_apis::Result::REJECTED : mobile_apis::Result::GENERIC_ERROR;
+ if (is_ui_not_ok) {
+ result_code = ui_result_ == hmi_apis::Common_Result::REJECTED
+ ? mobile_apis::Result::REJECTED
+ : mobile_apis::Result::GENERIC_ERROR;
- msg_params[strings::grammar_id] = application->get_grammar_id();
- msg_params[strings::type] = hmi_apis::Common_VRCommandType::Command;
+ msg_params[strings::grammar_id] = application->get_grammar_id();
+ msg_params[strings::type] = hmi_apis::Common_VRCommandType::Command;
- SendHMIRequest(hmi_apis::FunctionID::VR_DeleteCommand, &msg_params);
- application->RemoveCommand((*message_)[strings::msg_params]
- [strings::cmd_id].asUInt());
- result = false;
- }
+ SendHMIRequest(hmi_apis::FunctionID::VR_DeleteCommand, &msg_params);
+ application->RemoveCommand(
+ (*message_)[strings::msg_params][strings::cmd_id].asUInt());
+ result = false;
}
+ }
- if(BothSend() && hmi_apis::Common_Result::SUCCESS == ui_result_ &&
- hmi_apis::Common_Result::SUCCESS != vr_result_) {
+ if (BothSend() && hmi_apis::Common_Result::SUCCESS == ui_result_ &&
+ !is_no_vr_error) {
+ result_code = vr_result_ == hmi_apis::Common_Result::REJECTED
+ ? mobile_apis::Result::REJECTED
+ : mobile_apis::Result::GENERIC_ERROR;
- result_code =
- (vr_result_ == hmi_apis::Common_Result::REJECTED) ?
- mobile_apis::Result::REJECTED : mobile_apis::Result::GENERIC_ERROR;
+ SendHMIRequest(hmi_apis::FunctionID::UI_DeleteCommand, &msg_params);
- SendHMIRequest(hmi_apis::FunctionID::UI_DeleteCommand, &msg_params);
+ application->RemoveCommand(
+ (*message_)[strings::msg_params][strings::cmd_id].asUInt());
+ result = false;
+ }
- application->RemoveCommand((*message_)[strings::msg_params]
- [strings::cmd_id].asUInt());
- result = false;
- }
+ SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
- SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
- if (true == result) {
- application->UpdateHash();
- }
+ if (result) {
+ application->UpdateHash();
}
}
@@ -412,7 +443,7 @@ bool AddCommandRequest::IsWhiteSpaceExist() {
if ((*message_)[strings::msg_params].keyExists(strings::menu_params)) {
str = (*message_)[strings::msg_params][strings::menu_params]
- [strings::menu_name].asCharArray();
+ [strings::menu_name].asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid menu name syntax check failed.");
return true;
@@ -424,8 +455,8 @@ bool AddCommandRequest::IsWhiteSpaceExist() {
(*message_)[strings::msg_params][strings::vr_commands].length();
for (size_t i = 0; i < len; ++i) {
- str = (*message_)[strings::msg_params]
- [strings::vr_commands][i].asCharArray();
+ str = (*message_)[strings::msg_params][strings::vr_commands][i]
+ .asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid vr_commands syntax check failed");
return true;
@@ -434,8 +465,8 @@ bool AddCommandRequest::IsWhiteSpaceExist() {
}
if ((*message_)[strings::msg_params].keyExists(strings::cmd_icon)) {
- str = (*message_)[strings::msg_params]
- [strings::cmd_icon][strings::value].asCharArray();
+ str = (*message_)[strings::msg_params][strings::cmd_icon][strings::value]
+ .asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid cmd_icon value syntax check failed");
return true;
@@ -450,19 +481,19 @@ bool AddCommandRequest::BothSend() const {
void AddCommandRequest::RemoveCommand() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
- connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app.valid()) {
LOG4CXX_ERROR(logger_, "No application associated with session key");
return;
}
smart_objects::SmartObject msg_params(smart_objects::SmartType_Map);
- msg_params[strings::cmd_id] = (*message_)[strings::msg_params][strings::cmd_id];
+ msg_params[strings::cmd_id] =
+ (*message_)[strings::msg_params][strings::cmd_id];
msg_params[strings::app_id] = app->app_id();
- app->RemoveCommand((*message_)[strings::msg_params]
- [strings::cmd_id].asUInt());
+ app->RemoveCommand(
+ (*message_)[strings::msg_params][strings::cmd_id].asUInt());
if (BothSend() && !(is_vr_received_ || is_ui_received_)) {
// in case we have send bth UI and VR and no one respond
@@ -479,7 +510,6 @@ void AddCommandRequest::RemoveCommand() {
msg_params[strings::type] = hmi_apis::Common_VRCommandType::Command;
SendHMIRequest(hmi_apis::FunctionID::VR_DeleteCommand, &msg_params);
}
-
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/add_command_response.cc b/src/components/application_manager/src/commands/mobile/add_command_response.cc
index 51684c065b..fc468f9c57 100644
--- a/src/components/application_manager/src/commands/mobile/add_command_response.cc
+++ b/src/components/application_manager/src/commands/mobile/add_command_response.cc
@@ -32,23 +32,21 @@
*/
#include "application_manager/commands/mobile/add_command_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-AddCommandResponse::AddCommandResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+AddCommandResponse::AddCommandResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-AddCommandResponse::~AddCommandResponse() {
-}
+AddCommandResponse::~AddCommandResponse() {}
void AddCommandResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/add_sub_menu_request.cc b/src/components/application_manager/src/commands/mobile/add_sub_menu_request.cc
index f01645079c..83f137ac19 100644
--- a/src/components/application_manager/src/commands/mobile/add_sub_menu_request.cc
+++ b/src/components/application_manager/src/commands/mobile/add_sub_menu_request.cc
@@ -32,25 +32,24 @@
*/
#include "application_manager/commands/mobile/add_sub_menu_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application.h"
+#include "utils/helpers.h"
namespace application_manager {
namespace commands {
-AddSubMenuRequest::AddSubMenuRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+AddSubMenuRequest::AddSubMenuRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-AddSubMenuRequest::~AddSubMenuRequest() {
-}
+AddSubMenuRequest::~AddSubMenuRequest() {}
void AddSubMenuRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
- (*message_)[strings::params][strings::connection_key].asUInt());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
LOG4CXX_ERROR(logger_, "NULL pointer");
@@ -58,34 +57,37 @@ void AddSubMenuRequest::Run() {
return;
}
- if (app->FindSubMenu(
- (*message_)[strings::msg_params][strings::menu_id].asInt())) {
- LOG4CXX_ERROR(logger_, "INVALID_ID");
+ const int32_t menu_id =
+ (*message_)[strings::msg_params][strings::menu_id].asInt();
+ if (app->FindSubMenu(menu_id)) {
+ LOG4CXX_ERROR(logger_, "Menu with id " << menu_id << " is not found.");
SendResponse(false, mobile_apis::Result::INVALID_ID);
return;
}
- if (app->IsSubMenuNameAlreadyExist(
- (*message_)[strings::msg_params][strings::menu_name].asString())) {
- LOG4CXX_ERROR(logger_, "DUPLICATE_NAME");
+ const std::string& menu_name =
+ (*message_)[strings::msg_params][strings::menu_name].asString();
+
+ if (app->IsSubMenuNameAlreadyExist(menu_name)) {
+ LOG4CXX_ERROR(logger_, "Menu name " << menu_name << " is duplicated.");
SendResponse(false, mobile_apis::Result::DUPLICATE_NAME);
return;
}
if (!CheckSubMenuName()) {
- LOG4CXX_ERROR(logger_, "SubMenuName is not valid");
+ LOG4CXX_ERROR(logger_, "Sub-menu name is not valid.");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::menu_id] =
(*message_)[strings::msg_params][strings::menu_id];
if ((*message_)[strings::msg_params].keyExists(strings::position)) {
- msg_params[strings::menu_params][strings::position] =
- (*message_)[strings::msg_params][strings::position];
+ msg_params[strings::menu_params][strings::position] =
+ (*message_)[strings::msg_params][strings::position];
}
msg_params[strings::menu_params][strings::menu_name] =
(*message_)[strings::msg_params][strings::menu_name];
@@ -96,6 +98,7 @@ void AddSubMenuRequest::Run() {
void AddSubMenuRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
@@ -104,10 +107,13 @@ void AddSubMenuRequest::on_event(const event_engine::Event& event) {
static_cast<mobile_apis::Result::eType>(
message[strings::params][hmi_response::code].asInt());
- bool result = mobile_apis::Result::SUCCESS == result_code;
+ const bool result = Compare<mobile_api::Result::eType, EQ, ONE>(
+ result_code,
+ mobile_api::Result::SUCCESS,
+ mobile_api::Result::WARNINGS);
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "NULL pointer");
@@ -115,10 +121,10 @@ void AddSubMenuRequest::on_event(const event_engine::Event& event) {
}
if (result) {
- application->AddSubMenu((*message_)[strings::msg_params]
- [strings::menu_id].asInt(),
- (*message_)[strings::msg_params]);
- }
+ application->AddSubMenu(
+ (*message_)[strings::msg_params][strings::menu_id].asInt(),
+ (*message_)[strings::msg_params]);
+ }
SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
if (result) {
application->UpdateHash();
@@ -133,6 +139,7 @@ void AddSubMenuRequest::on_event(const event_engine::Event& event) {
}
bool AddSubMenuRequest::CheckSubMenuName() {
+ LOG4CXX_AUTO_TRACE(logger_);
const char* str = NULL;
str = (*message_)[strings::msg_params][strings::menu_name].asCharArray();
diff --git a/src/components/application_manager/src/commands/mobile/add_sub_menu_response.cc b/src/components/application_manager/src/commands/mobile/add_sub_menu_response.cc
index ff37a6a998..1fbdb4e66c 100644
--- a/src/components/application_manager/src/commands/mobile/add_sub_menu_response.cc
+++ b/src/components/application_manager/src/commands/mobile/add_sub_menu_response.cc
@@ -32,24 +32,23 @@
*/
#include "application_manager/commands/mobile/add_sub_menu_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
namespace application_manager {
namespace commands {
-AddSubMenuResponse::AddSubMenuResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+AddSubMenuResponse::AddSubMenuResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-AddSubMenuResponse::~AddSubMenuResponse() {
-}
+AddSubMenuResponse::~AddSubMenuResponse() {}
void AddSubMenuResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/alert_maneuver_request.cc b/src/components/application_manager/src/commands/mobile/alert_maneuver_request.cc
index f1575a1a4b..ea00bc8d70 100644
--- a/src/components/application_manager/src/commands/mobile/alert_maneuver_request.cc
+++ b/src/components/application_manager/src/commands/mobile/alert_maneuver_request.cc
@@ -1,6 +1,5 @@
/*
-
- Copyright (c) 2013, Ford Motor Company
+ Copyright (c) 2016, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -31,25 +30,28 @@
POSSIBILITY OF SUCH DAMAGE.
*/
-#include <string.h>
+#include <cstring>
+#include <string>
#include "application_manager/commands/mobile/alert_maneuver_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
+#include "application_manager/policies/policy_handler.h"
#include "application_manager/message_helper.h"
+#include "utils/helpers.h"
namespace application_manager {
namespace commands {
-AlertManeuverRequest::AlertManeuverRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message),
- tts_speak_result_code_(mobile_apis::Result::INVALID_ENUM),
- navi_alert_maneuver_result_code_(mobile_apis::Result::INVALID_ENUM) {
+AlertManeuverRequest::AlertManeuverRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager)
+ , tts_speak_result_code_(mobile_apis::Result::INVALID_ENUM)
+ , navi_alert_maneuver_result_code_(mobile_apis::Result::INVALID_ENUM) {
subscribe_on_event(hmi_apis::FunctionID::TTS_OnResetTimeout);
}
-AlertManeuverRequest::~AlertManeuverRequest() {
-}
+AlertManeuverRequest::~AlertManeuverRequest() {}
void AlertManeuverRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -61,7 +63,7 @@ void AlertManeuverRequest::Run() {
return;
}
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
+ ApplicationSharedPtr app = application_manager_.application(
(*message_)[strings::params][strings::connection_key].asUInt());
if (NULL == app.get()) {
@@ -78,10 +80,13 @@ void AlertManeuverRequest::Run() {
return;
}
- //ProcessSoftButtons checks strings on the contents incorrect character
+ // ProcessSoftButtons checks strings on the contents incorrect character
mobile_apis::Result::eType processing_result =
- MessageHelper::ProcessSoftButtons((*message_)[strings::msg_params], app);
+ MessageHelper::ProcessSoftButtons((*message_)[strings::msg_params],
+ app,
+ application_manager_.GetPolicyHandler(),
+ application_manager_);
if (mobile_apis::Result::SUCCESS != processing_result) {
LOG4CXX_ERROR(logger_, "Wrong soft buttons parameters!");
@@ -100,25 +105,25 @@ void AlertManeuverRequest::Run() {
}
}
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::app_id] = app->app_id();
if ((*message_)[strings::msg_params].keyExists(strings::soft_buttons)) {
msg_params[hmi_request::soft_buttons] =
- (*message_)[strings::msg_params][strings::soft_buttons];
- MessageHelper::SubscribeApplicationToSoftButton((*message_)[strings::msg_params],
- app, function_id());
+ (*message_)[strings::msg_params][strings::soft_buttons];
+ MessageHelper::SubscribeApplicationToSoftButton(
+ (*message_)[strings::msg_params], app, function_id());
}
pending_requests_.Add(hmi_apis::FunctionID::Navigation_AlertManeuver);
- SendHMIRequest(hmi_apis::FunctionID::Navigation_AlertManeuver,
- &msg_params, true);
+ SendHMIRequest(
+ hmi_apis::FunctionID::Navigation_AlertManeuver, &msg_params, true);
if (tts_is_ok) {
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[hmi_request::tts_chunks] =
(*message_)[strings::msg_params][strings::tts_chunks];
@@ -131,9 +136,12 @@ void AlertManeuverRequest::Run() {
void AlertManeuverRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
const smart_objects::SmartObject& message = event.smart_object();
-
- mobile_apis::Result::eType result_code = mobile_apis::Result::INVALID_ENUM;
+ bool is_tts_ok;
+ bool is_no_navi_error;
+ hmi_apis::Common_Result::eType tts_result;
+ hmi_apis::Common_Result::eType navi_result;
hmi_apis::FunctionID::eType event_id = event.id();
switch (event_id) {
case hmi_apis::FunctionID::Navigation_AlertManeuver: {
@@ -143,8 +151,23 @@ void AlertManeuverRequest::on_event(const event_engine::Event& event) {
navi_alert_maneuver_result_code_ =
static_cast<mobile_apis::Result::eType>(
- message[strings::params][hmi_response::code].asInt());
-
+ message[strings::params][hmi_response::code].asInt());
+ navi_result =
+ MessageHelper::MobileToHMIResult(navi_alert_maneuver_result_code_);
+ is_no_navi_error = Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ navi_result,
+ hmi_apis::Common_Result::SUCCESS,
+ hmi_apis::Common_Result::WARNINGS);
+
+ const bool is_navi_success =
+ Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ navi_result, hmi_apis::Common_Result::SUCCESS);
+ if (is_navi_success) {
+ info_navi_ =
+ message[strings::msg_params][hmi_response::message].asString();
+ } else {
+ info_navi_ = message[strings::msg_params][strings::info].asString();
+ }
break;
}
case hmi_apis::FunctionID::TTS_Speak: {
@@ -152,60 +175,85 @@ void AlertManeuverRequest::on_event(const event_engine::Event& event) {
pending_requests_.Remove(event_id);
- tts_speak_result_code_ =
- static_cast<mobile_apis::Result::eType>(
+ tts_speak_result_code_ = static_cast<mobile_apis::Result::eType>(
message[strings::params][hmi_response::code].asInt());
+ tts_result = MessageHelper::MobileToHMIResult(tts_speak_result_code_);
+
+ is_tts_ok = Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ tts_result,
+ hmi_apis::Common_Result::SUCCESS,
+ hmi_apis::Common_Result::UNSUPPORTED_RESOURCE,
+ hmi_apis::Common_Result::WARNINGS,
+ hmi_apis::Common_Result::INVALID_ENUM);
+
+ const bool is_tts_success =
+ Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ tts_result, hmi_apis::Common_Result::SUCCESS);
+ if (is_tts_success) {
+ info_tts_ =
+ message[strings::msg_params][hmi_response::message].asString();
+ } else {
+ info_tts_ = message[strings::msg_params][strings::info].asString();
+ }
break;
}
case hmi_apis::FunctionID::TTS_OnResetTimeout: {
LOG4CXX_INFO(logger_, "Received TTS_OnResetTimeout event");
- ApplicationManagerImpl::instance()->updateRequestTimeout(
+ application_manager_.updateRequestTimeout(
connection_key(), correlation_id(), default_timeout());
break;
}
default: {
- LOG4CXX_ERROR(logger_,"Received unknown event" << event.id());
- SendResponse(false, result_code, "Received unknown event");
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
+ SendResponse(
+ false, mobile_apis::Result::INVALID_ENUM, "Received unknown event");
return;
}
}
- if (pending_requests_.IsFinal(event_id)) {
-
- bool result = ((hmi_apis::Common_Result::SUCCESS ==
- static_cast<hmi_apis::Common_Result::eType>(tts_speak_result_code_) ||
- hmi_apis::Common_Result::UNSUPPORTED_RESOURCE ==
- static_cast<hmi_apis::Common_Result::eType>(tts_speak_result_code_) ||
- (hmi_apis::Common_Result::INVALID_ENUM ==
- static_cast<hmi_apis::Common_Result::eType>(tts_speak_result_code_))) &&
- (hmi_apis::Common_Result::SUCCESS ==
- static_cast<hmi_apis::Common_Result::eType>(navi_alert_maneuver_result_code_))) ||
- (hmi_apis::Common_Result::SUCCESS == static_cast<hmi_apis::Common_Result::eType>(
- tts_speak_result_code_) && hmi_apis::Common_Result::UNSUPPORTED_RESOURCE ==
- static_cast<hmi_apis::Common_Result::eType>(navi_alert_maneuver_result_code_));
-
- mobile_apis::Result::eType result_code =
- static_cast<mobile_apis::Result::eType>(std::max(tts_speak_result_code_,
- navi_alert_maneuver_result_code_));
-
- const char* return_info = NULL;
-
- if (result && hmi_apis::Common_Result::UNSUPPORTED_RESOURCE ==
- static_cast<hmi_apis::Common_Result::eType>(tts_speak_result_code_)) {
- result_code = mobile_apis::Result::WARNINGS;
- return_info =
- std::string("Unsupported phoneme type sent in a prompt").c_str();
- }
+ if (!pending_requests_.IsFinal(event_id)) {
+ LOG4CXX_DEBUG(logger_,
+ "There are some pending responses from HMI."
+ "AlertManeuverRequest still waiting.");
+ return;
+ }
+
+ const bool result =
+ (is_tts_ok && is_no_navi_error) ||
+ (hmi_apis::Common_Result::SUCCESS == tts_result &&
+ hmi_apis::Common_Result::UNSUPPORTED_RESOURCE == navi_result);
+
+ mobile_apis::Result::eType result_code =
+ static_cast<mobile_apis::Result::eType>(
+ std::max(tts_speak_result_code_, navi_alert_maneuver_result_code_));
+
+ std::string return_info;
- SendResponse(result, result_code, return_info,
- &(message[strings::msg_params]));
- } else {
- LOG4CXX_INFO(logger_,
- "There are some pending responses from HMI."
- "AlertManeuverRequest still waiting.");
+ const bool is_tts_or_navi_warning =
+ Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ hmi_apis::Common_Result::WARNINGS, tts_result, navi_result);
+
+ if (result && (is_tts_or_navi_warning ||
+ hmi_apis::Common_Result::UNSUPPORTED_RESOURCE == tts_result)) {
+ result_code = mobile_apis::Result::WARNINGS;
+ return_info = std::string("Unsupported phoneme type sent in a prompt");
+ }
+
+ if (!info_tts_.empty() && !info_navi_.empty()) {
+ info_tts_ += ". ";
+ }
+ return_info = info_tts_ + info_navi_;
+ bool must_be_empty_info = false;
+ if (return_info.find("\n") != std::string::npos ||
+ return_info.find("\t") != std::string::npos) {
+ must_be_empty_info = true;
}
+ SendResponse(result,
+ result_code,
+ (must_be_empty_info) ? NULL : return_info.c_str(),
+ &(message[strings::msg_params]));
}
bool AlertManeuverRequest::IsWhiteSpaceExist() {
diff --git a/src/components/application_manager/src/commands/mobile/alert_maneuver_response.cc b/src/components/application_manager/src/commands/mobile/alert_maneuver_response.cc
index 8f9c73267f..2f441594c2 100644
--- a/src/components/application_manager/src/commands/mobile/alert_maneuver_response.cc
+++ b/src/components/application_manager/src/commands/mobile/alert_maneuver_response.cc
@@ -32,24 +32,23 @@
*/
#include "application_manager/commands/mobile/alert_maneuver_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
namespace commands {
-AlertManeuverResponse::AlertManeuverResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+AlertManeuverResponse::AlertManeuverResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-AlertManeuverResponse::~AlertManeuverResponse() {
-}
+AlertManeuverResponse::~AlertManeuverResponse() {}
void AlertManeuverResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/alert_request.cc b/src/components/application_manager/src/commands/mobile/alert_request.cc
index ccabe4e177..53910a05b7 100644
--- a/src/components/application_manager/src/commands/mobile/alert_request.cc
+++ b/src/components/application_manager/src/commands/mobile/alert_request.cc
@@ -37,8 +37,9 @@
#include "application_manager/message_helper.h"
#include "application_manager/application_impl.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/policies/policy_handler.h"
+#include "utils/helpers.h"
namespace application_manager {
@@ -46,21 +47,21 @@ namespace commands {
namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
-AlertRequest::AlertRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message),
- awaiting_ui_alert_response_(false),
- awaiting_tts_speak_response_(false),
- awaiting_tts_stop_speaking_response_(false),
- response_success_(false),
- flag_other_component_sent_(false),
- response_result_(mobile_apis::Result::INVALID_ENUM),
- tts_speak_response_(mobile_apis::Result::INVALID_ENUM) {
+AlertRequest::AlertRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager)
+ , awaiting_ui_alert_response_(false)
+ , awaiting_tts_speak_response_(false)
+ , awaiting_tts_stop_speaking_response_(false)
+ , is_alert_succeeded_(false)
+ , is_ui_alert_sent_(false)
+ , alert_result_(mobile_apis::Result::INVALID_ENUM)
+ , tts_speak_result_(mobile_apis::Result::INVALID_ENUM) {
subscribe_on_event(hmi_apis::FunctionID::UI_OnResetTimeout);
subscribe_on_event(hmi_apis::FunctionID::TTS_OnResetTimeout);
}
-AlertRequest::~AlertRequest() {
-}
+AlertRequest::~AlertRequest() {}
bool AlertRequest::Init() {
/* Timeout in milliseconds.
@@ -73,9 +74,11 @@ bool AlertRequest::Init() {
default_timeout_ = def_value;
}
- // If soft buttons are present, SDL will not use initiate timeout tracking for response.
+ // If soft buttons are present, SDL will not use initiate timeout tracking for
+ // response.
if ((*message_)[strings::msg_params].keyExists(strings::soft_buttons)) {
- LOG4CXX_INFO(logger_, "Request contains soft buttons - request timeout "
+ LOG4CXX_INFO(logger_,
+ "Request contains soft buttons - request timeout "
"will be set to 0.");
default_timeout_ = 0;
}
@@ -86,48 +89,62 @@ bool AlertRequest::Init() {
void AlertRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- uint32_t app_id = (*message_)[strings::params][strings::connection_key]
- .asInt();
+ uint32_t app_id =
+ (*message_)[strings::params][strings::connection_key].asInt();
if (!Validate(app_id)) {
// Invalid command, abort execution
return;
}
+ bool tts_chunks_exists =
+ (*message_)[strings::msg_params].keyExists(strings::tts_chunks);
+ size_t length_tts_chunks = 0;
- if ((*message_)[strings::msg_params].keyExists(strings::tts_chunks)) {
- if (0 < (*message_)[strings::msg_params][strings::tts_chunks].length()) {
- awaiting_tts_speak_response_ = true;
- }
+ if (tts_chunks_exists) {
+ length_tts_chunks =
+ (*message_)[strings::msg_params][strings::tts_chunks].length();
+ }
+
+ if ((tts_chunks_exists && length_tts_chunks) ||
+ ((*message_)[strings::msg_params].keyExists(strings::play_tone) &&
+ (*message_)[strings::msg_params][strings::play_tone].asBool())) {
+ awaiting_tts_speak_response_ = true;
}
+
SendAlertRequest(app_id);
- SendPlayToneNotification(app_id);
if (awaiting_tts_speak_response_) {
- SendSpeakRequest(app_id);
+ SendSpeakRequest(app_id, tts_chunks_exists, length_tts_chunks);
}
}
void AlertRequest::onTimeOut() {
- if (false == (*message_)[strings::msg_params].keyExists(strings::soft_buttons)) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (false ==
+ (*message_)[strings::msg_params].keyExists(strings::soft_buttons)) {
CommandRequestImpl::onTimeOut();
return;
}
- LOG4CXX_INFO(logger_, "default timeout ignored. "
- "AlertRequest with soft buttons wait timeout on HMI side");
+ LOG4CXX_INFO(logger_,
+ "Default timeout ignored. "
+ "AlertRequest with soft buttons wait timeout on HMI side");
}
void AlertRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
+
const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
case hmi_apis::FunctionID::TTS_OnResetTimeout:
case hmi_apis::FunctionID::UI_OnResetTimeout: {
- LOG4CXX_INFO(logger_, "Received UI_OnResetTimeout event "
- " or TTS_OnResetTimeout event"
- << awaiting_tts_speak_response_ << " "
- << awaiting_tts_stop_speaking_response_ << " "
- << awaiting_ui_alert_response_);
- ApplicationManagerImpl::instance()->updateRequestTimeout(
+ LOG4CXX_INFO(logger_,
+ "Received UI_OnResetTimeout event "
+ " or TTS_OnResetTimeout event"
+ << awaiting_tts_speak_response_ << " "
+ << awaiting_tts_stop_speaking_response_ << " "
+ << awaiting_ui_alert_response_);
+ application_manager_.updateRequestTimeout(
connection_key(), correlation_id(), default_timeout());
break;
}
@@ -146,10 +163,16 @@ void AlertRequest::on_event(const event_engine::Event& event) {
static_cast<mobile_apis::Result::eType>(
message[strings::params][hmi_response::code].asInt());
// Mobile Alert request is successful when UI_Alert is successful
- response_success_ = (mobile_apis::Result::SUCCESS == result_code ||
- mobile_apis::Result::UNSUPPORTED_RESOURCE == result_code);
- response_result_ = result_code;
- response_params_ = message[strings::msg_params];
+
+ const bool is_alert_ok = Compare<mobile_api::Result::eType, EQ, ONE>(
+ result_code,
+ mobile_apis::Result::SUCCESS,
+ mobile_apis::Result::UNSUPPORTED_RESOURCE,
+ mobile_apis::Result::WARNINGS);
+
+ is_alert_succeeded_ = is_alert_ok;
+ alert_result_ = result_code;
+ alert_response_params_ = message[strings::msg_params];
break;
}
case hmi_apis::FunctionID::TTS_Speak: {
@@ -157,7 +180,7 @@ void AlertRequest::on_event(const event_engine::Event& event) {
// Unsubscribe from event to avoid unwanted messages
unsubscribe_from_event(hmi_apis::FunctionID::TTS_Speak);
awaiting_tts_speak_response_ = false;
- tts_speak_response_ = static_cast<mobile_apis::Result::eType>(
+ tts_speak_result_ = static_cast<mobile_apis::Result::eType>(
message[strings::params][hmi_response::code].asInt());
break;
}
@@ -169,62 +192,82 @@ void AlertRequest::on_event(const event_engine::Event& event) {
break;
}
default: {
- LOG4CXX_ERROR(logger_,"Received unknown event" << event.id());
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
return;
}
}
- if (!HasHmiResponsesToWait()) {
- std::string response_info("");
- if ((mobile_apis::Result::UNSUPPORTED_RESOURCE == tts_speak_response_) &&
- (!flag_other_component_sent_)) {
- response_success_ = false;
- response_result_ = mobile_apis::Result::WARNINGS;
- response_info = "Unsupported phoneme type sent in a prompt";
- } else if ((mobile_apis::Result::UNSUPPORTED_RESOURCE ==
- tts_speak_response_) && (mobile_apis::Result::UNSUPPORTED_RESOURCE ==
- response_result_)) {
- response_result_ = mobile_apis::Result::WARNINGS;
- response_info = "Unsupported phoneme type sent in a prompt and "
- "unsupported image sent in soft buttons";
- } else if ((mobile_apis::Result::UNSUPPORTED_RESOURCE ==
- tts_speak_response_) && (mobile_apis::Result::SUCCESS ==
- response_result_)) {
- response_result_ = mobile_apis::Result::WARNINGS;
- response_info = "Unsupported phoneme type sent in a prompt";
- } else if ((mobile_apis::Result::SUCCESS == tts_speak_response_) &&
- ((mobile_apis::Result::INVALID_ENUM == response_result_) &&
- (!flag_other_component_sent_))) {
- response_result_ = mobile_apis::Result::SUCCESS;
- response_success_ = true;
- }
- if (((mobile_apis::Result::ABORTED == tts_speak_response_ )||
- (mobile_apis::Result::REJECTED == tts_speak_response_)) &&
- (!flag_other_component_sent_)) {
- response_success_ = false;
- response_result_ = tts_speak_response_;
- }
- SendResponse(response_success_, response_result_,
- response_info.empty() ? NULL : response_info.c_str(),
- &response_params_);
+ if (HasHmiResponsesToWait()) {
+ return;
+ }
+
+ const bool is_tts_alert_unsupported =
+ Compare<mobile_api::Result::eType, EQ, ALL>(
+ mobile_api::Result::UNSUPPORTED_RESOURCE,
+ tts_speak_result_,
+ alert_result_);
+
+ const bool is_alert_ok = Compare<mobile_api::Result::eType, EQ, ONE>(
+ alert_result_, mobile_api::Result::SUCCESS, mobile_api::Result::WARNINGS);
+
+ std::string response_info;
+ if (mobile_apis::Result::UNSUPPORTED_RESOURCE == tts_speak_result_ &&
+ !is_ui_alert_sent_) {
+ is_alert_succeeded_ = false;
+ alert_result_ = mobile_apis::Result::WARNINGS;
+ response_info = "Unsupported phoneme type sent in a prompt";
+ } else if (is_tts_alert_unsupported) {
+ alert_result_ = mobile_apis::Result::WARNINGS;
+ response_info =
+ "Unsupported phoneme type sent in a prompt and "
+ "unsupported image sent in soft buttons";
+ } else if (mobile_apis::Result::UNSUPPORTED_RESOURCE == tts_speak_result_ &&
+ is_alert_ok) {
+ alert_result_ = mobile_apis::Result::WARNINGS;
+ response_info = "Unsupported phoneme type sent in a prompt";
+ } else if (mobile_apis::Result::SUCCESS == tts_speak_result_ &&
+ (mobile_apis::Result::INVALID_ENUM == alert_result_ &&
+ !is_ui_alert_sent_)) {
+ alert_result_ = mobile_apis::Result::SUCCESS;
+ is_alert_succeeded_ = true;
+ }
+
+ const bool is_tts_not_ok =
+ Compare<mobile_api::Result::eType, EQ, ONE>(tts_speak_result_,
+ mobile_api::Result::ABORTED,
+ mobile_api::Result::REJECTED);
+
+ if (is_tts_not_ok && !is_ui_alert_sent_) {
+ is_alert_succeeded_ = false;
+ alert_result_ = tts_speak_result_;
+ }
+
+ if (mobile_apis::Result::WARNINGS == tts_speak_result_) {
+ alert_result_ = mobile_apis::Result::WARNINGS;
}
+
+ SendResponse(is_alert_succeeded_,
+ alert_result_,
+ response_info.empty() ? NULL : response_info.c_str(),
+ &alert_response_params_);
}
bool AlertRequest::Validate(uint32_t app_id) {
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(app_id);
+ LOG4CXX_AUTO_TRACE(logger_);
+ ApplicationSharedPtr app = application_manager_.application(app_id);
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "No application associated with session key");
+ LOG4CXX_ERROR(logger_, "No application associated with session key");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return false;
}
if (mobile_apis::HMILevel::HMI_BACKGROUND == app->hmi_level() &&
app->IsCommandLimitsExceeded(
- static_cast<mobile_apis::FunctionID::eType>(function_id()),
- application_manager::TLimitSource::POLICY_TABLE)) {
+ static_cast<mobile_apis::FunctionID::eType>(function_id()),
+ application_manager::TLimitSource::POLICY_TABLE)) {
LOG4CXX_ERROR(logger_, "Alert frequency is too high.");
- SendResponse(false, mobile_apis::Result::REJECTED);
+ SendResponse(false, mobile_apis::Result::REJECTED);
return false;
}
@@ -233,10 +276,13 @@ bool AlertRequest::Validate(uint32_t app_id) {
return false;
}
- //ProcessSoftButtons checks strings on the contents incorrect character
+ // ProcessSoftButtons checks strings on the contents incorrect character
mobile_apis::Result::eType processing_result =
- MessageHelper::ProcessSoftButtons((*message_)[strings::msg_params], app);
+ MessageHelper::ProcessSoftButtons((*message_)[strings::msg_params],
+ app,
+ application_manager_.GetPolicyHandler(),
+ application_manager_);
if (mobile_apis::Result::SUCCESS != processing_result) {
LOG4CXX_ERROR(logger_, "INVALID_DATA!");
@@ -245,13 +291,13 @@ bool AlertRequest::Validate(uint32_t app_id) {
}
// check if mandatory params(alertText1 and TTSChunk) specified
- if ((!(*message_)[strings::msg_params].keyExists(strings::alert_text1))
- && (!(*message_)[strings::msg_params].keyExists(strings::alert_text2))
- && (!(*message_)[strings::msg_params].keyExists(strings::tts_chunks)
- && (1 > (*message_)[strings::msg_params]
- [strings::tts_chunks].length()))) {
- LOG4CXX_ERROR_EXT(logger_, "Mandatory parameters are missing");
- SendResponse(false, mobile_apis::Result::INVALID_DATA,
+ if ((!(*message_)[strings::msg_params].keyExists(strings::alert_text1)) &&
+ (!(*message_)[strings::msg_params].keyExists(strings::alert_text2)) &&
+ (!(*message_)[strings::msg_params].keyExists(strings::tts_chunks) &&
+ (1 > (*message_)[strings::msg_params][strings::tts_chunks].length()))) {
+ LOG4CXX_ERROR(logger_, "Mandatory parameters are missing");
+ SendResponse(false,
+ mobile_apis::Result::INVALID_DATA,
"Mandatory parameters are missing");
return false;
}
@@ -260,21 +306,22 @@ bool AlertRequest::Validate(uint32_t app_id) {
}
void AlertRequest::SendAlertRequest(int32_t app_id) {
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(app_id);
+ LOG4CXX_AUTO_TRACE(logger_);
+ ApplicationSharedPtr app = application_manager_.application(app_id);
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
- msg_params[hmi_request::alert_strings] = smart_objects::SmartObject(
- smart_objects::SmartType_Array);
+ msg_params[hmi_request::alert_strings] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
int32_t index = 0;
if ((*message_)[strings::msg_params].keyExists(strings::alert_text1)) {
msg_params[hmi_request::alert_strings][index][hmi_request::field_name] =
hmi_apis::Common_TextFieldName::alertText1;
- msg_params[hmi_request::alert_strings][index][hmi_request::field_text] =
- (*message_)[strings::msg_params][strings::alert_text1];
- index++;
+ msg_params[hmi_request::alert_strings][index][hmi_request::field_text] =
+ (*message_)[strings::msg_params][strings::alert_text1];
+ index++;
}
if ((*message_)[strings::msg_params].keyExists(strings::alert_text2)) {
msg_params[hmi_request::alert_strings][index][hmi_request::field_name] =
@@ -287,7 +334,7 @@ void AlertRequest::SendAlertRequest(int32_t app_id) {
msg_params[hmi_request::alert_strings][index][hmi_request::field_name] =
hmi_apis::Common_TextFieldName::alertText3;
msg_params[hmi_request::alert_strings][index][hmi_request::field_text] =
- (*message_)[strings::msg_params][strings::alert_text3];
+ (*message_)[strings::msg_params][strings::alert_text3];
}
// softButtons
@@ -304,7 +351,7 @@ void AlertRequest::SendAlertRequest(int32_t app_id) {
// NAVI platform progressIndicator
if ((*message_)[strings::msg_params].keyExists(strings::progress_indicator)) {
msg_params[strings::progress_indicator] =
- (*message_)[strings::msg_params][strings::progress_indicator];
+ (*message_)[strings::msg_params][strings::progress_indicator];
}
// PASA Alert type
@@ -316,44 +363,35 @@ void AlertRequest::SendAlertRequest(int32_t app_id) {
// check out if there are alert strings or soft buttons
if (msg_params[hmi_request::alert_strings].length() > 0 ||
msg_params.keyExists(hmi_request::soft_buttons)) {
-
awaiting_ui_alert_response_ = true;
- flag_other_component_sent_ = true;
+ is_ui_alert_sent_ = true;
SendHMIRequest(hmi_apis::FunctionID::UI_Alert, &msg_params, true);
}
}
-void AlertRequest::SendSpeakRequest(int32_t app_id) {
+void AlertRequest::SendSpeakRequest(int32_t app_id,
+ bool tts_chunks_exists,
+ size_t length_tts_chunks) {
+ LOG4CXX_AUTO_TRACE(logger_);
using namespace hmi_apis;
using namespace smart_objects;
// crate HMI speak request
SmartObject msg_params = smart_objects::SmartObject(SmartType_Map);
-
- msg_params[hmi_request::tts_chunks] = smart_objects::SmartObject(SmartType_Array);
- msg_params[hmi_request::tts_chunks] =
- (*message_)[strings::msg_params][strings::tts_chunks];
+ if (tts_chunks_exists && length_tts_chunks) {
+ msg_params[hmi_request::tts_chunks] =
+ smart_objects::SmartObject(SmartType_Array);
+ msg_params[hmi_request::tts_chunks] =
+ (*message_)[strings::msg_params][strings::tts_chunks];
+ }
+ if ((*message_)[strings::msg_params].keyExists(strings::play_tone) &&
+ (*message_)[strings::msg_params][strings::play_tone].asBool()) {
+ msg_params[strings::play_tone] = true;
+ }
msg_params[strings::app_id] = app_id;
msg_params[hmi_request::speak_type] = Common_MethodName::ALERT;
SendHMIRequest(FunctionID::TTS_Speak, &msg_params, true);
}
-void AlertRequest::SendPlayToneNotification(int32_t app_id) {
- LOG4CXX_AUTO_TRACE(logger_);
- using namespace hmi_apis;
- using namespace smart_objects;
-
- // check playtone parameter
- if ((*message_)[strings::msg_params].keyExists(strings::play_tone)) {
- if ((*message_)[strings::msg_params][strings::play_tone].asBool()) {
- // crate HMI basic communication playtone request
- SmartObject msg_params = smart_objects::SmartObject(SmartType_Map);
- msg_params[strings::app_id] = app_id;
- msg_params[strings::method_name] = Common_MethodName::ALERT;
- CreateHMINotification(FunctionID::BasicCommunication_PlayTone, msg_params);
- }
- }
-}
-
bool AlertRequest::CheckStringsOfAlertRequest() {
LOG4CXX_AUTO_TRACE(logger_);
const char* str = NULL;
@@ -362,7 +400,7 @@ bool AlertRequest::CheckStringsOfAlertRequest() {
str = (*message_)[strings::msg_params][strings::alert_text1].asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid alert_text_1 syntax check failed");
- return false;
+ return false;
}
}
@@ -370,7 +408,7 @@ bool AlertRequest::CheckStringsOfAlertRequest() {
str = (*message_)[strings::msg_params][strings::alert_text2].asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid alert_text_2 syntax check failed");
- return false;
+ return false;
}
}
@@ -378,7 +416,7 @@ bool AlertRequest::CheckStringsOfAlertRequest() {
str = (*message_)[strings::msg_params][strings::alert_text3].asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid alert_text_3 syntax check failed");
- return false;
+ return false;
}
}
@@ -397,8 +435,9 @@ bool AlertRequest::CheckStringsOfAlertRequest() {
}
bool AlertRequest::HasHmiResponsesToWait() {
- return awaiting_ui_alert_response_ || awaiting_tts_speak_response_
- || awaiting_tts_stop_speaking_response_;
+ LOG4CXX_AUTO_TRACE(logger_);
+ return awaiting_ui_alert_response_ || awaiting_tts_speak_response_ ||
+ awaiting_tts_stop_speaking_response_;
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/alert_response.cc b/src/components/application_manager/src/commands/mobile/alert_response.cc
index dac086a8b1..f8ca487eae 100644
--- a/src/components/application_manager/src/commands/mobile/alert_response.cc
+++ b/src/components/application_manager/src/commands/mobile/alert_response.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/alert_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
@@ -41,17 +41,16 @@ namespace application_manager {
namespace commands {
-AlertResponse::AlertResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+AlertResponse::AlertResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-AlertResponse::~AlertResponse() {
-}
+AlertResponse::~AlertResponse() {}
void AlertResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/change_registration_request.cc b/src/components/application_manager/src/commands/mobile/change_registration_request.cc
index 89b2dbaf00..63339fdc33 100644
--- a/src/components/application_manager/src/commands/mobile/change_registration_request.cc
+++ b/src/components/application_manager/src/commands/mobile/change_registration_request.cc
@@ -1,6 +1,6 @@
/*
- Copyright (c) 2013, Ford Motor Company
+ Copyright (c) 2016, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -34,33 +34,45 @@
#include <string.h>
#include <algorithm>
#include "application_manager/commands/mobile/change_registration_request.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
+namespace {
+namespace custom_str = utils::custom_string;
+struct IsSameNickname {
+ IsSameNickname(const custom_str::CustomString& app_id) : app_id_(app_id) {}
+ bool operator()(const policy::StringArray::value_type& nickname) const {
+ return app_id_.CompareIgnoreCase(nickname.c_str());
+ }
+
+ private:
+ const custom_str::CustomString& app_id_;
+};
+}
+
namespace application_manager {
namespace commands {
ChangeRegistrationRequest::ChangeRegistrationRequest(
- const MessageSharedPtr& message)
- : CommandRequestImpl(message),
- ui_result_(hmi_apis::Common_Result::INVALID_ENUM),
- vr_result_(hmi_apis::Common_Result::INVALID_ENUM),
- tts_result_(hmi_apis::Common_Result::INVALID_ENUM) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager)
+ , ui_result_(hmi_apis::Common_Result::INVALID_ENUM)
+ , vr_result_(hmi_apis::Common_Result::INVALID_ENUM)
+ , tts_result_(hmi_apis::Common_Result::INVALID_ENUM) {}
-ChangeRegistrationRequest::~ChangeRegistrationRequest() {
-}
+ChangeRegistrationRequest::~ChangeRegistrationRequest() {}
void ChangeRegistrationRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace smart_objects;
- ApplicationManagerImpl* instance = ApplicationManagerImpl::instance();
- const HMICapabilities& hmi_capabilities = instance->hmi_capabilities();
+ const HMICapabilities& hmi_capabilities =
+ application_manager_.hmi_capabilities();
- ApplicationSharedPtr app = instance->application(connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
LOG4CXX_ERROR(logger_, "NULL pointer");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
@@ -91,90 +103,84 @@ void ChangeRegistrationRequest::Run() {
tts_result_ = hmi_apis::Common_Result::UNSUPPORTED_RESOURCE;
}
+ SmartObject& msg_params = (*message_)[strings::msg_params];
+
const int32_t hmi_language =
- (*message_)[strings::msg_params][strings::hmi_display_language].asInt();
+ msg_params[strings::hmi_display_language].asInt();
- const int32_t language =
- (*message_)[strings::msg_params][strings::language].asInt();
+ const int32_t language = msg_params[strings::language].asInt();
- if (false ==
- (IsLanguageSupportedByUI(hmi_language) &&
- IsLanguageSupportedByVR(language) &&
- IsLanguageSupportedByTTS(language))) {
+ if (false == (IsLanguageSupportedByUI(hmi_language) &&
+ IsLanguageSupportedByVR(language) &&
+ IsLanguageSupportedByTTS(language))) {
LOG4CXX_ERROR(logger_, "Language is not supported");
SendResponse(false, mobile_apis::Result::REJECTED);
return;
}
+ if (msg_params.keyExists(strings::app_name) &&
+ !IsNicknameAllowed(msg_params[strings::app_name].asCustomString())) {
+ LOG4CXX_ERROR(logger_, "Nickname is not allowed.");
+ SendResponse(false, mobile_apis::Result::DISALLOWED);
+ return;
+ }
+
pending_requests_.Add(hmi_apis::FunctionID::UI_ChangeRegistration);
pending_requests_.Add(hmi_apis::FunctionID::VR_ChangeRegistration);
pending_requests_.Add(hmi_apis::FunctionID::TTS_ChangeRegistration);
// UI processing
- smart_objects::SmartObject ui_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ SmartObject ui_params = SmartObject(SmartType_Map);
ui_params[strings::language] = hmi_language;
ui_params[strings::app_id] = app->app_id();
- if ((*message_)[strings::msg_params].keyExists(strings::app_name)) {
- ui_params[strings::app_name] =
- (*message_)[strings::msg_params][strings::app_name];
- app->set_name((*message_)[strings::msg_params][strings::app_name].asString());
+ if (msg_params.keyExists(strings::app_name)) {
+ ui_params[strings::app_name] = msg_params[strings::app_name];
+ app->set_name(msg_params[strings::app_name].asCustomString());
}
- if ((*message_)[strings::msg_params].keyExists(
- strings::ngn_media_screen_app_name)) {
+ if (msg_params.keyExists(strings::ngn_media_screen_app_name)) {
ui_params[strings::ngn_media_screen_app_name] =
- (*message_)[strings::msg_params][strings::ngn_media_screen_app_name];
- app->set_ngn_media_screen_name((*message_)[strings::msg_params]
- [strings::ngn_media_screen_app_name]);
+ msg_params[strings::ngn_media_screen_app_name];
+ app->set_ngn_media_screen_name(
+ msg_params[strings::ngn_media_screen_app_name]);
}
- SendHMIRequest(hmi_apis::FunctionID::UI_ChangeRegistration,
- &ui_params, true);
+ SendHMIRequest(hmi_apis::FunctionID::UI_ChangeRegistration, &ui_params, true);
// VR processing
- smart_objects::SmartObject vr_params =
- smart_objects::SmartObject(smart_objects::SmartType_Map);
+ SmartObject vr_params = SmartObject(SmartType_Map);
- vr_params[strings::language] =
- (*message_)[strings::msg_params][strings::language];
+ vr_params[strings::language] = msg_params[strings::language];
vr_params[strings::app_id] = app->app_id();
- if ((*message_)[strings::msg_params].keyExists(strings::vr_synonyms)) {
- vr_params[strings::vr_synonyms] = (*message_)[strings::msg_params]
- [strings::vr_synonyms];
- app -> set_vr_synonyms((*message_)[strings::msg_params][strings::vr_synonyms]);
+ if (msg_params.keyExists(strings::vr_synonyms)) {
+ vr_params[strings::vr_synonyms] = msg_params[strings::vr_synonyms];
+ app->set_vr_synonyms(msg_params[strings::vr_synonyms]);
}
- SendHMIRequest(hmi_apis::FunctionID::VR_ChangeRegistration,
- &vr_params, true);
+ SendHMIRequest(hmi_apis::FunctionID::VR_ChangeRegistration, &vr_params, true);
// TTS processing
- smart_objects::SmartObject tts_params =
- smart_objects::SmartObject(smart_objects::SmartType_Map);
+ SmartObject tts_params = SmartObject(SmartType_Map);
- tts_params[strings::language] =
- (*message_)[strings::msg_params][strings::language];
+ tts_params[strings::language] = msg_params[strings::language];
tts_params[strings::app_id] = app->app_id();
- if ((*message_)[strings::msg_params].keyExists(strings::tts_name)) {
- tts_params[strings::tts_name] = (*message_)[strings::msg_params]
- [strings::tts_name];
- app->set_tts_name((*message_)[strings::msg_params][strings::tts_name]);
+ if (msg_params.keyExists(strings::tts_name)) {
+ tts_params[strings::tts_name] = msg_params[strings::tts_name];
+ app->set_tts_name(msg_params[strings::tts_name]);
}
- SendHMIRequest(hmi_apis::FunctionID::TTS_ChangeRegistration,
- &tts_params, true);
+ SendHMIRequest(
+ hmi_apis::FunctionID::TTS_ChangeRegistration, &tts_params, true);
}
bool ChangeRegistrationRequest::AllHmiResponsesSuccess(
- const hmi_apis::Common_Result::eType ui,
- const hmi_apis::Common_Result::eType vr,
- const hmi_apis::Common_Result::eType tts) {
-
- return
- hmi_apis::Common_Result::SUCCESS == ui &&
- hmi_apis::Common_Result::SUCCESS == vr &&
- hmi_apis::Common_Result::SUCCESS == tts;
+ const hmi_apis::Common_Result::eType ui,
+ const hmi_apis::Common_Result::eType vr,
+ const hmi_apis::Common_Result::eType tts) {
+ return hmi_apis::Common_Result::SUCCESS == ui &&
+ hmi_apis::Common_Result::SUCCESS == vr &&
+ hmi_apis::Common_Result::SUCCESS == tts;
}
void ChangeRegistrationRequest::on_event(const event_engine::Event& event) {
@@ -213,7 +219,7 @@ void ChangeRegistrationRequest::on_event(const event_engine::Event& event) {
if (pending_requests_.IsFinal(event_id)) {
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "NULL pointer");
@@ -222,36 +228,37 @@ void ChangeRegistrationRequest::on_event(const event_engine::Event& event) {
if (hmi_apis::Common_Result::SUCCESS == ui_result_) {
application->set_ui_language(static_cast<mobile_api::Language::eType>(
- (*message_)[strings::msg_params][strings::hmi_display_language].asInt()));
+ (*message_)[strings::msg_params][strings::hmi_display_language]
+ .asInt()));
}
- if (hmi_apis::Common_Result::SUCCESS == vr_result_
- || hmi_apis::Common_Result::SUCCESS == tts_result_) {
+ if (hmi_apis::Common_Result::SUCCESS == vr_result_ ||
+ hmi_apis::Common_Result::SUCCESS == tts_result_) {
application->set_language(static_cast<mobile_api::Language::eType>(
(*message_)[strings::msg_params][strings::language].asInt()));
}
- int32_t greates_result_code = std::max(std::max(ui_result_, vr_result_),
- tts_result_);
+ int32_t greates_result_code =
+ std::max(std::max(ui_result_, vr_result_), tts_result_);
(*message_)[strings::params][strings::function_id] =
- mobile_apis::FunctionID::eType::ChangeRegistrationID;
+ mobile_apis::FunctionID::eType::ChangeRegistrationID;
SendResponse(AllHmiResponsesSuccess(ui_result_, vr_result_, tts_result_),
static_cast<mobile_apis::Result::eType>(greates_result_code),
- NULL, &(message[strings::msg_params]));
+ NULL,
+ &(message[strings::msg_params]));
} else {
LOG4CXX_INFO(logger_,
- "There are some pending responses from HMI."
- "ChangeRegistrationRequest still waiting.");
+ "There are some pending responses from HMI."
+ "ChangeRegistrationRequest still waiting.");
}
}
bool ChangeRegistrationRequest::IsLanguageSupportedByUI(
const int32_t& hmi_display_lang) {
-
const HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ application_manager_.hmi_capabilities();
const smart_objects::SmartObject* ui_languages =
hmi_capabilities.ui_supported_languages();
@@ -274,7 +281,7 @@ bool ChangeRegistrationRequest::IsLanguageSupportedByUI(
bool ChangeRegistrationRequest::IsLanguageSupportedByVR(
const int32_t& hmi_display_lang) {
const HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ application_manager_.hmi_capabilities();
const smart_objects::SmartObject* vr_languages =
hmi_capabilities.vr_supported_languages();
@@ -297,7 +304,7 @@ bool ChangeRegistrationRequest::IsLanguageSupportedByVR(
bool ChangeRegistrationRequest::IsLanguageSupportedByTTS(
const int32_t& hmi_display_lang) {
const HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ application_manager_.hmi_capabilities();
const smart_objects::SmartObject* tts_languages =
hmi_capabilities.tts_supported_languages();
@@ -344,10 +351,10 @@ bool ChangeRegistrationRequest::IsWhiteSpaceExist() {
}
}
- if ((*message_)[strings::msg_params].
- keyExists(strings::ngn_media_screen_app_name)) {
- str = (*message_)[strings::msg_params]
- [strings::ngn_media_screen_app_name].asCharArray();
+ if ((*message_)[strings::msg_params].keyExists(
+ strings::ngn_media_screen_app_name)) {
+ str = (*message_)[strings::msg_params][strings::ngn_media_screen_app_name]
+ .asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_,
"Invalid ngn_media_screen_app_name syntax check failed");
@@ -379,22 +386,22 @@ mobile_apis::Result::eType ChangeRegistrationRequest::CheckCoincidence() {
const smart_objects::SmartObject& msg_params =
(*message_)[strings::msg_params];
- ApplicationManagerImpl::ApplicationListAccessor accessor;
- std::string app_name;
+ ApplicationSet accessor = application_manager_.applications().GetData();
+ custom_str::CustomString app_name;
uint32_t app_id = connection_key();
if (msg_params.keyExists(strings::app_name)) {
- app_name = msg_params[strings::app_name].asString();
+ app_name = msg_params[strings::app_name].asCustomString();
}
- ApplicationManagerImpl::ApplictionSetConstIt it = accessor.begin();
+ ApplicationSetConstIt it = accessor.begin();
for (; accessor.end() != it; ++it) {
if (app_id == (*it)->app_id()) {
continue;
}
- const std::string& cur_name = (*it)->name();
+ const custom_str::CustomString& cur_name = (*it)->name();
if (msg_params.keyExists(strings::app_name)) {
- if (!strcasecmp(app_name.c_str(), cur_name.c_str())) {
+ if (app_name.CompareIgnoreCase(cur_name)) {
LOG4CXX_ERROR(logger_, "Application name is known already.");
return mobile_apis::Result::DUPLICATE_NAME;
}
@@ -423,10 +430,57 @@ mobile_apis::Result::eType ChangeRegistrationRequest::CheckCoincidence() {
return mobile_apis::Result::DUPLICATE_NAME;
}
} // end vr check
- } // application for end
+ } // application for end
return mobile_apis::Result::SUCCESS;
}
+bool ChangeRegistrationRequest::IsNicknameAllowed(
+ const custom_str::CustomString& app_name) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
+
+ if (!app) {
+ LOG4CXX_ERROR(logger_,
+ "Can't find appication with connection key "
+ << connection_key());
+ return false;
+ }
+
+ const std::string policy_app_id = app->policy_app_id();
+
+ policy::StringArray app_nicknames;
+ policy::StringArray app_hmi_types;
+
+ bool init_result = application_manager_.GetPolicyHandler().GetInitialAppData(
+ policy_app_id, &app_nicknames, &app_hmi_types);
+
+ if (!init_result) {
+ LOG4CXX_ERROR(logger_,
+ "Error during getting of nickname list for application "
+ << policy_app_id);
+ return false;
+ }
+
+ if (!app_nicknames.empty()) {
+ IsSameNickname compare(app_name);
+ policy::StringArray::const_iterator it =
+ std::find_if(app_nicknames.begin(), app_nicknames.end(), compare);
+ if (app_nicknames.end() == it) {
+ LOG4CXX_WARN(logger_,
+ "Application name was not found in nicknames list.");
+
+ usage_statistics::AppCounter count_of_rejections_nickname_mismatch(
+ application_manager_.GetPolicyHandler().GetStatisticManager(),
+ policy_app_id,
+ usage_statistics::REJECTIONS_NICKNAME_MISMATCH);
+ ++count_of_rejections_nickname_mismatch;
+
+ return false;
+ }
+ }
+ return true;
+}
+
} // namespace commands
} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/change_registration_response.cc b/src/components/application_manager/src/commands/mobile/change_registration_response.cc
index 557614f173..210cae64c5 100644
--- a/src/components/application_manager/src/commands/mobile/change_registration_response.cc
+++ b/src/components/application_manager/src/commands/mobile/change_registration_response.cc
@@ -32,24 +32,21 @@
*/
#include "application_manager/commands/mobile/change_registration_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
ChangeRegistrationResponse::ChangeRegistrationResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-ChangeRegistrationResponse::~ChangeRegistrationResponse() {
-}
+ChangeRegistrationResponse::~ChangeRegistrationResponse() {}
void ChangeRegistrationResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/create_interaction_choice_set_request.cc b/src/components/application_manager/src/commands/mobile/create_interaction_choice_set_request.cc
index 58c6d7e192..b602601f26 100644
--- a/src/components/application_manager/src/commands/mobile/create_interaction_choice_set_request.cc
+++ b/src/components/application_manager/src/commands/mobile/create_interaction_choice_set_request.cc
@@ -1,6 +1,6 @@
/*
- Copyright (c) 2013, Ford Motor Company
+ Copyright (c) 2016, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -31,26 +31,26 @@
POSSIBILITY OF SUCH DAMAGE.
*/
-#include <string.h>
#include <string>
#include <algorithm>
#include <vector>
#include "application_manager/commands/mobile/create_interaction_choice_set_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
+#include "utils/gen_hash.h"
+#include "utils/helpers.h"
namespace application_manager {
namespace commands {
CreateInteractionChoiceSetRequest::CreateInteractionChoiceSetRequest(
- const MessageSharedPtr& message)
- : CommandRequestImpl(message),
- expected_chs_count_(0),
- received_chs_count_(0),
- error_from_hmi_(false) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager)
+ , expected_chs_count_(0)
+ , received_chs_count_(0)
+ , error_from_hmi_(false) {}
CreateInteractionChoiceSetRequest::~CreateInteractionChoiceSetRequest() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -59,8 +59,7 @@ CreateInteractionChoiceSetRequest::~CreateInteractionChoiceSetRequest() {
void CreateInteractionChoiceSetRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
using namespace mobile_apis;
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
- (*message_)[strings::params][strings::connection_key].asUInt());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
LOG4CXX_ERROR(logger_, "NULL pointer");
@@ -72,31 +71,37 @@ void CreateInteractionChoiceSetRequest::Run() {
++i) {
Result::eType verification_result_image = Result::SUCCESS;
Result::eType verification_result_secondary_image = Result::SUCCESS;
- if ((*message_)[strings::msg_params]
- [strings::choice_set][i].keyExists(strings::image)) {
+ if ((*message_)[strings::msg_params][strings::choice_set][i].keyExists(
+ strings::image)) {
verification_result_image = MessageHelper::VerifyImage(
- (*message_)[strings::msg_params][strings::choice_set]
- [i][strings::image], app);
+ (*message_)[strings::msg_params][strings::choice_set][i]
+ [strings::image],
+ app,
+ application_manager_);
}
- if ((*message_)[strings::msg_params]
- [strings::choice_set][i].keyExists(strings::secondary_image)) {
+ if ((*message_)[strings::msg_params][strings::choice_set][i].keyExists(
+ strings::secondary_image)) {
verification_result_secondary_image = MessageHelper::VerifyImage(
- (*message_)[strings::msg_params][strings::choice_set]
- [i][strings::secondary_image], app);
+ (*message_)[strings::msg_params][strings::choice_set][i]
+ [strings::secondary_image],
+ app,
+ application_manager_);
}
if (verification_result_image == Result::INVALID_DATA ||
verification_result_secondary_image == Result::INVALID_DATA) {
- LOG4CXX_ERROR(logger_, "VerifyImage INVALID_DATA!");
- SendResponse(false, Result::INVALID_DATA);
+ LOG4CXX_ERROR(logger_, "Image verification failed.");
+ SendResponse(false, Result::INVALID_DATA);
return;
}
}
- choice_set_id_ = (*message_)[strings::msg_params]
- [strings::interaction_choice_set_id].asInt();
+ choice_set_id_ =
+ (*message_)[strings::msg_params][strings::interaction_choice_set_id]
+ .asInt();
if (app->FindChoiceSet(choice_set_id_)) {
- LOG4CXX_ERROR(logger_, "Invalid ID");
+ LOG4CXX_ERROR(logger_,
+ "Choice set with id " << choice_set_id_ << " is not found.");
SendResponse(false, Result::INVALID_ID);
return;
}
@@ -106,134 +111,64 @@ void CreateInteractionChoiceSetRequest::Run() {
SendResponse(false, result);
return;
}
- uint32_t grammar_id = ApplicationManagerImpl::instance()->GenerateGrammarID();
+ uint32_t grammar_id = application_manager_.GenerateGrammarID();
(*message_)[strings::msg_params][strings::grammar_id] = grammar_id;
app->AddChoiceSet(choice_set_id_, (*message_)[strings::msg_params]);
SendVRAddCommandRequests(app);
}
mobile_apis::Result::eType CreateInteractionChoiceSetRequest::CheckChoiceSet(
- ApplicationConstSharedPtr app) {
+ ApplicationConstSharedPtr app) {
+ using namespace smart_objects;
LOG4CXX_AUTO_TRACE(logger_);
- const smart_objects::SmartArray* new_choice_set_array =
- (*message_)[strings::msg_params][strings::choice_set].asArray();
-
- smart_objects::SmartArray::const_iterator it_array =
- new_choice_set_array->begin();
+ std::set<uint32_t> choice_id_set;
- smart_objects::SmartArray::const_iterator it_array_end =
- new_choice_set_array->end();
+ const SmartArray* choice_set =
+ (*message_)[strings::msg_params][strings::choice_set].asArray();
- // Self check of new choice set for params coincidence
- for (; it_array != it_array_end; ++it_array) {
- const smart_objects::SmartArray* vr_array =
- (*it_array)[strings::vr_commands].asArray();
+ SmartArray::const_iterator choice_set_it = choice_set->begin();
- CoincidencePredicateChoiceID c((*it_array)[strings::choice_id].asInt());
- if (1 != std::count_if(
- new_choice_set_array->begin(),
- new_choice_set_array->end(), c)) {
- LOG4CXX_ERROR(logger_, "Incoming choice set has duplicate IDs.");
+ for (; choice_set->end() != choice_set_it; ++choice_set_it) {
+ std::pair<std::set<uint32_t>::iterator, bool> ins_res =
+ choice_id_set.insert((*choice_set_it)[strings::choice_id].asInt());
+ if (!ins_res.second) {
+ LOG4CXX_ERROR(logger_,
+ "Choise with ID "
+ << (*choice_set_it)[strings::choice_id].asInt()
+ << " already exists");
return mobile_apis::Result::INVALID_ID;
}
- // Check new choice set params along with already registered choice sets
- const DataAccessor<ChoiceSetMap> accessor = app->choice_set_map();
- const ChoiceSetMap& app_choice_set_map = accessor.GetData();
- ChoiceSetMap::const_iterator it = app_choice_set_map.begin();
- ChoiceSetMap::const_iterator itEnd = app_choice_set_map.end();
- for (; it != itEnd; ++it) {
- const smart_objects::SmartObject* app_choice_set = it->second;
- if (NULL != app_choice_set) {
- const smart_objects::SmartArray* curr_choice_set =
- (*app_choice_set)[strings::choice_set].asArray();
-
- if (0 != std::count_if(
- curr_choice_set->begin(),
- curr_choice_set->end(),
- c)) {
- LOG4CXX_ERROR(logger_, "Incoming choice ID already exists.");
- return mobile_apis::Result::INVALID_ID;
- }
- }
- }
-
- CoincidencePredicateMenuName m((*it_array)[strings::menu_name].asString());
- if (1 != std::count_if(
- new_choice_set_array->begin(),
- new_choice_set_array->end(),
- m)) {
- LOG4CXX_ERROR(logger_, "Incoming choice set has duplicate menu names.");
- return mobile_apis::Result::DUPLICATE_NAME;
- }
-
- // Check coincidence inside the current choice
-
- smart_objects::SmartArray::const_iterator it_vr = vr_array->begin();
- smart_objects::SmartArray::const_iterator it_vr_end = vr_array->end();
-
- for (; it_vr != it_vr_end; ++it_vr) {
- CoincidencePredicateVRCommands v((*it_vr));
- if (1 != std::count_if(vr_array->begin(), vr_array->end(), v)) {
- LOG4CXX_ERROR(logger_,
- "Incoming choice set has duplicate VR command(s)");
-
- return mobile_apis::Result::DUPLICATE_NAME;
- }
- }
-
- // Check along with VR commands in other choices in the new set
- smart_objects::SmartArray::const_iterator it_same_array =
- new_choice_set_array->begin();
-
- smart_objects::SmartArray::const_iterator it_same_array_end =
- new_choice_set_array->end();
-
- for (; it_same_array != it_same_array_end; ++it_same_array) {
- // Skip check for itself
- if ((*it_array)[strings::choice_id] ==
- (*it_same_array)[strings::choice_id]) {
- continue;
- }
-
- if (compareSynonyms((*it_array), (*it_same_array))) {
- LOG4CXX_ERROR(logger_,
- "Incoming choice set has duplicate VR command(s).");
-
- return mobile_apis::Result::DUPLICATE_NAME;
- }
- }
-
- if (IsWhiteSpaceExist((*it_array))) {
- LOG4CXX_ERROR(logger_,
- "Incoming choice set has contains \t\n \\t \\n");
+ if (IsWhiteSpaceExist(*choice_set_it)) {
+ LOG4CXX_ERROR(logger_, "Incoming choice set has contains \t\n \\t \\n");
return mobile_apis::Result::INVALID_DATA;
}
}
-
return mobile_apis::Result::SUCCESS;
}
bool CreateInteractionChoiceSetRequest::compareSynonyms(
- const NsSmartDeviceLink::NsSmartObjects::SmartObject& choice1,
- const NsSmartDeviceLink::NsSmartObjects::SmartObject& choice2) {
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& choice1,
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& choice2) {
smart_objects::SmartArray* vr_cmds_1 =
- choice1[strings::vr_commands].asArray();
+ choice1[strings::vr_commands].asArray();
DCHECK(vr_cmds_1 != NULL);
smart_objects::SmartArray* vr_cmds_2 =
- choice2[strings::vr_commands].asArray();
+ choice2[strings::vr_commands].asArray();
DCHECK(vr_cmds_2 != NULL);
smart_objects::SmartArray::iterator it;
- it = std::find_first_of(vr_cmds_1->begin(), vr_cmds_1->end(),
- vr_cmds_2->begin(), vr_cmds_2->end(),
+ it = std::find_first_of(vr_cmds_1->begin(),
+ vr_cmds_1->end(),
+ vr_cmds_2->begin(),
+ vr_cmds_2->end(),
CreateInteractionChoiceSetRequest::compareStr);
-
if (it != vr_cmds_1->end()) {
- LOG4CXX_INFO(logger_, "Incoming choice set has duplicated VR synonyms "
- << it->asString());
+ LOG4CXX_INFO(logger_,
+ "Incoming choice set has duplicated VR synonyms "
+ << it->asString());
return true;
}
@@ -241,13 +176,13 @@ bool CreateInteractionChoiceSetRequest::compareSynonyms(
}
bool CreateInteractionChoiceSetRequest::compareStr(
- const NsSmartDeviceLink::NsSmartObjects::SmartObject& str1,
- const NsSmartDeviceLink::NsSmartObjects::SmartObject& str2) {
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& str1,
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& str2) {
return 0 == strcasecmp(str1.asCharArray(), str2.asCharArray());
}
bool CreateInteractionChoiceSetRequest::IsWhiteSpaceExist(
- const smart_objects::SmartObject& choice_set) {
+ const smart_objects::SmartObject& choice_set) {
LOG4CXX_AUTO_TRACE(logger_);
const char* str = NULL;
@@ -274,8 +209,7 @@ bool CreateInteractionChoiceSetRequest::IsWhiteSpaceExist(
}
if (choice_set.keyExists(strings::vr_commands)) {
- const size_t len =
- choice_set[strings::vr_commands].length();
+ const size_t len = choice_set[strings::vr_commands].length();
for (size_t i = 0; i < len; ++i) {
str = choice_set[strings::vr_commands][i].asCharArray();
@@ -297,8 +231,9 @@ bool CreateInteractionChoiceSetRequest::IsWhiteSpaceExist(
if (choice_set.keyExists(strings::secondary_image)) {
str = choice_set[strings::secondary_image][strings::value].asCharArray();
if (!CheckSyntax(str)) {
- LOG4CXX_ERROR(logger_, "Invalid secondary_image value. "
- "Syntax check failed");
+ LOG4CXX_ERROR(logger_,
+ "Invalid secondary_image value. "
+ "Syntax check failed");
return true;
}
}
@@ -306,15 +241,15 @@ bool CreateInteractionChoiceSetRequest::IsWhiteSpaceExist(
}
void CreateInteractionChoiceSetRequest::SendVRAddCommandRequests(
- application_manager::ApplicationSharedPtr const app) {
+ application_manager::ApplicationSharedPtr const app) {
LOG4CXX_AUTO_TRACE(logger_);
smart_objects::SmartObject& choice_set = (*message_)[strings::msg_params];
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::type] = hmi_apis::Common_VRCommandType::Choice;
msg_params[strings::app_id] = app->app_id();
- msg_params[strings::grammar_id] = choice_set[strings::grammar_id];
+ msg_params[strings::grammar_id] = choice_set[strings::grammar_id];
const uint32_t choice_count = choice_set[strings::choice_set].length();
SetAllowedToTerminate(false);
@@ -324,17 +259,18 @@ void CreateInteractionChoiceSetRequest::SendVRAddCommandRequests(
{
sync_primitives::AutoLock error_lock(error_from_hmi_lock_);
if (error_from_hmi_) {
- LOG4CXX_WARN(logger_, "Error from HMI received. Stop sending VRCommands");
+ LOG4CXX_WARN(logger_,
+ "Error from HMI received. Stop sending VRCommands");
break;
}
}
msg_params[strings::cmd_id] =
- choice_set[strings::choice_set][chs_num][strings::choice_id];
- msg_params[strings::vr_commands] = smart_objects::SmartObject(
- smart_objects::SmartType_Array);
+ choice_set[strings::choice_set][chs_num][strings::choice_id];
+ msg_params[strings::vr_commands] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
msg_params[strings::vr_commands] =
- choice_set[strings::choice_set][chs_num][strings::vr_commands];
+ choice_set[strings::choice_set][chs_num][strings::vr_commands];
sync_primitives::AutoLock commands_lock(vr_commands_lock_);
const uint32_t vr_cmd_id = msg_params[strings::cmd_id].asUInt();
@@ -343,8 +279,9 @@ void CreateInteractionChoiceSetRequest::SendVRAddCommandRequests(
VRCommandInfo vr_command(vr_cmd_id);
sent_commands_map_[vr_corr_id] = vr_command;
- LOG4CXX_DEBUG(logger_, "VR_command sent corr_id "
- << vr_corr_id << " cmd_id " << vr_corr_id);
+ LOG4CXX_DEBUG(logger_,
+ "VR_command sent corr_id " << vr_corr_id << " cmd_id "
+ << vr_corr_id);
}
expected_chs_count_ = chs_num;
LOG4CXX_DEBUG(logger_, "expected_chs_count_ = " << expected_chs_count_);
@@ -353,58 +290,60 @@ void CreateInteractionChoiceSetRequest::SendVRAddCommandRequests(
void CreateInteractionChoiceSetRequest::on_event(
const event_engine::Event& event) {
using namespace hmi_apis;
+ using namespace helpers;
LOG4CXX_AUTO_TRACE(logger_);
const smart_objects::SmartObject& message = event.smart_object();
if (event.id() == hmi_apis::FunctionID::VR_AddCommand) {
received_chs_count_++;
- LOG4CXX_DEBUG(logger_, "Got VR.AddCommand response, there are "
- << expected_chs_count_ - received_chs_count_
- << " more to wait.");
-
- uint32_t corr_id = static_cast<uint32_t>(message[strings::params]
- [strings::correlation_id].asUInt());
- SentCommandsMap::iterator it = sent_commands_map_.find(corr_id);
- if (sent_commands_map_.end() == it) {
- LOG4CXX_WARN(logger_, "HMI response for unknown VR command received");
- return;
- }
+ LOG4CXX_DEBUG(logger_,
+ "Got VR.AddCommand response, there are "
+ << expected_chs_count_ - received_chs_count_
+ << " more to wait.");
- Common_Result::eType vr_result_ = static_cast<Common_Result::eType>(
- message[strings::params][hmi_response::code].asInt());
- if (Common_Result::SUCCESS == vr_result_) {
- VRCommandInfo& vr_command = it->second;
- vr_command.succesful_response_received_ = true;
- } else {
- LOG4CXX_DEBUG(logger_, "Hmi response is not Success: " << vr_result_
- << ". Stop sending VRAddCommand requests");
- sync_primitives::AutoLock error_lock(error_from_hmi_lock_);
- if (!error_from_hmi_) {
- error_from_hmi_ = true;
- SendResponse(false, GetMobileResultCode(vr_result_));
+ uint32_t corr_id = static_cast<uint32_t>(
+ message[strings::params][strings::correlation_id].asUInt());
+ {
+ sync_primitives::AutoLock commands_lock(vr_commands_lock_);
+ SentCommandsMap::iterator it = sent_commands_map_.find(corr_id);
+ if (sent_commands_map_.end() == it) {
+ LOG4CXX_WARN(logger_, "HMI response for unknown VR command received");
+ return;
}
- }
- // update request timeout for case we send many VR add command requests
- // and HMI has no time to send responses for all of them
- LOG4CXX_DEBUG(logger_, "expected_chs_count_ = " << expected_chs_count_
- << "received_chs_count_ = " << received_chs_count_);
- if (received_chs_count_ < expected_chs_count_) {
- sync_primitives::AutoLock timeout_lock_(is_timed_out_lock_);
- if (!is_timed_out_) {
- ApplicationManagerImpl::instance()->updateRequestTimeout(
- connection_key(), correlation_id(), default_timeout());
+ Common_Result::eType vr_result = static_cast<Common_Result::eType>(
+ message[strings::params][hmi_response::code].asInt());
+
+ const bool is_vr_no_error = Compare<Common_Result::eType, EQ, ONE>(
+ vr_result, Common_Result::SUCCESS, Common_Result::WARNINGS);
+
+ if (is_vr_no_error) {
+ VRCommandInfo& vr_command = it->second;
+ vr_command.succesful_response_received_ = true;
+ } else {
+ LOG4CXX_DEBUG(logger_,
+ "Hmi response is not Success: "
+ << vr_result
+ << ". Stop sending VRAddCommand requests");
+ if (!error_from_hmi_) {
+ error_from_hmi_ = true;
+ SendResponse(false, GetMobileResultCode(vr_result));
+ }
}
- } else {
- OnAllHMIResponsesReceived();
}
+ if (received_chs_count_ < expected_chs_count_) {
+ application_manager_.updateRequestTimeout(
+ connection_key(), correlation_id(), default_timeout());
+ LOG4CXX_DEBUG(logger_, "Timeout for request was updated");
+ return;
+ }
+ OnAllHMIResponsesReceived();
}
}
void CreateInteractionChoiceSetRequest::onTimeOut() {
LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock error_lock(error_from_hmi_lock_);
if (!error_from_hmi_) {
SendResponse(false, mobile_apis::Result::GENERIC_ERROR);
}
@@ -414,15 +353,14 @@ void CreateInteractionChoiceSetRequest::onTimeOut() {
// according to SDLAQ-CRS-2976
sync_primitives::AutoLock timeout_lock_(is_timed_out_lock_);
is_timed_out_ = true;
- ApplicationManagerImpl::instance()->TerminateRequest(
- connection_key(), correlation_id());
+ application_manager_.TerminateRequest(connection_key(), correlation_id());
}
void CreateInteractionChoiceSetRequest::DeleteChoices() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "NULL pointer");
return;
@@ -440,9 +378,9 @@ void CreateInteractionChoiceSetRequest::DeleteChoices() {
msg_param[strings::cmd_id] = vr_command_info.cmd_id_;
SendHMIRequest(hmi_apis::FunctionID::VR_DeleteCommand, &msg_param);
} else {
- LOG4CXX_WARN(
- logger_, "Succesfull response has not been received for cmd_id = "
- << vr_command_info.cmd_id_);
+ LOG4CXX_WARN(logger_,
+ "Succesfull response has not been received for cmd_id = "
+ << vr_command_info.cmd_id_);
}
}
sent_commands_map_.clear();
@@ -455,7 +393,7 @@ void CreateInteractionChoiceSetRequest::OnAllHMIResponsesReceived() {
SendResponse(true, mobile_apis::Result::SUCCESS);
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "NULL pointer");
return;
@@ -464,8 +402,8 @@ void CreateInteractionChoiceSetRequest::OnAllHMIResponsesReceived() {
} else {
DeleteChoices();
}
- ApplicationManagerImpl::instance()->TerminateRequest(connection_key(),
- correlation_id());
+
+ application_manager_.TerminateRequest(connection_key(), correlation_id());
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/create_interaction_choice_set_response.cc b/src/components/application_manager/src/commands/mobile/create_interaction_choice_set_response.cc
index bc81206088..0cc137d6a0 100644
--- a/src/components/application_manager/src/commands/mobile/create_interaction_choice_set_response.cc
+++ b/src/components/application_manager/src/commands/mobile/create_interaction_choice_set_response.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/create_interaction_choice_set_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
@@ -41,12 +41,10 @@ namespace application_manager {
namespace commands {
CreateInteractionChoiceSetResponse::CreateInteractionChoiceSetResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-CreateInteractionChoiceSetResponse::~CreateInteractionChoiceSetResponse() {
-}
+CreateInteractionChoiceSetResponse::~CreateInteractionChoiceSetResponse() {}
void CreateInteractionChoiceSetResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/mobile/delete_command_request.cc b/src/components/application_manager/src/commands/mobile/delete_command_request.cc
index 99dd53d177..9a7b92f7b8 100644
--- a/src/components/application_manager/src/commands/mobile/delete_command_request.cc
+++ b/src/components/application_manager/src/commands/mobile/delete_command_request.cc
@@ -32,51 +32,54 @@
*/
#include "application_manager/commands/mobile/delete_command_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
+#include "application_manager/message_helper.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
+#include "utils/helpers.h"
namespace application_manager {
namespace commands {
-DeleteCommandRequest::DeleteCommandRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message),
- is_ui_send_(false),
- is_vr_send_(false),
- is_ui_received_(false),
- is_vr_received_(false),
- ui_result_(hmi_apis::Common_Result::INVALID_ENUM),
- vr_result_(hmi_apis::Common_Result::INVALID_ENUM) {
-}
+DeleteCommandRequest::DeleteCommandRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager)
+ , is_ui_send_(false)
+ , is_vr_send_(false)
+ , is_ui_received_(false)
+ , is_vr_received_(false)
+ , ui_result_(hmi_apis::Common_Result::INVALID_ENUM)
+ , vr_result_(hmi_apis::Common_Result::INVALID_ENUM) {}
-DeleteCommandRequest::~DeleteCommandRequest() {
-}
+DeleteCommandRequest::~DeleteCommandRequest() {}
void DeleteCommandRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr application = ApplicationManagerImpl::instance()->application(
- (*message_)[strings::params][strings::connection_key].asUInt());
+ ApplicationSharedPtr application =
+ application_manager_.application(connection_key());
if (!application) {
- SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
LOG4CXX_ERROR(logger_, "Application is not registered");
+ SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
- smart_objects::SmartObject* command = application->FindCommand(
- (*message_)[strings::msg_params][strings::cmd_id].asInt());
+ const int32_t cmd_id =
+ (*message_)[strings::msg_params][strings::cmd_id].asInt();
+
+ smart_objects::SmartObject* command = application->FindCommand(cmd_id);
if (!command) {
+ LOG4CXX_ERROR(logger_, "Command with id " << cmd_id << " is not found.");
SendResponse(false, mobile_apis::Result::INVALID_ID);
- LOG4CXX_ERROR(logger_, "Invalid ID");
return;
}
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::cmd_id] =
(*message_)[strings::msg_params][strings::cmd_id];
@@ -110,74 +113,112 @@ void DeleteCommandRequest::Run() {
void DeleteCommandRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
+
const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
case hmi_apis::FunctionID::UI_DeleteCommand: {
- LOG4CXX_INFO(logger_, "Received UI_DeleteCommand event");
is_ui_received_ = true;
- ui_result_ = static_cast<hmi_apis::Common_Result::eType>(
- message[strings::params][hmi_response::code].asInt());
-
+ const int result = message[strings::params][hmi_response::code].asInt();
+ ui_result_ = static_cast<hmi_apis::Common_Result::eType>(result);
+ LOG4CXX_DEBUG(logger_,
+ "Received UI_DeleteCommand event with result "
+ << MessageHelper::HMIResultToString(ui_result_));
break;
}
case hmi_apis::FunctionID::VR_DeleteCommand: {
- LOG4CXX_INFO(logger_, "Received VR_DeleteCommand event");
is_vr_received_ = true;
- vr_result_ = static_cast<hmi_apis::Common_Result::eType>(
- message[strings::params][hmi_response::code].asInt());
-
+ const int result = message[strings::params][hmi_response::code].asInt();
+ vr_result_ = static_cast<hmi_apis::Common_Result::eType>(result);
+ LOG4CXX_DEBUG(logger_,
+ "Received VR_DeleteCommand event with result "
+ << MessageHelper::HMIResultToString(vr_result_));
break;
}
default: {
- LOG4CXX_ERROR(logger_,"Received unknown event" << event.id());
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
return;
}
}
- if (!IsPendingResponseExist()) {
- ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ if (IsPendingResponseExist()) {
+ LOG4CXX_DEBUG(logger_, "Still awaiting for other responses.");
+ return;
+ }
- if (!application) {
- LOG4CXX_ERROR(logger_, "NULL pointer");
- return;
- }
+ ApplicationSharedPtr application =
+ application_manager_.application(connection_key());
- smart_objects::SmartObject* command = application->FindCommand(
- (*message_)[strings::msg_params][strings::cmd_id].asInt());
-
- if (command) {
- mobile_apis::Result::eType result_code = mobile_apis::Result::INVALID_ENUM;
-
- bool result = ((hmi_apis::Common_Result::SUCCESS == ui_result_) &&
- (hmi_apis::Common_Result::SUCCESS == vr_result_)) ||
- ((hmi_apis::Common_Result::SUCCESS == ui_result_) &&
- (hmi_apis::Common_Result::INVALID_ENUM == vr_result_)) ||
- ((hmi_apis::Common_Result::INVALID_ENUM == ui_result_) &&
- (hmi_apis::Common_Result::SUCCESS == vr_result_));
-
- if (result) {
- application->RemoveCommand(
- (*message_)[strings::msg_params][strings::cmd_id].asInt());
- }
-
- if (!result && (hmi_apis::Common_Result::REJECTED == ui_result_)) {
- result_code = static_cast<mobile_apis::Result::eType>(vr_result_);
- } else {
- result_code = static_cast<mobile_apis::Result::eType>(
- std::max(ui_result_, vr_result_));
- }
-
- SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
- if (result) {
- application->UpdateHash();
- }
- }
+ if (!application) {
+ LOG4CXX_ERROR(logger_, "Application is not registered");
+ return;
+ }
+ smart_objects::SmartObject& msg_params = (*message_)[strings::msg_params];
+
+ const int32_t cmd_id = msg_params[strings::cmd_id].asInt();
+
+ smart_objects::SmartObject* command = application->FindCommand(cmd_id);
+
+ if (!command) {
+ LOG4CXX_ERROR(logger_,
+ "Command id " << cmd_id << " not found for "
+ "application with connection key "
+ << connection_key());
+ return;
+ }
+
+ const bool is_vr_success_invalid =
+ Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ vr_result_,
+ hmi_apis::Common_Result::SUCCESS,
+ hmi_apis::Common_Result::INVALID_ENUM);
+
+ const bool is_ui_success_invalid =
+ Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ ui_result_,
+ hmi_apis::Common_Result::SUCCESS,
+ hmi_apis::Common_Result::INVALID_ENUM);
+
+ const bool is_vr_ui_invalid =
+ Compare<hmi_apis::Common_Result::eType, EQ, ALL>(
+ hmi_apis::Common_Result::INVALID_ENUM, vr_result_, ui_result_);
+
+ const bool is_vr_or_ui_warning =
+ Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ hmi_apis::Common_Result::WARNINGS, ui_result_, vr_result_);
+
+ const bool result =
+ // In case of UI/VR is SUCCESS and other is SUCCESS/INVALID_ENUM
+ (is_vr_success_invalid && is_ui_success_invalid && !is_vr_ui_invalid) ||
+ // or one of them is WARNINGS
+ is_vr_or_ui_warning;
+
+ LOG4CXX_DEBUG(logger_, "Result code is " << (result ? "true" : "false"));
+
+ if (result) {
+ application->RemoveCommand(msg_params[strings::cmd_id].asInt());
+ }
+
+ mobile_apis::Result::eType result_code = mobile_apis::Result::INVALID_ENUM;
+ if (!result && hmi_apis::Common_Result::REJECTED == ui_result_) {
+ result_code = MessageHelper::HMIToMobileResult(vr_result_);
+ } else if (is_vr_or_ui_warning) {
+ LOG4CXX_DEBUG(logger_, "VR or UI result is warning");
+ result_code = mobile_apis::Result::WARNINGS;
+ } else {
+ result_code =
+ MessageHelper::HMIToMobileResult(std::max(ui_result_, vr_result_));
+ }
+
+ SendResponse(result, result_code, NULL, &msg_params);
+ if (result) {
+ application->UpdateHash();
}
}
bool DeleteCommandRequest::IsPendingResponseExist() {
+ LOG4CXX_AUTO_TRACE(logger_);
return is_ui_send_ != is_ui_received_ || is_vr_send_ != is_vr_received_;
}
diff --git a/src/components/application_manager/src/commands/mobile/delete_command_response.cc b/src/components/application_manager/src/commands/mobile/delete_command_response.cc
index 75178bcb4d..7abc1c11d4 100644
--- a/src/components/application_manager/src/commands/mobile/delete_command_response.cc
+++ b/src/components/application_manager/src/commands/mobile/delete_command_response.cc
@@ -32,23 +32,21 @@
*/
#include "application_manager/commands/mobile/delete_command_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-DeleteCommandResponse::DeleteCommandResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+DeleteCommandResponse::DeleteCommandResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-DeleteCommandResponse::~DeleteCommandResponse() {
-}
+DeleteCommandResponse::~DeleteCommandResponse() {}
void DeleteCommandResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/delete_file_request.cc b/src/components/application_manager/src/commands/mobile/delete_file_request.cc
index 4c753871ce..00d23bb094 100644
--- a/src/components/application_manager/src/commands/mobile/delete_file_request.cc
+++ b/src/components/application_manager/src/commands/mobile/delete_file_request.cc
@@ -32,27 +32,26 @@
*/
#include "application_manager/commands/mobile/delete_file_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
-#include "config_profile/profile.h"
+
#include "utils/file_system.h"
namespace application_manager {
namespace commands {
-DeleteFileRequest::DeleteFileRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+DeleteFileRequest::DeleteFileRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-DeleteFileRequest::~DeleteFileRequest() {
-}
+DeleteFileRequest::~DeleteFileRequest() {}
void DeleteFileRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (!application) {
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
@@ -61,20 +60,21 @@ void DeleteFileRequest::Run() {
}
if ((mobile_api::HMILevel::HMI_NONE == application->hmi_level()) &&
- (profile::Profile::instance()->delete_file_in_none() <=
+ (application_manager_.get_settings().delete_file_in_none() <=
application->delete_file_in_none_count())) {
- // If application is in the HMI_NONE level the quantity of allowed
- // DeleteFile request is limited by the configuration profile
- LOG4CXX_ERROR(logger_, "Too many requests from the app with HMILevel HMI_NONE ");
- SendResponse(false, mobile_apis::Result::REJECTED);
- return;
+ // If application is in the HMI_NONE level the quantity of allowed
+ // DeleteFile request is limited by the configuration profile
+ LOG4CXX_ERROR(logger_,
+ "Too many requests from the app with HMILevel HMI_NONE ");
+ SendResponse(false, mobile_apis::Result::REJECTED);
+ return;
}
const std::string& sync_file_name =
(*message_)[strings::msg_params][strings::sync_file_name].asString();
std::string full_file_path =
- profile::Profile::instance()->app_storage_folder() + "/";
+ application_manager_.get_settings().app_storage_folder() + "/";
full_file_path += application->folder_name();
full_file_path += "/";
full_file_path += sync_file_name;
@@ -97,17 +97,16 @@ void DeleteFileRequest::Run() {
}
}
-void DeleteFileRequest::SendFileRemovedNotification(
- const AppFile* file) const {
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+void DeleteFileRequest::SendFileRemovedNotification(const AppFile* file) const {
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
- msg_params[strings::app_id] = connection_key();
- msg_params[strings::file_name] = file->file_name;
- msg_params[strings::file_type] = file->file_type;
+ msg_params[strings::app_id] = connection_key();
+ msg_params[strings::file_name] = file->file_name;
+ msg_params[strings::file_type] = file->file_type;
- CreateHMINotification(
- hmi_apis::FunctionID::BasicCommunication_OnFileRemoved, msg_params);
+ CreateHMINotification(hmi_apis::FunctionID::BasicCommunication_OnFileRemoved,
+ msg_params);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/delete_file_response.cc b/src/components/application_manager/src/commands/mobile/delete_file_response.cc
index 1bbb18313f..8ed6f7ba2e 100644
--- a/src/components/application_manager/src/commands/mobile/delete_file_response.cc
+++ b/src/components/application_manager/src/commands/mobile/delete_file_response.cc
@@ -32,26 +32,24 @@
*/
#include "application_manager/commands/mobile/delete_file_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
namespace application_manager {
namespace commands {
-DeleteFileResponse::DeleteFileResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+DeleteFileResponse::DeleteFileResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-DeleteFileResponse::~DeleteFileResponse() {
-}
+DeleteFileResponse::~DeleteFileResponse() {}
void DeleteFileResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- uint32_t app_id = (*message_)[strings::params][strings::connection_key]
- .asUInt();
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(app_id);
+ uint32_t app_id =
+ (*message_)[strings::params][strings::connection_key].asUInt();
+ ApplicationSharedPtr app = application_manager_.application(app_id);
if (!app) {
LOG4CXX_ERROR(logger_, "Application not registered");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
@@ -59,8 +57,7 @@ void DeleteFileResponse::Run() {
}
(*message_)[strings::msg_params][strings::space_available] =
- static_cast<int32_t>(
- ApplicationManagerImpl::instance()->GetAvailableSpaceForApp(app->name()));
+ static_cast<uint32_t>(app->GetAvailableDiskSpace());
SendResponse((*message_)[strings::msg_params][strings::success].asBool());
}
diff --git a/src/components/application_manager/src/commands/mobile/delete_interaction_choice_set_request.cc b/src/components/application_manager/src/commands/mobile/delete_interaction_choice_set_request.cc
index 18c6b3b084..6ef8e5d9da 100644
--- a/src/components/application_manager/src/commands/mobile/delete_interaction_choice_set_request.cc
+++ b/src/components/application_manager/src/commands/mobile/delete_interaction_choice_set_request.cc
@@ -32,59 +32,60 @@
*/
#include "application_manager/commands/mobile/delete_interaction_choice_set_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
#include "application_manager/message_helper.h"
+
namespace application_manager {
namespace commands {
DeleteInteractionChoiceSetRequest::DeleteInteractionChoiceSetRequest(
- const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-DeleteInteractionChoiceSetRequest::~DeleteInteractionChoiceSetRequest() {
-}
+DeleteInteractionChoiceSetRequest::~DeleteInteractionChoiceSetRequest() {}
void DeleteInteractionChoiceSetRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
- (*message_)[strings::params][strings::connection_key].asUInt());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "No application associated with session key");
+ LOG4CXX_ERROR(logger_,
+ "No application associated with connection key "
+ << connection_key());
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
- const int32_t choise_set_id =
- (*message_)[strings::msg_params]
- [strings::interaction_choice_set_id].asInt();
+ const int32_t choice_set_id =
+ (*message_)[strings::msg_params][strings::interaction_choice_set_id]
+ .asInt();
- if (!app->FindChoiceSet(choise_set_id)) {
- LOG4CXX_ERROR_EXT(logger_, "INVALID_ID");
+ if (!app->FindChoiceSet(choice_set_id)) {
+ LOG4CXX_ERROR(logger_,
+ "Choice set with id " << choice_set_id << " is not found.");
SendResponse(false, mobile_apis::Result::INVALID_ID);
return;
}
if (ChoiceSetInUse(app)) {
- LOG4CXX_ERROR_EXT(logger_, "Choice set currently in use");
+ LOG4CXX_ERROR(logger_, "Choice set currently in use.");
SendResponse(false, mobile_apis::Result::IN_USE);
return;
}
SendVrDeleteCommand(app);
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
- msg_params[strings::interaction_choice_set_id] = choise_set_id;
+ msg_params[strings::interaction_choice_set_id] = choice_set_id;
msg_params[strings::app_id] = app->app_id();
- app->RemoveChoiceSet(choise_set_id);
+ app->RemoveChoiceSet(choice_set_id);
// Checking of HMI responses will be implemented with APPLINK-14600
const bool result = true;
@@ -94,49 +95,60 @@ void DeleteInteractionChoiceSetRequest::Run() {
}
}
-bool DeleteInteractionChoiceSetRequest::ChoiceSetInUse(ApplicationConstSharedPtr app) {
- if (app->is_perform_interaction_active()) {
- // retrieve stored choice sets for perform interaction
+bool DeleteInteractionChoiceSetRequest::ChoiceSetInUse(
+ ApplicationConstSharedPtr app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!app->is_perform_interaction_active()) {
+ return false;
+ }
const DataAccessor<PerformChoiceSetMap> accessor =
app->performinteraction_choice_set_map();
const PerformChoiceSetMap& choice_set_map = accessor.GetData();
- PerformChoiceSetMap::const_iterator it = choice_set_map.begin();
- for (; choice_set_map.end() != it; ++it) {
- const PerformChoice& choice = it->second;
- PerformChoice::const_iterator choice_it = choice.begin();
- for (; choice.end() != choice_it; ++choice_it) {
- if (choice_it->first == (*message_)[strings::msg_params]
- [strings::interaction_choice_set_id].asUInt()) {
- LOG4CXX_ERROR_EXT(logger_,
- "DeleteInteractionChoiceSetRequest::ChoiceSetInUse");
- return true;
- }
+ const uint32_t choice_set_id =
+ (*message_)[strings::msg_params][strings::interaction_choice_set_id]
+ .asUInt();
+
+ PerformChoiceSetMap::const_iterator it = choice_set_map.begin();
+ for (; choice_set_map.end() != it; ++it) {
+ const PerformChoice& choice = it->second;
+ PerformChoice::const_iterator choice_it = choice.begin();
+ for (; choice.end() != choice_it; ++choice_it) {
+ if (choice_it->first == choice_set_id) {
+ LOG4CXX_ERROR(logger_,
+ "Choice set with id " << choice_set_id << " is in use.");
+ return true;
}
}
}
- return false;
+ return true;
}
void DeleteInteractionChoiceSetRequest::SendVrDeleteCommand(
application_manager::ApplicationSharedPtr app) {
- LOG4CXX_INFO(logger_, "PerformInteractionRequest::SendVrDeleteCommand");
-
- smart_objects::SmartObject* choice_set =
- app->FindChoiceSet((*message_)[strings::msg_params]
- [strings::interaction_choice_set_id].asInt());
-
- if (choice_set) {
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- msg_params[strings::app_id] = app->app_id();
- msg_params[strings::type] = hmi_apis::Common_VRCommandType::Choice;
- msg_params[strings::grammar_id] = (*choice_set)[strings::grammar_id];
- choice_set = &((*choice_set)[strings::choice_set]);
- for (uint32_t i = 0; i < (*choice_set).length() ; ++i) {
- msg_params[strings::cmd_id] = (*choice_set)[i][strings::choice_id];
- SendHMIRequest(hmi_apis::FunctionID::VR_DeleteCommand, &msg_params);
- }
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ const uint32_t choice_set_id =
+ (*message_)[strings::msg_params][strings::interaction_choice_set_id]
+ .asUInt();
+
+ smart_objects::SmartObject* choice_set = app->FindChoiceSet(choice_set_id);
+
+ if (!choice_set) {
+ LOG4CXX_ERROR(logger_,
+ "Choice set with id " << choice_set_id << " is not found.");
+ return;
+ }
+
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ msg_params[strings::app_id] = app->app_id();
+ msg_params[strings::type] = hmi_apis::Common_VRCommandType::Choice;
+ msg_params[strings::grammar_id] = (*choice_set)[strings::grammar_id];
+ choice_set = &((*choice_set)[strings::choice_set]);
+ for (uint32_t i = 0; i < (*choice_set).length(); ++i) {
+ msg_params[strings::cmd_id] = (*choice_set)[i][strings::choice_id];
+ SendHMIRequest(hmi_apis::FunctionID::VR_DeleteCommand, &msg_params);
}
}
diff --git a/src/components/application_manager/src/commands/mobile/delete_interaction_choice_set_response.cc b/src/components/application_manager/src/commands/mobile/delete_interaction_choice_set_response.cc
index f9ee513b94..97e07529af 100644
--- a/src/components/application_manager/src/commands/mobile/delete_interaction_choice_set_response.cc
+++ b/src/components/application_manager/src/commands/mobile/delete_interaction_choice_set_response.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/delete_interaction_choice_set_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
@@ -42,12 +42,10 @@ namespace application_manager {
namespace commands {
DeleteInteractionChoiceSetResponse::DeleteInteractionChoiceSetResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-DeleteInteractionChoiceSetResponse::~DeleteInteractionChoiceSetResponse() {
-}
+DeleteInteractionChoiceSetResponse::~DeleteInteractionChoiceSetResponse() {}
void DeleteInteractionChoiceSetResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/mobile/delete_sub_menu_request.cc b/src/components/application_manager/src/commands/mobile/delete_sub_menu_request.cc
index 6b6bd3fbda..bdb5521921 100644
--- a/src/components/application_manager/src/commands/mobile/delete_sub_menu_request.cc
+++ b/src/components/application_manager/src/commands/mobile/delete_sub_menu_request.cc
@@ -32,26 +32,25 @@
*/
#include "application_manager/commands/mobile/delete_sub_menu_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/HMI_API.h"
+#include "utils/helpers.h"
namespace application_manager {
namespace commands {
-DeleteSubMenuRequest::DeleteSubMenuRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+DeleteSubMenuRequest::DeleteSubMenuRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-DeleteSubMenuRequest::~DeleteSubMenuRequest() {
-}
+DeleteSubMenuRequest::~DeleteSubMenuRequest() {}
void DeleteSubMenuRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
- (*message_)[strings::params][strings::connection_key].asUInt());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
@@ -59,15 +58,17 @@ void DeleteSubMenuRequest::Run() {
return;
}
- if (!app->FindSubMenu(
- (*message_)[strings::msg_params][strings::menu_id].asInt())) {
+ const int32_t menu_id =
+ (*message_)[strings::msg_params][strings::menu_id].asInt();
+
+ if (!app->FindSubMenu(menu_id)) {
+ LOG4CXX_ERROR(logger_, "Menu with id " << menu_id << " is not found.");
SendResponse(false, mobile_apis::Result::INVALID_ID);
- LOG4CXX_ERROR(logger_, "Invalid ID");
return;
}
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::menu_id] =
(*message_)[strings::msg_params][strings::menu_id];
@@ -76,7 +77,8 @@ void DeleteSubMenuRequest::Run() {
SendHMIRequest(hmi_apis::FunctionID::UI_DeleteSubMenu, &msg_params, true);
}
-void DeleteSubMenuRequest::DeleteSubMenuVRCommands(ApplicationConstSharedPtr app) {
+void DeleteSubMenuRequest::DeleteSubMenuVRCommands(
+ ApplicationConstSharedPtr app) {
LOG4CXX_AUTO_TRACE(logger_);
const DataAccessor<CommandsMap> accessor = app->commands_map();
@@ -84,16 +86,14 @@ void DeleteSubMenuRequest::DeleteSubMenuVRCommands(ApplicationConstSharedPtr app
CommandsMap::const_iterator it = commands.begin();
for (; commands.end() != it; ++it) {
-
if (!(*it->second).keyExists(strings::vr_commands)) {
continue;
}
- if ((*message_)[strings::msg_params][strings::menu_id].asInt()
- == (*it->second)[strings::menu_params]
- [hmi_request::parent_id].asInt()) {
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ if ((*message_)[strings::msg_params][strings::menu_id].asInt() ==
+ (*it->second)[strings::menu_params][hmi_request::parent_id].asInt()) {
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::cmd_id] = (*it->second)[strings::cmd_id].asInt();
msg_params[strings::app_id] = app->app_id();
msg_params[strings::grammar_id] = app->get_grammar_id();
@@ -104,7 +104,8 @@ void DeleteSubMenuRequest::DeleteSubMenuVRCommands(ApplicationConstSharedPtr app
}
}
-void DeleteSubMenuRequest::DeleteSubMenuUICommands(ApplicationSharedPtr const app) {
+void DeleteSubMenuRequest::DeleteSubMenuUICommands(
+ ApplicationSharedPtr const app) {
LOG4CXX_AUTO_TRACE(logger_);
const DataAccessor<CommandsMap> accessor(app->commands_map());
@@ -118,11 +119,10 @@ void DeleteSubMenuRequest::DeleteSubMenuUICommands(ApplicationSharedPtr const ap
continue;
}
- if ((*message_)[strings::msg_params][strings::menu_id].asInt()
- == (*it->second)[strings::menu_params]
- [hmi_request::parent_id].asInt()) {
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ if ((*message_)[strings::msg_params][strings::menu_id].asInt() ==
+ (*it->second)[strings::menu_params][hmi_request::parent_id].asInt()) {
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::app_id] = app->app_id();
msg_params[strings::cmd_id] = (*it->second)[strings::cmd_id].asInt();
app->RemoveCommand((*it->second)[strings::cmd_id].asInt());
@@ -138,6 +138,7 @@ void DeleteSubMenuRequest::DeleteSubMenuUICommands(ApplicationSharedPtr const ap
void DeleteSubMenuRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
@@ -146,10 +147,13 @@ void DeleteSubMenuRequest::on_event(const event_engine::Event& event) {
static_cast<mobile_apis::Result::eType>(
message[strings::params][hmi_response::code].asInt());
- bool result = mobile_apis::Result::SUCCESS == result_code;
+ const bool result = Compare<mobile_api::Result::eType, EQ, ONE>(
+ result_code,
+ mobile_api::Result::SUCCESS,
+ mobile_api::Result::WARNINGS);
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "NULL pointer");
@@ -162,9 +166,12 @@ void DeleteSubMenuRequest::on_event(const event_engine::Event& event) {
DeleteSubMenuUICommands(application);
application->RemoveSubMenu(
(*message_)[strings::msg_params][strings::menu_id].asInt());
- }
+ }
SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
+ if (result) {
+ application->UpdateHash();
+ }
break;
}
default: {
@@ -174,7 +181,6 @@ void DeleteSubMenuRequest::on_event(const event_engine::Event& event) {
}
}
-
} // namespace commands
} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/delete_sub_menu_response.cc b/src/components/application_manager/src/commands/mobile/delete_sub_menu_response.cc
index 05795e5908..ad9d2ad858 100644
--- a/src/components/application_manager/src/commands/mobile/delete_sub_menu_response.cc
+++ b/src/components/application_manager/src/commands/mobile/delete_sub_menu_response.cc
@@ -32,24 +32,21 @@
*/
#include "application_manager/commands/mobile/delete_sub_menu_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-DeleteSubMenuResponse::DeleteSubMenuResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+DeleteSubMenuResponse::DeleteSubMenuResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-DeleteSubMenuResponse::~DeleteSubMenuResponse() {
-}
+DeleteSubMenuResponse::~DeleteSubMenuResponse() {}
void DeleteSubMenuResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
-
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/diagnostic_message_request.cc b/src/components/application_manager/src/commands/mobile/diagnostic_message_request.cc
index f5e8808d38..5252ea0e33 100644
--- a/src/components/application_manager/src/commands/mobile/diagnostic_message_request.cc
+++ b/src/components/application_manager/src/commands/mobile/diagnostic_message_request.cc
@@ -33,27 +33,25 @@
#include <algorithm>
#include "application_manager/commands/mobile/diagnostic_message_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
-#include "config_profile/profile.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
namespace commands {
-DiagnosticMessageRequest::DiagnosticMessageRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+DiagnosticMessageRequest::DiagnosticMessageRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-DiagnosticMessageRequest::~DiagnosticMessageRequest() {
-}
+DiagnosticMessageRequest::~DiagnosticMessageRequest() {}
void DiagnosticMessageRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
LOG4CXX_ERROR(logger_, "Application is not registered.");
@@ -62,30 +60,31 @@ void DiagnosticMessageRequest::Run() {
}
const std::vector<uint32_t>& supported_diag_modes =
- profile::Profile::instance()->supported_diag_modes();
-
- uint32_t message_data_length =
- (*message_)[strings::msg_params][strings::message_data].length();
- for (uint32_t i = 0; i < message_data_length; ++i) {
- uint32_t message_data =
- (*message_)[strings::msg_params][strings::message_data][i].asUInt();
- if (supported_diag_modes.end() == std::find(supported_diag_modes.begin(),
- supported_diag_modes.end(),
- message_data)) {
- LOG4CXX_ERROR(logger_, "Received message data " << message_data <<
- " not supported");
- SendResponse(false, mobile_apis::Result::REJECTED,
- "Received message data not supported");
- return;
- }
+ application_manager_.get_settings().supported_diag_modes();
+
+ smart_objects::SmartObject& msg_data =
+ (*message_)[strings::msg_params][strings::message_data];
+
+ const uint8_t mode_position = 0;
+ const uint32_t msg_diagnostic_mode = msg_data[mode_position].asUInt();
+ if (supported_diag_modes.end() == std::find(supported_diag_modes.begin(),
+ supported_diag_modes.end(),
+ msg_diagnostic_mode)) {
+ LOG4CXX_ERROR(logger_,
+ "Received diagnostic mode " << msg_diagnostic_mode
+ << " is not supported.");
+ SendResponse(false,
+ mobile_apis::Result::REJECTED,
+ "Received diagnostic mode is not supported.");
+ return;
}
// Add app_id for HMI request
(*message_)[strings::msg_params][strings::app_id] = app->app_id();
SendHMIRequest(hmi_apis::FunctionID::VehicleInfo_DiagnosticMessage,
- &(*message_)[strings::msg_params], true);
-
+ &(*message_)[strings::msg_params],
+ true);
}
void DiagnosticMessageRequest::on_event(const event_engine::Event& event) {
diff --git a/src/components/application_manager/src/commands/mobile/diagnostic_message_response.cc b/src/components/application_manager/src/commands/mobile/diagnostic_message_response.cc
index 9c399a00c8..8c59a97a8b 100644
--- a/src/components/application_manager/src/commands/mobile/diagnostic_message_response.cc
+++ b/src/components/application_manager/src/commands/mobile/diagnostic_message_response.cc
@@ -32,23 +32,21 @@
*/
#include "application_manager/commands/mobile/diagnostic_message_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-DiagnosticMessageResponse::DiagnosticMessageResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+DiagnosticMessageResponse::DiagnosticMessageResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-DiagnosticMessageResponse::~DiagnosticMessageResponse() {
-}
+DiagnosticMessageResponse::~DiagnosticMessageResponse() {}
void DiagnosticMessageResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/dial_number_request.cc b/src/components/application_manager/src/commands/mobile/dial_number_request.cc
index 6e8f5e15ad..64685afe2e 100644
--- a/src/components/application_manager/src/commands/mobile/dial_number_request.cc
+++ b/src/components/application_manager/src/commands/mobile/dial_number_request.cc
@@ -33,15 +33,16 @@
#include <algorithm>
#include <string>
#include "application_manager/commands/mobile/dial_number_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
namespace application_manager {
namespace commands {
-DialNumberRequest::DialNumberRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {}
+DialNumberRequest::DialNumberRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
DialNumberRequest::~DialNumberRequest() {}
@@ -57,13 +58,14 @@ void DialNumberRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "NULL pointer");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
+
std::string number =
(*message_)[strings::msg_params][strings::number].asString();
if (!CheckSyntax(number)) {
@@ -71,10 +73,11 @@ void DialNumberRequest::Run() {
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
+
StripNumberParam(number);
if (number.empty()) {
- LOG4CXX_WARN(logger_,
- "After strip number param is empty. Invalid incoming data");
+ LOG4CXX_ERROR(logger_,
+ "After strip number param is empty. Invalid incoming data");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
@@ -89,8 +92,9 @@ void DialNumberRequest::Run() {
}
void DialNumberRequest::on_event(const event_engine::Event& event) {
+ LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "NULL pointer");
@@ -130,7 +134,7 @@ void DialNumberRequest::on_event(const event_engine::Event& event) {
void DialNumberRequest::StripNumberParam(std::string& number) {
std::size_t found = 0;
while (std::string::npos !=
- (found = number.find_first_not_of("+*#,;0123456789"))) {
+ (found = number.find_first_not_of("0123456789*#,;+"))) {
number.erase(number.begin() + found);
}
(*message_)[strings::msg_params][strings::number] = number;
diff --git a/src/components/application_manager/src/commands/mobile/dial_number_response.cc b/src/components/application_manager/src/commands/mobile/dial_number_response.cc
index 1daab5a4e1..750dcf25c4 100644
--- a/src/components/application_manager/src/commands/mobile/dial_number_response.cc
+++ b/src/components/application_manager/src/commands/mobile/dial_number_response.cc
@@ -31,21 +31,21 @@
*/
#include "application_manager/commands/mobile/dial_number_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-DialNumberResponse::DialNumberResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+DialNumberResponse::DialNumberResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-DialNumberResponse::~DialNumberResponse() {
-}
+DialNumberResponse::~DialNumberResponse() {}
void DialNumberResponse::Run() {
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/end_audio_pass_thru_request.cc b/src/components/application_manager/src/commands/mobile/end_audio_pass_thru_request.cc
index 78a867a6d8..5a922f595f 100644
--- a/src/components/application_manager/src/commands/mobile/end_audio_pass_thru_request.cc
+++ b/src/components/application_manager/src/commands/mobile/end_audio_pass_thru_request.cc
@@ -32,19 +32,16 @@
*/
#include "application_manager/commands/mobile/end_audio_pass_thru_request.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
EndAudioPassThruRequest::EndAudioPassThruRequest(
- const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-EndAudioPassThruRequest::~EndAudioPassThruRequest() {
-}
+EndAudioPassThruRequest::~EndAudioPassThruRequest() {}
void EndAudioPassThruRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -65,11 +62,9 @@ void EndAudioPassThruRequest::on_event(const event_engine::Event& event) {
bool result = mobile_apis::Result::SUCCESS == mobile_code;
if (result) {
- bool ended_successfully =
- ApplicationManagerImpl::instance()->end_audio_pass_thru();
+ bool ended_successfully = application_manager_.EndAudioPassThrough();
if (ended_successfully) {
- ApplicationManagerImpl::instance()->StopAudioPassThru(
- connection_key());
+ application_manager_.StopAudioPassThru(connection_key());
}
}
diff --git a/src/components/application_manager/src/commands/mobile/end_audio_pass_thru_response.cc b/src/components/application_manager/src/commands/mobile/end_audio_pass_thru_response.cc
index 0ac1a00bd4..bb477f5083 100644
--- a/src/components/application_manager/src/commands/mobile/end_audio_pass_thru_response.cc
+++ b/src/components/application_manager/src/commands/mobile/end_audio_pass_thru_response.cc
@@ -32,24 +32,21 @@
*/
#include "application_manager/commands/mobile/end_audio_pass_thru_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
EndAudioPassThruResponse::EndAudioPassThruResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-EndAudioPassThruResponse::~EndAudioPassThruResponse() {
-}
+EndAudioPassThruResponse::~EndAudioPassThruResponse() {}
void EndAudioPassThruResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/generic_response.cc b/src/components/application_manager/src/commands/mobile/generic_response.cc
index 69c841b2f1..20f6931bb9 100644
--- a/src/components/application_manager/src/commands/mobile/generic_response.cc
+++ b/src/components/application_manager/src/commands/mobile/generic_response.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/generic_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
namespace application_manager {
@@ -55,7 +55,7 @@ void GenericResponse::Run() {
(*message_)[strings::params][strings::message_type] = MessageType::kResponse;
(*message_)[strings::msg_params][strings::success] = false;
(*message_)[strings::msg_params][strings::result_code] =
- mobile_apis::Result::INVALID_DATA;
+ mobile_apis::Result::INVALID_DATA;
SendResponse(false);
}
diff --git a/src/components/application_manager/src/commands/mobile/get_dtcs_request.cc b/src/components/application_manager/src/commands/mobile/get_dtcs_request.cc
index f6791759a4..80bc89f853 100644
--- a/src/components/application_manager/src/commands/mobile/get_dtcs_request.cc
+++ b/src/components/application_manager/src/commands/mobile/get_dtcs_request.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/get_dtcs_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/HMI_API.h"
@@ -40,17 +40,16 @@ namespace application_manager {
namespace commands {
-GetDTCsRequest::GetDTCsRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+GetDTCsRequest::GetDTCsRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-GetDTCsRequest::~GetDTCsRequest() {
-}
+GetDTCsRequest::~GetDTCsRequest() {}
void GetDTCsRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
+ ApplicationSharedPtr app = application_manager_.application(
(*message_)[strings::params][strings::connection_key].asUInt());
if (!app) {
@@ -59,8 +58,8 @@ void GetDTCsRequest::Run() {
return;
}
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::ecu_name] =
(*message_)[strings::msg_params][strings::ecu_name];
diff --git a/src/components/application_manager/src/commands/mobile/get_dtcs_response.cc b/src/components/application_manager/src/commands/mobile/get_dtcs_response.cc
index 523711c975..ecaf5c3d8f 100644
--- a/src/components/application_manager/src/commands/mobile/get_dtcs_response.cc
+++ b/src/components/application_manager/src/commands/mobile/get_dtcs_response.cc
@@ -32,23 +32,21 @@
*/
#include "application_manager/commands/mobile/get_dtcs_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-GetDTCsResponse::GetDTCsResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+GetDTCsResponse::GetDTCsResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-GetDTCsResponse::~GetDTCsResponse() {
-}
+GetDTCsResponse::~GetDTCsResponse() {}
void GetDTCsResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/get_vehicle_data_request.cc b/src/components/application_manager/src/commands/mobile/get_vehicle_data_request.cc
index ed75e62c0c..8b7010c6a1 100644
--- a/src/components/application_manager/src/commands/mobile/get_vehicle_data_request.cc
+++ b/src/components/application_manager/src/commands/mobile/get_vehicle_data_request.cc
@@ -33,7 +33,7 @@
#include <string>
#include "application_manager/commands/mobile/get_vehicle_data_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
#include "interfaces/MOBILE_API.h"
@@ -46,18 +46,18 @@ namespace commands {
namespace str = strings;
#ifdef HMI_DBUS_API
-GetVehicleDataRequest::GetVehicleDataRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+GetVehicleDataRequest::GetVehicleDataRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-GetVehicleDataRequest::~GetVehicleDataRequest() {
-}
+GetVehicleDataRequest::~GetVehicleDataRequest() {}
void GetVehicleDataRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- int32_t app_id = (*message_)[strings::params][strings::connection_key].asUInt();
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(app_id);
+ int32_t app_id =
+ (*message_)[strings::params][strings::connection_key].asUInt();
+ ApplicationSharedPtr app = appplication_manager.application(app_id);
if (!app) {
LOG4CXX_ERROR(logger_, "NULL pointer");
@@ -69,8 +69,8 @@ void GetVehicleDataRequest::Run() {
VehicleData::const_iterator it = vehicle_data.begin();
for (; vehicle_data.end() != it; ++it) {
- if (true == (*message_)[str::msg_params].keyExists(it->first)
- && true == (*message_)[str::msg_params][it->first].asBool()) {
+ if (true == (*message_)[str::msg_params].keyExists(it->first) &&
+ true == (*message_)[str::msg_params][it->first].asBool()) {
SendRequestsToHmi(app->app_id());
return;
}
@@ -80,37 +80,44 @@ void GetVehicleDataRequest::Run() {
}
namespace {
- struct Subrequest {
- hmi_apis::FunctionID::eType func_id;
- const char* str;
- };
- Subrequest subrequests[] = {
- { hmi_apis::FunctionID::VehicleInfo_GetGpsData, str::gps},
- { hmi_apis::FunctionID::VehicleInfo_GetSpeed, str::speed},
- { hmi_apis::FunctionID::VehicleInfo_GetRpm, str::rpm},
- { hmi_apis::FunctionID::VehicleInfo_GetFuelLevel, str::fuel_level},
- { hmi_apis::FunctionID::VehicleInfo_GetFuelLevelState, str::fuel_level_state},
- { hmi_apis::FunctionID::VehicleInfo_GetInstantFuelConsumption, str::instant_fuel_consumption},
- { hmi_apis::FunctionID::VehicleInfo_GetExternalTemperature, str::external_temp},
- { hmi_apis::FunctionID::VehicleInfo_GetVin, str::vin},
- { hmi_apis::FunctionID::VehicleInfo_GetPrndl, str::prndl},
- { hmi_apis::FunctionID::VehicleInfo_GetTirePressure, str::tire_pressure},
- { hmi_apis::FunctionID::VehicleInfo_GetOdometer, str::odometer},
- { hmi_apis::FunctionID::VehicleInfo_GetBeltStatus, str::belt_status},
- { hmi_apis::FunctionID::VehicleInfo_GetBodyInformation, str::body_information},
- { hmi_apis::FunctionID::VehicleInfo_GetDeviceStatus, str::device_status},
- { hmi_apis::FunctionID::VehicleInfo_GetDriverBraking, str::driver_braking},
- { hmi_apis::FunctionID::VehicleInfo_GetWiperStatus, str::wiper_status},
- { hmi_apis::FunctionID::VehicleInfo_GetHeadLampStatus, str::head_lamp_status},
- { hmi_apis::FunctionID::VehicleInfo_GetEngineTorque, str::engine_torque},
- { hmi_apis::FunctionID::VehicleInfo_GetAccPedalPosition, str::acc_pedal_pos},
- { hmi_apis::FunctionID::VehicleInfo_GetSteeringWheelAngle, str::steering_wheel_angle},
- { hmi_apis::FunctionID::VehicleInfo_GetECallInfo, str::e_call_info},
- { hmi_apis::FunctionID::VehicleInfo_GetAirbagStatus, str::airbag_status},
- { hmi_apis::FunctionID::VehicleInfo_GetEmergencyEvent, str::emergency_event},
- { hmi_apis::FunctionID::VehicleInfo_GetClusterModeStatus, str::cluster_mode_status},
- { hmi_apis::FunctionID::VehicleInfo_GetMyKey, str::my_key},
- };
+struct Subrequest {
+ hmi_apis::FunctionID::eType func_id;
+ const char* str;
+};
+Subrequest subrequests[] = {
+ {hmi_apis::FunctionID::VehicleInfo_GetGpsData, str::gps},
+ {hmi_apis::FunctionID::VehicleInfo_GetSpeed, str::speed},
+ {hmi_apis::FunctionID::VehicleInfo_GetRpm, str::rpm},
+ {hmi_apis::FunctionID::VehicleInfo_GetFuelLevel, str::fuel_level},
+ {hmi_apis::FunctionID::VehicleInfo_GetFuelLevelState,
+ str::fuel_level_state},
+ {hmi_apis::FunctionID::VehicleInfo_GetInstantFuelConsumption,
+ str::instant_fuel_consumption},
+ {hmi_apis::FunctionID::VehicleInfo_GetExternalTemperature,
+ str::external_temp},
+ {hmi_apis::FunctionID::VehicleInfo_GetVin, str::vin},
+ {hmi_apis::FunctionID::VehicleInfo_GetPrndl, str::prndl},
+ {hmi_apis::FunctionID::VehicleInfo_GetTirePressure, str::tire_pressure},
+ {hmi_apis::FunctionID::VehicleInfo_GetOdometer, str::odometer},
+ {hmi_apis::FunctionID::VehicleInfo_GetBeltStatus, str::belt_status},
+ {hmi_apis::FunctionID::VehicleInfo_GetBodyInformation,
+ str::body_information},
+ {hmi_apis::FunctionID::VehicleInfo_GetDeviceStatus, str::device_status},
+ {hmi_apis::FunctionID::VehicleInfo_GetDriverBraking, str::driver_braking},
+ {hmi_apis::FunctionID::VehicleInfo_GetWiperStatus, str::wiper_status},
+ {hmi_apis::FunctionID::VehicleInfo_GetHeadLampStatus,
+ str::head_lamp_status},
+ {hmi_apis::FunctionID::VehicleInfo_GetEngineTorque, str::engine_torque},
+ {hmi_apis::FunctionID::VehicleInfo_GetAccPedalPosition, str::acc_pedal_pos},
+ {hmi_apis::FunctionID::VehicleInfo_GetSteeringWheelAngle,
+ str::steering_wheel_angle},
+ {hmi_apis::FunctionID::VehicleInfo_GetECallInfo, str::e_call_info},
+ {hmi_apis::FunctionID::VehicleInfo_GetAirbagStatus, str::airbag_status},
+ {hmi_apis::FunctionID::VehicleInfo_GetEmergencyEvent, str::emergency_event},
+ {hmi_apis::FunctionID::VehicleInfo_GetClusterModeStatus,
+ str::cluster_mode_status},
+ {hmi_apis::FunctionID::VehicleInfo_GetMyKey, str::my_key},
+};
}
void GetVehicleDataRequest::SendRequestsToHmi(const int32_t app_id) {
@@ -119,8 +126,8 @@ void GetVehicleDataRequest::SendRequestsToHmi(const int32_t app_id) {
for (size_t i = 0; i < sizeof(subrequests) / sizeof(subrequests[0]); ++i) {
const Subrequest& sr = subrequests[i];
- if (true == (*message_)[str::msg_params].keyExists(sr.str)
- && true == (*message_)[str::msg_params][sr.str].asBool()) {
+ if (true == (*message_)[str::msg_params].keyExists(sr.str) &&
+ true == (*message_)[str::msg_params][sr.str].asBool()) {
HmiRequest hmi_request;
hmi_request.str = sr.str;
hmi_request.func_id = sr.func_id;
@@ -133,7 +140,8 @@ void GetVehicleDataRequest::SendRequestsToHmi(const int32_t app_id) {
hmi_requests_.size() << " requests are going to be sent to HMI");
for (HmiRequests::const_iterator it = hmi_requests_.begin();
- it != hmi_requests_.end(); ++it) {
+ it != hmi_requests_.end();
+ ++it) {
SendHMIRequest(it->func_id, &msg_params, true);
}
}
@@ -144,12 +152,12 @@ void GetVehicleDataRequest::on_event(const event_engine::Event& event) {
const smart_objects::SmartObject& message = event.smart_object();
for (HmiRequests::iterator it = hmi_requests_.begin();
- it != hmi_requests_.end(); ++it) {
- HmiRequest & hmi_request = *it;
+ it != hmi_requests_.end();
+ ++it) {
+ HmiRequest& hmi_request = *it;
if (hmi_request.func_id == event.id()) {
- hmi_request.status =
- static_cast<hmi_apis::Common_Result::eType>(message[strings::params][hmi_response::code]
- .asInt());
+ hmi_request.status = static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asInt());
if (hmi_apis::Common_Result::SUCCESS == hmi_request.status)
hmi_request.value = message[str::msg_params][hmi_request.str];
hmi_request.complete = true;
@@ -161,7 +169,8 @@ void GetVehicleDataRequest::on_event(const event_engine::Event& event) {
bool any_arg_success = false;
mobile_api::Result::eType status = mobile_api::Result::eType::SUCCESS;
for (HmiRequests::const_iterator it = hmi_requests_.begin();
- it != hmi_requests_.end(); ++it) {
+ it != hmi_requests_.end();
+ ++it) {
if (!it->complete) {
all_complete = false;
break;
@@ -169,13 +178,16 @@ void GetVehicleDataRequest::on_event(const event_engine::Event& event) {
if (hmi_apis::Common_Result::SUCCESS != it->status) {
if (mobile_api::Result::SUCCESS == status) {
status = static_cast<mobile_apis::Result::eType>(it->status);
- } else if (status
- != static_cast<mobile_apis::Result::eType>(it->status)) {
+ } else if (status !=
+ static_cast<mobile_apis::Result::eType>(it->status)) {
status = mobile_api::Result::eType::GENERIC_ERROR;
}
- LOG4CXX_TRACE(logger_, "Status from HMI: " << it->status << ", so response status become " << status);
+ LOG4CXX_TRACE(logger_,
+ "Status from HMI: " << it->status
+ << ", so response status become "
+ << status);
} else {
- any_arg_success = true;
+ any_arg_success = true;
}
}
@@ -183,34 +195,34 @@ void GetVehicleDataRequest::on_event(const event_engine::Event& event) {
smart_objects::SmartObject response_params(smart_objects::SmartType_Map);
if (any_arg_success) {
for (HmiRequests::const_iterator it = hmi_requests_.begin();
- it != hmi_requests_.end(); ++it) {
+ it != hmi_requests_.end();
+ ++it) {
response_params[it->str] = it->value;
}
}
- LOG4CXX_INFO(
- logger_, "All HMI requests are complete");
- const char *info = NULL;
+ LOG4CXX_INFO(logger_, "All HMI requests are complete");
+ const char* info = NULL;
std::string error_message;
if (true == message[strings::params].keyExists(strings::error_msg)) {
error_message = message[strings::params][strings::error_msg].asString();
info = error_message.c_str();
}
- SendResponse( any_arg_success, status, info, &response_params);
+ SendResponse(any_arg_success, status, info, &response_params);
}
}
#else
-GetVehicleDataRequest::GetVehicleDataRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+GetVehicleDataRequest::GetVehicleDataRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-GetVehicleDataRequest::~GetVehicleDataRequest() {
-}
+GetVehicleDataRequest::~GetVehicleDataRequest() {}
void GetVehicleDataRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- int32_t app_id = (*message_)[strings::params][strings::connection_key].asUInt();
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(app_id);
+ int32_t app_id =
+ (*message_)[strings::params][strings::connection_key].asUInt();
+ ApplicationSharedPtr app = application_manager_.application(app_id);
if (!app) {
LOG4CXX_ERROR(logger_, "NULL pointer");
@@ -219,27 +231,27 @@ void GetVehicleDataRequest::Run() {
}
if (app->IsCommandLimitsExceeded(
- static_cast<mobile_apis::FunctionID::eType>(function_id()),
- application_manager::TLimitSource::CONFIG_FILE)) {
+ static_cast<mobile_apis::FunctionID::eType>(function_id()),
+ application_manager::TLimitSource::CONFIG_FILE)) {
LOG4CXX_ERROR(logger_, "GetVehicleData frequency is too high.");
SendResponse(false, mobile_apis::Result::REJECTED);
return;
}
const VehicleData& vehicle_data = MessageHelper::vehicle_data();
VehicleData::const_iterator it = vehicle_data.begin();
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::app_id] = app->app_id();
const uint32_t min_length_msg_params = 1;
for (; vehicle_data.end() != it; ++it) {
- if (true == (*message_)[str::msg_params].keyExists(it->first)
- && true == (*message_)[str::msg_params][it->first].asBool()) {
+ if (true == (*message_)[str::msg_params].keyExists(it->first) &&
+ true == (*message_)[str::msg_params][it->first].asBool()) {
msg_params[it->first] = (*message_)[strings::msg_params][it->first];
}
}
if (msg_params.length() > min_length_msg_params) {
- SendHMIRequest(hmi_apis::FunctionID::VehicleInfo_GetVehicleData,
- &msg_params, true);
+ SendHMIRequest(
+ hmi_apis::FunctionID::VehicleInfo_GetVehicleData, &msg_params, true);
return;
} else if (HasDisallowedParams()) {
SendResponse(false, mobile_apis::Result::DISALLOWED);
@@ -260,11 +272,11 @@ void GetVehicleDataRequest::on_event(const event_engine::Event& event) {
bool result = false;
if (mobile_apis::Result::SUCCESS == result_code ||
(hmi_apis::Common_Result::DATA_NOT_AVAILABLE ==
- static_cast<hmi_apis::Common_Result::eType>(result_code)
- && message[strings::msg_params].length() > 1)) {
+ static_cast<hmi_apis::Common_Result::eType>(result_code) &&
+ message[strings::msg_params].length() > 1)) {
result = true;
}
- const char *info = NULL;
+ const char* info = NULL;
std::string error_message;
if (true ==
message[strings::msg_params].keyExists(hmi_response::method)) {
@@ -284,8 +296,8 @@ void GetVehicleDataRequest::on_event(const event_engine::Event& event) {
}
}
-#endif // #ifdef HMI_DBUS_API
+#endif // #ifdef HMI_DBUS_API
-} // namespace commands
+} // namespace commands
-} // namespace application_manager
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/get_vehicle_data_response.cc b/src/components/application_manager/src/commands/mobile/get_vehicle_data_response.cc
index 5491e9b1aa..1e64746262 100644
--- a/src/components/application_manager/src/commands/mobile/get_vehicle_data_response.cc
+++ b/src/components/application_manager/src/commands/mobile/get_vehicle_data_response.cc
@@ -32,24 +32,23 @@
*/
#include "application_manager/commands/mobile/get_vehicle_data_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
namespace commands {
-GetVehicleDataResponse::GetVehicleDataResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+GetVehicleDataResponse::GetVehicleDataResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-GetVehicleDataResponse::~GetVehicleDataResponse() {
-}
+GetVehicleDataResponse::~GetVehicleDataResponse() {}
void GetVehicleDataResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/get_way_points_request.cc b/src/components/application_manager/src/commands/mobile/get_way_points_request.cc
new file mode 100644
index 0000000000..9baf747ee4
--- /dev/null
+++ b/src/components/application_manager/src/commands/mobile/get_way_points_request.cc
@@ -0,0 +1,59 @@
+#include "application_manager/application_manager.h"
+#include "application_manager/commands/mobile/get_way_points_request.h"
+
+namespace application_manager {
+
+namespace commands {
+
+GetWayPointsRequest::GetWayPointsRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
+
+GetWayPointsRequest::~GetWayPointsRequest() {}
+
+void GetWayPointsRequest::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
+
+ if (!app) {
+ LOG4CXX_ERROR(logger_,
+ "An application with connection key "
+ << connection_key() << " is not registered.");
+ SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
+ return;
+ }
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+
+ msg_params = (*message_)[strings::msg_params];
+ msg_params[strings::app_id] = app->app_id();
+ SendHMIRequest(hmi_apis::FunctionID::Navigation_GetWayPoints,
+ msg_params.empty() ? NULL : &msg_params,
+ true);
+}
+
+void GetWayPointsRequest::on_event(const event_engine::Event& event) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
+ const smart_objects::SmartObject& message = event.smart_object();
+ switch (event.id()) {
+ case hmi_apis::FunctionID::Navigation_GetWayPoints: {
+ LOG4CXX_INFO(logger_, "Received Navigation_GetWayPoints event");
+ mobile_apis::Result::eType result_code =
+ GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asUInt()));
+ bool result = mobile_apis::Result::SUCCESS == result_code;
+ SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
+ break;
+ }
+ default: {
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
+ break;
+ }
+ }
+}
+
+} // namespace commands
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/get_way_points_response.cc b/src/components/application_manager/src/commands/mobile/get_way_points_response.cc
new file mode 100644
index 0000000000..7956b34cae
--- /dev/null
+++ b/src/components/application_manager/src/commands/mobile/get_way_points_response.cc
@@ -0,0 +1,22 @@
+#include "application_manager/application_manager.h"
+#include "application_manager/commands/mobile/get_way_points_response.h"
+
+namespace application_manager {
+
+namespace commands {
+
+GetWayPointsResponse::GetWayPointsResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
+
+GetWayPointsResponse::~GetWayPointsResponse() {}
+
+void GetWayPointsResponse::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ application_manager_.SendMessageToMobile(message_);
+}
+
+} // namespace commands
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/list_files_request.cc b/src/components/application_manager/src/commands/mobile/list_files_request.cc
index 427443e3e9..425f1ddb46 100644
--- a/src/components/application_manager/src/commands/mobile/list_files_request.cc
+++ b/src/components/application_manager/src/commands/mobile/list_files_request.cc
@@ -31,10 +31,11 @@
POSSIBILITY OF SUCH DAMAGE.
*/
+#include <string>
#include "application_manager/commands/mobile/list_files_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
-#include "config_profile/profile.h"
+
#include "application_manager/mobile_command_factory.h"
#include "utils/file_system.h"
@@ -42,18 +43,17 @@ namespace application_manager {
namespace commands {
-ListFilesRequest::ListFilesRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+ListFilesRequest::ListFilesRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-ListFilesRequest::~ListFilesRequest() {
-}
+ListFilesRequest::~ListFilesRequest() {}
void ListFilesRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (!application) {
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
@@ -62,33 +62,43 @@ void ListFilesRequest::Run() {
}
if ((mobile_api::HMILevel::HMI_NONE == application->hmi_level()) &&
- (profile::Profile::instance()->list_files_in_none() <=
+ (application_manager_.get_settings().list_files_in_none() <=
application->list_files_in_none_count())) {
- // If application is in the HMI_NONE level the quantity of allowed
- // DeleteFile request is limited by the configuration profile
- LOG4CXX_ERROR(logger_, "Too many requests from the app with HMILevel HMI_NONE ");
- SendResponse(false, mobile_apis::Result::REJECTED);
- return;
+ // If application is in the HMI_NONE level the quantity of allowed
+ // DeleteFile request is limited by the configuration profile
+ LOG4CXX_ERROR(logger_,
+ "Too many requests from the app with HMILevel HMI_NONE ");
+ SendResponse(false, mobile_apis::Result::REJECTED);
+ return;
}
application->increment_list_files_in_none_count();
(*message_)[strings::msg_params][strings::space_available] =
- static_cast<int32_t>(ApplicationManagerImpl::instance()->
- GetAvailableSpaceForApp(application->folder_name()));
- int32_t i = 0;
+ static_cast<int32_t>(application->GetAvailableDiskSpace());
+ uint32_t i = 0;
const AppFilesMap& app_files = application->getAppFiles();
for (AppFilesMap::const_iterator it = app_files.begin();
- it != app_files.end(); ++it) {
- //In AppFile to application stored full path to file. In message required
- //to write only name file.
- //Plus one required for move to next letter after '/'.
- (*message_)[strings::msg_params][strings::filenames][i++] =
- it->first.substr(it->first.find_last_of('/') + 1);
+ it != app_files.end();
+ ++it) {
+ std::string filename = it->first.substr(it->first.find_last_of('/') + 1);
+ // In AppFile to application stored full path to file. In message required
+ // to write only name file.
+ // Plus one required for move to next letter after '/'.
+ if (i < application_manager_.get_settings().list_files_response_size()) {
+ LOG4CXX_DEBUG(logger_,
+ "File " + filename + " added to ListFiles response");
+ (*message_)[strings::msg_params][strings::filenames][i++] = filename;
+ } else {
+ LOG4CXX_DEBUG(logger_,
+ "File " + filename + " not added to ListFiles response");
+ }
}
(*message_)[strings::params][strings::message_type] =
application_manager::MessageType::kResponse;
- SendResponse(true, mobile_apis::Result::SUCCESS, NULL,
+ SendResponse(true,
+ mobile_apis::Result::SUCCESS,
+ NULL,
&(*message_)[strings::msg_params]);
}
diff --git a/src/components/application_manager/src/commands/mobile/list_files_response.cc b/src/components/application_manager/src/commands/mobile/list_files_response.cc
index 42bd1e6f07..fde15a94ef 100644
--- a/src/components/application_manager/src/commands/mobile/list_files_response.cc
+++ b/src/components/application_manager/src/commands/mobile/list_files_response.cc
@@ -32,24 +32,23 @@
*/
#include "application_manager/commands/mobile/list_files_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
namespace application_manager {
namespace commands {
-ListFilesResponse::ListFilesResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ListFilesResponse::ListFilesResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-ListFilesResponse::~ListFilesResponse() {
-}
+ListFilesResponse::~ListFilesResponse() {}
void ListFilesResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/on_app_interface_unregistered_notification.cc b/src/components/application_manager/src/commands/mobile/on_app_interface_unregistered_notification.cc
index e3e51faa6e..6064374dab 100644
--- a/src/components/application_manager/src/commands/mobile/on_app_interface_unregistered_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_app_interface_unregistered_notification.cc
@@ -39,12 +39,11 @@ namespace application_manager {
namespace commands {
OnAppInterfaceUnregisteredNotification::OnAppInterfaceUnregisteredNotification(
- const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
-OnAppInterfaceUnregisteredNotification::~OnAppInterfaceUnregisteredNotification() {
-}
+OnAppInterfaceUnregisteredNotification::
+ ~OnAppInterfaceUnregisteredNotification() {}
void OnAppInterfaceUnregisteredNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/mobile/on_audio_pass_thru_notification.cc b/src/components/application_manager/src/commands/mobile/on_audio_pass_thru_notification.cc
index d1329bf8ea..d0fa3597bc 100644
--- a/src/components/application_manager/src/commands/mobile/on_audio_pass_thru_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_audio_pass_thru_notification.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
OnAudioPassThruNotification::OnAudioPassThruNotification(
- const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
-OnAudioPassThruNotification::~OnAudioPassThruNotification() {
-}
+OnAudioPassThruNotification::~OnAudioPassThruNotification() {}
void OnAudioPassThruNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/mobile/on_button_event_notification.cc b/src/components/application_manager/src/commands/mobile/on_button_event_notification.cc
index b2ed8f8bfc..2f64e2f850 100644
--- a/src/components/application_manager/src/commands/mobile/on_button_event_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_button_event_notification.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/on_button_event_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
@@ -43,53 +43,51 @@ namespace commands {
namespace mobile {
OnButtonEventNotification::OnButtonEventNotification(
- const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
-OnButtonEventNotification::~OnButtonEventNotification() {
-}
+OnButtonEventNotification::~OnButtonEventNotification() {}
void OnButtonEventNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- const uint32_t btn_id =
- static_cast<uint32_t>(
- (*message_)[strings::msg_params][hmi_response::button_name].asInt());
+ const uint32_t btn_id = static_cast<uint32_t>(
+ (*message_)[strings::msg_params][hmi_response::button_name].asInt());
const bool is_app_id_exists =
(*message_)[strings::msg_params].keyExists(strings::app_id);
- const ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(
+ const ApplicationSharedPtr app = application_manager_.application(
(*message_)[strings::msg_params][strings::app_id].asUInt());
// CUSTOM_BUTTON notification
if (static_cast<uint32_t>(mobile_apis::ButtonName::CUSTOM_BUTTON) == btn_id) {
// app_id is mandatory for CUSTOM_BUTTON notification
if (!is_app_id_exists) {
- LOG4CXX_ERROR_EXT(logger_, "CUSTOM_BUTTON OnButtonEvent without app_id.");
+ LOG4CXX_ERROR(logger_, "CUSTOM_BUTTON OnButtonEvent without app_id.");
return;
}
// custom_button_id is mandatory for CUSTOM_BUTTON notification
- if (false == (*message_)[strings::msg_params].keyExists(
- hmi_response::custom_button_id)) {
- LOG4CXX_ERROR_EXT(logger_,
- "CUSTOM_BUTTON OnButtonEvent without custom_button_id.");
+ if (false ==
+ (*message_)[strings::msg_params].keyExists(
+ hmi_response::custom_button_id)) {
+ LOG4CXX_ERROR(logger_,
+ "CUSTOM_BUTTON OnButtonEvent without custom_button_id.");
return;
}
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "Application doesn't exist.");
+ LOG4CXX_ERROR(logger_, "Application doesn't exist.");
return;
}
uint32_t custom_btn_id = 0;
- custom_btn_id = (*message_)[strings::msg_params]
- [hmi_response::custom_button_id].asUInt();
+ custom_btn_id =
+ (*message_)[strings::msg_params][hmi_response::custom_button_id]
+ .asUInt();
if (false == app->IsSubscribedToSoftButton(custom_btn_id)) {
- LOG4CXX_ERROR_EXT(logger_,
+ LOG4CXX_ERROR(logger_,
"Application doesn't subscribed to this custom_button_id.");
return;
}
@@ -99,43 +97,45 @@ void OnButtonEventNotification::Run() {
}
const std::vector<ApplicationSharedPtr>& subscribed_apps =
- ApplicationManagerImpl::instance()->applications_by_button(btn_id);
+ application_manager_.applications_by_button(btn_id);
std::vector<ApplicationSharedPtr>::const_iterator it = subscribed_apps.begin();
for (; subscribed_apps.end() != it; ++it) {
ApplicationSharedPtr subscribed_app = *it;
if (!subscribed_app) {
- LOG4CXX_WARN_EXT(logger_, "Null pointer to subscribed app.");
+ LOG4CXX_WARN(logger_, "Null pointer to subscribed app.");
continue;
}
// Send ButtonEvent notification only in HMI_FULL or HMI_LIMITED mode
if ((mobile_api::HMILevel::HMI_FULL != subscribed_app->hmi_level()) &&
(mobile_api::HMILevel::HMI_LIMITED != subscribed_app->hmi_level())) {
- LOG4CXX_WARN_EXT(logger_, "OnButtonEvent in HMI_BACKGROUND or NONE");
+ LOG4CXX_WARN(logger_,
+ "OnButtonEvent notification is allowed only"
+ << "in FULL or LIMITED hmi level");
continue;
}
// if "app_id" absent send notification only in HMI_FULL mode
if (is_app_id_exists || subscribed_app->IsFullscreen()) {
- SendButtonEvent(subscribed_app);
- }
+ SendButtonEvent(subscribed_app);
}
}
+}
void OnButtonEventNotification::SendButtonEvent(ApplicationConstSharedPtr app) {
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "OnButtonEvent NULL pointer");
+ LOG4CXX_ERROR(logger_, "OnButtonEvent NULL pointer");
return;
}
- smart_objects::SmartObjectSPtr on_btn_event = new smart_objects::SmartObject();
+ smart_objects::SmartObjectSPtr on_btn_event =
+ new smart_objects::SmartObject();
if (!on_btn_event) {
- LOG4CXX_ERROR_EXT(logger_, "OnButtonEvent NULL pointer");
+ LOG4CXX_ERROR(logger_, "OnButtonEvent NULL pointer");
return;
}
-
(*on_btn_event)[strings::params][strings::connection_key] = app->app_id();
(*on_btn_event)[strings::params][strings::function_id] =
@@ -147,7 +147,7 @@ void OnButtonEventNotification::SendButtonEvent(ApplicationConstSharedPtr app) {
(*message_)[strings::msg_params][hmi_response::button_mode];
if ((*message_)[strings::msg_params].keyExists(
- hmi_response::custom_button_id)) {
+ hmi_response::custom_button_id)) {
(*on_btn_event)[strings::msg_params][strings::custom_button_id] =
(*message_)[strings::msg_params][strings::custom_button_id];
}
diff --git a/src/components/application_manager/src/commands/mobile/on_button_press_notification.cc b/src/components/application_manager/src/commands/mobile/on_button_press_notification.cc
index 72677c0f77..56673f921d 100644
--- a/src/components/application_manager/src/commands/mobile/on_button_press_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_button_press_notification.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/on_button_press_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
@@ -43,53 +43,51 @@ namespace commands {
namespace mobile {
OnButtonPressNotification::OnButtonPressNotification(
- const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
-OnButtonPressNotification::~OnButtonPressNotification() {
-}
+OnButtonPressNotification::~OnButtonPressNotification() {}
void OnButtonPressNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- const uint32_t btn_id =
- static_cast<uint32_t>(
- (*message_)[strings::msg_params][hmi_response::button_name].asInt());
+ const uint32_t btn_id = static_cast<uint32_t>(
+ (*message_)[strings::msg_params][hmi_response::button_name].asInt());
const bool is_app_id_exists =
(*message_)[strings::msg_params].keyExists(strings::app_id);
const ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(
+ application_manager_.application(
(*message_)[strings::msg_params][strings::app_id].asUInt());
// CUSTOM_BUTTON notification
if (static_cast<uint32_t>(mobile_apis::ButtonName::CUSTOM_BUTTON) == btn_id) {
// app_id is mandatory for CUSTOM_BUTTON notification
if (!is_app_id_exists) {
- LOG4CXX_ERROR_EXT(logger_, "CUSTOM_BUTTON OnButtonPress without app_id.");
+ LOG4CXX_ERROR(logger_, "CUSTOM_BUTTON OnButtonPress without app_id.");
return;
}
// custom_button_id is mandatory for CUSTOM_BUTTON notification
if (false == (*message_)[strings::msg_params].keyExists(
- hmi_response::custom_button_id)) {
- LOG4CXX_ERROR_EXT(logger_,
- "CUSTOM_BUTTON OnButtonPress without custom_button_id.");
+ hmi_response::custom_button_id)) {
+ LOG4CXX_ERROR(logger_,
+ "CUSTOM_BUTTON OnButtonPress without custom_button_id.");
return;
}
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "Application doesn't exist.");
+ LOG4CXX_ERROR(logger_, "Application doesn't exist.");
return;
}
uint32_t custom_btn_id = 0;
- custom_btn_id = (*message_)[strings::msg_params]
- [hmi_response::custom_button_id].asUInt();
+ custom_btn_id =
+ (*message_)[strings::msg_params][hmi_response::custom_button_id]
+ .asUInt();
if (false == app->IsSubscribedToSoftButton(custom_btn_id)) {
- LOG4CXX_ERROR_EXT(logger_,
+ LOG4CXX_ERROR(logger_,
"Application doesn't subscribed to this custom_button_id.");
return;
}
@@ -99,43 +97,45 @@ void OnButtonPressNotification::Run() {
}
const std::vector<ApplicationSharedPtr>& subscribed_apps =
- ApplicationManagerImpl::instance()->applications_by_button(btn_id);
+ application_manager_.applications_by_button(btn_id);
std::vector<ApplicationSharedPtr>::const_iterator it = subscribed_apps.begin();
for (; subscribed_apps.end() != it; ++it) {
ApplicationSharedPtr subscribed_app = *it;
if (!subscribed_app) {
- LOG4CXX_WARN_EXT(logger_, "Null pointer to subscribed app.");
+ LOG4CXX_WARN(logger_, "Null pointer to subscribed app.");
continue;
}
// Send ButtonPress notification only in HMI_FULL or HMI_LIMITED mode
if ((mobile_api::HMILevel::HMI_FULL != subscribed_app->hmi_level()) &&
(mobile_api::HMILevel::HMI_LIMITED != subscribed_app->hmi_level())) {
- LOG4CXX_WARN_EXT(logger_, "OnButtonPress in HMI_BACKGROUND or NONE");
+ LOG4CXX_WARN(logger_,
+ "OnButtonPress notification is allowed only"
+ << "in FULL or LIMITED hmi level");
continue;
}
// if "app_id" absent send notification only in HMI_FULL mode
if (is_app_id_exists || subscribed_app->IsFullscreen()) {
- SendButtonPress(subscribed_app);
- }
+ SendButtonPress(subscribed_app);
}
}
+}
void OnButtonPressNotification::SendButtonPress(ApplicationConstSharedPtr app) {
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "OnButtonPress NULL pointer");
+ LOG4CXX_ERROR(logger_, "OnButtonPress NULL pointer");
return;
}
- smart_objects::SmartObjectSPtr on_btn_press = new smart_objects::SmartObject();
+ smart_objects::SmartObjectSPtr on_btn_press =
+ new smart_objects::SmartObject();
if (!on_btn_press) {
- LOG4CXX_ERROR_EXT(logger_, "OnButtonPress NULL pointer");
+ LOG4CXX_ERROR(logger_, "OnButtonPress NULL pointer");
return;
}
-
(*on_btn_press)[strings::params][strings::connection_key] = app->app_id();
(*on_btn_press)[strings::params][strings::function_id] =
@@ -147,7 +147,7 @@ void OnButtonPressNotification::SendButtonPress(ApplicationConstSharedPtr app) {
(*message_)[strings::msg_params][hmi_response::button_mode];
if ((*message_)[strings::msg_params].keyExists(
- hmi_response::custom_button_id)) {
+ hmi_response::custom_button_id)) {
(*on_btn_press)[strings::msg_params][strings::custom_button_id] =
(*message_)[strings::msg_params][strings::custom_button_id];
}
diff --git a/src/components/application_manager/src/commands/mobile/on_command_notification.cc b/src/components/application_manager/src/commands/mobile/on_command_notification.cc
index 9bba1851f6..ae8aeff771 100644
--- a/src/components/application_manager/src/commands/mobile/on_command_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_command_notification.cc
@@ -32,37 +32,35 @@
*/
#include "application_manager/commands/mobile/on_command_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
namespace application_manager {
namespace commands {
-OnCommandNotification::OnCommandNotification(const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {
-}
+OnCommandNotification::OnCommandNotification(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
-OnCommandNotification::~OnCommandNotification() {
-}
+OnCommandNotification::~OnCommandNotification() {}
void OnCommandNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
+ ApplicationSharedPtr app = application_manager_.application(
(*message_)[strings::msg_params][strings::app_id].asInt());
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "No application associated with session key");
+ LOG4CXX_ERROR(logger_, "No application associated with session key");
return;
}
- const uint32_t cmd_id = (*message_)[strings::msg_params][strings::cmd_id]
- .asUInt();
+ const uint32_t cmd_id =
+ (*message_)[strings::msg_params][strings::cmd_id].asUInt();
if (!app->FindCommand(cmd_id)) {
- LOG4CXX_ERROR_EXT(logger_,
- " No applications found for the command " << cmd_id);
+ LOG4CXX_ERROR(logger_, " No applications found for the command " << cmd_id);
return;
}
diff --git a/src/components/application_manager/src/commands/mobile/on_driver_distraction_notification.cc b/src/components/application_manager/src/commands/mobile/on_driver_distraction_notification.cc
index e9145520f4..44ed2cf3b7 100644
--- a/src/components/application_manager/src/commands/mobile/on_driver_distraction_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_driver_distraction_notification.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/on_driver_distraction_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
@@ -43,12 +43,10 @@ namespace commands {
namespace mobile {
OnDriverDistractionNotification::OnDriverDistractionNotification(
- const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
-OnDriverDistractionNotification::~OnDriverDistractionNotification() {
-}
+OnDriverDistractionNotification::~OnDriverDistractionNotification() {}
void OnDriverDistractionNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/mobile/on_hash_change_notification.cc b/src/components/application_manager/src/commands/mobile/on_hash_change_notification.cc
index 10f3eb1ab6..19b93f2cbf 100644
--- a/src/components/application_manager/src/commands/mobile/on_hash_change_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_hash_change_notification.cc
@@ -33,7 +33,7 @@
*/
#include "application_manager/commands/mobile/on_hash_change_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
#include <string>
@@ -45,12 +45,10 @@ namespace commands {
namespace mobile {
OnHashChangeNotification::OnHashChangeNotification(
- const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
-OnHashChangeNotification::~OnHashChangeNotification() {
-}
+OnHashChangeNotification::~OnHashChangeNotification() {}
void OnHashChangeNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -60,17 +58,17 @@ void OnHashChangeNotification::Run() {
int32_t app_id;
app_id = (*message_)[strings::params][strings::connection_key].asInt();
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(app_id);
+ ApplicationSharedPtr app = application_manager_.application(app_id);
if (app) {
(*message_)[strings::msg_params][strings::hash_id] = app->curHash();
SendNotification();
} else {
- LOG4CXX_WARN(logger_, "Application with app_id " << app_id << " does not exist");
+ LOG4CXX_WARN(logger_,
+ "Application with app_id " << app_id << " does not exist");
}
-
}
-} //namespace mobile
+} // namespace mobile
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/on_hmi_status_notification.cc b/src/components/application_manager/src/commands/mobile/on_hmi_status_notification.cc
index e4a2d7c340..5225002652 100644
--- a/src/components/application_manager/src/commands/mobile/on_hmi_status_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_hmi_status_notification.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/on_hmi_status_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/message_helper.h"
#include "application_manager/message.h"
#include "interfaces/MOBILE_API.h"
@@ -41,20 +41,17 @@ namespace application_manager {
namespace commands {
OnHMIStatusNotification::OnHMIStatusNotification(
- const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
-OnHMIStatusNotification::~OnHMIStatusNotification() {
-}
+OnHMIStatusNotification::~OnHMIStatusNotification() {}
void OnHMIStatusNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- (*message_)[strings::params][strings::message_type] = static_cast<int32_t> (
- application_manager::MessageType::kNotification);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
- connection_key());
+ (*message_)[strings::params][strings::message_type] =
+ static_cast<int32_t>(application_manager::MessageType::kNotification);
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app.valid()) {
LOG4CXX_ERROR(logger_, "OnHMIStatusNotification application doesn't exist");
return;
@@ -67,18 +64,18 @@ void OnHMIStatusNotification::Run() {
(mobile_apis::HMILevel::HMI_NONE == hmi_level)) {
if (!(app->tts_properties_in_none())) {
app->set_tts_properties_in_none(true);
- LOG4CXX_INFO(logger_, "OnHMIStatusNotification::Send TTS GlobalProperties"
+ LOG4CXX_INFO(logger_,
+ "OnHMIStatusNotification::Send TTS GlobalProperties"
" with empty array to HMI");
- MessageHelper::SendTTSGlobalProperties(app, false);
+ MessageHelper::SendTTSGlobalProperties(app, false, application_manager_);
}
} else if ((mobile_apis::HMILevel::HMI_FULL == hmi_level) ||
- (mobile_apis::HMILevel::HMI_LIMITED == hmi_level)) {
+ (mobile_apis::HMILevel::HMI_LIMITED == hmi_level)) {
if (!(app->tts_properties_in_full())) {
app->set_tts_properties_in_full(true);
LOG4CXX_INFO(logger_,
"OnHMIStatusNotification AddAppToTTSGlobalPropertiesList");
- ApplicationManagerImpl::instance()->AddAppToTTSGlobalPropertiesList(
- app->app_id());
+ application_manager_.AddAppToTTSGlobalPropertiesList(app->app_id());
}
}
SendNotification();
diff --git a/src/components/application_manager/src/commands/mobile/on_hmi_status_notification_from_mobile.cc b/src/components/application_manager/src/commands/mobile/on_hmi_status_notification_from_mobile.cc
index 02b4b64aa0..9b16bd3572 100644
--- a/src/components/application_manager/src/commands/mobile/on_hmi_status_notification_from_mobile.cc
+++ b/src/components/application_manager/src/commands/mobile/on_hmi_status_notification_from_mobile.cc
@@ -32,7 +32,6 @@
*/
#include "application_manager/commands/mobile/on_hmi_status_notification_from_mobile.h"
-#include "application_manager/application_manager_impl.h"
#include "application_manager/message_helper.h"
#include "application_manager/message.h"
@@ -40,30 +39,27 @@ namespace application_manager {
namespace commands {
OnHMIStatusNotificationFromMobile::OnHMIStatusNotificationFromMobile(
- const MessageSharedPtr& message)
- : CommandNotificationFromMobileImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationFromMobileImpl(message, application_manager) {}
-OnHMIStatusNotificationFromMobile::~OnHMIStatusNotificationFromMobile() {
-}
+OnHMIStatusNotificationFromMobile::~OnHMIStatusNotificationFromMobile() {}
void OnHMIStatusNotificationFromMobile::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- (*message_)[strings::params][strings::message_type] = static_cast<int32_t> (
- application_manager::MessageType::kNotification);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
- connection_key());
+ (*message_)[strings::params][strings::message_type] =
+ static_cast<int32_t>(application_manager::MessageType::kNotification);
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app.valid()) {
- LOG4CXX_ERROR(logger_,
- "OnHMIStatusNotificationFromMobile application doesn't exist");
+ LOG4CXX_ERROR(
+ logger_, "OnHMIStatusNotificationFromMobile application doesn't exist");
return;
}
mobile_apis::HMILevel::eType current_hmi_state =
static_cast<mobile_apis::HMILevel::eType>(
- (*message_)[strings::msg_params][strings::hmi_level].asUInt());
+ (*message_)[strings::msg_params][strings::hmi_level].asUInt());
bool is_current_state_foreground =
mobile_apis::HMILevel::HMI_FULL == current_hmi_state;
@@ -72,44 +68,46 @@ void OnHMIStatusNotificationFromMobile::Run() {
connection_handler::DeviceHandle handle = app->device();
bool is_apps_requested_before =
- application_manager::ApplicationManagerImpl::instance()->
- IsAppsQueriedFrom(handle);
+ application_manager_.IsAppsQueriedFrom(handle);
- LOG4CXX_DEBUG(logger_, "Mobile HMI state notication came for connection key:"
- << connection_key() << " and handle: " << handle);
+ LOG4CXX_DEBUG(logger_,
+ "Mobile HMI state notication came for connection key:"
+ << connection_key() << " and handle: " << handle);
if (!is_apps_requested_before &&
ProtocolVersion::kV4 == app->protocol_version() && app->is_foreground()) {
// In case this notification will be received from mobile side with
// foreground level for app on mobile, this should trigger remote
// apps list query for SDL 4.0 app
- MessageHelper::SendQueryApps(connection_key());
+ MessageHelper::SendQueryApps(connection_key(), application_manager_);
return;
}
if (is_apps_requested_before) {
- LOG4CXX_DEBUG(logger_, "Remote apps list had been requested already "
- " for handle: " << handle);
+ LOG4CXX_DEBUG(logger_,
+ "Remote apps list had been requested already "
+ " for handle: "
+ << handle);
if (ProtocolVersion::kV4 == app->protocol_version()) {
- ApplicationManagerImpl::ApplicationListAccessor accessor;
+ const ApplicationSet& accessor =
+ application_manager_.applications().GetData();
bool is_another_foreground_sdl4_app = false;
- ApplicationManagerImpl::ApplictionSetIt it = accessor.begin();
- for (;accessor.end() != it; ++it) {
+ ApplicationSetConstIt it = accessor.begin();
+ for (; accessor.end() != it; ++it) {
if (connection_key() != (*it)->app_id() &&
ProtocolVersion::kV4 == (*it)->protocol_version() &&
- (*it)->is_foreground()) {
+ (*it)->is_foreground()) {
is_another_foreground_sdl4_app = true;
break;
}
}
if (!is_another_foreground_sdl4_app) {
- application_manager::ApplicationManagerImpl::instance()->
- MarkAppsGreyOut(handle, !is_current_state_foreground);
- application_manager::ApplicationManagerImpl::instance()->
- SendUpdateAppList();
+ application_manager_.MarkAppsGreyOut(handle,
+ !is_current_state_foreground);
+ application_manager_.SendUpdateAppList();
}
}
return;
diff --git a/src/components/application_manager/src/commands/mobile/on_keyboard_input_notification.cc b/src/components/application_manager/src/commands/mobile/on_keyboard_input_notification.cc
index 6285d684ea..851e9f3059 100644
--- a/src/components/application_manager/src/commands/mobile/on_keyboard_input_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_keyboard_input_notification.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/on_keyboard_input_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
@@ -43,36 +43,37 @@ namespace commands {
namespace mobile {
OnKeyBoardInputNotification::OnKeyBoardInputNotification(
- const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
-OnKeyBoardInputNotification::~OnKeyBoardInputNotification() {
-}
+OnKeyBoardInputNotification::~OnKeyBoardInputNotification() {}
void OnKeyBoardInputNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr app_to_notify;
- ApplicationManagerImpl::ApplicationListAccessor accessor;
- ApplicationManagerImpl::ApplictionSetIt it = accessor.begin();
- for (; accessor.end() != it; ++it) {
+ DataAccessor<ApplicationSet> accessor = application_manager_.applications();
+ ApplicationSetIt it = accessor.GetData().begin();
+ for (; accessor.GetData().end() != it; ++it) {
// if there is app with active perform interaction use it for notification
- if ((*it)->is_perform_interaction_active()) {
- LOG4CXX_INFO(logger_, "There is application with active PerformInteraction");
- app_to_notify = *it;
+ ApplicationSharedPtr app = *it;
+ if (app->is_perform_interaction_active()) {
+ LOG4CXX_INFO(logger_,
+ "There is application with active PerformInteraction");
+ app_to_notify = app;
break;
}
- if (mobile_apis::HMILevel::eType::HMI_FULL == (*it)->hmi_level()) {
+ if (mobile_apis::HMILevel::eType::HMI_FULL == app->hmi_level()) {
LOG4CXX_INFO(logger_, "There is application in HMI_FULL level");
- app_to_notify = *it;
+ app_to_notify = app;
}
}
if (app_to_notify.valid()) {
- (*message_)[strings::params][strings::connection_key] = app_to_notify->app_id();
+ (*message_)[strings::params][strings::connection_key] =
+ app_to_notify->app_id();
SendNotification();
}
}
diff --git a/src/components/application_manager/src/commands/mobile/on_language_change_notification.cc b/src/components/application_manager/src/commands/mobile/on_language_change_notification.cc
index 43b1b5b921..76420b85b6 100644
--- a/src/components/application_manager/src/commands/mobile/on_language_change_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_language_change_notification.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
OnLanguageChangeNotification::OnLanguageChangeNotification(
- const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
-OnLanguageChangeNotification::~OnLanguageChangeNotification() {
-}
+OnLanguageChangeNotification::~OnLanguageChangeNotification() {}
void OnLanguageChangeNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/mobile/on_permissions_change_notification.cc b/src/components/application_manager/src/commands/mobile/on_permissions_change_notification.cc
index 62ea1af1fc..a4167a802e 100644
--- a/src/components/application_manager/src/commands/mobile/on_permissions_change_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_permissions_change_notification.cc
@@ -40,12 +40,10 @@ namespace application_manager {
namespace commands {
OnPermissionsChangeNotification::OnPermissionsChangeNotification(
- const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
-OnPermissionsChangeNotification::~OnPermissionsChangeNotification() {
-}
+OnPermissionsChangeNotification::~OnPermissionsChangeNotification() {}
void OnPermissionsChangeNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/mobile/on_system_request_notification.cc b/src/components/application_manager/src/commands/mobile/on_system_request_notification.cc
index 166a4b7736..b42a6dc702 100644
--- a/src/components/application_manager/src/commands/mobile/on_system_request_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_system_request_notification.cc
@@ -36,8 +36,8 @@
#include "application_manager/commands/mobile/on_system_request_notification.h"
#include "interfaces/MOBILE_API.h"
#include "utils/file_system.h"
-#include "application_manager/application_manager_impl.h"
-#include "application_manager/policies/policy_handler.h"
+#include "application_manager/application_manager.h"
+#include "application_manager/policies/policy_handler_interface.h"
namespace application_manager {
@@ -46,8 +46,8 @@ namespace commands {
namespace mobile {
OnSystemRequestNotification::OnSystemRequestNotification(
- const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
OnSystemRequestNotification::~OnSystemRequestNotification() {}
@@ -56,8 +56,7 @@ void OnSystemRequestNotification::Run() {
using namespace application_manager;
using namespace mobile_apis;
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app.valid()) {
LOG4CXX_ERROR(logger_,
@@ -68,9 +67,10 @@ void OnSystemRequestNotification::Run() {
RequestType::eType request_type = static_cast<RequestType::eType>(
(*message_)[strings::msg_params][strings::request_type].asInt());
-
- if (!policy::PolicyHandler::instance()->IsRequestTypeAllowed(
- app->mobile_app_id(), request_type)) {
+ const policy::PolicyHandlerInterface& policy_handler =
+ application_manager_.GetPolicyHandler();
+ if (!policy_handler.IsRequestTypeAllowed(app->policy_app_id(),
+ request_type)) {
LOG4CXX_WARN(logger_,
"Request type " << request_type
<< " is not allowed by policies");
@@ -104,12 +104,16 @@ void OnSystemRequestNotification::Run() {
#ifdef EXTENDED_POLICY
void OnSystemRequestNotification::AddHeader(BinaryMessage& message) const {
LOG4CXX_AUTO_TRACE(logger_);
- const int timeout = policy::PolicyHandler::instance()->TimeoutExchange();
+ const int timeout = application_manager_.GetPolicyHandler().TimeoutExchange();
size_t content_length;
- char size_str[24];
- char timeout_str[24];
+ char size_str[24];
+
+ if (0 > sprintf(size_str, "%zu", static_cast<size_t>(message.size()))) {
+ memset(size_str, 0, sizeof(size_str));
+ }
+ char timeout_str[24];
if (0 > sprintf(timeout_str, "%d", timeout)) {
memset(timeout_str, 0, sizeof(timeout_str));
}
@@ -129,23 +133,29 @@ void OnSystemRequestNotification::AddHeader(BinaryMessage& message) const {
const std::string header =
- "{"
- " \"HTTPRequest\": {"
- "\"headers\": {"
- "\"ContentType\": \"application/json\","
- "\"ConnectTimeout\": " + std::string(timeout_str) + ","
- "\"DoOutput\": true,"
- "\"DoInput\": true,"
- "\"UseCaches\": false,"
- "\"RequestMethod\": \"POST\","
- "\"ReadTimeout\":" + std::string(timeout_str) + ","
- "\"InstanceFollowRedirects\": false,"
- "\"charset\": \"utf-8\","
- "\"Content-Length\": " + std::string(size_str) +
- "},"
- "\"body\": \"" + policy_table_string + "\""
+ "{"
+ " \"HTTPRequest\": {"
+ "\"headers\": {"
+ "\"ContentType\": \"application/json\","
+ "\"ConnectTimeout\": " +
+ std::string(timeout_str) +
+ ","
+ "\"DoOutput\": true,"
+ "\"DoInput\": true,"
+ "\"UseCaches\": false,"
+ "\"RequestMethod\": \"POST\","
+ "\"ReadTimeout\":" +
+ std::string(timeout_str) +
+ ","
+ "\"InstanceFollowRedirects\": false,"
+ "\"charset\": \"utf-8\","
+ "\"Content_-Length\": " +
+ std::string(size_str) +
+ "},"
+ "\"body\": \"" + policy_table_string +
+ "\""
"}"
- "}";
+ "}";
message.clear();
message.assign(header.begin(), header.end());
@@ -173,7 +183,7 @@ size_t OnSystemRequestNotification::ParsePTString(std::string& pt_string) const{
}
#endif
-} //namespace mobile
+} // namespace mobile
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/on_tbt_client_state_notification.cc b/src/components/application_manager/src/commands/mobile/on_tbt_client_state_notification.cc
index 99a5d665db..894469ac34 100644
--- a/src/components/application_manager/src/commands/mobile/on_tbt_client_state_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_tbt_client_state_notification.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/on_tbt_client_state_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
@@ -41,12 +41,10 @@ namespace application_manager {
namespace commands {
OnTBTClientStateNotification::OnTBTClientStateNotification(
- const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
-OnTBTClientStateNotification::~OnTBTClientStateNotification() {
-}
+OnTBTClientStateNotification::~OnTBTClientStateNotification() {}
void OnTBTClientStateNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -55,7 +53,7 @@ void OnTBTClientStateNotification::Run() {
static_cast<int32_t>(application_manager::MessageType::kNotification);
const std::vector<ApplicationSharedPtr>& applications =
- ApplicationManagerImpl::instance()->applications_with_navi();
+ application_manager_.applications_with_navi();
std::vector<ApplicationSharedPtr>::const_iterator it = applications.begin();
for (; applications.end() != it; ++it) {
diff --git a/src/components/application_manager/src/commands/mobile/on_touch_event_notification.cc b/src/components/application_manager/src/commands/mobile/on_touch_event_notification.cc
index 8780ab1b6a..c769194c95 100644
--- a/src/components/application_manager/src/commands/mobile/on_touch_event_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_touch_event_notification.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/on_touch_event_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
namespace application_manager {
@@ -42,18 +42,16 @@ namespace commands {
namespace mobile {
OnTouchEventNotification::OnTouchEventNotification(
- const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
-OnTouchEventNotification::~OnTouchEventNotification() {
-}
+OnTouchEventNotification::~OnTouchEventNotification() {}
void OnTouchEventNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
const std::vector<ApplicationSharedPtr>& applications =
- ApplicationManagerImpl::instance()->applications_with_navi();
+ application_manager_.applications_with_navi();
std::vector<ApplicationSharedPtr>::const_iterator it = applications.begin();
for (; applications.end() != it; ++it) {
diff --git a/src/components/application_manager/src/commands/mobile/on_vehicle_data_notification.cc b/src/components/application_manager/src/commands/mobile/on_vehicle_data_notification.cc
index 68755bef54..37abbab351 100644
--- a/src/components/application_manager/src/commands/mobile/on_vehicle_data_notification.cc
+++ b/src/components/application_manager/src/commands/mobile/on_vehicle_data_notification.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/on_vehicle_data_notification.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
#include "interfaces/MOBILE_API.h"
@@ -42,19 +42,17 @@ namespace application_manager {
namespace commands {
OnVehicleDataNotification::OnVehicleDataNotification(
- const MessageSharedPtr& message)
- : CommandNotificationImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
-OnVehicleDataNotification::~OnVehicleDataNotification() {
-}
+OnVehicleDataNotification::~OnVehicleDataNotification() {}
void OnVehicleDataNotification::Run() {
LOG4CXX_AUTO_TRACE(logger_);
std::vector<ApplicationSharedPtr> appNotification;
std::vector<ApplicationSharedPtr>::iterator appNotification_it =
- appNotification.begin();
+ appNotification.begin();
std::vector<smart_objects::SmartObject> appSO;
const VehicleData& vehicle_data = MessageHelper::vehicle_data();
@@ -63,39 +61,47 @@ void OnVehicleDataNotification::Run() {
for (; vehicle_data.end() != it; ++it) {
if (true == (*message_)[strings::msg_params].keyExists(it->first)) {
const std::vector<ApplicationSharedPtr>& applications =
- ApplicationManagerImpl::instance()->IviInfoUpdated(it->second,
- (*message_)[strings::msg_params][it->first].asInt());
+ application_manager_.IviInfoUpdated(
+ it->second, (*message_)[strings::msg_params][it->first].asInt());
+
+ std::vector<ApplicationSharedPtr>::const_iterator app_it =
+ applications.begin();
- std::vector<ApplicationSharedPtr>::const_iterator app_it = applications.begin();
for (; applications.end() != app_it; ++app_it) {
const ApplicationSharedPtr app = *app_it;
- DCHECK(app);
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "NULL pointer");
+ continue;
+ }
- appNotification_it = find(appNotification.begin(), appNotification.end(), app);
+ appNotification_it =
+ find(appNotification.begin(), appNotification.end(), app);
if (appNotification_it == appNotification.end()) {
appNotification.push_back(app);
- smart_objects::SmartObject msg_param = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_param =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_param[it->first] = (*message_)[strings::msg_params][it->first];
appSO.push_back(msg_param);
} else {
- size_t idx = std::distance(appNotification.begin(), appNotification_it);
+ size_t idx =
+ std::distance(appNotification.begin(), appNotification_it);
appSO[idx][it->first] = (*message_)[strings::msg_params][it->first];
}
}
}
}
- LOG4CXX_DEBUG(logger_, "Number of Notifications to be send: " <<
- appNotification.size());
+ LOG4CXX_DEBUG(
+ logger_,
+ "Number of Notifications to be send: " << appNotification.size());
for (size_t idx = 0; idx < appNotification.size(); idx++) {
- LOG4CXX_INFO(
- logger_,
- "Send OnVehicleData PRNDL notification to " << appNotification[idx]->name()
- << " application id " << appNotification[idx]->app_id());
+ LOG4CXX_INFO(logger_,
+ "Send OnVehicleData PRNDL notification to "
+ << appNotification[idx]->name().c_str()
+ << " application id " << appNotification[idx]->app_id());
(*message_)[strings::params][strings::connection_key] =
- appNotification[idx]->app_id();
+ appNotification[idx]->app_id();
(*message_)[strings::msg_params] = appSO[idx];
SendNotification();
}
diff --git a/src/components/application_manager/src/commands/mobile/on_way_point_change_notification.cc b/src/components/application_manager/src/commands/mobile/on_way_point_change_notification.cc
new file mode 100644
index 0000000000..0b24228810
--- /dev/null
+++ b/src/components/application_manager/src/commands/mobile/on_way_point_change_notification.cc
@@ -0,0 +1,61 @@
+/*
+
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/commands/mobile/on_way_point_change_notification.h"
+#include "application_manager/application_manager.h"
+
+namespace application_manager {
+namespace commands {
+
+OnWayPointChangeNotification::OnWayPointChangeNotification(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandNotificationImpl(message, application_manager) {}
+
+OnWayPointChangeNotification::~OnWayPointChangeNotification() {}
+
+void OnWayPointChangeNotification::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ std::set<int32_t> subscribed_for_way_points =
+ application_manager_.GetAppsSubscribedForWayPoints();
+
+ for (std::set<int32_t>::const_iterator app_id =
+ subscribed_for_way_points.begin();
+ app_id != subscribed_for_way_points.end();
+ ++app_id) {
+ (*message_)[strings::params][strings::connection_key] = *app_id;
+ SendNotification();
+ }
+}
+} // namespace commands
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/perform_audio_pass_thru_request.cc b/src/components/application_manager/src/commands/mobile/perform_audio_pass_thru_request.cc
index b1ac31b9d8..d595119d45 100644
--- a/src/components/application_manager/src/commands/mobile/perform_audio_pass_thru_request.cc
+++ b/src/components/application_manager/src/commands/mobile/perform_audio_pass_thru_request.cc
@@ -33,9 +33,10 @@
#include <cstring>
#include "application_manager/commands/mobile/perform_audio_pass_thru_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
+#include "utils/helpers.h"
namespace application_manager {
@@ -44,25 +45,19 @@ namespace commands {
namespace str = strings;
PerformAudioPassThruRequest::PerformAudioPassThruRequest(
- const MessageSharedPtr& message)
- : CommandRequestImpl(message),
- is_active_tts_speak_(false),
- result_tts_speak_(mobile_apis::Result::SUCCESS) {
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager)
+ , is_active_tts_speak_(false)
+ , result_tts_speak_(mobile_apis::Result::SUCCESS) {
subscribe_on_event(hmi_apis::FunctionID::TTS_OnResetTimeout);
}
-PerformAudioPassThruRequest::~PerformAudioPassThruRequest() {
-}
+PerformAudioPassThruRequest::~PerformAudioPassThruRequest() {}
void PerformAudioPassThruRequest::onTimeOut() {
LOG4CXX_AUTO_TRACE(logger_);
- if (ApplicationManagerImpl::instance()->end_audio_pass_thru()) {
- ApplicationManagerImpl::instance()->StopAudioPassThru(connection_key());
- }
-
FinishTTSSpeak();
-
CommandRequestImpl::onTimeOut();
}
@@ -75,8 +70,7 @@ bool PerformAudioPassThruRequest::Init() {
void PerformAudioPassThruRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
LOG4CXX_ERROR(logger_, "APPLICATION_NOT_REGISTERED");
@@ -92,7 +86,8 @@ void PerformAudioPassThruRequest::Run() {
if (IsWhiteSpaceExist()) {
LOG4CXX_ERROR(logger_,
- "Incoming perform audio pass thru has contains \\t\\n \\\\t \\\\n"
+ "Incoming perform audio pass thru has contains "
+ "\\t\\n \\\\t \\\\n"
" text contains only whitespace in initialPrompt");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
@@ -112,10 +107,18 @@ void PerformAudioPassThruRequest::Run() {
void PerformAudioPassThruRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
+
const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
case hmi_apis::FunctionID::UI_PerformAudioPassThru: {
+ LOG4CXX_TRACE(logger_, "Received UI_PerformAudioPassThru");
+
+ if (!WaitTTSSpeak()) {
+ LOG4CXX_DEBUG(logger_, "TTS.Speak is absent");
+ return;
+ }
mobile_apis::Result::eType mobile_code =
GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
@@ -128,47 +131,52 @@ void PerformAudioPassThruRequest::on_event(const event_engine::Event& event) {
return;
}
- if (ApplicationManagerImpl::instance()->end_audio_pass_thru()) {
- ApplicationManagerImpl::instance()->StopAudioPassThru(connection_key());
- }
-
FinishTTSSpeak();
std::string return_info;
- bool result = mobile_apis::Result::SUCCESS == mobile_code ||
- mobile_apis::Result::RETRY == mobile_code;
-
- if ((mobile_apis::Result::SUCCESS == mobile_code) &&
- (mobile_apis::Result::UNSUPPORTED_RESOURCE == result_tts_speak_)) {
+ const bool result = Compare<mobile_api::Result::eType, EQ, ONE>(
+ mobile_code,
+ mobile_apis::Result::SUCCESS,
+ mobile_apis::Result::RETRY,
+ mobile_apis::Result::WARNINGS);
+
+ const bool is_result_ok = Compare<mobile_api::Result::eType, EQ, ONE>(
+ mobile_code,
+ mobile_apis::Result::SUCCESS,
+ mobile_apis::Result::WARNINGS);
+
+ if (is_result_ok &&
+ mobile_apis::Result::UNSUPPORTED_RESOURCE == result_tts_speak_) {
mobile_code = mobile_apis::Result::WARNINGS;
return_info = "Unsupported phoneme type sent in a prompt";
}
- SendResponse(result, mobile_code, return_info.c_str(),
+ SendResponse(result,
+ mobile_code,
+ return_info.empty() ? NULL : return_info.c_str(),
&(message[strings::msg_params]));
break;
}
case hmi_apis::FunctionID::TTS_Speak: {
LOG4CXX_INFO(logger_, "Received TTS_Speak event");
- result_tts_speak_ = GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
- message[strings::params][hmi_response::code].asUInt()));
+ result_tts_speak_ =
+ GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asUInt()));
is_active_tts_speak_ = false;
if (mobile_apis::Result::SUCCESS == result_tts_speak_) {
SendRecordStartNotification();
StartMicrophoneRecording();
// update request timeout to get time for perform audio recording
- ApplicationManagerImpl::instance()->
- updateRequestTimeout(connection_key(),
- correlation_id(),
- default_timeout());
+ application_manager_.updateRequestTimeout(
+ connection_key(), correlation_id(), default_timeout());
}
break;
}
case hmi_apis::FunctionID::TTS_OnResetTimeout: {
LOG4CXX_INFO(logger_, "Received TTS_OnResetTimeout event");
- ApplicationManagerImpl::instance()->updateRequestTimeout(
+ application_manager_.updateRequestTimeout(
connection_key(), correlation_id(), default_timeout());
break;
}
@@ -180,7 +188,8 @@ void PerformAudioPassThruRequest::on_event(const event_engine::Event& event) {
}
void PerformAudioPassThruRequest::SendSpeakRequest() {
- // crate HMI TTS speak request
+ LOG4CXX_AUTO_TRACE(logger_);
+
using namespace hmi_apis;
using namespace smart_objects;
@@ -189,8 +198,8 @@ void PerformAudioPassThruRequest::SendSpeakRequest() {
if ((*message_)[str::msg_params].keyExists(str::initial_prompt) &&
(0 < (*message_)[str::msg_params][str::initial_prompt].length())) {
for (uint32_t i = 0;
- i < (*message_)[str::msg_params][str::initial_prompt].length();
- ++i) {
+ i < (*message_)[str::msg_params][str::initial_prompt].length();
+ ++i) {
msg_params[hmi_request::tts_chunks][i][str::text] =
(*message_)[str::msg_params][str::initial_prompt][i][str::text];
msg_params[hmi_request::tts_chunks][i][str::type] =
@@ -205,12 +214,13 @@ void PerformAudioPassThruRequest::SendSpeakRequest() {
}
void PerformAudioPassThruRequest::SendPerformAudioPassThruRequest() {
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[str::app_id] = connection_key();
- // duration
msg_params[hmi_request::max_duration] =
(*message_)[str::msg_params][str::max_duration];
@@ -218,21 +228,21 @@ void PerformAudioPassThruRequest::SendPerformAudioPassThruRequest() {
smart_objects::SmartObject(smart_objects::SmartType_Array);
if ((*message_)[str::msg_params].keyExists(str::audio_pass_display_text1)) {
- msg_params[hmi_request::audio_pass_display_texts]
- [0][hmi_request::field_name] = static_cast<int32_t>
- (hmi_apis::Common_TextFieldName::audioPassThruDisplayText1);
- msg_params[hmi_request::audio_pass_display_texts]
- [0][hmi_request::field_text] =
- (*message_)[str::msg_params][str::audio_pass_display_text1];
+ msg_params[hmi_request::audio_pass_display_texts][0]
+ [hmi_request::field_name] = static_cast<int32_t>(
+ hmi_apis::Common_TextFieldName::audioPassThruDisplayText1);
+ msg_params[hmi_request::audio_pass_display_texts][0]
+ [hmi_request::field_text] =
+ (*message_)[str::msg_params][str::audio_pass_display_text1];
}
if ((*message_)[str::msg_params].keyExists(str::audio_pass_display_text2)) {
- msg_params[hmi_request::audio_pass_display_texts]
- [1][hmi_request::field_name] = static_cast<int32_t>
- (hmi_apis::Common_TextFieldName::audioPassThruDisplayText2);
- msg_params[hmi_request::audio_pass_display_texts]
- [1][hmi_request::field_text] =
- (*message_)[str::msg_params][str::audio_pass_display_text2];
+ msg_params[hmi_request::audio_pass_display_texts][1]
+ [hmi_request::field_name] = static_cast<int32_t>(
+ hmi_apis::Common_TextFieldName::audioPassThruDisplayText2);
+ msg_params[hmi_request::audio_pass_display_texts][1]
+ [hmi_request::field_text] =
+ (*message_)[str::msg_params][str::audio_pass_display_text2];
}
if ((*message_)[str::msg_params].keyExists(str::mute_audio)) {
@@ -243,23 +253,28 @@ void PerformAudioPassThruRequest::SendPerformAudioPassThruRequest() {
msg_params[str::mute_audio] = true;
}
- SendHMIRequest(hmi_apis::FunctionID::UI_PerformAudioPassThru,
- &msg_params, true);
+ SendHMIRequest(
+ hmi_apis::FunctionID::UI_PerformAudioPassThru, &msg_params, true);
}
void PerformAudioPassThruRequest::SendRecordStartNotification() {
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::app_id] = connection_key();
CreateHMINotification(hmi_apis::FunctionID::UI_OnRecordStart, msg_params);
}
void PerformAudioPassThruRequest::StartMicrophoneRecording() {
- ApplicationManagerImpl::instance()->begin_audio_pass_thru();
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ application_manager_.BeginAudioPassThrough();
- ApplicationManagerImpl::instance()->StartAudioPassThruThread(
- connection_key(), correlation_id(),
+ application_manager_.StartAudioPassThruThread(
+ connection_key(),
+ correlation_id(),
(*message_)[str::msg_params][str::max_duration].asInt(),
(*message_)[str::msg_params][str::sampling_rate].asInt(),
(*message_)[str::msg_params][str::bits_per_sample].asInt(),
@@ -286,25 +301,25 @@ bool PerformAudioPassThruRequest::IsWhiteSpaceExist() {
}
}
- if ((*message_)[strings::msg_params].
- keyExists(strings::audio_pass_display_text1)) {
-
- str = (*message_)[strings::msg_params]
- [strings::audio_pass_display_text1].asCharArray();
+ if ((*message_)[strings::msg_params].keyExists(
+ strings::audio_pass_display_text1)) {
+ str = (*message_)[strings::msg_params][strings::audio_pass_display_text1]
+ .asCharArray();
if (!CheckSyntax(str)) {
- LOG4CXX_ERROR(logger_,
+ LOG4CXX_ERROR(
+ logger_,
"Invalid audio_pass_display_text1 value syntax check failed");
return true;
}
}
- if ((*message_)[strings::msg_params].
- keyExists(strings::audio_pass_display_text2)) {
-
- str = (*message_)[strings::msg_params]
- [strings::audio_pass_display_text2].asCharArray();
+ if ((*message_)[strings::msg_params].keyExists(
+ strings::audio_pass_display_text2)) {
+ str = (*message_)[strings::msg_params][strings::audio_pass_display_text2]
+ .asCharArray();
if (!CheckSyntax(str)) {
- LOG4CXX_ERROR(logger_,
+ LOG4CXX_ERROR(
+ logger_,
"Invalid audio_pass_display_text2 value syntax check failed");
return true;
}
@@ -312,11 +327,43 @@ bool PerformAudioPassThruRequest::IsWhiteSpaceExist() {
return false;
}
-void PerformAudioPassThruRequest::FinishTTSSpeak(){
- if (is_active_tts_speak_) {
- is_active_tts_speak_ = false;
- SendHMIRequest(hmi_apis::FunctionID::TTS_StopSpeaking, NULL);
+void PerformAudioPassThruRequest::FinishTTSSpeak() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (application_manager_.EndAudioPassThrough()) {
+ LOG4CXX_DEBUG(logger_, "Stop AudioPassThru.");
+ application_manager_.StopAudioPassThru(connection_key());
}
+ if (!is_active_tts_speak_) {
+ LOG4CXX_WARN(logger_, "TTS Speak is inactive.");
+ return;
+ }
+ is_active_tts_speak_ = false;
+ SendHMIRequest(hmi_apis::FunctionID::TTS_StopSpeaking, NULL);
+}
+
+bool PerformAudioPassThruRequest::WaitTTSSpeak() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ uint64_t default_timeout_msec =
+ application_manager_.get_settings().default_timeout();
+ const TimevalStruct start_time = date_time::DateTime::getCurrentTime();
+
+ // Waiting for TTS_Speak
+ while (is_active_tts_speak_) {
+ uint64_t difference_between_start_current_time =
+ date_time::DateTime::calculateTimeSpan(start_time);
+ // Send GENERIC_ERROR after default timeout
+ if (difference_between_start_current_time > default_timeout_msec) {
+ LOG4CXX_WARN(logger_, "Expired timeout for TTS.Speak response");
+ // Don't use onTimeOut(), because default_timeout_ is bigger than
+ // Default time in *.ini file
+ FinishTTSSpeak();
+ SendResponse(false,
+ mobile_apis::Result::eType::GENERIC_ERROR,
+ "Expired timeout for TTS.Speak response");
+ return false;
+ }
+ }
+ return true;
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/perform_audio_pass_thru_response.cc b/src/components/application_manager/src/commands/mobile/perform_audio_pass_thru_response.cc
index 585383889d..e8a638c076 100644
--- a/src/components/application_manager/src/commands/mobile/perform_audio_pass_thru_response.cc
+++ b/src/components/application_manager/src/commands/mobile/perform_audio_pass_thru_response.cc
@@ -32,25 +32,21 @@
*/
#include "application_manager/commands/mobile/perform_audio_pass_thru_response.h"
-#include "application_manager/application_manager_impl.h"
-
namespace application_manager {
namespace commands {
PerformAudioPassThruResponse::PerformAudioPassThruResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-PerformAudioPassThruResponse::~PerformAudioPassThruResponse() {
-}
+PerformAudioPassThruResponse::~PerformAudioPassThruResponse() {}
void PerformAudioPassThruResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/perform_interaction_request.cc b/src/components/application_manager/src/commands/mobile/perform_interaction_request.cc
index 54edc8e516..39ad51e822 100644
--- a/src/components/application_manager/src/commands/mobile/perform_interaction_request.cc
+++ b/src/components/application_manager/src/commands/mobile/perform_interaction_request.cc
@@ -1,6 +1,6 @@
/*
- Copyright (c) 2013, Ford Motor Company
+ Copyright (c) 2016, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -34,39 +34,44 @@
#include <string.h>
#include <string>
#include "application_manager/commands/mobile/perform_interaction_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
-#include "config_profile/profile.h"
+
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
#include "utils/file_system.h"
+#include "utils/helpers.h"
+#include "utils/custom_string.h"
+#include "utils/gen_hash.h"
namespace application_manager {
namespace commands {
+namespace custom_str = utils::custom_string;
+
uint32_t PerformInteractionRequest::pi_requests_count_ = 0;
PerformInteractionRequest::PerformInteractionRequest(
- const MessageSharedPtr& message)
-: CommandRequestImpl(message),
- vr_perform_interaction_code_(mobile_apis::Result::INVALID_ENUM),
- interaction_mode_(mobile_apis::InteractionMode::INVALID_ENUM),
- ui_response_recived_(false),
- vr_response_recived_(false),
- app_pi_was_active_before_(false) {
-
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager)
+ , interaction_mode_(mobile_apis::InteractionMode::INVALID_ENUM)
+ , ui_response_recived_(false)
+ , vr_response_recived_(false)
+ , ui_result_(false)
+ , vr_result_(false)
+ , app_pi_was_active_before_(false)
+ , vr_resultCode_(mobile_apis::Result::INVALID_ENUM)
+ , ui_resultCode_(mobile_apis::Result::INVALID_ENUM) {
subscribe_on_event(hmi_apis::FunctionID::UI_OnResetTimeout);
subscribe_on_event(hmi_apis::FunctionID::VR_OnCommand);
subscribe_on_event(hmi_apis::FunctionID::Buttons_OnButtonPress);
}
-PerformInteractionRequest::~PerformInteractionRequest() {
-}
+PerformInteractionRequest::~PerformInteractionRequest() {}
bool PerformInteractionRequest::Init() {
-
/* Timeout in milliseconds.
If omitted a standard value of 10000 milliseconds is used.*/
if ((*message_)[strings::msg_params].keyExists(strings::timeout)) {
@@ -87,8 +92,7 @@ bool PerformInteractionRequest::Init() {
void PerformInteractionRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
LOG4CXX_ERROR(logger_, "Application is not registered");
@@ -97,7 +101,7 @@ void PerformInteractionRequest::Run() {
}
if (app->is_perform_interaction_active()) {
- LOG4CXX_INFO(logger_, "Application has active PerformInteraction");
+ LOG4CXX_DEBUG(logger_, "Application has active PerformInteraction");
app_pi_was_active_before_ = true;
}
@@ -112,8 +116,9 @@ void PerformInteractionRequest::Run() {
if ((mobile_apis::InteractionMode::VR_ONLY == interaction_mode_) &&
(mobile_apis::LayoutMode::KEYBOARD == interaction_layout)) {
- LOG4CXX_ERROR_EXT(logger_, "PerformInteraction contains InteractionMode"
- "=VR_ONLY and interactionLayout=KEYBOARD");
+ LOG4CXX_ERROR(logger_,
+ "PerformInteraction contains InteractionMode"
+ "=VR_ONLY and interactionLayout=KEYBOARD");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
@@ -124,38 +129,41 @@ void PerformInteractionRequest::Run() {
if (0 == choice_set_id_list_length) {
if (mobile_apis::LayoutMode::KEYBOARD == interaction_layout) {
if (mobile_apis::InteractionMode::BOTH == interaction_mode_) {
- LOG4CXX_ERROR_EXT(logger_,"interactionChoiceSetIDList is empty,"
- " InteractionMode=BOTH and"
- " interactionLayout=KEYBOARD");
+ LOG4CXX_ERROR(logger_,
+ "interactionChoiceSetIDList is empty,"
+ " InteractionMode=BOTH and"
+ " interactionLayout=KEYBOARD");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
} else {
- LOG4CXX_ERROR_EXT(logger_,"interactionChoiceSetIDList is empty"
- " and interactionLayout!=KEYBOARD");
+ LOG4CXX_ERROR(logger_,
+ "interactionChoiceSetIDList is empty"
+ " and interactionLayout!=KEYBOARD");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
}
- if (msg_params.keyExists(strings::vr_help)) {
- if (mobile_apis::Result::SUCCESS != MessageHelper::VerifyImageVrHelpItems(
- msg_params[strings::vr_help], app)) {
- LOG4CXX_ERROR_EXT(
- logger_,
- "MessageHelper::VerifyImageVrHelpItems return INVALID_DATA!");
- SendResponse(false, mobile_apis::Result::INVALID_DATA);
- return;
- }
+ if (choice_set_id_list_length &&
+ (!CheckChoiceIDFromRequest(
+ app,
+ choice_set_id_list_length,
+ msg_params[strings::interaction_choice_set_id_list]))) {
+ LOG4CXX_ERROR(logger_,
+ "PerformInteraction has choice sets with "
+ "duplicated IDs or application does not have choice sets");
+ SendResponse(false, mobile_apis::Result::INVALID_ID);
+ return;
}
- smart_objects::SmartObject& choice_list =
- msg_params[strings::interaction_choice_set_id_list];
-
- for (size_t i = 0; i < choice_list.length(); ++i) {
- if (!app->FindChoiceSet(choice_list[i].asInt())) {
- LOG4CXX_ERROR(logger_, "Invalid ID");
- SendResponse(false, mobile_apis::Result::INVALID_ID);
+ if (msg_params.keyExists(strings::vr_help)) {
+ if (mobile_apis::Result::SUCCESS !=
+ MessageHelper::VerifyImageVrHelpItems(
+ msg_params[strings::vr_help], app, application_manager_)) {
+ LOG4CXX_ERROR(logger_,
+ "Verification of " << strings::vr_help << " failed.");
+ SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
}
@@ -169,27 +177,24 @@ void PerformInteractionRequest::Run() {
switch (interaction_mode_) {
case mobile_apis::InteractionMode::BOTH: {
- LOG4CXX_INFO(logger_, "Interaction Mode: BOTH");
- if (!CheckChoiceSetVRSynonyms(app) ||
- !CheckChoiceSetMenuNames(app) ||
+ LOG4CXX_DEBUG(logger_, "Interaction Mode: BOTH");
+ if (!CheckChoiceSetVRSynonyms(app) || !CheckChoiceSetMenuNames(app) ||
!CheckVrHelpItemPositions(app)) {
return;
}
break;
}
case mobile_apis::InteractionMode::MANUAL_ONLY: {
- LOG4CXX_INFO(logger_, "Interaction Mode: MANUAL_ONLY");
- if (!CheckChoiceSetVRSynonyms(app) ||
- !CheckChoiceSetMenuNames(app) ||
+ LOG4CXX_DEBUG(logger_, "Interaction Mode: MANUAL_ONLY");
+ if (!CheckChoiceSetVRSynonyms(app) || !CheckChoiceSetMenuNames(app) ||
!CheckVrHelpItemPositions(app)) {
return;
}
break;
}
case mobile_apis::InteractionMode::VR_ONLY: {
- LOG4CXX_INFO(logger_, "Interaction Mode: VR_ONLY");
- if (!CheckChoiceSetVRSynonyms(app) ||
- !CheckVrHelpItemPositions(app)) {
+ LOG4CXX_DEBUG(logger_, "Interaction Mode: VR_ONLY");
+ if (!CheckChoiceSetVRSynonyms(app) || !CheckVrHelpItemPositions(app)) {
return;
}
break;
@@ -210,25 +215,35 @@ void PerformInteractionRequest::Run() {
void PerformInteractionRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
+ const smart_objects::SmartObject& message = event.smart_object();
+ smart_objects::SmartObject msg_param =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
switch (event.id()) {
case hmi_apis::FunctionID::UI_OnResetTimeout: {
- LOG4CXX_INFO(logger_, "Received UI_OnResetTimeout event");
- ApplicationManagerImpl::instance()->updateRequestTimeout(connection_key(),
- correlation_id(),
- default_timeout());
+ LOG4CXX_DEBUG(logger_, "Received UI_OnResetTimeout event");
+ application_manager_.updateRequestTimeout(
+ connection_key(), correlation_id(), default_timeout());
break;
}
case hmi_apis::FunctionID::UI_PerformInteraction: {
- LOG4CXX_INFO(logger_, "Received UI_PerformInteraction event");
+ LOG4CXX_DEBUG(logger_, "Received UI_PerformInteraction event");
ui_response_recived_ = true;
- ProcessPerformInteractionResponse(event.smart_object());
+ unsubscribe_from_event(hmi_apis::FunctionID::UI_PerformInteraction);
+ ui_resultCode_ =
+ GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asUInt()));
+ ProcessPerformInteractionResponse(event.smart_object(), msg_param);
break;
}
case hmi_apis::FunctionID::VR_PerformInteraction: {
- LOG4CXX_INFO(logger_, "Received VR_PerformInteraction");
+ LOG4CXX_DEBUG(logger_, "Received VR_PerformInteraction");
vr_response_recived_ = true;
- ProcessVRResponse(event.smart_object());
+ unsubscribe_from_event(hmi_apis::FunctionID::VR_PerformInteraction);
+ vr_resultCode_ =
+ GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asUInt()));
+ ProcessVRResponse(event.smart_object(), msg_param);
break;
}
default: {
@@ -236,6 +251,12 @@ void PerformInteractionRequest::on_event(const event_engine::Event& event) {
break;
}
}
+
+ if (mobile_apis::InteractionMode::BOTH == interaction_mode_ &&
+ !HasHMIResponsesToWait()) {
+ LOG4CXX_DEBUG(logger_, "Send response in BOTH iteraction mode");
+ SendBothModeResponse(msg_param);
+ }
}
void PerformInteractionRequest::onTimeOut() {
@@ -248,16 +269,14 @@ void PerformInteractionRequest::onTimeOut() {
DisablePerformInteraction();
CommandRequestImpl::onTimeOut();
} else {
- ApplicationManagerImpl::instance()->updateRequestTimeout(connection_key(),
- correlation_id(),
- default_timeout());
+ application_manager_.updateRequestTimeout(
+ connection_key(), correlation_id(), default_timeout());
}
break;
}
case mobile_apis::InteractionMode::VR_ONLY: {
- ApplicationManagerImpl::instance()->updateRequestTimeout(connection_key(),
- correlation_id(),
- default_timeout());
+ application_manager_.updateRequestTimeout(
+ connection_key(), correlation_id(), default_timeout());
break;
}
case mobile_apis::InteractionMode::MANUAL_ONLY: {
@@ -273,155 +292,160 @@ void PerformInteractionRequest::onTimeOut() {
};
}
-
void PerformInteractionRequest::ProcessVRResponse(
- const smart_objects::SmartObject& message) {
+ const smart_objects::SmartObject& message,
+ smart_objects::SmartObject& msg_params) {
LOG4CXX_AUTO_TRACE(logger_);
using namespace mobile_apis;
using namespace mobile_apis::Result;
using namespace smart_objects;
+ using namespace helpers;
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
- if (!app.get()) {
+ if (!app) {
LOG4CXX_ERROR(logger_, "NULL pointer");
return;
}
- vr_perform_interaction_code_ = static_cast<eType>(
- message[strings::params][hmi_response::code].asInt());
- if (ABORTED == vr_perform_interaction_code_ ||
- TIMED_OUT == vr_perform_interaction_code_) {
- LOG4CXX_INFO(logger_, "VR response aborted");
+ CheckResponseResultCode();
+ msg_params[strings::trigger_source] =
+ static_cast<int32_t>(TriggerSource::TS_VR);
+
+ const bool is_vr_aborted_timeout =
+ Compare<Result::eType, EQ, ONE>(vr_resultCode_, ABORTED, TIMED_OUT);
+
+ if (is_vr_aborted_timeout) {
+ LOG4CXX_DEBUG(logger_, "VR response aborted");
if (InteractionMode::VR_ONLY == interaction_mode_) {
- LOG4CXX_INFO(logger_, "Aborted or Timeout Send Close Popup");
+ LOG4CXX_DEBUG(logger_, "Aborted or Timeout Send Close Popup");
TerminatePerformInteraction();
- SendResponse(false, vr_perform_interaction_code_);
- return;
- } else {
- LOG4CXX_INFO(logger_, "Update timeout for UI");
- ApplicationManagerImpl::instance()->
- updateRequestTimeout(connection_key(),
- correlation_id(),
- default_timeout());
+ SendResponse(false, vr_resultCode_);
return;
}
- }
-
- if (REJECTED == vr_perform_interaction_code_) {
- LOG4CXX_INFO(logger_, "VR had been rejected.");
- TerminatePerformInteraction();
- SendResponse(false, vr_perform_interaction_code_);
+ LOG4CXX_DEBUG(logger_, "Update timeout for UI");
+ application_manager_.updateRequestTimeout(
+ connection_key(), correlation_id(), default_timeout());
return;
}
- if (SUCCESS == vr_perform_interaction_code_ &&
+ if (SUCCESS == vr_resultCode_ &&
InteractionMode::MANUAL_ONLY == interaction_mode_) {
- LOG4CXX_INFO(logger_, "VR response SUCCESS in MANUAL_ONLY mode " <<
- "Wait for UI response");
+ LOG4CXX_DEBUG(logger_,
+ "VR response SUCCESS in MANUAL_ONLY mode "
+ << "Wait for UI response");
// in case MANUAL_ONLY mode VR.PI SUCCESS just return
return;
}
- SmartObject msg_params = SmartObject(SmartType_Map);
- SmartObject* ptr_msg_params = NULL;
- if (message[strings::msg_params].keyExists(strings::choice_id)) {
- if (CheckChoiceIDFromResponse(
- app, message[strings::msg_params][strings::choice_id].asInt())) {
- msg_params[strings::choice_id] =
- message[strings::msg_params][strings::choice_id].asInt();
- ptr_msg_params = &msg_params;
- } else {
+ const SmartObject& hmi_msg_params = message[strings::msg_params];
+ if (hmi_msg_params.keyExists(strings::choice_id)) {
+ const int choise_id = hmi_msg_params[strings::choice_id].asInt();
+ if (!CheckChoiceIDFromResponse(app, choise_id)) {
LOG4CXX_ERROR(logger_, "Wrong choiceID was received from HMI");
TerminatePerformInteraction();
- SendResponse(false, GENERIC_ERROR,"Wrong choiceID was received from HMI");
+ SendResponse(
+ false, GENERIC_ERROR, "Wrong choiceID was received from HMI");
return;
}
+ msg_params[strings::choice_id] = choise_id;
}
- eType result_code = INVALID_ENUM;
+ vr_result_ = true;
- if (UNSUPPORTED_RESOURCE == vr_perform_interaction_code_) {
- LOG4CXX_INFO(logger_, "VR response WARNINGS");
- result_code = WARNINGS;
- } else {
- LOG4CXX_INFO(logger_, "VR response SUCCESS");
- result_code = SUCCESS;
- msg_params[strings::trigger_source] =
- static_cast<int32_t>(TriggerSource::TS_VR);
- ptr_msg_params = &msg_params;
+ if (mobile_apis::InteractionMode::BOTH == interaction_mode_ &&
+ mobile_apis::Result::SUCCESS != vr_resultCode_) {
+ LOG4CXX_DEBUG(logger_, "VR response isn't SUCCESS in BOTH mode");
+ return;
}
+
+ LOG4CXX_DEBUG(logger_, "VR response consider to be SUCCESS");
TerminatePerformInteraction();
- SendResponse(true, result_code, NULL, ptr_msg_params);
+ SendResponse(vr_result_, SUCCESS, NULL, &msg_params);
}
void PerformInteractionRequest::ProcessPerformInteractionResponse(
- const smart_objects::SmartObject& message) {
+ const smart_objects::SmartObject& message,
+ smart_objects::SmartObject& msg_params) {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
+ using namespace smart_objects;
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
- if (!app.get()) {
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
+ if (!app) {
LOG4CXX_ERROR(logger_, "NULL pointer");
return;
}
- bool result = false;
- std::string info;
-
- smart_objects::SmartObject msg_params =
- smart_objects::SmartObject(smart_objects::SmartType_Map);
+ ui_result_ = Compare<mobile_api::Result::eType, EQ, ONE>(
+ ui_resultCode_,
+ mobile_apis::Result::SUCCESS,
+ mobile_apis::Result::WARNINGS,
+ mobile_apis::Result::UNSUPPORTED_RESOURCE);
- mobile_apis::Result::eType result_code =
- GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
- message[strings::params][hmi_response::code].asUInt()));
+ const bool is_pi_warning = Compare<mobile_api::Result::eType, EQ, ONE>(
+ ui_resultCode_, mobile_apis::Result::WARNINGS);
- if (mobile_apis::Result::SUCCESS == result_code) {
- result = true;
- }
+ const bool is_pi_unsupported = Compare<mobile_api::Result::eType, EQ, ONE>(
+ ui_resultCode_, mobile_apis::Result::UNSUPPORTED_RESOURCE);
- if (mobile_apis::Result::UNSUPPORTED_RESOURCE == result_code) {
- result = true;
- result_code = mobile_apis::Result::WARNINGS;
- info = "Unsupported phoneme type was sent in an item";
- }
+ std::string info;
- if (result) {
+ if (ui_result_) {
+ if (is_pi_warning) {
+ ui_resultCode_ = mobile_apis::Result::WARNINGS;
+ info = "Unsupported phoneme type was sent in an item";
+ if (message.keyExists(strings::params) &&
+ message[strings::params].keyExists(strings::data)) {
+ msg_params = message[strings::params][strings::data];
+ }
+ } else if (is_pi_unsupported) {
+ ui_resultCode_ = mobile_apis::Result::UNSUPPORTED_RESOURCE;
+ info = "Unsupported phoneme type was sent in an item";
+ } else if (message.keyExists(strings::msg_params)) {
+ msg_params = message[strings::msg_params];
+ }
// result code must be GENERIC_ERROR in case wrong choice_id
- if (message[strings::msg_params].keyExists(strings::choice_id)) {
- if (!CheckChoiceIDFromResponse(app, message[strings::msg_params]
- [strings::choice_id].asInt())) {
- result_code = mobile_apis::Result::GENERIC_ERROR;
+ if (msg_params.keyExists(strings::choice_id)) {
+ if (!CheckChoiceIDFromResponse(app,
+ msg_params[strings::choice_id].asInt())) {
+ ui_resultCode_ = mobile_apis::Result::GENERIC_ERROR;
info = "Wrong choiceID was received from HMI";
} else {
- msg_params = message[strings::msg_params];
- msg_params[strings::trigger_source] = mobile_apis::TriggerSource::TS_MENU;
+ msg_params[strings::trigger_source] =
+ mobile_apis::TriggerSource::TS_MENU;
+ }
+ } else if (msg_params.keyExists(strings::manual_text_entry)) {
+ msg_params[strings::trigger_source] =
+ mobile_apis::TriggerSource::TS_KEYBOARD;
+ if (msg_params[strings::manual_text_entry].empty()) {
+ msg_params.erase(strings::manual_text_entry);
}
- } else if (message[strings::msg_params].keyExists(strings::manual_text_entry)) {
- msg_params = message[strings::msg_params];
- msg_params[strings::trigger_source] = mobile_apis::TriggerSource::TS_KEYBOARD;
}
}
DisablePerformInteraction();
- const char* return_info = (info.empty()) ? NULL : info.c_str();
- const smart_objects::SmartObject* response_params = (msg_params.empty()) ? NULL : &msg_params;
- SendResponse(result, result_code, return_info, response_params);
+ const SmartObject* response_params = msg_params.empty() ? NULL : &msg_params;
+
+ if (mobile_apis::InteractionMode::BOTH != interaction_mode_) {
+ DisablePerformInteraction();
+ SendResponse(ui_result_, ui_resultCode_, info.c_str(), response_params);
+ }
}
void PerformInteractionRequest::SendUIPerformInteractionRequest(
application_manager::ApplicationSharedPtr const app) {
+ LOG4CXX_AUTO_TRACE(logger_);
smart_objects::SmartObject& choice_set_id_list =
(*message_)[strings::msg_params][strings::interaction_choice_set_id_list];
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
- mobile_apis::InteractionMode::eType mode =
+ mobile_apis::InteractionMode::eType mode =
static_cast<mobile_apis::InteractionMode::eType>(
- (*message_)[strings::msg_params][strings::interaction_mode].asInt());
+ (*message_)[strings::msg_params][strings::interaction_mode].asInt());
if (mobile_apis::InteractionMode::VR_ONLY != mode) {
msg_params[hmi_request::initial_text][hmi_request::field_name] =
@@ -443,24 +467,23 @@ void PerformInteractionRequest::SendUIPerformInteractionRequest(
if (mobile_apis::InteractionMode::BOTH == mode ||
mobile_apis::InteractionMode::MANUAL_ONLY == mode) {
- msg_params[strings::timeout] = default_timeout_/2;
+ msg_params[strings::timeout] = default_timeout_ / 2;
} else {
msg_params[strings::timeout] = default_timeout_;
}
msg_params[strings::app_id] = app->app_id();
if (mobile_apis::InteractionMode::VR_ONLY != mode) {
- msg_params[strings::choice_set] = smart_objects::SmartObject(
- smart_objects::SmartType_Array);
+ msg_params[strings::choice_set] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
}
int32_t index_array_of_vr_help = 0;
for (size_t i = 0; i < choice_set_id_list.length(); ++i) {
- smart_objects::SmartObject* choice_set = app->FindChoiceSet(
- choice_set_id_list[i].asInt());
+ smart_objects::SmartObject* choice_set =
+ app->FindChoiceSet(choice_set_id_list[i].asInt());
if (choice_set) {
// save perform interaction choice set
- app->AddPerformInteractionChoiceSet(correlation_id(),
- choice_set_id_list[i].asInt(),
- *choice_set);
+ app->AddPerformInteractionChoiceSet(
+ correlation_id(), choice_set_id_list[i].asInt(), *choice_set);
for (size_t j = 0; j < (*choice_set)[strings::choice_set].length(); ++j) {
if (mobile_apis::InteractionMode::VR_ONLY != mode) {
size_t index = msg_params[strings::choice_set].length();
@@ -469,8 +492,8 @@ void PerformInteractionRequest::SendUIPerformInteractionRequest(
// vrCommands should be added via VR.AddCommand only
msg_params[strings::choice_set][index].erase(strings::vr_commands);
}
- if (mobile_apis::InteractionMode::MANUAL_ONLY !=
- mode && !is_vr_help_item) {
+ if (mobile_apis::InteractionMode::MANUAL_ONLY != mode &&
+ !is_vr_help_item) {
smart_objects::SmartObject& vr_commands =
(*choice_set)[strings::choice_set][j][strings::vr_commands];
if (0 < vr_commands.length()) {
@@ -484,32 +507,31 @@ void PerformInteractionRequest::SendUIPerformInteractionRequest(
}
}
}
- if ((*message_)[strings::msg_params]
- .keyExists(hmi_request::interaction_layout)
- && mobile_apis::InteractionMode::VR_ONLY != mode) {
+ if ((*message_)[strings::msg_params].keyExists(
+ hmi_request::interaction_layout) &&
+ mobile_apis::InteractionMode::VR_ONLY != mode) {
msg_params[hmi_request::interaction_layout] =
- (*message_)[strings::msg_params][hmi_request::interaction_layout].
- asInt();
+ (*message_)[strings::msg_params][hmi_request::interaction_layout]
+ .asInt();
}
- CreateUIPerformInteraction(msg_params, app);
-}
-
-void PerformInteractionRequest::CreateUIPerformInteraction(
- const smart_objects::SmartObject& msg_params,
- application_manager::ApplicationSharedPtr const app) {
- SendHMIRequest(hmi_apis::FunctionID::UI_PerformInteraction,
- &msg_params, true);
+ SendHMIRequest(
+ hmi_apis::FunctionID::UI_PerformInteraction, &msg_params, true);
}
void PerformInteractionRequest::SendVRPerformInteractionRequest(
application_manager::ApplicationSharedPtr const app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
smart_objects::SmartObject msg_params =
smart_objects::SmartObject(smart_objects::SmartType_Map);
+
smart_objects::SmartObject& choice_list =
- (*message_)[strings::msg_params][strings::interaction_choice_set_id_list];
+ (*message_)[strings::msg_params][strings::interaction_choice_set_id_list];
if (mobile_apis::InteractionMode::MANUAL_ONLY != interaction_mode_) {
- msg_params[strings::grammar_id] = smart_objects::SmartObject(smart_objects::SmartType_Array);
+ msg_params[strings::grammar_id] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+
int32_t grammar_id_index = 0;
for (uint32_t i = 0; i < choice_list.length(); ++i) {
smart_objects::SmartObject* choice_set =
@@ -518,16 +540,14 @@ void PerformInteractionRequest::SendVRPerformInteractionRequest(
LOG4CXX_WARN(logger_, "Couldn't found choiset");
continue;
}
- msg_params[strings::grammar_id][grammar_id_index++]=
+ msg_params[strings::grammar_id][grammar_id_index++] =
(*choice_set)[strings::grammar_id].asUInt();
}
}
if ((*message_)[strings::msg_params].keyExists(strings::help_prompt)) {
-
msg_params[strings::help_prompt] =
(*message_)[strings::msg_params][strings::help_prompt];
-
} else {
if (choice_list.length() != 0) {
msg_params[strings::help_prompt] =
@@ -539,9 +559,8 @@ void PerformInteractionRequest::SendVRPerformInteractionRequest(
app->FindChoiceSet(choice_list[i].asInt());
if (choice_set) {
- for (uint32_t j = 0;
- j < (*choice_set)[strings::choice_set].length();
- ++j) {
+ for (uint32_t j = 0; j < (*choice_set)[strings::choice_set].length();
+ ++j) {
smart_objects::SmartObject& vr_commands =
(*choice_set)[strings::choice_set][j][strings::vr_commands];
if (0 < vr_commands.length()) {
@@ -550,8 +569,9 @@ void PerformInteractionRequest::SendVRPerformInteractionRequest(
// Since there is no custom data from application side, SDL should
// construct prompt and append delimiter to each item
item[strings::type] = hmi_apis::Common_SpeechCapabilities::SC_TEXT;
- item[strings::text] = vr_commands[0].asString() +
- profile::Profile::instance()->tts_delimiter();
+ item[strings::text] =
+ vr_commands[0].asString() +
+ application_manager_.get_settings().tts_delimiter();
msg_params[strings::help_prompt][index++] = item;
}
}
@@ -563,7 +583,7 @@ void PerformInteractionRequest::SendVRPerformInteractionRequest(
if ((*message_)[strings::msg_params].keyExists(strings::timeout_prompt)) {
msg_params[strings::timeout_prompt] =
- (*message_)[strings::msg_params][strings::timeout_prompt];
+ (*message_)[strings::msg_params][strings::timeout_prompt];
} else {
if (msg_params.keyExists(strings::help_prompt)) {
msg_params[strings::timeout_prompt] = msg_params[strings::help_prompt];
@@ -571,38 +591,40 @@ void PerformInteractionRequest::SendVRPerformInteractionRequest(
}
if ((*message_)[strings::msg_params].keyExists(strings::initial_prompt)) {
- msg_params[strings::initial_prompt] =
- (*message_)[strings::msg_params][strings::initial_prompt];
+ msg_params[strings::initial_prompt] =
+ (*message_)[strings::msg_params][strings::initial_prompt];
}
mobile_apis::InteractionMode::eType mode =
static_cast<mobile_apis::InteractionMode::eType>(
- (*message_)[strings::msg_params][strings::interaction_mode].asInt());
+ (*message_)[strings::msg_params][strings::interaction_mode].asInt());
if (mobile_apis::InteractionMode::BOTH == mode ||
mobile_apis::InteractionMode::MANUAL_ONLY == mode) {
- msg_params[strings::timeout] = default_timeout_/2;
+ msg_params[strings::timeout] = default_timeout_ / 2;
} else {
msg_params[strings::timeout] = default_timeout_;
}
-
- SendHMIRequest(hmi_apis::FunctionID::VR_PerformInteraction, &msg_params,
- true);
+ msg_params[strings::app_id] = app->app_id();
+ SendHMIRequest(
+ hmi_apis::FunctionID::VR_PerformInteraction, &msg_params, true);
}
bool PerformInteractionRequest::CheckChoiceSetMenuNames(
application_manager::ApplicationSharedPtr const app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
smart_objects::SmartObject& choice_list =
(*message_)[strings::msg_params][strings::interaction_choice_set_id_list];
for (size_t i = 0; i < choice_list.length(); ++i) {
// choice_set contains SmartObject msg_params
- smart_objects::SmartObject* i_choice_set = app->FindChoiceSet(
- choice_list[i].asInt());
+ smart_objects::SmartObject* i_choice_set =
+ app->FindChoiceSet(choice_list[i].asInt());
for (size_t j = 0; j < choice_list.length(); ++j) {
- smart_objects::SmartObject* j_choice_set = app->FindChoiceSet(
- choice_list[j].asInt());
+ smart_objects::SmartObject* j_choice_set =
+ app->FindChoiceSet(choice_list[j].asInt());
if (i == j) {
// skip check the same element
@@ -619,16 +641,17 @@ bool PerformInteractionRequest::CheckChoiceSetMenuNames(
size_t jj = 0;
for (; ii < (*i_choice_set)[strings::choice_set].length(); ++ii) {
for (; jj < (*j_choice_set)[strings::choice_set].length(); ++jj) {
- std::string ii_menu_name =
+ const std::string& ii_menu_name =
(*i_choice_set)[strings::choice_set][ii][strings::menu_name]
.asString();
- std::string jj_menu_name =
+ const std::string& jj_menu_name =
(*j_choice_set)[strings::choice_set][jj][strings::menu_name]
.asString();
if (ii_menu_name == jj_menu_name) {
LOG4CXX_ERROR(logger_, "Choice set has duplicated menu name");
- SendResponse(false, mobile_apis::Result::DUPLICATE_NAME,
+ SendResponse(false,
+ mobile_apis::Result::DUPLICATE_NAME,
"Choice set has duplicated menu name");
return false;
}
@@ -642,17 +665,19 @@ bool PerformInteractionRequest::CheckChoiceSetMenuNames(
bool PerformInteractionRequest::CheckChoiceSetVRSynonyms(
application_manager::ApplicationSharedPtr const app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
smart_objects::SmartObject& choice_list =
(*message_)[strings::msg_params][strings::interaction_choice_set_id_list];
for (size_t i = 0; i < choice_list.length(); ++i) {
// choice_set contains SmartObject msg_params
- smart_objects::SmartObject* i_choice_set = app->FindChoiceSet(
- choice_list[i].asInt());
+ smart_objects::SmartObject* i_choice_set =
+ app->FindChoiceSet(choice_list[i].asInt());
for (size_t j = 0; j < choice_list.length(); ++j) {
- smart_objects::SmartObject* j_choice_set = app->FindChoiceSet(
- choice_list[j].asInt());
+ smart_objects::SmartObject* j_choice_set =
+ app->FindChoiceSet(choice_list[j].asInt());
if (i == j) {
// skip check the same element
@@ -678,11 +703,14 @@ bool PerformInteractionRequest::CheckChoiceSetVRSynonyms(
for (size_t iii = 0; iii < ii_vr_commands.length(); ++iii) {
for (size_t jjj = 0; jjj < jj_vr_commands.length(); ++jjj) {
- std::string vr_cmd_i = ii_vr_commands[iii].asString();
- std::string vr_cmd_j = jj_vr_commands[jjj].asString();
- if (0 == strcasecmp(vr_cmd_i.c_str(), vr_cmd_j.c_str())) {
+ const custom_str::CustomString& vr_cmd_i =
+ ii_vr_commands[iii].asCustomString();
+ const custom_str::CustomString& vr_cmd_j =
+ jj_vr_commands[jjj].asCustomString();
+ if (vr_cmd_i.CompareIgnoreCase(vr_cmd_j)) {
LOG4CXX_ERROR(logger_, "Choice set has duplicated VR synonym");
- SendResponse(false, mobile_apis::Result::DUPLICATE_NAME,
+ SendResponse(false,
+ mobile_apis::Result::DUPLICATE_NAME,
"Choice set has duplicated VR synonym");
return false;
}
@@ -692,16 +720,15 @@ bool PerformInteractionRequest::CheckChoiceSetVRSynonyms(
}
}
}
-
return true;
}
bool PerformInteractionRequest::CheckVrHelpItemPositions(
application_manager::ApplicationSharedPtr const app) {
+ LOG4CXX_AUTO_TRACE(logger_);
if (!(*message_)[strings::msg_params].keyExists(strings::vr_help)) {
- LOG4CXX_INFO(logger_, ""
- "PerformInteractionRequest::CheckVrHelpItemPositions vr_help omitted");
+ LOG4CXX_DEBUG(logger_, strings::vr_help << " is omitted.");
return true;
}
@@ -712,7 +739,8 @@ bool PerformInteractionRequest::CheckVrHelpItemPositions(
for (size_t i = 0; i < vr_help.length(); ++i) {
if (position != vr_help[i][strings::position].asInt()) {
LOG4CXX_ERROR(logger_, "Non-sequential vrHelp item position");
- SendResponse(false, mobile_apis::Result::REJECTED,
+ SendResponse(false,
+ mobile_apis::Result::REJECTED,
"Non-sequential vrHelp item position");
return false;
}
@@ -722,8 +750,9 @@ bool PerformInteractionRequest::CheckVrHelpItemPositions(
}
void PerformInteractionRequest::DisablePerformInteraction() {
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
LOG4CXX_ERROR(logger_, "NULL pointer");
return;
@@ -750,7 +779,6 @@ bool PerformInteractionRequest::IsWhiteSpaceExist() {
return true;
}
-
if ((*message_)[strings::msg_params].keyExists(strings::initial_prompt)) {
const smart_objects::SmartArray* ip_array =
(*message_)[strings::msg_params][strings::initial_prompt].asArray();
@@ -827,8 +855,10 @@ bool PerformInteractionRequest::IsWhiteSpaceExist() {
}
void PerformInteractionRequest::TerminatePerformInteraction() {
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[hmi_request::method_name] = "UI.PerformInteraction";
SendHMIRequest(hmi_apis::FunctionID::UI_ClosePopUp, &msg_params);
DisablePerformInteraction();
@@ -847,8 +877,8 @@ bool PerformInteractionRequest::CheckChoiceIDFromResponse(
const PerformChoice& choice = choice_set_map_it->second;
PerformChoice::const_iterator it = choice.begin();
for (; choice.end() != it; ++it) {
- const smart_objects::SmartObject& choice_set = (*it->second).getElement(
- strings::choice_set);
+ const smart_objects::SmartObject& choice_set =
+ (*it->second).getElement(strings::choice_set);
for (size_t j = 0; j < choice_set.length(); ++j) {
if (choice_id ==
choice_set.getElement(j).getElement(strings::choice_id).asInt()) {
@@ -860,6 +890,101 @@ bool PerformInteractionRequest::CheckChoiceIDFromResponse(
return false;
}
+bool PerformInteractionRequest::CheckChoiceIDFromRequest(
+ ApplicationSharedPtr app,
+ const size_t choice_set_id_list_length,
+ const smart_objects::SmartObject& choice_set_id_list) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ size_t choice_list_length = 0;
+ std::set<uint32_t> choice_id_set;
+ smart_objects::SmartObject* choice_set = 0;
+ std::pair<std::set<uint32_t>::iterator, bool> ins_res;
+
+ for (size_t i = 0; i < choice_set_id_list_length; ++i) {
+ choice_set = app->FindChoiceSet(choice_set_id_list[i].asInt());
+ if (!choice_set) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Couldn't find choiset_id = " << choice_set_id_list[i].asInt());
+ return false;
+ }
+ choice_list_length = (*choice_set)[strings::choice_set].length();
+ const smart_objects::SmartObject& choices_list =
+ (*choice_set)[strings::choice_set];
+ for (size_t k = 0; k < choice_list_length; ++k) {
+ ins_res =
+ choice_id_set.insert(choices_list[k][strings::choice_id].asInt());
+ if (!ins_res.second) {
+ LOG4CXX_ERROR(logger_,
+ "Choise with ID "
+ << choices_list[k][strings::choice_id].asInt()
+ << " already exists");
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+const bool PerformInteractionRequest::HasHMIResponsesToWait() const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ return !ui_response_recived_ || !vr_response_recived_;
+}
+
+void PerformInteractionRequest::CheckResponseResultCode() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ mobile_apis::Result::eType resultCode = mobile_apis::Result::INVALID_ENUM;
+ bool result = false;
+ if (mobile_apis::Result::GENERIC_ERROR == vr_resultCode_) {
+ LOG4CXX_DEBUG(logger_, "VR response GENERIC_ERROR");
+ resultCode = mobile_apis::Result::GENERIC_ERROR;
+ } else if (mobile_apis::Result::REJECTED == vr_resultCode_) {
+ LOG4CXX_DEBUG(logger_, "VR had been rejected.");
+ resultCode = mobile_apis::Result::REJECTED;
+ } else if (mobile_apis::Result::WARNINGS == vr_resultCode_ ||
+ mobile_apis::Result::UNSUPPORTED_REQUEST == vr_resultCode_) {
+ LOG4CXX_DEBUG(logger_, "VR response WARNINGS");
+ resultCode = mobile_api::Result::WARNINGS;
+ result = true;
+ }
+
+ if (mobile_apis::Result::INVALID_ENUM != resultCode) {
+ TerminatePerformInteraction();
+ SendResponse(result, resultCode);
+ }
+}
+
+void PerformInteractionRequest::SendBothModeResponse(
+ const smart_objects::SmartObject& msg_param) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace mobile_apis::Result;
+
+ bool result = ui_result_ || vr_result_;
+ mobile_apis::Result::eType perform_interaction_result_code = ui_resultCode_;
+
+ if (UNSUPPORTED_RESOURCE == vr_resultCode_ &&
+ UNSUPPORTED_RESOURCE != ui_resultCode_) {
+ perform_interaction_result_code = vr_resultCode_;
+ } else if (UNSUPPORTED_RESOURCE == vr_resultCode_ &&
+ UNSUPPORTED_RESOURCE == ui_resultCode_) {
+ result = false;
+ }
+
+ const bool is_error_code = (SUCCESS != perform_interaction_result_code ||
+ WARNINGS != perform_interaction_result_code);
+
+ if (vr_resultCode_ == ui_resultCode_ && is_error_code) {
+ result = false;
+ }
+
+ const smart_objects::SmartObject* response_params =
+ msg_param.empty() ? NULL : &msg_param;
+
+ TerminatePerformInteraction();
+ SendResponse(result, perform_interaction_result_code, NULL, response_params);
+}
+
} // namespace commands
} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/perform_interaction_response.cc b/src/components/application_manager/src/commands/mobile/perform_interaction_response.cc
index 59d706926d..6003751669 100644
--- a/src/components/application_manager/src/commands/mobile/perform_interaction_response.cc
+++ b/src/components/application_manager/src/commands/mobile/perform_interaction_response.cc
@@ -32,24 +32,21 @@
*/
#include "application_manager/commands/mobile/perform_interaction_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
PerformInteractionResponse::PerformInteractionResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-PerformInteractionResponse::~PerformInteractionResponse() {
-}
+PerformInteractionResponse::~PerformInteractionResponse() {}
void PerformInteractionResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/put_file_request.cc b/src/components/application_manager/src/commands/mobile/put_file_request.cc
index 88743e3668..68e7ad60d1 100644
--- a/src/components/application_manager/src/commands/mobile/put_file_request.cc
+++ b/src/components/application_manager/src/commands/mobile/put_file_request.cc
@@ -31,36 +31,36 @@
POSSIBILITY OF SUCH DAMAGE.
*/
+#include <algorithm>
#include "application_manager/commands/mobile/put_file_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/policies/policy_handler.h"
#include "application_manager/application_impl.h"
-#include "config_profile/profile.h"
+
#include "utils/file_system.h"
namespace application_manager {
namespace commands {
-PutFileRequest::PutFileRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message)
- , offset_(0)
- , sync_file_name_()
- , length_(0)
- , file_type_(mobile_apis::FileType::INVALID_ENUM)
- , is_persistent_file_(false) {
-}
+PutFileRequest::PutFileRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager)
+ , offset_(0)
+ , sync_file_name_()
+ , length_(0)
+ , file_type_(mobile_apis::FileType::INVALID_ENUM)
+ , is_persistent_file_(false) {}
-PutFileRequest::~PutFileRequest() {
-}
+PutFileRequest::~PutFileRequest() {}
void PutFileRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
- smart_objects::SmartObject response_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ application_manager_.application(connection_key());
+ smart_objects::SmartObject response_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
if (!application) {
LOG4CXX_ERROR(logger_, "Application is not registered");
@@ -69,13 +69,14 @@ void PutFileRequest::Run() {
}
if (mobile_api::HMILevel::HMI_NONE == application->hmi_level() &&
- profile::Profile::instance()->put_file_in_none() <=
- application->put_file_in_none_count()) {
+ application_manager_.get_settings().put_file_in_none() <=
+ application->put_file_in_none_count()) {
// If application is in the HMI_NONE level the quantity of allowed
// PutFile request is limited by the configuration profile
LOG4CXX_ERROR(logger_,
"Too many requests from the app with HMILevel HMI_NONE ");
- SendResponse(false, mobile_apis::Result::REJECTED,
+ SendResponse(false,
+ mobile_apis::Result::REJECTED,
"Too many requests from the app with HMILevel HMI_NONE",
&response_params);
return;
@@ -83,7 +84,8 @@ void PutFileRequest::Run() {
if (!(*message_)[strings::params].keyExists(strings::binary_data)) {
LOG4CXX_ERROR(logger_, "Binary data empty");
- SendResponse(false, mobile_apis::Result::INVALID_DATA,
+ SendResponse(false,
+ mobile_apis::Result::INVALID_DATA,
"Binary data empty",
&response_params);
return;
@@ -91,7 +93,8 @@ void PutFileRequest::Run() {
if (!(*message_)[strings::msg_params].keyExists(strings::sync_file_name)) {
LOG4CXX_ERROR(logger_, "No file name");
- SendResponse(false, mobile_apis::Result::INVALID_DATA,
+ SendResponse(false,
+ mobile_apis::Result::INVALID_DATA,
"No file name",
&response_params);
return;
@@ -99,23 +102,24 @@ void PutFileRequest::Run() {
if (!(*message_)[strings::msg_params].keyExists(strings::file_type)) {
LOG4CXX_ERROR(logger_, "No file type");
- SendResponse(false, mobile_apis::Result::INVALID_DATA,
+ SendResponse(false,
+ mobile_apis::Result::INVALID_DATA,
"No file type",
&response_params);
return;
}
sync_file_name_ =
- (*message_)[strings::msg_params][strings::sync_file_name].asString();
- file_type_ =
- static_cast<mobile_apis::FileType::eType>(
+ (*message_)[strings::msg_params][strings::sync_file_name].asString();
+ file_type_ = static_cast<mobile_apis::FileType::eType>(
(*message_)[strings::msg_params][strings::file_type].asInt());
const std::vector<uint8_t> binary_data =
- (*message_)[strings::params][strings::binary_data].asBinary();
+ (*message_)[strings::params][strings::binary_data].asBinary();
// Policy table update in json format is currently to be received via PutFile
// TODO(PV): after latest discussion has to be changed
if (mobile_apis::FileType::JSON == file_type_) {
- policy::PolicyHandler::instance()->ReceiveMessageFromSDK(sync_file_name_, binary_data);
+ application_manager_.GetPolicyHandler().ReceiveMessageFromSDK(
+ sync_file_name_, binary_data);
}
offset_ = 0;
@@ -127,83 +131,92 @@ void PutFileRequest::Run() {
(*message_)[strings::msg_params].keyExists(strings::offset);
if (offset_exist) {
- offset_ = (*message_)[strings::msg_params][strings::offset].asInt64();
+ offset_ = (*message_)[strings::msg_params][strings::offset].asInt();
}
- if ((*message_)[strings::msg_params].
- keyExists(strings::persistent_file)) {
+ if ((*message_)[strings::msg_params].keyExists(strings::persistent_file)) {
is_persistent_file_ =
- (*message_)[strings::msg_params][strings::persistent_file].asBool();
+ (*message_)[strings::msg_params][strings::persistent_file].asBool();
}
- if ((*message_)[strings::msg_params].
- keyExists(strings::system_file)) {
+ if ((*message_)[strings::msg_params].keyExists(strings::system_file)) {
is_system_file =
- (*message_)[strings::msg_params][strings::system_file].asBool();
+ (*message_)[strings::msg_params][strings::system_file].asBool();
}
std::string file_path;
if (is_system_file) {
response_params[strings::space_available] = 0;
- file_path = profile::Profile::instance()->system_files_path();
+ file_path = application_manager_.get_settings().system_files_path();
} else {
- file_path = profile::Profile::instance()->app_storage_folder();
+ file_path = application_manager_.get_settings().app_storage_folder();
file_path += "/" + application->folder_name();
- uint32_t space_available = ApplicationManagerImpl::instance()->
- GetAvailableSpaceForApp(application->folder_name());
+ uint32_t space_available = application->GetAvailableDiskSpace();
if (binary_data.size() > space_available) {
-
response_params[strings::space_available] =
static_cast<uint32_t>(space_available);
LOG4CXX_ERROR(logger_, "Out of memory");
- SendResponse(false, mobile_apis::Result::OUT_OF_MEMORY,
- "Out of memory", &response_params);
+ SendResponse(false,
+ mobile_apis::Result::OUT_OF_MEMORY,
+ "Out of memory",
+ &response_params);
return;
}
}
if (!file_system::CreateDirectoryRecursively(file_path)) {
- LOG4CXX_ERROR(logger_, "Cann't create folder");
- SendResponse(false, mobile_apis::Result::GENERIC_ERROR,
- "Cann't create folder.", &response_params);
+ LOG4CXX_ERROR(logger_, "Can't create folder");
+ SendResponse(false,
+ mobile_apis::Result::GENERIC_ERROR,
+ "Can't create folder.",
+ &response_params);
return;
}
-
- mobile_apis::Result::eType save_result =
- ApplicationManagerImpl::instance()->SaveBinary(binary_data, file_path,
- sync_file_name_, offset_);
-
+ const std::string full_path = file_path + "/" + sync_file_name_;
+ UNUSED(full_path);
+ LOG4CXX_DEBUG(logger_,
+ "Wrtiting " << binary_data.size() << "bytes to " << full_path
+ << " (current size is"
+ << file_system::FileSize(full_path) << ")");
+
+ mobile_apis::Result::eType save_result = application_manager_.SaveBinary(
+ binary_data, file_path, sync_file_name_, offset_);
+
+ LOG4CXX_DEBUG(logger_,
+ "New size of " << full_path << " is "
+ << file_system::FileSize(full_path) << " bytes");
if (!is_system_file) {
- response_params[strings::space_available] = static_cast<uint32_t>(
- ApplicationManagerImpl::instance()->GetAvailableSpaceForApp(
- application->folder_name()));
+ response_params[strings::space_available] =
+ static_cast<uint32_t>(application->GetAvailableDiskSpace());
}
sync_file_name_ = file_path + "/" + sync_file_name_;
switch (save_result) {
case mobile_apis::Result::SUCCESS: {
-
+ LOG4CXX_INFO(logger_, "PutFile is successful");
if (!is_system_file) {
- AppFile file(sync_file_name_, is_persistent_file_,
- is_download_compleate, file_type_);
+ AppFile file(sync_file_name_,
+ is_persistent_file_,
+ is_download_compleate,
+ file_type_);
if (0 == offset_) {
LOG4CXX_INFO(logger_, "New file downloading");
if (!application->AddFile(file)) {
-
LOG4CXX_INFO(logger_,
"Couldn't add file to application (File already Exist"
- << " in application and was rewritten on FS)");
+ << " in application and was rewritten on FS)");
/* It can be first part of new big file, so we need to update
information about it's downloading status and persistence */
if (!application->UpdateFile(file)) {
- LOG4CXX_INFO(logger_, "Couldn't update file");
+ LOG4CXX_ERROR(logger_, "Couldn't update file");
/* If it is impossible to update file, application doesn't
know about existing this file */
- SendResponse(false, mobile_apis::Result::INVALID_DATA,
+ SendResponse(false,
+ mobile_apis::Result::INVALID_DATA,
"Couldn't update file",
&response_params);
return;
@@ -224,20 +237,21 @@ void PutFileRequest::Run() {
break;
}
default:
- LOG4CXX_WARN(logger_, "Save in unsuccessful. Result = " << save_result);
+ LOG4CXX_WARN(logger_,
+ "PutFile is unsuccessful. Result = " << save_result);
SendResponse(false, save_result, "Can't save file", &response_params);
break;
}
}
void PutFileRequest::SendOnPutFileNotification() {
- LOG4CXX_INFO(logger_, "SendOnPutFileNotification" );
- smart_objects::SmartObjectSPtr notification = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ LOG4CXX_INFO(logger_, "SendOnPutFileNotification");
+ smart_objects::SmartObjectSPtr notification =
+ new smart_objects::SmartObject(smart_objects::SmartType_Map);
smart_objects::SmartObject& message = *notification;
message[strings::params][strings::function_id] =
- hmi_apis::FunctionID::BasicCommunication_OnPutFile;
+ hmi_apis::FunctionID::BasicCommunication_OnPutFile;
message[strings::params][strings::message_type] = MessageType::kNotification;
message[strings::msg_params][strings::app_id] = connection_key();
@@ -250,7 +264,7 @@ void PutFileRequest::SendOnPutFileNotification() {
message[strings::msg_params][strings::length] = length_;
message[strings::msg_params][strings::persistent_file] = is_persistent_file_;
message[strings::msg_params][strings::file_type] = file_type_;
- ApplicationManagerImpl::instance()->ManageHMICommand(notification);
+ application_manager_.ManageHMICommand(notification);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/put_file_response.cc b/src/components/application_manager/src/commands/mobile/put_file_response.cc
index 52598fda16..50c62aef7f 100644
--- a/src/components/application_manager/src/commands/mobile/put_file_response.cc
+++ b/src/components/application_manager/src/commands/mobile/put_file_response.cc
@@ -34,31 +34,28 @@
#include "application_manager/commands/mobile/put_file_response.h"
#include "utils/file_system.h"
#include "application_manager/application_impl.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-PutFileResponse::PutFileResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+PutFileResponse::PutFileResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-PutFileResponse::~PutFileResponse() {
-}
+PutFileResponse::~PutFileResponse() {}
void PutFileResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- uint32_t app_id = (*message_)[strings::params][strings::connection_key]
- .asUInt();
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(app_id);
+ uint32_t app_id =
+ (*message_)[strings::params][strings::connection_key].asUInt();
+ ApplicationSharedPtr app = application_manager_.application(app_id);
if (!app) {
LOG4CXX_ERROR(logger_, "Application not registered");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
-
SendResponse((*message_)[strings::msg_params][strings::success].asBool());
}
diff --git a/src/components/application_manager/src/commands/mobile/read_did_request.cc b/src/components/application_manager/src/commands/mobile/read_did_request.cc
index 18f43f12ca..69885f9d40 100644
--- a/src/components/application_manager/src/commands/mobile/read_did_request.cc
+++ b/src/components/application_manager/src/commands/mobile/read_did_request.cc
@@ -1,6 +1,5 @@
/*
-
- Copyright (c) 2013, Ford Motor Company
+ Copyright (c) 2016, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -31,8 +30,9 @@
POSSIBILITY OF SUCH DAMAGE.
*/
+#include <string>
#include "application_manager/commands/mobile/read_did_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
@@ -41,45 +41,46 @@ namespace application_manager {
namespace commands {
-ReadDIDRequest::ReadDIDRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+ReadDIDRequest::ReadDIDRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-ReadDIDRequest::~ReadDIDRequest() {
-}
+ReadDIDRequest::~ReadDIDRequest() {}
void ReadDIDRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- uint32_t app_id = (*message_)[strings::params][strings::connection_key]
- .asUInt();
+ uint32_t app_id =
+ (*message_)[strings::params][strings::connection_key].asUInt();
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(app_id);
- LOG4CXX_INFO(logger_, "Correlation_id :" << (*message_)[strings::params][strings::correlation_id]
- .asUInt());
+ ApplicationSharedPtr app = application_manager_.application(app_id);
+ LOG4CXX_INFO(
+ logger_,
+ "Correlation_id :"
+ << (*message_)[strings::params][strings::correlation_id].asUInt());
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "An application is not registered.");
+ LOG4CXX_ERROR(logger_, "An application is not registered.");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
if (app->IsCommandLimitsExceeded(
- static_cast<mobile_apis::FunctionID::eType>(function_id()),
- application_manager::TLimitSource::CONFIG_FILE)) {
+ static_cast<mobile_apis::FunctionID::eType>(function_id()),
+ application_manager::TLimitSource::CONFIG_FILE)) {
LOG4CXX_ERROR(logger_, "ReadDID frequency is too high.");
SendResponse(false, mobile_apis::Result::REJECTED);
return;
}
if ((*message_)[strings::msg_params][strings::did_location].empty()) {
- LOG4CXX_ERROR_EXT(logger_, "INVALID_DATA");
+ LOG4CXX_ERROR(logger_, "INVALID_DATA");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::app_id] = app->app_id();
msg_params[strings::ecu_name] =
(*message_)[strings::msg_params][strings::ecu_name];
@@ -101,7 +102,13 @@ void ReadDIDRequest::on_event(const event_engine::Event& event) {
bool result = mobile_apis::Result::SUCCESS == result_code;
- SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
+ const std::string return_info =
+ message[strings::msg_params][hmi_response::message].asString();
+
+ SendResponse(result,
+ result_code,
+ return_info.c_str(),
+ &(message[strings::msg_params]));
break;
}
default: {
diff --git a/src/components/application_manager/src/commands/mobile/read_did_response.cc b/src/components/application_manager/src/commands/mobile/read_did_response.cc
index 1133fe89ed..e54c4ba005 100644
--- a/src/components/application_manager/src/commands/mobile/read_did_response.cc
+++ b/src/components/application_manager/src/commands/mobile/read_did_response.cc
@@ -32,23 +32,21 @@
*/
#include "application_manager/commands/mobile/read_did_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-ReadDIDResponse::ReadDIDResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ReadDIDResponse::ReadDIDResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-ReadDIDResponse::~ReadDIDResponse() {
-}
+ReadDIDResponse::~ReadDIDResponse() {}
void ReadDIDResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/register_app_interface_request.cc b/src/components/application_manager/src/commands/mobile/register_app_interface_request.cc
index 401dead91f..a49ca6d3e7 100644
--- a/src/components/application_manager/src/commands/mobile/register_app_interface_request.cc
+++ b/src/components/application_manager/src/commands/mobile/register_app_interface_request.cc
@@ -38,16 +38,19 @@
#include <map>
#include <string.h>
-#include "application_manager/application_manager_impl.h"
+#include <utils/make_shared.h>
+#include "application_manager/application_manager.h"
+#include "application_manager/policies/policy_handler_interface.h"
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
-#include "application_manager/policies/policy_handler.h"
-#include "config_profile/profile.h"
+#include "application_manager/resumption/resume_ctrl.h"
#include "interfaces/MOBILE_API.h"
+#include "interfaces/generated_msg_version.h"
namespace {
+namespace custom_str = utils::custom_string;
-mobile_apis::AppHMIType::eType StringToAppHMIType(const std::string &str) {
+mobile_apis::AppHMIType::eType StringToAppHMIType(const std::string& str) {
if ("DEFAULT" == str) {
return mobile_apis::AppHMIType::DEFAULT;
} else if ("COMMUNICATION" == str) {
@@ -94,34 +97,34 @@ std::string AppHMITypeToString(mobile_apis::AppHMIType::eType type) {
}
struct AppHMITypeInserter {
- AppHMITypeInserter(smart_objects::SmartObject &so_array)
+ AppHMITypeInserter(smart_objects::SmartObject& so_array)
: index_(0), so_array_(so_array) {}
- bool operator()(const std::string &app_hmi_type) {
+ bool operator()(const std::string& app_hmi_type) {
so_array_[index_] = StringToAppHMIType(app_hmi_type);
++index_;
return true;
}
-private:
+ private:
uint32_t index_;
- smart_objects::SmartObject &so_array_;
+ smart_objects::SmartObject& so_array_;
};
struct CheckMissedTypes {
- CheckMissedTypes(const policy::StringArray &policy_app_types,
- std::string &log)
+ CheckMissedTypes(const policy::StringArray& policy_app_types,
+ std::string& log)
: policy_app_types_(policy_app_types), log_(log) {}
- bool operator()(const smart_objects::SmartArray::value_type &value) {
+ bool operator()(const smart_objects::SmartArray::value_type& value) {
std::string app_type_str = AppHMITypeToString(
static_cast<mobile_apis::AppHMIType::eType>(value.asInt()));
if (!app_type_str.empty()) {
- policy::StringArray::const_iterator it = policy_app_types_.begin();
- policy::StringArray::const_iterator it_end = policy_app_types_.end();
- for (; it != it_end; ++it) {
- if (app_type_str == *it) {
- return true;
+ policy::StringArray::const_iterator it = policy_app_types_.begin();
+ policy::StringArray::const_iterator it_end = policy_app_types_.end();
+ for (; it != it_end; ++it) {
+ if (app_type_str == *it) {
+ return true;
}
}
}
@@ -132,19 +135,19 @@ struct CheckMissedTypes {
return true;
}
-private:
- const policy::StringArray &policy_app_types_;
- std::string &log_;
+ private:
+ const policy::StringArray& policy_app_types_;
+ std::string& log_;
};
struct IsSameNickname {
- IsSameNickname(const std::string &app_id) : app_id_(app_id) {}
- bool operator()(const policy::StringArray::value_type nickname) const {
- return !strcasecmp(app_id_.c_str(), nickname.c_str());
+ IsSameNickname(const custom_str::CustomString& app_id) : app_id_(app_id) {}
+ bool operator()(const policy::StringArray::value_type& nickname) const {
+ return app_id_.CompareIgnoreCase(nickname.c_str());
}
-private:
- const std::string &app_id_;
+ private:
+ const custom_str::CustomString& app_id_;
};
}
@@ -153,9 +156,9 @@ namespace application_manager {
namespace commands {
RegisterAppInterfaceRequest::RegisterAppInterfaceRequest(
- const MessageSharedPtr &message)
- : CommandRequestImpl(message),
- result_checking_app_hmi_type_(mobile_apis::Result::INVALID_ENUM) {}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager)
+ , result_checking_app_hmi_type_(mobile_apis::Result::INVALID_ENUM) {}
RegisterAppInterfaceRequest::~RegisterAppInterfaceRequest() {}
@@ -165,8 +168,9 @@ bool RegisterAppInterfaceRequest::Init() {
}
void RegisterAppInterfaceRequest::Run() {
- LOG4CXX_INFO(logger_, "RegisterAppInterfaceRequest::Run "
- << connection_key());
+ using namespace helpers;
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_, "Connection key is " << connection_key());
// Fix problem with SDL and HMI HTML. This problem is not actual for HMI PASA.
// Flag conditional compilation specific to customer is used in order to
@@ -175,24 +179,21 @@ void RegisterAppInterfaceRequest::Run() {
// FIXME(EZamakhov): on shutdown - get freez
// wait till HMI started
- while (ApplicationManagerImpl::exists() &&
- !ApplicationManagerImpl::instance()->IsStopping() &&
- !ApplicationManagerImpl::instance()->IsHMICooperating()) {
- LOG4CXX_DEBUG(logger_, "Waiting for the HMI... conn_key="
- << connection_key()
- << ", correlation_id=" << correlation_id()
- << ", default_timeout=" << default_timeout()
- << ", thread=" << pthread_self());
- ApplicationManagerImpl::instance()->updateRequestTimeout(
+ while (!application_manager_.IsStopping() &&
+ !application_manager_.IsHMICooperating()) {
+ LOG4CXX_DEBUG(logger_,
+ "Waiting for the HMI... conn_key="
+ << connection_key()
+ << ", correlation_id=" << correlation_id()
+ << ", default_timeout=" << default_timeout()
+ << ", thread=" << pthread_self());
+ application_manager_.updateRequestTimeout(
connection_key(), correlation_id(), default_timeout());
sleep(1);
// TODO(DK): timer_->StartWait(1);
}
- if (!ApplicationManagerImpl::exists()) {
- LOG4CXX_WARN(logger_, "The ApplicationManager doesn't exist!");
- return;
- } else if (ApplicationManagerImpl::instance()->IsStopping()) {
+ if (application_manager_.IsStopping()) {
LOG4CXX_WARN(logger_, "The ApplicationManager is stopping!");
return;
}
@@ -201,21 +202,35 @@ void RegisterAppInterfaceRequest::Run() {
(*message_)[strings::msg_params][strings::app_id].asString();
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (application) {
SendResponse(false, mobile_apis::Result::APPLICATION_REGISTERED_ALREADY);
return;
}
+ const smart_objects::SmartObject& msg_params =
+ (*message_)[strings::msg_params];
+
+ const std::string& policy_app_id = msg_params[strings::app_id].asString();
+
+ if (application_manager_.IsApplicationForbidden(connection_key(),
+ policy_app_id)) {
+ SendResponse(false, mobile_apis::Result::TOO_MANY_PENDING_REQUESTS);
+ return;
+ }
+
if (IsApplicationWithSameAppIdRegistered()) {
SendResponse(false, mobile_apis::Result::DISALLOWED);
return;
}
mobile_apis::Result::eType policy_result = CheckWithPolicyData();
- if (mobile_apis::Result::SUCCESS != policy_result &&
- mobile_apis::Result::WARNINGS != policy_result) {
+
+ if (Compare<mobile_apis::Result::eType, NEQ, ALL>(
+ policy_result,
+ mobile_apis::Result::SUCCESS,
+ mobile_apis::Result::WARNINGS)) {
SendResponse(false, policy_result);
return;
}
@@ -223,11 +238,12 @@ void RegisterAppInterfaceRequest::Run() {
mobile_apis::Result::eType coincidence_result = CheckCoincidence();
if (mobile_apis::Result::SUCCESS != coincidence_result) {
- LOG4CXX_ERROR_EXT(logger_, "Coincidence check failed.");
+ LOG4CXX_ERROR(logger_, "Coincidence check failed.");
if (mobile_apis::Result::DUPLICATE_NAME == coincidence_result) {
usage_statistics::AppCounter count_of_rejections_duplicate_name(
- policy::PolicyHandler::instance()->GetStatisticManager(),
- mobile_app_id, usage_statistics::REJECTIONS_DUPLICATE_NAME);
+ GetPolicyHandler().GetStatisticManager(),
+ policy_app_id,
+ usage_statistics::REJECTIONS_DUPLICATE_NAME);
++count_of_rejections_duplicate_name;
}
SendResponse(false, coincidence_result);
@@ -241,129 +257,172 @@ void RegisterAppInterfaceRequest::Run() {
return;
}
- const smart_objects::SmartObject &msg_params =
- (*message_)[strings::msg_params];
-
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->RegisterApplication(message_);
+ application = application_manager_.RegisterApplication(message_);
- if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "Application "
- << msg_params[strings::app_name].asString()
- << " hasn't been registered!");
+ if (!application) {
+ LOG4CXX_ERROR(logger_, "Application hasn't been registered!");
+ return;
+ }
+ // For resuming application need to restore hmi_app_id from resumeCtrl
+ resumption::ResumeCtrl& resumer = application_manager_.resume_controller();
+ const std::string& device_mac = application->mac_address();
+
+ // there is side affect with 2 mobile app with the same mobile app_id
+ if (resumer.IsApplicationSaved(policy_app_id, device_mac)) {
+ application->set_hmi_application_id(
+ resumer.GetHMIApplicationID(policy_app_id, device_mac));
} else {
- app->set_is_media_application(
- msg_params[strings::is_media_application].asBool());
+ application->set_hmi_application_id(
+ application_manager_.GenerateNewHMIAppID());
+ }
- if (msg_params.keyExists(strings::vr_synonyms)) {
- app->set_vr_synonyms(msg_params[strings::vr_synonyms]);
- }
+ application->set_is_media_application(
+ msg_params[strings::is_media_application].asBool());
- if (msg_params.keyExists(strings::ngn_media_screen_app_name)) {
- app->set_ngn_media_screen_name(
- msg_params[strings::ngn_media_screen_app_name]);
- }
+ if (msg_params.keyExists(strings::vr_synonyms)) {
+ application->set_vr_synonyms(msg_params[strings::vr_synonyms]);
+ }
- if (msg_params.keyExists(strings::tts_name)) {
- app->set_tts_name(msg_params[strings::tts_name]);
- }
+ if (msg_params.keyExists(strings::ngn_media_screen_app_name)) {
+ application->set_ngn_media_screen_name(
+ msg_params[strings::ngn_media_screen_app_name]);
+ }
- if (msg_params.keyExists(strings::app_hmi_type)) {
- app->set_app_types(msg_params[strings::app_hmi_type]);
+ if (msg_params.keyExists(strings::tts_name)) {
+ application->set_tts_name(msg_params[strings::tts_name]);
+ }
- // check app type
- const smart_objects::SmartObject &app_type =
- msg_params.getElement(strings::app_hmi_type);
+ if (msg_params.keyExists(strings::app_hmi_type)) {
+ application->set_app_types(msg_params[strings::app_hmi_type]);
- for (size_t i = 0; i < app_type.length(); ++i) {
- if (mobile_apis::AppHMIType::NAVIGATION ==
- static_cast<mobile_apis::AppHMIType::eType>(
- app_type.getElement(i).asUInt())) {
- app->set_is_navi(true);
- }
- if (mobile_apis::AppHMIType::COMMUNICATION ==
- static_cast<mobile_apis::AppHMIType::eType>(
- app_type.getElement(i).asUInt())) {
- app->set_voice_communication_supported(true);
- }
+ // check app type
+ const smart_objects::SmartObject& app_type =
+ msg_params.getElement(strings::app_hmi_type);
+
+ for (size_t i = 0; i < app_type.length(); ++i) {
+ if (mobile_apis::AppHMIType::NAVIGATION ==
+ static_cast<mobile_apis::AppHMIType::eType>(
+ app_type.getElement(i).asUInt())) {
+ application->set_is_navi(true);
+ }
+ if (mobile_apis::AppHMIType::COMMUNICATION ==
+ static_cast<mobile_apis::AppHMIType::eType>(
+ app_type.getElement(i).asUInt())) {
+ application->set_voice_communication_supported(true);
}
}
+ }
- const connection_handler::DeviceHandle handle = app->device();
- // Add device to policy table and set device info, if any
- std::string device_mac_address =
- application_manager::MessageHelper::GetDeviceMacAddressForHandle(
- handle);
- policy::DeviceParams dev_params;
- application_manager::MessageHelper::GetDeviceInfoForHandle(handle,
- &dev_params);
- policy::DeviceInfo device_info;
- device_info.AdoptDeviceType(dev_params.device_connection_type);
- if (msg_params.keyExists(strings::device_info)) {
- FillDeviceInfo(&device_info);
- }
+ // Add device to policy table and set device info, if any
+ policy::DeviceParams dev_params;
+ if (-1 ==
+ application_manager_.connection_handler()
+ .get_session_observer()
+ .GetDataOnDeviceID(application->device(),
+ &dev_params.device_name,
+ NULL,
+ &dev_params.device_mac_address,
+ &dev_params.device_connection_type)) {
+ LOG4CXX_ERROR(logger_,
+ "Failed to extract information for device "
+ << application->device());
+ }
+ policy::DeviceInfo device_info;
+ device_info.AdoptDeviceType(dev_params.device_connection_type);
+ if (msg_params.keyExists(strings::device_info)) {
+ FillDeviceInfo(&device_info);
+ }
- policy::PolicyHandler::instance()->SetDeviceInfo(device_mac_address,
- device_info);
+ GetPolicyHandler().SetDeviceInfo(device_mac, device_info);
- SendRegisterAppInterfaceResponseToMobile();
+ SendRegisterAppInterfaceResponseToMobile();
+ smart_objects::SmartObjectSPtr so = GetLockScreenIconUrlNotification(connection_key(), application);
+ application_manager_.ManageMobileCommand(so, commands::Command::ORIGIN_SDL);
+}
- MessageHelper::SendLockScreenIconUrlNotification(
- (*message_)[strings::params][strings::connection_key].asInt());
- }
+smart_objects::SmartObjectSPtr RegisterAppInterfaceRequest::GetLockScreenIconUrlNotification(
+ const uint32_t connection_key,
+ ApplicationSharedPtr app) {
+ DCHECK_OR_RETURN(app.get(), smart_objects::SmartObjectSPtr());
+ smart_objects::SmartObjectSPtr message =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+ (*message)[strings::params][strings::function_id] =
+ mobile_apis::FunctionID::OnSystemRequestID;
+ (*message)[strings::params][strings::connection_key] = connection_key;
+ (*message)[strings::params][strings::message_type] =
+ mobile_apis::messageType::notification;
+ (*message)[strings::params][strings::protocol_type] =
+ commands::CommandImpl::mobile_protocol_type_;
+ (*message)[strings::params][strings::protocol_version] =
+ commands::CommandImpl::protocol_version_;
+ (*message)[strings::msg_params][strings::request_type] =
+ mobile_apis::RequestType::LOCK_SCREEN_ICON_URL;
+ (*message)[strings::msg_params][strings::url] =
+ GetPolicyHandler().GetLockScreenIconUrl();
+ return message;
}
-void RegisterAppInterfaceRequest::SendRegisterAppInterfaceResponseToMobile(
- mobile_apis::Result::eType result) {
+void RegisterAppInterfaceRequest::SendRegisterAppInterfaceResponseToMobile() {
+ LOG4CXX_AUTO_TRACE(logger_);
smart_objects::SmartObject response_params(smart_objects::SmartType_Map);
- ApplicationManagerImpl *app_manager = ApplicationManagerImpl::instance();
- const HMICapabilities &hmi_capabilities = app_manager->hmi_capabilities();
+ mobile_apis::Result::eType result_code = mobile_apis::Result::SUCCESS;
+
+ const HMICapabilities& hmi_capabilities =
+ application_manager_.hmi_capabilities();
+
const uint32_t key = connection_key();
- ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(key);
+ ApplicationSharedPtr application = application_manager_.application(key);
+
+ resumption::ResumeCtrl& resumer = application_manager_.resume_controller();
if (!application) {
- LOG4CXX_ERROR(logger_, "There is no application for such connection key"
- << key);
+ LOG4CXX_ERROR(logger_,
+ "There is no application for such connection key" << key);
+ LOG4CXX_DEBUG(logger_, "Need to start resume data persistent timer");
+ resumer.OnAppRegistrationEnd();
return;
}
response_params[strings::sync_msg_version][strings::major_version] =
- APIVersion::kAPIV3;
+ major_version; // From generated file interfaces/generated_msg_version.h
response_params[strings::sync_msg_version][strings::minor_version] =
- APIVersion::kAPIV0;
+ minor_version; // From generated file interfaces/generated_msg_version.h
response_params[strings::language] = hmi_capabilities.active_vr_language();
response_params[strings::hmi_display_language] =
hmi_capabilities.active_ui_language();
- const smart_objects::SmartObject &msg_params =
+ const smart_objects::SmartObject& msg_params =
(*message_)[strings::msg_params];
if (msg_params[strings::language_desired].asInt() !=
hmi_capabilities.active_vr_language() ||
msg_params[strings::hmi_display_language_desired].asInt() !=
hmi_capabilities.active_ui_language()) {
+ LOG4CXX_WARN(logger_,
+ "Wrong language on registering application "
+ << application->name().c_str());
- LOG4CXX_WARN_EXT(logger_, "Wrong language on registering application "
- << application->name());
-
- LOG4CXX_ERROR_EXT(
+ LOG4CXX_ERROR(
logger_,
- "vr " << msg_params[strings::language_desired].asInt() << " - "
- << hmi_capabilities.active_vr_language() << "ui "
- << msg_params[strings::hmi_display_language_desired].asInt()
- << " - " << hmi_capabilities.active_ui_language());
-
- result = mobile_apis::Result::WRONG_LANGUAGE;
+ "VR language desired code is "
+ << msg_params[strings::language_desired].asInt()
+ << " , active VR language code is "
+ << hmi_capabilities.active_vr_language() << ", UI language code is "
+ << msg_params[strings::hmi_display_language_desired].asInt()
+ << " , active UI language code is "
+ << hmi_capabilities.active_ui_language());
+
+ result_code = mobile_apis::Result::WRONG_LANGUAGE;
}
if (hmi_capabilities.display_capabilities()) {
response_params[hmi_response::display_capabilities] =
smart_objects::SmartObject(smart_objects::SmartType_Map);
- smart_objects::SmartObject &display_caps =
+ smart_objects::SmartObject& display_caps =
response_params[hmi_response::display_capabilities];
display_caps[hmi_response::display_type] =
@@ -457,6 +516,10 @@ void RegisterAppInterfaceRequest::SendRegisterAppInterfaceResponseToMobile(
*hmi_capabilities.audio_pass_thru_capabilities();
}
}
+ if (hmi_capabilities.pcm_stream_capabilities()) {
+ response_params[strings::pcm_stream_capabilities] =
+ *hmi_capabilities.pcm_stream_capabilities();
+ }
if (hmi_capabilities.vehicle_type()) {
response_params[hmi_response::vehicle_type] =
*hmi_capabilities.vehicle_type();
@@ -466,8 +529,8 @@ void RegisterAppInterfaceRequest::SendRegisterAppInterfaceResponseToMobile(
*(hmi_capabilities.prerecorded_speech());
}
- const std::vector<uint32_t> &diag_modes =
- profile::Profile::instance()->supported_diag_modes();
+ const std::vector<uint32_t>& diag_modes =
+ application_manager_.get_settings().supported_diag_modes();
if (!diag_modes.empty()) {
std::vector<uint32_t>::const_iterator it = diag_modes.begin();
uint32_t index = 0;
@@ -484,82 +547,204 @@ void RegisterAppInterfaceRequest::SendRegisterAppInterfaceResponseToMobile(
response_params[strings::hmi_capabilities][strings::phone_call] =
hmi_capabilities.phone_call_supported();
response_params[strings::sdl_version] =
- profile::Profile::instance()->sdl_version();
- response_params[strings::system_software_version] =
- hmi_capabilities.ccpu_version();
-
- ResumeCtrl &resumer = ApplicationManagerImpl::instance()->resume_controller();
- std::string hash_id = "";
+ application_manager_.get_settings().sdl_version();
+ const std::string ccpu_version =
+ application_manager_.hmi_capabilities().ccpu_version();
+ if (!ccpu_version.empty()) {
+ response_params[strings::system_software_version] = ccpu_version;
+ }
- std::string add_info("");
bool resumption =
(*message_)[strings::msg_params].keyExists(strings::hash_id);
+
bool need_restore_vr = resumption;
+
+ std::string hash_id;
+ std::string add_info;
if (resumption) {
hash_id = (*message_)[strings::msg_params][strings::hash_id].asString();
if (!resumer.CheckApplicationHash(application, hash_id)) {
- LOG4CXX_WARN(logger_, "Hash does not match");
- result = mobile_apis::Result::RESUME_FAILED;
- add_info = "Hash does not match";
+ LOG4CXX_WARN(logger_,
+ "Hash from RAI does not match to saved resume data.");
+ result_code = mobile_apis::Result::RESUME_FAILED;
+ add_info = "Hash from RAI does not match to saved resume data.";
need_restore_vr = false;
} else if (!resumer.CheckPersistenceFilesForResumption(application)) {
- LOG4CXX_WARN(logger_, "Persistent data is missed");
- result = mobile_apis::Result::RESUME_FAILED;
- add_info = "Persistent data is missed";
+ LOG4CXX_WARN(logger_, "Persistent data is missing.");
+ result_code = mobile_apis::Result::RESUME_FAILED;
+ add_info = "Persistent data is missing.";
need_restore_vr = false;
} else {
- add_info = " Resume Succeed";
+ add_info = "Resume succeeded.";
}
}
- if ((mobile_apis::Result::SUCCESS == result) &&
+ if ((mobile_apis::Result::SUCCESS == result_code) &&
(mobile_apis::Result::INVALID_ENUM != result_checking_app_hmi_type_)) {
add_info += response_info_;
- result = result_checking_app_hmi_type_;
+ result_code = result_checking_app_hmi_type_;
}
// in case application exist in resumption we need to send resumeVrgrammars
if (false == resumption) {
- resumption = resumer.IsApplicationSaved(application->mobile_app_id());
+ resumption = resumer.IsApplicationSaved(application->policy_app_id(),
+ application->mac_address());
}
- MessageHelper::SendOnAppRegisteredNotificationToHMI(
+ SendOnAppRegisteredNotificationToHMI(
*(application.get()), resumption, need_restore_vr);
+ SendResponse(true, result_code, add_info.c_str(), &response_params);
- SendResponse(true, result, add_info.c_str(), &response_params);
+ // Check if application exists, because application might be unregestered
+ // during sending reponse to mobile.
+ application = application_manager_.application(key);
+ if (application) {
+ LOG4CXX_DEBUG(logger_, "Application with app_id = " << key << " exists.");
+ if (result_code != mobile_apis::Result::RESUME_FAILED) {
+ resumer.StartResumption(application, hash_id);
+ } else {
+ resumer.StartResumptionOnlyHMILevel(application);
+ }
- if (result != mobile_apis::Result::RESUME_FAILED) {
- resumer.StartResumption(application, hash_id);
+ // By default app subscribed to CUSTOM_BUTTON
+ SendSubscribeCustomButtonNotification();
+ MessageHelper::SendChangeRegistrationRequestToHMI(application,
+ application_manager_);
} else {
- resumer.StartResumptionOnlyHMILevel(application);
+ LOG4CXX_DEBUG(logger_,
+ "Application with app_id = " << key << " doesn't exist.");
+ }
+}
+
+void RegisterAppInterfaceRequest::SendOnAppRegisteredNotificationToHMI(
+ const Application& application_impl,
+ bool resumption,
+ bool need_restore_vr) {
+ using namespace smart_objects;
+ SmartObjectSPtr notification = utils::MakeShared<SmartObject>(SmartType_Map);
+ if (!notification) {
+ LOG4CXX_ERROR(logger_, "Failed to create smart object");
+ return;
+ }
+
+ (*notification)[strings::params] = SmartObject(SmartType_Map);
+ smart_objects::SmartObject& params = (*notification)[strings::params];
+ params[strings::function_id] = static_cast<int32_t>(
+ hmi_apis::FunctionID::BasicCommunication_OnAppRegistered);
+ params[strings::message_type] = static_cast<int32_t>(kNotification);
+ params[strings::protocol_version] = commands::CommandImpl::protocol_version_;
+ params[strings::protocol_type] = commands::CommandImpl::hmi_protocol_type_;
+
+ (*notification)[strings::msg_params] = SmartObject(SmartType_Map);
+ smart_objects::SmartObject& msg_params = (*notification)[strings::msg_params];
+ // Due to current requirements in case when we're in resumption mode
+ // we have to always send resumeVRGrammar field.
+ if (resumption) {
+ msg_params[strings::resume_vr_grammars] = need_restore_vr;
}
- // By default app subscribed to CUSTOM_BUTTON
- // Need to send notification to HMI
- SendSubscribeCustomButtonNotification();
- MessageHelper::SendChangeRegistrationRequestToHMI(application);
+ if (application_impl.vr_synonyms()) {
+ msg_params[strings::vr_synonyms] = *(application_impl.vr_synonyms());
+ }
+
+ if (application_impl.tts_name()) {
+ msg_params[strings::tts_name] = *(application_impl.tts_name());
+ }
+
+ std::string priority;
+ GetPolicyHandler().GetPriority(application_impl.policy_app_id(), &priority);
+
+ if (!priority.empty()) {
+ msg_params[strings::priority] = MessageHelper::GetPriorityCode(priority);
+ }
+
+ msg_params[strings::msg_params] = SmartObject(SmartType_Map);
+ smart_objects::SmartObject& application = msg_params[strings::application];
+ application[strings::app_name] = application_impl.name();
+ application[strings::app_id] = application_impl.app_id();
+ application[hmi_response::policy_app_id] = application_impl.policy_app_id();
+ application[strings::icon] = application_impl.app_icon_path();
+
+ const smart_objects::SmartObject* ngn_media_screen_name =
+ application_impl.ngn_media_screen_name();
+ if (ngn_media_screen_name) {
+ application[strings::ngn_media_screen_app_name] = *ngn_media_screen_name;
+ }
+
+ application[strings::hmi_display_language_desired] =
+ static_cast<int32_t>(application_impl.ui_language());
+
+ application[strings::is_media_application] =
+ application_impl.is_media_application();
+
+ const smart_objects::SmartObject* app_type = application_impl.app_types();
+ if (app_type) {
+ application[strings::app_type] = *app_type;
+ }
+
+ std::vector<std::string> request_types =
+ GetPolicyHandler().GetAppRequestTypes(application_impl.policy_app_id());
+
+ application[strings::request_type] = SmartObject(SmartType_Array);
+ smart_objects::SmartObject& request_array =
+ application[strings::request_type];
+
+ uint32_t index = 0;
+ std::vector<std::string>::const_iterator it = request_types.begin();
+ for (; request_types.end() != it; ++it) {
+ request_array[index] = *it;
+ ++index;
+ }
+
+ application[strings::device_info] = SmartObject(SmartType_Map);
+ smart_objects::SmartObject& device_info = application[strings::device_info];
+ const protocol_handler::SessionObserver& session_observer =
+ application_manager_.connection_handler().get_session_observer();
+ std::string device_name;
+ std::string mac_address;
+ std::string transport_type;
+ const connection_handler::DeviceHandle handle = application_impl.device();
+ if (-1 ==
+ session_observer.GetDataOnDeviceID(
+ handle, &device_name, NULL, &mac_address, &transport_type)) {
+ LOG4CXX_ERROR(logger_,
+ "Failed to extract information for device " << handle);
+ }
+
+ device_info[strings::name] = device_name;
+ device_info[strings::id] = mac_address;
+
+ const policy::DeviceConsent device_consent =
+ GetPolicyHandler().GetUserConsentForDevice(mac_address);
+ device_info[strings::isSDLAllowed] =
+ policy::DeviceConsent::kDeviceAllowed == device_consent;
+
+ device_info[strings::transport_type] =
+ application_manager_.GetDeviceTransportType(transport_type);
+
+ DCHECK(application_manager_.ManageHMICommand(notification));
}
mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckCoincidence() {
LOG4CXX_AUTO_TRACE(logger_);
- const smart_objects::SmartObject &msg_params =
+ const smart_objects::SmartObject& msg_params =
(*message_)[strings::msg_params];
- ApplicationManagerImpl::ApplicationListAccessor accessor;
+ ApplicationSet accessor = application_manager_.applications().GetData();
- ApplicationManagerImpl::ApplictionSetConstIt it = accessor.begin();
- const std::string app_name = msg_params[strings::app_name].asString();
+ ApplicationSetConstIt it = accessor.begin();
+ const custom_str::CustomString& app_name =
+ msg_params[strings::app_name].asCustomString();
for (; accessor.end() != it; ++it) {
-
// name check
- const std::string &cur_name = (*it)->name();
- if (!strcasecmp(app_name.c_str(), cur_name.c_str())) {
+ const custom_str::CustomString& cur_name = (*it)->name();
+ if (app_name.CompareIgnoreCase(cur_name)) {
LOG4CXX_ERROR(logger_, "Application name is known already.");
return mobile_apis::Result::DUPLICATE_NAME;
}
- const smart_objects::SmartObject *vr = (*it)->vr_synonyms();
- const std::vector<smart_objects::SmartObject> *curr_vr = NULL;
+ const smart_objects::SmartObject* vr = (*it)->vr_synonyms();
+ const std::vector<smart_objects::SmartObject>* curr_vr = NULL;
if (NULL != vr) {
curr_vr = vr->asArray();
CoincidencePredicateVR v(app_name);
@@ -572,7 +757,7 @@ mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckCoincidence() {
// vr check
if (msg_params.keyExists(strings::vr_synonyms)) {
- const std::vector<smart_objects::SmartObject> *new_vr =
+ const std::vector<smart_objects::SmartObject>* new_vr =
msg_params[strings::vr_synonyms].asArray();
CoincidencePredicateVR v(cur_name);
@@ -580,29 +765,29 @@ mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckCoincidence() {
LOG4CXX_ERROR(logger_, "vr_synonyms duplicated with app_name .");
return mobile_apis::Result::DUPLICATE_NAME;
}
- } // end vr check
+ } // end vr check
- } // application for end
+ } // application for end
return mobile_apis::Result::SUCCESS;
-} // method end
+} // method end
mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckWithPolicyData() {
- LOG4CXX_INFO(logger_, "CheckWithPolicyData");
+ LOG4CXX_AUTO_TRACE(logger_);
// TODO(AOleynik): Check is necessary to allow register application in case
// of disabled policy
// Remove this check, when HMI will support policy
- if (!policy::PolicyHandler::instance()->PolicyEnabled()) {
+ if (!GetPolicyHandler().PolicyEnabled()) {
return mobile_apis::Result::WARNINGS;
}
- smart_objects::SmartObject &message = *message_;
+ smart_objects::SmartObject& message = *message_;
policy::StringArray app_nicknames;
policy::StringArray app_hmi_types;
- std::string mobile_app_id =
+ const std::string mobile_app_id =
message[strings::msg_params][strings::app_id].asString();
- const bool init_result = policy::PolicyHandler::instance()->GetInitialAppData(
+ const bool init_result = GetPolicyHandler().GetInitialAppData(
mobile_app_id, &app_nicknames, &app_hmi_types);
if (!init_result) {
@@ -612,7 +797,7 @@ mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckWithPolicyData() {
if (!app_nicknames.empty()) {
IsSameNickname compare(
- message[strings::msg_params][strings::app_name].asString());
+ message[strings::msg_params][strings::app_name].asCustomString());
policy::StringArray::const_iterator it =
std::find_if(app_nicknames.begin(), app_nicknames.end(), compare);
if (app_nicknames.end() == it) {
@@ -621,8 +806,9 @@ mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckWithPolicyData() {
// App should be unregistered, if its name is not present in nicknames
// list
usage_statistics::AppCounter count_of_rejections_nickname_mismatch(
- policy::PolicyHandler::instance()->GetStatisticManager(),
- mobile_app_id, usage_statistics::REJECTIONS_NICKNAME_MISMATCH);
+ GetPolicyHandler().GetStatisticManager(),
+ mobile_app_id,
+ usage_statistics::REJECTIONS_NICKNAME_MISMATCH);
++count_of_rejections_nickname_mismatch;
return mobile_apis::Result::DISALLOWED;
}
@@ -642,9 +828,10 @@ mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckWithPolicyData() {
CheckMissedTypes checker(app_hmi_types, log);
std::for_each(app_types.begin(), app_types.end(), checker);
if (!log.empty()) {
- response_info_ = "Following AppHMITypes are not present in policy "
- "table:" +
- log;
+ response_info_ =
+ "Following AppHMITypes are not present in policy "
+ "table:" +
+ log;
result_checking_app_hmi_type_ = mobile_apis::Result::WARNINGS;
}
}
@@ -652,7 +839,7 @@ mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckWithPolicyData() {
message[strings::msg_params][strings::app_hmi_type] =
smart_objects::SmartObject(smart_objects::SmartType_Array);
- smart_objects::SmartObject &app_hmi_type =
+ smart_objects::SmartObject& app_hmi_type =
message[strings::msg_params][strings::app_hmi_type];
AppHMITypeInserter inserter(app_hmi_type);
@@ -663,7 +850,7 @@ mobile_apis::Result::eType RegisterAppInterfaceRequest::CheckWithPolicyData() {
}
void RegisterAppInterfaceRequest::FillDeviceInfo(
- policy::DeviceInfo *device_info) {
+ policy::DeviceInfo* device_info) {
const std::string hardware = "hardware";
const std::string firmware_rev = "firmwareRev";
const std::string os = "os";
@@ -671,10 +858,10 @@ void RegisterAppInterfaceRequest::FillDeviceInfo(
const std::string carrier = "carrier";
const std::string max_number_rfcom_ports = "maxNumberRFCOMMPorts";
- const smart_objects::SmartObject &msg_params =
+ const smart_objects::SmartObject& msg_params =
(*message_)[strings::msg_params];
- const smart_objects::SmartObject &device_info_so =
+ const smart_objects::SmartObject& device_info_so =
msg_params[strings::device_info];
if (device_info_so.keyExists(hardware)) {
@@ -701,22 +888,19 @@ void RegisterAppInterfaceRequest::FillDeviceInfo(
}
bool RegisterAppInterfaceRequest::IsApplicationWithSameAppIdRegistered() {
+ LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_INFO(logger_, "RegisterAppInterfaceRequest::"
- "IsApplicationWithSameAppIdRegistered");
+ const custom_string::CustomString mobile_app_id =
+ (*message_)[strings::msg_params][strings::app_id].asCustomString();
- const std::string mobile_app_id =
- (*message_)[strings::msg_params][strings::app_id].asString();
+ const ApplicationSet& applications =
+ application_manager_.applications().GetData();
- ApplicationManagerImpl::ApplicationListAccessor accessor;
- const ApplicationManagerImpl::ApplictionSet applications =
- accessor.applications();
-
- ApplicationManagerImpl::ApplictionSetConstIt it = applications.begin();
- ApplicationManagerImpl::ApplictionSetConstIt it_end = applications.end();
+ ApplicationSetConstIt it = applications.begin();
+ ApplicationSetConstIt it_end = applications.end();
for (; it != it_end; ++it) {
- if (!strcasecmp(mobile_app_id.c_str(), (*it)->mobile_app_id().c_str())) {
+ if (mobile_app_id.CompareIgnoreCase((*it)->policy_app_id().c_str())) {
return true;
}
}
@@ -726,7 +910,7 @@ bool RegisterAppInterfaceRequest::IsApplicationWithSameAppIdRegistered() {
bool RegisterAppInterfaceRequest::IsWhiteSpaceExist() {
LOG4CXX_AUTO_TRACE(logger_);
- const char *str = NULL;
+ const char* str = NULL;
str = (*message_)[strings::msg_params][strings::app_name].asCharArray();
if (!CheckSyntax(str)) {
@@ -735,7 +919,7 @@ bool RegisterAppInterfaceRequest::IsWhiteSpaceExist() {
}
if ((*message_)[strings::msg_params].keyExists(strings::tts_name)) {
- const smart_objects::SmartArray *tn_array =
+ const smart_objects::SmartArray* tn_array =
(*message_)[strings::msg_params][strings::tts_name].asArray();
smart_objects::SmartArray::const_iterator it_tn = tn_array->begin();
@@ -762,7 +946,7 @@ bool RegisterAppInterfaceRequest::IsWhiteSpaceExist() {
}
if ((*message_)[strings::msg_params].keyExists(strings::vr_synonyms)) {
- const smart_objects::SmartArray *vs_array =
+ const smart_objects::SmartArray* vs_array =
(*message_)[strings::msg_params][strings::vr_synonyms].asArray();
smart_objects::SmartArray::const_iterator it_vs = vs_array->begin();
@@ -786,7 +970,6 @@ bool RegisterAppInterfaceRequest::IsWhiteSpaceExist() {
}
if ((*message_)[strings::msg_params].keyExists(strings::device_info)) {
-
if ((*message_)[strings::msg_params][strings::device_info].keyExists(
strings::hardware)) {
str = (*message_)[strings::msg_params][strings::device_info]
@@ -849,12 +1032,14 @@ bool RegisterAppInterfaceRequest::IsWhiteSpaceExist() {
return true;
}
}
+
return false;
}
void RegisterAppInterfaceRequest::CheckResponseVehicleTypeParam(
- smart_objects::SmartObject &vehicle_type, const std::string &param,
- const std::string &backup_value) {
+ smart_objects::SmartObject& vehicle_type,
+ const std::string& param,
+ const std::string& backup_value) {
using namespace hmi_response;
if (!vehicle_type.keyExists(param) || vehicle_type[param].empty()) {
if (!backup_value.empty()) {
@@ -879,6 +1064,11 @@ void RegisterAppInterfaceRequest::SendSubscribeCustomButtonNotification() {
CreateHMINotification(FunctionID::Buttons_OnButtonSubscription, msg_params);
}
-} // namespace commands
+policy::PolicyHandlerInterface&
+RegisterAppInterfaceRequest::GetPolicyHandler() {
+ return application_manager_.GetPolicyHandler();
+}
+
+} // namespace commands
-} // namespace application_manager
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/register_app_interface_response.cc b/src/components/application_manager/src/commands/mobile/register_app_interface_response.cc
index b910881273..1d7f829a68 100644
--- a/src/components/application_manager/src/commands/mobile/register_app_interface_response.cc
+++ b/src/components/application_manager/src/commands/mobile/register_app_interface_response.cc
@@ -33,9 +33,10 @@
#include "application_manager/commands/mobile/register_app_interface_response.h"
#include "interfaces/MOBILE_API.h"
-#include "application_manager/policies/policy_handler.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
+#include "application_manager/policies/policy_handler_interface.h"
#include "connection_handler/connection_handler.h"
+#include "application_manager/policies/policy_handler_interface.h"
namespace application_manager {
@@ -44,7 +45,7 @@ namespace commands {
void RegisterAppInterfaceResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- mobile_apis::Result::eType result_code = mobile_apis::Result::INVALID_ENUM;
+ mobile_apis::Result::eType result_code = mobile_apis::Result::SUCCESS;
bool success = (*message_)[strings::msg_params][strings::success].asBool();
bool last_message = !success;
// Do not close connection in case of APPLICATION_NOT_REGISTERED despite it is
@@ -60,46 +61,48 @@ void RegisterAppInterfaceResponse::Run() {
SendResponse(success, result_code, last_message);
+ if (mobile_apis::Result::SUCCESS != result_code) {
+ return;
+ }
+
// Add registered application to the policy db right after response sent to
// mobile to be able to check all other API according to app permissions
application_manager::ApplicationSharedPtr application =
- application_manager::ApplicationManagerImpl::instance()->application(
- connection_key());
-
+ application_manager_.application(connection_key());
if (!application) {
- LOG4CXX_ERROR(logger_, "Application with connection key "
- << connection_key() << " is not registered.");
+ LOG4CXX_ERROR(logger_,
+ "Application with connection key " << connection_key()
+ << " is not registered.");
return;
}
- SetHeartBeatTimeout(connection_key(), application->mobile_app_id());
+ SetHeartBeatTimeout(connection_key(), application->policy_app_id());
// Default HMI level should be set before any permissions validation, since it
// relies on HMI level.
- ApplicationManagerImpl::instance()->OnApplicationRegistered(application);
+ application_manager_.OnApplicationRegistered(application);
// Sends OnPermissionChange notification to mobile right after RAI response
// and HMI level set-up
- policy::PolicyHandler::instance()->OnAppRegisteredOnMobile(
- application->mobile_app_id());
+ application_manager_.GetPolicyHandler().OnAppRegisteredOnMobile(
+ application->policy_app_id());
}
void RegisterAppInterfaceResponse::SetHeartBeatTimeout(
- uint32_t connection_key, const std::string &mobile_app_id) {
+ uint32_t connection_key, const std::string& mobile_app_id) {
LOG4CXX_AUTO_TRACE(logger_);
- policy::PolicyHandler *policy_handler = policy::PolicyHandler::instance();
- if (policy_handler->PolicyEnabled()) {
- const int32_t timeout = policy_handler->HeartBeatTimeout(mobile_app_id) /
- date_time::DateTime::MILLISECONDS_IN_SECOND;
+ policy::PolicyHandlerInterface& policy_handler =
+ application_manager_.GetPolicyHandler();
+ if (policy_handler.PolicyEnabled()) {
+ const uint32_t timeout = policy_handler.HeartBeatTimeout(mobile_app_id);
if (timeout > 0) {
- application_manager::ApplicationManagerImpl::instance()
- ->connection_handler()
- ->SetHeartBeatTimeout(connection_key, timeout);
+ application_manager_.connection_handler().SetHeartBeatTimeout(
+ connection_key, timeout);
}
} else {
LOG4CXX_INFO(logger_, "Policy is turn off");
}
}
-} // namespace commands
-} // namespace application_manager
+} // namespace commands
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/reset_global_properties_request.cc b/src/components/application_manager/src/commands/mobile/reset_global_properties_request.cc
index 2e1483eff6..e47ed01f51 100644
--- a/src/components/application_manager/src/commands/mobile/reset_global_properties_request.cc
+++ b/src/components/application_manager/src/commands/mobile/reset_global_properties_request.cc
@@ -32,10 +32,10 @@
*/
#include "application_manager/commands/mobile/reset_global_properties_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
-#include "config_profile/profile.h"
+
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
@@ -44,38 +44,36 @@ namespace application_manager {
namespace commands {
ResetGlobalPropertiesRequest::ResetGlobalPropertiesRequest(
- const MessageSharedPtr& message)
- : CommandRequestImpl(message),
- is_ui_send_(false),
- is_tts_send_(false),
- is_ui_received_(false),
- is_tts_received_(false),
- ui_result_(hmi_apis::Common_Result::INVALID_ENUM),
- tts_result_(hmi_apis::Common_Result::INVALID_ENUM) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager)
+ , is_ui_send_(false)
+ , is_tts_send_(false)
+ , is_ui_received_(false)
+ , is_tts_received_(false)
+ , ui_result_(hmi_apis::Common_Result::INVALID_ENUM)
+ , tts_result_(hmi_apis::Common_Result::INVALID_ENUM) {}
-ResetGlobalPropertiesRequest::~ResetGlobalPropertiesRequest() {
-}
+ResetGlobalPropertiesRequest::~ResetGlobalPropertiesRequest() {}
void ResetGlobalPropertiesRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- uint32_t app_id = (*message_)[strings::params][strings::connection_key].asUInt();
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(app_id);
+ uint32_t app_id =
+ (*message_)[strings::params][strings::connection_key].asUInt();
+ ApplicationSharedPtr app = application_manager_.application(app_id);
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "No application associated with session key");
+ LOG4CXX_ERROR(logger_, "No application associated with session key");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
- size_t obj_length = (*message_)[strings::msg_params][strings::properties]
- .length();
- //if application waits for sending ttsGlobalProperties need to remove this
- //application from tts_global_properties_app_list_
+ size_t obj_length =
+ (*message_)[strings::msg_params][strings::properties].length();
+ // if application waits for sending ttsGlobalProperties need to remove this
+ // application from tts_global_properties_app_list_
LOG4CXX_INFO(logger_, "RemoveAppFromTTSGlobalPropertiesList");
- ApplicationManagerImpl::instance()->RemoveAppFromTTSGlobalPropertiesList(
- app_id);
+ application_manager_.RemoveAppFromTTSGlobalPropertiesList(app_id);
bool helpt_promt = false;
bool timeout_prompt = false;
@@ -96,20 +94,23 @@ void ResetGlobalPropertiesRequest::Run() {
} else if (mobile_apis::GlobalProperty::TIMEOUTPROMPT == global_property) {
timeout_prompt = ResetTimeoutPromt(app);
} else if (((mobile_apis::GlobalProperty::VRHELPTITLE == global_property) ||
- (mobile_apis::GlobalProperty::VRHELPITEMS == global_property)) &&
- (0 == number_of_reset_vr)) {
+ (mobile_apis::GlobalProperty::VRHELPITEMS ==
+ global_property)) &&
+ (0 == number_of_reset_vr)) {
++number_of_reset_vr;
vr_help_title_items = ResetVrHelpTitleItems(app);
} else if (mobile_apis::GlobalProperty::MENUNAME == global_property) {
menu_name = true;
} else if (mobile_apis::GlobalProperty::MENUICON == global_property) {
menu_icon = true;
- } else if (mobile_apis::GlobalProperty::KEYBOARDPROPERTIES == global_property) {
+ } else if (mobile_apis::GlobalProperty::KEYBOARDPROPERTIES ==
+ global_property) {
is_key_board_properties = true;
}
}
- if (vr_help_title_items || menu_name || menu_icon || is_key_board_properties) {
+ if (vr_help_title_items || menu_name || menu_icon ||
+ is_key_board_properties) {
is_ui_send_ = true;
}
@@ -119,13 +120,14 @@ void ResetGlobalPropertiesRequest::Run() {
app->set_reset_global_properties_active(true);
- if (vr_help_title_items || menu_name || menu_icon || is_key_board_properties) {
-
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ if (vr_help_title_items || menu_name || menu_icon ||
+ is_key_board_properties) {
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
if (vr_help_title_items) {
- smart_objects::SmartObjectSPtr vr_help = MessageHelper::CreateAppVrHelp(app);
+ smart_objects::SmartObjectSPtr vr_help =
+ MessageHelper::CreateAppVrHelp(app);
if (!vr_help) {
return;
}
@@ -135,19 +137,20 @@ void ResetGlobalPropertiesRequest::Run() {
msg_params[hmi_request::menu_title] = "";
app->set_menu_title(msg_params[hmi_request::menu_title]);
}
- //TODO(DT): clarify the sending parameter menuIcon
- //if (menu_icon) {
+ // TODO(DT): clarify the sending parameter menuIcon
+ // if (menu_icon) {
//}
if (is_key_board_properties) {
- smart_objects::SmartObject key_board_properties = smart_objects::
- SmartObject(smart_objects::SmartType_Map);
- key_board_properties[strings::language] = static_cast<int32_t>
- (hmi_apis::Common_Language::EN_US);
- key_board_properties[hmi_request::keyboard_layout] = static_cast<int32_t>
- (hmi_apis::Common_KeyboardLayout::QWERTY);
+ smart_objects::SmartObject key_board_properties =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ key_board_properties[strings::language] =
+ static_cast<int32_t>(hmi_apis::Common_Language::EN_US);
+ key_board_properties[hmi_request::keyboard_layout] =
+ static_cast<int32_t>(hmi_apis::Common_KeyboardLayout::QWERTY);
// Look for APPLINK-4432 for details.
- /*smart_objects::SmartObject limited_character_list = smart_objects::SmartObject(
+ /*smart_objects::SmartObject limited_character_list =
+ smart_objects::SmartObject(
smart_objects::SmartType_Array);
limited_character_list[0] = "";
key_board_properties[hmi_request::limited_character_list] =
@@ -158,14 +161,14 @@ void ResetGlobalPropertiesRequest::Run() {
}
msg_params[strings::app_id] = app->app_id();
- SendHMIRequest(hmi_apis::FunctionID::UI_SetGlobalProperties,
- &msg_params, true);
+ SendHMIRequest(
+ hmi_apis::FunctionID::UI_SetGlobalProperties, &msg_params, true);
}
if (timeout_prompt || helpt_promt) {
// create ui request
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
if (helpt_promt) {
msg_params[strings::help_prompt] = (*app->help_prompt());
@@ -177,20 +180,20 @@ void ResetGlobalPropertiesRequest::Run() {
msg_params[strings::app_id] = app->app_id();
- SendHMIRequest(hmi_apis::FunctionID::TTS_SetGlobalProperties,
- &msg_params, true);
+ SendHMIRequest(
+ hmi_apis::FunctionID::TTS_SetGlobalProperties, &msg_params, true);
}
}
bool ResetGlobalPropertiesRequest::ResetHelpPromt(
application_manager::ApplicationSharedPtr app) {
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "Null pointer");
+ LOG4CXX_ERROR(logger_, "Null pointer");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return false;
}
- smart_objects::SmartObject so_help_prompt = smart_objects::SmartObject(
- smart_objects::SmartType_Array);
+ smart_objects::SmartObject so_help_prompt =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
app->set_help_prompt(so_help_prompt);
return true;
}
@@ -198,20 +201,20 @@ bool ResetGlobalPropertiesRequest::ResetHelpPromt(
bool ResetGlobalPropertiesRequest::ResetTimeoutPromt(
application_manager::ApplicationSharedPtr const app) {
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "Null pointer");
+ LOG4CXX_ERROR(logger_, "Null pointer");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return false;
}
- const std::vector<std::string>& time_out_promt = profile::Profile::instance()
- ->time_out_promt();
+ const std::vector<std::string>& time_out_promt =
+ application_manager_.get_settings().time_out_promt();
- smart_objects::SmartObject so_time_out_promt = smart_objects::SmartObject(
- smart_objects::SmartType_Array);
+ smart_objects::SmartObject so_time_out_promt =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
for (uint32_t i = 0; i < time_out_promt.size(); ++i) {
- smart_objects::SmartObject timeoutPrompt = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject timeoutPrompt =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
timeoutPrompt[strings::text] = time_out_promt[i];
timeoutPrompt[strings::type] = hmi_apis::Common_SpeechCapabilities::SC_TEXT;
so_time_out_promt[i] = timeoutPrompt;
@@ -225,7 +228,7 @@ bool ResetGlobalPropertiesRequest::ResetTimeoutPromt(
bool ResetGlobalPropertiesRequest::ResetVrHelpTitleItems(
application_manager::ApplicationSharedPtr const app) {
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "Null pointer");
+ LOG4CXX_ERROR(logger_, "Null pointer");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return false;
}
@@ -240,37 +243,38 @@ void ResetGlobalPropertiesRequest::on_event(const event_engine::Event& event) {
const smart_objects::SmartObject& message = event.smart_object();
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
switch (event.id()) {
- case hmi_apis::FunctionID::UI_SetGlobalProperties: {
- LOG4CXX_INFO(logger_, "Received UI_SetGlobalProperties event");
- is_ui_received_ = true;
- ui_result_ = static_cast<hmi_apis::Common_Result::eType>(
- message[strings::params][hmi_response::code].asInt());
- break;
- }
- case hmi_apis::FunctionID::TTS_SetGlobalProperties: {
- LOG4CXX_INFO(logger_, "Received TTS_SetGlobalProperties event");
- is_tts_received_ = true;
- tts_result_ = static_cast<hmi_apis::Common_Result::eType>(
- message[strings::params][hmi_response::code].asInt());
- break;
- }
- default: {
- LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
- return;
- }
+ case hmi_apis::FunctionID::UI_SetGlobalProperties: {
+ LOG4CXX_INFO(logger_, "Received UI_SetGlobalProperties event");
+ is_ui_received_ = true;
+ ui_result_ = static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asInt());
+ break;
+ }
+ case hmi_apis::FunctionID::TTS_SetGlobalProperties: {
+ LOG4CXX_INFO(logger_, "Received TTS_SetGlobalProperties event");
+ is_tts_received_ = true;
+ tts_result_ = static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asInt());
+ break;
+ }
+ default: {
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
+ return;
+ }
}
if (!IsPendingResponseExist()) {
- bool result = ((hmi_apis::Common_Result::SUCCESS == ui_result_)
- && (hmi_apis::Common_Result::SUCCESS == tts_result_ ||
- hmi_apis::Common_Result::UNSUPPORTED_RESOURCE == tts_result_))
- || ((hmi_apis::Common_Result::SUCCESS == ui_result_)
- && (hmi_apis::Common_Result::INVALID_ENUM == tts_result_))
- || ((hmi_apis::Common_Result::INVALID_ENUM == ui_result_)
- && (hmi_apis::Common_Result::SUCCESS == tts_result_));
+ bool result =
+ ((hmi_apis::Common_Result::SUCCESS == ui_result_) &&
+ (hmi_apis::Common_Result::SUCCESS == tts_result_ ||
+ hmi_apis::Common_Result::UNSUPPORTED_RESOURCE == tts_result_)) ||
+ ((hmi_apis::Common_Result::SUCCESS == ui_result_) &&
+ (hmi_apis::Common_Result::INVALID_ENUM == tts_result_)) ||
+ ((hmi_apis::Common_Result::INVALID_ENUM == ui_result_) &&
+ (hmi_apis::Common_Result::SUCCESS == tts_result_));
mobile_apis::Result::eType result_code;
const char* return_info = NULL;
@@ -278,21 +282,24 @@ void ResetGlobalPropertiesRequest::on_event(const event_engine::Event& event) {
if (result) {
if (hmi_apis::Common_Result::UNSUPPORTED_RESOURCE == tts_result_) {
result_code = mobile_apis::Result::WARNINGS;
- return_info = std::string("Unsupported phoneme type sent in a prompt").c_str();
+ return_info =
+ std::string("Unsupported phoneme type sent in a prompt").c_str();
} else {
result_code = static_cast<mobile_apis::Result::eType>(
- std::max(ui_result_, tts_result_));
+ std::max(ui_result_, tts_result_));
}
} else {
result_code = static_cast<mobile_apis::Result::eType>(
- std::max(ui_result_, tts_result_));
+ std::max(ui_result_, tts_result_));
}
- SendResponse(result, static_cast<mobile_apis::Result::eType>(result_code),
- return_info, &(message[strings::msg_params]));
+ SendResponse(result,
+ static_cast<mobile_apis::Result::eType>(result_code),
+ return_info,
+ &(message[strings::msg_params]));
if (!application) {
- LOG4CXX_DEBUG(logger_, "NULL pointer");
+ LOG4CXX_ERROR(logger_, "NULL pointer");
return;
}
@@ -304,7 +311,6 @@ void ResetGlobalPropertiesRequest::on_event(const event_engine::Event& event) {
}
}
-
bool ResetGlobalPropertiesRequest::IsPendingResponseExist() {
return is_ui_send_ != is_ui_received_ || is_tts_send_ != is_tts_received_;
}
diff --git a/src/components/application_manager/src/commands/mobile/reset_global_properties_response.cc b/src/components/application_manager/src/commands/mobile/reset_global_properties_response.cc
index 8e562956ae..c621977868 100644
--- a/src/components/application_manager/src/commands/mobile/reset_global_properties_response.cc
+++ b/src/components/application_manager/src/commands/mobile/reset_global_properties_response.cc
@@ -32,24 +32,21 @@
*/
#include "application_manager/commands/mobile/reset_global_properties_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
ResetGlobalPropertiesResponse::ResetGlobalPropertiesResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-ResetGlobalPropertiesResponse::~ResetGlobalPropertiesResponse() {
-}
+ResetGlobalPropertiesResponse::~ResetGlobalPropertiesResponse() {}
void ResetGlobalPropertiesResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/scrollable_message_request.cc b/src/components/application_manager/src/commands/mobile/scrollable_message_request.cc
index 10f080e0e7..89bd43fcd6 100644
--- a/src/components/application_manager/src/commands/mobile/scrollable_message_request.cc
+++ b/src/components/application_manager/src/commands/mobile/scrollable_message_request.cc
@@ -33,27 +33,27 @@
#include <string.h>
#include "application_manager/commands/mobile/scrollable_message_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
+#include "application_manager/policies/policy_handler.h"
#include "application_manager/message_helper.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
+#include "utils/helpers.h"
namespace application_manager {
namespace commands {
ScrollableMessageRequest::ScrollableMessageRequest(
- const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {
subscribe_on_event(hmi_apis::FunctionID::UI_OnResetTimeout);
}
-ScrollableMessageRequest::~ScrollableMessageRequest() {
-}
+ScrollableMessageRequest::~ScrollableMessageRequest() {}
bool ScrollableMessageRequest::Init() {
-
/* Timeout in milliseconds.
If omitted a standard value of 10000 milliseconds is used.*/
if ((*message_)[strings::msg_params].keyExists(strings::timeout)) {
@@ -70,8 +70,7 @@ bool ScrollableMessageRequest::Init() {
void ScrollableMessageRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = application_manager::ApplicationManagerImpl::instance()
- ->application((*message_)[strings::params][strings::connection_key].asUInt());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
LOG4CXX_ERROR(logger_, "Application is not registered");
@@ -79,10 +78,13 @@ void ScrollableMessageRequest::Run() {
return;
}
- //ProcessSoftButtons checks strings on the contents incorrect character
+ // ProcessSoftButtons checks strings on the contents incorrect character
mobile_apis::Result::eType processing_result =
- MessageHelper::ProcessSoftButtons((*message_)[strings::msg_params], app);
+ MessageHelper::ProcessSoftButtons((*message_)[strings::msg_params],
+ app,
+ application_manager_.GetPolicyHandler(),
+ application_manager_);
if (mobile_apis::Result::SUCCESS != processing_result) {
LOG4CXX_ERROR(logger_, "Wrong soft buttons parameters!");
@@ -90,13 +92,12 @@ void ScrollableMessageRequest::Run() {
return;
}
-
-
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[hmi_request::message_text][hmi_request::field_name] =
- static_cast<int32_t>(hmi_apis::Common_TextFieldName::scrollableMessageBody);
+ static_cast<int32_t>(
+ hmi_apis::Common_TextFieldName::scrollableMessageBody);
msg_params[hmi_request::message_text][hmi_request::field_text] =
(*message_)[strings::msg_params][strings::scroll_message_body];
msg_params[strings::app_id] = app->app_id();
@@ -114,36 +115,41 @@ void ScrollableMessageRequest::Run() {
void ScrollableMessageRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
case hmi_apis::FunctionID::UI_OnResetTimeout: {
LOG4CXX_INFO(logger_, "Received UI_OnResetTimeout event");
- ApplicationManagerImpl::instance()->updateRequestTimeout(connection_key(),
- correlation_id(),
- default_timeout());
+ application_manager_.updateRequestTimeout(
+ connection_key(), correlation_id(), default_timeout());
break;
}
case hmi_apis::FunctionID::UI_ScrollableMessage: {
LOG4CXX_INFO(logger_, "Received UI_ScrollableMessage event");
mobile_apis::Result::eType result_code =
- static_cast<mobile_apis::Result::eType>
- (message[strings::params][hmi_response::code].asInt());
+ static_cast<mobile_apis::Result::eType>(
+ message[strings::params][hmi_response::code].asInt());
+
HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
- bool result = false;
- if (mobile_apis::Result::SUCCESS == result_code) {
- result = true;
- } else if ((mobile_apis::Result::UNSUPPORTED_RESOURCE == result_code) &&
+ application_manager_.hmi_capabilities();
+
+ bool result = Compare<mobile_api::Result::eType, EQ, ONE>(
+ result_code,
+ mobile_api::Result::SUCCESS,
+ mobile_api::Result::WARNINGS);
+
+ if (mobile_apis::Result::UNSUPPORTED_RESOURCE == result_code &&
hmi_capabilities.is_ui_cooperating()) {
result = true;
}
+
SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
break;
}
default: {
- LOG4CXX_ERROR(logger_,"Received unknown event" << event.id());
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
break;
}
}
@@ -151,4 +157,3 @@ void ScrollableMessageRequest::on_event(const event_engine::Event& event) {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/mobile/scrollable_message_response.cc b/src/components/application_manager/src/commands/mobile/scrollable_message_response.cc
index 212a3ba912..a5b16bdb70 100644
--- a/src/components/application_manager/src/commands/mobile/scrollable_message_response.cc
+++ b/src/components/application_manager/src/commands/mobile/scrollable_message_response.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/scrollable_message_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "interfaces/HMI_API.h"
#include "interfaces/MOBILE_API.h"
@@ -41,22 +41,21 @@ namespace application_manager {
namespace commands {
ScrollableMessageResponse::ScrollableMessageResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
void ScrollableMessageResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- mobile_apis::Result::eType result_code = static_cast<mobile_apis::Result::eType>(
- (*message_)[strings::msg_params][strings::result_code].asInt());
- ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(
- (*message_)[strings::params][strings::connection_key].asInt());
+ mobile_apis::Result::eType result_code =
+ static_cast<mobile_apis::Result::eType>(
+ (*message_)[strings::msg_params][strings::result_code].asInt());
+ ApplicationSharedPtr application = application_manager_.application(
+ (*message_)[strings::params][strings::connection_key].asInt());
if ((mobile_apis::Result::REJECTED != result_code) && application) {
application->UnsubscribeFromSoftButtons(
(*message_)[strings::params][strings::function_id].asInt());
}
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/send_location_request.cc b/src/components/application_manager/src/commands/mobile/send_location_request.cc
index b1c96ebb98..975f7e43c3 100644
--- a/src/components/application_manager/src/commands/mobile/send_location_request.cc
+++ b/src/components/application_manager/src/commands/mobile/send_location_request.cc
@@ -30,39 +30,51 @@
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
+#include <algorithm>
+
#include "application_manager/commands/mobile/send_location_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/message_helper.h"
+#include "utils/helpers.h"
+#include "utils/custom_string.h"
namespace application_manager {
namespace commands {
-SendLocationRequest::SendLocationRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+SendLocationRequest::SendLocationRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-SendLocationRequest::~SendLocationRequest() {
-}
+SendLocationRequest::~SendLocationRequest() {}
void SendLocationRequest::Run() {
using namespace hmi_apis;
+ using smart_objects::SmartObject;
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = application_manager::ApplicationManagerImpl::instance()
- ->application(connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
- LOG4CXX_ERROR_EXT(logger_,
- "An application with connection key " << connection_key()
- << " is not registered.");
+ LOG4CXX_ERROR(logger_,
+ "An application with connection key "
+ << connection_key() << " is not registered.");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
- const smart_objects::SmartObject& msg_params = (*message_)[strings::msg_params];
- std::list<Common_TextFieldName::eType> fields_to_check;
+ smart_objects::SmartObject& msg_params = (*message_)[strings::msg_params];
+ if (msg_params.keyExists(strings::delivery_mode)) {
+ const std::vector<std::string>& allowed_params =
+ parameters_permissions().allowed_params;
+ if (allowed_params.end() == std::find(allowed_params.begin(),
+ allowed_params.end(),
+ strings::delivery_mode)) {
+ msg_params.erase(strings::delivery_mode);
+ }
+ }
+ std::vector<Common_TextFieldName::eType> fields_to_check;
if (msg_params.keyExists(strings::location_name)) {
fields_to_check.push_back(Common_TextFieldName::locationName);
}
@@ -87,11 +99,27 @@ void SendLocationRequest::Run() {
return;
}
- if ((*message_)[strings::msg_params].keyExists(strings::location_image)) {
+ if (msg_params.keyExists(strings::address)) {
+ const utils::custom_string::CustomString& address =
+ msg_params[strings::address].asCustomString();
+ if (address.empty()) {
+ msg_params.erase(strings::address);
+ }
+ }
+
+ if (!CheckFieldsCompatibility()) {
+ LOG4CXX_ERROR(logger_, "CheckFieldsCompatibility failed");
+ SendResponse(false, mobile_apis::Result::INVALID_DATA);
+ return;
+ }
+
+ if (msg_params.keyExists(strings::location_image)) {
mobile_apis::Result::eType verification_result =
mobile_apis::Result::SUCCESS;
verification_result = MessageHelper::VerifyImage(
- (*message_)[strings::msg_params][strings::location_image], app);
+ (*message_)[strings::msg_params][strings::location_image],
+ app,
+ application_manager_);
if (mobile_apis::Result::SUCCESS != verification_result) {
LOG4CXX_ERROR(logger_, "VerifyImage INVALID_DATA!");
SendResponse(false, verification_result);
@@ -99,61 +127,76 @@ void SendLocationRequest::Run() {
}
}
- smart_objects::SmartObject request_msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- request_msg_params = (*message_)[strings::msg_params];
+ SmartObject request_msg_params = SmartObject(smart_objects::SmartType_Map);
+ request_msg_params = msg_params;
request_msg_params[strings::app_id] = app->hmi_app_id();
-
- SendHMIRequest(hmi_apis::FunctionID::Navigation_SendLocation,
- &request_msg_params, true);
+ SendHMIRequest(
+ hmi_apis::FunctionID::Navigation_SendLocation, &request_msg_params, true);
}
void SendLocationRequest::on_event(const event_engine::Event& event) {
- LOG4CXX_INFO(logger_, "SendLocationRquest::on_event");
+ LOG4CXX_AUTO_TRACE(logger_);
+ namespace Result = mobile_apis::Result;
+ using namespace helpers;
const smart_objects::SmartObject& message = event.smart_object();
- switch (event.id()) {
- case hmi_apis::FunctionID::Navigation_SendLocation: {
- LOG4CXX_INFO(logger_, "Received Navigation_SendLocation event");
- mobile_apis::Result::eType result_code = GetMobileResultCode(
- static_cast<hmi_apis::Common_Result::eType>(
- message[strings::params][hmi_response::code].asUInt()));
- bool result =
- mobile_apis::Result::SUCCESS == result_code ||
- mobile_apis::Result::WARNINGS == result_code ||
- mobile_apis::Result::UNSUPPORTED_RESOURCE == result_code ;
- SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
- break;
- }
- default: {
- LOG4CXX_ERROR(logger_,"Received unknown event" << event.id());
- break;
- }
+ if (hmi_apis::FunctionID::Navigation_SendLocation == event.id()) {
+ LOG4CXX_INFO(logger_, "Received Navigation_SendLocation event");
+ mobile_apis::Result::eType result_code =
+ GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asUInt()));
+ const bool result =
+ Compare<Result::eType, EQ, ONE>(result_code,
+ Result::SAVED,
+ Result::SUCCESS,
+ Result::WARNINGS,
+ Result::UNSUPPORTED_RESOURCE);
+ SendResponse(result, result_code, NULL, &(message[strings::params]));
+ return;
}
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
}
-bool SendLocationRequest::IsWhiteSpaceExist() {
- LOG4CXX_INFO(logger_, "SendLocationRquest::IsWhiteSpaceExist");
- const char* str;
+bool SendLocationRequest::CheckFieldsCompatibility() {
const smart_objects::SmartObject& msg_params =
(*message_)[strings::msg_params];
-
- if (msg_params.keyExists(strings::location_name)) {
- str = msg_params[strings::location_name].asCharArray();
- if (!CheckSyntax(str)) {
- LOG4CXX_ERROR(logger_,
- "parameter locationName contains invalid character");
- return true;
- }
+ MessageHelper::PrintSmartObject(msg_params);
+ const bool longitude_degrees_exist =
+ msg_params.keyExists(strings::longitude_degrees);
+ const bool latitude_degrees_exist =
+ msg_params.keyExists(strings::latitude_degrees);
+ const bool address_exist = msg_params.keyExists(strings::address);
+
+ if (latitude_degrees_exist ^ longitude_degrees_exist) {
+ LOG4CXX_DEBUG(logger_,
+ "latitude and longitude should be provided only in pair");
+ return false;
}
- if (msg_params.keyExists(strings::location_description)) {
- str = msg_params[strings::location_description].asCharArray();
- if (!CheckSyntax(str)) {
- LOG4CXX_ERROR(logger_,
- "parameter locationDescription contains invalid character");
- return true;
- }
+ if (!address_exist && !longitude_degrees_exist && !latitude_degrees_exist) {
+ LOG4CXX_DEBUG(logger_,
+ "address or latitude/longtitude should should be provided");
+ return false;
+ }
+ return true;
+}
+void insert_if_contains(
+ const smart_objects::SmartObject& msg_params,
+ const std::string& param_key,
+ std::vector<utils::custom_string::CustomString>& output_vector) {
+ if (msg_params.keyExists(param_key)) {
+ output_vector.push_back(msg_params[param_key].asCustomString());
}
+}
+
+bool SendLocationRequest::IsWhiteSpaceExist() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ std::vector<utils::custom_string::CustomString> fields_to_check;
+ const smart_objects::SmartObject& msg_params =
+ (*message_)[strings::msg_params];
+ insert_if_contains(msg_params, strings::location_name, fields_to_check);
+ insert_if_contains(
+ msg_params, strings::location_description, fields_to_check);
+ insert_if_contains(msg_params, strings::phone_number, fields_to_check);
if (msg_params.keyExists(strings::address_lines)) {
const smart_objects::SmartArray* al_array =
@@ -161,60 +204,63 @@ bool SendLocationRequest::IsWhiteSpaceExist() {
smart_objects::SmartArray::const_iterator it_al = al_array->begin();
smart_objects::SmartArray::const_iterator it_al_end = al_array->end();
for (; it_al != it_al_end; ++it_al) {
- str = (*it_al).asCharArray();
- if(!CheckSyntax(str)) {
- LOG4CXX_ERROR(logger_,
- "parameter address_lines contains invalid character");
- return true;
- }
+ const utils::custom_string::CustomString& val = (*it_al).asCustomString();
+ fields_to_check.push_back(val);
}
}
- if (msg_params.keyExists(strings::phone_number)) {
- str = msg_params[strings::phone_number].asCharArray();
- if (!CheckSyntax(str)) {
- LOG4CXX_ERROR(logger_,
- "parameter phoneNumber contains invalid character");
- return true;
- }
+ if (msg_params.keyExists(strings::address)) {
+ const smart_objects::SmartObject& address_so = msg_params[strings::address];
+ insert_if_contains(address_so, strings::country_name, fields_to_check);
+ insert_if_contains(address_so, strings::country_code, fields_to_check);
+ insert_if_contains(address_so, strings::postal_code, fields_to_check);
+ insert_if_contains(
+ address_so, strings::administrative_area, fields_to_check);
+ insert_if_contains(address_so, strings::locality, fields_to_check);
+ insert_if_contains(address_so, strings::sub_locality, fields_to_check);
+ insert_if_contains(address_so, strings::thoroughfare, fields_to_check);
+ insert_if_contains(address_so, strings::sub_thoroughfare, fields_to_check);
}
- if (msg_params.keyExists(strings::location_image)) {
- str = msg_params[strings::location_image][strings::value].asCharArray();
- if (!CheckSyntax(str)) {
+ std::vector<utils::custom_string::CustomString>::iterator it =
+ fields_to_check.begin();
+ for (; it != fields_to_check.end(); ++it) {
+ const std::string& str = it->AsMBString();
+ if (!CheckSyntax(str, false)) {
LOG4CXX_ERROR(logger_,
- "parameter value in locationImage contains invalid character");
+ "string '" << str << "'' contains invalid characters");
return true;
}
}
-
return false;
}
-bool SendLocationRequest::CheckHMICapabilities(std::list<hmi_apis::Common_TextFieldName::eType>& fields_names) {
+bool SendLocationRequest::CheckHMICapabilities(
+ std::vector<hmi_apis::Common_TextFieldName::eType>& fields_names) {
using namespace smart_objects;
using namespace hmi_apis;
-
if (fields_names.empty()) {
return true;
}
- ApplicationManagerImpl* instance = ApplicationManagerImpl::instance();
- const HMICapabilities& hmi_capabilities = instance->hmi_capabilities();
+ const HMICapabilities& hmi_capabilities =
+ application_manager_.hmi_capabilities();
if (!hmi_capabilities.is_ui_cooperating()) {
- LOG4CXX_ERROR_EXT(logger_, "UI is not supported.");
+ LOG4CXX_ERROR(logger_, "UI is not supported.");
return false;
}
if (hmi_capabilities.display_capabilities()) {
const SmartObject disp_cap = (*hmi_capabilities.display_capabilities());
- const SmartObject& text_fields = disp_cap.getElement(hmi_response::text_fields);
+ const SmartObject& text_fields =
+ disp_cap.getElement(hmi_response::text_fields);
const size_t len = text_fields.length();
for (size_t i = 0; i < len; ++i) {
const SmartObject& text_field = text_fields[i];
const Common_TextFieldName::eType filed_name =
- static_cast<Common_TextFieldName::eType>(text_field.getElement(strings::name).asInt());
- const std::list<Common_TextFieldName::eType>::iterator it =
+ static_cast<Common_TextFieldName::eType>(
+ text_field.getElement(strings::name).asInt());
+ const std::vector<Common_TextFieldName::eType>::iterator it =
std::find(fields_names.begin(), fields_names.end(), filed_name);
if (it != fields_names.end()) {
fields_names.erase(it);
@@ -223,7 +269,7 @@ bool SendLocationRequest::CheckHMICapabilities(std::list<hmi_apis::Common_TextFi
}
if (!fields_names.empty()) {
- LOG4CXX_ERROR_EXT(logger_, "Some fields are not supported by capabilities");
+ LOG4CXX_ERROR(logger_, "Some fields are not supported by capabilities");
return false;
}
return true;
diff --git a/src/components/application_manager/src/commands/mobile/send_location_response.cc b/src/components/application_manager/src/commands/mobile/send_location_response.cc
index 32756c999d..167642e390 100644
--- a/src/components/application_manager/src/commands/mobile/send_location_response.cc
+++ b/src/components/application_manager/src/commands/mobile/send_location_response.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/send_location_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/HMI_API.h"
@@ -40,17 +40,16 @@ namespace application_manager {
namespace commands {
-SendLocationResponse::SendLocationResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+SendLocationResponse::SendLocationResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-SendLocationResponse::~SendLocationResponse() {
-}
+SendLocationResponse::~SendLocationResponse() {}
void SendLocationResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/set_app_icon_request.cc b/src/components/application_manager/src/commands/mobile/set_app_icon_request.cc
index bd9c9fa0cb..40b708e30d 100644
--- a/src/components/application_manager/src/commands/mobile/set_app_icon_request.cc
+++ b/src/components/application_manager/src/commands/mobile/set_app_icon_request.cc
@@ -31,38 +31,35 @@
POSSIBILITY OF SUCH DAMAGE.
*/
+#include <algorithm>
#include "application_manager/commands/mobile/set_app_icon_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
-#include "config_profile/profile.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
#include "utils/file_system.h"
+#include "utils/helpers.h"
namespace application_manager {
namespace commands {
-int8_t SetAppIconRequest::is_icons_saving_enabled_ = -1;
-
-SetAppIconRequest::SetAppIconRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
- if (-1 == is_icons_saving_enabled_) {
- const std::string path = profile::Profile::instance()->app_icons_folder();
- is_icons_saving_enabled_ =
- file_system::IsWritingAllowed(path) &&
- file_system::IsReadingAllowed(path);
- }
+SetAppIconRequest::SetAppIconRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager)
+ , is_icons_saving_enabled_(false) {
+ const std::string path =
+ application_manager_.get_settings().app_icons_folder();
+ is_icons_saving_enabled_ = file_system::IsWritingAllowed(path) &&
+ file_system::IsReadingAllowed(path);
}
-SetAppIconRequest::~SetAppIconRequest() {
-}
+SetAppIconRequest::~SetAppIconRequest() {}
void SetAppIconRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
LOG4CXX_ERROR(logger_, "Application is not registered");
@@ -74,7 +71,7 @@ void SetAppIconRequest::Run() {
(*message_)[strings::msg_params][strings::sync_file_name].asString();
std::string full_file_path =
- profile::Profile::instance()->app_storage_folder() + "/";
+ application_manager_.get_settings().app_storage_folder() + "/";
full_file_path += app->folder_name();
full_file_path += "/";
full_file_path += sync_file_name;
@@ -89,22 +86,22 @@ void SetAppIconRequest::Run() {
CopyToIconStorage(full_file_path);
}
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::app_id] = app->app_id();
- msg_params[strings::sync_file_name] = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ msg_params[strings::sync_file_name] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
-// Panasonic requres unchanged path value without encoded special characters
- const std::string full_file_path_for_hmi = file_system::ConvertPathForURL(
- full_file_path);
+ // Panasonic requres unchanged path value without encoded special characters
+ const std::string full_file_path_for_hmi =
+ file_system::ConvertPathForURL(full_file_path);
msg_params[strings::sync_file_name][strings::value] = full_file_path_for_hmi;
// TODO(VS): research why is image_type hardcoded
msg_params[strings::sync_file_name][strings::image_type] =
- static_cast<int32_t> (SetAppIconRequest::ImageType::DYNAMIC);
+ static_cast<int32_t>(SetAppIconRequest::ImageType::DYNAMIC);
// for further use in on_event function
(*message_)[strings::msg_params][strings::sync_file_name] =
@@ -114,38 +111,41 @@ void SetAppIconRequest::Run() {
}
void SetAppIconRequest::CopyToIconStorage(
- const std::string& path_to_file) const {
- if (!profile::Profile::instance()->enable_protocol_4()) {
+ const std::string& path_to_file) const {
+ if (!application_manager_.protocol_handler()
+ .get_settings()
+ .enable_protocol_4()) {
LOG4CXX_WARN(logger_,
"Icon copying skipped, since protocol ver. 4 is not enabled.");
return;
}
std::vector<uint8_t> file_content;
- if(!file_system::ReadBinaryFile(path_to_file, file_content)) {
+ if (!file_system::ReadBinaryFile(path_to_file, file_content)) {
LOG4CXX_ERROR(logger_, "Can't read icon file: " << path_to_file);
return;
}
const std::string icon_storage =
- profile::Profile::instance()->app_icons_folder();
- const uint64_t storage_max_size =
- static_cast<uint64_t>(
- profile::Profile::instance()->app_icons_folder_max_size());
+ application_manager_.get_settings().app_icons_folder();
+ const uint64_t storage_max_size = static_cast<uint64_t>(
+ application_manager_.get_settings().app_icons_folder_max_size());
const uint64_t file_size = file_system::FileSize(path_to_file);
if (storage_max_size < file_size) {
- LOG4CXX_ERROR(logger_, "Icon size (" << file_size << ") is bigger, than "
- " icons storage maximum size (" << storage_max_size << ")."
- "Copying skipped.");
+ LOG4CXX_ERROR(logger_,
+ "Icon size (" << file_size << ") is bigger, than "
+ " icons storage maximum size ("
+ << storage_max_size << ")."
+ "Copying skipped.");
return;
}
- const uint64_t storage_size = static_cast<uint64_t>(
- file_system::DirectorySize(icon_storage));
+ const uint64_t storage_size =
+ static_cast<uint64_t>(file_system::DirectorySize(icon_storage));
if (storage_max_size < (file_size + storage_size)) {
const uint32_t icons_amount =
- profile::Profile::instance()->app_icons_amount_to_remove();
+ application_manager_.get_settings().app_icons_amount_to_remove();
if (!icons_amount) {
LOG4CXX_DEBUG(logger_,
@@ -159,17 +159,16 @@ void SetAppIconRequest::CopyToIconStorage(
}
}
ApplicationConstSharedPtr app =
- application_manager::ApplicationManagerImpl::instance()->
- application(connection_key());
+ application_manager_.application(connection_key());
if (!app) {
- LOG4CXX_ERROR(logger_, "Can't get application for connection key: "
- << connection_key());
+ LOG4CXX_ERROR(
+ logger_,
+ "Can't get application for connection key: " << connection_key());
return;
}
- const std::string icon_path =
- icon_storage + "/" + app->mobile_app_id();
+ const std::string icon_path = icon_storage + "/" + app->policy_app_id();
if (!file_system::CreateFile(icon_path)) {
LOG4CXX_ERROR(logger_, "Can't create icon: " << icon_path);
return;
@@ -180,8 +179,9 @@ void SetAppIconRequest::CopyToIconStorage(
return;
}
- LOG4CXX_DEBUG(logger_, "Icon was successfully copied from :" << path_to_file
- << " to " << icon_path);
+ LOG4CXX_DEBUG(logger_,
+ "Icon was successfully copied from :" << path_to_file << " to "
+ << icon_path);
return;
}
@@ -191,7 +191,7 @@ void SetAppIconRequest::RemoveOldestIcons(const std::string& storage,
const std::vector<std::string> icons_list = file_system::ListFiles(storage);
std::map<uint64_t, std::string> icon_modification_time;
std::vector<std::string>::const_iterator it = icons_list.begin();
- for (;it != icons_list.end(); ++it) {
+ for (; it != icons_list.end(); ++it) {
const std::string file_name = *it;
const std::string file_path = storage + "/" + file_name;
if (!file_system::FileExists(file_path)) {
@@ -212,53 +212,56 @@ void SetAppIconRequest::RemoveOldestIcons(const std::string& storage,
LOG4CXX_DEBUG(logger_, "Error while deleting icon " << file_path);
}
icon_modification_time.erase(icon_modification_time.begin());
- LOG4CXX_DEBUG(logger_, "Old icon " << file_path
- << " was deleted successfully.");
+ LOG4CXX_DEBUG(logger_,
+ "Old icon " << file_path << " was deleted successfully.");
}
}
bool SetAppIconRequest::IsEnoughSpaceForIcon(const uint64_t icon_size) const {
const std::string icon_storage =
- profile::Profile::instance()->app_icons_folder();
- const uint64_t storage_max_size =
- static_cast<uint64_t>(
- profile::Profile::instance()->app_icons_folder_max_size());
- const uint64_t storage_size = static_cast<uint64_t>(
- file_system::DirectorySize(icon_storage));
+ application_manager_.get_settings().app_icons_folder();
+ const uint64_t storage_max_size = static_cast<uint64_t>(
+ application_manager_.get_settings().app_icons_folder_max_size());
+ const uint64_t storage_size =
+ static_cast<uint64_t>(file_system::DirectorySize(icon_storage));
return storage_max_size >= (icon_size + storage_size);
}
void SetAppIconRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
- const smart_objects::SmartObject& event_message = event.smart_object();
+ using namespace helpers;
+ const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
case hmi_apis::FunctionID::UI_SetAppIcon: {
mobile_apis::Result::eType result_code =
static_cast<mobile_apis::Result::eType>(
- event_message[strings::params][hmi_response::code].asInt());
+ message[strings::params][hmi_response::code].asInt());
- bool result = mobile_apis::Result::SUCCESS == result_code;
+ const bool result = Compare<mobile_api::Result::eType, EQ, ONE>(
+ result_code,
+ mobile_api::Result::SUCCESS,
+ mobile_api::Result::WARNINGS);
if (result) {
ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (!message_.valid() || !app.valid()) {
- LOG4CXX_ERROR(logger_, "NULL pointer.");
- return;
+ LOG4CXX_ERROR(logger_, "NULL pointer.");
+ return;
}
- const std::string path = (*message_)[strings::msg_params]
- [strings::sync_file_name]
- [strings::value].asString();
+ const std::string& path =
+ (*message_)[strings::msg_params][strings::sync_file_name]
+ [strings::value].asString();
app->set_app_icon_path(path);
LOG4CXX_INFO(logger_,
"Icon path was set to '" << app->app_icon_path() << "'");
}
- SendResponse(result, result_code, NULL, &(event_message[strings::msg_params]));
+ SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
break;
}
default: {
diff --git a/src/components/application_manager/src/commands/mobile/set_app_icon_response.cc b/src/components/application_manager/src/commands/mobile/set_app_icon_response.cc
index 563490bd46..29f3950ffc 100644
--- a/src/components/application_manager/src/commands/mobile/set_app_icon_response.cc
+++ b/src/components/application_manager/src/commands/mobile/set_app_icon_response.cc
@@ -32,23 +32,21 @@
*/
#include "application_manager/commands/mobile/set_app_icon_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-SetAppIconResponse::SetAppIconResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+SetAppIconResponse::SetAppIconResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-SetAppIconResponse::~SetAppIconResponse() {
-}
+SetAppIconResponse::~SetAppIconResponse() {}
void SetAppIconResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/set_display_layout_request.cc b/src/components/application_manager/src/commands/mobile/set_display_layout_request.cc
index f3d9e28c04..6cb6318791 100644
--- a/src/components/application_manager/src/commands/mobile/set_display_layout_request.cc
+++ b/src/components/application_manager/src/commands/mobile/set_display_layout_request.cc
@@ -32,26 +32,23 @@
*/
#include "application_manager/commands/mobile/set_display_layout_request.h"
-#include "application_manager/application_manager_impl.h"
-#include "application_manager/application_impl.h"
+#include "application_manager/application_impl.h"
namespace application_manager {
namespace commands {
SetDisplayLayoutRequest::SetDisplayLayoutRequest(
- const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-SetDisplayLayoutRequest::~SetDisplayLayoutRequest() {
-}
+SetDisplayLayoutRequest::~SetDisplayLayoutRequest() {}
void SetDisplayLayoutRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationConstSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (!app) {
LOG4CXX_ERROR(logger_, "Application is not registered");
@@ -61,8 +58,8 @@ void SetDisplayLayoutRequest::Run() {
(*message_)[strings::msg_params][strings::app_id] = app->app_id();
SendHMIRequest(hmi_apis::FunctionID::UI_SetDisplayLayout,
- &((*message_)[strings::msg_params]), true);
-
+ &((*message_)[strings::msg_params]),
+ true);
}
void SetDisplayLayoutRequest::on_event(const event_engine::Event& event) {
@@ -74,21 +71,25 @@ void SetDisplayLayoutRequest::on_event(const event_engine::Event& event) {
LOG4CXX_INFO(logger_, "Received UI_SetDisplayLayout event");
mobile_apis::Result::eType result_code =
- static_cast<mobile_apis::Result::eType>(
- message[strings::params][hmi_response::code].asInt());
+ static_cast<mobile_apis::Result::eType>(
+ message[strings::params][hmi_response::code].asInt());
bool response_success = mobile_apis::Result::SUCCESS == result_code;
smart_objects::SmartObject msg_params = message[strings::msg_params];
if (response_success) {
HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ application_manager_.hmi_capabilities();
// in case templates_available is empty copy from hmi capabilities
if (msg_params.keyExists(hmi_response::display_capabilities)) {
- if (0 == msg_params[hmi_response::display_capabilities][hmi_response::templates_available].length()) {
- msg_params[hmi_response::display_capabilities][hmi_response::templates_available] =
- hmi_capabilities.display_capabilities()->getElement(hmi_response::templates_available);
+ if (0 ==
+ msg_params[hmi_response::display_capabilities]
+ [hmi_response::templates_available].length()) {
+ msg_params[hmi_response::display_capabilities]
+ [hmi_response::templates_available] =
+ hmi_capabilities.display_capabilities()->getElement(
+ hmi_response::templates_available);
}
}
}
@@ -96,7 +97,7 @@ void SetDisplayLayoutRequest::on_event(const event_engine::Event& event) {
break;
}
default: {
- LOG4CXX_ERROR(logger_,"Received unknown event" << event.id());
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
return;
}
}
diff --git a/src/components/application_manager/src/commands/mobile/set_display_layout_response.cc b/src/components/application_manager/src/commands/mobile/set_display_layout_response.cc
index 3844b3bf05..b5e53803c8 100644
--- a/src/components/application_manager/src/commands/mobile/set_display_layout_response.cc
+++ b/src/components/application_manager/src/commands/mobile/set_display_layout_response.cc
@@ -33,25 +33,21 @@
#include "application_manager/commands/mobile/set_display_layout_response.h"
#include "application_manager/application_impl.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
SetDisplayLayoutResponse::SetDisplayLayoutResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-SetDisplayLayoutResponse::~SetDisplayLayoutResponse() {
-}
+SetDisplayLayoutResponse::~SetDisplayLayoutResponse() {}
void SetDisplayLayoutResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
-
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/set_global_properties_request.cc b/src/components/application_manager/src/commands/mobile/set_global_properties_request.cc
index 1c0948d07e..171b902df1 100644
--- a/src/components/application_manager/src/commands/mobile/set_global_properties_request.cc
+++ b/src/components/application_manager/src/commands/mobile/set_global_properties_request.cc
@@ -1,6 +1,5 @@
/*
-
- Copyright (c) 2013, Ford Motor Company
+ Copyright (c) 2015, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -34,29 +33,27 @@
#include <string.h>
#include <algorithm>
#include "application_manager/commands/mobile/set_global_properties_request.h"
-#include "application_manager/application_manager_impl.h"
-#include "application_manager/application_impl.h"
+
#include "application_manager/message_helper.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
+#include "utils/helpers.h"
namespace application_manager {
namespace commands {
SetGlobalPropertiesRequest::SetGlobalPropertiesRequest(
- const MessageSharedPtr& message)
- : CommandRequestImpl(message),
- is_ui_send_(false),
- is_tts_send_(false),
- is_ui_received_(false),
- is_tts_received_(false),
- ui_result_(hmi_apis::Common_Result::INVALID_ENUM),
- tts_result_(hmi_apis::Common_Result::INVALID_ENUM) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager)
+ , is_ui_send_(false)
+ , is_tts_send_(false)
+ , is_ui_received_(false)
+ , is_tts_received_(false)
+ , ui_result_(hmi_apis::Common_Result::INVALID_ENUM)
+ , tts_result_(hmi_apis::Common_Result::INVALID_ENUM) {}
-SetGlobalPropertiesRequest::~SetGlobalPropertiesRequest() {
-}
+SetGlobalPropertiesRequest::~SetGlobalPropertiesRequest() {}
void SetGlobalPropertiesRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -64,13 +61,12 @@ void SetGlobalPropertiesRequest::Run() {
const smart_objects::SmartObject& msg_params =
(*message_)[strings::msg_params];
- uint32_t app_id =
- (*message_)[strings::params][strings::connection_key].asUInt();
-
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(app_id);
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "No application associated with session key");
+ LOG4CXX_ERROR(logger_,
+ "No application associated with connection key "
+ << connection_key());
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
@@ -86,230 +82,144 @@ void SetGlobalPropertiesRequest::Run() {
if ((*message_)[strings::msg_params].keyExists(strings::menu_icon)) {
verification_result = MessageHelper::VerifyImage(
- (*message_)[strings::msg_params][strings::menu_icon], app);
+ (*message_)[strings::msg_params][strings::menu_icon],
+ app,
+ application_manager_);
if (mobile_apis::Result::SUCCESS != verification_result) {
- LOG4CXX_ERROR_EXT(
- logger_,
- "MessageHelper::VerifyImage return " << verification_result);
+ LOG4CXX_ERROR(
+ logger_, "MessageHelper::VerifyImage return " << verification_result);
SendResponse(false, verification_result);
return;
}
}
// Check for image file(s) in vrHelpItem
if ((*message_)[strings::msg_params].keyExists(strings::vr_help)) {
- if (mobile_apis::Result::SUCCESS != MessageHelper::VerifyImageVrHelpItems(
- (*message_)[strings::msg_params][strings::vr_help], app)) {
- LOG4CXX_ERROR_EXT(
- logger_,
- "MessageHelper::VerifyImage return INVALID_DATA!" );
+ if (mobile_apis::Result::SUCCESS !=
+ MessageHelper::VerifyImageVrHelpItems(
+ (*message_)[strings::msg_params][strings::vr_help],
+ app,
+ application_manager_)) {
+ LOG4CXX_ERROR(logger_, "MessageHelper::VerifyImage return INVALID_DATA!");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
}
if (IsWhiteSpaceExist()) {
+ LOG4CXX_ERROR(logger_, "White spaces found");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
- //if application waits for sending ttsGlobalProperties need to remove this
- //application from tts_global_properties_app_list_
- LOG4CXX_INFO(logger_, "RemoveAppFromTTSGlobalPropertiesList");
- ApplicationManagerImpl::instance()->RemoveAppFromTTSGlobalPropertiesList(
- app_id);
+ // if application waits for sending ttsGlobalProperties need to remove this
+ // application from tts_global_properties_app_list_
+ application_manager_.RemoveAppFromTTSGlobalPropertiesList(connection_key());
bool is_help_prompt_present = msg_params.keyExists(strings::help_prompt);
- bool is_timeout_prompt_present = msg_params.keyExists(
- strings::timeout_prompt);
+ bool is_timeout_prompt_present =
+ msg_params.keyExists(strings::timeout_prompt);
bool is_vr_help_title_present = msg_params.keyExists(strings::vr_help_title);
bool is_vr_help_present = msg_params.keyExists(strings::vr_help);
- bool is_menu_title_present = msg_params.keyExists(hmi_request::menu_title);
- bool is_menu_icon_present = msg_params.keyExists(hmi_request::menu_icon);
- bool is_keyboard_props_present =
- msg_params.keyExists(hmi_request::keyboard_properties);
-
- // Media-only applications support API v2.1 with less parameters
- // Code deleted according to APPLINK-6119 APPLINK-6133
- // Not sure that it is right
-
-// if (!app->allowed_support_navigation() &&
-// (is_keyboard_props_present ||
-// is_menu_icon_present ||
-// is_menu_title_present)
-// ) {
-// const std::string app_type =
-// app->is_media_application() ? "media" : "non-media";
-
-// const std::string message =
-// "There are too many parameters for "+app_type+" application.";
-// SendResponse(false,
-// mobile_apis::Result::INVALID_DATA,
-// message.c_str());
-// return;
-// }
-
- if ((is_vr_help_title_present && is_vr_help_present) ||
- (!is_vr_help_title_present && !is_vr_help_present)) {
- is_ui_send_ = true;
- }
- if (is_help_prompt_present || is_timeout_prompt_present) {
- is_tts_send_ = true;
+ // check VR params
+ if (is_vr_help_title_present ^ is_vr_help_present) {
+ LOG4CXX_ERROR(logger_,
+ "Reject because of vr_help or vr_help_title only provided");
+ SendResponse(false, mobile_apis::Result::REJECTED);
+ return;
}
-
if (is_vr_help_title_present && is_vr_help_present) {
- // check vrhelpitem position index
- if (!CheckVrHelpItemsOrder()) {
- LOG4CXX_ERROR(logger_, "Request rejected");
+ LOG4CXX_DEBUG(logger_, "VRHelp params presents");
+
+ if (!CheckVrHelpItemsOrder(msg_params[strings::vr_help])) {
+ LOG4CXX_ERROR(logger_,
+ "VR Help Items contains nonsequential positions"
+ << " (e.g. [1,2,4]) or not started from 1");
SendResponse(false, mobile_apis::Result::REJECTED);
return;
}
- app->set_vr_help_title(
- msg_params.getElement(strings::vr_help_title));
- app->set_vr_help(
- msg_params.getElement(strings::vr_help));
-
smart_objects::SmartObject params =
smart_objects::SmartObject(smart_objects::SmartType_Map);
- params[strings::vr_help_title] = (*app->vr_help_title());
- params[strings::vr_help] = (*app->vr_help());
- params[strings::app_id] = app->app_id();
- if (is_menu_title_present) {
-
- params[hmi_request::menu_title] =
- msg_params[hmi_request::menu_title].asString();
- app->set_menu_title(msg_params[hmi_request::menu_title]);
- }
- if (is_menu_icon_present) {
+ PrepareUIRequestVRHelpData(app, msg_params, params);
+ PrepareUIRequestMenuAndKeyboardData(app, msg_params, params);
- params[hmi_request::menu_icon] =
- msg_params[hmi_request::menu_icon];
- app->set_menu_icon(msg_params[hmi_request::menu_icon]);
- }
- if (is_keyboard_props_present) {
+ params[strings::app_id] = app->app_id();
+ SendUIRequest(params, true);
+ } else {
+ LOG4CXX_DEBUG(logger_, "VRHelp params does not present");
+ DCHECK_OR_RETURN_VOID(!is_vr_help_title_present && !is_vr_help_present);
- params[hmi_request::keyboard_properties] =
- msg_params[hmi_request::keyboard_properties];
- app->set_keyboard_props(msg_params[hmi_request::keyboard_properties]);
- }
+ smart_objects::SmartObject params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
- SendHMIRequest(hmi_apis::FunctionID::UI_SetGlobalProperties,
- &params, true);
- } else if (!is_vr_help_title_present && !is_vr_help_present) {
- const DataAccessor<CommandsMap> accessor = app->commands_map();
- const CommandsMap& cmdMap = accessor.GetData();
- CommandsMap::const_iterator command_it = cmdMap.begin();
-
- int32_t index = 0;
- smart_objects::SmartObject vr_help_items;
- for (; cmdMap.end() != command_it; ++command_it) {
- if (false == (*command_it->second).keyExists(strings::vr_commands)) {
- LOG4CXX_ERROR(logger_, "VR synonyms are empty");
+ if (ValidateVRHelpTitle(app->vr_help_title())) {
+ LOG4CXX_DEBUG(logger_, "App already contains VRHelp data");
+ } else {
+ if (!PrepareUIRequestDefaultVRHelpData(app, params)) {
+ LOG4CXX_ERROR(logger_, "default VRHElp data could not be generated");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
- // use only first
- vr_help_items[index][strings::position] = (index + 1);
- vr_help_items[index++][strings::text] =
- (*command_it->second)[strings::vr_commands][0];
}
+ PrepareUIRequestMenuAndKeyboardData(app, msg_params, params);
- app->set_vr_help_title(smart_objects::SmartObject(app->name()));
-
- smart_objects::SmartObject params =
- smart_objects::SmartObject(smart_objects::SmartType_Map);
-
- params[strings::vr_help_title] = (*app->vr_help_title());
- if (vr_help_items.length() > 0) {
- app->set_vr_help(vr_help_items);
- params[strings::vr_help] = (*app->vr_help());
- }
- params[strings::app_id] = app->app_id();
- if (is_menu_title_present) {
-
- params[hmi_request::menu_title] =
- msg_params[hmi_request::menu_title].asString();
- app->set_menu_title(msg_params[hmi_request::menu_title]);
- }
- if (is_menu_icon_present) {
-
- params[hmi_request::menu_icon] =
- msg_params[hmi_request::menu_icon];
- app->set_menu_icon(msg_params[hmi_request::menu_icon]);
- }
- if (is_keyboard_props_present) {
-
- params[hmi_request::keyboard_properties] =
- msg_params[hmi_request::keyboard_properties];
- app->set_keyboard_props(msg_params[hmi_request::keyboard_properties]);
+ // Preparing data
+ if (params.empty()) {
+ LOG4CXX_DEBUG(logger_, "No UI info provided");
+ } else {
+ params[strings::app_id] = app->app_id();
+ SendUIRequest(params, true);
}
-
- SendHMIRequest(hmi_apis::FunctionID::UI_SetGlobalProperties,
- &params, true);
- } else {
- LOG4CXX_ERROR(logger_, "Request rejected");
- SendResponse(false, mobile_apis::Result::REJECTED);
- return;
}
-
// check TTS params
if (is_help_prompt_present || is_timeout_prompt_present) {
+ LOG4CXX_DEBUG(logger_, "TTS params presents");
smart_objects::SmartObject params =
smart_objects::SmartObject(smart_objects::SmartType_Map);
if (is_help_prompt_present) {
- app->set_help_prompt(
- msg_params.getElement(strings::help_prompt));
+ app->set_help_prompt(msg_params.getElement(strings::help_prompt));
params[strings::help_prompt] = (*app->help_prompt());
}
if (is_timeout_prompt_present) {
- app->set_timeout_prompt(
- msg_params.getElement(strings::timeout_prompt));
+ app->set_timeout_prompt(msg_params.getElement(strings::timeout_prompt));
params[strings::timeout_prompt] = (*app->timeout_prompt());
}
params[strings::app_id] = app->app_id();
-
- SendHMIRequest(hmi_apis::FunctionID::TTS_SetGlobalProperties,
- &params, true);
+ SendTTSRequest(params, true);
}
}
-bool SetGlobalPropertiesRequest::CheckVrHelpItemsOrder() {
- const smart_objects::SmartObject vr_help = (*message_)[strings::msg_params]
- .getElement(strings::vr_help);
-
- // vr help item start position must be 1
- const uint32_t vr_help_item_start_position = 1;
-
- if (vr_help_item_start_position !=
- vr_help.getElement(0).getElement(strings::position).asUInt()) {
- LOG4CXX_ERROR(logger_, "VR help items start position is wrong");
- return false;
- }
-
- // Check if VR Help Items contains sequential positionss
- size_t i = 0;
- for (size_t j = 1; j < vr_help.length(); ++i, ++j) {
- if ((vr_help.getElement(i).getElement(strings::position).asInt() + 1)
- != vr_help.getElement(j).getElement(strings::position).asInt()) {
- LOG4CXX_ERROR(logger_, "VR help items order is wrong");
+bool SetGlobalPropertiesRequest::CheckVrHelpItemsOrder(
+ const smart_objects::SmartObject& vr_help) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN(vr_help.getType() == smart_objects::SmartType_Array, false);
+ const size_t vr_help_length = vr_help.length();
+ DCHECK_OR_RETURN(vr_help_length > 0, false);
+
+ for (size_t j = 0; j < vr_help_length; ++j) {
+ const size_t position =
+ vr_help.getElement(j).getElement(strings::position).asUInt();
+ // Elements shall start from 1 and increment one by one
+ if (position != (j + 1)) {
+ LOG4CXX_ERROR(logger_,
+ "VR help items order is wrong"
+ << " at " << j << ", position value:" << position);
return false;
}
}
-
return true;
}
void SetGlobalPropertiesRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
const smart_objects::SmartObject& message = event.smart_object();
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(CommandRequestImpl::connection_key());
-
switch (event.id()) {
case hmi_apis::FunctionID::UI_SetGlobalProperties: {
LOG4CXX_INFO(logger_, "Received UI_SetGlobalProperties event");
@@ -331,66 +241,189 @@ void SetGlobalPropertiesRequest::on_event(const event_engine::Event& event) {
}
}
- if (!IsPendingResponseExist()) {
- bool result = ((hmi_apis::Common_Result::SUCCESS == ui_result_)
- && (hmi_apis::Common_Result::SUCCESS == tts_result_ ||
- hmi_apis::Common_Result::UNSUPPORTED_RESOURCE == tts_result_))
- || ((hmi_apis::Common_Result::SUCCESS == ui_result_ ||
- hmi_apis::Common_Result::UNSUPPORTED_RESOURCE == ui_result_)
- && (hmi_apis::Common_Result::INVALID_ENUM == tts_result_))
- || ((hmi_apis::Common_Result::INVALID_ENUM == ui_result_ ||
- hmi_apis::Common_Result::UNSUPPORTED_RESOURCE == ui_result_)
- && (hmi_apis::Common_Result::SUCCESS == tts_result_));
-
- mobile_apis::Result::eType result_code;
- const char* return_info = NULL;
-
- if (result) {
- if (hmi_apis::Common_Result::UNSUPPORTED_RESOURCE == tts_result_) {
- result_code = mobile_apis::Result::WARNINGS;
- return_info =
- std::string("Unsupported phoneme type sent in a prompt").c_str();
- } else {
- result_code = static_cast<mobile_apis::Result::eType>(
- std::max(ui_result_, tts_result_));
- }
- } else {
- result_code = static_cast<mobile_apis::Result::eType>(
- std::max(ui_result_, tts_result_));
- }
+ if (IsPendingResponseExist()) {
+ LOG4CXX_DEBUG(logger_, "Continue waiting for response");
+ return;
+ }
- // TODO(AOleynik): APPLINK-15858
- ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ const bool is_tts_succeeded =
+ Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ tts_result_,
+ hmi_apis::Common_Result::SUCCESS,
+ hmi_apis::Common_Result::UNSUPPORTED_RESOURCE,
+ hmi_apis::Common_Result::WARNINGS);
+
+ const bool is_ui_succeeded = Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ ui_result_,
+ hmi_apis::Common_Result::SUCCESS,
+ hmi_apis::Common_Result::UNSUPPORTED_RESOURCE,
+ hmi_apis::Common_Result::WARNINGS);
+
+ const bool is_ui_invalid_unsupported =
+ Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ ui_result_,
+ hmi_apis::Common_Result::INVALID_ENUM,
+ hmi_apis::Common_Result::UNSUPPORTED_RESOURCE);
+
+ bool result = (is_tts_succeeded && is_ui_succeeded) ||
+ (is_ui_succeeded &&
+ hmi_apis::Common_Result::INVALID_ENUM == tts_result_) ||
+ (is_ui_invalid_unsupported && is_tts_succeeded);
+
+ mobile_apis::Result::eType result_code = mobile_apis::Result::INVALID_ENUM;
+ const char* return_info = NULL;
+
+ const bool is_ui_or_tts_warning =
+ Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ hmi_apis::Common_Result::WARNINGS, tts_result_, ui_result_);
+
+ if (result && (hmi_apis::Common_Result::UNSUPPORTED_RESOURCE == tts_result_ ||
+ is_ui_or_tts_warning)) {
+ result_code = mobile_apis::Result::WARNINGS;
+ return_info =
+ std::string("Unsupported phoneme type sent in a prompt").c_str();
+ } else {
+ result_code =
+ MessageHelper::HMIToMobileResult(std::max(ui_result_, tts_result_));
+ }
- SendResponse(result, result_code, return_info,
- &(message[strings::msg_params]));
+ // TODO{ALeshin} APPLINK-15858. connection_key removed during SendResponse
+ ApplicationSharedPtr application =
+ application_manager_.application(connection_key());
- if (!application) {
- LOG4CXX_DEBUG(logger_, "NULL pointer.");
- return;
- }
+ SendResponse(
+ result, result_code, return_info, &(message[strings::msg_params]));
+
+ if (!application) {
+ LOG4CXX_DEBUG(logger_, "NULL pointer.");
+ return;
+ }
+
+ if (result) {
+ application->UpdateHash();
+ }
+}
- if (result) {
- application->UpdateHash();
+bool SetGlobalPropertiesRequest::ValidateVRHelpTitle(
+ const smart_objects::SmartObject* const vr_help_so_ptr) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (vr_help_so_ptr) {
+ const std::string& vr_help = vr_help_so_ptr->asString();
+ LOG4CXX_TRACE(logger_, "App contains vr_help_title: \"" << vr_help << '"');
+ return !vr_help.empty();
+ }
+ return false;
+}
+
+void SetGlobalPropertiesRequest::PrepareUIRequestVRHelpData(
+ const ApplicationSharedPtr app,
+ const smart_objects::SmartObject& msg_params,
+ smart_objects::SmartObject& out_params) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(app);
+
+ app->set_vr_help_title(msg_params.getElement(strings::vr_help_title));
+ app->set_vr_help(msg_params.getElement(strings::vr_help));
+
+ out_params[strings::vr_help_title] = (*app->vr_help_title());
+ out_params[strings::vr_help] = (*app->vr_help());
+}
+
+bool SetGlobalPropertiesRequest::PrepareUIRequestDefaultVRHelpData(
+ const ApplicationSharedPtr app, smart_objects::SmartObject& out_params) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN(app, false);
+
+ LOG4CXX_DEBUG(logger_, "Generate default VRHelp data");
+ const DataAccessor<CommandsMap> accessor = app->commands_map();
+ const CommandsMap& cmdMap = accessor.GetData();
+
+ int32_t index = 0;
+ smart_objects::SmartObject vr_help_items;
+ for (CommandsMap::const_iterator command_it = cmdMap.begin();
+ cmdMap.end() != command_it;
+ ++command_it) {
+ const smart_objects::SmartObject& command = *command_it->second;
+ if (!command.keyExists(strings::vr_commands)) {
+ LOG4CXX_ERROR(logger_, "VR synonyms are empty");
+ return false;
}
+ // use only first
+ vr_help_items[index][strings::position] = (index + 1);
+ vr_help_items[index++][strings::text] =
+ (*command_it->second)[strings::vr_commands][0];
+ }
+
+ app->set_vr_help_title(smart_objects::SmartObject(app->name()));
+
+ out_params[strings::vr_help_title] = (*app->vr_help_title());
+ if (vr_help_items.length() > 0) {
+ app->set_vr_help(vr_help_items);
+ out_params[strings::vr_help] = (*app->vr_help());
}
+ return true;
}
-bool SetGlobalPropertiesRequest::IsPendingResponseExist() {
+void SetGlobalPropertiesRequest::PrepareUIRequestMenuAndKeyboardData(
+ const ApplicationSharedPtr app,
+ const smart_objects::SmartObject& msg_params,
+ smart_objects::SmartObject& out_params) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(app);
+
+ const bool is_menu_title_present =
+ msg_params.keyExists(hmi_request::menu_title);
+ const bool is_menu_icon_present =
+ msg_params.keyExists(hmi_request::menu_icon);
+ const bool is_keyboard_props_present =
+ msg_params.keyExists(hmi_request::keyboard_properties);
+
+ if (is_menu_title_present) {
+ out_params[hmi_request::menu_title] =
+ msg_params[hmi_request::menu_title].asString();
+ app->set_menu_title(msg_params[hmi_request::menu_title]);
+ }
+ if (is_menu_icon_present) {
+ out_params[hmi_request::menu_icon] = msg_params[hmi_request::menu_icon];
+ app->set_menu_icon(msg_params[hmi_request::menu_icon]);
+ }
+ if (is_keyboard_props_present) {
+ out_params[hmi_request::keyboard_properties] =
+ msg_params[hmi_request::keyboard_properties];
+ app->set_keyboard_props(msg_params[hmi_request::keyboard_properties]);
+ }
+}
+
+void SetGlobalPropertiesRequest::SendTTSRequest(
+ const smart_objects::SmartObject& params, bool use_events) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ SendHMIRequest(
+ hmi_apis::FunctionID::TTS_SetGlobalProperties, &params, use_events);
+ is_tts_send_ = true;
+}
+
+void SetGlobalPropertiesRequest::SendUIRequest(
+ const smart_objects::SmartObject& params, bool use_events) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ SendHMIRequest(
+ hmi_apis::FunctionID::UI_SetGlobalProperties, &params, use_events);
+ is_ui_send_ = true;
+}
+bool SetGlobalPropertiesRequest::IsPendingResponseExist() {
return is_ui_send_ != is_ui_received_ || is_tts_send_ != is_tts_received_;
}
bool SetGlobalPropertiesRequest::ValidateConditionalMandatoryParameters(
const smart_objects::SmartObject& params) {
- return params.keyExists(strings::help_prompt)
- || params.keyExists(strings::timeout_prompt)
- || params.keyExists(strings::vr_help_title)
- || params.keyExists(strings::vr_help)
- || params.keyExists(strings::menu_title)
- || params.keyExists(strings::menu_icon)
- || params.keyExists(strings::keyboard_properties);
+ LOG4CXX_AUTO_TRACE(logger_);
+ return params.keyExists(strings::help_prompt) ||
+ params.keyExists(strings::timeout_prompt) ||
+ params.keyExists(strings::vr_help_title) ||
+ params.keyExists(strings::vr_help) ||
+ params.keyExists(strings::menu_title) ||
+ params.keyExists(strings::menu_icon) ||
+ params.keyExists(strings::keyboard_properties);
}
bool SetGlobalPropertiesRequest::IsWhiteSpaceExist() {
@@ -450,12 +483,11 @@ bool SetGlobalPropertiesRequest::IsWhiteSpaceExist() {
str = (*it_vh)[strings::image][strings::value].asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_,
- "Invalid vr_help image value syntax check failed");
+ "Invalid vr_help image value syntax check failed");
return true;
}
- }
-
- }
+ } // if image exists
+ } // for - vh_array iteration
}
if (msg_params.keyExists(strings::menu_icon)) {
@@ -482,14 +514,12 @@ bool SetGlobalPropertiesRequest::IsWhiteSpaceExist() {
}
}
-
if (msg_params.keyExists(strings::keyboard_properties)) {
- if (msg_params[strings::keyboard_properties].
- keyExists(strings::limited_character_list)) {
-
+ if (msg_params[strings::keyboard_properties].keyExists(
+ strings::limited_character_list)) {
const smart_objects::SmartArray* lcl_array =
msg_params[strings::keyboard_properties]
- [strings::limited_character_list].asArray();
+ [strings::limited_character_list].asArray();
smart_objects::SmartArray::const_iterator it_lcl = lcl_array->begin();
smart_objects::SmartArray::const_iterator it_lcl_end = lcl_array->end();
@@ -497,30 +527,30 @@ bool SetGlobalPropertiesRequest::IsWhiteSpaceExist() {
for (; it_lcl != it_lcl_end; ++it_lcl) {
str = (*it_lcl).asCharArray();
if (!CheckSyntax(str)) {
- LOG4CXX_ERROR(logger_, "Invalid keyboard_properties "
- "limited_character_list syntax check failed");
+ LOG4CXX_ERROR(logger_,
+ "Invalid keyboard_properties "
+ "limited_character_list syntax check failed");
return true;
}
}
}
- if (msg_params[strings::keyboard_properties].
- keyExists(strings::auto_complete_text)) {
-
- str = msg_params[strings::keyboard_properties]
- [strings::auto_complete_text].asCharArray();
+ if (msg_params[strings::keyboard_properties].keyExists(
+ strings::auto_complete_text)) {
+ str =
+ msg_params[strings::keyboard_properties][strings::auto_complete_text]
+ .asCharArray();
if (!CheckSyntax(str)) {
- LOG4CXX_ERROR(logger_, "Invalid keyboard_properties "
- "auto_complete_text syntax check failed");
+ LOG4CXX_ERROR(logger_,
+ "Invalid keyboard_properties "
+ "auto_complete_text syntax check failed");
return true;
}
}
-
}
return false;
}
} // namespace commands
-
} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/set_global_properties_response.cc b/src/components/application_manager/src/commands/mobile/set_global_properties_response.cc
index 759333385d..5cfbcb2d58 100644
--- a/src/components/application_manager/src/commands/mobile/set_global_properties_response.cc
+++ b/src/components/application_manager/src/commands/mobile/set_global_properties_response.cc
@@ -32,25 +32,21 @@
*/
#include "application_manager/commands/mobile/set_global_properties_response.h"
-#include "application_manager/application_manager_impl.h"
-
namespace application_manager {
namespace commands {
SetGlobalPropertiesResponse::SetGlobalPropertiesResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-SetGlobalPropertiesResponse::~SetGlobalPropertiesResponse() {
-}
+SetGlobalPropertiesResponse::~SetGlobalPropertiesResponse() {}
void SetGlobalPropertiesResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/set_icon_request.cc b/src/components/application_manager/src/commands/mobile/set_icon_request.cc
index 4b06730752..85f34aead9 100644
--- a/src/components/application_manager/src/commands/mobile/set_icon_request.cc
+++ b/src/components/application_manager/src/commands/mobile/set_icon_request.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/set_icon_request.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
#include "application_manager/application_impl.h"
#include "config_profile/profile.h"
#include "interfaces/MOBILE_API.h"
@@ -43,18 +43,16 @@ namespace application_manager {
namespace commands {
-SetIconRequest::SetIconRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+SetIconRequest::SetIconRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-SetIconRequest::~SetIconRequest() {
-}
+SetIconRequest::~SetIconRequest() {}
void SetIconRequest::Run() {
- LOG4CXX_INFO(logger_, "SetIconRequest::Run");
+ LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
LOG4CXX_ERROR(logger_, "Application is not registered");
@@ -66,7 +64,7 @@ void SetIconRequest::Run() {
(*message_)[strings::msg_params][strings::sync_file_name].asString();
std::string full_file_path =
- profile::Profile::instance()->app_storage_folder() + "/";
+ application_manager_.get_settings().app_storage_folder() + "/";
full_file_path += app->folder_name();
full_file_path += "/";
full_file_path += sync_file_name;
@@ -77,22 +75,22 @@ void SetIconRequest::Run() {
return;
}
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::app_id] = app->app_id();
- msg_params[strings::sync_file_name] = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ msg_params[strings::sync_file_name] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
-// Panasonic requres unchanged path value without encoded special characters
- const std::string full_file_path_for_hmi = file_system::ConvertPathForURL(
- full_file_path);
+ // Panasonic requres unchanged path value without encoded special characters
+ const std::string full_file_path_for_hmi =
+ file_system::ConvertPathForURL(full_file_path);
msg_params[strings::sync_file_name][strings::value] = full_file_path_for_hmi;
// TODO(VS): research why is image_type hardcoded
msg_params[strings::sync_file_name][strings::image_type] =
- static_cast<int32_t> (SetIconRequest::ImageType::DYNAMIC);
+ static_cast<int32_t>(SetIconRequest::ImageType::DYNAMIC);
// for further use in on_event function
(*message_)[strings::msg_params][strings::sync_file_name] =
@@ -102,7 +100,7 @@ void SetIconRequest::Run() {
}
void SetIconRequest::on_event(const event_engine::Event& event) {
- LOG4CXX_INFO(logger_, "SetIconRequest::on_event");
+ LOG4CXX_AUTO_TRACE(logger_);
const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
@@ -115,11 +113,11 @@ void SetIconRequest::on_event(const event_engine::Event& event) {
if (result) {
ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
- const std::string path = (*message_)[strings::msg_params]
- [strings::sync_file_name]
- [strings::value].asString();
+ const std::string path =
+ (*message_)[strings::msg_params][strings::sync_file_name]
+ [strings::value].asString();
app->set_app_icon_path(path);
LOG4CXX_INFO(logger_,
diff --git a/src/components/application_manager/src/commands/mobile/set_icon_response.cc b/src/components/application_manager/src/commands/mobile/set_icon_response.cc
index f1580823d1..c140d04f51 100644
--- a/src/components/application_manager/src/commands/mobile/set_icon_response.cc
+++ b/src/components/application_manager/src/commands/mobile/set_icon_response.cc
@@ -32,23 +32,22 @@
*/
#include "application_manager/commands/mobile/set_icon_response.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
namespace application_manager {
namespace commands {
-SetIconResponse::SetIconResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+SetIconResponse::SetIconResponse(const MessageSharedPtr& message,
+ ApplicationManager& app_man)
+ : CommandResponseImpl(message, app_man) {}
-SetIconResponse::~SetIconResponse() {
-}
+SetIconResponse::~SetIconResponse() {}
void SetIconResponse::Run() {
- LOG4CXX_INFO(logger_, "SetIconResponse::Run");
+ LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/set_media_clock_timer_request.cc b/src/components/application_manager/src/commands/mobile/set_media_clock_timer_request.cc
index 536bb755ed..a198ce63c3 100644
--- a/src/components/application_manager/src/commands/mobile/set_media_clock_timer_request.cc
+++ b/src/components/application_manager/src/commands/mobile/set_media_clock_timer_request.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/set_media_clock_timer_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
@@ -41,18 +41,16 @@ namespace application_manager {
namespace commands {
-SetMediaClockRequest::SetMediaClockRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+SetMediaClockRequest::SetMediaClockRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-SetMediaClockRequest::~SetMediaClockRequest() {
-}
+SetMediaClockRequest::~SetMediaClockRequest() {}
void SetMediaClockRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
@@ -67,14 +65,14 @@ void SetMediaClockRequest::Run() {
}
if (isDataValid()) {
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
// copy entirely msg
msg_params = (*message_)[strings::msg_params];
msg_params[strings::app_id] = app->app_id();
- SendHMIRequest(hmi_apis::FunctionID::UI_SetMediaClockTimer,
- &msg_params, true);
+ SendHMIRequest(
+ hmi_apis::FunctionID::UI_SetMediaClockTimer, &msg_params, true);
} else {
SendResponse(false, mobile_apis::Result::INVALID_DATA);
}
@@ -110,7 +108,6 @@ bool SetMediaClockRequest::isDataValid() {
if (update_mode == mobile_apis::UpdateMode::COUNTUP ||
update_mode == mobile_apis::UpdateMode::COUNTDOWN) {
-
if (!msg_params.keyExists(strings::start_time)) {
LOG4CXX_INFO(logger_, "Invalid data");
return false;
@@ -134,9 +131,9 @@ bool SetMediaClockRequest::isDataValid() {
(msg_params[strings::end_time][strings::seconds].asUInt());
if (((end_time_in_seconds > start_time_in_seconds) &&
- (update_mode == mobile_apis::UpdateMode::COUNTDOWN)) ||
+ (update_mode == mobile_apis::UpdateMode::COUNTDOWN)) ||
((end_time_in_seconds < start_time_in_seconds) &&
- (update_mode == mobile_apis::UpdateMode::COUNTUP))) {
+ (update_mode == mobile_apis::UpdateMode::COUNTUP))) {
LOG4CXX_INFO(logger_, "Invalid data");
return false;
}
diff --git a/src/components/application_manager/src/commands/mobile/set_media_clock_timer_response.cc b/src/components/application_manager/src/commands/mobile/set_media_clock_timer_response.cc
index da6f204da4..30e802a1db 100644
--- a/src/components/application_manager/src/commands/mobile/set_media_clock_timer_response.cc
+++ b/src/components/application_manager/src/commands/mobile/set_media_clock_timer_response.cc
@@ -32,24 +32,21 @@
*/
#include "application_manager/commands/mobile/set_media_clock_timer_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
SetMediaClockTimerResponse::SetMediaClockTimerResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-SetMediaClockTimerResponse::~SetMediaClockTimerResponse() {
-}
+SetMediaClockTimerResponse::~SetMediaClockTimerResponse() {}
void SetMediaClockTimerResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/show_constant_tbt_request.cc b/src/components/application_manager/src/commands/mobile/show_constant_tbt_request.cc
index 1e861d14ce..2d79e13582 100644
--- a/src/components/application_manager/src/commands/mobile/show_constant_tbt_request.cc
+++ b/src/components/application_manager/src/commands/mobile/show_constant_tbt_request.cc
@@ -31,11 +31,13 @@
POSSIBILITY OF SUCH DAMAGE.
*/
-#include <string.h>
+#include <cstring>
#include "application_manager/commands/mobile/show_constant_tbt_request.h"
-#include "application_manager/application_manager_impl.h"
+
+#include "application_manager/policies/policy_handler.h"
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
+#include "application_manager/policies/policy_handler_interface.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
@@ -43,17 +45,16 @@ namespace application_manager {
namespace commands {
-ShowConstantTBTRequest::ShowConstantTBTRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+ShowConstantTBTRequest::ShowConstantTBTRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-ShowConstantTBTRequest::~ShowConstantTBTRequest() {
-}
+ShowConstantTBTRequest::~ShowConstantTBTRequest() {}
void ShowConstantTBTRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
+ ApplicationSharedPtr app = application_manager_.application(
(*message_)[strings::params][strings::connection_key].asUInt());
if (!app) {
@@ -68,8 +69,8 @@ void ShowConstantTBTRequest::Run() {
return;
}
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params = (*message_)[strings::msg_params];
if (IsWhiteSpaceExist()) {
@@ -79,10 +80,13 @@ void ShowConstantTBTRequest::Run() {
return;
}
- //ProcessSoftButtons checks strings on the contents incorrect character
+ // ProcessSoftButtons checks strings on the contents incorrect character
mobile_apis::Result::eType processing_result =
- MessageHelper::ProcessSoftButtons(msg_params, app);
+ MessageHelper::ProcessSoftButtons(msg_params,
+ app,
+ application_manager_.GetPolicyHandler(),
+ application_manager_);
if (mobile_apis::Result::SUCCESS != processing_result) {
LOG4CXX_ERROR(logger_, "INVALID_DATA!");
@@ -90,12 +94,10 @@ void ShowConstantTBTRequest::Run() {
return;
}
-
- mobile_apis::Result::eType verification_result =
- mobile_apis::Result::SUCCESS;
+ mobile_apis::Result::eType verification_result = mobile_apis::Result::SUCCESS;
if (msg_params.keyExists(strings::turn_icon)) {
verification_result = MessageHelper::VerifyImage(
- msg_params[strings::turn_icon], app);
+ msg_params[strings::turn_icon], app, application_manager_);
if (mobile_apis::Result::SUCCESS != verification_result) {
LOG4CXX_ERROR(logger_, "VerifyImage INVALID_DATA!");
SendResponse(false, verification_result);
@@ -105,7 +107,7 @@ void ShowConstantTBTRequest::Run() {
if (msg_params.keyExists(strings::next_turn_icon)) {
verification_result = MessageHelper::VerifyImage(
- msg_params[strings::next_turn_icon], app);
+ msg_params[strings::next_turn_icon], app, application_manager_);
if (mobile_apis::Result::SUCCESS != verification_result) {
LOG4CXX_ERROR(logger_, "VerifyImage INVALID_DATA!");
SendResponse(false, verification_result);
@@ -115,8 +117,8 @@ void ShowConstantTBTRequest::Run() {
msg_params[strings::app_id] = app->app_id();
- msg_params[hmi_request::navi_texts] = smart_objects::SmartObject(
- smart_objects::SmartType_Array);
+ msg_params[hmi_request::navi_texts] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
int32_t index = 0;
if (msg_params.keyExists(strings::navigation_text_1)) {
@@ -156,24 +158,24 @@ void ShowConstantTBTRequest::Run() {
}
if (msg_params.keyExists(strings::time_to_destination)) {
- // erase useless param
- msg_params.erase(strings::time_to_destination);
- msg_params[hmi_request::navi_texts][index][hmi_request::field_name] =
- static_cast<int32_t>(hmi_apis::Common_TextFieldName::timeToDestination);
- msg_params[hmi_request::navi_texts][index++][hmi_request::field_text] =
- (*message_)[strings::msg_params][strings::time_to_destination];
+ // erase useless param
+ msg_params.erase(strings::time_to_destination);
+ msg_params[hmi_request::navi_texts][index][hmi_request::field_name] =
+ static_cast<int32_t>(hmi_apis::Common_TextFieldName::timeToDestination);
+ msg_params[hmi_request::navi_texts][index++][hmi_request::field_text] =
+ (*message_)[strings::msg_params][strings::time_to_destination];
}
if (msg_params.keyExists(strings::soft_buttons)) {
- MessageHelper::SubscribeApplicationToSoftButton(msg_params, app, function_id());
+ MessageHelper::SubscribeApplicationToSoftButton(
+ msg_params, app, function_id());
}
app->set_tbt_show_command(msg_params);
- SendHMIRequest(hmi_apis::FunctionID::Navigation_ShowConstantTBT, &msg_params,
- true);
+ SendHMIRequest(
+ hmi_apis::FunctionID::Navigation_ShowConstantTBT, &msg_params, true);
}
-
void ShowConstantTBTRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
const smart_objects::SmartObject& message = event.smart_object();
@@ -181,25 +183,31 @@ void ShowConstantTBTRequest::on_event(const event_engine::Event& event) {
switch (event.id()) {
case hmi_apis::FunctionID::Navigation_ShowConstantTBT: {
LOG4CXX_INFO(logger_, "Received Navigation_ShowConstantTBT event");
+ std::string return_info;
mobile_apis::Result::eType result_code =
GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
message[strings::params][hmi_response::code].asInt()));
HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ application_manager_.hmi_capabilities();
bool result = false;
if (mobile_apis::Result::SUCCESS == result_code) {
result = true;
+ return_info =
+ message[strings::msg_params][hmi_response::message].asString();
} else if ((mobile_apis::Result::UNSUPPORTED_RESOURCE == result_code) &&
- hmi_capabilities.is_ui_cooperating()) {
+ hmi_capabilities.is_ui_cooperating()) {
result = true;
}
- SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
+ SendResponse(result,
+ result_code,
+ return_info.empty() ? 0 : return_info.c_str(),
+ &(message[strings::msg_params]));
break;
}
default: {
- LOG4CXX_ERROR(logger_,"Received unknown event" << event.id());
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
break;
}
}
@@ -210,8 +218,8 @@ bool ShowConstantTBTRequest::IsWhiteSpaceExist() {
const char* str = NULL;
if ((*message_)[strings::msg_params].keyExists(strings::turn_icon)) {
- str = (*message_)[strings::msg_params]
- [strings::turn_icon][strings::value].asCharArray();
+ str = (*message_)[strings::msg_params][strings::turn_icon][strings::value]
+ .asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid turn_icon value syntax check failed");
return true;
@@ -219,8 +227,8 @@ bool ShowConstantTBTRequest::IsWhiteSpaceExist() {
}
if ((*message_)[strings::msg_params].keyExists(strings::next_turn_icon)) {
- str = (*message_)[strings::msg_params]
- [strings::next_turn_icon][strings::value].asCharArray();
+ str = (*message_)[strings::msg_params][strings::next_turn_icon]
+ [strings::value].asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_,
"Invalid next_turn_icon value syntax check failed");
@@ -229,8 +237,8 @@ bool ShowConstantTBTRequest::IsWhiteSpaceExist() {
}
if ((*message_)[strings::msg_params].keyExists(strings::navigation_text_1)) {
- str = (*message_)[strings::msg_params]
- [strings::navigation_text_1].asCharArray();
+ str = (*message_)[strings::msg_params][strings::navigation_text_1]
+ .asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
LOG4CXX_ERROR(logger_,
"Invalid navigation_text_1 value syntax check failed");
@@ -239,8 +247,8 @@ bool ShowConstantTBTRequest::IsWhiteSpaceExist() {
}
if ((*message_)[strings::msg_params].keyExists(strings::navigation_text_2)) {
- str = (*message_)[strings::msg_params]
- [strings::navigation_text_2].asCharArray();
+ str = (*message_)[strings::msg_params][strings::navigation_text_2]
+ .asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
LOG4CXX_ERROR(logger_,
"Invalid navigation_text_2 value syntax check failed");
@@ -257,8 +265,8 @@ bool ShowConstantTBTRequest::IsWhiteSpaceExist() {
}
if ((*message_)[strings::msg_params].keyExists(strings::total_distance)) {
- str = (*message_)[strings::msg_params]
- [strings::total_distance].asCharArray();
+ str =
+ (*message_)[strings::msg_params][strings::total_distance].asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
LOG4CXX_ERROR(logger_,
"Invalid total_distance value syntax check failed");
@@ -266,9 +274,10 @@ bool ShowConstantTBTRequest::IsWhiteSpaceExist() {
}
}
- if ((*message_)[strings::msg_params].keyExists(strings::time_to_destination)) {
- str = (*message_)[strings::msg_params]
- [strings::time_to_destination].asCharArray();
+ if ((*message_)[strings::msg_params].keyExists(
+ strings::time_to_destination)) {
+ str = (*message_)[strings::msg_params][strings::time_to_destination]
+ .asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
LOG4CXX_ERROR(logger_,
"Invalid time_to_destination value syntax check failed");
diff --git a/src/components/application_manager/src/commands/mobile/show_constant_tbt_response.cc b/src/components/application_manager/src/commands/mobile/show_constant_tbt_response.cc
index e45cd760df..80a36129cf 100644
--- a/src/components/application_manager/src/commands/mobile/show_constant_tbt_response.cc
+++ b/src/components/application_manager/src/commands/mobile/show_constant_tbt_response.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/show_constant_tbt_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
@@ -40,17 +40,16 @@ namespace application_manager {
namespace commands {
ShowConstantTBTResponse::ShowConstantTBTResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
-ShowConstantTBTResponse::~ShowConstantTBTResponse() {
-}
+ : CommandResponseImpl(message, application_manager) {}
+
+ShowConstantTBTResponse::~ShowConstantTBTResponse() {}
void ShowConstantTBTResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/show_request.cc b/src/components/application_manager/src/commands/mobile/show_request.cc
index 0a136e0ac2..467d8d0236 100644
--- a/src/components/application_manager/src/commands/mobile/show_request.cc
+++ b/src/components/application_manager/src/commands/mobile/show_request.cc
@@ -30,75 +30,76 @@
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
+#include <string.h>
#include "application_manager/commands/mobile/show_request.h"
-#include "application_manager/application_manager_impl.h"
+
+#include "application_manager/policies/policy_handler.h"
#include "application_manager/application.h"
#include "application_manager/message_helper.h"
#include "utils/file_system.h"
-
-#include <string.h>
+#include "utils/helpers.h"
namespace application_manager {
namespace commands {
-ShowRequest::ShowRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+ShowRequest::ShowRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-ShowRequest::~ShowRequest() {
-}
+ShowRequest::~ShowRequest() {}
void ShowRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = application_manager::ApplicationManagerImpl::instance()
- ->application(
- (*message_)[strings::params][strings::connection_key].asInt());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
- LOG4CXX_ERROR_EXT(
- logger_, "Application is not registered");
+ LOG4CXX_ERROR(logger_, "Application is not registered");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
- //SDLAQ-CRS-494, VC3.1
+ // SDLAQ-CRS-494, VC3.1
if ((*message_)[strings::msg_params].empty()) {
- LOG4CXX_ERROR(logger_, "INVALID_DATA!");
+ LOG4CXX_ERROR(logger_, strings::msg_params << " is empty.");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
if (!CheckStringsOfShowRequest()) {
- LOG4CXX_ERROR(logger_, "Incorrect characters in string");
- SendResponse(false, mobile_apis::Result::INVALID_DATA);
- return;
- }
+ LOG4CXX_ERROR(logger_, "Incorrect characters in string");
+ SendResponse(false, mobile_apis::Result::INVALID_DATA);
+ return;
+ }
- //ProcessSoftButtons checks strings on the contents incorrect character
+ // ProcessSoftButtons checks strings on the contents incorrect character
mobile_apis::Result::eType processing_result = mobile_apis::Result::SUCCESS;
- if(((*message_)[strings::msg_params].keyExists(strings::soft_buttons)) &&
+ if (((*message_)[strings::msg_params].keyExists(strings::soft_buttons)) &&
((*message_)[strings::msg_params][strings::soft_buttons].length() > 0)) {
- processing_result =
- MessageHelper::ProcessSoftButtons((*message_)[strings::msg_params], app);
+ processing_result = MessageHelper::ProcessSoftButtons(
+ (*message_)[strings::msg_params],
+ app,
+ application_manager_.GetPolicyHandler(),
+ application_manager_);
}
if (mobile_apis::Result::SUCCESS != processing_result) {
- LOG4CXX_ERROR(logger_, "INVALID_DATA!");
+ LOG4CXX_ERROR(logger_, "Processing of soft buttons failed.");
SendResponse(false, processing_result);
return;
}
- mobile_apis::Result::eType verification_result =
- mobile_apis::Result::SUCCESS;
+ mobile_apis::Result::eType verification_result = mobile_apis::Result::SUCCESS;
if (((*message_)[strings::msg_params].keyExists(strings::graphic)) &&
- ((*message_)[strings::msg_params]
- [strings::graphic][strings::value].asString()).length()) {
+ ((*message_)[strings::msg_params][strings::graphic][strings::value]
+ .asString()).length()) {
verification_result = MessageHelper::VerifyImage(
- (*message_)[strings::msg_params][strings::graphic], app);
+ (*message_)[strings::msg_params][strings::graphic],
+ app,
+ application_manager_);
if (mobile_apis::Result::SUCCESS != verification_result) {
- LOG4CXX_ERROR(logger_, "VerifyImage INVALID_DATA!");
+ LOG4CXX_ERROR(logger_, "Image verification failed.");
SendResponse(false, verification_result);
return;
}
@@ -106,20 +107,22 @@ void ShowRequest::Run() {
if ((*message_)[strings::msg_params].keyExists(strings::secondary_graphic)) {
verification_result = MessageHelper::VerifyImage(
- (*message_)[strings::msg_params][strings::secondary_graphic], app);
+ (*message_)[strings::msg_params][strings::secondary_graphic],
+ app,
+ application_manager_);
if (mobile_apis::Result::SUCCESS != verification_result) {
- LOG4CXX_ERROR(logger_, "VerifyImage INVALID_DATA!");
+ LOG4CXX_ERROR(logger_, "Image verification failed.");
SendResponse(false, verification_result);
return;
}
}
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params[strings::app_id] = app->app_id();
- msg_params[hmi_request::show_strings] = smart_objects::SmartObject(
- smart_objects::SmartType_Array);
+ msg_params[hmi_request::show_strings] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
int32_t index = 0;
if ((*message_)[strings::msg_params].keyExists(strings::main_field_1)) {
@@ -190,7 +193,7 @@ void ShowRequest::Run() {
if ((*message_)[strings::msg_params].keyExists(strings::secondary_graphic)) {
msg_params[strings::secondary_graphic] =
- (*message_)[strings::msg_params][strings::secondary_graphic];
+ (*message_)[strings::msg_params][strings::secondary_graphic];
}
if ((*message_)[strings::msg_params].keyExists(strings::soft_buttons)) {
@@ -217,34 +220,37 @@ void ShowRequest::Run() {
void ShowRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
+
const smart_objects::SmartObject& message = event.smart_object();
switch (event.id()) {
case hmi_apis::FunctionID::UI_Show: {
- LOG4CXX_INFO(logger_, "Received UI_Show event");
- std::string response_info("");
+ LOG4CXX_DEBUG(logger_, "Received UI_Show event.");
+ std::string response_info;
mobile_apis::Result::eType result_code =
static_cast<mobile_apis::Result::eType>(
- message[strings::params][hmi_response::code].asInt());
+ message[strings::params][hmi_response::code].asInt());
- bool result = false;
+ const bool result = Compare<mobile_api::Result::eType, EQ, ONE>(
+ result_code,
+ mobile_api::Result::SUCCESS,
+ mobile_api::Result::WARNINGS);
- if (mobile_apis::Result::SUCCESS == result_code) {
- result = true;
- } else if (mobile_apis::Result::WARNINGS == result_code) {
- result = true;
- if (message[strings::params].keyExists(hmi_response::message)) {
- response_info = message[strings::params][hmi_response::message].asString();
- }
+ if (mobile_apis::Result::WARNINGS == result_code &&
+ message[strings::params].keyExists(hmi_response::message)) {
+ response_info =
+ message[strings::params][hmi_response::message].asString();
}
- SendResponse(result, result_code,
+ SendResponse(result,
+ result_code,
response_info.empty() ? NULL : response_info.c_str(),
- &(message[strings::msg_params]));
+ &(message[strings::msg_params]));
break;
}
default: {
- LOG4CXX_ERROR(logger_,"Received unknown event" << event.id());
+ LOG4CXX_ERROR(logger_, "Received unknown event " << event.id());
break;
}
}
@@ -258,7 +264,7 @@ bool ShowRequest::CheckStringsOfShowRequest() {
str = (*message_)[strings::msg_params][strings::main_field_4].asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid main_field_4 syntax check failed");
- return false;
+ return false;
}
}
if ((*message_)[strings::msg_params].keyExists(strings::main_field_3)) {
@@ -304,20 +310,20 @@ bool ShowRequest::CheckStringsOfShowRequest() {
}
}
if ((*message_)[strings::msg_params].keyExists(strings::custom_presets)) {
- smart_objects::SmartObject& custom_presets_array =
- (*message_)[strings::msg_params][strings::custom_presets];
- for (size_t i = 0; i < custom_presets_array.length(); ++i) {
- str = custom_presets_array[i].asCharArray();
- if (!CheckSyntax(str)) {
- LOG4CXX_ERROR(logger_, "Invalid custom_presets syntax check failed");
- return false;
- }
+ smart_objects::SmartObject& custom_presets_array =
+ (*message_)[strings::msg_params][strings::custom_presets];
+ for (size_t i = 0; i < custom_presets_array.length(); ++i) {
+ str = custom_presets_array[i].asCharArray();
+ if (!CheckSyntax(str)) {
+ LOG4CXX_ERROR(logger_, "Invalid custom_presets syntax check failed");
+ return false;
}
+ }
}
if ((*message_)[strings::msg_params].keyExists(strings::graphic)) {
- str = (*message_)[strings::msg_params]
- [strings::graphic][strings::value].asCharArray();
+ str = (*message_)[strings::msg_params][strings::graphic][strings::value]
+ .asCharArray();
if (strlen(str) && !CheckSyntax(str)) {
LOG4CXX_ERROR(logger_, "Invalid graphic value syntax check failed");
return false;
@@ -325,11 +331,11 @@ bool ShowRequest::CheckStringsOfShowRequest() {
}
if ((*message_)[strings::msg_params].keyExists(strings::secondary_graphic)) {
- str = (*message_)[strings::msg_params]
- [strings::secondary_graphic][strings::value].asCharArray();
+ str = (*message_)[strings::msg_params][strings::secondary_graphic]
+ [strings::value].asCharArray();
if (!CheckSyntax(str)) {
LOG4CXX_ERROR(logger_,
- "Invalid secondary_graphic value syntax check failed");
+ "Invalid secondary_graphic value syntax check failed");
return false;
}
}
diff --git a/src/components/application_manager/src/commands/mobile/show_response.cc b/src/components/application_manager/src/commands/mobile/show_response.cc
index 0c46cdd83c..8027c908f1 100644
--- a/src/components/application_manager/src/commands/mobile/show_response.cc
+++ b/src/components/application_manager/src/commands/mobile/show_response.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/show_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/HMI_API.h"
@@ -40,17 +40,16 @@ namespace application_manager {
namespace commands {
-ShowResponse::ShowResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ShowResponse::ShowResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-ShowResponse::~ShowResponse() {
-}
+ShowResponse::~ShowResponse() {}
void ShowResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/slider_request.cc b/src/components/application_manager/src/commands/mobile/slider_request.cc
index cef2bed1fc..3920b49db3 100644
--- a/src/components/application_manager/src/commands/mobile/slider_request.cc
+++ b/src/components/application_manager/src/commands/mobile/slider_request.cc
@@ -32,28 +32,30 @@
*/
#include "application_manager/commands/mobile/slider_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
+#include "application_manager/message_helper.h"
+#include "utils/helpers.h"
#include "config_profile/profile.h"
namespace application_manager {
namespace commands {
-SliderRequest::SliderRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
+SliderRequest::SliderRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {
subscribe_on_event(hmi_apis::FunctionID::UI_OnResetTimeout);
}
-SliderRequest::~SliderRequest() {
-}
+SliderRequest::~SliderRequest() {}
bool SliderRequest::Init() {
-
/* Timeout in milliseconds.
If omitted a standard value of 10000 milliseconds is used.*/
if ((*message_)[strings::msg_params].keyExists(strings::timeout)) {
- default_timeout_ = profile::Profile::instance()->default_timeout() +
+ default_timeout_ =
+ application_manager_.get_settings().default_timeout() +
(*message_)[strings::msg_params][strings::timeout].asUInt();
}
@@ -63,9 +65,8 @@ bool SliderRequest::Init() {
void SliderRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr application =
- application_manager::ApplicationManagerImpl::instance()->application(
- (*message_)[strings::params][strings::connection_key].asUInt());
+ ApplicationSharedPtr application = application_manager_.application(
+ (*message_)[strings::params][strings::connection_key].asUInt());
if (!application) {
LOG4CXX_ERROR(logger_, "Application is not registered");
@@ -73,8 +74,8 @@ void SliderRequest::Run() {
return;
}
- if ((*message_)[strings::msg_params][strings::num_ticks].asInt()
- < (*message_)[strings::msg_params][strings::position].asInt()) {
+ if ((*message_)[strings::msg_params][strings::num_ticks].asInt() <
+ (*message_)[strings::msg_params][strings::position].asInt()) {
LOG4CXX_ERROR(logger_, "INVALID_DATA");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
@@ -82,9 +83,8 @@ void SliderRequest::Run() {
if ((*message_)[strings::msg_params].keyExists(strings::slider_footer)) {
if (1 < (*message_)[strings::msg_params][strings::slider_footer].length()) {
- if ((*message_)[strings::msg_params][strings::num_ticks].asUInt()
- != (*message_)[strings::msg_params]
- [strings::slider_footer].length()) {
+ if ((*message_)[strings::msg_params][strings::num_ticks].asUInt() !=
+ (*message_)[strings::msg_params][strings::slider_footer].length()) {
LOG4CXX_ERROR(logger_, "INVALID_DATA");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
@@ -98,8 +98,8 @@ void SliderRequest::Run() {
return;
}
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params = (*message_)[strings::msg_params];
msg_params[strings::app_id] = application->app_id();
@@ -112,45 +112,60 @@ void SliderRequest::Run() {
void SliderRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
- const smart_objects::SmartObject& message = event.smart_object();
+ using namespace helpers;
+ using namespace smart_objects;
+ using namespace hmi_apis;
+
+ const SmartObject& message = event.smart_object();
const event_engine::Event::EventID event_id = event.id();
- if (event_id == hmi_apis::FunctionID::UI_OnResetTimeout) {
+ if (event_id == FunctionID::UI_OnResetTimeout) {
LOG4CXX_INFO(logger_, "Received UI_OnResetTimeout event");
- ApplicationManagerImpl::instance()->updateRequestTimeout(connection_key(),
- correlation_id(),
- default_timeout());
+ application_manager_.updateRequestTimeout(
+ connection_key(), correlation_id(), default_timeout());
return;
}
- if (event_id != hmi_apis::FunctionID::UI_Slider) {
+
+ if (event_id != FunctionID::UI_Slider) {
LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
return;
}
- //event_id == hmi_apis::FunctionID::UI_Slider:
- LOG4CXX_INFO(logger_, "Received UI_Slider event");
-
- const int response_code =
- message[strings::params][hmi_response::code].asInt();
- smart_objects::SmartObject response_msg_params = message[strings::msg_params];
- if (response_code == hmi_apis::Common_Result::ABORTED &&
- message[strings::params][strings::data].keyExists(strings::slider_position)) {
- //Copy slider_position info to msg_params section
- response_msg_params[strings::slider_position] =
- message[strings::params][strings::data][strings::slider_position];
+ LOG4CXX_DEBUG(logger_, "Received UI_Slider event");
+
+ const Common_Result::eType response_code = static_cast<Common_Result::eType>(
+ message[strings::params][hmi_response::code].asInt());
+
+ SmartObject response_msg_params = message[strings::msg_params];
+
+ const bool is_timeout_aborted = Compare<Common_Result::eType, EQ, ONE>(
+ response_code, Common_Result::TIMED_OUT, Common_Result::ABORTED);
+
+ if (is_timeout_aborted) {
+ if (message[strings::params][strings::data].keyExists(
+ strings::slider_position)) {
+ // Copy slider_position info to msg_params section
+ response_msg_params[strings::slider_position] =
+ message[strings::params][strings::data][strings::slider_position];
+ } else {
+ LOG4CXX_ERROR(logger_,
+ strings::slider_position << " field is absent"
+ " in response.");
+ response_msg_params[strings::slider_position] = 0;
+ }
}
- const bool is_response_success =
- (mobile_apis::Result::SUCCESS == response_code);
+ const bool is_response_success = Compare<Common_Result::eType, EQ, ONE>(
+ response_code, Common_Result::SUCCESS, Common_Result::WARNINGS);
SendResponse(is_response_success,
- mobile_apis::Result::eType(response_code),
+ MessageHelper::HMIToMobileResult(response_code),
0,
&response_msg_params);
}
bool SliderRequest::IsWhiteSpaceExist() {
- LOG4CXX_INFO(logger_, "PerformAudioPassThruRequest::IsWhiteSpaceExist");
+ LOG4CXX_AUTO_TRACE(logger_);
const char* str = NULL;
str = (*message_)[strings::msg_params][strings::slider_header].asCharArray();
@@ -179,4 +194,3 @@ bool SliderRequest::IsWhiteSpaceExist() {
} // namespace commands
} // namespace application_manager
-
diff --git a/src/components/application_manager/src/commands/mobile/slider_response.cc b/src/components/application_manager/src/commands/mobile/slider_response.cc
index 7f0c10b068..2cfcaf48fd 100644
--- a/src/components/application_manager/src/commands/mobile/slider_response.cc
+++ b/src/components/application_manager/src/commands/mobile/slider_response.cc
@@ -32,23 +32,21 @@
*/
#include "application_manager/commands/mobile/slider_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-SliderResponse::SliderResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+SliderResponse::SliderResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-SliderResponse::~SliderResponse() {
-}
+SliderResponse::~SliderResponse() {}
void SliderResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/speak_request.cc b/src/components/application_manager/src/commands/mobile/speak_request.cc
index b2f112a64a..7e4731b569 100644
--- a/src/components/application_manager/src/commands/mobile/speak_request.cc
+++ b/src/components/application_manager/src/commands/mobile/speak_request.cc
@@ -33,29 +33,30 @@
#include <string.h>
#include "application_manager/commands/mobile/speak_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
+#include "application_manager/message_helper.h"
+#include "utils/helpers.h"
namespace application_manager {
namespace commands {
-SpeakRequest::SpeakRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
+SpeakRequest::SpeakRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {
subscribe_on_event(hmi_apis::FunctionID::TTS_OnResetTimeout);
}
-SpeakRequest::~SpeakRequest() {
-}
+SpeakRequest::~SpeakRequest() {}
void SpeakRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = application_manager::ApplicationManagerImpl::instance()
- ->application(connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "NULL pointer");
+ LOG4CXX_ERROR(logger_, "NULL pointer");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
@@ -72,7 +73,8 @@ void SpeakRequest::Run() {
(*message_)[strings::msg_params][hmi_request::speak_type] =
hmi_apis::Common_MethodName::SPEAK;
SendHMIRequest(hmi_apis::FunctionID::TTS_Speak,
- &message_->getElement(strings::msg_params), true);
+ &message_->getElement(strings::msg_params),
+ true);
}
void SpeakRequest::on_event(const event_engine::Event& event) {
@@ -87,7 +89,7 @@ void SpeakRequest::on_event(const event_engine::Event& event) {
case hmi_apis::FunctionID::TTS_OnResetTimeout: {
LOG4CXX_INFO(logger_, "Received TTS_OnResetTimeout event");
- ApplicationManagerImpl::instance()->updateRequestTimeout(
+ application_manager_.updateRequestTimeout(
connection_key(), correlation_id(), default_timeout());
break;
}
@@ -99,38 +101,46 @@ void SpeakRequest::on_event(const event_engine::Event& event) {
}
void SpeakRequest::ProcessTTSSpeakResponse(
- const smart_objects::SmartObject& message) {
+ const smart_objects::SmartObject& message) {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr application = ApplicationManagerImpl::instance()->application(
- connection_key());
+ using namespace helpers;
+
+ ApplicationSharedPtr application =
+ application_manager_.application(connection_key());
if (!application) {
LOG4CXX_ERROR(logger_, "NULL pointer");
return;
}
- bool result = false;
+ hmi_apis::Common_Result::eType hmi_result_code =
+ static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asInt());
+
mobile_apis::Result::eType result_code =
- static_cast<mobile_apis::Result::eType>(
- message[strings::params][hmi_response::code].asInt());
- if (hmi_apis::Common_Result::SUCCESS ==
- static_cast<hmi_apis::Common_Result::eType>(result_code)) {
- result = true;
- }
+ MessageHelper::HMIToMobileResult(hmi_result_code);
+
+ const bool result = Compare<mobile_api::Result::eType, EQ, ONE>(
+ result_code, mobile_api::Result::SUCCESS, mobile_api::Result::WARNINGS);
+
(*message_)[strings::params][strings::function_id] =
- mobile_apis::FunctionID::SpeakID;
+ mobile_apis::FunctionID::SpeakID;
const char* return_info = NULL;
- if (hmi_apis::Common_Result::UNSUPPORTED_RESOURCE ==
- static_cast<hmi_apis::Common_Result::eType>(result_code)) {
+ const bool is_result_ok = Compare<mobile_api::Result::eType, EQ, ONE>(
+ result_code,
+ mobile_api::Result::UNSUPPORTED_RESOURCE,
+ mobile_api::Result::WARNINGS);
+
+ if (is_result_ok) {
result_code = mobile_apis::Result::WARNINGS;
- return_info = std::string(
- "Unsupported phoneme type sent in a prompt").c_str();
+ return_info =
+ std::string("Unsupported phoneme type sent in a prompt").c_str();
}
- SendResponse(result, static_cast<mobile_apis::Result::eType>(result_code),
- return_info, &(message[strings::msg_params]));
+ SendResponse(
+ result, result_code, return_info, &(message[strings::msg_params]));
}
bool SpeakRequest::IsWhiteSpaceExist() {
diff --git a/src/components/application_manager/src/commands/mobile/speak_response.cc b/src/components/application_manager/src/commands/mobile/speak_response.cc
index d99b1d0952..612d32c913 100644
--- a/src/components/application_manager/src/commands/mobile/speak_response.cc
+++ b/src/components/application_manager/src/commands/mobile/speak_response.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/speak_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/HMI_API.h"
@@ -40,17 +40,16 @@ namespace application_manager {
namespace commands {
-SpeakResponse::SpeakResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+SpeakResponse::SpeakResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-SpeakResponse::~SpeakResponse() {
-}
+SpeakResponse::~SpeakResponse() {}
void SpeakResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/subscribe_button_request.cc b/src/components/application_manager/src/commands/mobile/subscribe_button_request.cc
index 22bc57620a..7ec4e20fbd 100644
--- a/src/components/application_manager/src/commands/mobile/subscribe_button_request.cc
+++ b/src/components/application_manager/src/commands/mobile/subscribe_button_request.cc
@@ -32,7 +32,6 @@
*/
#include "application_manager/commands/mobile/subscribe_button_request.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
@@ -40,21 +39,19 @@ namespace commands {
namespace str = strings;
-SubscribeButtonRequest::SubscribeButtonRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+SubscribeButtonRequest::SubscribeButtonRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-SubscribeButtonRequest::~SubscribeButtonRequest() {
-}
+SubscribeButtonRequest::~SubscribeButtonRequest() {}
void SubscribeButtonRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "APPLICATION_NOT_REGISTERED");
+ LOG4CXX_ERROR(logger_, "APPLICATION_NOT_REGISTERED");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
@@ -64,21 +61,22 @@ void SubscribeButtonRequest::Run() {
(*message_)[str::msg_params][str::button_name].asUInt());
if (!IsSubscriptionAllowed(app, btn_id)) {
- LOG4CXX_ERROR_EXT(logger_, "Subscribe on button " << btn_id
- << " isn't allowed");
+ LOG4CXX_ERROR(logger_,
+ "Subscribe on button " << btn_id << " isn't allowed");
SendResponse(false, mobile_apis::Result::REJECTED);
return;
}
if (!CheckHMICapabilities(btn_id)) {
- LOG4CXX_ERROR_EXT(logger_, "Subscribe on button " << btn_id
- << " isn't allowed by HMI capabilities");
+ LOG4CXX_ERROR(logger_,
+ "Subscribe on button "
+ << btn_id << " isn't allowed by HMI capabilities");
SendResponse(false, mobile_apis::Result::UNSUPPORTED_RESOURCE);
return;
}
if (app->IsSubscribedToButton(btn_id)) {
- LOG4CXX_ERROR_EXT(logger_, "Already subscribed to button " << btn_id);
+ LOG4CXX_ERROR(logger_, "Already subscribed to button " << btn_id);
SendResponse(false, mobile_apis::Result::IGNORED);
return;
}
@@ -96,11 +94,10 @@ void SubscribeButtonRequest::Run() {
bool SubscribeButtonRequest::IsSubscriptionAllowed(
ApplicationSharedPtr app, mobile_apis::ButtonName::eType btn_id) {
-
if (!app->is_media_application() &&
((mobile_apis::ButtonName::SEEKLEFT == btn_id) ||
- (mobile_apis::ButtonName::SEEKRIGHT == btn_id)||
- (mobile_apis::ButtonName::TUNEUP == btn_id) ||
+ (mobile_apis::ButtonName::SEEKRIGHT == btn_id) ||
+ (mobile_apis::ButtonName::TUNEUP == btn_id) ||
(mobile_apis::ButtonName::TUNEDOWN == btn_id))) {
return false;
}
@@ -114,12 +111,9 @@ bool SubscribeButtonRequest::CheckHMICapabilities(
using namespace mobile_apis;
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl* app_mgr = ApplicationManagerImpl::instance();
- DCHECK_OR_RETURN(app_mgr, false);
-
- const HMICapabilities& hmi_caps = app_mgr->hmi_capabilities();
+ const HMICapabilities& hmi_caps = application_manager_.hmi_capabilities();
if (!hmi_caps.is_ui_cooperating()) {
- LOG4CXX_ERROR_EXT(logger_, "UI is not supported by HMI.");
+ LOG4CXX_ERROR(logger_, "UI is not supported by HMI.");
return false;
}
@@ -129,8 +123,8 @@ bool SubscribeButtonRequest::CheckHMICapabilities(
const size_t length = button_caps.length();
for (size_t i = 0; i < length; ++i) {
const SmartObject& caps = button_caps[i];
- const ButtonName::eType name =
- static_cast<ButtonName::eType>(caps.getElement(hmi_response::button_name).asInt());
+ const ButtonName::eType name = static_cast<ButtonName::eType>(
+ caps.getElement(hmi_response::button_name).asInt());
if (name == button) {
return true;
}
diff --git a/src/components/application_manager/src/commands/mobile/subscribe_button_response.cc b/src/components/application_manager/src/commands/mobile/subscribe_button_response.cc
index a3452ef19f..a92e58b19a 100644
--- a/src/components/application_manager/src/commands/mobile/subscribe_button_response.cc
+++ b/src/components/application_manager/src/commands/mobile/subscribe_button_response.cc
@@ -38,12 +38,10 @@ namespace application_manager {
namespace commands {
SubscribeButtonResponse::SubscribeButtonResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-SubscribeButtonResponse::~SubscribeButtonResponse() {
-}
+SubscribeButtonResponse::~SubscribeButtonResponse() {}
void SubscribeButtonResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/mobile/subscribe_vehicle_data_request.cc b/src/components/application_manager/src/commands/mobile/subscribe_vehicle_data_request.cc
index f00527037e..485c5d0009 100644
--- a/src/components/application_manager/src/commands/mobile/subscribe_vehicle_data_request.cc
+++ b/src/components/application_manager/src/commands/mobile/subscribe_vehicle_data_request.cc
@@ -32,62 +32,77 @@
*/
#include "application_manager/commands/mobile/subscribe_vehicle_data_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
+#include "utils/helpers.h"
namespace application_manager {
namespace commands {
SubscribeVehicleDataRequest::SubscribeVehicleDataRequest(
- const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-SubscribeVehicleDataRequest::~SubscribeVehicleDataRequest() {
-}
+SubscribeVehicleDataRequest::~SubscribeVehicleDataRequest() {}
#ifdef HMI_DBUS_API
namespace {
- struct Subrequest {
- hmi_apis::FunctionID::eType func_id;
- const char* str;
- };
- Subrequest subrequests[] = {
- { hmi_apis::FunctionID::VehicleInfo_SubscribeGps, strings::gps},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeSpeed, strings::speed},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeRpm, strings::rpm},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel, strings::fuel_level},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel_State, strings::fuel_level_state},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeInstantFuelConsumption, strings::instant_fuel_consumption},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeExternalTemperature, strings::external_temp},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeVin, strings::vin},
- { hmi_apis::FunctionID::VehicleInfo_SubscribePrndl, strings::prndl},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeTirePressure, strings::tire_pressure},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeOdometer, strings::odometer},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeBeltStatus, strings::belt_status},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeBodyInformation, strings::body_information},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeDeviceStatus, strings::device_status},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeDriverBraking, strings::driver_braking},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeWiperStatus, strings::wiper_status},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeHeadLampStatus, strings::head_lamp_status},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeEngineTorque, strings::engine_torque},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeAccPedalPosition, strings::acc_pedal_pos},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeSteeringWheelAngle, strings::steering_wheel_angle},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeECallInfo, strings::e_call_info},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeAirbagStatus, strings::airbag_status},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeEmergencyEvent, strings::emergency_event},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeClusterModeStatus, strings::cluster_mode_status},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeMyKey, strings::my_key},
- };
+struct Subrequest {
+ hmi_apis::FunctionID::eType func_id;
+ const char* str;
+};
+Subrequest subrequests[] = {
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeGps, strings::gps},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeSpeed, strings::speed},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeRpm, strings::rpm},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel, strings::fuel_level},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel_State,
+ strings::fuel_level_state},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeInstantFuelConsumption,
+ strings::instant_fuel_consumption},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeExternalTemperature,
+ strings::external_temp},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeVin, strings::vin},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribePrndl, strings::prndl},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeTirePressure,
+ strings::tire_pressure},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeOdometer, strings::odometer},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeBeltStatus,
+ strings::belt_status},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeBodyInformation,
+ strings::body_information},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeDeviceStatus,
+ strings::device_status},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeDriverBraking,
+ strings::driver_braking},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeWiperStatus,
+ strings::wiper_status},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeHeadLampStatus,
+ strings::head_lamp_status},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeEngineTorque,
+ strings::engine_torque},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeAccPedalPosition,
+ strings::acc_pedal_pos},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeSteeringWheelAngle,
+ strings::steering_wheel_angle},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeECallInfo,
+ strings::e_call_info},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeAirbagStatus,
+ strings::airbag_status},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeEmergencyEvent,
+ strings::emergency_event},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeClusterModeStatus,
+ strings::cluster_mode_status},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeMyKey, strings::my_key},
+};
}
-#endif // #ifdef HMI_DBUS_API
+#endif // #ifdef HMI_DBUS_API
void SubscribeVehicleDataRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
- CommandRequestImpl::connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
LOG4CXX_ERROR(logger_, "NULL pointer");
@@ -103,43 +118,88 @@ void SubscribeVehicleDataRequest::Run() {
const VehicleData& vehicle_data = MessageHelper::vehicle_data();
VehicleData::const_iterator it = vehicle_data.begin();
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
- smart_objects::SmartObject response_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- msg_params[strings::app_id] = app->app_id();
+ smart_objects::SmartObject response_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
for (; vehicle_data.end() != it; ++it) {
- std::string key_name = it->first;
+ const std::string& key_name = it->first;
if ((*message_)[strings::msg_params].keyExists(key_name)) {
bool is_key_enabled = (*message_)[strings::msg_params][key_name].asBool();
if (is_key_enabled) {
++items_to_subscribe;
- msg_params[key_name] = is_key_enabled;
VehicleDataType key_type = it->second;
- if (app->SubscribeToIVI(static_cast<uint32_t>(key_type))) {
+ if (app->IsSubscribedToIVI(key_type)) {
+ LOG4CXX_DEBUG(logger_,
+ "App with connection key "
+ << connection_key()
+ << " is subscribed already for VehicleDataType: "
+ << key_type);
++subscribed_items;
- } else {
+ vi_already_subscribed_by_this_app_.insert(key_type);
response_params[key_name][strings::data_type] = key_type;
response_params[key_name][strings::result_code] =
mobile_apis::VehicleDataResultCode::VDRC_DATA_ALREADY_SUBSCRIBED;
+ continue;
+ }
+
+ if (IsSomeoneSubscribedFor(key_type)) {
+ LOG4CXX_DEBUG(logger_,
+ "There are apps subscribed already for "
+ "VehicleDataType: "
+ << key_type);
+ if (!app->SubscribeToIVI(static_cast<uint32_t>(key_type))) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Unable to subscribe for VehicleDataType: " << key_type);
+ continue;
+ }
+ LOG4CXX_DEBUG(
+ logger_,
+ "App with connection key "
+ << connection_key()
+ << " have been subscribed for VehicleDataType: " << key_type);
+ ++subscribed_items;
+ vi_already_subscribed_by_another_apps_.insert(key_type);
+ response_params[key_name][strings::data_type] = key_type;
+ response_params[key_name][strings::result_code] =
+ mobile_apis::VehicleDataResultCode::VDRC_SUCCESS;
+ continue;
+ }
+
+ msg_params[key_name] = is_key_enabled;
+
+ if (app->SubscribeToIVI(static_cast<uint32_t>(key_type))) {
+ LOG4CXX_DEBUG(
+ logger_,
+ "App with connection key "
+ << connection_key()
+ << " have been subscribed for VehicleDataType: " << key_type);
+ ++subscribed_items;
}
}
}
}
+ bool is_everything_already_subscribed =
+ static_cast<uint32_t>(items_to_subscribe) ==
+ vi_already_subscribed_by_another_apps_.size() +
+ vi_already_subscribed_by_this_app_.size();
+
if (0 == items_to_subscribe) {
if (HasDisallowedParams()) {
SendResponse(false, mobile_apis::Result::DISALLOWED);
} else {
- SendResponse(false, mobile_apis::Result::INVALID_DATA,
- "No data in the request");
+ SendResponse(
+ false, mobile_apis::Result::INVALID_DATA, "No data in the request");
}
return;
- } else if (0 == subscribed_items) {
+ }
+
+ if (0 == subscribed_items) {
SendResponse(false,
mobile_apis::Result::IGNORED,
"Already subscribed on provided VehicleData.",
@@ -147,12 +207,26 @@ void SubscribeVehicleDataRequest::Run() {
return;
}
+ if (is_everything_already_subscribed) {
+ mobile_apis::Result::eType result_code =
+ vi_already_subscribed_by_this_app_.size()
+ ? mobile_apis::Result::IGNORED
+ : mobile_apis::Result::SUCCESS;
+
+ const char* info = vi_already_subscribed_by_this_app_.size()
+ ? "Already subscribed on some provided VehicleData."
+ : NULL;
+
+ SendResponse(true, result_code, info, &response_params);
+ return;
+ }
+
#ifdef HMI_DBUS_API
- //Generate list of subrequests
+ // Generate list of subrequests
for (size_t i = 0; i < sizeof(subrequests) / sizeof(subrequests[0]); ++i) {
const Subrequest& sr = subrequests[i];
- if (true == (*message_)[strings::msg_params].keyExists(sr.str)
- && true == (*message_)[strings::msg_params][sr.str].asBool()) {
+ if (true == (*message_)[strings::msg_params].keyExists(sr.str) &&
+ true == (*message_)[strings::msg_params][sr.str].asBool()) {
HmiRequest hmi_request;
hmi_request.str = sr.str;
hmi_request.func_id = sr.func_id;
@@ -160,24 +234,34 @@ void SubscribeVehicleDataRequest::Run() {
hmi_requests_.push_back(hmi_request);
}
}
- LOG4CXX_INFO(logger_, hmi_requests_.size() << " requests are going to be sent to HMI");
+ LOG4CXX_DEBUG(
+ logger_, hmi_requests_.size() << " requests are going to be sent to HMI");
- //Send subrequests
- for (HmiRequests::const_iterator it = hmi_requests_.begin(); it != hmi_requests_.end(); ++it)
+ // Send subrequests
+ for (HmiRequests::const_iterator it = hmi_requests_.begin();
+ it != hmi_requests_.end();
+ ++it)
SendHMIRequest(it->func_id, &msg_params, true);
#else
SendHMIRequest(hmi_apis::FunctionID::VehicleInfo_SubscribeVehicleData,
- &msg_params, true);
-#endif // #ifdef HMI_DBUS_API
+ &msg_params,
+ true);
+#endif // #ifdef HMI_DBUS_API
}
void SubscribeVehicleDataRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
const smart_objects::SmartObject& message = event.smart_object();
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
- CommandRequestImpl::connection_key());
+ if (hmi_apis::FunctionID::VehicleInfo_SubscribeVehicleData != event.id()) {
+ LOG4CXX_ERROR(logger_, "Received unknown event.");
+ return;
+ }
+
+ ApplicationSharedPtr app =
+ application_manager_.application(CommandRequestImpl::connection_key());
if (!app) {
LOG4CXX_ERROR(logger_, "NULL pointer.");
@@ -186,23 +270,24 @@ void SubscribeVehicleDataRequest::on_event(const event_engine::Event& event) {
#ifdef HMI_DBUS_API
for (HmiRequests::iterator it = hmi_requests_.begin();
- it != hmi_requests_.end(); ++it) {
- HmiRequest & hmi_request = *it;
+ it != hmi_requests_.end();
+ ++it) {
+ HmiRequest& hmi_request = *it;
if (hmi_request.func_id == event.id()) {
- hmi_request.status =
- static_cast<hmi_apis::Common_Result::eType>(message[strings::params][hmi_response::code]
- .asInt());
+ hmi_request.status = static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asInt());
if (hmi_apis::Common_Result::SUCCESS == hmi_request.status)
hmi_request.value = message[strings::msg_params][hmi_request.str];
hmi_request.complete = true;
break;
}
}
- bool all_complete = true;
+ bool all_complete = true;
bool any_arg_success = false;
mobile_api::Result::eType status = mobile_api::Result::eType::SUCCESS;
for (HmiRequests::const_iterator it = hmi_requests_.begin();
- it != hmi_requests_.end(); ++it) {
+ it != hmi_requests_.end();
+ ++it) {
if (!it->complete) {
all_complete = false;
break;
@@ -210,12 +295,14 @@ void SubscribeVehicleDataRequest::on_event(const event_engine::Event& event) {
if (hmi_apis::Common_Result::SUCCESS != it->status) {
if (mobile_api::Result::SUCCESS == status) {
status = static_cast<mobile_apis::Result::eType>(it->status);
- } else if (status
- != static_cast<mobile_apis::Result::eType>(it->status)) {
+ } else if (status !=
+ static_cast<mobile_apis::Result::eType>(it->status)) {
status = mobile_api::Result::eType::GENERIC_ERROR;
}
- LOG4CXX_TRACE(logger_, "Status from HMI: " << it->status <<
- ", so response status become " << status);
+ LOG4CXX_TRACE(logger_,
+ "Status from HMI: " << it->status
+ << ", so response status become "
+ << status);
} else {
any_arg_success = true;
}
@@ -225,7 +312,8 @@ void SubscribeVehicleDataRequest::on_event(const event_engine::Event& event) {
smart_objects::SmartObject response_params(smart_objects::SmartType_Map);
if (any_arg_success) {
for (HmiRequests::const_iterator it = hmi_requests_.begin();
- it != hmi_requests_.end(); ++it) {
+ it != hmi_requests_.end();
+ ++it) {
response_params[it->str] = it->value;
}
}
@@ -241,54 +329,105 @@ void SubscribeVehicleDataRequest::on_event(const event_engine::Event& event) {
static_cast<hmi_apis::Common_Result::eType>(
message[strings::params][hmi_response::code].asInt());
- bool result =
- hmi_result == hmi_apis::Common_Result::SUCCESS;
+ const bool is_result_no_error =
+ Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ hmi_result,
+ hmi_apis::Common_Result::SUCCESS,
+ hmi_apis::Common_Result::WARNINGS);
+
+ bool is_succeeded =
+ is_result_no_error || !vi_already_subscribed_by_another_apps_.empty();
mobile_apis::Result::eType result_code =
- hmi_result == hmi_apis::Common_Result::SUCCESS
- ? mobile_apis::Result::SUCCESS
- : static_cast<mobile_apis::Result::eType>(
- message[strings::params][hmi_response::code].asInt());
+ MessageHelper::HMIToMobileResult(hmi_result);
const char* return_info = NULL;
- if (result) {
- if (IsAnythingAlreadySubscribed(message[strings::msg_params])) {
+ if (is_succeeded) {
+ if (!vi_already_subscribed_by_this_app_.empty()) {
result_code = mobile_apis::Result::IGNORED;
- return_info =
- std::string("Already subscribed on some provided VehicleData.").c_str();
+ return_info = "Already subscribed on some provided VehicleData.";
}
}
- SendResponse(result,
- result_code,
- return_info,
- &(message[strings::msg_params]));
+ UnsubscribeFailedSubscriptions(app, message[strings::msg_params]);
+
+ if (!vi_already_subscribed_by_another_apps_.empty() ||
+ !vi_already_subscribed_by_this_app_.empty()) {
+ AddAlreadySubscribedVI(
+ const_cast<smart_objects::SmartObject&>(message[strings::msg_params]));
+ }
+
+ SendResponse(
+ is_succeeded, result_code, return_info, &(message[strings::msg_params]));
- if (result) {
+ if (is_succeeded) {
app->UpdateHash();
}
-#endif // #ifdef HMI_DBUS_API
+#endif // #ifdef HMI_DBUS_API
}
-bool SubscribeVehicleDataRequest::IsAnythingAlreadySubscribed(
- const smart_objects::SmartObject& msg_params) const {
- LOG4CXX_INFO(logger_, "IsAnythingAlreadySubscribed");
+void SubscribeVehicleDataRequest::AddAlreadySubscribedVI(
+ smart_objects::SmartObject& msg_params) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace mobile_apis;
+ VehicleInfoSubscriptions::const_iterator it_same_app =
+ vi_already_subscribed_by_this_app_.begin();
+ for (; vi_already_subscribed_by_this_app_.end() != it_same_app;
+ ++it_same_app) {
+ msg_params[*it_same_app][strings::result_code] =
+ VehicleDataResultCode::VDRC_DATA_ALREADY_SUBSCRIBED;
+ }
+
+ VehicleInfoSubscriptions::const_iterator it_another_app =
+ vi_already_subscribed_by_another_apps_.begin();
+ for (; vi_already_subscribed_by_another_apps_.end() != it_another_app;
+ ++it_another_app) {
+ msg_params[*it_another_app][strings::result_code] =
+ VehicleDataResultCode::VDRC_SUCCESS;
+ }
+}
+void SubscribeVehicleDataRequest::UnsubscribeFailedSubscriptions(
+ ApplicationSharedPtr app,
+ const smart_objects::SmartObject& msg_params) const {
+ LOG4CXX_AUTO_TRACE(logger_);
const VehicleData& vehicle_data = MessageHelper::vehicle_data();
VehicleData::const_iterator it = vehicle_data.begin();
for (; vehicle_data.end() != it; ++it) {
if (msg_params.keyExists(it->first)) {
- if (msg_params[it->first][strings::result_code].asInt() ==
- hmi_apis::Common_VehicleDataResultCode::VDRC_DATA_ALREADY_SUBSCRIBED) {
- return true;
+ if (msg_params[it->first][strings::result_code].asInt() !=
+ hmi_apis::Common_VehicleDataResultCode::VDRC_SUCCESS) {
+ LOG4CXX_DEBUG(logger_,
+ "Subscription for VehicleDataType "
+ << it->first
+ << " is unsuccessfull. "
+ "Unsubscribing app with connection key "
+ << connection_key() << " from it.");
+ app->UnsubscribeFromIVI(it->second);
}
}
}
-
- return false;
}
+struct SubscribedToIVIPredicate {
+ int32_t vehicle_info_;
+ SubscribedToIVIPredicate(int32_t vehicle_info)
+ : vehicle_info_(vehicle_info) {}
+ bool operator()(const ApplicationSharedPtr app) const {
+ return app ? app->IsSubscribedToIVI(vehicle_info_) : false;
+ }
+};
+
+bool SubscribeVehicleDataRequest::IsSomeoneSubscribedFor(
+ const uint32_t param_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ SubscribedToIVIPredicate finder(param_id);
+ DataAccessor<ApplicationSet> accessor = application_manager_.applications();
+ ApplicationSetConstIt it = std::find_if(
+ accessor.GetData().begin(), accessor.GetData().end(), finder);
+ return it != accessor.GetData().end();
+}
} // namespace commands
} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/subscribe_vehicle_data_response.cc b/src/components/application_manager/src/commands/mobile/subscribe_vehicle_data_response.cc
index c0554c62eb..7ed16407a5 100644
--- a/src/components/application_manager/src/commands/mobile/subscribe_vehicle_data_response.cc
+++ b/src/components/application_manager/src/commands/mobile/subscribe_vehicle_data_response.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/subscribe_vehicle_data_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "interfaces/MOBILE_API.h"
@@ -40,16 +40,14 @@ namespace application_manager {
namespace commands {
SubscribeVehicleDataResponse::SubscribeVehicleDataResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-SubscribeVehicleDataResponse::~SubscribeVehicleDataResponse() {
-}
+SubscribeVehicleDataResponse::~SubscribeVehicleDataResponse() {}
void SubscribeVehicleDataResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/subscribe_way_points_request.cc b/src/components/application_manager/src/commands/mobile/subscribe_way_points_request.cc
new file mode 100644
index 0000000000..8134730eee
--- /dev/null
+++ b/src/components/application_manager/src/commands/mobile/subscribe_way_points_request.cc
@@ -0,0 +1,72 @@
+#include "application_manager/application_manager.h"
+#include "application_manager/commands/mobile/subscribe_way_points_request.h"
+
+namespace application_manager {
+
+namespace commands {
+
+SubscribeWayPointsRequest::SubscribeWayPointsRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
+
+SubscribeWayPointsRequest::~SubscribeWayPointsRequest() {}
+
+void SubscribeWayPointsRequest::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
+
+ if (!app) {
+ LOG4CXX_ERROR(logger_,
+ "An application with connection key "
+ << connection_key() << " is not registered.");
+ SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
+ return;
+ }
+
+ if (application_manager_.IsAppSubscribedForWayPoints(app->app_id())) {
+ SendResponse(false, mobile_apis::Result::IGNORED);
+ return;
+ }
+
+ if (application_manager_.IsAnyAppSubscribedForWayPoints()) {
+ application_manager_.SubscribeAppForWayPoints(app->app_id());
+ SendResponse(true, mobile_apis::Result::SUCCESS);
+ app->UpdateHash();
+ return;
+ }
+
+ SendHMIRequest(
+ hmi_apis::FunctionID::Navigation_SubscribeWayPoints, NULL, true);
+}
+
+void SubscribeWayPointsRequest::on_event(const event_engine::Event& event) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
+ const smart_objects::SmartObject& message = event.smart_object();
+ switch (event.id()) {
+ case hmi_apis::FunctionID::Navigation_SubscribeWayPoints: {
+ LOG4CXX_INFO(logger_, "Received Navigation_SubscribeWayPoints event");
+ mobile_apis::Result::eType result_code =
+ GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asUInt()));
+ bool result = mobile_apis::Result::SUCCESS == result_code;
+ if (result) {
+ application_manager_.SubscribeAppForWayPoints(app->app_id());
+ }
+ SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
+ if (result) {
+ app->UpdateHash();
+ }
+ break;
+ }
+ default: {
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
+ break;
+ }
+ }
+}
+
+} // namespace commands
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/subscribe_way_points_response.cc b/src/components/application_manager/src/commands/mobile/subscribe_way_points_response.cc
new file mode 100644
index 0000000000..c2e642619a
--- /dev/null
+++ b/src/components/application_manager/src/commands/mobile/subscribe_way_points_response.cc
@@ -0,0 +1,22 @@
+#include "application_manager/application_manager.h"
+#include "application_manager/commands/mobile/subscribe_way_points_response.h"
+
+namespace application_manager {
+
+namespace commands {
+
+SubscribeWayPointsResponse::SubscribeWayPointsResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
+
+SubscribeWayPointsResponse::~SubscribeWayPointsResponse() {}
+
+void SubscribeWayPointsResponse::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ application_manager_.SendMessageToMobile(message_);
+}
+
+} // namespace commands
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/system_request.cc b/src/components/application_manager/src/commands/mobile/system_request.cc
index c0b8b0ebf7..b9acf5e930 100644
--- a/src/components/application_manager/src/commands/mobile/system_request.cc
+++ b/src/components/application_manager/src/commands/mobile/system_request.cc
@@ -31,26 +31,26 @@ Copyright (c) 2013, Ford Motor Company
POSSIBILITY OF SUCH DAMAGE.
*/
+#include "application_manager/commands/mobile/system_request.h"
+
#include <vector>
#include <string>
-#include <map>
-#include <set>
-#include "application_manager/commands/mobile/system_request.h"
-#include "application_manager/application_manager_impl.h"
-#include "application_manager/application_impl.h"
-#include "application_manager/policies/policy_handler.h"
+#include <stdio.h>
+#include <algorithm>
+#include <sstream>
+#include "application_manager/policies/policy_handler_interface.h"
#include "interfaces/MOBILE_API.h"
-#include "config_profile/profile.h"
#include "utils/file_system.h"
-#include "formatters/CFormatterJsonBase.hpp"
+#include "formatters/CFormatterJsonBase.h"
#include "json/json.h"
#include "utils/helpers.h"
+#include "utils/custom_string.h"
namespace application_manager {
+CREATE_LOGGERPTR_LOCAL(logger_, "ApplicationManager")
namespace {
-CREATE_LOGGERPTR_LOCAL(logger_, "ApplicationManager")
#ifdef ENABLE_LOG
const char* kQueryAppsValidationFailedPrefix =
":QUERY_APPS_VALIDATION_FAILED: ";
@@ -72,11 +72,11 @@ class QueryAppsDataValidator {
typedef std::set<std::string> SynonymsSet;
typedef std::map<std::string, SynonymsSet> SynonymsMap;
- QueryAppsDataValidator(const smart_objects::SmartObject& object,
- const ApplicationManagerImpl& manager)
+ QueryAppsDataValidator(smart_objects::SmartObject& object,
+ const ApplicationManager& manager)
: data_(object), manager_(manager) {}
- bool Validate() const {
+ bool Validate() {
LOG4CXX_AUTO_TRACE(logger_);
if (!data_.isValid()) {
LOG4CXX_ERROR(logger_,
@@ -102,19 +102,25 @@ class QueryAppsDataValidator {
return true;
}
- bool ValidateAppDataAndOsAndLanguagesData() const {
- const smart_objects::SmartArray* objects_array =
- data_[json::response].asArray();
+ bool ValidateAppDataAndOsAndLanguagesData() {
+ smart_objects::SmartArray* objects_array = data_[json::response].asArray();
+
if (!objects_array) {
LOG4CXX_WARN(logger_,
kQueryAppsValidationFailedPrefix
<< "QueryApps response is not array.");
return false;
}
- const std::size_t arr_size(objects_array->size());
+
SynonymsMap synonyms_map;
- for (std::size_t idx = 0; idx < arr_size; ++idx) {
- const smart_objects::SmartObject& app_data = (*objects_array)[idx];
+ bool has_response_valid_application = false;
+
+ smart_objects::SmartArray::iterator applications_iterator =
+ objects_array->begin();
+
+ for (; applications_iterator != objects_array->end();
+ ++applications_iterator) {
+ const smart_objects::SmartObject& app_data = *applications_iterator;
if (!app_data.isValid()) {
LOG4CXX_WARN(logger_,
@@ -122,59 +128,50 @@ class QueryAppsDataValidator {
<< "Wrong application data in json file.");
return false;
}
- std::set<std::string> app_ids_set;
- if (!ValidateAppIdAndAppName(app_data, app_ids_set)) {
+
+ if (!CheckMandatoryParametersPresent(app_data)) {
+ LOG4CXX_WARN(logger_,
+ "Application hasn`t some of mandatory parameters. "
+ "Application will be skipped.");
+ objects_array->erase(applications_iterator);
+ continue;
+ }
+
+ if (!ValidateAppIdAndAppName(app_data)) {
return false;
}
+
+ // If we dont have any of android/ios field
+ // we skip this json in CheckMandatoryParametersPresent
+ const std::string os_type =
+ (app_data.keyExists(json::android)) ? json::android : json::ios;
+
// Verify os and dependent languages data
- std::string os_type;
- if (app_data.keyExists(json::ios)) {
- os_type = json::ios;
- if (!app_data[os_type].keyExists(json::urlScheme)) {
- LOG4CXX_WARN(logger_,
- kQueryAppsValidationFailedPrefix
- << "Can't find URL scheme in json file.");
- return false;
- }
- if (app_data[os_type][json::urlScheme].asString().length() >
+ if (json::ios == os_type) {
+ if (app_data[json::ios][json::urlScheme].asString().length() >
kUrlSchemaLengthMax) {
LOG4CXX_WARN(
logger_,
kQueryAppsValidationFailedPrefix
<< "An urlscheme length exceeds maximum allowed ["
- << app_data[os_type][json::urlScheme].asString().length()
+ << app_data[json::ios][json::urlScheme].asString().length()
<< "]>[" << kUrlSchemaLengthMax << "]");
return false;
}
}
- if (os_type.empty()) {
- if (app_data.keyExists(json::android)) {
- os_type = json::android;
- if (!app_data[os_type].keyExists(json::packageName)) {
- LOG4CXX_WARN(logger_,
- kQueryAppsValidationFailedPrefix
- << "Can't find package name in json file.");
- return false;
- }
- if (app_data[json::android][json::packageName].asString().length() >
- kPackageNameLengthMax) {
- LOG4CXX_WARN(logger_,
- kQueryAppsValidationFailedPrefix
- << "Package name length ["
- << app_data[json::android][json::packageName]
- .asString()
- .length() << "] exceeds max length ["
- << kPackageNameLengthMax << "]in json file.");
- return false;
- }
- }
- }
- if (os_type.empty()) {
- LOG4CXX_WARN(logger_,
- kQueryAppsValidationFailedPrefix
- << "Can't find mobile OS type in json file.");
- return false;
+ if (json::android == os_type) {
+ if (app_data[json::android][json::packageName].asString().length() >
+ kPackageNameLengthMax) {
+ LOG4CXX_WARN(logger_,
+ kQueryAppsValidationFailedPrefix
+ << "Package name length ["
+ << app_data[json::android][json::packageName]
+ .asString()
+ .length() << "] exceeds max length ["
+ << kPackageNameLengthMax << "]in json file.");
+ return false;
+ }
}
// Languages verification
@@ -188,19 +185,12 @@ class QueryAppsDataValidator {
synonyms_map)) {
return false;
}
+ has_response_valid_application = true;
}
- return true;
+ return has_response_valid_application;
}
- bool ValidateAppIdAndAppName(const smart_objects::SmartObject& app_data,
- std::set<std::string>& app_ids_set) const {
- // Verify appid
- if (!app_data.keyExists(json::appId)) {
- LOG4CXX_WARN(logger_,
- kQueryAppsValidationFailedPrefix
- << "Can't find app ID in json file.");
- return false;
- }
+ bool ValidateAppIdAndAppName(const smart_objects::SmartObject& app_data) {
// Verify appid length
const std::string app_id(app_data[json::appId].asString());
if (app_id.length() > kAppIdLengthMax) {
@@ -212,30 +202,21 @@ class QueryAppsDataValidator {
}
// Verify that appid is unique
- if (app_ids_set.find(app_id) != app_ids_set.end()) {
+ if (applications_id_set_.find(app_id) != applications_id_set_.end()) {
LOG4CXX_WARN(logger_,
kQueryAppsValidationFailedPrefix
<< "An Object ID is not unigue [" << app_id << "]");
return false;
}
- app_ids_set.insert(app_id);
+ applications_id_set_.insert(app_id);
// Verify that app is not registered yet
ApplicationSharedPtr registered_app =
manager_.application_by_policy_id(app_id);
if (registered_app) {
- LOG4CXX_WARN(logger_,
- kQueryAppsValidationFailedPrefix
- << "Application with the same id: " << app_id
- << " is registered already.");
- return false;
- }
- // Verify app name exist
- if (!app_data.keyExists(json::name)) {
- LOG4CXX_WARN(logger_,
- kQueryAppsValidationFailedPrefix
- << "Can't find app name in json file.");
- return false;
+ LOG4CXX_INFO(logger_,
+ "Application with the id: " << app_id
+ << " is already registered.");
}
// And app name length
const std::string appName(app_data[json::name].asString());
@@ -404,8 +385,36 @@ class QueryAppsDataValidator {
return true;
}
- const smart_objects::SmartObject& data_;
- const ApplicationManagerImpl& manager_;
+ bool CheckMandatoryParametersPresent(
+ const smart_objects::SmartObject& app_data) const {
+ if (!app_data.keyExists(json::android) && !app_data.keyExists(json::ios)) {
+ return false;
+ }
+
+ if (app_data.keyExists(json::android) &&
+ !app_data[json::android].keyExists(json::packageName)) {
+ return false;
+ }
+
+ if (app_data.keyExists(json::ios) &&
+ !app_data[json::ios].keyExists(json::urlScheme)) {
+ return false;
+ }
+
+ if (!app_data.keyExists(json::appId)) {
+ return false;
+ }
+
+ if (!app_data.keyExists(json::name)) {
+ return false;
+ }
+
+ return true;
+ }
+
+ smart_objects::SmartObject& data_;
+ std::set<std::string> applications_id_set_;
+ const ApplicationManager& manager_;
DISALLOW_COPY_AND_ASSIGN(QueryAppsDataValidator);
};
@@ -413,23 +422,24 @@ class QueryAppsDataValidator {
namespace commands {
+namespace custom_str = utils::custom_string;
+
uint32_t SystemRequest::index = 0;
const std::string kSYNC = "SYNC";
const std::string kIVSU = "IVSU";
-SystemRequest::SystemRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+SystemRequest::SystemRequest(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-SystemRequest::~SystemRequest() {
-}
+SystemRequest::~SystemRequest() {}
void SystemRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (!(application.valid())) {
LOG4CXX_ERROR(logger_, "NULL pointer");
@@ -441,8 +451,10 @@ void SystemRequest::Run() {
static_cast<mobile_apis::RequestType::eType>(
(*message_)[strings::msg_params][strings::request_type].asInt());
- if (!policy::PolicyHandler::instance()->IsRequestTypeAllowed(
- application->mobile_app_id(), request_type)) {
+ const policy::PolicyHandlerInterface& policy_handler =
+ application_manager_.GetPolicyHandler();
+ if (!policy_handler.IsRequestTypeAllowed(application->policy_app_id(),
+ request_type)) {
SendResponse(false, mobile_apis::Result::DISALLOWED);
return;
}
@@ -469,15 +481,18 @@ void SystemRequest::Run() {
std::string binary_data_folder;
if ((*message_)[strings::params].keyExists(strings::binary_data)) {
binary_data = (*message_)[strings::params][strings::binary_data].asBinary();
- binary_data_folder = profile::Profile::instance()->system_files_path();
+ binary_data_folder =
+ application_manager_.get_settings().system_files_path();
} else {
- binary_data_folder = profile::Profile::instance()->app_storage_folder();
+ binary_data_folder =
+ application_manager_.get_settings().app_storage_folder();
binary_data_folder += "/";
binary_data_folder += application->folder_name();
binary_data_folder += "/";
}
- std::string file_dst_path = profile::Profile::instance()->system_files_path();
+ std::string file_dst_path =
+ application_manager_.get_settings().system_files_path();
file_dst_path += "/";
file_dst_path += file_name;
@@ -486,7 +501,7 @@ void SystemRequest::Run() {
logger_,
"Binary data is present. Trying to save it to: " << binary_data_folder);
if (mobile_apis::Result::SUCCESS !=
- (ApplicationManagerImpl::instance()->SaveBinary(
+ (application_manager_.SaveBinary(
binary_data, binary_data_folder, file_name, 0))) {
LOG4CXX_DEBUG(logger_, "Binary data can't be saved.");
SendResponse(false, mobile_apis::Result::GENERIC_ERROR);
@@ -524,7 +539,15 @@ void SystemRequest::Run() {
LOG4CXX_DEBUG(logger_, "Binary data ok.");
- if (mobile_apis::RequestType::QUERY_APPS == request_type) {
+ if (mobile_apis::RequestType::HTTP == request_type &&
+ (*message_)[strings::msg_params].keyExists(strings::file_name)) {
+ const std::string& file =
+ (*message_)[strings::msg_params][strings::file_name].asString();
+ application_manager_.GetPolicyHandler().ReceiveMessageFromSDK(file,
+ binary_data);
+ SendResponse(true, mobile_apis::Result::SUCCESS);
+ return;
+ } else if (mobile_apis::RequestType::QUERY_APPS == request_type) {
using namespace NsSmartDeviceLink::NsJSONHandler::Formatters;
smart_objects::SmartObject sm_object;
@@ -542,8 +565,7 @@ void SystemRequest::Run() {
return;
}
- ApplicationManagerImpl::instance()->ProcessQueryApp(sm_object,
- connection_key());
+ application_manager_.ProcessQueryApp(sm_object, connection_key());
SendResponse(true, mobile_apis::Result::SUCCESS);
return;
}
@@ -557,7 +579,7 @@ void SystemRequest::Run() {
}
if (mobile_apis::RequestType::PROPRIETARY != request_type) {
- msg_params[strings::app_id] = (application->mobile_app_id());
+ msg_params[strings::app_id] = (application->policy_app_id());
}
msg_params[strings::request_type] =
(*message_)[strings::msg_params][strings::request_type];
@@ -584,7 +606,7 @@ void SystemRequest::on_event(const event_engine::Event& event) {
mobile_api::Result::WARNINGS);
ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application(connection_key());
+ application_manager_.application(connection_key());
if (!(application.valid())) {
LOG4CXX_ERROR(logger_, "NULL pointer");
@@ -595,6 +617,7 @@ void SystemRequest::on_event(const event_engine::Event& event) {
file_system::DeleteFile(processing_file_);
processing_file_.clear();
}
+
SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
break;
}
@@ -606,7 +629,7 @@ void SystemRequest::on_event(const event_engine::Event& event) {
}
bool SystemRequest::ValidateQueryAppData(
- const smart_objects::SmartObject& data) const {
+ smart_objects::SmartObject& data) const {
if (!data.isValid()) {
LOG4CXX_ERROR(logger_,
kQueryAppsValidationFailedPrefix
@@ -620,10 +643,8 @@ bool SystemRequest::ValidateQueryAppData(
<< json::response << "' parameter.");
return false;
}
- ApplicationManagerImpl* manager = ApplicationManagerImpl::instance();
- DCHECK(manager);
- QueryAppsDataValidator validator(data, *manager);
+ QueryAppsDataValidator validator(data, application_manager_);
return validator.Validate();
}
diff --git a/src/components/application_manager/src/commands/mobile/system_response.cc b/src/components/application_manager/src/commands/mobile/system_response.cc
index 8b4fdafd1b..f5bc03f4a5 100644
--- a/src/components/application_manager/src/commands/mobile/system_response.cc
+++ b/src/components/application_manager/src/commands/mobile/system_response.cc
@@ -32,23 +32,21 @@
*/
#include "application_manager/commands/mobile/system_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
-SystemResponse::SystemResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+SystemResponse::SystemResponse(const MessageSharedPtr& message,
+ ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-SystemResponse::~SystemResponse() {
-}
+SystemResponse::~SystemResponse() {}
void SystemResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/mobile/unregister_app_interface_request.cc b/src/components/application_manager/src/commands/mobile/unregister_app_interface_request.cc
index dc63a11941..d7056a624e 100644
--- a/src/components/application_manager/src/commands/mobile/unregister_app_interface_request.cc
+++ b/src/components/application_manager/src/commands/mobile/unregister_app_interface_request.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/unregister_app_interface_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/message_helper.h"
namespace application_manager {
@@ -42,19 +42,19 @@ namespace commands {
void UnregisterAppInterfaceRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl* app_manager = ApplicationManagerImpl::instance();
-
- if (!app_manager->application(connection_key())) {
+ if (!application_manager_.application(connection_key())) {
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
LOG4CXX_ERROR(logger_, "Application is not registered");
return;
}
- MessageHelper::SendOnAppInterfaceUnregisteredNotificationToMobile(
- connection_key(),
- mobile_api::AppInterfaceUnregisteredReason::INVALID_ENUM);
- app_manager->UnregisterApplication(connection_key(),
- mobile_apis::Result::SUCCESS);
+ application_manager_.ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ connection_key(),
+ mobile_api::AppInterfaceUnregisteredReason::INVALID_ENUM),
+ commands::Command::ORIGIN_SDL);
+ application_manager_.UnregisterApplication(connection_key(),
+ mobile_apis::Result::SUCCESS);
SendResponse(true, mobile_apis::Result::SUCCESS);
}
diff --git a/src/components/application_manager/src/commands/mobile/unsubscribe_button_request.cc b/src/components/application_manager/src/commands/mobile/unsubscribe_button_request.cc
index a2958342ea..86df8fabb1 100644
--- a/src/components/application_manager/src/commands/mobile/unsubscribe_button_request.cc
+++ b/src/components/application_manager/src/commands/mobile/unsubscribe_button_request.cc
@@ -32,7 +32,7 @@
*/
#include "application_manager/commands/mobile/unsubscribe_button_request.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
namespace application_manager {
@@ -42,21 +42,18 @@ namespace commands {
namespace str = strings;
UnsubscribeButtonRequest::UnsubscribeButtonRequest(
- const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-UnsubscribeButtonRequest::~UnsubscribeButtonRequest() {
-}
+UnsubscribeButtonRequest::~UnsubscribeButtonRequest() {}
void UnsubscribeButtonRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
- LOG4CXX_ERROR_EXT(logger_, "APPLICATION_NOT_REGISTERED");
+ LOG4CXX_ERROR(logger_, "APPLICATION_NOT_REGISTERED");
SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
return;
}
@@ -64,13 +61,15 @@ void UnsubscribeButtonRequest::Run() {
const uint32_t btn_id =
(*message_)[str::msg_params][str::button_name].asUInt();
- if (!app->IsSubscribedToButton(static_cast<mobile_apis::ButtonName::eType>(btn_id))) {
- LOG4CXX_ERROR_EXT(logger_, "App doesn't subscibe to button " << btn_id);
+ if (!app->IsSubscribedToButton(
+ static_cast<mobile_apis::ButtonName::eType>(btn_id))) {
+ LOG4CXX_ERROR(logger_, "App doesn't subscibe to button " << btn_id);
SendResponse(false, mobile_apis::Result::IGNORED);
return;
}
- app->UnsubscribeFromButton(static_cast<mobile_apis::ButtonName::eType>(btn_id));
+ app->UnsubscribeFromButton(
+ static_cast<mobile_apis::ButtonName::eType>(btn_id));
SendUnsubscribeButtonNotification();
const bool is_succedeed = true;
diff --git a/src/components/application_manager/src/commands/mobile/unsubscribe_button_response.cc b/src/components/application_manager/src/commands/mobile/unsubscribe_button_response.cc
index 8bece66157..409579b294 100644
--- a/src/components/application_manager/src/commands/mobile/unsubscribe_button_response.cc
+++ b/src/components/application_manager/src/commands/mobile/unsubscribe_button_response.cc
@@ -32,19 +32,16 @@
*/
#include "application_manager/commands/mobile/unsubscribe_button_response.h"
-#include "application_manager/application_manager_impl.h"
namespace application_manager {
namespace commands {
UnsubscribeButtonResponse::UnsubscribeButtonResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-UnsubscribeButtonResponse::~UnsubscribeButtonResponse() {
-}
+UnsubscribeButtonResponse::~UnsubscribeButtonResponse() {}
void UnsubscribeButtonResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/mobile/unsubscribe_vehicle_data_request.cc b/src/components/application_manager/src/commands/mobile/unsubscribe_vehicle_data_request.cc
index 7d05ce328f..4fcc04c7be 100644
--- a/src/components/application_manager/src/commands/mobile/unsubscribe_vehicle_data_request.cc
+++ b/src/components/application_manager/src/commands/mobile/unsubscribe_vehicle_data_request.cc
@@ -33,65 +33,81 @@
#include "application_manager/commands/mobile/unsubscribe_vehicle_data_request.h"
#include "application_manager/commands/command_impl.h"
-#include "application_manager/application_manager_impl.h"
+
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
#include "application_manager/smart_object_keys.h"
+#include "utils/helpers.h"
namespace application_manager {
namespace commands {
UnsubscribeVehicleDataRequest::UnsubscribeVehicleDataRequest(
- const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
-UnsubscribeVehicleDataRequest::~UnsubscribeVehicleDataRequest() {
-}
+UnsubscribeVehicleDataRequest::~UnsubscribeVehicleDataRequest() {}
#ifdef HMI_DBUS_API
namespace {
- struct Subrequest {
- hmi_apis::FunctionID::eType func_id;
- const char* str;
- };
- Subrequest subrequests[] = {
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeGps, strings::gps},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeSpeed, strings::speed},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeRpm, strings::rpm},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeFuelLevel, strings::fuel_level},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeFuelLevel_State, strings::fuel_level_state},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeInstantFuelConsumption, strings::instant_fuel_consumption},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeExternalTemperature, strings::external_temp},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeVin, strings::vin},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribePrndl, strings::prndl},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeTirePressure, strings::tire_pressure},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeOdometer, strings::odometer},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeBeltStatus, strings::belt_status},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeBodyInformation, strings::body_information},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeDeviceStatus, strings::device_status},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeDriverBraking, strings::driver_braking},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeWiperStatus, strings::wiper_status},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeHeadLampStatus, strings::head_lamp_status},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeEngineTorque, strings::engine_torque},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeAccPedalPosition, strings::acc_pedal_pos},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeSteeringWheelAngle, strings::steering_wheel_angle},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeECallInfo, strings::e_call_info},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeAirbagStatus, strings::airbag_status},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeEmergencyEvent, strings::emergency_event},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeClusterModeStatus, strings::cluster_mode_status},
- { hmi_apis::FunctionID::VehicleInfo_UnsubscribeMyKey, strings::my_key},
- };
+struct Subrequest {
+ hmi_apis::FunctionID::eType func_id;
+ const char* str;
+};
+Subrequest subrequests[] = {
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeGps, strings::gps},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeSpeed, strings::speed},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeRpm, strings::rpm},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeFuelLevel,
+ strings::fuel_level},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeFuelLevel_State,
+ strings::fuel_level_state},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeInstantFuelConsumption,
+ strings::instant_fuel_consumption},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeExternalTemperature,
+ strings::external_temp},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeVin, strings::vin},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribePrndl, strings::prndl},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeTirePressure,
+ strings::tire_pressure},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeOdometer, strings::odometer},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeBeltStatus,
+ strings::belt_status},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeBodyInformation,
+ strings::body_information},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeDeviceStatus,
+ strings::device_status},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeDriverBraking,
+ strings::driver_braking},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeWiperStatus,
+ strings::wiper_status},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeHeadLampStatus,
+ strings::head_lamp_status},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeEngineTorque,
+ strings::engine_torque},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeAccPedalPosition,
+ strings::acc_pedal_pos},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeSteeringWheelAngle,
+ strings::steering_wheel_angle},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeECallInfo,
+ strings::e_call_info},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeAirbagStatus,
+ strings::airbag_status},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeEmergencyEvent,
+ strings::emergency_event},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeClusterModeStatus,
+ strings::cluster_mode_status},
+ {hmi_apis::FunctionID::VehicleInfo_UnsubscribeMyKey, strings::my_key},
+};
}
-#endif // #ifdef HMI_DBUS_API
+#endif // #ifdef HMI_DBUS_API
void UnsubscribeVehicleDataRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
- CommandRequestImpl::connection_key());
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
if (!app) {
LOG4CXX_ERROR(logger_, "NULL pointer");
@@ -99,62 +115,111 @@ void UnsubscribeVehicleDataRequest::Run() {
return;
}
- // counter for items to subscribe
int32_t items_to_unsubscribe = 0;
- // counter for subscribed items by application
int32_t unsubscribed_items = 0;
const VehicleData& vehicle_data = MessageHelper::vehicle_data();
VehicleData::const_iterator it = vehicle_data.begin();
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- smart_objects::SmartObject response_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
- msg_params[strings::app_id] = app->app_id();
+ smart_objects::SmartObject response_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
for (; vehicle_data.end() != it; ++it) {
- std::string key_name = it->first;
+ const std::string& key_name = it->first;
if ((*message_)[strings::msg_params].keyExists(key_name)) {
bool is_key_enabled = (*message_)[strings::msg_params][key_name].asBool();
if (is_key_enabled) {
++items_to_unsubscribe;
- msg_params[key_name] = is_key_enabled;
VehicleDataType key_type = it->second;
- if (app->UnsubscribeFromIVI(static_cast<uint32_t>(key_type))) {
+ if (!app->IsSubscribedToIVI(key_type)) {
++unsubscribed_items;
- } else {
+ vi_already_unsubscribed_by_this_app_.insert(key_type);
response_params[key_name][strings::data_type] = key_type;
response_params[key_name][strings::result_code] =
mobile_apis::VehicleDataResultCode::VDRC_DATA_NOT_SUBSCRIBED;
+ continue;
+ }
+
+ if (!app->UnsubscribeFromIVI(static_cast<uint32_t>(key_type))) {
+ LOG4CXX_ERROR(logger_,
+ "Unable to unsubscribe from "
+ "VehicleDataType: "
+ << key_type);
+ continue;
}
+
+ LOG4CXX_DEBUG(logger_,
+ "Unsubscribed app with connection key "
+ << connection_key()
+ << " from VehicleDataType: " << key_type);
+
+ ++unsubscribed_items;
+
+ if (IsSomeoneSubscribedFor(key_type)) {
+ LOG4CXX_DEBUG(logger_,
+ "There are another apps still subscribed for "
+ "VehicleDataType: "
+ << key_type);
+
+ vi_still_subscribed_by_another_apps_.insert(key_type);
+ response_params[key_name][strings::data_type] = key_type;
+ response_params[key_name][strings::result_code] =
+ mobile_apis::VehicleDataResultCode::VDRC_SUCCESS;
+ continue;
+ }
+
+ msg_params[key_name] = is_key_enabled;
}
}
}
+ bool is_everything_already_unsubscribed =
+ static_cast<uint32_t>(items_to_unsubscribe) ==
+ vi_still_subscribed_by_another_apps_.size() +
+ vi_already_unsubscribed_by_this_app_.size();
+
if (0 == items_to_unsubscribe) {
if (HasDisallowedParams()) {
SendResponse(false, mobile_apis::Result::DISALLOWED);
} else {
- SendResponse(false, mobile_apis::Result::INVALID_DATA,
- "No data in the request.");
+ SendResponse(
+ false, mobile_apis::Result::INVALID_DATA, "No data in the request.");
}
return;
- } else if (0 == unsubscribed_items) {
- SendResponse(false, mobile_apis::Result::IGNORED,
- "Was not subscribed on any VehicleData.", &response_params);
+ }
+
+ if (0 == unsubscribed_items) {
+ SendResponse(false,
+ mobile_apis::Result::IGNORED,
+ "Was not subscribed on any VehicleData.",
+ &response_params);
+ return;
+ }
+
+ if (is_everything_already_unsubscribed) {
+ mobile_apis::Result::eType result_code =
+ vi_already_unsubscribed_by_this_app_.size()
+ ? mobile_apis::Result::IGNORED
+ : mobile_apis::Result::SUCCESS;
+
+ const char* info = vi_already_unsubscribed_by_this_app_.size()
+ ? "Already subscribed on some provided VehicleData."
+ : NULL;
+
+ SendResponse(true, result_code, info, &response_params);
return;
}
#ifdef HMI_DBUS_API
- //Generate list of subrequests
+ // Generate list of subrequests
for (size_t i = 0; i < sizeof(subrequests) / sizeof(subrequests[0]); ++i) {
const Subrequest& sr = subrequests[i];
- if (true == (*message_)[strings::msg_params].keyExists(sr.str)
- && true == (*message_)[strings::msg_params][sr.str].asBool()) {
+ if (true == (*message_)[strings::msg_params].keyExists(sr.str) &&
+ true == (*message_)[strings::msg_params][sr.str].asBool()) {
HmiRequest hmi_request;
hmi_request.str = sr.str;
hmi_request.func_id = sr.func_id;
@@ -165,40 +230,49 @@ void UnsubscribeVehicleDataRequest::Run() {
LOG4CXX_INFO(logger_,
hmi_requests_.size() << " requests are going to be sent to HMI");
- //Send subrequests
+ // Send subrequests
for (HmiRequests::const_iterator it = hmi_requests_.begin();
- it != hmi_requests_.end(); ++it)
+ it != hmi_requests_.end();
+ ++it)
SendHMIRequest(it->func_id, &msg_params, true);
#else
SendHMIRequest(hmi_apis::FunctionID::VehicleInfo_UnsubscribeVehicleData,
- &msg_params, true);
-#endif // #ifdef HMI_DBUS_API
+ &msg_params,
+ true);
+#endif // #ifdef HMI_DBUS_API
}
void UnsubscribeVehicleDataRequest::on_event(const event_engine::Event& event) {
LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
const smart_objects::SmartObject& message = event.smart_object();
+ if (hmi_apis::FunctionID::VehicleInfo_UnsubscribeVehicleData != event.id()) {
+ LOG4CXX_ERROR(logger_, "Received unknown event.");
+ return;
+ }
+
#ifdef HMI_DBUS_API
for (HmiRequests::iterator it = hmi_requests_.begin();
- it != hmi_requests_.end(); ++it) {
- HmiRequest & hmi_request = *it;
+ it != hmi_requests_.end();
+ ++it) {
+ HmiRequest& hmi_request = *it;
if (hmi_request.func_id == event.id()) {
- hmi_request.status =
- static_cast<hmi_apis::Common_Result::eType>(message[strings::params][hmi_response::code]
- .asInt());
+ hmi_request.status = static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asInt());
if (hmi_apis::Common_Result::SUCCESS == hmi_request.status)
hmi_request.value = message[strings::msg_params][hmi_request.str];
hmi_request.complete = true;
break;
}
}
- bool all_complete = true;
+ bool all_complete = true;
bool any_arg_success = false;
mobile_api::Result::eType status = mobile_api::Result::eType::SUCCESS;
for (HmiRequests::const_iterator it = hmi_requests_.begin();
- it != hmi_requests_.end(); ++it) {
+ it != hmi_requests_.end();
+ ++it) {
if (!it->complete) {
all_complete = false;
break;
@@ -206,74 +280,129 @@ void UnsubscribeVehicleDataRequest::on_event(const event_engine::Event& event) {
if (hmi_apis::Common_Result::SUCCESS != it->status) {
if (mobile_api::Result::SUCCESS == status) {
status = static_cast<mobile_apis::Result::eType>(it->status);
- } else if (status
- != static_cast<mobile_apis::Result::eType>(it->status)) {
+ } else if (status !=
+ static_cast<mobile_apis::Result::eType>(it->status)) {
status = mobile_api::Result::eType::GENERIC_ERROR;
- } LOG4CXX_TRACE(logger_, "Status from HMI: " << it->status <<
- ", so response status become " << status);
+ }
+ LOG4CXX_TRACE(logger_,
+ "Status from HMI: " << it->status
+ << ", so response status become "
+ << status);
} else {
any_arg_success = true;
}
}
- if (all_complete) {
+ if (all_complete) {
smart_objects::SmartObject response_params(smart_objects::SmartType_Map);
if (any_arg_success) {
for (HmiRequests::const_iterator it = hmi_requests_.begin();
- it != hmi_requests_.end(); ++it) {
+ it != hmi_requests_.end();
+ ++it) {
response_params[it->str] = it->value;
}
}
+
LOG4CXX_INFO(logger_, "All HMI requests are complete");
+ if (true == any_arg_success) {
+ SetAllowedToTerminate(false);
+ }
SendResponse(any_arg_success, status, NULL, &response_params);
+ if (true == any_arg_success) {
+ UpdateHash();
+ }
}
#else
hmi_apis::Common_Result::eType hmi_result =
static_cast<hmi_apis::Common_Result::eType>(
message[strings::params][hmi_response::code].asInt());
- bool result =
- hmi_result == hmi_apis::Common_Result::SUCCESS;
+ bool is_succeeded = Compare<hmi_apis::Common_Result::eType, EQ, ONE>(
+ hmi_result,
+ hmi_apis::Common_Result::SUCCESS,
+ hmi_apis::Common_Result::WARNINGS);
mobile_apis::Result::eType result_code =
- hmi_result == hmi_apis::Common_Result::SUCCESS
- ? mobile_apis::Result::SUCCESS
- : static_cast<mobile_apis::Result::eType>(
- message[strings::params][hmi_response::code].asInt());
+ MessageHelper::HMIToMobileResult(hmi_result);
const char* return_info = NULL;
- if (result) {
- if (IsAnythingAlreadyUnsubscribed(message[strings::msg_params])) {
+ if (is_succeeded) {
+ if (vi_already_unsubscribed_by_this_app_.size()) {
result_code = mobile_apis::Result::IGNORED;
- return_info =
- std::string("Some provided VehicleData was not subscribed.").c_str();
+ return_info = "Some provided VehicleData was not subscribed.";
}
}
- SendResponse(result, result_code, return_info,
- &(message[strings::msg_params]));
-#endif // #ifdef HMI_DBUS_API
+ if (!vi_still_subscribed_by_another_apps_.empty() ||
+ !vi_already_unsubscribed_by_this_app_.empty()) {
+ AddAlreadyUnsubscribedVI(
+ const_cast<smart_objects::SmartObject&>(message[strings::msg_params]));
+ }
+
+ if (is_succeeded) {
+ SetAllowedToTerminate(false);
+ }
+ SendResponse(
+ is_succeeded, result_code, return_info, &(message[strings::msg_params]));
+ if (is_succeeded) {
+ UpdateHash();
+ }
+#endif // #ifdef HMI_DBUS_API
}
-bool UnsubscribeVehicleDataRequest::IsAnythingAlreadyUnsubscribed(
- const smart_objects::SmartObject& msg_params) const {
- LOG4CXX_INFO(logger_, "IsAnythingAlreadyUnsubscribed");
+struct SubscribedToIVIPredicate {
+ int32_t vehicle_info_;
+ SubscribedToIVIPredicate(int32_t vehicle_info)
+ : vehicle_info_(vehicle_info) {}
+ bool operator()(const ApplicationSharedPtr app) const {
+ return app ? app->IsSubscribedToIVI(vehicle_info_) : false;
+ }
+};
- const VehicleData& vehicle_data = MessageHelper::vehicle_data();
- VehicleData::const_iterator it = vehicle_data.begin();
+bool UnsubscribeVehicleDataRequest::IsSomeoneSubscribedFor(
+ const uint32_t param_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ SubscribedToIVIPredicate finder(param_id);
+ DataAccessor<ApplicationSet> accessor = application_manager_.applications();
+ ApplicationSetConstIt it = std::find_if(
+ accessor.GetData().begin(), accessor.GetData().end(), finder);
+ return it != accessor.GetData().end();
+}
- for (; vehicle_data.end() != it; ++it) {
- if (msg_params.keyExists(it->first)) {
- if (msg_params[it->first][strings::result_code].asInt() ==
- hmi_apis::Common_VehicleDataResultCode::VDRC_DATA_NOT_SUBSCRIBED) {
- return true;
- }
- }
+void UnsubscribeVehicleDataRequest::AddAlreadyUnsubscribedVI(
+ smart_objects::SmartObject& response) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace mobile_apis;
+ VehicleInfoSubscriptions::const_iterator it_same_app =
+ vi_already_unsubscribed_by_this_app_.begin();
+ for (; vi_already_unsubscribed_by_this_app_.end() != it_same_app;
+ ++it_same_app) {
+ response[*it_same_app][strings::result_code] =
+ VehicleDataResultCode::VDRC_DATA_NOT_SUBSCRIBED;
}
- return false;
+ VehicleInfoSubscriptions::const_iterator it_another_app =
+ vi_still_subscribed_by_another_apps_.begin();
+ for (; vi_still_subscribed_by_another_apps_.end() != it_another_app;
+ ++it_another_app) {
+ response[*it_another_app][strings::result_code] =
+ VehicleDataResultCode::VDRC_SUCCESS;
+ }
}
+void UnsubscribeVehicleDataRequest::UpdateHash() const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ ApplicationSharedPtr application =
+ application_manager_.application(connection_key());
+ if (application) {
+ application->UpdateHash();
+ } else {
+ LOG4CXX_ERROR(logger_,
+ "Application with connection_key = " << connection_key()
+ << " doesn't exist.");
+ }
+ application_manager_.TerminateRequest(connection_key(), correlation_id());
+}
} // namespace commands
} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/unsubscribe_vehicle_data_response.cc b/src/components/application_manager/src/commands/mobile/unsubscribe_vehicle_data_response.cc
index 87b2e6e5e1..e06158e4eb 100644
--- a/src/components/application_manager/src/commands/mobile/unsubscribe_vehicle_data_response.cc
+++ b/src/components/application_manager/src/commands/mobile/unsubscribe_vehicle_data_response.cc
@@ -37,12 +37,10 @@ namespace application_manager {
namespace commands {
UnsubscribeVehicleDataResponse::UnsubscribeVehicleDataResponse(
- const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-UnsubscribeVehicleDataResponse::~UnsubscribeVehicleDataResponse() {
-}
+UnsubscribeVehicleDataResponse::~UnsubscribeVehicleDataResponse() {}
void UnsubscribeVehicleDataResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/application_manager/src/commands/mobile/unsubscribe_way_points_request.cc b/src/components/application_manager/src/commands/mobile/unsubscribe_way_points_request.cc
new file mode 100644
index 0000000000..b19e292025
--- /dev/null
+++ b/src/components/application_manager/src/commands/mobile/unsubscribe_way_points_request.cc
@@ -0,0 +1,65 @@
+#include "application_manager/application_manager.h"
+#include "application_manager/commands/mobile/unsubscribe_way_points_request.h"
+
+namespace application_manager {
+
+namespace commands {
+
+UnSubscribeWayPointsRequest::UnSubscribeWayPointsRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
+
+UnSubscribeWayPointsRequest::~UnSubscribeWayPointsRequest() {}
+
+void UnSubscribeWayPointsRequest::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
+
+ if (!app) {
+ LOG4CXX_ERROR(logger_,
+ "An application with connection key "
+ << connection_key() << " is not registered.");
+ SendResponse(false, mobile_apis::Result::APPLICATION_NOT_REGISTERED);
+ return;
+ }
+
+ if (!application_manager_.IsAppSubscribedForWayPoints(app->app_id())) {
+ SendResponse(false, mobile_apis::Result::IGNORED);
+ return;
+ }
+
+ SendHMIRequest(
+ hmi_apis::FunctionID::Navigation_UnsubscribeWayPoints, NULL, true);
+}
+
+void UnSubscribeWayPointsRequest::on_event(const event_engine::Event& event) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ ApplicationSharedPtr app = application_manager_.application(connection_key());
+ const smart_objects::SmartObject& message = event.smart_object();
+ switch (event.id()) {
+ case hmi_apis::FunctionID::Navigation_UnsubscribeWayPoints: {
+ LOG4CXX_INFO(logger_, "Received Navigation_UnSubscribeWayPoints event");
+ mobile_apis::Result::eType result_code =
+ GetMobileResultCode(static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asUInt()));
+ bool result = mobile_apis::Result::SUCCESS == result_code;
+ if (result) {
+ application_manager_.UnsubscribeAppFromWayPoints(app->app_id());
+ }
+ SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
+ if (result) {
+ app->UpdateHash();
+ }
+ break;
+ }
+ default: {
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
+ break;
+ }
+ }
+}
+
+} // namespace commands
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/unsubscribe_way_points_response.cc b/src/components/application_manager/src/commands/mobile/unsubscribe_way_points_response.cc
new file mode 100644
index 0000000000..f6430d1f0d
--- /dev/null
+++ b/src/components/application_manager/src/commands/mobile/unsubscribe_way_points_response.cc
@@ -0,0 +1,22 @@
+#include "application_manager/application_manager.h"
+#include "application_manager/commands/mobile/unsubscribe_way_points_response.h"
+
+namespace application_manager {
+
+namespace commands {
+
+UnsubscribeWayPointsResponse::UnsubscribeWayPointsResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
+
+UnsubscribeWayPointsResponse::~UnsubscribeWayPointsResponse() {}
+
+void UnsubscribeWayPointsResponse::Run() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ application_manager_.SendMessageToMobile(message_);
+}
+
+} // namespace commands
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/commands/mobile/update_turn_list_request.cc b/src/components/application_manager/src/commands/mobile/update_turn_list_request.cc
index 650e698bf4..9b3b221446 100644
--- a/src/components/application_manager/src/commands/mobile/update_turn_list_request.cc
+++ b/src/components/application_manager/src/commands/mobile/update_turn_list_request.cc
@@ -33,27 +33,30 @@
#include <string>
#include "application_manager/commands/mobile/update_turn_list_request.h"
-#include "application_manager/application_manager_impl.h"
+
+#include "application_manager/policies/policy_handler.h"
#include "application_manager/application_impl.h"
#include "application_manager/message_helper.h"
#include "interfaces/MOBILE_API.h"
#include "interfaces/HMI_API.h"
+#include "utils/custom_string.h"
namespace application_manager {
namespace commands {
-UpdateTurnListRequest::UpdateTurnListRequest(const MessageSharedPtr& message)
- : CommandRequestImpl(message) {
-}
+namespace custom_str = utils::custom_string;
-UpdateTurnListRequest::~UpdateTurnListRequest() {
-}
+UpdateTurnListRequest::UpdateTurnListRequest(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandRequestImpl(message, application_manager) {}
+
+UpdateTurnListRequest::~UpdateTurnListRequest() {}
void UpdateTurnListRequest::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
+ ApplicationSharedPtr app = application_manager_.application(
(*message_)[strings::params][strings::connection_key].asUInt());
if (!app) {
@@ -69,10 +72,13 @@ void UpdateTurnListRequest::Run() {
return;
}
- //ProcessSoftButtons checks strings on the contents incorrect character
+ // ProcessSoftButtons checks strings on the contents incorrect character
mobile_apis::Result::eType processing_result =
- MessageHelper::ProcessSoftButtons((*message_)[strings::msg_params], app);
+ MessageHelper::ProcessSoftButtons((*message_)[strings::msg_params],
+ app,
+ application_manager_.GetPolicyHandler(),
+ application_manager_);
if (mobile_apis::Result::SUCCESS != processing_result) {
LOG4CXX_ERROR(logger_, "INVALID_DATA!");
@@ -84,20 +90,21 @@ void UpdateTurnListRequest::Run() {
smart_objects::SmartObject& turn_list_array =
((*message_)[strings::msg_params][strings::turn_list]);
for (uint32_t i = 0; i < turn_list_array.length(); ++i) {
- if((turn_list_array[i].keyExists(strings::turn_icon)) &&
- (mobile_apis::Result::SUCCESS != MessageHelper::VerifyImage(
- turn_list_array[i][strings::turn_icon], app))) {
- LOG4CXX_ERROR_EXT(
- logger_,
- "MessageHelper::VerifyImage return INVALID_DATA");
+ if ((turn_list_array[i].keyExists(strings::turn_icon)) &&
+ (mobile_apis::Result::SUCCESS !=
+ MessageHelper::VerifyImage(turn_list_array[i][strings::turn_icon],
+ app,
+ application_manager_))) {
+ LOG4CXX_ERROR(logger_,
+ "MessageHelper::VerifyImage return INVALID_DATA");
SendResponse(false, mobile_apis::Result::INVALID_DATA);
return;
}
}
}
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
msg_params = (*message_)[strings::msg_params];
if ((*message_)[strings::msg_params].keyExists(strings::turn_list)) {
@@ -109,15 +116,15 @@ void UpdateTurnListRequest::Run() {
for (uint32_t i = 0; i < msg_params[strings::turn_list].length(); ++i) {
if (msg_params[strings::turn_list][i].keyExists(hmi_request::navi_text)) {
- std::string navigation_text =
- msg_params[strings::turn_list][i][hmi_request::navi_text].asString();
+ const custom_str::CustomString& navigation_text =
+ msg_params[strings::turn_list][i][hmi_request::navi_text]
+ .asCustomString();
msg_params[strings::turn_list][i].erase(hmi_request::navi_text);
- msg_params[strings::turn_list]
- [i][hmi_request::navi_text][hmi_request::field_name] =
- static_cast<int>(hmi_apis::Common_TextFieldName::turnText);
- msg_params[strings::turn_list]
- [i][hmi_request::navi_text][hmi_request::field_text] =
- navigation_text;
+ msg_params[strings::turn_list][i][hmi_request::navi_text]
+ [hmi_request::field_name] = static_cast<int>(
+ hmi_apis::Common_TextFieldName::turnText);
+ msg_params[strings::turn_list][i][hmi_request::navi_text]
+ [hmi_request::field_text] = navigation_text;
}
}
}
@@ -125,14 +132,14 @@ void UpdateTurnListRequest::Run() {
msg_params[strings::app_id] = app->app_id();
if ((*message_)[strings::msg_params].keyExists(strings::soft_buttons)) {
- MessageHelper::SubscribeApplicationToSoftButton((*message_)[strings::msg_params],
- app, function_id());
+ MessageHelper::SubscribeApplicationToSoftButton(
+ (*message_)[strings::msg_params], app, function_id());
}
if ((*message_)[strings::msg_params].keyExists(strings::turn_list) ||
(*message_)[strings::msg_params].keyExists(strings::soft_buttons)) {
- SendHMIRequest(hmi_apis::FunctionID::Navigation_UpdateTurnList, &msg_params,
- true);
+ SendHMIRequest(
+ hmi_apis::FunctionID::Navigation_UpdateTurnList, &msg_params, true);
} else {
// conditional mandatory
LOG4CXX_ERROR(logger_, "INVALID_DATA!");
@@ -150,20 +157,20 @@ void UpdateTurnListRequest::on_event(const event_engine::Event& event) {
mobile_apis::Result::eType result_code =
static_cast<mobile_apis::Result::eType>(
- message[strings::params][hmi_response::code].asInt());
+ message[strings::params][hmi_response::code].asInt());
HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
+ application_manager_.hmi_capabilities();
- bool result = (mobile_apis::Result::SUCCESS == result_code) ||
+ bool result =
+ (mobile_apis::Result::SUCCESS == result_code) ||
((mobile_apis::Result::UNSUPPORTED_RESOURCE == result_code) &&
- (hmi_capabilities.is_ui_cooperating()));
-
+ (hmi_capabilities.is_ui_cooperating()));
SendResponse(result, result_code, NULL, &(message[strings::msg_params]));
break;
}
default: {
- LOG4CXX_ERROR(logger_,"Received unknown event" << event.id());
+ LOG4CXX_ERROR(logger_, "Received unknown event" << event.id());
break;
}
}
@@ -177,10 +184,10 @@ bool UpdateTurnListRequest::CheckTurnListArray() {
}
for (int32_t i = 0; i < length; ++i) {
- if (!((*message_)[strings::msg_params][strings::turn_list][i].
- keyExists(hmi_request::navi_text)) &&
- !((*message_)[strings::msg_params][strings::turn_list][i].
- keyExists(strings::turn_icon))) {
+ if (!((*message_)[strings::msg_params][strings::turn_list][i].keyExists(
+ hmi_request::navi_text)) &&
+ !((*message_)[strings::msg_params][strings::turn_list][i].keyExists(
+ strings::turn_icon))) {
return false;
}
}
@@ -202,7 +209,8 @@ bool UpdateTurnListRequest::IsWhiteSpaceExist() {
if ((*it_tl).keyExists(strings::navigation_text)) {
str = (*it_tl)[strings::navigation_text].asCharArray();
if (!CheckSyntax(str)) {
- LOG4CXX_ERROR(logger_,
+ LOG4CXX_ERROR(
+ logger_,
"Invalid turn_list navigation_text text syntax check failed");
return true;
}
@@ -211,12 +219,11 @@ bool UpdateTurnListRequest::IsWhiteSpaceExist() {
if ((*it_tl).keyExists(strings::turn_icon)) {
str = (*it_tl)[strings::turn_icon][strings::value].asCharArray();
if (!CheckSyntax(str)) {
- LOG4CXX_ERROR(logger_,
- "Invalid turn_list turn_icon value syntax check failed");
+ LOG4CXX_ERROR(
+ logger_, "Invalid turn_list turn_icon value syntax check failed");
return true;
}
}
-
}
}
return false;
diff --git a/src/components/application_manager/src/commands/mobile/update_turn_list_response.cc b/src/components/application_manager/src/commands/mobile/update_turn_list_response.cc
index 26e5c460d3..d40a4546fc 100644
--- a/src/components/application_manager/src/commands/mobile/update_turn_list_response.cc
+++ b/src/components/application_manager/src/commands/mobile/update_turn_list_response.cc
@@ -32,24 +32,23 @@
*/
#include "application_manager/commands/mobile/update_turn_list_response.h"
-#include "application_manager/application_manager_impl.h"
+
#include "interfaces/HMI_API.h"
namespace application_manager {
namespace commands {
-UpdateTurnListResponse::UpdateTurnListResponse(const MessageSharedPtr& message)
- : CommandResponseImpl(message) {
-}
+UpdateTurnListResponse::UpdateTurnListResponse(
+ const MessageSharedPtr& message, ApplicationManager& application_manager)
+ : CommandResponseImpl(message, application_manager) {}
-UpdateTurnListResponse::~UpdateTurnListResponse() {
-}
+UpdateTurnListResponse::~UpdateTurnListResponse() {}
void UpdateTurnListResponse::Run() {
LOG4CXX_AUTO_TRACE(logger_);
- ApplicationManagerImpl::instance()->SendMessageToMobile(message_);
+ application_manager_.SendMessageToMobile(message_);
}
} // namespace commands
diff --git a/src/components/application_manager/src/commands/pending.cc b/src/components/application_manager/src/commands/pending.cc
index 0c04464af3..c410a84fa5 100644
--- a/src/components/application_manager/src/commands/pending.cc
+++ b/src/components/application_manager/src/commands/pending.cc
@@ -37,13 +37,9 @@ namespace application_manager {
namespace commands {
+Pending::Pending() : last_(hmi_apis::FunctionID::INVALID_ENUM) {}
-Pending::Pending()
-: last_(hmi_apis::FunctionID::INVALID_ENUM) {
-}
-
-Pending::~Pending() {
-}
+Pending::~Pending() {}
void Pending::Add(hmi_apis::FunctionID::eType id) {
sync_primitives::AutoLock L(lock_);
diff --git a/src/components/application_manager/src/event_engine/event.cc b/src/components/application_manager/src/event_engine/event.cc
index 561e8a841f..cc180ca950 100644
--- a/src/components/application_manager/src/event_engine/event.cc
+++ b/src/components/application_manager/src/event_engine/event.cc
@@ -36,21 +36,17 @@
namespace application_manager {
namespace event_engine {
-Event::Event(const EventID& id)
-: id_(id)
-, response_so_() {
-}
+Event::Event(const EventID& id) : id_(id), response_so_() {}
-Event::~Event() {
-}
+Event::~Event() {}
-void Event::raise() {
- EventDispatcher::instance()->raise_event(*this);
+void Event::raise(EventDispatcher& event_dispatcher) {
+ event_dispatcher.raise_event(*this);
}
void Event::set_smart_object(const smart_objects::SmartObject& so) {
response_so_ = so;
}
-}
-}
+} // namespace event_engine
+} // namespace application_manager
diff --git a/src/components/application_manager/src/event_engine/event_dispatcher.cc b/src/components/application_manager/src/event_engine/event_dispatcher.cc
deleted file mode 100644
index bac94431f0..0000000000
--- a/src/components/application_manager/src/event_engine/event_dispatcher.cc
+++ /dev/null
@@ -1,138 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "interfaces/HMI_API.h"
-#include "application_manager/event_engine/event_observer.h"
-#include "application_manager/event_engine/event_dispatcher.h"
-
-namespace application_manager {
-namespace event_engine {
-using namespace sync_primitives;
-
-EventDispatcher::EventDispatcher()
- : observer_list_lock_(true),
- observers_() {
-}
-
-EventDispatcher::~EventDispatcher() {
-}
-
-void EventDispatcher::raise_event(const Event& event) {
- {
- AutoLock auto_lock(state_lock_);
- // check if event is notification
- if (hmi_apis::messageType::notification == event.smart_object_type()) {
- const uint32_t notification_correlation_id = 0;
- observers_list_ = observers_[event.id()][notification_correlation_id];
- }
-
- if (hmi_apis::messageType::response == event.smart_object_type()
- || hmi_apis::messageType::error_response == event.smart_object_type()) {
- observers_list_ = observers_[event.id()][event.smart_object_correlation_id()];
- }
- }
-
- // Call observers
- EventObserver* temp;
- while (observers_list_.size() > 0) {
- observer_list_lock_.Acquire();
- if (!observers_list_.empty()) {
- temp = observers_list_.front();
- observers_list_.pop_front();
- temp->on_event(event);
- }
- observer_list_lock_.Release();
- }
-}
-
-void EventDispatcher::add_observer(const Event::EventID& event_id,
- int32_t hmi_correlation_id,
- EventObserver* const observer) {
- AutoLock auto_lock(state_lock_);
- observers_[event_id][hmi_correlation_id].push_back(observer);
-}
-
-void EventDispatcher::remove_observer(const Event::EventID& event_id,
- EventObserver* const observer) {
- remove_observer_from_list(observer);
- AutoLock auto_lock(state_lock_);
- ObserversMap::iterator it = observers_[event_id].begin();
- for (; observers_[event_id].end() != it; ++it) {
-
- //ObserverList iterator
- ObserverList::iterator observer_it = it->second.begin();
- while (it->second.end() != observer_it) {
- if (observer->id() == (*observer_it)->id()) {
- observer_it = it->second.erase(observer_it);
- } else {
- ++observer_it;
- }
- }
- }
-}
-
-void EventDispatcher::remove_observer(EventObserver* const observer) {
- remove_observer_from_list(observer);
- AutoLock auto_lock(state_lock_);
- EventObserverMap::iterator event_map = observers_.begin();
- for (; observers_.end() != event_map; ++event_map) {
- ObserversMap::iterator it = event_map->second.begin();
- for (; event_map->second.end() != it; ++it) {
-
- //ObserverList iterator
- ObserverList::iterator observer_it = it->second.begin();
- while (it->second.end() != observer_it) {
- if (observer->id() == (*observer_it)->id()) {
- observer_it = it->second.erase(observer_it);
- } else {
- ++observer_it;
- }
- }
- }
- }
-}
-
-void EventDispatcher::remove_observer_from_list(EventObserver* const observer) {
- AutoLock auto_lock(observer_list_lock_);
- if (!observers_list_.empty()) {
- ObserverList::iterator it_begin = observers_list_.begin();
- for(; it_begin != observers_list_.end(); ++it_begin) {
- if ((*it_begin)->id() == observer->id()) {
- it_begin = observers_list_.erase(it_begin);
- }
- }
- }
-}
-
-} // namespace event_engine
-
-}// namespace application_manager
diff --git a/src/components/application_manager/src/event_engine/event_dispatcher_impl.cc b/src/components/application_manager/src/event_engine/event_dispatcher_impl.cc
new file mode 100644
index 0000000000..f8b8bc791d
--- /dev/null
+++ b/src/components/application_manager/src/event_engine/event_dispatcher_impl.cc
@@ -0,0 +1,126 @@
+/*
+ Copyright (c) 2016, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/event_engine/event_dispatcher_impl.h"
+#include "interfaces/HMI_API.h"
+#include "application_manager/event_engine/event_observer.h"
+#include <algorithm>
+
+namespace application_manager {
+namespace event_engine {
+using namespace sync_primitives;
+
+EventDispatcherImpl::EventDispatcherImpl()
+ : state_lock_(false), observer_lock_(true), observers_event_() {}
+
+EventDispatcherImpl::~EventDispatcherImpl() {}
+
+void EventDispatcherImpl::raise_event(const Event& event) {
+ {
+ AutoLock auto_lock(state_lock_);
+ // check if event is notification
+ if (hmi_apis::messageType::notification == event.smart_object_type()) {
+ const uint32_t notification_correlation_id = 0;
+ observers_ = observers_event_[event.id()][notification_correlation_id];
+ }
+
+ if (hmi_apis::messageType::response == event.smart_object_type() ||
+ hmi_apis::messageType::error_response == event.smart_object_type()) {
+ observers_ =
+ observers_event_[event.id()][event.smart_object_correlation_id()];
+ }
+ }
+
+ // Call observers
+ EventObserver* temp;
+ while (!observers_.empty()) {
+ AutoLock auto_lock(observer_lock_);
+ temp = *observers_.begin();
+ observers_.erase(observers_.begin());
+ temp->on_event(event);
+ }
+}
+
+void EventDispatcherImpl::add_observer(const Event::EventID& event_id,
+ int32_t hmi_correlation_id,
+ EventObserver& observer) {
+ AutoLock auto_lock(state_lock_);
+ observers_event_[event_id][hmi_correlation_id].push_back(&observer);
+}
+
+struct IdCheckFunctor {
+ IdCheckFunctor(const unsigned long id) : target_id(id) {}
+
+ bool operator()(const EventObserver* obs) const {
+ return (obs->id() == target_id);
+ }
+
+ private:
+ const unsigned long target_id;
+};
+
+void EventDispatcherImpl::remove_observer(const Event::EventID& event_id,
+ EventObserver& observer) {
+ remove_observer_from_vector(observer);
+ AutoLock auto_lock(state_lock_);
+ ObserversMap::iterator it = observers_event_[event_id].begin();
+
+ for (; observers_event_[event_id].end() != it; ++it) {
+ ObserverVector& obs_vec = it->second;
+ const ObserverVector::iterator obs_vec_it = obs_vec.end();
+ obs_vec.erase(
+ std::remove_if(
+ obs_vec.begin(), obs_vec_it, IdCheckFunctor(observer.id())),
+ obs_vec_it);
+ }
+}
+
+void EventDispatcherImpl::remove_observer(EventObserver& observer) {
+ remove_observer_from_vector(observer);
+ EventObserverMap::iterator event_map = observers_event_.begin();
+
+ for (; observers_event_.end() != event_map; ++event_map) {
+ remove_observer(event_map->first, observer);
+ }
+}
+
+void EventDispatcherImpl::remove_observer_from_vector(EventObserver& observer) {
+ AutoLock auto_lock(observer_lock_);
+
+ observers_.erase(
+ std::remove_if(
+ observers_.begin(), observers_.end(), IdCheckFunctor(observer.id())),
+ observers_.end());
+}
+
+} // namespace event_engine
+} // namespace application_manager
diff --git a/src/components/application_manager/src/event_engine/event_observer.cc b/src/components/application_manager/src/event_engine/event_observer.cc
index c6d81529f9..f89f6649b1 100644
--- a/src/components/application_manager/src/event_engine/event_observer.cc
+++ b/src/components/application_manager/src/event_engine/event_observer.cc
@@ -1,5 +1,5 @@
/*
- Copyright (c) 2013, Ford Motor Company
+ Copyright (c) 2016, Ford Motor Company
All rights reserved.
Redistribution and use in source and binary forms, with or without
@@ -30,15 +30,16 @@
POSSIBILITY OF SUCH DAMAGE.
*/
-#include "application_manager/event_engine/event.h"
#include "application_manager/event_engine/event_observer.h"
+#include "application_manager/event_engine/event.h"
+#include "application_manager/event_engine/event_dispatcher.h"
namespace application_manager {
namespace event_engine {
-EventObserver::EventObserver()
- : id_(0) {
- //Get unique id based on this
+EventObserver::EventObserver(EventDispatcher& event_dispatcher)
+ : id_(0), event_dispatcher_(event_dispatcher) {
+ // Get unique id based on this
id_ = reinterpret_cast<unsigned long>(this);
}
@@ -48,16 +49,16 @@ EventObserver::~EventObserver() {
void EventObserver::subscribe_on_event(const Event::EventID& event_id,
int32_t hmi_correlation_id) {
- EventDispatcher::instance()->add_observer(event_id, hmi_correlation_id, this);
+ event_dispatcher_.add_observer(event_id, hmi_correlation_id, *this);
}
void EventObserver::unsubscribe_from_event(const Event::EventID& event_id) {
- EventDispatcher::instance()->remove_observer(event_id, this);
+ event_dispatcher_.remove_observer(event_id, *this);
}
void EventObserver::unsubscribe_from_all_events() {
- EventDispatcher::instance()->remove_observer(this);
+ event_dispatcher_.remove_observer(*this);
}
-}
-}
+} // namespace event_engine
+} // namespace application_manager
diff --git a/src/components/application_manager/src/hmi_capabilities.cc b/src/components/application_manager/src/hmi_capabilities.cc
index 5c7f3f0b5d..7535984c16 100644
--- a/src/components/application_manager/src/hmi_capabilities.cc
+++ b/src/components/application_manager/src/hmi_capabilities.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -37,142 +37,145 @@
#include "json/json.h"
#include "utils/file_system.h"
#include "interfaces/HMI_API.h"
-#include "config_profile/profile.h"
#include "smart_objects/smart_object.h"
#include "application_manager/smart_object_keys.h"
#include "application_manager/message_helper.h"
-#include "application_manager/application_manager_impl.h"
-#include "formatters/CFormatterJsonBase.hpp"
+#include "application_manager/smart_object_keys.h"
+#include "application_manager/application_manager.h"
+#include "application_manager/message_helper.h"
+#include "formatters/CFormatterJsonBase.h"
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationManager")
namespace application_manager {
namespace Formatters = NsSmartDeviceLink::NsJSONHandler::Formatters;
-CREATE_LOGGERPTR_GLOBAL(logger_, "HMICapabilities")
-
-std::map<std::string, hmi_apis::Common_VrCapabilities::eType> vr_enum_capabilities =
-{
- {"TEXT", hmi_apis::Common_VrCapabilities::VR_TEXT}
-};
-
-std::map<std::string, hmi_apis::Common_ButtonName::eType> button_enum_name =
-{
- {"OK" , hmi_apis::Common_ButtonName::OK},
- {"SEEKLEFT" , hmi_apis::Common_ButtonName::SEEKLEFT},
- {"SEEKRIGHT" , hmi_apis::Common_ButtonName::SEEKRIGHT},
- {"TUNEUP" , hmi_apis::Common_ButtonName::TUNEUP},
- {"TUNEDOWN" , hmi_apis::Common_ButtonName::TUNEDOWN},
- {"PRESET_0" , hmi_apis::Common_ButtonName::PRESET_0},
- {"PRESET_1" , hmi_apis::Common_ButtonName::PRESET_1},
- {"PRESET_2" , hmi_apis::Common_ButtonName::PRESET_2},
- {"PRESET_3" , hmi_apis::Common_ButtonName::PRESET_3},
- {"PRESET_4" , hmi_apis::Common_ButtonName::PRESET_4},
- {"PRESET_5" , hmi_apis::Common_ButtonName::PRESET_5},
- {"PRESET_6" , hmi_apis::Common_ButtonName::PRESET_6},
- {"PRESET_7" , hmi_apis::Common_ButtonName::PRESET_7},
- {"PRESET_8" , hmi_apis::Common_ButtonName::PRESET_8},
- {"PRESET_9" , hmi_apis::Common_ButtonName::PRESET_9},
- {"CUSTOM_BUTTON" , hmi_apis::Common_ButtonName::CUSTOM_BUTTON},
- {"SEARCH" , hmi_apis::Common_ButtonName::SEARCH},
+std::map<std::string, hmi_apis::Common_VrCapabilities::eType>
+ vr_enum_capabilities = {{"TEXT", hmi_apis::Common_VrCapabilities::VR_TEXT}};
+
+std::map<std::string, hmi_apis::Common_ButtonName::eType> button_enum_name = {
+ {"OK", hmi_apis::Common_ButtonName::OK},
+ {"SEEKLEFT", hmi_apis::Common_ButtonName::SEEKLEFT},
+ {"SEEKRIGHT", hmi_apis::Common_ButtonName::SEEKRIGHT},
+ {"TUNEUP", hmi_apis::Common_ButtonName::TUNEUP},
+ {"TUNEDOWN", hmi_apis::Common_ButtonName::TUNEDOWN},
+ {"PRESET_0", hmi_apis::Common_ButtonName::PRESET_0},
+ {"PRESET_1", hmi_apis::Common_ButtonName::PRESET_1},
+ {"PRESET_2", hmi_apis::Common_ButtonName::PRESET_2},
+ {"PRESET_3", hmi_apis::Common_ButtonName::PRESET_3},
+ {"PRESET_4", hmi_apis::Common_ButtonName::PRESET_4},
+ {"PRESET_5", hmi_apis::Common_ButtonName::PRESET_5},
+ {"PRESET_6", hmi_apis::Common_ButtonName::PRESET_6},
+ {"PRESET_7", hmi_apis::Common_ButtonName::PRESET_7},
+ {"PRESET_8", hmi_apis::Common_ButtonName::PRESET_8},
+ {"PRESET_9", hmi_apis::Common_ButtonName::PRESET_9},
+ {"CUSTOM_BUTTON", hmi_apis::Common_ButtonName::CUSTOM_BUTTON},
+ {"SEARCH", hmi_apis::Common_ButtonName::SEARCH},
};
-std::map<std::string, hmi_apis::Common_TextFieldName::eType> text_fields_enum_name =
-{
+std::map<std::string,
+ hmi_apis::Common_TextFieldName::eType> text_fields_enum_name = {
{"mainField1", hmi_apis::Common_TextFieldName::mainField1},
{"mainField2", hmi_apis::Common_TextFieldName::mainField2},
{"mainField3", hmi_apis::Common_TextFieldName::mainField3},
{"mainField4", hmi_apis::Common_TextFieldName::mainField4},
- {"statusBar" , hmi_apis::Common_TextFieldName::statusBar},
+ {"statusBar", hmi_apis::Common_TextFieldName::statusBar},
{"mediaClock", hmi_apis::Common_TextFieldName::mediaClock},
{"mediaTrack", hmi_apis::Common_TextFieldName::mediaTrack},
{"alertText1", hmi_apis::Common_TextFieldName::alertText1},
{"alertText2", hmi_apis::Common_TextFieldName::alertText2},
{"alertText3", hmi_apis::Common_TextFieldName::alertText3},
- {"scrollableMessageBody" , hmi_apis::Common_TextFieldName::scrollableMessageBody},
- {"initialInteractionText", hmi_apis::Common_TextFieldName::initialInteractionText},
- {"navigationText1" , hmi_apis::Common_TextFieldName::navigationText1},
- {"navigationText2" , hmi_apis::Common_TextFieldName::navigationText2},
- {"ETA" , hmi_apis::Common_TextFieldName::ETA},
- {"totalDistance" , hmi_apis::Common_TextFieldName::totalDistance},
- {"audioPassThruDisplayText1", hmi_apis::Common_TextFieldName::audioPassThruDisplayText1},
- {"audioPassThruDisplayText2", hmi_apis::Common_TextFieldName::audioPassThruDisplayText2},
- {"sliderHeader" , hmi_apis::Common_TextFieldName::sliderHeader},
- {"sliderFooter" , hmi_apis::Common_TextFieldName::sliderFooter},
- {"notificationText" , hmi_apis::Common_TextFieldName::notificationText},
- {"menuName" , hmi_apis::Common_TextFieldName::menuName},
- {"secondaryText" , hmi_apis::Common_TextFieldName::secondaryText},
- {"tertiaryText" , hmi_apis::Common_TextFieldName::tertiaryText},
+ {"scrollableMessageBody",
+ hmi_apis::Common_TextFieldName::scrollableMessageBody},
+ {"initialInteractionText",
+ hmi_apis::Common_TextFieldName::initialInteractionText},
+ {"navigationText1", hmi_apis::Common_TextFieldName::navigationText1},
+ {"navigationText2", hmi_apis::Common_TextFieldName::navigationText2},
+ {"ETA", hmi_apis::Common_TextFieldName::ETA},
+ {"totalDistance", hmi_apis::Common_TextFieldName::totalDistance},
+ {"audioPassThruDisplayText1",
+ hmi_apis::Common_TextFieldName::audioPassThruDisplayText1},
+ {"audioPassThruDisplayText2",
+ hmi_apis::Common_TextFieldName::audioPassThruDisplayText2},
+ {"sliderHeader", hmi_apis::Common_TextFieldName::sliderHeader},
+ {"sliderFooter", hmi_apis::Common_TextFieldName::sliderFooter},
+ {"notificationText", hmi_apis::Common_TextFieldName::notificationText},
+ {"menuName", hmi_apis::Common_TextFieldName::menuName},
+ {"secondaryText", hmi_apis::Common_TextFieldName::secondaryText},
+ {"tertiaryText", hmi_apis::Common_TextFieldName::tertiaryText},
{"timeToDestination", hmi_apis::Common_TextFieldName::timeToDestination},
- {"locationName" , hmi_apis::Common_TextFieldName::locationName},
- {"locationDescription", hmi_apis::Common_TextFieldName::locationDescription},
- {"addressLines" , hmi_apis::Common_TextFieldName::turnText},
- {"turnText" , hmi_apis::Common_TextFieldName::addressLines},
- {"phoneNumber" , hmi_apis::Common_TextFieldName::phoneNumber},
- {"turnText" , hmi_apis::Common_TextFieldName::turnText},
- {"menuTitle" , hmi_apis::Common_TextFieldName::menuTitle},
+ {"locationName", hmi_apis::Common_TextFieldName::locationName},
+ {"locationDescription",
+ hmi_apis::Common_TextFieldName::locationDescription},
+ {"addressLines", hmi_apis::Common_TextFieldName::turnText},
+ {"turnText", hmi_apis::Common_TextFieldName::addressLines},
+ {"phoneNumber", hmi_apis::Common_TextFieldName::phoneNumber},
+ {"turnText", hmi_apis::Common_TextFieldName::turnText},
+ {"menuTitle", hmi_apis::Common_TextFieldName::menuTitle},
+ {"navigationText", hmi_apis::Common_TextFieldName::navigationText},
};
-std::map<std::string, hmi_apis::Common_MediaClockFormat::eType> media_clock_enum_name =
-{
- {"CLOCK1" , hmi_apis::Common_MediaClockFormat::CLOCK1},
- {"CLOCK2" , hmi_apis::Common_MediaClockFormat::CLOCK2},
- {"CLOCK3" , hmi_apis::Common_MediaClockFormat::CLOCK3},
- {"CLOCKTEXT1", hmi_apis::Common_MediaClockFormat::CLOCKTEXT1},
- {"CLOCKTEXT2", hmi_apis::Common_MediaClockFormat::CLOCKTEXT2},
- {"CLOCKTEXT3", hmi_apis::Common_MediaClockFormat::CLOCKTEXT3},
- {"CLOCKTEXT4", hmi_apis::Common_MediaClockFormat::CLOCKTEXT4},
+std::map<std::string, hmi_apis::Common_MediaClockFormat::eType>
+ media_clock_enum_name = {
+ {"CLOCK1", hmi_apis::Common_MediaClockFormat::CLOCK1},
+ {"CLOCK2", hmi_apis::Common_MediaClockFormat::CLOCK2},
+ {"CLOCK3", hmi_apis::Common_MediaClockFormat::CLOCK3},
+ {"CLOCKTEXT1", hmi_apis::Common_MediaClockFormat::CLOCKTEXT1},
+ {"CLOCKTEXT2", hmi_apis::Common_MediaClockFormat::CLOCKTEXT2},
+ {"CLOCKTEXT3", hmi_apis::Common_MediaClockFormat::CLOCKTEXT3},
+ {"CLOCKTEXT4", hmi_apis::Common_MediaClockFormat::CLOCKTEXT4},
};
-std::map<std::string, hmi_apis::Common_ImageType::eType> image_type_enum =
-{
- {"STATIC" , hmi_apis::Common_ImageType::STATIC},
- {"DYNAMIC", hmi_apis::Common_ImageType::DYNAMIC}
-};
+std::map<std::string, hmi_apis::Common_ImageType::eType> image_type_enum = {
+ {"STATIC", hmi_apis::Common_ImageType::STATIC},
+ {"DYNAMIC", hmi_apis::Common_ImageType::DYNAMIC}};
std::map<std::string, hmi_apis::Common_SamplingRate::eType> sampling_rate_enum =
-{
- {"8KHZ" , hmi_apis::Common_SamplingRate::RATE_8KHZ},
- {"16KHZ", hmi_apis::Common_SamplingRate::RATE_16KHZ},
- {"22KHZ", hmi_apis::Common_SamplingRate::RATE_22KHZ},
- {"44KHZ", hmi_apis::Common_SamplingRate::RATE_44KHZ}
-};
-
-std::map<std::string, hmi_apis::Common_BitsPerSample::eType> bit_per_sample_enum =
-{
- {"RATE_8_BIT", hmi_apis::Common_BitsPerSample::RATE_8_BIT},
- {"RATE_16_BIT", hmi_apis::Common_BitsPerSample::RATE_16_BIT}
-};
-
-std::map<std::string, hmi_apis::Common_AudioType::eType> audio_type_enum =
-{
- {"PCM", hmi_apis::Common_AudioType::PCM}
-};
-
-std::map<std::string, hmi_apis::Common_HmiZoneCapabilities::eType> hmi_zone_enum =
-{
- {"FRONT", hmi_apis::Common_HmiZoneCapabilities::FRONT},
- {"BACK", hmi_apis::Common_HmiZoneCapabilities::BACK},
+ {{"RATE_8KHZ", hmi_apis::Common_SamplingRate::RATE_8KHZ},
+ {"8KHZ", hmi_apis::Common_SamplingRate::RATE_8KHZ},
+ {"RATE_16KHZ", hmi_apis::Common_SamplingRate::RATE_16KHZ},
+ {"16KHZ", hmi_apis::Common_SamplingRate::RATE_16KHZ},
+ {"RATE_22KHZ", hmi_apis::Common_SamplingRate::RATE_22KHZ},
+ {"22KHZ", hmi_apis::Common_SamplingRate::RATE_22KHZ},
+ {"RATE_44KHZ", hmi_apis::Common_SamplingRate::RATE_44KHZ},
+ {"44KHZ", hmi_apis::Common_SamplingRate::RATE_44KHZ}};
+
+std::map<std::string, hmi_apis::Common_BitsPerSample::eType>
+ bit_per_sample_enum = {
+ {"RATE_8_BIT", hmi_apis::Common_BitsPerSample::RATE_8_BIT},
+ {"8_BIT", hmi_apis::Common_BitsPerSample::RATE_8_BIT},
+ {"RATE_16_BIT", hmi_apis::Common_BitsPerSample::RATE_16_BIT},
+ {"16_BIT", hmi_apis::Common_BitsPerSample::RATE_16_BIT}};
+
+std::map<std::string, hmi_apis::Common_AudioType::eType> audio_type_enum = {
+ {"PCM", hmi_apis::Common_AudioType::PCM}};
+
+std::map<std::string, hmi_apis::Common_HmiZoneCapabilities::eType>
+ hmi_zone_enum = {
+ {"FRONT", hmi_apis::Common_HmiZoneCapabilities::FRONT},
+ {"BACK", hmi_apis::Common_HmiZoneCapabilities::BACK},
};
const std::map<std::string, hmi_apis::Common_ImageFieldName::eType>
-image_field_name_enum =
-{
- {"softButtonImage", hmi_apis::Common_ImageFieldName::softButtonImage},
- {"choiceImage", hmi_apis::Common_ImageFieldName::choiceImage},
- {"choiceSecondaryImage", hmi_apis::Common_ImageFieldName::choiceSecondaryImage},
- {"vrHelpItem", hmi_apis::Common_ImageFieldName::vrHelpItem},
- {"turnIcon", hmi_apis::Common_ImageFieldName::turnIcon},
- {"menuIcon", hmi_apis::Common_ImageFieldName::menuIcon},
- {"cmdIcon", hmi_apis::Common_ImageFieldName::cmdIcon},
- {"appIcon", hmi_apis::Common_ImageFieldName::appIcon},
- {"graphic", hmi_apis::Common_ImageFieldName::graphic},
- {"showConstantTBTIcon", hmi_apis::Common_ImageFieldName::showConstantTBTIcon},
- {"showConstantTBTNextTurnIcon",
- hmi_apis::Common_ImageFieldName::showConstantTBTNextTurnIcon}
-};
-
-const std::map<std::string, hmi_apis::Common_FileType::eType> file_type_enum =
-{
+ image_field_name_enum = {
+ {"softButtonImage", hmi_apis::Common_ImageFieldName::softButtonImage},
+ {"choiceImage", hmi_apis::Common_ImageFieldName::choiceImage},
+ {"choiceSecondaryImage",
+ hmi_apis::Common_ImageFieldName::choiceSecondaryImage},
+ {"vrHelpItem", hmi_apis::Common_ImageFieldName::vrHelpItem},
+ {"turnIcon", hmi_apis::Common_ImageFieldName::turnIcon},
+ {"menuIcon", hmi_apis::Common_ImageFieldName::menuIcon},
+ {"cmdIcon", hmi_apis::Common_ImageFieldName::cmdIcon},
+ {"appIcon", hmi_apis::Common_ImageFieldName::appIcon},
+ {"graphic", hmi_apis::Common_ImageFieldName::graphic},
+ {"showConstantTBTIcon",
+ hmi_apis::Common_ImageFieldName::showConstantTBTIcon},
+ {"showConstantTBTNextTurnIcon",
+ hmi_apis::Common_ImageFieldName::showConstantTBTNextTurnIcon},
+ {"locationImage", hmi_apis::Common_ImageFieldName::locationImage}};
+
+const std::map<std::string, hmi_apis::Common_FileType::eType> file_type_enum = {
{"GRAPHIC_BMP", hmi_apis::Common_FileType::GRAPHIC_BMP},
{"GRAPHIC_JPEG", hmi_apis::Common_FileType::GRAPHIC_JPEG},
{"GRAPHIC_PNG", hmi_apis::Common_FileType::GRAPHIC_PNG},
@@ -180,69 +183,61 @@ const std::map<std::string, hmi_apis::Common_FileType::eType> file_type_enum =
{"AUDIO_MP3", hmi_apis::Common_FileType::AUDIO_MP3},
{"AUDIO_AAC", hmi_apis::Common_FileType::AUDIO_AAC},
{"BINARY", hmi_apis::Common_FileType::BINARY},
- {"JSON", hmi_apis::Common_FileType::JSON}
-};
-
-const std::map<std::string, hmi_apis::Common_DisplayType::eType> display_type_enum =
-{
- {"CID", hmi_apis::Common_DisplayType::CID},
- {"TYPE2", hmi_apis::Common_DisplayType::TYPE2},
- {"TYPE5", hmi_apis::Common_DisplayType::TYPE5},
- {"NGN", hmi_apis::Common_DisplayType::NGN},
- {"GEN2_8_DMA", hmi_apis::Common_DisplayType::GEN2_8_DMA},
- {"GEN2_6_DMA", hmi_apis::Common_DisplayType::GEN2_6_DMA},
- {"MFD3", hmi_apis::Common_DisplayType::MFD3},
- {"MFD4", hmi_apis::Common_DisplayType::MFD4},
- {"MFD5", hmi_apis::Common_DisplayType::MFD5},
- {"GEN3_8_INCH", hmi_apis::Common_DisplayType::GEN3_8_INCH}
-};
-
-const std::map<std::string, hmi_apis::Common_CharacterSet::eType> character_set_enum =
-{
- {"TYPE2SET" , hmi_apis::Common_CharacterSet::TYPE2SET},
- {"TYPE5SET" , hmi_apis::Common_CharacterSet::TYPE5SET},
- {"CID1SET" , hmi_apis::Common_CharacterSet::CID1SET},
- {"CID2SET" , hmi_apis::Common_CharacterSet::CID2SET}
-};
-
-HMICapabilities::HMICapabilities(ApplicationManagerImpl* const app_mngr)
- : is_vr_cooperating_(false),
- is_tts_cooperating_(false),
- is_ui_cooperating_(false),
- is_navi_cooperating_(false),
- is_ivi_cooperating_(false),
- is_vr_ready_response_recieved_(false),
- is_tts_ready_response_recieved_(false),
- is_ui_ready_response_recieved_(false),
- is_navi_ready_response_recieved_(false),
- is_ivi_ready_response_recieved_(false),
- attenuated_supported_(false),
- ui_language_(hmi_apis::Common_Language::INVALID_ENUM),
- vr_language_(hmi_apis::Common_Language::INVALID_ENUM),
- tts_language_(hmi_apis::Common_Language::INVALID_ENUM),
- vehicle_type_(NULL),
- ui_supported_languages_(NULL),
- tts_supported_languages_(NULL),
- vr_supported_languages_(NULL),
- display_capabilities_(NULL),
- hmi_zone_capabilities_(NULL),
- soft_buttons_capabilities_(NULL),
- button_capabilities_(NULL),
- preset_bank_capabilities_(NULL),
- vr_capabilities_(NULL),
- speech_capabilities_(NULL),
- audio_pass_thru_capabilities_(NULL),
- prerecorded_speech_(NULL),
- is_navigation_supported_(false),
- is_phone_call_supported_(false),
- app_mngr_(app_mngr) {
-
- if (false == load_capabilities_from_file()) {
- LOG4CXX_ERROR(logger_, "file hmi_capabilities.json was not loaded");
- } else {
- LOG4CXX_INFO(logger_, "file hmi_capabilities.json was loaded");
- }
- if (false == profile::Profile::instance()->launch_hmi()) {
+ {"JSON", hmi_apis::Common_FileType::JSON}};
+
+const std::map<std::string, hmi_apis::Common_DisplayType::eType>
+ display_type_enum = {
+ {"CID", hmi_apis::Common_DisplayType::CID},
+ {"TYPE2", hmi_apis::Common_DisplayType::TYPE2},
+ {"TYPE5", hmi_apis::Common_DisplayType::TYPE5},
+ {"NGN", hmi_apis::Common_DisplayType::NGN},
+ {"GEN2_8_DMA", hmi_apis::Common_DisplayType::GEN2_8_DMA},
+ {"GEN2_6_DMA", hmi_apis::Common_DisplayType::GEN2_6_DMA},
+ {"MFD3", hmi_apis::Common_DisplayType::MFD3},
+ {"MFD4", hmi_apis::Common_DisplayType::MFD4},
+ {"MFD5", hmi_apis::Common_DisplayType::MFD5},
+ {"GEN3_8_INCH", hmi_apis::Common_DisplayType::GEN3_8_INCH}};
+
+const std::map<std::string, hmi_apis::Common_CharacterSet::eType>
+ character_set_enum = {{"TYPE2SET", hmi_apis::Common_CharacterSet::TYPE2SET},
+ {"TYPE5SET", hmi_apis::Common_CharacterSet::TYPE5SET},
+ {"CID1SET", hmi_apis::Common_CharacterSet::CID1SET},
+ {"CID2SET", hmi_apis::Common_CharacterSet::CID2SET}};
+
+HMICapabilities::HMICapabilities(ApplicationManager& app_mngr)
+ : is_vr_cooperating_(false)
+ , is_tts_cooperating_(false)
+ , is_ui_cooperating_(false)
+ , is_navi_cooperating_(false)
+ , is_ivi_cooperating_(false)
+ , is_vr_ready_response_recieved_(false)
+ , is_tts_ready_response_recieved_(false)
+ , is_ui_ready_response_recieved_(false)
+ , is_navi_ready_response_recieved_(false)
+ , is_ivi_ready_response_recieved_(false)
+ , attenuated_supported_(false)
+ , ui_language_(hmi_apis::Common_Language::INVALID_ENUM)
+ , vr_language_(hmi_apis::Common_Language::INVALID_ENUM)
+ , tts_language_(hmi_apis::Common_Language::INVALID_ENUM)
+ , vehicle_type_(NULL)
+ , ui_supported_languages_(NULL)
+ , tts_supported_languages_(NULL)
+ , vr_supported_languages_(NULL)
+ , display_capabilities_(NULL)
+ , hmi_zone_capabilities_(NULL)
+ , soft_buttons_capabilities_(NULL)
+ , button_capabilities_(NULL)
+ , preset_bank_capabilities_(NULL)
+ , vr_capabilities_(NULL)
+ , speech_capabilities_(NULL)
+ , audio_pass_thru_capabilities_(NULL)
+ , pcm_stream_capabilities_(NULL)
+ , prerecorded_speech_(NULL)
+ , is_navigation_supported_(false)
+ , is_phone_call_supported_(false)
+ , app_mngr_(app_mngr)
+ , hmi_language_handler_(app_mngr_) {
+ if (false == app_mngr_.get_settings().launch_hmi()) {
is_vr_ready_response_recieved_ = true;
is_tts_ready_response_recieved_ = true;
is_ui_ready_response_recieved_ = true;
@@ -270,16 +265,16 @@ HMICapabilities::~HMICapabilities() {
delete vr_capabilities_;
delete speech_capabilities_;
delete audio_pass_thru_capabilities_;
+ delete pcm_stream_capabilities_;
delete prerecorded_speech_;
- app_mngr_ = NULL;
}
bool HMICapabilities::is_hmi_capabilities_initialized() const {
bool result = true;
- if (is_vr_ready_response_recieved_ && is_tts_ready_response_recieved_
- && is_ui_ready_response_recieved_ && is_navi_ready_response_recieved_
- && is_ivi_ready_response_recieved_) {
+ if (is_vr_ready_response_recieved_ && is_tts_ready_response_recieved_ &&
+ is_ui_ready_response_recieved_ && is_navi_ready_response_recieved_ &&
+ is_ivi_ready_response_recieved_) {
if (is_vr_cooperating_) {
if ((!vr_supported_languages_) ||
(hmi_apis::Common_Language::INVALID_ENUM == vr_language_)) {
@@ -295,9 +290,9 @@ bool HMICapabilities::is_hmi_capabilities_initialized() const {
}
if (is_ui_cooperating_) {
- if ((!ui_supported_languages_) ||
+ if ((!ui_supported_languages_) ||
(hmi_apis::Common_Language::INVALID_ENUM == ui_language_)) {
- result = false;
+ result = false;
}
}
@@ -319,8 +314,8 @@ bool HMICapabilities::VerifyImageType(int32_t image_type) const {
}
if (display_capabilities_->keyExists(hmi_response::image_capabilities)) {
- const smart_objects::SmartObject& image_caps = display_capabilities_
- ->getElement(hmi_response::image_capabilities);
+ const smart_objects::SmartObject& image_caps =
+ display_capabilities_->getElement(hmi_response::image_capabilities);
for (uint32_t i = 0; i < image_caps.length(); ++i) {
if (image_caps.getElement(i).asInt() == image_type) {
return true;
@@ -336,14 +331,18 @@ void HMICapabilities::set_is_vr_cooperating(bool value) {
is_vr_cooperating_ = value;
if (is_vr_cooperating_) {
utils::SharedPtr<smart_objects::SmartObject> get_language(
- MessageHelper::CreateModuleInfoSO(hmi_apis::FunctionID::VR_GetLanguage));
- app_mngr_->ManageHMICommand(get_language);
+ MessageHelper::CreateModuleInfoSO(hmi_apis::FunctionID::VR_GetLanguage,
+ app_mngr_));
+ hmi_language_handler_.set_handle_response_for(*get_language);
+ app_mngr_.ManageHMICommand(get_language);
utils::SharedPtr<smart_objects::SmartObject> get_all_languages(
- MessageHelper::CreateModuleInfoSO(hmi_apis::FunctionID::VR_GetSupportedLanguages));
- app_mngr_->ManageHMICommand(get_all_languages);
+ MessageHelper::CreateModuleInfoSO(
+ hmi_apis::FunctionID::VR_GetSupportedLanguages, app_mngr_));
+ app_mngr_.ManageHMICommand(get_all_languages);
utils::SharedPtr<smart_objects::SmartObject> get_capabilities(
- MessageHelper::CreateModuleInfoSO(hmi_apis::FunctionID::VR_GetCapabilities));
- app_mngr_->ManageHMICommand(get_capabilities);
+ MessageHelper::CreateModuleInfoSO(
+ hmi_apis::FunctionID::VR_GetCapabilities, app_mngr_));
+ app_mngr_.ManageHMICommand(get_capabilities);
}
}
@@ -352,17 +351,18 @@ void HMICapabilities::set_is_tts_cooperating(bool value) {
is_tts_cooperating_ = value;
if (is_tts_cooperating_) {
utils::SharedPtr<smart_objects::SmartObject> get_language(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::TTS_GetLanguage));
- app_mngr_->ManageHMICommand(get_language);
+ MessageHelper::CreateModuleInfoSO(hmi_apis::FunctionID::TTS_GetLanguage,
+ app_mngr_));
+ hmi_language_handler_.set_handle_response_for(*get_language);
+ app_mngr_.ManageHMICommand(get_language);
utils::SharedPtr<smart_objects::SmartObject> get_all_languages(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::TTS_GetSupportedLanguages));
- app_mngr_->ManageHMICommand(get_all_languages);
+ MessageHelper::CreateModuleInfoSO(
+ hmi_apis::FunctionID::TTS_GetSupportedLanguages, app_mngr_));
+ app_mngr_.ManageHMICommand(get_all_languages);
utils::SharedPtr<smart_objects::SmartObject> get_capabilities(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::TTS_GetCapabilities));
- app_mngr_->ManageHMICommand(get_capabilities);
+ MessageHelper::CreateModuleInfoSO(
+ hmi_apis::FunctionID::TTS_GetCapabilities, app_mngr_));
+ app_mngr_.ManageHMICommand(get_capabilities);
}
}
@@ -371,17 +371,18 @@ void HMICapabilities::set_is_ui_cooperating(bool value) {
is_ui_cooperating_ = value;
if (is_ui_cooperating_) {
utils::SharedPtr<smart_objects::SmartObject> get_language(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::UI_GetLanguage));
- app_mngr_->ManageHMICommand(get_language);
+ MessageHelper::CreateModuleInfoSO(hmi_apis::FunctionID::UI_GetLanguage,
+ app_mngr_));
+ hmi_language_handler_.set_handle_response_for(*get_language);
+ app_mngr_.ManageHMICommand(get_language);
utils::SharedPtr<smart_objects::SmartObject> get_all_languages(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::UI_GetSupportedLanguages));
- app_mngr_->ManageHMICommand(get_all_languages);
+ MessageHelper::CreateModuleInfoSO(
+ hmi_apis::FunctionID::UI_GetSupportedLanguages, app_mngr_));
+ app_mngr_.ManageHMICommand(get_all_languages);
utils::SharedPtr<smart_objects::SmartObject> get_capabilities(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::UI_GetCapabilities));
- app_mngr_->ManageHMICommand(get_capabilities);
+ MessageHelper::CreateModuleInfoSO(
+ hmi_apis::FunctionID::UI_GetCapabilities, app_mngr_));
+ app_mngr_.ManageHMICommand(get_capabilities);
}
}
@@ -395,9 +396,9 @@ void HMICapabilities::set_is_ivi_cooperating(bool value) {
is_ivi_cooperating_ = value;
if (is_ivi_cooperating_) {
utils::SharedPtr<smart_objects::SmartObject> get_type(
- MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::VehicleInfo_GetVehicleType));
- app_mngr_->ManageHMICommand(get_type);
+ MessageHelper::CreateModuleInfoSO(
+ hmi_apis::FunctionID::VehicleInfo_GetVehicleType, app_mngr_));
+ app_mngr_.ManageHMICommand(get_type);
}
}
@@ -406,18 +407,48 @@ void HMICapabilities::set_attenuated_supported(bool state) {
}
void HMICapabilities::set_active_ui_language(
- const hmi_apis::Common_Language::eType& language) {
+ const hmi_apis::Common_Language::eType& language) {
ui_language_ = language;
+ hmi_language_handler_.set_language_for(HMILanguageHandler::INTERFACE_UI,
+ language);
}
void HMICapabilities::set_active_vr_language(
- const hmi_apis::Common_Language::eType& language) {
+ const hmi_apis::Common_Language::eType& language) {
vr_language_ = language;
+ hmi_language_handler_.set_language_for(HMILanguageHandler::INTERFACE_VR,
+ language);
}
void HMICapabilities::set_active_tts_language(
- const hmi_apis::Common_Language::eType& language) {
+ const hmi_apis::Common_Language::eType& language) {
tts_language_ = language;
+ hmi_language_handler_.set_language_for(HMILanguageHandler::INTERFACE_TTS,
+ language);
+}
+
+const hmi_apis::Common_Language::eType HMICapabilities::active_ui_language()
+ const {
+ using namespace hmi_apis;
+ const Common_Language::eType language =
+ hmi_language_handler_.get_language_for(HMILanguageHandler::INTERFACE_UI);
+ return Common_Language::INVALID_ENUM != language ? language : ui_language_;
+}
+
+const hmi_apis::Common_Language::eType HMICapabilities::active_vr_language()
+ const {
+ using namespace hmi_apis;
+ const Common_Language::eType language =
+ hmi_language_handler_.get_language_for(HMILanguageHandler::INTERFACE_VR);
+ return Common_Language::INVALID_ENUM != language ? language : vr_language_;
+}
+
+const hmi_apis::Common_Language::eType HMICapabilities::active_tts_language()
+ const {
+ using namespace hmi_apis;
+ const Common_Language::eType language =
+ hmi_language_handler_.get_language_for(HMILanguageHandler::INTERFACE_TTS);
+ return Common_Language::INVALID_ENUM != language ? language : tts_language_;
}
void HMICapabilities::set_ui_supported_languages(
@@ -433,8 +464,8 @@ void HMICapabilities::set_tts_supported_languages(
if (tts_supported_languages_) {
delete tts_supported_languages_;
}
- tts_supported_languages_ = new smart_objects::SmartObject(
- supported_languages);
+ tts_supported_languages_ =
+ new smart_objects::SmartObject(supported_languages);
}
void HMICapabilities::set_vr_supported_languages(
@@ -458,8 +489,8 @@ void HMICapabilities::set_hmi_zone_capabilities(
if (hmi_zone_capabilities_) {
delete hmi_zone_capabilities_;
}
- hmi_zone_capabilities_ = new smart_objects::SmartObject(
- hmi_zone_capabilities);
+ hmi_zone_capabilities_ =
+ new smart_objects::SmartObject(hmi_zone_capabilities);
}
void HMICapabilities::set_soft_button_capabilities(
@@ -467,8 +498,8 @@ void HMICapabilities::set_soft_button_capabilities(
if (soft_buttons_capabilities_) {
delete soft_buttons_capabilities_;
}
- soft_buttons_capabilities_ = new smart_objects::SmartObject(
- soft_button_capabilities);
+ soft_buttons_capabilities_ =
+ new smart_objects::SmartObject(soft_button_capabilities);
}
void HMICapabilities::set_button_capabilities(
@@ -500,8 +531,17 @@ void HMICapabilities::set_audio_pass_thru_capabilities(
if (audio_pass_thru_capabilities_) {
delete audio_pass_thru_capabilities_;
}
- audio_pass_thru_capabilities_ = new smart_objects::SmartObject(
- audio_pass_thru_capabilities);
+ audio_pass_thru_capabilities_ =
+ new smart_objects::SmartObject(audio_pass_thru_capabilities);
+}
+
+void HMICapabilities::set_pcm_stream_capabilities(
+ const smart_objects::SmartObject& pcm_stream_capabilities) {
+ if (pcm_stream_capabilities_) {
+ delete pcm_stream_capabilities_;
+ }
+ pcm_stream_capabilities_ =
+ new smart_objects::SmartObject(pcm_stream_capabilities);
}
void HMICapabilities::set_preset_bank_capabilities(
@@ -509,12 +549,12 @@ void HMICapabilities::set_preset_bank_capabilities(
if (preset_bank_capabilities_) {
delete preset_bank_capabilities_;
}
- preset_bank_capabilities_ = new smart_objects::SmartObject(
- preset_bank_capabilities);
+ preset_bank_capabilities_ =
+ new smart_objects::SmartObject(preset_bank_capabilities);
}
void HMICapabilities::set_vehicle_type(
- const smart_objects::SmartObject& vehicle_type) {
+ const smart_objects::SmartObject& vehicle_type) {
if (vehicle_type_) {
delete vehicle_type_;
}
@@ -522,7 +562,7 @@ void HMICapabilities::set_vehicle_type(
}
void HMICapabilities::set_prerecorded_speech(
- const smart_objects::SmartObject& prerecorded_speech) {
+ const smart_objects::SmartObject& prerecorded_speech) {
if (prerecorded_speech_) {
delete prerecorded_speech_;
prerecorded_speech_ = NULL;
@@ -530,22 +570,32 @@ void HMICapabilities::set_prerecorded_speech(
prerecorded_speech_ = new smart_objects::SmartObject(prerecorded_speech);
}
-void HMICapabilities::set_navigation_supported(bool supported) {
+void HMICapabilities::set_ccpu_version(const std::string& ccpu_version) {
+ ccpu_version_ = ccpu_version;
+}
+
+void HMICapabilities::set_navigation_supported(const bool supported) {
is_navigation_supported_ = supported;
}
-void HMICapabilities::set_phone_call_supported(bool supported) {
+void HMICapabilities::set_phone_call_supported(const bool supported) {
is_phone_call_supported_ = supported;
}
-void HMICapabilities::set_ccpu_version(const std::string& ccpu_version) {
- ccpu_version_ = ccpu_version;
+void HMICapabilities::Init(resumption::LastState* last_state) {
+ hmi_language_handler_.Init(last_state);
+ if (false == load_capabilities_from_file()) {
+ LOG4CXX_ERROR(logger_, "file hmi_capabilities.json was not loaded");
+ } else {
+ LOG4CXX_INFO(logger_, "file hmi_capabilities.json was loaded");
+ }
+ hmi_language_handler_.set_default_capabilities_languages(
+ ui_language_, vr_language_, tts_language_);
}
bool HMICapabilities::load_capabilities_from_file() {
std::string json_string;
- std::string file_name =
- profile::Profile::instance()->hmi_capabilities_file_name();
+ std::string file_name = app_mngr_.get_settings().hmi_capabilities_file_name();
if (!file_system::FileExists(file_name)) {
return false;
@@ -556,9 +606,8 @@ bool HMICapabilities::load_capabilities_from_file() {
}
try {
-
Json::Reader reader_;
- Json::Value root_json;
+ Json::Value root_json;
bool result = reader_.parse(json_string, root_json, false);
if (!result) {
@@ -569,7 +618,7 @@ bool HMICapabilities::load_capabilities_from_file() {
Json::Value ui = root_json.get("UI", Json::Value::null);
if (check_existing_json_member(ui, "language")) {
- const std::string lang = ui.get("language", "EN_US").asString();
+ const std::string lang = ui.get("language", "EN-US").asString();
set_active_ui_language(MessageHelper::CommonLanguageFromString(lang));
}
@@ -584,13 +633,15 @@ bool HMICapabilities::load_capabilities_from_file() {
if (check_existing_json_member(ui, "displayCapabilities")) {
smart_objects::SmartObject display_capabilities_so;
Json::Value display_capabilities = ui.get("displayCapabilities", "");
- Formatters::CFormatterJsonBase::jsonValueToObj(
- display_capabilities, display_capabilities_so);
+ Formatters::CFormatterJsonBase::jsonValueToObj(display_capabilities,
+ display_capabilities_so);
if (display_capabilities_so.keyExists(hmi_response::display_type)) {
- std::map<std::string, hmi_apis::Common_DisplayType::eType>
- ::const_iterator it = display_type_enum.find(
- (display_capabilities_so[hmi_response::display_type]).asString());
+ std::map<std::string,
+ hmi_apis::Common_DisplayType::eType>::const_iterator it =
+ display_type_enum.find(
+ (display_capabilities_so[hmi_response::display_type])
+ .asString());
display_capabilities_so.erase(hmi_response::display_type);
if (display_type_enum.end() != it) {
display_capabilities_so[hmi_response::display_type] = it->second;
@@ -602,31 +653,35 @@ bool HMICapabilities::load_capabilities_from_file() {
display_capabilities_so[hmi_response::text_fields].length();
for (uint32_t i = 0; i < len; ++i) {
-
- if ((display_capabilities_so
- [hmi_response::text_fields][i]).keyExists(strings::name)) {
- std::map<std::string, hmi_apis::Common_TextFieldName::eType>
- ::const_iterator it_text_field_name = text_fields_enum_name.find(
- display_capabilities_so[hmi_response::text_fields]
- [i][strings::name].asString());
- display_capabilities_so[hmi_response::text_fields][i].erase(strings::name);
+ if ((display_capabilities_so[hmi_response::text_fields][i])
+ .keyExists(strings::name)) {
+ std::map<std::string,
+ hmi_apis::Common_TextFieldName::eType>::const_iterator
+ it_text_field_name = text_fields_enum_name.find(
+ display_capabilities_so[hmi_response::text_fields][i]
+ [strings::name].asString());
+ display_capabilities_so[hmi_response::text_fields][i].erase(
+ strings::name);
if (text_fields_enum_name.end() != it_text_field_name) {
- display_capabilities_so[hmi_response::text_fields]
- [i][strings::name] = it_text_field_name->second;
+ display_capabilities_so[hmi_response::text_fields][i]
+ [strings::name] =
+ it_text_field_name->second;
}
}
- if ((display_capabilities_so
- [hmi_response::text_fields][i]).keyExists(strings::character_set)) {
- std::map<std::string, hmi_apis::Common_CharacterSet::eType>
- ::const_iterator it_characte_set = character_set_enum.find(
- display_capabilities_so[hmi_response::text_fields]
- [i][strings::character_set].asString());
- display_capabilities_so
- [hmi_response::text_fields][i].erase(strings::character_set);
+ if ((display_capabilities_so[hmi_response::text_fields][i])
+ .keyExists(strings::character_set)) {
+ std::map<std::string,
+ hmi_apis::Common_CharacterSet::eType>::const_iterator
+ it_characte_set = character_set_enum.find(
+ display_capabilities_so[hmi_response::text_fields][i]
+ [strings::character_set]
+ .asString());
+ display_capabilities_so[hmi_response::text_fields][i].erase(
+ strings::character_set);
if (character_set_enum.end() != it_characte_set) {
- display_capabilities_so
- [hmi_response::text_fields][i][strings::character_set] =
- it_characte_set->second;
+ display_capabilities_so[hmi_response::text_fields][i]
+ [strings::character_set] =
+ it_characte_set->second;
}
}
}
@@ -637,23 +692,28 @@ bool HMICapabilities::load_capabilities_from_file() {
display_capabilities_so[hmi_response::image_fields];
for (uint32_t i = 0; i < array_image_fields.length(); ++i) {
if (array_image_fields[i].keyExists(strings::name)) {
- std::map<std::string, hmi_apis::Common_ImageFieldName::eType>
- ::const_iterator it = image_field_name_enum.find(
- (array_image_fields[i][strings::name]).asString());
+ std::map<std::string,
+ hmi_apis::Common_ImageFieldName::eType>::const_iterator
+ it = image_field_name_enum.find(
+ (array_image_fields[i][strings::name]).asString());
array_image_fields[i].erase(strings::name);
if (image_field_name_enum.end() != it) {
array_image_fields[i][strings::name] = it->second;
}
}
- if (array_image_fields[i].keyExists(strings::image_type_supported)) {
+ if (array_image_fields[i].keyExists(
+ strings::image_type_supported)) {
smart_objects::SmartObject& image_type_supported_array =
array_image_fields[i][strings::image_type_supported];
smart_objects::SmartObject image_type_supported_enum(
smart_objects::SmartType_Array);
- for (uint32_t k = 0, j = 0; k < image_type_supported_array.length(); ++k) {
- std::map<std::string, hmi_apis::Common_FileType::eType>
- ::const_iterator it = file_type_enum.find(
- (image_type_supported_array[k]).asString());
+ for (uint32_t k = 0, j = 0;
+ k < image_type_supported_array.length();
+ ++k) {
+ std::map<std::string,
+ hmi_apis::Common_FileType::eType>::const_iterator it =
+ file_type_enum.find(
+ (image_type_supported_array[k]).asString());
if (file_type_enum.end() != it) {
image_type_supported_enum[j++] = it->second;
}
@@ -664,15 +724,18 @@ bool HMICapabilities::load_capabilities_from_file() {
}
}
}
- if (display_capabilities_so.keyExists(hmi_response::media_clock_formats)) {
+ if (display_capabilities_so.keyExists(
+ hmi_response::media_clock_formats)) {
smart_objects::SmartObject& media_clock_formats_array =
display_capabilities_so[hmi_response::media_clock_formats];
smart_objects::SmartObject media_clock_formats_enum(
smart_objects::SmartType_Array);
- for (uint32_t i = 0, j = 0; i < media_clock_formats_array.length(); ++i) {
- std::map<std::string, hmi_apis::Common_MediaClockFormat::eType>
- ::const_iterator it = media_clock_enum_name.find(
- (media_clock_formats_array[i]).asString());
+ for (uint32_t i = 0, j = 0; i < media_clock_formats_array.length();
+ ++i) {
+ std::map<std::string,
+ hmi_apis::Common_MediaClockFormat::eType>::const_iterator
+ it = media_clock_enum_name.find(
+ (media_clock_formats_array[i]).asString());
if (media_clock_enum_name.end() != it) {
media_clock_formats_enum[j++] = it->second;
}
@@ -682,15 +745,17 @@ bool HMICapabilities::load_capabilities_from_file() {
media_clock_formats_enum;
}
- if (display_capabilities_so.keyExists(hmi_response::image_capabilities)) {
+ if (display_capabilities_so.keyExists(
+ hmi_response::image_capabilities)) {
smart_objects::SmartObject& image_capabilities_array =
display_capabilities_so[hmi_response::image_capabilities];
smart_objects::SmartObject image_capabilities_enum(
smart_objects::SmartType_Array);
- for (uint32_t i = 0, j = 0; i < image_capabilities_array.length(); ++i) {
- std::map<std::string, hmi_apis::Common_ImageType::eType>
- ::const_iterator it = image_type_enum.find(
- (image_capabilities_array[i]).asString());
+ for (uint32_t i = 0, j = 0; i < image_capabilities_array.length();
+ ++i) {
+ std::map<std::string,
+ hmi_apis::Common_ImageType::eType>::const_iterator it =
+ image_type_enum.find((image_capabilities_array[i]).asString());
if (image_type_enum.end() != it) {
image_capabilities_enum[j++] = it->second;
}
@@ -703,54 +768,79 @@ bool HMICapabilities::load_capabilities_from_file() {
}
if (check_existing_json_member(ui, "audioPassThruCapabilities")) {
- Json::Value audio_capabilities = ui.get("audioPassThruCapabilities", "");
+ Json::Value audio_capabilities =
+ ui.get("audioPassThruCapabilities", "");
smart_objects::SmartObject audio_capabilities_so =
smart_objects::SmartObject(smart_objects::SmartType_Array);
- int32_t i = 0;
- audio_capabilities_so[i] =
+ audio_capabilities_so =
smart_objects::SmartObject(smart_objects::SmartType_Map);
if (check_existing_json_member(audio_capabilities, "samplingRate")) {
- audio_capabilities_so[i]["samplingRate"] =
- sampling_rate_enum.find(
- audio_capabilities.get("samplingRate", "").asString())->second;
+ audio_capabilities_so["samplingRate"] =
+ sampling_rate_enum.find(audio_capabilities.get("samplingRate", "")
+ .asString())->second;
}
if (check_existing_json_member(audio_capabilities, "bitsPerSample")) {
- audio_capabilities_so[i]["bitsPerSample"] =
- bit_per_sample_enum.find(
- audio_capabilities.get("bitsPerSample", "").asString())->second;
+ audio_capabilities_so["bitsPerSample"] =
+ bit_per_sample_enum.find(audio_capabilities.get("bitsPerSample",
+ "").asString())
+ ->second;
}
if (check_existing_json_member(audio_capabilities, "audioType")) {
- audio_capabilities_so[i]["audioType"] =
- audio_type_enum.find(
- audio_capabilities.get("audioType", "").asString())->second;
+ audio_capabilities_so["audioType"] =
+ audio_type_enum.find(audio_capabilities.get("audioType", "")
+ .asString())->second;
}
set_audio_pass_thru_capabilities(audio_capabilities_so);
}
+ if (check_existing_json_member(ui, "pcmStreamCapabilities")) {
+ Json::Value pcm_capabilities = ui.get("pcmStreamCapabilities", "");
+ smart_objects::SmartObject pcm_capabilities_so =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+
+ if (check_existing_json_member(pcm_capabilities, "samplingRate")) {
+ pcm_capabilities_so["samplingRate"] =
+ sampling_rate_enum.find(pcm_capabilities.get("samplingRate", "")
+ .asString())->second;
+ }
+ if (check_existing_json_member(pcm_capabilities, "bitsPerSample")) {
+ pcm_capabilities_so["bitsPerSample"] =
+ bit_per_sample_enum.find(pcm_capabilities.get("bitsPerSample", "")
+ .asString())->second;
+ }
+ if (check_existing_json_member(pcm_capabilities, "audioType")) {
+ pcm_capabilities_so["audioType"] =
+ audio_type_enum.find(pcm_capabilities.get("audioType", "")
+ .asString())->second;
+ }
+
+ set_pcm_stream_capabilities(pcm_capabilities_so);
+ }
+
if (check_existing_json_member(ui, "hmiZoneCapabilities")) {
smart_objects::SmartObject hmi_zone_capabilities_so =
smart_objects::SmartObject(smart_objects::SmartType_Array);
- int32_t index = 0;
- hmi_zone_capabilities_so[index] =
- hmi_zone_enum.find(ui.get("hmiZoneCapabilities", "").asString())->second;
+ hmi_zone_capabilities_so =
+ hmi_zone_enum.find(ui.get("hmiZoneCapabilities", "").asString())
+ ->second;
set_hmi_zone_capabilities(hmi_zone_capabilities_so);
}
if (check_existing_json_member(ui, "softButtonCapabilities")) {
- Json::Value soft_button_capabilities = ui.get(
- "softButtonCapabilities", "");
+ Json::Value soft_button_capabilities =
+ ui.get("softButtonCapabilities", "");
smart_objects::SmartObject soft_button_capabilities_so;
Formatters::CFormatterJsonBase::jsonValueToObj(
soft_button_capabilities, soft_button_capabilities_so);
set_soft_button_capabilities(soft_button_capabilities_so);
}
- } //UI end
+ } // UI end
// VR
if (check_existing_json_member(root_json, "VR")) {
Json::Value vr = root_json.get("VR", "");
if (check_existing_json_member(vr, "language")) {
- const std::string lang = vr.get("language", "").asString();
+ const std::string lang = vr.get("language", "EN-US").asString();
set_active_vr_language(MessageHelper::CommonLanguageFromString(lang));
}
@@ -772,14 +862,14 @@ bool HMICapabilities::load_capabilities_from_file() {
}
set_vr_capabilities(vr_capabilities_so);
}
- }//VR end
+ } // VR end
- //TTS
+ // TTS
if (check_existing_json_member(root_json, "TTS")) {
Json::Value tts = root_json.get("TTS", "");
if (check_existing_json_member(tts, "language")) {
- const std::string lang = tts.get("language", "").asString();
+ const std::string lang = tts.get("language", "EN-US").asString();
set_active_tts_language(MessageHelper::CommonLanguageFromString(lang));
}
@@ -795,7 +885,7 @@ bool HMICapabilities::load_capabilities_from_file() {
set_speech_capabilities(
smart_objects::SmartObject(tts.get("capabilities", "").asString()));
}
- } //TTS end
+ } // TTS end
// Buttons
if (check_existing_json_member(root_json, "Buttons")) {
@@ -803,14 +893,15 @@ bool HMICapabilities::load_capabilities_from_file() {
if (check_existing_json_member(buttons, "capabilities")) {
Json::Value bt_capabilities = buttons.get("capabilities", "");
smart_objects::SmartObject buttons_capabilities_so;
- Formatters::CFormatterJsonBase::jsonValueToObj(
- bt_capabilities, buttons_capabilities_so);
+ Formatters::CFormatterJsonBase::jsonValueToObj(bt_capabilities,
+ buttons_capabilities_so);
for (uint32_t i = 0; i < buttons_capabilities_so.length(); ++i) {
if ((buttons_capabilities_so[i]).keyExists(strings::name)) {
- std::map<std::string, hmi_apis::Common_ButtonName::eType>
- ::const_iterator it = button_enum_name.find(
- (buttons_capabilities_so[i][strings::name]).asString());
+ std::map<std::string,
+ hmi_apis::Common_ButtonName::eType>::const_iterator it =
+ button_enum_name.find(
+ (buttons_capabilities_so[i][strings::name]).asString());
buttons_capabilities_so[i].erase(strings::name);
if (button_enum_name.end() != it) {
buttons_capabilities_so[i][strings::name] = it->second;
@@ -822,21 +913,20 @@ bool HMICapabilities::load_capabilities_from_file() {
if (check_existing_json_member(buttons, "presetBankCapabilities")) {
Json::Value presetBank = buttons.get("presetBankCapabilities", "");
smart_objects::SmartObject preset_bank_so;
- Formatters::CFormatterJsonBase::jsonValueToObj(
- presetBank, preset_bank_so);
+ Formatters::CFormatterJsonBase::jsonValueToObj(presetBank,
+ preset_bank_so);
set_preset_bank_capabilities(preset_bank_so);
}
- } //Buttons end
+ } // Buttons end
- //VehicleType
+ // VehicleType
if (check_existing_json_member(root_json, "VehicleInfo")) {
Json::Value vehicle_info = root_json.get("VehicleInfo", "");
smart_objects::SmartObject vehicle_type_so;
- Formatters::CFormatterJsonBase::jsonValueToObj(
- vehicle_info, vehicle_type_so);
+ Formatters::CFormatterJsonBase::jsonValueToObj(vehicle_info,
+ vehicle_type_so);
set_vehicle_type(vehicle_type_so);
- }// VehicleType end
-
+ } // VehicleType end
} catch (...) {
return false;
@@ -844,16 +934,16 @@ bool HMICapabilities::load_capabilities_from_file() {
return true;
}
-bool HMICapabilities::check_existing_json_member(
- const Json::Value& json_member, const char* name_of_member) {
+bool HMICapabilities::check_existing_json_member(const Json::Value& json_member,
+ const char* name_of_member) {
return json_member.isMember(name_of_member);
}
-void HMICapabilities::convert_json_languages_to_obj(Json::Value& json_languages,
- smart_objects::SmartObject& languages) {
+void HMICapabilities::convert_json_languages_to_obj(
+ Json::Value& json_languages, smart_objects::SmartObject& languages) {
for (uint32_t i = 0, j = 0; i < json_languages.size(); ++i) {
- languages[j++] = MessageHelper::CommonLanguageFromString(
- json_languages[i].asString());
+ languages[j++] =
+ MessageHelper::CommonLanguageFromString(json_languages[i].asString());
}
}
diff --git a/src/components/application_manager/src/hmi_command_factory.cc b/src/components/application_manager/src/hmi_command_factory.cc
index 2fc3499c09..67625fde88 100644
--- a/src/components/application_manager/src/hmi_command_factory.cc
+++ b/src/components/application_manager/src/hmi_command_factory.cc
@@ -72,7 +72,6 @@
#include "application_manager/commands/hmi/on_resume_audio_source_notification.h"
#include "application_manager/commands/hmi/on_ignition_cycle_over_notification.h"
#include "application_manager/commands/hmi/on_system_info_changed_notification.h"
-#include "application_manager/commands/hmi/on_emergency_event_notification.h"
#include "application_manager/commands/hmi/get_system_info_request.h"
#include "application_manager/commands/hmi/get_system_info_response.h"
#include "application_manager/commands/hmi/close_popup_request.h"
@@ -156,6 +155,7 @@
#include "application_manager/commands/hmi/sdl_activate_app_request.h"
#include "application_manager/commands/hmi/sdl_activate_app_response.h"
#include "application_manager/commands/hmi/on_app_permission_changed_notification.h"
+#include "application_manager/commands/hmi/on_event_changed_notification.h"
#ifdef HMI_DBUS_API
#include "application_manager/commands/hmi/vi_get_vehicle_data_request_template.h"
@@ -193,7 +193,7 @@
#include "application_manager/commands/hmi/vi_subscribe_vehicle_data_response.h"
#include "application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request.h"
#include "application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response.h"
-#endif // #ifdef HMI_DBUS_API
+#endif // #ifdef HMI_DBUS_API
#include "application_manager/commands/hmi/vi_get_dtcs_request.h"
#include "application_manager/commands/hmi/vi_get_dtcs_response.h"
@@ -209,6 +209,12 @@
#include "application_manager/commands/hmi/navi_alert_maneuver_response.h"
#include "application_manager/commands/hmi/navi_update_turn_list_request.h"
#include "application_manager/commands/hmi/navi_update_turn_list_response.h"
+#include "application_manager/commands/hmi/navi_subscribe_way_points_request.h"
+#include "application_manager/commands/hmi/navi_subscribe_way_points_response.h"
+#include "application_manager/commands/hmi/navi_unsubscribe_way_points_request.h"
+#include "application_manager/commands/hmi/navi_unsubscribe_way_points_response.h"
+#include "application_manager/commands/hmi/navi_get_way_points_request.h"
+#include "application_manager/commands/hmi/navi_get_way_points_response.h"
#include "application_manager/commands/hmi/on_ready_notification.h"
#include "application_manager/commands/hmi/on_device_chosen_notification.h"
#include "application_manager/commands/hmi/on_file_removed_notification.h"
@@ -216,7 +222,6 @@
#include "application_manager/commands/hmi/on_app_registered_notification.h"
#include "application_manager/commands/hmi/on_app_unregistered_notification.h"
#include "application_manager/commands/hmi/on_driver_distraction_notification.h"
-#include "application_manager/commands/hmi/on_play_tone_notification.h"
#include "application_manager/commands/hmi/on_tts_started_notification.h"
#include "application_manager/commands/hmi/on_tts_stopped_notification.h"
#include "application_manager/commands/hmi/on_vr_started_notification.h"
@@ -228,6 +233,7 @@
#include "application_manager/commands/hmi/on_vr_language_change_notification.h"
#include "application_manager/commands/hmi/on_tts_language_change_notification.h"
#include "application_manager/commands/hmi/on_navi_tbt_client_state_notification.h"
+#include "application_manager/commands/hmi/on_navi_way_point_change_notification.h"
#include "application_manager/commands/hmi/on_button_event_notification.h"
#include "application_manager/commands/hmi/on_button_press_notification.h"
#include "application_manager/commands/hmi/on_button_subscription_notification.h"
@@ -263,1815 +269,1973 @@
#include "application_manager/commands/hmi/navi_send_location_request.h"
#include "application_manager/commands/hmi/navi_send_location_response.h"
#include "application_manager/commands/hmi/on_tts_reset_timeout_notification.h"
-#include "application_manager/commands/hmi/on_phone_call_notification.h"
#include "application_manager/commands/hmi/dial_number_request.h"
#include "application_manager/commands/hmi/dial_number_response.h"
-namespace application_manager {
-
CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationManager")
+namespace application_manager {
CommandSharedPtr HMICommandFactory::CreateCommand(
- const commands::MessageSharedPtr& message) {
- const int function_id = (*message)[strings::params][strings::function_id]
- .asInt();
- LOG4CXX_INFO(logger_,
- "HMICommandFactory::CreateCommand function_id: " << function_id);
+ const commands::MessageSharedPtr& message,
+ ApplicationManager& application_manager) {
+ const int function_id =
+ (*message)[strings::params][strings::function_id].asInt();
+ LOG4CXX_DEBUG(
+ logger_, "HMICommandFactory::CreateCommand function_id: " << function_id);
- CommandSharedPtr command(
- new application_manager::commands::CommandImpl(message));
+ CommandSharedPtr command(new application_manager::commands::CommandImpl(
+ message, application_manager));
bool is_response = false;
- const int msg_type = (*message)[strings::params][strings::message_type].asInt();
- if (msg_type == static_cast<int>(application_manager::MessageType::kResponse)) {
+ const int msg_type =
+ (*message)[strings::params][strings::message_type].asInt();
+ if (msg_type ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
is_response = true;
- LOG4CXX_INFO(logger_, "HMICommandFactory::CreateCommand response");
- } else if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kErrorResponse)) {
+ LOG4CXX_DEBUG(logger_, "HMICommandFactory::CreateCommand response");
+ } else if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(
+ application_manager::MessageType::kErrorResponse)) {
is_response = true;
- LOG4CXX_INFO(logger_, "HMICommandFactory::CreateCommand error response");
+ LOG4CXX_DEBUG(logger_, "HMICommandFactory::CreateCommand error response");
} else {
- LOG4CXX_INFO(logger_, "HMICommandFactory::CreateCommand request");
+ LOG4CXX_DEBUG(logger_, "HMICommandFactory::CreateCommand request");
}
switch (function_id) {
case hmi_apis::FunctionID::BasicCommunication_OnStartDeviceDiscovery: {
- command.reset(new commands::OnStartDeviceDiscovery(message));
+ command.reset(
+ new commands::OnStartDeviceDiscovery(message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_UpdateDeviceList: {
if (is_response) {
- command.reset(new commands::UpdateDeviceListResponse(message));
+ command.reset(new commands::UpdateDeviceListResponse(
+ message, application_manager));
} else {
- command.reset(new commands::UpdateDeviceListRequest(message));
+ command.reset(new commands::UpdateDeviceListRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::BasicCommunication_ActivateApp: {
if (is_response) {
- command.reset(new commands::ActivateAppResponse(message));
+ command.reset(
+ new commands::ActivateAppResponse(message, application_manager));
} else {
- command.reset(new commands::ActivateAppRequest(message));
+ command.reset(
+ new commands::ActivateAppRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::BasicCommunication_GetSystemInfo: {
if (is_response) {
- command.reset(new commands::GetSystemInfoResponse(message));
+ command.reset(
+ new commands::GetSystemInfoResponse(message, application_manager));
} else {
- command.reset(new commands::GetSystemInfoRequest(message));
+ command.reset(
+ new commands::GetSystemInfoRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::SDL_ActivateApp: {
if (is_response) {
- command.reset(new commands::SDLActivateAppResponse(message));
+ command.reset(
+ new commands::SDLActivateAppResponse(message, application_manager));
} else {
- command.reset(new commands::SDLActivateAppRequest(message));
+ command.reset(
+ new commands::SDLActivateAppRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::BasicCommunication_PolicyUpdate: {
if (is_response) {
- command.reset(new commands::SDLPolicyUpdateResponse(message));
+ command.reset(new commands::SDLPolicyUpdateResponse(
+ message, application_manager));
} else {
- command.reset(new commands::SDLPolicyUpdate(message));
+ command.reset(
+ new commands::SDLPolicyUpdate(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::SDL_GetURLS: {
if (is_response) {
- command.reset(new commands::GetUrlsResponse(message));
+ command.reset(
+ new commands::GetUrlsResponse(message, application_manager));
} else {
- command.reset(new commands::GetUrls(message));
+ command.reset(new commands::GetUrls(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::SDL_OnAppPermissionChanged: {
- command.reset(new commands::OnAppPermissionChangedNotification(message));
+ command.reset(new commands::OnAppPermissionChangedNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::SDL_GetListOfPermissions: {
if (is_response) {
- command.reset(new commands::SDLGetListOfPermissionsResponse(message));
+ command.reset(new commands::SDLGetListOfPermissionsResponse(
+ message, application_manager));
} else {
- command.reset(new commands::SDLGetListOfPermissionsRequest(message));
+ command.reset(new commands::SDLGetListOfPermissionsRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::SDL_GetUserFriendlyMessage: {
if (is_response) {
- command.reset(new commands::SDLGetUserFriendlyMessageResponse(message));
+ command.reset(new commands::SDLGetUserFriendlyMessageResponse(
+ message, application_manager));
} else {
- command.reset(new commands::SDLGetUserFriendlyMessageRequest(message));
+ command.reset(new commands::SDLGetUserFriendlyMessageRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::SDL_GetStatusUpdate: {
if (is_response) {
- command.reset(new commands::SDLGetStatusUpdateResponse(message));
+ command.reset(new commands::SDLGetStatusUpdateResponse(
+ message, application_manager));
} else {
- command.reset(new commands::SDLGetStatusUpdateRequest(message));
+ command.reset(new commands::SDLGetStatusUpdateRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::SDL_OnStatusUpdate: {
- command.reset(new commands::OnStatusUpdateNotification(message));
+ command.reset(new commands::OnStatusUpdateNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::SDL_OnAppPermissionConsent: {
- command.reset(new commands::OnAppPermissionConsentNotification(message));
+ command.reset(new commands::OnAppPermissionConsentNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_MixingAudioSupported: {
if (is_response) {
- command.reset(new commands::MixingAudioSupportedResponse(message));
+ command.reset(new commands::MixingAudioSupportedResponse(
+ message, application_manager));
} else {
- command.reset(new commands::MixingAudioSupportedRequest(message));
+ command.reset(new commands::MixingAudioSupportedRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnExitAllApplications: {
- command.reset(new commands::OnExitAllApplicationsNotification(message));
+ command.reset(new commands::OnExitAllApplicationsNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::UI_AddCommand: {
if (is_response) {
- command.reset(new commands::UIAddCommandResponse(message));
+ command.reset(
+ new commands::UIAddCommandResponse(message, application_manager));
} else {
- command.reset(new commands::UIAddCommandRequest(message));
+ command.reset(
+ new commands::UIAddCommandRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_DeleteCommand: {
if (is_response) {
- command.reset(new commands::UIDeleteCommandResponse(message));
+ command.reset(new commands::UIDeleteCommandResponse(
+ message, application_manager));
} else {
- command.reset(new commands::UIDeleteCommandRequest(message));
+ command.reset(
+ new commands::UIDeleteCommandRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_AddSubMenu: {
if (is_response) {
- command.reset(new commands::UIAddSubmenuResponse(message));
+ command.reset(
+ new commands::UIAddSubmenuResponse(message, application_manager));
} else {
- command.reset(new commands::UIAddSubmenuRequest(message));
+ command.reset(
+ new commands::UIAddSubmenuRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_DeleteSubMenu: {
if (is_response) {
- command.reset(new commands::UIDeleteSubmenuResponse(message));
+ command.reset(new commands::UIDeleteSubmenuResponse(
+ message, application_manager));
} else {
- command.reset(new commands::UIDeleteSubmenuRequest(message));
+ command.reset(
+ new commands::UIDeleteSubmenuRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_SetMediaClockTimer: {
if (is_response) {
- command.reset(new commands::UISetMediaClockTimerResponse(message));
+ command.reset(new commands::UISetMediaClockTimerResponse(
+ message, application_manager));
} else {
- command.reset(new commands::UISetMediaClockTimerRequest(message));
+ command.reset(new commands::UISetMediaClockTimerRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_PerformInteraction: {
if (is_response) {
- command.reset(new commands::UIPerformInteractionResponse(message));
+ command.reset(new commands::UIPerformInteractionResponse(
+ message, application_manager));
} else {
- command.reset(new commands::UIPerformInteractionRequest(message));
+ command.reset(new commands::UIPerformInteractionRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_SetGlobalProperties: {
if (is_response) {
- command.reset(new commands::UISetGlobalPropertiesResponse(message));
+ command.reset(new commands::UISetGlobalPropertiesResponse(
+ message, application_manager));
} else {
- command.reset(new commands::UISetGlobalPropertiesRequest(message));
+ command.reset(new commands::UISetGlobalPropertiesRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_ScrollableMessage: {
if (is_response) {
- command.reset(new commands::UIScrollableMessageResponse(message));
+ command.reset(new commands::UIScrollableMessageResponse(
+ message, application_manager));
} else {
- command.reset(new commands::UIScrollableMessageRequest(message));
+ command.reset(new commands::UIScrollableMessageRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_SetAppIcon: {
if (is_response) {
- command.reset(new commands::UISetAppIconResponse(message));
+ command.reset(
+ new commands::UISetAppIconResponse(message, application_manager));
} else {
- command.reset(new commands::UISetAppIconRequest(message));
+ command.reset(
+ new commands::UISetAppIconRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_GetSupportedLanguages: {
if (is_response) {
- command.reset(new commands::UIGetSupportedLanguagesResponse(message));
+ command.reset(new commands::UIGetSupportedLanguagesResponse(
+ message, application_manager));
} else {
- command.reset(new commands::UIGetSupportedLanguagesRequest(message));
+ command.reset(new commands::UIGetSupportedLanguagesRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_GetLanguage: {
if (is_response) {
- command.reset(new commands::UIGetLanguageResponse(message));
+ command.reset(
+ new commands::UIGetLanguageResponse(message, application_manager));
} else {
- command.reset(new commands::UIGetLanguageRequest(message));
+ command.reset(
+ new commands::UIGetLanguageRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_GetCapabilities: {
if (is_response) {
- command.reset(new commands::UIGetCapabilitiesResponse(message));
+ command.reset(new commands::UIGetCapabilitiesResponse(
+ message, application_manager));
} else {
- command.reset(new commands::UIGetCapabilitiesRequest(message));
+ command.reset(new commands::UIGetCapabilitiesRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_ChangeRegistration: {
if (is_response) {
- command.reset(new commands::UIChangeRegistratioResponse(message));
+ command.reset(new commands::UIChangeRegistratioResponse(
+ message, application_manager));
} else {
- command.reset(new commands::UIChangeRegistrationRequest(message));
+ command.reset(new commands::UIChangeRegistrationRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_PerformAudioPassThru: {
if (is_response) {
- command.reset(new commands::UIPerformAudioPassThruResponse(message));
+ command.reset(new commands::UIPerformAudioPassThruResponse(
+ message, application_manager));
} else {
- command.reset(new commands::UIPerformAudioPassThruRequest(message));
+ command.reset(new commands::UIPerformAudioPassThruRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_EndAudioPassThru: {
if (is_response) {
- command.reset(new commands::UIEndAudioPassThruResponse(message));
+ command.reset(new commands::UIEndAudioPassThruResponse(
+ message, application_manager));
} else {
- command.reset(new commands::UIEndAudioPassThruRequest(message));
+ command.reset(new commands::UIEndAudioPassThruRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_Alert: {
if (is_response) {
- command.reset(new commands::UIAlertResponse(message));
+ command.reset(
+ new commands::UIAlertResponse(message, application_manager));
} else {
- command.reset(new commands::UIAlertRequest(message));
+ command.reset(
+ new commands::UIAlertRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::VR_IsReady: {
if (is_response) {
- command.reset(new commands::VRIsReadyResponse(message));
+ command.reset(
+ new commands::VRIsReadyResponse(message, application_manager));
} else {
- command.reset(new commands::VRIsReadyRequest(message));
+ command.reset(
+ new commands::VRIsReadyRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::VR_AddCommand: {
if (is_response) {
- command.reset(new commands::VRAddCommandResponse(message));
+ command.reset(
+ new commands::VRAddCommandResponse(message, application_manager));
} else {
- command.reset(new commands::VRAddCommandRequest(message));
+ command.reset(
+ new commands::VRAddCommandRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::VR_DeleteCommand: {
if (is_response) {
- command.reset(new commands::VRDeleteCommandResponse(message));
+ command.reset(new commands::VRDeleteCommandResponse(
+ message, application_manager));
} else {
- command.reset(new commands::VRDeleteCommandRequest(message));
+ command.reset(
+ new commands::VRDeleteCommandRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::VR_ChangeRegistration: {
if (is_response) {
- command.reset(new commands::VRChangeRegistrationResponse(message));
+ command.reset(new commands::VRChangeRegistrationResponse(
+ message, application_manager));
} else {
- command.reset(new commands::VRChangeRegistrationRequest(message));
+ command.reset(new commands::VRChangeRegistrationRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::VR_GetSupportedLanguages: {
if (is_response) {
- command.reset(new commands::VRGetSupportedLanguagesResponse(message));
+ command.reset(new commands::VRGetSupportedLanguagesResponse(
+ message, application_manager));
} else {
- command.reset(new commands::VRGetSupportedLanguagesRequest(message));
+ command.reset(new commands::VRGetSupportedLanguagesRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::VR_GetLanguage: {
if (is_response) {
- command.reset(new commands::VRGetLanguageResponse(message));
+ command.reset(
+ new commands::VRGetLanguageResponse(message, application_manager));
} else {
- command.reset(new commands::VRGetLanguageRequest(message));
+ command.reset(
+ new commands::VRGetLanguageRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::VR_GetCapabilities: {
if (is_response) {
- command.reset(new commands::VRGetCapabilitiesResponse(message));
+ command.reset(new commands::VRGetCapabilitiesResponse(
+ message, application_manager));
} else {
- command.reset(new commands::VRGetCapabilitiesRequest(message));
+ command.reset(new commands::VRGetCapabilitiesRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::TTS_IsReady: {
if (is_response) {
- command.reset(new commands::TTSIsReadyResponse(message));
+ command.reset(
+ new commands::TTSIsReadyResponse(message, application_manager));
} else {
- command.reset(new commands::TTSIsReadyRequest(message));
+ command.reset(
+ new commands::TTSIsReadyRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::TTS_ChangeRegistration: {
if (is_response) {
- command.reset(new commands::TTSChangeRegistratioResponse(message));
+ command.reset(new commands::TTSChangeRegistratioResponse(
+ message, application_manager));
} else {
- command.reset(new commands::TTSChangeRegistrationRequest(message));
+ command.reset(new commands::TTSChangeRegistrationRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::TTS_GetSupportedLanguages: {
if (is_response) {
- command.reset(new commands::TTSGetSupportedLanguagesResponse(message));
+ command.reset(new commands::TTSGetSupportedLanguagesResponse(
+ message, application_manager));
} else {
- command.reset(new commands::TTSGetSupportedLanguagesRequest(message));
+ command.reset(new commands::TTSGetSupportedLanguagesRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::TTS_StopSpeaking: {
if (is_response) {
- command.reset(new commands::TTSStopSpeakingResponse(message));
+ command.reset(new commands::TTSStopSpeakingResponse(
+ message, application_manager));
} else {
- command.reset(new commands::TTSStopSpeakingRequest(message));
+ command.reset(
+ new commands::TTSStopSpeakingRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::TTS_GetLanguage: {
if (is_response) {
- command.reset(new commands::TTSGetLanguageResponse(message));
+ command.reset(
+ new commands::TTSGetLanguageResponse(message, application_manager));
} else {
- command.reset(new commands::TTSGetLanguageRequest(message));
+ command.reset(
+ new commands::TTSGetLanguageRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::TTS_Speak: {
if (is_response) {
- command.reset(new commands::TTSSpeakResponse(message));
+ command.reset(
+ new commands::TTSSpeakResponse(message, application_manager));
} else {
- command.reset(new commands::TTSSpeakRequest(message));
+ command.reset(
+ new commands::TTSSpeakRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::TTS_SetGlobalProperties: {
if (is_response) {
- command.reset(new commands::TTSSetGlobalPropertiesResponse(message));
+ command.reset(new commands::TTSSetGlobalPropertiesResponse(
+ message, application_manager));
} else {
- command.reset(new commands::TTSSetGlobalPropertiesRequest(message));
+ command.reset(new commands::TTSSetGlobalPropertiesRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::TTS_GetCapabilities: {
if (is_response) {
- command.reset(new commands::TTSGetCapabilitiesResponse(message));
+ command.reset(new commands::TTSGetCapabilitiesResponse(
+ message, application_manager));
} else {
- command.reset(new commands::TTSGetCapabilitiesRequest(message));
+ command.reset(new commands::TTSGetCapabilitiesRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::TTS_Started: {
- command.reset(new commands::OnTTSStartedNotification(message));
+ command.reset(
+ new commands::OnTTSStartedNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::TTS_Stopped: {
- command.reset(new commands::OnTTSStoppedNotification(message));
+ command.reset(
+ new commands::OnTTSStoppedNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnAppActivated: {
- command.reset(new commands::OnAppActivatedNotification(message));
+ command.reset(new commands::OnAppActivatedNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnExitApplication: {
- command.reset(new commands::OnExitApplicationNotification(message));
+ command.reset(new commands::OnExitApplicationNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::UI_Show: {
if (is_response) {
- command.reset(new commands::UIShowResponse(message));
+ command.reset(
+ new commands::UIShowResponse(message, application_manager));
} else {
- command.reset(new commands::UIShowRequest(message));
+ command.reset(
+ new commands::UIShowRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_Slider: {
if (is_response) {
- command.reset(new commands::UISliderResponse(message));
+ command.reset(
+ new commands::UISliderResponse(message, application_manager));
} else {
- command.reset(new commands::UISliderRequest(message));
+ command.reset(
+ new commands::UISliderRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_ClosePopUp: {
if (is_response) {
- command.reset(new commands::ClosePopupResponse(message));
+ command.reset(
+ new commands::ClosePopupResponse(message, application_manager));
} else {
- command.reset(new commands::ClosePopupRequest(message));
+ command.reset(
+ new commands::ClosePopupRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::UI_IsReady: {
if (is_response) {
- command.reset(new commands::UIIsReadyResponse(message));
+ command.reset(
+ new commands::UIIsReadyResponse(message, application_manager));
} else {
- command.reset(new commands::UIIsReadyRequest(message));
+ command.reset(
+ new commands::UIIsReadyRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::VehicleInfo_IsReady: {
if (is_response) {
- command.reset(new commands::VIIsReadyResponse(message));
+ command.reset(
+ new commands::VIIsReadyResponse(message, application_manager));
} else {
- command.reset(new commands::VIIsReadyRequest(message));
+ command.reset(
+ new commands::VIIsReadyRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::VehicleInfo_ReadDID: {
if (is_response) {
- command.reset(new commands::VIReadDIDResponse(message));
+ command.reset(
+ new commands::VIReadDIDResponse(message, application_manager));
} else {
- command.reset(new commands::VIReadDIDRequest(message));
+ command.reset(
+ new commands::VIReadDIDRequest(message, application_manager));
}
break;
}
#ifdef HMI_DBUS_API
case hmi_apis::FunctionID::VehicleInfo_GetGpsData: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetGpsData > (message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetGpsData>(message,
+ application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetGpsData > (message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetGpsData>(message,
+ application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetSpeed: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetSpeed > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetSpeed>(message,
+ application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetSpeed > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetSpeed>(message,
+ application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetRpm: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetRpm > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetRpm>(message,
+ application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetRpm > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetRpm>(message,
+ application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetFuelLevel: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetFuelLevel > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetFuelLevel>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetFuelLevel > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetFuelLevel>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetFuelLevelState: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetFuelLevelState > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetFuelLevelState>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetFuelLevelState > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetFuelLevelState>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetInstantFuelConsumption: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetInstantFuelConsumption > (
- message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetInstantFuelConsumption>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetInstantFuelConsumption > (
- message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetInstantFuelConsumption>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetExternalTemperature: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetExternalTemperature > (
- message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetExternalTemperature>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetExternalTemperature > (
- message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetExternalTemperature>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetPrndl: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetPrndl > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetPrndl>(message,
+ application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetPrndl > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetPrndl>(message,
+ application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetVin: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetVin > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetVin>(message,
+ application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetVin > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetVin>(message,
+ application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetTirePressure: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetTirePressure > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetTirePressure>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetTirePressure > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetTirePressure>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetOdometer: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetOdometer > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetOdometer>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetOdometer > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetOdometer>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetBeltStatus: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetBeltStatus > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetBeltStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetBeltStatus > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetBeltStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetBodyInformation: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetBodyInformation > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetBodyInformation>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetBodyInformation > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetBodyInformation>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetDeviceStatus: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetDeviceStatus > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetDeviceStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetDeviceStatus > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetDeviceStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetDriverBraking: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetDriverBraking > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetDriverBraking>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetDriverBraking > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetDriverBraking>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetWiperStatus: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetWiperStatus > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetWiperStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetWiperStatus > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetWiperStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetHeadLampStatus: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetHeadLampStatus > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetHeadLampStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetHeadLampStatus > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetHeadLampStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetEngineTorque: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetEngineTorque > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetEngineTorque>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetEngineTorque > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetEngineTorque>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetAccPedalPosition: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetAccPedalPosition > (
- message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetAccPedalPosition>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetAccPedalPosition > (
- message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetAccPedalPosition>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetSteeringWheelAngle: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetSteeringWheelAngle > (
- message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetSteeringWheelAngle>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetSteeringWheelAngle > (
- message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetSteeringWheelAngle>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetECallInfo: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetECallInfo > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetECallInfo>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetECallInfo > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetECallInfo>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetAirbagStatus: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetAirbagStatus > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetAirbagStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetAirbagStatus > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetAirbagStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetEmergencyEvent: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetEmergencyEvent > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetEmergencyEvent>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetEmergencyEvent > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetEmergencyEvent>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetClusterModeStatus: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetClusterModeStatus > (
- message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetClusterModeStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetClusterModeStatus > (
- message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetClusterModeStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetMyKey: {
if (is_response)
- command.reset(
- new commands::VIGetVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetMyKey > (message));
+ command.reset(new commands::VIGetVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetMyKey>(message,
+ application_manager));
else
- command.reset(
- new commands::VIGetVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_GetMyKey > (message));
+ command.reset(new commands::VIGetVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_GetMyKey>(message,
+ application_manager));
break;
}
#else
case hmi_apis::FunctionID::VehicleInfo_GetVehicleData: {
if (is_response) {
- command.reset(new commands::VIGetVehicleDataResponse(message));
+ command.reset(new commands::VIGetVehicleDataResponse(
+ message, application_manager));
} else {
- command.reset(new commands::VIGetVehicleDataRequest(message));
+ command.reset(new commands::VIGetVehicleDataRequest(
+ message, application_manager));
}
break;
}
-#endif // #ifdef HMI_DBUS_API
+#endif // #ifdef HMI_DBUS_API
case hmi_apis::FunctionID::VehicleInfo_GetDTCs: {
if (is_response) {
- command.reset(new commands::VIGetDTCsResponse(message));
+ command.reset(
+ new commands::VIGetDTCsResponse(message, application_manager));
} else {
- command.reset(new commands::VIGetDTCsRequest(message));
+ command.reset(
+ new commands::VIGetDTCsRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::VehicleInfo_DiagnosticMessage: {
if (is_response) {
- command.reset(new commands::VIDiagnosticMessageResponse(message));
+ command.reset(new commands::VIDiagnosticMessageResponse(
+ message, application_manager));
} else {
- command.reset(new commands::VIDiagnosticMessageRequest(message));
+ command.reset(new commands::VIDiagnosticMessageRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::VehicleInfo_GetVehicleType: {
if (is_response) {
- command.reset(new commands::VIGetVehicleTypeResponse(message));
+ command.reset(new commands::VIGetVehicleTypeResponse(
+ message, application_manager));
} else {
- command.reset(new commands::VIGetVehicleTypeRequest(message));
+ command.reset(new commands::VIGetVehicleTypeRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::Navigation_IsReady: {
if (is_response) {
- command.reset(new commands::NaviIsReadyResponse(message));
+ command.reset(
+ new commands::NaviIsReadyResponse(message, application_manager));
} else {
- command.reset(new commands::NaviIsReadyRequest(message));
+ command.reset(
+ new commands::NaviIsReadyRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::Navigation_AlertManeuver: {
if (is_response) {
- command.reset(new commands::NaviAlertManeuverResponse(message));
+ command.reset(new commands::NaviAlertManeuverResponse(
+ message, application_manager));
+ } else {
+ command.reset(new commands::NaviAlertManeuverRequest(
+ message, application_manager));
+ }
+ break;
+ }
+ case hmi_apis::FunctionID::Navigation_GetWayPoints: {
+ if (is_response) {
+ command.reset(new commands::NaviGetWayPointsResponse(
+ message, application_manager));
} else {
- command.reset(new commands::NaviAlertManeuverRequest(message));
+ command.reset(new commands::NaviGetWayPointsRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::Navigation_UpdateTurnList: {
if (is_response) {
- command.reset(new commands::NaviUpdateTurnListResponse(message));
+ command.reset(new commands::NaviUpdateTurnListResponse(
+ message, application_manager));
} else {
- command.reset(new commands::NaviUpdateTurnListRequest(message));
+ command.reset(new commands::NaviUpdateTurnListRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::Navigation_ShowConstantTBT: {
if (is_response) {
- command.reset(new commands::NaviShowConstantTBTResponse(message));
+ command.reset(new commands::NaviShowConstantTBTResponse(
+ message, application_manager));
+ } else {
+ command.reset(new commands::NaviShowConstantTBTRequest(
+ message, application_manager));
+ }
+ break;
+ }
+ case hmi_apis::FunctionID::Navigation_SubscribeWayPoints: {
+ if (is_response) {
+ command.reset(new commands::NaviSubscribeWayPointsResponse(
+ message, application_manager));
+ } else {
+ command.reset(new commands::NaviSubscribeWayPointsRequest(
+ message, application_manager));
+ }
+ break;
+ }
+ case hmi_apis::FunctionID::Navigation_UnsubscribeWayPoints: {
+ if (is_response) {
+ command.reset(new commands::NaviUnsubscribeWayPointsResponse(
+ message, application_manager));
} else {
- command.reset(new commands::NaviShowConstantTBTRequest(message));
+ command.reset(new commands::NaviUnSubscribeWayPointsRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::Buttons_GetCapabilities: {
if (is_response) {
- command.reset(new commands::ButtonGetCapabilitiesResponse(message));
+ command.reset(new commands::ButtonGetCapabilitiesResponse(
+ message, application_manager));
} else {
- command.reset(new commands::ButtonGetCapabilitiesRequest(message));
+ command.reset(new commands::ButtonGetCapabilitiesRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::SDL_OnAllowSDLFunctionality: {
- command.reset(new commands::OnAllowSDLFunctionalityNotification(message));
+ command.reset(new commands::OnAllowSDLFunctionalityNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::SDL_OnSDLConsentNeeded: {
- command.reset(new commands::OnSDLConsentNeededNotification(message));
+ command.reset(new commands::OnSDLConsentNeededNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::SDL_UpdateSDL: {
if (is_response) {
- command.reset(new commands::UpdateSDLResponse(message));
+ command.reset(
+ new commands::UpdateSDLResponse(message, application_manager));
} else {
- command.reset(new commands::UpdateSDLRequest(message));
+ command.reset(
+ new commands::UpdateSDLRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnIgnitionCycleOver: {
- command.reset(new commands::OnIgnitionCycleOverNotification(message));
+ command.reset(new commands::OnIgnitionCycleOverNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnSystemInfoChanged: {
- command.reset(new commands::OnSystemInfoChangedNotification(message));
- break;
- }
- case hmi_apis::FunctionID::BasicCommunication_OnEmergencyEvent: {
- command.reset(new commands::OnEmergencyEventNotification(message));
- break;
- }
- case hmi_apis::FunctionID::BasicCommunication_PlayTone: {
- command.reset(new commands::OnPlayToneNotification(message));
+ command.reset(new commands::OnSystemInfoChangedNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnReady: {
- command.reset(new commands::OnReadyNotification(message));
+ command.reset(
+ new commands::OnReadyNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnDeviceChosen: {
- command.reset(new commands::OnDeviceChosenNotification(message));
+ command.reset(new commands::OnDeviceChosenNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::UI_OnSystemContext: {
- command.reset(new commands::OnSystemContextNotification(message));
+ command.reset(new commands::OnSystemContextNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::UI_OnDriverDistraction: {
- command.reset(
- new commands::hmi::OnDriverDistractionNotification(message));
+ command.reset(new commands::hmi::OnDriverDistractionNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnUpdateDeviceList: {
- command.reset(new commands::OnUpdateDeviceList(message));
+ command.reset(
+ new commands::OnUpdateDeviceList(message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnAppRegistered: {
- command.reset(new commands::OnAppRegisteredNotification(message));
+ command.reset(new commands::OnAppRegisteredNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnAppUnregistered: {
- command.reset(new commands::OnAppUnregisteredNotification(message));
+ command.reset(new commands::OnAppUnregisteredNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnFindApplications: {
- command.reset(new commands::OnFindApplications(message));
+ command.reset(
+ new commands::OnFindApplications(message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_UpdateAppList: {
if (is_response) {
- command.reset(new commands::UpdateAppListResponse(message));
+ command.reset(
+ new commands::UpdateAppListResponse(message, application_manager));
} else {
- command.reset(new commands::UpdateAppListRequest(message));
+ command.reset(
+ new commands::UpdateAppListRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::VR_Started: {
- command.reset(new commands::OnVRStartedNotification(message));
+ command.reset(
+ new commands::OnVRStartedNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::VR_Stopped: {
- command.reset(new commands::OnVRStoppedNotification(message));
+ command.reset(
+ new commands::OnVRStoppedNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::VR_OnCommand: {
- command.reset(new commands::OnVRCommandNotification(message));
+ command.reset(
+ new commands::OnVRCommandNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::UI_OnCommand: {
- command.reset(new commands::OnUICommandNotification(message));
+ command.reset(
+ new commands::OnUICommandNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnAppDeactivated: {
- command.reset(new commands::OnAppDeactivatedNotification(message));
+ command.reset(new commands::OnAppDeactivatedNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::UI_OnLanguageChange: {
- command.reset(new commands::OnUILanguageChangeNotification(message));
+ command.reset(new commands::OnUILanguageChangeNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VR_OnLanguageChange: {
- command.reset(new commands::OnVRLanguageChangeNotification(message));
+ command.reset(new commands::OnVRLanguageChangeNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::TTS_OnLanguageChange: {
- command.reset(new commands::OnTTSLanguageChangeNotification(message));
+ command.reset(new commands::OnTTSLanguageChangeNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::Buttons_OnButtonEvent: {
- command.reset(new commands::hmi::OnButtonEventNotification(message));
+ command.reset(new commands::hmi::OnButtonEventNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::Buttons_OnButtonPress: {
- command.reset(new commands::hmi::OnButtonPressNotification(message));
+ command.reset(new commands::hmi::OnButtonPressNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::Buttons_OnButtonSubscription: {
- command.reset(new commands::hmi::OnButtonSubscriptionNotification(message));
+ command.reset(new commands::hmi::OnButtonSubscriptionNotification(
+ message, application_manager));
break;
}
#ifdef HMI_DBUS_API
case hmi_apis::FunctionID::VehicleInfo_SubscribeGps: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeGps > (message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeGps>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeGps > (message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeGps>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeSpeed: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeSpeed > (message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeSpeed>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeSpeed > (message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeSpeed>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeRpm: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeRpm > (message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeRpm>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeRpm > (message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeRpm>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel > (message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel > (message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel_State: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel_State > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel_State>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel_State > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel_State>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeInstantFuelConsumption: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeInstantFuelConsumption > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeInstantFuelConsumption>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeInstantFuelConsumption > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeInstantFuelConsumption>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeExternalTemperature: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeExternalTemperature > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeExternalTemperature>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeExternalTemperature > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeExternalTemperature>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribePrndl: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribePrndl > (message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribePrndl>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribePrndl > (message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribePrndl>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeVin: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeVin > (message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeVin>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeVin > (message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeVin>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeTirePressure: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeTirePressure > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeTirePressure>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeTirePressure > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeTirePressure>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeOdometer: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeOdometer > (message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeOdometer>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeOdometer > (message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeOdometer>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeBeltStatus: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeBeltStatus > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeBeltStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeBeltStatus > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeBeltStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeBodyInformation: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeBodyInformation > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeBodyInformation>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeBodyInformation > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeBodyInformation>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeDeviceStatus: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeDeviceStatus > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeDeviceStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeDeviceStatus > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeDeviceStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeDriverBraking: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeDriverBraking > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeDriverBraking>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeDriverBraking > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeDriverBraking>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeWiperStatus: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeWiperStatus > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeWiperStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeWiperStatus > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeWiperStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeHeadLampStatus: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeHeadLampStatus > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeHeadLampStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeHeadLampStatus > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeHeadLampStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeEngineTorque: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeEngineTorque > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeEngineTorque>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeEngineTorque > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeEngineTorque>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeAccPedalPosition: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeAccPedalPosition > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeAccPedalPosition>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeAccPedalPosition > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeAccPedalPosition>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeSteeringWheelAngle: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeSteeringWheelAngle > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeSteeringWheelAngle>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeSteeringWheelAngle > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeSteeringWheelAngle>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeECallInfo: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeECallInfo > (message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeECallInfo>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeECallInfo > (message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeECallInfo>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeAirbagStatus: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeAirbagStatus > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeAirbagStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeAirbagStatus > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeAirbagStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeEmergencyEvent: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeEmergencyEvent > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeEmergencyEvent>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeEmergencyEvent > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeEmergencyEvent>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeClusterModeStatus: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeClusterModeStatus > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeClusterModeStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeClusterModeStatus > (
- message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeClusterModeStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_SubscribeMyKey: {
if (is_response)
- command.reset(
- new commands::VISubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeMyKey > (message));
+ command.reset(new commands::VISubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeMyKey>(
+ message, application_manager));
else
- command.reset(
- new commands::VISubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_SubscribeMyKey > (message));
+ command.reset(new commands::VISubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_SubscribeMyKey>(
+ message, application_manager));
break;
}
#else
case hmi_apis::FunctionID::VehicleInfo_SubscribeVehicleData: {
if (is_response) {
- command.reset(new commands::VISubscribeVehicleDataResponse(message));
+ command.reset(new commands::VISubscribeVehicleDataResponse(
+ message, application_manager));
} else {
- command.reset(new commands::VISubscribeVehicleDataRequest(message));
+ command.reset(new commands::VISubscribeVehicleDataRequest(
+ message, application_manager));
}
break;
}
-#endif // #ifdef HMI_DBUS_API
+#endif // #ifdef HMI_DBUS_API
#ifdef HMI_DBUS_API
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeGps: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeGps > (message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeGps>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeGps > (message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeGps>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeSpeed: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeSpeed > (message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeSpeed>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeSpeed > (message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeSpeed>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeRpm: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeRpm > (message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeRpm>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeRpm > (message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeRpm>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeFuelLevel: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeFuelLevel > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeFuelLevel>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeFuelLevel > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeFuelLevel>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeFuelLevel_State: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeFuelLevel_State > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeFuelLevel_State>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeFuelLevel_State > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeFuelLevel_State>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeInstantFuelConsumption: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeInstantFuelConsumption > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::
+ VehicleInfo_UnsubscribeInstantFuelConsumption>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeInstantFuelConsumption > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::
+ VehicleInfo_UnsubscribeInstantFuelConsumption>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeExternalTemperature: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeExternalTemperature > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeExternalTemperature>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeExternalTemperature > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeExternalTemperature>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribePrndl: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribePrndl > (message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribePrndl>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribePrndl > (message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribePrndl>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeVin: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeVin > (message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeVin>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeVin > (message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeVin>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeTirePressure: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeTirePressure > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeTirePressure>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeTirePressure > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeTirePressure>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeOdometer: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeOdometer > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeOdometer>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeOdometer > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeOdometer>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeBeltStatus: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeBeltStatus > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeBeltStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeBeltStatus > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeBeltStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeBodyInformation: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeBodyInformation > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeBodyInformation>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeBodyInformation > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeBodyInformation>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeDeviceStatus: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeDeviceStatus > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeDeviceStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeDeviceStatus > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeDeviceStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeDriverBraking: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeDriverBraking > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeDriverBraking>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeDriverBraking > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeDriverBraking>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeWiperStatus: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeWiperStatus > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeWiperStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeWiperStatus > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeWiperStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeHeadLampStatus: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeHeadLampStatus > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeHeadLampStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeHeadLampStatus > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeHeadLampStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeEngineTorque: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeEngineTorque > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeEngineTorque>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeEngineTorque > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeEngineTorque>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeAccPedalPosition: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeAccPedalPosition > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeAccPedalPosition>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeAccPedalPosition > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeAccPedalPosition>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeSteeringWheelAngle: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeSteeringWheelAngle > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeSteeringWheelAngle>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeSteeringWheelAngle > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeSteeringWheelAngle>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeECallInfo: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeECallInfo > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeECallInfo>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeECallInfo > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeECallInfo>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeAirbagStatus: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeAirbagStatus > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeAirbagStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeAirbagStatus > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeAirbagStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeEmergencyEvent: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeEmergencyEvent > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeEmergencyEvent>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeEmergencyEvent > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeEmergencyEvent>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeClusterModeStatus: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeClusterModeStatus > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeClusterModeStatus>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeClusterModeStatus > (
- message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeClusterModeStatus>(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeMyKey: {
if (is_response)
- command.reset(
- new commands::VIUnsubscribeVehicleDataResponseTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeMyKey > (message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponseTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeMyKey>(
+ message, application_manager));
else
- command.reset(
- new commands::VIUnsubscribeVehicleDataRequestTemplate <
- hmi_apis::FunctionID::VehicleInfo_UnsubscribeMyKey > (message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequestTemplate<
+ hmi_apis::FunctionID::VehicleInfo_UnsubscribeMyKey>(
+ message, application_manager));
break;
}
#else
case hmi_apis::FunctionID::VehicleInfo_UnsubscribeVehicleData: {
if (is_response) {
- command.reset(new commands::VIUnsubscribeVehicleDataResponse(message));
+ command.reset(new commands::VIUnsubscribeVehicleDataResponse(
+ message, application_manager));
} else {
- command.reset(new commands::VIUnsubscribeVehicleDataRequest(message));
+ command.reset(new commands::VIUnsubscribeVehicleDataRequest(
+ message, application_manager));
}
break;
}
-#endif // #ifdef HMI_DBUS_API
+#endif // #ifdef HMI_DBUS_API
#ifdef HMI_DBUS_API
case hmi_apis::FunctionID::VehicleInfo_OnGpsData: {
- command.reset(new commands::OnVIGpsDataNotification(message));
+ command.reset(
+ new commands::OnVIGpsDataNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnSpeed: {
- command.reset(new commands::OnVISpeedNotification(message));
+ command.reset(
+ new commands::OnVISpeedNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnRpm: {
- command.reset(new commands::OnVIRpmNotification(message));
+ command.reset(
+ new commands::OnVIRpmNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnFuelLevel: {
- command.reset(new commands::OnVIFuelLevelNotification(message));
+ command.reset(new commands::OnVIFuelLevelNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnFuelLevelState: {
- command.reset(new commands::OnVIFuelLevelStateNotification(message));
+ command.reset(new commands::OnVIFuelLevelStateNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnInstantFuelConsumption: {
- command.reset(
- new commands::OnVIInstantFuelConsumptionNotification(message));
+ command.reset(new commands::OnVIInstantFuelConsumptionNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnExternalTemperature: {
- command.reset(new commands::OnVIExternalTemperatureNotification(message));
+ command.reset(new commands::OnVIExternalTemperatureNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnVin: {
- command.reset(new commands::OnVIVinNotification(message));
+ command.reset(
+ new commands::OnVIVinNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnPrndl: {
- command.reset(new commands::OnVIPrndlNotification(message));
+ command.reset(
+ new commands::OnVIPrndlNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnTirePressure: {
- command.reset(new commands::OnVITirePressureNotification(message));
+ command.reset(new commands::OnVITirePressureNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnOdometer: {
- command.reset(new commands::OnVIOdometerNotification(message));
+ command.reset(
+ new commands::OnVIOdometerNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnBeltStatus: {
- command.reset(new commands::OnVIBeltStatusNotification(message));
+ command.reset(new commands::OnVIBeltStatusNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnBodyInformation: {
- command.reset(new commands::OnVIBodyInformationNotification(message));
+ command.reset(new commands::OnVIBodyInformationNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnDeviceStatus: {
- command.reset(new commands::OnVIDeviceStatusNotification(message));
+ command.reset(new commands::OnVIDeviceStatusNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnDriverBraking: {
- command.reset(new commands::OnVIDriverBrakingNotification(message));
+ command.reset(new commands::OnVIDriverBrakingNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnWiperStatus: {
- command.reset(new commands::OnVIWiperStatusNotification(message));
+ command.reset(new commands::OnVIWiperStatusNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnHeadLampStatus: {
- command.reset(new commands::OnVIHeadLampStatusNotification(message));
+ command.reset(new commands::OnVIHeadLampStatusNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnEngineTorque: {
- command.reset(new commands::OnVIEngineTorqueNotification(message));
+ command.reset(new commands::OnVIEngineTorqueNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnAccPedalPosition: {
- command.reset(new commands::OnVIAccPedalPositionNotification(message));
+ command.reset(new commands::OnVIAccPedalPositionNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnSteeringWheelAngle: {
- command.reset(new commands::OnVISteeringWheelAngleNotification(message));
+ command.reset(new commands::OnVISteeringWheelAngleNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VehicleInfo_OnMyKey: {
- command.reset(new commands::OnVIMyKeyNotification(message));
+ command.reset(
+ new commands::OnVIMyKeyNotification(message, application_manager));
break;
}
#else
case hmi_apis::FunctionID::VehicleInfo_OnVehicleData: {
- command.reset(new commands::OnVIVehicleDataNotification(message));
+ command.reset(new commands::OnVIVehicleDataNotification(
+ message, application_manager));
break;
}
-#endif // #ifdef HMI_DBUS_API
+#endif // #ifdef HMI_DBUS_API
case hmi_apis::FunctionID::Navigation_OnTBTClientState: {
- command.reset(new commands::OnNaviTBTClientStateNotification(message));
+ command.reset(new commands::OnNaviTBTClientStateNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::UI_OnKeyboardInput: {
- command.reset(new commands::hmi::OnUIKeyBoardInputNotification(message));
+ command.reset(new commands::hmi::OnUIKeyBoardInputNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::UI_OnTouchEvent: {
- command.reset(new commands::hmi::OnUITouchEventNotification(message));
+ command.reset(new commands::hmi::OnUITouchEventNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::UI_OnResetTimeout: {
- command.reset(new commands::hmi::OnUIResetTimeoutNotification(message));
+ command.reset(new commands::hmi::OnUIResetTimeoutNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::Navigation_StartStream: {
if (is_response) {
- command.reset(new commands::NaviStartStreamResponse(message));
+ command.reset(new commands::NaviStartStreamResponse(
+ message, application_manager));
} else {
- command.reset(new commands::NaviStartStreamRequest(message));
+ command.reset(
+ new commands::NaviStartStreamRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::Navigation_StopStream: {
if (is_response) {
- command.reset(new commands::NaviStopStreamResponse(message));
+ command.reset(
+ new commands::NaviStopStreamResponse(message, application_manager));
} else {
- command.reset(new commands::NaviStopStreamRequest(message));
+ command.reset(
+ new commands::NaviStopStreamRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::Navigation_StartAudioStream: {
if (is_response) {
- command.reset(new commands::AudioStartStreamResponse(message));
+ command.reset(new commands::AudioStartStreamResponse(
+ message, application_manager));
} else {
- command.reset(new commands::AudioStartStreamRequest(message));
+ command.reset(new commands::AudioStartStreamRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::Navigation_StopAudioStream: {
if (is_response) {
- command.reset(new commands::AudioStopStreamResponse(message));
+ command.reset(new commands::AudioStopStreamResponse(
+ message, application_manager));
} else {
- command.reset(new commands::AudioStopStreamRequest(message));
+ command.reset(
+ new commands::AudioStopStreamRequest(message, application_manager));
}
break;
}
case hmi_apis::FunctionID::Navigation_OnAudioDataStreaming: {
- command.reset(new commands::OnAudioDataStreamingNotification(message));
+ command.reset(new commands::OnAudioDataStreamingNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::Navigation_OnVideoDataStreaming: {
- command.reset(new commands::OnVideoDataStreamingNotification(message));
+ command.reset(new commands::OnVideoDataStreamingNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::VR_PerformInteraction: {
if (is_response) {
- command.reset(new commands::VRPerformInteractionResponse(message));
+ command.reset(new commands::VRPerformInteractionResponse(
+ message, application_manager));
} else {
- command.reset(new commands::VRPerformInteractionRequest(message));
+ command.reset(new commands::VRPerformInteractionRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnSystemRequest: {
- command.reset(new commands::OnSystemRequestNotification(message));
+ command.reset(new commands::OnSystemRequestNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnPutFile: {
- command.reset(new commands::OnPutFileNotification(message));
+ command.reset(
+ new commands::OnPutFileNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnResumeAudioSource: {
- command.reset(new commands::OnResumeAudioSourceNotification(message));
+ command.reset(new commands::OnResumeAudioSourceNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::UI_SetDisplayLayout: {
if (is_response) {
- command.reset(new commands::UiSetDisplayLayoutResponse(message));
+ command.reset(new commands::UiSetDisplayLayoutResponse(
+ message, application_manager));
} else {
- command.reset(new commands::UiSetDisplayLayoutRequest(message));
+ command.reset(new commands::UiSetDisplayLayoutRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnSDLClose: {
- command.reset(new commands::OnSDLCloseNotification(message));
+ command.reset(
+ new commands::OnSDLCloseNotification(message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnSDLPersistenceComplete: {
- command.reset(new commands::OnSDLPersistenceCompleteNotification(message));
+ command.reset(new commands::OnSDLPersistenceCompleteNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_OnFileRemoved: {
- command.reset(new commands::OnFileRemovedNotification(message));
+ command.reset(new commands::OnFileRemovedNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::UI_OnRecordStart: {
- command.reset(new commands::OnRecordStartdNotification(message));
+ command.reset(new commands::OnRecordStartdNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_SystemRequest: {
if (is_response) {
- command.reset(new commands::BasicCommunicationSystemResponse(message));
+ command.reset(new commands::BasicCommunicationSystemResponse(
+ message, application_manager));
} else {
- command.reset(new commands::BasicCommunicationSystemRequest(message));
+ command.reset(new commands::BasicCommunicationSystemRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::Navigation_SendLocation: {
if (is_response) {
- command.reset(new commands::NaviSendLocationResponse(message));
+ command.reset(new commands::NaviSendLocationResponse(
+ message, application_manager));
} else {
- command.reset(new commands::NaviSendLocationRequest(message));
+ command.reset(new commands::NaviSendLocationRequest(
+ message, application_manager));
}
break;
}
case hmi_apis::FunctionID::SDL_AddStatisticsInfo: {
- command.reset(new commands::AddStatisticsInfoNotification(message));
+ command.reset(new commands::AddStatisticsInfoNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::SDL_OnSystemError: {
- command.reset(new commands::OnSystemErrorNotification(message));
+ command.reset(new commands::OnSystemErrorNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::SDL_OnReceivedPolicyUpdate: {
- command.reset(new commands::OnReceivedPolicyUpdate(message));
+ command.reset(
+ new commands::OnReceivedPolicyUpdate(message, application_manager));
break;
}
case hmi_apis::FunctionID::SDL_OnPolicyUpdate: {
- command.reset(new commands::OnPolicyUpdate(message));
+ command.reset(new commands::OnPolicyUpdate(message, application_manager));
break;
}
case hmi_apis::FunctionID::SDL_OnDeviceStateChanged: {
- command.reset(new commands::OnDeviceStateChangedNotification(message));
+ command.reset(new commands::OnDeviceStateChangedNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::TTS_OnResetTimeout: {
- command.reset(new commands::hmi::OnTTSResetTimeoutNotification(message));
+ command.reset(new commands::hmi::OnTTSResetTimeoutNotification(
+ message, application_manager));
break;
}
- case hmi_apis::FunctionID::BasicCommunication_OnPhoneCall: {
- command.reset(new commands::hmi::OnPhoneCallNotification(message));
+ case hmi_apis::FunctionID::BasicCommunication_OnEventChanged: {
+ command.reset(new commands::OnEventChangedNotification(
+ message, application_manager));
break;
}
case hmi_apis::FunctionID::BasicCommunication_DialNumber: {
if (is_response) {
- command.reset(new commands::hmi::DialNumberResponse(message));
+ command.reset(new commands::hmi::DialNumberResponse(
+ message, application_manager));
} else {
- command.reset(new commands::hmi::DialNumberRequest(message));
+ command.reset(
+ new commands::hmi::DialNumberRequest(message, application_manager));
}
break;
}
+ case hmi_apis::FunctionID::Navigation_OnWayPointChange: {
+ command.reset(new commands::OnNaviWayPointChangeNotification(
+ message, application_manager));
+ break;
+ }
}
-
return command;
}
diff --git a/src/components/application_manager/src/hmi_language_handler.cc b/src/components/application_manager/src/hmi_language_handler.cc
new file mode 100644
index 0000000000..d37467ee76
--- /dev/null
+++ b/src/components/application_manager/src/hmi_language_handler.cc
@@ -0,0 +1,352 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include "application_manager/hmi_language_handler.h"
+#include "application_manager/application_manager.h"
+#include "application_manager/message_helper.h"
+#include "application_manager/hmi_capabilities.h"
+#include "utils/helpers.h"
+#include "resumption/last_state.h"
+
+static const std::string LanguagesKey = "Languages";
+static const std::string UIKey = "UI";
+static const std::string VRKey = "VR";
+static const std::string TTSKey = "TTS";
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationManager")
+namespace application_manager {
+
+HMILanguageHandler::HMILanguageHandler(ApplicationManager& application_manager)
+ : event_engine::EventObserver(application_manager.event_dispatcher())
+ , capabilities_ui_language_(hmi_apis::Common_Language::INVALID_ENUM)
+ , capabilities_vr_language_(hmi_apis::Common_Language::INVALID_ENUM)
+ , capabilities_tts_language_(hmi_apis::Common_Language::INVALID_ENUM)
+ , is_ui_language_received_(false)
+ , is_vr_language_received_(false)
+ , is_tts_language_received_(false)
+ , application_manager_(application_manager) {
+ subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_OnAppRegistered);
+}
+
+void HMILanguageHandler::set_language_for(
+ HMILanguageHandler::Interface interface,
+ hmi_apis::Common_Language::eType language) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ std::string key = "UNKNOWN";
+ switch (interface) {
+ case INTERFACE_UI:
+ key = UIKey;
+ break;
+ case INTERFACE_VR:
+ key = VRKey;
+ break;
+ case INTERFACE_TTS:
+ key = TTSKey;
+ break;
+ default:
+ LOG4CXX_WARN(logger_, "Unknown interface has been passed " << interface);
+ return;
+ }
+ LOG4CXX_DEBUG(logger_,
+ "Setting language " << language << " for interface "
+ << interface);
+ last_state_->dictionary[LanguagesKey][key] = language;
+ return;
+}
+
+hmi_apis::Common_Language::eType HMILanguageHandler::get_language_for(
+ HMILanguageHandler::Interface interface) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace resumption;
+ using namespace hmi_apis;
+ std::string key = "UNKNOWN";
+ switch (interface) {
+ case INTERFACE_UI:
+ key = UIKey;
+ break;
+ case INTERFACE_VR:
+ key = VRKey;
+ break;
+ case INTERFACE_TTS:
+ key = TTSKey;
+ break;
+ default:
+ LOG4CXX_WARN(logger_, "Unknown interfcase has been passed " << interface);
+ return Common_Language::INVALID_ENUM;
+ }
+
+ if (last_state_->dictionary.isMember(LanguagesKey)) {
+ if (last_state_->dictionary[LanguagesKey].isMember(key)) {
+ Common_Language::eType language = static_cast<Common_Language::eType>(
+ last_state_->dictionary[LanguagesKey][key].asInt());
+ return language;
+ }
+ }
+ return Common_Language::INVALID_ENUM;
+}
+
+void HMILanguageHandler::on_event(const event_engine::Event& event) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObject msg = event.smart_object();
+ switch (event.id()) {
+ case hmi_apis::FunctionID::UI_GetLanguage:
+ LOG4CXX_DEBUG(logger_, "Got UI language response.");
+ is_ui_language_received_ = true;
+ break;
+ case hmi_apis::FunctionID::VR_GetLanguage:
+ LOG4CXX_DEBUG(logger_, "Got VR language response.");
+ is_vr_language_received_ = true;
+ break;
+ case hmi_apis::FunctionID::TTS_GetLanguage:
+ LOG4CXX_DEBUG(logger_, "Got TTS language response.");
+ is_tts_language_received_ = true;
+ break;
+ case hmi_apis::FunctionID::BasicCommunication_OnAppRegistered:
+ if (!(msg[strings::params].keyExists(strings::app_id))) {
+ LOG4CXX_ERROR(logger_, "Message doesn't contain parameter app_id");
+ return;
+ }
+ CheckApplication(
+ std::make_pair(msg[strings::params][strings::app_id].asUInt(), true));
+ return;
+ default:
+ return;
+ }
+
+ if (is_ui_language_received_ && is_vr_language_received_ &&
+ is_tts_language_received_) {
+ LOG4CXX_DEBUG(logger_, "All GetLanguages responses gotten.");
+ VerifyWithPersistedLanguages();
+ }
+}
+
+void HMILanguageHandler::set_handle_response_for(
+ const event_engine::smart_objects::SmartObject& request) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
+ if (!request.keyExists(strings::params)) {
+ LOG4CXX_ERROR(logger_,
+ "Object does not have " << strings::params << " key.");
+ return;
+ }
+
+ if (!request[strings::params].keyExists(strings::function_id)) {
+ LOG4CXX_ERROR(logger_,
+ "Object does not have " << strings::function_id << " key.");
+ return;
+ }
+
+ if (!request[strings::params].keyExists(strings::correlation_id)) {
+ LOG4CXX_ERROR(
+ logger_, "Object does not have " << strings::correlation_id << " key.");
+ return;
+ }
+
+ hmi_apis::FunctionID::eType function_id =
+ static_cast<hmi_apis::FunctionID::eType>(
+ request[strings::params][strings::function_id].asInt());
+
+ if (!Compare<hmi_apis::FunctionID::eType, EQ, ONE>(
+ function_id,
+ hmi_apis::FunctionID::UI_GetLanguage,
+ hmi_apis::FunctionID::VR_GetLanguage,
+ hmi_apis::FunctionID::TTS_GetLanguage)) {
+ LOG4CXX_ERROR(logger_,
+ "Only *GetLanguage request are allowed to be subscribed.");
+ return;
+ }
+
+ uint32_t correlation_id =
+ request[strings::params][strings::correlation_id].asUInt();
+
+ subscribe_on_event(function_id, correlation_id);
+
+ LOG4CXX_DEBUG(logger_,
+ "Subscribed for function_id "
+ << function_id << " and correlation_id " << correlation_id);
+}
+
+void HMILanguageHandler::set_default_capabilities_languages(
+ hmi_apis::Common_Language::eType ui,
+ hmi_apis::Common_Language::eType vr,
+ hmi_apis::Common_Language::eType tts) {
+ capabilities_ui_language_ = ui;
+ if (hmi_apis::Common_Language::INVALID_ENUM == persisted_ui_language_) {
+ persisted_ui_language_ = ui;
+ }
+
+ capabilities_vr_language_ = vr;
+ if (hmi_apis::Common_Language::INVALID_ENUM == persisted_vr_language_) {
+ persisted_vr_language_ = vr;
+ }
+
+ capabilities_tts_language_ = tts;
+ if (hmi_apis::Common_Language::INVALID_ENUM == persisted_tts_language_) {
+ persisted_tts_language_ = tts;
+ }
+}
+
+void HMILanguageHandler::SendOnLanguageChangeToMobile(
+ const uint32_t connection_key) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ smart_objects::SmartObjectSPtr notification = new smart_objects::SmartObject;
+ DCHECK_OR_RETURN_VOID(notification);
+ smart_objects::SmartObject& message = *notification;
+ message[strings::params][strings::function_id] =
+ static_cast<int32_t>(mobile_api::FunctionID::OnLanguageChangeID);
+ message[strings::params][strings::message_type] =
+ static_cast<int32_t>(kNotification);
+ message[strings::params][strings::connection_key] = connection_key;
+
+ HMICapabilities& hmi_capabilities = application_manager_.hmi_capabilities();
+ message[strings::msg_params][strings::hmi_display_language] =
+ hmi_capabilities.active_ui_language();
+ message[strings::msg_params][strings::language] =
+ hmi_capabilities.active_vr_language();
+ if (application_manager_.ManageMobileCommand(notification,
+ commands::Command::ORIGIN_SDL)) {
+ LOG4CXX_INFO(logger_, "Mobile command sent");
+ } else {
+ LOG4CXX_WARN(logger_, "Cannot send mobile command");
+ }
+}
+
+void HMILanguageHandler::VerifyWithPersistedLanguages() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
+ const HMICapabilities& hmi_capabilities =
+ application_manager_.hmi_capabilities();
+
+ // Updated values compared with persisted
+ if (hmi_capabilities.active_ui_language() == persisted_ui_language_ &&
+ hmi_capabilities.active_vr_language() == persisted_vr_language_ &&
+ hmi_capabilities.active_tts_language() == persisted_tts_language_) {
+ LOG4CXX_INFO(logger_,
+ "All languages gotten from HMI match to persisted values.");
+ return;
+ }
+
+ LOG4CXX_INFO(logger_,
+ "Some languages gotten from HMI have "
+ "mismatch with persisted values.");
+
+ const ApplicationSet& accessor =
+ application_manager_.applications().GetData();
+ ApplicationSetIt it = accessor.begin();
+ for (; accessor.end() != it;) {
+ ApplicationConstSharedPtr app = *it++;
+
+ LOG4CXX_INFO(logger_,
+ "Application with app_id "
+ << app->app_id() << " will be unregistered because of "
+ "HMI language(s) mismatch.");
+
+ CheckApplication(std::make_pair(app->app_id(), false));
+ }
+
+ sync_primitives::AutoLock lock(apps_lock_);
+ if (0 == apps_.size()) {
+ LOG4CXX_DEBUG(logger_,
+ "No registered apps found. HMILanguageHandler unsubscribed "
+ "from all events.");
+ unsubscribe_from_all_events();
+ }
+}
+
+void HMILanguageHandler::HandleWrongLanguageApp(const Apps::value_type& app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ {
+ sync_primitives::AutoLock lock(apps_lock_);
+ Apps::iterator it = apps_.find(app.first);
+ if (apps_.end() == it) {
+ LOG4CXX_DEBUG(logger_,
+ "Application id "
+ << app.first
+ << " is not found within apps with wrong language.");
+ return;
+ }
+ apps_.erase(it);
+ if (0 == apps_.size()) {
+ LOG4CXX_DEBUG(logger_,
+ "HMILanguageHandler unsubscribed from all events.");
+ unsubscribe_from_all_events();
+ }
+ }
+ SendOnLanguageChangeToMobile(app.first);
+ application_manager_.ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ app.first,
+ mobile_api::AppInterfaceUnregisteredReason::LANGUAGE_CHANGE),
+ commands::Command::ORIGIN_SDL);
+ application_manager_.UnregisterApplication(
+ app.first, mobile_apis::Result::SUCCESS, false);
+ LOG4CXX_INFO(logger_,
+ "Unregistering application with app_id "
+ << app.first << " because of HMI language(s) mismatch.");
+}
+
+void HMILanguageHandler::CheckApplication(const Apps::value_type app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ bool is_need_handle_wrong_language = false;
+ {
+ sync_primitives::AutoLock lock(apps_lock_);
+ Apps::iterator it = apps_.find(app.first);
+ if (apps_.end() == it) {
+ LOG4CXX_INFO(logger_,
+ "Adding application id "
+ << app.first
+ << " Application registered: " << app.second);
+ apps_.insert(app);
+ return;
+ }
+ is_need_handle_wrong_language = apps_[app.first];
+ }
+ if (is_need_handle_wrong_language) {
+ HandleWrongLanguageApp(app);
+ }
+}
+
+void HMILanguageHandler::Init(resumption::LastState* value) {
+ last_state_ = value;
+ persisted_ui_language_ = get_language_for(INTERFACE_UI);
+ persisted_vr_language_ = get_language_for(INTERFACE_VR);
+ persisted_tts_language_ = get_language_for(INTERFACE_TTS);
+}
+
+void HMILanguageHandler::OnUnregisterApplication(uint32_t app_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(apps_lock_);
+ apps_.erase(app_id);
+}
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/hmi_state.cc b/src/components/application_manager/src/hmi_state.cc
index 2b165c1062..80628f9f33 100644
--- a/src/components/application_manager/src/hmi_state.cc
+++ b/src/components/application_manager/src/hmi_state.cc
@@ -1,65 +1,109 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
#include "application_manager/hmi_state.h"
+#include "application_manager/application_manager.h"
#include "utils/helpers.h"
namespace application_manager {
-HmiState::HmiState(uint32_t app_id, const StateContext& state_context_,
- StateID state_id):
- app_id_(app_id),
- state_id_(state_id),
- state_context_(state_context_),
- hmi_level_(mobile_apis::HMILevel::INVALID_ENUM),
- audio_streaming_state_(mobile_apis::AudioStreamingState::INVALID_ENUM),
- system_context_(mobile_apis::SystemContext::INVALID_ENUM) {
+HmiState::HmiState(uint32_t app_id,
+ const ApplicationManager& app_mngr,
+ StateID state_id)
+ : app_id_(app_id)
+ , state_id_(state_id)
+ , app_mngr_(app_mngr)
+ , hmi_level_(mobile_apis::HMILevel::INVALID_ENUM)
+ , audio_streaming_state_(mobile_apis::AudioStreamingState::INVALID_ENUM)
+ , system_context_(mobile_apis::SystemContext::INVALID_ENUM) {}
+
+HmiState::HmiState(uint32_t app_id, const ApplicationManager& app_mngr)
+ : app_id_(app_id)
+ , state_id_(STATE_ID_REGULAR)
+ , app_mngr_(app_mngr)
+ , hmi_level_(mobile_apis::HMILevel::INVALID_ENUM)
+ , audio_streaming_state_(mobile_apis::AudioStreamingState::INVALID_ENUM)
+ , system_context_(mobile_apis::SystemContext::INVALID_ENUM) {}
+
+void HmiState::set_parent(HmiStatePtr parent) {
+ DCHECK_OR_RETURN_VOID(parent);
+ parent_ = parent;
}
+bool HmiState::is_navi_app(const uint32_t app_id) const {
+ const ApplicationSharedPtr app = app_mngr_.application(app_id);
+ return app ? app->is_navi() : false;
+}
-HmiState::HmiState(uint32_t app_id, const StateContext& state_context):
- app_id_(app_id),
- state_id_(STATE_ID_REGULAR),
- state_context_(state_context),
- hmi_level_(mobile_apis::HMILevel::INVALID_ENUM),
- audio_streaming_state_(mobile_apis::AudioStreamingState::INVALID_ENUM),
- system_context_(mobile_apis::SystemContext::INVALID_ENUM) {
+bool HmiState::is_media_app(const uint32_t app_id) const {
+ const ApplicationSharedPtr app = app_mngr_.application(app_id);
+ return app ? app->is_media_application() : false;
}
-void HmiState::set_parent(HmiStatePtr parent) {
- DCHECK_OR_RETURN_VOID(parent);
- parent_ = parent;
+bool HmiState::is_voice_communication_app(const uint32_t app_id) const {
+ const ApplicationSharedPtr app = app_mngr_.application(app_id);
+ return app ? app->is_voice_communication_supported() : false;
}
-mobile_apis::AudioStreamingState::eType
-VRHmiState::audio_streaming_state() const {
+mobile_apis::AudioStreamingState::eType VRHmiState::audio_streaming_state()
+ const {
using namespace mobile_apis;
return AudioStreamingState::NOT_AUDIBLE;
}
-VRHmiState::VRHmiState(uint32_t app_id, StateContext& state_context):
- HmiState(app_id, state_context, STATE_ID_VR_SESSION) {
-}
+VRHmiState::VRHmiState(uint32_t app_id, const ApplicationManager& app_mngr)
+ : HmiState(app_id, app_mngr, STATE_ID_VR_SESSION) {}
-TTSHmiState::TTSHmiState(uint32_t app_id, StateContext& state_context):
- HmiState(app_id, state_context, STATE_ID_TTS_SESSION) {
-}
+TTSHmiState::TTSHmiState(uint32_t app_id, const ApplicationManager& app_mngr)
+ : HmiState(app_id, app_mngr, STATE_ID_TTS_SESSION) {}
-mobile_apis::AudioStreamingState::eType
-TTSHmiState::audio_streaming_state() const {
+mobile_apis::AudioStreamingState::eType TTSHmiState::audio_streaming_state()
+ const {
using namespace helpers;
using namespace mobile_apis;
AudioStreamingState::eType expected_state = AudioStreamingState::NOT_AUDIBLE;
- if (state_context_.is_attenuated_supported() &&
- AudioStreamingState::NOT_AUDIBLE != parent()->audio_streaming_state() &&
- Compare<HMILevel::eType, EQ, ONE> (hmi_level(), HMILevel::HMI_FULL,
- HMILevel::HMI_LIMITED)) {
+ if (app_mngr_.is_attenuated_supported() &&
+ AudioStreamingState::NOT_AUDIBLE != parent()->audio_streaming_state() &&
+ Compare<HMILevel::eType, EQ, ONE>(
+ hmi_level(), HMILevel::HMI_FULL, HMILevel::HMI_LIMITED)) {
expected_state = AudioStreamingState::ATTENUATED;
}
return expected_state;
}
-NaviStreamingHmiState::NaviStreamingHmiState(uint32_t app_id, StateContext& state_context):
- HmiState(app_id, state_context, STATE_ID_NAVI_STREAMING) {
-}
+NaviStreamingHmiState::NaviStreamingHmiState(uint32_t app_id,
+ const ApplicationManager& app_mngr)
+ : HmiState(app_id, app_mngr, STATE_ID_NAVI_STREAMING) {}
mobile_apis::AudioStreamingState::eType
NaviStreamingHmiState::audio_streaming_state() const {
@@ -67,9 +111,8 @@ NaviStreamingHmiState::audio_streaming_state() const {
using namespace mobile_apis;
AudioStreamingState::eType expected_state = parent()->audio_streaming_state();
- if (!state_context_.is_navi_app(app_id_) &&
- AudioStreamingState::AUDIBLE == expected_state) {
- if (state_context_.is_attenuated_supported()) {
+ if (!is_navi_app(app_id_) && AudioStreamingState::AUDIBLE == expected_state) {
+ if (app_mngr_.is_attenuated_supported()) {
expected_state = AudioStreamingState::ATTENUATED;
} else {
expected_state = AudioStreamingState::NOT_AUDIBLE;
@@ -78,22 +121,80 @@ NaviStreamingHmiState::audio_streaming_state() const {
return expected_state;
}
-PhoneCallHmiState::PhoneCallHmiState(uint32_t app_id, StateContext& state_context):
- HmiState(app_id, state_context, STATE_ID_PHONE_CALL) {
-}
+PhoneCallHmiState::PhoneCallHmiState(uint32_t app_id,
+ const ApplicationManager& app_mngr)
+ : HmiState(app_id, app_mngr, STATE_ID_PHONE_CALL) {}
mobile_apis::HMILevel::eType PhoneCallHmiState::hmi_level() const {
+ using namespace helpers;
using namespace mobile_apis;
- HMILevel::eType expected_level(HMILevel::HMI_BACKGROUND);
- if (parent()->hmi_level() == HMILevel::HMI_FULL
- && state_context_.is_navi_app(app_id_)) {
- expected_level = HMILevel::HMI_LIMITED;
- }
- return expected_level;
+ if (Compare<HMILevel::eType, EQ, ONE>(parent()->hmi_level(),
+ HMILevel::HMI_BACKGROUND,
+ HMILevel::HMI_NONE)) {
+ return parent()->hmi_level();
+ }
+ if (is_navi_app(app_id_)) {
+ return HMILevel::HMI_LIMITED;
+ }
+ if (!is_media_app(app_id_)) {
+ return parent()->hmi_level();
+ }
+ return HMILevel::HMI_BACKGROUND;
}
-SafetyModeHmiState::SafetyModeHmiState(uint32_t app_id, StateContext& state_context):
- HmiState(app_id, state_context, STATE_ID_SAFETY_MODE) {
+SafetyModeHmiState::SafetyModeHmiState(uint32_t app_id,
+ const ApplicationManager& app_mngr)
+ : HmiState(app_id, app_mngr, STATE_ID_SAFETY_MODE) {}
+
+DeactivateHMI::DeactivateHMI(uint32_t app_id,
+ const ApplicationManager& app_mngr)
+ : HmiState(app_id, app_mngr, STATE_ID_DEACTIVATE_HMI) {}
+
+mobile_apis::HMILevel::eType DeactivateHMI::hmi_level() const {
+ using namespace helpers;
+ using namespace mobile_apis;
+ if (Compare<HMILevel::eType, EQ, ONE>(parent()->hmi_level(),
+ HMILevel::HMI_BACKGROUND,
+ HMILevel::HMI_NONE)) {
+ return parent()->hmi_level();
+ }
+ return HMILevel::HMI_BACKGROUND;
+}
+
+AudioSource::AudioSource(uint32_t app_id, const ApplicationManager& app_mngr)
+ : HmiState(app_id, app_mngr, STATE_ID_AUDIO_SOURCE) {}
+
+mobile_apis::HMILevel::eType AudioSource::hmi_level() const {
+ using namespace mobile_apis;
+ using namespace helpers;
+ // TODO(AOleynik): That NONE check is necessary to avoid issue during
+ // calculation of HMI level during setting default HMI level
+ // Should be investigated (used in multiple places here), since looks weird
+ if (Compare<HMILevel::eType, EQ, ONE>(parent()->hmi_level(),
+ HMILevel::HMI_BACKGROUND,
+ HMILevel::HMI_NONE)) {
+ return parent()->hmi_level();
+ }
+ if (is_navi_app(app_id_)) {
+ return HMILevel::HMI_LIMITED;
+ }
+ return HMILevel::HMI_BACKGROUND;
}
+EmbeddedNavi::EmbeddedNavi(uint32_t app_id, const ApplicationManager& app_mngr)
+ : HmiState(app_id, app_mngr, STATE_ID_EMBEDDED_NAVI) {}
+
+mobile_apis::HMILevel::eType EmbeddedNavi::hmi_level() const {
+ using namespace mobile_apis;
+ using namespace helpers;
+ if (Compare<HMILevel::eType, EQ, ONE>(parent()->hmi_level(),
+ HMILevel::HMI_BACKGROUND,
+ HMILevel::HMI_NONE)) {
+ return parent()->hmi_level();
+ }
+ if (is_media_app(app_id_)) {
+ return HMILevel::HMI_LIMITED;
+ }
+ return HMILevel::HMI_BACKGROUND;
+}
}
diff --git a/src/components/application_manager/src/message.cc b/src/components/application_manager/src/message.cc
index bb500687dd..a7c887d348 100644
--- a/src/components/application_manager/src/message.cc
+++ b/src/components/application_manager/src/message.cc
@@ -56,19 +56,17 @@ MessageType MessageTypeFromRpcType(protocol_handler::RpcType rpc_type) {
}
Message::Message(protocol_handler::MessagePriority priority)
- : function_id_(0),
- correlation_id_(0),
- type_(kUnknownType),
- priority_(priority),
- connection_key_(0),
- binary_data_(NULL),
- data_size_(0),
- payload_size_(0),
- version_(kUnknownProtocol) {
-}
-
-Message::Message(const Message& message)
- : priority_(message.priority_) {
+ : function_id_(0)
+ , correlation_id_(0)
+ , type_(kUnknownType)
+ , priority_(priority)
+ , connection_key_(0)
+ , binary_data_(NULL)
+ , data_size_(0)
+ , payload_size_(0)
+ , version_(kUnknownProtocol) {}
+
+Message::Message(const Message& message) : priority_(message.priority_) {
*this = message;
}
@@ -99,13 +97,13 @@ bool Message::operator==(const Message& message) {
bool data_size = data_size_ == message.data_size_;
bool payload_size = payload_size_ == message.payload_size_;
-
- bool binary_data = std::equal(binary_data_->begin(), binary_data_->end(),
+ bool binary_data = std::equal(binary_data_->begin(),
+ binary_data_->end(),
message.binary_data_->begin(),
BinaryDataPredicate);
- return function_id && correlation_id && connection_key && type && binary_data
- && json_message && version && data_size && payload_size;
+ return function_id && correlation_id && connection_key && type &&
+ binary_data && json_message && version && data_size && payload_size;
}
Message::~Message() {
@@ -191,7 +189,7 @@ void Message::set_protocol_version(ProtocolVersion version) {
version_ = version;
}
-const smart_objects::SmartObject &Message::smart_object() const {
+const smart_objects::SmartObject& Message::smart_object() const {
return smart_object_;
}
diff --git a/src/components/application_manager/src/message_helper.cc b/src/components/application_manager/src/message_helper.cc
deleted file mode 100644
index fd42305f77..0000000000
--- a/src/components/application_manager/src/message_helper.cc
+++ /dev/null
@@ -1,2620 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "application_manager/message_helper.h"
-
-#define __STDC_FORMAT_MACROS
-#include <inttypes.h>
-#undef __STDC_FORMAT_MACROS
-
-#include <set>
-#include <string>
-#include <algorithm>
-#include <utility>
-#include <map>
-
-#include "application_manager/application.h"
-#include "application_manager/application_manager_impl.h"
-#include "application_manager/commands/command_impl.h"
-#include "application_manager/policies/policy_handler.h"
-#include "config_profile/profile.h"
-#include "connection_handler/connection_handler_impl.h"
-#include "interfaces/MOBILE_API.h"
-#include "smart_objects/enum_schema_item.h"
-#include "utils/file_system.h"
-#include "utils/macro.h"
-#include "utils/make_shared.h"
-#include "utils/logger.h"
-#include "utils/make_shared.h"
-
-#include "formatters/formatter_json_rpc.h"
-#include "formatters/CFormatterJsonSDLRPCv2.hpp"
-#include "formatters/CFormatterJsonSDLRPCv1.hpp"
-
-namespace application_manager {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationManager")
-
-namespace {
-
-typedef
-std::map<std::string, hmi_apis::Common_AppPriority::eType> CommonAppPriorityMap;
-
-CommonAppPriorityMap app_priority_values = {
- {"NORMAL", hmi_apis::Common_AppPriority::NORMAL},
- {"COMMUNICATION", hmi_apis::Common_AppPriority::COMMUNICATION},
- {"EMERGENCY", hmi_apis::Common_AppPriority::EMERGENCY},
- {"NAVIGATION", hmi_apis::Common_AppPriority::NAVIGATION},
- {"NONE", hmi_apis::Common_AppPriority::NONE},
- {"VOICECOM", hmi_apis::Common_AppPriority::VOICE_COMMUNICATION},
- {"INVALID_ENUM", hmi_apis::Common_AppPriority::INVALID_ENUM}
-};
-
-const uint32_t GetPriorityCode(const std::string& priority) {
- CommonAppPriorityMap::const_iterator it = app_priority_values.find(priority);
- if (app_priority_values.end() != it) {
- return static_cast<uint32_t>((*it).second);
- }
- return static_cast<uint32_t>(hmi_apis::Common_AppPriority::INVALID_ENUM);
-}
-
-bool ValidateSoftButtons(smart_objects::SmartObject& soft_buttons) {
- using namespace smart_objects;
- for (size_t i = 0; i < soft_buttons.length(); ++i) {
- SmartObject& button = soft_buttons[i];
-
- // Check if image parameter is valid
- if (button.keyExists(strings::image)) {
- SmartObject& buttonImage = button[strings::image];
-
- // Image name must not be empty and must not contain incorrect
- //character
- if (false == MessageHelper::VerifySoftButtonString(
- buttonImage[strings::value].asString())) {
- return false;
- }
- }
- }
- return true;
-} // namespace
-
-}
-std::pair<std::string, VehicleDataType> kVehicleDataInitializer[] = {
- std::make_pair(strings::gps, VehicleDataType::GPS), std::make_pair(
- strings::speed, VehicleDataType::SPEED), std::make_pair(
- strings::rpm, VehicleDataType::RPM), std::make_pair(
- strings::fuel_level, VehicleDataType::FUELLEVEL), std::make_pair(
- strings::fuel_level_state, VehicleDataType::FUELLEVEL_STATE),
- std::make_pair(strings::instant_fuel_consumption,
- VehicleDataType::FUELCONSUMPTION), std::make_pair(
- strings::external_temp, VehicleDataType::EXTERNTEMP), std::make_pair(
- strings::vin, VehicleDataType::VIN), std::make_pair(
- strings::prndl, VehicleDataType::PRNDL), std::make_pair(
- strings::tire_pressure, VehicleDataType::TIREPRESSURE), std::make_pair(
- strings::odometer, VehicleDataType::ODOMETER), std::make_pair(
- strings::belt_status, VehicleDataType::BELTSTATUS), std::make_pair(
- strings::body_information, VehicleDataType::BODYINFO), std::make_pair(
- strings::device_status, VehicleDataType::DEVICESTATUS), std::make_pair(
- strings::driver_braking, VehicleDataType::BRAKING), std::make_pair(
- strings::wiper_status, VehicleDataType::WIPERSTATUS), std::make_pair(
- strings::head_lamp_status, VehicleDataType::HEADLAMPSTATUS),
- std::make_pair(strings::e_call_info, VehicleDataType::ECALLINFO),
- std::make_pair(strings::airbag_status, VehicleDataType::AIRBAGSTATUS),
- std::make_pair(strings::emergency_event, VehicleDataType::EMERGENCYEVENT),
- std::make_pair(strings::cluster_mode_status,
- VehicleDataType::CLUSTERMODESTATUS), std::make_pair(
- strings::my_key, VehicleDataType::MYKEY),
- /*
- NOT DEFINED in mobile API
- std::make_pair(strings::gps, VehicleDataType::BATTVOLTAGE),
- */
- std::make_pair(strings::engine_torque, VehicleDataType::ENGINETORQUE),
- std::make_pair(strings::acc_pedal_pos, VehicleDataType::ACCPEDAL),
- std::make_pair(strings::steering_wheel_angle,
- VehicleDataType::STEERINGWHEEL),
-};
-
-const VehicleData MessageHelper::vehicle_data_(
- kVehicleDataInitializer, kVehicleDataInitializer +
- ARRAYSIZE(kVehicleDataInitializer));
-
-#ifdef HMI_DBUS_API
-namespace {
-struct VehicleInfo_Requests {
- hmi_apis::FunctionID::eType func_id;
- const char* str;
-};
-static VehicleInfo_Requests ivi_subrequests[] = {
- { hmi_apis::FunctionID::VehicleInfo_SubscribeGps, strings::gps},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeSpeed, strings::speed},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeRpm, strings::rpm},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel, strings::fuel_level},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel_State, strings::fuel_level_state},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeInstantFuelConsumption, strings::instant_fuel_consumption},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeExternalTemperature, strings::external_temp},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeVin, strings::vin},
- { hmi_apis::FunctionID::VehicleInfo_SubscribePrndl, strings::prndl},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeTirePressure, strings::tire_pressure},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeOdometer, strings::odometer},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeBeltStatus, strings::belt_status},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeBodyInformation, strings::body_information},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeDeviceStatus, strings::device_status},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeDriverBraking, strings::driver_braking},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeWiperStatus, strings::wiper_status},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeHeadLampStatus, strings::head_lamp_status},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeEngineTorque, strings::engine_torque},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeAccPedalPosition, strings::acc_pedal_pos},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeSteeringWheelAngle, strings::steering_wheel_angle},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeECallInfo, strings::e_call_info},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeAirbagStatus, strings::airbag_status},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeEmergencyEvent, strings::emergency_event},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeClusterModeStatus, strings::cluster_mode_status},
- { hmi_apis::FunctionID::VehicleInfo_SubscribeMyKey, strings::my_key},
-};
-}
-#endif // #ifdef HMI_DBUS_API
-
-std::string MessageHelper::CommonLanguageToString(
- hmi_apis::Common_Language::eType language) {
- using namespace NsSmartDeviceLink::NsSmartObjects;
- const char* str = 0;
- if (EnumConversionHelper<hmi_apis::Common_Language::eType>::EnumToCString(
- language, &str)) {
- return str ? str : "";
- }
- return std::string();
-}
-
-hmi_apis::Common_Language::eType MessageHelper::CommonLanguageFromString(
- const std::string& language) {
- using namespace NsSmartDeviceLink::NsSmartObjects;
- hmi_apis::Common_Language::eType value;
- if (EnumConversionHelper<hmi_apis::Common_Language::eType>::StringToEnum(
- language, &value)) {
- return value;
- }
- return hmi_apis::Common_Language::INVALID_ENUM;
-}
-
-uint32_t MessageHelper::GetAppCommandLimit(const std::string& policy_app_id) {
-
- std::string priority;
- policy::PolicyHandler::instance()->GetPriority(policy_app_id, &priority);
- return policy::PolicyHandler::instance()->GetNotificationsNumber(priority);
-}
-
-void MessageHelper::SendHMIStatusNotification(
- const Application& application_impl) {
- LOG4CXX_AUTO_TRACE(logger_);
- smart_objects::SmartObjectSPtr notification = new smart_objects::SmartObject;
- if (!notification) {
- // TODO(VS): please add logger.
- return;
- }
- smart_objects::SmartObject& message = *notification;
-
- message[strings::params][strings::function_id] =
- static_cast<int32_t>(mobile_api::FunctionID::OnHMIStatusID);
-
- message[strings::params][strings::message_type] =
- static_cast<int32_t>(application_manager::MessageType::kNotification);
-
- message[strings::params][strings::connection_key] =
- static_cast<int32_t>(application_impl.app_id());
-
- message[strings::msg_params][strings::hmi_level] =
- static_cast<int32_t>(application_impl.hmi_level());
-
- message[strings::msg_params][strings::audio_streaming_state] =
- static_cast<int32_t>(application_impl.audio_streaming_state());
-
- message[strings::msg_params][strings::system_context] =
- static_cast<int32_t>(application_impl.system_context());
-
- ApplicationManagerImpl::instance()->ManageMobileCommand(notification);
-}
-
-void MessageHelper::SendOnAppRegisteredNotificationToHMI(
- const Application& application_impl, bool resumption, bool need_restore_vr) {
- using namespace smart_objects;
-
- SmartObjectSPtr notification = utils::MakeShared<SmartObject>(SmartType_Map);
- if (!notification) {
- LOG4CXX_ERROR(logger_, "Failed to create smart object");
- return;
- }
-
- (*notification)[strings::params] = SmartObject(SmartType_Map);
- smart_objects::SmartObject& params = (*notification)[strings::params];
- params[strings::function_id] =
- static_cast<int32_t>(hmi_apis::FunctionID::BasicCommunication_OnAppRegistered);
- params[strings::message_type] = static_cast<int32_t>(kNotification);
- params[strings::protocol_version] = commands::CommandImpl::protocol_version_;
- params[strings::protocol_type] = commands::CommandImpl::hmi_protocol_type_;
-
- (*notification)[strings::msg_params] = SmartObject(SmartType_Map);
- smart_objects::SmartObject& msg_params = (*notification)[strings::msg_params];
- // Due to current requirements in case when we're in resumption mode
- // we have to always send resumeVRGrammar field.
- if (resumption) {
- msg_params[strings::resume_vr_grammars] = need_restore_vr;
- }
-
- if (application_impl.vr_synonyms()) {
- msg_params[strings::vr_synonyms] = *(application_impl.vr_synonyms());
- }
-
- if (application_impl.tts_name()) {
- msg_params[strings::tts_name] = *(application_impl.tts_name());
- }
-
- std::string priority;
- policy::PolicyHandler::instance()->GetPriority(
- application_impl.mobile_app_id(), &priority);
- if (!priority.empty()) {
- msg_params[strings::priority] = GetPriorityCode(priority);
- }
-
- smart_objects::SmartObject& application = msg_params[strings::application];
- application[strings::app_name] = application_impl.name();
- application[strings::app_id] = application_impl.app_id();
- application[hmi_response::policy_app_id] = application_impl.mobile_app_id();
- application[strings::icon] = application_impl.app_icon_path();
-
- const smart_objects::SmartObject* ngn_media_screen_name =
- application_impl.ngn_media_screen_name();
- if (ngn_media_screen_name) {
- application[strings::ngn_media_screen_app_name] = *ngn_media_screen_name;
- }
-
- application[strings::hmi_display_language_desired] =
- static_cast<int32_t>(application_impl.ui_language());
-
- application[strings::is_media_application] = application_impl.is_media_application();
-
- const smart_objects::SmartObject* app_type = application_impl.app_types();
-
- if (app_type) {
- application[strings::app_type] = *app_type;
- }
- if (application_impl.IsRegistered()) {
- std::vector<std::string> request_types =
- policy::PolicyHandler::instance()->GetAppRequestTypes(
- application_impl.mobile_app_id());
-
- application[strings::request_type] = SmartObject(SmartType_Array);
- smart_objects::SmartObject& request_array = application[strings::request_type];
-
- uint32_t index = 0;
- std::vector<std::string>::const_iterator it = request_types.begin();
- for (; request_types.end() != it; ++it) {
- request_array[index] = *it;
- ++index;
- }
- }
-
- application[strings::device_info] = SmartObject(SmartType_Map);
- smart_objects::SmartObject& device_info = application[strings::device_info];
- std::string device_name;
- std::string mac_address;
- std::string transport_type;
- if (-1 == connection_handler::ConnectionHandlerImpl::instance()->
- GetDataOnDeviceID(application_impl.device(), &device_name,
- NULL, &mac_address, &transport_type)) {
- LOG4CXX_ERROR(logger_, "Failed to extract information for device "
- << application_impl.device());
- }
- device_info[strings::name] = device_name;
- device_info[strings::id] = mac_address;
-
- const policy::DeviceConsent device_consent =
- policy::PolicyHandler::instance()->GetUserConsentForDevice(mac_address);
- device_info[strings::isSDLAllowed] =
- policy::DeviceConsent::kDeviceAllowed == device_consent;
-
- device_info[strings::transport_type] =
- ApplicationManagerImpl::instance()->GetDeviceTransportType(transport_type);
-
- DCHECK(ApplicationManagerImpl::instance()->ManageHMICommand(notification));
-}
-
-smart_objects::SmartObjectSPtr MessageHelper::GetHashUpdateNotification(
- const uint32_t app_id) {
-
- LOG4CXX_INFO(logger_, "GetHashUpdateNotification" << app_id);
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
- app_id);
-
- if (!app) {
- return NULL;
- }
-
- smart_objects::SmartObjectSPtr message = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- (*message)[strings::params][strings::function_id] =
- mobile_apis::FunctionID::OnHashChangeID;
- (*message)[strings::params][strings::connection_key] = app_id;
- (*message)[strings::params][strings::message_type] =
- static_cast<int32_t>(kNotification);
-
- return message;
-}
-
-smart_objects::SmartObject* MessageHelper::GetLockScreenIconUrlNotification(const uint32_t connection_key) {
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(connection_key);
- DCHECK(app.get());
-
- smart_objects::SmartObject* message = new smart_objects::SmartObject(smart_objects::SmartType_Map);
- (*message)[strings::params][strings::function_id] = mobile_apis::FunctionID::OnSystemRequestID;
- (*message)[strings::params][strings::connection_key] = connection_key;
- (*message)[strings::params][strings::message_type] = mobile_apis::messageType::notification;
- (*message)[strings::params][strings::protocol_type] = commands::CommandImpl::mobile_protocol_type_;
- (*message)[strings::params][strings::protocol_version] = commands::CommandImpl::protocol_version_;
-
- (*message)[strings::msg_params][strings::request_type] = mobile_apis::RequestType::LOCK_SCREEN_ICON_URL;
-
- (*message)[strings::msg_params][strings::url] = policy::PolicyHandler::instance()->GetLockScreenIconUrl();
-
-
- return message;
-}
-
-void MessageHelper::SendLockScreenIconUrlNotification(const uint32_t connection_key) {
- LOG4CXX_INFO(logger_, "SendLockScreenIconUrlNotification");
-
- smart_objects::SmartObject* so = GetLockScreenIconUrlNotification(connection_key);
- PrintSmartObject(*so);
- DCHECK(ApplicationManagerImpl::instance()->ManageMobileCommand(so));
-}
-
-void MessageHelper::SendHashUpdateNotification(const uint32_t app_id) {
- LOG4CXX_AUTO_TRACE(logger_);
-
- smart_objects::SmartObjectSPtr so = GetHashUpdateNotification(app_id);
- if (so) {
- PrintSmartObject(*so);
- if (!ApplicationManagerImpl::instance()->ManageMobileCommand(so)) {
- LOG4CXX_ERROR_EXT(logger_, "Failed to send HashUpdate notification.");
- } else {
- ApplicationManagerImpl::instance()->resume_controller().ApplicationsDataUpdated();
- }
- }
-}
-
-void MessageHelper::SendOnAppInterfaceUnregisteredNotificationToMobile(
- int32_t connection_key,
- mobile_api::AppInterfaceUnregisteredReason::eType reason) {
-
- LOG4CXX_AUTO_TRACE(logger_);
-
- smart_objects::SmartObjectSPtr notification = new smart_objects::SmartObject;
- DCHECK(notification);
- smart_objects::SmartObject& message = *notification;
-
- message[strings::params][strings::function_id] =
- static_cast<int32_t>(mobile_api::FunctionID::OnAppInterfaceUnregisteredID);
-
- message[strings::params][strings::message_type] =
- static_cast<int32_t>(kNotification);
-
- message[strings::params][strings::connection_key] = connection_key;
-
- message[strings::msg_params][strings::reason] = static_cast<int32_t>(reason);
-
- if (ApplicationManagerImpl::instance()->ManageMobileCommand(notification)) {
- LOG4CXX_DEBUG(logger_, "Mobile command sent");
- }
- else {
- LOG4CXX_WARN(logger_, "Cannot send mobile command");
- }
-}
-
-const VehicleData& MessageHelper::vehicle_data() {
- return vehicle_data_;
-}
-
-mobile_apis::HMILevel::eType MessageHelper::StringToHMILevel(
- const std::string& hmi_level) {
- using namespace NsSmartDeviceLink::NsSmartObjects;
- mobile_apis::HMILevel::eType value;
- if (EnumConversionHelper<mobile_apis::HMILevel::eType>::StringToEnum(
- hmi_level, &value)) {
- return value;
- }
- return mobile_apis::HMILevel::INVALID_ENUM;
-}
-
-std::string MessageHelper::StringifiedHMILevel(
- mobile_apis::HMILevel::eType hmi_level) {
- using namespace NsSmartDeviceLink::NsSmartObjects;
- const char* str = 0;
- if (EnumConversionHelper<mobile_apis::HMILevel::eType>::EnumToCString(
- hmi_level, &str)) {
- return str;
- }
- return std::string();
-}
-
-std::string MessageHelper::StringifiedFunctionID(
- mobile_apis::FunctionID::eType function_id) {
- LOG4CXX_AUTO_TRACE(logger_);
- using namespace NsSmartDeviceLink::NsSmartObjects;
- const char* str = 0;
- if (EnumConversionHelper<mobile_apis::FunctionID::eType>::EnumToCString(
- function_id, &str)) {
- const std::string enum_name = str;
- // Strip 'ID' suffix from value name
- DCHECK(enum_name.length() > 2
- && enum_name.substr(enum_name.length() - 2) == "ID");
- return enum_name.substr(0, enum_name.length() - 2);
- }
- return std::string();
-}
-
-#ifdef HMI_DBUS_API
-namespace {
-const std::map<std::string, uint16_t> create_get_vehicle_data_args() {
- std::map<std::string, uint16_t> rc;
- rc.insert(std::make_pair(strings::gps, hmi_apis::FunctionID::VehicleInfo_GetGpsData));
- rc.insert(std::make_pair(strings::speed, hmi_apis::FunctionID::VehicleInfo_GetSpeed));
- rc.insert(std::make_pair(strings::rpm, hmi_apis::FunctionID::VehicleInfo_GetRpm));
- rc.insert(std::make_pair(strings::fuel_level, hmi_apis::FunctionID::VehicleInfo_GetFuelLevel));
- rc.insert(std::make_pair(strings::fuel_level_state, hmi_apis::FunctionID::VehicleInfo_GetFuelLevelState));
- rc.insert(std::make_pair(strings::instant_fuel_consumption, hmi_apis::FunctionID::VehicleInfo_GetInstantFuelConsumption));
- rc.insert(std::make_pair(strings::external_temp, hmi_apis::FunctionID::VehicleInfo_GetExternalTemperature));
- rc.insert(std::make_pair(strings::vin, hmi_apis::FunctionID::VehicleInfo_GetVin));
- rc.insert(std::make_pair(strings::prndl, hmi_apis::FunctionID::VehicleInfo_GetPrndl));
- rc.insert(std::make_pair(strings::tire_pressure, hmi_apis::FunctionID::VehicleInfo_GetTirePressure));
- rc.insert(std::make_pair(strings::odometer, hmi_apis::FunctionID::VehicleInfo_GetOdometer));
- rc.insert(std::make_pair(strings::belt_status, hmi_apis::FunctionID::VehicleInfo_GetBeltStatus));
- rc.insert(std::make_pair(strings::body_information, hmi_apis::FunctionID::VehicleInfo_GetBodyInformation));
- rc.insert(std::make_pair(strings::device_status, hmi_apis::FunctionID::VehicleInfo_GetDeviceStatus));
- rc.insert(std::make_pair(strings::driver_braking, hmi_apis::FunctionID::VehicleInfo_GetDriverBraking));
- rc.insert(std::make_pair(strings::wiper_status, hmi_apis::FunctionID::VehicleInfo_GetWiperStatus));
- rc.insert(std::make_pair(strings::head_lamp_status, hmi_apis::FunctionID::VehicleInfo_GetHeadLampStatus));
- rc.insert(std::make_pair(strings::engine_torque, hmi_apis::FunctionID::VehicleInfo_GetEngineTorque));
- rc.insert(std::make_pair(strings::acc_pedal_pos, hmi_apis::FunctionID::VehicleInfo_GetAccPedalPosition));
- rc.insert(std::make_pair(strings::steering_wheel_angle, hmi_apis::FunctionID::VehicleInfo_GetSteeringWheelAngle));
- rc.insert(std::make_pair(strings::e_call_info, hmi_apis::FunctionID::VehicleInfo_GetECallInfo));
- rc.insert(std::make_pair(strings::airbag_status, hmi_apis::FunctionID::VehicleInfo_GetAirbagStatus));
- rc.insert(std::make_pair(strings::emergency_event, hmi_apis::FunctionID::VehicleInfo_GetEmergencyEvent));
- rc.insert(std::make_pair(strings::cluster_mode_status, hmi_apis::FunctionID::VehicleInfo_GetClusterModeStatus));
- rc.insert(std::make_pair(strings::my_key, hmi_apis::FunctionID::VehicleInfo_GetMyKey));
- return rc;
-}
-static std::map<std::string, uint16_t> vehicle_data_args = create_get_vehicle_data_args();
-}
-#endif
-
-void MessageHelper::CreateGetVehicleDataRequest(
- uint32_t correlation_id, const std::vector<std::string>& params) {
- LOG4CXX_AUTO_TRACE(logger_);
-#ifdef HMI_DBUS_API
- for (std::vector<std::string>::const_iterator it = params.begin();
- it != params.end(); it++) {
- smart_objects::SmartObjectSPtr request = new smart_objects::SmartObject;
-
- (*request)[strings::params][strings::message_type] = static_cast<int>(kRequest);
- (*request)[strings::params][strings::correlation_id] = correlation_id;
- (*request)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*request)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- (*request)[strings::params][strings::function_id] =
- static_cast<int>(vehicle_data_args[*it]);
- ApplicationManagerImpl::instance()->ManageHMICommand(request);
- }
-#else
- smart_objects::SmartObjectSPtr request = new smart_objects::SmartObject;
-
- (*request)[strings::params][strings::message_type] = static_cast<int>(kRequest);
- (*request)[strings::params][strings::function_id] =
- static_cast<int>(hmi_apis::FunctionID::VehicleInfo_GetVehicleData);
- (*request)[strings::params][strings::correlation_id] = correlation_id;
- (*request)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*request)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- (*request)[strings::msg_params] = smart_objects::SmartObject(smart_objects::SmartType_Map);
- for (std::vector<std::string>::const_iterator it = params.begin();
- it != params.end(); it++) {
- (*request)[strings::msg_params][*it] = true;
- }
- ApplicationManagerImpl::instance()->ManageHMICommand(request);
-#endif
-}
-
-smart_objects::SmartObjectSPtr MessageHelper::CreateBlockedByPoliciesResponse(
- mobile_apis::FunctionID::eType function_id,
- mobile_apis::Result::eType result, uint32_t correlation_id,
- uint32_t connection_key) {
- LOG4CXX_AUTO_TRACE(logger_);
- smart_objects::SmartObjectSPtr response = new smart_objects::SmartObject;
-
- (*response)[strings::params][strings::function_id] =
- static_cast<int>(function_id);
- (*response)[strings::params][strings::message_type] =
- static_cast<int>(kResponse);
- (*response)[strings::msg_params][strings::success] = false;
- (*response)[strings::msg_params][strings::result_code] =
- static_cast<int>(result);
- (*response)[strings::params][strings::correlation_id] = correlation_id;
- (*response)[strings::params][strings::connection_key] = connection_key;
- (*response)[strings::params][strings::protocol_type] =
- commands::CommandImpl::mobile_protocol_type_;
- (*response)[strings::params][strings::protocol_version] =
- static_cast<int>(kV2);
- return response;
-}
-
-smart_objects::SmartObjectSPtr MessageHelper::CreateDeviceListSO(
- const connection_handler::DeviceMap& devices) {
- LOG4CXX_AUTO_TRACE(logger_);
- smart_objects::SmartObjectSPtr device_list_so =
- new smart_objects::SmartObject(smart_objects::SmartType_Map);
-
- (*device_list_so)[strings::device_list] = smart_objects::SmartObject(
- smart_objects::SmartType_Array);
- smart_objects::SmartObject& list_so = (*device_list_so)[strings::device_list];
-
- int32_t index = 0;
- for (connection_handler::DeviceMap::const_iterator it = devices.begin();
- devices.end() != it; ++it) {
- const connection_handler::Device& d =
- static_cast<connection_handler::Device>(it->second);
- list_so[index][strings::name] = d.user_friendly_name();
- list_so[index][strings::id] = it->second.mac_address();
-
- const policy::DeviceConsent device_consent =
- policy::PolicyHandler::instance()->GetUserConsentForDevice(it->second.mac_address());
- list_so[index][strings::isSDLAllowed] =
- policy::DeviceConsent::kDeviceAllowed == device_consent;
- list_so[index][strings::transport_type] =
- ApplicationManagerImpl::instance()->GetDeviceTransportType(d.connection_type());
- ++index;
- }
- return device_list_so;
-}
-
-smart_objects::SmartObjectSPtr MessageHelper::CreateModuleInfoSO(
- uint32_t function_id) {
- LOG4CXX_AUTO_TRACE(logger_);
- smart_objects::SmartObjectSPtr module_info = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- smart_objects::SmartObject& object = *module_info;
- object[strings::params][strings::message_type] = static_cast<int>(kRequest);
- object[strings::params][strings::function_id] = static_cast<int>(function_id);
- object[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
- object[strings::msg_params] = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- return module_info;
-}
-
-smart_objects::SmartObjectSPtr MessageHelper::CreateSetAppIcon(
- const std::string& path_to_icon, uint32_t app_id) {
- LOG4CXX_AUTO_TRACE(logger_);
- smart_objects::SmartObjectSPtr set_icon = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- if (!set_icon) {
- return NULL;
- }
-
- smart_objects::SmartObject& object = *set_icon;
- object[strings::sync_file_name][strings::value] = path_to_icon;
- // TODO(PV): need to store actual image type
- object[strings::sync_file_name][strings::image_type] =
- static_cast<int>(mobile_api::ImageType::DYNAMIC);
- object[strings::app_id] = app_id;
-
- return set_icon;
-}
-
-bool MessageHelper::SendIVISubscribtions(const uint32_t app_id) {
- LOG4CXX_AUTO_TRACE(logger_);
-
- bool result = true;
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(
- app_id);
-
- if (!app.valid()) {
- LOG4CXX_ERROR(logger_, "Invalid application " << app_id);
- return result;
- }
-
- smart_objects::SmartObjectList requests = GetIVISubscriptionRequests(app);
- for (smart_objects::SmartObjectList::const_iterator it = requests.begin();
- it != requests.end(); ++it) {
- if (!ApplicationManagerImpl::instance()->ManageHMICommand(*it)) {
- result = false;
- }
- }
- return result;
-}
-
-smart_objects::SmartObjectList MessageHelper::GetIVISubscriptionRequests(
- ApplicationSharedPtr app) {
- LOG4CXX_AUTO_TRACE(logger_);
-
- smart_objects::SmartObjectList hmi_requests;
- if (!app.valid()) {
- LOG4CXX_ERROR(logger_, "Invalid application pointer ");
- return hmi_requests;
- }
-
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- msg_params[strings::app_id] = app->app_id();
- const VehicleData& vehicle_data = MessageHelper::vehicle_data_;
- VehicleData::const_iterator ivi_it = vehicle_data.begin();
- const std::set<uint32_t>& subscribes = app->SubscribesIVI();
-
- for (; vehicle_data.end() != ivi_it; ++ivi_it) {
- uint32_t type_id = static_cast<int>(ivi_it->second);
- if (subscribes.end() != subscribes.find(type_id)) {
- std::string key_name = ivi_it->first;
- msg_params[key_name] = true;
- }
- }
-
-#ifdef HMI_JSON_API
- smart_objects::SmartObjectSPtr request = MessageHelper::CreateModuleInfoSO(
- hmi_apis::FunctionID::VehicleInfo_SubscribeVehicleData);
- (*request)[strings::msg_params] = msg_params;
- hmi_requests.push_back(request);
-#endif // #ifdef HMI_JSON_API
-#ifdef HMI_DBUS_API
- //Generate list of ivi_subrequests
- for (size_t i = 0; i < sizeof(ivi_subrequests) / sizeof(ivi_subrequests[0]); ++i) {
- const VehicleInfo_Requests& sr = ivi_subrequests[i];
- if (true == msg_params.keyExists(sr.str)
- && true == msg_params[sr.str].asBool()) {
- smart_objects::SmartObjectSPtr request = MessageHelper::CreateModuleInfoSO(
- sr.func_id);
- (*request)[strings::msg_params] = msg_params;
- hmi_requests.push_back(request);
- }
- }
-#endif // #ifdef HMI_DBUS_API
- return hmi_requests;
-}
-
-void MessageHelper::SendOnButtonSubscriptionNotification(
- uint32_t app_id, hmi_apis::Common_ButtonName::eType button, bool is_subscribed) {
- using namespace smart_objects;
- using namespace hmi_apis;
- LOG4CXX_AUTO_TRACE(logger_);
-
- SmartObjectSPtr notification_ptr = utils::MakeShared<SmartObject>(SmartType_Map);
- if (!notification_ptr) {
- LOG4CXX_ERROR(logger_, "Memory allocation failed.");
- return;
- }
- SmartObject& notification = *notification_ptr;
-
- SmartObject msg_params = SmartObject(SmartType_Map);
- msg_params[strings::app_id] = app_id;
- msg_params[strings::name] = button;
- msg_params[strings::is_suscribed] = is_subscribed;
-
- notification[strings::params][strings::message_type] =
- static_cast<int32_t>(application_manager::MessageType::kNotification);
- notification[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- notification[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- notification[strings::params][strings::function_id] =
- hmi_apis::FunctionID::Buttons_OnButtonSubscription;
- notification[strings::msg_params] = msg_params;
-
- if (!ApplicationManagerImpl::instance()->ManageHMICommand(notification_ptr)) {
- LOG4CXX_ERROR(logger_, "Unable to send HMI notification");
- }
-}
-
-void MessageHelper::SendAllOnButtonSubscriptionNotificationsForApp(
- ApplicationConstSharedPtr app) {
- using namespace smart_objects;
- using namespace hmi_apis;
- using namespace mobile_apis;
- LOG4CXX_AUTO_TRACE(logger_);
-
- if (!app.valid()) {
- LOG4CXX_ERROR(logger_, "Invalid application pointer ");
- return;
- }
-
- std::set<ButtonName::eType> subscriptions = app->SubscribedButtons();
- std::set<ButtonName::eType>::iterator it = subscriptions.begin();
- for (; subscriptions.end() != it; ++it) {
- SendOnButtonSubscriptionNotification(
- app->hmi_app_id(), static_cast<Common_ButtonName::eType>(*it), true);
- }
-}
-
-void MessageHelper::SendSetAppIcon(uint32_t app_id,
- const std::string& icon_path) {
- using namespace smart_objects;
- SmartObjectSPtr set_app_icon(new smart_objects::SmartObject);
- if (set_app_icon) {
- SmartObject& so_to_send = *set_app_icon;
- so_to_send[strings::params][strings::function_id] =
- static_cast<int>(hmi_apis::FunctionID::UI_SetAppIcon);
- so_to_send[strings::params][strings::message_type] =
- static_cast<int>(hmi_apis::messageType::request);
- so_to_send[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- so_to_send[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- so_to_send[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
-
- so_to_send[strings::msg_params] = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- SmartObjectSPtr msg_params(MessageHelper::CreateSetAppIcon(icon_path, app_id));
-
- if (msg_params) {
- so_to_send[strings::msg_params] = *msg_params;
- }
- ApplicationManagerImpl::instance()->ManageHMICommand(set_app_icon);
- }
-}
-
-void MessageHelper::SendAppDataToHMI(ApplicationConstSharedPtr app) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (app) {
- SendSetAppIcon(app, app->app_icon_path());
- SendGlobalPropertiesToHMI(app);
- SendShowRequestToHMI(app);
- }
-}
-
-void MessageHelper::SendGlobalPropertiesToHMI(ApplicationConstSharedPtr app) {
- if (!app.valid()) {
- LOG4CXX_ERROR(logger_, "Invalid application");
- return;
- }
-
- smart_objects::SmartObjectList requests = CreateGlobalPropertiesRequestsToHMI(app);
- for (smart_objects::SmartObjectList::const_iterator it = requests.begin();
- it != requests.end(); ++it) {
- DCHECK(ApplicationManagerImpl::instance()->ManageHMICommand(*it))
- }
-}
-
-smart_objects::SmartObjectList MessageHelper::CreateGlobalPropertiesRequestsToHMI(
- ApplicationConstSharedPtr app) {
- LOG4CXX_AUTO_TRACE(logger_);
-
- smart_objects::SmartObjectList requests;
- if (!app.valid()) {
- LOG4CXX_ERROR(logger_, "Invalid application");
- return requests;
- }
-
- // UI global properties
-
- if (app->vr_help_title() || app->vr_help()) {
- smart_objects::SmartObjectSPtr ui_global_properties =
- new smart_objects::SmartObject(smart_objects::SmartType_Map);
-
- if (!ui_global_properties) {
- return requests;
- }
-
- (*ui_global_properties)[strings::params][strings::function_id] =
- static_cast<int>(hmi_apis::FunctionID::UI_SetGlobalProperties);
- (*ui_global_properties)[strings::params][strings::message_type] =
- static_cast<int>(hmi_apis::messageType::request);
- (*ui_global_properties)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*ui_global_properties)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- (*ui_global_properties)[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
-
- smart_objects::SmartObject ui_msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- if (app->vr_help_title()) {
- ui_msg_params[strings::vr_help_title] = (*app->vr_help_title());
- }
- if (app->vr_help()) {
- ui_msg_params[strings::vr_help] = (*app->vr_help());
- }
- if (app->keyboard_props()) {
- ui_msg_params[strings::keyboard_properties] = (*app->keyboard_props());
- }
- if (app->menu_title()) {
- ui_msg_params[strings::menu_title] = (*app->menu_title());
- }
- if (app->menu_icon()) {
- ui_msg_params[strings::menu_icon] = (*app->menu_icon());
- }
- ui_msg_params[strings::app_id] = app->app_id();
-
- (*ui_global_properties)[strings::msg_params] = ui_msg_params;
-
- requests.push_back(ui_global_properties);
- }
-
- // TTS global properties
- if (app->help_prompt() || app->timeout_prompt()) {
- smart_objects::SmartObjectSPtr tts_global_properties =
- new smart_objects::SmartObject(smart_objects::SmartType_Map);
-
- if (!tts_global_properties) {
- return requests;
- }
-
- (*tts_global_properties)[strings::params][strings::function_id] =
- static_cast<int>(hmi_apis::FunctionID::TTS_SetGlobalProperties);
- (*tts_global_properties)[strings::params][strings::message_type] =
- static_cast<int>(hmi_apis::messageType::request);
- (*tts_global_properties)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*tts_global_properties)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- (*tts_global_properties)[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
-
- smart_objects::SmartObject tts_msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- if (app->help_prompt()) {
- tts_msg_params[strings::help_prompt] = (*app->help_prompt());
- }
- if (app->timeout_prompt()) {
- tts_msg_params[strings::timeout_prompt] = (*app->timeout_prompt());
- }
- tts_msg_params[strings::app_id] = app->app_id();
-
- (*tts_global_properties)[strings::msg_params] = tts_msg_params;
-
- requests.push_back(tts_global_properties);
- }
- return requests;
-}
-
-void MessageHelper::SendTTSGlobalProperties(
- ApplicationSharedPtr app, bool default_help_prompt) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (!app) {
- return;
- }
- smart_objects::SmartObjectSPtr tts_global_properties(
- new smart_objects::SmartObject);
- if (tts_global_properties) {
- smart_objects::SmartObject& so_to_send = *tts_global_properties;
- so_to_send[strings::params][strings::function_id] =
- static_cast<int>(hmi_apis::FunctionID::TTS_SetGlobalProperties);
- so_to_send[strings::params][strings::message_type] =
- static_cast<int>(hmi_apis::messageType::request);
- so_to_send[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- so_to_send[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- so_to_send[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- msg_params[strings::help_prompt] = smart_objects::SmartObject(
- smart_objects::SmartType_Array);
- if (default_help_prompt) {
- const DataAccessor<CommandsMap> accessor = app->commands_map();
- const CommandsMap& commands = accessor.GetData();
- CommandsMap::const_iterator it = commands.begin();
- uint32_t index = 0;
- for (; commands.end() != it; ++it) {
- smart_objects::SmartObject item(smart_objects::SmartType_Map);
- if ((*it->second).keyExists(strings::menu_params)){
- item[strings::text] = (*it->second)[strings::menu_params][strings::menu_name].asString();
- item[strings::type] = mobile_apis::SpeechCapabilities::SC_TEXT;
- } else {
- continue;
- }
- msg_params[strings::help_prompt][index++] = item;
- }
- }
- app->set_help_prompt(msg_params[strings::help_prompt]);
- msg_params[strings::app_id] = app->app_id();
- so_to_send[strings::msg_params] = msg_params;
- ApplicationManagerImpl::instance()->ManageHMICommand(tts_global_properties);
- }
-}
-
-smart_objects::SmartObjectSPtr MessageHelper::CreateAppVrHelp(
- ApplicationConstSharedPtr app) {
- smart_objects::SmartObjectSPtr result = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- if (!result) {
- return NULL;
- }
- smart_objects::SmartObject& vr_help = *result;
- vr_help[strings::vr_help_title] = app->name();
-
- int32_t index = 0;
- if (app->vr_synonyms()) {
- smart_objects::SmartObject item(smart_objects::SmartType_Map);
- item[strings::text] = (*(app->vr_synonyms())).getElement(0);
- item[strings::position] = index + 1;
- vr_help[strings::vr_help][index++] = item;
- }
-
- // copy all app VR commands
- const DataAccessor<CommandsMap> cmd_accessor = app->commands_map();
- const CommandsMap& commands = cmd_accessor.GetData();
- CommandsMap::const_iterator it = commands.begin();
-
- for (; commands.end() != it; ++it) {
- smart_objects::SmartObject item(smart_objects::SmartType_Map);
- item[strings::text] = (*it->second)[strings::vr_commands][0].asString();
- item[strings::position] = index + 1;
- vr_help[strings::vr_help][index++] = item;
- }
- return result;
-}
-
-smart_objects::SmartObjectList MessageHelper::CreateShowRequestToHMI(
- ApplicationConstSharedPtr app) {
-
- smart_objects::SmartObjectList requests;
- if (!app) {
- LOG4CXX_ERROR(logger_, "Invalid application");
- return requests;
- }
-
- if (app->show_command()) {
- smart_objects::SmartObjectSPtr ui_show = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- (*ui_show)[strings::params][strings::function_id] =
- static_cast<int>(hmi_apis::FunctionID::UI_Show);
- (*ui_show)[strings::params][strings::message_type] =
- static_cast<int>(hmi_apis::messageType::request);
- (*ui_show)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*ui_show)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- (*ui_show)[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
- (*ui_show)[strings::msg_params] = (*app->show_command());
- requests.push_back(ui_show);
- }
- return requests;
-}
-
-void MessageHelper::SendShowRequestToHMI(ApplicationConstSharedPtr app) {
- if (!app) {
- return;
- }
- smart_objects::SmartObjectList shows = CreateShowRequestToHMI(app);
-
- for (smart_objects::SmartObjectList::const_iterator it = shows.begin();
- it != shows.end(); ++it) {
- DCHECK(ApplicationManagerImpl::instance()->ManageHMICommand(*it));
- }
-
-}
-
-void MessageHelper::SendShowConstantTBTRequestToHMI(
- ApplicationConstSharedPtr app) {
- if (!app) {
- return;
- }
-
- if (app->tbt_show_command()) {
- utils::SharedPtr<smart_objects::SmartObject> navi_show_tbt =
- new smart_objects::SmartObject(smart_objects::SmartType_Map);
- if (!navi_show_tbt) {
- return;
- }
- (*navi_show_tbt)[strings::params][strings::function_id] =
- static_cast<int>(hmi_apis::FunctionID::Navigation_ShowConstantTBT);
- (*navi_show_tbt)[strings::params][strings::message_type] =
- static_cast<int>(hmi_apis::messageType::request);
- (*navi_show_tbt)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*navi_show_tbt)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- (*navi_show_tbt)[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
- (*navi_show_tbt)[strings::msg_params] = (*app->tbt_show_command());
- DCHECK(ApplicationManagerImpl::instance()->ManageHMICommand(navi_show_tbt));
- }
-}
-
-void MessageHelper::SendAddCommandRequestToHMI(ApplicationConstSharedPtr app) {
- if (!app) {
- return;
- }
- smart_objects::SmartObjectList requests = CreateAddCommandRequestToHMI(app);
- for (smart_objects::SmartObjectList::iterator it = requests.begin(); it != requests.end();
- ++it) {
- DCHECK(ApplicationManagerImpl::instance()->ManageHMICommand(*it));
- }
-}
-
-smart_objects::SmartObjectList MessageHelper::CreateAddCommandRequestToHMI(
- ApplicationConstSharedPtr app) {
-
- smart_objects::SmartObjectList requests;
- if (!app) {
- LOG4CXX_ERROR(logger_, "Invalid application");
- return requests;
- }
-
- const DataAccessor<CommandsMap> accessor = app->commands_map();
- const CommandsMap& commands = accessor.GetData();
- CommandsMap::const_iterator i = commands.begin();
- for (; commands.end() != i; ++i) {
- // UI Interface
- if ((*i->second).keyExists(strings::menu_params)) {
- smart_objects::SmartObjectSPtr ui_command = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- if (!ui_command) {
- return requests;
- }
-
- (*ui_command)[strings::params][strings::function_id] =
- static_cast<int>(hmi_apis::FunctionID::UI_AddCommand);
- (*ui_command)[strings::params][strings::message_type] =
- static_cast<int>(hmi_apis::messageType::request);
- (*ui_command)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*ui_command)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- (*ui_command)[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
-
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- msg_params[strings::cmd_id] = i->first;
- msg_params[strings::menu_params] = (*i->second)[strings::menu_params];
- msg_params[strings::app_id] = app->app_id();
-
- if (((*i->second).keyExists(strings::cmd_icon))
- && (0 < (*i->second)[strings::cmd_icon][strings::value].length())) {
- msg_params[strings::cmd_icon] = (*i->second)[strings::cmd_icon];
- msg_params[strings::cmd_icon][strings::value] =
- (*i->second)[strings::cmd_icon][strings::value].asString();
- }
- (*ui_command)[strings::msg_params] = msg_params;
- requests.push_back(ui_command);
- }
-
- // VR Interface
- if ((*i->second).keyExists(strings::vr_commands)) {
- SendAddVRCommandToHMI(i->first, (*i->second)[strings::vr_commands],
- app->app_id());
- }
- }
- return requests;
-}
-
-smart_objects::SmartObjectSPtr MessageHelper::CreateChangeRegistration(
- int32_t function_id, int32_t language, uint32_t app_id,
- const smart_objects::SmartObject* app_types) {
- smart_objects::SmartObjectSPtr command = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- if (!command) {
- return NULL;
- }
- smart_objects::SmartObject& params = *command;
-
- params[strings::params][strings::message_type] =
- static_cast<int>(hmi_apis::messageType::request);
- params[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- params[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
-
- params[strings::params][strings::function_id] = function_id;
-
- params[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
-
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- msg_params[strings::language] = language;
- msg_params[strings::app_id] = app_id;
-
- if (app_types != NULL) {
- msg_params[strings::app_hmi_type] = *app_types;
- }
-
- params[strings::msg_params] = msg_params;
- return command;
-}
-
-void MessageHelper::SendUIChangeRegistrationRequestToHMI(ApplicationConstSharedPtr app) {
- if (!app.valid()) {
- LOG4CXX_ERROR(logger_, "Application is not valid");
- return;
- }
-
- if (NULL != app->app_types()) {
- smart_objects::SmartObjectSPtr ui_command = CreateChangeRegistration(
- hmi_apis::FunctionID::UI_ChangeRegistration, app->ui_language(),
- app->app_id(), app->app_types());
-
- if (ui_command) {
- ApplicationManagerImpl::instance()->ManageHMICommand(ui_command);
- }
- }
-}
-
-void MessageHelper::SendChangeRegistrationRequestToHMI(ApplicationConstSharedPtr app) {
- if (!app.valid()) {
- return;
- }
- if (mobile_apis::Language::INVALID_ENUM != app->language()) {
- smart_objects::SmartObjectSPtr vr_command = CreateChangeRegistration(
- hmi_apis::FunctionID::VR_ChangeRegistration, app->language(),
- app->app_id());
-
- if (vr_command) {
- ApplicationManagerImpl::instance()->ManageHMICommand(vr_command);
- }
- }
-
- if (mobile_apis::Language::INVALID_ENUM != app->language()) {
- smart_objects::SmartObjectSPtr tts_command = CreateChangeRegistration(
- hmi_apis::FunctionID::TTS_ChangeRegistration, app->language(),
- app->app_id());
-
- if (tts_command) {
- ApplicationManagerImpl::instance()->ManageHMICommand(tts_command);
- }
- }
-
- if (mobile_apis::Language::INVALID_ENUM != app->ui_language()) {
- smart_objects::SmartObjectSPtr ui_command = CreateChangeRegistration(
- hmi_apis::FunctionID::UI_ChangeRegistration, app->ui_language(),
- app->app_id());
-
- if (ui_command) {
- ApplicationManagerImpl::instance()->ManageHMICommand(ui_command);
- }
-
- }
-}
-
-void MessageHelper::SendAddVRCommandToHMI(
- uint32_t cmd_id, const smart_objects::SmartObject& vr_commands,
- uint32_t app_id) {
- smart_objects::SmartObjectSPtr request = CreateAddVRCommandToHMI(cmd_id,
- vr_commands,
- app_id);
- DCHECK(ApplicationManagerImpl::instance()->ManageHMICommand(request));
-}
-
-smart_objects::SmartObjectSPtr MessageHelper::CreateAddVRCommandToHMI(
- uint32_t cmd_id, const smart_objects::SmartObject& vr_commands,
- uint32_t app_id) {
- smart_objects::SmartObjectSPtr vr_command = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- if (!vr_command) {
- return NULL;
- }
-
- (*vr_command)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::VR_AddCommand;
- (*vr_command)[strings::params][strings::message_type] =
- hmi_apis::messageType::request;
- (*vr_command)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*vr_command)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- (*vr_command)[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
-
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- if (0 != cmd_id) {
- msg_params[strings::cmd_id] = cmd_id;
- }
- msg_params[strings::vr_commands] = vr_commands;
- if (0 < app_id) {
- msg_params[strings::app_id] = app_id;
- }
- msg_params[strings::grammar_id] =
- ApplicationManagerImpl::instance()->application(app_id)->get_grammar_id();
- msg_params[strings::type] = hmi_apis::Common_VRCommandType::Command;
-
- (*vr_command)[strings::msg_params] = msg_params;
-
- return vr_command;
-}
-
-bool MessageHelper::CreateHMIApplicationStruct(ApplicationConstSharedPtr app,
- smart_objects::SmartObject& output) {
- using namespace smart_objects;
- LOG4CXX_AUTO_TRACE(logger_);
-
- if (!app) {
- LOG4CXX_WARN(logger_, "Application is not valid");
- return false;
- }
-
- const SmartObject* app_types = app->app_types();
- const SmartObject* ngn_media_screen_name = app->ngn_media_screen_name();
- const connection_handler::DeviceHandle handle = app->device();
- std::string device_name = ApplicationManagerImpl::instance()->GetDeviceName(handle);
-
- std::string mac_address;
- std::string transport_type;
- if (-1 == connection_handler::ConnectionHandlerImpl::instance()->
- GetDataOnDeviceID(app->device(), &device_name,
- NULL, &mac_address, &transport_type)) {
- LOG4CXX_ERROR(logger_, "Failed to extract information for device "
- << app->device());
- }
-
- output = SmartObject(SmartType_Map);
- output[strings::app_name] = app->name();
- output[strings::icon] = app->app_icon_path();
- output[strings::app_id] = app->hmi_app_id();
-
- if (app->IsRegistered()) {
- output[strings::hmi_display_language_desired] = app->ui_language();
- output[strings::is_media_application] = app->is_media_application();
- }
-
- if (!app->IsRegistered()) {
- output[strings::greyOut] = app->is_greyed_out();
- const SmartObject* app_tts_name = app->tts_name();
- DCHECK_OR_RETURN(app_tts_name, false);
- if (!app_tts_name->empty()) {
- SmartObject output_tts_name = SmartObject(SmartType_Array);
- output_tts_name[0][strings::text] = *(app->tts_name());
- output_tts_name[0][strings::type] = hmi_apis::Common_SpeechCapabilities::SC_TEXT;
- output[json::ttsName] = output_tts_name;
- }
- if (!app->vr_synonyms()->empty()) {
- output[json::vrSynonyms] = *(app->vr_synonyms());
- }
- }
-
- if (ngn_media_screen_name) {
- output[strings::ngn_media_screen_app_name] = ngn_media_screen_name->asString();
- }
- if (app_types) {
- output[strings::app_type] = *app_types;
- }
-
- output[strings::device_info] = smart_objects::SmartObject(smart_objects::SmartType_Map);
- output[strings::device_info][strings::name] = device_name;
- output[strings::device_info][strings::id] = mac_address;
- const policy::DeviceConsent device_consent =
- policy::PolicyHandler::instance()->GetUserConsentForDevice(mac_address);
- output[strings::device_info][strings::isSDLAllowed] =
- policy::DeviceConsent::kDeviceAllowed == device_consent;
-
- output[strings::device_info][strings::transport_type] =
- ApplicationManagerImpl::instance()->GetDeviceTransportType(transport_type);
- return true;
-}
-
-void MessageHelper::SendAddSubMenuRequestToHMI(ApplicationConstSharedPtr app) {
- if (!app.valid()) {
- LOG4CXX_ERROR(logger_, "Invalid application");
- return;
- }
-
- smart_objects::SmartObjectList requests = CreateAddSubMenuRequestToHMI(app);
- for (smart_objects::SmartObjectList::iterator it = requests.begin();
- it != requests.end(); ++it) {
- DCHECK(ApplicationManagerImpl::instance()->ManageHMICommand(*it));
- }
-}
-
-smart_objects::SmartObjectList MessageHelper::CreateAddSubMenuRequestToHMI(
- ApplicationConstSharedPtr app) {
- smart_objects::SmartObjectList requsets;
- const DataAccessor<SubMenuMap> accessor = app->sub_menu_map();
- const SubMenuMap& sub_menu = accessor.GetData();
- SubMenuMap::const_iterator i = sub_menu.begin();
- for (; sub_menu.end() != i; ++i) {
- smart_objects::SmartObjectSPtr ui_sub_menu = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- if (!ui_sub_menu) {
- return requsets;
- }
-
- (*ui_sub_menu)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::UI_AddSubMenu;
- (*ui_sub_menu)[strings::params][strings::message_type] =
- hmi_apis::messageType::request;
- (*ui_sub_menu)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*ui_sub_menu)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- (*ui_sub_menu)[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
-
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- msg_params[strings::menu_id] = i->first;
- msg_params[strings::menu_params][strings::position] =
- (*i->second)[strings::position];
- msg_params[strings::menu_params][strings::menu_name] =
- (*i->second)[strings::menu_name];
- msg_params[strings::app_id] = app->app_id();
- (*ui_sub_menu)[strings::msg_params] = msg_params;
- requsets.push_back(ui_sub_menu);
- }
- return requsets;
-}
-
-void MessageHelper::SendOnAppUnregNotificationToHMI(
- ApplicationConstSharedPtr app, bool is_unexpected_disconnect) {
- smart_objects::SmartObjectSPtr notification = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- if (!notification) {
- return;
- }
-
- smart_objects::SmartObject& message = *notification;
-
- message[strings::params][strings::function_id] =
- hmi_apis::FunctionID::BasicCommunication_OnAppUnregistered;
-
- message[strings::params][strings::message_type] = MessageType::kNotification;
- // we put hmi_app_id because applicaton list does not contain application on this momment
- // and ReplaceHMIByMobileAppId function will be unable to replace app_id to hmi_app_id
- message[strings::msg_params][strings::app_id] = app->hmi_app_id();
- message[strings::msg_params][strings::unexpected_disconnect] =
- is_unexpected_disconnect;
- ApplicationManagerImpl::instance()->ManageHMICommand(notification);
-}
-
-uint32_t MessageHelper::SendActivateAppToHMI(uint32_t const app_id,
- hmi_apis::Common_HMILevel::eType level,
- bool send_policy_priority) {
- uint32_t correlation_id = 0;
- application_manager::ApplicationConstSharedPtr app =
- application_manager::ApplicationManagerImpl::instance()
- ->application(app_id);
- if (!app) {
- LOG4CXX_WARN(logger_, "Invalid app_id: " << app_id);
- return correlation_id;
- }
-
- correlation_id =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
- utils::SharedPtr<smart_objects::SmartObject> message = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- (*message)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::BasicCommunication_ActivateApp;
- (*message)[strings::params][strings::message_type] = MessageType::kRequest;
- (*message)[strings::params][strings::correlation_id] = correlation_id;
- (*message)[strings::msg_params][strings::app_id] = app_id;
-
- if (send_policy_priority) {
- std::string priority;
- // TODO(KKolodiy): need remove method policy_manager
-
- policy::PolicyHandler::instance()->GetPriority(
- app->mobile_app_id(), &priority);
- // According SDLAQ-CRS-2794
- // SDL have to send ActivateApp without "proirity" parameter to HMI.
- // in case of unconsented device
- std::string mac_adress;
- connection_handler::DeviceHandle device_handle = app->device();
- connection_handler::ConnectionHandlerImpl::instance()->
- GetDataOnDeviceID(device_handle, NULL, NULL, &mac_adress, NULL);
-
- policy::DeviceConsent consent =
- policy::PolicyHandler::instance()->GetUserConsentForDevice(mac_adress);
- if (!priority.empty() && (policy::DeviceConsent::kDeviceAllowed == consent)) {
- (*message)[strings::msg_params][strings::priority] = GetPriorityCode(priority);
- }
- }
-
- // We haven't send HMI level to HMI in case it FULL.
- if (hmi_apis::Common_HMILevel::INVALID_ENUM != level &&
- hmi_apis::Common_HMILevel::FULL != level) {
- (*message)[strings::msg_params][strings::activate_app_hmi_level] = level;
- }
-
- ApplicationManagerImpl::instance()->ManageHMICommand(message);
- return correlation_id;
-}
-
-void MessageHelper::SendOnResumeAudioSourceToHMI(const uint32_t app_id) {
- LOG4CXX_WARN(logger_, "SendOnResumeAudioSourceToHMI app_id: " << app_id);
- application_manager::ApplicationConstSharedPtr app =
- application_manager::ApplicationManagerImpl::instance()
- ->application(app_id);
- if (!app) {
- LOG4CXX_WARN(logger_, "Invalid app_id: " << app_id);
- return;
- }
-
- utils::SharedPtr<smart_objects::SmartObject> message = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- (*message)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::BasicCommunication_OnResumeAudioSource;
- (*message)[strings::params][strings::message_type] = MessageType::kNotification;
- (*message)[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
- (*message)[strings::msg_params][strings::app_id] = app_id;
-
- ApplicationManagerImpl::instance()->ManageHMICommand(message);
-}
-
-std::string MessageHelper::GetDeviceMacAddressForHandle(
- const uint32_t device_handle) {
-
- std::string device_mac_address = "";
- connection_handler::ConnectionHandlerImpl::instance()->GetDataOnDeviceID(
- device_handle, NULL, NULL, &device_mac_address);
- LOG4CXX_DEBUG(logger_, "result : " << device_handle);
- return device_mac_address;
-}
-
-void MessageHelper::GetDeviceInfoForHandle(const uint32_t device_handle,
- policy::DeviceParams* device_info) {
- if (!device_info) {
- return;
- }
- connection_handler::ConnectionHandlerImpl::instance()->GetDataOnDeviceID(
- device_handle, &device_info->device_name, NULL,
- &device_info->device_mac_address, &device_info->device_connection_type);
-}
-
-void MessageHelper::GetDeviceInfoForApp(uint32_t connection_key,
- policy::DeviceParams* device_info) {
- if (!device_info) {
- return;
- }
-
- device_info->device_handle = ApplicationManagerImpl::instance()->application(
- connection_key)->device();
-
- GetDeviceInfoForHandle(device_info->device_handle, device_info);
-}
-
-void MessageHelper::SendSDLActivateAppResponse(policy::AppPermissions& permissions,
- uint32_t correlation_id) {
- smart_objects::SmartObjectSPtr message = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- if (!message) {
- return;
- }
-
- (*message)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::SDL_ActivateApp;
- (*message)[strings::params][strings::message_type] = MessageType::kResponse;
- (*message)[strings::params][strings::correlation_id] = correlation_id;
- (*message)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- (*message)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*message)[strings::params][hmi_response::code] = 0;
-
- (*message)[strings::msg_params]["isSDLAllowed"] = permissions.isSDLAllowed;
- if (!permissions.isSDLAllowed) {
- (*message)[strings::msg_params]["device"]["name"] = permissions.deviceInfo
- .device_name;
- (*message)[strings::msg_params]["device"]["id"] = permissions.deviceInfo
- .device_mac_address;
- }
-
- (*message)[strings::msg_params]["isAppRevoked"] = permissions.appRevoked;
- (*message)[strings::msg_params]["isAppPermissionsRevoked"] = permissions
- .isAppPermissionsRevoked;
-
- if (permissions.isAppPermissionsRevoked) {
- FillAppRevokedPermissions(permissions, *message);
- }
-
- (*message)[strings::msg_params]["isPermissionsConsentNeeded"] = permissions
- .appPermissionsConsentNeeded;
-
- if (!permissions.priority.empty()) {
- (*message)[strings::msg_params]["priority"] = GetPriorityCode(
- permissions.priority);
- }
-
- ApplicationManagerImpl::instance()->ManageHMICommand(message);
-
- // If application is revoked it should not be activated
- if (permissions.appRevoked || !permissions.isSDLAllowed) {
- return;
- }
-}
-
-void MessageHelper::SendOnSDLConsentNeeded(
- const policy::DeviceParams& device_info) {
- smart_objects::SmartObjectSPtr message = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- if (!message) {
- return;
- }
-
- (*message)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::SDL_OnSDLConsentNeeded;
- (*message)[strings::params][strings::message_type] =
- MessageType::kNotification;
-
- (*message)[strings::msg_params]["device"]["id"] = device_info.device_mac_address;
- (*message)[strings::msg_params]["device"]["name"] = device_info.device_name;
-
- ApplicationManagerImpl::instance()->ManageHMICommand(message);
-}
-
-void MessageHelper::SendPolicyUpdate(
- const std::string& file_path,
- int timeout,
- const std::vector<int>& retries) {
- smart_objects::SmartObjectSPtr message = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- smart_objects::SmartObject& object = *message;
- object[strings::params][strings::function_id] =
- hmi_apis::FunctionID::BasicCommunication_PolicyUpdate;
- object[strings::params][strings::message_type] = MessageType::kRequest;
- object[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
- object[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- object[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
-
- object[strings::msg_params][hmi_request::file] = file_path;
- object[strings::msg_params][strings::timeout] = timeout;
- object[strings::msg_params][hmi_request::retry] = smart_objects::SmartObject(
- smart_objects::SmartType_Array);
- for (size_t i = 0; i < retries.size(); ++i) {
- object[strings::msg_params][hmi_request::retry][i] = retries[i];
- }
- ApplicationManagerImpl::instance()->ManageHMICommand(message);
-}
-
-void MessageHelper::SendGetUserFriendlyMessageResponse(
- const std::vector<policy::UserFriendlyMessage>& msg,
- uint32_t correlation_id) {
- smart_objects::SmartObjectSPtr message = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- if (!message) {
- return;
- }
-
- (*message)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::SDL_GetUserFriendlyMessage;
- (*message)[strings::params][strings::message_type] =
- MessageType::kResponse;
- (*message)[strings::params][strings::correlation_id] = correlation_id;
- (*message)[strings::params][hmi_response::code] = 0;
-
- // If no any messages found - skip sending of "messages" param
- if (msg.empty()) {
- ApplicationManagerImpl::instance()->ManageHMICommand(message);
- }
-
- const std::string messages = "messages";
- (*message)[strings::msg_params][messages] =
- smart_objects::SmartObject(smart_objects::SmartType_Array);
-
- smart_objects::SmartObject& user_friendly_messages =
- (*message)[strings::msg_params][messages];
-
- const std::string message_code = "messageCode";
-
- std::vector<policy::UserFriendlyMessage>::const_iterator it = msg.begin();
- std::vector<policy::UserFriendlyMessage>::const_iterator it_end = msg.end();
- for (uint32_t index = 0; it != it_end; ++it, ++index) {
- user_friendly_messages[index] = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- smart_objects::SmartObject& obj = user_friendly_messages[index];
- obj[message_code] = it->message_code;
- }
-
- ApplicationManagerImpl::instance()->ManageHMICommand(message);
-}
-
-void MessageHelper::SendGetListOfPermissionsResponse(
- const std::vector<policy::FunctionalGroupPermission>& permissions,
- uint32_t correlation_id) {
- smart_objects::SmartObjectSPtr message = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- if (!message) {
- return;
- }
-
- (*message)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::SDL_GetListOfPermissions;
- (*message)[strings::params][strings::message_type] =
- MessageType::kResponse;
- (*message)[strings::params][strings::correlation_id] = correlation_id;
- (*message)[strings::params][hmi_response::code] = 0;
-
- const std::string allowed_functions = "allowedFunctions";
- (*message)[strings::msg_params][allowed_functions] =
- smart_objects::SmartObject(smart_objects::SmartType_Array);
-
- smart_objects::SmartObject& allowed_functions_array =
- (*message)[strings::msg_params][allowed_functions];
-
- std::vector<policy::FunctionalGroupPermission>::const_iterator it =
- permissions.begin();
- std::vector<policy::FunctionalGroupPermission>::const_iterator it_end =
- permissions.end();
- for (uint32_t index = 0; it != it_end; ++it, ++index) {
- allowed_functions_array[index] = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- smart_objects::SmartObject& item = allowed_functions_array[index];
- item[strings::name] = (*it).group_alias;
- item[strings::id] = (*it).group_id;
- policy::GroupConsent permission_state = (*it).state;
- // If state undefined, 'allowed' parameter should be absent
- if (policy::kGroupUndefined != permission_state) {
- item["allowed"] = policy::kGroupAllowed == permission_state;
- }
- }
-
- ApplicationManagerImpl::instance()->ManageHMICommand(message);
-}
-
-smart_objects::SmartObjectSPtr MessageHelper::CreateNegativeResponse(
- uint32_t connection_key, int32_t function_id, uint32_t correlation_id,
- int32_t result_code) {
- smart_objects::SmartObjectSPtr response = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- smart_objects::SmartObject& response_data = *response;
- response_data[strings::params][strings::function_id] = function_id;
- response_data[strings::params][strings::message_type] =
- mobile_apis::messageType::response;
- response_data[strings::params][strings::correlation_id] = correlation_id;
- response_data[strings::params][strings::protocol_type] =
- commands::CommandImpl::mobile_protocol_type_;
- response_data[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- response_data[strings::msg_params][strings::result_code] = result_code;
- response_data[strings::msg_params][strings::success] = false;
- response_data[strings::params][strings::connection_key] = connection_key;
-
- return response;
-}
-
-void MessageHelper::SendNaviStartStream(int32_t connection_key) {
- LOG4CXX_AUTO_TRACE(logger_);
- smart_objects::SmartObjectSPtr start_stream = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- if (!start_stream) {
- return;
- }
-
- (*start_stream)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::Navigation_StartStream;
- (*start_stream)[strings::params][strings::message_type] =
- hmi_apis::messageType::request;
- (*start_stream)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*start_stream)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- (*start_stream)[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
-
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- uint32_t app_id = 0;
- connection_handler::ConnectionHandlerImpl::instance()->GetDataOnSessionKey(
- connection_key, &app_id);
-
- char url[100] = {'\0'};
- if ("socket" == profile::Profile::instance()->video_server_type()) {
- snprintf(url, sizeof(url) / sizeof(url[0]), "http://%s:%d",
- profile::Profile::instance()->server_address().c_str(),
- profile::Profile::instance()->video_streaming_port());
- } else if ("pipe" == profile::Profile::instance()->video_server_type()) {
- snprintf(url, sizeof(url) / sizeof(url[0]), "%s",
- profile::Profile::instance()->named_video_pipe_path().c_str());
- } else {
- int snprintf_result;
- snprintf_result = snprintf(url, sizeof(url) / sizeof(url[0]), "%s",
- profile::Profile::instance()->video_stream_file().c_str());
- DCHECK(snprintf_result);
- }
- msg_params[strings::app_id] = app_id;
- msg_params[strings::url] = url;
-
- (*start_stream)[strings::msg_params] = msg_params;
-
- ApplicationManagerImpl::instance()->ManageHMICommand(start_stream);
-}
-
-void MessageHelper::SendNaviStopStream(int32_t connection_key) {
- smart_objects::SmartObjectSPtr stop_stream = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- if (!stop_stream) {
- return;
- }
-
- (*stop_stream)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::Navigation_StopStream;
- (*stop_stream)[strings::params][strings::message_type] =
- hmi_apis::messageType::request;
- (*stop_stream)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*stop_stream)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- (*stop_stream)[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
-
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- uint32_t app_id = 0;
- connection_handler::ConnectionHandlerImpl::instance()->GetDataOnSessionKey(
- connection_key, &app_id);
-
- msg_params[strings::app_id] = app_id;
-
- (*stop_stream)[strings::msg_params] = msg_params;
-
- ApplicationManagerImpl::instance()->ManageHMICommand(stop_stream);
-}
-
-void MessageHelper::SendAudioStartStream(int32_t connection_key) {
-
- smart_objects::SmartObjectSPtr start_stream = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- if (!start_stream) {
- return;
- }
-
- (*start_stream)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::Navigation_StartAudioStream;
- (*start_stream)[strings::params][strings::message_type] =
- hmi_apis::messageType::request;
- (*start_stream)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*start_stream)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- (*start_stream)[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
-
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- uint32_t app_id = 0;
- connection_handler::ConnectionHandlerImpl::instance()->GetDataOnSessionKey(
- connection_key, &app_id);
-
- char url[100] = {'\0'};
- if ("socket" == profile::Profile::instance()->audio_server_type()) {
- snprintf(url, sizeof(url) / sizeof(url[0]), "http://%s:%d",
- profile::Profile::instance()->server_address().c_str(),
- profile::Profile::instance()->audio_streaming_port());
- } else if ("pipe" == profile::Profile::instance()->audio_server_type()) {
- snprintf(url, sizeof(url) / sizeof(url[0]), "%s",
- profile::Profile::instance()->named_audio_pipe_path().c_str());
- } else {
- int snprintf_result;
- snprintf_result = snprintf(url, sizeof(url) / sizeof(url[0]), "%s",
- profile::Profile::instance()->audio_stream_file().c_str());
- DCHECK(snprintf_result);
- }
-
- msg_params[strings::app_id] = app_id;
- msg_params[strings::url] = url;
-
- (*start_stream)[strings::msg_params] = msg_params;
-
- DCHECK(ApplicationManagerImpl::instance()->ManageHMICommand(start_stream));
-}
-
-void MessageHelper::SendAudioStopStream(int32_t connection_key) {
- smart_objects::SmartObjectSPtr stop_stream = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- if (!stop_stream) {
- return;
- }
-
- (*stop_stream)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::Navigation_StopAudioStream;
- (*stop_stream)[strings::params][strings::message_type] =
- hmi_apis::messageType::request;
- (*stop_stream)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*stop_stream)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- (*stop_stream)[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
-
- smart_objects::SmartObject msg_params = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- uint32_t app_id = 0;
- connection_handler::ConnectionHandlerImpl::instance()->GetDataOnSessionKey(
- connection_key, &app_id);
-
- msg_params[strings::app_id] = app_id;
-
- (*stop_stream)[strings::msg_params] = msg_params;
-
- ApplicationManagerImpl::instance()->ManageHMICommand(stop_stream);
-}
-
-void MessageHelper::SendOnDataStreaming(protocol_handler::ServiceType service,
- bool available) {
- using namespace protocol_handler;
- smart_objects::SmartObjectSPtr notification = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- if (!notification) {
- return;
- }
-
- if (ServiceType::kAudio != service && ServiceType::kMobileNav != service) {
- return;
- }
-
- (*notification)[strings::params][strings::function_id] =
- ServiceType::kAudio == service
- ? hmi_apis::FunctionID::Navigation_OnAudioDataStreaming
- : hmi_apis::FunctionID::Navigation_OnVideoDataStreaming;
- (*notification)[strings::params][strings::message_type] =
- hmi_apis::messageType::notification;
- (*notification)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*notification)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
-
- (*notification)[strings::msg_params]["available"] = available;
-
- ApplicationManagerImpl::instance()->ManageHMICommand(notification);
-}
-
-bool MessageHelper::SendStopAudioPathThru() {
- LOG4CXX_INFO(logger_, "MessageHelper::SendAudioStopAudioPathThru");
-
- smart_objects::SmartObjectSPtr result = new smart_objects::SmartObject;
- const uint32_t hmi_correlation_id = ApplicationManagerImpl::instance()
- ->GetNextHMICorrelationID();
- smart_objects::SmartObject& request = *result;
- request[strings::params][strings::message_type] = MessageType::kRequest;
- request[strings::params][strings::function_id] =
- hmi_apis::FunctionID::UI_EndAudioPassThru;
- request[strings::params][strings::correlation_id] = hmi_correlation_id;
- request[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- request[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
- return ApplicationManagerImpl::instance()->ManageHMICommand(result);
-}
-
-void MessageHelper::SendPolicySnapshotNotification(
- unsigned int connection_key, const std::vector<uint8_t>& policy_data,
- const std::string& url, int timeout) {
-
- using namespace mobile_apis;
- using namespace smart_objects;
-
- SmartObject content (SmartType_Map);
- if (!url.empty()) {
- content[strings::msg_params][strings::url] = url;
- }
-
- content[strings::msg_params][strings::request_type] = RequestType::HTTP;
- content[strings::params][strings::binary_data] = SmartObject(policy_data);
- content[strings::msg_params][strings::file_type] = FileType::BINARY;
-
- SendSystemRequestNotification(connection_key, content);
-}
-
-void MessageHelper::SendSystemRequestNotification (uint32_t connection_key,
- smart_objects::SmartObject& content) {
-
- using namespace mobile_apis;
- using namespace commands;
- using namespace smart_objects;
-
- content[strings::params][strings::function_id] = FunctionID::OnSystemRequestID;
- content[strings::params][strings::message_type] = messageType::notification;
- content[strings::params][strings::protocol_type] = CommandImpl::mobile_protocol_type_;
- content[strings::params][strings::protocol_version] = CommandImpl::protocol_version_;
-
- content[strings::params][strings::connection_key] = connection_key;
-
- ApplicationManagerImpl::instance()->ManageMobileCommand(new SmartObject(content));
-}
-
-void MessageHelper::SendLaunchApp(uint32_t connection_key,
- const std::string& urlSchema,
- const std::string& packageName) {
-
- using namespace mobile_apis;
- using namespace smart_objects;
-
- SmartObject content (SmartType_Map);
- content[strings::msg_params][strings::request_type] = RequestType::LAUNCH_APP;
- content[strings::msg_params][strings::app_id] = connection_key;
- if (!urlSchema.empty()) {
- content[strings::msg_params][strings::url] = urlSchema;
- } else if (!packageName.empty()) {
- content[strings::msg_params][strings::url] = packageName;
- }
-
- SendSystemRequestNotification(connection_key, content);
-}
-
-void application_manager::MessageHelper::SendQueryApps(
- uint32_t connection_key) {
- using namespace mobile_apis;
- using namespace smart_objects;
-
- policy::PolicyHandler* policy_handler = policy::PolicyHandler::instance();
-
- SmartObject content (SmartType_Map);
- content[strings::msg_params][strings::request_type] = RequestType::QUERY_APPS;
- content[strings::msg_params][strings::url] = policy_handler->RemoteAppsUrl();
- content[strings::msg_params][strings::timeout] =
- policy_handler->TimeoutExchange();
-
- Json::Value http;
- Json::Value& http_header = http[http_request::httpRequest][http_request::headers];
-
- const int timeout = policy_handler->TimeoutExchange();
-
- http_header[http_request::content_type] = "application/json";
- http_header[http_request::connect_timeout] = timeout;
- http_header[http_request::do_output] = true;
- http_header[http_request::do_input] = true;
- http_header[http_request::use_caches] = false;
- http_header[http_request::request_method] = http_request::GET;
- http_header[http_request::read_timeout] = timeout;
- http_header[http_request::instance_follow_redirect] = false;
- http_header[http_request::charset] = "utf-8";
- http_header[http_request::content_lenght] = 0;
-
- std::string data = http_header.toStyledString();
- std::vector<uint8_t> binary_data(data.begin(), data.end());
-
- content[strings::params][strings::binary_data] = SmartObject(binary_data);
- content[strings::msg_params][strings::file_type] = FileType::BINARY;
-
- SendSystemRequestNotification(connection_key, content);
-}
-
-void MessageHelper::SendOnPermissionsChangeNotification(
- uint32_t connection_key, const policy::Permissions& permissions) {
- utils::SharedPtr<smart_objects::SmartObject> notification = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- smart_objects::SmartObject& content = *notification;
-
- content[strings::params][strings::function_id] =
- mobile_apis::FunctionID::OnPermissionsChangeID;
- content[strings::params][strings::message_type] =
- mobile_apis::messageType::notification;
- content[strings::params][strings::protocol_type] =
- commands::CommandImpl::mobile_protocol_type_;
- content[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- content[strings::params][strings::connection_key] = connection_key;
-
- utils::SharedPtr<smart_objects::SmartObject> p_msg_params = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- smart_objects::SmartObject& msg_params = *p_msg_params;
-
- content[strings::msg_params] = msg_params;
-
- //content[strings::msg_params][strings::app_id] = connection_key;
-
- content[strings::msg_params]["permissionItem"] = smart_objects::SmartObject(
- smart_objects::SmartType_Array);
-
- smart_objects::SmartObject& permissions_item_array =
- content[strings::msg_params]["permissionItem"];
-
- policy::Permissions::const_iterator it_permissions = permissions.begin();
- policy::Permissions::const_iterator it_permissions_end = permissions.end();
-
- for (size_t index_pi = 0; it_permissions != it_permissions_end;
- ++it_permissions, ++index_pi) {
-
- permissions_item_array[index_pi] = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- smart_objects::SmartObject& permission_item =
- permissions_item_array[index_pi];
-
- // Filling the rpcName of PermissionItem
- permission_item["rpcName"] = (*it_permissions).first;
- const policy::RpcPermissions& rpc_permissions = (*it_permissions).second;
-
- // Creating SO for hmiPermissions
- permission_item["hmiPermissions"] = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- smart_objects::SmartObject& hmi_permissions =
- permission_item["hmiPermissions"];
-
- policy::HMIPermissions::const_iterator it_hmi_permissions = rpc_permissions
- .hmi_permissions.begin();
- policy::HMIPermissions::const_iterator it_hmi_permissions_end =
- rpc_permissions.hmi_permissions.end();
-
- // Filling the hmiPermissions of PermissionItem
- for (; it_hmi_permissions != it_hmi_permissions_end; ++it_hmi_permissions) {
- // Possible key names are "allowed", "userDisallowed"
- hmi_permissions[(*it_hmi_permissions).first] = smart_objects::SmartObject(
- smart_objects::SmartType_Array);
-
- smart_objects::SmartObject& hmi_levels =
- hmi_permissions[(*it_hmi_permissions).first];
-
- std::set<policy::HMILevel>::const_iterator it_hmi_levels =
- (*it_hmi_permissions).second.begin();
- std::set<policy::HMILevel>::const_iterator it_hmi_levels_end =
- (*it_hmi_permissions).second.end();
-
- for (size_t index_hmi_levels = 0; it_hmi_levels != it_hmi_levels_end;
- ++it_hmi_levels, ++index_hmi_levels) {
- hmi_levels[index_hmi_levels] = *it_hmi_levels;
- }
- }
-
- // Creating SO for parameterPermissions
- permission_item["parameterPermissions"] = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
-
- smart_objects::SmartObject& parameter_permissions =
- permission_item["parameterPermissions"];
-
- policy::ParameterPermissions::const_iterator it_parameter_permissions =
- rpc_permissions.parameter_permissions.begin();
- policy::ParameterPermissions::const_iterator it_parameter_permissions_end =
- rpc_permissions.parameter_permissions.end();
-
- // Filling the parameterPermissions of PermissionItem
- for (; it_parameter_permissions != it_parameter_permissions_end;
- ++it_parameter_permissions) {
- // Possible key names are "allowed", "userDisallowed"
- parameter_permissions[(*it_parameter_permissions).first] =
- smart_objects::SmartObject(smart_objects::SmartType_Array);
-
- smart_objects::SmartObject& parameters =
- parameter_permissions[(*it_parameter_permissions).first];
-
- std::set<policy::Parameter>::const_iterator it_parameters =
- (*it_parameter_permissions).second.begin();
- std::set<policy::Parameter>::const_iterator it_parameters_end =
- (*it_parameter_permissions).second.end();
-
- for (size_t index_parameters = 0; it_parameters != it_parameters_end;
- ++it_parameters, ++index_parameters) {
- parameters[index_parameters] = *it_parameters;
- }
- }
- }
-
- ApplicationManagerImpl::instance()->ManageMobileCommand(notification);
-}
-
-void MessageHelper::FillAppRevokedPermissions(
- const policy::AppPermissions& permissions,
- smart_objects::SmartObject& message) {
-
- message[strings::msg_params]["appRevokedPermissions"] =
- smart_objects::SmartObject(smart_objects::SmartType_Array);
- smart_objects::SmartObject& revoked_permission_items =
- message[strings::msg_params]["appRevokedPermissions"];
- for (size_t i = 0; i < permissions.appRevokedPermissions.size(); ++i) {
- revoked_permission_items[i] = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- smart_objects::SmartObject& permission_item = revoked_permission_items[i];
- permission_item["name"] = permissions.appRevokedPermissions[i].
- group_alias;
-
- permission_item["id"] = permissions.appRevokedPermissions[i].group_id;
-
- if (policy::kGroupUndefined !=
- permissions.appRevokedPermissions[i].state) {
- permission_item["allowed"] =
- policy::kGroupAllowed == permissions.appRevokedPermissions[i].state
- ? true : false;
- }
- }
-}
-
-void MessageHelper::SendOnAppPermissionsChangedNotification(
- uint32_t connection_key, const policy::AppPermissions& permissions) {
- using namespace smart_objects;
- SmartObjectSPtr notification = new SmartObject(SmartType_Map);
- if (!notification) {
- return;
- }
-
- SmartObject& message = *notification;
-
- message[strings::params][strings::function_id] =
- hmi_apis::FunctionID::SDL_OnAppPermissionChanged;
-
- message[strings::params][strings::message_type] = MessageType::kNotification;
- message[strings::msg_params][strings::app_id] = connection_key;
-
- // TODO(AOleynik): Add other parameters processing from incoming struct
- if (permissions.appRevoked) {
- message[strings::msg_params]["appRevoked"] = permissions.appRevoked;
- }
- if (permissions.isAppPermissionsRevoked) {
- message[strings::msg_params]["isAppPermissionsRevoked"] = permissions
- .isAppPermissionsRevoked;
-
- FillAppRevokedPermissions(permissions, message);
- }
-
- if (permissions.appPermissionsConsentNeeded) {
- message[strings::msg_params]["appPermissionsConsentNeeded"] = permissions
- .appPermissionsConsentNeeded;
- }
- if (permissions.appUnauthorized) {
- message[strings::msg_params]["appUnauthorized"] = permissions
- .appUnauthorized;
- }
- if (!permissions.priority.empty()) {
- message[strings::msg_params]["priority"] = GetPriorityCode(
- permissions.priority);
- }
- if (permissions.requestTypeChanged) {
- SmartObject request_types_array = SmartObject(SmartType_Array);
- for (uint16_t index = 0; index < permissions.requestType.size(); ++index) {
- request_types_array[index] = permissions.requestType[index];
- }
- message[strings::msg_params][strings::request_type] =
- request_types_array;
- }
-
- ApplicationManagerImpl::instance()->ManageHMICommand(notification);
-}
-
-void MessageHelper::SendGetStatusUpdateResponse(const std::string& status,
- uint32_t correlation_id) {
- smart_objects::SmartObjectSPtr message = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- if (!message) {
- return;
- }
-
- (*message)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::SDL_GetStatusUpdate;
- (*message)[strings::params][strings::message_type] =
- MessageType::kResponse;
- (*message)[strings::params][strings::correlation_id] = correlation_id;
- (*message)[strings::params][hmi_response::code] = 0;
-
- (*message)[strings::msg_params]["status"] = status;
-
- ApplicationManagerImpl::instance()->ManageHMICommand(message);
-}
-
-void MessageHelper::SendUpdateSDLResponse(const std::string& result,
- uint32_t correlation_id) {
- smart_objects::SmartObjectSPtr message = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- if (!message) {
- return;
- }
-
- (*message)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::SDL_UpdateSDL;
- (*message)[strings::params][strings::message_type] =
- MessageType::kResponse;
- (*message)[strings::params][strings::correlation_id] = correlation_id;
- (*message)[strings::params][hmi_response::code] = 0;
-
- (*message)[strings::msg_params]["result"] = result;
-
- ApplicationManagerImpl::instance()->ManageHMICommand(message);
-}
-
-void MessageHelper::SendOnStatusUpdate(const std::string& status) {
- smart_objects::SmartObjectSPtr message = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- if (!message) {
- return;
- }
-
- (*message)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::SDL_OnStatusUpdate;
- (*message)[strings::params][strings::message_type] =
- MessageType::kNotification;
-
- (*message)[strings::msg_params]["status"] = status;
-
- ApplicationManagerImpl::instance()->ManageHMICommand(message);
-}
-
-void MessageHelper::SendGetSystemInfoRequest() {
- smart_objects::SmartObjectSPtr message = new smart_objects::SmartObject(
- smart_objects::SmartType_Map);
- if (!message) {
- return;
- }
-
- (*message)[strings::params][strings::function_id] =
- hmi_apis::FunctionID::BasicCommunication_GetSystemInfo;
- (*message)[strings::params][strings::message_type] =
- MessageType::kRequest;
- (*message)[strings::params][strings::correlation_id] =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
- (*message)[strings::params][strings::protocol_version] =
- commands::CommandImpl::protocol_version_;
- (*message)[strings::params][strings::protocol_type] =
- commands::CommandImpl::hmi_protocol_type_;
-
- ApplicationManagerImpl::instance()->ManageHMICommand(message);
-}
-
-mobile_apis::Result::eType MessageHelper::VerifyImageFiles(
- smart_objects::SmartObject& message, ApplicationConstSharedPtr app) {
- if (NsSmartDeviceLink::NsSmartObjects::SmartType_Array == message.getType()) {
- for (uint32_t i = 0; i < message.length(); ++i) {
- mobile_apis::Result::eType res = VerifyImageFiles(message[i], app);
- if (mobile_apis::Result::SUCCESS != res) {
- LOG4CXX_DEBUG(logger_, "VerifyImageFiles result:" << res);
- return res;
- }
- }
- } else if (NsSmartDeviceLink::NsSmartObjects::SmartType_Map
- == message.getType()) {
- if (message.keyExists(strings::image_type)) {
- mobile_apis::Result::eType verification_result = VerifyImage(message,
- app);
-
- if (mobile_apis::Result::SUCCESS != verification_result) {
- LOG4CXX_DEBUG(logger_, "VerifyImageFiles result:" << verification_result);
- return verification_result; // exit point
- }
- } else {
- std::set<std::string> keys = message.enumerate();
-
- for (std::set<std::string>::const_iterator key = keys.begin();
- key != keys.end(); ++key) {
- if (strings::soft_buttons != (*key)) {
- mobile_apis::Result::eType res = VerifyImageFiles(message[*key], app);
- if (mobile_apis::Result::SUCCESS != res) {
- LOG4CXX_DEBUG(logger_, "VerifyImageFiles result:" << res);
- return res;
- }
- }
- }
- }
- } // all other types shoudn't be processed
-
- return mobile_apis::Result::SUCCESS;
-}
-
-mobile_apis::Result::eType MessageHelper::VerifyImage(
- smart_objects::SmartObject& image, ApplicationConstSharedPtr app) {
- // Checking image type first: if STATIC - skip existence check, since it is
- // HMI related file and it should know it location
- const uint32_t image_type = image[strings::image_type].asUInt();
- mobile_apis::ImageType::eType type =
- static_cast<mobile_apis::ImageType::eType>(image_type);
- if (mobile_apis::ImageType::STATIC == type) {
- return mobile_apis::Result::SUCCESS;
- }
-
- const std::string& file_name = image[strings::value].asString();
-
- std::string str = file_name;
- str.erase(remove(str.begin(), str.end(), ' '), str.end());
- if (0 == str.size()) {
- return mobile_apis::Result::INVALID_DATA;
- }
-
- std::string full_file_path;
- if (file_name.size() > 0 && file_name[0] == '/') {
- full_file_path = file_name;
- } else {
- const std::string& app_storage_folder =
- profile::Profile::instance()->app_storage_folder();
- if (!app_storage_folder.empty()) {
-// TODO(nvaganov@luxoft.com): APPLINK-11293
- if (app_storage_folder[0] == '/') { // absolute path
- full_file_path = app_storage_folder + "/";
- }
- else { // relative path
- full_file_path = file_system::CurrentWorkingDirectory() + "/" +
- app_storage_folder + "/";
- }
- }
- else { // empty app storage folder
- full_file_path = file_system::CurrentWorkingDirectory() + "/";
- }
-
- full_file_path += app->folder_name();
- full_file_path += "/";
- full_file_path += file_name;
- }
-
- if (!file_system::FileExists(full_file_path)) {
- return mobile_apis::Result::INVALID_DATA;
- }
-
- image[strings::value] = full_file_path;
-
- return mobile_apis::Result::SUCCESS;
-}
-
-mobile_apis::Result::eType MessageHelper::VerifyImageVrHelpItems(
- smart_objects::SmartObject& message, ApplicationConstSharedPtr app) {
- mobile_apis::Result::eType verification_result_image =
- mobile_apis::Result::SUCCESS;
- for (uint32_t i = 0; i < message.length(); ++i) {
- if (message[i].keyExists(strings::image)) {
- verification_result_image = VerifyImage(message[i][strings::image], app);
- if (mobile_apis::Result::SUCCESS != verification_result_image) {
- return verification_result_image;
- }
- }
- }
- return mobile_apis::Result::SUCCESS;
-}
-
-bool MessageHelper::VerifySoftButtonString(const std::string& str) {
-
- if ((std::string::npos != str.find_first_of("\t\n")) ||
- (std::string::npos != str.find("\\n")) ||
- (std::string::npos != str.find("\\t")) ||
- (std::string::npos == str.find_first_not_of(' '))) {
- LOG4CXX_ERROR(logger_, "MessageHelper::VerifySoftButtonString"
- "string contains incorrect character");
- return false;
- }
- return true;
-}
-
-bool MessageHelper::CheckWithPolicy(
- mobile_api::SystemAction::eType system_action,
- const std::string& app_mobile_id) {
- using namespace mobile_apis;
- bool result = true;
- policy::PolicyHandler* policy_handler = policy::PolicyHandler::instance();
- if (NULL != policy_handler && policy_handler->PolicyEnabled()) {
- result = policy_handler->CheckSystemAction(system_action, app_mobile_id);
- }
-
- return result;
-}
-
-mobile_apis::Result::eType MessageHelper::ProcessSoftButtons(
- smart_objects::SmartObject& message_params, ApplicationConstSharedPtr app) {
- using namespace mobile_apis;
- using namespace smart_objects;
-
- if (!message_params.keyExists(strings::soft_buttons)) {
- return mobile_apis::Result::SUCCESS;
- }
-
- const HMICapabilities& hmi_capabilities = ApplicationManagerImpl::instance()
- ->hmi_capabilities();
- const SmartObject* soft_button_capabilities = hmi_capabilities
- .soft_button_capabilities();
- bool image_supported = false;
- if (soft_button_capabilities) {
- image_supported = (*soft_button_capabilities)[hmi_response::image_supported]
- .asBool();
- }
-
- SmartObject& request_soft_buttons = message_params[strings::soft_buttons];
-
- // Check whether soft buttons request is well-formed
- if (!ValidateSoftButtons(request_soft_buttons)) {
- return Result::INVALID_DATA;
- }
-
- SmartObject soft_buttons(SmartType_Array);
-
- uint32_t j = 0;
- size_t size = request_soft_buttons.length();
- for (uint32_t i = 0; i < size; ++i) {
- const int system_action = request_soft_buttons[i][strings::system_action].asInt();
-
- if (!CheckWithPolicy(static_cast<SystemAction::eType>(system_action),
- app->mobile_app_id())) {
- return Result::DISALLOWED;
- }
-
- switch (request_soft_buttons[i][strings::type].asInt()) {
- case SoftButtonType::SBT_IMAGE: {
- if (!image_supported) {
- continue;
- }
- //Any text value for type "IMAGE" should be ignored.
- if (request_soft_buttons[i].keyExists(strings::text)) {
- request_soft_buttons[i].erase(strings::text);
- }
- if (request_soft_buttons[i].keyExists(strings::image)) {
- Result::eType verification_result = VerifyImage(
- request_soft_buttons[i][strings::image], app);
- if (Result::SUCCESS != verification_result) {
- return Result::INVALID_DATA;
- }
- } else {
- return Result::INVALID_DATA;
- }
- break;
- }
- case SoftButtonType::SBT_TEXT: {
- if ((!request_soft_buttons[i].keyExists(strings::text)) ||
- (!VerifySoftButtonString(
- request_soft_buttons[i][strings::text].asString()))) {
- return Result::INVALID_DATA;
- }
- break;
- }
- case SoftButtonType::SBT_BOTH: {
-
- if ((!request_soft_buttons[i].keyExists(strings::text)) ||
- ((request_soft_buttons[i][strings::text].length())
- && (!VerifySoftButtonString(
- request_soft_buttons[i][strings::text].asString())))) {
- return Result::INVALID_DATA;
- }
-
- bool image_exist = false;
- if (image_supported) {
- image_exist = request_soft_buttons[i].keyExists(strings::image);
- if (!image_exist) {
- return Result::INVALID_DATA;
- }
- }
- if (image_exist) {
- Result::eType verification_result = VerifyImage(
- request_soft_buttons[i][strings::image], app);
-
- if (Result::SUCCESS != verification_result) {
- return Result::INVALID_DATA;
-
- }
- }
- break;
- }
- default: {
- continue;
- break;
- }
- }
-
- soft_buttons[j] = request_soft_buttons[i];
- ++j;
- }
-
- request_soft_buttons = soft_buttons;
-
- if (0 == request_soft_buttons.length()) {
- message_params.erase(strings::soft_buttons);
- }
- return Result::SUCCESS;
-}
-
-void MessageHelper::SubscribeApplicationToSoftButton(
- smart_objects::SmartObject& message_params, ApplicationSharedPtr app,
- int32_t function_id) {
- SoftButtonID softbuttons_id;
- smart_objects::SmartObject& soft_buttons = message_params[strings::soft_buttons];
- unsigned int length = soft_buttons.length();
- for(unsigned int i = 0; i < length; ++i) {
- softbuttons_id.insert(soft_buttons[i][strings::soft_button_id].asUInt());
- }
- app->SubscribeToSoftButtons(function_id, softbuttons_id);
-}
-
-// TODO(AK): change printf to logger
-bool MessageHelper::PrintSmartObject(const smart_objects::SmartObject& object) {
- return true;
-#ifdef ENABLE_LOG
- static uint32_t tab = 0;
- std::string tab_buffer;
-
- if (tab == 0) {
- printf("\n-------------------------------------------------------------");
- }
-
- for (uint32_t i = 0; i < tab; ++i) {
- tab_buffer += "\t";
- }
-
- switch (object.getType()) {
- case NsSmartDeviceLink::NsSmartObjects::SmartType_Array: {
- for (size_t i = 0; i < object.length(); i++) {
- ++tab;
-
- printf("\n%s%zu: ", tab_buffer.c_str(), i);
- if (!PrintSmartObject(object.getElement(i))) {
- printf("\n");
- return false;
- }
- }
- break;
- }
- case NsSmartDeviceLink::NsSmartObjects::SmartType_Map: {
- std::set<std::string> keys = object.enumerate();
-
- for (std::set<std::string>::const_iterator key = keys.begin();
- key != keys.end(); key++) {
- ++tab;
-
- printf("\n%s%s: ", tab_buffer.c_str(), (*key).c_str());
- if (!PrintSmartObject(object[(*key).c_str()])) {
- printf("\n");
- return false;
- }
- }
- break;
- }
- case NsSmartDeviceLink::NsSmartObjects::SmartType_Boolean:
- object.asBool() ? printf("true\n") : printf("false\n");
- break;
- case NsSmartDeviceLink::NsSmartObjects::SmartType_Double: {
- printf("%f", object.asDouble());
- break;
- }
- case NsSmartDeviceLink::NsSmartObjects::SmartType_Integer:
- break;
- case NsSmartDeviceLink::NsSmartObjects::SmartType_String:
- printf("%s", object.asString().c_str());
- break;
- case NsSmartDeviceLink::NsSmartObjects::SmartType_Character:
- printf("%c", object.asChar());
- break;
- default:
- printf("PrintSmartObject - default case\n");
- break;
- }
-
- if (0 != tab) {
- --tab;
- } else {
- printf("\n-------------------------------------------------------------\n");
- }
-#endif
- return true;
-}
-
-} // namespace application_manager
diff --git a/src/components/application_manager/src/message_helper/message_helper.cc b/src/components/application_manager/src/message_helper/message_helper.cc
new file mode 100644
index 0000000000..08efba3d70
--- /dev/null
+++ b/src/components/application_manager/src/message_helper/message_helper.cc
@@ -0,0 +1,2501 @@
+/*
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/message_helper.h"
+
+#define __STDC_FORMAT_MACROS
+#include <inttypes.h>
+#undef __STDC_FORMAT_MACROS
+
+#include <set>
+#include <string>
+#include <algorithm>
+#include <utility>
+#include <map>
+
+#include "application_manager/application.h"
+#include "application_manager/application_manager.h"
+#include "application_manager/commands/command_impl.h"
+#include "application_manager/message_helper.h"
+#include "application_manager/policies/policy_handler_interface.h"
+#include "application_manager/resumption/resume_ctrl.h"
+#include "connection_handler/connection_handler_impl.h"
+#include "interfaces/MOBILE_API.h"
+#include "smart_objects/enum_schema_item.h"
+#include "utils/file_system.h"
+#include "utils/macro.h"
+#include "utils/logger.h"
+#include "utils/make_shared.h"
+
+#include "formatters/formatter_json_rpc.h"
+#include "formatters/CFormatterJsonSDLRPCv2.h"
+#include "formatters/CFormatterJsonSDLRPCv1.h"
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationManager")
+
+namespace application_manager {
+
+namespace {
+
+typedef std::map<std::string, hmi_apis::Common_AppPriority::eType>
+ CommonAppPriorityMap;
+
+CommonAppPriorityMap app_priority_values = {
+ {"NORMAL", hmi_apis::Common_AppPriority::NORMAL},
+ {"COMMUNICATION", hmi_apis::Common_AppPriority::COMMUNICATION},
+ {"EMERGENCY", hmi_apis::Common_AppPriority::EMERGENCY},
+ {"NAVIGATION", hmi_apis::Common_AppPriority::NAVIGATION},
+ {"NONE", hmi_apis::Common_AppPriority::NONE},
+ {"VOICECOM", hmi_apis::Common_AppPriority::VOICE_COMMUNICATION},
+ {"INVALID_ENUM", hmi_apis::Common_AppPriority::INVALID_ENUM}};
+
+bool ValidateSoftButtons(smart_objects::SmartObject& soft_buttons) {
+ using namespace smart_objects;
+ for (size_t i = 0; i < soft_buttons.length(); ++i) {
+ SmartObject& button = soft_buttons[i];
+
+ // Check if image parameter is valid
+ if (button.keyExists(strings::image)) {
+ SmartObject& buttonImage = button[strings::image];
+
+ // Image name must not be empty and must not contain incorrect
+ // character
+ if (false == MessageHelper::VerifySoftButtonString(
+ buttonImage[strings::value].asString())) {
+ return false;
+ }
+ }
+ }
+ return true;
+} // namespace
+}
+std::pair<std::string, VehicleDataType> kVehicleDataInitializer[] = {
+ std::make_pair(strings::gps, VehicleDataType::GPS),
+ std::make_pair(strings::speed, VehicleDataType::SPEED),
+ std::make_pair(strings::rpm, VehicleDataType::RPM),
+ std::make_pair(strings::fuel_level, VehicleDataType::FUELLEVEL),
+ std::make_pair(strings::fuel_level_state, VehicleDataType::FUELLEVEL_STATE),
+ std::make_pair(strings::instant_fuel_consumption,
+ VehicleDataType::FUELCONSUMPTION),
+ std::make_pair(strings::external_temp, VehicleDataType::EXTERNTEMP),
+ std::make_pair(strings::vin, VehicleDataType::VIN),
+ std::make_pair(strings::prndl, VehicleDataType::PRNDL),
+ std::make_pair(strings::tire_pressure, VehicleDataType::TIREPRESSURE),
+ std::make_pair(strings::odometer, VehicleDataType::ODOMETER),
+ std::make_pair(strings::belt_status, VehicleDataType::BELTSTATUS),
+ std::make_pair(strings::body_information, VehicleDataType::BODYINFO),
+ std::make_pair(strings::device_status, VehicleDataType::DEVICESTATUS),
+ std::make_pair(strings::driver_braking, VehicleDataType::BRAKING),
+ std::make_pair(strings::wiper_status, VehicleDataType::WIPERSTATUS),
+ std::make_pair(strings::head_lamp_status, VehicleDataType::HEADLAMPSTATUS),
+ std::make_pair(strings::e_call_info, VehicleDataType::ECALLINFO),
+ std::make_pair(strings::airbag_status, VehicleDataType::AIRBAGSTATUS),
+ std::make_pair(strings::emergency_event, VehicleDataType::EMERGENCYEVENT),
+ std::make_pair(strings::cluster_mode_status,
+ VehicleDataType::CLUSTERMODESTATUS),
+ std::make_pair(strings::my_key, VehicleDataType::MYKEY),
+ /*
+ NOT DEFINED in mobile API
+ std::make_pair(strings::gps, VehicleDataType::BATTVOLTAGE),
+ */
+ std::make_pair(strings::engine_torque, VehicleDataType::ENGINETORQUE),
+ std::make_pair(strings::acc_pedal_pos, VehicleDataType::ACCPEDAL),
+ std::make_pair(strings::steering_wheel_angle,
+ VehicleDataType::STEERINGWHEEL),
+};
+
+const VehicleData MessageHelper::vehicle_data_(
+ kVehicleDataInitializer,
+ kVehicleDataInitializer + ARRAYSIZE(kVehicleDataInitializer));
+
+#ifdef HMI_DBUS_API
+namespace {
+struct VehicleInfo_Requests {
+ hmi_apis::FunctionID::eType func_id;
+ const char* str;
+};
+static VehicleInfo_Requests ivi_subrequests[] = {
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeGps, strings::gps},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeSpeed, strings::speed},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeRpm, strings::rpm},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel, strings::fuel_level},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeFuelLevel_State,
+ strings::fuel_level_state},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeInstantFuelConsumption,
+ strings::instant_fuel_consumption},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeExternalTemperature,
+ strings::external_temp},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeVin, strings::vin},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribePrndl, strings::prndl},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeTirePressure,
+ strings::tire_pressure},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeOdometer, strings::odometer},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeBeltStatus,
+ strings::belt_status},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeBodyInformation,
+ strings::body_information},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeDeviceStatus,
+ strings::device_status},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeDriverBraking,
+ strings::driver_braking},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeWiperStatus,
+ strings::wiper_status},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeHeadLampStatus,
+ strings::head_lamp_status},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeEngineTorque,
+ strings::engine_torque},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeAccPedalPosition,
+ strings::acc_pedal_pos},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeSteeringWheelAngle,
+ strings::steering_wheel_angle},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeECallInfo,
+ strings::e_call_info},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeAirbagStatus,
+ strings::airbag_status},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeEmergencyEvent,
+ strings::emergency_event},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeClusterModeStatus,
+ strings::cluster_mode_status},
+ {hmi_apis::FunctionID::VehicleInfo_SubscribeMyKey, strings::my_key},
+};
+}
+#endif // #ifdef HMI_DBUS_API
+
+const uint32_t MessageHelper::GetPriorityCode(const std::string& priority) {
+ CommonAppPriorityMap::const_iterator it = app_priority_values.find(priority);
+ if (app_priority_values.end() != it) {
+ return static_cast<uint32_t>((*it).second);
+ }
+ return static_cast<uint32_t>(hmi_apis::Common_AppPriority::INVALID_ENUM);
+}
+
+std::string MessageHelper::CommonLanguageToString(
+ hmi_apis::Common_Language::eType language) {
+ using namespace NsSmartDeviceLink::NsSmartObjects;
+ const char* str = 0;
+ if (EnumConversionHelper<hmi_apis::Common_Language::eType>::EnumToCString(
+ language, &str)) {
+ return str ? str : "";
+ }
+ return std::string();
+}
+
+hmi_apis::Common_Language::eType MessageHelper::CommonLanguageFromString(
+ const std::string& language) {
+ using namespace NsSmartDeviceLink::NsSmartObjects;
+ hmi_apis::Common_Language::eType value;
+ if (EnumConversionHelper<hmi_apis::Common_Language::eType>::StringToEnum(
+ language, &value)) {
+ return value;
+ }
+ return hmi_apis::Common_Language::INVALID_ENUM;
+}
+
+smart_objects::SmartObjectSPtr MessageHelper::CreateRequestObject(
+ const uint32_t correlation_id) {
+ using namespace smart_objects;
+
+ SmartObjectSPtr request = utils::MakeShared<SmartObject>(SmartType_Map);
+ SmartObject& ref = *request;
+
+ ref[strings::params][strings::message_type] =
+ static_cast<int>(hmi_apis::messageType::request);
+ ref[strings::params][strings::protocol_version] =
+ commands::CommandImpl::protocol_version_;
+ ref[strings::params][strings::protocol_type] =
+ commands::CommandImpl::hmi_protocol_type_;
+ ref[strings::params][strings::correlation_id] = correlation_id;
+ return request;
+}
+
+smart_objects::SmartObjectSPtr MessageHelper::CreateHashUpdateNotification(
+ const uint32_t app_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObjectSPtr message =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+ (*message)[strings::params][strings::function_id] =
+ mobile_apis::FunctionID::OnHashChangeID;
+ (*message)[strings::params][strings::connection_key] = app_id;
+ (*message)[strings::params][strings::message_type] =
+ static_cast<int32_t>(kNotification);
+ return message;
+}
+
+void MessageHelper::SendHashUpdateNotification(const uint32_t app_id,
+ ApplicationManager& app_mngr) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ ApplicationSharedPtr app = app_mngr.application(app_id);
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Application not found by appID");
+ return;
+ }
+ smart_objects::SmartObjectSPtr so = CreateHashUpdateNotification(app_id);
+ PrintSmartObject(*so);
+ if (!app_mngr.ManageMobileCommand(so, commands::Command::ORIGIN_SDL)) {
+ LOG4CXX_ERROR(logger_, "Failed to send HashUpdate notification.");
+ return;
+ }
+ app_mngr.resume_controller().ApplicationsDataUpdated();
+}
+
+smart_objects::SmartObjectSPtr
+MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ int32_t connection_key,
+ mobile_api::AppInterfaceUnregisteredReason::eType reason) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ smart_objects::SmartObjectSPtr notification =
+ utils::MakeShared<smart_objects::SmartObject>();
+ smart_objects::SmartObject& message = *notification;
+
+ message[strings::params][strings::function_id] = static_cast<int32_t>(
+ mobile_api::FunctionID::OnAppInterfaceUnregisteredID);
+
+ message[strings::params][strings::message_type] =
+ static_cast<int32_t>(kNotification);
+
+ message[strings::params][strings::connection_key] = connection_key;
+
+ message[strings::msg_params][strings::reason] = static_cast<int32_t>(reason);
+
+ return notification;
+}
+
+const VehicleData& MessageHelper::vehicle_data() {
+ return vehicle_data_;
+}
+
+std::string MessageHelper::HMIResultToString(
+ hmi_apis::Common_Result::eType hmi_result) {
+ using namespace NsSmartDeviceLink::NsSmartObjects;
+ const char* str = 0;
+ if (EnumConversionHelper<hmi_apis::Common_Result::eType>::EnumToCString(
+ hmi_result, &str)) {
+ return str;
+ }
+ return std::string();
+}
+
+hmi_apis::Common_Result::eType MessageHelper::HMIResultFromString(
+ const std::string& hmi_result) {
+ using namespace NsSmartDeviceLink::NsSmartObjects;
+ hmi_apis::Common_Result::eType value;
+ if (EnumConversionHelper<hmi_apis::Common_Result::eType>::StringToEnum(
+ hmi_result, &value)) {
+ return value;
+ }
+ return hmi_apis::Common_Result::INVALID_ENUM;
+}
+
+std::string MessageHelper::MobileResultToString(
+ mobile_apis::Result::eType mobile_result) {
+ using namespace NsSmartDeviceLink::NsSmartObjects;
+ const char* str = 0;
+ if (EnumConversionHelper<mobile_apis::Result::eType>::EnumToCString(
+ mobile_result, &str)) {
+ return str;
+ }
+ return std::string();
+}
+
+mobile_apis::Result::eType MessageHelper::MobileResultFromString(
+ const std::string& mobile_result) {
+ using namespace NsSmartDeviceLink::NsSmartObjects;
+ mobile_apis::Result::eType value;
+ if (EnumConversionHelper<mobile_apis::Result::eType>::StringToEnum(
+ mobile_result, &value)) {
+ return value;
+ }
+ return mobile_apis::Result::INVALID_ENUM;
+}
+
+mobile_apis::Result::eType MessageHelper::HMIToMobileResult(
+ const hmi_apis::Common_Result::eType hmi_result) {
+ const std::string result = HMIResultToString(hmi_result);
+ if (result.empty()) {
+ return mobile_api::Result::INVALID_ENUM;
+ }
+ return MobileResultFromString(result);
+}
+
+hmi_apis::Common_Result::eType MessageHelper::MobileToHMIResult(
+ const mobile_apis::Result::eType mobile_result) {
+ const std::string result = MobileResultToString(mobile_result);
+ if (result.empty()) {
+ return hmi_apis::Common_Result::INVALID_ENUM;
+ }
+ return HMIResultFromString(result);
+}
+
+mobile_apis::HMILevel::eType MessageHelper::StringToHMILevel(
+ const std::string& hmi_level) {
+ using namespace NsSmartDeviceLink::NsSmartObjects;
+ mobile_apis::HMILevel::eType value;
+ if (EnumConversionHelper<mobile_apis::HMILevel::eType>::StringToEnum(
+ hmi_level, &value)) {
+ return value;
+ }
+ return mobile_apis::HMILevel::INVALID_ENUM;
+}
+
+std::string MessageHelper::StringifiedHMILevel(
+ mobile_apis::HMILevel::eType hmi_level) {
+ using namespace NsSmartDeviceLink::NsSmartObjects;
+ const char* str = 0;
+ if (EnumConversionHelper<mobile_apis::HMILevel::eType>::EnumToCString(
+ hmi_level, &str)) {
+ return str;
+ }
+ return std::string();
+}
+
+std::string MessageHelper::StringifiedFunctionID(
+ mobile_apis::FunctionID::eType function_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace NsSmartDeviceLink::NsSmartObjects;
+ const char* str = 0;
+ if (EnumConversionHelper<mobile_apis::FunctionID::eType>::EnumToCString(
+ function_id, &str)) {
+ const std::string enum_name = str;
+ // Strip 'ID' suffix from value name
+ DCHECK(enum_name.length() > 2 &&
+ enum_name.substr(enum_name.length() - 2) == "ID");
+ return enum_name.substr(0, enum_name.length() - 2);
+ }
+ return std::string();
+}
+
+#ifdef HMI_DBUS_API
+namespace {
+const std::map<std::string, uint16_t> create_get_vehicle_data_args() {
+ std::map<std::string, uint16_t> rc;
+ rc.insert(std::make_pair(strings::gps,
+ hmi_apis::FunctionID::VehicleInfo_GetGpsData));
+ rc.insert(std::make_pair(strings::speed,
+ hmi_apis::FunctionID::VehicleInfo_GetSpeed));
+ rc.insert(
+ std::make_pair(strings::rpm, hmi_apis::FunctionID::VehicleInfo_GetRpm));
+ rc.insert(std::make_pair(strings::fuel_level,
+ hmi_apis::FunctionID::VehicleInfo_GetFuelLevel));
+ rc.insert(
+ std::make_pair(strings::fuel_level_state,
+ hmi_apis::FunctionID::VehicleInfo_GetFuelLevelState));
+ rc.insert(std::make_pair(
+ strings::instant_fuel_consumption,
+ hmi_apis::FunctionID::VehicleInfo_GetInstantFuelConsumption));
+ rc.insert(
+ std::make_pair(strings::external_temp,
+ hmi_apis::FunctionID::VehicleInfo_GetExternalTemperature));
+ rc.insert(
+ std::make_pair(strings::vin, hmi_apis::FunctionID::VehicleInfo_GetVin));
+ rc.insert(std::make_pair(strings::prndl,
+ hmi_apis::FunctionID::VehicleInfo_GetPrndl));
+ rc.insert(std::make_pair(strings::tire_pressure,
+ hmi_apis::FunctionID::VehicleInfo_GetTirePressure));
+ rc.insert(std::make_pair(strings::odometer,
+ hmi_apis::FunctionID::VehicleInfo_GetOdometer));
+ rc.insert(std::make_pair(strings::belt_status,
+ hmi_apis::FunctionID::VehicleInfo_GetBeltStatus));
+ rc.insert(
+ std::make_pair(strings::body_information,
+ hmi_apis::FunctionID::VehicleInfo_GetBodyInformation));
+ rc.insert(std::make_pair(strings::device_status,
+ hmi_apis::FunctionID::VehicleInfo_GetDeviceStatus));
+ rc.insert(std::make_pair(strings::driver_braking,
+ hmi_apis::FunctionID::VehicleInfo_GetDriverBraking));
+ rc.insert(std::make_pair(strings::wiper_status,
+ hmi_apis::FunctionID::VehicleInfo_GetWiperStatus));
+ rc.insert(
+ std::make_pair(strings::head_lamp_status,
+ hmi_apis::FunctionID::VehicleInfo_GetHeadLampStatus));
+ rc.insert(std::make_pair(strings::engine_torque,
+ hmi_apis::FunctionID::VehicleInfo_GetEngineTorque));
+ rc.insert(
+ std::make_pair(strings::acc_pedal_pos,
+ hmi_apis::FunctionID::VehicleInfo_GetAccPedalPosition));
+ rc.insert(
+ std::make_pair(strings::steering_wheel_angle,
+ hmi_apis::FunctionID::VehicleInfo_GetSteeringWheelAngle));
+ rc.insert(std::make_pair(strings::e_call_info,
+ hmi_apis::FunctionID::VehicleInfo_GetECallInfo));
+ rc.insert(std::make_pair(strings::airbag_status,
+ hmi_apis::FunctionID::VehicleInfo_GetAirbagStatus));
+ rc.insert(
+ std::make_pair(strings::emergency_event,
+ hmi_apis::FunctionID::VehicleInfo_GetEmergencyEvent));
+ rc.insert(
+ std::make_pair(strings::cluster_mode_status,
+ hmi_apis::FunctionID::VehicleInfo_GetClusterModeStatus));
+ rc.insert(std::make_pair(strings::my_key,
+ hmi_apis::FunctionID::VehicleInfo_GetMyKey));
+ return rc;
+}
+static std::map<std::string, uint16_t> vehicle_data_args =
+ create_get_vehicle_data_args();
+}
+#endif
+
+void MessageHelper::CreateGetVehicleDataRequest(
+ const uint32_t correlation_id,
+ const std::vector<std::string>& params,
+ ApplicationManager& app_mngr) {
+ LOG4CXX_AUTO_TRACE(logger_);
+#ifdef HMI_DBUS_API
+ for (std::vector<std::string>::const_iterator it = params.begin();
+ it != params.end();
+ it++) {
+ smart_objects::SmartObjectSPtr request =
+ utils::MakeShared<smart_objects::SmartObject>();
+
+ (*request)[strings::params][strings::message_type] =
+ static_cast<int>(kRequest);
+ (*request)[strings::params][strings::correlation_id] = correlation_id;
+ (*request)[strings::params][strings::protocol_version] =
+ commands::CommandImpl::protocol_version_;
+ (*request)[strings::params][strings::protocol_type] =
+ commands::CommandImpl::hmi_protocol_type_;
+ (*request)[strings::params][strings::function_id] =
+ static_cast<int>(vehicle_data_args[*it]);
+ app_mngr.ManageHMICommand(request);
+ }
+#else
+
+ smart_objects::SmartObjectSPtr request =
+ utils::MakeShared<smart_objects::SmartObject>();
+
+ (*request)[strings::params][strings::message_type] =
+ static_cast<int>(kRequest);
+ (*request)[strings::params][strings::function_id] =
+ static_cast<int>(hmi_apis::FunctionID::VehicleInfo_GetVehicleData);
+ (*request)[strings::params][strings::correlation_id] = correlation_id;
+ (*request)[strings::params][strings::protocol_version] =
+ commands::CommandImpl::protocol_version_;
+ (*request)[strings::params][strings::protocol_type] =
+ commands::CommandImpl::hmi_protocol_type_;
+ (*request)[strings::msg_params] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ for (std::vector<std::string>::const_iterator it = params.begin();
+ it != params.end();
+ it++) {
+ (*request)[strings::msg_params][*it] = true;
+ }
+ app_mngr.ManageHMICommand(request);
+#endif
+}
+
+smart_objects::SmartObjectSPtr MessageHelper::CreateBlockedByPoliciesResponse(
+ mobile_apis::FunctionID::eType function_id,
+ mobile_apis::Result::eType result,
+ const uint32_t correlation_id,
+ uint32_t connection_key) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObjectSPtr response =
+ utils::MakeShared<smart_objects::SmartObject>();
+
+ (*response)[strings::params][strings::function_id] =
+ static_cast<int>(function_id);
+ (*response)[strings::params][strings::message_type] =
+ static_cast<int>(kResponse);
+ (*response)[strings::msg_params][strings::success] = false;
+ (*response)[strings::msg_params][strings::result_code] =
+ static_cast<int>(result);
+ (*response)[strings::params][strings::correlation_id] = correlation_id;
+ (*response)[strings::params][strings::connection_key] = connection_key;
+ (*response)[strings::params][strings::protocol_type] =
+ commands::CommandImpl::mobile_protocol_type_;
+ (*response)[strings::params][strings::protocol_version] =
+ static_cast<int>(kV2);
+ return response;
+}
+
+smart_objects::SmartObjectSPtr MessageHelper::CreateDeviceListSO(
+ const connection_handler::DeviceMap& devices,
+ const policy::PolicyHandlerInterface& policy_handler,
+ ApplicationManager& app_mngr) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObjectSPtr device_list_so =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+
+ (*device_list_so)[strings::device_list] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+ smart_objects::SmartObject& list_so = (*device_list_so)[strings::device_list];
+
+ int32_t index = 0;
+ for (connection_handler::DeviceMap::const_iterator it = devices.begin();
+ devices.end() != it;
+ ++it) {
+ const connection_handler::Device& d =
+ static_cast<connection_handler::Device>(it->second);
+ list_so[index][strings::name] = d.user_friendly_name();
+ list_so[index][strings::id] = it->second.mac_address();
+
+ const policy::DeviceConsent device_consent =
+ policy_handler.GetUserConsentForDevice(it->second.mac_address());
+ list_so[index][strings::isSDLAllowed] =
+ policy::DeviceConsent::kDeviceAllowed == device_consent;
+ list_so[index][strings::transport_type] =
+ app_mngr.GetDeviceTransportType(d.connection_type());
+ ++index;
+ }
+ return device_list_so;
+}
+
+smart_objects::SmartObjectSPtr MessageHelper::CreateModuleInfoSO(
+ uint32_t function_id, ApplicationManager& app_mngr) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObjectSPtr module_info =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+ smart_objects::SmartObject& object = *module_info;
+ object[strings::params][strings::message_type] = static_cast<int>(kRequest);
+ object[strings::params][strings::function_id] = static_cast<int>(function_id);
+ object[strings::params][strings::correlation_id] =
+ app_mngr.GetNextHMICorrelationID();
+ object[strings::msg_params] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ return module_info;
+}
+
+smart_objects::SmartObjectSPtr MessageHelper::CreateSetAppIcon(
+ const std::string& path_to_icon, uint32_t app_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObjectSPtr set_icon =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+
+ if (!set_icon) {
+ return NULL;
+ }
+
+ smart_objects::SmartObject& object = *set_icon;
+ object[strings::sync_file_name][strings::value] = path_to_icon;
+ // TODO(PV): need to store actual image type
+ object[strings::sync_file_name][strings::image_type] =
+ static_cast<int>(mobile_api::ImageType::DYNAMIC);
+ object[strings::app_id] = app_id;
+
+ return set_icon;
+}
+
+bool MessageHelper::SendIVISubscribtions(const uint32_t app_id,
+ ApplicationManager& app_mngr) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ bool result = true;
+ ApplicationSharedPtr app = app_mngr.application(app_id);
+
+ if (!app.valid()) {
+ LOG4CXX_ERROR(logger_, "Invalid application " << app_id);
+ return result;
+ }
+
+ smart_objects::SmartObjectList requests =
+ GetIVISubscriptionRequests(app, app_mngr);
+ for (smart_objects::SmartObjectList::const_iterator it = requests.begin();
+ it != requests.end();
+ ++it) {
+ if (!app_mngr.ManageHMICommand(*it)) {
+ result = false;
+ }
+ }
+ return result;
+}
+
+smart_objects::SmartObjectList MessageHelper::GetIVISubscriptionRequests(
+ ApplicationSharedPtr app, ApplicationManager& app_mngr) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ smart_objects::SmartObjectList hmi_requests;
+ if (!app.valid()) {
+ LOG4CXX_ERROR(logger_, "Invalid application pointer ");
+ return hmi_requests;
+ }
+
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ msg_params[strings::app_id] = app->app_id();
+ const VehicleData& vehicle_data = MessageHelper::vehicle_data_;
+ VehicleData::const_iterator ivi_it = vehicle_data.begin();
+ DataAccessor<VehicleInfoSubscriptions> vi_accessor = app->SubscribedIVI();
+ const VehicleInfoSubscriptions& subscriptions = vi_accessor.GetData();
+
+ for (; vehicle_data.end() != ivi_it; ++ivi_it) {
+ uint32_t type_id = static_cast<int>(ivi_it->second);
+ if (subscriptions.end() != subscriptions.find(type_id)) {
+ std::string key_name = ivi_it->first;
+ msg_params[key_name] = true;
+ }
+ }
+
+#ifdef HMI_JSON_API
+ smart_objects::SmartObjectSPtr request = MessageHelper::CreateModuleInfoSO(
+ hmi_apis::FunctionID::VehicleInfo_SubscribeVehicleData, app_mngr);
+ (*request)[strings::msg_params] = msg_params;
+ hmi_requests.push_back(request);
+#endif // #ifdef HMI_JSON_API
+#ifdef HMI_DBUS_API
+ // Generate list of ivi_subrequests
+ for (size_t i = 0; i < sizeof(ivi_subrequests) / sizeof(ivi_subrequests[0]);
+ ++i) {
+ const VehicleInfo_Requests& sr = ivi_subrequests[i];
+ if (true == msg_params.keyExists(sr.str) &&
+ true == msg_params[sr.str].asBool()) {
+ smart_objects::SmartObjectSPtr request =
+ MessageHelper::CreateModuleInfoSO(sr.func_id);
+ (*request)[strings::msg_params] = msg_params;
+ hmi_requests.push_back(request);
+ }
+ }
+#endif // #ifdef HMI_DBUS_API
+ return hmi_requests;
+}
+
+void MessageHelper::SendOnButtonSubscriptionNotification(
+ uint32_t app_id,
+ hmi_apis::Common_ButtonName::eType button,
+ bool is_subscribed,
+ ApplicationManager& app_mngr) {
+ using namespace smart_objects;
+ using namespace hmi_apis;
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ SmartObjectSPtr notification_ptr =
+ utils::MakeShared<SmartObject>(SmartType_Map);
+ if (!notification_ptr) {
+ LOG4CXX_ERROR(logger_, "Memory allocation failed.");
+ return;
+ }
+ SmartObject& notification = *notification_ptr;
+
+ SmartObject msg_params = SmartObject(SmartType_Map);
+ msg_params[strings::app_id] = app_id;
+ msg_params[strings::name] = button;
+ msg_params[strings::is_suscribed] = is_subscribed;
+
+ notification[strings::params][strings::message_type] =
+ static_cast<int32_t>(application_manager::MessageType::kNotification);
+ notification[strings::params][strings::protocol_version] =
+ commands::CommandImpl::protocol_version_;
+ notification[strings::params][strings::protocol_type] =
+ commands::CommandImpl::hmi_protocol_type_;
+ notification[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::Buttons_OnButtonSubscription;
+ notification[strings::msg_params] = msg_params;
+
+ if (!app_mngr.ManageHMICommand(notification_ptr)) {
+ LOG4CXX_ERROR(logger_, "Unable to send HMI notification");
+ }
+}
+
+void MessageHelper::SendAllOnButtonSubscriptionNotificationsForApp(
+ ApplicationConstSharedPtr app, ApplicationManager& app_mngr) {
+ using namespace smart_objects;
+ using namespace hmi_apis;
+ using namespace mobile_apis;
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (!app.valid()) {
+ LOG4CXX_ERROR(logger_, "Invalid application pointer ");
+ return;
+ }
+
+ DataAccessor<ButtonSubscriptions> button_accessor = app->SubscribedButtons();
+ ButtonSubscriptions subscriptions = button_accessor.GetData();
+ ButtonSubscriptions::iterator it = subscriptions.begin();
+ for (; subscriptions.end() != it; ++it) {
+ SendOnButtonSubscriptionNotification(
+ app->hmi_app_id(),
+ static_cast<Common_ButtonName::eType>(*it),
+ true,
+ app_mngr);
+ }
+}
+
+void MessageHelper::SendSetAppIcon(
+ const uint32_t app_id,
+ const std::string& icon_path,
+ application_manager::ApplicationManager& application_manager) {
+ using namespace smart_objects;
+
+ SmartObjectSPtr set_app_icon =
+ CreateRequestObject(application_manager.GetNextHMICorrelationID());
+ if (set_app_icon) {
+ SmartObject& so_to_send = *set_app_icon;
+ so_to_send[strings::params][strings::function_id] =
+ static_cast<int>(hmi_apis::FunctionID::UI_SetAppIcon);
+
+ so_to_send[strings::msg_params] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ SmartObjectSPtr msg_params(
+ MessageHelper::CreateSetAppIcon(icon_path, app_id));
+
+ if (msg_params) {
+ so_to_send[strings::msg_params] = *msg_params;
+ }
+ application_manager.ManageHMICommand(set_app_icon);
+ }
+}
+
+void MessageHelper::SendAppDataToHMI(ApplicationConstSharedPtr app,
+ ApplicationManager& app_man) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (app) {
+ SendSetAppIcon(app, app->app_icon_path(), app_man);
+ SendGlobalPropertiesToHMI(app, app_man);
+ SendShowRequestToHMI(app, app_man);
+ }
+}
+
+void MessageHelper::SendGlobalPropertiesToHMI(ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr) {
+ if (!app.valid()) {
+ LOG4CXX_ERROR(logger_, "Invalid application");
+ return;
+ }
+
+ smart_objects::SmartObjectList requests = CreateGlobalPropertiesRequestsToHMI(
+ app, app_mngr.GetNextHMICorrelationID());
+ for (smart_objects::SmartObjectList::const_iterator it = requests.begin();
+ it != requests.end();
+ ++it) {
+ DCHECK(app_mngr.ManageHMICommand(*it));
+ }
+}
+
+smart_objects::SmartObjectList
+MessageHelper::CreateGlobalPropertiesRequestsToHMI(
+ ApplicationConstSharedPtr app, const uint32_t correlation_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ smart_objects::SmartObjectList requests;
+ if (!app.valid()) {
+ LOG4CXX_ERROR(logger_, "Invalid application");
+ return requests;
+ }
+
+ // UI global properties
+
+ if (app->vr_help_title() || app->vr_help()) {
+ smart_objects::SmartObjectSPtr ui_global_properties =
+ CreateRequestObject(correlation_id);
+ if (!ui_global_properties) {
+ return requests;
+ }
+
+ (*ui_global_properties)[strings::params][strings::function_id] =
+ static_cast<int>(hmi_apis::FunctionID::UI_SetGlobalProperties);
+
+ smart_objects::SmartObject ui_msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ if (app->vr_help_title()) {
+ ui_msg_params[strings::vr_help_title] = (*app->vr_help_title());
+ }
+ if (app->vr_help()) {
+ ui_msg_params[strings::vr_help] = (*app->vr_help());
+ }
+ if (app->keyboard_props()) {
+ ui_msg_params[strings::keyboard_properties] = (*app->keyboard_props());
+ }
+ if (app->menu_title()) {
+ ui_msg_params[strings::menu_title] = (*app->menu_title());
+ }
+ if (app->menu_icon()) {
+ ui_msg_params[strings::menu_icon] = (*app->menu_icon());
+ }
+ ui_msg_params[strings::app_id] = app->app_id();
+
+ (*ui_global_properties)[strings::msg_params] = ui_msg_params;
+
+ requests.push_back(ui_global_properties);
+ }
+
+ // TTS global properties
+ if (app->help_prompt() || app->timeout_prompt()) {
+ smart_objects::SmartObjectSPtr tts_global_properties =
+ CreateRequestObject(correlation_id);
+ if (!tts_global_properties) {
+ return requests;
+ }
+
+ (*tts_global_properties)[strings::params][strings::function_id] =
+ static_cast<int>(hmi_apis::FunctionID::TTS_SetGlobalProperties);
+
+ smart_objects::SmartObject tts_msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ if (app->help_prompt()) {
+ tts_msg_params[strings::help_prompt] = (*app->help_prompt());
+ }
+ if (app->timeout_prompt()) {
+ tts_msg_params[strings::timeout_prompt] = (*app->timeout_prompt());
+ }
+ tts_msg_params[strings::app_id] = app->app_id();
+
+ (*tts_global_properties)[strings::msg_params] = tts_msg_params;
+
+ requests.push_back(tts_global_properties);
+ }
+ return requests;
+}
+
+void MessageHelper::SendTTSGlobalProperties(ApplicationSharedPtr app,
+ bool default_help_prompt,
+ ApplicationManager& app_man) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!app) {
+ return;
+ }
+ smart_objects::SmartObjectSPtr tts_global_properties =
+ CreateRequestObject(app_man.GetNextHMICorrelationID());
+ if (tts_global_properties) {
+ smart_objects::SmartObject& so_to_send = *tts_global_properties;
+ so_to_send[strings::params][strings::function_id] =
+ static_cast<int>(hmi_apis::FunctionID::TTS_SetGlobalProperties);
+
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ msg_params[strings::help_prompt] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+ if (default_help_prompt) {
+ const DataAccessor<CommandsMap> accessor = app->commands_map();
+ const CommandsMap& commands = accessor.GetData();
+ CommandsMap::const_iterator it = commands.begin();
+ uint32_t index = 0;
+ for (; commands.end() != it; ++it) {
+ smart_objects::SmartObject item(smart_objects::SmartType_Map);
+ if ((*it->second).keyExists(strings::menu_params)) {
+ item[strings::text] =
+ (*it->second)[strings::menu_params][strings::menu_name]
+ .asString();
+ item[strings::type] = mobile_apis::SpeechCapabilities::SC_TEXT;
+ } else {
+ continue;
+ }
+ msg_params[strings::help_prompt][index++] = item;
+ }
+ }
+ app->set_help_prompt(msg_params[strings::help_prompt]);
+ msg_params[strings::app_id] = app->app_id();
+ so_to_send[strings::msg_params] = msg_params;
+ app_man.ManageHMICommand(tts_global_properties);
+ }
+}
+
+smart_objects::SmartObjectSPtr MessageHelper::CreateAppVrHelp(
+ ApplicationConstSharedPtr app) {
+ smart_objects::SmartObjectSPtr result =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+ if (!result) {
+ return NULL;
+ }
+ smart_objects::SmartObject& vr_help = *result;
+ vr_help[strings::vr_help_title] = app->name();
+
+ int32_t index = 0;
+ if (app->vr_synonyms()) {
+ smart_objects::SmartObject item(smart_objects::SmartType_Map);
+ item[strings::text] = (*(app->vr_synonyms())).getElement(0);
+ item[strings::position] = index + 1;
+ vr_help[strings::vr_help][index++] = item;
+ }
+
+ // copy all app VR commands
+ const DataAccessor<CommandsMap> cmd_accessor = app->commands_map();
+ const CommandsMap& commands = cmd_accessor.GetData();
+ CommandsMap::const_iterator it = commands.begin();
+
+ for (; commands.end() != it; ++it) {
+ smart_objects::SmartObject item(smart_objects::SmartType_Map);
+ item[strings::text] = (*it->second)[strings::vr_commands][0].asString();
+ item[strings::position] = index + 1;
+ vr_help[strings::vr_help][index++] = item;
+ }
+ return result;
+}
+
+smart_objects::SmartObjectList MessageHelper::CreateShowRequestToHMI(
+ ApplicationConstSharedPtr app, const uint32_t correlation_id) {
+ smart_objects::SmartObjectList requests;
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Invalid application");
+ return requests;
+ }
+
+ if (app->show_command()) {
+ smart_objects::SmartObjectSPtr ui_show =
+ CreateRequestObject(correlation_id);
+ (*ui_show)[strings::params][strings::function_id] =
+ static_cast<int>(hmi_apis::FunctionID::UI_Show);
+
+ (*ui_show)[strings::msg_params] = (*app->show_command());
+ requests.push_back(ui_show);
+ }
+ return requests;
+}
+
+void MessageHelper::SendShowRequestToHMI(ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr) {
+ if (!app) {
+ return;
+ }
+ smart_objects::SmartObjectList shows =
+ CreateShowRequestToHMI(app, app_mngr.GetNextHMICorrelationID());
+
+ for (smart_objects::SmartObjectList::const_iterator it = shows.begin();
+ it != shows.end();
+ ++it) {
+ DCHECK(app_mngr.ManageHMICommand(*it));
+ }
+}
+
+void MessageHelper::SendShowConstantTBTRequestToHMI(
+ ApplicationConstSharedPtr app, ApplicationManager& app_man) {
+ if (!app) {
+ return;
+ }
+
+ if (app->tbt_show_command()) {
+ smart_objects::SmartObjectSPtr navi_show_tbt =
+ CreateRequestObject(app_man.GetNextHMICorrelationID());
+ if (!navi_show_tbt) {
+ return;
+ }
+ (*navi_show_tbt)[strings::params][strings::function_id] =
+ static_cast<int>(hmi_apis::FunctionID::Navigation_ShowConstantTBT);
+
+ (*navi_show_tbt)[strings::msg_params] = (*app->tbt_show_command());
+ DCHECK(app_man.ManageHMICommand(navi_show_tbt));
+ }
+}
+
+void MessageHelper::SendAddCommandRequestToHMI(ApplicationConstSharedPtr app,
+ ApplicationManager& app_man) {
+ if (!app) {
+ return;
+ }
+ smart_objects::SmartObjectList requests =
+ CreateAddCommandRequestToHMI(app, app_man);
+ for (smart_objects::SmartObjectList::iterator it = requests.begin();
+ it != requests.end();
+ ++it) {
+ DCHECK(app_man.ManageHMICommand(*it));
+ }
+}
+
+smart_objects::SmartObjectList MessageHelper::CreateAddCommandRequestToHMI(
+ ApplicationConstSharedPtr app, ApplicationManager& app_mngr) {
+ smart_objects::SmartObjectList requests;
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Invalid application");
+ return requests;
+ }
+
+ const DataAccessor<CommandsMap> accessor = app->commands_map();
+ const CommandsMap& commands = accessor.GetData();
+ CommandsMap::const_iterator i = commands.begin();
+ for (; commands.end() != i; ++i) {
+ // UI Interface
+ if ((*i->second).keyExists(strings::menu_params)) {
+ smart_objects::SmartObjectSPtr ui_command =
+ CreateRequestObject(app_mngr.GetNextHMICorrelationID());
+ if (!ui_command) {
+ return requests;
+ }
+
+ (*ui_command)[strings::params][strings::function_id] =
+ static_cast<int>(hmi_apis::FunctionID::UI_AddCommand);
+
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ msg_params[strings::cmd_id] = i->first;
+ msg_params[strings::menu_params] = (*i->second)[strings::menu_params];
+ msg_params[strings::app_id] = app->app_id();
+
+ if (((*i->second).keyExists(strings::cmd_icon)) &&
+ (0 < (*i->second)[strings::cmd_icon][strings::value].length())) {
+ msg_params[strings::cmd_icon] = (*i->second)[strings::cmd_icon];
+ msg_params[strings::cmd_icon][strings::value] =
+ (*i->second)[strings::cmd_icon][strings::value].asString();
+ }
+ (*ui_command)[strings::msg_params] = msg_params;
+ requests.push_back(ui_command);
+ }
+
+ // VR Interface
+ if ((*i->second).keyExists(strings::vr_commands)) {
+ SendAddVRCommandToHMI(i->first,
+ (*i->second)[strings::vr_commands],
+ app->app_id(),
+ app_mngr);
+ }
+ }
+ return requests;
+}
+
+smart_objects::SmartObjectList
+MessageHelper::CreateAddVRCommandRequestFromChoiceToHMI(
+ ApplicationConstSharedPtr app, ApplicationManager& app_mngr) {
+ smart_objects::SmartObjectList requests;
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Invalid application");
+ return requests;
+ }
+
+ const DataAccessor<ChoiceSetMap> accessor = app->choice_set_map();
+ const ChoiceSetMap& choices = accessor.GetData();
+ ChoiceSetMap::const_iterator it = choices.begin();
+ for (; choices.end() != it; ++it) {
+ const uint32_t choice_grammar_id =
+ (*(it->second))[strings::grammar_id].asUInt();
+ const size_t size = (*(it->second))[strings::choice_set].length();
+ for (size_t j = 0; j < size; ++j) {
+ smart_objects::SmartObjectSPtr vr_command =
+ CreateRequestObject(app_mngr.GetNextHMICorrelationID());
+ if (!vr_command) {
+ return requests;
+ }
+
+ (*vr_command)[strings::params][strings::function_id] =
+ static_cast<int>(hmi_apis::FunctionID::VR_AddCommand);
+
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ msg_params[strings::app_id] = app->app_id();
+ msg_params[strings::cmd_id] =
+ (*(it->second))[strings::choice_set][j][strings::choice_id];
+ msg_params[strings::vr_commands] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+ msg_params[strings::vr_commands] =
+ (*(it->second))[strings::choice_set][j][strings::vr_commands];
+ msg_params[strings::type] = hmi_apis::Common_VRCommandType::Choice;
+ msg_params[strings::grammar_id] = choice_grammar_id;
+
+ (*vr_command)[strings::msg_params] = msg_params;
+ requests.push_back(vr_command);
+ }
+ }
+ return requests;
+}
+
+smart_objects::SmartObjectSPtr MessageHelper::CreateChangeRegistration(
+ const int32_t function_id,
+ const int32_t language,
+ const uint32_t app_id,
+ const smart_objects::SmartObject* app_types,
+ ApplicationManager& app_mngr) {
+ smart_objects::SmartObjectSPtr command =
+ CreateRequestObject(app_mngr.GetNextHMICorrelationID());
+ if (!command) {
+ return NULL;
+ }
+ smart_objects::SmartObject& params = *command;
+ params[strings::params][strings::function_id] = function_id;
+
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ msg_params[strings::language] = language;
+ msg_params[strings::app_id] = app_id;
+
+ if (app_types != NULL) {
+ msg_params[strings::app_hmi_type] = *app_types;
+ }
+
+ params[strings::msg_params] = msg_params;
+ return command;
+}
+
+void MessageHelper::SendUIChangeRegistrationRequestToHMI(
+ ApplicationConstSharedPtr app, ApplicationManager& app_mngr) {
+ if (!app.valid()) {
+ LOG4CXX_ERROR(logger_, "Application is not valid");
+ return;
+ }
+
+ if (NULL != app->app_types()) {
+ smart_objects::SmartObjectSPtr ui_command =
+ CreateChangeRegistration(hmi_apis::FunctionID::UI_ChangeRegistration,
+ app->ui_language(),
+ app->app_id(),
+ app->app_types(),
+ app_mngr);
+
+ if (ui_command) {
+ app_mngr.ManageHMICommand(ui_command);
+ }
+ }
+}
+
+void MessageHelper::SendChangeRegistrationRequestToHMI(
+ ApplicationConstSharedPtr app, ApplicationManager& app_mngr) {
+ if (!app.valid()) {
+ return;
+ }
+ if (mobile_apis::Language::INVALID_ENUM != app->language()) {
+ smart_objects::SmartObjectSPtr vr_command =
+ CreateChangeRegistration(hmi_apis::FunctionID::VR_ChangeRegistration,
+ app->language(),
+ app->app_id(),
+ NULL,
+ app_mngr);
+
+ if (vr_command) {
+ app_mngr.ManageHMICommand(vr_command);
+ }
+ }
+
+ if (mobile_apis::Language::INVALID_ENUM != app->language()) {
+ smart_objects::SmartObjectSPtr tts_command =
+ CreateChangeRegistration(hmi_apis::FunctionID::TTS_ChangeRegistration,
+ app->language(),
+ app->app_id(),
+ NULL,
+ app_mngr);
+
+ if (tts_command) {
+ app_mngr.ManageHMICommand(tts_command);
+ }
+ }
+
+ if (mobile_apis::Language::INVALID_ENUM != app->ui_language()) {
+ smart_objects::SmartObjectSPtr ui_command =
+ CreateChangeRegistration(hmi_apis::FunctionID::UI_ChangeRegistration,
+ app->ui_language(),
+ app->app_id(),
+ NULL,
+ app_mngr);
+
+ if (ui_command) {
+ app_mngr.ManageHMICommand(ui_command);
+ }
+ }
+}
+
+void MessageHelper::SendAddVRCommandToHMI(
+ const uint32_t cmd_id,
+ const smart_objects::SmartObject& vr_commands,
+ const uint32_t app_id,
+ ApplicationManager& app_mngr) {
+ smart_objects::SmartObjectSPtr request =
+ CreateAddVRCommandToHMI(cmd_id, vr_commands, app_id, app_mngr);
+ DCHECK(app_mngr.ManageHMICommand(request));
+}
+
+smart_objects::SmartObjectSPtr MessageHelper::CreateAddVRCommandToHMI(
+ const uint32_t cmd_id,
+ const smart_objects::SmartObject& vr_commands,
+ uint32_t app_id,
+ ApplicationManager& app_mngr) {
+ smart_objects::SmartObjectSPtr vr_command =
+ CreateRequestObject(app_mngr.GetNextHMICorrelationID());
+ if (!vr_command) {
+ return NULL;
+ }
+
+ (*vr_command)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::VR_AddCommand;
+
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ if (0 != cmd_id) {
+ msg_params[strings::cmd_id] = cmd_id;
+ }
+ msg_params[strings::vr_commands] = vr_commands;
+ if (0 < app_id) {
+ msg_params[strings::app_id] = app_id;
+ }
+ msg_params[strings::grammar_id] =
+ app_mngr.application(app_id)->get_grammar_id();
+ msg_params[strings::type] = hmi_apis::Common_VRCommandType::Command;
+
+ (*vr_command)[strings::msg_params] = msg_params;
+
+ return vr_command;
+}
+
+bool MessageHelper::CreateHMIApplicationStruct(
+ ApplicationConstSharedPtr app,
+ const protocol_handler::SessionObserver& session_observer,
+ const policy::PolicyHandlerInterface& policy_handler,
+ NsSmartDeviceLink::NsSmartObjects::SmartObject* output,
+ ApplicationManager& app_mngr) {
+ using NsSmartDeviceLink::NsSmartObjects::SmartObject;
+ DCHECK_OR_RETURN(output, false);
+ SmartObject& message = *output;
+
+ if (!app) {
+ LOG4CXX_WARN(logger_, "Application is not valid");
+ return false;
+ }
+
+ const smart_objects::SmartObject* app_types = app->app_types();
+ const smart_objects::SmartObject* ngn_media_screen_name =
+ app->ngn_media_screen_name();
+ std::string device_name;
+ std::string mac_address;
+ std::string transport_type;
+ if (-1 ==
+ session_observer.GetDataOnDeviceID(
+ app->device(), &device_name, NULL, &mac_address, &transport_type)) {
+ LOG4CXX_ERROR(logger_,
+ "Failed to extract information for device " << app->device());
+ }
+
+ message = smart_objects::SmartObject(smart_objects::SmartType_Map);
+ message[strings::app_name] = app->name();
+ message[strings::app_id] = app->hmi_app_id();
+ const std::string icon_path = app->app_icon_path();
+ if (!icon_path.empty()) {
+ message[strings::icon] = icon_path;
+ }
+ if (app->IsRegistered()) {
+ message[strings::hmi_display_language_desired] = app->ui_language();
+ message[strings::is_media_application] = app->is_media_application();
+ } else {
+ message[strings::greyOut] = app->is_greyed_out();
+ }
+ if (app->tts_name() && !app->tts_name()->empty()) {
+ message[json::ttsName] = *(app->tts_name());
+ }
+ if (app->vr_synonyms() && !app->vr_synonyms()->empty()) {
+ message[json::vrSynonyms] = *(app->vr_synonyms());
+ }
+ if (ngn_media_screen_name) {
+ message[strings::ngn_media_screen_app_name] =
+ ngn_media_screen_name->asString();
+ }
+ if (app_types) {
+ message[strings::app_type] = *app_types;
+ }
+
+ message[strings::device_info] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ message[strings::device_info][strings::name] = device_name;
+ message[strings::device_info][strings::id] = mac_address;
+ const policy::DeviceConsent device_consent =
+ policy_handler.GetUserConsentForDevice(mac_address);
+ message[strings::device_info][strings::isSDLAllowed] =
+ policy::DeviceConsent::kDeviceAllowed == device_consent;
+
+ message[strings::device_info][strings::transport_type] =
+ app_mngr.GetDeviceTransportType(transport_type);
+ return true;
+}
+
+void MessageHelper::SendAddSubMenuRequestToHMI(ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr) {
+ if (!app.valid()) {
+ LOG4CXX_ERROR(logger_, "Invalid application");
+ return;
+ }
+
+ smart_objects::SmartObjectList requests =
+ CreateAddSubMenuRequestToHMI(app, app_mngr.GetNextHMICorrelationID());
+ for (smart_objects::SmartObjectList::iterator it = requests.begin();
+ it != requests.end();
+ ++it) {
+ DCHECK(app_mngr.ManageHMICommand(*it));
+ }
+}
+
+smart_objects::SmartObjectList MessageHelper::CreateAddSubMenuRequestToHMI(
+ ApplicationConstSharedPtr app, const uint32_t correlation_id) {
+ smart_objects::SmartObjectList requsets;
+ const DataAccessor<SubMenuMap> accessor = app->sub_menu_map();
+ const SubMenuMap& sub_menu = accessor.GetData();
+ SubMenuMap::const_iterator i = sub_menu.begin();
+ for (; sub_menu.end() != i; ++i) {
+ smart_objects::SmartObjectSPtr ui_sub_menu =
+ CreateRequestObject(correlation_id);
+ if (!ui_sub_menu) {
+ return requsets;
+ }
+
+ (*ui_sub_menu)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::UI_AddSubMenu;
+
+ smart_objects::SmartObject msg_params =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+
+ msg_params[strings::menu_id] = i->first;
+ msg_params[strings::menu_params][strings::position] =
+ (*i->second)[strings::position];
+ msg_params[strings::menu_params][strings::menu_name] =
+ (*i->second)[strings::menu_name];
+ msg_params[strings::app_id] = app->app_id();
+ (*ui_sub_menu)[strings::msg_params] = msg_params;
+ requsets.push_back(ui_sub_menu);
+ }
+ return requsets;
+}
+
+void MessageHelper::SendOnAppUnregNotificationToHMI(
+ ApplicationConstSharedPtr app,
+ bool is_unexpected_disconnect,
+ ApplicationManager& app_mngr) {
+ smart_objects::SmartObjectSPtr notification =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+
+ smart_objects::SmartObject& message = *notification;
+
+ message[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::BasicCommunication_OnAppUnregistered;
+
+ message[strings::params][strings::message_type] = MessageType::kNotification;
+ // we put hmi_app_id because applicaton list does not contain application on
+ // this momment
+ // and ReplaceHMIByMobileAppId function will be unable to replace app_id to
+ // hmi_app_id
+ message[strings::msg_params][strings::app_id] = app->hmi_app_id();
+ message[strings::msg_params][strings::unexpected_disconnect] =
+ is_unexpected_disconnect;
+ app_mngr.ManageHMICommand(notification);
+}
+
+smart_objects::SmartObjectSPtr MessageHelper::GetBCActivateAppRequestToHMI(
+ ApplicationConstSharedPtr app,
+ const protocol_handler::SessionObserver& session_observer,
+ const policy::PolicyHandlerInterface& policy_handler,
+ hmi_apis::Common_HMILevel::eType level,
+ bool send_policy_priority,
+ ApplicationManager& app_mngr) {
+ DCHECK_OR_RETURN(app, smart_objects::SmartObjectSPtr());
+
+ const uint32_t correlation_id = app_mngr.GetNextHMICorrelationID();
+ smart_objects::SmartObjectSPtr message =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+ (*message)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::BasicCommunication_ActivateApp;
+ (*message)[strings::params][strings::message_type] = MessageType::kRequest;
+ (*message)[strings::params][strings::correlation_id] = correlation_id;
+ (*message)[strings::msg_params][strings::app_id] = app->app_id();
+
+ if (send_policy_priority) {
+ std::string priority;
+ // TODO(KKolodiy): need remove method policy_manager
+
+ policy_handler.GetPriority(app->policy_app_id(), &priority);
+ // According SDLAQ-CRS-2794
+ // SDL have to send ActivateApp without "proirity" parameter to HMI.
+ // in case of unconsented device
+ const std::string& mac_adress = app->mac_address();
+
+ policy::DeviceConsent consent =
+ policy_handler.GetUserConsentForDevice(mac_adress);
+ if (!priority.empty() &&
+ (policy::DeviceConsent::kDeviceAllowed == consent)) {
+ (*message)[strings::msg_params][strings::priority] =
+ GetPriorityCode(priority);
+ }
+ }
+
+ // We haven't send HMI level to HMI in case it FULL.
+ if (hmi_apis::Common_HMILevel::INVALID_ENUM != level &&
+ hmi_apis::Common_HMILevel::FULL != level) {
+ (*message)[strings::msg_params][strings::activate_app_hmi_level] = level;
+ }
+ return message;
+}
+
+void MessageHelper::SendOnResumeAudioSourceToHMI(const uint32_t app_id,
+ ApplicationManager& app_mngr) {
+ LOG4CXX_WARN(logger_, "SendOnResumeAudioSourceToHMI app_id: " << app_id);
+ application_manager::ApplicationConstSharedPtr app =
+ app_mngr.application(app_id);
+ if (!app) {
+ LOG4CXX_WARN(logger_, "Invalid app_id: " << app_id);
+ return;
+ }
+
+ utils::SharedPtr<smart_objects::SmartObject> message =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+
+ (*message)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::BasicCommunication_OnResumeAudioSource;
+ (*message)[strings::params][strings::message_type] =
+ MessageType::kNotification;
+ (*message)[strings::params][strings::correlation_id] =
+ app_mngr.GetNextHMICorrelationID();
+ (*message)[strings::msg_params][strings::app_id] = app_id;
+
+ app_mngr.ManageHMICommand(message);
+}
+
+void MessageHelper::SendSDLActivateAppResponse(
+ policy::AppPermissions& permissions,
+ const uint32_t correlation_id,
+ ApplicationManager& app_mngr) {
+ smart_objects::SmartObjectSPtr message =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+
+ (*message)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::SDL_ActivateApp;
+ (*message)[strings::params][strings::message_type] = MessageType::kResponse;
+ (*message)[strings::params][strings::correlation_id] = correlation_id;
+ (*message)[strings::params][strings::protocol_type] =
+ commands::CommandImpl::hmi_protocol_type_;
+ (*message)[strings::params][strings::protocol_version] =
+ commands::CommandImpl::protocol_version_;
+ (*message)[strings::params][hmi_response::code] = 0;
+
+ (*message)[strings::msg_params]["isSDLAllowed"] = permissions.isSDLAllowed;
+ if (!permissions.isSDLAllowed) {
+ (*message)[strings::msg_params]["device"]["name"] =
+ permissions.deviceInfo.device_name;
+ (*message)[strings::msg_params]["device"]["id"] =
+ permissions.deviceInfo.device_mac_address;
+ }
+
+ (*message)[strings::msg_params]["isAppRevoked"] = permissions.appRevoked;
+ (*message)[strings::msg_params]["isAppPermissionsRevoked"] =
+ permissions.isAppPermissionsRevoked;
+
+ if (permissions.isAppPermissionsRevoked) {
+ FillAppRevokedPermissions(permissions, *message);
+ }
+
+ (*message)[strings::msg_params]["isPermissionsConsentNeeded"] =
+ permissions.appPermissionsConsentNeeded;
+
+ if (!permissions.priority.empty()) {
+ (*message)[strings::msg_params]["priority"] =
+ GetPriorityCode(permissions.priority);
+ }
+
+ // If application is revoked it should not be activated
+ if (permissions.appRevoked || !permissions.isSDLAllowed) {
+ return;
+ }
+
+ app_mngr.ManageHMICommand(message);
+}
+
+void MessageHelper::SendOnSDLConsentNeeded(
+ const policy::DeviceParams& device_info, ApplicationManager& app_man) {
+ smart_objects::SmartObjectSPtr message =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+
+ (*message)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::SDL_OnSDLConsentNeeded;
+ (*message)[strings::params][strings::message_type] =
+ MessageType::kNotification;
+
+ (*message)[strings::msg_params]["device"]["id"] =
+ device_info.device_mac_address;
+ (*message)[strings::msg_params]["device"]["name"] = device_info.device_name;
+
+ app_man.ManageHMICommand(message);
+}
+
+void MessageHelper::SendPolicyUpdate(const std::string& file_path,
+ const int timeout,
+ const std::vector<int>& retries,
+ ApplicationManager& app_mngr) {
+ smart_objects::SmartObjectSPtr message =
+ CreateRequestObject(app_mngr.GetNextHMICorrelationID());
+ smart_objects::SmartObject& object = *message;
+ object[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::BasicCommunication_PolicyUpdate;
+
+ object[strings::msg_params][hmi_request::file] = file_path;
+ object[strings::msg_params][strings::timeout] = timeout;
+ object[strings::msg_params][hmi_request::retry] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+ for (size_t i = 0; i < retries.size(); ++i) {
+ object[strings::msg_params][hmi_request::retry][i] = retries[i];
+ }
+ app_mngr.ManageHMICommand(message);
+}
+
+void MessageHelper::SendGetUserFriendlyMessageResponse(
+ const std::vector<policy::UserFriendlyMessage>& msg,
+ uint32_t correlation_id,
+ ApplicationManager& app_mngr) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObjectSPtr message =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+
+ (*message)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::SDL_GetUserFriendlyMessage;
+ (*message)[strings::params][strings::message_type] = MessageType::kResponse;
+ (*message)[strings::params][strings::correlation_id] = correlation_id;
+ (*message)[strings::params][hmi_response::code] = 0;
+
+ // If no any messages found - skip sending of "messages" param
+ if (msg.empty()) {
+ app_mngr.ManageHMICommand(message);
+ return;
+ }
+
+ const std::string messages = "messages";
+ (*message)[strings::msg_params][messages] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+
+ smart_objects::SmartObject& user_friendly_messages =
+ (*message)[strings::msg_params][messages];
+
+ const std::string message_code = "messageCode";
+
+ std::vector<policy::UserFriendlyMessage>::const_iterator it = msg.begin();
+ std::vector<policy::UserFriendlyMessage>::const_iterator it_end = msg.end();
+ for (uint32_t index = 0; it != it_end; ++it, ++index) {
+ user_friendly_messages[index] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+
+ smart_objects::SmartObject& obj = user_friendly_messages[index];
+ obj[message_code] = it->message_code;
+ }
+
+ app_mngr.ManageHMICommand(message);
+}
+
+void MessageHelper::SendGetListOfPermissionsResponse(
+ const std::vector<policy::FunctionalGroupPermission>& permissions,
+ const uint32_t correlation_id,
+ ApplicationManager& app_mngr) {
+ smart_objects::SmartObject message(smart_objects::SmartType_Map);
+
+ message[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::SDL_GetListOfPermissions;
+ message[strings::params][strings::message_type] = MessageType::kResponse;
+ message[strings::params][strings::correlation_id] = correlation_id;
+ message[strings::params][hmi_response::code] = 0;
+
+ const std::string allowed_functions = "allowedFunctions";
+ message[strings::msg_params][allowed_functions] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+
+ smart_objects::SmartObject& allowed_functions_array =
+ message[strings::msg_params][allowed_functions];
+
+ std::vector<policy::FunctionalGroupPermission>::const_iterator it =
+ permissions.begin();
+ std::vector<policy::FunctionalGroupPermission>::const_iterator it_end =
+ permissions.end();
+ for (uint32_t index = 0; it != it_end; ++it, ++index) {
+ allowed_functions_array[index] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+
+ smart_objects::SmartObject& item = allowed_functions_array[index];
+ item[strings::name] = (*it).group_alias;
+ item[strings::id] = (*it).group_id;
+ policy::GroupConsent permission_state = (*it).state;
+ // If state undefined, 'allowed' parameter should be absent
+ if (policy::kGroupUndefined != permission_state) {
+ item["allowed"] = policy::kGroupAllowed == permission_state;
+ }
+ }
+
+ app_mngr.ManageHMICommand(
+ utils::MakeShared<smart_objects::SmartObject>(message));
+}
+
+smart_objects::SmartObjectSPtr MessageHelper::CreateNegativeResponse(
+ uint32_t connection_key,
+ int32_t function_id,
+ const uint32_t correlation_id,
+ int32_t result_code) {
+ smart_objects::SmartObject response_data(smart_objects::SmartType_Map);
+ response_data[strings::params][strings::function_id] = function_id;
+ response_data[strings::params][strings::message_type] =
+ mobile_apis::messageType::response;
+ response_data[strings::params][strings::correlation_id] = correlation_id;
+ response_data[strings::params][strings::protocol_type] =
+ commands::CommandImpl::mobile_protocol_type_;
+ response_data[strings::params][strings::protocol_version] =
+ commands::CommandImpl::protocol_version_;
+ response_data[strings::msg_params][strings::result_code] = result_code;
+ response_data[strings::msg_params][strings::success] = false;
+ response_data[strings::params][strings::connection_key] = connection_key;
+
+ return utils::MakeShared<smart_objects::SmartObject>(response_data);
+}
+
+void MessageHelper::SendNaviStartStream(const int32_t app_id,
+ ApplicationManager& app_mngr) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObjectSPtr start_stream =
+ CreateRequestObject(app_mngr.GetNextHMICorrelationID());
+ if (!start_stream) {
+ return;
+ }
+
+ (*start_stream)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::Navigation_StartStream;
+
+ char url[100] = {'\0'};
+ if ("socket" == app_mngr.get_settings().video_server_type()) {
+ snprintf(url,
+ sizeof(url) / sizeof(url[0]),
+ "http://%s:%d",
+ app_mngr.get_settings().server_address().c_str(),
+ app_mngr.get_settings().video_streaming_port());
+ } else if ("pipe" == app_mngr.get_settings().video_server_type()) {
+ snprintf(url,
+ sizeof(url) / sizeof(url[0]),
+ "%s",
+ app_mngr.get_settings().named_video_pipe_path().c_str());
+ } else {
+ int snprintf_result =
+ snprintf(url,
+ sizeof(url) / sizeof(url[0]),
+ "%s",
+ app_mngr.get_settings().video_stream_file().c_str());
+ DCHECK(snprintf_result);
+ }
+
+ (*start_stream)[strings::msg_params][strings::app_id] = app_id;
+ (*start_stream)[strings::msg_params][strings::url] = url;
+
+ app_mngr.ManageHMICommand(start_stream);
+}
+
+void MessageHelper::SendNaviStopStream(const int32_t app_id,
+ ApplicationManager& app_mngr) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObjectSPtr stop_stream =
+ CreateRequestObject(app_mngr.GetNextHMICorrelationID());
+ if (!stop_stream) {
+ return;
+ }
+
+ (*stop_stream)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::Navigation_StopStream;
+
+ (*stop_stream)[strings::msg_params][strings::app_id] = app_id;
+
+ app_mngr.ManageHMICommand(stop_stream);
+}
+
+void MessageHelper::SendAudioStartStream(const int32_t app_id,
+ ApplicationManager& app_mngr) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObjectSPtr start_stream =
+ CreateRequestObject(app_mngr.GetNextHMICorrelationID());
+
+ if (!start_stream) {
+ return;
+ }
+
+ (*start_stream)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::Navigation_StartAudioStream;
+
+ char url[100] = {'\0'};
+ if ("socket" == app_mngr.get_settings().audio_server_type()) {
+ snprintf(url,
+ sizeof(url) / sizeof(url[0]),
+ "http://%s:%d",
+ app_mngr.get_settings().server_address().c_str(),
+ app_mngr.get_settings().audio_streaming_port());
+ } else if ("pipe" == app_mngr.get_settings().audio_server_type()) {
+ snprintf(url,
+ sizeof(url) / sizeof(url[0]),
+ "%s",
+ app_mngr.get_settings().named_audio_pipe_path().c_str());
+ } else {
+ int snprintf_result =
+ snprintf(url,
+ sizeof(url) / sizeof(url[0]),
+ "%s",
+ app_mngr.get_settings().audio_stream_file().c_str());
+ DCHECK(snprintf_result);
+ }
+
+ (*start_stream)[strings::msg_params][strings::app_id] = app_id;
+ (*start_stream)[strings::msg_params][strings::url] = url;
+
+ DCHECK(app_mngr.ManageHMICommand(start_stream));
+}
+
+void MessageHelper::SendAudioStopStream(const int32_t app_id,
+ ApplicationManager& app_mngr) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObjectSPtr stop_stream =
+ CreateRequestObject(app_mngr.GetNextHMICorrelationID());
+
+ if (!stop_stream) {
+ return;
+ }
+
+ (*stop_stream)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::Navigation_StopAudioStream;
+
+ (*stop_stream)[strings::msg_params][strings::app_id] = app_id;
+
+ app_mngr.ManageHMICommand(stop_stream);
+}
+
+void MessageHelper::SendOnDataStreaming(
+ const protocol_handler::ServiceType service,
+ const bool available,
+ ApplicationManager& app_mngr) {
+ using namespace protocol_handler;
+ using namespace helpers;
+
+ if (!Compare<ServiceType, EQ, ONE>(
+ service, ServiceType::kAudio, ServiceType::kMobileNav)) {
+ return;
+ }
+
+ smart_objects::SmartObjectSPtr notification =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+
+ (*notification)[strings::params][strings::function_id] =
+ ServiceType::kAudio == service
+ ? hmi_apis::FunctionID::Navigation_OnAudioDataStreaming
+ : hmi_apis::FunctionID::Navigation_OnVideoDataStreaming;
+ (*notification)[strings::params][strings::message_type] =
+ hmi_apis::messageType::notification;
+ (*notification)[strings::params][strings::protocol_version] =
+ commands::CommandImpl::protocol_version_;
+ (*notification)[strings::params][strings::protocol_type] =
+ commands::CommandImpl::hmi_protocol_type_;
+
+ (*notification)[strings::msg_params]["available"] = available;
+
+ app_mngr.ManageHMICommand(notification);
+}
+
+bool MessageHelper::SendStopAudioPathThru(ApplicationManager& app_mngr) {
+ LOG4CXX_INFO(logger_, "MessageHelper::SendAudioStopAudioPathThru");
+
+ smart_objects::SmartObjectSPtr result =
+ CreateRequestObject(app_mngr.GetNextHMICorrelationID());
+
+ (*result)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::UI_EndAudioPassThru;
+
+ return app_mngr.ManageHMICommand(result);
+}
+
+bool MessageHelper::SendUnsubscribedWayPoints(ApplicationManager& app_mngr) {
+ LOG4CXX_INFO(logger_, "MessageHelper::SendUnsubscribedWayPoints");
+
+ smart_objects::SmartObjectSPtr result =
+ CreateRequestObject(app_mngr.GetNextHMICorrelationID());
+
+ (*result)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::Navigation_UnsubscribeWayPoints;
+
+ return app_mngr.ManageHMICommand(result);
+}
+
+void MessageHelper::SendPolicySnapshotNotification(
+ uint32_t connection_key,
+ const std::vector<uint8_t>& policy_data,
+ const std::string& url,
+ ApplicationManager& app_mngr) {
+ smart_objects::SmartObject content(smart_objects::SmartType_Map);
+
+ if (!url.empty()) {
+ content[strings::msg_params][strings::url] =
+ url; // Doesn't work with mobile_notification::syncp_url ("URL")
+ } else {
+ LOG4CXX_WARN(logger_, "No service URLs");
+ }
+
+ content[strings::msg_params][strings::request_type] =
+ mobile_apis::RequestType::PROPRIETARY;
+ content[strings::params][strings::binary_data] =
+ smart_objects::SmartObject(policy_data);
+ content[strings::msg_params][strings::file_type] =
+ mobile_apis::FileType::BINARY;
+
+ SendSystemRequestNotification(connection_key, content, app_mngr);
+}
+
+void MessageHelper::SendSystemRequestNotification(
+ const uint32_t connection_key,
+ smart_objects::SmartObject& content,
+ ApplicationManager& app_mngr) {
+ content[strings::params][strings::function_id] =
+ mobile_apis::FunctionID::OnSystemRequestID;
+ content[strings::params][strings::message_type] =
+ mobile_apis::messageType::notification;
+ content[strings::params][strings::protocol_type] =
+ commands::CommandImpl::mobile_protocol_type_;
+ content[strings::params][strings::protocol_version] =
+ commands::CommandImpl::protocol_version_;
+
+ content[strings::params][strings::connection_key] = connection_key;
+
+#ifdef DEBUG
+ PrintSmartObject(content);
+#endif
+
+ DCHECK(app_mngr.ManageMobileCommand(
+ utils::MakeShared<smart_objects::SmartObject>(content),
+ commands::Command::ORIGIN_SDL));
+}
+
+void MessageHelper::SendLaunchApp(const uint32_t connection_key,
+ const std::string& urlSchema,
+ const std::string& packageName,
+ ApplicationManager& app_mngr) {
+ using namespace mobile_apis;
+ using namespace smart_objects;
+
+ SmartObject content(SmartType_Map);
+ content[strings::msg_params][strings::request_type] = RequestType::LAUNCH_APP;
+ content[strings::msg_params][strings::app_id] = connection_key;
+ if (!urlSchema.empty()) {
+ content[strings::msg_params][strings::url] = urlSchema;
+ } else if (!packageName.empty()) {
+ content[strings::msg_params][strings::url] = packageName;
+ }
+
+ SendSystemRequestNotification(connection_key, content, app_mngr);
+}
+
+void MessageHelper::SendQueryApps(const uint32_t connection_key,
+ ApplicationManager& app_mngr) {
+ using namespace mobile_apis;
+
+ policy::PolicyHandlerInterface& policy_handler = app_mngr.GetPolicyHandler();
+
+ smart_objects::SmartObject content(smart_objects::SmartType_Map);
+ content[strings::msg_params][strings::request_type] = RequestType::QUERY_APPS;
+ content[strings::msg_params][strings::url] = policy_handler.RemoteAppsUrl();
+ content[strings::msg_params][strings::timeout] =
+ policy_handler.TimeoutExchange();
+
+ Json::Value http_header;
+
+ const int timeout = policy_handler.TimeoutExchange();
+
+ http_header[http_request::content_type] = "application/json";
+ http_header[http_request::connect_timeout] = timeout;
+ http_header[http_request::do_output] = true;
+ http_header[http_request::do_input] = true;
+ http_header[http_request::use_caches] = false;
+ http_header[http_request::request_method] = http_request::GET;
+ http_header[http_request::read_timeout] = timeout;
+ http_header[http_request::instance_follow_redirect] = false;
+ http_header[http_request::charset] = "utf-8";
+ http_header[http_request::content_lenght] = 0;
+
+ std::string data = http_header.toStyledString();
+ std::vector<uint8_t> binary_data(data.begin(), data.end());
+
+ content[strings::params][strings::binary_data] =
+ smart_objects::SmartObject(binary_data);
+ content[strings::msg_params][strings::file_type] = FileType::BINARY;
+
+ SendSystemRequestNotification(connection_key, content, app_mngr);
+}
+
+void MessageHelper::SendOnPermissionsChangeNotification(
+ uint32_t connection_key,
+ const policy::Permissions& permissions,
+ ApplicationManager& app_mngr) {
+ smart_objects::SmartObject content(smart_objects::SmartType_Map);
+
+ content[strings::params][strings::function_id] =
+ mobile_apis::FunctionID::OnPermissionsChangeID;
+ content[strings::params][strings::message_type] =
+ mobile_apis::messageType::notification;
+ content[strings::params][strings::protocol_type] =
+ commands::CommandImpl::mobile_protocol_type_;
+ content[strings::params][strings::protocol_version] =
+ commands::CommandImpl::protocol_version_;
+ content[strings::params][strings::connection_key] = connection_key;
+
+ content[strings::msg_params] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+
+ // content[strings::msg_params][strings::app_id] = connection_key;
+
+ content[strings::msg_params]["permissionItem"] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+
+ smart_objects::SmartObject& permissions_item_array =
+ content[strings::msg_params]["permissionItem"];
+
+ policy::Permissions::const_iterator it_permissions = permissions.begin();
+ policy::Permissions::const_iterator it_permissions_end = permissions.end();
+
+ for (size_t index_pi = 0; it_permissions != it_permissions_end;
+ ++it_permissions, ++index_pi) {
+ permissions_item_array[index_pi] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+
+ smart_objects::SmartObject& permission_item =
+ permissions_item_array[index_pi];
+
+ // Filling the rpcName of PermissionItem
+ permission_item["rpcName"] = (*it_permissions).first;
+ const policy::RpcPermissions& rpc_permissions = (*it_permissions).second;
+
+ // Creating SO for hmiPermissions
+ permission_item["hmiPermissions"] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+
+ smart_objects::SmartObject& hmi_permissions =
+ permission_item["hmiPermissions"];
+
+ policy::HMIPermissions::const_iterator it_hmi_permissions =
+ rpc_permissions.hmi_permissions.begin();
+ policy::HMIPermissions::const_iterator it_hmi_permissions_end =
+ rpc_permissions.hmi_permissions.end();
+
+ // Filling the hmiPermissions of PermissionItem
+ for (; it_hmi_permissions != it_hmi_permissions_end; ++it_hmi_permissions) {
+ // Possible key names are "allowed", "userDisallowed"
+ hmi_permissions[(*it_hmi_permissions).first] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+
+ smart_objects::SmartObject& hmi_levels =
+ hmi_permissions[(*it_hmi_permissions).first];
+
+ std::set<policy::HMILevel>::const_iterator it_hmi_levels =
+ (*it_hmi_permissions).second.begin();
+ std::set<policy::HMILevel>::const_iterator it_hmi_levels_end =
+ (*it_hmi_permissions).second.end();
+
+ for (size_t index_hmi_levels = 0; it_hmi_levels != it_hmi_levels_end;
+ ++it_hmi_levels, ++index_hmi_levels) {
+ hmi_levels[index_hmi_levels] = *it_hmi_levels;
+ }
+ }
+
+ // Creating SO for parameterPermissions
+ permission_item["parameterPermissions"] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+
+ smart_objects::SmartObject& parameter_permissions =
+ permission_item["parameterPermissions"];
+
+ policy::ParameterPermissions::const_iterator it_parameter_permissions =
+ rpc_permissions.parameter_permissions.begin();
+ policy::ParameterPermissions::const_iterator it_parameter_permissions_end =
+ rpc_permissions.parameter_permissions.end();
+
+ // Filling the parameterPermissions of PermissionItem
+ for (; it_parameter_permissions != it_parameter_permissions_end;
+ ++it_parameter_permissions) {
+ // Possible key names are "allowed", "userDisallowed"
+ parameter_permissions[(*it_parameter_permissions).first] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+
+ smart_objects::SmartObject& parameters =
+ parameter_permissions[(*it_parameter_permissions).first];
+
+ std::set<policy::Parameter>::const_iterator it_parameters =
+ (*it_parameter_permissions).second.begin();
+ std::set<policy::Parameter>::const_iterator it_parameters_end =
+ (*it_parameter_permissions).second.end();
+
+ for (size_t index_parameters = 0; it_parameters != it_parameters_end;
+ ++it_parameters, ++index_parameters) {
+ parameters[index_parameters] = *it_parameters;
+ }
+ }
+ }
+
+ app_mngr.ManageMobileCommand(
+ utils::MakeShared<smart_objects::SmartObject>(content),
+ commands::Command::ORIGIN_SDL);
+}
+
+void MessageHelper::FillAppRevokedPermissions(
+ const policy::AppPermissions& permissions,
+ smart_objects::SmartObject& message) {
+ message[strings::msg_params]["appRevokedPermissions"] =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+ smart_objects::SmartObject& revoked_permission_items =
+ message[strings::msg_params]["appRevokedPermissions"];
+ for (size_t i = 0; i < permissions.appRevokedPermissions.size(); ++i) {
+ revoked_permission_items[i] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ smart_objects::SmartObject& permission_item = revoked_permission_items[i];
+ permission_item["name"] = permissions.appRevokedPermissions[i].group_alias;
+
+ permission_item["id"] = permissions.appRevokedPermissions[i].group_id;
+
+ if (policy::kGroupUndefined != permissions.appRevokedPermissions[i].state) {
+ permission_item["allowed"] =
+ policy::kGroupAllowed == permissions.appRevokedPermissions[i].state
+ ? true
+ : false;
+ }
+ }
+}
+
+void MessageHelper::SendOnAppPermissionsChangedNotification(
+ const uint32_t connection_key,
+ const policy::AppPermissions& permissions,
+ ApplicationManager& app_mngr) {
+ smart_objects::SmartObject message(smart_objects::SmartType_Map);
+
+ message[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::SDL_OnAppPermissionChanged;
+
+ message[strings::params][strings::message_type] = MessageType::kNotification;
+ message[strings::msg_params][strings::app_id] = connection_key;
+
+ // TODO(AOleynik): Add other parameters processing from incoming struct
+ if (permissions.appRevoked) {
+ message[strings::msg_params]["appRevoked"] = permissions.appRevoked;
+ }
+ if (permissions.isAppPermissionsRevoked) {
+ message[strings::msg_params]["isAppPermissionsRevoked"] =
+ permissions.isAppPermissionsRevoked;
+
+ FillAppRevokedPermissions(permissions, message);
+ }
+
+ if (permissions.appPermissionsConsentNeeded) {
+ message[strings::msg_params]["appPermissionsConsentNeeded"] =
+ permissions.appPermissionsConsentNeeded;
+ }
+ if (permissions.appUnauthorized) {
+ message[strings::msg_params]["appUnauthorized"] =
+ permissions.appUnauthorized;
+ }
+ if (!permissions.priority.empty()) {
+ message[strings::msg_params]["priority"] =
+ GetPriorityCode(permissions.priority);
+ }
+ if (permissions.requestTypeChanged) {
+ smart_objects::SmartObject request_types_array(
+ smart_objects::SmartType_Array);
+ ;
+ for (uint16_t index = 0; index < permissions.requestType.size(); ++index) {
+ request_types_array[index] = permissions.requestType[index];
+ }
+ message[strings::msg_params][strings::request_type] = request_types_array;
+ }
+
+ app_mngr.ManageHMICommand(
+ utils::MakeShared<smart_objects::SmartObject>(message));
+}
+
+void MessageHelper::SendGetStatusUpdateResponse(const std::string& status,
+ const uint32_t correlation_id,
+ ApplicationManager& app_mngr) {
+ smart_objects::SmartObjectSPtr message =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+ if (!message) {
+ return;
+ }
+
+ (*message)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::SDL_GetStatusUpdate;
+ (*message)[strings::params][strings::message_type] = MessageType::kResponse;
+ (*message)[strings::params][strings::correlation_id] = correlation_id;
+ (*message)[strings::params][hmi_response::code] = 0;
+
+ (*message)[strings::msg_params]["status"] = status;
+
+ app_mngr.ManageHMICommand(message);
+}
+
+void MessageHelper::SendUpdateSDLResponse(const std::string& result,
+ const uint32_t correlation_id,
+ ApplicationManager& app_mngr) {
+ smart_objects::SmartObjectSPtr message =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+ DCHECK(message);
+
+ (*message)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::SDL_UpdateSDL;
+ (*message)[strings::params][strings::message_type] = MessageType::kResponse;
+ (*message)[strings::params][strings::correlation_id] = correlation_id;
+ (*message)[strings::params][hmi_response::code] = 0;
+
+ (*message)[strings::msg_params]["result"] = result;
+
+ app_mngr.ManageHMICommand(message);
+}
+
+void MessageHelper::SendOnStatusUpdate(const std::string& status,
+ ApplicationManager& app_mngr) {
+ smart_objects::SmartObjectSPtr message =
+ utils::MakeShared<smart_objects::SmartObject>(
+ smart_objects::SmartType_Map);
+ if (!message) {
+ return;
+ }
+
+ (*message)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::SDL_OnStatusUpdate;
+ (*message)[strings::params][strings::message_type] =
+ MessageType::kNotification;
+
+ (*message)[strings::msg_params]["status"] = status;
+
+ app_mngr.ManageHMICommand(message);
+}
+
+void MessageHelper::SendGetSystemInfoRequest(ApplicationManager& app_mngr) {
+ smart_objects::SmartObjectSPtr message =
+ CreateRequestObject(app_mngr.GetNextHMICorrelationID());
+ if (!message) {
+ return;
+ }
+
+ (*message)[strings::params][strings::function_id] =
+ hmi_apis::FunctionID::BasicCommunication_GetSystemInfo;
+
+ app_mngr.ManageHMICommand(message);
+}
+
+mobile_apis::Result::eType MessageHelper::VerifyImageFiles(
+ smart_objects::SmartObject& message,
+ ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr) {
+ if (NsSmartDeviceLink::NsSmartObjects::SmartType_Array == message.getType()) {
+ for (uint32_t i = 0; i < message.length(); ++i) {
+ mobile_apis::Result::eType res =
+ VerifyImageFiles(message[i], app, app_mngr);
+ if (mobile_apis::Result::SUCCESS != res) {
+ LOG4CXX_DEBUG(logger_, "VerifyImageFiles result:" << res);
+ return res;
+ }
+ }
+ } else if (NsSmartDeviceLink::NsSmartObjects::SmartType_Map ==
+ message.getType()) {
+ if (message.keyExists(strings::image_type)) {
+ mobile_apis::Result::eType verification_result =
+ VerifyImage(message, app, app_mngr);
+
+ if (mobile_apis::Result::SUCCESS != verification_result) {
+ LOG4CXX_DEBUG(logger_,
+ "VerifyImageFiles result:" << verification_result);
+ return verification_result; // exit point
+ }
+ } else {
+ std::set<std::string> keys = message.enumerate();
+
+ for (std::set<std::string>::const_iterator key = keys.begin();
+ key != keys.end();
+ ++key) {
+ if (strings::soft_buttons != (*key)) {
+ mobile_apis::Result::eType res =
+ VerifyImageFiles(message[*key], app, app_mngr);
+ if (mobile_apis::Result::SUCCESS != res) {
+ LOG4CXX_DEBUG(logger_, "VerifyImageFiles result:" << res);
+ return res;
+ }
+ }
+ }
+ }
+ } // all other types shoudn't be processed
+
+ return mobile_apis::Result::SUCCESS;
+}
+
+mobile_apis::Result::eType MessageHelper::VerifyImage(
+ smart_objects::SmartObject& image,
+ ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr) {
+ // Checking image type first: if STATIC - skip existence check, since it is
+ // HMI related file and it should know it location
+ const uint32_t image_type = image[strings::image_type].asUInt();
+ mobile_apis::ImageType::eType type =
+ static_cast<mobile_apis::ImageType::eType>(image_type);
+ if (mobile_apis::ImageType::STATIC == type) {
+ return mobile_apis::Result::SUCCESS;
+ }
+
+ const std::string& file_name = image[strings::value].asString();
+
+ std::string str = file_name;
+ str.erase(remove(str.begin(), str.end(), ' '), str.end());
+ if (0 == str.size()) {
+ return mobile_apis::Result::INVALID_DATA;
+ }
+
+ std::string full_file_path;
+ if (file_name.size() > 0 && file_name[0] == '/') {
+ full_file_path = file_name;
+ } else {
+ const std::string& app_storage_folder =
+ app_mngr.get_settings().app_storage_folder();
+ if (!app_storage_folder.empty()) {
+ // TODO(nvaganov@luxoft.com): APPLINK-11293
+ if (app_storage_folder[0] == '/') { // absolute path
+ full_file_path = app_storage_folder + "/";
+ } else { // relative path
+ full_file_path = file_system::CurrentWorkingDirectory() + "/" +
+ app_storage_folder + "/";
+ }
+ } else { // empty app storage folder
+ full_file_path = file_system::CurrentWorkingDirectory() + "/";
+ }
+
+ full_file_path += app->folder_name();
+ full_file_path += "/";
+ full_file_path += file_name;
+ }
+
+ if (!file_system::FileExists(full_file_path)) {
+ return mobile_apis::Result::INVALID_DATA;
+ }
+
+ image[strings::value] = full_file_path;
+
+ return mobile_apis::Result::SUCCESS;
+}
+
+mobile_apis::Result::eType MessageHelper::VerifyImageVrHelpItems(
+ smart_objects::SmartObject& message,
+ ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr) {
+ mobile_apis::Result::eType verification_result_image =
+ mobile_apis::Result::SUCCESS;
+ for (uint32_t i = 0; i < message.length(); ++i) {
+ if (message[i].keyExists(strings::image)) {
+ verification_result_image =
+ VerifyImage(message[i][strings::image], app, app_mngr);
+ if (mobile_apis::Result::SUCCESS != verification_result_image) {
+ return verification_result_image;
+ }
+ }
+ }
+ return mobile_apis::Result::SUCCESS;
+}
+
+bool MessageHelper::VerifySoftButtonString(const std::string& str) {
+ if ((std::string::npos != str.find_first_of("\t\n")) ||
+ (std::string::npos != str.find("\\n")) ||
+ (std::string::npos != str.find("\\t")) ||
+ (std::string::npos == str.find_first_not_of(' '))) {
+ LOG4CXX_ERROR(logger_,
+ "MessageHelper::VerifySoftButtonString"
+ "string contains incorrect character");
+ return false;
+ }
+ return true;
+}
+
+bool CheckWithPolicy(mobile_api::SystemAction::eType system_action,
+ const std::string& app_mobile_id,
+ const policy::PolicyHandlerInterface& policy_handler) {
+ using namespace mobile_apis;
+ bool result = true;
+ if (policy_handler.PolicyEnabled()) {
+ result = policy_handler.CheckSystemAction(system_action, app_mobile_id);
+ }
+ return result;
+}
+
+mobile_apis::Result::eType MessageHelper::ProcessSoftButtons(
+ smart_objects::SmartObject& message_params,
+ ApplicationConstSharedPtr app,
+ const policy::PolicyHandlerInterface& policy_handler,
+ ApplicationManager& app_mngr) {
+ using namespace mobile_apis;
+ using namespace smart_objects;
+
+ if (!message_params.keyExists(strings::soft_buttons)) {
+ return mobile_apis::Result::SUCCESS;
+ }
+
+ SmartObject& request_soft_buttons = message_params[strings::soft_buttons];
+
+ // Check whether soft buttons request is well-formed
+ if (!ValidateSoftButtons(request_soft_buttons)) {
+ return Result::INVALID_DATA;
+ }
+
+ SmartObject soft_buttons(SmartType_Array);
+
+ uint32_t j = 0;
+ size_t size = request_soft_buttons.length();
+ for (uint32_t i = 0; i < size; ++i) {
+ const int system_action =
+ request_soft_buttons[i][strings::system_action].asInt();
+
+ if (!CheckWithPolicy(static_cast<SystemAction::eType>(system_action),
+ app->policy_app_id(),
+ policy_handler)) {
+ return Result::DISALLOWED;
+ }
+
+ switch (request_soft_buttons[i][strings::type].asInt()) {
+ case SoftButtonType::SBT_IMAGE: {
+ // Any text value for type "IMAGE" should be ignored.
+ if (request_soft_buttons[i].keyExists(strings::text)) {
+ request_soft_buttons[i].erase(strings::text);
+ }
+
+ if ((!request_soft_buttons[i].keyExists(strings::image) ||
+ (Result::SUCCESS !=
+ VerifyImage(
+ request_soft_buttons[i][strings::image], app, app_mngr)))) {
+ return Result::INVALID_DATA;
+ }
+ break;
+ }
+ case SoftButtonType::SBT_TEXT: {
+ if (request_soft_buttons[i].keyExists(strings::image)) {
+ request_soft_buttons[i].erase(strings::image);
+ }
+ if ((!request_soft_buttons[i].keyExists(strings::text)) ||
+ (!VerifySoftButtonString(
+ request_soft_buttons[i][strings::text].asString()))) {
+ return Result::INVALID_DATA;
+ }
+ break;
+ }
+ case SoftButtonType::SBT_BOTH: {
+ if ((!request_soft_buttons[i].keyExists(strings::text)) ||
+ ((request_soft_buttons[i][strings::text].length()) &&
+ (!VerifySoftButtonString(
+ request_soft_buttons[i][strings::text].asString())))) {
+ return Result::INVALID_DATA;
+ }
+
+ if ((!request_soft_buttons[i].keyExists(strings::image) ||
+ (Result::SUCCESS !=
+ VerifyImage(
+ request_soft_buttons[i][strings::image], app, app_mngr)))) {
+ return Result::INVALID_DATA;
+ }
+ break;
+ }
+ default: {
+ continue;
+ break;
+ }
+ }
+
+ soft_buttons[j++] = request_soft_buttons[i];
+ }
+
+ request_soft_buttons = soft_buttons;
+
+ if (0 == request_soft_buttons.length()) {
+ message_params.erase(strings::soft_buttons);
+ }
+ return Result::SUCCESS;
+}
+
+void MessageHelper::SubscribeApplicationToSoftButton(
+ smart_objects::SmartObject& message_params,
+ ApplicationSharedPtr app,
+ int32_t function_id) {
+ SoftButtonID softbuttons_id;
+ smart_objects::SmartObject& soft_buttons =
+ message_params[strings::soft_buttons];
+ unsigned int length = soft_buttons.length();
+ for (unsigned int i = 0; i < length; ++i) {
+ softbuttons_id.insert(soft_buttons[i][strings::soft_button_id].asUInt());
+ }
+ app->SubscribeToSoftButtons(function_id, softbuttons_id);
+}
+
+// TODO(AK): change printf to logger
+bool MessageHelper::PrintSmartObject(const smart_objects::SmartObject& object) {
+ return true;
+#ifdef ENABLE_LOG
+ static uint32_t tab = 0;
+ std::string tab_buffer;
+
+ if (tab == 0) {
+ printf("\n-------------------------------------------------------------");
+ }
+
+ for (uint32_t i = 0; i < tab; ++i) {
+ tab_buffer += "\t";
+ }
+
+ switch (object.getType()) {
+ case NsSmartDeviceLink::NsSmartObjects::SmartType_Array: {
+ for (size_t i = 0; i < object.length(); i++) {
+ ++tab;
+
+ printf("\n%s%zu: ", tab_buffer.c_str(), i);
+ if (!PrintSmartObject(object.getElement(i))) {
+ printf("\n");
+ return false;
+ }
+ }
+ break;
+ }
+ case NsSmartDeviceLink::NsSmartObjects::SmartType_Map: {
+ std::set<std::string> keys = object.enumerate();
+
+ for (std::set<std::string>::const_iterator key = keys.begin();
+ key != keys.end();
+ key++) {
+ ++tab;
+
+ printf("\n%s%s: ", tab_buffer.c_str(), (*key).c_str());
+ if (!PrintSmartObject(object[(*key).c_str()])) {
+ printf("\n");
+ return false;
+ }
+ }
+ break;
+ }
+ case NsSmartDeviceLink::NsSmartObjects::SmartType_Boolean:
+ object.asBool() ? printf("true\n") : printf("false\n");
+ break;
+ case NsSmartDeviceLink::NsSmartObjects::SmartType_Double: {
+ printf("%f", object.asDouble());
+ break;
+ }
+ case NsSmartDeviceLink::NsSmartObjects::SmartType_Integer:
+ break;
+ case NsSmartDeviceLink::NsSmartObjects::SmartType_String:
+ printf("%s", object.asString().c_str());
+ break;
+ case NsSmartDeviceLink::NsSmartObjects::SmartType_Character:
+ printf("%c", object.asChar());
+ break;
+ default:
+ printf("PrintSmartObject - default case\n");
+ break;
+ }
+
+ if (0 != tab) {
+ --tab;
+ } else {
+ printf("\n-------------------------------------------------------------\n");
+ }
+#endif
+ return true;
+}
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/mobile_command_factory.cc b/src/components/application_manager/src/mobile_command_factory.cc
index 2bb1dff921..688bacf1ac 100644
--- a/src/components/application_manager/src/mobile_command_factory.cc
+++ b/src/components/application_manager/src/mobile_command_factory.cc
@@ -51,7 +51,6 @@
#include "application_manager/commands/mobile/delete_interaction_choice_set_response.h"
#include "application_manager/commands/mobile/delete_sub_menu_request.h"
#include "application_manager/commands/mobile/delete_sub_menu_response.h"
-#include "application_manager/commands/mobile/dial_number_request.h"
#include "application_manager/commands/mobile/end_audio_pass_thru_request.h"
#include "application_manager/commands/mobile/end_audio_pass_thru_response.h"
#include "application_manager/commands/mobile/generic_response.h"
@@ -59,6 +58,8 @@
#include "application_manager/commands/mobile/get_dtcs_response.h"
#include "application_manager/commands/mobile/get_vehicle_data_request.h"
#include "application_manager/commands/mobile/get_vehicle_data_response.h"
+#include "application_manager/commands/mobile/get_way_points_request.h"
+#include "application_manager/commands/mobile/get_way_points_response.h"
#include "application_manager/commands/mobile/list_files_request.h"
#include "application_manager/commands/mobile/list_files_response.h"
#include "application_manager/commands/mobile/on_app_interface_unregistered_notification.h"
@@ -74,6 +75,7 @@
#include "application_manager/commands/mobile/on_tbt_client_state_notification.h"
#include "application_manager/commands/mobile/on_vehicle_data_notification.h"
#include "application_manager/commands/mobile/on_hash_change_notification.h"
+#include "application_manager/commands/mobile/on_way_point_change_notification.h"
#include "application_manager/commands/mobile/perform_audio_pass_thru_request.h"
#include "application_manager/commands/mobile/perform_audio_pass_thru_response.h"
#include "application_manager/commands/mobile/perform_interaction_request.h"
@@ -108,6 +110,10 @@
#include "application_manager/commands/mobile/subscribe_button_response.h"
#include "application_manager/commands/mobile/subscribe_vehicle_data_request.h"
#include "application_manager/commands/mobile/subscribe_vehicle_data_response.h"
+#include "application_manager/commands/mobile/subscribe_way_points_request.h"
+#include "application_manager/commands/mobile/subscribe_way_points_response.h"
+#include "application_manager/commands/mobile/unsubscribe_way_points_request.h"
+#include "application_manager/commands/mobile/unsubscribe_way_points_response.h"
#include "application_manager/commands/mobile/unregister_app_interface_request.h"
#include "application_manager/commands/mobile/unregister_app_interface_response.h"
#include "application_manager/commands/mobile/unsubscribe_button_request.h"
@@ -128,438 +134,569 @@
#include "application_manager/commands/mobile/dial_number_request.h"
#include "application_manager/commands/mobile/dial_number_response.h"
#include "interfaces/MOBILE_API.h"
+#include "utils/make_shared.h"
namespace application_manager {
-commands::Command *MobileCommandFactory::CreateCommand(
+CommandSharedPtr MobileCommandFactory::CreateCommand(
const commands::MessageSharedPtr& message,
- commands::Command::CommandOrigin origin) {
+ commands::Command::CommandOrigin origin,
+ ApplicationManager& application_manager) {
+ CommandSharedPtr command;
switch ((*message)[strings::params][strings::function_id].asInt()) {
case mobile_apis::FunctionID::RegisterAppInterfaceID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kRequest)) {
- return new commands::RegisterAppInterfaceRequest(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kRequest)) {
+ command.reset(new commands::RegisterAppInterfaceRequest(
+ message, application_manager));
+
} else {
- return new commands::RegisterAppInterfaceResponse(message);
+ command.reset(new commands::RegisterAppInterfaceResponse(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::UnregisterAppInterfaceID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kRequest)) {
- return new commands::UnregisterAppInterfaceRequest(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kRequest)) {
+ command.reset(new commands::UnregisterAppInterfaceRequest(
+ message, application_manager));
} else {
- return new commands::UnregisterAppInterfaceResponse(message);
+ command.reset(new commands::UnregisterAppInterfaceResponse(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::SetGlobalPropertiesID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::SetGlobalPropertiesResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::SetGlobalPropertiesResponse(
+ message, application_manager));
} else {
- return new commands::SetGlobalPropertiesRequest(message);
+ command.reset(new commands::SetGlobalPropertiesRequest(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::ResetGlobalPropertiesID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::ResetGlobalPropertiesResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::ResetGlobalPropertiesResponse(
+ message, application_manager));
} else {
- return new commands::ResetGlobalPropertiesRequest(message);
+ command.reset(new commands::ResetGlobalPropertiesRequest(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::AddCommandID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::AddCommandResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::AddCommandResponse(message, application_manager));
} else {
- return new commands::AddCommandRequest(message);
+ command.reset(
+ new commands::AddCommandRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::DeleteCommandID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::DeleteCommandResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::DeleteCommandResponse(message, application_manager));
} else {
- return new commands::DeleteCommandRequest(message);
+ command.reset(
+ new commands::DeleteCommandRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::AddSubMenuID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::AddSubMenuResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::AddSubMenuResponse(message, application_manager));
} else {
- return new commands::AddSubMenuRequest(message);
+ command.reset(
+ new commands::AddSubMenuRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::DeleteSubMenuID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::DeleteSubMenuResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::DeleteSubMenuResponse(message, application_manager));
} else {
- return new commands::DeleteSubMenuRequest(message);
+ command.reset(
+ new commands::DeleteSubMenuRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::DeleteInteractionChoiceSetID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return
- new commands::DeleteInteractionChoiceSetResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::DeleteInteractionChoiceSetResponse(
+ message, application_manager));
} else {
- return new commands::DeleteInteractionChoiceSetRequest(message);
+ command.reset(new commands::DeleteInteractionChoiceSetRequest(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::AlertID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::AlertResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::AlertResponse(message, application_manager));
} else {
- return new commands::AlertRequest(message);
+ command.reset(new commands::AlertRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::SpeakID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::SpeakResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::SpeakResponse(message, application_manager));
} else {
- return new commands::SpeakRequest(message);
+ command.reset(new commands::SpeakRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::SliderID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::SliderResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::SliderResponse(message, application_manager));
} else {
- return new commands::SliderRequest(message);
+ command.reset(
+ new commands::SliderRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::PerformAudioPassThruID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::PerformAudioPassThruResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::PerformAudioPassThruResponse(
+ message, application_manager));
} else {
- return new commands::PerformAudioPassThruRequest(message);
+ command.reset(new commands::PerformAudioPassThruRequest(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::CreateInteractionChoiceSetID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return
- new commands::CreateInteractionChoiceSetResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::CreateInteractionChoiceSetResponse(
+ message, application_manager));
} else {
- return new commands::CreateInteractionChoiceSetRequest(message);
+ command.reset(new commands::CreateInteractionChoiceSetRequest(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::PerformInteractionID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::PerformInteractionResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::PerformInteractionResponse(
+ message, application_manager));
} else {
- return new commands::PerformInteractionRequest(message);
+ command.reset(new commands::PerformInteractionRequest(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::EndAudioPassThruID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::EndAudioPassThruResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::EndAudioPassThruResponse(
+ message, application_manager));
} else {
- return new commands::EndAudioPassThruRequest(message);
+ command.reset(new commands::EndAudioPassThruRequest(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::PutFileID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::PutFileResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::PutFileResponse(message, application_manager));
} else {
- return new commands::PutFileRequest(message);
+ command.reset(
+ new commands::PutFileRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::DeleteFileID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::DeleteFileResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::DeleteFileResponse(message, application_manager));
} else {
- return new commands::DeleteFileRequest(message);
+ command.reset(
+ new commands::DeleteFileRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::ListFilesID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::ListFilesResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::ListFilesResponse(message, application_manager));
} else {
- return new commands::ListFilesRequest(message);
+ command.reset(
+ new commands::ListFilesRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::SubscribeButtonID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::SubscribeButtonResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::SubscribeButtonResponse(
+ message, application_manager));
} else {
- return new commands::SubscribeButtonRequest(message);
+ command.reset(
+ new commands::SubscribeButtonRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::UnsubscribeButtonID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::UnsubscribeButtonResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::UnsubscribeButtonResponse(
+ message, application_manager));
} else {
- return new commands::UnsubscribeButtonRequest(message);
+ command.reset(new commands::UnsubscribeButtonRequest(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::ShowConstantTBTID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::ShowConstantTBTResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::ShowConstantTBTResponse(
+ message, application_manager));
} else {
- return new commands::ShowConstantTBTRequest(message);
+ command.reset(
+ new commands::ShowConstantTBTRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::ShowID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::ShowResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::ShowResponse(message, application_manager));
} else {
- return new commands::ShowRequest(message);
+ command.reset(new commands::ShowRequest(message, application_manager));
+ }
+ break;
+ }
+ case mobile_apis::FunctionID::GetWayPointsID: {
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command = utils::MakeShared<commands::GetWayPointsResponse>(
+ message, application_manager);
+ } else {
+ command = utils::MakeShared<commands::GetWayPointsRequest>(
+ message, application_manager);
}
break;
}
case mobile_apis::FunctionID::SubscribeVehicleDataID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::SubscribeVehicleDataResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::SubscribeVehicleDataResponse(
+ message, application_manager));
} else {
- return new commands::SubscribeVehicleDataRequest(message);
+ command.reset(new commands::SubscribeVehicleDataRequest(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::UnsubscribeVehicleDataID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::UnsubscribeVehicleDataResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::UnsubscribeVehicleDataResponse(
+ message, application_manager));
} else {
- return new commands::UnsubscribeVehicleDataRequest(message);
+ command.reset(new commands::UnsubscribeVehicleDataRequest(
+ message, application_manager));
+ }
+ break;
+ }
+ case mobile_apis::FunctionID::SubscribeWayPointsID: {
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command = utils::MakeShared<commands::SubscribeWayPointsResponse>(
+ message, application_manager);
+ } else {
+ command = utils::MakeShared<commands::SubscribeWayPointsRequest>(
+ message, application_manager);
+ }
+ break;
+ }
+ case mobile_apis::FunctionID::UnsubscribeWayPointsID: {
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command = utils::MakeShared<commands::UnsubscribeWayPointsResponse>(
+ message, application_manager);
+ } else {
+ command = utils::MakeShared<commands::UnSubscribeWayPointsRequest>(
+ message, application_manager);
}
break;
}
case mobile_apis::FunctionID::ReadDIDID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::ReadDIDResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::ReadDIDResponse(message, application_manager));
} else {
- return new commands::ReadDIDRequest(message);
+ command.reset(
+ new commands::ReadDIDRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::GetVehicleDataID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::GetVehicleDataResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::GetVehicleDataResponse(message, application_manager));
} else {
- return new commands::GetVehicleDataRequest(message);
+ command.reset(
+ new commands::GetVehicleDataRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::ScrollableMessageID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::ScrollableMessageResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::ScrollableMessageResponse(
+ message, application_manager));
} else {
- return new commands::ScrollableMessageRequest(message);
+ command.reset(new commands::ScrollableMessageRequest(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::AlertManeuverID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::AlertManeuverResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::AlertManeuverResponse(message, application_manager));
} else {
- return new commands::AlertManeuverRequest(message);
+ command.reset(
+ new commands::AlertManeuverRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::SetAppIconID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::SetAppIconResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::SetAppIconResponse(message, application_manager));
} else {
- return new commands::SetAppIconRequest(message);
+ command.reset(
+ new commands::SetAppIconRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::SetDisplayLayoutID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::SetDisplayLayoutResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::SetDisplayLayoutResponse(
+ message, application_manager));
} else {
- return new commands::SetDisplayLayoutRequest(message);
+ command.reset(new commands::SetDisplayLayoutRequest(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::UpdateTurnListID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::UpdateTurnListResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::UpdateTurnListResponse(message, application_manager));
} else {
- return new commands::UpdateTurnListRequest(message);
+ command.reset(
+ new commands::UpdateTurnListRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::ChangeRegistrationID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::ChangeRegistrationResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::ChangeRegistrationResponse(
+ message, application_manager));
} else {
- return new commands::ChangeRegistrationRequest(message);
+ command.reset(new commands::ChangeRegistrationRequest(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::GetDTCsID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::GetDTCsResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::GetDTCsResponse(message, application_manager));
} else {
- return new commands::GetDTCsRequest(message);
+ command.reset(
+ new commands::GetDTCsRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::DiagnosticMessageID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::DiagnosticMessageResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::DiagnosticMessageResponse(
+ message, application_manager));
} else {
- return new commands::DiagnosticMessageRequest(message);
+ command.reset(new commands::DiagnosticMessageRequest(
+ message, application_manager));
}
break;
}
case mobile_apis::FunctionID::SetMediaClockTimerID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::SetMediaClockTimerResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(new commands::SetMediaClockTimerResponse(
+ message, application_manager));
} else {
- return new commands::SetMediaClockRequest(message);
+ command.reset(
+ new commands::SetMediaClockRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::SystemRequestID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::SystemResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::SystemResponse(message, application_manager));
} else {
- return new commands::SystemRequest(message);
+ command.reset(
+ new commands::SystemRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::SendLocationID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::SendLocationResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::SendLocationResponse(message, application_manager));
} else {
- return new commands::SendLocationRequest(message);
+ command.reset(
+ new commands::SendLocationRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::DialNumberID: {
- if ((*message)[strings::params][strings::message_type]
- == static_cast<int>(application_manager::MessageType::kResponse)) {
- return new commands::DialNumberResponse(message);
+ if ((*message)[strings::params][strings::message_type] ==
+ static_cast<int>(application_manager::MessageType::kResponse)) {
+ command.reset(
+ new commands::DialNumberResponse(message, application_manager));
} else {
- return new commands::DialNumberRequest(message);
+ command.reset(
+ new commands::DialNumberRequest(message, application_manager));
}
break;
}
case mobile_apis::FunctionID::OnButtonEventID: {
- return new commands::mobile::OnButtonEventNotification(message);
+ command.reset(new commands::mobile::OnButtonEventNotification(
+ message, application_manager));
break;
}
case mobile_apis::FunctionID::OnButtonPressID: {
- return new commands::mobile::OnButtonPressNotification(message);
+ command.reset(new commands::mobile::OnButtonPressNotification(
+ message, application_manager));
break;
}
case mobile_apis::FunctionID::OnAudioPassThruID: {
- return new commands::OnAudioPassThruNotification(message);
+ command.reset(new commands::OnAudioPassThruNotification(
+ message, application_manager));
break;
}
case mobile_apis::FunctionID::OnVehicleDataID: {
- return new commands::OnVehicleDataNotification(message);
+ command.reset(new commands::OnVehicleDataNotification(
+ message, application_manager));
break;
}
case mobile_apis::FunctionID::OnAppInterfaceUnregisteredID: {
- return
- new commands::OnAppInterfaceUnregisteredNotification(message);
+ command.reset(new commands::OnAppInterfaceUnregisteredNotification(
+ message, application_manager));
break;
}
case mobile_apis::FunctionID::OnCommandID: {
- return new commands::OnCommandNotification(message);
+ command.reset(
+ new commands::OnCommandNotification(message, application_manager));
break;
}
case mobile_apis::FunctionID::OnTBTClientStateID: {
- return new commands::OnTBTClientStateNotification(message);
+ command.reset(new commands::OnTBTClientStateNotification(
+ message, application_manager));
break;
}
case mobile_apis::FunctionID::OnDriverDistractionID: {
- return
- new commands::mobile::OnDriverDistractionNotification(message);
+ command.reset(new commands::mobile::OnDriverDistractionNotification(
+ message, application_manager));
break;
}
case mobile_apis::FunctionID::OnLanguageChangeID: {
- return new commands::OnLanguageChangeNotification(message);
+ command.reset(new commands::OnLanguageChangeNotification(
+ message, application_manager));
break;
}
case mobile_apis::FunctionID::OnPermissionsChangeID: {
- return new commands::OnPermissionsChangeNotification(message);
+ command.reset(new commands::OnPermissionsChangeNotification(
+ message, application_manager));
break;
}
case mobile_apis::FunctionID::OnHMIStatusID: {
- if (origin == commands::Command::ORIGIN_MOBILE) {
- return new commands::OnHMIStatusNotificationFromMobile(message);
+ if (commands::Command::ORIGIN_SDL == origin) {
+ command.reset(new commands::OnHMIStatusNotification(
+ message, application_manager));
+ } else {
+ command.reset(new commands::OnHMIStatusNotificationFromMobile(
+ message, application_manager));
}
- return new commands::OnHMIStatusNotification(message);
break;
}
case mobile_apis::FunctionID::OnKeyboardInputID: {
- return new commands::mobile::OnKeyBoardInputNotification(message);
+ command.reset(new commands::mobile::OnKeyBoardInputNotification(
+ message, application_manager));
break;
}
case mobile_apis::FunctionID::OnTouchEventID: {
- return new commands::mobile::OnTouchEventNotification(message);
+ command.reset(new commands::mobile::OnTouchEventNotification(
+ message, application_manager));
break;
}
case mobile_apis::FunctionID::OnSystemRequestID: {
- return new commands::mobile::OnSystemRequestNotification(message);
+ command.reset(new commands::mobile::OnSystemRequestNotification(
+ message, application_manager));
break;
}
case mobile_apis::FunctionID::OnHashChangeID: {
- return new commands::mobile::OnHashChangeNotification(message);
+ command.reset(new commands::mobile::OnHashChangeNotification(
+ message, application_manager));
+ break;
+ }
+ case mobile_apis::FunctionID::OnWayPointChangeID: {
+ command = utils::MakeShared<commands::OnWayPointChangeNotification>(
+ message, application_manager);
break;
}
default: {
(*message)[strings::params][strings::function_id] =
static_cast<int32_t>(mobile_apis::FunctionID::GenericResponseID);
- return new commands::GenericResponse(message);
+ command.reset(
+ new commands::GenericResponse(message, application_manager));
}
}
+ return command;
}
} // namespace application_manager
diff --git a/src/components/application_manager/src/mobile_message_handler.cc b/src/components/application_manager/src/mobile_message_handler.cc
index 732faf8a58..09d9512b19 100644
--- a/src/components/application_manager/src/mobile_message_handler.cc
+++ b/src/components/application_manager/src/mobile_message_handler.cc
@@ -41,6 +41,7 @@
#include <stdint.h>
#include <memory>
+#include <string>
namespace {
const uint8_t kRequest = 0x0;
@@ -52,45 +53,88 @@ const uint8_t kUnknown = 0xF;
namespace application_manager {
using protocol_handler::Extract;
-CREATE_LOGGERPTR_GLOBAL(logger_, "MobileMessageHandler")
+namespace {
+typedef std::map<MessageType, std::string> MessageTypeMap;
+MessageTypeMap messageTypes = {std::make_pair(kRequest, "Request"),
+ std::make_pair(kResponse, "Response"),
+ std::make_pair(kNotification, "Notification")};
+}
+CREATE_LOGGERPTR_GLOBAL(logger_, "ApplicationManager")
-application_manager::Message* MobileMessageHandler::HandleIncomingMessageProtocol(
- const protocol_handler::RawMessagePtr message) {
- if (message->protocol_version() == ProtocolVersion::kV1) {
- return MobileMessageHandler::HandleIncomingMessageProtocolV1(message);
+application_manager::Message*
+MobileMessageHandler::HandleIncomingMessageProtocol(
+ const protocol_handler::RawMessagePtr message) {
+ DCHECK_OR_RETURN(message, NULL);
+ application_manager::Message* out_message = NULL;
+ switch (message->protocol_version()) {
+ case ProtocolVersion::kV1:
+ LOG4CXX_DEBUG(logger_, "Protocol version - V1");
+ out_message =
+ MobileMessageHandler::HandleIncomingMessageProtocolV1(message);
+ break;
+ case ProtocolVersion::kV2:
+ LOG4CXX_DEBUG(logger_, "Protocol version - V2");
+ out_message =
+ MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
+ break;
+ case ProtocolVersion::kV3:
+ LOG4CXX_DEBUG(logger_, "Protocol version - V3");
+ out_message =
+ MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
+ break;
+ case ProtocolVersion::kV4:
+ LOG4CXX_DEBUG(logger_, "Protocol version - V4");
+ out_message =
+ MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
+ break;
+ default:
+ LOG4CXX_WARN(logger_, "Can't recognise protocol version");
+ out_message = NULL;
+ break;
}
- if ((message->protocol_version() == ProtocolVersion::kV2) ||
- (message->protocol_version() == ProtocolVersion::kV3) ||
- (message->protocol_version() == ProtocolVersion::kV4)) {
- return MobileMessageHandler::HandleIncomingMessageProtocolV2(message);
+ if (out_message == NULL) {
+ LOG4CXX_WARN(logger_, "Message is NULL");
+ return NULL;
}
- return NULL;
+ LOG4CXX_DEBUG(logger_,
+ "Incoming RPC_INFO: " << (out_message->connection_key() >> 16)
+ << ", "
+ << messageTypes[out_message->type()]
+ << ", " << out_message->function_id()
+ << ", " << out_message->correlation_id()
+ << ", " << out_message->json_message());
+ return out_message;
}
-protocol_handler::RawMessage* MobileMessageHandler::HandleOutgoingMessageProtocol(
- const MobileMessage& message) {
+protocol_handler::RawMessage*
+MobileMessageHandler::HandleOutgoingMessageProtocol(
+ const MobileMessage& message) {
+ LOG4CXX_DEBUG(logger_,
+ "Outgoing RPC_INFO: " << (message->connection_key() >> 16)
+ << ", " << messageTypes[message->type()]
+ << ", " << message->function_id() << ", "
+ << message->correlation_id() << ", "
+ << message->json_message());
+
if (message->protocol_version() == application_manager::kV1) {
return MobileMessageHandler::HandleOutgoingMessageProtocolV1(message);
}
if ((message->protocol_version() == application_manager::kV2) ||
- (message->protocol_version() == application_manager::kV3) ||
- (message->protocol_version() == application_manager::kV4)) {
+ (message->protocol_version() == application_manager::kV3) ||
+ (message->protocol_version() == application_manager::kV4)) {
return MobileMessageHandler::HandleOutgoingMessageProtocolV2(message);
}
return NULL;
}
-
application_manager::Message*
MobileMessageHandler::HandleIncomingMessageProtocolV1(
- const ::protocol_handler::RawMessagePtr message) {
- LOG4CXX_INFO(logger_,
- "MobileMessageHandler HandleIncomingMessageProtocolV1()");
+ const ::protocol_handler::RawMessagePtr message) {
+ LOG4CXX_AUTO_TRACE(logger_);
application_manager::Message* outgoing_message =
- new application_manager::Message(
- protocol_handler::MessagePriority::FromServiceType(
- message->service_type())
- );
+ new application_manager::Message(
+ protocol_handler::MessagePriority::FromServiceType(
+ message->service_type()));
if (!message) {
NOTREACHED();
return NULL;
@@ -98,11 +142,10 @@ MobileMessageHandler::HandleIncomingMessageProtocolV1(
outgoing_message->set_connection_key(message->connection_key());
outgoing_message->set_protocol_version(
- static_cast<application_manager::ProtocolVersion>(message
- ->protocol_version()));
- outgoing_message->set_json_message(
- std::string(reinterpret_cast<const char*>(message->data()),
- message->data_size()));
+ static_cast<application_manager::ProtocolVersion>(
+ message->protocol_version()));
+ outgoing_message->set_json_message(std::string(
+ reinterpret_cast<const char*>(message->data()), message->data_size()));
if (outgoing_message->json_message().empty()) {
delete outgoing_message;
@@ -114,20 +157,18 @@ MobileMessageHandler::HandleIncomingMessageProtocolV1(
application_manager::Message*
MobileMessageHandler::HandleIncomingMessageProtocolV2(
- const ::protocol_handler::RawMessagePtr message) {
- LOG4CXX_INFO(logger_,
- "MobileMessageHandler HandleIncomingMessageProtocolV2()");
-
+ const ::protocol_handler::RawMessagePtr message) {
+ LOG4CXX_AUTO_TRACE(logger_);
utils::BitStream message_bytestream(message->data(), message->data_size());
protocol_handler::ProtocolPayloadV2 payload;
- protocol_handler::Extract(&message_bytestream, &payload,
- message->data_size());
+ protocol_handler::Extract(
+ &message_bytestream, &payload, message->data_size());
// Silently drop message if it wasn't parsed correctly
if (message_bytestream.IsBad()) {
- LOG4CXX_WARN(logger_,
- "Drop ill-formed message from mobile, partially parsed: "
- << payload);
+ LOG4CXX_WARN(
+ logger_,
+ "Drop ill-formed message from mobile, partially parsed: " << payload);
return NULL;
}
@@ -143,8 +184,8 @@ MobileMessageHandler::HandleIncomingMessageProtocolV2(
outgoing_message->set_correlation_id(int32_t(payload.header.correlation_id));
outgoing_message->set_connection_key(message->connection_key());
outgoing_message->set_protocol_version(
- static_cast<application_manager::ProtocolVersion>(message
- ->protocol_version()));
+ static_cast<application_manager::ProtocolVersion>(
+ message->protocol_version()));
outgoing_message->set_data_size(message->data_size());
outgoing_message->set_payload_size(message->payload_size());
@@ -157,13 +198,11 @@ MobileMessageHandler::HandleIncomingMessageProtocolV2(
protocol_handler::RawMessage*
MobileMessageHandler::HandleOutgoingMessageProtocolV1(
- const MobileMessage& message) {
- LOG4CXX_INFO(logger_,
- "MobileMessageHandler HandleOutgoingMessageProtocolV1()");
+ const MobileMessage& message) {
+ LOG4CXX_AUTO_TRACE(logger_);
std::string messageString = message->json_message();
if (messageString.length() == 0) {
- LOG4CXX_INFO(logger_,
- "Drop ill-formed message from mobile");
+ LOG4CXX_WARN(logger_, "Drop ill-formed message from mobile");
return NULL;
}
@@ -171,18 +210,17 @@ MobileMessageHandler::HandleOutgoingMessageProtocolV1(
memcpy(rawMessage, messageString.c_str(), messageString.length() + 1);
protocol_handler::RawMessage* result = new protocol_handler::RawMessage(
- message->connection_key(), 1, rawMessage, messageString.length() + 1);
+ message->connection_key(), 1, rawMessage, messageString.length() + 1);
- delete [] rawMessage;
+ delete[] rawMessage;
return result;
}
protocol_handler::RawMessage*
MobileMessageHandler::HandleOutgoingMessageProtocolV2(
- const MobileMessage& message) {
- LOG4CXX_INFO(logger_,
- "MobileMessageHandler HandleOutgoingMessageProtocolV2()");
+ const MobileMessage& message) {
+ LOG4CXX_AUTO_TRACE(logger_);
if (message->json_message().length() == 0) {
LOG4CXX_ERROR(logger_, "json string is empty.");
}
@@ -231,10 +269,10 @@ MobileMessageHandler::HandleOutgoingMessageProtocolV2(
dataForSending[offset++] = jsonSize;
memcpy(dataForSending + offset, message->json_message().c_str(), jsonSize);
-
+
// Default the service type to RPC Service
- uint8_t type = 0x07;
-
+ uint8_t type = 0x07;
+
if (message->has_binary_data()) {
// Change the service type to Hybrid Service
type = 0x0F;
@@ -246,13 +284,13 @@ MobileMessageHandler::HandleOutgoingMessageProtocolV2(
}
protocol_handler::RawMessage* msgToProtocolHandler =
- new protocol_handler::RawMessage(message->connection_key(),
- message->protocol_version(),
- dataForSending,
- dataForSendingSize,
- type);
+ new protocol_handler::RawMessage(message->connection_key(),
+ message->protocol_version(),
+ dataForSending,
+ dataForSendingSize,
+ type);
- delete [] dataForSending;
+ delete[] dataForSending;
return msgToProtocolHandler;
}
diff --git a/src/components/application_manager/src/policies/delegates/app_permission_delegate.cc b/src/components/application_manager/src/policies/delegates/app_permission_delegate.cc
index f6fe4b2538..7b5954a3c3 100644
--- a/src/components/application_manager/src/policies/delegates/app_permission_delegate.cc
+++ b/src/components/application_manager/src/policies/delegates/app_permission_delegate.cc
@@ -31,25 +31,26 @@
*/
#include "application_manager/policies/delegates/app_permission_delegate.h"
-#include "application_manager/policies/policy_handler.h"
+#include "application_manager/application_manager.h"
namespace policy {
- CREATE_LOGGERPTR_GLOBAL(logger_, "AppPermissionDelegate")
+CREATE_LOGGERPTR_GLOBAL(logger_, "PolicyHandler")
- AppPermissionDelegate::AppPermissionDelegate(
- const uint32_t connection_key, const PermissionConsent& permissions)
- : connection_key_(connection_key),
- permissions_(permissions) {
- }
+AppPermissionDelegate::AppPermissionDelegate(
+ const uint32_t connection_key,
+ const PermissionConsent& permissions,
+ policy::PolicyHandlerInterface& policy_handler)
+ : connection_key_(connection_key)
+ , permissions_(permissions)
+ , policy_handler_(policy_handler) {}
- void AppPermissionDelegate::threadMain() {
+void AppPermissionDelegate::threadMain() {
LOG4CXX_AUTO_TRACE(logger_);
- PolicyHandler::instance()->OnAppPermissionConsentInternal(connection_key_,
- permissions_);
+ policy_handler_.OnAppPermissionConsentInternal(connection_key_, permissions_);
}
void AppPermissionDelegate::exitThreadMain() {
// Do nothing
}
-} // namespace policy
+} // namespace policy
diff --git a/src/components/application_manager/src/policies/delegates/statistics_delegate.cc b/src/components/application_manager/src/policies/delegates/statistics_delegate.cc
index d4335cec8c..11c1dc9a91 100644
--- a/src/components/application_manager/src/policies/delegates/statistics_delegate.cc
+++ b/src/components/application_manager/src/policies/delegates/statistics_delegate.cc
@@ -33,71 +33,71 @@
#include "application_manager/policies/delegates/statistics_delegate.h"
#include "application_manager/policies/policy_handler.h"
-CREATE_LOGGERPTR_GLOBAL(logger_, "StatisticDelegate")
+CREATE_LOGGERPTR_GLOBAL(logger_, "PolicyHandler")
namespace policy {
- StatisticsDelegate::StatisticsDelegate(usage_statistics::GlobalCounterId type)
- : type_(INCREMENT_GLOBAL),
- global_counter_(type),
- app_id_(""),
- value_(""),
- timespan_seconds_(0) {
-
- }
-
- StatisticsDelegate::StatisticsDelegate(const std::string& app_id,
+StatisticsDelegate::StatisticsDelegate(PolicyHandler& policy_handler,
+ usage_statistics::GlobalCounterId type)
+ : type_(INCREMENT_GLOBAL)
+ , global_counter_(type)
+ , app_id_("")
+ , value_("")
+ , timespan_seconds_(0)
+ , policy_handler_(policy_handler) {}
+
+StatisticsDelegate::StatisticsDelegate(PolicyHandler& policy_handler,
+ const std::string& app_id,
usage_statistics::AppCounterId type)
- : type_(INCREMENT_APP),
- app_counter_(type),
- app_id_(app_id),
- value_(""),
- timespan_seconds_(0) {
-
- }
-
- StatisticsDelegate::StatisticsDelegate(const std::string& app_id,
+ : type_(INCREMENT_APP)
+ , app_counter_(type)
+ , app_id_(app_id)
+ , value_("")
+ , timespan_seconds_(0)
+ , policy_handler_(policy_handler) {}
+
+StatisticsDelegate::StatisticsDelegate(PolicyHandler& policy_handler,
+ const std::string& app_id,
usage_statistics::AppInfoId type,
const std::string& value)
- : type_(SET),
- app_info_(type),
- app_id_(app_id),
- value_(value),
- timespan_seconds_(0) {
-
- }
-
- StatisticsDelegate::StatisticsDelegate(const std::string& app_id,
+ : type_(SET)
+ , app_info_(type)
+ , app_id_(app_id)
+ , value_(value)
+ , timespan_seconds_(0)
+ , policy_handler_(policy_handler) {}
+
+StatisticsDelegate::StatisticsDelegate(PolicyHandler& policy_handler,
+ const std::string& app_id,
usage_statistics::AppStopwatchId type,
int32_t timespan_seconds)
- : type_(ADD),
- stop_watch_(type),
- app_id_(app_id),
- value_(""),
- timespan_seconds_(timespan_seconds) {
-
+ : type_(ADD)
+ , stop_watch_(type)
+ , app_id_(app_id)
+ , value_("")
+ , timespan_seconds_(timespan_seconds)
+ , policy_handler_(policy_handler) {}
+
+void StatisticsDelegate::threadMain() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ switch (type_) {
+ case INCREMENT_GLOBAL:
+ policy_handler_.Increment(global_counter_);
+ break;
+ case INCREMENT_APP:
+ policy_handler_.Increment(app_id_, app_counter_);
+ break;
+ case SET:
+ policy_handler_.Set(app_id_, app_info_, value_);
+ break;
+ case ADD:
+ policy_handler_.Add(app_id_, stop_watch_, timespan_seconds_);
+ break;
+ default:
+ LOG4CXX_ERROR(logger_, "Unknown statistics operator");
+ break;
}
+}
- void StatisticsDelegate::threadMain() {
- LOG4CXX_AUTO_TRACE(logger_);
- switch (type_) {
- case INCREMENT_GLOBAL:
- PolicyHandler::instance()->Increment(global_counter_);
- break;
- case INCREMENT_APP:
- PolicyHandler::instance()->Increment(app_id_, app_counter_);
- break;
- case SET:
- PolicyHandler::instance()->Set(app_id_, app_info_, value_);
- break;
- case ADD:
- PolicyHandler::instance()->Add(app_id_, stop_watch_, timespan_seconds_);
- break;
- default:
- LOG4CXX_ERROR(logger_,"Unknown statistics operator");
- break;
- }
- }
-
- void StatisticsDelegate::exitThreadMain() {
- // Do nothing
- }
-} // namespace policy
+void StatisticsDelegate::exitThreadMain() {
+ // Do nothing
+}
+} // namespace policy
diff --git a/src/components/application_manager/src/policies/policy_event_observer.cc b/src/components/application_manager/src/policies/policy_event_observer.cc
index 09f97dd3f1..492abe499a 100644
--- a/src/components/application_manager/src/policies/policy_event_observer.cc
+++ b/src/components/application_manager/src/policies/policy_event_observer.cc
@@ -43,11 +43,13 @@ class PolicyHandler;
CREATE_LOGGERPTR_GLOBAL(logger_, "PolicyHandler")
-PolicyEventObserver::PolicyEventObserver(PolicyHandler* const policy_handler)
- : policy_handler_(policy_handler) {
-}
+PolicyEventObserver::PolicyEventObserver(
+ policy::PolicyHandlerInterface* const policy_handler,
+ application_manager::event_engine::EventDispatcher& event_dispatcher)
+ : EventObserver(event_dispatcher), policy_handler_(policy_handler) {}
-void PolicyEventObserver::set_policy_handler(policy::PolicyHandler* const policy_handler) {
+void PolicyEventObserver::set_policy_handler(
+ PolicyHandlerInterface* const policy_handler) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock auto_lock(policy_handler_lock_);
LOG4CXX_DEBUG(logger_, "Set policy handler " << policy_handler);
@@ -67,10 +69,8 @@ void PolicyEventObserver::on_event(const event_engine::Event& event) {
ProcessOdometerEvent(message);
break;
}
- default: {
- break;
- }
- unsubscribe_from_event(hmi_apis::FunctionID::VehicleInfo_GetOdometer);
+ default: { break; }
+ unsubscribe_from_event(hmi_apis::FunctionID::VehicleInfo_GetOdometer);
#else
case hmi_apis::FunctionID::VehicleInfo_GetVehicleData: {
ProcessOdometerEvent(message);
@@ -82,27 +82,21 @@ void PolicyEventObserver::on_event(const event_engine::Event& event) {
unsubscribe_from_event(hmi_apis::FunctionID::BasicCommunication_OnReady);
break;
}
- default: {
- break;
- }
+ default: { break; }
#endif
}
}
-void PolicyEventObserver::ProcessOdometerEvent(const smart_objects::SmartObject& message) {
- if (hmi_apis::Common_Result::SUCCESS
- == static_cast<hmi_apis::Common_Result::eType>(message[strings::params][hmi_response::code]
- .asInt())) {
-
+void PolicyEventObserver::ProcessOdometerEvent(
+ const smart_objects::SmartObject& message) {
+ if (hmi_apis::Common_Result::SUCCESS ==
+ static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asInt())) {
if (message[strings::msg_params].keyExists(strings::odometer)) {
- TimevalStruct current_time = date_time::DateTime::getCurrentTime();
- const int kSecondsInDay = 60 * 60 * 24;
- int days_after_epoch = current_time.tv_sec / kSecondsInDay;
-
if (policy_handler_) {
policy_handler_->PTUpdatedAt(
- message[strings::msg_params][strings::odometer].asInt(),
- days_after_epoch);
+ Counters::KILOMETERS,
+ message[strings::msg_params][strings::odometer].asInt());
}
}
}
diff --git a/src/components/application_manager/src/policies/policy_handler.cc b/src/components/application_manager/src/policies/policy_handler.cc
index 8732a122c5..6070de641b 100644
--- a/src/components/application_manager/src/policies/policy_handler.cc
+++ b/src/components/application_manager/src/policies/policy_handler.cc
@@ -29,9 +29,7 @@
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
-
#include "application_manager/policies/policy_handler.h"
-
#include <unistd.h>
#include <dlfcn.h>
#include <algorithm>
@@ -40,7 +38,8 @@
#include "application_manager/policies/delegates/app_permission_delegate.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
+#include "application_manager/state_controller.h"
#include "application_manager/message_helper.h"
#include "policy/policy_manager_impl.h"
#include "connection_handler/connection_handler.h"
@@ -48,16 +47,19 @@
#include "utils/date_time.h"
#include "json/value.h"
#include "json/writer.h"
-#include "config_profile/profile.h"
#include "application_manager/usage_statistics.h"
#include "policy/policy_types.h"
#include "interfaces/MOBILE_API.h"
#include "utils/file_system.h"
+#include "utils/scope_guard.h"
+#include "utils/make_shared.h"
namespace policy {
using namespace application_manager;
+CREATE_LOGGERPTR_GLOBAL(logger_, "PolicyHandler")
+
namespace {
using namespace mobile_apis;
typedef std::map<RequestType::eType, std::string> RequestTypeMap;
@@ -91,30 +93,50 @@ const std::string RequestTypeToString(RequestType::eType type) {
}
return "";
}
+
+const policy::DeviceParams GetDeviceParams(
+ connection_handler::DeviceHandle device_handle,
+ const protocol_handler::SessionObserver& session_observer) {
+ CREATE_LOGGERPTR_LOCAL(logger_, "PolicyHandler")
+ policy::DeviceParams device_params;
+ if (-1 ==
+ session_observer.GetDataOnDeviceID(
+ device_handle,
+ &device_params.device_name,
+ NULL,
+ &device_params.device_mac_address,
+ &device_params.device_connection_type)) {
+ LOG4CXX_ERROR(logger_,
+ "Failed to extract information for device " << device_handle);
+ }
+ device_params.device_handle = device_handle;
+ return device_params;
+}
}
-#define POLICY_LIB_CHECK(return_value) \
- { \
- sync_primitives::AutoReadLock lock(policy_manager_lock_); \
- if (!policy_manager_) { \
- LOG4CXX_DEBUG(logger_, "The shared library of policy is not loaded"); \
- return return_value; \
- } \
+
+#define POLICY_LIB_CHECK(return_value) \
+ { \
+ sync_primitives::AutoReadLock lock(policy_manager_lock_); \
+ if (!policy_manager_) { \
+ LOG4CXX_DEBUG(logger_, "The shared library of policy is not loaded"); \
+ return return_value; \
+ } \
}
-#define POLICY_LIB_CHECK_VOID() \
- { \
- sync_primitives::AutoReadLock lock(policy_manager_lock_); \
- if (!policy_manager_) { \
- LOG4CXX_DEBUG(logger_, "The shared library of policy is not loaded"); \
- return; \
- } \
+#define POLICY_LIB_CHECK_VOID() \
+ { \
+ sync_primitives::AutoReadLock lock(policy_manager_lock_); \
+ if (!policy_manager_) { \
+ LOG4CXX_DEBUG(logger_, "The shared library of policy is not loaded"); \
+ return; \
+ } \
}
-CREATE_LOGGERPTR_GLOBAL(logger_, "PolicyHandler")
+static const std::string kCerficateFileName = "certificate";
struct ApplicationListHmiLevelSorter {
- bool operator()(const application_manager::ApplicationSharedPtr &lhs,
- const application_manager::ApplicationSharedPtr &rhs) {
+ bool operator()(const application_manager::ApplicationSharedPtr& lhs,
+ const application_manager::ApplicationSharedPtr& rhs) {
if (lhs && rhs) {
mobile_apis::HMILevel::eType lhs_hmi_level = lhs->hmi_level();
mobile_apis::HMILevel::eType rhs_hmi_level = rhs->hmi_level();
@@ -133,34 +155,40 @@ typedef std::set<application_manager::ApplicationSharedPtr,
struct DeactivateApplication {
explicit DeactivateApplication(
- const connection_handler::DeviceHandle &device_id)
- : device_id_(device_id) {}
+ const connection_handler::DeviceHandle& device_id,
+ StateController& state_ctrl)
+ : device_id_(device_id), state_ctrl_(state_ctrl) {}
- void operator()(const ApplicationSharedPtr &app) {
+ void operator()(const ApplicationSharedPtr& app) {
if (device_id_ == app->device()) {
- ApplicationManagerImpl::instance()->SetState<true>(
- app->app_id(), mobile_apis::HMILevel::HMI_NONE,
- mobile_apis::AudioStreamingState::NOT_AUDIBLE);
+ state_ctrl_.SetRegularState(app,
+ mobile_apis::HMILevel::HMI_NONE,
+ mobile_apis::AudioStreamingState::NOT_AUDIBLE,
+ true);
}
}
-private:
+ private:
connection_handler::DeviceHandle device_id_;
+ StateController& state_ctrl_;
};
-struct SDLAlowedNotification {
- SDLAlowedNotification(const connection_handler::DeviceHandle &device_id,
- PolicyManager *policy_manager)
- : device_id_(device_id), policy_manager_(policy_manager) {}
+struct SDLAllowedNotification {
+ SDLAllowedNotification(const connection_handler::DeviceHandle& device_id,
+ PolicyManager* policy_manager,
+ StateController& state_controller)
+ : device_id_(device_id)
+ , policy_manager_(policy_manager)
+ , state_controller_(state_controller) {}
- void operator()(const ApplicationSharedPtr &app) {
+ void operator()(const ApplicationSharedPtr& app) {
if (!policy_manager_) {
return;
}
if (device_id_ == app->device()) {
std::string hmi_level;
mobile_apis::HMILevel::eType default_mobile_hmi;
- policy_manager_->GetDefaultHmi(app->mobile_app_id(), &hmi_level);
+ policy_manager_->GetDefaultHmi(app->policy_app_id(), &hmi_level);
if ("BACKGROUND" == hmi_level) {
default_mobile_hmi = mobile_apis::HMILevel::HMI_BACKGROUND;
} else if ("FULL" == hmi_level) {
@@ -172,47 +200,52 @@ struct SDLAlowedNotification {
} else {
return;
}
- ApplicationManagerImpl::instance()->SetState<true>(app->app_id(),
- default_mobile_hmi);
+ state_controller_.SetRegularState(app, default_mobile_hmi, true);
}
}
-private:
+ private:
connection_handler::DeviceHandle device_id_;
- PolicyManager *policy_manager_;
+ PolicyManager* policy_manager_;
+ StateController& state_controller_;
};
struct LinkAppToDevice {
explicit LinkAppToDevice(
- std::map<std::string, std::string> &app_to_device_link)
- : app_to_device_link_(app_to_device_link) {
+ std::map<std::string, std::string>& app_to_device_link,
+ const ApplicationManager& application_manager)
+ : app_to_device_link_(app_to_device_link)
+ , application_manager_(application_manager) {
app_to_device_link_.clear();
}
- void operator()(const ApplicationSharedPtr &app) {
+ void operator()(const ApplicationSharedPtr& app) {
if (!app.valid()) {
- LOG4CXX_WARN(logger_, "Invalid pointer to application was passed."
- "Skip current application.");
+ LOG4CXX_WARN(logger_,
+ "Invalid pointer to application was passed."
+ "Skip current application.");
return;
}
- DeviceParams device_params;
- MessageHelper::GetDeviceInfoForApp(app->app_id(), &device_params);
- const std::string app_id = app->mobile_app_id();
+ DeviceParams device_params = GetDeviceParams(
+ app->device(),
+ application_manager_.connection_handler().get_session_observer());
+ const std::string app_id = app->policy_app_id();
if (device_params.device_mac_address.empty()) {
- LOG4CXX_WARN(logger_, "Couldn't find device, which hosts application "
- << app_id);
+ LOG4CXX_WARN(logger_,
+ "Couldn't find device, which hosts application " << app_id);
return;
}
app_to_device_link_[app_id] = device_params.device_mac_address;
}
-private:
- std::map<std::string, std::string> &app_to_device_link_;
+ private:
+ std::map<std::string, std::string>& app_to_device_link_;
+ const ApplicationManager& application_manager_;
};
struct PermissionsConsolidator {
void Consolidate(
- const std::vector<policy::FunctionalGroupPermission> &permissions) {
+ const std::vector<policy::FunctionalGroupPermission>& permissions) {
std::vector<policy::FunctionalGroupPermission>::const_iterator it =
permissions.begin();
std::vector<policy::FunctionalGroupPermission>::const_iterator it_end =
@@ -220,7 +253,8 @@ struct PermissionsConsolidator {
for (; it != it_end; ++it) {
std::vector<policy::FunctionalGroupPermission>::iterator it_consolidated =
std::find(consolidated_permissions_.begin(),
- consolidated_permissions_.end(), *it);
+ consolidated_permissions_.end(),
+ *it);
// If found, consolidate states
if (consolidated_permissions_.end() != it_consolidated) {
@@ -239,23 +273,26 @@ struct PermissionsConsolidator {
}
}
- const std::vector<policy::FunctionalGroupPermission> &
+ const std::vector<policy::FunctionalGroupPermission>&
GetConsolidatedPermissions() const {
return consolidated_permissions_;
}
-private:
+ private:
std::vector<policy::FunctionalGroupPermission> consolidated_permissions_;
};
-PolicyHandler *PolicyHandler::instance_ = NULL;
const std::string PolicyHandler::kLibrary = "libPolicy.so";
-PolicyHandler::PolicyHandler()
-
- : AsyncRunner("PolicyHandler async runner thread"), dl_handle_(0),
- last_activated_app_id_(0), app_to_device_link_lock_(true),
- statistic_manager_impl_(new StatisticManagerImpl()) {}
+PolicyHandler::PolicyHandler(const PolicySettings& settings,
+ ApplicationManager& application_manager)
+ : AsyncRunner("PolicyHandler async runner thread")
+ , dl_handle_(0)
+ , last_activated_app_id_(0)
+ , app_to_device_link_lock_(true)
+ , statistic_manager_impl_(utils::MakeShared<StatisticManagerImpl>(this))
+ , settings_(settings)
+ , application_manager_(application_manager) {}
PolicyHandler::~PolicyHandler() {}
@@ -263,43 +300,54 @@ bool PolicyHandler::LoadPolicyLibrary() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoWriteLock lock(policy_manager_lock_);
if (!PolicyEnabled()) {
- LOG4CXX_WARN(logger_, "System is configured to work without policy "
- "functionality.");
- policy_manager_ = NULL;
+ LOG4CXX_WARN(logger_,
+ "System is configured to work without policy "
+ "functionality.");
+ policy_manager_.reset();
return NULL;
}
dl_handle_ = dlopen(kLibrary.c_str(), RTLD_LAZY);
- char *error_string = dlerror();
- if (error_string == NULL) {
+ char* error = dlerror();
+ if (!error) {
if (CreateManager()) {
policy_manager_->set_listener(this);
- event_observer_ = new PolicyEventObserver(this);
+ event_observer_ =
+ utils::SharedPtr<PolicyEventObserver>(new PolicyEventObserver(
+ this, application_manager_.event_dispatcher()));
}
} else {
- LOG4CXX_ERROR(logger_, error_string);
+ LOG4CXX_ERROR(logger_, error);
}
return policy_manager_.valid();
}
-bool PolicyHandler::PolicyEnabled() {
- return profile::Profile::instance()->enable_policy();
+bool PolicyHandler::PolicyEnabled() const {
+ return get_settings().enable_policy();
}
bool PolicyHandler::CreateManager() {
- typedef PolicyManager *(*CreateManager)();
+ typedef PolicyManager* (*CreateManager)();
+ typedef void (*DeleteManager)(PolicyManager*);
CreateManager create_manager =
reinterpret_cast<CreateManager>(dlsym(dl_handle_, "CreateManager"));
- char *error_string = dlerror();
- if (error_string == NULL) {
- policy_manager_ = create_manager();
+ DeleteManager delete_manager =
+ reinterpret_cast<DeleteManager>(dlsym(dl_handle_, "DeleteManager"));
+ char* error_string = dlerror();
+ if (NULL == error_string) {
+ policy_manager_ =
+ utils::SharedPtr<PolicyManager>(create_manager(), delete_manager);
} else {
LOG4CXX_WARN(logger_, error_string);
}
return policy_manager_.valid();
}
+const PolicySettings& PolicyHandler::get_settings() const {
+ return settings_;
+}
+
bool PolicyHandler::InitPolicyTable() {
LOG4CXX_AUTO_TRACE(logger_);
POLICY_LIB_CHECK(false);
@@ -307,10 +355,9 @@ bool PolicyHandler::InitPolicyTable() {
// info necessary for policy table
event_observer_->subscribe_on_event(
hmi_apis::FunctionID::BasicCommunication_OnReady);
- std::string preloaded_file =
- profile::Profile::instance()->preloaded_pt_file();
+ const std::string& preloaded_file = get_settings().preloaded_pt_file();
if (file_system::FileExists(preloaded_file)) {
- return policy_manager_->InitPT(preloaded_file);
+ return policy_manager_->InitPT(preloaded_file, &get_settings());
}
LOG4CXX_FATAL(logger_, "The file which contains preloaded PT is not exist");
return false;
@@ -319,8 +366,7 @@ bool PolicyHandler::InitPolicyTable() {
bool PolicyHandler::ResetPolicyTable() {
LOG4CXX_TRACE(logger_, "Reset policy table.");
POLICY_LIB_CHECK(false);
- std::string preloaded_file =
- profile::Profile::instance()->preloaded_pt_file();
+ const std::string& preloaded_file = get_settings().preloaded_pt_file();
if (file_system::FileExists(preloaded_file)) {
return policy_manager_->ResetPT(preloaded_file);
}
@@ -334,53 +380,57 @@ bool PolicyHandler::ClearUserConsent() {
return policy_manager_->ResetUserConsent();
}
-uint32_t PolicyHandler::GetAppIdForSending() {
- ApplicationManagerImpl::ApplicationListAccessor accessor;
+uint32_t PolicyHandler::GetAppIdForSending() const {
+ POLICY_LIB_CHECK(0);
+ const ApplicationSet& accessor =
+ application_manager_.applications().GetData();
HmiLevelOrderedApplicationList app_list(accessor.begin(), accessor.end());
LOG4CXX_INFO(logger_, "Apps size: " << app_list.size());
- DeviceParams device_param;
for (HmiLevelOrderedApplicationList::const_iterator first = app_list.begin();
- first != app_list.end(); ++first) {
+ first != app_list.end();
+ ++first) {
if ((*first)->IsRegistered()) {
const uint32_t app_id = (*first)->app_id();
- MessageHelper::GetDeviceInfoForApp(app_id, &device_param);
+ DeviceParams device_params = GetDeviceParams(
+ (*first)->device(),
+ application_manager_.connection_handler().get_session_observer());
+
if (kDeviceAllowed ==
policy_manager_->GetUserConsentForDevice(
- device_param.device_mac_address)) {
+ device_params.device_mac_address)) {
return app_id;
}
}
}
-
return 0;
}
void PolicyHandler::OnAppPermissionConsent(
- const uint32_t connection_key, const PermissionConsent &permissions) {
+ const uint32_t connection_key, const PermissionConsent& permissions) {
LOG4CXX_AUTO_TRACE(logger_);
- AsyncRun(new AppPermissionDelegate(connection_key, permissions));
+ AsyncRun(new AppPermissionDelegate(connection_key, permissions, *this));
}
-void PolicyHandler::OnDeviceConsentChanged(const std::string &device_id,
- bool is_allowed) {
+void PolicyHandler::OnDeviceConsentChanged(const std::string& device_id,
+ const bool is_allowed) {
POLICY_LIB_CHECK_VOID();
connection_handler::DeviceHandle device_handle;
- ApplicationManagerImpl::instance()->connection_handler()->GetDeviceID(
- device_id, &device_handle);
+ application_manager_.connection_handler().GetDeviceID(device_id,
+ &device_handle);
// In case of changed consent for device, related applications will be
// limited to pre_DataConsent permissions, if device disallowed, or switch
// back to their own permissions, if device allowed again, and must be
// notified about these changes
- ApplicationManagerImpl::ApplicationListAccessor accessor;
- ApplicationManagerImpl::ApplictionSetConstIt it_app_list = accessor.begin();
- ApplicationManagerImpl::ApplictionSetConstIt it_app_list_end = accessor.end();
+ const ApplicationSet& accessor =
+ application_manager_.applications().GetData();
+ ApplicationSetConstIt it_app_list = accessor.begin();
+ ApplicationSetConstIt it_app_list_end = accessor.end();
for (; it_app_list != it_app_list_end; ++it_app_list) {
if (device_handle == (*it_app_list).get()->device()) {
-
- const std::string policy_app_id = (*it_app_list)->mobile_app_id();
+ const std::string policy_app_id = (*it_app_list)->policy_app_id();
// If app has predata policy, which is assigned without device consent or
// with negative data consent, there no necessity to change smth and send
@@ -396,48 +446,71 @@ void PolicyHandler::OnDeviceConsentChanged(const std::string &device_id,
}
}
+void PolicyHandler::SendOnAppPermissionsChanged(
+ const AppPermissions& permissions, const std::string& policy_app_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_,
+ "PolicyHandler::SendOnAppPermissionsChanged for "
+ << policy_app_id);
+ ApplicationSharedPtr app =
+ application_manager_.application_by_policy_id(policy_app_id);
+ if (!app.valid()) {
+ LOG4CXX_WARN(logger_, "No app found for policy app id = " << policy_app_id);
+ return;
+ }
+ MessageHelper::SendOnAppPermissionsChangedNotification(
+ app->app_id(), permissions, application_manager_);
+}
+
void PolicyHandler::OnPTExchangeNeeded() {
POLICY_LIB_CHECK_VOID();
- policy_manager_->ForcePTExchange();
+ MessageHelper::SendOnStatusUpdate(policy_manager_->ForcePTExchange(),
+ application_manager_);
}
-void PolicyHandler::GetAvailableApps(std::queue<std::string> &apps) {
+void PolicyHandler::GetAvailableApps(std::queue<std::string>& apps) {
LOG4CXX_INFO(logger_, "GetAvailable apps");
- ApplicationManagerImpl::ApplicationListAccessor accessor;
- const ApplicationManagerImpl::ApplictionSet app_list =
- accessor.applications();
- ApplicationManagerImpl::ApplictionSetConstIt iter = app_list.begin();
+ const ApplicationSet& app_list =
+ application_manager_.applications().GetData();
+ ApplicationSetConstIt iter = app_list.begin();
for (; app_list.end() != iter; ++iter) {
LOG4CXX_INFO(logger_, "one more app");
- apps.push((*iter)->mobile_app_id());
+ apps.push((*iter)->policy_app_id());
}
}
-void PolicyHandler::AddApplication(const std::string &application_id) {
+void PolicyHandler::AddApplication(const std::string& application_id) {
POLICY_LIB_CHECK_VOID();
policy_manager_->AddApplication(application_id);
}
-void PolicyHandler::SetDeviceInfo(std::string &device_id,
- const DeviceInfo &device_info) {
+void PolicyHandler::AddDevice(const std::string& device_id,
+ const std::string& connection_type) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ POLICY_LIB_CHECK_VOID();
+ policy_manager_->AddDevice(device_id, connection_type);
+}
+
+void PolicyHandler::SetDeviceInfo(const std::string& device_id,
+ const DeviceInfo& device_info) {
LOG4CXX_AUTO_TRACE(logger_);
POLICY_LIB_CHECK_VOID();
policy_manager_->SetDeviceInfo(device_id, device_info);
}
void PolicyHandler::OnAppPermissionConsentInternal(
- const uint32_t connection_key, PermissionConsent &permissions) {
+ const uint32_t connection_key, PermissionConsent& permissions) {
LOG4CXX_AUTO_TRACE(logger_);
POLICY_LIB_CHECK_VOID();
if (connection_key) {
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key);
+ ApplicationSharedPtr app = application_manager_.application(connection_key);
if (app.valid()) {
- permissions.policy_app_id = app->mobile_app_id();
- policy::DeviceParams device_params;
- MessageHelper::GetDeviceInfoForHandle(app->device(), &device_params);
+ permissions.policy_app_id = app->policy_app_id();
+ DeviceParams device_params = GetDeviceParams(
+ app->device(),
+ application_manager_.connection_handler().get_session_observer());
permissions.device_id = device_params.device_mac_address;
}
@@ -451,8 +524,9 @@ void PolicyHandler::OnAppPermissionConsentInternal(
sync_primitives::AutoLock lock(app_to_device_link_lock_);
if (!app_to_device_link_.size()) {
- LOG4CXX_WARN(logger_, "There are no applications previously stored for "
- "setting common permissions.");
+ LOG4CXX_WARN(logger_,
+ "There are no applications previously stored for "
+ "setting common permissions.");
return;
}
@@ -462,22 +536,25 @@ void PolicyHandler::OnAppPermissionConsentInternal(
app_to_device_link_.end();
for (; it != it_end; ++it) {
ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application_by_policy_id(it->first);
+ application_manager_.application_by_policy_id(it->first);
// If list of apps sent to HMI for user consents is not the same as current,
// permissions should be set only for coincident to registered apps
if (!app.valid()) {
- LOG4CXX_WARN(logger_, "Invalid pointer to application was passed."
- "Permissions setting skipped.");
+ LOG4CXX_WARN(logger_,
+ "Invalid pointer to application was passed."
+ "Permissions setting skipped.");
continue;
}
- policy::DeviceParams device_params;
- MessageHelper::GetDeviceInfoForHandle(app->device(), &device_params);
+ DeviceParams device_params = GetDeviceParams(
+ app->device(),
+ application_manager_.connection_handler().get_session_observer());
if (device_params.device_mac_address != it->second) {
- LOG4CXX_WARN(logger_, "Device_id of application is changed."
- "Permissions setting skipped.");
+ LOG4CXX_WARN(logger_,
+ "Device_id of application is changed."
+ "Permissions setting skipped.");
continue;
}
@@ -487,15 +564,32 @@ void PolicyHandler::OnAppPermissionConsentInternal(
}
}
+void policy::PolicyHandler::SetDaysAfterEpoch() {
+ POLICY_LIB_CHECK_VOID();
+ TimevalStruct current_time = date_time::DateTime::getCurrentTime();
+ const int kSecondsInDay = 60 * 60 * 24;
+ int days_after_epoch = current_time.tv_sec / kSecondsInDay;
+ PTUpdatedAt(Counters::DAYS_AFTER_EPOCH, days_after_epoch);
+}
+
+#ifdef ENABLE_SECURITY
+std::string PolicyHandler::RetrieveCertificate() const {
+ POLICY_LIB_CHECK(std::string(""));
+ return policy_manager_->RetrieveCertificate();
+}
+#endif // ENABLE_SECURITY
+
void PolicyHandler::OnGetUserFriendlyMessage(
- const std::vector<std::string> &message_codes, const std::string &language,
+ const std::vector<std::string>& message_codes,
+ const std::string& language,
uint32_t correlation_id) {
LOG4CXX_AUTO_TRACE(logger_);
POLICY_LIB_CHECK_VOID();
std::vector<UserFriendlyMessage> result =
policy_manager_->GetUserFriendlyMessages(message_codes, language);
// Send response to HMI with gathered data
- MessageHelper::SendGetUserFriendlyMessageResponse(result, correlation_id);
+ MessageHelper::SendGetUserFriendlyMessageResponse(
+ result, correlation_id, application_manager_);
}
void PolicyHandler::OnGetListOfPermissions(const uint32_t connection_key,
@@ -506,10 +600,11 @@ void PolicyHandler::OnGetListOfPermissions(const uint32_t connection_key,
// applications
if (!connection_key) {
sync_primitives::AutoLock lock(app_to_device_link_lock_);
- LinkAppToDevice linker(app_to_device_link_);
- ApplicationManagerImpl::ApplicationListAccessor accessor;
- ApplicationManagerImpl::ApplictionSetConstIt it_app = accessor.begin();
- ApplicationManagerImpl::ApplictionSetConstIt it_app_end = accessor.end();
+ LinkAppToDevice linker(app_to_device_link_, application_manager_);
+ const ApplicationSet& accessor =
+ application_manager_.applications().GetData();
+ ApplicationSetConstIt it_app = accessor.begin();
+ ApplicationSetConstIt it_app_end = accessor.end();
// Add all currently registered applications
std::for_each(it_app, it_app_end, linker);
@@ -519,31 +614,35 @@ void PolicyHandler::OnGetListOfPermissions(const uint32_t connection_key,
std::map<std::string, std::string>::const_iterator it =
app_to_device_link_.begin();
for (; it != app_to_device_link_.end(); ++it) {
- policy_manager_->GetUserConsentForApp(it->second, it->first,
- group_permissions);
+ policy_manager_->GetUserConsentForApp(
+ it->second, it->first, group_permissions);
consolidator.Consolidate(group_permissions);
}
MessageHelper::SendGetListOfPermissionsResponse(
- consolidator.GetConsolidatedPermissions(), correlation_id);
+ consolidator.GetConsolidatedPermissions(),
+ correlation_id,
+ application_manager_);
return;
}
// Single app only
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key);
+ ApplicationSharedPtr app = application_manager_.application(connection_key);
if (!app.valid()) {
- LOG4CXX_WARN(logger_, "Connection key '"
- << connection_key
- << "' "
- "not found within registered applications.");
+ LOG4CXX_WARN(logger_,
+ "Connection key '"
+ << connection_key
+ << "' "
+ "not found within registered applications.");
return;
}
- DeviceParams device_params;
- MessageHelper::GetDeviceInfoForApp(connection_key, &device_params);
+ DeviceParams device_params = GetDeviceParams(
+ app->device(),
+ application_manager_.connection_handler().get_session_observer());
+
std::vector<FunctionalGroupPermission> group_permissions;
if (device_params.device_mac_address.empty()) {
LOG4CXX_WARN(logger_, "Couldn't find device, which hosts application.");
@@ -551,11 +650,11 @@ void PolicyHandler::OnGetListOfPermissions(const uint32_t connection_key,
LOG4CXX_WARN(logger_, "Couldn't find application to get permissions.");
} else {
policy_manager_->GetUserConsentForApp(device_params.device_mac_address,
- app->mobile_app_id(),
+ app->policy_app_id(),
group_permissions);
- MessageHelper::SendGetListOfPermissionsResponse(group_permissions,
- correlation_id);
+ MessageHelper::SendGetListOfPermissionsResponse(
+ group_permissions, correlation_id, application_manager_);
}
}
@@ -563,42 +662,46 @@ void PolicyHandler::OnGetStatusUpdate(const uint32_t correlation_id) {
LOG4CXX_AUTO_TRACE(logger_);
POLICY_LIB_CHECK_VOID();
MessageHelper::SendGetStatusUpdateResponse(
- policy_manager_->GetPolicyTableStatus(), correlation_id);
+ policy_manager_->GetPolicyTableStatus(),
+ correlation_id,
+ application_manager_);
}
-void PolicyHandler::OnUpdateStatusChanged(const std::string &status) {
+void PolicyHandler::OnUpdateStatusChanged(const std::string& status) {
LOG4CXX_AUTO_TRACE(logger_);
- MessageHelper::SendOnStatusUpdate(status);
+ MessageHelper::SendOnStatusUpdate(status, application_manager_);
}
std::string PolicyHandler::OnCurrentDeviceIdUpdateRequired(
- const std::string &policy_app_id) {
+ const std::string& policy_app_id) {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application_by_policy_id(
- policy_app_id);
+ application_manager_.application_by_policy_id(policy_app_id);
if (!app.valid()) {
- LOG4CXX_WARN(logger_, "Application with id '"
- << policy_app_id
- << "' "
- "not found within registered applications.");
+ LOG4CXX_WARN(logger_,
+ "Application with id '"
+ << policy_app_id
+ << "' "
+ "not found within registered applications.");
return "";
}
- DeviceParams device_param;
- MessageHelper::GetDeviceInfoForApp(app->app_id(), &device_param);
- return device_param.device_mac_address;
+ DeviceParams device_params = GetDeviceParams(
+ app->device(),
+ application_manager_.connection_handler().get_session_observer());
+
+ return device_params.device_mac_address;
}
-void PolicyHandler::OnSystemInfoChanged(const std::string &language) {
+void PolicyHandler::OnSystemInfoChanged(const std::string& language) {
LOG4CXX_AUTO_TRACE(logger_);
POLICY_LIB_CHECK_VOID();
policy_manager_->SetSystemLanguage(language);
}
-void PolicyHandler::OnGetSystemInfo(const std::string &ccpu_version,
- const std::string &wers_country_code,
- const std::string &language) {
+void PolicyHandler::OnGetSystemInfo(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language) {
LOG4CXX_AUTO_TRACE(logger_);
POLICY_LIB_CHECK_VOID();
policy_manager_->SetSystemInfo(ccpu_version, wers_country_code, language);
@@ -607,35 +710,37 @@ void PolicyHandler::OnGetSystemInfo(const std::string &ccpu_version,
void PolicyHandler::OnSystemInfoUpdateRequired() {
LOG4CXX_AUTO_TRACE(logger_);
POLICY_LIB_CHECK_VOID();
- MessageHelper::SendGetSystemInfoRequest();
+ MessageHelper::SendGetSystemInfoRequest(application_manager_);
}
void PolicyHandler::OnVIIsReady() {
+ LOG4CXX_AUTO_TRACE(logger_);
const uint32_t correlation_id =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
+ application_manager_.GetNextHMICorrelationID();
std::vector<std::string> params;
params.push_back(strings::vin);
- MessageHelper::CreateGetVehicleDataRequest(correlation_id, params);
+ MessageHelper::CreateGetVehicleDataRequest(
+ correlation_id, params, application_manager_);
}
void PolicyHandler::OnVehicleDataUpdated(
- const smart_objects::SmartObject &message) {
+ const smart_objects::SmartObject& message) {
POLICY_LIB_CHECK_VOID();
}
void PolicyHandler::OnPendingPermissionChange(
- const std::string &policy_app_id) {
- LOG4CXX_DEBUG(logger_, "PolicyHandler::OnPendingPermissionChange for "
- << policy_app_id);
+ const std::string& policy_app_id) {
+ LOG4CXX_DEBUG(logger_,
+ "PolicyHandler::OnPendingPermissionChange for "
+ << policy_app_id);
POLICY_LIB_CHECK_VOID();
ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application_by_policy_id(
- policy_app_id);
+ application_manager_.application_by_policy_id(policy_app_id);
if (!app.valid()) {
- LOG4CXX_WARN(logger_, "No app found for " << policy_app_id
- << " policy app id.");
+ LOG4CXX_WARN(logger_,
+ "No app found for " << policy_app_id << " policy app id.");
return;
}
@@ -646,10 +751,12 @@ void PolicyHandler::OnPendingPermissionChange(
if (permissions.appRevoked) {
application_manager::MessageHelper::SendOnAppPermissionsChangedNotification(
- app_id, permissions);
- ApplicationManagerImpl::instance()->SetState<true>(
- app->app_id(), mobile_apis::HMILevel::HMI_NONE,
- mobile_apis::AudioStreamingState::NOT_AUDIBLE);
+ app_id, permissions, application_manager_);
+ application_manager_.state_controller().SetRegularState(
+ app,
+ mobile_apis::HMILevel::HMI_NONE,
+ mobile_apis::AudioStreamingState::NOT_AUDIBLE,
+ true);
policy_manager_->RemovePendingPermissionChanges(policy_app_id);
return;
}
@@ -657,89 +764,93 @@ void PolicyHandler::OnPendingPermissionChange(
mobile_apis::HMILevel::eType app_hmi_level = app->hmi_level();
switch (app_hmi_level) {
- case mobile_apis::HMILevel::eType::HMI_FULL:
- case mobile_apis::HMILevel::eType::HMI_LIMITED: {
- if (permissions.appPermissionsConsentNeeded) {
- MessageHelper::SendOnAppPermissionsChangedNotification(app->app_id(),
- permissions);
-
- policy_manager_->RemovePendingPermissionChanges(policy_app_id);
- // "Break" statement has to be here to continue processing in case of
- // there is another "true" flag in permissions struct
- break;
+ case mobile_apis::HMILevel::eType::HMI_FULL:
+ case mobile_apis::HMILevel::eType::HMI_LIMITED: {
+ if (permissions.appPermissionsConsentNeeded) {
+ MessageHelper::SendOnAppPermissionsChangedNotification(
+ app->app_id(), permissions, application_manager_);
+
+ policy_manager_->RemovePendingPermissionChanges(policy_app_id);
+ // "Break" statement has to be here to continue processing in case of
+ // there is another "true" flag in permissions struct
+ break;
+ }
}
- }
- case mobile_apis::HMILevel::eType::HMI_BACKGROUND: {
- if (permissions.isAppPermissionsRevoked) {
- MessageHelper::SendOnAppPermissionsChangedNotification(app->app_id(),
- permissions);
+ case mobile_apis::HMILevel::eType::HMI_BACKGROUND: {
+ if (permissions.isAppPermissionsRevoked) {
+ MessageHelper::SendOnAppPermissionsChangedNotification(
+ app->app_id(), permissions, application_manager_);
- policy_manager_->RemovePendingPermissionChanges(policy_app_id);
+ policy_manager_->RemovePendingPermissionChanges(policy_app_id);
+ }
+ break;
}
- break;
- }
- default:
- break;
+ default:
+ break;
}
if (permissions.appUnauthorized) {
if (mobile_apis::HMILevel::HMI_FULL == app_hmi_level ||
mobile_apis::HMILevel::HMI_LIMITED == app_hmi_level) {
- MessageHelper::SendOnAppPermissionsChangedNotification(app->app_id(),
- permissions);
+ MessageHelper::SendOnAppPermissionsChangedNotification(
+ app->app_id(), permissions, application_manager_);
}
- MessageHelper::SendOnAppInterfaceUnregisteredNotificationToMobile(
- app->app_id(),
- mobile_api::AppInterfaceUnregisteredReason::APP_UNAUTHORIZED);
+ application_manager_.ManageMobileCommand(
+ MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ app->app_id(),
+ mobile_api::AppInterfaceUnregisteredReason::APP_UNAUTHORIZED),
+ commands::Command::ORIGIN_SDL);
- ApplicationManagerImpl::instance()->OnAppUnauthorized(app->app_id());
+ application_manager_.OnAppUnauthorized(app->app_id());
policy_manager_->RemovePendingPermissionChanges(policy_app_id);
}
+
if (permissions.requestTypeChanged) {
- MessageHelper::SendOnAppPermissionsChangedNotification(app->app_id(),
- permissions);
+ MessageHelper::SendOnAppPermissionsChangedNotification(
+ app->app_id(), permissions, application_manager_);
policy_manager_->RemovePendingPermissionChanges(policy_app_id);
}
}
-bool PolicyHandler::SendMessageToSDK(const BinaryMessage &pt_string,
- const std::string &url) {
+bool PolicyHandler::SendMessageToSDK(const BinaryMessage& pt_string,
+ const std::string& url) {
LOG4CXX_AUTO_TRACE(logger_);
POLICY_LIB_CHECK(false);
uint32_t app_id = GetAppIdForSending();
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(app_id);
+ ApplicationSharedPtr app = application_manager_.application(app_id);
if (!app.valid()) {
- LOG4CXX_WARN(logger_, "There is no registered application with "
- "connection key '"
- << app_id << "'");
+ LOG4CXX_WARN(logger_,
+ "There is no registered application with "
+ "connection key '"
+ << app_id << "'");
return false;
}
- const std::string &mobile_app_id = app->mobile_app_id();
+ const std::string& mobile_app_id = app->policy_app_id();
if (mobile_app_id.empty()) {
- LOG4CXX_WARN(logger_, "Application with connection key '"
- << app_id << "'"
- " has no application id.");
+ LOG4CXX_WARN(logger_,
+ "Application with connection key '"
+ << app_id << "'"
+ " has no application id.");
return false;
}
- LOG4CXX_DEBUG(logger_, "Update url is " << url << " for application "
- << ApplicationManagerImpl::instance()
- ->application(app_id)
- ->name());
+ LOG4CXX_DEBUG(logger_,
+ "Update url is " << url << " for application "
+ "with connection key " << app_id);
- MessageHelper::SendPolicySnapshotNotification(app_id, pt_string, url, 0);
+ MessageHelper::SendPolicySnapshotNotification(
+ app_id, pt_string, url, application_manager_);
return true;
}
-bool PolicyHandler::ReceiveMessageFromSDK(const std::string &file,
- const BinaryMessage &pt_string) {
+bool PolicyHandler::ReceiveMessageFromSDK(const std::string& file,
+ const BinaryMessage& pt_string) {
POLICY_LIB_CHECK(false);
bool ret = policy_manager_->LoadPT(file, pt_string);
@@ -747,8 +858,9 @@ bool PolicyHandler::ReceiveMessageFromSDK(const std::string &file,
if (ret) {
LOG4CXX_INFO(logger_, "PTU was successful.");
policy_manager_->CleanupUnpairedDevices();
- int32_t correlation_id =
- ApplicationManagerImpl::instance()->GetNextHMICorrelationID();
+ int32_t correlation_id = application_manager_.GetNextHMICorrelationID();
+
+ SetDaysAfterEpoch();
event_observer_->subscribe_on_event(
#ifdef HMI_DBUS_API
@@ -759,8 +871,8 @@ bool PolicyHandler::ReceiveMessageFromSDK(const std::string &file,
);
std::vector<std::string> vehicle_data_args;
vehicle_data_args.push_back(strings::odometer);
- MessageHelper::CreateGetVehicleDataRequest(correlation_id,
- vehicle_data_args);
+ MessageHelper::CreateGetVehicleDataRequest(
+ correlation_id, vehicle_data_args, application_manager_);
} else {
LOG4CXX_WARN(logger_, "Exchange wasn't successful, trying another one.");
OnPTExchangeNeeded();
@@ -785,54 +897,50 @@ bool PolicyHandler::UnloadPolicyLibrary() {
return ret;
}
-void PolicyHandler::OnAllowSDLFunctionalityNotification(bool is_allowed,
- uint32_t device_id) {
+void PolicyHandler::OnAllowSDLFunctionalityNotification(
+ bool is_allowed, const std::string& device_mac) {
LOG4CXX_AUTO_TRACE(logger_);
POLICY_LIB_CHECK_VOID();
+ using namespace mobile_apis;
// Device ids, need to be changed
- std::set<uint32_t> device_ids;
- bool device_specific = device_id != 0;
+ std::vector<std::string> device_macs;
+ const bool device_specific = !device_mac.empty();
// Common devices consents change
+ connection_handler::ConnectionHandler& connection_handler =
+ application_manager_.connection_handler();
if (!device_specific) {
- ApplicationManagerImpl::ApplicationListAccessor accessor;
- const ApplicationManagerImpl::ApplictionSet app_list =
- accessor.applications();
-
- ApplicationManagerImpl::ApplictionSetConstIt it_app_list = app_list.begin();
- ApplicationManagerImpl::ApplictionSetConstIt it_app_end = app_list.end();
-
- for (; it_app_list != it_app_end; ++it_app_list) {
- if (!(*it_app_list).valid()) {
- continue;
- }
- device_ids.insert(it_app_list->get()->device());
- }
+ connection_handler.GetConnectedDevicesMAC(device_macs);
} else {
- device_ids.insert(device_id);
+ device_macs.push_back(device_mac);
}
- std::set<uint32_t>::const_iterator it_ids = device_ids.begin();
- std::set<uint32_t>::const_iterator it_ids_end = device_ids.end();
+ std::vector<std::string>::const_iterator it_ids = device_macs.begin();
+ std::vector<std::string>::const_iterator it_ids_end = device_macs.end();
for (; it_ids != it_ids_end; ++it_ids) {
- const uint32_t device_id = *it_ids;
-
- DeviceParams device_params;
- MessageHelper::GetDeviceInfoForHandle(device_id, &device_params);
- device_params.device_handle = device_id;
- if (kDefaultDeviceMacAddress == device_params.device_mac_address) {
- LOG4CXX_WARN(logger_, "Device with handle " << device_id
- << " wasn't found.");
+ const std::string device_id = *it_ids;
+
+ if (kDefaultDeviceMacAddress == device_id) {
+ LOG4CXX_WARN(logger_, "Device with id " << device_id << " wasn't found.");
return;
}
- policy_manager_->SetUserConsentForDevice(device_params.device_mac_address,
- is_allowed);
+ policy_manager_->SetUserConsentForDevice(device_id, is_allowed);
+ uint32_t device_handle = 0;
+ if (!connection_handler.GetDeviceID(device_mac, &device_handle)) {
+ LOG4CXX_WARN(logger_,
+ "Device hadle with mac " << device_mac << " wasn't found.");
+ }
}
// Case, when specific device was changed
- if (device_id) {
- DeviceHandles::iterator it =
- std::find(pending_device_handles_.begin(),
- pending_device_handles_.end(), device_id);
+ if (device_specific) {
+ uint32_t device_handle = 0;
+ if (!connection_handler.GetDeviceID(device_mac, &device_handle)) {
+ LOG4CXX_WARN(logger_,
+ "Device hadle with mac " << device_mac << " wasn't found.");
+ }
+ DeviceHandles::iterator it = std::find(pending_device_handles_.begin(),
+ pending_device_handles_.end(),
+ device_handle);
// If consent done from HMI menu
if (it == pending_device_handles_.end()) {
return;
@@ -851,14 +959,13 @@ void PolicyHandler::OnIgnitionCycleOver() {
void PolicyHandler::OnActivateApp(uint32_t connection_key,
uint32_t correlation_id) {
LOG4CXX_AUTO_TRACE(logger_);
-
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(connection_key);
+ POLICY_LIB_CHECK_VOID();
+ ApplicationSharedPtr app = application_manager_.application(connection_key);
if (!app.valid()) {
LOG4CXX_WARN(logger_, "Activated App failed: no app found.");
return;
}
- std::string policy_app_id = app->mobile_app_id();
+ std::string policy_app_id = app->policy_app_id();
AppPermissions permissions(policy_app_id);
@@ -878,19 +985,20 @@ void PolicyHandler::OnActivateApp(uint32_t connection_key,
// In this case we need to activate application
if (false == permissions.appRevoked && true == permissions.isSDLAllowed) {
LOG4CXX_INFO(logger_, "Application will be activated");
- if (ApplicationManagerImpl::instance()->ActivateApplication(app)) {
+ if (application_manager_.ActivateApplication(app)) {
last_activated_app_id_ = 0;
}
} else {
- LOG4CXX_INFO(logger_, "Application should not be activated");
+ LOG4CXX_WARN(logger_, "Application should not be activated");
}
- MessageHelper::SendSDLActivateAppResponse(permissions, correlation_id);
+ MessageHelper::SendSDLActivateAppResponse(
+ permissions, correlation_id, application_manager_);
}
void PolicyHandler::KmsChanged(int kilometers) {
- LOG4CXX_DEBUG(logger_, "PolicyHandler::KmsChanged " << kilometers
- << " kilometers");
+ LOG4CXX_DEBUG(logger_,
+ "PolicyHandler::KmsChanged " << kilometers << " kilometers");
POLICY_LIB_CHECK_VOID();
policy_manager_->KmsChanged(kilometers);
}
@@ -899,21 +1007,22 @@ void PolicyHandler::PTExchangeAtUserRequest(uint32_t correlation_id) {
LOG4CXX_TRACE(logger_, "PT exchange at user request");
POLICY_LIB_CHECK_VOID();
std::string update_status = policy_manager_->ForcePTExchange();
- MessageHelper::SendUpdateSDLResponse(update_status, correlation_id);
+ MessageHelper::SendUpdateSDLResponse(
+ update_status, correlation_id, application_manager_);
}
-void PolicyHandler::OnPermissionsUpdated(const std::string &policy_app_id,
- const Permissions &permissions,
- const HMILevel &default_hmi) {
+void PolicyHandler::OnPermissionsUpdated(const std::string& policy_app_id,
+ const Permissions& permissions,
+ const HMILevel& default_hmi) {
LOG4CXX_AUTO_TRACE(logger_);
OnPermissionsUpdated(policy_app_id, permissions);
ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application_by_policy_id(
- policy_app_id);
+ application_manager_.application_by_policy_id(policy_app_id);
if (!app.valid()) {
- LOG4CXX_WARN(logger_, "Connection_key not found for application_id:"
- << policy_app_id);
+ LOG4CXX_WARN(
+ logger_,
+ "Connection_key not found for application_id:" << policy_app_id);
return;
}
@@ -924,8 +1033,9 @@ void PolicyHandler::OnPermissionsUpdated(const std::string &policy_app_id,
MessageHelper::StringToHMILevel(default_hmi);
if (mobile_apis::HMILevel::INVALID_ENUM == hmi_level) {
- LOG4CXX_WARN(logger_, "Couldn't convert default hmi level " << default_hmi
- << " to enum.");
+ LOG4CXX_WARN(logger_,
+ "Couldn't convert default hmi level " << default_hmi
+ << " to enum.");
return;
}
if (current_hmi_level == hmi_level) {
@@ -933,50 +1043,56 @@ void PolicyHandler::OnPermissionsUpdated(const std::string &policy_app_id,
return;
}
switch (current_hmi_level) {
- case mobile_apis::HMILevel::HMI_NONE: {
- LOG4CXX_INFO(logger_, "Changing hmi level of application "
- << policy_app_id << " to default hmi level "
- << default_hmi);
- ApplicationManagerImpl::instance()->SetState<true>(
- app->app_id(), mobile_apis::HMILevel::HMI_FULL);
- break;
- }
- default:
- LOG4CXX_WARN(logger_, "Application " << policy_app_id
- << " is running."
- "HMI level won't be changed.");
- break;
+ case mobile_apis::HMILevel::HMI_NONE: {
+ LOG4CXX_INFO(logger_,
+ "Changing hmi level of application "
+ << policy_app_id << " to default hmi level "
+ << default_hmi);
+
+ if (hmi_level == mobile_apis::HMILevel::HMI_FULL) {
+ application_manager_.state_controller().SetRegularState(
+ app, hmi_level, true);
+ } else {
+ application_manager_.state_controller().SetRegularState(
+ app, hmi_level, false);
+ }
+ break;
+ }
+ default:
+ LOG4CXX_WARN(logger_,
+ "Application " << policy_app_id
+ << " is running."
+ "HMI level won't be changed.");
+ break;
}
}
-void PolicyHandler::OnPermissionsUpdated(const std::string &policy_app_id,
- const Permissions &permissions) {
+void PolicyHandler::OnPermissionsUpdated(const std::string& policy_app_id,
+ const Permissions& permissions) {
LOG4CXX_AUTO_TRACE(logger_);
ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application_by_policy_id(
- policy_app_id);
+ application_manager_.application_by_policy_id(policy_app_id);
if (!app.valid()) {
- LOG4CXX_WARN(logger_, "Connection_key not found for application_id:"
- << policy_app_id);
+ LOG4CXX_WARN(
+ logger_,
+ "Connection_key not found for application_id:" << policy_app_id);
return;
}
- MessageHelper::SendOnPermissionsChangeNotification(app->app_id(),
- permissions);
+ MessageHelper::SendOnPermissionsChangeNotification(
+ app->app_id(), permissions, application_manager_);
- LOG4CXX_DEBUG(logger_, "Notification sent for application_id:"
- << policy_app_id << " and connection_key "
- << app->app_id());
+ LOG4CXX_DEBUG(logger_,
+ "Notification sent for application_id:"
+ << policy_app_id << " and connection_key "
+ << app->app_id());
}
-bool PolicyHandler::SaveSnapshot(const BinaryMessage &pt_string,
- std::string &snap_path) {
- using namespace profile;
-
- const std::string &policy_snapshot_file_name =
- Profile::instance()->policies_snapshot_file_name();
- const std::string &system_files_path =
- Profile::instance()->system_files_path();
+bool PolicyHandler::SaveSnapshot(const BinaryMessage& pt_string,
+ std::string& snap_path) {
+ const std::string& policy_snapshot_file_name =
+ settings_.policies_snapshot_file_name();
+ const std::string& system_files_path = settings_.system_files_path();
snap_path = system_files_path + '/' + policy_snapshot_file_name;
bool result = false;
@@ -991,7 +1107,7 @@ bool PolicyHandler::SaveSnapshot(const BinaryMessage &pt_string,
return result;
}
-void PolicyHandler::OnSnapshotCreated(const BinaryMessage &pt_string) {
+void PolicyHandler::OnSnapshotCreated(const BinaryMessage& pt_string) {
LOG4CXX_AUTO_TRACE(logger_);
POLICY_LIB_CHECK_VOID();
#ifdef EXTENDED_POLICY
@@ -1000,58 +1116,65 @@ void PolicyHandler::OnSnapshotCreated(const BinaryMessage &pt_string) {
LOG4CXX_ERROR(logger_, "Snapshot processing skipped.");
return;
}
- MessageHelper::SendPolicyUpdate(
- policy_snapshot_full_path, policy_manager_->TimeoutExchange(),
- policy_manager_->RetrySequenceDelaysSeconds());
+ MessageHelper::SendPolicyUpdate(policy_snapshot_full_path,
+ policy_manager_->TimeoutExchange(),
+ policy_manager_->RetrySequenceDelaysSeconds(),
+ application_manager_);
#else
EndpointUrls urls;
policy_manager_->GetServiceUrls("0x07", urls);
+
+ if (urls.empty()) {
+ LOG4CXX_ERROR(logger_, "Service URLs are empty! NOT sending PT to mobile!");
+ return;
+ }
SendMessageToSDK(pt_string, urls.front().url.front());
#endif
}
-bool PolicyHandler::GetPriority(const std::string &policy_app_id,
- std::string *priority) {
+bool PolicyHandler::GetPriority(const std::string& policy_app_id,
+ std::string* priority) const {
POLICY_LIB_CHECK(false);
return policy_manager_->GetPriority(policy_app_id, priority);
}
-void PolicyHandler::CheckPermissions(const PTString &app_id,
- const PTString &hmi_level,
- const PTString &rpc,
- const RPCParams &rpc_params,
- CheckPermissionResult &result) {
+void PolicyHandler::CheckPermissions(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ const RPCParams& rpc_params,
+ CheckPermissionResult& result) {
POLICY_LIB_CHECK_VOID();
policy_manager_->CheckPermissions(app_id, hmi_level, rpc, rpc_params, result);
}
-uint32_t PolicyHandler::GetNotificationsNumber(const std::string &priority) {
+uint32_t PolicyHandler::GetNotificationsNumber(
+ const std::string& priority) const {
POLICY_LIB_CHECK(0);
return policy_manager_->GetNotificationsNumber(priority);
}
-DeviceConsent
-PolicyHandler::GetUserConsentForDevice(const std::string &device_id) {
+DeviceConsent PolicyHandler::GetUserConsentForDevice(
+ const std::string& device_id) const {
POLICY_LIB_CHECK(kDeviceDisallowed);
return policy_manager_->GetUserConsentForDevice(device_id);
}
-bool PolicyHandler::GetDefaultHmi(const std::string &policy_app_id,
- std::string *default_hmi) {
+bool PolicyHandler::GetDefaultHmi(const std::string& policy_app_id,
+ std::string* default_hmi) const {
POLICY_LIB_CHECK(false);
return policy_manager_->GetDefaultHmi(policy_app_id, default_hmi);
}
-bool PolicyHandler::GetInitialAppData(const std::string &application_id,
- StringArray *nicknames,
- StringArray *app_hmi_types) {
+bool PolicyHandler::GetInitialAppData(const std::string& application_id,
+ StringArray* nicknames,
+ StringArray* app_hmi_types) {
POLICY_LIB_CHECK(false);
- return policy_manager_->GetInitialAppData(application_id, nicknames,
- app_hmi_types);
+ return policy_manager_->GetInitialAppData(
+ application_id, nicknames, app_hmi_types);
}
-void PolicyHandler::GetServiceUrls(const std::string &service_type,
- EndpointUrls &end_points) {
+void PolicyHandler::GetServiceUrls(const std::string& service_type,
+ EndpointUrls& end_points) {
POLICY_LIB_CHECK_VOID();
policy_manager_->GetServiceUrls(service_type, end_points);
}
@@ -1061,6 +1184,7 @@ std::string PolicyHandler::GetLockScreenIconUrl() const {
return policy_manager_->GetLockScreenIconUrl();
}
+
void PolicyHandler::ResetRetrySequence() {
POLICY_LIB_CHECK_VOID();
policy_manager_->ResetRetrySequence();
@@ -1086,67 +1210,74 @@ void PolicyHandler::OnSystemReady() {
policy_manager_->OnSystemReady();
}
-void PolicyHandler::PTUpdatedAt(int kilometers, int days_after_epoch) {
+void PolicyHandler::PTUpdatedAt(Counters counter, int value) {
POLICY_LIB_CHECK_VOID();
- policy_manager_->PTUpdatedAt(kilometers, days_after_epoch);
+ policy_manager_->PTUpdatedAt(counter, value);
}
-void PolicyHandler::add_listener(PolicyHandlerObserver *listener) {
+void PolicyHandler::add_listener(PolicyHandlerObserver* listener) {
+ if (NULL == listener) {
+ return;
+ }
sync_primitives::AutoLock lock(listeners_lock_);
listeners_.push_back(listener);
}
-void PolicyHandler::remove_listener(PolicyHandlerObserver *listener) {
+void PolicyHandler::remove_listener(PolicyHandlerObserver* listener) {
+ if (NULL == listener) {
+ return;
+ }
sync_primitives::AutoLock lock(listeners_lock_);
listeners_.remove(listener);
}
utils::SharedPtr<usage_statistics::StatisticsManager>
-PolicyHandler::GetStatisticManager() {
+PolicyHandler::GetStatisticManager() const {
return statistic_manager_impl_;
}
void PolicyHandler::AddStatisticsInfo(int type) {
POLICY_LIB_CHECK_VOID();
switch (static_cast<hmi_apis::Common_StatisticsType::eType>(type)) {
- case hmi_apis::Common_StatisticsType::iAPP_BUFFER_FULL: {
- usage_statistics::GlobalCounter count_of_iap_buffer_full(
- GetStatisticManager(), usage_statistics::IAP_BUFFER_FULL);
- ++count_of_iap_buffer_full;
- break;
- }
- default: { LOG4CXX_WARN(logger_, "Type of statistics is unknown"); }
+ case hmi_apis::Common_StatisticsType::iAPP_BUFFER_FULL: {
+ usage_statistics::GlobalCounter count_of_iap_buffer_full(
+ GetStatisticManager(), usage_statistics::IAP_BUFFER_FULL);
+ ++count_of_iap_buffer_full;
+ break;
+ }
+ default: { LOG4CXX_WARN(logger_, "Type of statistics is unknown"); }
}
}
void PolicyHandler::OnSystemError(int code) {
POLICY_LIB_CHECK_VOID();
switch (static_cast<hmi_apis::Common_SystemError::eType>(code)) {
- case hmi_apis::Common_SystemError::SYNC_REBOOTED: {
- usage_statistics::GlobalCounter count_of_sync_reboots(
- GetStatisticManager(), usage_statistics::SYNC_REBOOTS);
- ++count_of_sync_reboots;
- break;
- }
- case hmi_apis::Common_SystemError::SYNC_OUT_OF_MEMMORY: {
- usage_statistics::GlobalCounter count_sync_out_of_memory(
- GetStatisticManager(), usage_statistics::SYNC_OUT_OF_MEMORY);
- ++count_sync_out_of_memory;
- break;
- }
- default: { LOG4CXX_WARN(logger_, "System error is unknown"); }
+ case hmi_apis::Common_SystemError::SYNC_REBOOTED: {
+ usage_statistics::GlobalCounter count_of_sync_reboots(
+ GetStatisticManager(), usage_statistics::SYNC_REBOOTS);
+ ++count_of_sync_reboots;
+ break;
+ }
+ case hmi_apis::Common_SystemError::SYNC_OUT_OF_MEMMORY: {
+ usage_statistics::GlobalCounter count_sync_out_of_memory(
+ GetStatisticManager(), usage_statistics::SYNC_OUT_OF_MEMORY);
+ ++count_sync_out_of_memory;
+ break;
+ }
+ default: { LOG4CXX_WARN(logger_, "System error is unknown"); }
}
}
-std::string PolicyHandler::GetAppName(const std::string &policy_app_id) {
+custom_str::CustomString PolicyHandler::GetAppName(
+ const std::string& policy_app_id) {
ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application_by_policy_id(
- policy_app_id);
+ application_manager_.application_by_policy_id(policy_app_id);
if (!app.valid()) {
- LOG4CXX_WARN(logger_, "Connection_key not found for application_id:"
- << policy_app_id);
- return "";
+ LOG4CXX_WARN(
+ logger_,
+ "Connection_key not found for application_id:" << policy_app_id);
+ return custom_str::CustomString("");
}
return app->name();
}
@@ -1161,26 +1292,29 @@ void PolicyHandler::OnUpdateHMIAppType(
}
}
-void PolicyHandler::OnCertificateUpdated(const std::string &certificate_data) {
+void PolicyHandler::OnCertificateUpdated(const std::string& certificate_data) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(listeners_lock_);
HandlersCollection::const_iterator it = listeners_.begin();
for (; it != listeners_.end(); ++it) {
- (*it)->OnCertificateUpdated(certificate_data);
+ PolicyHandlerObserver* observer = *it;
+ observer->OnCertificateUpdated(certificate_data);
}
}
-bool PolicyHandler::CanUpdate() { return 0 != GetAppIdForSending(); }
+bool PolicyHandler::CanUpdate() {
+ return 0 != GetAppIdForSending();
+}
-void PolicyHandler::RemoveDevice(const std::string &device_id) {
+void PolicyHandler::RemoveDevice(const std::string& device_id) {
LOG4CXX_AUTO_TRACE(logger_);
POLICY_LIB_CHECK_VOID();
policy_manager_->MarkUnpairedDevice(device_id);
}
-bool PolicyHandler::IsApplicationRevoked(const std::string &app_id) {
- LOG4CXX_TRACE(logger_, "PolicyHandler::IsApplicationRevoked");
+bool PolicyHandler::IsApplicationRevoked(const std::string& app_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
POLICY_LIB_CHECK(false);
return policy_manager_->IsApplicationRevoked(app_id);
@@ -1192,36 +1326,36 @@ void PolicyHandler::OnUpdateRequestSentToMobile() {
policy_manager_->OnUpdateStarted();
}
-bool PolicyHandler::CheckKeepContext(const std::string &policy_app_id) {
+bool PolicyHandler::CheckKeepContext(const std::string& policy_app_id) const {
POLICY_LIB_CHECK(false);
return policy_manager_->CanAppKeepContext(policy_app_id);
}
-bool PolicyHandler::CheckStealFocus(const std::string &policy_app_id) {
+bool PolicyHandler::CheckStealFocus(const std::string& policy_app_id) const {
POLICY_LIB_CHECK(false);
return policy_manager_->CanAppStealFocus(policy_app_id);
}
bool PolicyHandler::CheckSystemAction(
mobile_apis::SystemAction::eType system_action,
- const std::string &policy_app_id) {
+ const std::string& policy_app_id) const {
using namespace mobile_apis;
LOG4CXX_AUTO_TRACE(logger_);
switch (system_action) {
- case SystemAction::STEAL_FOCUS:
- return CheckStealFocus(policy_app_id);
- case SystemAction::KEEP_CONTEXT:
- return CheckKeepContext(policy_app_id);
- case SystemAction::DEFAULT_ACTION:
- return true;
- default:
- break;
+ case SystemAction::STEAL_FOCUS:
+ return CheckStealFocus(policy_app_id);
+ case SystemAction::KEEP_CONTEXT:
+ return CheckKeepContext(policy_app_id);
+ case SystemAction::DEFAULT_ACTION:
+ return true;
+ default:
+ break;
}
LOG4CXX_DEBUG(logger_, "Unknown system action");
return false;
}
-uint16_t PolicyHandler::HeartBeatTimeout(const std::string &app_id) const {
+uint32_t PolicyHandler::HeartBeatTimeout(const std::string& app_id) const {
POLICY_LIB_CHECK(0);
return policy_manager_->HeartBeatTimeout(app_id);
}
@@ -1243,18 +1377,18 @@ void policy::PolicyHandler::OnAppsSearchStarted() {
policy_manager_->OnAppsSearchStarted();
}
-void policy::PolicyHandler::OnAppsSearchCompleted() {
+void PolicyHandler::OnAppsSearchCompleted() {
POLICY_LIB_CHECK();
policy_manager_->OnAppsSearchCompleted();
}
-void PolicyHandler::OnAppRegisteredOnMobile(const std::string &application_id) {
+void PolicyHandler::OnAppRegisteredOnMobile(const std::string& application_id) {
POLICY_LIB_CHECK_VOID();
policy_manager_->OnAppRegisteredOnMobile(application_id);
}
bool PolicyHandler::IsRequestTypeAllowed(
- const std::string &policy_app_id,
+ const std::string& policy_app_id,
mobile_apis::RequestType::eType type) const {
POLICY_LIB_CHECK(false);
using namespace mobile_apis;
@@ -1278,35 +1412,40 @@ bool PolicyHandler::IsRequestTypeAllowed(
return request_types.end() != it;
}
-const std::vector<std::string>
-PolicyHandler::GetAppRequestTypes(const std::string &policy_app_id) const {
+const std::vector<std::string> PolicyHandler::GetAppRequestTypes(
+ const std::string& policy_app_id) const {
POLICY_LIB_CHECK(std::vector<std::string>());
return policy_manager_->GetAppRequestTypes(policy_app_id);
}
+const VehicleInfo policy::PolicyHandler::GetVehicleInfo() const {
+ POLICY_LIB_CHECK(VehicleInfo());
+ return policy_manager_->GetVehicleInfo();
+}
+
void PolicyHandler::Increment(usage_statistics::GlobalCounterId type) {
POLICY_LIB_CHECK();
policy_manager_->Increment(type);
}
-void PolicyHandler::Increment(const std::string &app_id,
+void PolicyHandler::Increment(const std::string& app_id,
usage_statistics::AppCounterId type) {
POLICY_LIB_CHECK();
policy_manager_->Increment(app_id, type);
}
-void PolicyHandler::Set(const std::string &app_id,
+void PolicyHandler::Set(const std::string& app_id,
usage_statistics::AppInfoId type,
- const std::string &value) {
+ const std::string& value) {
POLICY_LIB_CHECK();
policy_manager_->Set(app_id, type, value);
}
-void PolicyHandler::Add(const std::string &app_id,
+void PolicyHandler::Add(const std::string& app_id,
usage_statistics::AppStopwatchId type,
int32_t timespan_seconds) {
POLICY_LIB_CHECK();
policy_manager_->Add(app_id, type, timespan_seconds);
}
-} // namespace policy
+} // namespace policy
diff --git a/src/components/application_manager/src/policies/policy_retry_sequence.cc b/src/components/application_manager/src/policies/policy_retry_sequence.cc
index e1b47a0d96..a88aef0cc1 100644
--- a/src/components/application_manager/src/policies/policy_retry_sequence.cc
+++ b/src/components/application_manager/src/policies/policy_retry_sequence.cc
@@ -42,8 +42,7 @@ CREATE_LOGGERPTR_GLOBAL(logger_, "PolicyHandler")
RetrySequence::RetrySequence(PolicyHandler* const policy_handler)
// TODO (Risk copy of PolicyHandler Pointer)
- : policy_handler_(policy_handler) {
-}
+ : policy_handler_(policy_handler) {}
void RetrySequence::threadMain() {
StartNextRetry();
@@ -54,8 +53,7 @@ void RetrySequence::StartNextRetry() {
DCHECK(policy_handler_);
// TODO(Ezamakhov): inverstigate StartNextRetry on unload policy lib
- BinaryMessageSptr pt_snapshot = policy_handler_
- ->RequestPTUpdate();
+ BinaryMessageSptr pt_snapshot = policy_handler_->RequestPTUpdate();
if (pt_snapshot) {
policy_handler_->SendMessageToSDK(*pt_snapshot);
@@ -77,4 +75,3 @@ void RetrySequence::StartNextRetry() {
}
} // namespace policy
-
diff --git a/src/components/application_manager/src/policies/pt_exchange_handler_ext.cc b/src/components/application_manager/src/policies/pt_exchange_handler_ext.cc
index eba808f406..e1d5199063 100644
--- a/src/components/application_manager/src/policies/pt_exchange_handler_ext.cc
+++ b/src/components/application_manager/src/policies/pt_exchange_handler_ext.cc
@@ -43,38 +43,38 @@ using application_manager::MessageHelper;
using profile::Profile;
using std::string;
-
namespace policy {
CREATE_LOGGERPTR_GLOBAL(logger_, "PolicyHandler")
PTExchangeHandlerExt::PTExchangeHandlerExt(PolicyHandler* policy_handler)
- : PTExchangeHandler(),
- policy_handler_(policy_handler) {
+ : PTExchangeHandler(), policy_handler_(policy_handler) {
DCHECK(policy_handler_);
}
-PTExchangeHandlerExt::~PTExchangeHandlerExt() {
-}
+PTExchangeHandlerExt::~PTExchangeHandlerExt() {}
void PTExchangeHandlerExt::Start() {
LOG4CXX_TRACE(logger_, "Start exchange PT");
const string policy_snapshot_file_name =
- Profile::instance()->policies_snapshot_file_name();
+ policy_handler_->get_settings().policies_snapshot_file_name();
const std::string system_files_path =
- Profile::instance()->system_files_path();
- const std::string policy_snapshot_full_path = system_files_path + '/' +
- policy_snapshot_file_name;
+ policy_handler_->get_settings().system_files_path();
+ const std::string policy_snapshot_full_path =
+ system_files_path + '/' + policy_snapshot_file_name;
BinaryMessageSptr pt_snapshot = policy_handler_->RequestPTUpdate();
if (pt_snapshot.valid()) {
if (file_system::CreateDirectoryRecursively(system_files_path) &&
file_system::WriteBinaryFile(policy_snapshot_full_path, *pt_snapshot)) {
- MessageHelper::SendPolicyUpdate(policy_snapshot_full_path,
- policy_handler_->TimeoutExchange(),
- policy_handler_->RetrySequenceDelaysSeconds());
+ MessageHelper::SendPolicyUpdate(
+ policy_snapshot_full_path,
+ policy_handler_->TimeoutExchange(),
+ policy_handler_->RetrySequenceDelaysSeconds());
} else {
- LOG4CXX_ERROR(logger_, "Failed to write snapshot file to " << policy_snapshot_file_name);
+ LOG4CXX_ERROR(logger_,
+ "Failed to write snapshot file to "
+ << policy_snapshot_file_name);
}
} else {
LOG4CXX_ERROR(logger_, "Failed to obtain policy table snapshot");
diff --git a/src/components/application_manager/src/policies/pt_exchange_handler_impl.cc b/src/components/application_manager/src/policies/pt_exchange_handler_impl.cc
index 5a01e28d6d..d1c6fafb07 100644
--- a/src/components/application_manager/src/policies/pt_exchange_handler_impl.cc
+++ b/src/components/application_manager/src/policies/pt_exchange_handler_impl.cc
@@ -42,8 +42,9 @@ namespace policy {
CREATE_LOGGERPTR_GLOBAL(logger_, "PolicyHandler")
PTExchangeHandlerImpl::PTExchangeHandlerImpl(PolicyHandler* handler)
- : policy_handler_(handler),
- retry_sequence_(threads::CreateThread("RetrySequence", new RetrySequence(handler))) {
+ : policy_handler_(handler)
+ , retry_sequence_(
+ threads::CreateThread("RetrySequence", new RetrySequence(handler))) {
DCHECK(policy_handler_);
LOG4CXX_INFO(logger_, "Exchan created");
}
@@ -59,7 +60,8 @@ void PTExchangeHandlerImpl::Start() {
retry_sequence_->stop();
threads::DeleteThread(retry_sequence_);
- retry_sequence_ = threads::CreateThread("RetrySequence", new RetrySequence(policy_handler_));
+ retry_sequence_ = threads::CreateThread("RetrySequence",
+ new RetrySequence(policy_handler_));
if (policy_handler_) {
policy_handler_->ResetRetrySequence();
diff --git a/src/components/application_manager/src/request_controller.cc b/src/components/application_manager/src/request_controller.cc
index 098a55fa73..b2ced9b01b 100644
--- a/src/components/application_manager/src/request_controller.cc
+++ b/src/components/application_manager/src/request_controller.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -31,11 +31,12 @@
*/
#include "utils/logger.h"
-#include "config_profile/profile.h"
+
#include "application_manager/request_controller.h"
#include "application_manager/commands/command_request_impl.h"
#include "application_manager/commands/hmi/request_to_hmi.h"
#include "utils/make_shared.h"
+#include "utils/timer_task_impl.h"
namespace application_manager {
@@ -43,16 +44,18 @@ namespace request_controller {
using namespace sync_primitives;
-CREATE_LOGGERPTR_GLOBAL(logger_, "RequestController");
+CREATE_LOGGERPTR_GLOBAL(logger_, "RequestController")
-RequestController::RequestController()
- : pool_state_(UNDEFINED),
- pool_size_(profile::Profile::instance()->thread_pool_size()),
- timer_("RequestCtrlTimer", this, &RequestController::onTimer, true),
- is_low_voltage_(false) {
+RequestController::RequestController(const RequestControlerSettings& settings)
+ : pool_state_(UNDEFINED)
+ , pool_size_(settings.thread_pool_size())
+ , timer_("AM RequestCtrlTimer",
+ new timer::TimerTaskImpl<RequestController>(
+ this, &RequestController::onTimer))
+ , is_low_voltage_(false)
+ , settings_(settings) {
LOG4CXX_AUTO_TRACE(logger_);
InitializeThreadpool();
- timer_.start(dafault_sleep_time_);
}
RequestController::~RequestController() {
@@ -68,7 +71,7 @@ void RequestController::InitializeThreadpool() {
pool_state_ = TPoolState::STARTED;
char name[50];
for (uint32_t i = 0; i < pool_size_; i++) {
- snprintf(name, sizeof(name)/sizeof(name[0]), "AM Pool %d", i);
+ snprintf(name, sizeof(name) / sizeof(name[0]), "AM Pool %d", i);
pool_.push_back(threads::CreateThread(name, new Worker(this)));
pool_[i]->start();
LOG4CXX_DEBUG(logger_, "Request thread initialized: " << name);
@@ -78,7 +81,7 @@ void RequestController::InitializeThreadpool() {
void RequestController::DestroyThreadpool() {
LOG4CXX_AUTO_TRACE(logger_);
{
- AutoLock auto_lock(mobile_request_info_list_lock_);
+ AutoLock auto_lock(mobile_request_list_lock_);
pool_state_ = TPoolState::STOPPED;
LOG4CXX_DEBUG(logger_, "Broadcasting STOP signal to all threads...");
cond_var_.Broadcast(); // notify all threads we are shutting down
@@ -92,24 +95,22 @@ void RequestController::DestroyThreadpool() {
pool_.clear();
}
-RequestController::TResult RequestController::CheckPosibilitytoAdd(
+RequestController::TResult RequestController::CheckPosibilitytoAdd(
const RequestPtr request) {
LOG4CXX_AUTO_TRACE(logger_);
const uint32_t& app_hmi_level_none_time_scale =
- profile::Profile::instance()->app_hmi_level_none_time_scale();
+ settings_.app_hmi_level_none_time_scale();
// app_hmi_level_none_max_request_per_time_scale
const uint32_t& hmi_level_none_count =
- profile::Profile::instance()->app_hmi_level_none_time_scale_max_requests();
+ settings_.app_hmi_level_none_time_scale_max_requests();
- const uint32_t& app_time_scale =
- profile::Profile::instance()->app_time_scale();
+ const uint32_t& app_time_scale = settings_.app_time_scale();
const uint32_t& max_request_per_time_scale =
- profile::Profile::instance()->app_time_scale_max_requests();
+ settings_.app_time_scale_max_requests();
- const uint32_t& pending_requests_amount =
- profile::Profile::instance()->pending_requests_amount();
+ const uint32_t& pending_requests_amount = settings_.pending_requests_amount();
if (!CheckPendingRequestsAmount(pending_requests_amount)) {
LOG4CXX_ERROR(logger_, "Too many pending request");
@@ -117,16 +118,17 @@ RequestController::TResult RequestController::CheckPosibilitytoAdd(
}
if (!waiting_for_response_.CheckHMILevelTimeScaleMaxRequest(
- mobile_apis::HMILevel::HMI_NONE,
- request->connection_key(),
- app_hmi_level_none_time_scale,
- hmi_level_none_count)) {
+ mobile_apis::HMILevel::HMI_NONE,
+ request->connection_key(),
+ app_hmi_level_none_time_scale,
+ hmi_level_none_count)) {
LOG4CXX_ERROR(logger_, "Too many application requests in hmi level NONE");
return RequestController::NONE_HMI_LEVEL_MANY_REQUESTS;
}
- if (!waiting_for_response_.CheckTimeScaleMaxRequest(request->connection_key(),
- app_time_scale,
- max_request_per_time_scale)) {
+ if (!waiting_for_response_.CheckTimeScaleMaxRequest(
+ request->connection_key(),
+ app_time_scale,
+ max_request_per_time_scale)) {
LOG4CXX_ERROR(logger_, "Too many application requests");
return RequestController::TOO_MANY_REQUESTS;
}
@@ -137,12 +139,14 @@ bool RequestController::CheckPendingRequestsAmount(
const uint32_t& pending_requests_amount) {
LOG4CXX_AUTO_TRACE(logger_);
if (pending_requests_amount > 0) {
- const size_t pending_requests_size = mobile_request_info_list_.size();
+ const size_t pending_requests_size = mobile_request_list_.size();
const bool available_to_add =
pending_requests_amount > pending_requests_size;
if (!available_to_add) {
- LOG4CXX_WARN(logger_, "Pending requests count " << pending_requests_size
- << " exceed application limit " << pending_requests_amount);
+ LOG4CXX_WARN(logger_,
+ "Pending requests count " << pending_requests_size
+ << " exceed application limit "
+ << pending_requests_amount);
}
return available_to_add;
}
@@ -151,27 +155,24 @@ bool RequestController::CheckPendingRequestsAmount(
}
RequestController::TResult RequestController::addMobileRequest(
- const RequestPtr request,
- const mobile_apis::HMILevel::eType& hmi_level) {
+ const RequestPtr request, const mobile_apis::HMILevel::eType& hmi_level) {
LOG4CXX_AUTO_TRACE(logger_);
if (!request) {
LOG4CXX_ERROR(logger_, "Null Pointer request");
cond_var_.NotifyOne();
return INVALID_DATA;
}
- LOG4CXX_DEBUG(logger_, "correlation_id : " << request->correlation_id()
- << "connection_key : " << request->connection_key());
+ LOG4CXX_DEBUG(
+ logger_,
+ "correlation_id : " << request->correlation_id()
+ << "connection_key : " << request->connection_key());
RequestController::TResult result = CheckPosibilitytoAdd(request);
- if (SUCCESS ==result) {
- // Temporary set timeout to zero. Correct value will be set at the moment
- // of processing start - in threadMain()
- RequestInfoPtr request_info_ptr(utils::MakeShared<MobileRequestInfo>(request, 0u));
- request_info_ptr->set_hmi_level(hmi_level);
- AutoLock auto_lock_list(mobile_request_info_list_lock_);
- mobile_request_info_list_.push_back(request_info_ptr);
- LOG4CXX_DEBUG(logger_, "Waiting for execution: "
- << mobile_request_info_list_.size());
- // wake up one thread that is waiting for a task to be available
+ if (SUCCESS == result) {
+ AutoLock auto_lock_list(mobile_request_list_lock_);
+ mobile_request_list_.push_back(request);
+ LOG4CXX_DEBUG(logger_,
+ "Waiting for execution: " << mobile_request_list_.size());
+ // wake up one thread that is waiting for a task to be available
}
cond_var_.NotifyOne();
return result;
@@ -187,19 +188,20 @@ RequestController::TResult RequestController::addHMIRequest(
}
LOG4CXX_DEBUG(logger_, " correlation_id : " << request->correlation_id());
- const uint32_t timeout_in_seconds =
- request->default_timeout() / date_time::DateTime::MILLISECONDS_IN_SECOND;
- RequestInfoPtr request_info_ptr(new HMIRequestInfo(request,
- timeout_in_seconds));
+ const uint64_t timeout_in_mseconds =
+ static_cast<uint64_t>(request->default_timeout());
+ RequestInfoPtr request_info_ptr =
+ utils::MakeShared<HMIRequestInfo>(request, timeout_in_mseconds);
- if (0 != timeout_in_seconds) {
- waiting_for_response_.Add(request_info_ptr);
- LOG4CXX_INFO(logger_, "Waiting for response cont:"
- << waiting_for_response_.Size());
- } else {
- LOG4CXX_INFO(logger_, "Default timeout was set to 0."
- "RequestController will not track timeout of this request.");
+ if (0 == timeout_in_mseconds) {
+ LOG4CXX_DEBUG(logger_,
+ "Default timeout was set to 0."
+ "RequestController will not track timeout of this request.");
}
+ waiting_for_response_.Add(request_info_ptr);
+ LOG4CXX_DEBUG(logger_,
+ "Waiting for response count:" << waiting_for_response_.Size());
+
UpdateTimer();
return RequestController::SUCCESS;
}
@@ -213,7 +215,7 @@ void RequestController::removeNotification(
const commands::Command* notification) {
LOG4CXX_AUTO_TRACE(logger_);
std::list<RequestPtr>::iterator it = notification_list_.begin();
- for (; notification_list_.end() != it; ) {
+ for (; notification_list_.end() != it;) {
if (it->get() == notification) {
notification_list_.erase(it++);
LOG4CXX_DEBUG(logger_, "Notification removed");
@@ -225,18 +227,18 @@ void RequestController::removeNotification(
LOG4CXX_DEBUG(logger_, "Cant find notification");
}
-void RequestController::terminateRequest(
- const uint32_t& correlation_id,
- const uint32_t& connection_key, bool force_terminate) {
+void RequestController::terminateRequest(const uint32_t& correlation_id,
+ const uint32_t& connection_key,
+ bool force_terminate) {
LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(logger_, "correlation_id = " << correlation_id
- << " connection_key = " << connection_key
- << " force_terminate = " << force_terminate);
- RequestInfoPtr request = waiting_for_response_.Find(connection_key,
- correlation_id);
+ LOG4CXX_DEBUG(logger_,
+ "correlation_id = "
+ << correlation_id << " connection_key = " << connection_key
+ << " force_terminate = " << force_terminate);
+ RequestInfoPtr request =
+ waiting_for_response_.Find(connection_key, correlation_id);
if (request) {
- if (force_terminate ||
- request->request()->AllowedToTerminate()) {
+ if (force_terminate || request->request()->AllowedToTerminate()) {
waiting_for_response_.RemoveRequest(request);
} else {
LOG4CXX_WARN(logger_, "Request was not terminated");
@@ -247,14 +249,13 @@ void RequestController::terminateRequest(
}
}
-void RequestController::OnMobileResponse(
- const uint32_t& mobile_correlation_id,
- const uint32_t& connection_key) {
+void RequestController::OnMobileResponse(const uint32_t& mobile_correlation_id,
+ const uint32_t& connection_key) {
LOG4CXX_AUTO_TRACE(logger_);
terminateRequest(mobile_correlation_id, connection_key);
}
-void RequestController::OnHMIResponse(const uint32_t &correlation_id) {
+void RequestController::OnHMIResponse(const uint32_t& correlation_id) {
LOG4CXX_AUTO_TRACE(logger_);
terminateRequest(correlation_id, RequestInfo::HmiConnectoinKey);
}
@@ -262,40 +263,39 @@ void RequestController::OnHMIResponse(const uint32_t &correlation_id) {
void RequestController::terminateWaitingForExecutionAppRequests(
const uint32_t& app_id) {
LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(logger_, "app_id: " << app_id
- << "Waiting for execution" << mobile_request_info_list_.size());
- AutoLock auto_lock(mobile_request_info_list_lock_);
- std::list<RequestInfoPtr>::iterator request_it =
- mobile_request_info_list_.begin();
- while (mobile_request_info_list_.end() != request_it) {
- RequestInfoPtr request_info = (*request_it);
- if ((request_info.valid()) &&
- (request_info->request()->connection_key() == app_id)) {
- mobile_request_info_list_.erase(request_it++);
+ LOG4CXX_DEBUG(logger_,
+ "app_id: " << app_id << "Waiting for execution"
+ << mobile_request_list_.size());
+ AutoLock auto_lock(mobile_request_list_lock_);
+ std::list<RequestPtr>::iterator request_it = mobile_request_list_.begin();
+ while (mobile_request_list_.end() != request_it) {
+ RequestPtr request = (*request_it);
+ if ((request.valid()) && (request->connection_key() == app_id)) {
+ mobile_request_list_.erase(request_it++);
} else {
++request_it;
}
}
- LOG4CXX_DEBUG(logger_, "Waiting for execution "
- << mobile_request_info_list_.size());
+ LOG4CXX_DEBUG(logger_,
+ "Waiting for execution " << mobile_request_list_.size());
}
void RequestController::terminateWaitingForResponseAppRequests(
const uint32_t& app_id) {
LOG4CXX_AUTO_TRACE(logger_);
waiting_for_response_.RemoveByConnectionKey(app_id);
- LOG4CXX_DEBUG(logger_, "Waiting for response count : "
- << waiting_for_response_.Size());
+ LOG4CXX_DEBUG(
+ logger_, "Waiting for response count : " << waiting_for_response_.Size());
}
-void RequestController::terminateAppRequests(
- const uint32_t& app_id) {
+void RequestController::terminateAppRequests(const uint32_t& app_id) {
LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(logger_, "app_id : " << app_id
- << "Requests waiting for execution count : "
- << mobile_request_info_list_.size()
- << "Requests waiting for response count : "
- << waiting_for_response_.Size());
+ LOG4CXX_DEBUG(logger_,
+ "app_id : " << app_id
+ << "Requests waiting for execution count : "
+ << mobile_request_list_.size()
+ << "Requests waiting for response count : "
+ << waiting_for_response_.Size());
terminateWaitingForExecutionAppRequests(app_id);
terminateWaitingForResponseAppRequests(app_id);
@@ -311,39 +311,41 @@ void RequestController::terminateAllMobileRequests() {
LOG4CXX_AUTO_TRACE(logger_);
waiting_for_response_.RemoveMobileRequests();
LOG4CXX_DEBUG(logger_, "Mobile Requests waiting for response cleared");
- AutoLock waiting_execution_auto_lock(mobile_request_info_list_lock_);
- mobile_request_info_list_.clear();
+ AutoLock waiting_execution_auto_lock(mobile_request_list_lock_);
+ mobile_request_list_.clear();
LOG4CXX_DEBUG(logger_, "Mobile Requests waiting for execution cleared");
UpdateTimer();
}
-void RequestController::updateRequestTimeout(
- const uint32_t& app_id,
- const uint32_t& correlation_id,
- const uint32_t& new_timeout) {
+void RequestController::updateRequestTimeout(const uint32_t& app_id,
+ const uint32_t& correlation_id,
+ const uint32_t& new_timeout) {
LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(logger_, "app_id : " << app_id
- << " mobile_correlation_id : " << correlation_id
- << " new_timeout : " << new_timeout);
- LOG4CXX_DEBUG(logger_, "New_timeout is NULL. RequestCtrl will "
- "not manage this request any more");
+
+ LOG4CXX_DEBUG(logger_,
+ "app_id : " << app_id
+ << " mobile_correlation_id : " << correlation_id
+ << " new_timeout : " << new_timeout);
+ LOG4CXX_DEBUG(logger_,
+ "New_timeout is NULL. RequestCtrl will "
+ "not manage this request any more");
+
RequestInfoPtr request_info =
waiting_for_response_.Find(app_id, correlation_id);
if (request_info) {
- uint32_t timeout_in_seconds =
- new_timeout/date_time::DateTime::MILLISECONDS_IN_SECOND;
waiting_for_response_.RemoveRequest(request_info);
- request_info->updateTimeOut(timeout_in_seconds);
+ request_info->updateTimeOut(new_timeout);
waiting_for_response_.Add(request_info);
UpdateTimer();
- LOG4CXX_INFO(logger_, "Timeout updated for "
- << " app_id " << app_id
- << " correlation_id " << correlation_id
- << " new_timeout " << new_timeout);
+ LOG4CXX_INFO(logger_,
+ "Timeout updated for "
+ << " app_id: " << app_id << " correlation_id: "
+ << correlation_id << " new_timeout (ms): " << new_timeout);
} else {
- LOG4CXX_ERROR(logger_, "Can't find request with "
- << " app_id " << app_id
- << " correlation_id " << correlation_id);
+ LOG4CXX_ERROR(logger_,
+ "Can't find request with "
+ << " app_id: " << app_id
+ << " correlation_id: " << correlation_id);
}
}
@@ -367,25 +369,28 @@ bool RequestController::IsLowVoltage() {
void RequestController::onTimer() {
LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(logger_, "ENTER Waiting fore response count: "
- << waiting_for_response_.Size());
+ LOG4CXX_DEBUG(
+ logger_,
+ "ENTER Waiting fore response count: " << waiting_for_response_.Size());
RequestInfoPtr probably_expired =
waiting_for_response_.FrontWithNotNullTimeout();
while (probably_expired && probably_expired->isExpired()) {
- LOG4CXX_INFO(logger_, "Timeout for "
- << (RequestInfo::HMIRequest
- == probably_expired ->requst_type() ? "HMI": "Mobile")
- << " request id: "
- << probably_expired ->requestId()
- << " connection_key: " <<
- probably_expired ->app_id() << " is expired");
+ LOG4CXX_INFO(logger_,
+ "Timeout for "
+ << (RequestInfo::HMIRequest ==
+ probably_expired->requst_type()
+ ? "HMI"
+ : "Mobile")
+ << " request id: " << probably_expired->requestId()
+ << " connection_key: " << probably_expired->app_id()
+ << " is expired");
const uint32_t experied_request_id = probably_expired->requestId();
const uint32_t experied_app_id = probably_expired->app_id();
probably_expired->request()->onTimeOut();
- if (RequestInfo::HmiConnectoinKey == probably_expired ->app_id()) {
- LOG4CXX_DEBUG(logger_, "Erase HMI request: "
- << probably_expired ->requestId());
+ if (RequestInfo::HmiConnectoinKey == probably_expired->app_id()) {
+ LOG4CXX_DEBUG(logger_,
+ "Erase HMI request: " << probably_expired->requestId());
waiting_for_response_.RemoveRequest(probably_expired);
}
probably_expired = waiting_for_response_.FrontWithNotNullTimeout();
@@ -398,27 +403,25 @@ void RequestController::onTimer() {
}
}
UpdateTimer();
- LOG4CXX_DEBUG(logger_, "EXIT Waiting for response count : "
- << waiting_for_response_.Size());
+ LOG4CXX_DEBUG(
+ logger_,
+ "EXIT Waiting for response count : " << waiting_for_response_.Size());
}
RequestController::Worker::Worker(RequestController* requestController)
- : request_controller_(requestController)
- , stop_flag_(false) {
-}
+ : request_controller_(requestController), stop_flag_(false) {}
-RequestController::Worker::~Worker() {
-}
+RequestController::Worker::~Worker() {}
void RequestController::Worker::threadMain() {
LOG4CXX_AUTO_TRACE(logger_);
AutoLock auto_lock(thread_lock_);
while (!stop_flag_) {
// Try to pick a request
- AutoLock auto_lock(request_controller_->mobile_request_info_list_lock_);
+ AutoLock auto_lock(request_controller_->mobile_request_list_lock_);
while ((request_controller_->pool_state_ != TPoolState::STOPPED) &&
- (request_controller_->mobile_request_info_list_.empty())) {
+ (request_controller_->mobile_request_list_.empty())) {
// Wait until there is a task in the queue
// Unlock mutex while wait, then lock it back when signaled
LOG4CXX_INFO(logger_, "Unlocking and waiting");
@@ -431,29 +434,29 @@ void RequestController::Worker::threadMain() {
break;
}
- if (request_controller_->mobile_request_info_list_.empty()) {
+ if (request_controller_->mobile_request_list_.empty()) {
LOG4CXX_WARN(logger_, "Mobile request list is empty");
break;
}
- RequestInfoPtr request_info_ptr(
- request_controller_->mobile_request_info_list_.front());
- request_controller_->mobile_request_info_list_.pop_front();
- bool init_res = request_info_ptr->request()->Init(); // to setup specific
- // default timeout
+ RequestPtr request_ptr(request_controller_->mobile_request_list_.front());
+ request_controller_->mobile_request_list_.pop_front();
+
+ bool init_res = request_ptr->Init(); // to setup specific
+ // default timeout
- const uint32_t timeout_in_seconds =
- request_info_ptr->request()->default_timeout() /
- date_time::DateTime::MILLISECONDS_IN_SECOND;
- // Start time, end time and timeout need to be updated to appropriate values
- request_info_ptr->update_start_time(date_time::DateTime::getCurrentTime());
- request_info_ptr->updateTimeOut(timeout_in_seconds);
+ const uint32_t timeout_in_mseconds = request_ptr->default_timeout();
+ RequestInfoPtr request_info_ptr =
+ utils::MakeShared<MobileRequestInfo>(request_ptr, timeout_in_mseconds);
request_controller_->waiting_for_response_.Add(request_info_ptr);
- if (0 != timeout_in_seconds) {
+ LOG4CXX_DEBUG(logger_, "timeout_in_mseconds " << timeout_in_mseconds);
+
+ if (0 != timeout_in_mseconds) {
request_controller_->UpdateTimer();
} else {
- LOG4CXX_DEBUG(logger_, "Default timeout was set to 0. "
+ LOG4CXX_DEBUG(logger_,
+ "Default timeout was set to 0. "
"RequestController will not track timeout "
"of this request.");
}
@@ -462,11 +465,12 @@ void RequestController::Worker::threadMain() {
// execute
if ((false == request_controller_->IsLowVoltage()) &&
- request_info_ptr->request()->CheckPermissions() && init_res) {
- LOG4CXX_DEBUG(logger_, "Execute MobileRequest corr_id = "
- << request_info_ptr->requestId()
- << " with timeout: " << timeout_in_seconds);
- request_info_ptr->request()->Run();
+ request_ptr->CheckPermissions() && init_res) {
+ LOG4CXX_DEBUG(logger_,
+ "Execute MobileRequest corr_id = "
+ << request_info_ptr->requestId()
+ << " with timeout: " << timeout_in_mseconds);
+ request_ptr->Run();
}
}
}
@@ -480,27 +484,33 @@ void RequestController::Worker::exitThreadMain() {
void RequestController::UpdateTimer() {
LOG4CXX_AUTO_TRACE(logger_);
RequestInfoPtr front = waiting_for_response_.FrontWithNotNullTimeout();
+ // Buffer for sending request
+ const uint32_t delay_time = 100u;
if (front) {
const TimevalStruct current_time = date_time::DateTime::getCurrentTime();
- const TimevalStruct end_time = front->end_time();
+ TimevalStruct end_time = front->end_time();
+ date_time::DateTime::AddMilliseconds(end_time, delay_time);
if (current_time < end_time) {
- const uint64_t secs = end_time.tv_sec - current_time.tv_sec;
- LOG4CXX_DEBUG(logger_, "Sleep for " << secs << " secs");
+ const uint32_t msecs = static_cast<uint32_t>(
+ date_time::DateTime::getmSecs(end_time - current_time));
+ LOG4CXX_DEBUG(logger_, "Sleep for " << msecs << " millisecs");
// Timeout for bigger than 5 minutes is a mistake
- timer_.updateTimeOut(secs);
+ timer_.Start(msecs, true);
} else {
- LOG4CXX_WARN(logger_, "Request app_id = " << front->app_id()
- << "correlation_id = " << front->requestId()
- << "is expired a long time ago: "
- << end_time.tv_sec << " - "
- << current_time.tv_sec << " >= "
- << front->timeout_sec());
- timer_.updateTimeOut(0);
+ LOG4CXX_WARN(
+ logger_,
+ "Request app_id: "
+ << front->app_id() << " correlation_id: " << front->requestId()
+ << " is expired. "
+ << "End time (ms): " << date_time::DateTime::getmSecs(end_time)
+ << " Current time (ms): "
+ << date_time::DateTime::getmSecs(current_time)
+ << " Diff (current - end) (ms): "
+ << date_time::DateTime::getmSecs(current_time - end_time)
+ << " Request timeout (sec): "
+ << front->timeout_msec() /
+ date_time::DateTime::MILLISECONDS_IN_SECOND);
}
- } else {
- LOG4CXX_DEBUG(logger_, "Sleep for default sleep time "
- << dafault_sleep_time_ << " secs");
- timer_.updateTimeOut(dafault_sleep_time_);
}
}
diff --git a/src/components/application_manager/src/request_info.cc b/src/components/application_manager/src/request_info.cc
index 26af81ea53..80b18a53c6 100644
--- a/src/components/application_manager/src/request_info.cc
+++ b/src/components/application_manager/src/request_info.cc
@@ -40,51 +40,44 @@ namespace application_manager {
namespace request_controller {
-CREATE_LOGGERPTR_GLOBAL(logger_, "RequestController");
+CREATE_LOGGERPTR_GLOBAL(logger_, "RequestController")
uint32_t RequestInfo::HmiConnectoinKey = 0;
-HMIRequestInfo::HMIRequestInfo(
- RequestPtr request,
- const uint64_t timeout_sec):
- RequestInfo(request, HMIRequest, timeout_sec) {
- correlation_id_ = request_->correlation_id();
- app_id_ = RequestInfo::HmiConnectoinKey;
+HMIRequestInfo::HMIRequestInfo(RequestPtr request, const uint64_t timeout_msec)
+ : RequestInfo(request, HMIRequest, timeout_msec) {
+ correlation_id_ = request_->correlation_id();
+ app_id_ = RequestInfo::HmiConnectoinKey;
}
-HMIRequestInfo::HMIRequestInfo(
- RequestPtr request,
- const TimevalStruct &start_time,
- const uint64_t timeout_sec):
- RequestInfo(request, HMIRequest, start_time, timeout_sec) {
- correlation_id_ = request_->correlation_id();
- app_id_ = RequestInfo::HmiConnectoinKey;
+HMIRequestInfo::HMIRequestInfo(RequestPtr request,
+ const TimevalStruct& start_time,
+ const uint64_t timeout_msec)
+ : RequestInfo(request, HMIRequest, start_time, timeout_msec) {
+ correlation_id_ = request_->correlation_id();
+ app_id_ = RequestInfo::HmiConnectoinKey;
}
-MobileRequestInfo::MobileRequestInfo(
- RequestPtr request,
- const uint64_t timeout_sec):
- RequestInfo(request, MobileRequest, timeout_sec) {
- correlation_id_ = request_.get()->correlation_id();
- app_id_ = request_.get()->connection_key();
+MobileRequestInfo::MobileRequestInfo(RequestPtr request,
+ const uint64_t timeout_msec)
+ : RequestInfo(request, MobileRequest, timeout_msec) {
+ correlation_id_ = request_.get()->correlation_id();
+ app_id_ = request_.get()->connection_key();
}
-MobileRequestInfo::MobileRequestInfo(
- RequestPtr request,
- const TimevalStruct &start_time,
- const uint64_t timeout_sec):
- RequestInfo(request, MobileRequest, start_time, timeout_sec) {
- correlation_id_ = request_.get()->correlation_id();
- app_id_ = request_.get()->connection_key();
+MobileRequestInfo::MobileRequestInfo(RequestPtr request,
+ const TimevalStruct& start_time,
+ const uint64_t timeout_msec)
+ : RequestInfo(request, MobileRequest, start_time, timeout_msec) {
+ correlation_id_ = request_.get()->correlation_id();
+ app_id_ = request_.get()->connection_key();
}
RequestInfo::RequestInfo(RequestPtr request,
const RequestInfo::RequestType requst_type,
const TimevalStruct& start_time,
- const uint64_t timeout_sec):
- request_(request),
- start_time_(start_time),
- timeout_sec_(timeout_sec) {
+ const uint64_t timeout_msec)
+ : request_(request), start_time_(start_time), timeout_msec_(timeout_msec) {
updateEndTime();
requst_type_ = requst_type;
correlation_id_ = request_->correlation_id();
@@ -93,23 +86,18 @@ RequestInfo::RequestInfo(RequestPtr request,
void application_manager::request_controller::RequestInfo::updateEndTime() {
end_time_ = date_time::DateTime::getCurrentTime();
- end_time_.tv_sec += timeout_sec_;
-
- // possible delay during IPC
- const uint32_t hmi_delay_sec = 1;
- end_time_.tv_sec += hmi_delay_sec;
+ date_time::DateTime::AddMilliseconds(end_time_, timeout_msec_);
}
-void RequestInfo::updateTimeOut(const uint64_t& timeout_sec) {
- timeout_sec_ = timeout_sec;
+void RequestInfo::updateTimeOut(const uint64_t& timeout_msec) {
+ timeout_msec_ = timeout_msec;
updateEndTime();
}
bool RequestInfo::isExpired() {
TimevalStruct curr_time = date_time::DateTime::getCurrentTime();
- return end_time_.tv_sec <= curr_time.tv_sec;
- // TODO(AKutsan) APPLINK-9711 Need to use compareTime method when timer will support millisecconds
- // return date_time::GREATER == date_time::DateTime::compareTime(end_time_, curr_time);
+ return date_time::DateTime::getmSecs(end_time_) <=
+ date_time::DateTime::getmSecs(curr_time);
}
uint64_t RequestInfo::hash() {
@@ -120,7 +108,7 @@ uint64_t RequestInfo::GenerateHash(uint32_t var1, uint32_t var2) {
uint64_t hash_result = 0;
hash_result = var1;
hash_result = hash_result << 32;
- hash_result = hash_result | var2;
+ hash_result = hash_result | var2;
return hash_result;
}
@@ -131,8 +119,10 @@ FakeRequestInfo::FakeRequestInfo(uint32_t app_id, uint32_t correaltion_id) {
bool RequestInfoSet::Add(RequestInfoPtr request_info) {
DCHECK_OR_RETURN(request_info, false);
- LOG4CXX_DEBUG(logger_, "Add request app_id = " << request_info->app_id()
- << "; corr_id = " << request_info->requestId());
+ LOG4CXX_DEBUG(
+ logger_,
+ "Add request app_id = " << request_info->app_id()
+ << "; corr_id = " << request_info->requestId());
sync_primitives::AutoLock lock(this_lock_);
CheckSetSizes();
const std::pair<HashSortedRequestInfoSet::iterator, bool>& insert_resilt =
@@ -147,8 +137,10 @@ bool RequestInfoSet::Add(RequestInfoPtr request_info) {
CheckSetSizes();
return true;
} else {
- LOG4CXX_ERROR(logger_, "Request with app_id = " << request_info->app_id()
- << "; corr_id " << request_info->requestId() << " Already exist ");
+ LOG4CXX_ERROR(logger_,
+ "Request with app_id = "
+ << request_info->app_id() << "; corr_id "
+ << request_info->requestId() << " Already exist ");
}
CheckSetSizes();
return false;
@@ -166,7 +158,7 @@ RequestInfoPtr RequestInfoSet::Find(const uint32_t connection_key,
HashSortedRequestInfoSet::iterator it =
hash_sorted_pending_requests_.find(request_info_for_search);
if (it != hash_sorted_pending_requests_.end()) {
- result = *it;
+ result = *it;
}
return result;
}
@@ -189,7 +181,7 @@ RequestInfoPtr RequestInfoSet::FrontWithNotNullTimeout() {
TimeSortedRequestInfoSet::iterator it = time_sorted_pending_requests_.begin();
while (it != time_sorted_pending_requests_.end()) {
RequestInfoPtr tmp = *it;
- if (0 == tmp ->timeout_sec()) {
+ if (0 == tmp->timeout_msec()) {
++it;
} else {
result = tmp;
@@ -207,8 +199,7 @@ bool RequestInfoSet::Erase(const RequestInfoPtr request_info) {
}
CheckSetSizes();
- size_t erased_count =
- hash_sorted_pending_requests_.erase(request_info);
+ size_t erased_count = hash_sorted_pending_requests_.erase(request_info);
DCHECK((erased_count <= 1));
if (1 == erased_count) {
TimeSortedRequestInfoSet::iterator it =
@@ -233,17 +224,17 @@ bool RequestInfoSet::RemoveRequest(const RequestInfoPtr request_info) {
return Erase(request_info);
}
-
-uint32_t RequestInfoSet::RemoveRequests(const RequestInfoSet::AppIdCompararator& filter) {
+uint32_t RequestInfoSet::RemoveRequests(
+ const RequestInfoSet::AppIdCompararator& filter) {
LOG4CXX_AUTO_TRACE(logger_);
uint32_t erased = 0;
sync_primitives::AutoLock lock(this_lock_);
- HashSortedRequestInfoSet::iterator it = std::find_if(
- hash_sorted_pending_requests_.begin(),
- hash_sorted_pending_requests_.end(),
- filter);
- while (it != hash_sorted_pending_requests_.end()) {
+ HashSortedRequestInfoSet::iterator it =
+ std::find_if(hash_sorted_pending_requests_.begin(),
+ hash_sorted_pending_requests_.end(),
+ filter);
+ while (it != hash_sorted_pending_requests_.end()) {
HashSortedRequestInfoSet::iterator to_erase = it++;
Erase(*to_erase);
it = std::find_if(it, hash_sorted_pending_requests_.end(), filter);
@@ -253,15 +244,16 @@ uint32_t RequestInfoSet::RemoveRequests(const RequestInfoSet::AppIdCompararator&
return erased;
}
-
uint32_t RequestInfoSet::RemoveByConnectionKey(uint32_t connection_key) {
LOG4CXX_AUTO_TRACE(logger_);
- return RemoveRequests(AppIdCompararator(AppIdCompararator::Equal, connection_key));
+ return RemoveRequests(
+ AppIdCompararator(AppIdCompararator::Equal, connection_key));
}
uint32_t RequestInfoSet::RemoveMobileRequests() {
LOG4CXX_AUTO_TRACE(logger_);
- return RemoveRequests(AppIdCompararator(AppIdCompararator::NotEqual, RequestInfo::HmiConnectoinKey));
+ return RemoveRequests(AppIdCompararator(AppIdCompararator::NotEqual,
+ RequestInfo::HmiConnectoinKey));
}
const size_t RequestInfoSet::Size() {
@@ -281,8 +273,7 @@ bool RequestInfoSet::CheckTimeScaleMaxRequest(
uint32_t app_time_scale,
uint32_t max_request_per_time_scale) {
LOG4CXX_AUTO_TRACE(logger_);
- if (max_request_per_time_scale > 0
- && app_time_scale > 0) {
+ if (max_request_per_time_scale > 0 && app_time_scale > 0) {
TimevalStruct end = date_time::DateTime::getCurrentTime();
TimevalStruct start = {0, 0};
start.tv_sec = end.tv_sec - app_time_scale;
@@ -290,10 +281,13 @@ bool RequestInfoSet::CheckTimeScaleMaxRequest(
sync_primitives::AutoLock lock(this_lock_);
TimeScale scale(start, end, app_id);
const uint32_t count = std::count_if(time_sorted_pending_requests_.begin(),
- time_sorted_pending_requests_.end(), scale);
+ time_sorted_pending_requests_.end(),
+ scale);
if (count >= max_request_per_time_scale) {
- LOG4CXX_WARN(logger_, "Processing requests count " << count <<
- " exceed application limit " << max_request_per_time_scale);
+ LOG4CXX_WARN(logger_,
+ "Processing requests count " << count
+ << " exceed application limit "
+ << max_request_per_time_scale);
return false;
}
LOG4CXX_DEBUG(logger_, "Requests count " << count);
@@ -303,13 +297,13 @@ bool RequestInfoSet::CheckTimeScaleMaxRequest(
return true;
}
-bool RequestInfoSet::CheckHMILevelTimeScaleMaxRequest(mobile_apis::HMILevel::eType hmi_level,
+bool RequestInfoSet::CheckHMILevelTimeScaleMaxRequest(
+ mobile_apis::HMILevel::eType hmi_level,
uint32_t app_id,
uint32_t app_time_scale,
uint32_t max_request_per_time_scale) {
LOG4CXX_AUTO_TRACE(logger_);
- if (max_request_per_time_scale > 0 &&
- app_time_scale > 0) {
+ if (max_request_per_time_scale > 0 && app_time_scale > 0) {
TimevalStruct end = date_time::DateTime::getCurrentTime();
TimevalStruct start = {0, 0};
start.tv_sec = end.tv_sec - app_time_scale;
@@ -317,11 +311,14 @@ bool RequestInfoSet::CheckHMILevelTimeScaleMaxRequest(mobile_apis::HMILevel::eTy
sync_primitives::AutoLock lock(this_lock_);
HMILevelTimeScale scale(start, end, app_id, hmi_level);
const uint32_t count = std::count_if(time_sorted_pending_requests_.begin(),
- time_sorted_pending_requests_.end(), scale);
+ time_sorted_pending_requests_.end(),
+ scale);
if (count >= max_request_per_time_scale) {
- LOG4CXX_WARN(logger_, "Processing requests count " << count
- << " exceed application limit " << max_request_per_time_scale
- << " in hmi level " << hmi_level);
+ LOG4CXX_WARN(logger_,
+ "Processing requests count "
+ << count << " exceed application limit "
+ << max_request_per_time_scale << " in hmi level "
+ << hmi_level);
return false;
}
LOG4CXX_DEBUG(logger_, "Requests count " << count);
@@ -331,7 +328,8 @@ bool RequestInfoSet::CheckHMILevelTimeScaleMaxRequest(mobile_apis::HMILevel::eTy
return true;
}
-bool RequestInfoSet::AppIdCompararator::operator()(const RequestInfoPtr value_compare) const {
+bool RequestInfoSet::AppIdCompararator::operator()(
+ const RequestInfoPtr value_compare) const {
switch (compare_type_) {
case Equal:
return value_compare->app_id() == app_id_;
diff --git a/src/components/application_manager/src/resume_ctrl.cpp b/src/components/application_manager/src/resume_ctrl.cpp
deleted file mode 100644
index 983699e020..0000000000
--- a/src/components/application_manager/src/resume_ctrl.cpp
+++ /dev/null
@@ -1,1311 +0,0 @@
-/*
- Copyright (c) 2015, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-#include "application_manager/resume_ctrl.h"
-
-#include <fstream>
-#include <algorithm>
-
-#include "config_profile/profile.h"
-#include "utils/file_system.h"
-#include "connection_handler/connection_handler_impl.h"
-#include "application_manager/application_manager_impl.h"
-#include "application_manager/application.h"
-#include "application_manager/message_helper.h"
-#include "smart_objects/smart_object.h"
-#include "connection_handler/connection.h"
-#include "formatters/CFormatterJsonBase.hpp"
-#include "application_manager/commands/command_impl.h"
-#include "resumption/last_state.h"
-#include "policy/policy_manager_impl.h"
-#include "application_manager/policies/policy_handler.h"
-#include "application_manager/state_controller.h"
-
-namespace application_manager {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "ResumeCtrl")
-
-namespace Formatters = NsSmartDeviceLink::NsJSONHandler::Formatters;
-
-ResumeCtrl::ResumeCtrl(ApplicationManagerImpl* app_mngr)
- : resumtion_lock_(true),
- app_mngr_(app_mngr),
- save_persistent_data_timer_("RsmCtrlPercist",
- this, &ResumeCtrl::SaveDataOnTimer, true),
- restore_hmi_level_timer_("RsmCtrlRstore",
- this, &ResumeCtrl::ApplicationResumptiOnTimer),
- is_resumption_active_(false),
- is_data_saved(true),
- launch_time_(time(NULL)) {
- LoadResumeData();
- save_persistent_data_timer_.start(profile::Profile::instance()->app_resumption_save_persistent_data_timeout());
-}
-
-void ResumeCtrl::SaveAllApplications() {
- LOG4CXX_AUTO_TRACE(logger_);
- std::set<ApplicationSharedPtr> apps(retrieve_application());
- std::for_each(apps.begin(),
- apps.end(),
- std::bind1st(std::mem_fun(&ResumeCtrl::SaveApplication), this));
- // remove old
-}
-
-void ResumeCtrl::SaveApplication(ApplicationConstSharedPtr application) {
- DCHECK(application.get());
-
- if (!application) {
- LOG4CXX_FATAL(logger_, "Application object is NULL.");
- return;
- }
-
- const std::string& m_app_id = application->mobile_app_id();
- LOG4CXX_TRACE(logger_, "ENTER app_id : " << application->app_id()
- << " mobile app_id : " << m_app_id);
-
- const std::string hash = application->curHash(); // let's make a copy not to depend on application
- const uint32_t grammar_id = application->get_grammar_id();
- const uint32_t time_stamp = (uint32_t)time(NULL);
-
- const mobile_apis::HMILevel::eType hmi_level = application->hmi_level();
-
- resumtion_lock_.Acquire();
- Json::Value& json_app = GetFromSavedOrAppend(m_app_id);
-
- json_app[strings::device_mac] =
- MessageHelper::GetDeviceMacAddressForHandle(application->device());
- json_app[strings::app_id] = m_app_id;
- json_app[strings::grammar_id] = grammar_id;
- json_app[strings::connection_key] = application->app_id();
- json_app[strings::hmi_app_id] = application->hmi_app_id();
- json_app[strings::is_media_application] = application->IsAudioApplication();
- json_app[strings::hmi_level] = static_cast<int32_t> (hmi_level);
- json_app[strings::ign_off_count] = 0;
- json_app[strings::suspend_count] = 0;
- json_app[strings::hash_id] = hash;
- json_app[strings::application_commands] =
- GetApplicationCommands(application);
- json_app[strings::application_submenus] =
- GetApplicationSubMenus(application);
- json_app[strings::application_choise_sets] =
- GetApplicationInteractionChoiseSets(application);
- json_app[strings::application_global_properties] =
- GetApplicationGlobalProperties(application);
- json_app[strings::application_subscribtions] =
- GetApplicationSubscriptions(application);
- json_app[strings::application_files] = GetApplicationFiles(application);
- json_app[strings::time_stamp] = time_stamp;
- LOG4CXX_DEBUG(logger_, "SaveApplication : " << json_app.toStyledString());
-
- resumtion_lock_.Release();
-}
-
-void ResumeCtrl::on_event(const event_engine::Event& event) {
- LOG4CXX_TRACE(logger_, "Response from HMI command");
-}
-
-bool ResumeCtrl::RestoreAppHMIState(ApplicationSharedPtr application) {
- LOG4CXX_AUTO_TRACE(logger_);
- using namespace mobile_apis;
- if (!application) {
- LOG4CXX_ERROR(logger_, " RestoreApplicationHMILevel() application pointer in invalid");
- return false;
- }
- LOG4CXX_DEBUG(logger_, "ENTER app_id : " << application->app_id());
-
- sync_primitives::AutoLock lock(resumtion_lock_);
- const int idx = GetObjectIndex(application->mobile_app_id());
- if (-1 != idx) {
- const Json::Value& json_app = GetSavedApplications()[idx];
- if (json_app.isMember(strings::hmi_level)) {
-
- const HMILevel::eType saved_hmi_level =
- static_cast<mobile_apis::HMILevel::eType>(
- json_app[strings::hmi_level].asInt());
- LOG4CXX_DEBUG(logger_, "Saved HMI Level is : " << saved_hmi_level);
- return SetAppHMIState(application, saved_hmi_level);
- } else {
- LOG4CXX_FATAL(logger_, "There are some unknown keys among the stored apps");
- }
- }
- LOG4CXX_INFO(logger_, "Failed to restore application HMILevel");
- return false;
-}
-
-bool ResumeCtrl::SetupDefaultHMILevel(ApplicationSharedPtr application) {
- DCHECK_OR_RETURN(application, false);
- LOG4CXX_AUTO_TRACE(logger_);
- mobile_apis::HMILevel::eType default_hmi =
- ApplicationManagerImpl::instance()-> GetDefaultHmiLevel(application);
- bool result = SetAppHMIState(application, default_hmi, false);
- return result;
-}
-
-bool ResumeCtrl::SetAppHMIState(ApplicationSharedPtr application,
- const mobile_apis::HMILevel::eType hmi_level,
- bool check_policy) {
- using namespace mobile_apis;
- LOG4CXX_AUTO_TRACE(logger_);
- if (false == application.valid()) {
- LOG4CXX_ERROR(logger_, "Application pointer in invalid");
- return false;
- }
- LOG4CXX_TRACE(logger_, " app_id : ( " << application->app_id()
- << ", hmi_level : " << hmi_level
- << ", check_policy : " << check_policy << " )");
- const std::string device_id =
- MessageHelper::GetDeviceMacAddressForHandle(application->device());
-
- if (check_policy &&
- policy::PolicyHandler::instance()->GetUserConsentForDevice(device_id)
- != policy::DeviceConsent::kDeviceAllowed) {
- LOG4CXX_ERROR(logger_, "Resumption abort. Data consent wasn't allowed");
- SetupDefaultHMILevel(application);
- return false;
- }
- HMILevel::eType restored_hmi_level = hmi_level;
-
- if ((hmi_level == application->hmi_level()) &&
- (hmi_level != mobile_apis::HMILevel::HMI_NONE)) {
- LOG4CXX_DEBUG(logger_, "Hmi level " << hmi_level << " should not be set to "
- << application->mobile_app_id()
- <<" current hmi_level is " << application->hmi_level());
- return false;
- }
-
- if (HMILevel::HMI_FULL == hmi_level) {
- restored_hmi_level = app_mngr_->IsHmiLevelFullAllowed(application);
- } else if (HMILevel::HMI_LIMITED == hmi_level) {
- bool allowed_limited = application->is_media_application();
- ApplicationManagerImpl::ApplicationListAccessor accessor;
- ApplicationManagerImpl::ApplictionSetConstIt it = accessor.begin();
- for (; accessor.end() != it && allowed_limited; ++it) {
- const ApplicationSharedPtr curr_app = *it;
- if (curr_app->is_media_application()) {
- if (curr_app->hmi_level() == HMILevel::HMI_FULL ||
- curr_app->hmi_level() == HMILevel::HMI_LIMITED) {
- allowed_limited = false;
- }
- }
- }
- if (allowed_limited) {
- restored_hmi_level = HMILevel::HMI_LIMITED;
- } else {
- restored_hmi_level =
- ApplicationManagerImpl::instance()->GetDefaultHmiLevel(application);
- }
- }
- if (HMILevel::HMI_LIMITED == restored_hmi_level) {
- MessageHelper::SendOnResumeAudioSourceToHMI(application->app_id());
- }
-
- const AudioStreamingState::eType restored_audio_state =
- application->is_media_application() &&
- (HMILevel::HMI_FULL == restored_hmi_level ||
- HMILevel::HMI_LIMITED == restored_hmi_level)
- ? AudioStreamingState::AUDIBLE : AudioStreamingState::NOT_AUDIBLE;
-
- if (restored_hmi_level == HMILevel::HMI_FULL) {
- ApplicationManagerImpl::instance()->SetState<true>(application->app_id(),
- restored_hmi_level,
- restored_audio_state);
- } else {
- ApplicationManagerImpl::instance()->SetState<false>(application->app_id(),
- restored_hmi_level,
- restored_audio_state);
- }
- LOG4CXX_INFO(logger_, "Set up application "
- << application->mobile_app_id()
- << " to HMILevel " << hmi_level);
- return true;
-}
-
-bool ResumeCtrl::RestoreApplicationData(ApplicationSharedPtr application) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (!application.valid()) {
- LOG4CXX_ERROR(logger_, "Application pointer in invalid");
- return false;
- }
-
- LOG4CXX_DEBUG(logger_, "ENTER app_id : " << application->app_id());
-
- sync_primitives::AutoLock lock(resumtion_lock_);
- const int idx = GetObjectIndex(application->mobile_app_id());
- if (-1 == idx) {
- LOG4CXX_WARN(logger_, "Application not saved");
- return false;
- }
-
- const Json::Value& saved_app = GetSavedApplications()[idx];
- if(saved_app.isMember(strings::grammar_id)) {
- const uint32_t app_grammar_id = saved_app[strings::grammar_id].asUInt();
- application->set_grammar_id(app_grammar_id);
-
- AddFiles(application, saved_app);
- AddSubmenues(application, saved_app);
- AddCommands(application, saved_app);
- AddChoicesets(application, saved_app);
- SetGlobalProperties(application, saved_app);
- AddSubscriptions(application, saved_app);
- }
- return true;
-}
-
-bool ResumeCtrl::IsHMIApplicationIdExist(uint32_t hmi_app_id) {
- LOG4CXX_TRACE(logger_, "ENTER hmi_app_id :" << hmi_app_id);
- sync_primitives::AutoLock lock(resumtion_lock_);
- for (Json::Value::iterator it = GetSavedApplications().begin();
- it != GetSavedApplications().end(); ++it) {
- if ((*it).isMember(strings::hmi_app_id)) {
- if ((*it)[strings::hmi_app_id].asUInt() == hmi_app_id) {
- return true;
- }
- }
- }
- ApplicationManagerImpl::ApplicationListAccessor accessor;
- ApplicationManagerImpl::ApplictionSet apps(accessor.applications());
- ApplicationManagerImpl::ApplictionSetIt it = apps.begin();
- ApplicationManagerImpl::ApplictionSetIt it_end = apps.end();
-
- for (;it != it_end; ++it) {
- if (hmi_app_id == (*it)->hmi_app_id()) {
- LOG4CXX_TRACE(logger_, "EXIT result = true");
- return true;
- }
- }
- LOG4CXX_TRACE(logger_, "EXIT result = false");
- return false;
-}
-
-bool ResumeCtrl::IsApplicationSaved(const std::string& mobile_app_id) {
- LOG4CXX_TRACE(logger_, "ENTER mobile_app_id :" << mobile_app_id);
-
- sync_primitives::AutoLock lock(resumtion_lock_);
- int index = GetObjectIndex(mobile_app_id);
- if (-1 == index) {
- return false;
- }
-
- if (!IsResumptionDataValid(index)) {
- LOG4CXX_INFO(logger_, "Resumption data for app " << mobile_app_id <<
- " is corrupted. Remove application from resumption list");
- RemoveApplicationFromSaved(mobile_app_id);
- return false;
- }
-
- return true;
-}
-
-uint32_t ResumeCtrl::GetHMIApplicationID(const std::string& mobile_app_id) {
- LOG4CXX_AUTO_TRACE(logger_);
- uint32_t hmi_app_id = 0;
-
- sync_primitives::AutoLock lock(resumtion_lock_);
- const int idx = GetObjectIndex(mobile_app_id);
- if (-1 == idx) {
- LOG4CXX_WARN(logger_, "Application not saved");
- return hmi_app_id;
- }
-
- const Json::Value& json_app = GetSavedApplications()[idx];
- if (json_app.isMember(strings::app_id)) {
- hmi_app_id = json_app[strings::hmi_app_id].asUInt();
- }
- LOG4CXX_DEBUG(logger_, "hmi_app_id :" << hmi_app_id);
- return hmi_app_id;
-}
-
-bool ResumeCtrl::RemoveApplicationFromSaved(const std::string& mobile_app_id) {
- LOG4CXX_TRACE(logger_, "Remove mobile_app_id " << mobile_app_id);
- sync_primitives::AutoLock lock(resumtion_lock_);
- bool result = false;
- std::vector<Json::Value> temp;
- for (Json::Value::iterator it = GetSavedApplications().begin();
- it != GetSavedApplications().end(); ++it) {
- if ((*it).isMember(strings::app_id)) {
- const std::string& saved_m_app_id = (*it)[strings::app_id].asString();
-
- if (saved_m_app_id != mobile_app_id) {
- temp.push_back((*it));
- } else {
- result = true;
- }
- }
- }
-
- if (false == result) {
- LOG4CXX_TRACE(logger_, "EXIT result: " << (result ? "true" : "false"));
- return result;
- }
-
- GetSavedApplications().clear();
- for (std::vector<Json::Value>::iterator it = temp.begin();
- it != temp.end(); ++it) {
- GetSavedApplications().append((*it));
- }
- LOG4CXX_TRACE(logger_, "EXIT result: " << (result ? "true" : "false"));
- return result;
-}
-
-void ResumeCtrl::Suspend() {
- LOG4CXX_AUTO_TRACE(logger_);
- StopRestoreHmiLevelTimer();
- StopSavePersistentDataTimer();
- SaveAllApplications();
- Json::Value to_save;
- sync_primitives::AutoLock lock(resumtion_lock_);
- for (Json::Value::iterator it = GetSavedApplications().begin();
- it != GetSavedApplications().end(); ++it) {
- if ((*it).isMember(strings::suspend_count)) {
- const uint32_t suspend_count = (*it)[strings::suspend_count].asUInt();
- (*it)[strings::suspend_count] = suspend_count + 1;
- } else {
- LOG4CXX_WARN(logger_, "Unknown key among saved applications");
- (*it)[strings::suspend_count] = 1;
- }
- if ((*it).isMember(strings::ign_off_count)) {
- const uint32_t ign_off_count = (*it)[strings::ign_off_count].asUInt();
- if (ign_off_count < kApplicationLifes) {
- (*it)[strings::ign_off_count] = ign_off_count + 1;
- to_save.append(*it);
- }
- } else {
- LOG4CXX_WARN(logger_, "Unknown key among saved applications");
- (*it)[strings::ign_off_count] = 1;
- }
- }
- SetSavedApplication(to_save);
- SetLastIgnOffTime(time(NULL));
- LOG4CXX_DEBUG(logger_,
- GetResumptionData().toStyledString());
- resumption::LastState::instance()->SaveToFileSystem();
-}
-
-void ResumeCtrl::OnAwake() {
- LOG4CXX_AUTO_TRACE(logger_);
-
- sync_primitives::AutoLock lock(resumtion_lock_);
- for (Json::Value::iterator it = GetSavedApplications().begin();
- it != GetSavedApplications().end(); ++it) {
- if ((*it).isMember(strings::ign_off_count)) {
- const uint32_t ign_off_count = (*it)[strings::ign_off_count].asUInt();
- (*it)[strings::ign_off_count] = ign_off_count - 1;
- } else {
- LOG4CXX_WARN(logger_, "Unknown key among saved applications");
- (*it)[strings::ign_off_count] = 0;
- }
- }
- ResetLaunchTime();
- StartSavePersistentDataTimer();
-}
-
-
-
-void ResumeCtrl::StartSavePersistentDataTimer() {
- LOG4CXX_AUTO_TRACE(logger_);
- if (!save_persistent_data_timer_.isRunning()) {
- save_persistent_data_timer_.start(
- profile::Profile::instance()->app_resumption_save_persistent_data_timeout());
- }
-}
-
-void ResumeCtrl::StopSavePersistentDataTimer() {
- LOG4CXX_AUTO_TRACE(logger_);
- if (save_persistent_data_timer_.isRunning()) {
- save_persistent_data_timer_.stop();
- }
-}
-
-
-void ResumeCtrl::StopRestoreHmiLevelTimer() {
- LOG4CXX_AUTO_TRACE(logger_);
- if (restore_hmi_level_timer_.isRunning()) {
- restore_hmi_level_timer_.stop();
- }
-}
-
-
-bool ResumeCtrl::StartResumption(ApplicationSharedPtr application,
- const std::string& hash) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (!application) {
- LOG4CXX_WARN(logger_, "Application not exist");
- return false;
- }
-
- LOG4CXX_DEBUG(logger_, " Resume app_id = " << application->app_id()
- << " hmi_app_id = " << application->hmi_app_id()
- << " mobile_id = " << application->mobile_app_id()
- << "received hash = " << hash);
-
- sync_primitives::AutoLock lock(resumtion_lock_);
- const int idx = GetObjectIndex(application->mobile_app_id());
- if (-1 == idx) {
- LOG4CXX_WARN(logger_, "Application not saved");
- return false;
- }
-
- const Json::Value& json_app = GetSavedApplications()[idx];
- LOG4CXX_DEBUG(logger_, "Saved_application_data: " << json_app.toStyledString());
- if (json_app.isMember(strings::hash_id) && json_app.isMember(strings::time_stamp)) {
- const std::string& saved_hash = json_app[strings::hash_id].asString();
-
- if (saved_hash == hash) {
- RestoreApplicationData(application);
- }
- application->UpdateHash();
-
- queue_lock_.Acquire();
- waiting_for_timer_.push_back(application->app_id());
- queue_lock_.Release();
- if (!is_resumption_active_) {
- is_resumption_active_ = true;
- restore_hmi_level_timer_.start(
- profile::Profile::instance()->app_resuming_timeout());
- }
- } else {
- LOG4CXX_INFO(logger_, "There are some unknown keys in the dictionary.");
- return false;
- }
-
- return true;
-}
-
-void ResumeCtrl::StartAppHmiStateResumption(ApplicationSharedPtr application) {
- LOG4CXX_AUTO_TRACE(logger_);
- using namespace profile;
- using namespace date_time;
- DCHECK_OR_RETURN_VOID(application);
- const int idx = GetObjectIndex(application->mobile_app_id());
- DCHECK_OR_RETURN_VOID(idx != -1);
- const Json::Value& json_app = GetSavedApplications()[idx];
-
- if (!json_app.isMember(strings::ign_off_count)) {
- LOG4CXX_INFO(logger_, "Do not need to resume application "
- << application->app_id());
- SetupDefaultHMILevel(application);
- return;
- }
-
- // check if if is resumption during one IGN cycle
- const uint32_t ign_off_count = json_app[strings::ign_off_count].asUInt();
-
- if (0 == ign_off_count) {
- if (CheckAppRestrictions(application, json_app)) {
- LOG4CXX_INFO(logger_, "Resume application after short IGN cycle");
- RestoreAppHMIState(application);
- RemoveApplicationFromSaved(application->mobile_app_id());
- } else {
- LOG4CXX_INFO(logger_, "Do not need to resume application "
- << application->app_id());
- }
- } else {
- if (CheckIgnCycleRestrictions(json_app) &&
- CheckAppRestrictions(application, json_app)) {
- LOG4CXX_INFO(logger_, "Resume application after IGN cycle");
- RestoreAppHMIState(application);
- RemoveApplicationFromSaved(application->mobile_app_id());
- } else {
- LOG4CXX_INFO(logger_, "Do not need to resume application "
- << application->app_id());
- }
- }
-}
-
-std::set<ApplicationSharedPtr> ResumeCtrl::retrieve_application() {
- ApplicationManagerImpl::ApplicationListAccessor accessor;
- return std::set<ApplicationSharedPtr>(accessor.begin(), accessor.end());
-}
-
-bool ResumeCtrl::StartResumptionOnlyHMILevel(ApplicationSharedPtr application) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (!application.valid()) {
- LOG4CXX_WARN(logger_, "Application do not exists");
- return false;
- }
-
- LOG4CXX_DEBUG(logger_, "ENTER app_id = " << application->app_id()
- << "mobile_id = "
- << application->mobile_app_id());
-
- sync_primitives::AutoLock lock(resumtion_lock_);
- const int idx = GetObjectIndex(application->mobile_app_id());
- if (-1 == idx) {
- LOG4CXX_WARN(logger_, "Application not saved");
- return false;
- }
-
- queue_lock_.Acquire();
- waiting_for_timer_.push_back(application->app_id());
- queue_lock_.Release();
- if (!is_resumption_active_) {
- is_resumption_active_ = true;
- restore_hmi_level_timer_.start(
- profile::Profile::instance()->app_resuming_timeout());
- }
-
- return true;
-}
-
-bool ResumeCtrl::CheckPersistenceFilesForResumption(ApplicationSharedPtr application) {
- LOG4CXX_AUTO_TRACE(logger_);
-
- if (!application.valid()) {
- LOG4CXX_WARN(logger_, "Application do not exists");
- return false;
- }
- LOG4CXX_DEBUG(logger_, "Process app_id = " << application->app_id());
-
- sync_primitives::AutoLock lock(resumtion_lock_);
- const int idx = GetObjectIndex(application->mobile_app_id());
- if (-1 == idx) {
- LOG4CXX_WARN(logger_, "Application not saved");
- return false;
- }
-
- const Json::Value& saved_app = GetSavedApplications()[idx];
-
- if (!saved_app.isMember(strings::application_commands) ||
- !saved_app.isMember(strings::application_choise_sets)) {
- LOG4CXX_WARN(logger_, "application_commands or "
- "application_choise_sets are not exists");
- return false;
- }
-
- if (!CheckIcons(application, saved_app[strings::application_commands])) {
- return false;
- }
- if (!CheckIcons(application, saved_app[strings::application_choise_sets])) {
- return false;
- }
- LOG4CXX_DEBUG(logger_, " result = true");
- return true;
-}
-
-bool ResumeCtrl::CheckApplicationHash(ApplicationSharedPtr application,
- const std::string& hash) {
- if (!application) {
- LOG4CXX_ERROR(logger_, "Application pointer is invalid");
- return false;
- }
-
- LOG4CXX_DEBUG(logger_, "ENTER app_id : " << application->app_id()
- << " hash : " << hash);
-
- sync_primitives::AutoLock lock(resumtion_lock_);
- const int idx = GetObjectIndex(application->mobile_app_id());
- if (-1 == idx) {
- LOG4CXX_WARN(logger_, "Application not saved");
- return false;
- }
-
- const Json::Value& json_app = GetSavedApplications()[idx];
-
- if (json_app.isMember(strings::hash_id)) {
- const std::string& saved_hash = json_app[strings::hash_id].asString();
-
- LOG4CXX_TRACE(logger_, "Found saved application : " << json_app.toStyledString());
- LOG4CXX_INFO(logger_, "received hash = " << hash);
- LOG4CXX_INFO(logger_, "saved hash = " << saved_hash);
- if (hash == saved_hash) {
- return true;
- }
- }
-
- return false;
-}
-
-void ResumeCtrl::SaveDataOnTimer() {
- LOG4CXX_AUTO_TRACE(logger_);
- if (is_resumption_active_) {
- LOG4CXX_WARN(logger_, "Resumption timer is active skip saving");
- return;
- }
-
- if (false == is_data_saved) {
- SaveAllApplications();
- is_data_saved = true;
- resumption::LastState::instance()->SaveToFileSystem();
- }
-}
-
-bool ResumeCtrl::IsDeviceMacAddressEqual(ApplicationSharedPtr application,
- const std::string& saved_device_mac) {
- const std::string device_mac =
- MessageHelper::GetDeviceMacAddressForHandle(application->device());
- return device_mac == saved_device_mac;
-}
-
-Json::Value&ResumeCtrl::GetResumptionData() {
- LOG4CXX_AUTO_TRACE(logger_);
- Json::Value& last_state = resumption::LastState::instance()->dictionary;
- if (!last_state.isMember(strings::resumption)) {
- last_state[strings::resumption] = Json::Value(Json::objectValue);
- LOG4CXX_WARN(logger_, "resumption section is missed");
- }
- Json::Value& resumption = last_state[strings::resumption];
- if (!resumption.isObject()) {
- LOG4CXX_ERROR(logger_, "resumption type INVALID rewrite");
- resumption = Json::Value(Json::objectValue);
- }
- return resumption;
-}
-
-Json::Value& ResumeCtrl::GetSavedApplications() {
- LOG4CXX_AUTO_TRACE(logger_);
- Json::Value& resumption = GetResumptionData();
- if (!resumption.isMember(strings::resume_app_list)) {
- resumption[strings::resume_app_list] = Json::Value(Json::arrayValue);
- LOG4CXX_WARN(logger_, "app_list section is missed");
- }
- Json::Value& resume_app_list = resumption[strings::resume_app_list];
- if (!resume_app_list.isArray()) {
- LOG4CXX_ERROR(logger_, "resume_app_list type INVALID rewrite");
- resume_app_list = Json::Value(Json::arrayValue);
- }
- return resume_app_list;
-}
-
-time_t ResumeCtrl::GetIgnOffTime() {
- LOG4CXX_AUTO_TRACE(logger_);
- Json::Value& resumption = GetResumptionData();
- if (!resumption.isMember(strings::last_ign_off_time)) {
- resumption[strings::last_ign_off_time] = 0;
- LOG4CXX_WARN(logger_, "last_save_time section is missed");
- }
- time_t last_ign_off = static_cast<time_t>(
- resumption[strings::last_ign_off_time].asUInt());
- return last_ign_off;
-}
-
-void ResumeCtrl::SetLastIgnOffTime(time_t ign_off_time) {
- LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_WARN(logger_, "ign_off_time = " << ign_off_time);
- Json::Value& resumption = GetResumptionData();
- resumption[strings::last_ign_off_time] = static_cast<uint32_t>(ign_off_time);
-}
-
-
-void ResumeCtrl::SetSavedApplication(Json::Value& apps_json) {
- Json::Value& app_list = GetSavedApplications();
- app_list = apps_json;
-}
-
-void ResumeCtrl::ClearResumptionInfo() {
- LOG4CXX_AUTO_TRACE(logger_);
- Json::Value empty_json;
-
- SetSavedApplication(empty_json);
- resumption::LastState::instance()->SaveToFileSystem();
-}
-
-Json::Value ResumeCtrl::GetApplicationCommands(
- ApplicationConstSharedPtr application) {
- LOG4CXX_AUTO_TRACE(logger_);
- Json::Value result;
- DCHECK(application.get());
- if (!application) {
- LOG4CXX_ERROR(logger_, "NULL Pointer App");
- return result;
- }
- const DataAccessor<CommandsMap> accessor = application->commands_map();
- const CommandsMap& commands = accessor.GetData();
- CommandsMap::const_iterator it = commands.begin();
- for (;it != commands.end(); ++it) {
- smart_objects::SmartObject* so = it->second;
- Json::Value curr;
- Formatters::CFormatterJsonBase::objToJsonValue(*so, curr);
- result.append(curr);
- }
- return result;
-}
-
-Json::Value ResumeCtrl::GetApplicationSubMenus(
- ApplicationConstSharedPtr application) {
- LOG4CXX_AUTO_TRACE(logger_);
- Json::Value result;
- DCHECK(application.get());
- if (!application) {
- LOG4CXX_ERROR(logger_, "NULL Pointer App");
- return result;
- }
- const DataAccessor<SubMenuMap> accessor = application->sub_menu_map();
- const SubMenuMap& sub_menus = accessor.GetData();
- SubMenuMap::const_iterator it = sub_menus.begin();
- for (;it != sub_menus.end(); ++it) {
- smart_objects::SmartObject* so = it->second;
- Json::Value curr;
- Formatters::CFormatterJsonBase::objToJsonValue(*so, curr);
- result.append(curr);
- }
- return result;
-}
-
-Json::Value ResumeCtrl::GetApplicationInteractionChoiseSets(
- ApplicationConstSharedPtr application) {
- DCHECK(application.get());
- LOG4CXX_TRACE(logger_, "ENTER app_id:"
- << application->app_id());
-
- Json::Value result;
- const DataAccessor<ChoiceSetMap> accessor = application->choice_set_map();
- const ChoiceSetMap& choices = accessor.GetData();
- ChoiceSetMap::const_iterator it = choices.begin();
- for ( ;it != choices.end(); ++it) {
- smart_objects::SmartObject* so = it->second;
- Json::Value curr;
- Formatters::CFormatterJsonBase::objToJsonValue(*so, curr);
- result.append(curr);
- }
- return result;
-}
-
-Json::Value ResumeCtrl::GetApplicationGlobalProperties(
- ApplicationConstSharedPtr application) {
- LOG4CXX_AUTO_TRACE(logger_);
- Json::Value sgp;
- DCHECK(application.get());
- if (!application) {
- LOG4CXX_ERROR(logger_, "NULL Pointer App");
- return sgp;
- }
-
- const smart_objects::SmartObject* help_promt = application->help_prompt();
- const smart_objects::SmartObject* timeout_prompt = application->timeout_prompt();
- const smart_objects::SmartObject* vr_help = application->vr_help();
- const smart_objects::SmartObject* vr_help_title = application->vr_help_title();
- const smart_objects::SmartObject* vr_synonyms = application->vr_synonyms();
- const smart_objects::SmartObject* keyboard_props = application->keyboard_props();
- const smart_objects::SmartObject* menu_title = application->menu_title();
- const smart_objects::SmartObject* menu_icon = application->menu_icon();
-
- sgp[strings::help_prompt] = JsonFromSO(help_promt);
- sgp[strings::timeout_prompt] = JsonFromSO(timeout_prompt);
- sgp[strings::vr_help] = JsonFromSO(vr_help);
- sgp[strings::vr_help_title] = JsonFromSO(vr_help_title);
- sgp[strings::vr_synonyms] = JsonFromSO(vr_synonyms);
- sgp[strings::keyboard_properties] = JsonFromSO(keyboard_props);
- sgp[strings::menu_title] = JsonFromSO(menu_title);
- sgp[strings::menu_icon] = JsonFromSO(menu_icon);
- return sgp;
-}
-
-Json::Value ResumeCtrl::GetApplicationSubscriptions(
- ApplicationConstSharedPtr application) {
- LOG4CXX_AUTO_TRACE(logger_);
- Json::Value result;
- DCHECK(application.get());
- if (!application) {
- LOG4CXX_ERROR(logger_, "NULL Pointer App");
- return result;
- }
- LOG4CXX_DEBUG(logger_, "app_id:" << application->app_id());
- LOG4CXX_DEBUG(logger_, "SubscribedButtons:" << application->SubscribedButtons().size());
- Append(application->SubscribedButtons().begin(),
- application->SubscribedButtons().end(),
- strings::application_buttons, result);
- LOG4CXX_DEBUG(logger_, "SubscribesIVI:" << application->SubscribesIVI().size());
- Append(application->SubscribesIVI().begin(),
- application->SubscribesIVI().end(),
- strings::application_vehicle_info, result);
- return result;
-}
-
-Json::Value ResumeCtrl::GetApplicationFiles(
- ApplicationConstSharedPtr application) {
- DCHECK(application.get());
- LOG4CXX_TRACE(logger_, "ENTER app_id:"
- << application->app_id());
-
- Json::Value result;
- const AppFilesMap& app_files = application->getAppFiles();
- for(AppFilesMap::const_iterator file_it = app_files.begin();
- file_it != app_files.end(); file_it++) {
- const AppFile& file = file_it->second;
- if (file.is_persistent) {
- Json::Value file_data;
- file_data[strings::persistent_file] = file.is_persistent;
- file_data[strings::is_download_complete] = file.is_download_complete;
- file_data[strings::sync_file_name] = file.file_name;
- file_data[strings::file_type] = file.file_type;
- result.append(file_data);
- }
- }
- return result;
-}
-
-Json::Value ResumeCtrl::GetApplicationShow(
- ApplicationConstSharedPtr application) {
- DCHECK(application.get());
- LOG4CXX_TRACE(logger_, "ENTER app_id:"
- << application->app_id());
-
- Json::Value result;
- const smart_objects::SmartObject* show_so = application->show_command();
- if (!show_so) {
- return result;
- }
- result = JsonFromSO(show_so);
- return result;
-}
-
-Json::Value ResumeCtrl::JsonFromSO(const smart_objects::SmartObject *so) {
- Json::Value temp;
- if (so) {
- Formatters::CFormatterJsonBase::objToJsonValue(*so, temp);
- }
- return temp;
-}
-
-bool ResumeCtrl::ProcessHMIRequest(smart_objects::SmartObjectSPtr request,
- bool use_events) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (use_events) {
- const hmi_apis::FunctionID::eType function_id =
- static_cast<hmi_apis::FunctionID::eType>(
- (*request)[strings::function_id].asInt());
-
- const int32_t hmi_correlation_id =
- (*request)[strings::correlation_id].asInt();
- subscribe_on_event(function_id, hmi_correlation_id);
- }
- if (!ApplicationManagerImpl::instance()->ManageHMICommand(request)) {
- LOG4CXX_ERROR(logger_, "Unable to send request");
- return true;
- }
- return false;
-}
-
-void ResumeCtrl::AddFiles(ApplicationSharedPtr application, const Json::Value& saved_app) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (saved_app.isMember(strings::application_files)) {
- const Json::Value& application_files = saved_app[strings::application_files];
- for (Json::Value::iterator json_it = application_files.begin();
- json_it != application_files.end(); ++json_it) {
- const Json::Value& file_data = *json_it;
-
- const bool is_persistent = file_data.isMember(strings::persistent_file) &&
- file_data[strings::persistent_file].asBool();
- if (is_persistent) {
- AppFile file;
- file.is_persistent = is_persistent;
- file.is_download_complete = file_data[strings::is_download_complete].asBool();
- file.file_name = file_data[strings::sync_file_name].asString();
- file.file_type = static_cast<mobile_apis::FileType::eType> (
- file_data[strings::file_type].asInt());
- application->AddFile(file);
- }
- }
- } else {
- LOG4CXX_FATAL(logger_, "application_files section is not exists");
- }
-}
-
-void ResumeCtrl::AddSubmenues(ApplicationSharedPtr application, const Json::Value& saved_app) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (saved_app.isMember(strings::application_submenus)) {
- const Json::Value& app_submenus = saved_app[strings::application_submenus];
- for (Json::Value::iterator json_it = app_submenus.begin();
- json_it != app_submenus.end(); ++json_it) {
- const Json::Value& json_submenu = *json_it;
- smart_objects::SmartObject message(smart_objects::SmartType::SmartType_Map);
- Formatters::CFormatterJsonBase::jsonValueToObj(json_submenu, message);
- application->AddSubMenu(message[strings::menu_id].asUInt(), message);
- }
-
- ProcessHMIRequests(MessageHelper::CreateAddSubMenuRequestToHMI(application));
- } else {
- LOG4CXX_FATAL(logger_, "application_submenus section is not exists");
- }
-}
-
-void ResumeCtrl::AddCommands(ApplicationSharedPtr application, const Json::Value& saved_app) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (saved_app.isMember(strings::application_commands)) {
- const Json::Value& app_commands = saved_app[strings::application_commands];
- for (Json::Value::iterator json_it = app_commands.begin();
- json_it != app_commands.end(); ++json_it) {
- const Json::Value& json_command = *json_it;
- smart_objects::SmartObject message(smart_objects::SmartType::SmartType_Map);
- Formatters::CFormatterJsonBase::jsonValueToObj(json_command, message);
- application->AddCommand(message[strings::cmd_id].asUInt(), message);
- }
-
- ProcessHMIRequests(MessageHelper::CreateAddCommandRequestToHMI(application));
- } else {
- LOG4CXX_FATAL(logger_, "application_commands section is not exists");
- }
-}
-
-void ResumeCtrl::AddChoicesets(ApplicationSharedPtr application, const Json::Value& saved_app) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (saved_app.isMember(strings::application_choise_sets)) {
- const Json::Value& app_choise_sets = saved_app[strings::application_choise_sets];
- for (Json::Value::iterator json_it = app_choise_sets.begin();
- json_it != app_choise_sets.end(); ++json_it) {
- const Json::Value& json_choiset = *json_it;
- smart_objects::SmartObject msg_param(smart_objects::SmartType::SmartType_Map);
- Formatters::CFormatterJsonBase::jsonValueToObj(json_choiset , msg_param);
- const int32_t choice_set_id = msg_param
- [strings::interaction_choice_set_id].asInt();
- uint32_t choice_grammar_id = msg_param[strings::grammar_id].asUInt();
- application->AddChoiceSet(choice_set_id, msg_param);
-
- const size_t size = msg_param[strings::choice_set].length();
- for (size_t j = 0; j < size; ++j) {
- smart_objects::SmartObject choise_params(smart_objects::SmartType_Map);
- choise_params[strings::app_id] = application->app_id();
- choise_params[strings::cmd_id] =
- msg_param[strings::choice_set][j][strings::choice_id];
- choise_params[strings::vr_commands] = smart_objects::SmartObject(
- smart_objects::SmartType_Array);
- choise_params[strings::vr_commands] =
- msg_param[strings::choice_set][j][strings::vr_commands];
-
- choise_params[strings::type] = hmi_apis::Common_VRCommandType::Choice;
- choise_params[strings::grammar_id] = choice_grammar_id;
- SendHMIRequest(hmi_apis::FunctionID::VR_AddCommand, &choise_params);
- }
- }
- } else {
- LOG4CXX_FATAL(logger_, "There is no any choicesets");
- }
-}
-
-void ResumeCtrl::SetGlobalProperties(ApplicationSharedPtr application, const Json::Value& saved_app) {
- LOG4CXX_AUTO_TRACE(logger_);
- const Json::Value& global_properties = saved_app[strings::application_global_properties];
- if (!global_properties.isNull()) {
- smart_objects::SmartObject properties_so(smart_objects::SmartType::SmartType_Map);
- Formatters::CFormatterJsonBase::jsonValueToObj(global_properties , properties_so);
- application->load_global_properties(properties_so);
- MessageHelper::SendGlobalPropertiesToHMI(application);
- }
-}
-
-void ResumeCtrl::AddSubscriptions(ApplicationSharedPtr application, const Json::Value& saved_app) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (saved_app.isMember(strings::application_subscribtions)) {
- const Json::Value& subscribtions = saved_app[strings::application_subscribtions];
-
- if (subscribtions.isMember(strings::application_buttons)) {
- const Json::Value& subscribtions_buttons = subscribtions[strings::application_buttons];
- mobile_apis::ButtonName::eType btn;
- for (Json::Value::iterator json_it = subscribtions_buttons.begin();
- json_it != subscribtions_buttons.end(); ++json_it) {
- btn = static_cast<mobile_apis::ButtonName::eType>((*json_it).asInt());
- application->SubscribeToButton(btn);
- }
- }
- if (subscribtions.isMember(strings::application_vehicle_info)) {
- const Json::Value& subscribtions_ivi= subscribtions[strings::application_vehicle_info];
- VehicleDataType ivi;
- for (Json::Value::iterator json_it = subscribtions_ivi.begin();
- json_it != subscribtions_ivi.end(); ++json_it) {
- ivi = static_cast<VehicleDataType>((*json_it).asInt());
- application->SubscribeToIVI(ivi);
- }
- }
- ProcessHMIRequests(MessageHelper::GetIVISubscriptionRequests(application));
- MessageHelper::SendAllOnButtonSubscriptionNotificationsForApp(application);
- }
-}
-
-void ResumeCtrl::ProcessHMIRequests(const smart_objects::SmartObjectList& requests) {
- for (smart_objects::SmartObjectList::const_iterator it = requests.begin(),
- total = requests.end();
- it != total; ++it) {
- ProcessHMIRequest(*it, true);
- }
-}
-
-bool ResumeCtrl::CheckIcons(ApplicationSharedPtr application,
- const Json::Value& json_object) {
- LOG4CXX_AUTO_TRACE(logger_);
- bool result = true;
- if (!json_object.isNull()) {
- Json::Value::const_iterator json_it = json_object.begin();
- for (;json_it != json_object.end() && result; ++json_it) {
- const Json::Value& json_command = *json_it;
- if (!json_command.isNull()) {
- smart_objects::SmartObject message(smart_objects::SmartType::SmartType_Map);
- Formatters::CFormatterJsonBase::jsonValueToObj(json_command, message);
- const mobile_apis::Result::eType verify_images =
- MessageHelper::VerifyImageFiles(message, application);
- result = (mobile_apis::Result::INVALID_DATA != verify_images);
- } else {
- LOG4CXX_WARN(logger_, "Invalid json object");
- }
- }
- } else {
- LOG4CXX_WARN(logger_, "Passed json object is null");
- }
- LOG4CXX_DEBUG(logger_, "CheckIcons result " << result);
- return result;
-}
-
-Json::Value& ResumeCtrl::GetFromSavedOrAppend(const std::string& mobile_app_id) {
- LOG4CXX_AUTO_TRACE(logger_);
- for (Json::Value::iterator it = GetSavedApplications().begin();
- it != GetSavedApplications().end(); ++it) {
- if (mobile_app_id == (*it)[strings::app_id].asString()) {
- return *it;
- }
- }
-
- return GetSavedApplications().append(Json::Value());
-}
-
-bool ResumeCtrl::CheckIgnCycleRestrictions(const Json::Value& json_app) {
- LOG4CXX_AUTO_TRACE(logger_);
- bool result = true;
-
- if (!CheckDelayAfterIgnOn()) {
- LOG4CXX_INFO(logger_, "Application was connected long after ign on");
- result = false;
- }
-
- if (!DisconnectedJustBeforeIgnOff(json_app)) {
- LOG4CXX_INFO(logger_, "Application was dissconnected long before ign off");
- result = false;
- }
- return result;
-}
-
-bool ResumeCtrl::DisconnectedInLastIgnCycle(const Json::Value& json_app) {
- LOG4CXX_AUTO_TRACE(logger_);
- DCHECK_OR_RETURN(json_app.isMember(strings::suspend_count), false);
- const uint32_t suspend_count = json_app[strings::suspend_count].asUInt();
- LOG4CXX_DEBUG(logger_, " suspend_count " << suspend_count);
- return (1 == suspend_count);
-}
-
-bool ResumeCtrl::DisconnectedJustBeforeIgnOff(const Json::Value& json_app) {
- using namespace date_time;
- using namespace profile;
- LOG4CXX_AUTO_TRACE(logger_);
- DCHECK_OR_RETURN(json_app.isMember(strings::time_stamp), false);
-
- const time_t time_stamp =
- static_cast<time_t>(json_app[strings::time_stamp].asUInt());
- time_t ign_off_time = GetIgnOffTime();
- const uint32_t sec_spent_before_ign = labs(ign_off_time - time_stamp);
- LOG4CXX_DEBUG(logger_,"ign_off_time " << ign_off_time
- << "; app_disconnect_time " << time_stamp
- << "; sec_spent_before_ign " << sec_spent_before_ign
- << "; resumption_delay_before_ign " <<
- Profile::instance()->resumption_delay_before_ign());
- return sec_spent_before_ign <=
- Profile::instance()->resumption_delay_before_ign();
-}
-
-bool ResumeCtrl::CheckDelayAfterIgnOn() {
- using namespace date_time;
- using namespace profile;
- LOG4CXX_AUTO_TRACE(logger_);
- time_t curr_time = time(NULL);
- time_t sdl_launch_time = launch_time();
- const uint32_t seconds_from_sdl_start = labs(curr_time - sdl_launch_time);
- const uint32_t wait_time =
- Profile::instance()->resumption_delay_after_ign();
- LOG4CXX_DEBUG(logger_, "curr_time " << curr_time
- << "; sdl_launch_time " << sdl_launch_time
- << "; seconds_from_sdl_start " << seconds_from_sdl_start
- << "; wait_time " << wait_time);
- return seconds_from_sdl_start <= wait_time;
-}
-
-bool ResumeCtrl::CheckAppRestrictions(ApplicationSharedPtr application,
- const Json::Value& json_app) {
- using namespace mobile_apis;
- LOG4CXX_AUTO_TRACE(logger_);
- DCHECK_OR_RETURN(json_app.isMember(strings::hmi_level), false);
-
- const bool is_media_app = application->is_media_application();
- const HMILevel::eType hmi_level =
- static_cast<HMILevel::eType>(json_app[strings::hmi_level].asInt());
- LOG4CXX_DEBUG(logger_, "is_media_app " << is_media_app
- << "; hmi_level " << hmi_level);
-
- if (is_media_app) {
- if (hmi_level == HMILevel::HMI_FULL ||
- hmi_level == HMILevel::HMI_LIMITED) {
- return true;
- }
- }
- return false;
-}
-
-int ResumeCtrl::GetObjectIndex(const std::string& mobile_app_id) {
- LOG4CXX_AUTO_TRACE(logger_);
-
- sync_primitives::AutoLock lock(resumtion_lock_);
- const Json::Value& apps = GetSavedApplications();
- const Json::ArrayIndex size = apps.size();
- Json::ArrayIndex idx = 0;
- for (; idx != size; ++idx) {
- const std::string& saved_app_id = apps[idx][strings::app_id].asString();
- if (mobile_app_id == saved_app_id) {
- LOG4CXX_DEBUG(logger_, "Found " << idx);
- return idx;
- }
- }
- return -1;
-}
-time_t ResumeCtrl::launch_time() const {
- return launch_time_;
-}
-
-void ResumeCtrl::ResetLaunchTime() {
- launch_time_ = time(NULL);
-}
-
-void ResumeCtrl::ApplicationResumptiOnTimer() {
- LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock auto_lock(queue_lock_);
- is_resumption_active_ = false;
- std::vector<uint32_t>::iterator it = waiting_for_timer_.begin();
-
- for (; it != waiting_for_timer_.end(); ++it) {
- ApplicationSharedPtr app =
- ApplicationManagerImpl::instance()->application(*it);
- if (!app.get()) {
- LOG4CXX_ERROR(logger_, "Invalid app_id = " << *it);
- continue;
- }
-
- StartAppHmiStateResumption(app);
- }
-
- waiting_for_timer_.clear();
-}
-
-void ResumeCtrl::LoadResumeData() {
- LOG4CXX_AUTO_TRACE(logger_);
-
- sync_primitives::AutoLock lock(resumtion_lock_);
-
- Json::Value& resume_app_list = GetSavedApplications();
- Json::Value::iterator full_app = resume_app_list.end();
- time_t time_stamp_full = 0;
- Json::Value::iterator limited_app = resume_app_list.end();
- time_t time_stamp_limited = 0;
-
- Json::Value::iterator it = resume_app_list.begin();
- for (; it != resume_app_list.end(); ++it) {
- if ((*it).isMember(strings::ign_off_count) &&
- (*it).isMember(strings::hmi_level)) {
-
- // only apps with first IGN should be resumed
- const int32_t first_ign = 1;
- if (first_ign == (*it)[strings::ign_off_count].asInt()) {
-
- const mobile_apis::HMILevel::eType saved_hmi_level =
- static_cast<mobile_apis::HMILevel::eType>((*it)[strings::hmi_level].asInt());
-
- const time_t saved_time_stamp =
- static_cast<time_t>((*it)[strings::time_stamp].asUInt());
-
- if (mobile_apis::HMILevel::HMI_FULL == saved_hmi_level) {
- if (time_stamp_full < saved_time_stamp) {
- time_stamp_full = saved_time_stamp;
- full_app = it;
- }
- }
-
- if (mobile_apis::HMILevel::HMI_LIMITED == saved_hmi_level) {
- if (time_stamp_limited < saved_time_stamp) {
- time_stamp_limited = saved_time_stamp;
- limited_app = it;
- }
- }
- }
-
- // set invalid HMI level for all
- (*it)[strings::hmi_level] =
- static_cast<int32_t>(mobile_apis::HMILevel::INVALID_ENUM);
- }
- }
-
- if (full_app != resume_app_list.end()) {
- (*full_app)[strings::hmi_level] =
- static_cast<int32_t>(mobile_apis::HMILevel::HMI_FULL);
- }
-
- if (limited_app != resume_app_list.end()) {
- (*limited_app)[strings::hmi_level] =
- static_cast<int32_t>(mobile_apis::HMILevel::HMI_LIMITED);
- }
- LOG4CXX_DEBUG(logger_, GetResumptionData().toStyledString());
-}
-
-bool ResumeCtrl::IsResumptionDataValid(uint32_t index) {
- const Json::Value& json_app = GetSavedApplications()[index];
- if (!json_app.isMember(strings::app_id) ||
- !json_app.isMember(strings::ign_off_count) ||
- !json_app.isMember(strings::hmi_level) ||
- !json_app.isMember(strings::hmi_app_id) ||
- !json_app.isMember(strings::time_stamp)) {
- LOG4CXX_ERROR(logger_, "Wrong resumption data");
- return false;
- }
-
- if (json_app.isMember(strings::hmi_app_id) &&
- 0 >= json_app[strings::hmi_app_id].asUInt()) {
- LOG4CXX_ERROR(logger_, "Wrong resumption hmi app ID");
- return false;
- }
-
- return true;
-}
-
-uint32_t ResumeCtrl::SendHMIRequest(
- const hmi_apis::FunctionID::eType& function_id,
- const smart_objects::SmartObject* msg_params, bool use_events) {
- LOG4CXX_AUTO_TRACE(logger_);
- smart_objects::SmartObjectSPtr result =
- MessageHelper::CreateModuleInfoSO(function_id);
- uint32_t hmi_correlation_id =
- (*result)[strings::params][strings::correlation_id].asUInt();
- if (use_events) {
- subscribe_on_event(function_id, hmi_correlation_id);
- }
-
- if (msg_params) {
- (*result)[strings::msg_params] = *msg_params;
- }
-
- if (!ApplicationManagerImpl::instance()->ManageHMICommand(result)) {
- LOG4CXX_ERROR(logger_, "Unable to send request");
- }
- return hmi_correlation_id;
-}
-
-} // namespace application_manager
diff --git a/src/components/application_manager/src/resumption/resume_ctrl.cc b/src/components/application_manager/src/resumption/resume_ctrl.cc
new file mode 100644
index 0000000000..5e24c5572c
--- /dev/null
+++ b/src/components/application_manager/src/resumption/resume_ctrl.cc
@@ -0,0 +1,795 @@
+/*
+ Copyright (c) 2016, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "application_manager/resumption/resume_ctrl.h"
+
+#include <fstream>
+#include <algorithm>
+
+#include "application_manager/application_manager.h"
+
+#include "utils/file_system.h"
+#include "connection_handler/connection_handler_impl.h"
+#include "application_manager/message_helper.h"
+#include "connection_handler/connection.h"
+#include "application_manager/commands/command_impl.h"
+#include "policy/policy_manager_impl.h"
+#include "application_manager/policies/policy_handler.h"
+#include "application_manager/state_controller.h"
+#include "utils/helpers.h"
+#include "application_manager/resumption/resumption_data_db.h"
+#include "application_manager/resumption/resumption_data_json.h"
+#include "utils/make_shared.h"
+#include "utils/timer_task_impl.h"
+
+namespace resumption {
+using namespace application_manager;
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "Resumption")
+
+ResumeCtrl::ResumeCtrl(ApplicationManager& application_manager)
+ : event_engine::EventObserver(application_manager.event_dispatcher())
+ , queue_lock_(false)
+ , restore_hmi_level_timer_(
+ "RsmCtrlRstore",
+ new timer::TimerTaskImpl<ResumeCtrl>(
+ this, &ResumeCtrl::ApplicationResumptiOnTimer))
+ , save_persistent_data_timer_("RsmCtrlPercist",
+ new timer::TimerTaskImpl<ResumeCtrl>(
+ this, &ResumeCtrl::SaveDataOnTimer))
+ , is_resumption_active_(false)
+ , is_data_saved_(false)
+ , launch_time_(time(NULL))
+ , application_manager_(application_manager) {}
+#ifdef BUILD_TESTS
+void ResumeCtrl::set_resumption_storage(
+ utils::SharedPtr<ResumptionData> mock_storage) {
+ resumption_storage_ = mock_storage;
+}
+#endif // BUILD_TESTS
+
+bool ResumeCtrl::Init(resumption::LastState& last_state) {
+ bool use_db = application_manager_.get_settings().use_db_for_resumption();
+ if (use_db) {
+ resumption_storage_.reset(
+ new ResumptionDataDB(In_File_Storage, application_manager_));
+ if (!resumption_storage_->Init()) {
+ return false;
+ }
+
+ ResumptionDataDB* db =
+ dynamic_cast<ResumptionDataDB*>(resumption_storage_.get());
+
+ if (!db->IsDBVersionActual()) {
+ LOG4CXX_INFO(logger_,
+ "DB version had been changed. "
+ "Rebuilding resumption DB.");
+
+ smart_objects::SmartObject data;
+ db->GetAllData(data);
+
+ if (!db->RefreshDB()) {
+ return false;
+ }
+
+ db->SaveAllData(data);
+ db->UpdateDBVersion();
+ }
+ } else {
+ resumption_storage_.reset(
+ new ResumptionDataJson(last_state, application_manager_));
+ if (!resumption_storage_->Init()) {
+ LOG4CXX_DEBUG(logger_, "Resumption storage initialisation failed");
+ return false;
+ }
+ }
+ LoadResumeData();
+ save_persistent_data_timer_.Start(
+ application_manager_.get_settings()
+ .app_resumption_save_persistent_data_timeout(),
+ false);
+ return true;
+}
+
+ResumeCtrl::~ResumeCtrl() {}
+
+void ResumeCtrl::SaveAllApplications() {
+ DataAccessor<ApplicationSet> accessor(application_manager_.applications());
+ std::for_each(accessor.GetData().begin(),
+ accessor.GetData().end(),
+ std::bind1st(std::mem_fun(&ResumeCtrl::SaveApplication), this));
+}
+
+void ResumeCtrl::SaveApplication(ApplicationSharedPtr application) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(application);
+ LOG4CXX_INFO(logger_,
+ "application with appID " << application->app_id()
+ << " will be saved");
+ resumption_storage_->SaveApplication(application);
+}
+
+void ResumeCtrl::on_event(const event_engine::Event& event) {
+ LOG4CXX_DEBUG(logger_, "Event received" << event.id());
+}
+
+bool ResumeCtrl::RestoreAppHMIState(ApplicationSharedPtr application) {
+ using namespace mobile_apis;
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN(application, false);
+ LOG4CXX_DEBUG(logger_,
+ "app_id : " << application->app_id() << "; policy_app_id : "
+ << application->policy_app_id());
+ const std::string& device_mac = application->mac_address();
+ smart_objects::SmartObject saved_app(smart_objects::SmartType_Map);
+ bool result = resumption_storage_->GetSavedApplication(
+ application->policy_app_id(), device_mac, saved_app);
+ if (result) {
+ DCHECK_OR_RETURN(application, false);
+ if (saved_app.keyExists(strings::hmi_level)) {
+ const HMILevel::eType saved_hmi_level =
+ static_cast<mobile_apis::HMILevel::eType>(
+ saved_app[strings::hmi_level].asInt());
+ LOG4CXX_DEBUG(logger_, "Saved HMI Level is : " << saved_hmi_level);
+ return SetAppHMIState(application, saved_hmi_level, true);
+ } else {
+ result = false;
+ LOG4CXX_ERROR(logger_, "saved app data corrupted");
+ }
+ } else {
+ LOG4CXX_ERROR(logger_, "Application not saved");
+ }
+ return result;
+}
+
+bool ResumeCtrl::SetupDefaultHMILevel(ApplicationSharedPtr application) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN(application, false);
+ mobile_apis::HMILevel::eType default_hmi =
+ application_manager_.GetDefaultHmiLevel(application);
+ return SetAppHMIState(application, default_hmi, false);
+}
+
+void ResumeCtrl::ApplicationResumptiOnTimer() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock auto_lock(queue_lock_);
+ WaitingForTimerList::iterator it = waiting_for_timer_.begin();
+
+ for (; it != waiting_for_timer_.end(); ++it) {
+ ApplicationSharedPtr app = application_manager_.application(*it);
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Invalid app_id = " << *it);
+ continue;
+ }
+ StartAppHmiStateResumption(app);
+ }
+ is_resumption_active_ = false;
+ waiting_for_timer_.clear();
+ StartSavePersistentDataTimer();
+}
+
+void ResumeCtrl::OnAppActivated(ApplicationSharedPtr application) {
+ if (is_resumption_active_) {
+ RemoveFromResumption(application->app_id());
+ }
+}
+
+void ResumeCtrl::RemoveFromResumption(uint32_t app_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ queue_lock_.Acquire();
+ waiting_for_timer_.remove(app_id);
+ queue_lock_.Release();
+}
+
+bool ResumeCtrl::SetAppHMIState(ApplicationSharedPtr application,
+ const mobile_apis::HMILevel::eType hmi_level,
+ bool check_policy) {
+ using namespace mobile_apis;
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN(application, false);
+ LOG4CXX_TRACE(logger_,
+ " app_id : " << application->app_id()
+ << ", hmi_level : " << hmi_level
+ << ", check_policy : " << check_policy);
+ const std::string& device_mac = application->mac_address();
+ if (check_policy &&
+ application_manager_.GetUserConsentForDevice(device_mac) !=
+ policy::DeviceConsent::kDeviceAllowed) {
+ LOG4CXX_ERROR(logger_, "Resumption abort. Data consent wasn't allowed.");
+ SetupDefaultHMILevel(application);
+ return false;
+ }
+ application->set_is_resuming(true);
+ application_manager_.state_controller().SetRegularState(application,
+ hmi_level);
+ LOG4CXX_INFO(logger_,
+ "Application with policy id " << application->policy_app_id()
+ << " got HMI level " << hmi_level);
+ return true;
+}
+
+bool ResumeCtrl::IsHMIApplicationIdExist(uint32_t hmi_app_id) {
+ LOG4CXX_DEBUG(logger_, "hmi_app_id :" << hmi_app_id);
+ return resumption_storage_->IsHMIApplicationIdExist(hmi_app_id);
+}
+
+bool ResumeCtrl::IsApplicationSaved(const std::string& policy_app_id,
+ const std::string& device_id) {
+ return -1 !=
+ resumption_storage_->IsApplicationSaved(policy_app_id, device_id);
+}
+
+uint32_t ResumeCtrl::GetHMIApplicationID(const std::string& policy_app_id,
+ const std::string& device_mac) const {
+ return resumption_storage_->GetHMIApplicationID(policy_app_id, device_mac);
+}
+
+bool ResumeCtrl::RemoveApplicationFromSaved(
+ ApplicationConstSharedPtr application) {
+ const std::string& device_mac = application->mac_address();
+ return resumption_storage_->RemoveApplicationFromSaved(
+ application->policy_app_id(), device_mac);
+}
+
+void ResumeCtrl::OnSuspend() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ StopSavePersistentDataTimer();
+ SaveAllApplications();
+ resumption_storage_->OnSuspend();
+ resumption_storage_->Persist();
+}
+
+void ResumeCtrl::OnAwake() {
+ ResetLaunchTime();
+ StartSavePersistentDataTimer();
+ return resumption_storage_->OnAwake();
+}
+
+void ResumeCtrl::StartSavePersistentDataTimer() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!save_persistent_data_timer_.is_running()) {
+ save_persistent_data_timer_.Start(
+ application_manager_.get_settings()
+ .app_resumption_save_persistent_data_timeout(),
+ false);
+ }
+}
+
+void ResumeCtrl::StopSavePersistentDataTimer() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (save_persistent_data_timer_.is_running()) {
+ save_persistent_data_timer_.Stop();
+ }
+}
+
+bool ResumeCtrl::StartResumption(ApplicationSharedPtr application,
+ const std::string& hash) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN(application, false);
+ LOG4CXX_DEBUG(
+ logger_,
+ " Resume app_id = " << application->app_id()
+ << " hmi_app_id = " << application->hmi_app_id()
+ << " policy_id = " << application->policy_app_id()
+ << " received hash = " << hash);
+ SetupDefaultHMILevel(application);
+ smart_objects::SmartObject saved_app;
+ const std::string& device_mac = application->mac_address();
+ bool result = resumption_storage_->GetSavedApplication(
+ application->policy_app_id(), device_mac, saved_app);
+ if (result) {
+ const std::string& saved_hash = saved_app[strings::hash_id].asString();
+ result = saved_hash == hash ? RestoreApplicationData(application) : false;
+ application->UpdateHash();
+ AddToResumptionTimerQueue(application->app_id());
+ }
+ return result;
+}
+
+bool ResumeCtrl::StartResumptionOnlyHMILevel(ApplicationSharedPtr application) {
+ // sync_primitives::AutoLock lock(resumtion_lock_);
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!application) {
+ LOG4CXX_WARN(logger_, "Application does not exist.");
+ return false;
+ }
+ LOG4CXX_DEBUG(logger_,
+ "HMI level resumption requested for application id "
+ << application->app_id() << "with hmi_app_id "
+ << application->hmi_app_id() << ", policy_app_id "
+ << application->policy_app_id());
+ SetupDefaultHMILevel(application);
+ const std::string& device_mac = application->mac_address();
+ smart_objects::SmartObject saved_app;
+ bool result = resumption_storage_->GetSavedApplication(
+ application->policy_app_id(), device_mac, saved_app);
+ if (result) {
+ // sync_primitives::AutoUnlock unlock(lock);
+ AddToResumptionTimerQueue(application->app_id());
+ }
+ LOG4CXX_INFO(logger_, "StartResumptionOnlyHMILevel::Result = " << result);
+ return result;
+}
+
+void ResumeCtrl::StartAppHmiStateResumption(ApplicationSharedPtr application) {
+ using namespace date_time;
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(application);
+ smart_objects::SmartObject saved_app;
+ const std::string& device_mac = application->mac_address();
+ bool result = resumption_storage_->GetSavedApplication(
+ application->policy_app_id(), device_mac, saved_app);
+ DCHECK_OR_RETURN_VOID(result);
+ const uint32_t ign_off_count = saved_app[strings::ign_off_count].asUInt();
+ bool restore_data_allowed = false;
+ restore_data_allowed =
+ CheckAppRestrictions(application, saved_app) &&
+ ((0 == ign_off_count) || CheckIgnCycleRestrictions(saved_app));
+ if (restore_data_allowed) {
+ LOG4CXX_INFO(logger_,
+ "Resume application " << application->policy_app_id());
+ RestoreAppHMIState(application);
+ RemoveApplicationFromSaved(application);
+ } else {
+ LOG4CXX_INFO(logger_,
+ "Do not need to resume application "
+ << application->policy_app_id());
+ }
+}
+
+void ResumeCtrl::ResetLaunchTime() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ launch_time_ = time(NULL);
+}
+
+bool ResumeCtrl::CheckPersistenceFilesForResumption(
+ ApplicationSharedPtr application) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN(application, false);
+ LOG4CXX_DEBUG(logger_,
+ " Resume app_id = " << application->app_id() << " policy_id = "
+ << application->policy_app_id());
+ smart_objects::SmartObject saved_app;
+ const std::string& device_mac = application->mac_address();
+ bool result = resumption_storage_->GetSavedApplication(
+ application->policy_app_id(), device_mac, saved_app);
+ if (result) {
+ if (saved_app.keyExists(strings::application_commands)) {
+ if (!CheckIcons(application, saved_app[strings::application_commands])) {
+ return false;
+ }
+ }
+ if (saved_app.keyExists(strings::application_choice_sets)) {
+ if (!CheckIcons(application,
+ saved_app[strings::application_choice_sets])) {
+ return false;
+ }
+ }
+ }
+ return true;
+}
+
+bool ResumeCtrl::CheckApplicationHash(ApplicationSharedPtr application,
+ const std::string& hash) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN(application, false);
+ LOG4CXX_DEBUG(logger_,
+ "app_id : " << application->app_id() << " hash : " << hash);
+ smart_objects::SmartObject saved_app;
+ const std::string& device_mac = application->mac_address();
+ bool result = resumption_storage_->GetSavedApplication(
+ application->policy_app_id(), device_mac, saved_app);
+ return result ? saved_app[strings::hash_id].asString() == hash : false;
+}
+
+void ResumeCtrl::SaveDataOnTimer() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (is_resumption_active_) {
+ LOG4CXX_WARN(logger_, "Resumption timer is active skip saving");
+ return;
+ }
+
+ if (false == is_data_saved_) {
+ SaveAllApplications();
+ is_data_saved_ = true;
+ if (!application_manager_.get_settings().use_db_for_resumption()) {
+ resumption_storage_->Persist();
+ }
+ }
+}
+
+bool ResumeCtrl::IsDeviceMacAddressEqual(ApplicationSharedPtr application,
+ const std::string& saved_device_mac) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ const std::string device_mac = application->mac_address();
+ return device_mac == saved_device_mac;
+}
+
+bool ResumeCtrl::RestoreApplicationData(ApplicationSharedPtr application) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN(application, false);
+ LOG4CXX_DEBUG(logger_, "app_id : " << application->app_id());
+
+ smart_objects::SmartObject saved_app(smart_objects::SmartType_Map);
+ const std::string& device_mac = application->mac_address();
+ bool result = resumption_storage_->GetSavedApplication(
+ application->policy_app_id(), device_mac, saved_app);
+ if (result) {
+ if (saved_app.keyExists(strings::grammar_id)) {
+ const uint32_t app_grammar_id = saved_app[strings::grammar_id].asUInt();
+ application->set_grammar_id(app_grammar_id);
+ AddFiles(application, saved_app);
+ AddSubmenues(application, saved_app);
+ AddCommands(application, saved_app);
+ AddChoicesets(application, saved_app);
+ SetGlobalProperties(application, saved_app);
+ AddSubscriptions(application, saved_app);
+ AddWayPointsSubscription(application, saved_app);
+ result = true;
+ } else {
+ LOG4CXX_WARN(logger_,
+ "Saved data of application does not contain grammar_id");
+ result = false;
+ }
+ } else {
+ LOG4CXX_WARN(logger_, "Application not saved");
+ }
+ return result;
+}
+
+void ResumeCtrl::AddFiles(ApplicationSharedPtr application,
+ const smart_objects::SmartObject& saved_app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (saved_app.keyExists(strings::application_files)) {
+ const smart_objects::SmartObject& application_files =
+ saved_app[strings::application_files];
+ for (size_t i = 0; i < application_files.length(); ++i) {
+ const smart_objects::SmartObject& file_data = application_files[i];
+ const bool is_persistent =
+ file_data.keyExists(strings::persistent_file) &&
+ file_data[strings::persistent_file].asBool();
+ if (is_persistent) {
+ AppFile file;
+ file.is_persistent = is_persistent;
+ file.is_download_complete =
+ file_data[strings::is_download_complete].asBool();
+ file.file_name = file_data[strings::sync_file_name].asString();
+ file.file_type = static_cast<mobile_apis::FileType::eType>(
+ file_data[strings::file_type].asInt());
+ application->AddFile(file);
+ }
+ }
+ } else {
+ LOG4CXX_FATAL(logger_, "application_files section is not exists");
+ }
+}
+
+void ResumeCtrl::AddSubmenues(ApplicationSharedPtr application,
+ const smart_objects::SmartObject& saved_app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (saved_app.keyExists(strings::application_submenus)) {
+ const smart_objects::SmartObject& app_submenus =
+ saved_app[strings::application_submenus];
+ for (size_t i = 0; i < app_submenus.length(); ++i) {
+ const smart_objects::SmartObject& submenu = app_submenus[i];
+ application->AddSubMenu(submenu[strings::menu_id].asUInt(), submenu);
+ }
+ ProcessHMIRequests(MessageHelper::CreateAddSubMenuRequestToHMI(
+ application, application_manager_.GetNextHMICorrelationID()));
+ } else {
+ LOG4CXX_FATAL(logger_, "application_submenus section is not exists");
+ }
+}
+
+void ResumeCtrl::AddCommands(ApplicationSharedPtr application,
+ const smart_objects::SmartObject& saved_app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (saved_app.keyExists(strings::application_commands)) {
+ const smart_objects::SmartObject& app_commands =
+ saved_app[strings::application_commands];
+ for (size_t i = 0; i < app_commands.length(); ++i) {
+ const smart_objects::SmartObject& command = app_commands[i];
+
+ application->AddCommand(command[strings::cmd_id].asUInt(), command);
+ }
+ ProcessHMIRequests(MessageHelper::CreateAddCommandRequestToHMI(
+ application, application_manager_));
+ } else {
+ LOG4CXX_FATAL(logger_, "application_commands section is not exists");
+ }
+}
+
+void ResumeCtrl::AddChoicesets(ApplicationSharedPtr application,
+ const smart_objects::SmartObject& saved_app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (saved_app.keyExists(strings::application_choice_sets)) {
+ const smart_objects::SmartObject& app_choice_sets =
+ saved_app[strings::application_choice_sets];
+ for (size_t i = 0; i < app_choice_sets.length(); ++i) {
+ const smart_objects::SmartObject& choice_set = app_choice_sets[i];
+ const int32_t choice_set_id =
+ choice_set[strings::interaction_choice_set_id].asInt();
+ application->AddChoiceSet(choice_set_id, choice_set);
+ }
+ ProcessHMIRequests(MessageHelper::CreateAddVRCommandRequestFromChoiceToHMI(
+ application, application_manager_));
+ } else {
+ LOG4CXX_FATAL(logger_, "There is no any choicesets");
+ }
+}
+
+void ResumeCtrl::SetGlobalProperties(
+ ApplicationSharedPtr application,
+ const smart_objects::SmartObject& saved_app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (saved_app.keyExists(strings::application_global_properties)) {
+ const smart_objects::SmartObject& properties_so =
+ saved_app[strings::application_global_properties];
+ application->load_global_properties(properties_so);
+ MessageHelper::SendGlobalPropertiesToHMI(application, application_manager_);
+ }
+}
+
+void ResumeCtrl::AddWayPointsSubscription(
+ app_mngr::ApplicationSharedPtr application,
+ const smart_objects::SmartObject& saved_app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (saved_app.keyExists(strings::subscribed_for_way_points)) {
+ const smart_objects::SmartObject& subscribed_for_way_points_so =
+ saved_app[strings::subscribed_for_way_points];
+ if (true == subscribed_for_way_points_so.asBool()) {
+ application_manager_.SubscribeAppForWayPoints(application->app_id());
+ }
+ }
+}
+
+void ResumeCtrl::AddSubscriptions(ApplicationSharedPtr application,
+ const smart_objects::SmartObject& saved_app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (saved_app.keyExists(strings::application_subscribtions)) {
+ const smart_objects::SmartObject& subscribtions =
+ saved_app[strings::application_subscribtions];
+
+ if (subscribtions.keyExists(strings::application_buttons)) {
+ const smart_objects::SmartObject& subscribtions_buttons =
+ subscribtions[strings::application_buttons];
+ mobile_apis::ButtonName::eType btn;
+ for (size_t i = 0; i < subscribtions_buttons.length(); ++i) {
+ btn = static_cast<mobile_apis::ButtonName::eType>(
+ (subscribtions_buttons[i]).asInt());
+ application->SubscribeToButton(btn);
+ }
+ }
+ MessageHelper::SendAllOnButtonSubscriptionNotificationsForApp(
+ application, application_manager_);
+
+ if (subscribtions.keyExists(strings::application_vehicle_info)) {
+ const smart_objects::SmartObject& subscribtions_ivi =
+ subscribtions[strings::application_vehicle_info];
+ VehicleDataType ivi;
+ for (size_t i = 0; i < subscribtions_ivi.length(); ++i) {
+ ivi = static_cast<VehicleDataType>((subscribtions_ivi[i]).asInt());
+ application->SubscribeToIVI(ivi);
+ }
+ ProcessHMIRequests(MessageHelper::GetIVISubscriptionRequests(
+ application, application_manager_));
+ }
+ }
+}
+
+bool ResumeCtrl::CheckIgnCycleRestrictions(
+ const smart_objects::SmartObject& saved_app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ bool result = true;
+
+ if (!CheckDelayAfterIgnOn()) {
+ LOG4CXX_INFO(logger_, "Application was connected long after ign on");
+ result = false;
+ }
+
+ if (!DisconnectedJustBeforeIgnOff(saved_app)) {
+ LOG4CXX_INFO(logger_, "Application was dissconnected long before ign off");
+ result = false;
+ }
+ return result;
+}
+
+bool ResumeCtrl::DisconnectedJustBeforeIgnOff(
+ const smart_objects::SmartObject& saved_app) {
+ using namespace date_time;
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN(saved_app.keyExists(strings::time_stamp), false);
+
+ const time_t time_stamp =
+ static_cast<time_t>(saved_app[strings::time_stamp].asUInt());
+ time_t ign_off_time =
+ static_cast<time_t>(resumption_storage_->GetIgnOffTime());
+ const uint32_t sec_spent_before_ign = labs(ign_off_time - time_stamp);
+ LOG4CXX_DEBUG(
+ logger_,
+ "ign_off_time "
+ << ign_off_time << "; app_disconnect_time " << time_stamp
+ << "; sec_spent_before_ign " << sec_spent_before_ign
+ << "; resumption_delay_before_ign "
+ << application_manager_.get_settings().resumption_delay_before_ign());
+ return sec_spent_before_ign <=
+ application_manager_.get_settings().resumption_delay_before_ign();
+}
+
+bool ResumeCtrl::CheckAppRestrictions(
+ ApplicationConstSharedPtr application,
+ const smart_objects::SmartObject& saved_app) {
+ using namespace mobile_apis;
+ using namespace helpers;
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN(saved_app.keyExists(strings::hmi_level), false);
+
+ const bool is_media_app = application->is_media_application();
+ const HMILevel::eType hmi_level =
+ static_cast<HMILevel::eType>(saved_app[strings::hmi_level].asInt());
+ const bool result = Compare<HMILevel::eType, EQ, ONE>(
+ hmi_level, HMILevel::HMI_FULL, HMILevel::HMI_LIMITED)
+ ? true
+ : false;
+ LOG4CXX_DEBUG(logger_,
+ "is_media_app " << is_media_app << "; hmi_level " << hmi_level
+ << " result " << result);
+ return result;
+}
+
+bool ResumeCtrl::CheckIcons(ApplicationSharedPtr application,
+ smart_objects::SmartObject& obj) {
+ using namespace smart_objects;
+ LOG4CXX_AUTO_TRACE(logger_);
+ const mobile_apis::Result::eType verify_images =
+ MessageHelper::VerifyImageFiles(obj, application, application_manager_);
+ return mobile_apis::Result::INVALID_DATA != verify_images;
+}
+
+bool ResumeCtrl::CheckDelayAfterIgnOn() {
+ using namespace date_time;
+ LOG4CXX_AUTO_TRACE(logger_);
+ const time_t curr_time = time(NULL);
+ const time_t sdl_launch_time = launch_time();
+ const uint32_t seconds_from_sdl_start = labs(curr_time - sdl_launch_time);
+ const uint32_t wait_time =
+ application_manager_.get_settings().resumption_delay_after_ign();
+ LOG4CXX_DEBUG(logger_,
+ "curr_time " << curr_time << "; sdl_launch_time "
+ << sdl_launch_time << "; seconds_from_sdl_start "
+ << seconds_from_sdl_start << "; wait_time "
+ << wait_time);
+ return seconds_from_sdl_start <= wait_time;
+}
+
+time_t ResumeCtrl::launch_time() const {
+ return launch_time_;
+}
+
+time_t ResumeCtrl::GetIgnOffTime() {
+ return resumption_storage_->GetIgnOffTime();
+}
+
+bool ResumeCtrl::ProcessHMIRequest(smart_objects::SmartObjectSPtr request,
+ bool use_events) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (use_events) {
+ const hmi_apis::FunctionID::eType function_id =
+ static_cast<hmi_apis::FunctionID::eType>(
+ (*request)[strings::function_id].asInt());
+
+ const int32_t hmi_correlation_id =
+ (*request)[strings::correlation_id].asInt();
+ subscribe_on_event(function_id, hmi_correlation_id);
+ }
+ if (!application_manager_.ManageHMICommand(request)) {
+ LOG4CXX_ERROR(logger_, "Unable to send request");
+ return false;
+ }
+ return true;
+}
+
+void ResumeCtrl::ProcessHMIRequests(
+ const smart_objects::SmartObjectList& requests) {
+ for (smart_objects::SmartObjectList::const_iterator it = requests.begin(),
+ total = requests.end();
+ it != total;
+ ++it) {
+ ProcessHMIRequest(*it, true);
+ }
+}
+
+void ResumeCtrl::AddToResumptionTimerQueue(const uint32_t app_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ queue_lock_.Acquire();
+ waiting_for_timer_.push_back(app_id);
+ queue_lock_.Release();
+ LOG4CXX_DEBUG(logger_,
+ "Application ID " << app_id << " have been added"
+ " to resumption queue.");
+ if (!is_resumption_active_) {
+ is_resumption_active_ = true;
+ restore_hmi_level_timer_.Start(
+ application_manager_.get_settings().app_resuming_timeout(), true);
+ }
+}
+
+void ResumeCtrl::LoadResumeData() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObject so_applications_data;
+ resumption_storage_->GetDataForLoadResumeData(so_applications_data);
+ size_t length = so_applications_data.length();
+ for (size_t i = 0; i < length; ++i) {
+ smart_objects::SmartObject& application = so_applications_data[i];
+ if (IsAppDataResumptionExpired(application)) {
+ const std::string device_id = application[strings::device_id].asString();
+ const std::string app_id = application[strings::app_id].asString();
+ LOG4CXX_INFO(logger_, "Data resumption is expired.");
+ LOG4CXX_DEBUG(logger_,
+ "Resumption data for application "
+ << app_id << " and device id " << device_id
+ << " will be dropped.");
+ resumption_storage_->DropAppDataResumption(device_id, app_id);
+ continue;
+ }
+ }
+}
+
+void ResumeCtrl::OnAppRegistrationStart(const std::string& policy_app_id,
+ const std::string& device_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (IsApplicationSaved(policy_app_id, device_id)) {
+ LOG4CXX_INFO(
+ logger_,
+ "Application is found in resumption "
+ "data and will try to resume. Stopping resume data persistent timer");
+ StopSavePersistentDataTimer();
+ }
+}
+
+void ResumeCtrl::OnAppRegistrationEnd() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ StartSavePersistentDataTimer();
+}
+
+bool ResumeCtrl::IsAppDataResumptionExpired(
+ const smart_objects::SmartObject& application) const {
+ const int32_t max_ign_off_count = 3;
+ return max_ign_off_count <= application[strings::ign_off_count].asInt();
+}
+
+} // namespce resumption
diff --git a/src/components/application_manager/src/resumption/resumption_data.cc b/src/components/application_manager/src/resumption/resumption_data.cc
new file mode 100644
index 0000000000..273cd5413e
--- /dev/null
+++ b/src/components/application_manager/src/resumption/resumption_data.cc
@@ -0,0 +1,218 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/resumption/resumption_data.h"
+#include "utils/logger.h"
+#include "application_manager/smart_object_keys.h"
+#include "application_manager/vehicle_info_data.h"
+#include "application_manager/application_manager_settings.h"
+
+namespace resumption {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "Resumption")
+
+ResumptionData::ResumptionData(
+ const application_manager::ApplicationManager& application_manager)
+ : resumption_lock_(true), application_manager_(application_manager) {}
+
+smart_objects::SmartObject ResumptionData::GetApplicationCommands(
+ app_mngr::ApplicationConstSharedPtr application) const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObject commands_array(smart_objects::SmartType_Array);
+ DCHECK_OR_RETURN(application, commands_array);
+ if (!application) {
+ LOG4CXX_ERROR(logger_, "NULL Pointer App");
+ return commands_array;
+ }
+ const DataAccessor<CommandsMap> accessor = application->commands_map();
+ const CommandsMap& commands = accessor.GetData();
+ CommandsMap::const_iterator it = commands.begin();
+ for (int i = 0; it != commands.end(); ++it, ++i) {
+ commands_array[i] = *(it->second);
+ }
+ return commands_array;
+}
+
+smart_objects::SmartObject ResumptionData::GetApplicationSubMenus(
+ app_mngr::ApplicationConstSharedPtr application) const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ DCHECK(application.get());
+ smart_objects::SmartObject submenues_array =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+
+ if (!application) {
+ LOG4CXX_ERROR(logger_, "NULL Pointer App");
+ return submenues_array;
+ }
+ const DataAccessor<SubMenuMap> accessor = application->sub_menu_map();
+ const SubMenuMap& sub_menus = accessor.GetData();
+ SubMenuMap::const_iterator it = sub_menus.begin();
+ for (int i = 0; it != sub_menus.end(); ++it, ++i) {
+ submenues_array[i] = *(it->second);
+ }
+ return submenues_array;
+}
+
+smart_objects::SmartObject ResumptionData::GetApplicationInteractionChoiseSets(
+ app_mngr::ApplicationConstSharedPtr application) const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ DCHECK(application.get());
+ smart_objects::SmartObject interaction_choice_set_array =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+ if (!application) {
+ LOG4CXX_ERROR(logger_, "NULL Pointer App");
+ return interaction_choice_set_array;
+ }
+ const DataAccessor<ChoiceSetMap> accessor = application->choice_set_map();
+ const ChoiceSetMap& choices = accessor.GetData();
+ ChoiceSetMap::const_iterator it = choices.begin();
+ for (int i = 0; it != choices.end(); ++it, ++i) {
+ interaction_choice_set_array[i] = *(it->second);
+ }
+ return interaction_choice_set_array;
+}
+
+smart_objects::SmartObject ResumptionData::GetApplicationGlobalProperties(
+ app_mngr::ApplicationConstSharedPtr application) const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ DCHECK(application.get());
+ smart_objects::SmartObject global_properties =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ if (!application) {
+ LOG4CXX_ERROR(logger_, "NULL Pointer App");
+ return global_properties;
+ }
+
+ global_properties[strings::help_prompt] =
+ PointerToSmartObj(application->help_prompt());
+ global_properties[strings::timeout_prompt] =
+ PointerToSmartObj(application->timeout_prompt());
+ global_properties[strings::vr_help] =
+ PointerToSmartObj(application->vr_help());
+ global_properties[strings::vr_help_title] =
+ PointerToSmartObj(application->vr_help_title());
+ global_properties[strings::keyboard_properties] =
+ PointerToSmartObj(application->keyboard_props());
+ global_properties[strings::menu_title] =
+ PointerToSmartObj(application->menu_title());
+ global_properties[strings::menu_icon] =
+ PointerToSmartObj(application->menu_icon());
+ return global_properties;
+}
+
+smart_objects::SmartObject ResumptionData::GetApplicationSubscriptions(
+ app_mngr::ApplicationConstSharedPtr application) const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK(application.get());
+ smart_objects::SmartObject subscriptions =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ if (!application) {
+ LOG4CXX_ERROR(logger_, "NULL Pointer App");
+ return subscriptions;
+ }
+ LOG4CXX_DEBUG(logger_, "app_id:" << application->app_id());
+
+ DataAccessor<ButtonSubscriptions> button_accessor =
+ application->SubscribedButtons();
+
+ const ButtonSubscriptions& button_subscriptions = button_accessor.GetData();
+
+ LOG4CXX_DEBUG(logger_, "SubscribedButtons:" << button_subscriptions.size());
+ Append(button_subscriptions.begin(),
+ button_subscriptions.end(),
+ strings::application_buttons,
+ subscriptions);
+
+ DataAccessor<VehicleInfoSubscriptions> vi_accessor =
+ application->SubscribedIVI();
+
+ const VehicleInfoSubscriptions& vi_subscription = vi_accessor.GetData();
+
+ LOG4CXX_DEBUG(logger_, "SubscribedIVI:" << vi_subscription.size());
+ Append(vi_subscription.begin(),
+ vi_subscription.end(),
+ strings::application_vehicle_info,
+ subscriptions);
+ return subscriptions;
+}
+
+smart_objects::SmartObject ResumptionData::GetApplicationFiles(
+ app_mngr::ApplicationConstSharedPtr application) const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK(application.get());
+ LOG4CXX_TRACE(logger_, "ENTER app_id:" << application->app_id());
+
+ smart_objects::SmartObject files =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+ if (!application) {
+ LOG4CXX_ERROR(logger_, "NULL Pointer App");
+ return files;
+ }
+
+ const AppFilesMap& app_files = application->getAppFiles();
+ int i = 0;
+ for (AppFilesMap::const_iterator file_it = app_files.begin();
+ file_it != app_files.end();
+ file_it++) {
+ const AppFile& file = file_it->second;
+ if (file.is_persistent) {
+ smart_objects::SmartObject file_data =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
+ file_data[strings::persistent_file] = file.is_persistent;
+ file_data[strings::is_download_complete] = file.is_download_complete;
+ file_data[strings::sync_file_name] = file.file_name;
+ file_data[strings::file_type] = file.file_type;
+ files[i++] = file_data;
+ }
+ }
+ return files;
+}
+
+smart_objects::SmartObject ResumptionData::PointerToSmartObj(
+ const smart_objects::SmartObject* ptr) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObject temp;
+ if (ptr != NULL) {
+ temp = *ptr;
+ }
+ return temp;
+}
+} // namespace resumption
diff --git a/src/components/application_manager/src/resumption/resumption_data_db.cc b/src/components/application_manager/src/resumption/resumption_data_db.cc
new file mode 100644
index 0000000000..08de6d8190
--- /dev/null
+++ b/src/components/application_manager/src/resumption/resumption_data_db.cc
@@ -0,0 +1,2810 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#include <string>
+#include <unistd.h>
+
+#include "application_manager/application_manager_impl.h"
+#include "application_manager/resumption/resumption_data_db.h"
+#include "application_manager/resumption/resumption_sql_queries.h"
+#include "application_manager/smart_object_keys.h"
+#include "application_manager/message_helper.h"
+#include "utils/helpers.h"
+#include "utils/gen_hash.h"
+#include "utils/scope_guard.h"
+#include "application_manager/application_manager_settings.h"
+
+namespace {
+const std::string kDatabaseName = "resumption";
+}
+
+namespace resumption {
+CREATE_LOGGERPTR_GLOBAL(logger_, "Resumption")
+
+ResumptionDataDB::ResumptionDataDB(
+ DbStorage db_storage,
+ const application_manager::ApplicationManager& application_manager)
+ : ResumptionData(application_manager) {
+ if (db_storage == In_File_Storage) {
+ db_ = new utils::dbms::SQLDatabase(kDatabaseName);
+#ifndef __QNX__
+ std::string path = application_manager_.get_settings().app_storage_folder();
+ if (!path.empty()) {
+ db_->set_path(path + "/");
+ }
+ } else if (db_storage == In_Memory_Storage) {
+ db_ = new utils::dbms::SQLDatabase();
+#endif // __QNX__
+ } else {
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_ERROR(logger_, "Get not existed type of database storage");
+ }
+}
+
+ResumptionDataDB::~ResumptionDataDB() {
+ db_->Close();
+ delete db_;
+}
+
+bool ResumptionDataDB::Init() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (!db_->Open()) {
+ LOG4CXX_ERROR(logger_, "Failed opening database.");
+ LOG4CXX_INFO(logger_, "Starting opening retries.");
+ const uint16_t attempts =
+ application_manager_.get_settings().attempts_to_open_resumption_db();
+ LOG4CXX_DEBUG(logger_, "Total attempts number is: " << attempts);
+ bool is_opened = false;
+ const uint16_t open_attempt_timeout_ms =
+ application_manager_.get_settings()
+ .open_attempt_timeout_ms_resumption_db();
+ const useconds_t sleep_interval_mcsec = open_attempt_timeout_ms * 1000;
+ LOG4CXX_DEBUG(logger_,
+ "Open attempt timeout(ms) is: " << open_attempt_timeout_ms);
+ for (int i = 0; i < attempts; ++i) {
+ usleep(sleep_interval_mcsec);
+ LOG4CXX_INFO(logger_, "Attempt: " << i + 1);
+ if (db_->Open()) {
+ LOG4CXX_INFO(logger_, "Database opened.");
+ is_opened = true;
+ break;
+ }
+ }
+ if (!is_opened) {
+ LOG4CXX_ERROR(logger_,
+ "Open retry sequence failed. Tried "
+ << attempts << " attempts with "
+ << open_attempt_timeout_ms
+ << " open timeout(ms) for each.");
+ return false;
+ }
+ }
+#ifndef __QNX__
+ if (!db_->IsReadWrite()) {
+ LOG4CXX_ERROR(logger_, "There are no read/write permissions for database");
+ return false;
+ }
+#endif // __QNX__
+ utils::dbms::SQLQuery query(db());
+ if (!query.Exec(kCreateSchema)) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Failed creating schema of database: " << query.LastError().text());
+ return false;
+ }
+ utils::dbms::SQLQuery query_checks_resumption(db());
+ if (!query_checks_resumption.Prepare(kChecksResumptionData) ||
+ !query_checks_resumption.Exec()) {
+ LOG4CXX_ERROR(logger_,
+ "Failed verification or execution query kChecksResumptionData"
+ << query_checks_resumption.LastError().text());
+ return false;
+ }
+ if (0 == query_checks_resumption.GetInteger(0)) {
+ utils::dbms::SQLQuery query_insert_resumption(db());
+ if (!query_insert_resumption.Prepare(kInsertInitData) ||
+ !query_insert_resumption.Exec()) {
+ LOG4CXX_ERROR(logger_,
+ "Failed insert init data to database: "
+ << query_insert_resumption.LastError().text());
+ return false;
+ }
+ }
+ return true;
+}
+
+void ResumptionDataDB::SaveApplication(
+ app_mngr::ApplicationSharedPtr application) {
+ using namespace app_mngr;
+ using namespace mobile_api;
+ using namespace helpers;
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(application);
+ bool application_exist = false;
+ const std::string& policy_app_id = application->policy_app_id();
+ const std::string& device_mac = application->mac_address();
+ LOG4CXX_INFO(logger_,
+ "app_id : " << application->app_id() << " policy_app_id : "
+ << policy_app_id << " device_id : " << device_mac);
+
+ if (!CheckExistenceApplication(
+ policy_app_id, device_mac, application_exist)) {
+ LOG4CXX_ERROR(logger_, "Problem with access to DB");
+ return;
+ }
+
+ if (application->is_application_data_changed()) {
+ if (application_exist) {
+ if (!DeleteSavedApplication(policy_app_id, device_mac)) {
+ LOG4CXX_ERROR(logger_, "Deleting of application data is not finished");
+ return;
+ }
+ }
+
+ if (!SaveApplicationToDB(application, policy_app_id, device_mac)) {
+ LOG4CXX_ERROR(logger_, "Saving of application data is not finished");
+ return;
+ }
+ LOG4CXX_INFO(logger_, "All data from application were saved successfully");
+ application->set_is_application_data_changed(false);
+ } else {
+ if (application_exist) {
+ if (!UpdateApplicationData(application, policy_app_id, device_mac)) {
+ LOG4CXX_ERROR(logger_, "Updating application data is failed");
+ return;
+ }
+ LOG4CXX_INFO(logger_, "Application data were updated successfully");
+ } else {
+ if (Compare<HMILevel::eType, EQ, ONE>(application->hmi_level(),
+ HMILevel::HMI_FULL,
+ HMILevel::HMI_LIMITED)) {
+ if (!InsertApplicationData(application, policy_app_id, device_mac)) {
+ LOG4CXX_ERROR(logger_, "Saving data of application is failed");
+ return;
+ }
+ }
+ }
+ }
+ WriteDb();
+}
+
+bool ResumptionDataDB::IsHMIApplicationIdExist(uint32_t hmi_app_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ return CheckExistenceHMIId(hmi_app_id);
+}
+
+uint32_t ResumptionDataDB::GetHMIApplicationID(
+ const std::string& policy_app_id, const std::string& device_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ uint32_t hmi_app_id = 0;
+ SelectHMIId(policy_app_id, device_id, hmi_app_id);
+ return hmi_app_id;
+}
+
+void ResumptionDataDB::OnSuspend() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ utils::dbms::SQLQuery query_update_suspend_data(db());
+ utils::dbms::SQLQuery query_update_last_ign_off_time(db());
+ /*
+ application_lifes - contains amount of ignition cycles during which
+ db stores data of application
+ */
+ const int application_lifes = 3;
+
+ if (DeleteAppWithIgnCount(application_lifes)) {
+ LOG4CXX_INFO(logger_,
+ "Saved application with ign_off_count = " << application_lifes
+ << " was deleted");
+ } else {
+ LOG4CXX_WARN(logger_, "Problem with removing applications");
+ }
+
+ if (query_update_suspend_data.Prepare(kUpdateSuspendData)) {
+ if (query_update_suspend_data.Exec()) {
+ LOG4CXX_INFO(logger_,
+ "Data ign_off_count and suspend_count were updated");
+ }
+ }
+
+ if (query_update_last_ign_off_time.Prepare(KUpdateLastIgnOffTime)) {
+ query_update_last_ign_off_time.Bind(0, static_cast<int64_t>(time(NULL)));
+ if (query_update_last_ign_off_time.Exec()) {
+ LOG4CXX_INFO(logger_, "Data last_ign_off_time was updated");
+ }
+ }
+}
+
+bool ResumptionDataDB::DeleteAppWithIgnCount(const int application_lifes) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery select_apps_for_removing(db());
+ utils::dbms::SQLQuery count_app(db());
+
+ if (!select_apps_for_removing.Prepare(kSelectApplicationsIgnOffCount) ||
+ !count_app.Prepare(kCountApplicationsIgnOff)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with verification query select_apps_for_removing or"
+ " query count_app");
+ return false;
+ }
+ /* Positions of binding data for "query count_app" :
+ field "ign_off_count" from table "application" = 0*/
+ count_app.Bind(0, application_lifes);
+ if (!count_app.Exec() || !count_app.GetInteger(0)) {
+ LOG4CXX_WARN(logger_, "Problem with execution or count app=0");
+ return false;
+ }
+ std::string policy_app_id;
+ std::string device_id;
+ /* Positions of binding data for "select_apps_for_removing" :
+ field "ign_off_count" from table "application" = 0*/
+ select_apps_for_removing.Bind(0, application_lifes);
+ while (select_apps_for_removing.Next()) {
+ device_id = select_apps_for_removing.GetString(0);
+ policy_app_id = select_apps_for_removing.GetString(1);
+ if (!DeleteSavedApplication(policy_app_id, device_id)) {
+ LOG4CXX_WARN(logger_, "Problem with removing application data");
+ return false;
+ }
+ }
+ LOG4CXX_WARN(logger_, "Applications data were removed successfully");
+ WriteDb();
+ return true;
+}
+
+bool ResumptionDataDB::GetHashId(const std::string& policy_app_id,
+ const std::string& device_id,
+ std::string& hash_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ return SelectHashId(policy_app_id, device_id, hash_id);
+}
+
+void ResumptionDataDB::OnAwake() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ UpdateDataOnAwake();
+}
+
+bool ResumptionDataDB::GetSavedApplication(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ bool application_exist = false;
+
+ if (!CheckExistenceApplication(policy_app_id, device_id, application_exist) ||
+ !application_exist) {
+ LOG4CXX_ERROR(logger_,
+ "Problem with access to DB or application does not exists");
+ return false;
+ }
+
+ if (!SelectDataFromAppTable(policy_app_id, device_id, saved_app)) {
+ LOG4CXX_ERROR(logger_,
+ "Problem with restoring of data from application table");
+ return false;
+ }
+
+ if (!SelectFilesData(policy_app_id, device_id, saved_app)) {
+ LOG4CXX_ERROR(logger_, "Problem with restoring of files data");
+ return false;
+ }
+
+ if (!SelectSubmenuData(policy_app_id, device_id, saved_app)) {
+ LOG4CXX_ERROR(logger_, "Problem with restoring of submenu data");
+ return false;
+ }
+
+ if (!SelectCommandData(policy_app_id, device_id, saved_app)) {
+ LOG4CXX_ERROR(logger_, "Problem with restoring of command data");
+ return false;
+ }
+
+ if (!SelectSubscriptionsData(policy_app_id, device_id, saved_app)) {
+ LOG4CXX_ERROR(logger_, "Problem with restoring of subscriptions data");
+ return false;
+ }
+
+ if (!SelectChoiceSetData(policy_app_id, device_id, saved_app)) {
+ LOG4CXX_ERROR(logger_, "Problem with restoring of choice set data");
+ return false;
+ }
+
+ if (!SelectGlobalPropertiesData(policy_app_id, device_id, saved_app)) {
+ LOG4CXX_ERROR(logger_, "Problem with restoring of global properties data");
+ return false;
+ }
+ LOG4CXX_INFO(logger_,
+ "Application data were successfully fetched from data base");
+ return true;
+}
+
+bool ResumptionDataDB::RemoveApplicationFromSaved(
+ const std::string& policy_app_id, const std::string& device_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ bool application_exist = false;
+ if (!CheckExistenceApplication(policy_app_id, device_id, application_exist) ||
+ !application_exist) {
+ LOG4CXX_ERROR(logger_,
+ "Problem with access to DB or application does not"
+ " exist");
+ return false;
+ }
+ bool result = false;
+ if (DeleteSavedApplication(policy_app_id, device_id)) {
+ WriteDb();
+ result = true;
+ }
+ return result;
+}
+
+uint32_t ResumptionDataDB::GetIgnOffTime() const {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ return SelectIgnOffTime();
+}
+
+ssize_t ResumptionDataDB::IsApplicationSaved(
+ const std::string& policy_app_id, const std::string& device_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ bool application_exist = false;
+ if (CheckExistenceApplication(policy_app_id, device_id, application_exist) &&
+ application_exist) {
+ LOG4CXX_INFO(logger_, "Application exists in stored data");
+ return 0;
+ }
+ return -1;
+}
+
+void ResumptionDataDB::GetDataForLoadResumeData(
+ smart_objects::SmartObject& saved_data) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ SelectDataForLoadResumeData(saved_data);
+}
+
+bool ResumptionDataDB::SelectHMILevel(const std::string& policy_app_id,
+ const std::string& device_id,
+ int& hmi_level) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query_count(db());
+ utils::dbms::SQLQuery query_select(db());
+ if (query_count.Prepare(kSelectCountHMILevel) &&
+ query_select.Prepare(kSelectHMILevel)) {
+ /* Positions of binding data for "query_count" and "query_select" :
+ field "deviceID" from table "application" = 0
+ field "appID" from table "application" = 1 */
+ query_count.Bind(0, device_id);
+ query_count.Bind(1, policy_app_id);
+ query_select.Bind(0, device_id);
+ query_select.Bind(1, policy_app_id);
+ /* Position of data in "query_select" :
+ field "hmiLevel" from table "application" = 0 */
+ if (query_count.Exec() && query_count.GetInteger(0) &&
+ query_select.Exec()) {
+ hmi_level = query_select.GetInteger(0);
+ return true;
+ }
+ }
+ return false;
+}
+
+bool ResumptionDataDB::CheckExistenceHMIId(uint32_t hmi_app_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ utils::dbms::SQLQuery query(db());
+ if (query.Prepare(kCheckHMIId)) {
+ query.Bind(0, static_cast<int64_t>(hmi_app_id));
+ if (query.Exec() && (query.GetInteger(0))) {
+ LOG4CXX_INFO(logger_, "Saved data has HMI appID = " << hmi_app_id);
+ return true;
+ }
+ }
+ LOG4CXX_FATAL(logger_,
+ "HMI appID = " << hmi_app_id << " doesn't exist in saved data");
+ return false;
+}
+
+void ResumptionDataDB::SelectHMIId(const std::string& policy_app_id,
+ const std::string& device_id,
+ uint32_t& hmi_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ utils::dbms::SQLQuery query_select(db());
+ utils::dbms::SQLQuery query_check(db());
+ /* Positions of binding data for "query_select" and "query_check" :
+ field "deviceID" from table "application" = 0
+ field "appID" from table "application" = 1 */
+ if (query_select.Prepare(kSelectHMIId) &&
+ query_check.Prepare(kSelectCountHMIId)) {
+ query_select.Bind(0, device_id);
+ query_select.Bind(1, policy_app_id);
+ query_check.Bind(0, device_id);
+ query_check.Bind(1, policy_app_id);
+ /* Position of data in "query_select" :
+ field "hmiAppID" from table "application" = 0 */
+ if (query_check.Exec() && query_check.GetInteger(0) &&
+ query_select.Exec()) {
+ hmi_id = query_select.GetUInteger(0);
+ LOG4CXX_INFO(logger_, "HMI appID = " << hmi_id);
+ return;
+ }
+ }
+ LOG4CXX_FATAL(logger_,
+ "Saved data doesn't have application with "
+ "device id = "
+ << device_id << " and policy appID = " << policy_app_id);
+}
+
+bool ResumptionDataDB::SelectHashId(const std::string& policy_app_id,
+ const std::string& device_id,
+ std::string& hash_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery count(db());
+ utils::dbms::SQLQuery select_hash(db());
+ if (!select_hash.Prepare(kSelectHashId) || !count.Prepare(kCountHashId)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with verification count query or"
+ " select_hash query");
+ return false;
+ }
+ /* Positions of binding data for "count" and "select_hash" :
+ field "deviceID" from table "application" = 0
+ field "appID" from table "application" = 1 */
+ count.Bind(0, device_id);
+ count.Bind(1, policy_app_id);
+ select_hash.Bind(0, device_id);
+ select_hash.Bind(1, policy_app_id);
+ /* Position of data in "select_hash" :
+ field "hashID" from table "application" = 0 */
+ if (count.Exec() && count.GetInteger(0) && select_hash.Exec()) {
+ hash_id = select_hash.GetString(0);
+ LOG4CXX_INFO(logger_, "Saved hash ID = " << hash_id);
+ return true;
+ }
+ LOG4CXX_WARN(logger_,
+ "Saved data doesn't have application with "
+ "device id = "
+ << device_id << " and policy appID = " << policy_app_id
+ << "or hashID");
+ return false;
+}
+
+uint32_t ResumptionDataDB::SelectIgnOffTime() const {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ uint32_t ignOffTime = 0;
+ utils::dbms::SQLQuery query(db());
+ if (query.Prepare(kSelectIgnOffTime)) {
+ if (query.Exec()) {
+ ignOffTime = query.GetUInteger(0);
+ LOG4CXX_INFO(logger_, "Last ign off time = " << ignOffTime);
+ return ignOffTime;
+ }
+ }
+ LOG4CXX_ERROR(logger_, "Problem with prepare query");
+ return ignOffTime;
+}
+
+bool ResumptionDataDB::CheckExistenceApplication(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ bool& application_exist) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ bool result = false;
+ utils::dbms::SQLQuery query(db());
+ /* Positions of binding data for "query":
+ field "deviceID" from table "application" = 0
+ field "appID" from table "application" = 1 */
+ if (query.Prepare(kCheckApplication)) {
+ query.Bind(0, device_id);
+ query.Bind(1, policy_app_id);
+ result = query.Exec();
+ }
+ /* Position of data in "query" :
+ amount of application = 0 */
+ if (result && query.GetInteger(0)) {
+ LOG4CXX_INFO(logger_,
+ "Saved data has application with policy appID = "
+ << policy_app_id << " and deviceID = " << device_id);
+ application_exist = true;
+ } else if (result) {
+ LOG4CXX_INFO(logger_, "Saved data does not contain application");
+ application_exist = false;
+ } else {
+ LOG4CXX_ERROR(logger_, "Problem with access DB");
+ }
+ return result;
+}
+
+void ResumptionDataDB::SelectDataForLoadResumeData(
+ smart_objects::SmartObject& saved_data) const {
+ using namespace app_mngr;
+ using namespace smart_objects;
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ utils::dbms::SQLQuery select_data(db());
+ utils::dbms::SQLQuery count_application(db());
+ if (!select_data.Prepare(kSelectDataForLoadResumeData) ||
+ !count_application.Prepare(kCountApplications)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with verification select_data query"
+ " or count application");
+ return;
+ }
+
+ if (!count_application.Exec() || !count_application.GetInteger(0)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with execution count_application query"
+ " or appliction table does not contain data");
+ return;
+ }
+ SmartObject so_array_data(SmartType_Array);
+ uint32_t i = 0;
+ /* Position of data in "select_data" :
+ field "hmiLevel" from table "application" = 0
+ field "ign_off_count" from table "application" = 1
+ field "timeStamp" from table "application" = 2
+ field "appID" from table "application" = 3
+ field "deviceID" from table "application" = 4 */
+ while (select_data.Next()) {
+ SmartObject so_obj(SmartType_Map);
+ so_obj[strings::hmi_level] = select_data.GetInteger(0);
+ so_obj[strings::ign_off_count] = select_data.GetInteger(1);
+ so_obj[strings::time_stamp] = select_data.GetUInteger(2);
+ so_obj[strings::app_id] = select_data.GetString(3);
+ so_obj[strings::device_id] = select_data.GetString(4);
+ so_array_data[i++] = so_obj;
+ }
+ saved_data = so_array_data;
+}
+
+void ResumptionDataDB::UpdateHmiLevel(const std::string& policy_app_id,
+ const std::string& device_id,
+ mobile_apis::HMILevel::eType hmi_level) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ utils::dbms::SQLQuery query(db());
+ /* Positions of binding data for "query":
+ field "hmiLevel" from table "application" = 0
+ field "deviceID" from table "application" = 1
+ field "appID" from table "application" = 2 */
+ if (query.Prepare(kUpdateHMILevel)) {
+ query.Bind(0, hmi_level);
+ query.Bind(1, device_id);
+ query.Bind(2, policy_app_id);
+ if (query.Exec()) {
+ LOG4CXX_INFO(logger_,
+ "Saved data has application with policy appID = "
+ << policy_app_id << " and deviceID = " << device_id
+ << " has new HMI level = " << hmi_level);
+ WriteDb();
+ }
+ }
+}
+
+void ResumptionDataDB::Persist() {
+ WriteDb();
+}
+
+bool ResumptionDataDB::RefreshDB() const {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Exec(resumption::kDropSchema)) {
+ LOG4CXX_WARN(logger_,
+ "Failed dropping database: " << query.LastError().text());
+ return false;
+ }
+ if (!query.Exec(resumption::kCreateSchema)) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Failed creating schema of database: " << query.LastError().text());
+ return false;
+ }
+ if (!query.Exec(resumption::kInsertInitData)) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Failed insert init data to database: " << query.LastError().text());
+ return false;
+ }
+ return true;
+}
+
+bool ResumptionDataDB::GetAllData(smart_objects::SmartObject& data) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(resumption::kSelectAllApps)) {
+ LOG4CXX_ERROR(logger_, "Can't get applications data from DB.");
+ return false;
+ }
+
+ data = smart_objects::SmartObject(smart_objects::SmartType_Array);
+
+ uint32_t index = 0;
+ std::string app_id;
+ std::string device_id;
+ while (query.Next()) {
+ app_id = query.GetString(0);
+ device_id = query.GetString(1);
+ if (GetSavedApplication(app_id, device_id, data[index])) {
+ ++index;
+ }
+ }
+ return true;
+}
+
+bool ResumptionDataDB::SaveAllData(const smart_objects::SmartObject& data) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (smart_objects::SmartType_Array != data.getType()) {
+ LOG4CXX_ERROR(logger_, "Unexpected type for resumption data.");
+ return false;
+ }
+ const smart_objects::SmartArray* apps = data.asArray();
+ smart_objects::SmartArray::const_iterator it_apps = apps->begin();
+ for (; apps->end() != it_apps; ++it_apps) {
+ if (!SaveApplicationToDB((*it_apps),
+ (*it_apps)["appID"].asString(),
+ (*it_apps)["deviceID"].asString())) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool ResumptionDataDB::IsDBVersionActual() const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(resumption::kSelectDBVersion) || !query.Exec()) {
+ LOG4CXX_ERROR(logger_,
+ "Failed to get DB version: " << query.LastError().text());
+ return false;
+ }
+
+ const int32_t saved_db_version = query.GetInteger(0);
+ const int32_t current_db_version = GetDBVersion();
+ LOG4CXX_DEBUG(logger_,
+ "Saved DB version is: " << saved_db_version
+ << ". Current DB vesion is: "
+ << current_db_version);
+
+ return current_db_version == saved_db_version;
+}
+
+bool ResumptionDataDB::UpdateDBVersion() const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(resumption::kUpdateDBVersion)) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Incorrect DB version update query: " << query.LastError().text());
+ return false;
+ }
+
+ query.Bind(0, GetDBVersion());
+
+ if (!query.Exec()) {
+ LOG4CXX_ERROR(logger_,
+ "DB version update failed: " << query.LastError().text());
+ return false;
+ }
+
+ return true;
+}
+
+bool ResumptionDataDB::DropAppDataResumption(const std::string& device_id,
+ const std::string& app_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ utils::ScopeGuard guard =
+ utils::MakeObjGuard(*db_, &utils::dbms::SQLDatabase::RollbackTransaction);
+
+ db_->BeginTransaction();
+ if (!DeleteSavedFiles(app_id, device_id)) {
+ return false;
+ }
+ if (!DeleteSavedSubMenu(app_id, device_id)) {
+ return false;
+ }
+ if (!DeleteSavedSubscriptions(app_id, device_id)) {
+ return false;
+ }
+ if (!DeleteSavedCommands(app_id, device_id)) {
+ return false;
+ }
+ if (!DeleteSavedChoiceSet(app_id, device_id)) {
+ return false;
+ }
+ if (!DeleteSavedGlobalProperties(app_id, device_id)) {
+ return false;
+ }
+ if (!UpdateGrammarID(app_id, device_id, 0)) {
+ return false;
+ }
+ db_->CommitTransaction();
+
+ guard.Dismiss();
+ return true;
+}
+
+const int32_t ResumptionDataDB::GetDBVersion() const {
+ return utils::Djb2HashFromString(resumption::kCreateSchema);
+}
+
+bool ResumptionDataDB::SelectFilesData(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+ uint32_t count_item = 0;
+ if (!SelectCountFromArray(
+ count_item, kSelectCountFiles, policy_app_id, device_id)) {
+ return false;
+ }
+
+ saved_app[strings::application_files] = SmartObject(SmartType_Array);
+
+ if (0 == count_item) {
+ LOG4CXX_INFO(logger_, "Application does not contain files data");
+ return true;
+ }
+ utils::dbms::SQLQuery select_files(db());
+ if (!PrepareSelectQuery(
+ select_files, policy_app_id, device_id, kSelectFiles)) {
+ LOG4CXX_WARN(logger_, "Problem with verification select_files");
+ return false;
+ }
+ saved_app[strings::application_files] = SmartObject(SmartType_Array);
+ /* Position of data in "select_files" :
+ field "fileType" from table "file" = 0
+ field "is_download_complete" from table "file" = 1
+ field "persistentFile" from table "file" = 2
+ field "syncFileName" from table "file" = 3*/
+ uint32_t i = 0;
+ while (select_files.Next()) {
+ SmartObject array_item(SmartType_Map);
+ array_item[strings::file_type] = select_files.GetInteger(0);
+ array_item[strings::is_download_complete] = select_files.GetBoolean(1);
+ array_item[strings::persistent_file] = select_files.GetBoolean(2);
+ array_item[strings::sync_file_name] = select_files.GetString(3);
+ saved_app[strings::application_files][i++] = array_item;
+ }
+ LOG4CXX_INFO(logger_, "File data was restored successfully");
+ return true;
+}
+
+bool ResumptionDataDB::SelectSubmenuData(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+ uint32_t count_item = 0;
+ if (!SelectCountFromArray(
+ count_item, kSelectCountSubMenu, policy_app_id, device_id)) {
+ return false;
+ }
+
+ saved_app[strings::application_submenus] = SmartObject(SmartType_Array);
+
+ if (0 == count_item) {
+ LOG4CXX_INFO(logger_, "Application does not contain submenu data");
+ return true;
+ }
+ utils::dbms::SQLQuery select_sub_menu(db());
+ if (!PrepareSelectQuery(
+ select_sub_menu, policy_app_id, device_id, kSelectSubMenu)) {
+ LOG4CXX_WARN(logger_, "Problem with verification select_sub_menu");
+ return false;
+ }
+ saved_app[strings::application_submenus] = SmartObject(SmartType_Array);
+ /* Position of data in "select_sub_menu" :
+ field "menuID" from table "subMenu" = 0
+ field "menuName" from table "subMenu" = 1
+ field "position" from table "subMenu" = 2*/
+ uint32_t i = 0;
+ while (select_sub_menu.Next()) {
+ SmartObject array_item(SmartType_Map);
+ array_item[strings::menu_id] = select_sub_menu.GetInteger(0);
+ array_item[strings::menu_name] = select_sub_menu.GetString(1);
+ if (!(select_sub_menu.IsNull(2))) {
+ array_item[strings::position] = select_sub_menu.GetInteger(2);
+ }
+ saved_app[strings::application_submenus][i++] = array_item;
+ }
+ LOG4CXX_INFO(logger_, "Sub menu data was restored successfully");
+ return true;
+}
+
+bool ResumptionDataDB::SelectCommandData(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+ uint32_t count_item = 0;
+ if (!SelectCountFromArray(
+ count_item, kSelectCountCommands, policy_app_id, device_id)) {
+ return false;
+ }
+
+ saved_app[strings::application_commands] = SmartObject(SmartType_Array);
+
+ if (0 == count_item) {
+ LOG4CXX_INFO(logger_, "Application does not contain commands data");
+ return true;
+ }
+
+ utils::dbms::SQLQuery select_commands(db());
+ if (!PrepareSelectQuery(
+ select_commands, policy_app_id, device_id, kSelectCommands)) {
+ return false;
+ }
+ int64_t command_key = 0;
+ int32_t command_idx = -1;
+ size_t vr_cmd_idx = 0;
+ bool vr_command_exist = false;
+ /* Position of data in "select_commands" :
+ field "idcommand" from table "command" = 0
+ field "cmdID" from table "command" = 1
+ field "menuName" from table "command" = 2
+ field "parentID" from table "command" = 3
+ field "position" from table "command" = 4
+ field "value" from table "image" = 5
+ field "imageType" from table "image" = 6
+ field "vrCommand" from table "vrCommandsArray" = 7*/
+ while (select_commands.Next()) {
+ if (command_key != select_commands.GetLongInt(0)) {
+ ++command_idx;
+ saved_app[strings::application_commands][command_idx] =
+ SmartObject(SmartType_Map);
+ SmartObject& so_item =
+ saved_app[strings::application_commands][command_idx];
+ so_item[strings::cmd_id] = select_commands.GetInteger(1);
+ SmartObject menu_params(SmartType_Map);
+ SmartObject cmd_icon(SmartType_Map);
+ if (!(select_commands.IsNull(2))) {
+ menu_params[strings::menu_name] = select_commands.GetString(2);
+ }
+ if (!(select_commands.IsNull(3))) {
+ menu_params[hmi_request::parent_id] = select_commands.GetInteger(3);
+ }
+ if (!(select_commands.IsNull(4))) {
+ menu_params[strings::position] = select_commands.GetInteger(4);
+ }
+ if (!menu_params.empty()) {
+ so_item[strings::menu_params] = menu_params;
+ }
+ if (!(select_commands.IsNull(5))) {
+ cmd_icon[strings::value] = select_commands.GetString(5);
+ }
+ if (!(select_commands.IsNull(6))) {
+ cmd_icon[strings::image_type] = select_commands.GetInteger(6);
+ }
+ if (!cmd_icon.empty()) {
+ so_item[strings::cmd_icon] = cmd_icon;
+ }
+ if (!(select_commands.IsNull(7))) {
+ vr_command_exist = true;
+ so_item[strings::vr_commands] = SmartObject(SmartType_Array);
+ } else {
+ vr_command_exist = false;
+ }
+ vr_cmd_idx = 0;
+ command_key = select_commands.GetLongInt(0);
+ }
+ if (vr_command_exist) {
+ saved_app[strings::application_commands][command_idx]
+ [strings::vr_commands][vr_cmd_idx++] =
+ select_commands.GetString(7);
+ }
+ }
+ LOG4CXX_INFO(logger_, "Commands were restored from DB successfully");
+ return true;
+}
+
+bool ResumptionDataDB::SelectSubscriptionsData(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+ uint32_t count_item = 0;
+ if (!SelectCountFromArray(
+ count_item, kSelectCountSubscriptions, policy_app_id, device_id)) {
+ return false;
+ }
+
+ saved_app[strings::application_subscribtions] = SmartObject(SmartType_Map);
+
+ if (0 == count_item) {
+ LOG4CXX_INFO(logger_, "Application does not contain subscriptions data");
+ return true;
+ }
+ utils::dbms::SQLQuery select_subscriptions(db());
+ if (!PrepareSelectQuery(select_subscriptions,
+ policy_app_id,
+ device_id,
+ kSelectSubscriptions)) {
+ LOG4CXX_WARN(logger_, "Problem with verification select_subscriptions");
+ return false;
+ }
+ SmartObject application_buttons(SmartType_Array);
+ SmartObject application_vehicle_info(SmartType_Array);
+ size_t buttons_idx = 0;
+ size_t vi_idx = 0;
+ /* Position of data in "select_subscriptions" :
+ field "vehicleValue" from table "applicationSubscribtionsArray" = 0
+ field "ButtonNameValue" from table "applicationSubscribtionsArray" = 1*/
+ while (select_subscriptions.Next()) {
+ if (!select_subscriptions.IsNull(0)) {
+ application_vehicle_info[vi_idx++] = select_subscriptions.GetInteger(0);
+ }
+ if (!select_subscriptions.IsNull(1)) {
+ application_buttons[buttons_idx++] = select_subscriptions.GetInteger(1);
+ }
+ }
+ if (!application_buttons.empty()) {
+ saved_app[strings::application_subscribtions]
+ [strings::application_buttons] = application_buttons;
+ }
+
+ if (!application_vehicle_info.empty()) {
+ saved_app[strings::application_subscribtions]
+ [strings::application_vehicle_info] = application_vehicle_info;
+ }
+ LOG4CXX_INFO(logger_, "Subscriptions were restored from DB successfully");
+ return true;
+}
+
+bool ResumptionDataDB::SelectChoiceSetData(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+ uint32_t count_item = 0;
+ if (!SelectCountFromArray(
+ count_item, kSelectCountChoiceSet, policy_app_id, device_id)) {
+ return false;
+ }
+
+ saved_app[strings::application_choice_sets] = SmartObject(SmartType_Array);
+
+ if (0 == count_item) {
+ LOG4CXX_INFO(logger_, "Application does not contain choice set data");
+ return true;
+ }
+ utils::dbms::SQLQuery select_choice_set(db());
+ if (!PrepareSelectQuery(
+ select_choice_set, policy_app_id, device_id, kSelectChoiceSets)) {
+ LOG4CXX_WARN(logger_, "Problem with verification select_choice_set");
+ return false;
+ }
+
+ int64_t application_choice_set_key = 0;
+ int64_t choice_key = 0;
+ int32_t choice_set_idx = -1;
+ int32_t choice_idx = -1;
+ size_t vr_cmd_idx = 0;
+ /* Position of data in "select_choice_set" :
+ field "idapplicationChoiceSet" from table "applicationChoiceSet" = 0
+ field "grammarID" from table "applicationChoiceSet" = 1
+ field "interactionChoiceSetID" from table "applicationChoiceSet" = 2
+ field "idchoice" from table "choice" = 3
+ field "choiceID" from table "choice" = 4
+ field "menuName" from table "choice" = 5
+ field "secondaryText" from table "choice" = 6
+ field "tertiaryText" from table "choice" = 7
+ field "idimage" from table "choice" = 8
+ field "idsecondaryImage" from table "choice" = 9
+ field "vrCommand" from table "vrCommandsArray" = 10*/
+ while (select_choice_set.Next()) {
+ if (application_choice_set_key != select_choice_set.GetLongInt(0)) {
+ ++choice_set_idx;
+ saved_app[strings::application_choice_sets][choice_set_idx] =
+ SmartObject(SmartType_Map);
+ SmartObject& choice_set_item =
+ saved_app[strings::application_choice_sets][choice_set_idx];
+ choice_set_item[strings::grammar_id] = select_choice_set.GetInteger(1);
+ choice_set_item[strings::interaction_choice_set_id] =
+ select_choice_set.GetInteger(2);
+ saved_app[strings::application_choice_sets][choice_set_idx]
+ [strings::choice_set] = SmartObject(SmartType_Array);
+ application_choice_set_key = select_choice_set.GetLongInt(0);
+ choice_idx = -1;
+ }
+ if (choice_key != select_choice_set.GetLongInt(3)) {
+ ++choice_idx;
+ choice_key = select_choice_set.GetLongInt(3);
+
+ saved_app[strings::application_choice_sets][choice_set_idx]
+ [strings::choice_set][choice_idx] = SmartObject(SmartType_Map);
+ SmartObject& choice_item =
+ saved_app[strings::application_choice_sets][choice_set_idx]
+ [strings::choice_set][choice_idx];
+ choice_item[strings::choice_id] = select_choice_set.GetUInteger(4);
+ choice_item[strings::menu_name] = select_choice_set.GetString(5);
+ if (!(select_choice_set.IsNull(6))) {
+ choice_item[strings::secondary_text] = select_choice_set.GetString(6);
+ }
+ if (!(select_choice_set.IsNull(7))) {
+ choice_item[strings::tertiary_text] = select_choice_set.GetString(7);
+ }
+ if (!(select_choice_set.IsNull(8))) {
+ SmartObject image(SmartType_Map);
+ if (!SelectImageData(select_choice_set.GetLongInt(8), image)) {
+ return false;
+ }
+ choice_item[strings::image] = image;
+ }
+ if (!(select_choice_set.IsNull(9))) {
+ SmartObject secondary_image(SmartType_Map);
+ if (!SelectImageData(select_choice_set.GetLongInt(9),
+ secondary_image)) {
+ return false;
+ }
+ choice_item[strings::secondary_image] = secondary_image;
+ }
+ choice_item[strings::vr_commands] = SmartObject(SmartType_Array);
+ vr_cmd_idx = 0;
+ }
+ saved_app[strings::application_choice_sets][choice_set_idx]
+ [strings::choice_set][choice_idx][strings::vr_commands]
+ [vr_cmd_idx++] = select_choice_set.GetString(10);
+ }
+
+ LOG4CXX_INFO(logger_, "Choice sets were restored from DB successfully");
+ return true;
+}
+
+bool ResumptionDataDB::SelectGlobalPropertiesData(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+ uint32_t count_item = 0;
+ if (!SelectCountFromArray(
+ count_item, kSelectCountGlobalProperties, policy_app_id, device_id)) {
+ return false;
+ }
+
+ saved_app[strings::application_global_properties] =
+ SmartObject(SmartType_Map);
+
+ if (0 == count_item) {
+ LOG4CXX_INFO(logger_,
+ "Application does not contain global properties data");
+ return true;
+ }
+ utils::dbms::SQLQuery select_globalproperties(db());
+ if (!PrepareSelectQuery(select_globalproperties,
+ policy_app_id,
+ device_id,
+ kSelectGlobalProperties)) {
+ LOG4CXX_WARN(logger_, "Problem with verification select_globalproperties");
+ return false;
+ }
+ saved_app[strings::application_global_properties] =
+ SmartObject(SmartType_Map);
+ SmartObject& global_properties =
+ saved_app[strings::application_global_properties];
+ SmartObject keyboard_properties(SmartType_Map);
+ SmartObject help_prompt(SmartType_Array);
+ SmartObject timeout_prompt(SmartType_Array);
+ size_t help_prompt_idx = 0;
+ size_t timeout_prompt_idx = 0;
+ int64_t global_properties_key = 0;
+ /* Position of data in "select_globalproperties" :
+ field "idglobalProperties" from table "globalProperties" = 0
+ field "vrHelpTitle" from table "globalProperties" = 1
+ field "menuTitle" from table "globalProperties" = 2
+ field "idmenuIcon" from table "globalProperties" = 3
+ field "language" from table "globalProperties" = 4
+ field "keyboardLayout" from table "globalProperties" = 5
+ field "keypressMode" from table "globalProperties" = 6
+ field "autoCompleteText" from table "globalProperties" = 7
+ field "idhelpPrompt" from table "helpTimeoutPromptArray" = 8
+ field "idtimeoutPrompt" from table "helpTimeoutPromptArray" = 9*/
+ while (select_globalproperties.Next()) {
+ if (global_properties_key != select_globalproperties.GetLongInt(0)) {
+ global_properties_key = select_globalproperties.GetLongInt(0);
+ if (!select_globalproperties.IsNull(1)) {
+ global_properties[strings::vr_help_title] =
+ select_globalproperties.GetString(1);
+ }
+ if (!select_globalproperties.IsNull(2)) {
+ global_properties[strings::menu_title] =
+ select_globalproperties.GetString(2);
+ }
+ if (!select_globalproperties.IsNull(3)) {
+ SmartObject image(SmartType_Map);
+ if (!SelectImageData(select_globalproperties.GetLongInt(3), image)) {
+ return false;
+ }
+ global_properties[strings::menu_icon] = image;
+ }
+ if (!select_globalproperties.IsNull(4)) {
+ keyboard_properties[strings::language] =
+ select_globalproperties.GetInteger(4);
+ }
+ if (!select_globalproperties.IsNull(5)) {
+ keyboard_properties[hmi_request::keyboard_layout] =
+ select_globalproperties.GetInteger(5);
+ }
+ if (!select_globalproperties.IsNull(6)) {
+ keyboard_properties[strings::key_press_mode] =
+ select_globalproperties.GetInteger(6);
+ }
+ if (!select_globalproperties.IsNull(7)) {
+ keyboard_properties[strings::auto_complete_text] =
+ select_globalproperties.GetString(7);
+ }
+ }
+ if (!select_globalproperties.IsNull(8)) {
+ SmartObject tts_chunk(SmartType_Map);
+ if (!SelectTTSChunkData(select_globalproperties.GetLongInt(8),
+ tts_chunk)) {
+ return false;
+ }
+ help_prompt[help_prompt_idx++] = tts_chunk;
+ }
+ if (!select_globalproperties.IsNull(9)) {
+ SmartObject tts_chunk(SmartType_Map);
+ if (!SelectTTSChunkData(select_globalproperties.GetLongInt(9),
+ tts_chunk)) {
+ return false;
+ }
+ timeout_prompt[timeout_prompt_idx++] = tts_chunk;
+ }
+ }
+ if (help_prompt_idx != 0) {
+ global_properties[strings::help_prompt] = help_prompt;
+ }
+ if (timeout_prompt_idx != 0) {
+ global_properties[strings::timeout_prompt] = timeout_prompt;
+ }
+ if (!keyboard_properties.empty()) {
+ global_properties[strings::keyboard_properties] = keyboard_properties;
+ if (!SelectCharactersData(
+ global_properties_key,
+ global_properties[strings::keyboard_properties])) {
+ return false;
+ }
+ }
+ if (!SelectVrHelpItemsData(global_properties_key, global_properties)) {
+ return false;
+ }
+ return true;
+}
+
+bool ResumptionDataDB::SelectVrHelpItemsData(
+ int64_t global_properties_key,
+ smart_objects::SmartObject& global_properties) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+ utils::dbms::SQLQuery checks_vrhelp_item(db());
+ if (!checks_vrhelp_item.Prepare(kChecksVrHelpItem)) {
+ LOG4CXX_WARN(logger_, "Problem with verification checks_vrhelp_item query");
+ return false;
+ }
+ checks_vrhelp_item.Bind(0, global_properties_key);
+ if (!checks_vrhelp_item.Exec()) {
+ LOG4CXX_WARN(logger_, "Problem with execution checks_vrhelp_item query");
+ return false;
+ }
+ if (0 == checks_vrhelp_item.GetInteger(0)) {
+ LOG4CXX_INFO(logger_, "Global properties doesn't contain vr help item");
+ return true;
+ }
+ utils::dbms::SQLQuery select_vrhelp_item(db());
+ if (!select_vrhelp_item.Prepare(kSelectVrHelpItem)) {
+ LOG4CXX_WARN(logger_, "Problem with verification select_vrhelp_item query");
+ return false;
+ }
+ global_properties[strings::vr_help] = SmartObject(SmartType_Array);
+ SmartObject& vr_help_items = global_properties[strings::vr_help];
+ select_vrhelp_item.Bind(0, global_properties_key);
+ size_t vr_help_item_idx = 0;
+ /* Position of data in "select_vrhelp_item" :
+ field "text" from table "vrHelpItem" = 0
+ field "position" from table "vrHelpItem" = 1
+ field "imageType" from table "image" = 2
+ field "value" from table "image" = 3*/
+ while (select_vrhelp_item.Next()) {
+ SmartObject item(SmartType_Map);
+ item[strings::text] = select_vrhelp_item.GetString(0);
+ item[strings::position] = select_vrhelp_item.GetInteger(1);
+ if (!select_vrhelp_item.IsNull(2) && !select_vrhelp_item.IsNull(3)) {
+ SmartObject image(SmartType_Map);
+ image[strings::image_type] = select_vrhelp_item.GetInteger(2);
+ image[strings::value] = select_vrhelp_item.GetString(3);
+ item[strings::image] = image;
+ }
+ vr_help_items[vr_help_item_idx++] = item;
+ }
+ LOG4CXX_INFO(logger_, "VR Help items were restored successfully");
+ return true;
+}
+
+bool ResumptionDataDB::SelectCharactersData(
+ int64_t global_properties_key,
+ smart_objects::SmartObject& keyboard_properties) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+ utils::dbms::SQLQuery checks_characters(db());
+ if (!checks_characters.Prepare(kChecksCharacter)) {
+ LOG4CXX_WARN(logger_, "Problem with verification checks_characters query");
+ return false;
+ }
+ checks_characters.Bind(0, global_properties_key);
+ if (!checks_characters.Exec()) {
+ LOG4CXX_WARN(logger_, "Problem with execution checks_characters query");
+ return false;
+ }
+ if (0 == checks_characters.GetInteger(0)) {
+ LOG4CXX_INFO(
+ logger_,
+ "Keyboard properties doesn't contain table limited character list");
+ return true;
+ }
+ utils::dbms::SQLQuery select_characters(db());
+ if (!select_characters.Prepare(kSelectCharacter)) {
+ LOG4CXX_WARN(logger_, "Problem with verification select_characters query");
+ return false;
+ }
+
+ keyboard_properties[strings::limited_character_list] =
+ SmartObject(SmartType_Array);
+ SmartObject& characters =
+ keyboard_properties[strings::limited_character_list];
+ select_characters.Bind(0, global_properties_key);
+ size_t characters_idx = 0;
+ /* Position of data in "select_characters" :
+ field "limitedCharacterList" from table "tableLimitedCharacterList" = 0*/
+ while (select_characters.Next()) {
+ characters[characters_idx++] = select_characters.GetString(0);
+ }
+ return true;
+}
+
+bool ResumptionDataDB::SelectImageData(
+ int64_t image_key, smart_objects::SmartObject& image) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ utils::dbms::SQLQuery select_image(db());
+
+ if (!select_image.Prepare(kSelectImage)) {
+ LOG4CXX_WARN(logger_, "Problem with verification select_image query");
+ return false;
+ }
+ select_image.Bind(0, image_key);
+ if (!select_image.Exec()) {
+ LOG4CXX_WARN(logger_, "Problem with execution select_image query");
+ return false;
+ }
+ /* Position of data in "select_image" :
+ field "imageType" from table "image" = 0
+ field "value" from table "image" = 1*/
+ image[strings::image_type] = select_image.GetInteger(0);
+ image[strings::value] = select_image.GetString(1);
+ return true;
+}
+
+bool ResumptionDataDB::SelectTTSChunkData(
+ int64_t tts_chunk_key, smart_objects::SmartObject& tts_chunk) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ utils::dbms::SQLQuery select_tts_chunk(db());
+
+ if (!select_tts_chunk.Prepare(kSelectTTSChunk)) {
+ LOG4CXX_WARN(logger_, "Problem with verification select_tts_chunk query");
+ return false;
+ }
+ select_tts_chunk.Bind(0, tts_chunk_key);
+ if (!select_tts_chunk.Exec()) {
+ LOG4CXX_WARN(logger_, "Problem with execution select_tts_chunk query");
+ return false;
+ }
+ /* Position of data in "select_tts_chunk" :
+ field "text" from table "TTSChunk" = 0
+ field "type" from table "TTSChunk" = 1*/
+ tts_chunk[strings::text] = select_tts_chunk.GetString(0);
+ tts_chunk[strings::type] = select_tts_chunk.GetInteger(1);
+ return true;
+}
+
+bool ResumptionDataDB::SelectDataFromAppTable(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(kSelectAppTable)) {
+ LOG4CXX_WARN(logger_, "Problem with verification kSelectAppTable query");
+ return false;
+ }
+ query.Bind(0, policy_app_id);
+ query.Bind(1, device_id);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Problem with execution kSelectAppTable query");
+ return false;
+ }
+
+ // Position of data in "query" :
+ // field "appID" from table "application" = 0
+ // field "connection_key" from table "application" = 1
+ // field "grammarID" from table "application" = 2
+ // field "hashID" from table "application" = 3
+ // field "hmiAppID" from table "application" = 4
+ // field "hmiLevel" from table "application" = 5
+ // field "ign_off_count" from table "application" = 6
+ // field "timeStamp" from table "application" = 7
+ // field "deviceID" from table "application" = 8
+ // field "isMediaApplication" from table "application" = 9
+ // field "IsSubscribedForWayPoints" from table "application" = 10
+ uint32_t connection_key = query.GetUInteger(1);
+
+ saved_app[strings::app_id] = query.GetString(0);
+ saved_app[strings::connection_key] = connection_key;
+ uint32_t grammarID = query.GetUInteger(2);
+ if (grammarID) {
+ saved_app[strings::grammar_id] = grammarID;
+ }
+ saved_app[strings::hash_id] = query.GetString(3);
+ saved_app[strings::hmi_app_id] = query.GetUInteger(4);
+ saved_app[strings::hmi_level] = query.GetInteger(5);
+ saved_app[strings::ign_off_count] = query.GetInteger(6);
+ saved_app[strings::time_stamp] = query.GetUInteger(7);
+ saved_app[strings::device_id] = query.GetString(8);
+ saved_app[strings::is_media_application] = query.GetBoolean(9);
+ saved_app[strings::subscribed_for_way_points] = query.GetBoolean(10);
+
+ LOG4CXX_INFO(logger_,
+ "Data from application table was restored successfully");
+ return true;
+}
+
+bool ResumptionDataDB::SelectCountFromArray(
+ uint32_t& count_item,
+ const std::string& text_query,
+ const std::string& policy_app_id,
+ const std::string& device_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(text_query)) {
+ LOG4CXX_WARN(logger_, "Problem with verification query");
+ return false;
+ }
+ query.Bind(0, policy_app_id);
+ query.Bind(1, device_id);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Problem with execution query");
+ return false;
+ }
+ count_item = query.GetInteger(0);
+ LOG4CXX_INFO(logger_, "count_item=" << count_item);
+ return true;
+}
+
+bool ResumptionDataDB::DeleteSavedApplication(const std::string& policy_app_id,
+ const std::string& device_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ utils::ScopeGuard guard =
+ utils::MakeObjGuard(*db_, &utils::dbms::SQLDatabase::RollbackTransaction);
+
+ db_->BeginTransaction();
+ if (!DeleteSavedFiles(policy_app_id, device_id)) {
+ return false;
+ }
+ if (!DeleteSavedSubMenu(policy_app_id, device_id)) {
+ return false;
+ }
+ if (!DeleteSavedSubscriptions(policy_app_id, device_id)) {
+ return false;
+ }
+ if (!DeleteSavedCommands(policy_app_id, device_id)) {
+ return false;
+ }
+ if (!DeleteSavedChoiceSet(policy_app_id, device_id)) {
+ return false;
+ }
+ if (!DeleteSavedGlobalProperties(policy_app_id, device_id)) {
+ return false;
+ }
+ if (!DeleteDataFromApplicationTable(policy_app_id, device_id)) {
+ return false;
+ }
+ db_->CommitTransaction();
+
+ guard.Dismiss();
+ return true;
+}
+
+bool ResumptionDataDB::DeleteSavedFiles(const std::string& policy_app_id,
+ const std::string& device_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!ExecQueryToDeleteData(policy_app_id, device_id, kDeleteFile)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from file.");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(
+ policy_app_id, device_id, kDeleteApplicationFilesArray)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from applicationFilesArray.");
+ return false;
+ }
+ return true;
+}
+
+bool ResumptionDataDB::DeleteSavedSubMenu(const std::string& policy_app_id,
+ const std::string& device_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (!ExecQueryToDeleteData(policy_app_id, device_id, kDeleteSubMenu)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from subMenu.");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(
+ policy_app_id, device_id, kDeleteApplicationSubMenuArray)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from applicationSubMenuArray.");
+ return false;
+ }
+ return true;
+}
+
+bool ResumptionDataDB::DeleteSavedSubscriptions(
+ const std::string& policy_app_id, const std::string& device_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (!ExecQueryToDeleteData(
+ policy_app_id, device_id, kDeleteApplicationSubscribtionsArray)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect delete from applicationSubscribtionsArray.");
+ return false;
+ }
+ return true;
+}
+
+bool ResumptionDataDB::DeleteSavedCommands(const std::string& policy_app_id,
+ const std::string& device_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (!ExecQueryToDeleteData(
+ policy_app_id, device_id, kDeleteImageFromCommands)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete image from commands.");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(policy_app_id, device_id, kDeleteVrCommands)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete vrcommands from commands.");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(policy_app_id, device_id, kDeleteCommands)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete commands.");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(
+ policy_app_id, device_id, kDeleteApplicationCommandsArray)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete applicationCommandsArray.");
+ return false;
+ }
+
+ return true;
+}
+
+bool ResumptionDataDB::DeleteSavedChoiceSet(const std::string& policy_app_id,
+ const std::string& device_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (!ExecUnionQueryToDeleteData(
+ policy_app_id, device_id, kDeleteImageFromChoiceSet)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete image from choice set");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(
+ policy_app_id, device_id, kDeleteVrCommandsFromChoiceSet)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete vrCommands from choice set");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(policy_app_id, device_id, kDeleteChoice)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete choiceSet");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(policy_app_id, device_id, kDeleteChoiceArray)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from choiceArray");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(
+ policy_app_id, device_id, kDeleteApplicationChoiceSet)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete applicationChoiceSet");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(
+ policy_app_id, device_id, kDeleteApplicationChoiceSetArray)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from ApplicationChoiceSetArray");
+ return false;
+ }
+
+ return true;
+}
+
+bool ResumptionDataDB::DeleteSavedGlobalProperties(
+ const std::string& policy_app_id, const std::string& device_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (!ExecUnionQueryToDeleteData(
+ policy_app_id, device_id, kDeleteImageFromGlobalProperties)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete image from globalProperties");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(policy_app_id, device_id, kDeletevrHelpItem)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete vrHelpItem");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(
+ policy_app_id, device_id, kDeletevrHelpItemArray)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete vrHelpItemArray");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(
+ policy_app_id, device_id, kDeleteTableLimitedCharacterList)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from tableLimitedCharacterList");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(policy_app_id, device_id, kDeleteCharacterArray)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from characterArray");
+ return false;
+ }
+
+ if (!ExecUnionQueryToDeleteData(policy_app_id, device_id, kDeleteTTSChunk)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from TTSChunk");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(
+ policy_app_id, device_id, kDeleteHelpTimeoutPromptArray)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from HelpTimeoutPromptArray");
+ return false;
+ }
+
+ if (!ExecQueryToDeleteData(
+ policy_app_id, device_id, kDeleteGlobalProperties)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from GlobalProperties");
+ return false;
+ }
+
+ return true;
+}
+
+bool ResumptionDataDB::DeleteDataFromApplicationTable(
+ const std::string& policy_app_id, const std::string& device_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (!ExecQueryToDeleteData(
+ policy_app_id, device_id, kDeleteFromApplicationTable)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete data from application table");
+ return false;
+ }
+
+ return true;
+}
+
+bool ResumptionDataDB::ExecQueryToDeleteData(const std::string& policy_app_id,
+ const std::string& device_id,
+ const std::string& text_query) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ bool result = query.Prepare(text_query);
+ if (result) {
+ query.Bind(0, policy_app_id);
+ query.Bind(1, device_id);
+ result = query.Exec();
+ }
+ return result;
+}
+
+bool ResumptionDataDB::ExecUnionQueryToDeleteData(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ const std::string& text_query) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ bool result = query.Prepare(text_query);
+ if (result) {
+ query.Bind(0, policy_app_id);
+ query.Bind(1, device_id);
+ query.Bind(2, policy_app_id);
+ query.Bind(3, device_id);
+ result = query.Exec();
+ }
+ return result;
+}
+
+bool ResumptionDataDB::ExecInsertImage(
+ int64_t& image_primary_key, const smart_objects::SmartObject& image) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ utils::dbms::SQLQuery count_image_query(db());
+ utils::dbms::SQLQuery query(db());
+ uint16_t count_image = 0;
+ bool result = count_image_query.Prepare(kSelectCountImage);
+ if (result) {
+ count_image_query.Bind(0, image[strings::value].asString());
+ result = count_image_query.Exec();
+ if (result) {
+ count_image = count_image_query.GetInteger(0);
+ }
+ }
+ if (!result) {
+ LOG4CXX_WARN(logger_,
+ "Problem with preparing or execution count_image_query.");
+ return false;
+ }
+ if (count_image) {
+ result = query.Prepare(kSelectPrimaryKeyImage);
+ if (result) {
+ query.Bind(0, image[strings::value].asString());
+ result = query.Exec();
+ if (result) {
+ image_primary_key = query.GetLongInt(0);
+ }
+ }
+ if (!result) {
+ LOG4CXX_WARN(logger_,
+ "Problem with preparing or execution "
+ "query for select primary key of image");
+ }
+ } else {
+ result = query.Prepare(kInsertImage);
+ if (result) {
+ query.Bind(0, image[strings::image_type].asInt());
+ query.Bind(1, image[strings::value].asString());
+ result = query.Exec();
+ if (result) {
+ image_primary_key = query.LastInsertId();
+ }
+ }
+ if (!result) {
+ LOG4CXX_WARN(logger_,
+ "Problem with preparing or execution "
+ "query for insert image to image table");
+ }
+ }
+ return result;
+}
+
+bool ResumptionDataDB::ExecInsertChoice(
+ int64_t choice_set_key,
+ const smart_objects::SmartObject& choice_array) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ utils::dbms::SQLQuery insert_choice(db());
+
+ if (!insert_choice.Prepare(kInsertChoice)) {
+ LOG4CXX_WARN(logger_, "Incorrect preparation insert_choice query");
+ return false;
+ }
+ /* Positions of binding data for "insert_choice":
+ field "choiceID" from table "choice" = 0
+ field "menuName" from table "choice" = 1
+ field "secondaryText" from table "choice" = 2
+ field "tertiaryText" from table "choice" = 3
+ field "idimage" from table "choice" = 4
+ field "idsecondaryImage" from table "choice" = 5*/
+ int64_t image_primary_key = 0;
+ int64_t choice_primary_key = 0;
+ size_t length_choice_array = choice_array.length();
+ for (size_t i = 0; i < length_choice_array; ++i) {
+ insert_choice.Bind(0, (choice_array[i][strings::choice_id]).asInt());
+ insert_choice.Bind(1, (choice_array[i][strings::menu_name]).asString());
+
+ CustomBind(strings::secondary_text, choice_array[i], insert_choice, 2);
+ CustomBind(strings::tertiary_text, choice_array[i], insert_choice, 3);
+
+ if (choice_array[i].keyExists(strings::image)) {
+ if (!ExecInsertImage(image_primary_key,
+ choice_array[i][strings::image])) {
+ LOG4CXX_WARN(logger_, "Problem with insert image to choice");
+ return false;
+ }
+ insert_choice.Bind(4, image_primary_key);
+ } else {
+ insert_choice.Bind(4);
+ }
+ if (choice_array[i].keyExists(strings::secondary_image)) {
+ if (!ExecInsertImage(image_primary_key,
+ choice_array[i][strings::secondary_image])) {
+ LOG4CXX_WARN(logger_, "Problem with insert secondary_image to choice");
+ return false;
+ }
+ insert_choice.Bind(5, image_primary_key);
+ } else {
+ insert_choice.Bind(5);
+ }
+ if (!insert_choice.Exec()) {
+ LOG4CXX_WARN(logger_, "Problem with execution insert_choice query");
+ return false;
+ }
+ choice_primary_key = insert_choice.LastInsertId();
+
+ if ((!ExecInsertVrCommands(choice_primary_key,
+ choice_array[i][strings::vr_commands],
+ kVRCommandFromChoice)) ||
+ !insert_choice.Reset()) {
+ LOG4CXX_WARN(logger_, "problemm with add vr commands to choice");
+ return false;
+ }
+
+ if (!ExecInsertDataToArray(
+ choice_set_key, choice_primary_key, kInsertChoiceArray)) {
+ LOG4CXX_INFO(logger_, "Problem with insertion data to choiceArray table");
+ return false;
+ }
+ }
+ LOG4CXX_INFO(logger_, "Choice data were saved to DB successfully");
+ return true;
+}
+
+bool ResumptionDataDB::ExecInsertVrCommands(
+ const int64_t primary_key,
+ const smart_objects::SmartObject& vr_commands_array,
+ AccessoryVRCommand value) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery insert_vr_command(db());
+
+ if (!insert_vr_command.Prepare(kInsertVrCommand)) {
+ LOG4CXX_WARN(logger_, "Incorrect preparation insert_vr_command query");
+ return false;
+ }
+ size_t length_vr_commands = vr_commands_array.length();
+
+ /* Positions of binding data for "insert_vr_command":
+ field "vrCommand" from table "vrCommandsArray" = 0
+ field "idcommand" from table "vrCommandsArray" = 1
+ field "idchoice" from table "vrCommandsArray" = 2*/
+ for (size_t i = 0; i < length_vr_commands; ++i) {
+ insert_vr_command.Bind(0, vr_commands_array[i].asString());
+ if (AccessoryVRCommand::kVRCommandFromCommand == value) {
+ insert_vr_command.Bind(1, primary_key);
+ insert_vr_command.Bind(2);
+ } else if (AccessoryVRCommand::kVRCommandFromChoice == value) {
+ insert_vr_command.Bind(1);
+ insert_vr_command.Bind(2, primary_key);
+ }
+ if (!insert_vr_command.Exec() || !insert_vr_command.Reset()) {
+ LOG4CXX_WARN(logger_, "Problem with insert vr_command to DB");
+ return false;
+ }
+ }
+ LOG4CXX_INFO(logger_, "Insertion of Vr command were executed successfully");
+ return true;
+}
+
+bool ResumptionDataDB::ExecInsertDataToArray(
+ int64_t first_primary_key,
+ int64_t second_primary_key,
+ const std::string& text_query) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ bool result;
+ utils::dbms::SQLQuery query_insert_array(db());
+ result = query_insert_array.Prepare(text_query);
+ if (result) {
+ query_insert_array.Bind(0, first_primary_key);
+ query_insert_array.Bind(1, second_primary_key);
+ result = query_insert_array.Exec();
+ }
+ return result;
+}
+
+bool ResumptionDataDB::SaveApplicationToDB(
+ app_mngr::ApplicationSharedPtr application,
+ const std::string& policy_app_id,
+ const std::string& device_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ int64_t application_primary_key = 0;
+ int64_t global_properties_key = 0;
+ db_->BeginTransaction();
+ if (!InsertGlobalPropertiesData(GetApplicationGlobalProperties(application),
+ global_properties_key)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert globalProperties data to DB.");
+ db_->RollbackTransaction();
+ return false;
+ }
+ ApplicationParams app(application);
+ if (!InsertApplicationData(app,
+ policy_app_id,
+ device_id,
+ &application_primary_key,
+ global_properties_key)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert application data to DB.");
+ db_->RollbackTransaction();
+ return false;
+ }
+ if (!InsertFilesData(GetApplicationFiles(application),
+ application_primary_key)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert file data to DB.");
+ db_->RollbackTransaction();
+ return false;
+ }
+
+ if (!InsertSubMenuData(GetApplicationSubMenus(application),
+ application_primary_key)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert submenu data to DB.");
+ db_->RollbackTransaction();
+ return false;
+ }
+ if (!InsertCommandsData(GetApplicationCommands(application),
+ application_primary_key)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert commands data to DB.");
+ db_->RollbackTransaction();
+ return false;
+ }
+ if (!InsertSubscriptionsData(GetApplicationSubscriptions(application),
+ application_primary_key)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert subscribtions data to DB.");
+ db_->RollbackTransaction();
+ return false;
+ }
+ if (!InsertChoiceSetData(GetApplicationInteractionChoiseSets(application),
+ application_primary_key)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert choiceset data to DB.");
+ db_->RollbackTransaction();
+ return false;
+ }
+ db_->CommitTransaction();
+ return true;
+}
+
+bool ResumptionDataDB::SaveApplicationToDB(
+ const smart_objects::SmartObject& application,
+ const std::string& policy_app_id,
+ const std::string& device_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ int64_t application_primary_key = 0;
+ int64_t global_properties_key = 0;
+ db_->BeginTransaction();
+ if (!InsertGlobalPropertiesData(application["globalProperties"],
+ global_properties_key)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert globalProperties data to DB.");
+ db_->RollbackTransaction();
+ return false;
+ }
+ if (!InsertApplicationData(application,
+ policy_app_id,
+ device_id,
+ &application_primary_key,
+ global_properties_key)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert application data to DB.");
+ db_->RollbackTransaction();
+ return false;
+ }
+ if (!InsertFilesData(application["applicationFiles"],
+ application_primary_key)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert file data to DB.");
+ db_->RollbackTransaction();
+ return false;
+ }
+
+ if (!InsertSubMenuData(application["applicationSubMenus"],
+ application_primary_key)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert submenu data to DB.");
+ db_->RollbackTransaction();
+ return false;
+ }
+ if (!InsertCommandsData(application["applicationCommands"],
+ application_primary_key)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert commands data to DB.");
+ db_->RollbackTransaction();
+ return false;
+ }
+ if (!InsertSubscriptionsData(application["subscribtions"],
+ application_primary_key)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert subscribtions data to DB.");
+ db_->RollbackTransaction();
+ return false;
+ }
+ if (!InsertChoiceSetData(application["applicationChoiceSets"],
+ application_primary_key)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert choiceset data to DB.");
+ db_->RollbackTransaction();
+ return false;
+ }
+ db_->CommitTransaction();
+ return true;
+}
+
+bool ResumptionDataDB::InsertFilesData(const smart_objects::SmartObject& files,
+ int64_t application_primary_key) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+ const size_t length_files_array = files.length();
+ if (0 == length_files_array) {
+ LOG4CXX_INFO(logger_, "Application doesn't contain files");
+ return true;
+ }
+
+ utils::dbms::SQLQuery query_insert_file(db());
+
+ if (!query_insert_file.Prepare(kInsertToFile)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with verification queries for insertion files");
+ return false;
+ }
+ /* Positions of binding data for "query_insert_file":
+ field "fileType" from table "file" = 0
+ field "is_download_complete" from table "file" = 1
+ field "persistentFile" from table "file" = 2
+ field "syncFileName" from table "file" = 3*/
+ for (size_t i = 0; i < length_files_array; ++i) {
+ query_insert_file.Bind(0, (files[i][strings::file_type]).asInt());
+ query_insert_file.Bind(1,
+ (files[i][strings::is_download_complete]).asBool());
+ query_insert_file.Bind(2, (files[i][strings::persistent_file]).asBool());
+ query_insert_file.Bind(3, (files[i][strings::sync_file_name]).asString());
+
+ if (!query_insert_file.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect insertion of files data");
+ return false;
+ }
+
+ if ((!ExecInsertDataToArray(application_primary_key,
+ query_insert_file.LastInsertId(),
+ kInsertToApplicationFilesArray)) ||
+ !query_insert_file.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insertion to application files array");
+ return false;
+ }
+ }
+
+ LOG4CXX_INFO(logger_, "Files data were inserted successfully to DB");
+ return true;
+}
+
+bool ResumptionDataDB::InsertSubMenuData(
+ const smart_objects::SmartObject& submenus,
+ int64_t application_primary_key) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+ const size_t length_submenu_array = submenus.length();
+ if (0 == length_submenu_array) {
+ LOG4CXX_INFO(logger_, "Application doesn't contain submenu");
+ return true;
+ }
+ utils::dbms::SQLQuery query_insert_submenu(db());
+
+ if (!query_insert_submenu.Prepare(kInsertToSubMenu)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with verification queries for insertion submenu");
+ return false;
+ }
+ /* Positions of binding data for "query_insert_submenu":
+ field "menuID" from table "submenu" = 0
+ field "menuName" from table "submenu" = 1
+ field "position" from table "submenu" = 2*/
+ for (size_t i = 0; i < length_submenu_array; ++i) {
+ query_insert_submenu.Bind(0, (submenus[i][strings::menu_id]).asInt());
+ query_insert_submenu.Bind(1, (submenus[i][strings::menu_name]).asString());
+ CustomBind(strings::position, submenus[i], query_insert_submenu, 2);
+
+ if (!query_insert_submenu.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect insertion of submenu data");
+ return false;
+ }
+
+ if ((!ExecInsertDataToArray(application_primary_key,
+ query_insert_submenu.LastInsertId(),
+ kInsertToApplicationSubMenuArray)) ||
+ !query_insert_submenu.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insertion to application submenu array");
+ return false;
+ }
+ }
+
+ LOG4CXX_INFO(logger_, "Data about submenu were inserted successfully to DB");
+ return true;
+}
+
+bool ResumptionDataDB::InsertCommandsData(
+ const smart_objects::SmartObject& commands,
+ int64_t application_primary_key) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+ const size_t length_command_array = commands.length();
+ if (0 == length_command_array) {
+ LOG4CXX_INFO(logger_, "Application doesn't contain command");
+ return true;
+ }
+ utils::dbms::SQLQuery query_insert_command(db());
+ int64_t image_primary_key = 0;
+ int64_t command_primary_key = 0;
+
+ if (!query_insert_command.Prepare(kInsertToCommand)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with verification queries for insertion commands");
+ return false;
+ }
+ /* Positions of binding data for "query_insert_command":
+ field "cmdID" from table "command" = 0
+ field "idimage" from table "command" = 1
+ field "menuName" from table "command" = 2
+ field "parentID" from table "command" = 3
+ field "position" from table "command" = 4*/
+ for (size_t i = 0; i < length_command_array; ++i) {
+ query_insert_command.Bind(0, commands[i][strings::cmd_id].asInt());
+ if (commands[i].keyExists(strings::cmd_icon)) {
+ if (!ExecInsertImage(image_primary_key, commands[i][strings::cmd_icon])) {
+ LOG4CXX_WARN(logger_, "Problem with insert command image to DB");
+ return false;
+ }
+ query_insert_command.Bind(1, image_primary_key);
+ } else {
+ query_insert_command.Bind(1);
+ }
+
+ if (commands[i].keyExists(strings::menu_params)) {
+ const SmartObject& menu_params = commands[i][strings::menu_params];
+ query_insert_command.Bind(2, menu_params[strings::menu_name].asString());
+
+ CustomBind(hmi_request::parent_id, menu_params, query_insert_command, 3);
+ CustomBind(strings::position, menu_params, query_insert_command, 4);
+ } else {
+ query_insert_command.Bind(2);
+ query_insert_command.Bind(3);
+ query_insert_command.Bind(4);
+ }
+ if (!query_insert_command.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect insertion of command data to DB");
+ return false;
+ }
+ command_primary_key = query_insert_command.LastInsertId();
+ if (commands[i].keyExists(strings::vr_commands)) {
+ if (!ExecInsertVrCommands(command_primary_key,
+ commands[i][strings::vr_commands],
+ kVRCommandFromCommand)) {
+ return false;
+ }
+ }
+ if ((!ExecInsertDataToArray(application_primary_key,
+ command_primary_key,
+ kInsertApplicationCommandArray)) ||
+ !query_insert_command.Reset()) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect insertion to application commands array");
+ return false;
+ }
+ }
+ return true;
+}
+
+bool ResumptionDataDB::InsertSubscriptionsData(
+ const smart_objects::SmartObject& subscriptions,
+ int64_t application_primary_key) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+
+ if (subscriptions.empty()) {
+ LOG4CXX_INFO(logger_, "Application doesn't contain subscriptions");
+ return true;
+ }
+ const SmartObject& btn_sub = subscriptions[strings::application_buttons];
+ const SmartObject& vi_sub = subscriptions[strings::application_vehicle_info];
+ size_t btn_sub_length = btn_sub.length();
+ size_t vi_sub_length = vi_sub.length();
+ size_t max_length =
+ (btn_sub_length > vi_sub_length) ? btn_sub_length : vi_sub_length;
+
+ utils::dbms::SQLQuery insert_subscriptions(db());
+ if (!insert_subscriptions.Prepare(kInsertSubscriptions)) {
+ LOG4CXX_WARN(
+ logger_,
+ "Problem with verification queries for insertion subscriptions");
+ return false;
+ }
+ /* Positions of binding data for "insert_subscriptions":
+ field "idApplication" from table "applicationSubscribtionsArray" = 0
+ field "vehicleValue" from table "applicationSubscribtionsArray" = 1
+ field "ButtonNameValue" from table "applicationSubscribtionsArray" = 2*/
+ for (size_t i = 0; i < max_length; ++i) {
+ insert_subscriptions.Bind(0, application_primary_key);
+ if (i < vi_sub_length) {
+ insert_subscriptions.Bind(1, vi_sub[i].asInt());
+ } else {
+ insert_subscriptions.Bind(1);
+ }
+ if (i < btn_sub_length) {
+ insert_subscriptions.Bind(2, btn_sub[i].asInt());
+ } else {
+ insert_subscriptions.Bind(2);
+ }
+ if (!insert_subscriptions.Exec() || !insert_subscriptions.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insertion of buttons to subscriptions");
+ return false;
+ }
+ }
+ LOG4CXX_INFO(logger_, "Subscriptions data were saved successfully");
+ return true;
+}
+
+bool ResumptionDataDB::InsertChoiceSetData(
+ const smart_objects::SmartObject& choicesets,
+ int64_t application_primary_key) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+
+ if (choicesets.empty()) {
+ LOG4CXX_INFO(logger_, "Application doesn't contain choiceSet");
+ return true;
+ }
+ int64_t choice_set_key = 0;
+ size_t length_choceset_array = choicesets.length();
+ for (size_t i = 0; i < length_choceset_array; ++i) {
+ if (!ExecInsertApplicationChoiceSet(choice_set_key, choicesets[i])) {
+ return false;
+ }
+
+ if (!ExecInsertChoice(choice_set_key, choicesets[i][strings::choice_set])) {
+ return false;
+ }
+
+ if (!ExecInsertDataToArray(choice_set_key,
+ application_primary_key,
+ kInsertApplicationChoiceSetArray)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with insertion data to"
+ " applicationChoiceSetArray table");
+ return false;
+ }
+ }
+ LOG4CXX_INFO(logger_, "Choice set data were saved to DB successfully");
+ return true;
+}
+
+bool ResumptionDataDB::ExecInsertApplicationChoiceSet(
+ int64_t& choice_set_primary_key,
+ const smart_objects::SmartObject& choiceset) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+
+ utils::dbms::SQLQuery insert_application_choice_set(db());
+ if (!insert_application_choice_set.Prepare(kInsertApplicationChoiceSet)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with preparation insert "
+ "application choice set query");
+ return false;
+ }
+ /* Positions of binding data for "insert_application_choice_set":
+ field "grammarID" from table "applicationChoiceSet" = 0
+ field "interactionChoiceSetID" from table "applicationChoiceSet" = 1*/
+ insert_application_choice_set.Bind(
+ 0, static_cast<int64_t>(choiceset[strings::grammar_id].asUInt()));
+ insert_application_choice_set.Bind(
+ 1, choiceset[strings::interaction_choice_set_id].asInt());
+
+ if (!insert_application_choice_set.Exec()) {
+ LOG4CXX_WARN(logger_,
+ "Problem with execution insert application choice set query");
+ return false;
+ }
+ choice_set_primary_key = insert_application_choice_set.LastInsertId();
+ LOG4CXX_INFO(logger_, "Application choice data were saved successfully");
+ return true;
+}
+
+bool ResumptionDataDB::InsertGlobalPropertiesData(
+ const smart_objects::SmartObject& global_properties,
+ int64_t& global_properties_key) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+ SmartMap::iterator it_begin = global_properties.map_begin();
+ SmartMap::iterator it_end = global_properties.map_end();
+ bool data_exists = false;
+ while (it_begin != it_end) {
+ if (SmartType::SmartType_Null != ((it_begin->second).getType())) {
+ LOG4CXX_INFO(logger_, "Global properties contains - " << it_begin->first);
+ data_exists = true;
+ break;
+ }
+ ++it_begin;
+ }
+ if (!data_exists) {
+ LOG4CXX_INFO(logger_, "Application doesn't contain global properties");
+ return true;
+ }
+
+ utils::dbms::SQLQuery insert_global_properties(db());
+ if (!insert_global_properties.Prepare(kInsertGlobalProperties)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with preparation query "
+ "insert_global_properties");
+ return false;
+ }
+ /* Positions of binding data for "insert_global_properties":
+ field "vrHelpTitle" from table "globalProperties" = 0
+ field "menuTitle" from table "globalProperties" = 1
+ field "idmenuIcon" from table "globalProperties" = 2
+ field "language" from table "globalProperties" = 3
+ field "keyboardLayout" from table "globalProperties" = 4
+ field "keypressMode" from table "globalProperties" = 5
+ field "autoCompleteText" from table "globalProperties" = 6*/
+
+ CustomBind(
+ strings::vr_help_title, global_properties, insert_global_properties, 0);
+ CustomBind(
+ strings::menu_title, global_properties, insert_global_properties, 1);
+
+ if (SmartType::SmartType_Null ==
+ global_properties[strings::menu_icon].getType()) {
+ insert_global_properties.Bind(2);
+ } else {
+ int64_t image_key = 0;
+ if (ExecInsertImage(image_key, global_properties[strings::menu_icon])) {
+ insert_global_properties.Bind(2, image_key);
+ } else {
+ LOG4CXX_WARN(logger_, "Problem with insert image to global properties");
+ return false;
+ }
+ }
+
+ if (SmartType::SmartType_Null ==
+ global_properties[strings::keyboard_properties].getType()) {
+ insert_global_properties.Bind(3);
+ insert_global_properties.Bind(4);
+ insert_global_properties.Bind(5);
+ insert_global_properties.Bind(6);
+ } else {
+ const SmartObject& kb_prop =
+ global_properties[strings::keyboard_properties];
+
+ CustomBind(strings::language, kb_prop, insert_global_properties, 3);
+ CustomBind(
+ hmi_request::keyboard_layout, kb_prop, insert_global_properties, 4);
+ CustomBind(strings::key_press_mode, kb_prop, insert_global_properties, 5);
+ CustomBind(
+ strings::auto_complete_text, kb_prop, insert_global_properties, 6);
+ }
+ if (!insert_global_properties.Exec()) {
+ LOG4CXX_WARN(logger_,
+ "Problem with insert data to global properties table");
+ return false;
+ }
+
+ global_properties_key = insert_global_properties.LastInsertId();
+ if ((SmartType::SmartType_Null !=
+ global_properties[strings::keyboard_properties].getType()) &&
+ (global_properties[strings::keyboard_properties].keyExists(
+ strings::limited_character_list))) {
+ if (!ExecInsertLimitedCharacters(
+ global_properties_key,
+ global_properties[strings::keyboard_properties]
+ [strings::limited_character_list])) {
+ LOG4CXX_WARN(logger_,
+ "Problem with insert data to limited_character table");
+ return false;
+ }
+ }
+
+ if (SmartType::SmartType_Null !=
+ global_properties[strings::vr_help].getType()) {
+ if (!ExecInsertVRHelpItem(global_properties_key,
+ global_properties[strings::vr_help])) {
+ LOG4CXX_WARN(logger_, "Problem with insert data to vrHelpItem table");
+ return false;
+ }
+ }
+
+ if (!ExecInsertHelpTimeoutArray(global_properties, global_properties_key)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with insert data to HelpTimeoutPromptArray table");
+ return false;
+ }
+
+ LOG4CXX_INFO(logger_, "Global properties data were saved successfully");
+ return true;
+}
+
+bool ResumptionDataDB::ExecInsertHelpTimeoutArray(
+ const smart_objects::SmartObject& global_properties,
+ int64_t global_properties_key) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ using namespace smart_objects;
+ size_t timeout_prompt_length = 0;
+ size_t help_prompt_length = 0;
+
+ if (SmartType::SmartType_Null !=
+ global_properties[strings::help_prompt].getType()) {
+ help_prompt_length = global_properties[strings::help_prompt].length();
+ }
+
+ if (SmartType::SmartType_Null !=
+ global_properties[strings::timeout_prompt].getType()) {
+ timeout_prompt_length = global_properties[strings::timeout_prompt].length();
+ }
+ if (0 == timeout_prompt_length && 0 == help_prompt_length) {
+ LOG4CXX_INFO(logger_,
+ "Application doesn't HelpPrompt and timoutPrompt data");
+ return true;
+ }
+
+ utils::dbms::SQLQuery insert_help_prompt_array(db());
+
+ if (!insert_help_prompt_array.Prepare(kInsertHelpTimeoutPromptArray)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with verification query insert_help_prompt_array");
+ return false;
+ }
+ int64_t tts_chunk_key = 0;
+
+ size_t max_length = (timeout_prompt_length > help_prompt_length)
+ ? timeout_prompt_length
+ : help_prompt_length;
+ /* Positions of binding data for "insert_help_prompt_array":
+ field "idglobalProperties" from table "helpTimeoutPromptArray" = 0
+ field "idtimeoutPrompt" from table "helpTimeoutPromptArray" = 1
+ field "idhelpPrompt" from table "helpTimeoutPromptArray" = 2*/
+ for (size_t i = 0; i < max_length; ++i) {
+ insert_help_prompt_array.Bind(0, global_properties_key);
+ if (i < timeout_prompt_length) {
+ if (!ExecInsertTTSChunks(global_properties[strings::timeout_prompt][i],
+ tts_chunk_key)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with insertion timeoutPrompt's ttsChunk");
+ return false;
+ }
+ insert_help_prompt_array.Bind(1, tts_chunk_key);
+ } else {
+ insert_help_prompt_array.Bind(1);
+ }
+
+ if (i < help_prompt_length) {
+ if (!ExecInsertTTSChunks(global_properties[strings::help_prompt][i],
+ tts_chunk_key)) {
+ LOG4CXX_WARN(logger_, "Problem with insertion helpPrompt's ttsChunk");
+ return false;
+ }
+ insert_help_prompt_array.Bind(2, tts_chunk_key);
+ } else {
+ insert_help_prompt_array.Bind(2);
+ }
+ if (!insert_help_prompt_array.Exec() || !insert_help_prompt_array.Reset()) {
+ LOG4CXX_WARN(
+ logger_,
+ "Problem with execution or resetting insert_help_prompt_array query");
+ return false;
+ }
+ }
+ LOG4CXX_INFO(logger_, "Data were saved to helpTimeoutPromptArray table");
+ return true;
+}
+
+bool ResumptionDataDB::ExecInsertTTSChunks(
+ const smart_objects::SmartObject& tts_chunk, int64_t& tts_chunk_key) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ utils::dbms::SQLQuery insert_tts_chunk(db());
+ if (!insert_tts_chunk.Prepare(kInsertTTSChunk)) {
+ LOG4CXX_WARN(logger_, "Problem with verification insert_tts_chunk query");
+ return false;
+ }
+ /* Positions of binding data for "insert_tts_chunk":
+ field "type" from table "TTSChunk" = 0
+ field "text" from table "TTSChunk" = 1*/
+ insert_tts_chunk.Bind(0, tts_chunk[strings::type].asInt());
+ insert_tts_chunk.Bind(1, tts_chunk[strings::text].asString());
+ if (!insert_tts_chunk.Exec()) {
+ LOG4CXX_WARN(logger_, "Problem with execution insert_tts_chunk query");
+ return false;
+ }
+ tts_chunk_key = insert_tts_chunk.LastInsertId();
+ LOG4CXX_WARN(logger_, "TTSChunk was saved successfully");
+ return true;
+}
+
+bool ResumptionDataDB::ExecInsertLimitedCharacters(
+ int64_t global_properties_key,
+ const smart_objects::SmartObject& characters_array) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ utils::dbms::SQLQuery insert_characters(db());
+ if (!insert_characters.Prepare(kInsertTableLimitedCharacter)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with preparation query "
+ "insert_characters");
+ return false;
+ }
+ size_t length_characters_array = characters_array.length();
+ /* Positions of binding data for "insert_characters":
+ field "limitedCharacterList" from table "tableLimitedCharacterList" = 0*/
+ for (size_t i = 0; i < length_characters_array; ++i) {
+ insert_characters.Bind(0, characters_array[i].asString());
+
+ if (!insert_characters.Exec()) {
+ LOG4CXX_WARN(logger_,
+ "Problem with insert data to limited_character table");
+ return false;
+ }
+ if ((!ExecInsertDataToArray(global_properties_key,
+ insert_characters.LastInsertId(),
+ kInsertCharacterArray)) ||
+ (!insert_characters.Reset())) {
+ LOG4CXX_WARN(logger_, "Problem with insert data to characterArray table");
+ return false;
+ }
+ }
+ LOG4CXX_INFO(logger_,
+ "Data were saved successfully to limited_character table");
+ return true;
+}
+
+bool ResumptionDataDB::ExecInsertVRHelpItem(
+ int64_t global_properties_key,
+ const smart_objects::SmartObject& vrhelp_array) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ utils::dbms::SQLQuery insert_vrhelp_item(db());
+ if (!insert_vrhelp_item.Prepare(kInsertVRHelpItem)) {
+ LOG4CXX_WARN(logger_, "Problem with preparation query insert_vrhelp_item");
+ return false;
+ }
+ int64_t image_primary_key = 0;
+ size_t length_vrhelp_array = vrhelp_array.length();
+ /* Positions of binding data for "insert_vrhelp_item":
+ field "text" from table "vrHelpItem" = 0
+ field "position" from table "vrHelpItem" = 1
+ field "idimage" from table "vrHelpItem" = 2*/
+ for (size_t i = 0; i < length_vrhelp_array; ++i) {
+ insert_vrhelp_item.Bind(0, vrhelp_array[i][strings::text].asString());
+ insert_vrhelp_item.Bind(1, vrhelp_array[i][strings::position].asInt());
+ if (vrhelp_array[i].keyExists(strings::image)) {
+ if (!ExecInsertImage(image_primary_key,
+ vrhelp_array[i][strings::image])) {
+ LOG4CXX_INFO(logger_, "Problem with insert image to vrHelpItem table");
+ return false;
+ }
+ insert_vrhelp_item.Bind(2, image_primary_key);
+ } else {
+ insert_vrhelp_item.Bind(2);
+ }
+
+ if (!insert_vrhelp_item.Exec()) {
+ LOG4CXX_INFO(logger_, "Problem with insert data vrHelpItem table");
+ return false;
+ }
+
+ if ((!ExecInsertDataToArray(global_properties_key,
+ insert_vrhelp_item.LastInsertId(),
+ kInsertVRHelpItemArray)) ||
+ (!insert_vrhelp_item.Reset())) {
+ LOG4CXX_WARN(logger_,
+ "Problem with insert data to vrHelpItemArray table");
+ return false;
+ }
+ }
+ LOG4CXX_INFO(logger_,
+ "Data were saved successfully to vrHelpItem array table");
+ return true;
+}
+
+bool ResumptionDataDB::InsertApplicationData(
+ app_mngr::ApplicationSharedPtr application,
+ const std::string& policy_app_id,
+ const std::string& device_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ ApplicationParams app(application);
+ return InsertApplicationData(app, policy_app_id, device_id, NULL, 0);
+}
+
+bool ResumptionDataDB::InsertApplicationData(
+ const ApplicationParams& application,
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ int64_t* application_primary_key,
+ int64_t global_properties_key) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ utils::dbms::SQLQuery query(db());
+
+ if (!application.m_is_valid) {
+ LOG4CXX_ERROR(logger_, "Invalid application params passed.");
+ return false;
+ }
+
+ const std::string hash = application.m_hash;
+ const int64_t grammar_id = application.m_grammar_id;
+ const int64_t time_stamp = static_cast<int64_t>(time(NULL));
+ const int64_t connection_key = application.m_connection_key;
+ const int64_t hmi_app_id = application.m_hmi_app_id;
+ const mobile_apis::HMILevel::eType hmi_level = application.m_hmi_level;
+ bool is_media_application = application.m_is_media_application;
+ bool is_subscribed_for_way_points =
+ application_manager_.IsAppSubscribedForWayPoints(connection_key);
+
+ if (!query.Prepare(kInsertApplication)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with verification query "
+ "for insert to table application");
+ return false;
+ }
+
+ /* Positions of binding data for "query":
+ field "connection_key" from table "application" = 0
+ field "grammarID" from table "application" = 1
+ field "hashID" from table "application" = 2
+ field "hmiAppID" from table "application" = 3
+ field "hmiLevel" from table "application" = 4
+ field "ign_off_count" from table "application" = 5
+ field "timeStamp" from table "application" = 6
+ field "idglobalProperties" from table "application" = 7
+ field "isMediaApplication" from table "application" = 8
+ field "appID" from table "application" = 9
+ field "deviceID" from table "application" = 10
+ field "isSubscribedForWayPoints" from table "application" = 11*/
+ query.Bind(0, connection_key);
+ query.Bind(1, grammar_id);
+ query.Bind(2, hash);
+ query.Bind(3, hmi_app_id);
+ query.Bind(4, static_cast<int32_t>(hmi_level));
+ query.Bind(5, 0);
+ query.Bind(6, time_stamp);
+ if (global_properties_key) {
+ query.Bind(7, global_properties_key);
+ } else {
+ query.Bind(7);
+ }
+ query.Bind(8, is_media_application);
+ query.Bind(9, policy_app_id);
+ query.Bind(10, device_id);
+ query.Bind(11, is_subscribed_for_way_points);
+
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Problem with execution query");
+ return false;
+ }
+ if (NULL != application_primary_key) {
+ *application_primary_key = query.LastInsertId();
+ }
+ LOG4CXX_INFO(logger_, "Data were saved successfully to application table");
+ return true;
+}
+
+void ResumptionDataDB::CustomBind(const std::string& key,
+ const smart_objects::SmartObject& so,
+ utils::dbms::SQLQuery& query,
+ const int pos) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace smart_objects;
+ if (so.keyExists(key) && SmartType::SmartType_Null != so[key].getType()) {
+ switch (so[key].getType()) {
+ case SmartType::SmartType_Integer: {
+ query.Bind(pos, so[key].asInt());
+ break;
+ }
+ case SmartType::SmartType_String: {
+ query.Bind(pos, so[key].asString());
+ break;
+ }
+ default: {
+ LOG4CXX_WARN(logger_, "Incorrect type");
+ break;
+ }
+ }
+ } else {
+ query.Bind(pos);
+ }
+}
+
+bool ResumptionDataDB::PrepareSelectQuery(utils::dbms::SQLQuery& query,
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ const std::string& text_query) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!query.Prepare(text_query)) {
+ LOG4CXX_WARN(logger_, "Problem with verification query");
+ return false;
+ }
+ query.Bind(0, policy_app_id);
+ query.Bind(1, device_id);
+ return true;
+}
+
+void ResumptionDataDB::UpdateDataOnAwake() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ utils::dbms::SQLQuery query(db());
+ if (query.Prepare(kUpdateIgnOffCount)) {
+ if (query.Exec()) {
+ LOG4CXX_INFO(logger_,
+ "Values of ignition off counts were updated successfully");
+ WriteDb();
+ }
+ }
+}
+
+bool ResumptionDataDB::UpdateApplicationData(
+ app_mngr::ApplicationConstSharedPtr application,
+ const std::string& policy_app_id,
+ const std::string& device_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ utils::dbms::SQLQuery query(db());
+
+ const int64_t time_stamp = static_cast<int64_t>(time(NULL));
+ const mobile_apis::HMILevel::eType hmi_level = application->hmi_level();
+
+ if (!query.Prepare(kUpdateApplicationData)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with verification query "
+ "for updating some application data");
+ return false;
+ }
+
+ /* Positions of binding data for "query":
+ field "hmiLevel" from table "application" = 0
+ field "timeStamp" from table "application" = 1
+ field "appID" from table "application" = 2
+ field "deviceID" from table "application" = 3*/
+ query.Bind(0, static_cast<int32_t>(hmi_level));
+ query.Bind(1, time_stamp);
+ query.Bind(2, policy_app_id);
+ query.Bind(3, device_id);
+
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Problem with execution query");
+ return false;
+ }
+ LOG4CXX_INFO(logger_, "Data were updated successfully in application table");
+ return true;
+}
+
+void ResumptionDataDB::WriteDb() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ db_->Backup();
+}
+
+bool ResumptionDataDB::UpdateGrammarID(const std::string& policy_app_id,
+ const std::string& device_id,
+ const uint32_t grammar_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ utils::dbms::SQLQuery query(db());
+
+ if (!query.Prepare(kUpdateGrammarID)) {
+ LOG4CXX_WARN(logger_,
+ "Problem with verification query for updating grammar id.");
+ return false;
+ }
+
+ // Positions of binding data for "query":
+ // field "grammarID" from table "application" = 0
+ // field "appID" from table "application" = 1
+ // field "deviceID" from table "application" = 2
+ query.Bind(0, static_cast<int32_t>(grammar_id));
+ query.Bind(1, policy_app_id);
+ query.Bind(2, device_id);
+
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Problem with execution query");
+ return false;
+ }
+ LOG4CXX_INFO(logger_, "Data were updated successfully in application table");
+ return true;
+}
+
+utils::dbms::SQLDatabase* ResumptionDataDB::db() const {
+#ifdef __QNX__
+ utils::dbms::SQLDatabase* db = new utils::dbms::SQLDatabase(kDatabaseName);
+ db->Open();
+ return db;
+#else
+ return db_;
+#endif
+}
+
+ApplicationParams::ApplicationParams(
+ const smart_objects::SmartObject& application)
+ : m_hash()
+ , m_grammar_id(0)
+ , m_connection_key(0)
+ , m_hmi_app_id(0)
+ , m_hmi_level(mobile_apis::HMILevel::INVALID_ENUM)
+ , m_is_media_application(false)
+ , m_is_valid(false) {
+ using namespace app_mngr::strings;
+ if (!application.keyExists(app_id) || !application.keyExists(hash_id) ||
+ !application.keyExists(grammar_id) ||
+ !application.keyExists(connection_key) ||
+ !application.keyExists(hmi_app_id) || !application.keyExists(hmi_level) ||
+ !application.keyExists(is_media_application)) {
+ return;
+ }
+ m_is_valid = true;
+ m_hash = application[hash_id].asString();
+ m_grammar_id = application[grammar_id].asInt();
+ m_connection_key = application[connection_key].asInt();
+ m_hmi_app_id = application[hmi_app_id].asInt();
+ m_hmi_level =
+ static_cast<mobile_apis::HMILevel::eType>(application[hmi_level].asInt());
+ m_is_media_application = application[is_media_application].asBool();
+}
+
+ApplicationParams::ApplicationParams(app_mngr::ApplicationSharedPtr application)
+ : m_hash()
+ , m_grammar_id(0)
+ , m_connection_key(0)
+ , m_hmi_app_id(0)
+ , m_hmi_level(mobile_apis::HMILevel::INVALID_ENUM)
+ , m_is_media_application(false)
+ , m_is_valid(false) {
+ if (application) {
+ m_is_valid = true;
+ m_hash = application->curHash();
+ m_grammar_id = application->get_grammar_id();
+ m_connection_key = application->app_id();
+ m_hmi_app_id = application->hmi_app_id();
+ m_hmi_level = application->hmi_level();
+ m_is_media_application = application->IsAudioApplication();
+ }
+}
+
+} // namespace resumption
diff --git a/src/components/application_manager/src/resumption/resumption_data_json.cc b/src/components/application_manager/src/resumption/resumption_data_json.cc
new file mode 100644
index 0000000000..f60f934fef
--- /dev/null
+++ b/src/components/application_manager/src/resumption/resumption_data_json.cc
@@ -0,0 +1,487 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/application_manager_impl.h"
+#include "application_manager/resumption/resumption_data_json.h"
+#include "smart_objects/smart_object.h"
+#include "json/json.h"
+#include "formatters/CFormatterJsonBase.h"
+#include "application_manager/message_helper.h"
+#include "application_manager/smart_object_keys.h"
+#include "application_manager/application_manager_settings.h"
+
+namespace resumption {
+
+namespace Formatters = NsSmartDeviceLink::NsJSONHandler::Formatters;
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "Resumption")
+
+ResumptionDataJson::ResumptionDataJson(
+ LastState& last_state,
+ const application_manager::ApplicationManager& application_manager)
+ : ResumptionData(application_manager), last_state_(last_state) {}
+
+void ResumptionDataJson::SaveApplication(
+ app_mngr::ApplicationSharedPtr application) {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(application);
+
+ const std::string& policy_app_id = application->policy_app_id();
+ LOG4CXX_DEBUG(logger_,
+ "app_id : " << application->app_id()
+ << " policy_app_id : " << policy_app_id);
+ const std::string hash = application->curHash();
+ const uint32_t grammar_id = application->get_grammar_id();
+ const uint32_t time_stamp = (uint32_t)time(NULL);
+ const std::string device_mac = application->mac_address();
+ const mobile_apis::HMILevel::eType hmi_level = application->hmi_level();
+ const bool is_subscribed_for_way_points =
+ application_manager_.IsAppSubscribedForWayPoints(application->app_id());
+
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ Json::Value tmp;
+ Json::Value& json_app = GetFromSavedOrAppend(policy_app_id, device_mac);
+
+ json_app[strings::device_id] = device_mac;
+ json_app[strings::app_id] = policy_app_id;
+ json_app[strings::grammar_id] = grammar_id;
+ json_app[strings::connection_key] = application->app_id();
+ json_app[strings::hmi_app_id] = application->hmi_app_id();
+ json_app[strings::is_media_application] = application->IsAudioApplication();
+ json_app[strings::hmi_level] = static_cast<int32_t>(hmi_level);
+ json_app[strings::ign_off_count] = 0;
+ json_app[strings::hash_id] = hash;
+ Formatters::CFormatterJsonBase::objToJsonValue(
+ GetApplicationCommands(application), tmp);
+ json_app[strings::application_commands] = tmp;
+ Formatters::CFormatterJsonBase::objToJsonValue(
+ GetApplicationSubMenus(application), tmp);
+ json_app[strings::application_submenus] = tmp;
+ Formatters::CFormatterJsonBase::objToJsonValue(
+ GetApplicationInteractionChoiseSets(application), tmp);
+ json_app[strings::application_choice_sets] = tmp;
+ Formatters::CFormatterJsonBase::objToJsonValue(
+ GetApplicationGlobalProperties(application), tmp);
+ json_app[strings::application_global_properties] = tmp;
+ Formatters::CFormatterJsonBase::objToJsonValue(
+ GetApplicationSubscriptions(application), tmp);
+ json_app[strings::application_subscribtions] = tmp;
+ Formatters::CFormatterJsonBase::objToJsonValue(
+ GetApplicationFiles(application), tmp);
+ json_app[strings::application_files] = tmp;
+ json_app[strings::time_stamp] = time_stamp;
+ json_app[strings::subscribed_for_way_points] = is_subscribed_for_way_points;
+
+ LOG4CXX_DEBUG(logger_, "SaveApplication : " << json_app.toStyledString());
+}
+
+bool ResumptionDataJson::IsHMIApplicationIdExist(uint32_t hmi_app_id) const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ for (Json::Value::iterator it = GetSavedApplications().begin();
+ it != GetSavedApplications().end();
+ ++it) {
+ if ((*it).isMember(strings::hmi_app_id)) {
+ if ((*it)[strings::hmi_app_id].asUInt() == hmi_app_id) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+uint32_t ResumptionDataJson::GetHMIApplicationID(
+ const std::string& policy_app_id, const std::string& device_id) const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ uint32_t hmi_app_id = 0;
+
+ const int idx = GetObjectIndex(policy_app_id, device_id);
+ if (-1 == idx) {
+ LOG4CXX_WARN(logger_, "Application not saved");
+ return hmi_app_id;
+ }
+
+ const Json::Value& json_app = GetSavedApplications()[idx];
+ if (json_app.isMember(strings::app_id) &&
+ json_app.isMember(strings::device_id)) {
+ hmi_app_id = json_app[strings::hmi_app_id].asUInt();
+ }
+ LOG4CXX_DEBUG(logger_, "hmi_app_id :" << hmi_app_id);
+ return hmi_app_id;
+}
+
+void ResumptionDataJson::OnSuspend() {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ Json::Value to_save;
+ for (Json::Value::iterator it = GetSavedApplications().begin();
+ it != GetSavedApplications().end();
+ ++it) {
+ if ((*it).isMember(strings::ign_off_count)) {
+ Json::Value& ign_off_count = (*it)[strings::ign_off_count];
+ const uint32_t counter_value = ign_off_count.asUInt();
+ ign_off_count = counter_value + 1;
+ } else {
+ LOG4CXX_WARN(logger_, "Unknown key among saved applications");
+ Json::Value& ign_off_count = (*it)[strings::ign_off_count];
+ ign_off_count = 1;
+ }
+ to_save.append(*it);
+ }
+ SetSavedApplication(to_save);
+ SetLastIgnOffTime(time(NULL));
+ LOG4CXX_DEBUG(logger_, GetResumptionData().toStyledString());
+}
+
+void ResumptionDataJson::OnAwake() {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+
+ for (Json::Value::iterator it = GetSavedApplications().begin();
+ it != GetSavedApplications().end();
+ ++it) {
+ if ((*it).isMember(strings::ign_off_count)) {
+ const uint32_t ign_off_count = (*it)[strings::ign_off_count].asUInt();
+ if (0 == ign_off_count) {
+ LOG4CXX_WARN(logger_, "Application has not been suspended");
+ } else {
+ (*it)[strings::ign_off_count] = ign_off_count - 1;
+ }
+ } else {
+ LOG4CXX_WARN(logger_, "Unknown key among saved applications");
+ (*it)[strings::ign_off_count] = 0;
+ }
+ }
+}
+
+bool ResumptionDataJson::GetHashId(const std::string& policy_app_id,
+ const std::string& device_id,
+ std::string& hash_id) const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ const int idx = GetObjectIndex(policy_app_id, device_id);
+ if (-1 == idx) {
+ LOG4CXX_WARN(logger_, "Application not saved");
+ return false;
+ }
+
+ const Json::Value& json_app = GetSavedApplications()[idx];
+ LOG4CXX_DEBUG(logger_,
+ "Saved_application_data: " << json_app.toStyledString());
+ if (json_app.isMember(strings::hash_id) &&
+ json_app.isMember(strings::time_stamp)) {
+ hash_id = json_app[strings::hash_id].asString();
+ return true;
+ }
+ LOG4CXX_WARN(logger_, "There are some unknown keys in the dictionary.");
+ return false;
+}
+
+bool ResumptionDataJson::GetSavedApplication(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app) const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ const int idx = GetObjectIndex(policy_app_id, device_id);
+ if (-1 == idx) {
+ return false;
+ }
+ const Json::Value& json_saved_app = GetSavedApplications()[idx];
+ Formatters::CFormatterJsonBase::jsonValueToObj(json_saved_app, saved_app);
+
+ return true;
+}
+
+bool ResumptionDataJson::RemoveApplicationFromSaved(
+ const std::string& policy_app_id, const std::string& device_id) {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ bool result = false;
+ std::vector<Json::Value> temp;
+ for (Json::Value::iterator it = GetSavedApplications().begin();
+ it != GetSavedApplications().end();
+ ++it) {
+ if ((*it).isMember(strings::app_id) && (*it).isMember(strings::device_id)) {
+ const std::string& saved_policy_app_id =
+ (*it)[strings::app_id].asString();
+ const std::string& saved_device_id = (*it)[strings::device_id].asString();
+ if (saved_policy_app_id == policy_app_id &&
+ saved_device_id == device_id) {
+ result = true;
+ } else {
+ temp.push_back((*it));
+ }
+ }
+ }
+
+ if (false == result) {
+ LOG4CXX_TRACE(logger_, "EXIT result: " << (result ? "true" : "false"));
+ return result;
+ }
+
+ GetSavedApplications().clear();
+ for (std::vector<Json::Value>::iterator it = temp.begin(); it != temp.end();
+ ++it) {
+ GetSavedApplications().append((*it));
+ }
+ LOG4CXX_TRACE(logger_, "EXIT result: " << (result ? "true" : "false"));
+ return result;
+}
+
+uint32_t ResumptionDataJson::GetIgnOffTime() const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ Json::Value& resumption = GetResumptionData();
+ if (!resumption.isMember(strings::last_ign_off_time)) {
+ resumption[strings::last_ign_off_time] = 0;
+ LOG4CXX_WARN(logger_, "last_save_time section is missed");
+ }
+ return resumption[strings::last_ign_off_time].asUInt();
+}
+
+ssize_t ResumptionDataJson::IsApplicationSaved(
+ const std::string& policy_app_id, const std::string& device_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ return GetObjectIndex(policy_app_id, device_id);
+}
+
+Json::Value& ResumptionDataJson::GetFromSavedOrAppend(
+ const std::string& policy_app_id, const std::string& device_id) const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ for (Json::Value::iterator it = GetSavedApplications().begin();
+ it != GetSavedApplications().end();
+ ++it) {
+ if (device_id == (*it)[strings::device_id].asString() &&
+ policy_app_id == (*it)[strings::app_id].asString()) {
+ return *it;
+ }
+ }
+
+ return GetSavedApplications().append(Json::Value());
+}
+
+void ResumptionDataJson::GetDataForLoadResumeData(
+ smart_objects::SmartObject& saved_data) const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ smart_objects::SmartObject so_array_data(smart_objects::SmartType_Array);
+ int i = 0;
+ for (Json::Value::iterator it = GetSavedApplications().begin();
+ it != GetSavedApplications().end();
+ ++it) {
+ if (((*it).isMember(strings::hmi_level)) &&
+ ((*it).isMember(strings::ign_off_count)) &&
+ ((*it).isMember(strings::time_stamp)) &&
+ ((*it).isMember(strings::app_id)) &&
+ ((*it).isMember(strings::device_id))) {
+ smart_objects::SmartObject so(smart_objects::SmartType_Map);
+ so[strings::hmi_level] = (*it)[strings::hmi_level].asInt();
+ so[strings::ign_off_count] = (*it)[strings::ign_off_count].asInt();
+ so[strings::time_stamp] = (*it)[strings::time_stamp].asUInt();
+ so[strings::app_id] = (*it)[strings::app_id].asString();
+ so[strings::device_id] = (*it)[strings::device_id].asString();
+ so_array_data[i++] = so;
+ }
+ }
+ saved_data = so_array_data;
+}
+
+ResumptionDataJson::~ResumptionDataJson() {
+ // TODO Probably Save Data on disk
+}
+
+void ResumptionDataJson::UpdateHmiLevel(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ mobile_apis::HMILevel::eType hmi_level) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+
+ int idx = GetObjectIndex(policy_app_id, device_id);
+ if (-1 == idx) {
+ LOG4CXX_WARN(logger_,
+ "Application isn't saved with mobile_app_id = "
+ << policy_app_id << " device_id = " << device_id);
+ return;
+ }
+ GetSavedApplications()[idx][strings::hmi_level] = hmi_level;
+}
+
+Json::Value& ResumptionDataJson::GetSavedApplications() const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ Json::Value& resumption = GetResumptionData();
+ if (!resumption.isMember(strings::resume_app_list)) {
+ resumption[strings::resume_app_list] = Json::Value(Json::arrayValue);
+ LOG4CXX_WARN(logger_, "app_list section is missed");
+ }
+ Json::Value& resume_app_list = resumption[strings::resume_app_list];
+ if (!resume_app_list.isArray()) {
+ LOG4CXX_ERROR(logger_, "resume_app_list type INVALID rewrite");
+ resume_app_list = Json::Value(Json::arrayValue);
+ }
+ return resume_app_list;
+}
+
+Json::Value& ResumptionDataJson::GetResumptionData() const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ Json::Value& dictionary = last_state().dictionary;
+ if (!dictionary.isMember(strings::resumption)) {
+ last_state().dictionary[strings::resumption] =
+ Json::Value(Json::objectValue);
+ LOG4CXX_WARN(logger_, "resumption section is missed");
+ }
+ Json::Value& resumption = dictionary[strings::resumption];
+ if (!resumption.isObject()) {
+ LOG4CXX_ERROR(logger_, "resumption type INVALID rewrite");
+ resumption = Json::Value(Json::objectValue);
+ }
+ return resumption;
+}
+
+ssize_t ResumptionDataJson::GetObjectIndex(const std::string& policy_app_id,
+ const std::string& device_id) const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ const Json::Value& apps = GetSavedApplications();
+ const Json::ArrayIndex size = apps.size();
+ Json::ArrayIndex idx = 0;
+ for (; idx != size; ++idx) {
+ if (apps[idx].isMember(strings::app_id) &&
+ apps[idx].isMember(strings::device_id)) {
+ const std::string& saved_app_id = apps[idx][strings::app_id].asString();
+ const std::string& saved_device_id =
+ apps[idx][strings::device_id].asString();
+ if (device_id == saved_device_id && policy_app_id == saved_app_id) {
+ LOG4CXX_DEBUG(logger_, "Found " << idx);
+ return idx;
+ }
+ }
+ }
+ return -1;
+}
+
+bool ResumptionDataJson::IsResumptionDataValid(uint32_t index) const {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ const Json::Value& json_app = GetSavedApplications()[index];
+ if (!json_app.isMember(strings::app_id) ||
+ !json_app.isMember(strings::ign_off_count) ||
+ !json_app.isMember(strings::hmi_level) ||
+ !json_app.isMember(strings::hmi_app_id) ||
+ !json_app.isMember(strings::time_stamp) ||
+ !json_app.isMember(strings::device_id)) {
+ LOG4CXX_ERROR(logger_, "Wrong resumption data");
+ return false;
+ }
+
+ if (json_app.isMember(strings::hmi_app_id) &&
+ 0 >= json_app[strings::hmi_app_id].asUInt()) {
+ LOG4CXX_ERROR(logger_, "Wrong resumption hmi app ID");
+ return false;
+ }
+
+ return true;
+}
+
+void ResumptionDataJson::SetSavedApplication(Json::Value& apps_json) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ Json::Value& app_list = GetSavedApplications();
+ app_list = apps_json;
+}
+
+void ResumptionDataJson::SetLastIgnOffTime(time_t ign_off_time) {
+ using namespace app_mngr;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ LOG4CXX_WARN(logger_, "ign_off_time = " << ign_off_time);
+ Json::Value& resumption = GetResumptionData();
+ resumption[strings::last_ign_off_time] = static_cast<uint32_t>(ign_off_time);
+}
+
+bool ResumptionDataJson::Init() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ return true;
+}
+
+bool ResumptionDataJson::DropAppDataResumption(const std::string& device_id,
+ const std::string& app_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace app_mngr;
+ sync_primitives::AutoLock autolock(resumption_lock_);
+ Json::Value& application = GetFromSavedOrAppend(app_id, device_id);
+ if (application.isNull()) {
+ LOG4CXX_DEBUG(logger_,
+ "Application " << app_id << " with device_id " << device_id
+ << " hasn't been found in resumption data.");
+ return false;
+ }
+ application[strings::application_commands].clear();
+ application[strings::application_submenus].clear();
+ application[strings::application_choice_sets].clear();
+ application[strings::application_global_properties].clear();
+ application[strings::application_subscribtions].clear();
+ application[strings::application_files].clear();
+ application.removeMember(strings::grammar_id);
+ LOG4CXX_DEBUG(logger_,
+ "Resumption data for application "
+ << app_id << " with device_id " << device_id
+ << " has been dropped.");
+ return true;
+}
+
+void ResumptionDataJson::Persist() {
+ last_state().SaveToFileSystem();
+}
+
+} // resumption
diff --git a/src/components/application_manager/src/resumption/resumption_sql_queries.cc b/src/components/application_manager/src/resumption/resumption_sql_queries.cc
new file mode 100644
index 0000000000..5f318e6955
--- /dev/null
+++ b/src/components/application_manager/src/resumption/resumption_sql_queries.cc
@@ -0,0 +1,981 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "application_manager/resumption/resumption_sql_queries.h"
+
+namespace resumption {
+
+const std::string kCreateSchema =
+ "BEGIN ; "
+ "CREATE TABLE IF NOT EXISTS `resumption`( "
+ " `idresumption` INTEGER PRIMARY KEY, "
+ " `last_ign_off_time` INTEGER "
+ " ); "
+ "CREATE TABLE IF NOT EXISTS `subscribedForWayPoints`( "
+ " `appID` INTEGER "
+ " ); "
+ "CREATE TABLE IF NOT EXISTS `image`( "
+ " `idimage` INTEGER PRIMARY KEY NOT NULL, "
+ " `imageType` INTEGER, "
+ " `value` TEXT UNIQUE "
+ " ); "
+ "CREATE TABLE IF NOT EXISTS `applicationChoiceSet`( "
+ " `idapplicationChoiceSet` INTEGER PRIMARY KEY NOT NULL, "
+ " `grammarID` INTEGER, "
+ " `interactionChoiceSetID` INTEGER "
+ " ); "
+ "CREATE TABLE IF NOT EXISTS `file`( "
+ " `idfile` INTEGER PRIMARY KEY NOT NULL, "
+ " `fileType` INTEGER, "
+ " `is_download_complete` BOOL, "
+ " `persistentFile` BOOL, "
+ " `syncFileName` TEXT "
+ " ); "
+ "CREATE TABLE IF NOT EXISTS `subMenu`( "
+ " `idsubMenu` INTEGER PRIMARY KEY NOT NULL, "
+ " `menuID` INTEGER, "
+ " `menuName` TEXT, "
+ " `position` INTEGER "
+ " ); "
+ "CREATE TABLE IF NOT EXISTS `TTSChunk`( "
+ " `idTTSChunk` INTEGER PRIMARY KEY NOT NULL, "
+ " `type` INTEGER, "
+ " `text` TEXT "
+ " ); "
+ "CREATE TABLE IF NOT EXISTS `vrHelpItem`( "
+ " `idvrHelpItem` INTEGER PRIMARY KEY NOT NULL, "
+ " `text` TEXT, "
+ " `position` INTEGER, "
+ " `idimage` INTEGER, "
+ " CONSTRAINT `fk_image` "
+ " FOREIGN KEY(`idimage`) "
+ " REFERENCES `image`(`idimage`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`vrHelpItem.fk_image_idx` ON `vrHelpItem`(`idimage`); "
+ "CREATE TABLE IF NOT EXISTS `tableLimitedCharacterList`( "
+ " `idtableLimitedCharacterList` INTEGER PRIMARY KEY NOT NULL, "
+ " `limitedCharacterList` VARCHAR(45) "
+ " ); "
+ "CREATE TABLE IF NOT EXISTS `characterArray`( "
+ " `idcharacterArray` INTEGER PRIMARY KEY NOT NULL, "
+ " `idglobalProperties` INTEGER, "
+ " `idtableLimitedCharacterList` INTEGER, "
+ " CONSTRAINT `fk_globalProperties` "
+ " FOREIGN KEY(`idglobalProperties`) "
+ " REFERENCES `globalProperties`(`idglobalProperties`), "
+ " CONSTRAINT `fk_tableLimitedCharacterList` "
+ " FOREIGN KEY(`idtableLimitedCharacterList`) "
+ " REFERENCES `tableLimitedCharacterList`(`idtableLimitedCharacterList`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`characterArray.fk_globalProperties_idx` "
+ " ON `characterArray`(`idglobalProperties`); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`characterArray.fk_tableLimitedCharacterList_idx` "
+ " ON `characterArray`(`idtableLimitedCharacterList`); "
+ "CREATE TABLE IF NOT EXISTS `choice`( "
+ " `idchoice` INTEGER PRIMARY KEY NOT NULL, "
+ " `choiceID` INTEGER, "
+ " `menuName` TEXT, "
+ " `secondaryText` TEXT, "
+ " `tertiaryText` TEXT, "
+ " `idimage` INTEGER, "
+ " `idsecondaryImage` INTEGER, "
+ " CONSTRAINT `fk_image` "
+ " FOREIGN KEY(`idimage`,`idsecondaryImage`) "
+ " REFERENCES `image`(`idimage`,`idimage`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`choice.fk_image_idx` ON `choice`(`idimage`,`idsecondaryImage`); "
+ "CREATE TABLE IF NOT EXISTS `command`( "
+ " `idcommand` INTEGER PRIMARY KEY NOT NULL, "
+ " `cmdID` INTEGER, "
+ " `menuName` TEXT, "
+ " `parentID` INTEGER, "
+ " `position` INTEGER, "
+ " `idimage` INTEGER, "
+ " CONSTRAINT `fk_image` "
+ " FOREIGN KEY(`idimage`) "
+ " REFERENCES `image`(`idimage`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`command.fk_image_idx` ON `command`(`idimage`); "
+ "CREATE TABLE IF NOT EXISTS `globalProperties`( "
+ " `idglobalProperties` INTEGER PRIMARY KEY NOT NULL, "
+ " `vrHelpTitle` TEXT, "
+ " `menuTitle` TEXT, "
+ " `idmenuIcon` INTEGER, "
+ " `language` INTEGER, "
+ " `keyboardLayout` INTEGER, "
+ " `keypressMode` INTEGER, "
+ " `autoCompleteText` TEXT, "
+ " CONSTRAINT `fk_image` "
+ " FOREIGN KEY(`idmenuIcon`) "
+ " REFERENCES `image`(`idimage`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`globalProperties.fk_image_idx` ON `globalProperties`(`idmenuIcon`); "
+ "CREATE TABLE IF NOT EXISTS `choiceArray`( "
+ " `idchoiceArray` INTEGER PRIMARY KEY NOT NULL, "
+ " `idapplicationChoiceSet` INTEGER, "
+ " `idchoice` INTEGER, "
+ " CONSTRAINT `fk_applicationChoiceSet` "
+ " FOREIGN KEY(`idapplicationChoiceSet`) "
+ " REFERENCES `applicationChoiceSet`(`idapplicationChoiceSet`), "
+ " CONSTRAINT `fk_choice` "
+ " FOREIGN KEY(`idchoice`) "
+ " REFERENCES `choice`(`idchoice`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`choiceArray.fk_applicationChoiceSet_idx` "
+ " ON `choiceArray`(`idapplicationChoiceSet`); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`choiceArray.fk_choice_idx` ON `choiceArray`(`idchoice`); "
+ "CREATE TABLE IF NOT EXISTS `vrCommandsArray`( "
+ " `idvrCommandsArray` INTEGER PRIMARY KEY NOT NULL, "
+ " `idchoice` INTEGER, "
+ " `vrCommand` TEXT, "
+ " `idcommand` INTEGER, "
+ " CONSTRAINT `fk_choice` "
+ " FOREIGN KEY(`idchoice`) "
+ " REFERENCES `choice`(`idchoice`), "
+ " CONSTRAINT `fk_command` "
+ " FOREIGN KEY(`idcommand`) "
+ " REFERENCES `command`(`idcommand`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`vrCommandsArray.fk_choice_idx` ON `vrCommandsArray`(`idchoice`); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`vrCommandsArray.fk_command_idx` ON `vrCommandsArray`(`idcommand`); "
+ "CREATE TABLE IF NOT EXISTS `helpTimeoutPromptArray`( "
+ " `idhelpTimeoutPromptArray` INTEGER PRIMARY KEY NOT NULL, "
+ " `idhelpPrompt` INTEGER, "
+ " `idtimeoutPrompt` INTEGER, "
+ " `idglobalProperties` INTEGER, "
+ " CONSTRAINT `fk_globalProperties` "
+ " FOREIGN KEY(`idglobalProperties`) "
+ " REFERENCES `globalProperties`(`idglobalProperties`), "
+ " CONSTRAINT `fk_TTSChunk` "
+ " FOREIGN KEY(`idtimeoutPrompt`,`idhelpPrompt`) "
+ " REFERENCES `TTSChunk`(`idTTSChunk`,`idTTSChunk`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`helpTimeoutPromptArray.fk_globalProperties_idx` "
+ " ON `helpTimeoutPromptArray`(`idglobalProperties`); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`helpTimeoutPromptArray.fk_TTSChunk_idx` "
+ " ON `helpTimeoutPromptArray`(`idtimeoutPrompt`,`idhelpPrompt`); "
+ "CREATE TABLE IF NOT EXISTS `vrHelpItemArray`( "
+ " `idvrHelpItemArray` INTEGER PRIMARY KEY NOT NULL, "
+ " `idglobalProperties` INTEGER, "
+ " `idvrHelpItem` INTEGER, "
+ " CONSTRAINT `fk_vrHelpItem` "
+ " FOREIGN KEY(`idvrHelpItem`) "
+ " REFERENCES `vrHelpItem`(`idvrHelpItem`), "
+ " CONSTRAINT `fk_vrglobalProperties` "
+ " FOREIGN KEY(`idglobalProperties`) "
+ " REFERENCES `globalProperties`(`idglobalProperties`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`vrHelpItemArray.fk_vrHelpItem_idx` ON `vrHelpItemArray`(`idvrHelpItem`); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`vrHelpItemArray.fk_vrglobalProperties_idx` ON "
+ "`vrHelpItemArray`(`idglobalProperties`); "
+ "CREATE TABLE IF NOT EXISTS `application`( "
+ " `idApplication` INTEGER PRIMARY KEY NOT NULL, "
+ " `appID` TEXT, "
+ " `connection_key` INTEGER, "
+ " `grammarID` INTEGER, "
+ " `hashID` TEXT, "
+ " `hmiAppID` INTEGER, "
+ " `hmiLevel` INTEGER, "
+ " `ign_off_count` INTEGER, "
+ " `timeStamp` INTEGER, "
+ " `deviceID` TEXT, "
+ " `idglobalProperties` INTEGER, "
+ " `isMediaApplication` BOOL, "
+ " `isSubscribedForWayPoints` BOOL, "
+ " CONSTRAINT `fk_globalProperties` "
+ " FOREIGN KEY(`idglobalProperties`) "
+ " REFERENCES `globalProperties`(`idglobalProperties`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`application.fk_globalProperties_idx` ON "
+ "`application`(`idglobalProperties`); "
+ "CREATE TABLE IF NOT EXISTS `applicationChoiceSetArray`( "
+ " `idapplicationChoiceSetArray` INTEGER PRIMARY KEY NOT NULL, "
+ " `idapplicationChoiceSet` INTEGER, "
+ " `idApplication` INTEGER, "
+ " CONSTRAINT `fk_applicationChoiceSet` "
+ " FOREIGN KEY(`idapplicationChoiceSet`) "
+ " REFERENCES `applicationChoiceSet`(`idapplicationChoiceSet`), "
+ " CONSTRAINT `fk_Aplication` "
+ " FOREIGN KEY(`idApplication`) "
+ " REFERENCES `application`(`idApplication`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`applicationChoiceSetArray.fk_applicationChoiceSet_idx` "
+ " ON `applicationChoiceSetArray`(`idapplicationChoiceSet`); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`applicationChoiceSetArray.fk_Aplication_idx` "
+ " ON `applicationChoiceSetArray`(`idApplication`); "
+ "CREATE TABLE IF NOT EXISTS `applicationCommandsArray`( "
+ " `idapplicationCommandsArray` INTEGER PRIMARY KEY NOT NULL, "
+ " `idApplication` INTEGER, "
+ " `idcommand` INTEGER, "
+ " CONSTRAINT `fk_Application` "
+ " FOREIGN KEY(`idApplication`) "
+ " REFERENCES `application`(`idApplication`), "
+ " CONSTRAINT `fk_command` "
+ " FOREIGN KEY(`idcommand`) "
+ " REFERENCES `command`(`idcommand`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`applicationCommandsArray.fk_Application_idx` "
+ " ON `applicationCommandsArray`(`idApplication`); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`applicationCommandsArray.fk_command_idx` "
+ " ON `applicationCommandsArray`(`idcommand`); "
+ "CREATE TABLE IF NOT EXISTS `applicationFilesArray`( "
+ " `idapplicationFilesArray` INTEGER PRIMARY KEY NOT NULL, "
+ " `idApplication` INTEGER, "
+ " `idfile` INTEGER, "
+ " CONSTRAINT `fk_Application` "
+ " FOREIGN KEY(`idApplication`) "
+ " REFERENCES `application`(`idApplication`), "
+ " CONSTRAINT `fk_file` "
+ " FOREIGN KEY(`idfile`) "
+ " REFERENCES `file`(`idfile`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`applicationFilesArray.fk_Application_idx` "
+ " ON `applicationFilesArray`(`idApplication`); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`applicationFilesArray.fk_file_idx` ON `applicationFilesArray`(`idfile`); "
+ "CREATE TABLE IF NOT EXISTS `applicationSubMenuArray`( "
+ " `idapplicationSubMenuArray` INTEGER PRIMARY KEY NOT NULL, "
+ " `idApplication` INTEGER, "
+ " `idsubMenu` INTEGER, "
+ " CONSTRAINT `fk_subMenu` "
+ " FOREIGN KEY(`idsubMenu`) "
+ " REFERENCES `subMenu`(`idsubMenu`), "
+ " CONSTRAINT `fk_Application` "
+ " FOREIGN KEY(`idApplication`) "
+ " REFERENCES `application`(`idApplication`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`applicationSubMenuArray.fk_subMenu_idx` "
+ " ON `applicationSubMenuArray`(`idsubMenu`); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`applicationSubMenuArray.fk_Application_idx` "
+ " ON `applicationSubMenuArray`(`idApplication`); "
+ "CREATE TABLE IF NOT EXISTS `applicationSubscribtionsArray`( "
+ " `idapplicationSubscribtionsArray` INTEGER PRIMARY KEY NOT NULL, "
+ " `vehicleValue` INTEGER, "
+ " `ButtonNameValue` INTEGER, "
+ " `idApplication` INTEGER, "
+ " CONSTRAINT `fk_Application` "
+ " FOREIGN KEY(`idApplication`) "
+ " REFERENCES `application`(`idApplication`) "
+ " ); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`applicationSubscribtionsArray.fk_Application_idx` "
+ " ON `applicationSubscribtionsArray`(`idApplication`); "
+ "CREATE TABLE IF NOT EXISTS `_internal_data`( "
+ " `db_version_hash` INTEGER "
+ " ); "
+ "COMMIT;";
+
+const std::string kDropSchema =
+ "BEGIN; "
+ "DROP INDEX IF EXISTS "
+ "`message.fk_message_consumer_friendly_messages1_idx`; "
+ "DROP TABLE IF EXISTS `resumption`; "
+ "DROP TABLE IF EXISTS `subscribedForWayPoints`; "
+ "DROP TABLE IF EXISTS `image`; "
+ "DROP TABLE IF EXISTS `applicationChoiceSet`; "
+ "DROP TABLE IF EXISTS `file`; "
+ "DROP TABLE IF EXISTS `subMenu`; "
+ "DROP TABLE IF EXISTS `TTSChunk`; "
+ "DROP TABLE IF EXISTS `vrHelpItem`; "
+ "DROP INDEX IF EXISTS `vrHelpItem.fk_image_idx`; "
+ "DROP TABLE IF EXISTS `tableLimitedCharacterList`; "
+ "DROP TABLE IF EXISTS `characterArray`; "
+ "DROP INDEX IF EXISTS `characterArray.fk_globalProperties_idx`; "
+ "DROP INDEX IF EXISTS `characterArray.fk_tableLimitedCharacterList_idx`; "
+ "DROP TABLE IF EXISTS `choice`; "
+ "DROP INDEX IF EXISTS `choice.fk_image_idx`; "
+ "DROP TABLE IF EXISTS `command`; "
+ "DROP INDEX IF EXISTS `command.fk_image_idx`; "
+ "DROP TABLE IF EXISTS `globalProperties`; "
+ "DROP INDEX IF EXISTS `globalProperties.fk_image_idx`; "
+ "DROP TABLE IF EXISTS `choiceArray`; "
+ "DROP INDEX IF EXISTS `choiceArray.fk_applicationChoiceSet_idx`; "
+ "DROP INDEX IF EXISTS `choiceArray.fk_choice_idx`; "
+ "DROP TABLE IF EXISTS `vrCommandsArray`; "
+ "DROP INDEX IF EXISTS `vrCommandsArray.fk_choice_idx`; "
+ "DROP INDEX IF EXISTS `vrCommandsArray.fk_command_idx`; "
+ "DROP TABLE IF EXISTS `helpTimeoutPromptArray`; "
+ "DROP INDEX IF EXISTS `helpTimeoutPromptArray.fk_globalProperties_idx`; "
+ "DROP INDEX IF EXISTS `helpTimeoutPromptArray.fk_TTSChunk_idx`; "
+ "DROP TABLE IF EXISTS `vrHelpItemArray`; "
+ "DROP INDEX IF EXISTS `vrHelpItemArray.fk_vrHelpItem_idx`; "
+ "DROP INDEX IF EXISTS `vrHelpItemArray.fk_vrglobalProperties_idx`; "
+ "DROP TABLE IF EXISTS `application`; "
+ "DROP INDEX IF EXISTS `application.fk_globalProperties_idx`; "
+ "DROP TABLE IF EXISTS `applicationChoiceSetArray`; "
+ "DROP INDEX IF EXISTS "
+ "`applicationChoiceSetArray.fk_applicationChoiceSet_idx`; "
+ "DROP INDEX IF EXISTS `applicationChoiceSetArray.fk_Aplication_idx`; "
+ "DROP TABLE IF EXISTS `applicationCommandsArray`; "
+ "DROP INDEX IF EXISTS `applicationCommandsArray.fk_Application_idx`; "
+ "DROP INDEX IF EXISTS `applicationCommandsArray.fk_command_idx`; "
+ "DROP TABLE IF EXISTS `applicationFilesArray`; "
+ "DROP INDEX IF EXISTS `applicationFilesArray.fk_Application_idx`; "
+ "DROP INDEX IF EXISTS `applicationFilesArray.fk_file_idx`; "
+ "DROP TABLE IF EXISTS `applicationSubMenuArray`; "
+ "DROP INDEX IF EXISTS `applicationSubMenuArray.fk_subMenu_idx`; "
+ "DROP INDEX IF EXISTS `applicationSubMenuArray.fk_Application_idx`; "
+ "DROP TABLE IF EXISTS `applicationSubscribtionsArray`; "
+ "DROP INDEX IF EXISTS `applicationSubscribtionsArray.fk_Application_idx`; "
+ "DROP TABLE IF EXISTS `_internal_data`; "
+ "COMMIT; "
+ "VACUUM;";
+
+const std::string kInsertInitData =
+ "INSERT OR IGNORE INTO `resumption` (`last_ign_off_time`) VALUES (0); "
+ "INSERT OR IGNORE INTO `_internal_data` (`db_version_hash`) VALUES(0); ";
+
+const std::string kChecksResumptionData =
+ " SELECT COUNT(`idresumption`) "
+ " FROM `resumption`;";
+
+const std::string kSelectCountHMILevel =
+ "SELECT COUNT(`hmiLevel`) FROM `application` "
+ "WHERE `deviceID` = ? AND `appID` = ?";
+
+const std::string kSelectHMILevel =
+ "SELECT `hmiLevel` FROM `application` "
+ "WHERE `deviceID` = ? AND `appID` = ?";
+
+const std::string kCheckHMIId =
+ "SELECT COUNT(`hmiAppID`) FROM `application` "
+ "WHERE `hmiAppID` = ?";
+
+const std::string kSelectHMIId =
+ "SELECT `hmiAppID` FROM `application` "
+ "WHERE `deviceID` = ? AND `appID` = ?";
+
+const std::string kSelectCountHMIId =
+ "SELECT COUNT(`hmiAppID`) FROM `application` "
+ "WHERE `deviceID` = ? AND `appID` = ?";
+
+const std::string kCountHashId =
+ "SELECT COUNT(`hashID`) FROM `application` "
+ "WHERE `deviceID` = ? AND `appID` = ?";
+
+const std::string kSelectHashId =
+ "SELECT `hashID` FROM `application` "
+ "WHERE `deviceID` = ? AND `appID` = ?";
+
+const std::string kSelectIgnOffTime =
+ "SELECT `last_ign_off_time` FROM `resumption`";
+
+const std::string kCheckApplication =
+ "SELECT COUNT (`deviceID`) FROM `application` "
+ "WHERE `deviceID` = ? AND `appID` = ?";
+
+const std::string kCountApplications =
+ "SELECT COUNT(`appID`) FROM `application`;";
+
+const std::string kSelectDataForLoadResumeData =
+ "SELECT `hmiLevel`, `ign_off_count`, `timeStamp`, `appID`, `deviceID` "
+ "FROM `application`;";
+
+const std::string kUpdateHMILevel =
+ "UPDATE `application` "
+ "SET `hmiLevel` = ? "
+ "WHERE `deviceID` = ? AND `appID` = ?";
+
+const std::string kUpdateIgnOffCount =
+ "UPDATE `application` "
+ "SET `ign_off_count` = `ign_off_count` - 1 "
+ "WHERE `ign_off_count` > 0";
+
+const std::string kCountApplicationsIgnOff =
+ "SELECT COUNT(`ign_off_count`) "
+ "FROM `application` "
+ "WHERE `ign_off_count` >= ?";
+
+const std::string kSelectApplicationsIgnOffCount =
+ "SELECT `deviceID`, `appID` "
+ "FROM `application` "
+ "WHERE `ign_off_count` >= ?";
+
+const std::string kUpdateSuspendData =
+ "UPDATE `application` "
+ "SET `ign_off_count` = `ign_off_count` + 1";
+
+const std::string KUpdateLastIgnOffTime =
+ "UPDATE `resumption` "
+ "SET `last_ign_off_time` = ?";
+
+const std::string kDeleteFile =
+ "DELETE FROM `file` "
+ "WHERE `idfile` IN (SELECT `idfile` "
+ "FROM `applicationFilesArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?))";
+
+const std::string kDeleteApplicationFilesArray =
+ "DELETE FROM `applicationFilesArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?)";
+
+const std::string kDeleteSubMenu =
+ "DELETE FROM `subMenu` "
+ "WHERE `idsubMenu` IN (SELECT `idsubMenu` "
+ "FROM `applicationSubMenuArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?))";
+
+const std::string kDeleteApplicationSubMenuArray =
+ "DELETE FROM `applicationSubMenuArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?)";
+
+const std::string kDeleteApplicationSubscribtionsArray =
+ "DELETE FROM `applicationSubscribtionsArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?)";
+
+const std::string kDeleteImageFromCommands =
+ "DELETE FROM `image` "
+ "WHERE `idimage` IN (SELECT `idimage` "
+ "FROM `command` "
+ "WHERE `idcommand` IN (SELECT `idcommand` "
+ "FROM `applicationCommandsArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?)))";
+
+const std::string kDeleteVrCommands =
+ "DELETE FROM `vrCommandsArray` "
+ "WHERE `idcommand` IN (SELECT `idcommand` "
+ "FROM `applicationCommandsArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?))";
+
+const std::string kDeleteCommands =
+ "DELETE FROM `command` "
+ "WHERE `idcommand` IN (SELECT `idcommand` "
+ "FROM `applicationCommandsArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?))";
+
+const std::string kDeleteApplicationCommandsArray =
+ "DELETE FROM `applicationCommandsArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?)";
+
+const std::string kDeleteImageFromChoiceSet =
+ "DELETE FROM `image` "
+ "WHERE `idimage` IN (SELECT `idimage` "
+ "FROM `choice` "
+ "WHERE `idchoice` IN (SELECT `idchoice` "
+ "FROM `choiceArray` "
+ "WHERE `idapplicationChoiceSet` IN (SELECT `idapplicationChoiceSet` "
+ "FROM `applicationChoiceSetArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?))) "
+ "UNION "
+ "SELECT `idsecondaryImage` "
+ "FROM `choice` "
+ "WHERE `idchoice` IN (SELECT `idchoice` "
+ "FROM `choiceArray` "
+ "WHERE `idapplicationChoiceSet` IN (SELECT `idapplicationChoiceSet` "
+ "FROM `applicationChoiceSetArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?))))";
+
+const std::string kDeleteVrCommandsFromChoiceSet =
+ "DELETE FROM `vrCommandsArray` "
+ "WHERE `idchoice` IN (SELECT `idchoice` "
+ "FROM `choiceArray` "
+ "WHERE `idapplicationChoiceSet` IN (SELECT `idapplicationChoiceSet` "
+ "FROM `applicationChoiceSetArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?)))";
+
+const std::string kDeleteChoice =
+ "DELETE FROM `choice` "
+ "WHERE `idchoice` IN (SELECT `idchoice` "
+ "FROM `choiceArray` "
+ "WHERE `idapplicationChoiceSet` IN (SELECT `idapplicationChoiceSetArray` "
+ "FROM `applicationChoiceSetArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?)))";
+
+const std::string kDeleteChoiceArray =
+ "DELETE FROM `choiceArray` "
+ "WHERE `idapplicationChoiceSet` IN (SELECT `idapplicationChoiceSetArray` "
+ "FROM `applicationChoiceSetArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?))";
+
+const std::string kDeleteApplicationChoiceSet =
+ "DELETE FROM `applicationChoiceSet` "
+ "WHERE `idapplicationChoiceSet` IN (SELECT `idapplicationChoiceSetArray` "
+ "FROM `applicationChoiceSetArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?))";
+
+const std::string kDeleteApplicationChoiceSetArray =
+ "DELETE FROM `applicationChoiceSetArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?)";
+
+const std::string kDeleteImageFromGlobalProperties =
+ "DELETE FROM `image` "
+ "WHERE `idimage` IN (SELECT `idimage` "
+ "FROM `vrHelpItem` "
+ "WHERE `idvrHelpItem` IN (SELECT `idvrHelpItem` "
+ "FROM `vrHelpItemArray` "
+ "WHERE `idglobalProperties` = (SELECT `idglobalProperties` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?)) "
+ "UNION "
+ "SELECT `idmenuIcon` "
+ "FROM `globalProperties` "
+ "WHERE `idglobalProperties` = (SELECT `idglobalProperties` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?))";
+
+const std::string kDeletevrHelpItem =
+ "DELETE FROM `vrHelpItem` "
+ "WHERE `idvrHelpItem` IN (SELECT `idvrHelpItem` "
+ "FROM `vrHelpItemArray` "
+ "WHERE `idglobalProperties` = (SELECT `idglobalProperties` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?))";
+
+const std::string kDeletevrHelpItemArray =
+ "DELETE FROM `vrHelpItemArray` "
+ "WHERE `idglobalProperties` = (SELECT `idglobalProperties` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?)";
+
+const std::string kDeleteTableLimitedCharacterList =
+ "DELETE FROM `tableLimitedCharacterList` "
+ "WHERE `idtableLimitedCharacterList` IN (SELECT "
+ "`idtableLimitedCharacterList` "
+ "FROM `characterArray` "
+ "WHERE `idglobalProperties` = (SELECT `idglobalProperties` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND deviceID = ?))";
+
+const std::string kDeleteCharacterArray =
+ "DELETE FROM `characterArray` "
+ "WHERE `idglobalProperties` = (SELECT `idglobalProperties` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?)";
+
+const std::string kDeleteTTSChunk =
+ "DELETE FROM `TTSChunk` "
+ "WHERE `idTTSChunk` IN (SELECT `idhelpPrompt` "
+ "FROM `helpTimeoutPromptArray` "
+ "WHERE `idglobalProperties` = (SELECT `idglobalProperties` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?) "
+ "UNION "
+ "SELECT `idtimeoutPrompt` "
+ "FROM `helpTimeoutPromptArray` "
+ "WHERE `idglobalProperties` = (SELECT `idglobalProperties` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?))";
+
+const std::string kDeleteFromApplicationTable =
+ "DELETE FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?";
+
+const std::string kDeleteHelpTimeoutPromptArray =
+ "DELETE FROM `helpTimeoutPromptArray` "
+ "WHERE `idglobalProperties` = (SELECT `idglobalProperties` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?)";
+
+const std::string kDeleteGlobalProperties =
+ "DELETE FROM `globalProperties` "
+ "WHERE `idglobalProperties` = (SELECT `idglobalProperties` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?)";
+
+const std::string kSelectCountImage =
+ "SELECT COUNT (`value`) "
+ "FROM `image` "
+ "WHERE `value` = ?";
+
+const std::string kSelectPrimaryKeyImage =
+ "SELECT `idimage` "
+ "FROM `image` "
+ "WHERE `value` = ?";
+
+const std::string kInsertImage =
+ "INSERT INTO `image` "
+ "(`imageType`, `value`) "
+ "VALUES "
+ "(?, ?);";
+
+const std::string kInsertToFile =
+ "INSERT INTO `file` "
+ "(`fileType`, `is_download_complete`, `persistentFile`, `syncFileName`) "
+ "VALUES "
+ "(?, ?, ?, ?)";
+
+const std::string kInsertToApplicationFilesArray =
+ "INSERT INTO `applicationFilesArray` "
+ "(`idApplication`, `idfile`) "
+ "VALUES "
+ "(?, ?)";
+
+const std::string kInsertToSubMenu =
+ "INSERT INTO `subMenu` "
+ "(`menuID`, `menuName`, `position`) "
+ "VALUES "
+ "(?, ?, ?);";
+
+const std::string kInsertToApplicationSubMenuArray =
+ "INSERT INTO `applicationSubMenuArray` "
+ "(`idApplication`, `idsubMenu`) "
+ "VALUES "
+ "(?, ?);";
+
+const std::string kInsertToCommand =
+ "INSERT INTO `command` "
+ "(`cmdID`, `idimage`, `menuName`, `parentID`, `position`) "
+ "VALUES "
+ "(?, ?, ?, ?, ?);";
+
+const std::string kInsertApplicationCommandArray =
+ "INSERT INTO `applicationCommandsArray` "
+ "(`idApplication`, `idcommand`) "
+ "VALUES "
+ "(?, ?);";
+
+const std::string kInsertVrCommand =
+ "INSERT INTO `vrCommandsArray` "
+ "(`vrCommand`, `idcommand`, `idchoice`) "
+ "VALUES "
+ "(?, ?, ?);";
+
+const std::string kInsertSubscriptions =
+ "INSERT INTO `applicationSubscribtionsArray` "
+ "(`idApplication`, `vehicleValue`, `ButtonNameValue`) "
+ "VALUES "
+ "(?, ?, ?);";
+
+const std::string kInsertChoice =
+ "INSERT INTO `choice` "
+ "(`choiceID`, `menuName`, `secondaryText`, "
+ "`tertiaryText`, `idimage`, `idsecondaryImage`) "
+ "VALUES "
+ "(?, ?, ?, ?, ?, ?);";
+
+const std::string kInsertApplicationChoiceSet =
+ "INSERT INTO `applicationChoiceSet` "
+ "(`grammarID`, `interactionChoiceSetID`) "
+ "VALUES "
+ "(?, ?);";
+
+const std::string kInsertChoiceArray =
+ "INSERT INTO `choiceArray` "
+ "(`idapplicationChoiceSet`, `idchoice`) "
+ "VALUES "
+ "(?, ?);";
+
+const std::string kInsertApplicationChoiceSetArray =
+ "INSERT INTO `applicationChoiceSetArray` "
+ "(`idapplicationChoiceSet`, `idApplication`) "
+ "VALUES "
+ "(?, ?);";
+
+const std::string kInsertGlobalProperties =
+ "INSERT INTO `globalProperties` "
+ "(`vrHelpTitle`, `menuTitle`, `idmenuIcon`, `language`, "
+ "`keyboardLayout`, `keypressMode`, `autoCompleteText`) "
+ "VALUES "
+ "(?, ?, ?, ?, ?, ?, ?);";
+
+const std::string kInsertTableLimitedCharacter =
+ "INSERT INTO `tableLimitedCharacterList` "
+ "(`limitedCharacterList`) "
+ "VALUES "
+ "(?);";
+
+const std::string kInsertCharacterArray =
+ "INSERT INTO `characterArray` "
+ "(`idglobalProperties`, `idtableLimitedCharacterList`) "
+ "VALUES "
+ "(?, ?);";
+
+const std::string kInsertVRHelpItem =
+ "INSERT INTO `vrHelpItem` "
+ "(`text`, `position`, `idimage`) "
+ "VALUES "
+ "(?, ?, ?);";
+
+const std::string kInsertVRHelpItemArray =
+ "INSERT INTO `vrHelpItemArray` "
+ "(`idglobalProperties`, `idvrHelpItem`) "
+ "VALUES "
+ "(?, ?);";
+
+const std::string kInsertHelpTimeoutPromptArray =
+ "INSERT INTO `helpTimeoutPromptArray` "
+ "(`idglobalProperties`, `idtimeoutPrompt`, `idhelpPrompt`) "
+ "VALUES "
+ "(?, ?, ?);";
+
+const std::string kInsertTTSChunk =
+ "INSERT INTO `TTSChunk` "
+ "(`type`, `text`) "
+ "VALUES "
+ "(?, ?);";
+
+const std::string kInsertApplication =
+ "INSERT INTO `application` "
+ "(`connection_key`, `grammarID`, `hashID`, "
+ "`hmiAppID`, `hmiLevel`, `ign_off_count`, "
+ "`timeStamp`, `idglobalProperties`, "
+ "`isMediaApplication`, `appID`, `deviceID`, `isSubscribedForWayPoints`) "
+ "VALUES "
+ "(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);";
+
+const std::string kSelectCountFiles =
+ "SELECT COUNT (`idfile`) "
+ "FROM `applicationFilesArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?);";
+
+const std::string kSelectFiles =
+ "SELECT `fileType`, `is_download_complete`, `persistentFile`, "
+ "`syncFileName`"
+ "FROM `file` "
+ "WHERE `idfile` IN ( "
+ "SELECT `idfile` "
+ "FROM `applicationFilesArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?));";
+
+const std::string kSelectCountSubMenu =
+ "SELECT COUNT (`idsubMenu`) "
+ "FROM `applicationSubMenuArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?);";
+
+const std::string kSelectSubMenu =
+ "SELECT `menuID`, `menuName`, `position` "
+ "FROM `subMenu` "
+ "WHERE `idsubMenu` IN (SELECT `idsubMenu` "
+ "FROM `applicationSubMenuArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?));";
+
+const std::string kSelectCountCommands =
+ "SELECT COUNT (`idcommand`) "
+ "FROM `applicationCommandsArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?);";
+
+const std::string kSelectCommands =
+ "SELECT `command`.`idcommand`, `cmdID`, `menuName`, `parentID`, "
+ "`position`, `value`, `imageType`, `vrCommand` "
+ "FROM `command` LEFT OUTER JOIN `image` on `command`.`idimage` = "
+ "`image`.`idimage` "
+ "LEFT OUTER JOIN `vrcommandsarray` on `command`.`idcommand` = "
+ "`vrcommandsarray`.`idcommand` "
+ "WHERE `command`.`idcommand` IN (SELECT `idcommand` "
+ "FROM `applicationCommandsArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?));";
+
+const std::string kSelectCountSubscriptions =
+ "SELECT COUNT (`idApplication`) "
+ "FROM `applicationSubscribtionsArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?);";
+
+const std::string kSelectSubscriptions =
+ "SELECT `vehicleValue`, `ButtonNameValue` "
+ "FROM `applicationSubscribtionsArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?);";
+
+const std::string kSelectCountChoiceSet =
+ "SELECT COUNT (`idApplication`) "
+ "FROM `applicationChoiceSetArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?);";
+
+const std::string kSelectChoiceSets =
+ "SELECT `applicationChoiceSet`.`idapplicationChoiceSet`, `grammarID`, "
+ "`interactionChoiceSetID`, "
+ "`choice`.`idchoice`, `choiceID`, `menuName`, `secondaryText`, "
+ "`tertiaryText`, `choice`.`idimage`, "
+ "`idsecondaryImage`, `vrCommand` "
+ "FROM `applicationChoiceSet` INNER JOIN `choicearray` on "
+ "`applicationChoiceSet`.`idapplicationChoiceSet` = "
+ "`choicearray`.`idapplicationChoiceSet` "
+ "INNER JOIN `choice` on `choicearray`.`idchoice` = `choice`.`idchoice` "
+ "LEFT OUTER JOIN `vrCommandsArray` on `choice`.`idchoice` = "
+ "`vrCommandsArray`.`idchoice` "
+ "WHERE `applicationChoiceSet`.`idapplicationChoiceSet` in (select "
+ "`idapplicationChoiceSet` "
+ "FROM `applicationChoiceSetArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?));";
+
+const std::string kSelectImage =
+ "SELECT `imageType`, `value` "
+ "FROM `image` "
+ "WHERE `idimage` = ?;";
+
+const std::string kSelectCountGlobalProperties =
+ "SELECT COUNT(idglobalProperties) "
+ "FROM `application` "
+ "WHERE `appID` = ? and `deviceID` = ?;";
+
+const std::string kSelectGlobalProperties =
+ "SELECT `globalProperties`.`idglobalProperties`, `vrHelpTitle`, "
+ "`menuTitle`, `idmenuIcon`, "
+ "`language`, `keyboardLayout`, `keypressMode`, `autoCompleteText`, "
+ "`helpTimeoutPromptArray`.`idhelpPrompt`, "
+ "`helpTimeoutPromptArray`.`idtimeoutPrompt` "
+ "FROM `globalProperties` LEFT OUTER JOIN `helpTimeoutPromptArray` ON "
+ "`globalProperties`.`idglobalProperties` = "
+ "`helpTimeoutPromptArray`.`idglobalProperties` "
+ "WHERE `globalProperties`.`idglobalProperties` = ( "
+ "SELECT `idglobalProperties` FROM `application` WHERE `appID` = ? AND "
+ "`deviceID` = ?);";
+
+const std::string kChecksVrHelpItem =
+ "SELECT COUNT(`idvrHelpItem`) "
+ "FROM `vrHelpItemArray` "
+ "WHERE `idglobalProperties`= ?;";
+
+const std::string kSelectVrHelpItem =
+ "SELECT `text`, `position`, `imageType`, `value` "
+ "FROM `vrHelpItem` LEFT OUTER JOIN `image` ON "
+ "`vrHelpItem`.`idimage` = `image`.`idimage` "
+ "WHERE `idvrHelpItem` in (SELECT `idvrHelpItem` "
+ "FROM `vrHelpItemArray` "
+ "WHERE `idglobalProperties` = ?);";
+
+const std::string kChecksCharacter =
+ "SELECT COUNT(`idtableLimitedCharacterList`) "
+ "FROM `characterArray` "
+ "WHERE `idglobalProperties`= ?;";
+
+const std::string kSelectCharacter =
+ "SELECT `limitedCharacterList` "
+ "FROM `tableLimitedCharacterList` "
+ "WHERE `idtableLimitedCharacterList` "
+ "in (SELECT `idtableLimitedCharacterList` "
+ "FROM `characterArray` "
+ "WHERE `idglobalProperties` = ?);";
+
+const std::string kSelectTTSChunk =
+ "SELECT `text`, `type` "
+ "FROM `TTSChunk` "
+ "WHERE `idTTSChunk` = ?;";
+
+const std::string kSelectAppTable =
+ "SELECT `appID`, `connection_key`, `grammarID`, `hashID`, `hmiAppID`, "
+ "`hmiLevel`, `ign_off_count`, "
+ "`timeStamp`, `deviceID`, `isMediaApplication`, `isSubscribedForWayPoints` "
+ "FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?;";
+
+const std::string kSelectAllApps =
+ "SELECT `appID`, `deviceID` FROM `application`;";
+
+const std::string kUpdateApplicationData =
+ "UPDATE `application` "
+ "SET `hmiLevel` = ?, `timeStamp` = ? "
+ "WHERE `appID` = ? AND `deviceID` = ?;";
+
+const std::string kSelectDBVersion =
+ "SELECT `db_version_hash` from `_internal_data`; ";
+
+const std::string kUpdateDBVersion =
+ "UPDATE `_internal_data` SET `db_version_hash` = ? ; ";
+
+const std::string kUpdateGrammarID =
+ "UPDATE `application` "
+ "SET `grammarID` = ? "
+ "WHERE `appID` = ? AND `deviceID` = ?;";
+
+const std::string kInsertSubscribedForWayPoints =
+ "INSERT INTO `subscribedForWayPoints` (`appID`) VALUES (?);";
+
+const std::string kSelectSubscribedForWayPoints =
+ "SELECT `appID` FROM `subscribedForWayPoints`;";
+
+const std::string kDeleteSubscribedForWayPoints =
+ "DELETE FROM `subscribedForWayPoints`;";
+
+} // namespace resumption
diff --git a/src/components/application_manager/src/smart_object_keys.cc b/src/components/application_manager/src/smart_object_keys.cc
new file mode 100644
index 0000000000..8b8c17fc5a
--- /dev/null
+++ b/src/components/application_manager/src/smart_object_keys.cc
@@ -0,0 +1,405 @@
+#include <application_manager/smart_object_keys.h>
+
+namespace application_manager {
+
+namespace strings {
+
+const char* params = "params";
+const char* message_type = "message_type";
+const char* correlation_id = "correlation_id";
+const char* function_id = "function_id";
+const char* protocol_version = "protocol_version";
+const char* protocol_type = "protocol_type";
+const char* connection_key = "connection_key";
+const char* error = "error";
+const char* error_msg = "message";
+const char* default_app_id = "default";
+const char* msg_params = "msg_params";
+const char* method_name = "methodName";
+const char* info = "info";
+const char* app_id = "appID";
+const char* hmi_app_id = "hmiAppID";
+const char* device_id = "deviceID";
+const char* subscribed_for_way_points = "subscribed_for_way_points";
+const char* url = "url";
+const char* urlScheme = "urlScheme";
+const char* packageName = "packageName";
+const char* cmd_icon = "cmdIcon";
+const char* result_code = "resultCode";
+const char* success = "success";
+const char* sync_msg_version = "syncMsgVersion";
+const char* major_version = "majorVersion";
+const char* minor_version = "minorVersion";
+const char* app_name = "appName";
+const char* ngn_media_screen_app_name = "ngnMediaScreenAppName";
+const char* vr_synonyms = "vrSynonyms";
+const char* uses_vehicle_data = "usesVehicleData";
+const char* is_media_application = "isMediaApplication";
+const char* greyOut = "greyOut";
+const char* language_desired = "languageDesired";
+const char* auto_activated_id = "autoActivateID";
+const char* app_type = "appType";
+const char* app_hmi_type = "appHMIType";
+const char* tts_name = "ttsName";
+const char* binary_data = "binary_data";
+const char* timeout_prompt = "timeoutPrompt";
+const char* timeout = "timeout";
+const char* vr_help_title = "vrHelpTitle";
+const char* vr_help = "vrHelp";
+const char* main_field_1 = "mainField1";
+const char* main_field_2 = "mainField2";
+const char* main_field_3 = "mainField3";
+const char* main_field_4 = "mainField4";
+const char* eta = "eta";
+const char* time_to_destination = "timeToDestination";
+const char* total_distance = "totalDistance";
+const char* alignment = "alignment";
+const char* graphic = "graphic";
+const char* secondary_graphic = "secondaryGraphic";
+const char* status_bar = "statusBar";
+const char* media_clock = "mediaClock";
+const char* media_track = "mediaTrack";
+const char* properties = "properties";
+const char* cmd_id = "cmdID";
+const char* menu_params = "menuParams";
+const char* menu_title = "menuTitle";
+const char* menu_icon = "menuIcon";
+const char* keyboard_properties = "keyboardProperties";
+const char* vr_commands = "vrCommands";
+const char* position = "position";
+const char* num_ticks = "numTicks";
+const char* slider_footer = "sliderFooter";
+const char* menu_id = "menuID";
+const char* menu_name = "menuName";
+const char* interaction_choice_set_id = "interactionChoiceSetID";
+const char* interaction_choice_set_id_list = "interactionChoiceSetIDList";
+const char* choice_set = "choiceSet";
+const char* choice_id = "choiceID";
+const char* grammar_id = "grammarID";
+const char* navigation_text_1 = "navigationText1";
+const char* navigation_text_2 = "navigationText2";
+const char* alert_text1 = "alertText1";
+const char* alert_text2 = "alertText2";
+const char* alert_text3 = "alertText3";
+const char* tts_chunks = "ttsChunks";
+const char* initial_prompt = "initialPrompt";
+const char* initial_text = "initialText";
+const char* duration = "duration";
+const char* progress_indicator = "progressIndicator";
+const char* alert_type = "alertType";
+const char* play_tone = "playTone";
+const char* soft_buttons = "softButtons";
+const char* soft_button_id = "softButtonID";
+const char* custom_presets = "customPresets";
+const char* audio_pass_display_text1 = "audioPassThruDisplayText1";
+const char* audio_pass_display_text2 = "audioPassThruDisplayText2";
+const char* max_duration = "maxDuration";
+const char* sampling_rate = "samplingRate";
+const char* bits_per_sample = "bitsPerSample";
+const char* audio_type = "audioType";
+const char* mute_audio = "muteAudio";
+const char* button_name = "buttonName";
+const char* button_event_mode = "buttonEventMode";
+const char* button_press_mode = "buttonPressMode";
+const char* custom_button_id = "customButtonID";
+const char* data_type = "dataType";
+const char* turn_list = "turnList";
+const char* turn_icon = "turnIcon";
+const char* next_turn_icon = "nextTurnIcon";
+const char* value = "value";
+const char* hmi_display_language = "hmiDisplayLanguage";
+const char* language = "language";
+const char* data = "data";
+const char* start_time = "startTime";
+const char* end_time = "endTime";
+const char* hours = "hours";
+const char* minutes = "minutes";
+const char* seconds = "seconds";
+const char* update_mode = "updateMode";
+const char* trigger_source = "triggerSource";
+const char* hmi_level = "hmiLevel";
+const char* activate_app_hmi_level = "level";
+const char* audio_streaming_state = "audioStreamingState";
+const char* system_context = "systemContext";
+const char* speech_capabilities = "speechCapabilities";
+const char* vr_capabilities = "vrCapabilities";
+const char* audio_pass_thru_capabilities = "audioPassThruCapabilities";
+const char* pcm_stream_capabilities = "pcmStreamCapabilities";
+// PutFile
+const char* sync_file_name = "syncFileName";
+const char* file_name = "fileName";
+const char* file_type = "fileType";
+const char* file_size = "fileSize";
+const char* request_type = "requestType";
+const char* persistent_file = "persistentFile";
+const char* file_data = "fileData";
+const char* space_available = "spaceAvailable";
+const char* image_type = "imageType";
+const char* image = "image";
+const char* type = "type";
+const char* system_file = "systemFile";
+const char* offset = "offset";
+const char* length = "length";
+const char* secondary_image = "secondaryImage";
+const char* filenames = "filenames";
+
+const char* hmi_display_language_desired = "hmiDisplayLanguageDesired";
+const char* ecu_name = "ecuName";
+const char* dtc_mask = "dtcMask";
+const char* did_location = "didLocation";
+const char* app_list = "appList";
+const char* device_list = "deviceList";
+const char* device_info = "deviceInfo";
+const char* name = "name";
+const char* id = "id";
+const char* isSDLAllowed = "isSDLAllowed";
+const char* transport_type = "transportType";
+const char* application = "application";
+const char* applications = "applications";
+const char* icon = "icon";
+const char* device_name = "deviceName";
+const char* reason = "reason";
+const char* available = "available";
+const char* text = "text";
+const char* character_set = "characterSet";
+const char* secondary_text = "secondaryText";
+const char* tertiary_text = "tertiaryText";
+const char* hardware = "hardware";
+const char* firmware_rev = "firmwareRev";
+const char* os = "os";
+const char* os_version = "osVersion";
+const char* carrier = "carrier";
+const char* slider_header = "sliderHeader";
+const char* key_press_mode = "keypressMode";
+
+// duplicate names from hmi_request
+const char* limited_character_list = "limitedCharacterList";
+const char* auto_complete_text = "autoCompleteText";
+const char* navigation_text = "navigationText";
+
+// vehicle info
+const char* gps = "gps";
+const char* speed = "speed";
+const char* rpm = "rpm";
+const char* fuel_level = "fuelLevel";
+const char* fuel_level_state = "fuelLevel_State";
+const char* instant_fuel_consumption = "instantFuelConsumption";
+const char* external_temp = "externalTemperature";
+const char* vin = "vin";
+const char* prndl = "prndl";
+const char* tire_pressure = "tirePressure";
+const char* odometer = "odometer";
+const char* belt_status = "beltStatus";
+const char* body_information = "bodyInformation";
+const char* device_status = "deviceStatus";
+const char* driver_braking = "driverBraking";
+const char* wiper_status = "wiperStatus";
+const char* head_lamp_status = "headLampStatus";
+const char* engine_torque = "engineTorque";
+const char* acc_pedal_pos = "accPedalPosition";
+const char* steering_wheel_angle = "steeringWheelAngle";
+const char* e_call_info = "eCallInfo";
+const char* airbag_status = "airbagStatus";
+const char* emergency_event = "emergencyEvent";
+const char* cluster_mode_status = "clusterModeStatus";
+const char* my_key = "myKey";
+const char* help_prompt = "helpPrompt";
+const char* scroll_message_body = "scrollableMessageBody";
+const char* data_result = "dataResult";
+const char* dtc_list = "dtcList";
+const char* interaction_mode = "interactionMode";
+const char* slider_position = "sliderPosition";
+const char* system_action = "systemAction";
+const char* prerecorded_speech = "prerecordedSpeech";
+const char* supported_diag_modes = "supportedDiagModes";
+const char* hmi_capabilities = "hmiCapabilities";
+const char* navigation = "navigation";
+const char* phone_call = "phoneCall";
+const char* sdl_version = "sdlVersion";
+const char* system_software_version = "systemSoftwareVersion";
+const char* priority = "priority";
+
+// resuming
+const char* application_commands = "applicationCommands";
+const char* application_submenus = "applicationSubMenus";
+const char* application_choice_sets = "applicationChoiceSets";
+const char* application_global_properties = "globalProperties";
+const char* application_vehicle_info = "vehicleInfo";
+const char* application_buttons = "buttons";
+const char* application_subscribtions = "subscribtions";
+const char* application_files = "applicationFiles";
+const char* application_show = "applicationShow";
+const char* resumption = "resumption";
+const char* resume_app_list = "resume_app_list";
+const char* last_ign_off_time = "last_ign_off_time";
+
+const char* resume_vr_grammars = "resumeVrGrammars";
+
+const char* ign_off_count = "ign_off_count";
+const char* suspend_count = "suspend_count";
+
+const char* connection_info = "connection_info";
+const char* is_download_complete = "is_download_complete";
+
+const char* hash_id = "hashID";
+const char* time_stamp = "timeStamp";
+const char* manual_text_entry = "manualTextEntry";
+const char* image_type_supported = "imageTypeSupported";
+const char* unexpected_disconnect = "unexpectedDisconnect";
+const char* longitude_degrees = "longitudeDegrees";
+const char* latitude_degrees = "latitudeDegrees";
+const char* address = "address";
+const char* country_name = "countryName";
+const char* country_code = "countryCode";
+const char* postal_code = "postalCode";
+const char* administrative_area = "administrativeArea";
+const char* locality = "locality";
+const char* sub_locality = "subLocality";
+const char* thoroughfare = "thoroughfare";
+const char* sub_thoroughfare = "subThoroughfare";
+const char* location_name = "locationName";
+const char* location_description = "locationDescription";
+const char* address_lines = "addressLines";
+const char* phone_number = "phoneNumber";
+const char* number = "number";
+const char* location_image = "locationImage";
+const char* is_suscribed = "isSubscribed";
+const char* message_data = "messageData";
+
+const char* delivery_mode = "deliveryMode";
+} // namespace strings
+
+namespace json {
+const char* appId = "appId";
+const char* name = "name";
+const char* ios = "ios";
+const char* android = "android";
+const char* appHmiType = "appHmiType";
+const char* urlScheme = "urlScheme";
+const char* packageName = "packageName";
+const char* response = "response";
+const char* is_media_application = "isMediaApplication";
+const char* default_ = "default";
+const char* languages = "languages";
+const char* ttsName = "ttsName";
+const char* vrSynonyms = "vrSynonyms";
+} // namespace json
+
+namespace http_request {
+const char* httpRequest = "HTTPRequest";
+const char* headers = "headers";
+const char* content_type = "ContentType";
+const char* connect_timeout = "ConnectTimout";
+const char* do_output = "DoOutput";
+const char* do_input = "DoInput";
+const char* use_caches = "UseCaches";
+const char* request_method = "RequestMethod";
+const char* read_timeout = "ReadTimeout";
+const char* instance_follow_redirect = "InstanceFollowRedirect";
+const char* charset = "charset";
+const char* content_lenght = "Content_Lenght";
+const char* GET = "GET";
+} // http_request
+
+namespace mobile_notification {
+const char* state = "state";
+const char* syncp_timeout = "Timeout";
+const char* syncp_url = "URL";
+} // namespace mobile_notification
+
+namespace hmi_levels {
+const char* kFull = "FULL";
+const char* kLimited = "LIMITED";
+const char* kBackground = "BACKGROUND";
+const char* kNone = "NONE";
+}
+
+namespace hmi_request {
+const char* parent_id = "parentID";
+const char* field_name = "fieldName";
+const char* field_text = "fieldText";
+const char* alert_strings = "alertStrings";
+const char* duration = "duration";
+const char* soft_buttons = "softButtons";
+const char* tts_chunks = "ttsChunks";
+const char* speak_type = "speakType";
+const char* audio_pass_display_texts = "audioPassThruDisplayTexts";
+const char* max_duration = "maxDuration";
+const char* reason = "reason";
+const char* message_text = "messageText";
+const char* initial_text = "initialText";
+const char* navi_texts = "navigationTexts";
+const char* navi_text = "navigationText";
+const char* show_strings = "showStrings";
+const char* interaction_layout = "interactionLayout";
+const char* menu_title = "menuTitle";
+const char* menu_icon = "menuIcon";
+const char* keyboard_properties = "keyboardProperties";
+const char* method_name = "methodName";
+const char* keyboard_layout = "keyboardLayout";
+const char* limited_character_list = "limitedCharacterList";
+const char* auto_complete_text = "autoCompleteText";
+const char* file = "file";
+const char* retry = "retry";
+const char* service = "service";
+} // namespace hmi_request
+
+namespace hmi_response {
+const char* code = "code";
+const char* message = "message";
+const char* method = "method";
+const char* try_again_time = "tryAgainTime";
+const char* custom_button_id = "customButtonID";
+const char* button_name = "name";
+const char* button_mode = "mode";
+const char* attenuated_supported = "attenuatedSupported";
+const char* languages = "languages";
+const char* language = "language";
+const char* display_capabilities = "displayCapabilities";
+const char* hmi_zone_capabilities = "hmiZoneCapabilities";
+const char* soft_button_capabilities = "softButtonCapabilities";
+const char* image_supported = "imageSupported";
+const char* button_capabilities = "buttonCapabilities";
+const char* capabilities = "capabilities";
+const char* speech_capabilities = "speechCapabilities";
+const char* prerecorded_speech_capabilities = "prerecordedSpeechCapabilities";
+const char* preset_bank_capabilities = "presetBankCapabilities";
+const char* allowed = "allowed";
+const char* vehicle_type = "vehicleType";
+const char* did_result = "didResult";
+const char* result_code = "resultCode";
+const char* dtc = "dtc";
+const char* ecu_header = "ecuHeader";
+const char* image_capabilities = "imageCapabilities";
+const char* display_type = "displayType";
+const char* text_fields = "textFields";
+const char* media_clock_formats = "mediaClockFormats";
+const char* graphic_supported = "graphicSupported";
+const char* image_fields = "imageFields";
+const char* templates_available = "templatesAvailable";
+const char* screen_params = "screenParams";
+const char* num_custom_presets_available = "numCustomPresetsAvailable";
+const char* urls = "urls";
+const char* policy_app_id = "policyAppID";
+const char* enabled = "enabled";
+
+} // namespace hmi_response
+
+namespace hmi_notification {
+const char* prndl = "prndl";
+const char* file_name = "file_name";
+const char* system_context = "systemContext";
+const char* state = "state";
+const char* result = "result";
+const char* statistic_type = "statisticType";
+const char* error = "error";
+const char* policyfile = "policyfile";
+const char* is_active = "isActive";
+const char* is_deactivated = "isDeactivated";
+const char* event_name = "eventName";
+
+} // namespace hmi_notification
+
+} // namespace application_manager
+
+#
diff --git a/src/components/application_manager/src/state_context.cc b/src/components/application_manager/src/state_context.cc
deleted file mode 100644
index ae3b40e094..0000000000
--- a/src/components/application_manager/src/state_context.cc
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-#include "application_manager/state_context.h"
-#include "application_manager/application_manager_impl.h"
-#include "config_profile/profile.h"
-
-namespace application_manager {
-
-
-bool StateContext::is_navi_app(const uint32_t app_id) const {
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(app_id);
- DCHECK_OR_RETURN(app, false);
- return app ? app->is_navi() : false;
-}
-
-bool StateContext::is_meida_app(const uint32_t app_id) const {
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(app_id);
- return app ? app->is_media_application() : false;
-}
-
-bool StateContext::is_voice_comunication_app(const uint32_t app_id) const {
- ApplicationSharedPtr app = ApplicationManagerImpl::instance()->application(app_id);
- return app ? app->is_voice_communication_supported() : false;
-}
-
-bool StateContext::is_attenuated_supported() const{
- const HMICapabilities& hmi_capabilities =
- ApplicationManagerImpl::instance()->hmi_capabilities();
- return hmi_capabilities.attenuated_supported() &&
- profile::Profile::instance()->is_mixing_audio_supported();
-}
-
-}
diff --git a/src/components/application_manager/src/state_controller.cc b/src/components/application_manager/src/state_controller.cc
deleted file mode 100644
index 05aaa2d2eb..0000000000
--- a/src/components/application_manager/src/state_controller.cc
+++ /dev/null
@@ -1,469 +0,0 @@
-/*
- Copyright (c) 2015, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "application_manager/state_controller.h"
-#include "application_manager/application_manager_impl.h"
-#include "application_manager/message_helper.h"
-#include "utils/helpers.h"
-
-namespace application_manager {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "StateController");
-
-bool IsStatusChanged(HmiStatePtr old_state, HmiStatePtr new_state) {
- if (old_state->hmi_level() != new_state->hmi_level() ||
- old_state->audio_streaming_state() !=
- new_state->audio_streaming_state() ||
- old_state->system_context() != new_state->system_context()) {
- return true;
- }
- return false;
-}
-
-StateController::StateController() : EventObserver() {
- subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_OnEmergencyEvent);
- subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_OnPhoneCall);
- subscribe_on_event(hmi_apis::FunctionID::TTS_Started);
- subscribe_on_event(hmi_apis::FunctionID::TTS_Stopped);
- subscribe_on_event(hmi_apis::FunctionID::VR_Started);
- subscribe_on_event(hmi_apis::FunctionID::VR_Stopped);
-}
-
-void StateController::SetRegularState(
- ApplicationSharedPtr app,
- const mobile_apis::AudioStreamingState::eType audio_state) {
- if (!app) {
- return;
- }
- HmiStatePtr prev_state = app->RegularHmiState();
- DCHECK_OR_RETURN_VOID(prev_state);
- HmiStatePtr hmi_state =
- CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
- DCHECK_OR_RETURN_VOID(hmi_state);
- hmi_state->set_hmi_level(prev_state->hmi_level());
- hmi_state->set_audio_streaming_state(audio_state);
- hmi_state->set_system_context(prev_state->system_context());
- SetRegularState<false>(app, hmi_state);
-}
-
-void StateController::HmiLevelConflictResolver::
-operator()(ApplicationSharedPtr to_resolve) {
- using namespace mobile_apis;
- using namespace helpers;
- DCHECK_OR_RETURN_VOID(state_ctrl_);
- if (to_resolve == applied_)
- return;
- if (Compare<HMILevel::eType, EQ, ONE>(state_->hmi_level(), HMILevel::HMI_FULL,
- HMILevel::HMI_LIMITED)) {
- HmiStatePtr cur_state = to_resolve->RegularHmiState();
- if (Compare<HMILevel::eType, EQ, ONE>(cur_state->hmi_level(),
- HMILevel::HMI_FULL,
- HMILevel::HMI_LIMITED)) {
- if (applied_->IsAudioApplication() &&
- state_ctrl_->IsSameAppType(applied_, to_resolve)) {
- state_ctrl_->SetupRegularHmiState(to_resolve, HMILevel::HMI_BACKGROUND,
- AudioStreamingState::NOT_AUDIBLE);
- } else {
- state_ctrl_->SetupRegularHmiState(to_resolve, HMILevel::HMI_LIMITED,
- AudioStreamingState::AUDIBLE);
- }
- }
- }
-}
-
-void StateController::SetupRegularHmiState(ApplicationSharedPtr app,
- HmiStatePtr state) {
- using namespace mobile_apis;
- LOG4CXX_AUTO_TRACE(logger_);
- DCHECK_OR_RETURN_VOID(state);
- LOG4CXX_DEBUG(logger_, "hmi_level " << state->hmi_level() << ", audio_state "
- << state->audio_streaming_state()
- << ", system_context "
- << state->system_context());
- HmiStatePtr curr_state = app->CurrentHmiState();
- HmiStatePtr old_state =
- CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
- DCHECK_OR_RETURN_VOID(old_state);
- old_state->set_hmi_level(curr_state->hmi_level());
- old_state->set_audio_streaming_state(curr_state->audio_streaming_state());
- old_state->set_system_context(curr_state->system_context());
- app->SetRegularState(state);
- if (state->hmi_level() == mobile_apis::HMILevel::HMI_NONE) {
- app->ResetDataInNone();
- }
- if (!app->IsAudioApplication()) {
- if (state->hmi_level() == HMILevel::HMI_LIMITED) {
- LOG4CXX_ERROR(logger_, "Trying to setup LIMITED to non audio app");
- state->set_hmi_level(HMILevel::HMI_BACKGROUND);
- }
- if (state->audio_streaming_state() != AudioStreamingState::NOT_AUDIBLE) {
- LOG4CXX_ERROR(logger_, "Trying to setup audio state "
- << state->audio_streaming_state()
- << " to non audio app");
- state->set_audio_streaming_state(AudioStreamingState::NOT_AUDIBLE);
- }
- }
- HmiStatePtr new_state = app->CurrentHmiState();
- OnStateChanged(app, old_state, new_state);
-}
-
-void StateController::SetupRegularHmiState(
- ApplicationSharedPtr app, const mobile_apis::HMILevel::eType hmi_level,
- const mobile_apis::AudioStreamingState::eType audio_state) {
- using namespace mobile_apis;
- using namespace helpers;
- LOG4CXX_AUTO_TRACE(logger_);
- DCHECK_OR_RETURN_VOID(app);
- HmiStatePtr prev_state = app->RegularHmiState();
- DCHECK_OR_RETURN_VOID(prev_state);
- HmiStatePtr new_state =
- CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
- DCHECK_OR_RETURN_VOID(new_state);
- new_state->set_hmi_level(hmi_level);
- new_state->set_audio_streaming_state(audio_state);
- new_state->set_system_context(prev_state->system_context());
- SetupRegularHmiState(app, new_state);
-}
-
-void StateController::ApplyRegularState(ApplicationSharedPtr app,
- HmiStatePtr state) {
- DCHECK_OR_RETURN_VOID(app);
- DCHECK_OR_RETURN_VOID(state);
- DCHECK_OR_RETURN_VOID(state->state_id() == HmiState::STATE_ID_REGULAR);
- SetupRegularHmiState(app, state);
- ForEachApplication<HmiLevelConflictResolver, ApplicationManagerImpl>(
- HmiLevelConflictResolver(app, state, this));
-}
-
-bool StateController::IsSameAppType(ApplicationConstSharedPtr app1,
- ApplicationConstSharedPtr app2) {
- return app1->is_media_application() == app2->is_media_application() ||
- app1->is_navi() == app2->is_navi() ||
- app1->is_voice_communication_supported() ==
- app2->is_voice_communication_supported();
-}
-
-void StateController::on_event(const event_engine::Event &event) {
- using namespace smart_objects;
- using namespace event_engine;
- using namespace hmi_apis;
-
- LOG4CXX_AUTO_TRACE(logger_);
- const SmartObject &message = event.smart_object();
- const FunctionID::eType id = static_cast<FunctionID::eType>(event.id());
- switch (id) {
- case FunctionID::BasicCommunication_ActivateApp: {
- OnActivateAppResponse(message);
- break;
- }
- case FunctionID::BasicCommunication_OnEmergencyEvent: {
- bool is_active =
- message[strings::msg_params][hmi_response::enabled].asBool();
- if (is_active) {
- OnSafetyModeEnabled();
- } else {
- OnSafetyModeDisabled();
- }
- break;
- }
- case FunctionID::BasicCommunication_OnPhoneCall: {
- bool is_active =
- message[strings::msg_params][hmi_notification::is_active].asBool();
- if (is_active) {
- OnPhoneCallStarted();
- } else {
- OnPhoneCallEnded();
- }
- break;
- }
- case FunctionID::VR_Started: {
- OnVRStarted();
- break;
- }
- case FunctionID::VR_Stopped: {
- OnVREnded();
- break;
- }
- case FunctionID::TTS_Started: {
- OnTTSStarted();
- break;
- }
- case FunctionID::TTS_Stopped: {
- OnTTSStopped();
- break;
- }
- default:
- break;
- }
-}
-
-void StateController::OnStateChanged(ApplicationSharedPtr app,
- HmiStatePtr old_state,
- HmiStatePtr new_state) {
- DCHECK_OR_RETURN_VOID(app);
- DCHECK_OR_RETURN_VOID(old_state);
- DCHECK_OR_RETURN_VOID(new_state);
- if (IsStatusChanged(old_state, new_state)) {
- MessageHelper::SendHMIStatusNotification(*app);
- if (new_state->hmi_level() == mobile_apis::HMILevel::HMI_NONE) {
- app->ResetDataInNone();
- }
- ApplicationManagerImpl::instance()->OnHMILevelChanged(
- app->app_id(), old_state->hmi_level(), new_state->hmi_level());
- } else {
- LOG4CXX_ERROR(logger_, "Status not changed");
- }
-}
-
-void StateController::OnApplicationRegistered(
- ApplicationSharedPtr app,
- const mobile_apis::HMILevel::eType default_level) {
- namespace HMILevel = mobile_apis::HMILevel;
- namespace AudioStreamingState = mobile_apis::AudioStreamingState;
- namespace SystemContext = mobile_apis::SystemContext;
- LOG4CXX_AUTO_TRACE(logger_);
- DCHECK_OR_RETURN_VOID(app);
-
- active_states_lock_.Acquire();
- StateIDList::iterator it = active_states_.begin();
- for (; it != active_states_.end(); ++it) {
- HmiStatePtr new_state = CreateHmiState(app->app_id(), *it);
- DCHECK_OR_RETURN_VOID(new_state);
- DCHECK_OR_RETURN_VOID(new_state->state_id() != HmiState::STATE_ID_REGULAR);
- HmiStatePtr old_hmi_state = app->CurrentHmiState();
- new_state->set_parent(old_hmi_state);
- app->AddHMIState(new_state);
- }
- active_states_lock_.Release();
-
- HmiStatePtr default_state =
- CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
- DCHECK_OR_RETURN_VOID(default_state);
- default_state->set_hmi_level(default_level);
- default_state->set_audio_streaming_state(CalcAudioState(app, default_level));
- default_state->set_system_context(SystemContext::SYSCTXT_MAIN);
-
- HmiStatePtr initial_state = app->RegularHmiState();
-
- app->SetRegularState(default_state);
-
- HmiStatePtr new_state = app->CurrentHmiState();
-
- OnStateChanged(app, initial_state, new_state);
-}
-
-void StateController::TempStateStarted(HmiState::StateID ID) {
- LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock autolock(active_states_lock_);
- StateIDList::iterator it =
- std::find(active_states_.begin(), active_states_.end(), ID);
- if (it == active_states_.end()) {
- active_states_.push_back(ID);
- } else {
- LOG4CXX_ERROR(logger_, "StateID " << ID << " is already active");
- }
-}
-
-void StateController::TempStateStopped(HmiState::StateID ID) {
- LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock autolock(active_states_lock_);
- active_states_.remove(ID);
-}
-void StateController::OnActivateAppResponse(
- const smart_objects::SmartObject &message) {
- const hmi_apis::Common_Result::eType code =
- static_cast<hmi_apis::Common_Result::eType>(
- message[strings::params][hmi_response::code].asInt());
- const int32_t correlation_id =
- message[strings::params][strings::correlation_id].asInt();
- const uint32_t hmi_app_id =
- ApplicationManagerImpl::instance()->application_id(correlation_id);
- ApplicationSharedPtr application =
- ApplicationManagerImpl::instance()->application_by_hmi_app(hmi_app_id);
- if (application) {
- HmiStatePtr pending_state = waiting_for_activate[application->app_id()];
- DCHECK_OR_RETURN_VOID(pending_state);
- if (code != hmi_apis::Common_Result::SUCCESS) {
- const HmiStatePtr cur = application->RegularHmiState();
- pending_state->set_hmi_level(cur->hmi_level());
- }
- ApplyRegularState(application, pending_state);
- }
-}
-
-void StateController::OnPhoneCallStarted() {
- LOG4CXX_AUTO_TRACE(logger_);
- ForEachApplication(std::bind1st(
- std::mem_fun(
- &StateController::HMIStateStarted<HmiState::STATE_ID_PHONE_CALL>),
- this));
- TempStateStarted(HmiState::STATE_ID_PHONE_CALL);
-}
-
-void StateController::OnPhoneCallEnded() {
- LOG4CXX_AUTO_TRACE(logger_);
- ForEachApplication(std::bind1st(
- std::mem_fun(
- &StateController::HMIStateStopped<HmiState::STATE_ID_PHONE_CALL>),
- this));
- TempStateStopped(HmiState::STATE_ID_PHONE_CALL);
-}
-
-void StateController::OnSafetyModeEnabled() {
- LOG4CXX_AUTO_TRACE(logger_);
- ForEachApplication(std::bind1st(
- std::mem_fun(
- &StateController::HMIStateStarted<HmiState::STATE_ID_SAFETY_MODE>),
- this));
- TempStateStarted(HmiState::STATE_ID_SAFETY_MODE);
-}
-
-void StateController::OnSafetyModeDisabled() {
- LOG4CXX_AUTO_TRACE(logger_);
-
- ForEachApplication(std::bind1st(
- std::mem_fun(
- &StateController::HMIStateStopped<HmiState::STATE_ID_SAFETY_MODE>),
- this));
- TempStateStopped(HmiState::STATE_ID_SAFETY_MODE);
-}
-
-void StateController::OnVRStarted() {
- LOG4CXX_AUTO_TRACE(logger_);
- ForEachApplication(std::bind1st(
- std::mem_fun(
- &StateController::HMIStateStarted<HmiState::STATE_ID_VR_SESSION>),
- this));
- TempStateStarted(HmiState::STATE_ID_VR_SESSION);
-}
-
-void StateController::OnVREnded() {
- LOG4CXX_AUTO_TRACE(logger_);
- ForEachApplication(std::bind1st(
- std::mem_fun(
- &StateController::HMIStateStopped<HmiState::STATE_ID_VR_SESSION>),
- this));
- TempStateStopped(HmiState::STATE_ID_VR_SESSION);
-}
-
-void StateController::OnTTSStarted() {
- LOG4CXX_AUTO_TRACE(logger_);
- ForEachApplication(std::bind1st(
- std::mem_fun(
- &StateController::HMIStateStarted<HmiState::STATE_ID_TTS_SESSION>),
- this));
- TempStateStarted(HmiState::STATE_ID_TTS_SESSION);
-}
-
-void StateController::OnTTSStopped() {
- LOG4CXX_AUTO_TRACE(logger_);
- ForEachApplication(std::bind1st(
- std::mem_fun(
- &StateController::HMIStateStopped<HmiState::STATE_ID_TTS_SESSION>),
- this));
- TempStateStopped(HmiState::STATE_ID_TTS_SESSION);
-}
-
-void StateController::OnNaviStreamingStarted() {
- LOG4CXX_AUTO_TRACE(logger_);
- ForEachApplication(std::bind1st(
- std::mem_fun(
- &StateController::HMIStateStarted<HmiState::STATE_ID_NAVI_STREAMING>),
- this));
- TempStateStarted(HmiState::STATE_ID_NAVI_STREAMING);
-}
-
-void StateController::OnNaviStreamingStopped() {
- LOG4CXX_AUTO_TRACE(logger_);
- ForEachApplication(std::bind1st(
- std::mem_fun(
- &StateController::HMIStateStopped<HmiState::STATE_ID_NAVI_STREAMING>),
- this));
- TempStateStopped(HmiState::STATE_ID_NAVI_STREAMING);
-}
-
-HmiStatePtr StateController::CreateHmiState(uint32_t app_id,
- HmiState::StateID state_id) {
- LOG4CXX_AUTO_TRACE(logger_);
- HmiStatePtr new_state;
- switch (state_id) {
- case HmiState::STATE_ID_PHONE_CALL: {
- new_state.reset(new PhoneCallHmiState(app_id, state_context_));
- break;
- }
- case HmiState::STATE_ID_SAFETY_MODE: {
- new_state.reset(new SafetyModeHmiState(app_id, state_context_));
- break;
- }
- case HmiState::STATE_ID_VR_SESSION: {
- new_state.reset(new VRHmiState(app_id, state_context_));
- break;
- }
- case HmiState::STATE_ID_TTS_SESSION: {
- new_state.reset(new TTSHmiState(app_id, state_context_));
- break;
- }
- case HmiState::STATE_ID_NAVI_STREAMING: {
- new_state.reset(new NaviStreamingHmiState(app_id, state_context_));
- break;
- }
- case HmiState::STATE_ID_REGULAR: {
- new_state.reset(new HmiState(app_id, state_context_));
- break;
- }
- default:
- LOG4CXX_FATAL(logger_, "Invalid state_id " << state_id);
- NOTREACHED();
- break;
- }
- return new_state;
-}
-
-mobile_apis::AudioStreamingState::eType StateController::CalcAudioState(
- ApplicationSharedPtr app,
- const mobile_apis::HMILevel::eType hmi_level) const {
- namespace HMILevel = mobile_apis::HMILevel;
- namespace AudioStreamingState = mobile_apis::AudioStreamingState;
- using helpers::Compare;
- using helpers::EQ;
- using helpers::ONE;
-
- AudioStreamingState::eType audio_state = AudioStreamingState::NOT_AUDIBLE;
- if (Compare<HMILevel::eType, EQ, ONE>(hmi_level, HMILevel::HMI_FULL,
- HMILevel::HMI_LIMITED)) {
- if (app->IsAudioApplication()) {
- audio_state = AudioStreamingState::AUDIBLE;
- }
- }
- return audio_state;
-}
-}
diff --git a/src/components/application_manager/src/state_controller_impl.cc b/src/components/application_manager/src/state_controller_impl.cc
new file mode 100644
index 0000000000..839cc13026
--- /dev/null
+++ b/src/components/application_manager/src/state_controller_impl.cc
@@ -0,0 +1,966 @@
+/*
+ Copyright (c) 2015, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/state_controller_impl.h"
+#include "application_manager/usage_statistics.h"
+#include "utils/helpers.h"
+#include "utils/make_shared.h"
+#include "connection_handler/connection_handler.h"
+
+namespace application_manager {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "StateControllerImpl")
+
+bool IsStatusChanged(HmiStatePtr old_state, HmiStatePtr new_state) {
+ if (old_state->hmi_level() != new_state->hmi_level() ||
+ old_state->audio_streaming_state() !=
+ new_state->audio_streaming_state() ||
+ old_state->system_context() != new_state->system_context()) {
+ return true;
+ }
+ return false;
+}
+
+StateControllerImpl::StateControllerImpl(ApplicationManager& app_mngr)
+ : EventObserver(app_mngr.event_dispatcher()), app_mngr_(app_mngr) {
+ subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_OnAppActivated);
+ subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_OnAppDeactivated);
+ subscribe_on_event(hmi_apis::FunctionID::TTS_Started);
+ subscribe_on_event(hmi_apis::FunctionID::TTS_Stopped);
+ subscribe_on_event(hmi_apis::FunctionID::VR_Started);
+ subscribe_on_event(hmi_apis::FunctionID::VR_Stopped);
+ subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_OnEventChanged);
+}
+
+void StateControllerImpl::SetRegularState(ApplicationSharedPtr app,
+ HmiStatePtr state,
+ const bool send_activate_app) {
+ CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Invalid application pointer");
+ return;
+ }
+ DCHECK_OR_RETURN_VOID(state);
+ DCHECK_OR_RETURN_VOID(state->state_id() == HmiState::STATE_ID_REGULAR);
+
+ if (state->hmi_level() == mobile_apis::HMILevel::INVALID_ENUM ||
+ state->audio_streaming_state() ==
+ mobile_apis::AudioStreamingState::INVALID_ENUM ||
+ state->system_context() == mobile_apis::SystemContext::INVALID_ENUM) {
+ LOG4CXX_ERROR(logger_, "Get invalid state");
+ return;
+ }
+
+ if (app->is_resuming() && !IsResumptionAllowed(app, state)) {
+ return;
+ }
+
+ HmiStatePtr resolved_state = ResolveHmiState(app, state);
+ if (!resolved_state) {
+ state->set_state_id(HmiState::STATE_ID_POSTPONED);
+ app->SetPostponedState(state);
+ return;
+ }
+ hmi_apis::Common_HMILevel::eType hmi_level =
+ static_cast<hmi_apis::Common_HMILevel::eType>(
+ resolved_state->hmi_level());
+
+ const bool is_full_allowed = (hmi_apis::Common_HMILevel::FULL == hmi_level);
+
+ if (send_activate_app && is_full_allowed) {
+ const int64_t corr_id = SendBCActivateApp(app, hmi_level, true);
+ if (-1 != corr_id) {
+ subscribe_on_event(hmi_apis::FunctionID::BasicCommunication_ActivateApp,
+ corr_id);
+ waiting_for_activate[app->app_id()] = resolved_state;
+ return;
+ }
+ LOG4CXX_ERROR(logger_, "Unable to send BC.ActivateApp");
+ return;
+ }
+ ApplyRegularState(app, resolved_state);
+}
+
+void StateControllerImpl::SetRegularState(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const mobile_apis::AudioStreamingState::eType audio_state,
+ const bool send_activate_app) {
+ CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Invalid application pointer");
+ return;
+ }
+ HmiStatePtr prev_regular = app->RegularHmiState();
+ DCHECK_OR_RETURN_VOID(prev_regular);
+ HmiStatePtr hmi_state =
+ CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
+ DCHECK_OR_RETURN_VOID(hmi_state);
+ hmi_state->set_hmi_level(hmi_level);
+ hmi_state->set_audio_streaming_state(audio_state);
+ hmi_state->set_system_context(prev_regular->system_context());
+ SetRegularState(app, hmi_state, send_activate_app);
+}
+
+void StateControllerImpl::SetRegularState(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const bool send_activate_app) {
+ using namespace mobile_apis;
+ using namespace helpers;
+ CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Invalid application pointer");
+ return;
+ }
+ const HmiStatePtr hmi_state =
+ CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
+
+ DCHECK_OR_RETURN_VOID(hmi_state);
+ hmi_state->set_hmi_level(hmi_level);
+ hmi_state->set_audio_streaming_state(CalcAudioState(app, hmi_level));
+ hmi_state->set_system_context(SystemContext::SYSCTXT_MAIN);
+ SetRegularState(app, hmi_state, send_activate_app);
+}
+
+void StateControllerImpl::SetRegularState(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const mobile_apis::AudioStreamingState::eType audio_state,
+ const mobile_apis::SystemContext::eType system_context,
+ const bool send_activate_app) {
+ CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Invalid application pointer");
+ return;
+ }
+ HmiStatePtr hmi_state =
+ CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
+ DCHECK_OR_RETURN_VOID(hmi_state);
+ hmi_state->set_hmi_level(hmi_level);
+ hmi_state->set_audio_streaming_state(audio_state);
+ hmi_state->set_system_context(system_context);
+ SetRegularState(app, hmi_state, send_activate_app);
+}
+
+void StateControllerImpl::SetRegularState(
+ ApplicationSharedPtr app, const mobile_apis::HMILevel::eType hmi_level) {
+ CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Invalid application pointer");
+ return;
+ }
+ HmiStatePtr prev_state = app->RegularHmiState();
+ HmiStatePtr hmi_state =
+ CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
+ DCHECK_OR_RETURN_VOID(hmi_state);
+ hmi_state->set_hmi_level(hmi_level);
+ hmi_state->set_audio_streaming_state(CalcAudioState(app, hmi_level));
+ hmi_state->set_system_context(prev_state
+ ? prev_state->system_context()
+ : mobile_apis::SystemContext::SYSCTXT_MAIN);
+ SetRegularState(app, hmi_state);
+}
+
+void StateControllerImpl::SetRegularState(
+ ApplicationSharedPtr app,
+ const mobile_apis::SystemContext::eType system_context) {
+ CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Invalid application pointer");
+ return;
+ }
+ HmiStatePtr prev_regular = app->RegularHmiState();
+ DCHECK_OR_RETURN_VOID(prev_regular);
+ HmiStatePtr hmi_state =
+ CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
+ DCHECK_OR_RETURN_VOID(hmi_state);
+ hmi_state->set_hmi_level(prev_regular->hmi_level());
+ hmi_state->set_audio_streaming_state(
+ CalcAudioState(app, prev_regular->hmi_level()));
+ hmi_state->set_system_context(system_context);
+ SetRegularState(app, hmi_state, false);
+}
+
+void StateControllerImpl::SetRegularState(
+ ApplicationSharedPtr app,
+ const mobile_apis::AudioStreamingState::eType audio_state) {
+ CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Invalid application pointer");
+ return;
+ }
+ HmiStatePtr prev_state = app->RegularHmiState();
+ DCHECK_OR_RETURN_VOID(prev_state);
+ HmiStatePtr hmi_state =
+ CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
+ DCHECK_OR_RETURN_VOID(hmi_state);
+ hmi_state->set_hmi_level(prev_state->hmi_level());
+ hmi_state->set_audio_streaming_state(audio_state);
+ hmi_state->set_system_context(prev_state->system_context());
+ SetRegularState(app, hmi_state, false);
+}
+
+void StateControllerImpl::SetRegularState(ApplicationSharedPtr app,
+ HmiStatePtr state) {
+ CREATE_LOGGERPTR_LOCAL(logger_, "StateControllerImpl");
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Invalid application pointer");
+ return;
+ }
+ DCHECK_OR_RETURN_VOID(state);
+ if (mobile_apis::HMILevel::HMI_FULL == state->hmi_level()) {
+ SetRegularState(app, state, true);
+ } else {
+ SetRegularState(app, state, false);
+ }
+}
+
+void StateControllerImpl::HmiLevelConflictResolver::operator()(
+ ApplicationSharedPtr to_resolve) {
+ using namespace mobile_apis;
+ using namespace helpers;
+ DCHECK_OR_RETURN_VOID(state_ctrl_);
+ if (to_resolve == applied_)
+ return;
+ HmiStatePtr cur_state = to_resolve->RegularHmiState();
+
+ const bool applied_grabs_audio =
+ Compare<HMILevel::eType, EQ, ONE>(
+ state_->hmi_level(), HMILevel::HMI_FULL, HMILevel::HMI_LIMITED) &&
+ applied_->IsAudioApplication();
+ const bool applied_grabs_full = state_->hmi_level() == HMILevel::HMI_FULL;
+ const bool to_resolve_handles_full =
+ cur_state->hmi_level() == HMILevel::HMI_FULL;
+ const bool to_resolve_handles_audio =
+ Compare<HMILevel::eType, EQ, ONE>(
+ cur_state->hmi_level(), HMILevel::HMI_FULL, HMILevel::HMI_LIMITED) &&
+ to_resolve->IsAudioApplication();
+ const bool same_app_type = state_ctrl_->IsSameAppType(applied_, to_resolve);
+
+ // If applied Hmi state is FULL:
+ // all not audio applications will get BACKGROUND
+ // all applications with same HMI type will get BACKGROUND
+ // all audio applications with other HMI type(navi, vc, media) in FULL will
+ // get LIMMITED HMI level
+
+ // If applied Hmi state is LIMITED:
+ // all applications with other HMI types will save HMI states
+ // all not audio applications will save HMI states
+ // all applications with same HMI type will get BACKGROUND
+
+ // If applied Hmi state is BACKGROUND:
+ // all applications will save HMI states
+
+ HMILevel::eType result_hmi_level = cur_state->hmi_level();
+ if (applied_grabs_full && to_resolve_handles_audio && !same_app_type)
+ result_hmi_level = HMILevel::HMI_LIMITED;
+
+ if ((applied_grabs_full && to_resolve_handles_full &&
+ !to_resolve->IsAudioApplication()) ||
+ (applied_grabs_audio && to_resolve_handles_audio && same_app_type))
+ result_hmi_level = HMILevel::HMI_BACKGROUND;
+
+ if (cur_state->hmi_level() != result_hmi_level) {
+ LOG4CXX_DEBUG(logger_,
+ "Application " << to_resolve->app_id()
+ << " will change HMI level to "
+ << result_hmi_level);
+ state_ctrl_->SetupRegularHmiState(to_resolve,
+ result_hmi_level,
+ result_hmi_level == HMILevel::HMI_LIMITED
+ ? AudioStreamingState::AUDIBLE
+ : AudioStreamingState::NOT_AUDIBLE);
+ } else {
+ LOG4CXX_DEBUG(logger_,
+ "Application " << to_resolve->app_id()
+ << " will not change HMI level");
+ }
+}
+
+HmiStatePtr StateControllerImpl::ResolveHmiState(ApplicationSharedPtr app,
+ HmiStatePtr state) const {
+ using namespace mobile_apis;
+ using namespace helpers;
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_,
+ "State to resolve: hmi_level "
+ << state->hmi_level() << ", audio_state "
+ << state->audio_streaming_state() << ", system_context "
+ << state->system_context());
+
+ HmiStatePtr available_state =
+ CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
+ DCHECK_OR_RETURN(available_state, HmiStatePtr());
+ available_state->set_hmi_level(state->hmi_level());
+ available_state->set_audio_streaming_state(state->audio_streaming_state());
+ available_state->set_system_context(state->system_context());
+
+ if (app->is_resuming()) {
+ HMILevel::eType available_level =
+ GetAvailableHmiLevel(app, state->hmi_level());
+ available_state->set_hmi_level(available_level);
+ available_state->set_audio_streaming_state(
+ CalcAudioState(app, available_level));
+ }
+ return IsStateAvailable(app, available_state) ? available_state
+ : HmiStatePtr();
+}
+
+bool StateControllerImpl::IsResumptionAllowed(ApplicationSharedPtr app,
+ HmiStatePtr state) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace helpers;
+ using namespace mobile_apis;
+ if (!app->is_resuming() ||
+ !Compare<HMILevel::eType, EQ, ONE>(
+ state->hmi_level(), HMILevel::HMI_FULL, HMILevel::HMI_LIMITED)) {
+ LOG4CXX_DEBUG(logger_, "Application is not in resuming mode.");
+ return true;
+ }
+
+ if (IsTempStateActive(HmiState::StateID::STATE_ID_AUDIO_SOURCE) &&
+ app->is_media_application()) {
+ LOG4CXX_DEBUG(logger_,
+ "Resumption for media app is not allowed. "
+ << "AUDIO_SOURCE event is active");
+ return false;
+ }
+
+ if (IsTempStateActive(HmiState::StateID::STATE_ID_EMBEDDED_NAVI) &&
+ app->is_navi()) {
+ LOG4CXX_DEBUG(logger_,
+ "Resumption for navi app is not allowed. "
+ << "EMBEDDED_NAVI event is active");
+ return false;
+ }
+
+ return true;
+}
+
+mobile_apis::HMILevel::eType StateControllerImpl::GetAvailableHmiLevel(
+ ApplicationSharedPtr app, mobile_apis::HMILevel::eType hmi_level) const {
+ using namespace mobile_apis;
+ using namespace helpers;
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ mobile_apis::HMILevel::eType result = hmi_level;
+ if (!Compare<HMILevel::eType, EQ, ONE>(
+ hmi_level, HMILevel::HMI_FULL, HMILevel::HMI_LIMITED)) {
+ return result;
+ }
+
+ const bool is_audio_app = app->IsAudioApplication();
+ const bool does_audio_app_with_same_type_exist =
+ app_mngr_.IsAppTypeExistsInFullOrLimited(app);
+ if (HMILevel::HMI_LIMITED == hmi_level) {
+ if (!is_audio_app || does_audio_app_with_same_type_exist) {
+ result = app_mngr_.GetDefaultHmiLevel(app);
+ }
+ return result;
+ }
+
+ const bool is_active_app_exist = app_mngr_.active_application();
+ if (is_audio_app) {
+ if (does_audio_app_with_same_type_exist) {
+ result = app_mngr_.GetDefaultHmiLevel(app);
+ } else if (is_active_app_exist) {
+ result = mobile_apis::HMILevel::HMI_LIMITED;
+ } else if (app->is_navi() &&
+ IsTempStateActive(HmiState::StateID::STATE_ID_AUDIO_SOURCE)) {
+ LOG4CXX_DEBUG(logger_,
+ "Navigation app will be resumed to LIMITED, "
+ "because of AUDIO_SOURCE ia active.");
+ result = mobile_apis::HMILevel::HMI_LIMITED;
+ } else if (app->is_media_application() &&
+ IsTempStateActive(HmiState::StateID::STATE_ID_EMBEDDED_NAVI)) {
+ LOG4CXX_DEBUG(logger_,
+ "Media app will be resumed to LIMITED, "
+ "because of EMBEDDED_NAVI is active.");
+ result = mobile_apis::HMILevel::HMI_LIMITED;
+ }
+ } else if (is_active_app_exist) {
+ result = app_mngr_.GetDefaultHmiLevel(app);
+ }
+
+ return result;
+}
+
+bool StateControllerImpl::IsStateAvailable(ApplicationSharedPtr app,
+ HmiStatePtr state) const {
+ using namespace mobile_apis;
+ using namespace helpers;
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_,
+ "Checking state: hmi_level "
+ << state->hmi_level() << ", audio_state "
+ << state->audio_streaming_state() << ", system_context "
+ << state->system_context());
+
+ if (app->is_resuming()) {
+ return IsStateAvailableForResumption(app, state);
+ }
+
+ if (IsTempStateActive(HmiState::StateID::STATE_ID_AUDIO_SOURCE) ||
+ IsTempStateActive(HmiState::StateID::STATE_ID_EMBEDDED_NAVI)) {
+ if (HMILevel::HMI_FULL == state->hmi_level()) {
+ LOG4CXX_DEBUG(logger_,
+ "AUDIO_SOURCE or EMBEDDED_NAVI is active."
+ << " Requested state is not available");
+ return false;
+ }
+ }
+
+ LOG4CXX_DEBUG(logger_, "Requested state is available");
+ return true;
+}
+
+bool StateControllerImpl::IsStateAvailableForResumption(
+ ApplicationSharedPtr app, HmiStatePtr state) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ using namespace mobile_apis;
+ using namespace helpers;
+
+ if (!app->is_resuming() ||
+ !Compare<HMILevel::eType, EQ, ONE>(
+ state->hmi_level(), HMILevel::HMI_FULL, HMILevel::HMI_LIMITED)) {
+ LOG4CXX_DEBUG(logger_,
+ "Application is not in resuming mode."
+ << " Requested state is available");
+ return true;
+ }
+
+ if (IsTempStateActive(HmiState::StateID::STATE_ID_VR_SESSION) ||
+ IsTempStateActive(HmiState::StateID::STATE_ID_SAFETY_MODE)) {
+ LOG4CXX_DEBUG(logger_,
+ "Requested state is not available. "
+ << "VR session or emergency event is active");
+ return false;
+ }
+ if (IsTempStateActive(HmiState::StateID::STATE_ID_PHONE_CALL) &&
+ app->is_media_application()) {
+ LOG4CXX_DEBUG(logger_,
+ "Requested state for media application "
+ << "is not available. Phone call is active");
+ return false;
+ }
+ if (IsTempStateActive(HmiState::StateID::STATE_ID_DEACTIVATE_HMI)) {
+ LOG4CXX_DEBUG(logger_,
+ "Requested state is not available. "
+ << "Deactivate HMI event is active");
+ return false;
+ }
+
+ LOG4CXX_DEBUG(logger_, "Requested state is available");
+ return true;
+}
+
+void StateControllerImpl::SetupRegularHmiState(ApplicationSharedPtr app,
+ HmiStatePtr state) {
+ namespace HMILevel = mobile_apis::HMILevel;
+ namespace AudioStreamingState = mobile_apis::AudioStreamingState;
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(state);
+ LOG4CXX_DEBUG(logger_,
+ "hmi_level " << state->hmi_level() << ", audio_state "
+ << state->audio_streaming_state()
+ << ", system_context " << state->system_context());
+ HmiStatePtr curr_state = app->CurrentHmiState();
+ HmiStatePtr old_state =
+ CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
+ DCHECK_OR_RETURN_VOID(old_state);
+ old_state->set_hmi_level(curr_state->hmi_level());
+ old_state->set_audio_streaming_state(curr_state->audio_streaming_state());
+ old_state->set_system_context(curr_state->system_context());
+ app->SetRegularState(state);
+
+ if (HMILevel::HMI_LIMITED == state->hmi_level() && app->is_resuming()) {
+ LOG4CXX_DEBUG(logger_,
+ "Resuming to LIMITED level. "
+ << "Send OnResumeAudioSource notification");
+ MessageHelper::SendOnResumeAudioSourceToHMI(app->app_id(), app_mngr_);
+ }
+ app->set_is_resuming(false);
+
+ HmiStatePtr new_state = app->CurrentHmiState();
+ OnStateChanged(app, old_state, new_state);
+}
+
+void StateControllerImpl::SetupRegularHmiState(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const mobile_apis::AudioStreamingState::eType audio_state) {
+ namespace HMILevel = mobile_apis::HMILevel;
+ namespace AudioStreamingState = mobile_apis::AudioStreamingState;
+ using helpers::Compare;
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(app);
+ HmiStatePtr prev_state = app->RegularHmiState();
+ DCHECK_OR_RETURN_VOID(prev_state);
+ HmiStatePtr new_state =
+ CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
+ DCHECK_OR_RETURN_VOID(new_state);
+ new_state->set_hmi_level(hmi_level);
+ new_state->set_audio_streaming_state(audio_state);
+ new_state->set_system_context(prev_state->system_context());
+ SetupRegularHmiState(app, new_state);
+}
+
+void StateControllerImpl::ApplyRegularState(ApplicationSharedPtr app,
+ HmiStatePtr state) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(app);
+ DCHECK_OR_RETURN_VOID(state);
+ DCHECK_OR_RETURN_VOID(state->state_id() == HmiState::STATE_ID_REGULAR);
+ SetupRegularHmiState(app, state);
+ ForEachApplication<HmiLevelConflictResolver>(
+ HmiLevelConflictResolver(app, state, this));
+}
+
+bool StateControllerImpl::IsSameAppType(ApplicationConstSharedPtr app1,
+ ApplicationConstSharedPtr app2) {
+ const bool both_media =
+ app1->is_media_application() && app2->is_media_application();
+ const bool both_navi = app1->is_navi() && app2->is_navi();
+ const bool both_vc = app1->is_voice_communication_supported() &&
+ app2->is_voice_communication_supported();
+ const bool both_simple =
+ !app1->IsAudioApplication() && !app2->IsAudioApplication();
+ return both_simple || both_media || both_navi || both_vc;
+}
+
+void StateControllerImpl::on_event(const event_engine::Event& event) {
+ using smart_objects::SmartObject;
+ using event_engine::Event;
+ using namespace hmi_apis;
+ namespace FunctionID = hmi_apis::FunctionID;
+
+ LOG4CXX_AUTO_TRACE(logger_);
+ const SmartObject& message = event.smart_object();
+ const FunctionID::eType id = static_cast<FunctionID::eType>(event.id());
+ switch (id) {
+ case FunctionID::BasicCommunication_ActivateApp: {
+ OnActivateAppResponse(message);
+ break;
+ }
+ case FunctionID::BasicCommunication_OnAppActivated: {
+ OnAppActivated(message);
+ break;
+ }
+ case FunctionID::BasicCommunication_OnAppDeactivated: {
+ OnAppDeactivated(message);
+ break;
+ }
+ case FunctionID::VR_Started: {
+ ApplyTempState<HmiState::STATE_ID_VR_SESSION>();
+ break;
+ }
+ case FunctionID::VR_Stopped: {
+ CancelTempState<HmiState::STATE_ID_VR_SESSION>();
+ break;
+ }
+ case FunctionID::TTS_Started: {
+ ApplyTempState<HmiState::STATE_ID_TTS_SESSION>();
+ break;
+ }
+ case FunctionID::TTS_Stopped: {
+ CancelTempState<HmiState::STATE_ID_TTS_SESSION>();
+ break;
+ }
+ case FunctionID::BasicCommunication_OnEventChanged: {
+ bool is_active =
+ message[strings::msg_params][hmi_notification::is_active].asBool();
+ const uint32_t id =
+ message[strings::msg_params][hmi_notification::event_name].asUInt();
+ // TODO(AOleynik): Add verification/conversion check here
+ Common_EventTypes::eType state_id =
+ static_cast<Common_EventTypes::eType>(id);
+ if (is_active) {
+ if (Common_EventTypes::AUDIO_SOURCE == state_id) {
+ ApplyTempState<HmiState::STATE_ID_AUDIO_SOURCE>();
+ break;
+ }
+ if (Common_EventTypes::EMBEDDED_NAVI == state_id) {
+ ApplyTempState<HmiState::STATE_ID_EMBEDDED_NAVI>();
+ break;
+ }
+ if (Common_EventTypes::PHONE_CALL == state_id) {
+ ApplyTempState<HmiState::STATE_ID_PHONE_CALL>();
+ break;
+ }
+ if (Common_EventTypes::EMERGENCY_EVENT == state_id) {
+ ApplyTempState<HmiState::STATE_ID_SAFETY_MODE>();
+ break;
+ }
+ if (Common_EventTypes::DEACTIVATE_HMI == state_id) {
+ ApplyTempState<HmiState::STATE_ID_DEACTIVATE_HMI>();
+ break;
+ }
+ } else {
+ if (Common_EventTypes::AUDIO_SOURCE == state_id) {
+ CancelTempState<HmiState::STATE_ID_AUDIO_SOURCE>();
+ break;
+ }
+ if (Common_EventTypes::EMBEDDED_NAVI == state_id) {
+ CancelTempState<HmiState::STATE_ID_EMBEDDED_NAVI>();
+ break;
+ }
+ if (Common_EventTypes::PHONE_CALL == state_id) {
+ CancelTempState<HmiState::STATE_ID_PHONE_CALL>();
+ break;
+ }
+ if (Common_EventTypes::EMERGENCY_EVENT == state_id) {
+ CancelTempState<HmiState::STATE_ID_SAFETY_MODE>();
+ break;
+ }
+ if (Common_EventTypes::DEACTIVATE_HMI == state_id) {
+ CancelTempState<HmiState::STATE_ID_DEACTIVATE_HMI>();
+ break;
+ }
+ }
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+void StateControllerImpl::OnStateChanged(ApplicationSharedPtr app,
+ HmiStatePtr old_state,
+ HmiStatePtr new_state) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(app);
+ DCHECK_OR_RETURN_VOID(old_state);
+ DCHECK_OR_RETURN_VOID(new_state);
+ LOG4CXX_DEBUG(logger_,
+ "old: hmi_level " << old_state->hmi_level() << ", audio_state "
+ << old_state->audio_streaming_state()
+ << ", system_context "
+ << old_state->system_context());
+ LOG4CXX_DEBUG(logger_,
+ "new: hmi_level " << new_state->hmi_level() << ", audio_state "
+ << new_state->audio_streaming_state()
+ << ", system_context "
+ << new_state->system_context());
+ if (IsStatusChanged(old_state, new_state)) {
+ app_mngr_.SendHMIStatusNotification(app);
+ if (new_state->hmi_level() == mobile_apis::HMILevel::HMI_NONE) {
+ app->ResetDataInNone();
+ }
+ app_mngr_.OnHMILevelChanged(
+ app->app_id(), old_state->hmi_level(), new_state->hmi_level());
+ app->usage_report().RecordHmiStateChanged(new_state->hmi_level());
+ } else {
+ LOG4CXX_ERROR(logger_, "Status not changed");
+ }
+}
+
+bool StateControllerImpl::IsTempStateActive(HmiState::StateID ID) const {
+ sync_primitives::AutoLock autolock(active_states_lock_);
+ StateIDList::const_iterator itr =
+ std::find(active_states_.begin(), active_states_.end(), ID);
+ return active_states_.end() != itr;
+}
+
+void StateControllerImpl::OnApplicationRegistered(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType default_level) {
+ namespace HMILevel = mobile_apis::HMILevel;
+ namespace AudioStreamingState = mobile_apis::AudioStreamingState;
+ namespace SystemContext = mobile_apis::SystemContext;
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(app);
+
+ active_states_lock_.Acquire();
+ StateIDList::iterator it = active_states_.begin();
+ for (; it != active_states_.end(); ++it) {
+ HmiStatePtr new_state = CreateHmiState(app->app_id(), *it);
+ DCHECK_OR_RETURN_VOID(new_state);
+ DCHECK_OR_RETURN_VOID(new_state->state_id() != HmiState::STATE_ID_REGULAR);
+ HmiStatePtr old_hmi_state = app->CurrentHmiState();
+ new_state->set_parent(old_hmi_state);
+ app->AddHMIState(new_state);
+ }
+ active_states_lock_.Release();
+
+ HmiStatePtr default_state =
+ CreateHmiState(app->app_id(), HmiState::StateID::STATE_ID_REGULAR);
+ DCHECK_OR_RETURN_VOID(default_state);
+ default_state->set_hmi_level(default_level);
+ default_state->set_audio_streaming_state(CalcAudioState(app, default_level));
+ default_state->set_system_context(SystemContext::SYSCTXT_MAIN);
+
+ HmiStatePtr initial_state = app->RegularHmiState();
+
+ app->SetRegularState(default_state);
+
+ HmiStatePtr new_state = app->CurrentHmiState();
+
+ OnStateChanged(app, initial_state, new_state);
+}
+
+int64_t StateControllerImpl::SendBCActivateApp(
+ ApplicationConstSharedPtr app,
+ hmi_apis::Common_HMILevel::eType level,
+ bool send_policy_priority) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ smart_objects::SmartObjectSPtr bc_activate_app_request =
+ MessageHelper::GetBCActivateAppRequestToHMI(
+ app,
+ app_mngr_.connection_handler().get_session_observer(),
+ app_mngr_.GetPolicyHandler(),
+ level,
+ send_policy_priority,
+ app_mngr_);
+ if (!bc_activate_app_request) {
+ LOG4CXX_ERROR(logger_, "Unable to create BC.ActivateAppRequest");
+ return -1;
+ }
+ if (!app_mngr_.ManageHMICommand(bc_activate_app_request)) {
+ LOG4CXX_ERROR(logger_, "Unable to send BC.ActivateAppRequest");
+ return -1;
+ }
+ const int64_t corr_id =
+ (*bc_activate_app_request)[strings::params][strings::correlation_id]
+ .asInt();
+ return corr_id;
+}
+
+void StateControllerImpl::ApplyPostponedStateForApp(ApplicationSharedPtr app) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ HmiStatePtr state = app->PostponedHmiState();
+ if (state) {
+ app->RemovePostponedState();
+ state->set_state_id(HmiState::STATE_ID_REGULAR);
+ SetRegularState(app, state);
+ }
+}
+
+void StateControllerImpl::TempStateStarted(HmiState::StateID ID) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock autolock(active_states_lock_);
+ StateIDList::iterator it =
+ std::find(active_states_.begin(), active_states_.end(), ID);
+ if (it == active_states_.end()) {
+ active_states_.push_back(ID);
+ } else {
+ LOG4CXX_ERROR(logger_, "StateID " << ID << " is already active");
+ }
+}
+
+void StateControllerImpl::TempStateStopped(HmiState::StateID ID) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ {
+ sync_primitives::AutoLock autolock(active_states_lock_);
+ active_states_.remove(ID);
+ }
+ ForEachApplication(std::bind1st(
+ std::mem_fun(&StateControllerImpl::ApplyPostponedStateForApp), this));
+}
+
+void StateControllerImpl::DeactivateApp(ApplicationSharedPtr app) {
+ using namespace mobile_apis;
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ DCHECK_OR_RETURN_VOID(app);
+ HmiStatePtr regular = app->RegularHmiState();
+ DCHECK_OR_RETURN_VOID(regular);
+ HmiStatePtr new_regular = utils::MakeShared<HmiState>(*regular);
+
+ if (app->IsAudioApplication()) {
+ new_regular->set_hmi_level(HMILevel::HMI_LIMITED);
+ new_regular->set_audio_streaming_state(AudioStreamingState::AUDIBLE);
+ } else {
+ new_regular->set_hmi_level(HMILevel::HMI_BACKGROUND);
+ new_regular->set_audio_streaming_state(AudioStreamingState::NOT_AUDIBLE);
+ }
+
+ SetRegularState(app, new_regular, false);
+}
+
+void StateControllerImpl::OnActivateAppResponse(
+ const smart_objects::SmartObject& message) {
+ const hmi_apis::Common_Result::eType code =
+ static_cast<hmi_apis::Common_Result::eType>(
+ message[strings::params][hmi_response::code].asInt());
+ const int32_t correlation_id =
+ message[strings::params][strings::correlation_id].asInt();
+ const uint32_t hmi_app_id = app_mngr_.application_id(correlation_id);
+ ApplicationSharedPtr application =
+ app_mngr_.application_by_hmi_app(hmi_app_id);
+ if (application && hmi_apis::Common_Result::SUCCESS == code) {
+ HmiStatePtr pending_state = waiting_for_activate[application->app_id()];
+ DCHECK_OR_RETURN_VOID(pending_state);
+ ApplyRegularState(application, pending_state);
+ }
+}
+
+void StateControllerImpl::OnAppActivated(
+ const smart_objects::SmartObject& message) {
+ using namespace mobile_apis;
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ uint32_t app_id = message[strings::msg_params][strings::app_id].asUInt();
+ ApplicationSharedPtr app = app_mngr_.application(app_id);
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Application with id " << app_id << " not found");
+ return;
+ }
+
+ SetRegularState(app, HMILevel::HMI_FULL, true);
+}
+
+void StateControllerImpl::OnAppDeactivated(
+ const smart_objects::SmartObject& message) {
+ using namespace hmi_apis;
+ using namespace mobile_apis;
+ using namespace helpers;
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ uint32_t app_id = message[strings::msg_params][strings::app_id].asUInt();
+ ApplicationSharedPtr app = app_mngr_.application(app_id);
+ if (!app) {
+ LOG4CXX_ERROR(logger_, "Application with id " << app_id << " not found");
+ return;
+ }
+
+ if (HMILevel::HMI_FULL != app->hmi_level()) {
+ return;
+ }
+
+ // TODO(AOleynik): Need to delete DeactivateReason and modify OnAppDeactivated
+ // when HMI will support that, otherwise won't be testable
+ DeactivateApp(app);
+}
+
+void StateControllerImpl::OnNaviStreamingStarted() {
+ ApplyTempState<HmiState::STATE_ID_NAVI_STREAMING>();
+}
+
+void StateControllerImpl::OnNaviStreamingStopped() {
+ CancelTempState<HmiState::STATE_ID_NAVI_STREAMING>();
+}
+
+bool StateControllerImpl::IsStateActive(HmiState::StateID state_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ switch (state_id) {
+ case HmiState::STATE_ID_CURRENT:
+ case HmiState::STATE_ID_REGULAR:
+ return true;
+ default:
+ return IsTempStateActive(state_id);
+ }
+ return false;
+}
+
+HmiStatePtr StateControllerImpl::CreateHmiState(
+ uint32_t app_id, HmiState::StateID state_id) const {
+ using namespace utils;
+ LOG4CXX_AUTO_TRACE(logger_);
+ HmiStatePtr new_state;
+ switch (state_id) {
+ case HmiState::STATE_ID_PHONE_CALL: {
+ new_state = MakeShared<PhoneCallHmiState>(app_id, app_mngr_);
+ break;
+ }
+ case HmiState::STATE_ID_SAFETY_MODE: {
+ new_state = MakeShared<SafetyModeHmiState>(app_id, app_mngr_);
+ break;
+ }
+ case HmiState::STATE_ID_VR_SESSION: {
+ new_state = MakeShared<VRHmiState>(app_id, app_mngr_);
+ break;
+ }
+ case HmiState::STATE_ID_TTS_SESSION: {
+ new_state = MakeShared<TTSHmiState>(app_id, app_mngr_);
+ break;
+ }
+ case HmiState::STATE_ID_NAVI_STREAMING: {
+ new_state = MakeShared<NaviStreamingHmiState>(app_id, app_mngr_);
+ break;
+ }
+ case HmiState::STATE_ID_REGULAR: {
+ new_state = MakeShared<HmiState>(app_id, app_mngr_);
+ break;
+ }
+ case HmiState::STATE_ID_POSTPONED: {
+ new_state = MakeShared<HmiState>(app_id, app_mngr_, state_id);
+ break;
+ }
+ case HmiState::STATE_ID_DEACTIVATE_HMI: {
+ new_state = MakeShared<DeactivateHMI>(app_id, app_mngr_);
+ break;
+ }
+ case HmiState::STATE_ID_AUDIO_SOURCE: {
+ new_state = MakeShared<AudioSource>(app_id, app_mngr_);
+ break;
+ }
+ case HmiState::STATE_ID_EMBEDDED_NAVI: {
+ new_state = MakeShared<EmbeddedNavi>(app_id, app_mngr_);
+ break;
+ }
+ default:
+ LOG4CXX_FATAL(logger_, "Invalid state_id " << state_id);
+ NOTREACHED();
+ break;
+ }
+ return new_state;
+}
+
+mobile_apis::AudioStreamingState::eType StateControllerImpl::CalcAudioState(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level) const {
+ namespace HMILevel = mobile_apis::HMILevel;
+ namespace AudioStreamingState = mobile_apis::AudioStreamingState;
+ using helpers::Compare;
+ using helpers::EQ;
+ using helpers::ONE;
+
+ AudioStreamingState::eType audio_state = AudioStreamingState::NOT_AUDIBLE;
+ if (Compare<HMILevel::eType, EQ, ONE>(
+ hmi_level, HMILevel::HMI_FULL, HMILevel::HMI_LIMITED)) {
+ if (app->IsAudioApplication()) {
+ audio_state = AudioStreamingState::AUDIBLE;
+ }
+ }
+ return audio_state;
+}
+
+} // namespace application_manager
diff --git a/src/components/application_manager/src/usage_statistics.cc b/src/components/application_manager/src/usage_statistics.cc
index ad986d2223..42c48520e9 100644
--- a/src/components/application_manager/src/usage_statistics.cc
+++ b/src/components/application_manager/src/usage_statistics.cc
@@ -31,11 +31,11 @@
*/
#include "application_manager/usage_statistics.h"
-
#include "smart_objects/smart_object.h"
#include "smart_objects/enum_schema_item.h"
-#include "usage_statistics/statistics_manager.h"
+#include "policy/usage_statistics/statistics_manager.h"
#include "utils/macro.h"
+#include "utils/make_shared.h"
using namespace mobile_apis;
using namespace NsSmartDeviceLink::NsSmartObjects;
@@ -47,27 +47,52 @@ namespace {
std::string LanguageIdToString(Language::eType lang_id) {
const char* str;
- const bool ok = EnumConversionHelper<Language::eType>::EnumToCString(lang_id, &str);
+ const bool ok =
+ EnumConversionHelper<Language::eType>::EnumToCString(lang_id, &str);
return ok ? str : "unknown";
}
} // namespace
-UsageStatistics::UsageStatistics(const std::string& app_id,
- utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager)
- : time_in_hmi_state_(statistics_manager, app_id),
- app_registration_language_gui_(statistics_manager, app_id, LANGUAGE_GUI),
- app_registration_language_vui_(statistics_manager, app_id, LANGUAGE_VUI),
- count_of_rejected_rpc_calls_(statistics_manager, app_id,
- REJECTED_RPC_CALLS),
- count_of_rpcs_sent_in_hmi_none_(statistics_manager, app_id,
- RPCS_IN_HMI_NONE),
- count_of_user_selections_(statistics_manager, app_id, USER_SELECTIONS),
- count_of_run_attempts_while_revoked_(statistics_manager, app_id,
- RUN_ATTEMPTS_WHILE_REVOKED),
- count_of_removals_for_bad_behavior_(statistics_manager, app_id,
- REMOVALS_MISBEHAVED) {
- time_in_hmi_state_.Start(SECONDS_HMI_NONE);
+UsageStatistics::UsageStatistics(
+ const std::string& app_id,
+ utils::SharedPtr<StatisticsManager> statistics_manager)
+ : time_in_hmi_state_sptr_(
+ new usage_statistics::AppStopwatchImpl(statistics_manager, app_id))
+ , app_registration_language_gui_(statistics_manager, app_id, LANGUAGE_GUI)
+ , app_registration_language_vui_(statistics_manager, app_id, LANGUAGE_VUI)
+ , count_of_rejected_rpc_calls_(
+ statistics_manager, app_id, REJECTED_RPC_CALLS)
+ , count_of_rpcs_sent_in_hmi_none_(
+ statistics_manager, app_id, RPCS_IN_HMI_NONE)
+ , count_of_user_selections_(statistics_manager, app_id, USER_SELECTIONS)
+ , count_of_run_attempts_while_revoked_(
+ statistics_manager, app_id, RUN_ATTEMPTS_WHILE_REVOKED)
+ , count_of_removals_for_bad_behavior_(
+ statistics_manager, app_id, REMOVALS_MISBEHAVED)
+ , count_of_tls_error_(statistics_manager, app_id, COUNT_OF_TLS_ERRORS) {
+ time_in_hmi_state_sptr_->Start(SECONDS_HMI_NONE);
+}
+
+UsageStatistics::UsageStatistics(
+ const std::string& app_id,
+ utils::SharedPtr<StatisticsManager> statistics_manager,
+ AppStopwatch* time_in_hmi_state_ptr)
+ : time_in_hmi_state_sptr_(time_in_hmi_state_ptr)
+ , app_registration_language_gui_(statistics_manager, app_id, LANGUAGE_GUI)
+ , app_registration_language_vui_(statistics_manager, app_id, LANGUAGE_VUI)
+ , count_of_rejected_rpc_calls_(
+ statistics_manager, app_id, REJECTED_RPC_CALLS)
+ , count_of_rpcs_sent_in_hmi_none_(
+ statistics_manager, app_id, RPCS_IN_HMI_NONE)
+ , count_of_user_selections_(statistics_manager, app_id, USER_SELECTIONS)
+ , count_of_run_attempts_while_revoked_(
+ statistics_manager, app_id, RUN_ATTEMPTS_WHILE_REVOKED)
+ , count_of_removals_for_bad_behavior_(
+ statistics_manager, app_id, REMOVALS_MISBEHAVED)
+ , count_of_tls_error_(statistics_manager, app_id, COUNT_OF_TLS_ERRORS) {
+ DCHECK(time_in_hmi_state_sptr_.get());
+ time_in_hmi_state_sptr_->Start(SECONDS_HMI_NONE);
}
void UsageStatistics::RecordHmiStateChanged(HMILevel::eType new_hmi_level) {
@@ -89,7 +114,7 @@ void UsageStatistics::RecordHmiStateChanged(HMILevel::eType new_hmi_level) {
default:
NOTREACHED();
}
- time_in_hmi_state_.Switch(next_stopwatch);
+ time_in_hmi_state_sptr_->Switch(next_stopwatch);
}
void UsageStatistics::RecordAppRegistrationGuiLanguage(
@@ -122,4 +147,8 @@ void UsageStatistics::RecordRemovalsForBadBehavior() {
++count_of_removals_for_bad_behavior_;
}
+void UsageStatistics::RecordTLSError() {
+ ++count_of_tls_error_;
+}
+
} // namespace application_manager
diff --git a/src/components/application_manager/test/CMakeLists.txt b/src/components/application_manager/test/CMakeLists.txt
index 473ae6765e..118cda4fcb 100644
--- a/src/components/application_manager/test/CMakeLists.txt
+++ b/src/components/application_manager/test/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2014, Ford Motor Company
+# Copyright (c) 2015, Ford Motor Company
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -31,66 +31,61 @@
# TODO{ALeshin}: APPLINK-10792. Do not write tests which use
# application manager(AM) singleton while refactoring of AM is finished.
-# Replace include for mocking singltone
-get_property(the_include_dirs DIRECTORY "" PROPERTY INCLUDE_DIRECTORIES)
-set(class_to_mock ${CMAKE_SOURCE_DIR}/src/components/application_manager/include)
-list(FIND the_include_dirs ${class_to_mock} find_idx)
-if(find_idx GREATER -1)
- LIST_REPLACE(the_include_dirs ${find_idx} ${AM_MOCK_DIR}/include)
-endif()
-set_property(DIRECTORY "" PROPERTY INCLUDE_DIRECTORIES ${the_include_dirs})
-
-include_directories(
- ${CMAKE_SOURCE_DIR}/src/3rd_party-static/gmock-1.7.0/include
- ${CMAKE_SOURCE_DIR}/src/3rd_party-static/gmock-1.7.0/gtest/include
- ${COMPONENTS_DIR}/application_manager/include/application_manager/
- ${COMPONENTS_DIR}/application_manager/include/application_manager/policies
-)
-
-set(testSources
- #${AM_TEST_DIR}/command_impl_test.cc
- ${COMPONENTS_DIR}/application_manager/test/mobile_message_handler_test.cc
- #${AM_TEST_DIR}/request_info_test.cc
-)
-
-set(mockedSources
- ${AM_MOCK_DIR}/src/application_manager_impl.cc
-)
-
-set(AM_SOURCES
- ${AM_SOURCE_DIR}/src/policies/policy_handler.cc
- ${AM_SOURCE_DIR}/src/policies/policy_event_observer.cc
-
- ${AM_SOURCE_DIR}/src/commands/command_impl.cc
- ${AM_SOURCE_DIR}/src/commands/command_request_impl.cc
- ${AM_SOURCE_DIR}/src/commands/command_response_impl.cc
- ${AM_SOURCE_DIR}/src/commands/command_notification_impl.cc
- ${AM_SOURCE_DIR}/src/commands/command_notification_from_mobile_impl.cc
- ${AM_SOURCE_DIR}/src/commands/pending.cc
-
- ${AM_SOURCE_DIR}/src/usage_statistics.cc
- ${AM_SOURCE_DIR}/src/request_info.cc
- ${AM_SOURCE_DIR}/src/message.cc
- ${AM_SOURCE_DIR}/src/application_impl.cc
- ${AM_SOURCE_DIR}/src/state_controller.cc
- ${AM_SOURCE_DIR}/src/mobile_command_factory.cc
- ${AM_SOURCE_DIR}/src/message_helper.cc
- ${AM_SOURCE_DIR}/src/hmi_command_factory.cc
- ${AM_SOURCE_DIR}/src/hmi_capabilities.cc
- ${AM_SOURCE_DIR}/src/application_data_impl.cc
- ${AM_SOURCE_DIR}/src/request_controller.cc
- ${AM_SOURCE_DIR}/src/resume_ctrl.cpp
- ${AM_SOURCE_DIR}/src/mobile_message_handler.cc
-)
+if (BUILD_TESTS)
+
include_directories(
- ${AM_SOURCE_DIR}/policy/src/policy/policy_table/table_struct
+ ${GMOCK_INCLUDE_DIRECTORY}
+ ${CMAKE_BINARY_DIR}/src/components/
+ ${COMPONENTS_DIR}/application_manager/include/
+ ${COMPONENTS_DIR}/utils/include/
+ ${COMPONENTS_DIR}/resumption/include/
+ ${COMPONENTS_DIR}/utils/include/
+ ${COMPONENTS_DIR}/policy/include/
+ ${COMPONENTS_DIR}/media_manager/include/
+ ${COMPONENTS_DIR}/security_manager/include/
+ ${COMPONENTS_DIR}/policy/test/include/
+ ${COMPONENTS_DIR}/application_manager/test/include/
+ )
+
+ set(testSources
+ ${AM_TEST_DIR}/mobile_message_handler_test.cc
+ ${AM_TEST_DIR}/mobile_message_handler_v1_test.cc
+ ${AM_TEST_DIR}/request_info_test.cc
+ ${AM_TEST_DIR}/resumption_sql_queries_test.cc
+ ${AM_TEST_DIR}/event_engine_test.cc
+ ${AM_TEST_DIR}/policy_event_observer_test.cc
+ ${AM_TEST_DIR}/application_impl_test.cc
+ ${AM_TEST_DIR}/hmi_capabilities_test.cc
+ ${AM_TEST_DIR}/application_state_test.cc
+ ${AM_TEST_DIR}/usage_statistics_test.cc
+ ${AM_TEST_DIR}/policy_handler_test.cc
+ ${AM_TEST_DIR}/mock_message_helper.cc
+ )
+ set (request_controller_SOURCES
+ ${AM_TEST_DIR}/request_controller/request_controller_test.cc
)
+
set(testLibraries
- gmock
+ ApplicationManager
+ Utils
+ dbms
+ jsoncpp
+ Policy
+ connectionHandler
+ HMI_API
+ MOBILE_API
+ v4_protocol_v1_2_no_extra
+ SmartObjects
+ formatters
gmock_main
UsageStatistics
dl
ProtocolLibrary
+ ConfigProfile
+ MediaManager
+ Resumption
+ ProtocolHandler
+ SecurityManager
)
set(test_exec_libraries
@@ -113,32 +108,65 @@ IF(${CMAKE_SYSTEM_NAME} MATCHES "QNX")
list(REMOVE_ITEM test_exec_libraries dl)
endif()
-if(ENABLE_LOG)
- list(APPEND LIBRARIES log4cxx -L${LOG4CXX_LIBS_DIRECTORY})
- list(APPEND LIBRARIES apr-1 -L${APR_LIBS_DIRECTORY})
- list(APPEND LIBRARIES aprutil-1 -L${APR_UTIL_LIBS_DIRECTORY})
- list(APPEND LIBRARIES expat -L${EXPAT_LIBS_DIRECTORY})
-endif()
+ set(testLibraries
+ Utils
+ ApplicationManager
+ jsoncpp
+ Policy
+ connectionHandler
+ HMI_API
+ MOBILE_API
+ v4_protocol_v1_2_no_extra
+ SmartObjects
+ formatters
+ gmock_main
+ UsageStatistics
+ dl
+ ProtocolLibrary
+ ConfigProfile
+ MediaManager
+ Resumption
+ ProtocolHandler
+ SecurityManager
+ )
-add_library("ApplicationManagerTest" ${mockedSources} ${testSources})
+ if (${CMAKE_SYSTEM_NAME} MATCHES "QNX")
+ list(REMOVE_ITEM test_exec_libraries dl)
+ endif()
-target_link_libraries("ApplicationManagerTest" ${testLibraries} AMHMICommandsLibrary
- AMMobileCommandsLibrary
- AMEventEngine
- AMPolicyLibrary)
+ if (ENABLE_LOG)
+ list(APPEND LIBRARIES log4cxx -L${LOG4CXX_LIBS_DIRECTORY})
+ list(APPEND LIBRARIES apr-1 -L${APR_LIBS_DIRECTORY})
+ list(APPEND LIBRARIES aprutil-1 -L${APR_UTIL_LIBS_DIRECTORY})
+ list(APPEND LIBRARIES expat -L${EXPAT_LIBS_DIRECTORY})
+ endif()
-create_test("application_manager_test" "${testSources}" "${ApplicationManagerTest}")
-target_link_libraries("application_manager_test"
- ApplicationManagerTest ${test_exec_libraries}
- ApplicationManager
- ProtocolLibrary
- connectionHandler
- ConfigProfile
- jsoncpp
- MediaManager
- ProtocolHandler
- Resumption
-)
+ file(COPY smartDeviceLink_test2.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+ file(COPY sdl_preloaded_pt.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+ file(COPY sdl_pt_update.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
-#add_executable(application_manager_test ${testSources})
-#target_link_libraries(application_manager_test ApplicationManagerTest ${test_exec_libraries})
+add_custom_command(
+OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/libPolicy.so
+ COMMAND ${CMAKE_COMMAND} -E
+ copy ${COMPONENTS_DIR}/policy/libPolicy.so ${CMAKE_CURRENT_BINARY_DIR})
+ set(CMAKE_EXE_LINKER_FLAGS
+ "${CMAKE_EXE_LINKER_FLAGS} -Wl,-rpath=${CMAKE_CURRENT_BINARY_DIR}")
+ create_test("application_manager_test" "${testSources}" "${testLibraries}" )
+# TODO [AKozoriz] : Fix not buildable tests
+ set(ResumptionData_SOURCES
+ ${AM_TEST_DIR}/resumption/resumption_data_test.cc
+ ${AM_TEST_DIR}/resumption/resumption_data_db_test.cc
+ ${AM_TEST_DIR}/resumption/resumption_data_json_test.cc
+ ${AM_TEST_DIR}/resumption/resume_ctrl_test.cc
+ ${AM_TEST_DIR}/mock_message_helper.cc
+ )
+
+ file(COPY hmi_capabilities.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+ file(COPY smartDeviceLink_test.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+
+ file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/resumption)
+ file(COPY smartDeviceLink_test.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/resumption)
+ create_test("resumption/data_resumption_test" "${ResumptionData_SOURCES}" "${testLibraries}")
+
+ add_subdirectory(state_controller)
+endif()
diff --git a/src/components/application_manager/test/application_impl_test.cc b/src/components/application_manager/test/application_impl_test.cc
new file mode 100644
index 0000000000..7989f11fce
--- /dev/null
+++ b/src/components/application_manager/test/application_impl_test.cc
@@ -0,0 +1,732 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/application_impl.h"
+#include <iostream>
+#include "gtest/gtest.h"
+#include "application_manager/hmi_state.h"
+#include "utils/file_system.h"
+
+#include "utils/make_shared.h"
+#include "application_manager/mock_message_helper.h"
+#include "utils/custom_string.h"
+#include "application_manager/mock_application_manager.h"
+#include "application_manager/mock_application_manager_settings.h"
+#include "application_manager/mock_request_controller_settings.h"
+#include "application_manager/event_engine/event_dispatcher.h"
+#include "application_manager/state_controller.h"
+#include "resumption/last_state.h"
+#include "application_manager/resumption/resume_ctrl.h"
+#include "application_manager/policies/mock_policy_handler_interface.h"
+#include "policy/mock_statistics_manager.h"
+
+namespace test {
+namespace components {
+namespace application_manager_test {
+
+using namespace application_manager;
+
+using namespace mobile_apis;
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+namespace custom_str = utils::custom_string;
+
+using ::testing::_;
+using ::testing::Return;
+using ::testing::ReturnRef;
+using ::testing::AtLeast;
+using usage_statistics_test::MockStatisticsManager;
+
+typedef void (ApplicationImpl::*AddSet)(HmiStatePtr args);
+
+class ApplicationImplTest : public ::testing::Test {
+ protected:
+ virtual void SetUp() OVERRIDE {
+ app_id = 10;
+ policy_app_id = "policy_app_id";
+ app_name = "app_name";
+ mac_address = "mac_address";
+ test_lvl = HMILevel::INVALID_ENUM;
+ state_id = HmiState::STATE_ID_REGULAR;
+ audiostate = AudioStreamingState::NOT_AUDIBLE;
+ syst_context = SystemContext::SYSCTXT_MAIN;
+
+ testHmiState = CreateTestHmiState();
+ EXPECT_CALL(mock_application_manager_, CreateRegularState(app_id, _, _, _))
+ .WillOnce(Return(testHmiState));
+ EXPECT_CALL(mock_application_manager_, get_settings())
+ .WillRepeatedly(ReturnRef(mock_application_manager_settings_));
+ EXPECT_CALL(mock_application_manager_settings_, app_icons_folder())
+ .WillRepeatedly(ReturnRef(directory_name));
+ EXPECT_CALL(mock_application_manager_settings_, app_storage_folder())
+ .WillRepeatedly(ReturnRef(directory_name));
+ EXPECT_CALL(mock_application_manager_settings_,
+ audio_data_stopped_timeout()).WillOnce(Return(0));
+ EXPECT_CALL(mock_application_manager_settings_,
+ video_data_stopped_timeout()).WillOnce(Return(0));
+ app_impl = new ApplicationImpl(app_id,
+ policy_app_id,
+ mac_address,
+ app_name,
+ utils::MakeShared<MockStatisticsManager>(),
+ mock_application_manager_);
+ }
+ void TearDown() OVERRIDE {
+ delete app_impl;
+ }
+ HmiStatePtr CreateTestHmiState();
+
+ HmiStatePtr TestAddHmiState(HMILevel::eType hmi_lvl,
+ HmiState::StateID id_state,
+ AddSet hmi_action);
+
+ void CheckCurrentHMIState();
+ MockApplicationManagerSettings mock_application_manager_settings_;
+ MockApplicationManager mock_application_manager_;
+ ApplicationImpl* app_impl;
+ uint32_t app_id;
+ std::string policy_app_id;
+ std::string mac_address;
+ custom_str::CustomString app_name;
+ const std::string directory_name = "./test_storage";
+ HmiState::StateID state_id;
+ HmiStatePtr testHmiState;
+ HMILevel::eType test_lvl;
+ AudioStreamingState::eType audiostate;
+ SystemContext::eType syst_context;
+};
+
+HmiStatePtr ApplicationImplTest::CreateTestHmiState() {
+ HmiStatePtr testState =
+ utils::MakeShared<HmiState>(app_id, mock_application_manager_, state_id);
+ testState->set_hmi_level(test_lvl);
+ testState->set_audio_streaming_state(audiostate);
+ testState->set_system_context(syst_context);
+ return testState;
+}
+
+HmiStatePtr ApplicationImplTest::TestAddHmiState(HMILevel::eType hmi_lvl,
+ HmiState::StateID id_state,
+ AddSet hmi_action) {
+ test_lvl = hmi_lvl;
+ state_id = id_state;
+ HmiStatePtr state = CreateTestHmiState();
+ (app_impl->*hmi_action)(state);
+ return state;
+}
+
+void ApplicationImplTest::CheckCurrentHMIState() {
+ HmiStatePtr current_state = app_impl->CurrentHmiState();
+ EXPECT_EQ(test_lvl, current_state->hmi_level());
+ EXPECT_EQ(state_id, current_state->state_id());
+}
+
+TEST_F(ApplicationImplTest, AddHmiState_GetCurrentState) {
+ TestAddHmiState(HMILevel::HMI_FULL,
+ HmiState::STATE_ID_PHONE_CALL,
+ &ApplicationImpl::AddHMIState);
+
+ CheckCurrentHMIState();
+ EXPECT_EQ(app_id, app_impl->app_id());
+}
+
+TEST_F(ApplicationImplTest, AddRegularHmiState_GetCurrentState) {
+ TestAddHmiState(HMILevel::HMI_LIMITED,
+ HmiState::STATE_ID_REGULAR,
+ &ApplicationImpl::SetRegularState);
+
+ CheckCurrentHMIState();
+ EXPECT_EQ(app_id, app_impl->app_id());
+}
+
+TEST_F(ApplicationImplTest, AddStateAddRegularState_GetCurrentState) {
+ TestAddHmiState(HMILevel::HMI_FULL,
+ HmiState::STATE_ID_REGULAR,
+ &ApplicationImpl::SetRegularState);
+ TestAddHmiState(HMILevel::HMI_LIMITED,
+ HmiState::STATE_ID_NAVI_STREAMING,
+ &ApplicationImpl::AddHMIState);
+
+ CheckCurrentHMIState();
+ EXPECT_EQ(app_id, app_impl->app_id());
+}
+
+TEST_F(ApplicationImplTest, AddStateAddRegularState_GetRegularState) {
+ TestAddHmiState(HMILevel::HMI_FULL,
+ HmiState::STATE_ID_REGULAR,
+ &ApplicationImpl::SetRegularState);
+ TestAddHmiState(HMILevel::HMI_LIMITED,
+ HmiState::STATE_ID_NAVI_STREAMING,
+ &ApplicationImpl::AddHMIState);
+
+ HmiStatePtr current_state = app_impl->RegularHmiState();
+ EXPECT_EQ(HMILevel::HMI_FULL, current_state->hmi_level());
+ EXPECT_EQ(HmiState::STATE_ID_REGULAR, current_state->state_id());
+ EXPECT_EQ(app_id, app_impl->app_id());
+}
+
+TEST_F(ApplicationImplTest, AddStates_RemoveLastState) {
+ // First state
+ TestAddHmiState(HMILevel::HMI_FULL,
+ HmiState::STATE_ID_PHONE_CALL,
+ &ApplicationImpl::AddHMIState);
+ HmiStatePtr state2 = TestAddHmiState(HMILevel::HMI_NONE,
+ HmiState::STATE_ID_NAVI_STREAMING,
+ &ApplicationImpl::AddHMIState);
+ HmiStatePtr state3 = TestAddHmiState(HMILevel::HMI_LIMITED,
+ HmiState::STATE_ID_TTS_SESSION,
+ &ApplicationImpl::AddHMIState);
+
+ CheckCurrentHMIState();
+
+ // Remove last state
+ app_impl->RemoveHMIState(state3->state_id());
+ HmiStatePtr current_state = app_impl->CurrentHmiState();
+ EXPECT_EQ(state2, current_state);
+ EXPECT_EQ(HMILevel::HMI_NONE, current_state->hmi_level());
+ EXPECT_EQ(HmiState::STATE_ID_NAVI_STREAMING, current_state->state_id());
+}
+
+TEST_F(ApplicationImplTest, AddStates_RemoveNotLastNotFirstState) {
+ HmiStatePtr state1 = TestAddHmiState(HMILevel::HMI_FULL,
+ HmiState::STATE_ID_PHONE_CALL,
+ &ApplicationImpl::AddHMIState);
+ HmiStatePtr state2 = TestAddHmiState(HMILevel::HMI_NONE,
+ HmiState::STATE_ID_NAVI_STREAMING,
+ &ApplicationImpl::AddHMIState);
+ HmiStatePtr state3 = TestAddHmiState(HMILevel::HMI_LIMITED,
+ HmiState::STATE_ID_TTS_SESSION,
+ &ApplicationImpl::AddHMIState);
+
+ CheckCurrentHMIState();
+
+ // Remove not last state
+ app_impl->RemoveHMIState(state2->state_id());
+ HmiStatePtr current_state = app_impl->CurrentHmiState();
+ EXPECT_EQ(state3, current_state);
+ // HMI level is equal to parent hmi_level
+ EXPECT_EQ(HMILevel::HMI_FULL, current_state->hmi_level());
+ EXPECT_EQ(HmiState::STATE_ID_TTS_SESSION, current_state->state_id());
+ EXPECT_EQ(state1, current_state->parent());
+}
+
+TEST_F(ApplicationImplTest, AddStates_RemoveFirstState) {
+ HmiStatePtr state1 = TestAddHmiState(HMILevel::HMI_FULL,
+ HmiState::STATE_ID_PHONE_CALL,
+ &ApplicationImpl::AddHMIState);
+ // Second state
+ TestAddHmiState(HMILevel::HMI_NONE,
+ HmiState::STATE_ID_NAVI_STREAMING,
+ &ApplicationImpl::AddHMIState);
+ HmiStatePtr state3 = TestAddHmiState(HMILevel::HMI_LIMITED,
+ HmiState::STATE_ID_TTS_SESSION,
+ &ApplicationImpl::AddHMIState);
+ CheckCurrentHMIState();
+
+ // Remove first added state
+ app_impl->RemoveHMIState(state1->state_id());
+ HmiStatePtr current_state = app_impl->CurrentHmiState();
+ EXPECT_EQ(state3, current_state);
+ // Last state does not have a parent
+ EXPECT_EQ(HMILevel::HMI_LIMITED, current_state->hmi_level());
+ EXPECT_EQ(HmiState::STATE_ID_TTS_SESSION, current_state->state_id());
+ EXPECT_EQ(NULL, current_state->parent());
+}
+
+TEST_F(ApplicationImplTest, SetRegularState_RemoveFirstState) {
+ HmiStatePtr state1 = TestAddHmiState(HMILevel::HMI_NONE,
+ HmiState::STATE_ID_NAVI_STREAMING,
+ &ApplicationImpl::AddHMIState);
+ // Set regular state
+ HmiStatePtr state2 = TestAddHmiState(HMILevel::HMI_FULL,
+ HmiState::STATE_ID_REGULAR,
+ &ApplicationImpl::SetRegularState);
+ HmiStatePtr state3 = TestAddHmiState(HMILevel::HMI_LIMITED,
+ HmiState::STATE_ID_TTS_SESSION,
+ &ApplicationImpl::AddHMIState);
+ CheckCurrentHMIState();
+
+ // Remove first state
+ app_impl->RemoveHMIState(state1->state_id());
+ HmiStatePtr current_state = app_impl->CurrentHmiState();
+ EXPECT_EQ(state3, current_state);
+ // Last state has a parent
+ EXPECT_EQ(HMILevel::HMI_FULL, current_state->hmi_level());
+ EXPECT_EQ(HmiState::STATE_ID_TTS_SESSION, current_state->state_id());
+ EXPECT_EQ(state2, current_state->parent());
+}
+
+TEST_F(ApplicationImplTest, SetPostponedState_RemovePostponedState) {
+ // Set postponed hmi state
+ HmiStatePtr state1 = TestAddHmiState(HMILevel::HMI_NONE,
+ HmiState::STATE_ID_POSTPONED,
+ &ApplicationImpl::SetPostponedState);
+
+ // Check that state was setted correctly
+ HmiStatePtr state2 = app_impl->PostponedHmiState();
+ EXPECT_EQ(state1, state2);
+
+ // Check that state was correctly removed
+ app_impl->RemovePostponedState();
+ state2 = app_impl->PostponedHmiState();
+ EXPECT_EQ(NULL, state2);
+}
+
+TEST_F(ApplicationImplTest, AddStateAddRegularState_GetHmiLvlAudioSystemState) {
+ audiostate = AudioStreamingState::ATTENUATED;
+ syst_context = SystemContext::SYSCTXT_ALERT;
+ TestAddHmiState(HMILevel::HMI_FULL,
+ HmiState::STATE_ID_REGULAR,
+ &ApplicationImpl::SetRegularState);
+
+ EXPECT_EQ(test_lvl, app_impl->hmi_level());
+ EXPECT_EQ(audiostate, app_impl->audio_streaming_state());
+ EXPECT_EQ(syst_context, app_impl->system_context());
+
+ audiostate = AudioStreamingState::AUDIBLE;
+ syst_context = SystemContext::SYSCTXT_MENU;
+ TestAddHmiState(HMILevel::HMI_LIMITED,
+ HmiState::STATE_ID_NAVI_STREAMING,
+ &ApplicationImpl::AddHMIState);
+
+ EXPECT_EQ(test_lvl, app_impl->hmi_level());
+ EXPECT_EQ(audiostate, app_impl->audio_streaming_state());
+ EXPECT_EQ(syst_context, app_impl->system_context());
+}
+
+TEST_F(ApplicationImplTest, IsAudioApplication) {
+ EXPECT_FALSE(app_impl->IsAudioApplication());
+ app_impl->set_is_navi(true);
+ app_impl->set_is_media_application(false);
+ app_impl->set_voice_communication_supported(false);
+ EXPECT_TRUE(app_impl->IsAudioApplication());
+ app_impl->set_is_navi(false);
+ app_impl->set_is_media_application(true);
+ app_impl->set_voice_communication_supported(false);
+ EXPECT_TRUE(app_impl->IsAudioApplication());
+ app_impl->set_is_navi(false);
+ app_impl->set_is_media_application(false);
+ app_impl->set_voice_communication_supported(true);
+ EXPECT_TRUE(app_impl->IsAudioApplication());
+ app_impl->set_is_media_application(false);
+ app_impl->set_voice_communication_supported(false);
+ app_impl->set_is_navi(false);
+ EXPECT_FALSE(app_impl->IsAudioApplication());
+}
+
+TEST_F(ApplicationImplTest, AddFile) {
+ AppFile test_file;
+
+ test_file.is_persistent = true;
+ test_file.is_download_complete = false;
+ test_file.file_type = FileType::AUDIO_AAC;
+ test_file.file_name = "test_file 1";
+
+ EXPECT_TRUE(app_impl->AddFile(test_file));
+ test_file.is_download_complete = true;
+ EXPECT_FALSE(app_impl->AddFile(test_file));
+ test_file.file_name = "test_file 2";
+ EXPECT_TRUE(app_impl->AddFile(test_file));
+}
+
+TEST_F(ApplicationImplTest, UpdateFile) {
+ AppFile test_file;
+
+ test_file.is_persistent = true;
+ test_file.is_download_complete = false;
+ test_file.file_type = FileType::AUDIO_AAC;
+ test_file.file_name = "test_file 1";
+
+ EXPECT_FALSE(app_impl->UpdateFile(test_file));
+ EXPECT_TRUE(app_impl->AddFile(test_file));
+ test_file.is_download_complete = true;
+ EXPECT_FALSE(app_impl->AddFile(test_file));
+ EXPECT_TRUE(app_impl->UpdateFile(test_file));
+}
+
+TEST_F(ApplicationImplTest, DeleteFile) {
+ AppFile test_file;
+ test_file.is_persistent = true;
+ test_file.is_download_complete = false;
+ test_file.file_type = FileType::AUDIO_AAC;
+ test_file.file_name = "test_file 1";
+
+ EXPECT_FALSE(app_impl->DeleteFile(test_file.file_name));
+ EXPECT_TRUE(app_impl->AddFile(test_file));
+ EXPECT_TRUE(app_impl->DeleteFile(test_file.file_name));
+ EXPECT_FALSE(app_impl->DeleteFile(test_file.file_name));
+ EXPECT_TRUE(app_impl->AddFile(test_file));
+}
+
+TEST_F(ApplicationImplTest, GetFile) {
+ AppFile test_file;
+ test_file.is_persistent = true;
+ test_file.is_download_complete = true;
+ test_file.file_type = FileType::GRAPHIC_JPEG;
+ test_file.file_name = "test_file 1";
+
+ EXPECT_EQ(NULL, app_impl->GetFile(test_file.file_name));
+ EXPECT_TRUE(app_impl->AddFile(test_file));
+ const AppFile* app_file = app_impl->GetFile(test_file.file_name);
+ EXPECT_EQ(test_file.is_persistent, app_file->is_persistent);
+ EXPECT_EQ(test_file.is_download_complete, app_file->is_download_complete);
+ EXPECT_EQ(test_file.file_type, app_file->file_type);
+}
+
+TEST_F(ApplicationImplTest, SetIconPath) {
+ AppFile test_file;
+ test_file.is_persistent = true;
+ test_file.is_download_complete = false;
+ test_file.file_type = FileType::GRAPHIC_BMP;
+ test_file.file_name = "test_file 1";
+
+ EXPECT_TRUE(app_impl->AddFile(test_file));
+ test_file.file_name = "test_file 2";
+ test_file.file_type = FileType::GRAPHIC_PNG;
+ EXPECT_TRUE(app_impl->AddFile(test_file));
+
+ EXPECT_TRUE(app_impl->set_app_icon_path(test_file.file_name));
+ EXPECT_EQ(test_file.file_name, app_impl->app_icon_path());
+}
+
+TEST_F(ApplicationImplTest, LoadPersistentFiles) {
+ // Precondition
+ // Create test folder with diff files
+
+ app_impl->MarkRegistered();
+ std::string folder_name = "";
+ app_impl->set_folder_name(folder_name);
+
+ file_system::CreateDirectory(directory_name);
+
+ EXPECT_TRUE(file_system::CreateFile(directory_name + "/test_file1.json"));
+ EXPECT_TRUE(file_system::CreateFile(directory_name + "/test_file2.bmp"));
+ EXPECT_TRUE(file_system::CreateFile(directory_name + "/test_file3.jpeg"));
+ EXPECT_TRUE(file_system::CreateFile(directory_name + "/test_file4.png"));
+ EXPECT_TRUE(file_system::CreateFile(directory_name + "/test_file5"));
+ EXPECT_TRUE(file_system::CreateFile(directory_name + "/test_file6.wave"));
+ EXPECT_TRUE(file_system::CreateFile(directory_name + "/test_file7.mp4"));
+ EXPECT_TRUE(file_system::CreateFile(directory_name + "/test_file8.mp3"));
+
+ app_impl->LoadPersistentFiles();
+
+ AppFilesMap files_map = app_impl->getAppFiles();
+
+ EXPECT_EQ(8u, files_map.size());
+ const AppFile* test_file1 =
+ app_impl->GetFile(directory_name + "//test_file1.json");
+ ASSERT_TRUE(test_file1);
+ EXPECT_EQ(FileType::JSON, test_file1->file_type);
+ const AppFile* test_file2 =
+ app_impl->GetFile(directory_name + "//test_file2.bmp");
+ ASSERT_TRUE(test_file2);
+ EXPECT_EQ(FileType::GRAPHIC_BMP, test_file2->file_type);
+ const AppFile* test_file3 =
+ app_impl->GetFile(directory_name + "//test_file3.jpeg");
+ ASSERT_TRUE(test_file3);
+ EXPECT_EQ(FileType::GRAPHIC_JPEG, test_file3->file_type);
+ const AppFile* test_file4 =
+ app_impl->GetFile(directory_name + "//test_file4.png");
+ ASSERT_TRUE(test_file4);
+ EXPECT_EQ(FileType::GRAPHIC_PNG, test_file4->file_type);
+ const AppFile* test_file5 =
+ app_impl->GetFile(directory_name + "//test_file5");
+ ASSERT_TRUE(test_file5);
+ EXPECT_EQ(FileType::BINARY, test_file5->file_type);
+ const AppFile* test_file6 =
+ app_impl->GetFile(directory_name + "//test_file6.wave");
+ ASSERT_TRUE(test_file6);
+ EXPECT_EQ(FileType::AUDIO_WAVE, test_file6->file_type);
+ const AppFile* test_file7 =
+ app_impl->GetFile(directory_name + "//test_file7.mp4");
+ ASSERT_TRUE(test_file7);
+ EXPECT_EQ(FileType::AUDIO_AAC, test_file7->file_type);
+ const AppFile* test_file8 =
+ app_impl->GetFile(directory_name + "//test_file8.mp3");
+ ASSERT_TRUE(test_file8);
+ EXPECT_EQ(FileType::AUDIO_MP3, test_file8->file_type);
+}
+
+TEST_F(ApplicationImplTest, IsCommandLimitsExceeded_SetLimitFromConfig) {
+ std::pair<uint32_t, int32_t> get_frequency;
+ get_frequency.first = 5;
+ get_frequency.second = 1;
+ EXPECT_CALL(mock_application_manager_settings_, read_did_frequency())
+ .WillRepeatedly(ReturnRef(get_frequency));
+ EXPECT_CALL(mock_application_manager_settings_, get_vehicle_data_frequency())
+ .WillRepeatedly(ReturnRef(get_frequency));
+ for (uint32_t i = 0; i < get_frequency.first; i++) {
+ EXPECT_FALSE(app_impl->IsCommandLimitsExceeded(FunctionID::ReadDIDID,
+ TLimitSource::CONFIG_FILE));
+ }
+ EXPECT_TRUE(app_impl->IsCommandLimitsExceeded(FunctionID::ReadDIDID,
+ TLimitSource::CONFIG_FILE));
+
+ for (uint32_t i = 0; i < get_frequency.first; i++) {
+ EXPECT_FALSE(app_impl->IsCommandLimitsExceeded(FunctionID::GetVehicleDataID,
+ TLimitSource::CONFIG_FILE));
+ }
+ EXPECT_TRUE(app_impl->IsCommandLimitsExceeded(FunctionID::GetVehicleDataID,
+ TLimitSource::CONFIG_FILE));
+}
+
+TEST_F(ApplicationImplTest, IsCommandLimitsExceeded_LimitFromPT) {
+ policy_test::MockPolicyHandlerInterface policy_interface;
+ EXPECT_CALL(mock_application_manager_, GetPolicyHandler())
+ .WillRepeatedly(ReturnRef(policy_interface));
+ EXPECT_CALL(policy_interface, GetPriority(policy_app_id, _))
+ .WillRepeatedly(Return(false));
+
+ EXPECT_CALL(policy_interface, GetNotificationsNumber(_))
+ .WillOnce(Return(100u));
+ EXPECT_FALSE(app_impl->IsCommandLimitsExceeded(FunctionID::ReadDIDID,
+ TLimitSource::POLICY_TABLE));
+
+ EXPECT_CALL(policy_interface, GetNotificationsNumber(_))
+ .WillOnce(Return(100u));
+ EXPECT_FALSE(app_impl->IsCommandLimitsExceeded(FunctionID::GetVehicleDataID,
+ TLimitSource::POLICY_TABLE));
+ EXPECT_CALL(policy_interface, GetNotificationsNumber(_))
+ .WillRepeatedly(Return(0));
+ EXPECT_TRUE(app_impl->IsCommandLimitsExceeded(FunctionID::ReadDIDID,
+ TLimitSource::POLICY_TABLE));
+ EXPECT_TRUE(app_impl->IsCommandLimitsExceeded(FunctionID::GetVehicleDataID,
+ TLimitSource::POLICY_TABLE));
+}
+
+TEST_F(ApplicationImplTest, SubscribeToButton_UnsubscribeFromButton) {
+ EXPECT_TRUE(app_impl->SubscribeToButton(ButtonName::PRESET_0));
+ // It is impossible to subsribe to the same button twice
+ EXPECT_FALSE(app_impl->SubscribeToButton(ButtonName::PRESET_0));
+ EXPECT_TRUE(app_impl->IsSubscribedToButton(ButtonName::PRESET_0));
+ EXPECT_TRUE(app_impl->UnsubscribeFromButton(ButtonName::PRESET_0));
+ EXPECT_FALSE(app_impl->IsSubscribedToButton(ButtonName::PRESET_0));
+}
+
+TEST_F(ApplicationImplTest, SubscribeToDefaultButton_UnsubscribeFromButton) {
+ EXPECT_TRUE(app_impl->IsSubscribedToButton(ButtonName::CUSTOM_BUTTON));
+ EXPECT_FALSE(app_impl->SubscribeToButton(ButtonName::CUSTOM_BUTTON));
+}
+
+TEST_F(ApplicationImplTest, SubscribeToSoftButton_UnsubscribeFromSoftButton) {
+ const uint btn_count = 10;
+ for (uint i = 0; i < btn_count; i++) {
+ EXPECT_FALSE(app_impl->IsSubscribedToSoftButton(i));
+ }
+
+ SoftButtonID test_button;
+ for (uint i = 0; i < btn_count; i++) {
+ test_button.insert(i);
+ }
+ app_impl->SubscribeToSoftButtons(FunctionID::ScrollableMessageID,
+ test_button);
+
+ for (uint i = 0; i < btn_count; i++) {
+ EXPECT_TRUE(app_impl->IsSubscribedToSoftButton(i));
+ }
+ app_impl->UnsubscribeFromSoftButtons(FunctionID::ScrollableMessageID);
+
+ for (uint i = 0; i < btn_count; i++) {
+ EXPECT_FALSE(app_impl->IsSubscribedToSoftButton(i));
+ }
+}
+
+TEST_F(ApplicationImplTest, ChangeSupportingAppHMIType_TypeNotNaviNotVoice) {
+ smart_objects::SmartObject type_media;
+ type_media[0] = AppHMIType::MEDIA;
+
+ EXPECT_FALSE(app_impl->is_navi());
+ EXPECT_FALSE(app_impl->is_voice_communication_supported());
+
+ app_impl->set_app_types(type_media);
+ app_impl->ChangeSupportingAppHMIType();
+
+ EXPECT_FALSE(app_impl->is_navi());
+ EXPECT_FALSE(app_impl->is_voice_communication_supported());
+}
+
+TEST_F(ApplicationImplTest, ChangeSupportingAppHMIType_TypeIsVoice) {
+ smart_objects::SmartObject type_comm;
+ type_comm[0] = AppHMIType::COMMUNICATION;
+
+ EXPECT_FALSE(app_impl->is_navi());
+ EXPECT_FALSE(app_impl->is_voice_communication_supported());
+
+ app_impl->set_app_types(type_comm);
+ app_impl->ChangeSupportingAppHMIType();
+
+ EXPECT_FALSE(app_impl->is_navi());
+ EXPECT_TRUE(app_impl->is_voice_communication_supported());
+}
+
+TEST_F(ApplicationImplTest, ChangeSupportingAppHMIType_TypeIsNavi) {
+ smart_objects::SmartObject type_navi;
+ type_navi[0] = AppHMIType::NAVIGATION;
+
+ EXPECT_FALSE(app_impl->is_navi());
+ EXPECT_FALSE(app_impl->is_voice_communication_supported());
+
+ app_impl->set_app_types(type_navi);
+ app_impl->ChangeSupportingAppHMIType();
+
+ EXPECT_TRUE(app_impl->is_navi());
+ EXPECT_FALSE(app_impl->is_voice_communication_supported());
+}
+
+TEST_F(ApplicationImplTest, ChangeSupportingAppHMIType_TypeIsNaviAndVoice) {
+ smart_objects::SmartObject app_types;
+ app_types[0] = AppHMIType::NAVIGATION;
+ app_types[1] = AppHMIType::COMMUNICATION;
+ app_types[2] = AppHMIType::MEDIA;
+
+ EXPECT_FALSE(app_impl->is_navi());
+ EXPECT_FALSE(app_impl->is_voice_communication_supported());
+
+ app_impl->set_app_types(app_types);
+ app_impl->ChangeSupportingAppHMIType();
+
+ EXPECT_TRUE(app_impl->is_navi());
+ EXPECT_TRUE(app_impl->is_voice_communication_supported());
+}
+
+TEST_F(ApplicationImplTest, UpdateHash_AppMngrNotSuspended) {
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendHashUpdateNotification(app_id, _)).Times(1);
+ app_impl->UpdateHash();
+
+ EXPECT_TRUE(app_impl->is_application_data_changed());
+}
+
+TEST_F(ApplicationImplTest, StartStreaming_MobileNavi_StreamingNotApproved) {
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendNaviStartStream(app_id, _));
+ app_impl->StartStreaming(protocol_handler::ServiceType::kMobileNav);
+
+ EXPECT_EQ(0u, app_impl->video_stream_retry_number());
+}
+
+TEST_F(ApplicationImplTest, StartStreaming_Audio_StreamingNotApproved) {
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendAudioStartStream(app_id, _));
+ app_impl->StartStreaming(protocol_handler::ServiceType::kAudio);
+
+ EXPECT_EQ(0u, app_impl->video_stream_retry_number());
+}
+
+TEST_F(ApplicationImplTest, StartStreaming_StreamingApproved) {
+ app_impl->set_video_streaming_approved(true);
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendNaviStartStream(app_id, _)).Times(0);
+ app_impl->StartStreaming(protocol_handler::ServiceType::kMobileNav);
+
+ app_impl->set_audio_streaming_approved(true);
+
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendAudioStartStream(app_id, _)).Times(0);
+ app_impl->StartStreaming(protocol_handler::ServiceType::kAudio);
+}
+
+TEST_F(ApplicationImplTest, SuspendNaviStreaming) {
+ protocol_handler::ServiceType type =
+ protocol_handler::ServiceType::kMobileNav;
+ EXPECT_CALL(mock_application_manager_, OnAppStreaming(app_id, type, false));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnDataStreaming(type, false, _));
+ app_impl->SuspendStreaming(type);
+}
+
+TEST_F(ApplicationImplTest, SuspendAudioStreaming) {
+ protocol_handler::ServiceType type = protocol_handler::ServiceType::kAudio;
+ EXPECT_CALL(mock_application_manager_, OnAppStreaming(app_id, type, false));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnDataStreaming(type, false, _));
+ app_impl->SuspendStreaming(type);
+}
+
+// TODO {AKozoriz} : Fix tests with streaming (APPLINK-19289)
+TEST_F(ApplicationImplTest, DISABLED_Suspend_WakeUpAudioStreaming) {
+ protocol_handler::ServiceType type = protocol_handler::ServiceType::kAudio;
+ EXPECT_CALL(mock_application_manager_, OnAppStreaming(app_id, type, false));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnDataStreaming(type, false, _));
+ app_impl->SuspendStreaming(type);
+
+ EXPECT_CALL(mock_application_manager_, OnAppStreaming(app_id, type, true));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnDataStreaming(type, true, _));
+ app_impl->WakeUpStreaming(type);
+}
+
+TEST_F(ApplicationImplTest, DISABLED_Suspend_WakeUpNaviStreaming) {
+ protocol_handler::ServiceType type =
+ protocol_handler::ServiceType::kMobileNav;
+ EXPECT_CALL(mock_application_manager_, OnAppStreaming(app_id, type, false));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnDataStreaming(type, false, _));
+ app_impl->SuspendStreaming(type);
+
+ EXPECT_CALL(mock_application_manager_, OnAppStreaming(app_id, type, true));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnDataStreaming(type, true, _));
+ app_impl->WakeUpStreaming(type);
+}
+
+TEST_F(ApplicationImplTest, StopStreaming_StreamingApproved) {
+ // Stop navigation streaming
+ protocol_handler::ServiceType type =
+ protocol_handler::ServiceType::kMobileNav;
+ app_impl->set_video_streaming_approved(true);
+
+ EXPECT_CALL(mock_application_manager_, OnAppStreaming(app_id, type, false));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnDataStreaming(type, false, _));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendNaviStopStream(app_id, _));
+
+ app_impl->StopStreaming(type);
+ EXPECT_FALSE(app_impl->video_streaming_approved());
+
+ // Stop audio streaming
+ app_impl->set_audio_streaming_approved(true);
+ type = protocol_handler::ServiceType::kAudio;
+ EXPECT_CALL(mock_application_manager_, OnAppStreaming(app_id, type, false));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnDataStreaming(type, false, _));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendAudioStopStream(app_id, _));
+
+ app_impl->StopStreaming(type);
+ EXPECT_FALSE(app_impl->audio_streaming_approved());
+}
+
+} // namespace application_manager_test
+} // namespace components
+} // namespace test
diff --git a/src/components/application_manager/test/application_state_test.cc b/src/components/application_manager/test/application_state_test.cc
new file mode 100644
index 0000000000..7bc34966b4
--- /dev/null
+++ b/src/components/application_manager/test/application_state_test.cc
@@ -0,0 +1,268 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/application_state.h"
+#include "gtest/gtest.h"
+#include "application_manager/hmi_state.h"
+#include "application_manager/mock_application_manager.h"
+#include "application_manager/event_engine/event_dispatcher.h"
+#include "resumption/last_state.h"
+#include "application_manager/policies/policy_handler.h"
+#include "application_manager/state_controller.h"
+#include "application_manager/resumption/resume_ctrl.h"
+
+#include "utils/make_shared.h"
+
+namespace test {
+namespace components {
+namespace application_manager_test {
+
+using namespace application_manager;
+using namespace mobile_apis;
+typedef HmiState::StateID StateID;
+
+namespace {
+std::vector<StateID> GenerateCurrentStates() {
+ std::vector<StateID> states;
+ states.push_back(StateID::STATE_ID_PHONE_CALL);
+ states.push_back(StateID::STATE_ID_SAFETY_MODE);
+ states.push_back(StateID::STATE_ID_VR_SESSION);
+ states.push_back(StateID::STATE_ID_TTS_SESSION);
+ states.push_back(StateID::STATE_ID_NAVI_STREAMING);
+ states.push_back(StateID::STATE_ID_DEACTIVATE_HMI);
+ return states;
+}
+}
+
+class ApplicationStateTest : public ::testing::Test {
+ protected:
+ static std::vector<StateID> added_states_;
+ ApplicationState app_state;
+ const StateID current_id = StateID::STATE_ID_CURRENT;
+ const StateID postponed_id = StateID::STATE_ID_POSTPONED;
+ const uint32_t app_id = 10;
+ MockApplicationManager app_mngr_;
+};
+
+std::vector<StateID> ApplicationStateTest::added_states_ =
+ GenerateCurrentStates();
+
+TEST_F(ApplicationStateTest, AddStates_GetCurrentStates) {
+ std::vector<StateID>::iterator new_state = added_states_.begin();
+ for (; new_state != added_states_.end(); ++new_state) {
+ HmiStatePtr state =
+ utils::MakeShared<HmiState>(app_id, app_mngr_, *new_state);
+ app_state.AddState(state);
+ EXPECT_EQ(state, app_state.GetState(current_id));
+ }
+}
+
+TEST_F(ApplicationStateTest, AddStates_RemoveStates_GetCurrentState) {
+ std::vector<StateID>::iterator new_state = added_states_.begin();
+ for (; new_state != added_states_.end(); ++new_state) {
+ HmiStatePtr state =
+ utils::MakeShared<HmiState>(app_id, app_mngr_, *new_state);
+ app_state.AddState(state);
+
+ HmiStatePtr curr_state = app_state.GetState(current_id);
+ ASSERT_EQ(*new_state, curr_state->state_id());
+ }
+
+ new_state = added_states_.end() - 1;
+ while (new_state != added_states_.begin()) {
+ app_state.RemoveState(*new_state);
+ HmiStatePtr curr_state = app_state.GetState(current_id);
+ --new_state;
+ EXPECT_EQ(*new_state, curr_state->state_id());
+ }
+}
+
+TEST_F(ApplicationStateTest, AddStatesAddPostponedState_GetPostponedState) {
+ // Added some states
+ std::vector<StateID>::iterator new_state = added_states_.begin();
+ for (; new_state != added_states_.end(); ++new_state) {
+ HmiStatePtr state =
+ utils::MakeShared<HmiState>(app_id, app_mngr_, *new_state);
+ app_state.AddState(state);
+ }
+ // Postponed state wasn't added
+ HmiStatePtr get_postponed_id = app_state.GetState(postponed_id);
+ EXPECT_EQ(NULL, get_postponed_id);
+ // Add posponed state
+ HmiStatePtr state =
+ utils::MakeShared<HmiState>(app_id, app_mngr_, postponed_id);
+ app_state.AddState(state);
+ // Postponed state exists
+ get_postponed_id = app_state.GetState(postponed_id);
+ EXPECT_EQ(state, get_postponed_id);
+}
+
+TEST_F(ApplicationStateTest, AddStates_GetRegularState) {
+ // Add state
+ std::vector<StateID>::iterator new_state = added_states_.begin();
+ HmiStatePtr state =
+ utils::MakeShared<HmiState>(app_id, app_mngr_, *new_state);
+ state->set_hmi_level(HMILevel::HMI_FULL);
+ app_state.AddState(state);
+ ++new_state;
+ // Add some other
+ for (; new_state != added_states_.end(); ++new_state) {
+ state = utils::MakeShared<HmiState>(app_id, app_mngr_, *new_state);
+ app_state.AddState(state);
+ state->set_hmi_level(HMILevel::HMI_LIMITED);
+ }
+
+ // Regular state will be the first added state
+ new_state = added_states_.begin();
+ HmiStatePtr reg_state = app_state.GetState(StateID::STATE_ID_REGULAR);
+ EXPECT_EQ(*new_state, reg_state->state_id());
+ EXPECT_EQ(HMILevel::HMI_FULL, reg_state->hmi_level());
+}
+
+TEST_F(ApplicationStateTest, AddRegularState_RemoveFirstState_GetRegularState) {
+ std::vector<StateID>::iterator new_state = added_states_.begin();
+ HmiStatePtr state =
+ utils::MakeShared<HmiState>(app_id, app_mngr_, *new_state);
+ app_state.AddState(state);
+ ++new_state;
+
+ // Add postponed state
+ state = utils::MakeShared<HmiState>(app_id, app_mngr_, postponed_id);
+ app_state.AddState(state);
+
+ // Make sure that the state was added
+ HmiStatePtr post_state = app_state.GetState(postponed_id);
+ ASSERT_EQ(state, post_state);
+
+ for (; new_state != added_states_.end(); ++new_state) {
+ state = utils::MakeShared<HmiState>(app_id, app_mngr_, *new_state);
+ app_state.AddState(state);
+ }
+
+ // Regular state will be the first added state
+ new_state = added_states_.begin();
+ HmiStatePtr reg_state = app_state.GetState(StateID::STATE_ID_REGULAR);
+ ASSERT_EQ(*new_state, reg_state->state_id());
+
+ app_state.RemoveState(*new_state);
+
+ ++new_state;
+ // Now regular state is the next state except postponed
+ reg_state = app_state.GetState(StateID::STATE_ID_REGULAR);
+ EXPECT_EQ(*new_state, reg_state->state_id());
+}
+
+TEST_F(ApplicationStateTest, AddRegularState_PreviousStatePostponed) {
+ // Add some state
+ StateID first_state = StateID::STATE_ID_PHONE_CALL;
+ HmiStatePtr state =
+ utils::MakeShared<HmiState>(app_id, app_mngr_, first_state);
+ app_state.AddState(state);
+
+ // Add postponed state
+ state = utils::MakeShared<HmiState>(app_id, app_mngr_, postponed_id);
+ app_state.AddState(state);
+
+ // Add new postponed state
+ const uint32_t app_id2 = 10;
+ state = utils::MakeShared<HmiState>(app_id2, app_mngr_, postponed_id);
+ app_state.AddState(state);
+
+ // Add regular state
+ state =
+ utils::MakeShared<HmiState>(app_id, app_mngr_, StateID::STATE_ID_REGULAR);
+ app_state.AddState(state);
+
+ // Postponed state is the first
+ HmiStatePtr reg_state = app_state.GetState(StateID::STATE_ID_POSTPONED);
+ ASSERT_EQ(postponed_id, reg_state->state_id());
+
+ // Regular state is the second one
+ reg_state = app_state.GetState(StateID::STATE_ID_REGULAR);
+ EXPECT_EQ(StateID::STATE_ID_REGULAR, reg_state->state_id());
+}
+
+TEST_F(ApplicationStateTest, InitState_GetRegularState) {
+ StateID init_state = StateID::STATE_ID_REGULAR;
+ HmiStatePtr state =
+ utils::MakeShared<HmiState>(app_id, app_mngr_, init_state);
+
+ app_state.InitState(state);
+
+ HmiStatePtr reg_state = app_state.GetState(StateID::STATE_ID_REGULAR);
+ EXPECT_EQ(state, reg_state);
+
+ HmiStatePtr curr_state = app_state.GetState(StateID::STATE_ID_CURRENT);
+ EXPECT_EQ(state, curr_state);
+}
+
+TEST_F(ApplicationStateTest, AddPosponedState_DeletePosponedState) {
+ // Precondition
+ StateID init_state = StateID::STATE_ID_REGULAR;
+ HmiStatePtr state =
+ utils::MakeShared<HmiState>(app_id, app_mngr_, init_state);
+ state->set_hmi_level(mobile_apis::HMILevel::HMI_FULL);
+
+ app_state.InitState(state);
+
+ // Add postponed state
+ state = utils::MakeShared<HmiState>(app_id, app_mngr_, postponed_id);
+ app_state.AddState(state);
+
+ // Make sure that state was added
+ HmiStatePtr get_postponed_state = app_state.GetState(postponed_id);
+ ASSERT_EQ(state, get_postponed_state);
+
+ // Remove postponed state
+ app_state.RemoveState(postponed_id);
+
+ get_postponed_state = app_state.GetState(postponed_id);
+ EXPECT_EQ(NULL, get_postponed_state);
+}
+
+TEST_F(ApplicationStateTest,
+ AddRegularState_RemoveRegularState_RegularStateNotDeleted) {
+ StateID reg_state = StateID::STATE_ID_REGULAR;
+ HmiStatePtr state = utils::MakeShared<HmiState>(app_id, app_mngr_, reg_state);
+ app_state.InitState(state);
+
+ // Try deleting regular state
+ app_state.RemoveState(reg_state);
+
+ // Get regular state
+ HmiStatePtr get_reg_state = app_state.GetState(reg_state);
+ EXPECT_EQ(state, get_reg_state);
+}
+
+} // namespace application_manager_test
+} // namespace components
+} // namespace test
diff --git a/src/components/application_manager/test/command_impl_test.cc b/src/components/application_manager/test/command_impl_test.cc
deleted file mode 100644
index 677515784f..0000000000
--- a/src/components/application_manager/test/command_impl_test.cc
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "gtest/gtest.h"
-#include "gmock/gmock.h"
-#include "application_manager/application_manager_impl.h"
-#include "application_manager/commands/command_request_impl.h"
-#include "application_manager/message_helper.h"
-#include "application_manager/smart_object_keys.h"
-#include "interfaces/MOBILE_API.h"
-
-using ::testing::Return;
-using ::testing::Truly;
-
-
-bool MessageResultCodeIsGENERIC_ERROR(const utils::SharedPtr<smart_objects::SmartObject>& message) {
- if (!message) {
- return false;
- }
- const smart_objects::SmartObject& so = *(message.get());
- int32_t result_code = so[application_manager::strings::msg_params]
- [application_manager::strings::result_code].asInt();
- if (mobile_apis::Result::GENERIC_ERROR
- == static_cast<mobile_apis::Result::eType>(result_code)) {
- return true;
- } else {
- return false;
- }
-}
-
-TEST(ApplicationManager, SingletonInstance_CallTwice_ReferencesAreSame) {
- application_manager::ApplicationManagerImpl* am = application_manager::ApplicationManagerImpl::instance();
- application_manager::ApplicationManagerImpl* am2 = application_manager::ApplicationManagerImpl::instance();
- ASSERT_EQ(am, am2);
- //EXPECT_CALL((*am), GetNextHMICorrelationID()).WillRepeatedly(Return(1));
- //smart_objects::SmartObjectSPtr so = application_manager::MessageHelper::CreateModuleInfoSO(0);
- application_manager::ApplicationManagerImpl::destroy();
-}
-
-TEST(MobileCommandsTest, CommandImplTimeOut) {
- application_manager::ApplicationManagerImpl* am = application_manager::ApplicationManagerImpl::instance();
- smart_objects::SmartObjectSPtr so = application_manager::MessageHelper::CreateModuleInfoSO(0);
- application_manager::commands::CommandRequestImpl request(so);
- EXPECT_CALL((*am), ManageMobileCommand(Truly(MessageResultCodeIsGENERIC_ERROR)));
- request.onTimeOut();
- application_manager::ApplicationManagerImpl::destroy();
-}
diff --git a/src/components/application_manager/test/commands/mobile/subscribe_way_points_request_test.cc b/src/components/application_manager/test/commands/mobile/subscribe_way_points_request_test.cc
new file mode 100644
index 0000000000..35755a08bb
--- /dev/null
+++ b/src/components/application_manager/test/commands/mobile/subscribe_way_points_request_test.cc
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "utils/shared_ptr.h"
+#include "smart_objects/smart_object.h"
+#include "commands/commands_test.h"
+#include "commands/command_request_test.h"
+#include "application_manager/application.h"
+#include "application_manager/mock_application_manager.h"
+#include "application_manager/mock_application.h"
+#include "application_manager/mock_hmi_capabilities.h"
+#include "mobile/subscribe_way_points_request.h"
+#include "interfaces/MOBILE_API.h"
+#include "application_manager/smart_object_keys.h"
+
+namespace test {
+namespace components {
+namespace commands_test {
+namespace mobile_commands_test {
+
+using ::testing::_;
+using ::testing::Return;
+using ::testing::ReturnRef;
+using ::testing::DoAll;
+using ::testing::SaveArg;
+using ::testing::InSequence;
+namespace am = ::application_manager;
+using am::commands::SubscribeWayPointsRequest;
+using am::commands::MessageSharedPtr;
+
+typedef SharedPtr<SubscribeWayPointsRequest> CommandPtr;
+
+class SubscribeWayPointsRequestTest
+ : public CommandRequestTest<CommandsTestMocks::kIsNice> {
+ public:
+ typedef TypeIf<kMocksIsNice,
+ NiceMock<application_manager_test::MockHMICapabilities>,
+ application_manager_test::MockHMICapabilities>::Result
+ MockHMICapabilities;
+};
+
+TEST_F(SubscribeWayPointsRequestTest, Run_SUCCESS) {
+ CommandPtr command(CreateCommand<SubscribeWayPointsRequest>());
+ MockAppPtr app(CreateMockApp());
+
+ ON_CALL(app_mngr_, application(_)).WillByDefault(Return(app));
+ ON_CALL(app_mngr_, IsAppSubscribedForWayPoints(_))
+ .WillByDefault(Return(false));
+ ON_CALL(app_mngr_, IsAnyAppSubscribedForWayPoints())
+ .WillByDefault(Return(true));
+
+ {
+ InSequence dummy;
+ EXPECT_CALL(app_mngr_, SubscribeAppForWayPoints(_));
+ EXPECT_CALL(*app, UpdateHash());
+ }
+
+ MessageSharedPtr mobile_result_msg(
+ CatchMobileCommandResult(CallRun(*command)));
+
+ EXPECT_EQ(mobile_apis::Result::SUCCESS,
+ static_cast<mobile_apis::Result::eType>(
+ (*mobile_result_msg)[am::strings::msg_params]
+ [am::strings::result_code].asInt()));
+}
+
+TEST_F(SubscribeWayPointsRequestTest, OnEvent_SUCCESS) {
+ CommandPtr command(CreateCommand<SubscribeWayPointsRequest>());
+ MockAppPtr app(CreateMockApp());
+ Event event(hmi_apis::FunctionID::Navigation_SubscribeWayPoints);
+
+ MessageSharedPtr event_msg(CreateMessage(smart_objects::SmartType_Map));
+ (*event_msg)[am::strings::params][am::hmi_response::code] =
+ mobile_apis::Result::SUCCESS;
+ (*event_msg)[am::strings::msg_params] = 0;
+
+ event.set_smart_object(*event_msg);
+
+ ON_CALL(app_mngr_, application(_)).WillByDefault(Return(app));
+
+ {
+ InSequence dummy;
+ EXPECT_CALL(app_mngr_, SubscribeAppForWayPoints(_));
+ EXPECT_CALL(app_mngr_, ManageMobileCommand(_, _));
+ EXPECT_CALL(*app, UpdateHash());
+ }
+
+ command->on_event(event);
+}
+
+} // namespace mobile_commands_test
+} // namespace commands_test
+} // namespace components
+} // namespace test
diff --git a/src/components/application_manager/test/commands/mobile/unsubscribe_way_points_request_test.cc b/src/components/application_manager/test/commands/mobile/unsubscribe_way_points_request_test.cc
new file mode 100644
index 0000000000..0a5ff9745b
--- /dev/null
+++ b/src/components/application_manager/test/commands/mobile/unsubscribe_way_points_request_test.cc
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "utils/shared_ptr.h"
+#include "smart_objects/smart_object.h"
+#include "commands/commands_test.h"
+#include "commands/command_request_test.h"
+#include "application_manager/application.h"
+#include "application_manager/mock_application_manager.h"
+#include "application_manager/mock_application.h"
+#include "application_manager/mock_hmi_capabilities.h"
+#include "mobile/unsubscribe_way_points_request.h"
+#include "interfaces/MOBILE_API.h"
+#include "application_manager/smart_object_keys.h"
+
+namespace test {
+namespace components {
+namespace commands_test {
+namespace mobile_commands_test {
+
+using ::testing::_;
+using ::testing::Return;
+using ::testing::ReturnRef;
+using ::testing::DoAll;
+using ::testing::SaveArg;
+using ::testing::InSequence;
+namespace am = ::application_manager;
+using am::commands::UnSubscribeWayPointsRequest;
+using am::commands::MessageSharedPtr;
+
+typedef SharedPtr<UnSubscribeWayPointsRequest> CommandPtr;
+
+class UnsubscribeWayPointsRequestTest
+ : public CommandRequestTest<CommandsTestMocks::kIsNice> {
+ public:
+ typedef TypeIf<kMocksIsNice,
+ NiceMock<application_manager_test::MockHMICapabilities>,
+ application_manager_test::MockHMICapabilities>::Result
+ MockHMICapabilities;
+};
+
+TEST_F(UnsubscribeWayPointsRequestTest, OnEvent_SUCCESS) {
+ CommandPtr command(CreateCommand<UnSubscribeWayPointsRequest>());
+ MockAppPtr app(CreateMockApp());
+ Event event(hmi_apis::FunctionID::Navigation_UnsubscribeWayPoints);
+
+ MessageSharedPtr event_msg(CreateMessage(smart_objects::SmartType_Map));
+ (*event_msg)[am::strings::params][am::hmi_response::code] =
+ mobile_apis::Result::SUCCESS;
+ (*event_msg)[am::strings::msg_params] = 0;
+
+ event.set_smart_object(*event_msg);
+
+ ON_CALL(app_mngr_, application(_)).WillByDefault(Return(app));
+
+ {
+ InSequence dummy;
+ EXPECT_CALL(app_mngr_, UnsubscribeAppFromWayPoints(_));
+ EXPECT_CALL(app_mngr_, ManageMobileCommand(_, _));
+ EXPECT_CALL(*app, UpdateHash());
+ }
+
+ command->on_event(event);
+}
+
+} // namespace mobile_commands_test
+} // namespace commands_test
+} // namespace components
+} // namespace test
diff --git a/src/components/application_manager/test/event_engine_test.cc b/src/components/application_manager/test/event_engine_test.cc
new file mode 100644
index 0000000000..e88dd2ba4e
--- /dev/null
+++ b/src/components/application_manager/test/event_engine_test.cc
@@ -0,0 +1,183 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+
+#include "application_manager/event_engine/event_observer.h"
+#include "application_manager/event_engine/event.h"
+#include "application_manager/event_engine/event_dispatcher_impl.h"
+#include "application_manager/event_observer_mock.h"
+#include "application_manager/mock_event_dispatcher.h"
+#include "smart_objects/smart_object.h"
+#include "utils/make_shared.h"
+#include "interfaces/HMI_API.h"
+
+namespace test {
+namespace components {
+namespace event_engine_test {
+
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+using application_manager::event_engine::EventDispatcherImpl;
+using application_manager::event_engine::Event;
+using application_manager::event_engine::EventObserver;
+using testing::_;
+
+class EventEngineTest : public testing::Test {
+ public:
+ EventEngineTest()
+ : event_id(Event::EventID::BasicCommunication_ActivateApp)
+ , event_id2(Event::EventID::BasicCommunication_OnAppActivated)
+ , event_id3(Event::EventID::VR_IsReady)
+ , event_observer_mock_(mock_event_dispatcher_) {}
+
+ protected:
+ EventDispatcherImpl* event_dispatcher_instance_;
+ Event* event_;
+ const application_manager::event_engine::Event::EventID event_id;
+ const application_manager::event_engine::Event::EventID event_id2;
+ const application_manager::event_engine::Event::EventID event_id3;
+ MockEventDispatcher mock_event_dispatcher_;
+ MockEventObserver event_observer_mock_;
+ const int32_t correlation_id = 1121;
+ smart_objects::SmartObject smart_object_with_type_notification;
+ smart_objects::SmartObject smart_object_with_type_response;
+ smart_objects::SmartObject smart_object_with_type_error_response;
+ smart_objects::SmartObject smart_object_with_type_request;
+ smart_objects::SmartObject smart_object_with_invalid_type;
+
+ virtual void SetUp() OVERRIDE {
+ event_dispatcher_instance_ = new EventDispatcherImpl();
+ event_ = new Event(hmi_apis::FunctionID::eType::VR_IsReady);
+ smart_object_with_type_notification["params"]["message_type"] =
+ hmi_apis::messageType::notification;
+ smart_object_with_type_notification["params"]["correlation_id"] =
+ correlation_id;
+ smart_object_with_type_notification["params"]["function_id"] =
+ hmi_apis::FunctionID::eType::VR_IsReady;
+
+ smart_object_with_type_response["params"]["message_type"] =
+ hmi_apis::messageType::response;
+ smart_object_with_type_response["params"]["correlation_id"] =
+ correlation_id;
+ smart_object_with_type_response["params"]["function_id"] =
+ hmi_apis::FunctionID::eType::VR_IsReady;
+
+ smart_object_with_type_error_response["params"]["message_type"] =
+ hmi_apis::messageType::error_response;
+ smart_object_with_type_error_response["params"]["correlation_id"] =
+ correlation_id;
+ smart_object_with_type_error_response["params"]["function_id"] =
+ hmi_apis::FunctionID::eType::VR_IsReady;
+
+ smart_object_with_type_request["params"]["message_type"] =
+ hmi_apis::messageType::request;
+ smart_object_with_type_request["params"]["correlation_id"] = correlation_id;
+ smart_object_with_type_request["params"]["function_id"] =
+ hmi_apis::FunctionID::eType::VR_IsReady;
+
+ smart_object_with_invalid_type["params"]["message_type"] =
+ hmi_apis::messageType::INVALID_ENUM;
+ smart_object_with_invalid_type["params"]["correlation_id"] = correlation_id;
+ smart_object_with_invalid_type["params"]["function_id"] =
+ hmi_apis::FunctionID::eType::VR_IsReady;
+ }
+
+ void TearDown() OVERRIDE {
+ delete event_dispatcher_instance_;
+ delete event_;
+ }
+
+ void CheckRaiseEvent(const Event::EventID& event_id,
+ const uint32_t calls_number,
+ const smart_objects::SmartObject& so) {
+ // Arrange
+ event_dispatcher_instance_->add_observer(
+ event_id, correlation_id, event_observer_mock_);
+ event_->set_smart_object(so);
+ EXPECT_CALL(event_observer_mock_, on_event(_)).Times(calls_number);
+ event_dispatcher_instance_->raise_event(*event_);
+ }
+};
+
+TEST_F(EventEngineTest, EventObserverTest_ExpectObserversEmpty) {
+ // Arrange
+ EventObserver* event_observer_ptr =
+ static_cast<EventObserver*>(&event_observer_mock_);
+ // Check
+ EXPECT_EQ(reinterpret_cast<unsigned long>(event_observer_ptr),
+ event_observer_mock_.id());
+}
+
+TEST_F(EventEngineTest,
+ EventDispatcherImpl_RaiseEvent_EventSOTypeResponse_ExpectEventRaised) {
+ CheckRaiseEvent(event_id3, 1u, smart_object_with_type_response);
+}
+
+TEST_F(
+ EventEngineTest,
+ EventDispatcherImpl_RaiseEvent_EventSOTypeErrorResponse_ExpectEventRaised) {
+ CheckRaiseEvent(event_id3, 1u, smart_object_with_type_error_response);
+}
+
+TEST_F(EventEngineTest,
+ EventDispatcherImpl_RaiseEvent_EventSOTypeInvalid_ExpectEventNotRaised) {
+ CheckRaiseEvent(event_id3, 0u, smart_object_with_invalid_type);
+}
+
+TEST_F(EventEngineTest,
+ EventDispatcherImpl_RaiseEvent_EventSOTypeRequest_ExpectEventNotRaised) {
+ CheckRaiseEvent(event_id3, 0u, smart_object_with_type_request);
+}
+
+TEST_F(
+ EventEngineTest,
+ EventDispatcherImpl_RaiseEvent_EventSOTypeNotification_ExpectEventNotRaised) {
+ CheckRaiseEvent(event_id3, 0u, smart_object_with_type_notification);
+}
+
+TEST_F(EventEngineTest, Event_set_smart_object_ExpectObjectSet) {
+ // Act
+ event_->set_smart_object(smart_object_with_type_notification);
+ const int32_t obj_type =
+ static_cast<int32_t>(hmi_apis::messageType::notification);
+ const int32_t function_id =
+ static_cast<int32_t>(hmi_apis::FunctionID::eType::VR_IsReady);
+ // Checks
+ EXPECT_EQ(obj_type, event_->smart_object_type());
+ EXPECT_EQ(function_id, event_->smart_object_function_id());
+ EXPECT_EQ(correlation_id, event_->smart_object_correlation_id());
+ EXPECT_EQ(smart_object_with_type_notification, event_->smart_object());
+}
+
+} // namespace event_engine
+} // namespace components
+} // namespace test
diff --git a/src/components/application_manager/test/hmi_capabilities.json b/src/components/application_manager/test/hmi_capabilities.json
new file mode 100644
index 0000000000..c174dfcba4
--- /dev/null
+++ b/src/components/application_manager/test/hmi_capabilities.json
@@ -0,0 +1,466 @@
+{
+ "UI":
+ {
+ "language":"EN_US",
+ "languages":[
+ "EN_US","ES_MX","FR_CA","DE_DE","ES_ES","EN_GB","RU_RU","TR_TR","PL_PL","FR_FR","IT_IT","SV_SE","PT_PT","NL_NL","ZH_TW",
+"JA_JP","AR_SA","KO_KR","PT_BR","CS_CZ","DA_DK","NO_NO"
+ ],
+ "displayCapabilities":
+ {
+ "displayType":"GEN2_8_DMA",
+ "textFields": [{
+ "name": "mainField1",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "mainField2",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "mainField3",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "mainField4",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "statusBar",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "mediaClock",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "mediaTrack",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "alertText1",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "alertText2",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "alertText3",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "scrollableMessageBody",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "initialInteractionText",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "navigationText1",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "navigationText2",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "ETA",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "totalDistance",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "navigationText",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "audioPassThruDisplayText1",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "audioPassThruDisplayText2",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "sliderHeader",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "sliderFooter",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "notificationText",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "menuName",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "secondaryText",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "tertiaryText",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "timeToDestination",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "turnText",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ },
+ {
+ "name": "menuTitle",
+ "characterSet": "TYPE2SET",
+ "width": 500,
+ "rows": 1
+ }
+ ],
+ "imageFields":
+ [
+ {
+ "name":"softButtonImage",
+ "imageTypeSupported":
+ [
+ ],
+ "imageResolution":
+ {
+ "resolutionWidth":35,
+ "resolutionHeight":35
+ }
+ },
+ {
+ "name":"choiceImage",
+ "imageTypeSupported":
+ [
+ ],
+ "imageResolution":
+ {
+ "resolutionWidth":35,
+ "resolutionHeight":35
+ }
+ },
+ {
+ "name":"choiceSecondaryImage",
+ "imageTypeSupported":
+ [
+ ],
+ "imageResolution":
+ {
+ "resolutionWidth":35,
+ "resolutionHeight":35
+ }
+ },
+ {
+ "name":"menuIcon",
+ "imageTypeSupported":
+ [
+ ],
+ "imageResolution":
+ {
+ "resolutionWidth":35,
+ "resolutionHeight":35
+ }
+ },
+ {
+ "name":"cmdIcon",
+ "imageTypeSupported":
+ [
+ ],
+ "imageResolution":
+ {
+ "resolutionWidth":35,
+ "resolutionHeight":35
+ }
+ },
+ {
+ "name":"appIcon",
+ "imageTypeSupported":
+ [
+ ],
+ "imageResolution":
+ {
+ "resolutionWidth":35,
+ "resolutionHeight":35
+ }
+ },
+ {
+ "name":"graphic",
+ "imageTypeSupported":
+ [
+
+ ],
+ "imageResolution":
+ {
+ "resolutionWidth":35,
+ "resolutionHeight":35
+ }
+ },
+ {
+ "name":"locationImage",
+ "imageTypeSupported":
+ [
+ "GRAPHIC_PNG"
+ ],
+ "imageResolution":
+ {
+ "resolutionWidth":35,
+ "resolutionHeight":35
+ }
+ }
+
+ ],
+ "mediaClockFormats":
+ [
+ "CLOCK1","CLOCK2","CLOCK3","CLOCKTEXT1","CLOCKTEXT2","CLOCKTEXT3","CLOCKTEXT4"
+ ],
+ "graphicSupported":true,
+ "templatesAvailable":
+ [
+
+ "DEFAULT","MEDIA","NON-MEDIA","ONSCREEN_PRESETS","NAV_FULLSCREEN_MAP","NAV_KEYBOARD",
+ "GRAPHIC_WITH_TEXT","TEXT_WITH_GRAPHIC","TILES_ONLY","TEXTBUTTONS_ONLY",
+ "GRAPHIC_WITH_TILES","TILES_WITH_GRAPHIC","GRAPHIC_WITH_TEXT_AND_SOFTBUTTONS",
+ "TEXT_AND_SOFTBUTTONS_WITH_GRAPHIC","GRAPHIC_WITH_TEXTBUTTONS",
+ "TEXTBUTTONS_WITH_GRAPHIC","LARGE_GRAPHIC_WITH_SOFTBUTTONS",
+ "DOUBLE_GRAPHIC_WITH_SOFTBUTTONS","LARGE_GRAPHIC_ONLY"
+ ],
+ "screenParams":
+ {
+ "resolution":
+ {
+ "resolutionWidth":800,
+ "resolutionHeight":350
+ },
+ "touchEventAvailable":
+ {
+ "pressAvailable":true,
+ "multiTouchAvailable":false,
+ "doublePressAvailable":false
+ }
+ },
+ "numCustomPresetsAvailable":8,
+ "imageCapabilities":
+ [
+ "DYNAMIC",
+ "STATIC"
+ ]
+ },
+ "audioPassThruCapabilities":
+ {
+ "samplingRate" : "44KHZ",
+ "bitsPerSample" : "RATE_8_BIT",
+ "audioType" : "PCM"
+ },
+ "pcmStreamCapabilities":
+ {
+ "samplingRate" : "16KHZ",
+ "bitsPerSample" : "RATE_16_BIT",
+ "audioType" : "PCM"
+ },
+ "hmiZoneCapabilities":"FRONT",
+ "softButtonCapabilities":
+ [
+ {
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true,
+ "imageSupported" :true
+ }
+ ]
+ },
+ "VR":
+ {
+ "capabilities":["TEXT"],
+ "language":"ES_MX",
+ "languages":
+ [
+ "AR_SA", "EN_US","ES_MX","FR_CA","DE_DE","ES_ES","EN_GB","RU_RU","TR_TR","PL_PL","FR_FR","IT_IT","SV_SE","PT_PT","NL_NL","ZH_TW",
+"JA_JP","KO_KR","PT_BR","CS_CZ","DA_DK","NO_NO"
+ ]
+},
+ "TTS":
+ {
+ "capabilities":"TEXT",
+ "language":"DE_DE",
+ "languages":
+ [
+ "DA_DK","CS_CZ","KO_KR","EN_US","ES_MX","FR_CA","DE_DE","ES_ES","EN_GB","RU_RU","TR_TR","PL_PL","FR_FR","IT_IT","SV_SE","PT_PT","NL_NL","ZH_TW",
+"JA_JP","AR_SA","PT_BR","NO_NO"
+ ]
+ },
+ "Buttons":
+ {
+ "capabilities":
+ [
+ {
+ "name":"PRESET_0",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ },
+ {
+ "name":"PRESET_1",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ },
+ {
+ "name":"PRESET_2",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ },
+ {
+ "name":"PRESET_3",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ },
+ {
+ "name":"PRESET_4",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ },
+ {
+ "name":"PRESET_5",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ },
+ {
+ "name":"PRESET_6",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ },
+ {
+ "name":"PRESET_7",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ },
+ {
+ "name":"PRESET_8",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ },
+ {
+ "name":"PRESET_9",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ },
+ {
+ "name":"OK",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ },
+ {
+ "name":"SEEKLEFT",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ },
+ {
+ "name":"SEEKRIGHT",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ },
+ {
+ "name":"TUNEUP",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ },
+ {
+ "name":"TUNEDOWN",
+ "shortPressAvailable":true,
+ "longPressAvailable" :true,
+ "upDownAvailable" :true
+ }
+ ],
+ "presetBankCapabilities":
+ {
+ "onScreenPresetsAvailable":true
+ }
+ },
+ "VehicleInfo":
+ {
+ "make" :"Ford",
+ "model" :"Fiesta",
+ "modelYear" :"2013",
+ "trim" :"SE"
+ },
+ "SyncMessageVersion":
+ {
+ "majorVersion": 3,
+ "minorVersion": 0
+ }
+}
diff --git a/src/components/application_manager/test/hmi_capabilities_test.cc b/src/components/application_manager/test/hmi_capabilities_test.cc
new file mode 100644
index 0000000000..1ed2123eba
--- /dev/null
+++ b/src/components/application_manager/test/hmi_capabilities_test.cc
@@ -0,0 +1,527 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/hmi_capabilities.h"
+#include "gtest/gtest.h"
+#include "smart_objects/smart_object.h"
+#include "application_manager/mock_message_helper.h"
+#include "smart_objects/enum_schema_item.h"
+#include "interfaces/HMI_API.h"
+#include "utils/make_shared.h"
+#include "application_manager/hmi_capabilities_for_testing.h"
+#include "utils/file_system.h"
+#include "application_manager/mock_application_manager.h"
+#include "application_manager/mock_application_manager_settings.h"
+#include "application_manager/mock_event_dispatcher.h"
+#include "application_manager/state_controller.h"
+#include "resumption/last_state.h"
+#include "application_manager/resumption/resume_ctrl.h"
+
+namespace test {
+namespace components {
+namespace application_manager_test {
+
+using ::testing::_;
+using ::testing::Return;
+using ::testing::ReturnRef;
+using ::testing::AtLeast;
+using ::testing::Invoke;
+using ::testing::InSequence;
+
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+using namespace application_manager;
+
+class HMICapabilitiesTest : public ::testing::Test {
+ protected:
+ HMICapabilitiesTest() : last_state_("app_storage_folder", "app_info_data") {}
+ virtual void SetUp() OVERRIDE {
+ EXPECT_CALL(app_mngr_, event_dispatcher())
+ .WillOnce(ReturnRef(mock_event_dispatcher));
+ EXPECT_CALL(app_mngr_, get_settings())
+ .WillRepeatedly(ReturnRef(mock_application_manager_settings_));
+ EXPECT_CALL(mock_application_manager_settings_,
+ hmi_capabilities_file_name()).WillOnce(ReturnRef(kFileName));
+ EXPECT_CALL(mock_event_dispatcher, add_observer(_, _, _)).Times(1);
+ EXPECT_CALL(mock_event_dispatcher, remove_observer(_)).Times(1);
+ EXPECT_CALL(mock_application_manager_settings_, launch_hmi())
+ .WillOnce(Return(false));
+ hmi_capabilities_test =
+ utils::MakeShared<HMICapabilitiesForTesting>(app_mngr_);
+ hmi_capabilities_test->Init(&last_state_);
+ }
+
+ void TearDown() OVERRIDE {
+ hmi_capabilities_test.reset();
+ }
+ static void TearDownTestCase() {
+ if (file_system::FileExists("./app_info_data")) {
+ EXPECT_TRUE(::file_system::DeleteFile("./app_info_data"));
+ }
+ }
+
+ void SetCooperating();
+ MockApplicationManager app_mngr_;
+ event_engine_test::MockEventDispatcher mock_event_dispatcher;
+ resumption::LastState last_state_;
+ MockApplicationManagerSettings mock_application_manager_settings_;
+ utils::SharedPtr<HMICapabilitiesForTesting> hmi_capabilities_test;
+ const std::string kFileName = "hmi_capabilities.json";
+};
+
+const char* const cstring_values_[] = {
+ "EN_US", "ES_MX", "FR_CA", "DE_DE", "ES_ES", "EN_GB", "RU_RU", "TR_TR",
+ "PL_PL", "FR_FR", "IT_IT", "SV_SE", "PT_PT", "NL_NL", "EN_AU", "ZH_CN",
+ "ZH_TW", "JA_JP", "AR_SA", "KO_KR", "PT_BR", "CS_CZ", "DA_DK", "NO_NO",
+ "NL_BE", "EL_GR", "HU_HU", "FI_FI", "SK_SK"};
+
+const hmi_apis::Common_Language::eType enum_values_[] = {
+ hmi_apis::Common_Language::EN_US, hmi_apis::Common_Language::ES_MX,
+ hmi_apis::Common_Language::FR_CA, hmi_apis::Common_Language::DE_DE,
+ hmi_apis::Common_Language::ES_ES, hmi_apis::Common_Language::EN_GB,
+ hmi_apis::Common_Language::RU_RU, hmi_apis::Common_Language::TR_TR,
+ hmi_apis::Common_Language::PL_PL, hmi_apis::Common_Language::FR_FR,
+ hmi_apis::Common_Language::IT_IT, hmi_apis::Common_Language::SV_SE,
+ hmi_apis::Common_Language::PT_PT, hmi_apis::Common_Language::NL_NL,
+ hmi_apis::Common_Language::EN_AU, hmi_apis::Common_Language::ZH_CN,
+ hmi_apis::Common_Language::ZH_TW, hmi_apis::Common_Language::JA_JP,
+ hmi_apis::Common_Language::AR_SA, hmi_apis::Common_Language::KO_KR,
+ hmi_apis::Common_Language::PT_BR, hmi_apis::Common_Language::CS_CZ,
+ hmi_apis::Common_Language::DA_DK, hmi_apis::Common_Language::NO_NO,
+ hmi_apis::Common_Language::NL_BE, hmi_apis::Common_Language::EL_GR,
+ hmi_apis::Common_Language::HU_HU, hmi_apis::Common_Language::FI_FI,
+ hmi_apis::Common_Language::SK_SK};
+
+struct CStringComparator {
+ bool operator()(const char* a, const char* b) {
+ return strcmp(a, b) < 0;
+ }
+};
+
+typedef std::map<const char*,
+ hmi_apis::Common_Language::eType,
+ CStringComparator> CStringToEnumMap;
+
+CStringToEnumMap InitCStringToEnumMap() {
+ size_t value = sizeof(cstring_values_) / sizeof(cstring_values_[0]);
+ CStringToEnumMap result;
+ for (size_t i = 0; i < value; ++i) {
+ result[cstring_values_[i]] = enum_values_[i];
+ }
+ return result;
+}
+
+bool StringToEnum(const char* str, hmi_apis::Common_Language::eType& value) {
+ size_t count_value = sizeof(cstring_values_) / sizeof(cstring_values_[0]);
+ CStringToEnumMap result;
+ for (size_t i = 0; i < count_value; ++i) {
+ result[cstring_values_[i]] = enum_values_[i];
+ }
+
+ CStringToEnumMap::const_iterator it = result.find(str);
+ if (it == result.end()) {
+ return false;
+ }
+ value = it->second;
+ return true;
+}
+
+hmi_apis::Common_Language::eType TestCommonLanguageFromString(
+ const std::string& language) {
+ hmi_apis::Common_Language::eType value;
+ if (StringToEnum(language.c_str(), value)) {
+ return value;
+ }
+ return hmi_apis::Common_Language::INVALID_ENUM;
+}
+
+TEST_F(HMICapabilitiesTest, LoadCapabilitiesFromFile) {
+ const std::string hmi_capabilities_file = "hmi_capabilities.json";
+ EXPECT_CALL(mock_application_manager_settings_, hmi_capabilities_file_name())
+ .WillOnce(ReturnRef(hmi_capabilities_file));
+ EXPECT_CALL(*(MockMessageHelper::message_helper_mock()),
+ CommonLanguageFromString(_))
+ .WillRepeatedly(Invoke(TestCommonLanguageFromString));
+
+ if (file_system::FileExists("./app_info_data")) {
+ EXPECT_TRUE(::file_system::DeleteFile("./app_info_data"));
+ }
+ EXPECT_TRUE(hmi_capabilities_test->LoadCapabilitiesFromFile());
+
+ // Check active languages
+ EXPECT_EQ(hmi_apis::Common_Language::EN_US,
+ hmi_capabilities_test->active_ui_language());
+ EXPECT_EQ(hmi_apis::Common_Language::ES_MX,
+ hmi_capabilities_test->active_vr_language());
+ EXPECT_EQ(hmi_apis::Common_Language::DE_DE,
+ hmi_capabilities_test->active_tts_language());
+
+ // Check UI languages
+ const smart_objects::SmartObject ui_supported_languages =
+ *(hmi_capabilities_test->ui_supported_languages());
+
+ EXPECT_EQ(hmi_apis::Common_Language::EN_US,
+ static_cast<hmi_apis::Common_Language::eType>(
+ ui_supported_languages[0].asInt()));
+ EXPECT_EQ(hmi_apis::Common_Language::ES_MX,
+ static_cast<hmi_apis::Common_Language::eType>(
+ ui_supported_languages[1].asInt()));
+ EXPECT_EQ(hmi_apis::Common_Language::FR_CA,
+ static_cast<hmi_apis::Common_Language::eType>(
+ ui_supported_languages[2].asInt()));
+
+ // Check VR languages
+ const smart_objects::SmartObject vr_supported_languages =
+ *(hmi_capabilities_test->vr_supported_languages());
+
+ EXPECT_EQ(hmi_apis::Common_Language::AR_SA,
+ static_cast<hmi_apis::Common_Language::eType>(
+ vr_supported_languages[0].asInt()));
+ EXPECT_EQ(hmi_apis::Common_Language::EN_US,
+ static_cast<hmi_apis::Common_Language::eType>(
+ vr_supported_languages[1].asInt()));
+ EXPECT_EQ(hmi_apis::Common_Language::ES_MX,
+ static_cast<hmi_apis::Common_Language::eType>(
+ vr_supported_languages[2].asInt()));
+
+ // Check TTS languages
+ const smart_objects::SmartObject tts_supported_languages =
+ *(hmi_capabilities_test->tts_supported_languages());
+
+ EXPECT_EQ(hmi_apis::Common_Language::DA_DK,
+ static_cast<hmi_apis::Common_Language::eType>(
+ tts_supported_languages[0].asInt()));
+ EXPECT_EQ(hmi_apis::Common_Language::CS_CZ,
+ static_cast<hmi_apis::Common_Language::eType>(
+ tts_supported_languages[1].asInt()));
+ EXPECT_EQ(hmi_apis::Common_Language::KO_KR,
+ static_cast<hmi_apis::Common_Language::eType>(
+ tts_supported_languages[2].asInt()));
+
+ // Check button capabilities
+ const smart_objects::SmartObject buttons_capabilities_so =
+ *(hmi_capabilities_test->button_capabilities());
+
+ // Count of buttons in json file
+ const uint32_t btn_length = buttons_capabilities_so.length();
+ EXPECT_EQ(15u, btn_length);
+ for (uint32_t i = 0; i < btn_length; ++i) {
+ EXPECT_TRUE((buttons_capabilities_so[i]).keyExists(strings::name));
+ EXPECT_TRUE((buttons_capabilities_so[i]).keyExists("shortPressAvailable"));
+ EXPECT_TRUE((buttons_capabilities_so[i]).keyExists("longPressAvailable"));
+ EXPECT_TRUE((buttons_capabilities_so[i]).keyExists("upDownAvailable"));
+ EXPECT_TRUE(buttons_capabilities_so[i]["shortPressAvailable"].asBool());
+ EXPECT_TRUE(buttons_capabilities_so[i]["longPressAvailable"].asBool());
+ EXPECT_TRUE(buttons_capabilities_so[i]["upDownAvailable"].asBool());
+ }
+ const smart_objects::SmartObject display_capabilities_so =
+ *(hmi_capabilities_test->display_capabilities());
+
+ // Check display type
+ EXPECT_EQ(hmi_apis::Common_DisplayType::GEN2_8_DMA,
+ static_cast<hmi_apis::Common_DisplayType::eType>(
+ display_capabilities_so[hmi_response::display_type].asInt()));
+
+ EXPECT_TRUE(display_capabilities_so["graphicSupported"].asBool());
+
+ // Check text fields
+ const uint32_t text_len =
+ display_capabilities_so[hmi_response::text_fields].length();
+ EXPECT_NE(0u, text_len);
+ for (uint32_t i = 0; i < text_len; ++i) {
+ EXPECT_TRUE((display_capabilities_so[hmi_response::text_fields][i])
+ .keyExists(strings::name));
+ EXPECT_TRUE((display_capabilities_so[hmi_response::text_fields][i])
+ .keyExists(strings::character_set));
+ }
+
+ // Check image fields
+ EXPECT_TRUE((display_capabilities_so).keyExists(hmi_response::image_fields));
+ const uint32_t img_len =
+ display_capabilities_so[hmi_response::image_fields].length();
+ EXPECT_NE(0u, img_len);
+ for (uint32_t i = 0; i < img_len; ++i) {
+ EXPECT_TRUE((display_capabilities_so[hmi_response::image_fields][i])
+ .keyExists(strings::name));
+ EXPECT_TRUE((display_capabilities_so[hmi_response::image_fields][i])
+ .keyExists(strings::image_type_supported));
+ if (display_capabilities_so[hmi_response::image_fields][i][strings::name] ==
+ hmi_apis::Common_ImageFieldName::locationImage) {
+ EXPECT_EQ(hmi_apis::Common_FileType::GRAPHIC_PNG,
+ static_cast<hmi_apis::Common_FileType::eType>(
+ display_capabilities_so[hmi_response::image_fields][i]
+ [strings::image_type_supported][0]
+ .asInt()));
+ }
+ }
+
+ // Check media clock formats
+ EXPECT_TRUE(
+ (display_capabilities_so).keyExists(hmi_response::media_clock_formats));
+ const uint32_t media_length =
+ display_capabilities_so[hmi_response::media_clock_formats].length();
+ EXPECT_NE(0u, media_length);
+ for (uint32_t i = 0; i < media_length; ++i) {
+ EXPECT_EQ(
+ i,
+ display_capabilities_so[hmi_response::media_clock_formats][i].asUInt());
+ }
+
+ EXPECT_TRUE(
+ (display_capabilities_so).keyExists(hmi_response::image_capabilities));
+ EXPECT_EQ(hmi_apis::Common_ImageType::DYNAMIC,
+ static_cast<hmi_apis::Common_ImageType::eType>(
+ display_capabilities_so[hmi_response::image_capabilities][0]
+ .asInt()));
+ EXPECT_EQ(hmi_apis::Common_ImageType::STATIC,
+ static_cast<hmi_apis::Common_ImageType::eType>(
+ display_capabilities_so[hmi_response::image_capabilities][1]
+ .asInt()));
+
+ // Check audio pass thru
+ const smart_objects::SmartObject audio_pass_thru_capabilities_so =
+ *(hmi_capabilities_test->audio_pass_thru_capabilities());
+ EXPECT_EQ(hmi_apis::Common_SamplingRate::RATE_44KHZ,
+ static_cast<hmi_apis::Common_SamplingRate::eType>(
+ audio_pass_thru_capabilities_so["samplingRate"].asInt()));
+ EXPECT_EQ(hmi_apis::Common_BitsPerSample::RATE_8_BIT,
+ static_cast<hmi_apis::Common_BitsPerSample::eType>(
+ audio_pass_thru_capabilities_so["bitsPerSample"].asInt()));
+ EXPECT_EQ(hmi_apis::Common_AudioType::PCM,
+ static_cast<hmi_apis::Common_AudioType::eType>(
+ audio_pass_thru_capabilities_so["audioType"].asInt()));
+
+ // Check hmi zone capabilities
+ const smart_objects::SmartObject hmi_zone_capabilities_so =
+ *(hmi_capabilities_test->hmi_zone_capabilities());
+ EXPECT_EQ(hmi_apis::Common_HmiZoneCapabilities::FRONT,
+ static_cast<hmi_apis::Common_HmiZoneCapabilities::eType>(
+ hmi_zone_capabilities_so.asInt()));
+
+ const smart_objects::SmartObject soft_button_capabilities_so =
+ *(hmi_capabilities_test->soft_button_capabilities());
+
+ EXPECT_TRUE(soft_button_capabilities_so[0]["shortPressAvailable"].asBool());
+ EXPECT_TRUE(soft_button_capabilities_so[0]["longPressAvailable"].asBool());
+ EXPECT_TRUE(soft_button_capabilities_so[0]["upDownAvailable"].asBool());
+ EXPECT_TRUE(soft_button_capabilities_so[0]["imageSupported"].asBool());
+
+ const smart_objects::SmartObject preset_bank_so =
+ *(hmi_capabilities_test->preset_bank_capabilities());
+ EXPECT_TRUE(preset_bank_so["onScreenPresetsAvailable"].asBool());
+
+ // Check vehicle type
+ const smart_objects::SmartObject vehicle_type_so =
+ *(hmi_capabilities_test->vehicle_type());
+ EXPECT_TRUE(preset_bank_so["onScreenPresetsAvailable"].asBool());
+
+ EXPECT_EQ("Ford", vehicle_type_so["make"].asString());
+ EXPECT_EQ("Fiesta", vehicle_type_so["model"].asString());
+ EXPECT_EQ("2013", vehicle_type_so["modelYear"].asString());
+ EXPECT_EQ("SE", vehicle_type_so["trim"].asString());
+}
+
+TEST_F(HMICapabilitiesTest, ConvertJsonLanguagesToObj) {
+ Json::Value json_languages(Json::arrayValue);
+ json_languages[0] = "EN_US";
+ json_languages[1] = "ES_MX";
+ smart_objects::SmartObject sm_obj =
+ smart_objects::SmartObject(smart_objects::SmartType_Array);
+
+ EXPECT_CALL(*(MockMessageHelper::message_helper_mock()),
+ CommonLanguageFromString(json_languages[0].asString()))
+ .WillOnce(Return(hmi_apis::Common_Language::EN_US));
+
+ EXPECT_CALL(*(MockMessageHelper::message_helper_mock()),
+ CommonLanguageFromString(json_languages[1].asString()))
+ .WillOnce(Return(hmi_apis::Common_Language::ES_MX));
+
+ hmi_capabilities_test->ConvertJsonLanguagesToObj(json_languages, sm_obj);
+
+ EXPECT_EQ(hmi_apis::Common_Language::EN_US,
+ static_cast<hmi_apis::Common_Language::eType>(sm_obj[0].asInt()));
+ EXPECT_EQ(hmi_apis::Common_Language::ES_MX,
+ static_cast<hmi_apis::Common_Language::eType>(sm_obj[1].asInt()));
+}
+
+TEST_F(HMICapabilitiesTest,
+ HmiCapabilitiesInitialized_UiVrTtsIviNotCooperating) {
+ // Precondition
+ hmi_capabilities_test->set_is_vr_cooperating(false);
+ hmi_capabilities_test->set_is_tts_cooperating(false);
+
+ hmi_capabilities_test->set_is_ui_cooperating(false);
+ hmi_capabilities_test->set_is_navi_cooperating(false);
+ hmi_capabilities_test->set_is_ivi_cooperating(false);
+ EXPECT_TRUE(hmi_capabilities_test->is_hmi_capabilities_initialized());
+}
+
+TEST_F(HMICapabilitiesTest, HmiCapabilitiesInitialized) {
+ // Precondition
+ SetCooperating();
+ smart_objects::SmartObjectSPtr language(
+ new smart_objects::SmartObject(smart_objects::SmartType_Map));
+
+ EXPECT_CALL(*(MockMessageHelper::message_helper_mock()),
+ CreateModuleInfoSO(_, _)).WillRepeatedly(Return(language));
+
+ hmi_capabilities_test->set_is_vr_cooperating(true);
+ smart_objects::SmartObject supported_languages;
+ supported_languages[0] = "EN_US";
+ hmi_capabilities_test->set_vr_supported_languages(supported_languages);
+ hmi_capabilities_test->set_tts_supported_languages(supported_languages);
+ hmi_capabilities_test->set_ui_supported_languages(supported_languages);
+ hmi_capabilities_test->set_vehicle_type(supported_languages);
+
+ hmi_capabilities_test->set_is_tts_cooperating(true);
+ hmi_capabilities_test->set_is_ui_cooperating(true);
+ hmi_capabilities_test->set_is_navi_cooperating(true);
+ hmi_capabilities_test->set_is_ivi_cooperating(true);
+
+ hmi_capabilities_test->set_active_vr_language(
+ hmi_apis::Common_Language::EN_US);
+ SetCooperating();
+ hmi_capabilities_test->set_active_tts_language(
+ hmi_apis::Common_Language::EN_US);
+ SetCooperating();
+ hmi_capabilities_test->set_active_ui_language(
+ hmi_apis::Common_Language::EN_US);
+
+ EXPECT_TRUE(hmi_capabilities_test->is_hmi_capabilities_initialized());
+}
+
+TEST_F(HMICapabilitiesTest, VerifyImageType) {
+ const int32_t image_type = 1;
+ smart_objects::SmartObject sm_obj;
+ sm_obj[hmi_response::image_capabilities][0] = image_type;
+ hmi_capabilities_test->set_display_capabilities(sm_obj);
+
+ EXPECT_TRUE(hmi_capabilities_test->VerifyImageType(image_type));
+
+ const int32_t new_image_type = 2;
+ EXPECT_FALSE(hmi_capabilities_test->VerifyImageType(new_image_type));
+}
+
+void HMICapabilitiesTest::SetCooperating() {
+ smart_objects::SmartObjectSPtr test_so;
+ EXPECT_CALL(*(MockMessageHelper::message_helper_mock()),
+ CreateModuleInfoSO(_, _)).WillRepeatedly(Return(test_so));
+ EXPECT_CALL(app_mngr_, ManageHMICommand(_)).WillRepeatedly(Return(true));
+}
+
+TEST_F(HMICapabilitiesTest, SetVRCooperating) {
+ // Without sequence it is impossible to check correct call of ManageHMICommand
+ InSequence dummy;
+ smart_objects::SmartObjectSPtr language(
+ new smart_objects::SmartObject(smart_objects::SmartType_Map));
+ EXPECT_CALL(*(MockMessageHelper::message_helper_mock()),
+ CreateModuleInfoSO(hmi_apis::FunctionID::VR_GetLanguage, _))
+ .WillOnce(Return(language));
+ EXPECT_CALL(app_mngr_, ManageHMICommand(language));
+
+ smart_objects::SmartObjectSPtr support_language;
+ EXPECT_CALL(*(MockMessageHelper::message_helper_mock()),
+ CreateModuleInfoSO(hmi_apis::FunctionID::VR_GetSupportedLanguages,
+ _)).WillOnce(Return(support_language));
+ EXPECT_CALL(app_mngr_, ManageHMICommand(support_language));
+
+ smart_objects::SmartObjectSPtr capabilities;
+ EXPECT_CALL(*(MockMessageHelper::message_helper_mock()),
+ CreateModuleInfoSO(hmi_apis::FunctionID::VR_GetCapabilities, _))
+ .WillOnce(Return(capabilities));
+ EXPECT_CALL(app_mngr_, ManageHMICommand(capabilities));
+
+ hmi_capabilities_test->set_is_vr_cooperating(true);
+}
+
+TEST_F(HMICapabilitiesTest, SetTTSCooperating) {
+ smart_objects::SmartObjectSPtr language(
+ new smart_objects::SmartObject(smart_objects::SmartType_Map));
+ InSequence dummy;
+ EXPECT_CALL(*(MockMessageHelper::message_helper_mock()),
+ CreateModuleInfoSO(hmi_apis::FunctionID::TTS_GetLanguage, _))
+ .WillOnce(Return(language));
+ EXPECT_CALL(app_mngr_, ManageHMICommand(language));
+
+ smart_objects::SmartObjectSPtr support_language;
+ EXPECT_CALL(
+ *(MockMessageHelper::message_helper_mock()),
+ CreateModuleInfoSO(hmi_apis::FunctionID::TTS_GetSupportedLanguages, _))
+ .WillOnce(Return(support_language));
+ EXPECT_CALL(app_mngr_, ManageHMICommand(support_language));
+
+ smart_objects::SmartObjectSPtr capabilities;
+ EXPECT_CALL(*(MockMessageHelper::message_helper_mock()),
+ CreateModuleInfoSO(hmi_apis::FunctionID::TTS_GetCapabilities, _))
+ .WillOnce(Return(capabilities));
+ EXPECT_CALL(app_mngr_, ManageHMICommand(capabilities));
+
+ hmi_capabilities_test->set_is_tts_cooperating(true);
+}
+
+TEST_F(HMICapabilitiesTest, SetUICooperating) {
+ InSequence dummy;
+ smart_objects::SmartObjectSPtr language(
+ new smart_objects::SmartObject(smart_objects::SmartType_Map));
+ EXPECT_CALL(*(MockMessageHelper::message_helper_mock()),
+ CreateModuleInfoSO(hmi_apis::FunctionID::UI_GetLanguage, _))
+ .WillOnce(Return(language));
+ EXPECT_CALL(app_mngr_, ManageHMICommand(language));
+
+ smart_objects::SmartObjectSPtr support_language;
+ EXPECT_CALL(*(MockMessageHelper::message_helper_mock()),
+ CreateModuleInfoSO(hmi_apis::FunctionID::UI_GetSupportedLanguages,
+ _)).WillOnce(Return(support_language));
+ EXPECT_CALL(app_mngr_, ManageHMICommand(support_language));
+
+ smart_objects::SmartObjectSPtr capabilities;
+ EXPECT_CALL(*(MockMessageHelper::message_helper_mock()),
+ CreateModuleInfoSO(hmi_apis::FunctionID::UI_GetCapabilities, _))
+ .WillOnce(Return(capabilities));
+ EXPECT_CALL(app_mngr_, ManageHMICommand(capabilities));
+
+ hmi_capabilities_test->set_is_ui_cooperating(true);
+}
+
+TEST_F(HMICapabilitiesTest, SetIviCooperating) {
+ smart_objects::SmartObjectSPtr ivi_type;
+ EXPECT_CALL(
+ *(MockMessageHelper::message_helper_mock()),
+ CreateModuleInfoSO(hmi_apis::FunctionID::VehicleInfo_GetVehicleType, _))
+ .WillOnce(Return(ivi_type));
+ EXPECT_CALL(app_mngr_, ManageHMICommand(ivi_type));
+
+ hmi_capabilities_test->set_is_ivi_cooperating(true);
+}
+
+} // namespace application_manager_test
+} // namespace components
+} // namespace test
diff --git a/src/components/application_manager/test/include/application_manager/application_manager_mock.h b/src/components/application_manager/test/include/application_manager/application_manager_mock.h
new file mode 100644
index 0000000000..35f5f4dbdb
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/application_manager_mock.h
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MANAGER_MOCK_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MANAGER_MOCK_H_
+#include <string>
+#include <vector>
+#include "gmock/gmock.h"
+#include "application_manager/application_manager.h"
+#include "application_manager/usage_statistics.h"
+#include "application_manager/commands/command.h"
+#include "media_manager/media_manager.h"
+#include "resumption/last_state.h"
+#include "application_manager/policies/policy_handler.h"
+namespace test {
+namespace components {
+namespace state_controller_test {
+namespace am = application_manager;
+
+class ApplicationManagerMock : public application_manager::ApplicationManager {
+ public:
+ MOCK_METHOD1(Init, bool(resumption::LastState& last_state));
+ MOCK_METHOD0(Stop, bool());
+
+ MOCK_METHOD1(set_hmi_message_handler,
+ void(hmi_message_handler::HMIMessageHandler*));
+ MOCK_METHOD1(set_protocol_handler, void(protocol_handler::ProtocolHandler*));
+ MOCK_METHOD1(set_connection_handler,
+ void(connection_handler::ConnectionHandler*));
+ MOCK_CONST_METHOD0(applications, DataAccessor<am::ApplicationSet>());
+ MOCK_CONST_METHOD1(application, am::ApplicationSharedPtr(uint32_t app_id));
+ MOCK_CONST_METHOD1(application_by_hmi_app,
+ am::ApplicationSharedPtr(uint32_t));
+ MOCK_CONST_METHOD0(active_application, am::ApplicationSharedPtr());
+ MOCK_CONST_METHOD1(application_by_policy_id,
+ am::ApplicationSharedPtr(const std::string&));
+ MOCK_METHOD1(applications_by_button,
+ std::vector<am::ApplicationSharedPtr>(uint32_t));
+ MOCK_METHOD0(applications_with_navi, std::vector<am::ApplicationSharedPtr>());
+ MOCK_CONST_METHOD0(get_limited_media_application, am::ApplicationSharedPtr());
+ MOCK_CONST_METHOD0(get_limited_navi_application, am::ApplicationSharedPtr());
+ MOCK_CONST_METHOD0(get_limited_voice_application, am::ApplicationSharedPtr());
+ MOCK_METHOD1(application_id, const uint32_t(const int32_t));
+ MOCK_METHOD2(set_application_id, void(const int32_t, const uint32_t));
+ MOCK_METHOD3(OnHMILevelChanged,
+ void(uint32_t,
+ mobile_apis::HMILevel::eType,
+ mobile_apis::HMILevel::eType));
+ MOCK_METHOD1(SendHMIStatusNotification, void(const am::ApplicationSharedPtr));
+ MOCK_CONST_METHOD1(
+ GetDefaultHmiLevel,
+ mobile_apis::HMILevel::eType(am::ApplicationConstSharedPtr));
+ MOCK_METHOD0(hmi_capabilities, am::HMICapabilities&());
+ MOCK_METHOD0(is_attenuated_supported, bool());
+ MOCK_CONST_METHOD1(IsAppTypeExistsInFullOrLimited,
+ bool(am::ApplicationConstSharedPtr));
+ MOCK_METHOD1(OnApplicationRegistered, void(am::ApplicationSharedPtr));
+ MOCK_METHOD2(SendMessageToMobile,
+ void(const smart_objects::SmartObjectSPtr message,
+ bool final_message));
+ MOCK_METHOD1(SendMessageToMobile,
+ void(const smart_objects::SmartObjectSPtr message));
+ MOCK_METHOD1(SendMessageToHMI,
+ void(const smart_objects::SmartObjectSPtr message));
+ MOCK_METHOD2(ManageMobileCommand,
+ bool(const smart_objects::SmartObjectSPtr message,
+ am::commands::Command::CommandOrigin origin));
+ MOCK_METHOD1(ManageHMICommand,
+ bool(const smart_objects::SmartObjectSPtr message));
+ MOCK_CONST_METHOD2(CanAppStream,
+ bool(uint32_t app_id,
+ protocol_handler::ServiceType service_type));
+ MOCK_METHOD1(ForbidStreaming, void(uint32_t app_id));
+ MOCK_METHOD2(SendAudioPassThroughNotification,
+ void(uint32_t session_key, std::vector<uint8_t>& binary_data));
+ MOCK_CONST_METHOD0(connection_handler,
+ connection_handler::ConnectionHandler&());
+};
+} // namespace state_controller_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MANAGER_MOCK_H_
diff --git a/src/components/application_manager/test/include/application_manager/application_mock.h b/src/components/application_manager/test/include/application_manager/application_mock.h
new file mode 100644
index 0000000000..9896ecfdd4
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/application_mock.h
@@ -0,0 +1,280 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MOCK_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MOCK_H_
+
+#include <string>
+
+#include "gmock/gmock.h"
+#include "application_manager/application.h"
+
+namespace test {
+namespace components {
+namespace state_controller_test {
+
+namespace am = application_manager;
+
+namespace custom_str = utils::custom_string;
+
+class MockApplication : public application_manager::Application {
+ public:
+ // InitialApplicationData
+ MOCK_CONST_METHOD0(app_types, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(vr_synonyms, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(mac_address, const std::string&());
+ MOCK_CONST_METHOD0(mobile_app_id, std::string());
+ MOCK_CONST_METHOD0(tts_name, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(ngn_media_screen_name,
+ const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(language, const mobile_apis::Language::eType&());
+ MOCK_CONST_METHOD0(ui_language, const mobile_apis::Language::eType&());
+ MOCK_METHOD1(set_app_types,
+ void(const smart_objects::SmartObject& app_types));
+ MOCK_METHOD1(set_vr_synonyms,
+ void(const smart_objects::SmartObject& vr_synonyms));
+ MOCK_METHOD1(set_mobile_app_id, void(const std::string& mobile_app_id));
+ MOCK_METHOD1(set_tts_name, void(const smart_objects::SmartObject& tts_name));
+ MOCK_METHOD1(set_ngn_media_screen_name,
+ void(const smart_objects::SmartObject& ngn_name));
+ MOCK_METHOD1(set_language,
+ void(const mobile_apis::Language::eType& language));
+ MOCK_METHOD1(set_ui_language,
+ void(const mobile_apis::Language::eType& ui_language));
+
+ // DynamicApplicationData
+ MOCK_CONST_METHOD0(help_prompt, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(timeout_prompt, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(vr_help_title, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(vr_help, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(tbt_state, const mobile_apis::TBTState::eType&());
+ MOCK_CONST_METHOD0(show_command, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(tbt_show_command, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(SubscribedButtons,
+ DataAccessor<application_manager::ButtonSubscriptions>());
+ MOCK_CONST_METHOD0(
+ SubscribedIVI,
+ DataAccessor<application_manager::VehicleInfoSubscriptions>());
+ MOCK_CONST_METHOD0(keyboard_props, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(menu_title, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(menu_icon, const smart_objects::SmartObject*());
+ MOCK_METHOD1(load_global_properties,
+ void(const smart_objects::SmartObject& so));
+ MOCK_METHOD1(set_help_prompt,
+ void(const smart_objects::SmartObject& help_prompt));
+ MOCK_METHOD1(set_timeout_prompt,
+ void(const smart_objects::SmartObject& timeout_prompt));
+ MOCK_METHOD1(set_vr_help_title,
+ void(const smart_objects::SmartObject& vr_help_title));
+ MOCK_METHOD0(reset_vr_help_title, void());
+ MOCK_METHOD1(set_vr_help, void(const smart_objects::SmartObject& vr_help));
+ MOCK_METHOD0(reset_vr_help, void());
+ MOCK_METHOD1(set_tbt_state,
+ void(const mobile_apis::TBTState::eType& tbt_state));
+ MOCK_METHOD1(set_show_command,
+ void(const smart_objects::SmartObject& show_command));
+ MOCK_METHOD1(set_tbt_show_command,
+ void(const smart_objects::SmartObject& tbt_show));
+ MOCK_METHOD1(set_keyboard_props,
+ void(const smart_objects::SmartObject& keyboard_props));
+ MOCK_METHOD1(set_menu_title,
+ void(const smart_objects::SmartObject& menu_title));
+ MOCK_METHOD1(set_menu_icon,
+ void(const smart_objects::SmartObject& menu_icon));
+ MOCK_CONST_METHOD0(audio_stream_retry_number, uint32_t());
+ MOCK_METHOD1(set_audio_stream_retry_number,
+ void(const uint32_t& audio_stream_retry_number));
+ MOCK_CONST_METHOD0(video_stream_retry_number, uint32_t());
+ MOCK_METHOD1(set_video_stream_retry_number,
+ void(const uint32_t& video_stream_retry_number));
+ MOCK_METHOD2(AddCommand,
+ void(uint32_t cmd_id,
+ const smart_objects::SmartObject& command));
+ MOCK_METHOD1(RemoveCommand, void(uint32_t cmd_id));
+ MOCK_METHOD1(FindCommand, smart_objects::SmartObject*(uint32_t cmd_id));
+ MOCK_METHOD2(AddSubMenu,
+ void(uint32_t menu_id, const smart_objects::SmartObject& menu));
+ MOCK_METHOD1(RemoveSubMenu, void(uint32_t menu_id));
+ MOCK_CONST_METHOD1(FindSubMenu,
+ smart_objects::SmartObject*(uint32_t menu_id));
+ MOCK_METHOD1(IsSubMenuNameAlreadyExist, bool(const std::string& name));
+ MOCK_METHOD2(AddChoiceSet,
+ void(uint32_t choice_set_id,
+ const smart_objects::SmartObject& choice_set));
+ MOCK_METHOD1(RemoveChoiceSet, void(uint32_t choice_set_id));
+ MOCK_METHOD1(FindChoiceSet,
+ smart_objects::SmartObject*(uint32_t choice_set_id));
+ MOCK_METHOD3(AddPerformInteractionChoiceSet,
+ void(uint32_t correlation_id,
+ uint32_t choice_set_id,
+ const smart_objects::SmartObject& choice_set));
+ MOCK_METHOD1(DeletePerformInteractionChoiceSet,
+ void(uint32_t correlation_id));
+ MOCK_CONST_METHOD0(performinteraction_choice_set_map,
+ DataAccessor<application_manager::PerformChoiceSetMap>());
+ MOCK_CONST_METHOD0(commands_map,
+ DataAccessor<application_manager::CommandsMap>());
+ MOCK_CONST_METHOD0(sub_menu_map,
+ DataAccessor<application_manager::SubMenuMap>());
+ MOCK_CONST_METHOD0(choice_set_map,
+ DataAccessor<application_manager::ChoiceSetMap>());
+ MOCK_METHOD1(set_perform_interaction_active, void(uint32_t active));
+ MOCK_CONST_METHOD0(is_perform_interaction_active, uint32_t());
+ MOCK_METHOD1(set_perform_interaction_layout,
+ void(mobile_apis::LayoutMode::eType layout));
+ MOCK_CONST_METHOD0(perform_interaction_layout,
+ mobile_apis::LayoutMode::eType());
+ MOCK_METHOD1(set_perform_interaction_mode, void(int32_t mode));
+ MOCK_CONST_METHOD0(perform_interaction_mode, int32_t());
+ MOCK_METHOD1(set_reset_global_properties_active, void(bool active));
+ MOCK_CONST_METHOD0(is_reset_global_properties_active, bool());
+ // Application
+
+ MOCK_CONST_METHOD0(active_message, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(curHash, const std::string&());
+ MOCK_METHOD0(UpdateHash, void());
+ MOCK_CONST_METHOD0(is_application_data_changed, bool());
+ MOCK_METHOD1(set_is_application_data_changed,
+ void(bool state_application_data));
+ MOCK_METHOD0(CloseActiveMessage, void());
+ MOCK_CONST_METHOD0(IsFullscreen, bool());
+ MOCK_METHOD0(ChangeSupportingAppHMIType, void());
+ MOCK_CONST_METHOD0(is_navi, bool());
+ MOCK_METHOD1(set_is_navi, void(bool allow));
+ MOCK_CONST_METHOD0(video_streaming_approved, bool());
+ MOCK_METHOD1(set_video_streaming_approved, void(bool state));
+ MOCK_CONST_METHOD0(audio_streaming_approved, bool());
+ MOCK_METHOD1(set_audio_streaming_approved, void(bool state));
+ MOCK_CONST_METHOD0(video_streaming_allowed, bool());
+ MOCK_METHOD1(set_video_streaming_allowed, void(bool state));
+ MOCK_CONST_METHOD0(audio_streaming_allowed, bool());
+ MOCK_METHOD1(set_audio_streaming_allowed, void(bool state));
+ MOCK_METHOD1(StartStreaming,
+ void(protocol_handler::ServiceType service_type));
+ MOCK_METHOD1(StopStreamingForce,
+ void(protocol_handler::ServiceType service_type));
+ MOCK_METHOD1(StopStreaming, void(protocol_handler::ServiceType service_type));
+ MOCK_METHOD1(SuspendStreaming,
+ void(protocol_handler::ServiceType service_type));
+ MOCK_METHOD1(WakeUpStreaming,
+ void(protocol_handler::ServiceType service_type));
+ MOCK_CONST_METHOD0(is_voice_communication_supported, bool());
+ MOCK_METHOD1(set_voice_communication_supported,
+ void(bool is_voice_communication_supported));
+ MOCK_CONST_METHOD0(app_allowed, bool());
+ MOCK_CONST_METHOD0(has_been_activated, bool());
+ MOCK_METHOD1(set_activated, bool(bool is_active));
+ MOCK_CONST_METHOD0(version, const application_manager::Version&());
+ MOCK_METHOD1(set_hmi_application_id, void(uint32_t hmi_app_id));
+ MOCK_CONST_METHOD0(hmi_app_id, uint32_t());
+ MOCK_CONST_METHOD0(app_id, uint32_t());
+ MOCK_CONST_METHOD0(name, const custom_str::CustomString&());
+ MOCK_METHOD1(set_folder_name, void(const std::string& folder_name));
+ MOCK_CONST_METHOD0(folder_name, const std::string());
+ MOCK_CONST_METHOD0(is_media_application, bool());
+ MOCK_CONST_METHOD0(is_foreground, bool());
+ MOCK_METHOD1(set_foreground, void(bool is_foreground));
+ MOCK_CONST_METHOD0(hmi_level, const mobile_apis::HMILevel::eType());
+ MOCK_CONST_METHOD0(put_file_in_none_count, const uint32_t());
+ MOCK_CONST_METHOD0(delete_file_in_none_count, const uint32_t());
+ MOCK_CONST_METHOD0(list_files_in_none_count, const uint32_t());
+ MOCK_CONST_METHOD0(system_context, const mobile_apis::SystemContext::eType());
+ MOCK_CONST_METHOD0(audio_streaming_state,
+ const mobile_apis::AudioStreamingState::eType());
+ MOCK_CONST_METHOD0(app_icon_path, const std::string&());
+ MOCK_CONST_METHOD0(device, connection_handler::DeviceHandle());
+ MOCK_METHOD1(set_tts_properties_in_none, void(bool active));
+ MOCK_METHOD0(tts_properties_in_none, bool());
+ MOCK_METHOD1(set_tts_properties_in_full, void(bool active));
+ MOCK_METHOD0(tts_properties_in_full, bool());
+ MOCK_METHOD1(set_version, void(const application_manager::Version& version));
+ MOCK_METHOD1(set_name, void(const custom_str::CustomString& name));
+ MOCK_METHOD1(set_is_media_application, void(bool is_media));
+ MOCK_METHOD0(increment_put_file_in_none_count, void());
+ MOCK_METHOD0(increment_delete_file_in_none_count, void());
+ MOCK_METHOD0(increment_list_files_in_none_count, void());
+ MOCK_METHOD1(set_app_icon_path, bool(const std::string& file_name));
+ MOCK_METHOD1(set_app_allowed, void(const bool allowed));
+ MOCK_METHOD1(set_device, void(connection_handler::DeviceHandle device));
+ MOCK_CONST_METHOD0(get_grammar_id, uint32_t());
+ MOCK_METHOD1(set_grammar_id, void(uint32_t value));
+ MOCK_METHOD1(
+ set_protocol_version,
+ void(const application_manager::ProtocolVersion& protocol_version));
+ MOCK_CONST_METHOD0(protocol_version, application_manager::ProtocolVersion());
+ MOCK_METHOD1(set_is_resuming, void(bool is_resuming));
+ MOCK_CONST_METHOD0(is_resuming, bool());
+ MOCK_METHOD1(AddFile, bool(const application_manager::AppFile& file));
+ MOCK_CONST_METHOD0(getAppFiles, const application_manager::AppFilesMap&());
+ MOCK_METHOD1(UpdateFile, bool(const application_manager::AppFile& file));
+ MOCK_METHOD1(DeleteFile, bool(const std::string& file_name));
+ MOCK_METHOD1(
+ GetFile,
+ const application_manager::AppFile*(const std::string& file_name));
+ MOCK_METHOD1(SubscribeToButton,
+ bool(mobile_apis::ButtonName::eType btn_name));
+ MOCK_METHOD1(IsSubscribedToButton,
+ bool(mobile_apis::ButtonName::eType btn_name));
+ MOCK_METHOD1(UnsubscribeFromButton,
+ bool(mobile_apis::ButtonName::eType btn_name));
+ MOCK_METHOD1(SubscribeToIVI, bool(uint32_t vehicle_info_type));
+ MOCK_CONST_METHOD1(IsSubscribedToIVI, bool(uint32_t vehicle_info_type));
+ MOCK_METHOD1(UnsubscribeFromIVI, bool(uint32_t vehicle_info_type));
+ MOCK_METHOD0(ResetDataInNone, void());
+ MOCK_METHOD2(IsCommandLimitsExceeded,
+ bool(mobile_apis::FunctionID::eType cmd_id,
+ application_manager::TLimitSource source));
+ MOCK_METHOD0(usage_report, application_manager::UsageStatistics&());
+ MOCK_METHOD1(SetRegularState, void(application_manager::HmiStatePtr state));
+ MOCK_METHOD1(SetPostponedState, void(application_manager::HmiStatePtr state));
+ MOCK_METHOD0(RemovePostponedState, void());
+ MOCK_METHOD1(AddHMIState, void(application_manager::HmiStatePtr state));
+ MOCK_METHOD1(RemoveHMIState,
+ void(application_manager::HmiState::StateID state_id));
+ MOCK_CONST_METHOD0(CurrentHmiState, const application_manager::HmiStatePtr());
+ MOCK_CONST_METHOD0(RegularHmiState, const application_manager::HmiStatePtr());
+ MOCK_CONST_METHOD0(PostponedHmiState,
+ const application_manager::HmiStatePtr());
+ MOCK_METHOD2(SubscribeToSoftButtons,
+ void(int32_t cmd_id,
+ const application_manager::SoftButtonID& softbuttons_id));
+ MOCK_METHOD1(IsSubscribedToSoftButton, bool(const uint32_t softbutton_id));
+ MOCK_METHOD1(UnsubscribeFromSoftButtons, void(int32_t cmd_id));
+ MOCK_CONST_METHOD0(IsAudioApplication, bool());
+ MOCK_METHOD0(LoadPersistentFiles, void());
+};
+
+} // namespace state_controller_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MOCK_H_
diff --git a/src/components/application_manager/test/include/application_manager/event_observer_mock.h b/src/components/application_manager/test/include/application_manager/event_observer_mock.h
new file mode 100644
index 0000000000..3d3d72c5ab
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/event_observer_mock.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_MOCK_EVENT_OBSERVER_MOCK_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_MOCK_EVENT_OBSERVER_MOCK_H_
+
+#include "application_manager/event_engine/event_observer.h"
+#include "application_manager/event_engine/event.h"
+#include "gmock/gmock.h"
+
+namespace test {
+namespace components {
+namespace event_engine_test {
+
+class MockEventObserver
+ : public application_manager::event_engine::EventObserver {
+ public:
+ MockEventObserver(
+ ::application_manager::event_engine::EventDispatcher& event_dispatcher)
+ : application_manager::event_engine::EventObserver(event_dispatcher) {}
+ MOCK_METHOD1(on_event,
+ void(const application_manager::event_engine::Event& event));
+};
+
+} // namespace event_engine_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_MOCK_EVENT_OBSERVER_MOCK_H_
diff --git a/src/components/application_manager/test/include/application_manager/hmi_capabilities_for_testing.h b/src/components/application_manager/test/include/application_manager/hmi_capabilities_for_testing.h
new file mode 100644
index 0000000000..ec8e92e859
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/hmi_capabilities_for_testing.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_HMI_CAPABILITIES_FOR_TESTING_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_HMI_CAPABILITIES_FOR_TESTING_H_
+
+#include "application_manager/hmi_capabilities.h"
+
+namespace test {
+namespace components {
+namespace application_manager_test {
+
+class HMICapabilitiesForTesting
+ : public ::application_manager::HMICapabilities {
+ public:
+ HMICapabilitiesForTesting(::application_manager::ApplicationManager& app_mngr)
+ : HMICapabilities(app_mngr) {}
+ bool LoadCapabilitiesFromFile() {
+ return load_capabilities_from_file();
+ }
+
+ void ConvertJsonLanguagesToObj(
+ Json::Value& json_languages,
+ ::NsSmartDeviceLink::NsSmartObjects::SmartObject& languages) {
+ convert_json_languages_to_obj(json_languages, languages);
+ }
+};
+
+} // namespace application_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_HMI_CAPABILITIES_FOR_TESTING_H_
diff --git a/src/components/application_manager/test/include/application_manager/mock_application.h b/src/components/application_manager/test/include/application_manager/mock_application.h
new file mode 100644
index 0000000000..066ad9baae
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/mock_application.h
@@ -0,0 +1,285 @@
+/*
+* Copyright (c) 2016, Ford Motor Company
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are met:
+*
+* Redistributions of source code must retain the above copyright notice, this
+* list of conditions and the following disclaimer.
+*
+* Redistributions in binary form must reproduce the above copyright notice,
+* this list of conditions and the following
+* disclaimer in the documentation and/or other materials provided with the
+* distribution.
+*
+* Neither the name of the Ford Motor Company nor the names of its contributors
+* may be used to endorse or promote products derived from this software
+* without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+* POSSIBILITY OF SUCH DAMAGE.
+*/
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_APPLICATION_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_APPLICATION_H_
+#include <string>
+#include "gmock/gmock.h"
+#include "application_manager/application.h"
+#include "smart_objects/smart_object.h"
+#include "utils/custom_string.h"
+
+namespace test {
+namespace components {
+namespace application_manager_test {
+
+namespace custom_str = utils::custom_string;
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+class MockApplication : public ::application_manager::Application {
+ public:
+ MockApplication() {}
+ MOCK_CONST_METHOD0(active_message, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(curHash, const std::string&());
+ MOCK_METHOD0(UpdateHash, void());
+ MOCK_CONST_METHOD0(flag_sending_hash_change_after_awake, bool());
+ MOCK_METHOD1(set_flag_sending_hash_change_after_awake, void(bool flag));
+ MOCK_CONST_METHOD0(is_application_data_changed, bool());
+ MOCK_METHOD1(set_is_application_data_changed,
+ void(bool state_application_data));
+ MOCK_METHOD0(CloseActiveMessage, void());
+ MOCK_CONST_METHOD0(IsFullscreen, bool());
+ MOCK_METHOD0(ChangeSupportingAppHMIType, void());
+ MOCK_CONST_METHOD0(is_navi, bool());
+ MOCK_METHOD1(set_is_navi, void(bool allow));
+ MOCK_CONST_METHOD0(video_streaming_approved, bool());
+ MOCK_METHOD1(set_video_streaming_approved, void(bool state));
+ MOCK_CONST_METHOD0(audio_streaming_approved, bool());
+ MOCK_METHOD1(set_audio_streaming_approved, void(bool state));
+ MOCK_CONST_METHOD0(video_streaming_allowed, bool());
+ MOCK_METHOD1(set_video_streaming_allowed, void(bool state));
+ MOCK_CONST_METHOD0(audio_streaming_allowed, bool());
+ MOCK_METHOD1(set_audio_streaming_allowed, void(bool state));
+ MOCK_METHOD1(StartStreaming,
+ void(protocol_handler::ServiceType service_type));
+ MOCK_METHOD1(StopStreaming, void(protocol_handler::ServiceType service_type));
+ MOCK_METHOD1(StopStreamingForce,
+ void(protocol_handler::ServiceType service_type));
+ MOCK_METHOD1(SuspendStreaming,
+ void(protocol_handler::ServiceType service_type));
+ MOCK_METHOD1(WakeUpStreaming,
+ void(protocol_handler::ServiceType service_type));
+ MOCK_CONST_METHOD0(is_voice_communication_supported, bool());
+ MOCK_METHOD1(set_voice_communication_supported,
+ void(bool is_voice_communication_supported));
+ MOCK_CONST_METHOD0(app_allowed, bool());
+ MOCK_CONST_METHOD0(has_been_activated, bool());
+ MOCK_METHOD1(set_activated, bool(bool is_active));
+ MOCK_CONST_METHOD0(version, const ::application_manager::Version&());
+ MOCK_METHOD1(set_hmi_application_id, void(uint32_t hmi_app_id));
+ MOCK_CONST_METHOD0(hmi_app_id, uint32_t());
+ MOCK_CONST_METHOD0(name, const custom_str::CustomString&());
+ MOCK_METHOD1(set_folder_name, void(const std::string& folder_name));
+ MOCK_CONST_METHOD0(folder_name, const std::string());
+ MOCK_CONST_METHOD0(is_media_application, bool());
+ MOCK_CONST_METHOD0(hmi_level, const mobile_apis::HMILevel::eType());
+ MOCK_CONST_METHOD0(put_file_in_none_count, const uint32_t());
+ MOCK_CONST_METHOD0(delete_file_in_none_count, const uint32_t());
+ MOCK_CONST_METHOD0(list_files_in_none_count, const uint32_t());
+ MOCK_CONST_METHOD0(system_context, const mobile_apis::SystemContext::eType());
+ MOCK_CONST_METHOD0(audio_streaming_state,
+ const mobile_apis::AudioStreamingState::eType());
+ MOCK_CONST_METHOD0(app_icon_path, const std::string&());
+ MOCK_CONST_METHOD0(device, connection_handler::DeviceHandle());
+ MOCK_CONST_METHOD0(CurrentHmiState, const application_manager::HmiStatePtr());
+ MOCK_CONST_METHOD0(RegularHmiState, const application_manager::HmiStatePtr());
+ MOCK_CONST_METHOD0(PostponedHmiState,
+ const application_manager::HmiStatePtr());
+ MOCK_METHOD1(set_tts_properties_in_none, void(bool active));
+ MOCK_METHOD0(tts_properties_in_none, bool());
+ MOCK_METHOD1(set_tts_properties_in_full, void(bool active));
+ MOCK_METHOD0(tts_properties_in_full, bool());
+ MOCK_METHOD1(set_version,
+ void(const ::application_manager::Version& version));
+ MOCK_METHOD1(set_name, void(const custom_str::CustomString& name));
+ MOCK_METHOD1(set_is_media_application, void(bool is_media));
+ MOCK_METHOD0(increment_put_file_in_none_count, void());
+ MOCK_METHOD0(increment_delete_file_in_none_count, void());
+ MOCK_METHOD0(increment_list_files_in_none_count, void());
+ MOCK_METHOD1(set_app_icon_path, bool(const std::string& file_name));
+ MOCK_METHOD1(set_app_allowed, void(const bool allowed));
+ MOCK_METHOD1(set_device, void(connection_handler::DeviceHandle device));
+ MOCK_CONST_METHOD0(get_grammar_id, uint32_t());
+ MOCK_METHOD1(set_grammar_id, void(uint32_t value));
+ MOCK_METHOD1(
+ set_protocol_version,
+ void(const ::application_manager::ProtocolVersion& protocol_version));
+ MOCK_CONST_METHOD0(protocol_version,
+ ::application_manager::ProtocolVersion());
+ MOCK_METHOD1(set_is_resuming, void(bool));
+ MOCK_CONST_METHOD0(is_resuming, bool());
+ MOCK_METHOD1(AddFile, bool(const ::application_manager::AppFile& file));
+ MOCK_CONST_METHOD0(getAppFiles, const ::application_manager::AppFilesMap&());
+ MOCK_METHOD1(UpdateFile, bool(const ::application_manager::AppFile& file));
+ MOCK_METHOD1(DeleteFile, bool(const std::string& file_name));
+ MOCK_METHOD1(
+ GetFile,
+ const ::application_manager::AppFile*(const std::string& file_name));
+ MOCK_METHOD1(SubscribeToButton,
+ bool(mobile_apis::ButtonName::eType btn_name));
+ MOCK_METHOD1(IsSubscribedToButton,
+ bool(mobile_apis::ButtonName::eType btn_name));
+ MOCK_METHOD1(UnsubscribeFromButton,
+ bool(mobile_apis::ButtonName::eType btn_name));
+ MOCK_METHOD1(SubscribeToIVI, bool(uint32_t vehicle_info_type));
+ MOCK_CONST_METHOD1(IsSubscribedToIVI, bool(uint32_t vehicle_info_type));
+ MOCK_METHOD1(UnsubscribeFromIVI, bool(uint32_t vehicle_info_type));
+ MOCK_METHOD0(ResetDataInNone, void());
+ MOCK_METHOD2(IsCommandLimitsExceeded,
+ bool(mobile_apis::FunctionID::eType cmd_id,
+ ::application_manager::TLimitSource source));
+ MOCK_METHOD0(usage_report, ::application_manager::UsageStatistics&());
+ MOCK_METHOD1(SetRegularState, void(::application_manager::HmiStatePtr state));
+ MOCK_METHOD1(SetPostponedState,
+ void(::application_manager::HmiStatePtr state));
+ MOCK_METHOD0(RemovePostponedState, void());
+ MOCK_METHOD1(AddHMIState, void(::application_manager::HmiStatePtr state));
+ MOCK_METHOD1(RemoveHMIState,
+ void(::application_manager::HmiState::StateID state_id));
+ MOCK_METHOD2(SubscribeToSoftButtons,
+ void(int32_t cmd_id,
+ const ::application_manager::SoftButtonID& softbuttons_id));
+ MOCK_METHOD1(IsSubscribedToSoftButton, bool(const uint32_t softbutton_id));
+ MOCK_METHOD1(UnsubscribeFromSoftButtons, void(int32_t cmd_id));
+ MOCK_CONST_METHOD0(IsAudioApplication, bool());
+ MOCK_METHOD0(LoadPersistentFiles, void());
+ // InitialApplicationData methods
+ MOCK_CONST_METHOD0(app_types, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(vr_synonyms, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(policy_app_id, std::string());
+ MOCK_CONST_METHOD0(tts_name, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(ngn_media_screen_name,
+ const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(language, const mobile_apis::Language::eType&());
+ MOCK_CONST_METHOD0(ui_language, const mobile_apis::Language::eType&());
+ MOCK_METHOD1(set_app_types,
+ void(const smart_objects::SmartObject& app_types));
+ MOCK_METHOD1(set_vr_synonyms,
+ void(const smart_objects::SmartObject& vr_synonyms));
+ MOCK_METHOD1(set_policy_app_id, void(const std::string& policy_app_id));
+ MOCK_METHOD1(set_tts_name, void(const smart_objects::SmartObject& tts_name));
+ MOCK_METHOD1(set_ngn_media_screen_name,
+ void(const smart_objects::SmartObject& ngn_name));
+ MOCK_METHOD1(set_language,
+ void(const mobile_apis::Language::eType& language));
+ MOCK_METHOD1(set_ui_language,
+ void(const mobile_apis::Language::eType& ui_language));
+ // DynamicApplicationData methods
+ MOCK_CONST_METHOD0(help_prompt, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(timeout_prompt, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(vr_help_title, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(vr_help, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(tbt_state, const mobile_apis::TBTState::eType&());
+ MOCK_CONST_METHOD0(show_command, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(tbt_show_command, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(
+ SubscribedButtons,
+ DataAccessor< ::application_manager::ButtonSubscriptions>());
+ MOCK_CONST_METHOD0(
+ SubscribedIVI,
+ DataAccessor< ::application_manager::VehicleInfoSubscriptions>());
+ MOCK_CONST_METHOD0(keyboard_props, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(menu_title, const smart_objects::SmartObject*());
+ MOCK_CONST_METHOD0(menu_icon, const smart_objects::SmartObject*());
+ MOCK_METHOD1(load_global_properties,
+ void(const smart_objects::SmartObject& so));
+ MOCK_METHOD1(set_help_prompt,
+ void(const smart_objects::SmartObject& help_prompt));
+ MOCK_METHOD1(set_timeout_prompt,
+ void(const smart_objects::SmartObject& timeout_prompt));
+ MOCK_METHOD1(set_vr_help_title,
+ void(const smart_objects::SmartObject& vr_help_title));
+ MOCK_METHOD0(reset_vr_help_title, void());
+ MOCK_METHOD1(set_vr_help, void(const smart_objects::SmartObject& vr_help));
+ MOCK_METHOD0(reset_vr_help, void());
+ MOCK_METHOD1(set_tbt_state,
+ void(const mobile_apis::TBTState::eType& tbt_state));
+ MOCK_METHOD1(set_show_command,
+ void(const smart_objects::SmartObject& show_command));
+ MOCK_METHOD1(set_tbt_show_command,
+ void(const smart_objects::SmartObject& tbt_show));
+ MOCK_METHOD1(set_keyboard_props,
+ void(const smart_objects::SmartObject& keyboard_props));
+ MOCK_METHOD1(set_menu_title,
+ void(const smart_objects::SmartObject& menu_title));
+ MOCK_METHOD1(set_menu_icon,
+ void(const smart_objects::SmartObject& menu_icon));
+ MOCK_CONST_METHOD0(audio_stream_retry_number, uint32_t());
+ MOCK_METHOD1(set_audio_stream_retry_number,
+ void(const uint32_t& audio_stream_retry_number));
+ MOCK_CONST_METHOD0(video_stream_retry_number, uint32_t());
+ MOCK_METHOD1(set_video_stream_retry_number,
+ void(const uint32_t& video_stream_retry_number));
+ MOCK_METHOD2(AddCommand,
+ void(uint32_t cmd_id,
+ const smart_objects::SmartObject& command));
+ MOCK_METHOD1(RemoveCommand, void(uint32_t cmd_id));
+ MOCK_METHOD1(FindCommand, smart_objects::SmartObject*(uint32_t cmd_id));
+ MOCK_METHOD2(AddSubMenu,
+ void(uint32_t menu_id, const smart_objects::SmartObject& menu));
+ MOCK_METHOD1(RemoveSubMenu, void(uint32_t menu_id));
+ MOCK_CONST_METHOD1(FindSubMenu,
+ smart_objects::SmartObject*(uint32_t menu_id));
+ MOCK_METHOD1(IsSubMenuNameAlreadyExist, bool(const std::string& name));
+ MOCK_METHOD2(AddChoiceSet,
+ void(uint32_t choice_set_id,
+ const smart_objects::SmartObject& choice_set));
+ MOCK_METHOD1(RemoveChoiceSet, void(uint32_t choice_set_id));
+ MOCK_METHOD1(FindChoiceSet,
+ smart_objects::SmartObject*(uint32_t choice_set_id));
+ MOCK_METHOD3(AddPerformInteractionChoiceSet,
+ void(uint32_t correlation_id,
+ uint32_t choice_set_id,
+ const smart_objects::SmartObject& choice_set));
+ MOCK_METHOD1(DeletePerformInteractionChoiceSet,
+ void(uint32_t correlation_id));
+ MOCK_CONST_METHOD0(
+ performinteraction_choice_set_map,
+ DataAccessor< ::application_manager::PerformChoiceSetMap>());
+ MOCK_CONST_METHOD0(commands_map,
+ DataAccessor< ::application_manager::CommandsMap>());
+ MOCK_CONST_METHOD0(sub_menu_map,
+ DataAccessor< ::application_manager::SubMenuMap>());
+ MOCK_CONST_METHOD0(choice_set_map,
+ DataAccessor< ::application_manager::ChoiceSetMap>());
+ MOCK_METHOD1(set_perform_interaction_active, void(uint32_t active));
+ MOCK_CONST_METHOD0(is_perform_interaction_active, uint32_t());
+ MOCK_METHOD1(set_perform_interaction_mode, void(int32_t mode));
+ MOCK_CONST_METHOD0(perform_interaction_mode, int32_t());
+ MOCK_METHOD1(set_perform_interaction_layout,
+ void(mobile_apis::LayoutMode::eType mode));
+ MOCK_CONST_METHOD0(perform_interaction_layout,
+ mobile_apis::LayoutMode::eType());
+ MOCK_METHOD1(set_reset_global_properties_active, void(bool active));
+ MOCK_CONST_METHOD0(is_reset_global_properties_active, bool());
+ MOCK_CONST_METHOD0(app_id, uint32_t());
+ MOCK_CONST_METHOD0(mac_address, const std::string&());
+ MOCK_METHOD0(GetAvailableDiskSpace, uint32_t());
+ MOCK_METHOD1(set_mobile_app_id, void(const std::string& policy_app_id));
+ MOCK_CONST_METHOD0(is_foreground, bool());
+ MOCK_METHOD1(set_foreground, void(bool is_foreground));
+ MOCK_CONST_METHOD0(IsRegistered, bool());
+};
+
+} // namespace application_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_APPLICATION_H_
diff --git a/src/components/application_manager/test/include/application_manager/mock_application_manager.h b/src/components/application_manager/test/include/application_manager/mock_application_manager.h
new file mode 100644
index 0000000000..6ad8aeb250
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/mock_application_manager.h
@@ -0,0 +1,248 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_APPLICATION_MANAGER_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_APPLICATION_MANAGER_H_
+
+#include <string>
+#include <vector>
+
+#include "gmock/gmock.h"
+
+#include "application_manager/application_manager.h"
+#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager_settings.h"
+#include "application_manager/commands/command.h"
+#include "application_manager/hmi_capabilities.h"
+#include "application_manager/vehicle_info_data.h"
+#include "application_manager/state_controller.h"
+#include "resumption/last_state.h"
+#include "interfaces/MOBILE_API.h"
+
+namespace test {
+namespace components {
+namespace application_manager_test {
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+
+class MockApplicationManager : public application_manager::ApplicationManager {
+ public:
+ MOCK_METHOD2(Init,
+ bool(resumption::LastState& last_state,
+ media_manager::MediaManager* media_manager));
+ MOCK_METHOD0(Stop, bool());
+ MOCK_METHOD1(set_hmi_message_handler,
+ void(hmi_message_handler::HMIMessageHandler* handler));
+ MOCK_METHOD1(set_protocol_handler,
+ void(protocol_handler::ProtocolHandler* handler));
+ MOCK_METHOD1(set_connection_handler,
+ void(connection_handler::ConnectionHandler* handler));
+ MOCK_CONST_METHOD0(applications,
+ DataAccessor<application_manager::ApplicationSet>());
+ MOCK_CONST_METHOD1(
+ application, application_manager::ApplicationSharedPtr(uint32_t app_id));
+ MOCK_CONST_METHOD0(active_application,
+ application_manager::ApplicationSharedPtr());
+ MOCK_CONST_METHOD1(
+ application_by_hmi_app,
+ application_manager::ApplicationSharedPtr(uint32_t hmi_app_id));
+ MOCK_CONST_METHOD1(application_by_policy_id,
+ application_manager::ApplicationSharedPtr(
+ const std::string& policy_app_id));
+ MOCK_METHOD1(
+ applications_by_button,
+ std::vector<application_manager::ApplicationSharedPtr>(uint32_t button));
+ MOCK_METHOD0(applications_with_navi,
+ std::vector<application_manager::ApplicationSharedPtr>());
+ MOCK_CONST_METHOD0(get_limited_media_application,
+ application_manager::ApplicationSharedPtr());
+ MOCK_CONST_METHOD0(get_limited_navi_application,
+ application_manager::ApplicationSharedPtr());
+ MOCK_CONST_METHOD0(get_limited_voice_application,
+ application_manager::ApplicationSharedPtr());
+ MOCK_METHOD1(application_id, uint32_t(const int32_t correlation_id));
+ MOCK_METHOD2(set_application_id,
+ void(const int32_t correlation_id, const uint32_t app_id));
+ MOCK_METHOD3(OnHMILevelChanged,
+ void(uint32_t app_id,
+ mobile_apis::HMILevel::eType from,
+ mobile_apis::HMILevel::eType to));
+ MOCK_METHOD1(
+ SendHMIStatusNotification,
+ void(const utils::SharedPtr<application_manager::Application> app));
+ MOCK_METHOD2(SendMessageToMobile,
+ void(application_manager::commands::MessageSharedPtr, bool));
+ MOCK_METHOD1(
+ SendMessageToHMI,
+ void(const application_manager::commands::MessageSharedPtr message));
+ MOCK_METHOD1(
+ ManageHMICommand,
+ bool(const application_manager::commands::MessageSharedPtr message));
+ MOCK_METHOD2(
+ ManageMobileCommand,
+ bool(const application_manager::commands::MessageSharedPtr message,
+ application_manager::commands::Command::CommandOrigin origin));
+ MOCK_CONST_METHOD1(
+ GetDefaultHmiLevel,
+ mobile_apis::HMILevel::eType(
+ application_manager::ApplicationConstSharedPtr application));
+ MOCK_METHOD0(hmi_capabilities, application_manager::HMICapabilities&());
+ MOCK_CONST_METHOD0(hmi_capabilities,
+ const application_manager::HMICapabilities&());
+ MOCK_METHOD2(ProcessQueryApp,
+ void(const smart_objects::SmartObject& sm_object,
+ const uint32_t connection_key));
+ MOCK_CONST_METHOD0(is_attenuated_supported, bool());
+ MOCK_CONST_METHOD1(IsAppTypeExistsInFullOrLimited,
+ bool(application_manager::ApplicationConstSharedPtr app));
+ MOCK_METHOD1(OnApplicationRegistered,
+ void(application_manager::ApplicationSharedPtr app));
+ MOCK_CONST_METHOD0(connection_handler,
+ connection_handler::ConnectionHandler&());
+ MOCK_CONST_METHOD0(protocol_handler, protocol_handler::ProtocolHandler&());
+ MOCK_METHOD0(GetPolicyHandler, policy::PolicyHandlerInterface&());
+ MOCK_METHOD0(GetNextHMICorrelationID, uint32_t());
+ MOCK_METHOD0(GenerateNewHMIAppID, uint32_t());
+ MOCK_METHOD1(EndNaviServices, void(uint32_t app_id));
+ MOCK_METHOD0(BeginAudioPassThrough, bool());
+ MOCK_METHOD0(EndAudioPassThrough, bool());
+ MOCK_METHOD1(ConnectToDevice, void(const std::string& device_mac));
+ MOCK_METHOD0(OnHMIStartedCooperation, void());
+ MOCK_CONST_METHOD0(IsHMICooperating, bool());
+ MOCK_METHOD2(IviInfoUpdated,
+ std::vector<application_manager::ApplicationSharedPtr>(
+ application_manager::VehicleDataType vehicle_info,
+ int value));
+ MOCK_METHOD1(RegisterApplication,
+ application_manager::ApplicationSharedPtr(const utils::SharedPtr<
+ smart_objects::SmartObject>& request_for_registration));
+ MOCK_METHOD0(SendUpdateAppList, void());
+ MOCK_METHOD2(MarkAppsGreyOut,
+ void(const connection_handler::DeviceHandle handle,
+ bool is_greyed_out));
+ MOCK_CONST_METHOD1(IsAppsQueriedFrom,
+ bool(const connection_handler::DeviceHandle handle));
+ MOCK_CONST_METHOD0(IsStopping, bool());
+ MOCK_METHOD1(RemoveAppFromTTSGlobalPropertiesList,
+ void(const uint32_t app_id));
+ MOCK_METHOD4(
+ SaveBinary,
+ mobile_apis::Result::eType(const std::vector<uint8_t>& binary_data,
+ const std::string& file_path,
+ const std::string& file_name,
+ const int64_t offset));
+ MOCK_METHOD1(SetAllAppsAllowed, void(const bool allowed));
+ MOCK_METHOD1(set_driver_distraction, void(bool is_distracting));
+ MOCK_METHOD6(StartAudioPassThruThread,
+ void(int32_t session_key,
+ int32_t correlation_id,
+ int32_t max_duration,
+ int32_t sampling_rate,
+ int32_t bits_per_sample,
+ int32_t audio_type));
+ MOCK_METHOD0(StartDevicesDiscovery, void());
+ MOCK_METHOD1(StopAudioPassThru, void(int32_t application_key));
+ MOCK_METHOD2(TerminateRequest,
+ void(uint32_t connection_key, uint32_t corr_id));
+ MOCK_METHOD4(UnregisterApplication,
+ void(const uint32_t&, mobile_apis::Result::eType, bool, bool));
+ MOCK_METHOD3(updateRequestTimeout,
+ void(uint32_t connection_key,
+ uint32_t mobile_correlation_id,
+ uint32_t new_timeout_value));
+ MOCK_METHOD0(state_controller, application_manager::StateController&());
+ MOCK_METHOD1(SetUnregisterAllApplicationsReason,
+ void(mobile_apis::AppInterfaceUnregisteredReason::eType reason));
+ MOCK_METHOD1(HeadUnitReset,
+ void(mobile_apis::AppInterfaceUnregisteredReason::eType reason));
+ MOCK_CONST_METHOD2(HMILevelAllowsStreaming,
+ bool(uint32_t app_id,
+ protocol_handler::ServiceType service_type));
+ MOCK_METHOD5(CheckPolicyPermissions,
+ mobile_apis::Result::eType(
+ const std::string&,
+ mobile_apis::HMILevel::eType,
+ mobile_apis::FunctionID::eType,
+ const application_manager::RPCParams&,
+ application_manager::CommandParametersPermissions*));
+ MOCK_CONST_METHOD2(IsApplicationForbidden,
+ bool(uint32_t connection_key,
+ const std::string& policy_app_id));
+ MOCK_METHOD0(resume_controller, resumption::ResumeCtrl&());
+ MOCK_METHOD1(
+ GetDeviceTransportType,
+ hmi_apis::Common_TransportType::eType(const std::string& transport_type));
+ MOCK_METHOD1(AddAppToTTSGlobalPropertiesList, void(const uint32_t app_id));
+ MOCK_METHOD0(GenerateGrammarID, uint32_t());
+ MOCK_CONST_METHOD1(GetUserConsentForDevice,
+ policy::DeviceConsent(const std::string& device_id));
+ MOCK_METHOD1(OnAppUnauthorized, void(const uint32_t& app_id));
+ MOCK_METHOD1(ActivateApplication,
+ bool(application_manager::ApplicationSharedPtr app));
+ MOCK_METHOD3(OnAppStreaming,
+ void(uint32_t app_id,
+ protocol_handler::ServiceType service_type,
+ bool state));
+ MOCK_CONST_METHOD4(CreateRegularState,
+ application_manager::HmiStatePtr(
+ uint32_t app_id,
+ mobile_apis::HMILevel::eType hmi_level,
+ mobile_apis::AudioStreamingState::eType audio_state,
+ mobile_apis::SystemContext::eType system_context));
+ MOCK_METHOD2(SendAudioPassThroughNotification,
+ void(uint32_t session_key, std::vector<uint8_t>& binary_data));
+ MOCK_CONST_METHOD2(CanAppStream,
+ bool(uint32_t app_id,
+ protocol_handler::ServiceType service_type));
+ MOCK_METHOD1(ForbidStreaming, void(uint32_t app_id));
+ MOCK_CONST_METHOD0(get_settings,
+ const application_manager::ApplicationManagerSettings&());
+ MOCK_METHOD0(event_dispatcher,
+ application_manager::event_engine::EventDispatcher&());
+
+ MOCK_CONST_METHOD1(IsAppSubscribedForWayPoints, bool(const uint32_t));
+ MOCK_METHOD1(SubscribeAppForWayPoints, void(const uint32_t));
+ MOCK_METHOD1(UnsubscribeAppFromWayPoints, void(const uint32_t));
+ MOCK_CONST_METHOD0(IsAnyAppSubscribedForWayPoints, bool());
+ MOCK_CONST_METHOD0(GetAppsSubscribedForWayPoints, const std::set<int32_t>());
+ MOCK_CONST_METHOD1(
+ WaitingApplicationByID,
+ application_manager::ApplicationConstSharedPtr(const uint32_t));
+ MOCK_CONST_METHOD0(
+ AppsWaitingForRegistration,
+ DataAccessor<application_manager::AppsWaitRegistrationSet>());
+};
+
+} // namespace application_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_APPLICATION_MANAGER_H_
diff --git a/src/components/application_manager/test/include/application_manager/mock_event_dispatcher.h b/src/components/application_manager/test/include/application_manager/mock_event_dispatcher.h
new file mode 100644
index 0000000000..916f4a69f0
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/mock_event_dispatcher.h
@@ -0,0 +1,68 @@
+/*
+ Copyright (c) 2016, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_EVENT_DISPATCHER_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_EVENT_DISPATCHER_H_
+
+#include <list>
+#include "application_manager/event_engine/event.h"
+#include "application_manager/event_engine/event_dispatcher.h"
+#include "application_manager/event_engine/event_observer.h"
+
+namespace test {
+namespace components {
+namespace event_engine_test {
+
+class MockEventDispatcher
+ : public ::application_manager::event_engine::EventDispatcher {
+ public:
+ MOCK_METHOD1(raise_event,
+ void(const ::application_manager::event_engine::Event& event));
+ MOCK_METHOD3(
+ add_observer,
+ void(const ::application_manager::event_engine::Event::EventID& event_id,
+ int32_t hmi_correlation_id,
+ ::application_manager::event_engine::EventObserver& observer));
+ MOCK_METHOD2(
+ remove_observer,
+ void(const ::application_manager::event_engine::Event::EventID& event_id,
+ ::application_manager::event_engine::EventObserver& observer));
+ MOCK_METHOD1(
+ remove_observer,
+ void(::application_manager::event_engine::EventObserver& observer));
+};
+
+} // namespace event_engine_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_EVENT_DISPATCHER_H_
diff --git a/src/components/application_manager/test/include/application_manager/mock_message_helper.h b/src/components/application_manager/test/include/application_manager/mock_message_helper.h
new file mode 100644
index 0000000000..289b20a105
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/mock_message_helper.h
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_MOCK_MESSAGE_HELPER_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_MOCK_MESSAGE_HELPER_H_
+#include "gmock/gmock.h"
+#include "application_manager/application.h"
+#include "interfaces/HMI_API.h"
+#include "policy/policy_types.h"
+#include "application_manager/policies/policy_handler_interface.h"
+#include "application_manager/application_manager.h"
+
+namespace application_manager {
+
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+class MockMessageHelper {
+ public:
+ MOCK_METHOD1(GetHashUpdateNotification,
+ smart_objects::SmartObjectSPtr(const uint32_t app_id));
+ MOCK_METHOD2(SendHashUpdateNotification,
+ void(const uint32_t app_id, ApplicationManager& app_mngr));
+ MOCK_METHOD1(HMIResultToString,
+ std::string(hmi_apis::Common_Result::eType hmi_result));
+ MOCK_METHOD1(HMIResultFromString,
+ hmi_apis::Common_Result::eType(const std::string& hmi_result));
+ MOCK_METHOD1(MobileResultToString,
+ std::string(mobile_apis::Result::eType mobile_result));
+ MOCK_METHOD1(MobileResultFromString,
+ mobile_api::Result::eType(const std::string& mobile_result));
+ MOCK_METHOD1(HMIToMobileResult,
+ mobile_api::Result::eType(
+ const hmi_apis::Common_Result::eType hmi_result));
+ MOCK_METHOD1(MobileToHMIResult,
+ hmi_apis::Common_Result::eType(
+ const mobile_api::Result::eType mobile_result));
+ MOCK_METHOD1(StringToHMILevel,
+ mobile_api::HMILevel::eType(const std::string& hmi_level));
+ MOCK_METHOD1(CreateDeviceListSO,
+ smart_objects::SmartObjectSPtr(
+ const connection_handler::DeviceMap& devices));
+ MOCK_METHOD2(SendNaviStartStream,
+ void(int32_t connection_key, ApplicationManager& app_mngr));
+ MOCK_METHOD2(SendNaviStopStream,
+ void(int32_t connection_key, ApplicationManager& app_mngr));
+ MOCK_METHOD3(SendOnAppPermissionsChangedNotification,
+ void(uint32_t connection_key,
+ const policy::AppPermissions& permissions,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD2(SendAudioStartStream,
+ void(int32_t connection_key, ApplicationManager& app_mngr));
+ MOCK_METHOD2(SendAudioStopStream,
+ void(int32_t connection_key, ApplicationManager& app_mngr));
+ MOCK_METHOD3(SendOnDataStreaming,
+ void(protocol_handler::ServiceType service,
+ bool available,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD3(CreateGetVehicleDataRequest,
+ void(uint32_t correlation_id,
+ const std::vector<std::string>& params,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD3(SendUpdateSDLResponse,
+ void(const std::string& result,
+ uint32_t correlation_id,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD3(SendGetUserFriendlyMessageResponse,
+ void(const std::vector<policy::UserFriendlyMessage>& msg,
+ uint32_t correlation_id,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD3(SendGetStatusUpdateResponse,
+ void(const std::string& status,
+ uint32_t correlation_id,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD2(SendOnStatusUpdate,
+ void(const std::string& status, ApplicationManager& app_mngr));
+ MOCK_METHOD3(SendSDLActivateAppResponse,
+ void(policy::AppPermissions& permissions,
+ uint32_t correlation_id,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD1(SendGetSystemInfoRequest, void(ApplicationManager& app_mngr));
+
+ MOCK_METHOD4(SendPolicyUpdate,
+ void(const std::string& file_path,
+ int timeout,
+ const std::vector<int>& retries,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD3(
+ SendGetListOfPermissionsResponse,
+ void(const std::vector<policy::FunctionalGroupPermission>& permissions,
+ uint32_t correlation_id,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD3(SendOnPermissionsChangeNotification,
+ void(uint32_t connection_key,
+ const policy::Permissions& permissions,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD4(SendPolicySnapshotNotification,
+ void(uint32_t connection_key,
+ const std::vector<uint8_t>& policy_data,
+ const std::string& url,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD1(CommonLanguageFromString,
+ hmi_apis::Common_Language::eType(const std::string& language));
+ MOCK_METHOD1(CommonLanguageToString,
+ std::string(hmi_apis::Common_Language::eType));
+ MOCK_METHOD2(CreateModuleInfoSO,
+ smart_objects::SmartObjectSPtr(uint32_t function_id,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD2(SendAllOnButtonSubscriptionNotificationsForApp,
+ void(ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD2(SendOnResumeAudioSourceToHMI,
+ void(uint32_t app_id, ApplicationManager& app_mngr));
+ MOCK_METHOD2(CreateAddSubMenuRequestToHMI,
+ smart_objects::SmartObjectList(ApplicationConstSharedPtr app,
+ const uint32_t correlation_id));
+ MOCK_METHOD2(CreateAddCommandRequestToHMI,
+ smart_objects::SmartObjectList(ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD1(CreateAddVRCommandRequestFromChoiceToHMI,
+ smart_objects::SmartObjectList(ApplicationConstSharedPtr app));
+ MOCK_METHOD1(SendGlobalPropertiesToHMI, void(ApplicationConstSharedPtr app));
+ MOCK_METHOD1(GetIVISubscriptionRequests,
+ smart_objects::SmartObjectList(ApplicationSharedPtr app));
+ MOCK_METHOD3(VerifyImageFiles,
+ mobile_apis::Result::eType(smart_objects::SmartObject& message,
+
+ ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD6(GetBCActivateAppRequestToHMI,
+ smart_objects::SmartObjectSPtr(
+ ApplicationConstSharedPtr app,
+ const protocol_handler::SessionObserver& session_observer,
+ const policy::PolicyHandlerInterface& policy_handler,
+ hmi_apis::Common_HMILevel::eType level,
+ bool send_policy_priority,
+ ApplicationManager& app_mngr));
+ MOCK_METHOD2(GetOnAppInterfaceUnregisteredNotificationToMobile,
+ NsSmartDeviceLink::NsSmartObjects::SmartObjectSPtr(
+ int32_t connection_key,
+ mobile_apis::AppInterfaceUnregisteredReason::eType reason));
+
+ static MockMessageHelper* message_helper_mock();
+};
+
+} // namespace application_manager
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_MOCK_MESSAGE_HELPER_H_
diff --git a/src/components/application_manager/test/include/application_manager/mock_resumption_data.h b/src/components/application_manager/test/include/application_manager/mock_resumption_data.h
new file mode 100644
index 0000000000..09fe8d38b3
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/mock_resumption_data.h
@@ -0,0 +1,95 @@
+/*
+* Copyright (c) 2016, Ford Motor Company
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are met:
+*
+* Redistributions of source code must retain the above copyright notice, this
+* list of conditions and the following disclaimer.
+*
+* Redistributions in binary form must reproduce the above copyright notice,
+* this list of conditions and the following
+* disclaimer in the documentation and/or other materials provided with the
+* distribution.
+*
+* Neither the name of the Ford Motor Company nor the names of its contributors
+* may be used to endorse or promote products derived from this software
+* without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+* POSSIBILITY OF SUCH DAMAGE.
+*/
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_RESUMPTION_DATA_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_RESUMPTION_DATA_H_
+#include <string>
+#include "gmock/gmock.h"
+#include "application_manager/resumption/resumption_data.h"
+#include "application_manager/application.h"
+#include "application_manager/mock_application_manager_settings.h"
+#include "application_manager/mock_application_manager.h"
+
+namespace test {
+namespace components {
+namespace resumption_test {
+
+namespace app_mngr = application_manager;
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+
+class MockResumptionData : public ::resumption::ResumptionData {
+ public:
+ MockResumptionData(
+ const application_manager_test::MockApplicationManager& settings)
+ : ResumptionData(settings) {}
+ MOCK_METHOD1(SaveApplication,
+ void(app_mngr::ApplicationSharedPtr application));
+ MOCK_CONST_METHOD2(GetStoredHMILevel,
+ int32_t(const std::string& policy_app_id,
+ const std::string& device_id));
+ MOCK_CONST_METHOD1(IsHMIApplicationIdExist, bool(uint32_t hmi_app_id));
+ MOCK_CONST_METHOD2(GetHMIApplicationID,
+ uint32_t(const std::string& policy_app_id,
+ const std::string& device_id));
+ MOCK_METHOD0(OnSuspend, void());
+ MOCK_CONST_METHOD3(GetHashId,
+ bool(const std::string& policy_app_id,
+ const std::string& device_id,
+ std::string& hash_id));
+ MOCK_METHOD0(OnAwake, void());
+ MOCK_CONST_METHOD3(GetSavedApplication,
+ bool(const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app));
+ MOCK_METHOD2(RemoveApplicationFromSaved,
+ bool(const std::string& policy_app_id,
+ const std::string& device_id));
+ MOCK_CONST_METHOD0(GetIgnOffTime, uint32_t());
+ MOCK_CONST_METHOD2(IsApplicationSaved,
+ ssize_t(const std::string& policy_app_id,
+ const std::string& device_id));
+ MOCK_CONST_METHOD1(GetDataForLoadResumeData,
+ void(smart_objects::SmartObject& saved_data));
+ MOCK_METHOD3(UpdateHmiLevel,
+ void(const std::string& policy_app_id,
+ const std::string& device_id,
+ mobile_apis::HMILevel::eType hmi_level));
+ MOCK_METHOD0(Init, bool());
+ MOCK_METHOD2(DropAppDataResumption,
+ bool(const std::string& device_id, const std::string& app_id));
+ MOCK_METHOD0(Persist, void());
+};
+
+} // namespace resumption_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_RESUMPTION_DATA_H_
diff --git a/src/components/application_manager/test/include/application_manager/mock_statistics_manager.h b/src/components/application_manager/test/include/application_manager/mock_statistics_manager.h
new file mode 100644
index 0000000000..668959fe2e
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/mock_statistics_manager.h
@@ -0,0 +1,65 @@
+/* Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_MOCK_STATISTICS_MANAGER_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_MOCK_STATISTICS_MANAGER_H_
+
+#include <string>
+
+#include "gmock/gmock.h"
+
+#include "policy/usage_statistics/statistics_manager.h"
+#include "application_manager/usage_statistics.h"
+
+namespace test {
+namespace components {
+namespace application_manager_test {
+
+using namespace ::usage_statistics;
+class MockStatisticsManager : public StatisticsManager {
+ public:
+ MOCK_METHOD1(Increment, void(GlobalCounterId type));
+ MOCK_METHOD2(Increment, void(const std::string& app_id, AppCounterId type));
+ MOCK_METHOD3(Set,
+ void(const std::string& app_id,
+ AppInfoId type,
+ const std::string& value));
+ MOCK_METHOD3(Add,
+ void(const std::string& app_id,
+ AppStopwatchId type,
+ int32_t timespan_seconds));
+ virtual ~MockStatisticsManager() {}
+};
+
+} // namespace application_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_MOCK_STATISTICS_MANAGER_H_
diff --git a/src/components/application_manager/test/include/application_manager/mock_telemetry_observer.h b/src/components/application_manager/test/include/application_manager/mock_telemetry_observer.h
new file mode 100644
index 0000000000..bc5d444eed
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/mock_telemetry_observer.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_MOCK_TIME_METRIC_OBSERVER_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_MOCK_TIME_METRIC_OBSERVER_H_
+
+#include "gmock/gmock.h"
+#include "application_manager/telemetry_observer.h"
+
+namespace test {
+namespace components {
+namespace application_manager_test {
+
+class MockAMTelemetryObserver
+ : public application_manager::AMTelemetryObserver {
+ public:
+ MOCK_METHOD1(OnMessage, void(MessageMetricSharedPtr));
+};
+
+} // namespace application_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_MOCK_TIME_METRIC_OBSERVER_H_
diff --git a/src/components/application_manager/test/include/application_manager/policy_handler_interface_mock.h b/src/components/application_manager/test/include/application_manager/policy_handler_interface_mock.h
new file mode 100644
index 0000000000..51a0678b24
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/policy_handler_interface_mock.h
@@ -0,0 +1,203 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_MOCK_POLICY_HANDLER_INTERFACE_MOCK_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_MOCK_POLICY_HANDLER_INTERFACE_MOCK_H_
+
+#include "application_manager/policies/policy_handler_interface.h"
+#include "gmock/gmock.h"
+#include "policy/policy_types.h"
+
+namespace policy {
+
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+class MockPolicyHandlerInterface : public policy::PolicyHandlerInterface {
+ public:
+ MOCK_METHOD0(LoadPolicyLibrary, bool());
+ MOCK_CONST_METHOD0(PolicyEnabled, bool());
+ MOCK_METHOD0(InitPolicyTable, bool());
+ MOCK_METHOD0(ResetPolicyTable, bool());
+ MOCK_METHOD0(ClearUserConsent, bool());
+ MOCK_METHOD2(SendMessageToSDK,
+ bool(const policy::BinaryMessage& pt_string,
+ const std::string& url));
+ MOCK_METHOD2(ReceiveMessageFromSDK,
+ bool(const std::string& file,
+ const policy::BinaryMessage& pt_string));
+ MOCK_METHOD0(UnloadPolicyLibrary, bool());
+ MOCK_METHOD3(OnPermissionsUpdated,
+ void(const std::string& policy_app_id,
+ const policy::Permissions& permissions,
+ const policy::HMILevel& default_hmi));
+ MOCK_METHOD2(OnPermissionsUpdated,
+ void(const std::string& policy_app_id,
+ const policy::Permissions& permissions));
+ MOCK_METHOD3(OnSnapshotCreated,
+ void(const policy::BinaryMessage& pt_string,
+ const std::vector<int>& retry_delay_seconds,
+ int timeout_exchange));
+ MOCK_CONST_METHOD2(GetPriority,
+ bool(const std::string& policy_app_id,
+ std::string* priority));
+ MOCK_METHOD5(CheckPermissions,
+ void(const policy::PTString& app_id,
+ const policy::PTString& hmi_level,
+ const policy::PTString& rpc,
+ const policy::RPCParams& rpc_params,
+ policy::CheckPermissionResult& result));
+ MOCK_CONST_METHOD1(GetNotificationsNumber,
+ uint32_t(const std::string& priority));
+ MOCK_CONST_METHOD1(GetUserConsentForDevice,
+ policy::DeviceConsent(const std::string& device_id));
+ MOCK_CONST_METHOD2(GetDefaultHmi,
+ bool(const std::string& policy_app_id,
+ std::string* default_hmi));
+
+ MOCK_METHOD3(GetInitialAppData,
+ bool(const std::string& application_id,
+ policy::StringArray* nicknames,
+ policy::StringArray* app_hmi_types));
+ MOCK_METHOD2(GetInitialAppData,
+ bool(const std::string& application_id,
+ policy::StringArray* nicknames));
+ MOCK_METHOD1(GetInitialAppData, bool(const std::string& application_id));
+ MOCK_METHOD2(GetUpdateUrls,
+ void(int service_type, policy::EndpointUrls& end_points));
+ MOCK_METHOD0(ResetRetrySequence, void());
+ MOCK_METHOD0(NextRetryTimeout, uint32_t());
+ MOCK_METHOD0(TimeoutExchange, int());
+ MOCK_METHOD0(OnExceededTimeout, void());
+ MOCK_METHOD0(OnSystemReady, void());
+ MOCK_METHOD2(PTUpdatedAt, void(policy::Counters counter, int value));
+ MOCK_METHOD1(add_listener, void(policy::PolicyHandlerObserver* listener));
+ MOCK_METHOD1(remove_listener, void(policy::PolicyHandlerObserver* listener));
+ MOCK_CONST_METHOD0(GetStatisticManager,
+ utils::SharedPtr<usage_statistics::StatisticsManager>());
+ MOCK_CONST_METHOD2(CheckSystemAction,
+ bool(mobile_apis::SystemAction::eType system_action,
+ const std::string& policy_app_id));
+ MOCK_METHOD1(KmsChanged, void(int kms));
+ MOCK_METHOD2(OnActivateApp,
+ void(uint32_t connection_key, uint32_t correlation_id));
+ MOCK_METHOD2(OnAllowSDLFunctionalityNotification,
+ void(bool is_allowed, const std::string& device_id));
+ MOCK_METHOD0(OnIgnitionCycleOver, void());
+ MOCK_METHOD1(OnPendingPermissionChange,
+ void(const std::string& policy_app_id));
+ MOCK_METHOD1(PTExchangeAtUserRequest, void(uint32_t correlation_id));
+ MOCK_METHOD2(AddDevice,
+ void(const std::string& device_id,
+ const std::string& connection_type));
+ MOCK_METHOD2(SetDeviceInfo,
+ void(const std::string& device_id,
+ const policy::DeviceInfo& device_info));
+ MOCK_METHOD2(OnAppPermissionConsent,
+ void(const uint32_t connection_key,
+ const policy::PermissionConsent& permissions));
+ MOCK_METHOD3(OnGetUserFriendlyMessage,
+ void(const std::vector<std::string>& message_codes,
+ const std::string& language,
+ uint32_t correlation_id));
+ MOCK_METHOD2(OnGetListOfPermissions,
+ void(const uint32_t connection_key,
+ const uint32_t correlation_id));
+ MOCK_METHOD1(OnGetStatusUpdate, void(const uint32_t correlation_id));
+ MOCK_METHOD1(OnUpdateStatusChanged, void(const std::string& status));
+ MOCK_METHOD1(OnCurrentDeviceIdUpdateRequired,
+ std::string(const std::string& policy_app_id));
+ MOCK_METHOD1(OnSystemInfoChanged, void(const std::string& language));
+ MOCK_METHOD3(OnGetSystemInfo,
+ void(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language));
+ MOCK_METHOD0(OnSystemInfoUpdateRequired, void());
+ MOCK_METHOD0(OnVIIsReady, void());
+ MOCK_METHOD1(OnVehicleDataUpdated,
+ void(const smart_objects::SmartObject& message));
+ MOCK_METHOD1(RemoveDevice, void(const std::string& device_id));
+ MOCK_METHOD1(AddStatisticsInfo, void(int type));
+ MOCK_METHOD1(OnSystemError, void(int code));
+ MOCK_CONST_METHOD0(GetAppIdForSending, uint32_t());
+ MOCK_METHOD1(
+ GetAppName,
+ utils::custom_string::CustomString(const std::string& policy_app_id));
+ MOCK_METHOD1(OnUpdateHMIAppType,
+ void(std::map<std::string, policy::StringArray> app_hmi_types));
+ MOCK_METHOD1(OnCertificateUpdated, void(const std::string& certificate_data));
+ MOCK_METHOD1(OnCertificateDecrypted, void(bool is_succeeded));
+ MOCK_METHOD0(CanUpdate, bool());
+ MOCK_METHOD2(OnDeviceConsentChanged,
+ void(const std::string& device_id, bool is_allowed));
+ MOCK_CONST_METHOD2(SendOnAppPermissionsChanged,
+ void(const policy::AppPermissions& permissions,
+ const std::string& policy_app_id));
+ MOCK_METHOD0(OnPTExchangeNeeded, void());
+ MOCK_METHOD1(GetAvailableApps, void(std::queue<std::string>& apps));
+ MOCK_METHOD1(AddApplication, void(const std::string& application_id));
+ MOCK_METHOD1(IsApplicationRevoked, bool(const std::string& app_id));
+ MOCK_METHOD0(OnUpdateRequestSentToMobile, void());
+ MOCK_CONST_METHOD1(HeartBeatTimeout, uint32_t(const std::string& app_id));
+ MOCK_METHOD0(OnAppsSearchStarted, void());
+ MOCK_METHOD0(OnAppsSearchCompleted, void());
+ MOCK_METHOD1(OnAppRegisteredOnMobile,
+ void(const std::string& application_id));
+ MOCK_CONST_METHOD2(IsRequestTypeAllowed,
+ bool(const std::string& policy_app_id,
+ mobile_apis::RequestType::eType type));
+ MOCK_CONST_METHOD1(
+ GetAppRequestTypes,
+ const std::vector<std::string>(const std::string& policy_app_id));
+ MOCK_CONST_METHOD0(GetVehicleInfo, const policy::VehicleInfo());
+ MOCK_METHOD1(Increment, void(usage_statistics::GlobalCounterId type));
+ MOCK_METHOD2(Increment,
+ void(const std::string& app_id,
+ usage_statistics::AppCounterId type));
+ MOCK_METHOD3(Set,
+ void(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value));
+ MOCK_METHOD3(Add,
+ void(const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int32_t timespan_seconds));
+ MOCK_CONST_METHOD0(RetrieveCertificate, std::string());
+ MOCK_CONST_METHOD0(get_settings, const policy::PolicySettings&());
+
+ private:
+ MOCK_METHOD2(OnAppPermissionConsentInternal,
+ void(const uint32_t connection_key,
+ policy::PermissionConsent& permissions));
+};
+
+} // namespace policy
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_MOCK_POLICY_HANDLER_INTERFACE_MOCK_H_
diff --git a/src/components/application_manager/test/include/application_manager/resumption_data_mock.h b/src/components/application_manager/test/include/application_manager/resumption_data_mock.h
new file mode 100644
index 0000000000..6625b3e5b3
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/resumption_data_mock.h
@@ -0,0 +1,94 @@
+/*
+* Copyright (c) 2016, Ford Motor Company
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are met:
+*
+* Redistributions of source code must retain the above copyright notice, this
+* list of conditions and the following disclaimer.
+*
+* Redistributions in binary form must reproduce the above copyright notice,
+* this list of conditions and the following
+* disclaimer in the documentation and/or other materials provided with the
+* distribution.
+*
+* Neither the name of the Ford Motor Company nor the names of its contributors
+* may be used to endorse or promote products derived from this software
+* without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+* POSSIBILITY OF SUCH DAMAGE.
+*/
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_RESUMPTION_DATA_MOCK_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_RESUMPTION_DATA_MOCK_H_
+#include <string>
+#include "gmock/gmock.h"
+#include "application_manager/resumption/resumption_data.h"
+#include "application_manager/application.h"
+#include "application_manager/mock_application_manager_settings.h"
+#include "application_manager/mock_application_manager.h"
+
+namespace test {
+namespace components {
+namespace resumption_test {
+namespace app_mngr = application_manager;
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+
+class MockResumptionData : public ::resumption::ResumptionData {
+ public:
+ MockResumptionData(const application_manager_test::MockApplicationManager&
+ application_manager)
+ : ResumptionData(application_manager) {}
+ MOCK_METHOD1(SaveApplication,
+ void(app_mngr::ApplicationSharedPtr application));
+ MOCK_CONST_METHOD2(GetStoredHMILevel,
+ int32_t(const std::string& policy_app_id,
+ const std::string& device_id));
+ MOCK_CONST_METHOD1(IsHMIApplicationIdExist, bool(uint32_t hmi_app_id));
+ MOCK_CONST_METHOD2(GetHMIApplicationID,
+ uint32_t(const std::string& policy_app_id,
+ const std::string& device_id));
+ MOCK_METHOD0(OnSuspend, void());
+ MOCK_CONST_METHOD3(GetHashId,
+ bool(const std::string& policy_app_id,
+ const std::string& device_id,
+ std::string& hash_id));
+ MOCK_METHOD0(OnAwake, void());
+ MOCK_CONST_METHOD3(GetSavedApplication,
+ bool(const std::string& policy_app_id,
+ const std::string& device_id,
+ smart_objects::SmartObject& saved_app));
+ MOCK_METHOD2(RemoveApplicationFromSaved,
+ bool(const std::string& policy_app_id,
+ const std::string& device_id));
+ MOCK_CONST_METHOD0(GetIgnOffTime, uint32_t());
+ MOCK_CONST_METHOD2(IsApplicationSaved,
+ ssize_t(const std::string& policy_app_id,
+ const std::string& device_id));
+ MOCK_CONST_METHOD1(GetDataForLoadResumeData,
+ void(smart_objects::SmartObject& saved_data));
+ MOCK_METHOD3(UpdateHmiLevel,
+ void(const std::string& policy_app_id,
+ const std::string& device_id,
+ mobile_apis::HMILevel::eType hmi_level));
+ MOCK_METHOD0(Init, bool());
+ MOCK_METHOD2(DropAppDataResumption,
+ bool(const std::string& device_id, const std::string& app_id));
+ MOCK_METHOD0(Persist, void());
+};
+
+} // namespace resumption_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_RESUMPTION_DATA_MOCK_H_
diff --git a/src/components/application_manager/test/include/application_manager/resumption_data_test.h b/src/components/application_manager/test/include/application_manager/resumption_data_test.h
new file mode 100644
index 0000000000..b648b8ab82
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/resumption_data_test.h
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_RESUMPTION_DATA_TEST_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_RESUMPTION_DATA_TEST_H_
+
+#include <string>
+#include <algorithm>
+#include "gtest/gtest.h"
+#include "application_manager/usage_statistics.h"
+#include "application_manager/mock_application.h"
+#include "application_manager/mock_application_manager.h"
+#include "utils/data_accessor.h"
+#include "config_profile/profile.h"
+#include "application_manager/policies/policy_handler.h"
+#include "application_manager/state_controller.h"
+#include "application_manager/resumption/resume_ctrl.h"
+#include "application_manager/event_engine/event_dispatcher.h"
+#include "application_manager/mock_application_manager_settings.h"
+
+namespace test {
+namespace components {
+namespace resumption_test {
+
+using ::testing::NiceMock;
+namespace am = application_manager;
+namespace sm = smart_objects;
+using namespace Json;
+
+using namespace resumption;
+using namespace mobile_apis;
+
+class ResumptionDataTest : public ::testing::Test {
+ protected:
+ ResumptionDataTest()
+ : kCountOfCommands_(5u)
+ , kCountOfChoice_(2u)
+ , kCountOfChoiceSets_(4u)
+ , kCountOfSubmenues_(3u)
+ , kCountOfFiles_(8u)
+ , kCountOfVrhelptitle_(2u)
+ , kMacAddress_("12345") {}
+ // Check structure in saved application
+ void CheckSavedApp(sm::SmartObject& saved_data);
+ // Set data for resumption
+ virtual void PrepareData();
+ utils::SharedPtr<NiceMock<application_manager_test::MockApplication>>
+ app_mock;
+
+ profile::Profile profile_;
+ HMILevel::eType hmi_level_;
+ size_t app_id_;
+ size_t hmi_app_id_;
+ std::string policy_app_id_;
+ size_t ign_off_count_;
+ const size_t tts_chunks_count = 4;
+
+ size_t grammar_id_;
+ std::string hash_;
+ bool is_audio_;
+ const connection_handler::DeviceHandle device_handle_ = 10;
+
+ sm::SmartObject* help_prompt_;
+ sm::SmartObject* timeout_prompt_;
+ sm::SmartObject* vr_help_;
+ sm::SmartObject* vr_help_title_;
+ sm::SmartObject* vr_synonyms_;
+ sm::SmartObject* keyboard_props_;
+ sm::SmartObject* menu_title_;
+ sm::SmartObject* menu_icon_;
+
+ void SetCommands();
+ void SetSubmenues();
+ void SetChoiceSet();
+ void SetAppFiles();
+ void SetGlobalProporties();
+ void SetKeyboardProperties();
+ void SetMenuTitleAndIcon();
+ void SetHelpAndTimeoutPrompt();
+ void SetVRHelpTitle();
+ void SetSubscriptions();
+
+ void CheckCommands(sm::SmartObject& res_list);
+ void CheckGlobalProporties(sm::SmartObject& res_list);
+ void CheckSubmenues(sm::SmartObject& res_list);
+ void CheckChoiceSet(sm::SmartObject& res_list);
+ void CheckAppFiles(sm::SmartObject& res_list);
+ void CheckKeyboardProperties(sm::SmartObject& res_list);
+ void CheckMenuTitle(sm::SmartObject& res_list);
+ void CheckMenuIcon(sm::SmartObject& res_list);
+ void CheckHelpPrompt(sm::SmartObject& res_list);
+ void CheckTimeoutPrompt(sm::SmartObject& res_list);
+ void CheckVRHelp(NsSmartDeviceLink::NsSmartObjects::SmartObject& res_list);
+ void CheckVRTitle(sm::SmartObject& res_list);
+ void CheckSubscriptions(sm::SmartObject& res_list);
+
+ const size_t kCountOfCommands_;
+ const size_t kCountOfChoice_;
+ const size_t kCountOfChoiceSets_;
+ const size_t kCountOfSubmenues_;
+ const size_t kCountOfFiles_;
+ const size_t kCountOfVrhelptitle_;
+ const std::string kMacAddress_;
+
+ am::CommandsMap test_commands_map;
+ am::SubMenuMap test_submenu_map;
+ am::ChoiceSetMap test_choiceset_map;
+ am::AppFilesMap app_files_map_;
+
+ am::ButtonSubscriptions btn_subscr;
+ am::VehicleInfoSubscriptions ivi;
+
+ sync_primitives::Lock sublock_;
+ sync_primitives::Lock comlock_;
+ sync_primitives::Lock setlock_;
+ sync_primitives::Lock btnlock_;
+ sync_primitives::Lock ivilock_;
+ application_manager_test::MockApplicationManagerSettings
+ mock_application_manager_settings_;
+ application_manager_test::MockApplicationManager mock_application_manager_;
+};
+
+} // namespace resumption_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_RESUMPTION_DATA_TEST_H_
diff --git a/src/components/application_manager/test/include/application_manager/statistics_manager_mock.h b/src/components/application_manager/test/include/application_manager/statistics_manager_mock.h
new file mode 100644
index 0000000000..cff4194118
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/statistics_manager_mock.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATISTICS_MANAGER_MOCK_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATISTICS_MANAGER_MOCK_H_
+
+#include <string>
+#include "gmock/gmock.h"
+#include "policy/usage_statistics/statistics_manager.h"
+
+namespace test {
+namespace components {
+namespace state_controller_test {
+
+namespace us = usage_statistics;
+
+class MockStatisticsManager : public us::StatisticsManager {
+ public:
+ MOCK_METHOD1(Increment, void(us::GlobalCounterId));
+ MOCK_METHOD2(Increment, void(const std::string&, us::AppCounterId));
+ MOCK_METHOD3(Set,
+ void(const std::string&, us::AppInfoId, const std::string&));
+ MOCK_METHOD3(Add, void(const std::string&, us::AppStopwatchId, int32_t));
+};
+
+} // namespace state_controller_test
+}
+}
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATISTICS_MANAGER_MOCK_H_
diff --git a/src/components/application_manager/test/include/application_manager/test_resumption_data_db.h b/src/components/application_manager/test/include/application_manager/test_resumption_data_db.h
new file mode 100644
index 0000000000..e10f60afac
--- /dev/null
+++ b/src/components/application_manager/test/include/application_manager/test_resumption_data_db.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_TEST_RESUMPTION_DATA_DB_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_TEST_RESUMPTION_DATA_DB_H_
+
+#include "utils/sqlite_wrapper/sql_database.h"
+#include "application_manager/resumption/resumption_data_db.h"
+#include "application_manager/mock_application_manager_settings.h"
+#include "application_manager/mock_application_manager.h"
+
+using ::resumption::ResumptionDataDB;
+
+namespace test {
+namespace components {
+namespace resumption_test {
+
+class TestResumptionDataDB : public ResumptionDataDB {
+ public:
+ utils::dbms::SQLDatabase* get_db_handle() {
+ return db();
+ }
+
+ application_manager_test::MockApplicationManager mock_application_manager_;
+ TestResumptionDataDB(DbStorage db_storage)
+ : ResumptionDataDB(db_storage, mock_application_manager_) {}
+};
+
+} // namespace resumption_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_TEST_RESUMPTION_DATA_DB_H_
diff --git a/src/components/application_manager/test/message_helper/CMakeLists.txt b/src/components/application_manager/test/message_helper/CMakeLists.txt
new file mode 100755
index 0000000000..bfc0228bbb
--- /dev/null
+++ b/src/components/application_manager/test/message_helper/CMakeLists.txt
@@ -0,0 +1,61 @@
+# Copyright (c) 2015, Ford Motor Company
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer.
+#
+# Redistributions in binary form must reproduce the above copyright notice,
+# this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided with the
+# distribution.
+#
+# Neither the name of the Ford Motor Company nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+
+if(BUILD_TESTS)
+
+set(appMain_DIR ${CMAKE_SOURCE_DIR}/src/appMain)
+
+include_directories(
+ ${GMOCK_INCLUDE_DIRECTORY}
+ ${COMPONENTS_DIR}/application_manager/test/message_helper/include
+ ${COMPONENTS_DIR}/application_manager/test/state_controller/include
+ ${COMPONENTS_DIR}/include
+ ${COMPONENTS_DIR}
+)
+
+set(LIBRARIES
+ gmock
+ ApplicationManager
+ MessageHelper
+ jsoncpp
+ connectionHandler
+ MediaManager
+ Resumption
+ ProtocolHandler
+ Utils
+)
+
+set(SOURCES
+ #message_helper_test.cc
+)
+
+create_test("message_helper_test" "${SOURCES}" "${LIBRARIES}")
+
+endif()
diff --git a/src/components/application_manager/test/message_helper/CMakeLists.txt.user b/src/components/application_manager/test/message_helper/CMakeLists.txt.user
new file mode 100755
index 0000000000..e7522c1793
--- /dev/null
+++ b/src/components/application_manager/test/message_helper/CMakeLists.txt.user
@@ -0,0 +1,189 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE QtCreatorProject>
+<!-- Written by QtCreator 3.5.1, 2015-11-19T12:59:06. -->
+<qtcreator>
+ <data>
+ <variable>EnvironmentId</variable>
+ <value type="QByteArray">{6965f0e8-9b58-4b26-8426-81354d6c3400}</value>
+ </data>
+ <data>
+ <variable>ProjectExplorer.Project.ActiveTarget</variable>
+ <value type="int">0</value>
+ </data>
+ <data>
+ <variable>ProjectExplorer.Project.EditorSettings</variable>
+ <valuemap type="QVariantMap">
+ <value type="bool" key="EditorConfiguration.AutoIndent">true</value>
+ <value type="bool" key="EditorConfiguration.AutoSpacesForTabs">false</value>
+ <value type="bool" key="EditorConfiguration.CamelCaseNavigation">true</value>
+ <valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.0">
+ <value type="QString" key="language">Cpp</value>
+ <valuemap type="QVariantMap" key="value">
+ <value type="QByteArray" key="CurrentPreferences">CppGlobal</value>
+ </valuemap>
+ </valuemap>
+ <valuemap type="QVariantMap" key="EditorConfiguration.CodeStyle.1">
+ <value type="QString" key="language">QmlJS</value>
+ <valuemap type="QVariantMap" key="value">
+ <value type="QByteArray" key="CurrentPreferences">QmlJSGlobal</value>
+ </valuemap>
+ </valuemap>
+ <value type="int" key="EditorConfiguration.CodeStyle.Count">2</value>
+ <value type="QByteArray" key="EditorConfiguration.Codec">UTF-8</value>
+ <value type="bool" key="EditorConfiguration.ConstrainTooltips">false</value>
+ <value type="int" key="EditorConfiguration.IndentSize">4</value>
+ <value type="bool" key="EditorConfiguration.KeyboardTooltips">false</value>
+ <value type="int" key="EditorConfiguration.MarginColumn">80</value>
+ <value type="bool" key="EditorConfiguration.MouseHiding">true</value>
+ <value type="bool" key="EditorConfiguration.MouseNavigation">true</value>
+ <value type="int" key="EditorConfiguration.PaddingMode">1</value>
+ <value type="bool" key="EditorConfiguration.ScrollWheelZooming">true</value>
+ <value type="bool" key="EditorConfiguration.ShowMargin">false</value>
+ <value type="int" key="EditorConfiguration.SmartBackspaceBehavior">0</value>
+ <value type="bool" key="EditorConfiguration.SpacesForTabs">true</value>
+ <value type="int" key="EditorConfiguration.TabKeyBehavior">0</value>
+ <value type="int" key="EditorConfiguration.TabSize">8</value>
+ <value type="bool" key="EditorConfiguration.UseGlobal">true</value>
+ <value type="int" key="EditorConfiguration.Utf8BomBehavior">1</value>
+ <value type="bool" key="EditorConfiguration.addFinalNewLine">true</value>
+ <value type="bool" key="EditorConfiguration.cleanIndentation">true</value>
+ <value type="bool" key="EditorConfiguration.cleanWhitespace">true</value>
+ <value type="bool" key="EditorConfiguration.inEntireDocument">false</value>
+ </valuemap>
+ </data>
+ <data>
+ <variable>ProjectExplorer.Project.PluginSettings</variable>
+ <valuemap type="QVariantMap"/>
+ </data>
+ <data>
+ <variable>ProjectExplorer.Project.Target.0</variable>
+ <valuemap type="QVariantMap">
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Desktop Qt 5.5.1 GCC 64bit</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Desktop Qt 5.5.1 GCC 64bit</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">qt.55.gcc_64_kit</value>
+ <value type="int" key="ProjectExplorer.Target.ActiveBuildConfiguration">0</value>
+ <value type="int" key="ProjectExplorer.Target.ActiveDeployConfiguration">0</value>
+ <value type="int" key="ProjectExplorer.Target.ActiveRunConfiguration">0</value>
+ <valuemap type="QVariantMap" key="ProjectExplorer.Target.BuildConfiguration.0">
+ <value type="bool" key="CMakeProjectManager.CMakeBuildConfiguration.UseNinja">false</value>
+ <value type="QString" key="ProjectExplorer.BuildConfiguration.BuildDirectory">/home/oherasym/sdl_panasonic/src/components/application_manager/test/message_helper-build</value>
+ <valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
+ <valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
+ <value type="QString" key="CMakeProjectManager.MakeStep.AdditionalArguments"></value>
+ <valuelist type="QVariantList" key="CMakeProjectManager.MakeStep.BuildTargets"/>
+ <value type="bool" key="CMakeProjectManager.MakeStep.Clean">false</value>
+ <value type="QString" key="CMakeProjectManager.MakeStep.MakeCommand"></value>
+ <value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">CMakeProjectManager.MakeStep</value>
+ </valuemap>
+ <value type="int" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Build</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Build</value>
+ </valuemap>
+ <valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.1">
+ <valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
+ <value type="QString" key="CMakeProjectManager.MakeStep.AdditionalArguments">clean</value>
+ <valuelist type="QVariantList" key="CMakeProjectManager.MakeStep.BuildTargets"/>
+ <value type="bool" key="CMakeProjectManager.MakeStep.Clean">true</value>
+ <value type="QString" key="CMakeProjectManager.MakeStep.MakeCommand"></value>
+ <value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">CMakeProjectManager.MakeStep</value>
+ </valuemap>
+ <value type="int" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Clean</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Clean</value>
+ </valuemap>
+ <value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">2</value>
+ <value type="bool" key="ProjectExplorer.BuildConfiguration.ClearSystemEnvironment">false</value>
+ <valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">all</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">CMakeProjectManager.CMakeBuildConfiguration</value>
+ </valuemap>
+ <value type="int" key="ProjectExplorer.Target.BuildConfigurationCount">1</value>
+ <valuemap type="QVariantMap" key="ProjectExplorer.Target.DeployConfiguration.0">
+ <valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
+ <value type="int" key="ProjectExplorer.BuildStepList.StepsCount">0</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Deploy</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Deploy</value>
+ </valuemap>
+ <value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">1</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Deploy locally</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.DefaultDeployConfiguration</value>
+ </valuemap>
+ <value type="int" key="ProjectExplorer.Target.DeployConfigurationCount">1</value>
+ <valuemap type="QVariantMap" key="ProjectExplorer.Target.PluginSettings"/>
+ <valuemap type="QVariantMap" key="ProjectExplorer.Target.RunConfiguration.0">
+ <valuelist type="QVariantList" key="Analyzer.Valgrind.AddedSuppressionFiles"/>
+ <value type="bool" key="Analyzer.Valgrind.Callgrind.CollectBusEvents">false</value>
+ <value type="bool" key="Analyzer.Valgrind.Callgrind.CollectSystime">false</value>
+ <value type="bool" key="Analyzer.Valgrind.Callgrind.EnableBranchSim">false</value>
+ <value type="bool" key="Analyzer.Valgrind.Callgrind.EnableCacheSim">false</value>
+ <value type="bool" key="Analyzer.Valgrind.Callgrind.EnableEventToolTips">true</value>
+ <value type="double" key="Analyzer.Valgrind.Callgrind.MinimumCostRatio">0.01</value>
+ <value type="double" key="Analyzer.Valgrind.Callgrind.VisualisationMinimumCostRatio">10</value>
+ <value type="bool" key="Analyzer.Valgrind.FilterExternalIssues">true</value>
+ <value type="int" key="Analyzer.Valgrind.LeakCheckOnFinish">1</value>
+ <value type="int" key="Analyzer.Valgrind.NumCallers">25</value>
+ <valuelist type="QVariantList" key="Analyzer.Valgrind.RemovedSuppressionFiles"/>
+ <value type="int" key="Analyzer.Valgrind.SelfModifyingCodeDetection">1</value>
+ <value type="bool" key="Analyzer.Valgrind.Settings.UseGlobalSettings">true</value>
+ <value type="bool" key="Analyzer.Valgrind.ShowReachable">false</value>
+ <value type="bool" key="Analyzer.Valgrind.TrackOrigins">true</value>
+ <value type="QString" key="Analyzer.Valgrind.ValgrindExecutable">valgrind</value>
+ <valuelist type="QVariantList" key="Analyzer.Valgrind.VisibleErrorKinds">
+ <value type="int">0</value>
+ <value type="int">1</value>
+ <value type="int">2</value>
+ <value type="int">3</value>
+ <value type="int">4</value>
+ <value type="int">5</value>
+ <value type="int">6</value>
+ <value type="int">7</value>
+ <value type="int">8</value>
+ <value type="int">9</value>
+ <value type="int">10</value>
+ <value type="int">11</value>
+ <value type="int">12</value>
+ <value type="int">13</value>
+ <value type="int">14</value>
+ </valuelist>
+ <value type="int" key="PE.EnvironmentAspect.Base">2</value>
+ <valuelist type="QVariantList" key="PE.EnvironmentAspect.Changes"/>
+ <value type="QString" key="ProjectExplorer.CustomExecutableRunConfiguration.Arguments"></value>
+ <value type="QString" key="ProjectExplorer.CustomExecutableRunConfiguration.Executable"></value>
+ <value type="QString" key="ProjectExplorer.CustomExecutableRunConfiguration.WorkingDirectory">%{buildDir}</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Custom Executable</value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
+ <value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.CustomExecutableRunConfiguration</value>
+ <value type="uint" key="RunConfiguration.QmlDebugServerPort">3768</value>
+ <value type="bool" key="RunConfiguration.UseCppDebugger">false</value>
+ <value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value>
+ <value type="bool" key="RunConfiguration.UseMultiProcess">false</value>
+ <value type="bool" key="RunConfiguration.UseQmlDebugger">false</value>
+ <value type="bool" key="RunConfiguration.UseQmlDebuggerAuto">true</value>
+ </valuemap>
+ <value type="int" key="ProjectExplorer.Target.RunConfigurationCount">1</value>
+ </valuemap>
+ </data>
+ <data>
+ <variable>ProjectExplorer.Project.TargetCount</variable>
+ <value type="int">1</value>
+ </data>
+ <data>
+ <variable>ProjectExplorer.Project.Updater.FileVersion</variable>
+ <value type="int">18</value>
+ </data>
+ <data>
+ <variable>Version</variable>
+ <value type="int">18</value>
+ </data>
+</qtcreator>
diff --git a/src/components/application_manager/test/message_helper/message_helper_test.cc b/src/components/application_manager/test/message_helper/message_helper_test.cc
new file mode 100644
index 0000000000..77e791dc82
--- /dev/null
+++ b/src/components/application_manager/test/message_helper/message_helper_test.cc
@@ -0,0 +1,906 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <string>
+#include <vector>
+
+#include "gmock/gmock.h"
+#include "utils/macro.h"
+#include "utils/make_shared.h"
+#include "application_manager/policies/policy_handler.h"
+#include "application_manager/test/resumption/include/application_mock.h"
+#include "utils/custom_string.h"
+#include "policy/mock_policy_settings.h"
+#include "application_manager/policies/policy_handler.h"
+#include "application_manager/mock_application_manager.h"
+#include "application_manager/event_engine/event_dispatcher.h"
+#include "application_manager/state_controller.h"
+#include "application_manager/resumption/resume_ctrl.h"
+
+namespace application_manager {
+namespace test {
+
+namespace HmiLanguage = hmi_apis::Common_Language;
+namespace HmiResults = hmi_apis::Common_Result;
+namespace MobileResults = mobile_apis::Result;
+
+typedef ::test::components::resumption_test::MockApplication AppMock;
+typedef utils::SharedPtr<AppMock> MockApplicationSharedPtr;
+typedef std::vector<std::string> StringArray;
+typedef ::application_manager::Application App;
+typedef utils::SharedPtr<App> ApplicationSharedPtr;
+
+using testing::AtLeast;
+using testing::ReturnRefOfCopy;
+using testing::ReturnRef;
+using testing::Return;
+
+TEST(MessageHelperTestCreate,
+ CreateBlockedByPoliciesResponse_SmartObject_Equal) {
+ mobile_apis::FunctionID::eType function_id =
+ mobile_apis::FunctionID::eType::AddCommandID;
+ mobile_apis::Result::eType result = mobile_apis::Result::eType::ABORTED;
+ uint32_t correlation_id = 0;
+ uint32_t connection_key = 0;
+ bool success = false;
+
+ smart_objects::SmartObjectSPtr ptr =
+ MessageHelper::CreateBlockedByPoliciesResponse(
+ function_id, result, correlation_id, connection_key);
+
+ EXPECT_TRUE(ptr);
+
+ smart_objects::SmartObject& obj = *ptr;
+
+ EXPECT_EQ(function_id, obj[strings::params][strings::function_id].asInt());
+ EXPECT_EQ(kResponse, obj[strings::params][strings::message_type].asInt());
+ EXPECT_EQ(success, obj[strings::msg_params][strings::success].asBool());
+ EXPECT_EQ(result, obj[strings::msg_params][strings::result_code].asInt());
+ EXPECT_EQ(correlation_id,
+ obj[strings::params][strings::correlation_id].asUInt());
+ EXPECT_EQ(connection_key,
+ obj[strings::params][strings::connection_key].asUInt());
+ EXPECT_EQ(kV2, obj[strings::params][strings::protocol_version].asInt());
+}
+
+TEST(MessageHelperTestCreate, CreateSetAppIcon_SendNullPathImagetype_Equal) {
+ std::string path_to_icon = "";
+ uint32_t app_id = 0;
+ smart_objects::SmartObjectSPtr ptr =
+ MessageHelper::CreateSetAppIcon(path_to_icon, app_id);
+
+ EXPECT_TRUE(ptr);
+
+ smart_objects::SmartObject& obj = *ptr;
+
+ int image_type = static_cast<int>(mobile_api::ImageType::DYNAMIC);
+
+ EXPECT_EQ(path_to_icon,
+ obj[strings::sync_file_name][strings::value].asString());
+ EXPECT_EQ(image_type,
+ obj[strings::sync_file_name][strings::image_type].asInt());
+ EXPECT_EQ(app_id, obj[strings::app_id].asUInt());
+}
+
+TEST(MessageHelperTestCreate, CreateSetAppIcon_SendPathImagetype_Equal) {
+ std::string path_to_icon = "/qwe/qwe/";
+ uint32_t app_id = 10;
+ smart_objects::SmartObjectSPtr ptr =
+ MessageHelper::CreateSetAppIcon(path_to_icon, app_id);
+
+ EXPECT_TRUE(ptr);
+
+ smart_objects::SmartObject& obj = *ptr;
+
+ int image_type = static_cast<int>(mobile_api::ImageType::DYNAMIC);
+
+ EXPECT_EQ(path_to_icon,
+ obj[strings::sync_file_name][strings::value].asString());
+ EXPECT_EQ(image_type,
+ obj[strings::sync_file_name][strings::image_type].asInt());
+ EXPECT_EQ(app_id, obj[strings::app_id].asUInt());
+}
+
+TEST(MessageHelperTestCreate,
+ CreateGlobalPropertiesRequestsToHMI_SmartObject_EmptyList) {
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<MockApplication>();
+ EXPECT_CALL(*appSharedMock, vr_help_title()).Times(AtLeast(1));
+ EXPECT_CALL(*appSharedMock, vr_help()).Times(AtLeast(1));
+ EXPECT_CALL(*appSharedMock, help_prompt()).Times(AtLeast(1));
+ EXPECT_CALL(*appSharedMock, timeout_prompt()).Times(AtLeast(1));
+
+ smart_objects::SmartObjectList ptr =
+ MessageHelper::CreateGlobalPropertiesRequestsToHMI(appSharedMock, 0u);
+
+ EXPECT_TRUE(ptr.empty());
+}
+
+TEST(MessageHelperTestCreate,
+ CreateGlobalPropertiesRequestsToHMI_SmartObject_NotEmpty) {
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ smart_objects::SmartObjectSPtr objPtr =
+ MakeShared<smart_objects::SmartObject>();
+
+ (*objPtr)[0][strings::vr_help_title] = "111";
+ (*objPtr)[1][strings::vr_help] = "222";
+ (*objPtr)[2][strings::keyboard_properties] = "333";
+ (*objPtr)[3][strings::menu_title] = "444";
+ (*objPtr)[4][strings::menu_icon] = "555";
+ (*objPtr)[5][strings::help_prompt] = "666";
+ (*objPtr)[6][strings::timeout_prompt] = "777";
+
+ EXPECT_CALL(*appSharedMock, vr_help_title())
+ .Times(AtLeast(3))
+ .WillRepeatedly(Return(&(*objPtr)[0]));
+ EXPECT_CALL(*appSharedMock, vr_help())
+ .Times(AtLeast(2))
+ .WillRepeatedly(Return(&(*objPtr)[1]));
+ EXPECT_CALL(*appSharedMock, help_prompt())
+ .Times(AtLeast(3))
+ .WillRepeatedly(Return(&(*objPtr)[5]));
+ EXPECT_CALL(*appSharedMock, timeout_prompt())
+ .Times(AtLeast(2))
+ .WillRepeatedly(Return(&(*objPtr)[6]));
+ EXPECT_CALL(*appSharedMock, keyboard_props())
+ .Times(AtLeast(2))
+ .WillRepeatedly(Return(&(*objPtr)[2]));
+ EXPECT_CALL(*appSharedMock, menu_title())
+ .Times(AtLeast(2))
+ .WillRepeatedly(Return(&(*objPtr)[3]));
+ EXPECT_CALL(*appSharedMock, menu_icon())
+ .Times(AtLeast(2))
+ .WillRepeatedly(Return(&(*objPtr)[4]));
+ EXPECT_CALL(*appSharedMock, app_id()).WillRepeatedly(Return(0));
+
+ smart_objects::SmartObjectList ptr =
+ MessageHelper::CreateGlobalPropertiesRequestsToHMI(appSharedMock, 0u);
+
+ EXPECT_FALSE(ptr.empty());
+
+ smart_objects::SmartObject& first = *ptr[0];
+ smart_objects::SmartObject& second = *ptr[1];
+
+ EXPECT_EQ((*objPtr)[0], first[strings::msg_params][strings::vr_help_title]);
+ EXPECT_EQ((*objPtr)[1], first[strings::msg_params][strings::vr_help]);
+ EXPECT_EQ((*objPtr)[2],
+ first[strings::msg_params][strings::keyboard_properties]);
+ EXPECT_EQ((*objPtr)[3], first[strings::msg_params][strings::menu_title]);
+ EXPECT_EQ((*objPtr)[4], first[strings::msg_params][strings::menu_icon]);
+ EXPECT_EQ((*objPtr)[5], second[strings::msg_params][strings::help_prompt]);
+ EXPECT_EQ((*objPtr)[6], second[strings::msg_params][strings::timeout_prompt]);
+}
+
+TEST(MessageHelperTestCreate, CreateShowRequestToHMI_SendSmartObject_Equal) {
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+
+ smart_objects::SmartObjectSPtr smartObjectPtr =
+ utils::MakeShared<smart_objects::SmartObject>();
+
+ const smart_objects::SmartObject& object = *smartObjectPtr;
+
+ EXPECT_CALL(*appSharedMock, show_command())
+ .Times(AtLeast(2))
+ .WillRepeatedly(Return(&object));
+
+ smart_objects::SmartObjectList ptr =
+ MessageHelper::CreateShowRequestToHMI(appSharedMock, 0u);
+
+ EXPECT_FALSE(ptr.empty());
+
+ smart_objects::SmartObject& obj = *ptr[0];
+
+ int function_id = static_cast<int>(hmi_apis::FunctionID::UI_Show);
+
+ EXPECT_EQ(function_id, obj[strings::params][strings::function_id].asInt());
+ EXPECT_EQ(*smartObjectPtr, obj[strings::msg_params]);
+}
+
+TEST(MessageHelperTestCreate,
+ CreateAddCommandRequestToHMI_SendSmartObject_Empty) {
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<MockApplication>();
+ ::application_manager::CommandsMap vis;
+ DataAccessor<application_manager::CommandsMap> data_accessor(vis, true);
+
+ EXPECT_CALL(*appSharedMock, commands_map()).WillOnce(Return(data_accessor));
+ application_manager_test::MockApplicationManager mock_application_manager;
+ smart_objects::SmartObjectList ptr =
+ MessageHelper::CreateAddCommandRequestToHMI(appSharedMock,
+ mock_application_manager);
+
+ EXPECT_TRUE(ptr.empty());
+}
+
+TEST(MessageHelperTestCreate,
+ CreateAddCommandRequestToHMI_SendSmartObject_Equal) {
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ CommandsMap vis;
+ DataAccessor<CommandsMap> data_accessor(vis, true);
+ smart_objects::SmartObjectSPtr smartObjectPtr =
+ utils::MakeShared<smart_objects::SmartObject>();
+
+ smart_objects::SmartObject& object = *smartObjectPtr;
+
+ object[strings::menu_params] = 1;
+ object[strings::cmd_icon] = 1;
+ object[strings::cmd_icon][strings::value] = "10";
+
+ vis.insert(std::pair<uint32_t, smart_objects::SmartObject*>(5, &object));
+
+ EXPECT_CALL(*appSharedMock, commands_map()).WillOnce(Return(data_accessor));
+ EXPECT_CALL(*appSharedMock, app_id()).WillOnce(Return(1u));
+ application_manager_test::MockApplicationManager mock_application_manager;
+ smart_objects::SmartObjectList ptr =
+ MessageHelper::CreateAddCommandRequestToHMI(appSharedMock,
+ mock_application_manager);
+
+ EXPECT_FALSE(ptr.empty());
+
+ smart_objects::SmartObject& obj = *ptr[0];
+
+ int function_id = static_cast<int>(hmi_apis::FunctionID::UI_AddCommand);
+
+ EXPECT_EQ(function_id, obj[strings::params][strings::function_id].asInt());
+ EXPECT_EQ(1u, obj[strings::msg_params][strings::app_id].asUInt());
+ EXPECT_EQ(5, obj[strings::msg_params][strings::cmd_id].asInt());
+ EXPECT_EQ(object[strings::menu_params],
+ obj[strings::msg_params][strings::menu_params]);
+ EXPECT_EQ(object[strings::cmd_icon],
+ obj[strings::msg_params][strings::cmd_icon]);
+ EXPECT_EQ(
+ "10",
+ obj[strings::msg_params][strings::cmd_icon][strings::value].asString());
+}
+
+TEST(MessageHelperTestCreate,
+ CreateAddVRCommandRequestFromChoiceToHMI_SendEmptyData_EmptyList) {
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ application_manager::ChoiceSetMap vis;
+ DataAccessor< ::application_manager::ChoiceSetMap> data_accessor(vis, true);
+
+ EXPECT_CALL(*appSharedMock, choice_set_map()).WillOnce(Return(data_accessor));
+ application_manager_test::MockApplicationManager mock_application_manager;
+ smart_objects::SmartObjectList ptr =
+ MessageHelper::CreateAddVRCommandRequestFromChoiceToHMI(
+ appSharedMock, mock_application_manager);
+
+ EXPECT_TRUE(ptr.empty());
+}
+
+TEST(MessageHelperTestCreate,
+ CreateAddVRCommandRequestFromChoiceToHMI_SendObject_EqualList) {
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ application_manager::ChoiceSetMap vis;
+ DataAccessor< ::application_manager::ChoiceSetMap> data_accessor(vis, true);
+ smart_objects::SmartObjectSPtr smartObjectPtr =
+ utils::MakeShared<smart_objects::SmartObject>();
+
+ smart_objects::SmartObject& object = *smartObjectPtr;
+
+ object[strings::choice_set] = "10";
+ object[strings::grammar_id] = 111;
+ object[strings::choice_set][0][strings::choice_id] = 1;
+ object[strings::choice_set][0][strings::vr_commands] = 2;
+
+ vis.insert(std::pair<uint32_t, smart_objects::SmartObject*>(5, &object));
+ vis.insert(std::pair<uint32_t, smart_objects::SmartObject*>(6, &object));
+ vis.insert(std::pair<uint32_t, smart_objects::SmartObject*>(7, &object));
+ vis.insert(std::pair<uint32_t, smart_objects::SmartObject*>(8, &object));
+ vis.insert(std::pair<uint32_t, smart_objects::SmartObject*>(9, &object));
+
+ EXPECT_CALL(*appSharedMock, choice_set_map()).WillOnce(Return(data_accessor));
+ EXPECT_CALL(*appSharedMock, app_id())
+ .Times(AtLeast(5))
+ .WillRepeatedly(Return(1u));
+ application_manager_test::MockApplicationManager mock_application_manager;
+ smart_objects::SmartObjectList ptr =
+ MessageHelper::CreateAddVRCommandRequestFromChoiceToHMI(
+ appSharedMock, mock_application_manager);
+
+ EXPECT_FALSE(ptr.empty());
+
+ int function_id = static_cast<int>(hmi_apis::FunctionID::VR_AddCommand);
+ int type = static_cast<int>(hmi_apis::Common_VRCommandType::Choice);
+
+ smart_objects::SmartObject& obj = *ptr[0];
+
+ EXPECT_EQ(function_id, obj[strings::params][strings::function_id].asInt());
+ EXPECT_EQ(1u, obj[strings::msg_params][strings::app_id].asUInt());
+ EXPECT_EQ(111u, obj[strings::msg_params][strings::grammar_id].asUInt());
+ EXPECT_EQ(object[strings::choice_set][0][strings::choice_id],
+ obj[strings::msg_params][strings::cmd_id]);
+ EXPECT_EQ(object[strings::choice_set][0][strings::vr_commands],
+ obj[strings::msg_params][strings::vr_commands]);
+ EXPECT_EQ(type, obj[strings::msg_params][strings::type].asInt());
+}
+
+TEST(MessageHelperTestCreate, CreateAddSubMenuRequestToHMI_SendObject_Equal) {
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ application_manager::SubMenuMap vis;
+ DataAccessor< ::application_manager::SubMenuMap> data_accessor(vis, true);
+ smart_objects::SmartObjectSPtr smartObjectPtr =
+ utils::MakeShared<smart_objects::SmartObject>();
+
+ smart_objects::SmartObject& object = *smartObjectPtr;
+
+ object[strings::position] = 1;
+ object[strings::menu_name] = 1;
+
+ vis.insert(std::pair<uint32_t, smart_objects::SmartObject*>(5, &object));
+
+ EXPECT_CALL(*appSharedMock, sub_menu_map()).WillOnce(Return(data_accessor));
+ EXPECT_CALL(*appSharedMock, app_id()).Times(AtLeast(1)).WillOnce(Return(1u));
+
+ const uint32_t cor_id = 0u;
+ smart_objects::SmartObjectList ptr =
+ MessageHelper::CreateAddSubMenuRequestToHMI(appSharedMock, cor_id);
+
+ EXPECT_FALSE(ptr.empty());
+
+ smart_objects::SmartObject& obj = *ptr[0];
+
+ int function_id = static_cast<int>(hmi_apis::FunctionID::UI_AddSubMenu);
+
+ EXPECT_EQ(function_id, obj[strings::params][strings::function_id].asInt());
+ EXPECT_EQ(5, obj[strings::msg_params][strings::menu_id].asInt());
+ EXPECT_EQ(1,
+ obj[strings::msg_params][strings::menu_params][strings::position]
+ .asInt());
+ EXPECT_EQ(1,
+ obj[strings::msg_params][strings::menu_params][strings::menu_name]
+ .asInt());
+ EXPECT_EQ(1u, obj[strings::msg_params][strings::app_id].asUInt());
+}
+
+TEST(MessageHelperTestCreate,
+ CreateAddSubMenuRequestToHMI_SendEmptyMap_EmptySmartObjectList) {
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ application_manager::SubMenuMap vis;
+ DataAccessor< ::application_manager::SubMenuMap> data_accessor(vis, true);
+
+ EXPECT_CALL(*appSharedMock, sub_menu_map()).WillOnce(Return(data_accessor));
+
+ const uint32_t cor_id = 0u;
+ smart_objects::SmartObjectList ptr =
+ MessageHelper::CreateAddSubMenuRequestToHMI(appSharedMock, cor_id);
+
+ EXPECT_TRUE(ptr.empty());
+}
+
+TEST(MessageHelperTestCreate, CreateNegativeResponse_SendSmartObject_Equal) {
+ uint32_t connection_key = 111;
+ int32_t function_id = 222;
+ uint32_t correlation_id = 333u;
+ int32_t result_code = 0;
+
+ smart_objects::SmartObjectSPtr ptr = MessageHelper::CreateNegativeResponse(
+ connection_key, function_id, correlation_id, result_code);
+
+ EXPECT_TRUE(ptr);
+
+ smart_objects::SmartObject& obj = *ptr;
+
+ int objFunction_id = obj[strings::params][strings::function_id].asInt();
+ uint32_t objCorrelation_id =
+ obj[strings::params][strings::correlation_id].asUInt();
+ int objResult_code = obj[strings::msg_params][strings::result_code].asInt();
+ uint32_t objConnection_key =
+ obj[strings::params][strings::connection_key].asUInt();
+
+ int message_type = static_cast<int>(mobile_apis::messageType::response);
+ int protocol_type =
+ static_cast<int>(commands::CommandImpl::mobile_protocol_type_);
+ int protocol_version =
+ static_cast<int>(commands::CommandImpl::protocol_version_);
+ bool success = false;
+
+ EXPECT_EQ(function_id, objFunction_id);
+ EXPECT_EQ(message_type, obj[strings::params][strings::message_type].asInt());
+ EXPECT_EQ(protocol_type,
+ obj[strings::params][strings::protocol_type].asInt());
+ EXPECT_EQ(protocol_version,
+ obj[strings::params][strings::protocol_version].asInt());
+ EXPECT_EQ(correlation_id, objCorrelation_id);
+ EXPECT_EQ(result_code, objResult_code);
+ EXPECT_EQ(success, obj[strings::msg_params][strings::success].asBool());
+ EXPECT_EQ(connection_key, objConnection_key);
+}
+
+class MessageHelperTest : public ::testing::Test {
+ public:
+ MessageHelperTest()
+ : language_strings{"EN-US", "ES-MX", "FR-CA", "DE-DE", "ES-ES", "EN-GB",
+ "RU-RU", "TR-TR", "PL-PL", "FR-FR", "IT-IT", "SV-SE",
+ "PT-PT", "NL-NL", "EN-AU", "ZH-CN", "ZH-TW", "JA-JP",
+ "AR-SA", "KO-KR", "PT-BR", "CS-CZ", "DA-DK", "NO-NO",
+ "NL-BE", "EL-GR", "HU-HU", "FI-FI", "SK-SK"}
+ , hmi_result_strings{"SUCCESS",
+ "UNSUPPORTED_REQUEST",
+ "UNSUPPORTED_RESOURCE",
+ "DISALLOWED",
+ "REJECTED",
+ "ABORTED",
+ "IGNORED",
+ "RETRY",
+ "IN_USE",
+ "DATA_NOT_AVAILABLE",
+ "TIMED_OUT",
+ "INVALID_DATA",
+ "CHAR_LIMIT_EXCEEDED",
+ "INVALID_ID",
+ "DUPLICATE_NAME",
+ "APPLICATION_NOT_REGISTERED",
+ "WRONG_LANGUAGE",
+ "OUT_OF_MEMORY",
+ "TOO_MANY_PENDING_REQUESTS",
+ "NO_APPS_REGISTERED",
+ "NO_DEVICES_CONNECTED",
+ "WARNINGS",
+ "GENERIC_ERROR",
+ "USER_DISALLOWED",
+ "TRUNCATED_DATA"}
+ , mobile_result_strings{"SUCCESS",
+ "UNSUPPORTED_REQUEST",
+ "UNSUPPORTED_RESOURCE",
+ "DISALLOWED",
+ "REJECTED",
+ "ABORTED",
+ "IGNORED",
+ "RETRY",
+ "IN_USE",
+ "VEHICLE_DATA_NOT_AVAILABLE",
+ "TIMED_OUT",
+ "INVALID_DATA",
+ "CHAR_LIMIT_EXCEEDED",
+ "INVALID_ID",
+ "DUPLICATE_NAME",
+ "APPLICATION_NOT_REGISTERED",
+ "WRONG_LANGUAGE",
+ "OUT_OF_MEMORY",
+ "TOO_MANY_PENDING_REQUESTS",
+ "TOO_MANY_APPLICATIONS",
+ "APPLICATION_REGISTERED_ALREADY",
+ "WARNINGS",
+ "GENERIC_ERROR",
+ "USER_DISALLOWED",
+ "UNSUPPORTED_VERSION",
+ "VEHICLE_DATA_NOT_ALLOWED",
+ "FILE_NOT_FOUND",
+ "CANCEL_ROUTE",
+ "TRUNCATED_DATA",
+ "SAVED",
+ "INVALID_CERT",
+ "EXPIRED_CERT",
+ "RESUME_FAILED"}
+ , function_id_strings{"RESERVED",
+ "RegisterAppInterface",
+ "UnregisterAppInterface",
+ "SetGlobalProperties",
+ "ResetGlobalProperties",
+ "AddCommand",
+ "DeleteCommand",
+ "AddSubMenu",
+ "DeleteSubMenu",
+ "CreateInteractionChoiceSet",
+ "PerformInteraction",
+ "DeleteInteractionChoiceSet",
+ "Alert",
+ "Show",
+ "Speak",
+ "SetMediaClockTimer",
+ "PerformAudioPassThru",
+ "EndAudioPassThru",
+ "SubscribeButton",
+ "UnsubscribeButton",
+ "SubscribeVehicleData",
+ "UnsubscribeVehicleData",
+ "GetVehicleData",
+ "ReadDID",
+ "GetDTCs",
+ "ScrollableMessage",
+ "Slider",
+ "ShowConstantTBT",
+ "AlertManeuver",
+ "UpdateTurnList",
+ "ChangeRegistration",
+ "GenericResponse",
+ "PutFile",
+ "DeleteFile",
+ "ListFiles",
+ "SetAppIcon",
+ "SetDisplayLayout",
+ "DiagnosticMessage",
+ "SystemRequest",
+ "SendLocation",
+ "DialNumber"}
+ , events_id_strings{"OnHMIStatus",
+ "OnAppInterfaceUnregistered",
+ "OnButtonEvent",
+ "OnButtonPress",
+ "OnVehicleData",
+ "OnCommand",
+ "OnTBTClientState",
+ "OnDriverDistraction",
+ "OnPermissionsChange",
+ "OnAudioPassThru",
+ "OnLanguageChange",
+ "OnKeyboardInput",
+ "OnTouchEvent",
+ "OnSystemRequest",
+ "OnHashChange"}
+ , hmi_level_strings{"FULL", "LIMITED", "BACKGROUND", "NONE"}
+ , delta_from_functions_id(32768) {}
+
+ protected:
+ application_manager_test::MockApplicationManager mock_application_manager;
+ const StringArray language_strings;
+ const StringArray hmi_result_strings;
+ const StringArray mobile_result_strings;
+ const StringArray function_id_strings;
+ const StringArray events_id_strings;
+ const StringArray hmi_level_strings;
+
+ const size_t delta_from_functions_id;
+};
+
+TEST_F(MessageHelperTest,
+ CommonLanguageFromString_StringValueOfEnum_CorrectEType) {
+ HmiLanguage::eType enum_value;
+ HmiLanguage::eType enum_from_string_value;
+ // Check all languages >= 0
+ for (size_t array_index = 0; array_index < language_strings.size();
+ ++array_index) {
+ enum_value = static_cast<HmiLanguage::eType>(array_index);
+ enum_from_string_value =
+ MessageHelper::CommonLanguageFromString(language_strings[array_index]);
+ EXPECT_EQ(enum_value, enum_from_string_value);
+ }
+ // Check InvalidEnum == -1
+ enum_value = HmiLanguage::INVALID_ENUM;
+ enum_from_string_value = MessageHelper::CommonLanguageFromString("");
+ EXPECT_EQ(enum_value, enum_from_string_value);
+}
+
+TEST_F(MessageHelperTest,
+ CommonLanguageToString_ETypeValueOfEnum_CorrectString) {
+ std::string string_from_enum;
+ HmiLanguage::eType casted_enum;
+ // Check all languages >=0
+ for (size_t array_index = 0; array_index < language_strings.size();
+ ++array_index) {
+ casted_enum = static_cast<HmiLanguage::eType>(array_index);
+ string_from_enum = MessageHelper::CommonLanguageToString(casted_enum);
+ EXPECT_EQ(language_strings[array_index], string_from_enum);
+ }
+ // Check InvalidEnum == -1
+ string_from_enum =
+ MessageHelper::CommonLanguageToString(HmiLanguage::INVALID_ENUM);
+ EXPECT_EQ("", string_from_enum);
+}
+
+TEST_F(MessageHelperTest, ConvertEnumAPINoCheck_AnyEnumType_AnotherEnumType) {
+ hmi_apis::Common_LayoutMode::eType tested_enum_value =
+ hmi_apis::Common_LayoutMode::ICON_ONLY;
+ hmi_apis::Common_AppHMIType::eType converted =
+ MessageHelper::ConvertEnumAPINoCheck<hmi_apis::Common_LayoutMode::eType,
+ hmi_apis::Common_AppHMIType::eType>(
+ tested_enum_value);
+ EXPECT_EQ(hmi_apis::Common_AppHMIType::DEFAULT, converted);
+}
+
+TEST_F(MessageHelperTest, HMIResultFromString_StringValueOfEnum_CorrectEType) {
+ HmiResults::eType enum_value;
+ HmiResults::eType enum_from_string_value;
+ // Check all results >= 0
+ for (size_t array_index = 0; array_index < hmi_result_strings.size();
+ ++array_index) {
+ enum_value = static_cast<HmiResults::eType>(array_index);
+ enum_from_string_value =
+ MessageHelper::HMIResultFromString(hmi_result_strings[array_index]);
+ EXPECT_EQ(enum_value, enum_from_string_value);
+ }
+ // Check InvalidEnum == -1
+ enum_value = HmiResults::INVALID_ENUM;
+ enum_from_string_value = MessageHelper::HMIResultFromString("");
+ EXPECT_EQ(enum_value, enum_from_string_value);
+}
+
+TEST_F(MessageHelperTest, HMIResultToString_ETypeValueOfEnum_CorrectString) {
+ std::string string_from_enum;
+ HmiResults::eType casted_enum;
+ // Check all results >=0
+ for (size_t array_index = 0; array_index < hmi_result_strings.size();
+ ++array_index) {
+ casted_enum = static_cast<HmiResults::eType>(array_index);
+ string_from_enum = MessageHelper::HMIResultToString(casted_enum);
+ EXPECT_EQ(hmi_result_strings[array_index], string_from_enum);
+ }
+ // Check InvalidEnum == -1
+ string_from_enum = MessageHelper::HMIResultToString(HmiResults::INVALID_ENUM);
+ EXPECT_EQ("", string_from_enum);
+}
+
+TEST_F(MessageHelperTest,
+ HMIToMobileResult_HmiResultEType_GetCorrectMobileResultEType) {
+ MobileResults::eType tested_enum;
+ HmiResults::eType casted_hmi_enum;
+ MobileResults::eType converted_enum;
+ // Check enums >=0
+ for (size_t enum_index = 0; enum_index < hmi_result_strings.size();
+ ++enum_index) {
+ tested_enum =
+ MessageHelper::MobileResultFromString(hmi_result_strings[enum_index]);
+ casted_hmi_enum = static_cast<HmiResults::eType>(enum_index);
+ converted_enum = MessageHelper::HMIToMobileResult(casted_hmi_enum);
+ EXPECT_EQ(tested_enum, converted_enum);
+ }
+ // Check invalid enums == -1
+ tested_enum = MobileResults::INVALID_ENUM;
+ converted_enum = MessageHelper::HMIToMobileResult(HmiResults::INVALID_ENUM);
+ EXPECT_EQ(tested_enum, converted_enum);
+ // Check when out of range (true == result.empty())
+ casted_hmi_enum = static_cast<HmiResults::eType>(INT_MAX);
+ converted_enum = MessageHelper::HMIToMobileResult(casted_hmi_enum);
+ EXPECT_EQ(tested_enum, converted_enum);
+}
+
+TEST_F(MessageHelperTest, VerifySoftButtonString_WrongStrings_False) {
+ const StringArray wrong_strings{"soft_button1\t\ntext",
+ "soft_button1\\ntext",
+ "soft_button1\\ttext",
+ " ",
+ "soft_button1\t\n",
+ "soft_button1\\n",
+ "soft_button1\\t"};
+ for (size_t i = 0; i < wrong_strings.size(); ++i) {
+ EXPECT_FALSE(MessageHelper::VerifySoftButtonString(wrong_strings[i]));
+ }
+}
+
+TEST_F(MessageHelperTest, VerifySoftButtonString_CorrectStrings_True) {
+ const StringArray wrong_strings{"soft_button1.text",
+ "soft_button1?text",
+ " asd asdasd .././/",
+ "soft_button1??....asd",
+ "soft_button12313fcvzxc./.,"};
+ for (size_t i = 0; i < wrong_strings.size(); ++i) {
+ EXPECT_TRUE(MessageHelper::VerifySoftButtonString(wrong_strings[i]));
+ }
+}
+
+TEST_F(MessageHelperTest,
+ GetIVISubscriptionRequests_ValidApplication_HmiRequestNotEmpty) {
+ // Creating sharedPtr to MockApplication
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ // Creating data acessor
+ application_manager::VehicleInfoSubscriptions vis;
+ DataAccessor<application_manager::VehicleInfoSubscriptions> data_accessor(
+ vis, true);
+ // Calls for ApplicationManager
+ EXPECT_CALL(*appSharedMock, app_id()).WillOnce(Return(1u));
+ EXPECT_CALL(*appSharedMock, SubscribedIVI()).WillOnce(Return(data_accessor));
+
+ smart_objects::SmartObjectList outList =
+ MessageHelper::GetIVISubscriptionRequests(appSharedMock,
+ mock_application_manager);
+ // Expect not empty request
+ EXPECT_FALSE(outList.empty());
+}
+
+TEST_F(MessageHelperTest,
+ ProcessSoftButtons_SmartObjectWithoutButtonsKey_Success) {
+ // Creating sharedPtr to MockApplication
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ // Creating input data for method
+ smart_objects::SmartObject object;
+ policy_handler_test::MockPolicySettings policy_settings_;
+ const policy::PolicyHandler policy_handler(policy_settings_,
+ mock_application_manager);
+ // Method call
+ mobile_apis::Result::eType result = MessageHelper::ProcessSoftButtons(
+ object, appSharedMock, policy_handler, mock_application_manager);
+ // Expect
+ EXPECT_EQ(mobile_apis::Result::SUCCESS, result);
+}
+
+TEST_F(MessageHelperTest,
+ ProcessSoftButtons_IncorectSoftButonValue_InvalidData) {
+ // Creating sharedPtr to MockApplication
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ // Creating input data for method
+ smart_objects::SmartObject object;
+ smart_objects::SmartObject& buttons = object[strings::soft_buttons];
+ // Setting invalid image string to button
+ buttons[0][strings::image][strings::value] = "invalid\\nvalue";
+ policy_handler_test::MockPolicySettings policy_settings_;
+ const policy::PolicyHandler policy_handler(policy_settings_,
+ mock_application_manager);
+ // Method call
+ mobile_apis::Result::eType result = MessageHelper::ProcessSoftButtons(
+ object, appSharedMock, policy_handler, mock_application_manager);
+ // Expect
+ EXPECT_EQ(mobile_apis::Result::INVALID_DATA, result);
+}
+
+TEST_F(MessageHelperTest, VerifyImage_ImageTypeIsStatic_Success) {
+ // Creating sharedPtr to MockApplication
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ // Creating input data for method
+ smart_objects::SmartObject image;
+ image[strings::image_type] = mobile_apis::ImageType::STATIC;
+ // Method call
+ mobile_apis::Result::eType result = MessageHelper::VerifyImage(
+ image, appSharedMock, mock_application_manager);
+ // EXPECT
+ EXPECT_EQ(mobile_apis::Result::SUCCESS, result);
+}
+
+TEST_F(MessageHelperTest, VerifyImage_ImageValueNotValid_InvalidData) {
+ // Creating sharedPtr to MockApplication
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ // Creating input data for method
+ smart_objects::SmartObject image;
+ image[strings::image_type] = mobile_apis::ImageType::DYNAMIC;
+ // Invalid value
+ image[strings::value] = " ";
+ // Method call
+ mobile_apis::Result::eType result = MessageHelper::VerifyImage(
+ image, appSharedMock, mock_application_manager);
+ // EXPECT
+ EXPECT_EQ(mobile_apis::Result::INVALID_DATA, result);
+}
+
+TEST_F(MessageHelperTest, VerifyImageFiles_SmartObjectWithValidData_Success) {
+ // Creating sharedPtr to MockApplication
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ // Creating input data for method
+ smart_objects::SmartObject images;
+ images[0][strings::image_type] = mobile_apis::ImageType::STATIC;
+ images[1][strings::image_type] = mobile_apis::ImageType::STATIC;
+ // Method call
+ mobile_apis::Result::eType result = MessageHelper::VerifyImageFiles(
+ images, appSharedMock, mock_application_manager);
+ // EXPECT
+ EXPECT_EQ(mobile_apis::Result::SUCCESS, result);
+}
+
+TEST_F(MessageHelperTest,
+ VerifyImageFiles_SmartObjectWithInvalidData_NotSuccsess) {
+ // Creating sharedPtr to MockApplication
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ // Creating input data for method
+ smart_objects::SmartObject images;
+ images[0][strings::image_type] = mobile_apis::ImageType::DYNAMIC;
+ images[1][strings::image_type] = mobile_apis::ImageType::DYNAMIC;
+ // Invalid values
+ images[0][strings::value] = " ";
+ images[1][strings::value] = "image\\n";
+ // Method call
+ mobile_apis::Result::eType result = MessageHelper::VerifyImageFiles(
+ images, appSharedMock, mock_application_manager);
+ // EXPECT
+ EXPECT_EQ(mobile_apis::Result::INVALID_DATA, result);
+}
+
+TEST_F(MessageHelperTest,
+ VerifyImageVrHelpItems_SmartObjectWithSeveralValidImages_Succsess) {
+ // Creating sharedPtr to MockApplication
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ // Creating input data for method
+ smart_objects::SmartObject message;
+ message[0][strings::image][strings::image_type] =
+ mobile_apis::ImageType::STATIC;
+ message[1][strings::image][strings::image_type] =
+ mobile_apis::ImageType::STATIC;
+ // Method call
+ mobile_apis::Result::eType result = MessageHelper::VerifyImageVrHelpItems(
+ message, appSharedMock, mock_application_manager);
+ // EXPECT
+ EXPECT_EQ(mobile_apis::Result::SUCCESS, result);
+}
+
+TEST_F(MessageHelperTest,
+ VerifyImageVrHelpItems_SmartObjWithSeveralInvalidImages_NotSuccsess) {
+ // Creating sharedPtr to MockApplication
+ MockApplicationSharedPtr appSharedMock = utils::MakeShared<AppMock>();
+ // Creating input data for method
+ smart_objects::SmartObject message;
+ message[0][strings::image][strings::image_type] =
+ mobile_apis::ImageType::DYNAMIC;
+ message[1][strings::image][strings::image_type] =
+ mobile_apis::ImageType::DYNAMIC;
+ // Invalid values
+ message[0][strings::image][strings::value] = " ";
+ message[1][strings::image][strings::value] = "image\\n";
+ // Method call
+ mobile_apis::Result::eType result = MessageHelper::VerifyImageVrHelpItems(
+ message, appSharedMock, mock_application_manager);
+ // EXPECT
+ EXPECT_EQ(mobile_apis::Result::INVALID_DATA, result);
+}
+
+TEST_F(MessageHelperTest,
+ StringifiedFunctionID_FinctionId_EqualsWithStringsInArray) {
+ // Start from 1 because 1 == RESERVED and haven`t ID in last 2 characters
+ // if FUNCTION ID == 1 inner DCHECK is false
+ mobile_apis::FunctionID::eType casted_enum;
+ std::string converted;
+ for (size_t i = 1; i < function_id_strings.size(); ++i) {
+ casted_enum = static_cast<mobile_apis::FunctionID::eType>(i);
+ converted = MessageHelper::StringifiedFunctionID(casted_enum);
+ EXPECT_EQ(function_id_strings[i], converted);
+ }
+ // EventIDs emum strarts from delta_from_functions_id = 32768
+ for (size_t i = delta_from_functions_id;
+ i < events_id_strings.size() + delta_from_functions_id;
+ ++i) {
+ casted_enum = static_cast<mobile_apis::FunctionID::eType>(i);
+ converted = MessageHelper::StringifiedFunctionID(casted_enum);
+ EXPECT_EQ(events_id_strings[i - delta_from_functions_id], converted);
+ }
+}
+
+TEST_F(MessageHelperTest,
+ StringifiedHmiLevel_LevelEnum_EqualsWithStringsInArray) {
+ mobile_apis::HMILevel::eType casted_enum;
+ std::string converted_value;
+ for (size_t i = 0; i < hmi_level_strings.size(); ++i) {
+ casted_enum = static_cast<mobile_apis::HMILevel::eType>(i);
+ converted_value = MessageHelper::StringifiedHMILevel(casted_enum);
+ EXPECT_EQ(hmi_level_strings[i], converted_value);
+ }
+}
+
+TEST_F(MessageHelperTest, StringToHmiLevel_LevelString_EqEType) {
+ mobile_apis::HMILevel::eType tested_enum;
+ mobile_apis::HMILevel::eType converted_enum;
+ for (size_t i = 0; i < hmi_level_strings.size(); ++i) {
+ tested_enum = static_cast<mobile_apis::HMILevel::eType>(i);
+ converted_enum = MessageHelper::StringToHMILevel(hmi_level_strings[i]);
+ EXPECT_EQ(tested_enum, converted_enum);
+ }
+}
+
+TEST_F(MessageHelperTest, SubscribeApplicationToSoftButton_CallFromApp) {
+ // Create application mock
+ MockApplicationSharedPtr appSharedPtr = utils::MakeShared<AppMock>();
+ // Prepare data for method
+ smart_objects::SmartObject message_params;
+ size_t function_id = 1;
+ //
+ EXPECT_CALL(*appSharedPtr,
+ SubscribeToSoftButtons(function_id, SoftButtonID())).Times(1);
+ MessageHelper::SubscribeApplicationToSoftButton(
+ message_params, appSharedPtr, function_id);
+}
+
+} // namespace test
+} // namespace application_manager
diff --git a/src/components/application_manager/test/mobile_message_handler_test.cc b/src/components/application_manager/test/mobile_message_handler_test.cc
index ec144826a8..34a817d096 100644
--- a/src/components/application_manager/test/mobile_message_handler_test.cc
+++ b/src/components/application_manager/test/mobile_message_handler_test.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,19 +30,226 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
+#include "application_manager/mobile_message_handler.h"
+
+#include <string>
+#include <ctime>
+#include <algorithm>
+#include <iterator>
+#include <vector>
#include "gmock/gmock.h"
-#include "application_manager/mobile_message_handler.h"
+#include "application_manager/message.h"
+#include "protocol/raw_message.h"
+#include "utils/make_shared.h"
+namespace application_manager {
+namespace test {
+using protocol_handler::RawMessage;
+using protocol_handler::RawMessagePtr;
+using protocol_handler::ServiceType;
+using protocol_handler::MessagePriority;
+using protocol_handler::PROTOCOL_HEADER_V2_SIZE;
+using application_manager::MobileMessageHandler;
+using application_manager::ProtocolVersion;
using ::testing::_;
-namespace application_manager {
+using testing::Return;
+
+namespace {
+
+const unsigned char kJjson_size = 0x5e;
+const unsigned char kCorrelation_id = 0x5c;
+unsigned char binary_header[PROTOCOL_HEADER_V2_SIZE] = {0x20,
+ 0x00,
+ 0x00,
+ 0xf7,
+ 0x00,
+ 0x00,
+ 0x00,
+ kCorrelation_id,
+ 0x00,
+ 0x00,
+ 0x00,
+ kJjson_size};
+
+std::string data(
+ "{\n \"audioStreamingState\" : \"AUDIBLE\",\n \"hmiLevel\" : "
+ "\"FULL\",\n \"systemContext\" : \"MAIN\"\n}\n");
+
+} // namespace
+
+template <class T, class T2, class T3>
+T joiner(T2 begin, T2 end, const T3& data) {
+ T cont(begin, end);
+ std::copy(data.begin(), data.end(), std::back_inserter(cont));
+ return cont;
+}
+
+class MobileMessageHandlerTest : public testing::Test {
+ public:
+ MobileMessageHandlerTest() : connection_key_(1) {}
+
+ protected:
+ RawMessagePtr message_ptr_;
+ const uint32_t connection_key_;
+
+ Message* HandleIncomingMessage(const uint32_t protocol_version,
+ const std::string data,
+ const uint32_t payload_size) {
+ std::vector<uint8_t> full_data = joiner<std::vector<uint8_t> >(
+ binary_header, binary_header + PROTOCOL_HEADER_V2_SIZE, data);
+
+ size_t full_size = sizeof(uint8_t) * full_data.size();
+
+ message_ptr_ = utils::MakeShared<RawMessage>(connection_key_,
+ protocol_version,
+ &full_data[0],
+ full_size,
+ ServiceType::kRpc,
+ payload_size);
+
+ return MobileMessageHandler::HandleIncomingMessageProtocol(message_ptr_);
+ }
+
+ void TestHandlingIncomingMessageWithBinaryDataProtocol(
+ int32_t protocol_version) {
+ // Arrange
+ // Add binary data to json message
+ std::string binary_data("\a\a\a\a");
+ std::string json_plus_binary_data =
+ joiner<std::string>(data.begin(), data.end(), binary_data);
+ size_t full_data_size = json_plus_binary_data.size() * sizeof(uint8_t) +
+ PROTOCOL_HEADER_V2_SIZE;
+
+ // Act
+ size_t payload_size = data.size();
+ Message* message = HandleIncomingMessage(
+ protocol_version, json_plus_binary_data, payload_size);
+
+ // Checks
+ EXPECT_EQ(data, message->json_message());
+ EXPECT_EQ(1, message->connection_key());
+ EXPECT_EQ(247, message->function_id());
+ EXPECT_EQ(protocol_version, message->protocol_version());
+ EXPECT_EQ(0x5c, message->correlation_id());
+ EXPECT_EQ(full_data_size, message->data_size());
+ EXPECT_EQ(payload_size, message->payload_size());
+ EXPECT_TRUE(message->has_binary_data());
+ EXPECT_EQ(MessageType::kNotification, message->type());
+ }
+
+ void TestHandlingIncomingMessageWithoutBinaryDataProtocol(
+ uint32_t protocol_version) {
+ // Arrange
+ size_t payload_size = data.size();
+ size_t full_data_size = data.size() + PROTOCOL_HEADER_V2_SIZE;
+ Message* message =
+ HandleIncomingMessage(protocol_version, data, payload_size);
+
+ // Checks
+ EXPECT_EQ(data, message->json_message());
+ EXPECT_EQ(1, message->connection_key());
+ EXPECT_EQ(247, message->function_id());
+ EXPECT_EQ(protocol_version, (uint32_t)message->protocol_version());
+ EXPECT_EQ(0x5c, message->correlation_id());
+ EXPECT_EQ(full_data_size, message->data_size());
+ EXPECT_EQ(payload_size, message->payload_size());
+ EXPECT_FALSE(message->has_binary_data());
+ EXPECT_EQ(MessageType::kNotification, message->type());
+ }
+
+ MobileMessage CreateMessageForSending(uint32_t protocol_version,
+ uint32_t function_id,
+ uint32_t correlation_id,
+ uint32_t connection_key,
+ const std::string& json_msg,
+ BinaryData* data = NULL) {
+ MobileMessage message = utils::MakeShared<Message>(
+ MessagePriority::FromServiceType(ServiceType::kRpc));
+ message->set_function_id(function_id);
+ message->set_correlation_id(correlation_id);
+ message->set_connection_key(connection_key);
+ message->set_protocol_version(
+ static_cast<ProtocolVersion>(protocol_version));
+ message->set_message_type(MessageType::kNotification);
+ if (data) {
+ message->set_binary_data(data);
+ }
+ if (!json_msg.empty()) {
+ message->set_json_message(json_msg);
+ }
+ return message;
+ }
+
+ void TestHandlingOutgoingMessageProtocolWithoutBinaryData(
+ const uint32_t protocol_version) {
+ // Arrange
+ const uint32_t function_id = 247u;
+ const uint32_t correlation_id = 92u;
+ const uint32_t connection_key = 1u;
+
+ MobileMessage message_to_send = CreateMessageForSending(
+ protocol_version, function_id, correlation_id, connection_key, data);
+ // Act
+ RawMessage* result_message =
+ MobileMessageHandler::HandleOutgoingMessageProtocol(message_to_send);
+
+ std::vector<uint8_t> full_data = joiner<std::vector<uint8_t> >(
+ binary_header, binary_header + PROTOCOL_HEADER_V2_SIZE, data);
+
+ size_t full_size = sizeof(uint8_t) * full_data.size();
+
+ // Checks
+ EXPECT_EQ(protocol_version, result_message->protocol_version());
+ EXPECT_EQ(connection_key, result_message->connection_key());
+ EXPECT_EQ(full_size, result_message->data_size());
+ for (uint8_t i = 0; i < full_data.size(); ++i) {
+ EXPECT_EQ(full_data[i], result_message->data()[i]);
+ }
+ EXPECT_EQ(ServiceType::kRpc, result_message->service_type());
+ }
+
+ void TestHandlingOutgoingMessageProtocolWithBinaryData(
+ const uint32_t protocol_version) {
+ // Arrange
+ BinaryData* bin_dat = new BinaryData;
+ bin_dat->push_back('\a');
+
+ const uint32_t function_id = 247u;
+ const uint32_t correlation_id = 92u;
+ const uint32_t connection_key = 1u;
+
+ MobileMessage message_to_send = CreateMessageForSending(protocol_version,
+ function_id,
+ correlation_id,
+ connection_key,
+ data,
+ bin_dat);
+ // Act
+ RawMessage* result_message =
+ MobileMessageHandler::HandleOutgoingMessageProtocol(message_to_send);
+ std::vector<uint8_t> full_data = joiner<std::vector<uint8_t> >(
+ binary_header, binary_header + PROTOCOL_HEADER_V2_SIZE, data);
+ size_t full_size =
+ sizeof(uint8_t) * full_data.size() + bin_dat->size() * sizeof(uint8_t);
+
+ // Checks
+ EXPECT_EQ(protocol_version, result_message->protocol_version());
+ EXPECT_EQ(connection_key, result_message->connection_key());
+ EXPECT_EQ(full_size, result_message->data_size());
+ for (uint8_t i = 0; i < full_data.size(); ++i) {
+ EXPECT_EQ(full_data[i], result_message->data()[i]);
+ }
+ EXPECT_EQ(0x0F, result_message->service_type());
+ }
+};
TEST(mobile_message_test, basic_test) {
// Example message
- MobileMessage message = new application_manager::Message(
- protocol_handler::MessagePriority::kDefault);
+ MobileMessage message =
+ utils::MakeShared<Message>(protocol_handler::MessagePriority::kDefault);
EXPECT_FALSE(message->has_binary_data());
BinaryData* binary_data = new BinaryData;
binary_data->push_back('X');
@@ -50,4 +257,98 @@ TEST(mobile_message_test, basic_test) {
EXPECT_TRUE(message->has_binary_data());
}
+TEST_F(
+ MobileMessageHandlerTest,
+ Test_HandleIncomingMessageProtocol_MessageWithUnknownProtocolVersion_ExpectNull) {
+ // Arrange
+ size_t payload_size = data.size();
+ std::srand(time(0));
+ // Generate unknown random protocol version except 1-3
+ uint32_t protocol_version = 4 + rand() % UINT32_MAX;
+ Message* message =
+ HandleIncomingMessage(protocol_version, data, payload_size);
+
+ // Checks
+ EXPECT_EQ(NULL, message);
+}
+
+TEST_F(
+ MobileMessageHandlerTest,
+ Test_HandleOutgoingMessageProtocol_MessageWithUnknownProtocolVersion_ExpectNull) {
+ // Arrange
+ std::srand(time(0));
+
+ const uint32_t function_id = 247u;
+ const uint32_t correlation_id = 92u;
+ const uint32_t connection_key = 1u;
+ // Generate unknown random protocol version except 1-3
+ uint32_t protocol_version = 4 + rand() % UINT32_MAX;
+
+ MobileMessage message_to_send = CreateMessageForSending(
+ protocol_version, function_id, correlation_id, connection_key, data);
+ // Act
+ RawMessage* result_message =
+ MobileMessageHandler::HandleOutgoingMessageProtocol(message_to_send);
+
+ // Check
+ EXPECT_EQ(NULL, result_message);
+}
+
+TEST_F(
+ MobileMessageHandlerTest,
+ Test_HandleIncomingMessageProtocol_MessageWithProtocolV2_WithoutBinaryData) {
+ const uint32_t protocol_version = 2u;
+ TestHandlingIncomingMessageWithoutBinaryDataProtocol(protocol_version);
+}
+
+TEST_F(
+ MobileMessageHandlerTest,
+ Test_HandleIncomingMessageProtocol_MessageWithProtocolV3_WithoutBinaryData) {
+ const uint32_t protocol_version = 3u;
+ TestHandlingIncomingMessageWithoutBinaryDataProtocol(protocol_version);
}
+
+TEST_F(
+ MobileMessageHandlerTest,
+ Test_HandleIncomingMessageProtocol_MessageWithProtocolV2_WithBinaryData) {
+ const uint32_t protocol_version = 2u;
+ TestHandlingIncomingMessageWithBinaryDataProtocol(protocol_version);
+}
+
+TEST_F(
+ MobileMessageHandlerTest,
+ Test_HandleIncomingMessageProtocol_MessageWithProtocolV3_WithBinaryData) {
+ const uint32_t protocol_version = 3u;
+ TestHandlingIncomingMessageWithBinaryDataProtocol(protocol_version);
+}
+
+TEST_F(
+ MobileMessageHandlerTest,
+ Test_HandleOutgoingMessageProtocol_MessageWithProtocolV2_WithoutBinaryData) {
+ const uint32_t protocol_version = 2u;
+ TestHandlingOutgoingMessageProtocolWithoutBinaryData(protocol_version);
+}
+
+TEST_F(
+ MobileMessageHandlerTest,
+ Test_HandleOutgoingMessageProtocol_MessageWithProtocolV3_WithoutBinaryData) {
+ const uint32_t protocol_version = 3u;
+ TestHandlingOutgoingMessageProtocolWithoutBinaryData(protocol_version);
+}
+
+TEST_F(
+ MobileMessageHandlerTest,
+ Test_HandleOutgoingMessageProtocol_MessageWithProtocolV2_WithBinaryData) {
+ const uint32_t protocol_version = 2u;
+ TestHandlingOutgoingMessageProtocolWithBinaryData(protocol_version);
+}
+
+TEST_F(
+ MobileMessageHandlerTest,
+ Test_HandleOutgoingMessageProtocol_MessageWithProtocolV3_WithBinaryData) {
+ const uint32_t protocol_version = 3u;
+ TestHandlingOutgoingMessageProtocolWithBinaryData(protocol_version);
+}
+
+} // namespace test
+} // namespace application_manager
diff --git a/src/components/application_manager/test/mobile_message_handler_v1_test.cc b/src/components/application_manager/test/mobile_message_handler_v1_test.cc
new file mode 100644
index 0000000000..8301bf6f18
--- /dev/null
+++ b/src/components/application_manager/test/mobile_message_handler_v1_test.cc
@@ -0,0 +1,126 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/mobile_message_handler.h"
+
+#include <string>
+#include <vector>
+#include <algorithm>
+#include <iterator>
+
+#include "gmock/gmock.h"
+#include "application_manager/message.h"
+#include "protocol/raw_message.h"
+#include "utils/make_shared.h"
+
+using protocol_handler::RawMessage;
+using protocol_handler::RawMessagePtr;
+using protocol_handler::PROTOCOL_HEADER_V1_SIZE;
+
+namespace application_manager {
+namespace test {
+
+const int32_t connection_key_p1 = 1;
+const int32_t protocol_version_1 = 1;
+
+const std::string data_json(
+ "\"{\"menu\": {\"id\": \"file\",\"va"
+ "lue\": \"File\",\"popup\": {\"menuitem\": [ {\"val"
+ "ue\": \"New\", \"onclick\": \"CreateNe"
+ "wDoc()\"}, {\"value\": \"Open\", \"oncli"
+ "ck\": \"OpenDoc()\"},{\"value\": \"Cl"
+ "ose\", \"onclick\": \"CloseDoc()\"}]}}}\"");
+
+const unsigned char binary[PROTOCOL_HEADER_V1_SIZE] = {
+ 0x20, 0x00, 0x00, 0xf7, 0x00, 0x00, 0x00, 0x10};
+
+const unsigned char* data_v1 =
+ reinterpret_cast<const unsigned char*>(data_json.c_str());
+
+TEST(MobileMessageHandlerTestV1Test,
+ HandleIncomingMessageProtocolV1_SendJSONData_ExpectEqual) {
+ RawMessagePtr message = utils::MakeShared<RawMessage>(
+ connection_key_p1, protocol_version_1, data_v1, data_json.length());
+
+ application_manager::Message* ptr =
+ MobileMessageHandler::HandleIncomingMessageProtocol(message);
+
+ ASSERT_TRUE(ptr);
+
+ EXPECT_EQ(connection_key_p1, ptr->connection_key());
+ EXPECT_EQ(protocol_version_1, ptr->protocol_version());
+ EXPECT_EQ(data_json, ptr->json_message());
+}
+
+TEST(MobileMessageHandlerTestV1Test,
+ HandleIncomingMessageProtocolV1_SendBinaryJSONData_ExpectEqual) {
+ std::string full_data(reinterpret_cast<const char*>(binary));
+ full_data += data_json;
+ const unsigned char* data_v1 =
+ reinterpret_cast<const unsigned char*>(full_data.c_str());
+
+ RawMessagePtr message = utils::MakeShared<RawMessage>(
+ connection_key_p1, protocol_version_1, data_v1, full_data.length());
+
+ application_manager::Message* ptr =
+ MobileMessageHandler::HandleIncomingMessageProtocol(message);
+
+ ASSERT_TRUE(ptr);
+
+ EXPECT_EQ(connection_key_p1, ptr->connection_key());
+ EXPECT_EQ(protocol_version_1, ptr->protocol_version());
+ EXPECT_EQ(full_data, ptr->json_message());
+}
+
+TEST(MobileMessageHandlerTestV1Test,
+ HandleOutgoingMessageProtocol_SendMessage_ExpectEqual) {
+ uint32_t connection_key = 1;
+
+ MobileMessage message =
+ utils::MakeShared<Message>(protocol_handler::MessagePriority::kDefault);
+
+ message->set_protocol_version(application_manager::ProtocolVersion::kV1);
+ message->set_json_message(data_json);
+ message->set_connection_key(connection_key_p1);
+
+ RawMessage* ptr =
+ MobileMessageHandler::HandleOutgoingMessageProtocol(message);
+
+ ASSERT_TRUE(ptr);
+
+ EXPECT_EQ(connection_key, ptr->connection_key());
+ EXPECT_EQ(static_cast<uint32_t>(application_manager::ProtocolVersion::kV1),
+ ptr->protocol_version());
+}
+
+} // namespace test
+} // namespace application_manager
diff --git a/src/components/application_manager/test/mock/include/application_manager/application.h b/src/components/application_manager/test/mock/include/application_manager/application.h
deleted file mode 120000
index 7b86b18d4b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/application.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/application.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/application_data_impl.h b/src/components/application_manager/test/mock/include/application_manager/application_data_impl.h
deleted file mode 120000
index a53ea11d5b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/application_data_impl.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/application_data_impl.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/application_impl.h b/src/components/application_manager/test/mock/include/application_manager/application_impl.h
deleted file mode 120000
index 838885790a..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/application_impl.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/application_impl.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/application_manager.h b/src/components/application_manager/test/mock/include/application_manager/application_manager.h
deleted file mode 120000
index d9f08e4c22..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/application_manager.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/application_manager.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/application_manager_impl.h b/src/components/application_manager/test/mock/include/application_manager/application_manager_impl.h
deleted file mode 100644
index bc6a4e6ba4..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/application_manager_impl.h
+++ /dev/null
@@ -1,373 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_H_
-#define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_H_
-#include "gtest/gtest.h"
-#include "gmock/gmock.h"
-
-#include <stdint.h>
-#include <vector>
-#include <map>
-#include <set>
-#include "application_manager/hmi_command_factory.h"
-#include "application_manager/application_manager.h"
-#include "application_manager/hmi_capabilities.h"
-#include "application_manager/message.h"
-#include "application_manager/request_controller.h"
-#include "application_manager/resume_ctrl.h"
-#include "application_manager/vehicle_info_data.h"
-#include "application_manager/state_controller.h"
-#include "protocol_handler/protocol_observer.h"
-#include "protocol_handler/protocol_handler.h"
-#include "hmi_message_handler/hmi_message_observer.h"
-#include "hmi_message_handler/hmi_message_sender.h"
-
-#include "media_manager/media_manager_impl.h"
-
-#include "connection_handler/connection_handler_observer.h"
-#include "connection_handler/device.h"
-
-#include "formatters/CSmartFactory.hpp"
-
-#include "interfaces/HMI_API.h"
-#include "interfaces/HMI_API_schema.h"
-#include "interfaces/MOBILE_API_schema.h"
-
-#include "interfaces/v4_protocol_v1_2_no_extra.h"
-#include "interfaces/v4_protocol_v1_2_no_extra_schema.h"
-#ifdef TIME_TESTER
-#include "time_metric_observer.h"
-#endif // TIME_TESTER
-
-#include "utils/macro.h"
-#include "utils/shared_ptr.h"
-#include "utils/message_queue.h"
-#include "utils/prioritized_queue.h"
-#include "utils/threads/thread.h"
-#include "utils/threads/message_loop_thread.h"
-#include "utils/lock.h"
-#include "utils/singleton.h"
-
-namespace application_manager {
- enum VRTTSSessionChanging {
- kVRSessionChanging = 0,
- kTTSSessionChanging
- };
-
-namespace impl {
-
-struct MessageFromMobile: public utils::SharedPtr<Message> {
- explicit MessageFromMobile(const utils::SharedPtr<Message>& message)
- : utils::SharedPtr<Message>(message) {
- }
- // PrioritizedQueue requres this method to decide which priority to assign
- size_t PriorityOrder() const {
- return (*this)->Priority().OrderingValue();
- }
-};
-
-struct MessageToMobile: public utils::SharedPtr<Message> {
- explicit MessageToMobile(const utils::SharedPtr<Message>& message,
- bool final_message)
- : utils::SharedPtr<Message>(message),
- is_final(final_message) {
- }
- // PrioritizedQueue requres this method to decide which priority to assign
- size_t PriorityOrder() const {
- return (*this)->Priority().OrderingValue();
- }
- // Signals if connection to mobile must be closed after sending this message
- bool is_final;
-};
-
-struct MessageFromHmi: public utils::SharedPtr<Message> {
- explicit MessageFromHmi(const utils::SharedPtr<Message>& message)
- : utils::SharedPtr<Message>(message) {
- }
- // PrioritizedQueue requres this method to decide which priority to assign
- size_t PriorityOrder() const {
- return (*this)->Priority().OrderingValue();
- }
-};
-
-struct MessageToHmi: public utils::SharedPtr<Message> {
- explicit MessageToHmi(const utils::SharedPtr<Message>& message)
- : utils::SharedPtr<Message>(message) {
- }
- // PrioritizedQueue requres this method to decide which priority to assign
- size_t PriorityOrder() const {
- return (*this)->Priority().OrderingValue();
- }
-};
-
-typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageFromMobile> > FromMobileQueue;
-typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageToMobile> > ToMobileQueue;
-typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageFromHmi> > FromHmiQueue;
-typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageToHmi> > ToHmiQueue;
-
-// AudioPassThru
-typedef struct {
-std::vector<uint8_t> binary_data;
-int32_t session_key;
-} AudioData;
-typedef std::queue<AudioData> RawAudioDataQueue;
-typedef threads::MessageLoopThread<RawAudioDataQueue> AudioPassThruQueue;
-}
-typedef std::vector<std::string> RPCParams;
-
-class ApplicationManagerImpl : public ApplicationManager,
- public hmi_message_handler::HMIMessageObserver,
- public protocol_handler::ProtocolObserver,
- public connection_handler::ConnectionHandlerObserver,
- public impl::FromMobileQueue::Handler, public impl::ToMobileQueue::Handler,
- public impl::FromHmiQueue::Handler, public impl::ToHmiQueue::Handler,
- public impl::AudioPassThruQueue::Handler,
- public utils::Singleton<ApplicationManagerImpl> {
-
- friend class ResumeCtrl;
- friend class CommandImpl;
-
- public:
- ApplicationManagerImpl() {
- std::cout << "ApplicationManagerImpl Mock created " << std::endl;
- }
-
- MOCK_METHOD0(Init, bool());
- MOCK_METHOD0(Stop, bool());
- MOCK_METHOD1(OnMessageReceived, void (utils::SharedPtr<application_manager::Message>));
- MOCK_METHOD1(OnErrorSending, void (utils::SharedPtr<application_manager::Message>));
- MOCK_METHOD1(OnMessageReceived, void (const ::protocol_handler::RawMessagePtr));
- MOCK_METHOD1(OnMobileMessageSent, void (const ::protocol_handler::RawMessagePtr));
- MOCK_METHOD1(OnDeviceListUpdated, void (const connection_handler::DeviceMap&));
- MOCK_METHOD0(OnFindNewApplicationsRequest, void ());
- MOCK_METHOD1(RemoveDevice, void (const connection_handler::DeviceHandle&));
- MOCK_METHOD3(OnServiceStartedCallback, bool (const connection_handler::DeviceHandle&,
- const int32_t&,
- const protocol_handler::ServiceType&));
- MOCK_METHOD3(OnServiceEndedCallback, void (const int32_t&,
- const protocol_handler::ServiceType&,
- const connection_handler::CloseSessionReason&));
- MOCK_METHOD1(Handle, void (const impl::MessageFromMobile));
- MOCK_METHOD1(Handle, void (const impl::MessageToMobile));
- MOCK_METHOD1(Handle, void (const impl::MessageFromHmi));
- MOCK_METHOD1(Handle, void (const impl::MessageToHmi));
- MOCK_METHOD1(Handle, void (const impl::AudioData));
-
- //ApplicationManager methods
- MOCK_METHOD1(set_hmi_message_handler, void (hmi_message_handler::HMIMessageHandler*));
- MOCK_METHOD1(set_protocol_handler, void (protocol_handler::ProtocolHandler*));
- MOCK_METHOD1(set_connection_handler, void (connection_handler::ConnectionHandler*));
-
- //ApplicationManagerImpl methods:
-#ifdef TIME_TESTER
- MOCK_METHOD1(SetTimeMetricObserver, void(AMMetricObserver*));
-#endif
- MOCK_METHOD1(RegisterApplication,
- ApplicationSharedPtr(const utils::SharedPtr<smart_objects::SmartObject>&));
- MOCK_METHOD0(hmi_capabilities, HMICapabilities& ());
- MOCK_METHOD1(ProcessQueryApp, void (const smart_objects::SmartObject& sm_object));
- MOCK_METHOD1(ManageHMICommand, bool (const utils::SharedPtr<smart_objects::SmartObject>&));
- MOCK_METHOD1(ManageMobileCommand, bool (const utils::SharedPtr<smart_objects::SmartObject>& message));
- MOCK_METHOD1(SendMessageToHMI, bool (const utils::SharedPtr<smart_objects::SmartObject>&));
- MOCK_METHOD2(SendMessageToMobile, bool (const utils::SharedPtr<smart_objects::SmartObject>&,
- bool));
- MOCK_METHOD1(SendMessageToMobile, bool (const utils::SharedPtr<smart_objects::SmartObject>&));
- MOCK_METHOD1(GetDeviceName, std::string (connection_handler::DeviceHandle));
- MOCK_METHOD1(GetDeviceTransportType, hmi_apis::Common_TransportType::eType (const std::string&));
- MOCK_METHOD1(application, ApplicationSharedPtr (uint32_t));
- MOCK_METHOD1(application_by_policy_id, ApplicationSharedPtr (const std::string&));
- MOCK_METHOD1(RemoveAppDataFromHMI, bool(ApplicationSharedPtr));
- MOCK_METHOD1(HeadUnitReset, void(mobile_api::AppInterfaceUnregisteredReason::eType));
- MOCK_METHOD1(LoadAppDataToHMI, bool(ApplicationSharedPtr));
- MOCK_METHOD1(ActivateApplication, bool (ApplicationSharedPtr));
- MOCK_METHOD1(IsHmiLevelFullAllowed, mobile_api::HMILevel::eType (ApplicationSharedPtr));
- MOCK_METHOD3(OnHMILevelChanged, void (uint32_t, mobile_apis::HMILevel::eType, mobile_apis::HMILevel::eType));
- MOCK_METHOD2(UnregisterRevokedApplication, void(uint32_t, mobile_apis::Result::eType));
- MOCK_METHOD1(SetUnregisterAllApplicationsReason, void(mobile_api::AppInterfaceUnregisteredReason::eType));
- MOCK_METHOD0(UnregisterAllApplications, void());
- MOCK_METHOD0(connection_handler, connection_handler::ConnectionHandler*());
- MOCK_METHOD0(protocol_handler, protocol_handler::ProtocolHandler*());
- MOCK_METHOD0(hmi_message_handler, hmi_message_handler::HMIMessageHandler*());
- MOCK_METHOD5(CheckPolicyPermissions, mobile_apis::Result::eType(const std::string&,
- mobile_apis::HMILevel::eType,
- mobile_apis::FunctionID::eType,
- const RPCParams&,
- CommandParametersPermissions*));
- MOCK_METHOD3(updateRequestTimeout, void(uint32_t, uint32_t, uint32_t));
- MOCK_METHOD0(GenerateGrammarID, uint32_t());
- MOCK_METHOD0(GenerateNewHMIAppID, uint32_t());
- MOCK_METHOD1(GetAvailableSpaceForApp, uint32_t(const std::string&));
- MOCK_METHOD0(begin_audio_pass_thru, bool ());
- MOCK_METHOD0(end_audio_pass_thru, uint32_t());
- MOCK_METHOD1(StopAudioPassThru, void(uint32_t));
- MOCK_METHOD1(applications_by_button, std::vector<ApplicationSharedPtr>(uint32_t));
- MOCK_METHOD0(applications_with_navi, std::vector<ApplicationSharedPtr>());
- MOCK_METHOD1(applications_by_ivi, std::vector<ApplicationSharedPtr>(uint32_t));
- MOCK_METHOD2(IviInfoUpdated, std::vector<utils::SharedPtr<Application>> (VehicleDataType,
- int));
- MOCK_METHOD6(StartAudioPassThruThread, void(uint32_t, uint32_t, uint32_t,
- uint32_t, uint32_t, uint32_t));
- MOCK_METHOD4(SaveBinary, mobile_apis::Result::eType(const std::vector<uint8_t>&,
- const std::string&,
- const std::string&,
- const int64_t));
- MOCK_METHOD1(ReplaceHMIByMobileAppId, void(smart_objects::SmartObject&));
- MOCK_METHOD1(ReplaceMobileByHMIAppId, void(smart_objects::SmartObject&));
- MOCK_METHOD0(resume_controller, ResumeCtrl&());
- MOCK_METHOD1(GetDefaultHmiLevel, mobile_api::HMILevel::eType (ApplicationSharedPtr));
-
- MOCK_METHOD2(HMILevelAllowsStreaming, bool(uint32_t, protocol_handler::ServiceType));
- MOCK_METHOD2(CanAppStream, bool(uint32_t, protocol_handler::ServiceType));
- MOCK_METHOD1(EndNaviServices, void(int32_t));
- MOCK_METHOD1(ForbidStreaming, void(int32_t));
- MOCK_METHOD3(OnAppStreaming, void(int32_t, protocol_handler::ServiceType, bool));
-
- MOCK_METHOD1(Unmute, void(VRTTSSessionChanging));
- MOCK_METHOD1(Mute, void(VRTTSSessionChanging));
- MOCK_METHOD2(set_application_id, void(const int32_t, const uint32_t));
- MOCK_METHOD1(application_id, uint32_t(const int32_t));
- MOCK_METHOD1(removeNotification, void(const commands::Command*));
- MOCK_METHOD1(addNotification, void(const CommandSharedPtr ));
- MOCK_METHOD0(StartDevicesDiscovery, void());
- MOCK_METHOD2(SendAudioPassThroughNotification, void(uint32_t, std::vector<uint8_t>&));
- MOCK_METHOD1(set_all_apps_allowed, void(const bool));
- MOCK_METHOD4(CreateRegularState, HmiStatePtr (uint32_t, mobile_api::HMILevel::eType,
- mobile_apis::AudioStreamingState::eType,
- mobile_apis::SystemContext::eType));
-
- template<bool SendActivateApp>
- MOCK_METHOD2(SetState, void(uint32_t, HmiState));
- template<bool SendActivateApp>
- MOCK_METHOD2(SetState, void(uint32_t, mobile_api::HMILevel::eType));
- template<bool SendActivateApp>
- MOCK_METHOD3(SetState, void(uint32_t, mobile_api::HMILevel::eType,
- mobile_apis::AudioStreamingState::eType));
- template<bool SendActivateApp>
- MOCK_METHOD4(SetState, void(uint32_t, mobile_api::HMILevel::eType,
- mobile_apis::AudioStreamingState::eType,
- mobile_apis::SystemContext::eType));
- MOCK_METHOD2(SetState, void(uint32_t,
- mobile_apis::AudioStreamingState::eType));
-
- MOCK_CONST_METHOD0(all_apps_allowed, bool());
- MOCK_METHOD1(set_vr_session_started, void(const bool));
- MOCK_CONST_METHOD0(vr_session_started, bool());
- MOCK_METHOD1(set_driver_distraction, void(const bool));
- MOCK_CONST_METHOD0(driver_distraction, bool());
- MOCK_METHOD1(ConnectToDevice, void(uint32_t));
- MOCK_METHOD0(OnHMIStartedCooperation, void());
- MOCK_METHOD0(GetNextHMICorrelationID, uint32_t ());
- MOCK_CONST_METHOD0(IsHMICooperating, bool());
- MOCK_METHOD0(OnTimerSendTTSGlobalProperties, void());
- MOCK_METHOD0(CreatePhoneCallAppList, void());
- MOCK_METHOD0(ResetPhoneCallAppList, void());
- MOCK_METHOD2(ChangeAppsHMILevel, void(uint32_t, mobile_apis::HMILevel::eType));
- MOCK_METHOD1(AddAppToTTSGlobalPropertiesList, void(const uint32_t));
- MOCK_METHOD1(RemoveAppFromTTSGlobalPropertiesList, void(const uint32_t));
- MOCK_METHOD1(application_by_hmi_app, ApplicationSharedPtr(uint32_t));
- MOCK_METHOD2(UnregisterApplication, void(const uint32_t,mobile_apis::Result::eType));
- MOCK_METHOD3(UnregisterApplication, void(const uint32_t,mobile_apis::Result::eType,
- bool));
- MOCK_METHOD4(UnregisterApplication, void(const uint32_t,mobile_apis::Result::eType,
- bool, bool));
- MOCK_METHOD1(OnAppUnauthorized, void(const uint32_t&));
- MOCK_CONST_METHOD0(get_limited_media_application, ApplicationSharedPtr());
- MOCK_CONST_METHOD0(get_limited_navi_application, ApplicationSharedPtr());
- MOCK_CONST_METHOD0(get_limited_voice_application, ApplicationSharedPtr());
- MOCK_CONST_METHOD1(IsAppTypeExistsInFullOrLimited, bool(ApplicationSharedPtr));
- MOCK_CONST_METHOD0(active_application, ApplicationSharedPtr ());
- MOCK_METHOD0(OnApplicationListUpdateTimer, void());
- MOCK_METHOD0(OnLowVoltage, void());
- MOCK_METHOD0(OnWakeUp, void());
- MOCK_METHOD1(OnUpdateHMIAppType, void(std::map<std::string, std::vector<std::string> >));
- MOCK_METHOD3(set_state, void(ApplicationSharedPtr app,
- mobile_apis::HMILevel::eType,
- mobile_apis::AudioStreamingState::eType));
-MOCK_CONST_METHOD0(IsStopping, bool());
-
- struct ApplicationsAppIdSorter {
- bool operator() (const ApplicationSharedPtr lhs,
- const ApplicationSharedPtr rhs) {
- return lhs->app_id() < rhs->app_id();
- }
- };
-
- // typedef for Applications list
- typedef std::set<ApplicationSharedPtr,
- ApplicationsAppIdSorter> ApplictionSet;
-
- // typedef for Applications list iterator
- typedef ApplictionSet::iterator ApplictionSetIt;
-
- // typedef for Applications list const iterator
- typedef ApplictionSet::const_iterator ApplictionSetConstIt;
-
-
- /**
- * Class for thread-safe access to applications list
- */
- class ApplicationListAccessor: public DataAccessor<ApplictionSet> {
- public:
- ApplicationListAccessor() :
- DataAccessor<ApplictionSet>(ApplictionSet(),sync_primitives::Lock()) {
- }
- MOCK_CONST_METHOD0(applications, const ApplictionSet());
- MOCK_METHOD0(begin, ApplictionSetConstIt());
- MOCK_METHOD0(end, ApplictionSetConstIt());
- MOCK_METHOD1(Erase, void(ApplicationSharedPtr));
- MOCK_METHOD1(Insert, void(ApplicationSharedPtr));
- MOCK_METHOD0(Empty, bool());
- };
-
- friend class ApplicationListAccessor;
-
-
- class ApplicationListUpdateTimer : public timer::TimerThread<ApplicationManagerImpl> {
- public:
- ApplicationListUpdateTimer(ApplicationManagerImpl* callee) :
- timer::TimerThread<ApplicationManagerImpl>("AM ListUpdater",
- callee, &ApplicationManagerImpl::OnApplicationListUpdateTimer
- ) {
- }
- };
- typedef utils::SharedPtr<ApplicationListUpdateTimer> ApplicationListUpdateTimerSptr;
-
-
- private:
- //FIXME(AKutsan) In resume_controller is is nessesery to change realisation for remove using application_list_
- ApplictionSet application_list_;
- FRIEND_BASE_SINGLETON_CLASS(ApplicationManagerImpl);
-};
-
-} //application_manager
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_H_
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/command.h b/src/components/application_manager/test/mock/include/application_manager/commands/command.h
deleted file mode 120000
index 07b2c07963..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/command.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/commands/command.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/command_impl.h b/src/components/application_manager/test/mock/include/application_manager/commands/command_impl.h
deleted file mode 120000
index eb9e9576d1..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/command_impl.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/commands/command_impl.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/command_notification_from_mobile_impl.h b/src/components/application_manager/test/mock/include/application_manager/commands/command_notification_from_mobile_impl.h
deleted file mode 120000
index 1e3d6f0afe..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/command_notification_from_mobile_impl.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/commands/command_notification_from_mobile_impl.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/command_notification_impl.h b/src/components/application_manager/test/mock/include/application_manager/commands/command_notification_impl.h
deleted file mode 120000
index 2b946196d2..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/command_notification_impl.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/commands/command_notification_impl.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/command_request_impl.h b/src/components/application_manager/test/mock/include/application_manager/commands/command_request_impl.h
deleted file mode 120000
index 953008ead7..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/command_request_impl.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/commands/command_request_impl.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/command_response_impl.h b/src/components/application_manager/test/mock/include/application_manager/commands/command_response_impl.h
deleted file mode 120000
index 71136ecbf9..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/command_response_impl.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/commands/command_response_impl.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/activate_app_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/activate_app_request.h
deleted file mode 120000
index 5ebc425677..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/activate_app_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/activate_app_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/activate_app_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/activate_app_response.h
deleted file mode 120000
index 74e0b401ae..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/activate_app_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/activate_app_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/add_statistics_info_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/add_statistics_info_notification.h
deleted file mode 120000
index 0a68ef8aa0..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/add_statistics_info_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/add_statistics_info_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_all_apps_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_all_apps_request.h
deleted file mode 120000
index f110d55969..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_all_apps_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/allow_all_apps_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_all_apps_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_all_apps_response.h
deleted file mode 120000
index 5d81eebc08..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_all_apps_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/allow_all_apps_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_app_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_app_request.h
deleted file mode 120000
index 4674c56259..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_app_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/allow_app_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_app_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_app_response.h
deleted file mode 120000
index a972bbe3fe..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/allow_app_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/allow_app_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/basic_communication_on_awake_sdl.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/basic_communication_on_awake_sdl.h
deleted file mode 120000
index a7f0223e3e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/basic_communication_on_awake_sdl.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/basic_communication_on_awake_sdl.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/basic_communication_system_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/basic_communication_system_request.h
deleted file mode 120000
index 4190191f1b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/basic_communication_system_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/basic_communication_system_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/basic_communication_system_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/basic_communication_system_response.h
deleted file mode 120000
index 62e9bdbac4..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/basic_communication_system_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/basic_communication_system_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/button_get_capabilities_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/button_get_capabilities_request.h
deleted file mode 120000
index 8262591764..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/button_get_capabilities_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/button_get_capabilities_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/button_get_capabilities_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/button_get_capabilities_response.h
deleted file mode 120000
index 8ca8d92829..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/button_get_capabilities_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/button_get_capabilities_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/close_popup_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/close_popup_request.h
deleted file mode 120000
index bac5ced3ba..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/close_popup_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/close_popup_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/close_popup_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/close_popup_response.h
deleted file mode 120000
index 607da1f8bb..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/close_popup_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/close_popup_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_system_info_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_system_info_request.h
deleted file mode 120000
index 45a17a4c4d..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_system_info_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/get_system_info_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_system_info_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_system_info_response.h
deleted file mode 120000
index dd46df23e7..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_system_info_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/get_system_info_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_urls.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_urls.h
deleted file mode 120000
index 68789b0a50..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_urls.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/get_urls.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_urls_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_urls_response.h
deleted file mode 120000
index b76a19d07b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/get_urls_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/get_urls_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/mixing_audio_supported_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/mixing_audio_supported_request.h
deleted file mode 120000
index 73c501170c..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/mixing_audio_supported_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/mixing_audio_supported_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/mixing_audio_supported_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/mixing_audio_supported_response.h
deleted file mode 120000
index 041b46c653..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/mixing_audio_supported_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/mixing_audio_supported_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_alert_maneuver_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_alert_maneuver_request.h
deleted file mode 120000
index 9b879237eb..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_alert_maneuver_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_alert_maneuver_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_alert_maneuver_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_alert_maneuver_response.h
deleted file mode 120000
index 4ed6ec165d..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_alert_maneuver_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_alert_maneuver_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_start_stream_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_start_stream_request.h
deleted file mode 120000
index 0c83f540ae..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_start_stream_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_audio_start_stream_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_start_stream_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_start_stream_response.h
deleted file mode 120000
index fd9ca2d591..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_start_stream_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_audio_start_stream_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_stop_stream_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_stop_stream_request.h
deleted file mode 120000
index 3b9a69ee37..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_stop_stream_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_audio_stop_stream_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_stop_stream_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_stop_stream_response.h
deleted file mode 120000
index 46c13499ce..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_audio_stop_stream_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_audio_stop_stream_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_is_ready_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_is_ready_request.h
deleted file mode 120000
index beff169e82..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_is_ready_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_is_ready_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_is_ready_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_is_ready_response.h
deleted file mode 120000
index e1c9b1266f..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_is_ready_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_is_ready_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_send_location_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_send_location_request.h
deleted file mode 120000
index c3f11a7981..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_send_location_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_send_location_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_send_location_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_send_location_response.h
deleted file mode 120000
index 8728efe1e7..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_send_location_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_send_location_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_show_constant_tbt_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_show_constant_tbt_request.h
deleted file mode 120000
index 82bb72563c..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_show_constant_tbt_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_show_constant_tbt_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_show_constant_tbt_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_show_constant_tbt_response.h
deleted file mode 120000
index 116c2428d1..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_show_constant_tbt_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_show_constant_tbt_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_start_stream_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_start_stream_request.h
deleted file mode 120000
index 9f6e2036f4..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_start_stream_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_start_stream_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_start_stream_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_start_stream_response.h
deleted file mode 120000
index 788f569dd1..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_start_stream_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_start_stream_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_stop_stream_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_stop_stream_request.h
deleted file mode 120000
index 433340adb1..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_stop_stream_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_stop_stream_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_stop_stream_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_stop_stream_response.h
deleted file mode 120000
index 5015565371..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_stop_stream_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_stop_stream_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_update_turn_list_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_update_turn_list_request.h
deleted file mode 120000
index 2d8888a1b8..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_update_turn_list_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_update_turn_list_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_update_turn_list_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_update_turn_list_response.h
deleted file mode 120000
index 37f5dcf4b9..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/navi_update_turn_list_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/navi_update_turn_list_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/notification_from_hmi.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/notification_from_hmi.h
deleted file mode 120000
index d2fb7da954..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/notification_from_hmi.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/notification_from_hmi.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/notification_to_hmi.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/notification_to_hmi.h
deleted file mode 120000
index cd2036c6cb..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/notification_to_hmi.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/notification_to_hmi.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_allow_sdl_functionality_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_allow_sdl_functionality_notification.h
deleted file mode 120000
index 7088e09776..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_allow_sdl_functionality_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_allow_sdl_functionality_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_activated_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_activated_notification.h
deleted file mode 120000
index e3dee83334..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_activated_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_app_activated_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_deactivated_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_deactivated_notification.h
deleted file mode 120000
index 3db5068c21..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_deactivated_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_app_deactivated_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_permission_changed_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_permission_changed_notification.h
deleted file mode 120000
index 698c66aeeb..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_permission_changed_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_app_permission_changed_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_permission_consent_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_permission_consent_notification.h
deleted file mode 120000
index 4feacfd699..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_permission_consent_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_app_permission_consent_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_registered_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_registered_notification.h
deleted file mode 120000
index 8c6b32f1bd..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_registered_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_app_registered_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_unregistered_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_unregistered_notification.h
deleted file mode 120000
index e5a5bc23cd..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_app_unregistered_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_app_unregistered_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_button_event_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_button_event_notification.h
deleted file mode 120000
index 5276b6e208..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_button_event_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_button_event_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_button_press_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_button_press_notification.h
deleted file mode 120000
index 89460e876d..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_button_press_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_button_press_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_button_subscription_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_button_subscription_notification.h
deleted file mode 120000
index f35c69137b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_button_subscription_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_button_subscription_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_device_chosen_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_device_chosen_notification.h
deleted file mode 120000
index 3cceadabde..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_device_chosen_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_device_chosen_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_device_state_changed_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_device_state_changed_notification.h
deleted file mode 120000
index 87c152730e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_device_state_changed_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_device_state_changed_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_driver_distraction_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_driver_distraction_notification.h
deleted file mode 120000
index 8d7b4e9990..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_driver_distraction_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_driver_distraction_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_emergency_event_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_emergency_event_notification.h
deleted file mode 120000
index 4458ec5028..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_emergency_event_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_emergency_event_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_exit_all_applications_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_exit_all_applications_notification.h
deleted file mode 120000
index 482ae71548..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_exit_all_applications_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_exit_all_applications_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_exit_application_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_exit_application_notification.h
deleted file mode 120000
index ebe9dc9b9f..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_exit_application_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_exit_application_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_file_removed_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_file_removed_notification.h
deleted file mode 120000
index bec80bf2c9..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_file_removed_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_file_removed_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_find_applications.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_find_applications.h
deleted file mode 120000
index 5c427c8837..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_find_applications.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_find_applications.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ignition_cycle_over_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ignition_cycle_over_notification.h
deleted file mode 120000
index 8caf1afa59..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ignition_cycle_over_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_ignition_cycle_over_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_navi_tbt_client_state_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_navi_tbt_client_state_notification.h
deleted file mode 120000
index 2ef1136e29..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_navi_tbt_client_state_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_navi_tbt_client_state_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_phone_call_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_phone_call_notification.h
deleted file mode 120000
index 4ab1c99860..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_phone_call_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_phone_call_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_play_tone_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_play_tone_notification.h
deleted file mode 120000
index 21fd85dac3..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_play_tone_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_play_tone_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_policy_update.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_policy_update.h
deleted file mode 120000
index fb8c782b83..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_policy_update.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_policy_update.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_put_file_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_put_file_notification.h
deleted file mode 120000
index 61c4005e46..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_put_file_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_put_file_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ready_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ready_notification.h
deleted file mode 120000
index 735af42379..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ready_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_ready_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_received_policy_update.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_received_policy_update.h
deleted file mode 120000
index c53f1ce658..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_received_policy_update.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_received_policy_update.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_record_start_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_record_start_notification.h
deleted file mode 120000
index 733827254b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_record_start_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_record_start_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_resume_audio_source_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_resume_audio_source_notification.h
deleted file mode 120000
index f7b6f6bba1..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_resume_audio_source_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_resume_audio_source_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_sdl_close_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_sdl_close_notification.h
deleted file mode 120000
index a8cd1db472..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_sdl_close_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_sdl_close_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_sdl_consent_needed_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_sdl_consent_needed_notification.h
deleted file mode 120000
index 531002efa6..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_sdl_consent_needed_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_sdl_consent_needed_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_sdl_persistence_complete_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_sdl_persistence_complete_notification.h
deleted file mode 120000
index 2a8c51814d..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_sdl_persistence_complete_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_sdl_persistence_complete_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_start_device_discovery.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_start_device_discovery.h
deleted file mode 120000
index 459d55684a..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_start_device_discovery.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_start_device_discovery.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_status_update_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_status_update_notification.h
deleted file mode 120000
index 5304b2fcbe..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_status_update_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_status_update_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_context_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_context_notification.h
deleted file mode 120000
index 4403b0fc90..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_context_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_system_context_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_error_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_error_notification.h
deleted file mode 120000
index 8612089978..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_error_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_system_error_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_info_changed_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_info_changed_notification.h
deleted file mode 120000
index 9bfb39bb89..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_info_changed_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_system_info_changed_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_request_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_request_notification.h
deleted file mode 120000
index 923cbe7956..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_system_request_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_system_request_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_language_change_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_language_change_notification.h
deleted file mode 120000
index 2ad7fd6287..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_language_change_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_tts_language_change_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_reset_timeout_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_reset_timeout_notification.h
deleted file mode 120000
index e91f381a03..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_reset_timeout_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_tts_reset_timeout_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_started_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_started_notification.h
deleted file mode 120000
index c5c748cecc..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_started_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_tts_started_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_stopped_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_stopped_notification.h
deleted file mode 120000
index d40bc7ffb5..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_tts_stopped_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_tts_stopped_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_command_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_command_notification.h
deleted file mode 120000
index 86b7591eb3..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_command_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_ui_command_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_keyboard_input_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_keyboard_input_notification.h
deleted file mode 120000
index 04873772df..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_keyboard_input_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_ui_keyboard_input_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_language_change_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_language_change_notification.h
deleted file mode 120000
index 419745c084..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_language_change_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_ui_language_change_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_reset_timeout_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_reset_timeout_notification.h
deleted file mode 120000
index 3a68034b36..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_reset_timeout_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_ui_reset_timeout_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_touch_event_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_touch_event_notification.h
deleted file mode 120000
index 86531d491e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_ui_touch_event_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_ui_touch_event_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_update_device_list.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_update_device_list.h
deleted file mode 120000
index 2a6c0c4acf..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_update_device_list.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_update_device_list.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_acc_pedal_position_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_acc_pedal_position_notification.h
deleted file mode 120000
index 35f259dd5b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_acc_pedal_position_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_acc_pedal_position_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_belt_status_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_belt_status_notification.h
deleted file mode 120000
index 2ca86120d9..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_belt_status_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_belt_status_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_body_information_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_body_information_notification.h
deleted file mode 120000
index c0ff7d8c27..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_body_information_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_body_information_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_device_status_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_device_status_notification.h
deleted file mode 120000
index 4f32e21534..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_device_status_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_device_status_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_driver_braking_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_driver_braking_notification.h
deleted file mode 120000
index 01fc3fdf49..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_driver_braking_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_driver_braking_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_engine_torque_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_engine_torque_notification.h
deleted file mode 120000
index a2f074b766..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_engine_torque_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_engine_torque_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_external_temperature_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_external_temperature_notification.h
deleted file mode 120000
index aef5bd9136..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_external_temperature_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_external_temperature_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_fuel_level_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_fuel_level_notification.h
deleted file mode 120000
index 1f63c652b3..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_fuel_level_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_fuel_level_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_fuel_level_state_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_fuel_level_state_notification.h
deleted file mode 120000
index 2f8a4a8aab..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_fuel_level_state_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_fuel_level_state_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_gps_data_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_gps_data_notification.h
deleted file mode 120000
index 9fcf1f9808..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_gps_data_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_gps_data_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_head_lamp_status_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_head_lamp_status_notification.h
deleted file mode 120000
index c837834b48..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_head_lamp_status_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_head_lamp_status_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_instant_fuel_consumption_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_instant_fuel_consumption_notification.h
deleted file mode 120000
index bdbbf718b9..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_instant_fuel_consumption_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_instant_fuel_consumption_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_my_key_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_my_key_notification.h
deleted file mode 120000
index d1d9ed76b4..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_my_key_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_my_key_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_odometer_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_odometer_notification.h
deleted file mode 120000
index d1b3715060..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_odometer_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_odometer_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_prndl_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_prndl_notification.h
deleted file mode 120000
index 1e5fe3c22e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_prndl_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_prndl_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_rpm_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_rpm_notification.h
deleted file mode 120000
index 1be92ae38c..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_rpm_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_rpm_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_speed_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_speed_notification.h
deleted file mode 120000
index 6ed9e5a224..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_speed_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_speed_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_steering_wheel_angle_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_steering_wheel_angle_notification.h
deleted file mode 120000
index 7dbf52e868..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_steering_wheel_angle_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_steering_wheel_angle_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_tire_pressure_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_tire_pressure_notification.h
deleted file mode 120000
index d86bd602c9..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_tire_pressure_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_tire_pressure_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_vehicle_data_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_vehicle_data_notification.h
deleted file mode 120000
index a86015d35e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_vehicle_data_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_vehicle_data_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_vin_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_vin_notification.h
deleted file mode 120000
index 4d055a2dbe..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_vin_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_vin_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_wiper_status_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_wiper_status_notification.h
deleted file mode 120000
index 0de802fea8..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vi_wiper_status_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vi_wiper_status_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_command_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_command_notification.h
deleted file mode 120000
index ca58b0c54c..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_command_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vr_command_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_language_change_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_language_change_notification.h
deleted file mode 120000
index 0ee1334d1c..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_language_change_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vr_language_change_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_started_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_started_notification.h
deleted file mode 120000
index 3ad1e6a4c2..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_started_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vr_started_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_stopped_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_stopped_notification.h
deleted file mode 120000
index b230685cf3..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/on_vr_stopped_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/on_vr_stopped_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/request_from_hmi.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/request_from_hmi.h
deleted file mode 120000
index cc64e0435d..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/request_from_hmi.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/request_from_hmi.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/request_to_hmi.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/request_to_hmi.h
deleted file mode 120000
index 8f4f9bfc62..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/request_to_hmi.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/request_to_hmi.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/response_from_hmi.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/response_from_hmi.h
deleted file mode 120000
index 7352ba5033..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/response_from_hmi.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/response_from_hmi.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/response_to_hmi.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/response_to_hmi.h
deleted file mode 120000
index eea5e52522..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/response_to_hmi.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/response_to_hmi.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_activate_app_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_activate_app_request.h
deleted file mode 120000
index dbd2927575..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_activate_app_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/sdl_activate_app_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_activate_app_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_activate_app_response.h
deleted file mode 120000
index 359281f715..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_activate_app_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/sdl_activate_app_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_list_of_permissions_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_list_of_permissions_request.h
deleted file mode 120000
index 852f46c8e7..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_list_of_permissions_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/sdl_get_list_of_permissions_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_list_of_permissions_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_list_of_permissions_response.h
deleted file mode 120000
index aabab692de..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_list_of_permissions_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/sdl_get_list_of_permissions_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_status_update_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_status_update_request.h
deleted file mode 120000
index 19aea33e82..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_status_update_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/sdl_get_status_update_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_status_update_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_status_update_response.h
deleted file mode 120000
index 2b8a3579e2..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_status_update_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/sdl_get_status_update_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_user_friendly_message_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_user_friendly_message_request.h
deleted file mode 120000
index a7de550338..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_user_friendly_message_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/sdl_get_user_friendly_message_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_user_friendly_message_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_user_friendly_message_response.h
deleted file mode 120000
index 888023b1c7..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_get_user_friendly_message_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/sdl_get_user_friendly_message_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_policy_update.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_policy_update.h
deleted file mode 120000
index fce6df879e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_policy_update.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/sdl_policy_update.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_policy_update_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_policy_update_response.h
deleted file mode 120000
index 32c5d5c9d0..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/sdl_policy_update_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/sdl_policy_update_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_change_registration_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_change_registration_request.h
deleted file mode 120000
index 07988fae12..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_change_registration_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_change_registration_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_change_registration_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_change_registration_response.h
deleted file mode 120000
index a3f6db17e4..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_change_registration_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_change_registration_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_capabilities_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_capabilities_request.h
deleted file mode 120000
index bf50cc1ea8..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_capabilities_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_get_capabilities_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_capabilities_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_capabilities_response.h
deleted file mode 120000
index 2b3a1013ec..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_capabilities_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_get_capabilities_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_language_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_language_request.h
deleted file mode 120000
index 11363e063d..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_language_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_get_language_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_language_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_language_response.h
deleted file mode 120000
index a60f44c467..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_language_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_get_language_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_supported_languages_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_supported_languages_request.h
deleted file mode 120000
index f3f6d97664..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_supported_languages_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_get_supported_languages_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_supported_languages_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_supported_languages_response.h
deleted file mode 120000
index 855129ba90..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_get_supported_languages_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_get_supported_languages_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_is_ready_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_is_ready_request.h
deleted file mode 120000
index 76a09f3446..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_is_ready_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_is_ready_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_is_ready_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_is_ready_response.h
deleted file mode 120000
index 42e69db575..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_is_ready_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_is_ready_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_set_global_properties_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_set_global_properties_request.h
deleted file mode 120000
index 6ec0b44a60..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_set_global_properties_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_set_global_properties_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_set_global_properties_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_set_global_properties_response.h
deleted file mode 120000
index 0067742926..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_set_global_properties_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_set_global_properties_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_speak_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_speak_request.h
deleted file mode 120000
index 09dd90b890..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_speak_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_speak_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_speak_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_speak_response.h
deleted file mode 120000
index af8a6598fe..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_speak_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_speak_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_stop_speaking_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_stop_speaking_request.h
deleted file mode 120000
index 8d32593fd1..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_stop_speaking_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_stop_speaking_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_stop_speaking_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_stop_speaking_response.h
deleted file mode 120000
index d8cec177c0..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/tts_stop_speaking_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/tts_stop_speaking_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_command_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_command_request.h
deleted file mode 120000
index 7c8ecca061..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_command_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_add_command_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_command_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_command_response.h
deleted file mode 120000
index c48d437da7..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_command_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_add_command_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_submenu_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_submenu_request.h
deleted file mode 120000
index 07ed923893..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_submenu_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_add_submenu_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_submenu_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_submenu_response.h
deleted file mode 120000
index 1fb095cc44..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_add_submenu_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_add_submenu_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_alert_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_alert_request.h
deleted file mode 120000
index 576c8967ae..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_alert_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_alert_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_alert_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_alert_response.h
deleted file mode 120000
index 78b58a1b20..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_alert_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_alert_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_change_registration_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_change_registration_request.h
deleted file mode 120000
index ae2a74d2ab..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_change_registration_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_change_registration_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_change_registration_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_change_registration_response.h
deleted file mode 120000
index 4a207b3ea7..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_change_registration_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_change_registration_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_command_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_command_request.h
deleted file mode 120000
index cd78986534..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_command_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_delete_command_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_command_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_command_response.h
deleted file mode 120000
index 0421c44faa..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_command_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_delete_command_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_submenu_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_submenu_request.h
deleted file mode 120000
index 4afa039810..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_submenu_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_delete_submenu_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_submenu_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_submenu_response.h
deleted file mode 120000
index 4374dea7cc..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_delete_submenu_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_delete_submenu_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_end_audio_pass_thru_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_end_audio_pass_thru_request.h
deleted file mode 120000
index c19af2221d..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_end_audio_pass_thru_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_end_audio_pass_thru_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_end_audio_pass_thru_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_end_audio_pass_thru_response.h
deleted file mode 120000
index 20a9a7ff12..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_end_audio_pass_thru_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_end_audio_pass_thru_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_capabilities_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_capabilities_request.h
deleted file mode 120000
index c999d31f26..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_capabilities_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_get_capabilities_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_capabilities_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_capabilities_response.h
deleted file mode 120000
index 4d8267f2de..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_capabilities_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_get_capabilities_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_language_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_language_request.h
deleted file mode 120000
index b5a3e98402..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_language_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_get_language_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_language_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_language_response.h
deleted file mode 120000
index e06614fba2..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_language_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_get_language_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_supported_languages_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_supported_languages_request.h
deleted file mode 120000
index 90bedce441..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_supported_languages_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_get_supported_languages_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_supported_languages_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_supported_languages_response.h
deleted file mode 120000
index ae94b347bb..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_get_supported_languages_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_get_supported_languages_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_is_ready_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_is_ready_request.h
deleted file mode 120000
index 53e9aadbb2..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_is_ready_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_is_ready_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_is_ready_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_is_ready_response.h
deleted file mode 120000
index b2e926541a..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_is_ready_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_is_ready_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_request.h
deleted file mode 120000
index 8255ac277f..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_perform_audio_pass_thru_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_response.h
deleted file mode 120000
index 3b26071854..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_audio_pass_thru_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_perform_audio_pass_thru_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_interaction_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_interaction_request.h
deleted file mode 120000
index 668e395635..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_interaction_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_perform_interaction_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_interaction_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_interaction_response.h
deleted file mode 120000
index 30e74367b6..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_perform_interaction_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_perform_interaction_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_scrollable_message_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_scrollable_message_request.h
deleted file mode 120000
index c554acc317..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_scrollable_message_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_scrollable_message_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_scrollable_message_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_scrollable_message_response.h
deleted file mode 120000
index e5bb7ab1b2..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_scrollable_message_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_scrollable_message_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_app_icon_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_app_icon_request.h
deleted file mode 120000
index d79aae3c4d..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_app_icon_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_set_app_icon_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_app_icon_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_app_icon_response.h
deleted file mode 120000
index d961f29dcc..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_app_icon_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_set_app_icon_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_display_layout_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_display_layout_request.h
deleted file mode 120000
index f4d379ef2e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_display_layout_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_set_display_layout_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_display_layout_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_display_layout_response.h
deleted file mode 120000
index e09307f1e2..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_display_layout_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_set_display_layout_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_global_properties_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_global_properties_request.h
deleted file mode 120000
index 09760bc97f..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_global_properties_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_set_global_properties_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_global_properties_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_global_properties_response.h
deleted file mode 120000
index 7975cd942c..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_global_properties_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_set_global_properties_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_icon_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_icon_request.h
deleted file mode 120000
index 8d3d935498..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_icon_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_set_icon_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_icon_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_icon_response.h
deleted file mode 120000
index 6415eaf205..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_icon_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_set_icon_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_media_clock_timer_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_media_clock_timer_request.h
deleted file mode 120000
index 65d9c7fbd4..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_media_clock_timer_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_set_media_clock_timer_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_media_clock_timer_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_media_clock_timer_response.h
deleted file mode 120000
index 3035e4f461..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_set_media_clock_timer_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_set_media_clock_timer_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_show_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_show_request.h
deleted file mode 120000
index 5669790e29..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_show_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_show_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_show_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_show_response.h
deleted file mode 120000
index 22d0aab4ab..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_show_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_show_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_slider_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_slider_request.h
deleted file mode 120000
index bc7ee7f1b7..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_slider_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_slider_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_slider_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_slider_response.h
deleted file mode 120000
index b630730e4f..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/ui_slider_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/ui_slider_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_app_list_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_app_list_request.h
deleted file mode 120000
index 28a8e01032..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_app_list_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/update_app_list_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_app_list_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_app_list_response.h
deleted file mode 120000
index 11af157345..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_app_list_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/update_app_list_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_device_list_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_device_list_request.h
deleted file mode 120000
index bf55fd6c45..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_device_list_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/update_device_list_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_device_list_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_device_list_response.h
deleted file mode 120000
index 87653d8d0d..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_device_list_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/update_device_list_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_sdl_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_sdl_request.h
deleted file mode 120000
index 116a6c36c8..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_sdl_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/update_sdl_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_sdl_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_sdl_response.h
deleted file mode 120000
index d12d01f24f..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/update_sdl_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/update_sdl_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_diagnostic_message_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_diagnostic_message_request.h
deleted file mode 120000
index d11b2d66cb..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_diagnostic_message_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_diagnostic_message_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_diagnostic_message_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_diagnostic_message_response.h
deleted file mode 120000
index a9874fb19c..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_diagnostic_message_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_diagnostic_message_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_dtcs_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_dtcs_request.h
deleted file mode 120000
index 5e5516e662..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_dtcs_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_get_dtcs_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_dtcs_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_dtcs_response.h
deleted file mode 120000
index 378b95743b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_dtcs_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_get_dtcs_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_request.h
deleted file mode 120000
index 2dde6fcea0..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_get_vehicle_data_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_request_template.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_request_template.h
deleted file mode 120000
index abc1bbb910..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_request_template.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_get_vehicle_data_request_template.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_response.h
deleted file mode 120000
index 0f5636732a..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_get_vehicle_data_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_response_template.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_response_template.h
deleted file mode 120000
index cbde6eb303..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_data_response_template.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_get_vehicle_data_response_template.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_type_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_type_request.h
deleted file mode 120000
index 534638fb6e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_type_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_get_vehicle_type_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_type_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_type_response.h
deleted file mode 120000
index d346b466cc..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_get_vehicle_type_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_get_vehicle_type_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_is_ready_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_is_ready_request.h
deleted file mode 120000
index 2b345707b5..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_is_ready_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_is_ready_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_is_ready_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_is_ready_response.h
deleted file mode 120000
index 95ba17d5e5..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_is_ready_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_is_ready_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_read_did_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_read_did_request.h
deleted file mode 120000
index de1f2ac0d6..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_read_did_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_read_did_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_read_did_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_read_did_response.h
deleted file mode 120000
index 2ba6a58d24..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_read_did_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_read_did_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request.h
deleted file mode 120000
index 61ddc3a548..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request_template.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request_template.h
deleted file mode 120000
index 0822b5732a..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request_template.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_subscribe_vehicle_data_request_template.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response.h
deleted file mode 120000
index 485cc17afe..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response_template.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response_template.h
deleted file mode 120000
index 6790cc663c..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response_template.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_subscribe_vehicle_data_response_template.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request.h
deleted file mode 120000
index 786a8cabe9..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request_template.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request_template.h
deleted file mode 120000
index c95c2267a1..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request_template.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_request_template.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response.h
deleted file mode 120000
index 7fe6df28ee..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response_template.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response_template.h
deleted file mode 120000
index aed21a8296..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response_template.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vi_unsubscribe_vehicle_data_response_template.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_add_command_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_add_command_request.h
deleted file mode 120000
index 7fe9944f31..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_add_command_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_add_command_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_add_command_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_add_command_response.h
deleted file mode 120000
index 734f31c8d4..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_add_command_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_add_command_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_change_registration_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_change_registration_request.h
deleted file mode 120000
index d8e68ce6d9..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_change_registration_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_change_registration_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_change_registration_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_change_registration_response.h
deleted file mode 120000
index b220b61c94..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_change_registration_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_change_registration_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_delete_command_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_delete_command_request.h
deleted file mode 120000
index 864ab3d817..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_delete_command_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_delete_command_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_delete_command_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_delete_command_response.h
deleted file mode 120000
index 02be59d164..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_delete_command_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_delete_command_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_capabilities_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_capabilities_request.h
deleted file mode 120000
index 48f24ad628..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_capabilities_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_get_capabilities_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_capabilities_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_capabilities_response.h
deleted file mode 120000
index e5f7e2d645..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_capabilities_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_get_capabilities_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_language_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_language_request.h
deleted file mode 120000
index a625a08837..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_language_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_get_language_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_language_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_language_response.h
deleted file mode 120000
index 8facd3e436..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_language_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_get_language_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_supported_languages_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_supported_languages_request.h
deleted file mode 120000
index df9ab1ed8d..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_supported_languages_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_get_supported_languages_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_supported_languages_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_supported_languages_response.h
deleted file mode 120000
index dbd01ab4ff..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_get_supported_languages_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_get_supported_languages_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_is_ready_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_is_ready_request.h
deleted file mode 120000
index 79cbd18e87..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_is_ready_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_is_ready_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_is_ready_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_is_ready_response.h
deleted file mode 120000
index b9db7f3fda..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_is_ready_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_is_ready_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_perform_interaction_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_perform_interaction_request.h
deleted file mode 120000
index c26f6f8237..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_perform_interaction_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_perform_interaction_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_perform_interaction_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_perform_interaction_response.h
deleted file mode 120000
index 6dcda065e2..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/hmi/vr_perform_interaction_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/hmi/vr_perform_interaction_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_command_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_command_request.h
deleted file mode 120000
index cbae637fe0..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_command_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/add_command_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_command_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_command_response.h
deleted file mode 120000
index d2bd280607..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_command_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/add_command_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_sub_menu_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_sub_menu_request.h
deleted file mode 120000
index e2e5940aae..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_sub_menu_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/add_sub_menu_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_sub_menu_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_sub_menu_response.h
deleted file mode 120000
index fdac5156c3..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/add_sub_menu_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/add_sub_menu_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_maneuver_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_maneuver_request.h
deleted file mode 120000
index ff657e3327..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_maneuver_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/alert_maneuver_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_maneuver_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_maneuver_response.h
deleted file mode 120000
index b78ff30d89..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_maneuver_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/alert_maneuver_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_request.h
deleted file mode 120000
index c251277605..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/alert_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_response.h
deleted file mode 120000
index 42269e9ed6..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/alert_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/alert_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/change_registration_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/change_registration_request.h
deleted file mode 120000
index aa92e20658..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/change_registration_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/change_registration_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/change_registration_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/change_registration_response.h
deleted file mode 120000
index b0cb006227..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/change_registration_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/change_registration_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/create_interaction_choice_set_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/create_interaction_choice_set_request.h
deleted file mode 120000
index 64357af6c8..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/create_interaction_choice_set_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/create_interaction_choice_set_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/create_interaction_choice_set_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/create_interaction_choice_set_response.h
deleted file mode 120000
index eb4145c228..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/create_interaction_choice_set_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/create_interaction_choice_set_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_command_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_command_request.h
deleted file mode 120000
index d7187ab756..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_command_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/delete_command_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_command_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_command_response.h
deleted file mode 120000
index 4d877b7cdb..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_command_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/delete_command_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_file_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_file_request.h
deleted file mode 120000
index 7f82ed14e0..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_file_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/delete_file_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_file_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_file_response.h
deleted file mode 120000
index f419031684..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_file_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/delete_file_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_interaction_choice_set_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_interaction_choice_set_request.h
deleted file mode 120000
index d1ac513649..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_interaction_choice_set_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/delete_interaction_choice_set_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_interaction_choice_set_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_interaction_choice_set_response.h
deleted file mode 120000
index abf9ed5eb5..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_interaction_choice_set_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/delete_interaction_choice_set_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_sub_menu_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_sub_menu_request.h
deleted file mode 120000
index 10baa78dd3..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_sub_menu_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/delete_sub_menu_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_sub_menu_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_sub_menu_response.h
deleted file mode 120000
index 22f6561919..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/delete_sub_menu_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/delete_sub_menu_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/diagnostic_message_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/diagnostic_message_request.h
deleted file mode 120000
index cfc9d7bc38..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/diagnostic_message_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/diagnostic_message_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/diagnostic_message_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/diagnostic_message_response.h
deleted file mode 120000
index 73fe20f089..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/diagnostic_message_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/diagnostic_message_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/dial_number_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/dial_number_request.h
deleted file mode 120000
index c448f3a5aa..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/dial_number_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/dial_number_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/end_audio_pass_thru_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/end_audio_pass_thru_request.h
deleted file mode 120000
index 331f7b8cca..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/end_audio_pass_thru_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/end_audio_pass_thru_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/end_audio_pass_thru_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/end_audio_pass_thru_response.h
deleted file mode 120000
index 7b7eff611e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/end_audio_pass_thru_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/end_audio_pass_thru_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/generic_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/generic_response.h
deleted file mode 120000
index 10f5e3b009..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/generic_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/generic_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_dtcs_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_dtcs_request.h
deleted file mode 120000
index 995fb84419..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_dtcs_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/get_dtcs_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_dtcs_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_dtcs_response.h
deleted file mode 120000
index 53786a9163..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_dtcs_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/get_dtcs_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_vehicle_data_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_vehicle_data_request.h
deleted file mode 120000
index 18e2658a63..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_vehicle_data_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/get_vehicle_data_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_vehicle_data_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_vehicle_data_response.h
deleted file mode 120000
index 9641c9cb72..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/get_vehicle_data_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/get_vehicle_data_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/list_files_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/list_files_request.h
deleted file mode 120000
index 633ee9dda3..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/list_files_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/list_files_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/list_files_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/list_files_response.h
deleted file mode 120000
index 75443a836e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/list_files_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/list_files_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_app_interface_unregistered_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_app_interface_unregistered_notification.h
deleted file mode 120000
index 82c74342aa..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_app_interface_unregistered_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_app_interface_unregistered_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_audio_pass_thru_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_audio_pass_thru_notification.h
deleted file mode 120000
index 7cf9f3d1c0..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_audio_pass_thru_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_audio_pass_thru_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_button_event_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_button_event_notification.h
deleted file mode 120000
index d41cba2c0c..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_button_event_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_button_event_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_button_press_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_button_press_notification.h
deleted file mode 120000
index 7ef855750a..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_button_press_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_button_press_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_command_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_command_notification.h
deleted file mode 120000
index 759c4d33f1..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_command_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_command_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_driver_distraction_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_driver_distraction_notification.h
deleted file mode 120000
index ebe3fed8ff..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_driver_distraction_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_driver_distraction_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_hash_change_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_hash_change_notification.h
deleted file mode 120000
index 16aa5c9bb0..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_hash_change_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_hash_change_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_hmi_status_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_hmi_status_notification.h
deleted file mode 120000
index bc9cedbfb3..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_hmi_status_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_hmi_status_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_hmi_status_notification_from_mobile.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_hmi_status_notification_from_mobile.h
deleted file mode 120000
index 617cc46042..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_hmi_status_notification_from_mobile.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_hmi_status_notification_from_mobile.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_keyboard_input_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_keyboard_input_notification.h
deleted file mode 120000
index 41474d2cb7..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_keyboard_input_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_keyboard_input_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_language_change_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_language_change_notification.h
deleted file mode 120000
index d65fdc56a7..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_language_change_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_language_change_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_permissions_change_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_permissions_change_notification.h
deleted file mode 120000
index 9dff29eebf..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_permissions_change_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_permissions_change_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_system_request_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_system_request_notification.h
deleted file mode 120000
index 77c3741be5..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_system_request_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_system_request_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_tbt_client_state_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_tbt_client_state_notification.h
deleted file mode 120000
index 63d770348d..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_tbt_client_state_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_tbt_client_state_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_touch_event_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_touch_event_notification.h
deleted file mode 120000
index 6ec885678f..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_touch_event_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_touch_event_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_vehicle_data_notification.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_vehicle_data_notification.h
deleted file mode 120000
index 4b628b7c62..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/on_vehicle_data_notification.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/on_vehicle_data_notification.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_audio_pass_thru_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_audio_pass_thru_request.h
deleted file mode 120000
index 0316606c08..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_audio_pass_thru_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/perform_audio_pass_thru_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_audio_pass_thru_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_audio_pass_thru_response.h
deleted file mode 120000
index ba81d3e53b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_audio_pass_thru_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/perform_audio_pass_thru_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_interaction_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_interaction_request.h
deleted file mode 120000
index 9cb56984d5..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_interaction_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/perform_interaction_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_interaction_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_interaction_response.h
deleted file mode 120000
index 8b90adea95..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/perform_interaction_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/perform_interaction_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/put_file_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/put_file_request.h
deleted file mode 120000
index be4b97728e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/put_file_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/put_file_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/put_file_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/put_file_response.h
deleted file mode 120000
index 664c76e53f..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/put_file_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/put_file_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/read_did_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/read_did_request.h
deleted file mode 120000
index c9727e504f..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/read_did_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/read_did_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/read_did_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/read_did_response.h
deleted file mode 120000
index 95e0c625a5..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/read_did_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/read_did_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/register_app_interface_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/register_app_interface_request.h
deleted file mode 120000
index cc1fb2feef..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/register_app_interface_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/register_app_interface_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/register_app_interface_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/register_app_interface_response.h
deleted file mode 120000
index 0f1ffccc69..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/register_app_interface_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/register_app_interface_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/reset_global_properties_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/reset_global_properties_request.h
deleted file mode 120000
index ea2ae40b8f..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/reset_global_properties_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/reset_global_properties_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/reset_global_properties_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/reset_global_properties_response.h
deleted file mode 120000
index daba7103a2..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/reset_global_properties_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/reset_global_properties_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/scrollable_message_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/scrollable_message_request.h
deleted file mode 120000
index 50bd0a294b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/scrollable_message_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/scrollable_message_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/scrollable_message_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/scrollable_message_response.h
deleted file mode 120000
index d73af42f69..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/scrollable_message_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/scrollable_message_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/send_location_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/send_location_request.h
deleted file mode 120000
index d362057759..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/send_location_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/send_location_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/send_location_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/send_location_response.h
deleted file mode 120000
index 547cf897e5..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/send_location_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/send_location_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_app_icon_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_app_icon_request.h
deleted file mode 120000
index a2b137233e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_app_icon_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/set_app_icon_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_app_icon_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_app_icon_response.h
deleted file mode 120000
index 6deebcabc8..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_app_icon_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/set_app_icon_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_display_layout_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_display_layout_request.h
deleted file mode 120000
index f02f9317c6..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_display_layout_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/set_display_layout_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_display_layout_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_display_layout_response.h
deleted file mode 120000
index b5b2e73549..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_display_layout_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/set_display_layout_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_global_properties_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_global_properties_request.h
deleted file mode 120000
index fee7f8c00b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_global_properties_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/set_global_properties_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_global_properties_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_global_properties_response.h
deleted file mode 120000
index 76c7bf2497..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_global_properties_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/set_global_properties_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_icon_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_icon_request.h
deleted file mode 120000
index 2db9520a22..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_icon_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/set_icon_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_icon_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_icon_response.h
deleted file mode 120000
index ac04c4d9f3..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_icon_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/set_icon_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_media_clock_timer_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_media_clock_timer_request.h
deleted file mode 120000
index 1961671131..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_media_clock_timer_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/set_media_clock_timer_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_media_clock_timer_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_media_clock_timer_response.h
deleted file mode 120000
index ecffab999b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/set_media_clock_timer_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/set_media_clock_timer_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_constant_tbt_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_constant_tbt_request.h
deleted file mode 120000
index 35acb02f10..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_constant_tbt_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/show_constant_tbt_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_constant_tbt_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_constant_tbt_response.h
deleted file mode 120000
index 5b3738ca80..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_constant_tbt_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/show_constant_tbt_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_request.h
deleted file mode 120000
index e299277b4d..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/show_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_response.h
deleted file mode 120000
index afa7d2547e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/show_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/show_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/slider_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/slider_request.h
deleted file mode 120000
index 8a1c85497e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/slider_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/slider_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/slider_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/slider_response.h
deleted file mode 120000
index a869256ee0..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/slider_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/slider_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/speak_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/speak_request.h
deleted file mode 120000
index 5921def798..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/speak_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/speak_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/speak_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/speak_response.h
deleted file mode 120000
index f4b69f7937..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/speak_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/speak_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_button_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_button_request.h
deleted file mode 120000
index e5da6a4484..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_button_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/subscribe_button_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_button_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_button_response.h
deleted file mode 120000
index dda081d9b4..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_button_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/subscribe_button_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_vehicle_data_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_vehicle_data_request.h
deleted file mode 120000
index 8e4908abd8..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_vehicle_data_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/subscribe_vehicle_data_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_vehicle_data_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_vehicle_data_response.h
deleted file mode 120000
index 262a56f0d4..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/subscribe_vehicle_data_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/subscribe_vehicle_data_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/system_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/system_request.h
deleted file mode 120000
index b4b9ca7641..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/system_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/system_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/system_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/system_response.h
deleted file mode 120000
index f71dd2f314..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/system_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/system_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unregister_app_interface_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unregister_app_interface_request.h
deleted file mode 120000
index 0851fea063..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unregister_app_interface_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/unregister_app_interface_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unregister_app_interface_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unregister_app_interface_response.h
deleted file mode 120000
index 16ed184de8..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unregister_app_interface_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/unregister_app_interface_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_button_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_button_request.h
deleted file mode 120000
index 98b4796053..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_button_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/unsubscribe_button_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_button_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_button_response.h
deleted file mode 120000
index 12d3efc86e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_button_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/unsubscribe_button_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_vehicle_data_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_vehicle_data_request.h
deleted file mode 120000
index 8bd2f28445..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_vehicle_data_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/unsubscribe_vehicle_data_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_vehicle_data_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_vehicle_data_response.h
deleted file mode 120000
index 980a885341..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/unsubscribe_vehicle_data_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/unsubscribe_vehicle_data_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/update_turn_list_request.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/update_turn_list_request.h
deleted file mode 120000
index 4432804761..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/update_turn_list_request.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/update_turn_list_request.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/update_turn_list_response.h b/src/components/application_manager/test/mock/include/application_manager/commands/mobile/update_turn_list_response.h
deleted file mode 120000
index c778fb169e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/mobile/update_turn_list_response.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/commands/mobile/update_turn_list_response.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/commands/pending.h b/src/components/application_manager/test/mock/include/application_manager/commands/pending.h
deleted file mode 120000
index 4dd9a4a88f..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/commands/pending.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/commands/pending.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/event_engine/event.h b/src/components/application_manager/test/mock/include/application_manager/event_engine/event.h
deleted file mode 120000
index 7b6f069885..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/event_engine/event.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/event_engine/event.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/event_engine/event_dispatcher.h b/src/components/application_manager/test/mock/include/application_manager/event_engine/event_dispatcher.h
deleted file mode 120000
index b0f651781b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/event_engine/event_dispatcher.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/event_engine/event_dispatcher.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/event_engine/event_observer.h b/src/components/application_manager/test/mock/include/application_manager/event_engine/event_observer.h
deleted file mode 120000
index dc6af86240..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/event_engine/event_observer.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/event_engine/event_observer.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/hmi_capabilities.h b/src/components/application_manager/test/mock/include/application_manager/hmi_capabilities.h
deleted file mode 120000
index 9ceb7b9b97..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/hmi_capabilities.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/hmi_capabilities.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/hmi_command_factory.h b/src/components/application_manager/test/mock/include/application_manager/hmi_command_factory.h
deleted file mode 120000
index 327faa9730..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/hmi_command_factory.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/hmi_command_factory.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/hmi_state.h b/src/components/application_manager/test/mock/include/application_manager/hmi_state.h
deleted file mode 120000
index 62e3c1a937..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/hmi_state.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/hmi_state.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/message.h b/src/components/application_manager/test/mock/include/application_manager/message.h
deleted file mode 120000
index 3ae48a9129..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/message.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/message.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/message_helper.h b/src/components/application_manager/test/mock/include/application_manager/message_helper.h
deleted file mode 120000
index 6227694b37..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/message_helper.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/message_helper.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/mobile_command_factory.h b/src/components/application_manager/test/mock/include/application_manager/mobile_command_factory.h
deleted file mode 120000
index 20bd35432a..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/mobile_command_factory.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/mobile_command_factory.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/mobile_message_handler.h b/src/components/application_manager/test/mock/include/application_manager/mobile_message_handler.h
deleted file mode 120000
index 8cfa824c4a..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/mobile_message_handler.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/mobile_message_handler.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/policies/delegates/app_permission_delegate.h b/src/components/application_manager/test/mock/include/application_manager/policies/delegates/app_permission_delegate.h
deleted file mode 120000
index 0dc895b545..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/policies/delegates/app_permission_delegate.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/policies/delegates/app_permission_delegate.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/policies/delegates/statistics_delegate.h b/src/components/application_manager/test/mock/include/application_manager/policies/delegates/statistics_delegate.h
deleted file mode 120000
index 4e71cefaa3..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/policies/delegates/statistics_delegate.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../../include/application_manager/policies/delegates/statistics_delegate.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/policies/policy_event_observer.h b/src/components/application_manager/test/mock/include/application_manager/policies/policy_event_observer.h
deleted file mode 120000
index 5cba69ed20..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/policies/policy_event_observer.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/policies/policy_event_observer.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/policies/policy_handler.h b/src/components/application_manager/test/mock/include/application_manager/policies/policy_handler.h
deleted file mode 120000
index 522113630c..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/policies/policy_handler.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/policies/policy_handler.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/policies/policy_handler_observer.h b/src/components/application_manager/test/mock/include/application_manager/policies/policy_handler_observer.h
deleted file mode 120000
index 22acc100db..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/policies/policy_handler_observer.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/policies/policy_handler_observer.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/policies/policy_retry_sequence.h b/src/components/application_manager/test/mock/include/application_manager/policies/policy_retry_sequence.h
deleted file mode 120000
index 569a62252b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/policies/policy_retry_sequence.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/policies/policy_retry_sequence.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/policies/pt_exchange_handler.h b/src/components/application_manager/test/mock/include/application_manager/policies/pt_exchange_handler.h
deleted file mode 120000
index 22e071c885..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/policies/pt_exchange_handler.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/policies/pt_exchange_handler.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/policies/pt_exchange_handler_ext.h b/src/components/application_manager/test/mock/include/application_manager/policies/pt_exchange_handler_ext.h
deleted file mode 120000
index 080045466b..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/policies/pt_exchange_handler_ext.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/policies/pt_exchange_handler_ext.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/policies/pt_exchange_handler_impl.h b/src/components/application_manager/test/mock/include/application_manager/policies/pt_exchange_handler_impl.h
deleted file mode 120000
index f3a2017c58..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/policies/pt_exchange_handler_impl.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../../include/application_manager/policies/pt_exchange_handler_impl.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/request_controller.h b/src/components/application_manager/test/mock/include/application_manager/request_controller.h
deleted file mode 120000
index 1b619cf77c..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/request_controller.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/request_controller.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/request_info.h b/src/components/application_manager/test/mock/include/application_manager/request_info.h
deleted file mode 120000
index c726e09a39..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/request_info.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/request_info.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/resume_ctrl.h b/src/components/application_manager/test/mock/include/application_manager/resume_ctrl.h
deleted file mode 120000
index 889e967d4e..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/resume_ctrl.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/resume_ctrl.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/smart_object_keys.h b/src/components/application_manager/test/mock/include/application_manager/smart_object_keys.h
deleted file mode 120000
index 94919c6ced..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/smart_object_keys.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/smart_object_keys.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/state_context.h b/src/components/application_manager/test/mock/include/application_manager/state_context.h
deleted file mode 120000
index f94c0054c2..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/state_context.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/state_context.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/state_controller.h b/src/components/application_manager/test/mock/include/application_manager/state_controller.h
deleted file mode 120000
index 6c61865d18..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/state_controller.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/state_controller.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/time_metric_observer.h b/src/components/application_manager/test/mock/include/application_manager/time_metric_observer.h
deleted file mode 120000
index 4786675fde..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/time_metric_observer.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/time_metric_observer.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/usage_statistics.h b/src/components/application_manager/test/mock/include/application_manager/usage_statistics.h
deleted file mode 120000
index bff65d5633..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/usage_statistics.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/usage_statistics.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/include/application_manager/vehicle_info_data.h b/src/components/application_manager/test/mock/include/application_manager/vehicle_info_data.h
deleted file mode 120000
index 0ea43f1210..0000000000
--- a/src/components/application_manager/test/mock/include/application_manager/vehicle_info_data.h
+++ /dev/null
@@ -1 +0,0 @@
-../../../../include/application_manager/vehicle_info_data.h \ No newline at end of file
diff --git a/src/components/application_manager/test/mock/src/application_manager_impl.cc b/src/components/application_manager/test/mock/src/application_manager_impl.cc
deleted file mode 100644
index b5d80e740a..0000000000
--- a/src/components/application_manager/test/mock/src/application_manager_impl.cc
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "application_manager/application_manager_impl.h"
diff --git a/src/components/application_manager/test/mock_message_helper.cc b/src/components/application_manager/test/mock_message_helper.cc
new file mode 100644
index 0000000000..c53927d3a4
--- /dev/null
+++ b/src/components/application_manager/test/mock_message_helper.cc
@@ -0,0 +1,309 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/message_helper.h"
+#include "application_manager/mock_message_helper.h"
+#include "application_manager/policies/policy_handler_interface.h"
+
+namespace application_manager {
+
+void MessageHelper::SendHashUpdateNotification(uint32_t const app_id,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendHashUpdateNotification(
+ app_id, app_mngr);
+}
+void MessageHelper::SendNaviStartStream(int32_t connection_key,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendNaviStartStream(connection_key,
+ app_mngr);
+}
+void MessageHelper::SendNaviStopStream(int32_t connection_key,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendNaviStopStream(connection_key,
+ app_mngr);
+}
+void MessageHelper::SendAudioStartStream(int32_t connection_key,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendAudioStartStream(connection_key,
+ app_mngr);
+}
+void MessageHelper::SendAudioStopStream(int32_t connection_key,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendAudioStopStream(connection_key,
+ app_mngr);
+}
+void MessageHelper::SendOnDataStreaming(protocol_handler::ServiceType service,
+ bool available,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendOnDataStreaming(
+ service, available, app_mngr);
+}
+
+smart_objects::SmartObjectSPtr GetHashUpdateNotification(
+ const uint32_t app_id) {
+ return MockMessageHelper::message_helper_mock()->GetHashUpdateNotification(
+ app_id);
+}
+
+std::string MessageHelper::HMIResultToString(
+ hmi_apis::Common_Result::eType hmi_result) {
+ return MockMessageHelper::message_helper_mock()->HMIResultToString(
+ hmi_result);
+}
+
+hmi_apis::Common_Result::eType MessageHelper::HMIResultFromString(
+ const std::string& hmi_result) {
+ return MockMessageHelper::message_helper_mock()->HMIResultFromString(
+ hmi_result);
+}
+
+std::string MessageHelper::MobileResultToString(
+ mobile_apis::Result::eType mobile_result) {
+ return MockMessageHelper::message_helper_mock()->MobileResultToString(
+ mobile_result);
+}
+
+mobile_api::Result::eType MessageHelper::MobileResultFromString(
+ const std::string& mobile_result) {
+ return MockMessageHelper::message_helper_mock()->MobileResultFromString(
+ mobile_result);
+}
+
+mobile_api::Result::eType MessageHelper::HMIToMobileResult(
+ const hmi_apis::Common_Result::eType hmi_result) {
+ return MockMessageHelper::message_helper_mock()->HMIToMobileResult(
+ hmi_result);
+}
+
+hmi_apis::Common_Result::eType MessageHelper::MobileToHMIResult(
+ const mobile_api::Result::eType mobile_result) {
+ return MockMessageHelper::message_helper_mock()->MobileToHMIResult(
+ mobile_result);
+}
+
+mobile_api::HMILevel::eType MessageHelper::StringToHMILevel(
+ const std::string& hmi_level) {
+ return MockMessageHelper::message_helper_mock()->StringToHMILevel(hmi_level);
+}
+
+smart_objects::SmartObjectSPtr CreateDeviceListSO(
+ const connection_handler::DeviceMap& devices) {
+ return MockMessageHelper::message_helper_mock()->CreateDeviceListSO(devices);
+}
+
+void MessageHelper::SendOnAppPermissionsChangedNotification(
+ uint32_t connection_key,
+ const policy::AppPermissions& permissions,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()
+ ->SendOnAppPermissionsChangedNotification(
+ connection_key, permissions, app_mngr);
+}
+
+void MessageHelper::SendGetUserFriendlyMessageResponse(
+ const std::vector<policy::UserFriendlyMessage>& msg,
+ uint32_t correlation_id,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendGetUserFriendlyMessageResponse(
+ msg, correlation_id, app_mngr);
+}
+
+void MessageHelper::SendGetStatusUpdateResponse(const std::string& status,
+ uint32_t correlation_id,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendGetStatusUpdateResponse(
+ status, correlation_id, app_mngr);
+}
+
+void MessageHelper::SendOnStatusUpdate(const std::string& status,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendOnStatusUpdate(status,
+ app_mngr);
+}
+
+void MessageHelper::SendGetSystemInfoRequest(ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendGetSystemInfoRequest(app_mngr);
+}
+
+void MessageHelper::CreateGetVehicleDataRequest(
+ uint32_t correlation_id,
+ const std::vector<std::string>& params,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->CreateGetVehicleDataRequest(
+ correlation_id, params, app_mngr);
+}
+
+void MessageHelper::SendGetListOfPermissionsResponse(
+ const std::vector<policy::FunctionalGroupPermission>& permissions,
+ uint32_t correlation_id,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendGetListOfPermissionsResponse(
+ permissions, correlation_id, app_mngr);
+}
+
+void MessageHelper::SendOnPermissionsChangeNotification(
+ uint32_t connection_key,
+ const policy::Permissions& permissions,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendOnPermissionsChangeNotification(
+ connection_key, permissions, app_mngr);
+}
+
+void MessageHelper::SendPolicySnapshotNotification(
+ uint32_t connection_key,
+ const std::vector<uint8_t>& policy_data,
+ const std::string& url,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendPolicySnapshotNotification(
+ connection_key, policy_data, url, app_mngr);
+}
+
+void MessageHelper::SendSDLActivateAppResponse(
+ policy::AppPermissions& permissions,
+ uint32_t correlation_id,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendSDLActivateAppResponse(
+ permissions, correlation_id, app_mngr);
+}
+
+void MessageHelper::SendPolicyUpdate(const std::string& file_path,
+ int timeout,
+ const std::vector<int>& retries,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendPolicyUpdate(
+ file_path, timeout, retries, app_mngr);
+}
+
+void MessageHelper::SendUpdateSDLResponse(const std::string& result,
+ uint32_t correlation_id,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendUpdateSDLResponse(
+ result, correlation_id, app_mngr);
+}
+
+hmi_apis::Common_Language::eType MessageHelper::CommonLanguageFromString(
+ const std::string& language) {
+ return MockMessageHelper::message_helper_mock()->CommonLanguageFromString(
+ language);
+}
+
+smart_objects::SmartObjectSPtr MessageHelper::CreateModuleInfoSO(
+ uint32_t function_id, ApplicationManager& app_mngr) {
+ return MockMessageHelper::message_helper_mock()->CreateModuleInfoSO(
+ function_id, app_mngr);
+}
+
+MockMessageHelper* MockMessageHelper::message_helper_mock() {
+ static MockMessageHelper message_helper_mock;
+ return &message_helper_mock;
+}
+void MessageHelper::SendAllOnButtonSubscriptionNotificationsForApp(
+ ApplicationConstSharedPtr app, ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()
+ ->SendAllOnButtonSubscriptionNotificationsForApp(app, app_mngr);
+}
+
+void MessageHelper::SendOnResumeAudioSourceToHMI(const uint32_t app_id,
+ ApplicationManager& app_mngr) {
+ MockMessageHelper::message_helper_mock()->SendOnResumeAudioSourceToHMI(
+ app_id, app_mngr);
+}
+
+smart_objects::SmartObjectList MessageHelper::CreateAddSubMenuRequestToHMI(
+ ApplicationConstSharedPtr app, const uint32_t correlation_id) {
+ return MockMessageHelper::message_helper_mock()->CreateAddSubMenuRequestToHMI(
+ app, correlation_id);
+}
+
+smart_objects::SmartObjectList MessageHelper::CreateAddCommandRequestToHMI(
+ ApplicationConstSharedPtr app, ApplicationManager& app_mngr) {
+ return MockMessageHelper::message_helper_mock()->CreateAddCommandRequestToHMI(
+ app, app_mngr);
+}
+
+smart_objects::SmartObjectList
+MessageHelper::CreateAddVRCommandRequestFromChoiceToHMI(
+ ApplicationConstSharedPtr app, ApplicationManager& app_mngr) {
+ return MockMessageHelper::message_helper_mock()
+ ->CreateAddVRCommandRequestFromChoiceToHMI(app);
+}
+
+void MessageHelper::SendGlobalPropertiesToHMI(ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr) {
+ return MockMessageHelper::message_helper_mock()->SendGlobalPropertiesToHMI(
+ app);
+}
+
+smart_objects::SmartObjectList MessageHelper::GetIVISubscriptionRequests(
+ ApplicationSharedPtr app, ApplicationManager& app_mngr) {
+ return MockMessageHelper::message_helper_mock()->GetIVISubscriptionRequests(
+ app);
+}
+
+mobile_apis::Result::eType MessageHelper::VerifyImageFiles(
+ smart_objects::SmartObject& message,
+ ApplicationConstSharedPtr app,
+ ApplicationManager& app_mngr) {
+ return MockMessageHelper::message_helper_mock()->VerifyImageFiles(
+ message, app, app_mngr);
+}
+std::string MessageHelper::CommonLanguageToString(
+ hmi_apis::Common_Language::eType lang) {
+ return MockMessageHelper::message_helper_mock()->CommonLanguageToString(lang);
+}
+
+smart_objects::SmartObjectSPtr MessageHelper::GetBCActivateAppRequestToHMI(
+ ApplicationConstSharedPtr app,
+ const protocol_handler::SessionObserver& session_observer,
+ const policy::PolicyHandlerInterface& policy_handler,
+ hmi_apis::Common_HMILevel::eType level,
+ bool send_policy_priority,
+ ApplicationManager& app_mngr) {
+ return MockMessageHelper::message_helper_mock()->GetBCActivateAppRequestToHMI(
+ app,
+ session_observer,
+ policy_handler,
+ level,
+ send_policy_priority,
+ app_mngr);
+}
+
+NsSmartDeviceLink::NsSmartObjects::SmartObjectSPtr
+MessageHelper::GetOnAppInterfaceUnregisteredNotificationToMobile(
+ int32_t connection_key,
+ mobile_apis::AppInterfaceUnregisteredReason::eType reason) {
+ return MockMessageHelper::message_helper_mock()
+ ->GetOnAppInterfaceUnregisteredNotificationToMobile(connection_key,
+ reason);
+}
+
+} // namespace application_manager
diff --git a/src/components/application_manager/test/policy_event_observer_test.cc b/src/components/application_manager/test/policy_event_observer_test.cc
new file mode 100644
index 0000000000..25b54453e5
--- /dev/null
+++ b/src/components/application_manager/test/policy_event_observer_test.cc
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/policies/policy_event_observer.h"
+#include "application_manager/policies/mock_policy_handler_interface.h"
+
+#include "gmock/gmock.h"
+#include "policy/policy_types.h"
+#include "smart_objects/smart_object.h"
+#include "application_manager/mock_event_dispatcher.h"
+
+namespace test {
+namespace components {
+namespace policy_test {
+
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+using application_manager::event_engine::Event;
+using namespace policy;
+
+using testing::_;
+using ::testing::Return;
+
+class PolicyEventObserverTest : public ::testing::Test {
+ public:
+ PolicyEventObserverTest()
+ : policy_event_observer_(NULL), event_(NULL), field_name("odometer") {}
+
+ protected:
+ MockPolicyHandlerInterface policy_handler_mock_;
+ event_engine_test::MockEventDispatcher mock_event_dispatcher_;
+ PolicyEventObserver* policy_event_observer_;
+ Event* event_;
+ smart_objects::SmartObject smart_object_;
+ const std::string field_name;
+ const int field_value = 100;
+
+ virtual void SetUp() OVERRIDE {
+ policy_event_observer_ =
+ new PolicyEventObserver(&policy_handler_mock_, mock_event_dispatcher_);
+ }
+
+ void TearDown() OVERRIDE {
+ delete policy_event_observer_;
+ DeleteEvent();
+ }
+
+ void CreateEvent(const Event::EventID& event_id) {
+ event_ = new Event(event_id);
+ }
+
+ void CookSmartObject(const hmi_apis::Common_Result::eType& result,
+ const std::string& msg_params_field,
+ int msg_params_field_value) {
+ smart_object_["params"]["code"] = result;
+ smart_object_["msg_params"][msg_params_field] = msg_params_field_value;
+ }
+
+ void CheckResultsOnEvent(uint32_t pt_updated_calls_number,
+ uint32_t on_system_ready_calls_number) {
+ event_->set_smart_object(smart_object_);
+ EXPECT_CALL(policy_handler_mock_,
+ PTUpdatedAt(Counters::KILOMETERS, field_value))
+ .Times(pt_updated_calls_number);
+ EXPECT_CALL(policy_handler_mock_, OnSystemReady())
+ .Times(on_system_ready_calls_number);
+ policy_event_observer_->on_event(*event_);
+ }
+
+ void DeleteEvent() {
+ delete event_;
+ }
+};
+
+TEST_F(PolicyEventObserverTest, OnEvent_EventInvalid_ExpectNoProcessingEvent) {
+ // Arrange
+ CreateEvent(Event::EventID::INVALID_ENUM);
+ CookSmartObject(hmi_apis::Common_Result::SUCCESS, field_name, field_value);
+ CheckResultsOnEvent(0u, 0u);
+}
+
+TEST_F(PolicyEventObserverTest,
+ OnEvent_EventInvalidCommonResult_ExpectNoProcessingEvent) {
+ // Arrange
+ CreateEvent(Event::EventID::VehicleInfo_GetVehicleData);
+ CookSmartObject(
+ hmi_apis::Common_Result::INVALID_DATA, field_name, field_value);
+ // Check
+ CheckResultsOnEvent(0u, 0u);
+}
+
+TEST_F(PolicyEventObserverTest,
+ OnEvent_EventGetVehicleData_ExpectProcessOdometerEvent) {
+ // Arrange
+ CreateEvent(Event::EventID::VehicleInfo_GetVehicleData);
+ CookSmartObject(hmi_apis::Common_Result::SUCCESS, field_name, field_value);
+ // Check
+ CheckResultsOnEvent(1u, 0u);
+}
+
+TEST_F(PolicyEventObserverTest,
+ OnEvent_EventBasicCommunication_OnReady_ExpectOnSystemReady) {
+ // Arrange
+ CreateEvent(Event::EventID::BasicCommunication_OnReady);
+ CookSmartObject(hmi_apis::Common_Result::SUCCESS, field_name, field_value);
+ // Check
+ CheckResultsOnEvent(0u, 1u);
+}
+
+} // namespace policy_event_observer
+} // namespace components
+} // namespace test
diff --git a/src/components/application_manager/test/policy_handler_test.cc b/src/components/application_manager/test/policy_handler_test.cc
new file mode 100644
index 0000000000..44b4791f85
--- /dev/null
+++ b/src/components/application_manager/test/policy_handler_test.cc
@@ -0,0 +1,1478 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <string>
+#include <vector>
+#include <fstream>
+#include "gmock/gmock.h"
+
+#include "application_manager/policies/policy_handler.h"
+#include "policy/mock_policy_manager.h"
+#include "connection_handler/connection_handler_impl.h"
+#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_impl.h"
+#include "security_manager/mock_security_manager.h"
+#include "security_manager/mock_crypto_manager.h"
+#include "application_manager/mock_message_helper.h"
+#include "connection_handler/mock_connection_handler_settings.h"
+#include "transport_manager/mock_transport_manager.h"
+#include "policy/policy_types.h"
+#include "json/reader.h"
+#include "json/writer.h"
+#include "json/value.h"
+#include "smart_objects/smart_object.h"
+#include "utils/file_system.h"
+#include "utils/make_shared.h"
+#include "utils/custom_string.h"
+#include "policy/usage_statistics/counter.h"
+#include "policy/usage_statistics/statistics_manager.h"
+#include "interfaces/MOBILE_API.h"
+#include "policy/mock_policy_settings.h"
+#include "application_manager/mock_application.h"
+#include "policy/usage_statistics/mock_statistics_manager.h"
+#include "protocol_handler/mock_session_observer.h"
+#include "connection_handler/mock_connection_handler.h"
+#include "application_manager/mock_application_manager.h"
+#include "application_manager/policies/mock_policy_handler_observer.h"
+#include "application_manager/mock_event_dispatcher.h"
+#include "application_manager/mock_state_controller.h"
+
+namespace test {
+namespace components {
+namespace policy_handler_test {
+
+using namespace application_manager;
+using namespace policy;
+using namespace utils::custom_string;
+using testing::_;
+using ::testing::Return;
+using ::testing::ReturnRef;
+using ::testing::NiceMock;
+using ::testing::SetArgReferee;
+using ::testing::SetArgPointee;
+using ::testing::DoAll;
+using ::testing::SetArgReferee;
+
+class PolicyHandlerTest : public ::testing::Test {
+ public:
+ PolicyHandlerTest()
+ : policy_handler_(policy_settings_, app_manager_)
+ , kPolicyAppId_("fake_app_id")
+ , kMacAddr_("kMacAddr_ess")
+ , kDeviceId_("fake_device_id")
+ , kHmiLevel_("NONE")
+ , kRpc_("fake_rpc")
+ , priority_("fake_priority")
+ , default_hmi_("fake_hmi")
+ , kPreloadPTFile_("sdl_preloaded_pt.json")
+ , kAppStorageFolder_("storage")
+ , app_set(test_app, app_lock)
+ , kAppId_(10u)
+ , kSnapshotFile_("snapshot")
+ , kSnapshotStorage_("snapshot_storage") {}
+
+ protected:
+ NiceMock<MockPolicySettings> policy_settings_;
+ NiceMock<event_engine_test::MockEventDispatcher> mock_event_dispatcher_;
+ utils::SharedPtr<application_manager_test::MockApplication> mock_app_;
+ connection_handler_test::MockConnectionHandler conn_handler;
+ protocol_handler_test::MockSessionObserver mock_session_observer;
+ application_manager_test::MockStateController mock_state_controller;
+ PolicyHandler policy_handler_;
+ utils::SharedPtr<policy_manager_test::MockPolicyManager> mock_policy_manager_;
+ application_manager_test::MockApplicationManager app_manager_;
+ const std::string kPolicyAppId_;
+ const std::string kMacAddr_;
+ const std::string kDeviceId_;
+ const std::string kHmiLevel_;
+ const std::string kRpc_;
+ std::string priority_;
+ std::string default_hmi_;
+ const std::string kPreloadPTFile_;
+ const std::string kAppStorageFolder_;
+ ApplicationSet test_app;
+ sync_primitives::Lock app_lock;
+ DataAccessor<ApplicationSet> app_set;
+ const uint32_t kAppId_;
+ const std::string kSnapshotFile_;
+ const std::string kSnapshotStorage_;
+
+ virtual void SetUp() OVERRIDE {
+ ON_CALL(app_manager_, applications()).WillByDefault(Return(app_set));
+ ON_CALL(policy_settings_, enable_policy()).WillByDefault(Return(true));
+ ON_CALL(app_manager_, event_dispatcher())
+ .WillByDefault(ReturnRef(mock_event_dispatcher_));
+ std::string path = file_system::CreateDirectory("storage");
+ file_system::CreateFile(path + "/" + "certificate");
+ mock_policy_manager_ =
+ utils::MakeShared<policy_manager_test::MockPolicyManager>();
+ ASSERT_TRUE(mock_policy_manager_.valid());
+
+ ON_CALL(app_manager_, connection_handler())
+ .WillByDefault(ReturnRef(conn_handler));
+ ON_CALL(conn_handler, get_session_observer())
+ .WillByDefault(ReturnRef(mock_session_observer));
+
+ mock_app_ = utils::MakeShared<application_manager_test::MockApplication>();
+ }
+
+ virtual void TearDown() OVERRIDE {
+ ON_CALL(mock_event_dispatcher_, remove_observer(_, _));
+ }
+
+ void ChangePolicyManagerToMock() {
+ policy_handler_.SetPolicyManager(mock_policy_manager_);
+ }
+
+ void EnablePolicy() {
+ ON_CALL(policy_settings_, enable_policy()).WillByDefault(Return(true));
+ ON_CALL(policy_settings_, preloaded_pt_file())
+ .WillByDefault(ReturnRef(kPreloadPTFile_));
+ ON_CALL(policy_settings_, app_storage_folder())
+ .WillByDefault(ReturnRef(kAppStorageFolder_));
+ }
+
+ void EnablePolicyAndPolicyManagerMock() {
+ EnablePolicy();
+ ChangePolicyManagerToMock();
+ }
+
+ void TestActivateApp(const uint32_t connection_key,
+ const uint32_t correlation_id);
+ void GetAppIDForSending();
+ void OnPendingPermissionChangePrecondition(
+ mobile_apis::HMILevel::eType hmi_level);
+
+ void ExtendedPolicyExpectations() {
+ const std::vector<int> retry_sequence_delay_seconds;
+
+ EXPECT_CALL(policy_settings_, policies_snapshot_file_name())
+ .WillOnce(ReturnRef(kSnapshotFile_));
+ EXPECT_CALL(policy_settings_, system_files_path())
+ .WillOnce(ReturnRef(kSnapshotStorage_));
+ EXPECT_CALL(*mock_policy_manager_, TimeoutExchange()).WillOnce(Return(1));
+ EXPECT_CALL(*mock_policy_manager_, RetrySequenceDelaysSeconds())
+ .WillOnce(Return(retry_sequence_delay_seconds));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendPolicyUpdate(_, _, _, _));
+ }
+};
+
+TEST_F(PolicyHandlerTest, LoadPolicyLibrary_Method_ExpectLibraryLoaded) {
+ // Check before policy enabled from ini file
+ EXPECT_CALL(policy_settings_, enable_policy()).WillRepeatedly(Return(false));
+ EXPECT_FALSE(policy_handler_.LoadPolicyLibrary());
+ EXPECT_CALL(policy_settings_, enable_policy()).WillRepeatedly(Return(true));
+ // Check
+ EXPECT_TRUE(policy_handler_.LoadPolicyLibrary());
+
+ EXPECT_TRUE(policy_handler_.UnloadPolicyLibrary());
+}
+
+TEST_F(PolicyHandlerTest,
+ InitPolicyTable_WithoutPreloadedFile_ExpectPolicyTableNotInitialized) {
+ // Check
+ EXPECT_FALSE(policy_handler_.InitPolicyTable());
+}
+
+TEST_F(PolicyHandlerTest,
+ InitPolicyTable_WithPreloadedFile_ExpectPolicyTableInitialized) {
+ // Arrange
+ EnablePolicy();
+ EXPECT_TRUE(policy_handler_.LoadPolicyLibrary());
+ // Check
+ EXPECT_TRUE(policy_handler_.InitPolicyTable());
+ EXPECT_TRUE(policy_handler_.UnloadPolicyLibrary());
+}
+
+TEST_F(PolicyHandlerTest,
+ ResetPolicyTable_WithoutPreloadedFile_ExpectPolicyTableNotReset) {
+ // Check
+ EXPECT_FALSE(policy_handler_.ResetPolicyTable());
+}
+
+TEST_F(PolicyHandlerTest, ResetPolicyTable_PTNotInitialised_PTNotReset) {
+ // Arrange
+ EnablePolicy();
+ EXPECT_TRUE(policy_handler_.LoadPolicyLibrary());
+ // Check
+ EXPECT_TRUE(policy_handler_.ResetPolicyTable());
+}
+
+TEST_F(PolicyHandlerTest,
+ ResetPolicyTable_WithPreloadedFile_ExpectPolicyTableReset) {
+ // Arrange
+ EnablePolicy();
+ EXPECT_TRUE(policy_handler_.LoadPolicyLibrary());
+ EXPECT_TRUE(policy_handler_.InitPolicyTable());
+ // Check
+ EXPECT_TRUE(policy_handler_.ResetPolicyTable());
+}
+
+TEST_F(PolicyHandlerTest, ResetPolicyTable_ExpectCallPMResetPT) {
+ ChangePolicyManagerToMock();
+ EnablePolicy();
+ EXPECT_CALL(*mock_policy_manager_, ResetPT(_));
+ policy_handler_.ResetPolicyTable();
+}
+
+TEST_F(PolicyHandlerTest, ClearUserConsent) {
+ EnablePolicyAndPolicyManagerMock();
+ EXPECT_CALL(*mock_policy_manager_, ResetUserConsent());
+ policy_handler_.ClearUserConsent();
+}
+
+TEST_F(PolicyHandlerTest, ReceiveMessageFromSDK) {
+ // Arrange
+ EnablePolicy();
+ EXPECT_TRUE(policy_handler_.LoadPolicyLibrary());
+ // Check
+ EXPECT_TRUE(policy_handler_.InitPolicyTable());
+ ChangePolicyManagerToMock();
+ std::string file_name("sdl_pt_update.json");
+ std::ifstream ifile(file_name);
+ Json::Reader reader;
+ std::string json;
+ Json::Value root(Json::objectValue);
+ if (ifile.is_open() && reader.parse(ifile, root, true)) {
+ json = root.toStyledString();
+ }
+ ifile.close();
+ BinaryMessage msg(json.begin(), json.end());
+ // Checks
+ EXPECT_CALL(app_manager_, GetNextHMICorrelationID());
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ CreateGetVehicleDataRequest(_, _, _));
+ EXPECT_CALL(*mock_policy_manager_, PTUpdatedAt(_, _));
+ EXPECT_CALL(*mock_policy_manager_, LoadPT("", msg)).WillOnce(Return(true));
+ EXPECT_CALL(*mock_policy_manager_, CleanupUnpairedDevices());
+ policy_handler_.ReceiveMessageFromSDK("", msg);
+}
+
+TEST_F(PolicyHandlerTest, ReceiveMessageFromSDK_PTNotLoaded) {
+ // Arrange
+ ChangePolicyManagerToMock();
+ BinaryMessage msg;
+ // Checks
+
+ EXPECT_CALL(*mock_policy_manager_, LoadPT("", msg)).WillOnce(Return(false));
+ EXPECT_CALL(*mock_policy_manager_, ForcePTExchange()).WillOnce(Return(""));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnStatusUpdate(_, _));
+ EXPECT_CALL(app_manager_, GetNextHMICorrelationID()).Times(0);
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ CreateGetVehicleDataRequest(_, _, _)).Times(0);
+ policy_handler_.ReceiveMessageFromSDK("", msg);
+}
+
+TEST_F(PolicyHandlerTest, UnloadPolicyLibrary_method_ExpectLibraryUnloaded) {
+ // Arrange
+ EnablePolicy();
+ EXPECT_TRUE(policy_handler_.LoadPolicyLibrary());
+ EXPECT_TRUE(policy_handler_.InitPolicyTable());
+ ChangePolicyManagerToMock();
+ // Act
+ EXPECT_TRUE(policy_handler_.UnloadPolicyLibrary());
+ // Check
+ EXPECT_FALSE(policy_handler_.InitPolicyTable());
+}
+
+TEST_F(PolicyHandlerTest, OnPermissionsUpdated_method_With2Parameters) {
+ // Check expectations
+ EXPECT_CALL(app_manager_, application_by_policy_id(_))
+ .WillOnce(Return(mock_app_));
+ EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId_));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnPermissionsChangeNotification(kAppId_, _, _));
+ // Act
+ Permissions perms;
+ policy_handler_.OnPermissionsUpdated(kPolicyAppId_, perms);
+}
+
+TEST_F(PolicyHandlerTest,
+ OnPermissionsUpdated_MethodWith3Parameters_FromNONE_ToFULL) {
+ // Set hmi level from NONE to FULL
+ const std::string new_kHmiLevel_string = "HMI_FULL";
+ mobile_apis::HMILevel::eType new_hmi_level = mobile_apis::HMILevel::HMI_FULL;
+ // Check expectations
+ EXPECT_CALL(app_manager_, application_by_policy_id(_))
+ .Times(2)
+ .WillRepeatedly(Return(mock_app_));
+ EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId_));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ StringToHMILevel(new_kHmiLevel_string))
+ .WillOnce(Return(new_hmi_level));
+
+ EXPECT_CALL(*mock_app_, hmi_level())
+ .WillOnce(Return(mobile_apis::HMILevel::HMI_NONE));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnPermissionsChangeNotification(kAppId_, _, _));
+
+ EXPECT_CALL(app_manager_, state_controller())
+ .WillRepeatedly(ReturnRef(mock_state_controller));
+ EXPECT_CALL(mock_state_controller, SetRegularState(_, new_hmi_level, true));
+ // Act
+ Permissions perms;
+ policy_handler_.OnPermissionsUpdated(
+ kPolicyAppId_, perms, new_kHmiLevel_string);
+}
+
+TEST_F(PolicyHandlerTest,
+ OnPermissionsUpdated_MethodWith3Parameters_FromNONE_ToNotFull) {
+ // Set hmi level from NONE to Limited
+ const std::string new_kHmiLevel_string = "HMI_LIMITED";
+ mobile_apis::HMILevel::eType new_hmi_level =
+ mobile_apis::HMILevel::HMI_LIMITED;
+ // Check expectations
+ EXPECT_CALL(app_manager_, application_by_policy_id(_))
+ .Times(2)
+ .WillRepeatedly(Return(mock_app_));
+ EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId_));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ StringToHMILevel(new_kHmiLevel_string))
+ .WillOnce(Return(new_hmi_level));
+
+ EXPECT_CALL(*mock_app_, hmi_level())
+ .WillOnce(Return(mobile_apis::HMILevel::HMI_NONE));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnPermissionsChangeNotification(kAppId_, _, _));
+
+ EXPECT_CALL(app_manager_, state_controller())
+ .WillRepeatedly(ReturnRef(mock_state_controller));
+ EXPECT_CALL(mock_state_controller, SetRegularState(_, new_hmi_level, false));
+ // Act
+ Permissions perms;
+ policy_handler_.OnPermissionsUpdated(
+ kPolicyAppId_, perms, new_kHmiLevel_string);
+}
+
+TEST_F(PolicyHandlerTest,
+ OnPermissionsUpdated_MethodWith3Parameters_FromNotNONE) {
+ // Set hmi level from LIMITED to FULL
+ std::string new_kHmiLevel_string = "HMI_FULL";
+ mobile_apis::HMILevel::eType new_hmi_level = mobile_apis::HMILevel::HMI_FULL;
+ // Check expectations
+ EXPECT_CALL(app_manager_, application_by_policy_id(_))
+ .Times(2)
+ .WillRepeatedly(Return(mock_app_));
+ EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId_));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ StringToHMILevel(new_kHmiLevel_string))
+ .WillOnce(Return(new_hmi_level));
+
+ EXPECT_CALL(*mock_app_, hmi_level())
+ .WillOnce(Return(mobile_apis::HMILevel::HMI_LIMITED));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnPermissionsChangeNotification(kAppId_, _, _));
+
+ EXPECT_CALL(app_manager_, state_controller()).Times(0);
+ // Act
+ Permissions perms;
+ policy_handler_.OnPermissionsUpdated(
+ kPolicyAppId_, perms, new_kHmiLevel_string);
+}
+
+TEST_F(PolicyHandlerTest, GetPriority) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, GetPriority(kPolicyAppId_, &priority_));
+ // Act
+ policy_handler_.GetPriority(kPolicyAppId_, &priority_);
+}
+
+TEST_F(PolicyHandlerTest, CheckPermissions) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ CheckPermissionResult result;
+ RPCParams kRpc_params;
+ // Check expectations
+ EXPECT_CALL(
+ *mock_policy_manager_,
+ CheckPermissions(kPolicyAppId_, kHmiLevel_, kRpc_, kRpc_params, _));
+ // Act
+ policy_handler_.CheckPermissions(
+ kPolicyAppId_, kHmiLevel_, kRpc_, kRpc_params, result);
+}
+
+TEST_F(PolicyHandlerTest, GetNotificationsNumber) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, GetNotificationsNumber(priority_));
+ // Act
+ policy_handler_.GetNotificationsNumber(priority_);
+}
+
+TEST_F(PolicyHandlerTest, GetUserConsentForDevice) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, GetUserConsentForDevice(kDeviceId_))
+ .WillOnce(Return(DeviceConsent::kDeviceHasNoConsent));
+ // Act
+ policy_handler_.GetUserConsentForDevice(kDeviceId_);
+}
+
+TEST_F(PolicyHandlerTest, GetDefaultHmi) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_,
+ GetDefaultHmi(kPolicyAppId_, &default_hmi_));
+ // Act
+ policy_handler_.GetDefaultHmi(kPolicyAppId_, &default_hmi_);
+}
+
+TEST_F(PolicyHandlerTest, GetInitialAppData) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ StringArray* nicknames = NULL;
+ StringArray* app_hmi_types = NULL;
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_,
+ GetInitialAppData(kPolicyAppId_, nicknames, app_hmi_types));
+ // Act
+ policy_handler_.GetInitialAppData(kPolicyAppId_, nicknames, app_hmi_types);
+}
+
+TEST_F(PolicyHandlerTest, GetServiceUrls) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ EndpointUrls endpoints;
+ const std::string service_type_ = "0x0";
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, GetServiceUrls(service_type_, _));
+ // Act
+ policy_handler_.GetServiceUrls(service_type_, endpoints);
+}
+
+TEST_F(PolicyHandlerTest, ResetRetrySequence) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, ResetRetrySequence());
+ // Act
+ policy_handler_.ResetRetrySequence();
+}
+
+TEST_F(PolicyHandlerTest, NextRetryTimeout) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, NextRetryTimeout());
+ // Act
+ policy_handler_.NextRetryTimeout();
+}
+
+TEST_F(PolicyHandlerTest, TimeoutExchange) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, TimeoutExchange());
+ // Act
+ policy_handler_.TimeoutExchange();
+}
+
+TEST_F(PolicyHandlerTest, OnExceededTimeout) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, OnExceededTimeout());
+ // Act
+ policy_handler_.OnExceededTimeout();
+}
+
+TEST_F(PolicyHandlerTest, OnSystemReady) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, OnSystemReady());
+ // Act
+ policy_handler_.OnSystemReady();
+}
+
+TEST_F(PolicyHandlerTest, PTUpdatedAt_method_UseCounter_KILOMETERS) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ const int value = 1000;
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, PTUpdatedAt(Counters::KILOMETERS, value));
+ // Act
+ policy_handler_.PTUpdatedAt(Counters::KILOMETERS, value);
+}
+
+TEST_F(PolicyHandlerTest, PTUpdatedAt_method_UseCounter_DAYS_AFTER_EPOCH) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ const int value = 16000;
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_,
+ PTUpdatedAt(Counters::DAYS_AFTER_EPOCH, value));
+ // Act
+ policy_handler_.PTUpdatedAt(Counters::DAYS_AFTER_EPOCH, value);
+}
+
+TEST_F(PolicyHandlerTest, CheckSystemAction_method_WithType_KEEP_CONTEXT) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ mobile_apis::SystemAction::eType system_action =
+ mobile_apis::SystemAction::eType::KEEP_CONTEXT;
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, CanAppKeepContext(kPolicyAppId_));
+ // Act
+ policy_handler_.CheckSystemAction(system_action, kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest, CheckSystemAction_method_WithType_STEAL_FOCUS) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ mobile_apis::SystemAction::eType system_action =
+ mobile_apis::SystemAction::eType::STEAL_FOCUS;
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, CanAppStealFocus(kPolicyAppId_));
+ // Act
+ policy_handler_.CheckSystemAction(system_action, kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest, CheckSystemAction_method_WithType_DEFAULT_ACTION) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ mobile_apis::SystemAction::eType system_action =
+ mobile_apis::SystemAction::eType::DEFAULT_ACTION;
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, CanAppStealFocus(kPolicyAppId_)).Times(0);
+ EXPECT_CALL(*mock_policy_manager_, CanAppKeepContext(kPolicyAppId_)).Times(0);
+ // Act
+ EXPECT_TRUE(policy_handler_.CheckSystemAction(system_action, kPolicyAppId_));
+}
+
+TEST_F(PolicyHandlerTest, CheckSystemAction_method_WithType_INVALID_ENUM) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ mobile_apis::SystemAction::eType system_action =
+ mobile_apis::SystemAction::eType::INVALID_ENUM;
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, CanAppStealFocus(kPolicyAppId_)).Times(0);
+ EXPECT_CALL(*mock_policy_manager_, CanAppKeepContext(kPolicyAppId_)).Times(0);
+ // Act
+ EXPECT_FALSE(policy_handler_.CheckSystemAction(system_action, kPolicyAppId_));
+}
+
+TEST_F(PolicyHandlerTest, KmsChanged) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ const int kilometers = 1600;
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, KmsChanged(kilometers));
+ // Act
+ policy_handler_.KmsChanged(kilometers);
+}
+// policy_handler l:1026
+
+void PolicyHandlerTest::TestActivateApp(const uint32_t connection_key,
+ const uint32_t correlation_id) {
+ utils::SharedPtr<application_manager_test::MockApplication> application1 =
+ utils::MakeShared<application_manager_test::MockApplication>();
+ EXPECT_CALL(app_manager_, ActivateApplication(_))
+ .WillRepeatedly(Return(true));
+ EXPECT_CALL(app_manager_, application(connection_key))
+ .WillRepeatedly(Return(application1));
+
+ AppPermissions permissions(kPolicyAppId_);
+ permissions.appPermissionsConsentNeeded = true;
+
+ // Check expectations
+ EXPECT_CALL(*application1, policy_app_id()).WillOnce(Return(kPolicyAppId_));
+ EXPECT_CALL(*mock_policy_manager_, GetAppPermissionsChanges(_))
+ .WillOnce(Return(permissions));
+ ON_CALL(*mock_policy_manager_, Increment(_, _)).WillByDefault(Return());
+ EXPECT_CALL(*mock_policy_manager_, RemovePendingPermissionChanges(_));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendSDLActivateAppResponse(_, _, _));
+ ON_CALL(*application1, app_id()).WillByDefault(Return(kAppId_));
+ // Act
+ policy_handler_.OnActivateApp(connection_key, correlation_id);
+}
+
+TEST_F(PolicyHandlerTest, OnActivateApp) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ const uint32_t connection_key = 1;
+ const uint32_t correlation_id = 2;
+ TestActivateApp(connection_key, correlation_id);
+}
+
+TEST_F(PolicyHandlerTest, OnIgnitionCycleOver) {
+ // Arrange
+ ChangePolicyManagerToMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, IncrementIgnitionCycles());
+ // Act
+ policy_handler_.OnIgnitionCycleOver();
+}
+
+void PolicyHandlerTest::OnPendingPermissionChangePrecondition(
+ mobile_apis::HMILevel::eType hmi_level) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+
+ utils::SharedPtr<application_manager_test::MockApplication> application =
+ utils::MakeShared<application_manager_test::MockApplication>();
+
+ EXPECT_CALL(app_manager_, application_by_policy_id(kPolicyAppId_))
+ .WillOnce(Return(application));
+ EXPECT_CALL(*application, app_id()).WillRepeatedly(Return(kAppId_));
+ EXPECT_CALL(*application, hmi_level()).WillRepeatedly(Return(hmi_level));
+}
+
+TEST_F(PolicyHandlerTest,
+ OnPendingPermissionChange_AppInLimitedConsentnotNeeded) {
+ // Arrange
+ OnPendingPermissionChangePrecondition(
+ mobile_apis::HMILevel::eType::HMI_LIMITED);
+ // Check expectations
+ AppPermissions permissions(kPolicyAppId_);
+ permissions.appPermissionsConsentNeeded = false;
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnAppPermissionsChangedNotification(kAppId_, _, _)).Times(0);
+
+ EXPECT_CALL(*mock_policy_manager_, GetAppPermissionsChanges(_))
+ .WillOnce(Return(permissions));
+ EXPECT_CALL(*mock_policy_manager_,
+ RemovePendingPermissionChanges(kPolicyAppId_)).Times(0);
+ // Act
+ policy_handler_.OnPendingPermissionChange(kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest, OnPendingPermissionChange_AppInLimitedConsentNeeded) {
+ // Arrange
+ OnPendingPermissionChangePrecondition(
+ mobile_apis::HMILevel::eType::HMI_LIMITED);
+ AppPermissions permissions(kPolicyAppId_);
+ permissions.appPermissionsConsentNeeded = true;
+ // Check expectations
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnAppPermissionsChangedNotification(kAppId_, _, _));
+ EXPECT_CALL(*mock_policy_manager_, GetAppPermissionsChanges(_))
+ .WillOnce(Return(permissions));
+ EXPECT_CALL(*mock_policy_manager_,
+ RemovePendingPermissionChanges(kPolicyAppId_));
+ // Act
+ policy_handler_.OnPendingPermissionChange(kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest, OnPendingPermissionChange_AppLimitedAndRevoked) {
+ // Arrange
+ OnPendingPermissionChangePrecondition(
+ mobile_apis::HMILevel::eType::HMI_LIMITED);
+ AppPermissions permissions(kPolicyAppId_);
+ permissions.appRevoked = true;
+
+ // Check expectations
+ EXPECT_CALL(app_manager_, state_controller())
+ .WillRepeatedly(ReturnRef(mock_state_controller));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnAppPermissionsChangedNotification(kAppId_, _, _));
+ EXPECT_CALL(mock_state_controller,
+ SetRegularState(_,
+ mobile_apis::HMILevel::HMI_NONE,
+ mobile_apis::AudioStreamingState::NOT_AUDIBLE,
+ true));
+
+ EXPECT_CALL(*mock_policy_manager_, GetAppPermissionsChanges(_))
+ .WillOnce(Return(permissions));
+ EXPECT_CALL(*mock_policy_manager_,
+ RemovePendingPermissionChanges(kPolicyAppId_));
+ // Act
+ policy_handler_.OnPendingPermissionChange(kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest, OnPendingPermissionChange_AppInBackgroundAndRevoked) {
+ // Arrange
+ OnPendingPermissionChangePrecondition(
+ mobile_apis::HMILevel::eType::HMI_BACKGROUND);
+ AppPermissions permissions(kPolicyAppId_);
+ permissions.isAppPermissionsRevoked = true;
+
+ // Check expectations
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnAppPermissionsChangedNotification(kAppId_, _, _));
+
+ EXPECT_CALL(*mock_policy_manager_, GetAppPermissionsChanges(_))
+ .WillOnce(Return(permissions));
+ EXPECT_CALL(*mock_policy_manager_,
+ RemovePendingPermissionChanges(kPolicyAppId_));
+ // Act
+ policy_handler_.OnPendingPermissionChange(kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest,
+ OnPendingPermissionChange_AppInLIMITEDAndUnauthorized) {
+ // Arrange
+ OnPendingPermissionChangePrecondition(
+ mobile_apis::HMILevel::eType::HMI_LIMITED);
+ AppPermissions permissions(kPolicyAppId_);
+ permissions.appUnauthorized = true;
+
+ NsSmartDeviceLink::NsSmartObjects::SmartObjectSPtr message =
+ utils::MakeShared<NsSmartDeviceLink::NsSmartObjects::SmartObject>();
+ // Check expectations
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnAppPermissionsChangedNotification(kAppId_, _, _));
+
+ EXPECT_CALL(*mock_policy_manager_, GetAppPermissionsChanges(_))
+ .WillOnce(Return(permissions));
+
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ GetOnAppInterfaceUnregisteredNotificationToMobile(
+ kAppId_,
+ mobile_api::AppInterfaceUnregisteredReason::APP_UNAUTHORIZED))
+ .WillOnce(Return(message));
+ EXPECT_CALL(app_manager_,
+ ManageMobileCommand(_, commands::Command::ORIGIN_SDL));
+
+ EXPECT_CALL(*mock_policy_manager_,
+ RemovePendingPermissionChanges(kPolicyAppId_));
+
+ // Act
+ policy_handler_.OnPendingPermissionChange(kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest,
+ OnPendingPermissionChange_AppInBackgroundAndUnauthorized) {
+ // Arrange
+ OnPendingPermissionChangePrecondition(
+ mobile_apis::HMILevel::eType::HMI_BACKGROUND);
+ AppPermissions permissions(kPolicyAppId_);
+ permissions.appUnauthorized = true;
+
+ NsSmartDeviceLink::NsSmartObjects::SmartObjectSPtr message =
+ utils::MakeShared<NsSmartDeviceLink::NsSmartObjects::SmartObject>();
+ // Check expectations
+ // Notification won't be sent
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnAppPermissionsChangedNotification(kAppId_, _, _)).Times(0);
+
+ EXPECT_CALL(*mock_policy_manager_, GetAppPermissionsChanges(_))
+ .WillOnce(Return(permissions));
+
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ GetOnAppInterfaceUnregisteredNotificationToMobile(
+ kAppId_,
+ mobile_api::AppInterfaceUnregisteredReason::APP_UNAUTHORIZED))
+ .WillOnce(Return(message));
+ EXPECT_CALL(app_manager_,
+ ManageMobileCommand(_, commands::Command::ORIGIN_SDL));
+
+ EXPECT_CALL(*mock_policy_manager_,
+ RemovePendingPermissionChanges(kPolicyAppId_));
+
+ // Act
+ policy_handler_.OnPendingPermissionChange(kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest, PTExchangeAtUserRequest) {
+ // Arrange
+ ChangePolicyManagerToMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, ForcePTExchange());
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendUpdateSDLResponse(_, _, _));
+ // Act
+ const uint32_t correlation_id = 2;
+ policy_handler_.PTExchangeAtUserRequest(correlation_id);
+}
+
+TEST_F(PolicyHandlerTest, AddDevice) {
+ // Arrange
+ ChangePolicyManagerToMock();
+ // Check expectations
+ const std::string connection_type("BT");
+ EXPECT_CALL(*mock_policy_manager_, AddDevice(kDeviceId_, connection_type));
+ // Act
+ policy_handler_.AddDevice(kDeviceId_, connection_type);
+}
+
+TEST_F(PolicyHandlerTest, SetDeviceInfo) {
+ // Arrange
+ ChangePolicyManagerToMock();
+ // Check expectations
+ std::string kDeviceId_;
+ const DeviceInfo device_info;
+ EXPECT_CALL(*mock_policy_manager_, SetDeviceInfo(kDeviceId_, _));
+ // Act
+ policy_handler_.SetDeviceInfo(kDeviceId_, device_info);
+}
+
+TEST_F(PolicyHandlerTest, OnGetUserFriendlyMessage) {
+ // Arrange
+ ChangePolicyManagerToMock();
+ // Check expectations
+ std::vector<std::string> message_codes;
+ const std::string language("ru-ru");
+ const uint32_t correlation_id = 2;
+ EXPECT_CALL(*mock_policy_manager_,
+ GetUserFriendlyMessages(message_codes, language))
+ .WillOnce(Return(std::vector<UserFriendlyMessage>()));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendGetUserFriendlyMessageResponse(_, _, _));
+ // Act
+ policy_handler_.OnGetUserFriendlyMessage(
+ message_codes, language, correlation_id);
+}
+
+TEST_F(PolicyHandlerTest, OnGetStatusUpdate) {
+ // Arrange
+ ChangePolicyManagerToMock();
+ const uint32_t correlation_id = 2;
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, GetPolicyTableStatus());
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendGetStatusUpdateResponse(_, correlation_id, _));
+ // Act
+ policy_handler_.OnGetStatusUpdate(correlation_id);
+}
+
+TEST_F(PolicyHandlerTest, OnUpdateStatusChanged) {
+ // Check expectations
+ const std::string& status("new status");
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnStatusUpdate(status, _));
+ // Act
+ policy_handler_.OnUpdateStatusChanged(status);
+}
+
+TEST_F(PolicyHandlerTest, OnCurrentDeviceIdUpdateRequired) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ utils::SharedPtr<application_manager_test::MockApplication> application =
+ utils::MakeShared<application_manager_test::MockApplication>();
+ EXPECT_CALL(app_manager_, application_by_policy_id(kPolicyAppId_))
+ .WillOnce(Return(application));
+ EXPECT_CALL(app_manager_, connection_handler())
+ .WillOnce(ReturnRef(conn_handler));
+ protocol_handler_test::MockSessionObserver session_observer;
+
+ EXPECT_CALL(conn_handler, get_session_observer())
+ .WillOnce(ReturnRef(session_observer));
+
+ EXPECT_CALL(session_observer, GetDataOnDeviceID(0u, _, _, _, _));
+
+ // Act
+ policy_handler_.OnCurrentDeviceIdUpdateRequired(kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest, OnSystemInfoChanged) {
+ // Arrange
+ ChangePolicyManagerToMock();
+ // Check expectations
+ const std::string language("ru-ru");
+ EXPECT_CALL(*mock_policy_manager_, SetSystemLanguage(language));
+ // Act
+ policy_handler_.OnSystemInfoChanged(language);
+}
+
+TEST_F(PolicyHandlerTest, OnGetSystemInfo) {
+ // Arrange
+ ChangePolicyManagerToMock();
+ // Check expectations
+ const std::string ccpu_version("4.1.3.B_EB355B");
+ const std::string wers_country_code("WAEGB");
+ const std::string language("ru-ru");
+ EXPECT_CALL(*mock_policy_manager_,
+ SetSystemInfo(ccpu_version, wers_country_code, language));
+ // Act
+ policy_handler_.OnGetSystemInfo(ccpu_version, wers_country_code, language);
+}
+
+TEST_F(PolicyHandlerTest, IsApplicationRevoked) {
+ // Arrange
+ EnablePolicy();
+ ChangePolicyManagerToMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, IsApplicationRevoked(kPolicyAppId_));
+ // Act
+ policy_handler_.IsApplicationRevoked(kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest, OnSystemInfoUpdateRequired) {
+ // Arrange
+ ChangePolicyManagerToMock();
+ // Check expectations
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendGetSystemInfoRequest(_));
+ // Act
+ policy_handler_.OnSystemInfoUpdateRequired();
+}
+
+TEST_F(PolicyHandlerTest, GetAppRequestTypes) {
+ // Arrange
+ EnablePolicy();
+ ChangePolicyManagerToMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, GetAppRequestTypes(kPolicyAppId_))
+ .WillOnce(Return(std::vector<std::string>()));
+ // Act
+ policy_handler_.GetAppRequestTypes(kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest, OnVIIsReady) {
+ // Arrange
+ ChangePolicyManagerToMock();
+ // Check expectations
+ EXPECT_CALL(app_manager_, GetNextHMICorrelationID());
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ CreateGetVehicleDataRequest(_, _, _));
+ // Act
+ policy_handler_.OnVIIsReady();
+}
+
+TEST_F(PolicyHandlerTest, RemoveDevice) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, MarkUnpairedDevice(kDeviceId_));
+ // Act
+ policy_handler_.RemoveDevice(kDeviceId_);
+}
+
+TEST_F(PolicyHandlerTest, GetAppName) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ const CustomString app_name("my_mobile_app");
+
+ utils::SharedPtr<application_manager_test::MockApplication> application =
+ utils::MakeShared<application_manager_test::MockApplication>();
+
+ EXPECT_CALL(*application, name()).WillOnce(ReturnRef(app_name));
+ EXPECT_CALL(app_manager_, application_by_policy_id(kPolicyAppId_))
+ .WillOnce(Return(application));
+ // Act
+ EXPECT_EQ(app_name, policy_handler_.GetAppName(kPolicyAppId_));
+}
+
+TEST_F(PolicyHandlerTest, OnUpdateRequestSentToMobile) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, OnUpdateStarted());
+ // Act
+ policy_handler_.OnUpdateRequestSentToMobile();
+}
+
+TEST_F(PolicyHandlerTest, OnUpdateHMIAppType) {
+ // Arrange
+ EnablePolicy();
+ application_manager_test::MockPolicyHandlerObserver policy_handler_observer;
+ policy_handler_.add_listener(&policy_handler_observer);
+ std::map<std::string, StringArray> app_hmi_types;
+ StringArray arr;
+ arr.push_back("test_hmi_type");
+ app_hmi_types["app1"] = arr;
+ // Check expectations
+ EXPECT_CALL(policy_handler_observer, OnUpdateHMIAppType(_));
+ // Act
+ policy_handler_.OnUpdateHMIAppType(app_hmi_types);
+}
+
+TEST_F(PolicyHandlerTest, SendOnAppPermissionsChanged) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+
+ utils::SharedPtr<application_manager_test::MockApplication> application =
+ utils::MakeShared<application_manager_test::MockApplication>();
+ // Check expectations
+ EXPECT_CALL(app_manager_, application_by_policy_id(kPolicyAppId_))
+ .WillOnce(Return(application));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnAppPermissionsChangedNotification(_, _, _));
+ AppPermissions permissions(kPolicyAppId_);
+ // Act
+ policy_handler_.SendOnAppPermissionsChanged(permissions, kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest, OnPTExchangeNeeded) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, ForcePTExchange());
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendOnStatusUpdate(_, _));
+ // Act
+ policy_handler_.OnPTExchangeNeeded();
+}
+
+TEST_F(PolicyHandlerTest, AddApplication) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, AddApplication(kPolicyAppId_));
+ // Act
+ policy_handler_.AddApplication(kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest, HeartBeatTimeout) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, HeartBeatTimeout(kPolicyAppId_));
+ // Act
+ policy_handler_.HeartBeatTimeout(kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest, OnAppsSearchStarted) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, OnAppsSearchStarted());
+ // Act
+ policy_handler_.OnAppsSearchStarted();
+}
+
+TEST_F(PolicyHandlerTest, OnAppsSearchCompleted) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, OnAppsSearchCompleted());
+ // Act
+ policy_handler_.OnAppsSearchCompleted();
+}
+
+TEST_F(PolicyHandlerTest, OnAppRegisteredOnMobile) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+
+ EXPECT_CALL(*mock_policy_manager_, OnAppRegisteredOnMobile(kPolicyAppId_));
+ // Act
+ policy_handler_.OnAppRegisteredOnMobile(kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest, IsRequestTypeAllowed) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+
+ mobile_apis::RequestType::eType type =
+ mobile_apis::RequestType::eType::EMERGENCY;
+ EXPECT_CALL(*mock_policy_manager_, GetAppRequestTypes(kPolicyAppId_))
+ .WillOnce(Return(std::vector<std::string>()));
+ // Act
+ policy_handler_.IsRequestTypeAllowed(kPolicyAppId_, type);
+}
+
+TEST_F(PolicyHandlerTest, GetVehicleInfo) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ EXPECT_CALL(*mock_policy_manager_, GetVehicleInfo())
+ .WillOnce(Return(VehicleInfo()));
+ // Act
+ policy_handler_.GetVehicleInfo();
+}
+
+TEST_F(PolicyHandlerTest, Increment_method_WithOneParameter) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+ usage_statistics::GlobalCounterId type =
+ usage_statistics::GlobalCounterId::IAP_BUFFER_FULL;
+ EXPECT_CALL(*mock_policy_manager_, Increment(type));
+ // Act
+ policy_handler_.Increment(type);
+}
+
+TEST_F(PolicyHandlerTest, Increment_method_WithTwoParameters) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+
+ usage_statistics::AppCounterId type =
+ usage_statistics::AppCounterId::USER_SELECTIONS;
+ EXPECT_CALL(*mock_policy_manager_, Increment(kPolicyAppId_, type));
+ // Act
+ policy_handler_.Increment(kPolicyAppId_, type);
+}
+
+TEST_F(PolicyHandlerTest, Set) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+
+ const std::string value("ru-ru");
+ usage_statistics::AppInfoId type = usage_statistics::AppInfoId::LANGUAGE_GUI;
+ EXPECT_CALL(*mock_policy_manager_, Set(kPolicyAppId_, type, value));
+ // Act
+ policy_handler_.Set(kPolicyAppId_, type, value);
+}
+
+TEST_F(PolicyHandlerTest, Add) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ // Check expectations
+
+ const int32_t timespan_seconds = 100;
+ usage_statistics::AppStopwatchId type =
+ usage_statistics::AppStopwatchId::SECONDS_HMI_FULL;
+ EXPECT_CALL(*mock_policy_manager_,
+ Add(kPolicyAppId_, type, timespan_seconds));
+ // Act
+ policy_handler_.Add(kPolicyAppId_, type, timespan_seconds);
+}
+
+TEST_F(PolicyHandlerTest, GetAvailableApps) {
+ // Set does not have any apps
+ std::queue<std::string> apps;
+ policy_handler_.GetAvailableApps(apps);
+ EXPECT_EQ(0u, apps.size());
+
+ // Added one app
+ test_app.insert(mock_app_);
+
+ EXPECT_CALL(*mock_app_, policy_app_id()).WillOnce(Return("app_id"));
+
+ policy_handler_.GetAvailableApps(apps);
+
+ EXPECT_EQ(1u, apps.size());
+}
+
+TEST_F(PolicyHandlerTest, OnGetListOfPermissions) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+
+ const uint32_t kAppId_ = 10u;
+ const uint32_t kCorId = 1u;
+ const std::string default_mac = "00:00:00:00:00:00";
+ test_app.insert(mock_app_);
+
+ // Expectations
+ EXPECT_CALL(*mock_policy_manager_, GetUserConsentForApp(default_mac, _, _));
+
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendGetListOfPermissionsResponse(_, kCorId, _));
+
+ EXPECT_CALL(app_manager_, application(kAppId_))
+ .WillRepeatedly(Return(mock_app_));
+
+ policy_handler_.OnGetListOfPermissions(kAppId_, kCorId);
+}
+
+TEST_F(PolicyHandlerTest, OnGetListOfPermissions_WithoutConnectionKey) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+
+ const uint32_t kAppId_ = 0u;
+ const uint32_t kCorId = 1u;
+ test_app.insert(mock_app_);
+
+ // Expectations
+ EXPECT_CALL(app_manager_, applications()).WillRepeatedly(Return(app_set));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendGetListOfPermissionsResponse(_, kCorId, _));
+
+ policy_handler_.OnGetListOfPermissions(kAppId_, kCorId);
+}
+
+TEST_F(PolicyHandlerTest, RetrieveCertificate) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+ const std::string test_certificate = "test certificate";
+ EXPECT_CALL(*mock_policy_manager_, RetrieveCertificate())
+ .WillOnce(Return(test_certificate));
+ EXPECT_EQ(test_certificate, policy_handler_.RetrieveCertificate());
+}
+
+TEST_F(PolicyHandlerTest, OnSnapshotCreated_UrlNotAdded) {
+ EnablePolicyAndPolicyManagerMock();
+ BinaryMessage msg;
+ EndpointUrls test_data;
+#ifdef EXTENDED_POLICY
+ ExtendedPolicyExpectations();
+#else
+ EXPECT_CALL(*mock_policy_manager_, GetServiceUrls(_, _))
+ .WillRepeatedly(SetArgReferee<1>(test_data));
+#endif // EXTENDED_POLICY
+
+ policy_handler_.OnSnapshotCreated(msg);
+}
+
+TEST_F(PolicyHandlerTest, OnSnapshotCreated_UrlAdded) {
+ EnablePolicyAndPolicyManagerMock();
+ BinaryMessage msg;
+ EndpointUrls test_data;
+ EndpointData data("some_data");
+ test_data.push_back(data);
+
+#ifdef EXTENDED_POLICY
+ ExtendedPolicyExpectations();
+#else
+ EXPECT_CALL(*mock_policy_manager_, GetServiceUrls(_, _))
+ .WillRepeatedly(SetArgReferee<1>(test_data));
+ EXPECT_CALL(app_manager_, connection_handler())
+ .WillOnce(ReturnRef(conn_handler));
+ EXPECT_CALL(conn_handler, get_session_observer())
+ .WillOnce(ReturnRef(mock_session_observer));
+ EXPECT_CALL(*mock_app_, device()).WillOnce(Return(0));
+ EXPECT_CALL(app_manager_, applications()).WillOnce(Return(app_set));
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendPolicySnapshotNotification(_, _, _, _));
+ // Check expectations for get app id
+ GetAppIDForSending();
+ // Expectations
+ EXPECT_CALL(app_manager_, application(kAppId_))
+ .WillRepeatedly(Return(mock_app_));
+ EXPECT_CALL(*mock_app_, policy_app_id()).WillOnce(Return(kPolicyAppId_));
+#endif // EXTENDED_POLICY
+
+ policy_handler_.OnSnapshotCreated(msg);
+}
+
+TEST_F(PolicyHandlerTest,
+ OnAllowSDLFunctionalityNotification_AllowedWithDevId_AppActivated) {
+ // Arrange
+
+ EnablePolicyAndPolicyManagerMock();
+ const uint32_t connection_key = 1;
+ const uint32_t correlation_id = 2;
+ TestActivateApp(connection_key, correlation_id);
+
+ const bool is_allowed = true;
+ std::vector<std::string> device_macs;
+ device_macs.push_back(kPolicyAppId_);
+
+ // Not called because id was setted
+ EXPECT_CALL(conn_handler, GetConnectedDevicesMAC(_)).Times(0);
+ EXPECT_CALL(conn_handler, GetDeviceID(kPolicyAppId_, _))
+ .WillRepeatedly(Return(true));
+
+ policy_handler_.OnAllowSDLFunctionalityNotification(is_allowed,
+ kPolicyAppId_);
+}
+
+TEST_F(PolicyHandlerTest,
+ OnAllowSDLFunctionalityNotification_Allowed_WithoutDevId_AppActivated) {
+ // Arrange
+ const bool is_allowed = true;
+ std::vector<std::string> device_macs;
+ device_macs.push_back(kPolicyAppId_);
+ EnablePolicyAndPolicyManagerMock();
+ const uint32_t connection_key = 1;
+ const uint32_t correlation_id = 2;
+ TestActivateApp(connection_key, correlation_id);
+
+ // Device ID is not setted by us
+ EXPECT_CALL(conn_handler, GetConnectedDevicesMAC(_))
+ .WillOnce(SetArgReferee<0>(device_macs));
+
+ EXPECT_CALL(*mock_policy_manager_,
+ SetUserConsentForDevice(kPolicyAppId_, is_allowed));
+
+ policy_handler_.OnAllowSDLFunctionalityNotification(is_allowed, "");
+}
+
+TEST_F(PolicyHandlerTest, OnDeviceConsentChanged_ConsentAllowed) {
+ const bool is_allowed = true;
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+
+ connection_handler::DeviceHandle test_device_id = 100u;
+ EXPECT_CALL(app_manager_, connection_handler())
+ .WillOnce(ReturnRef(conn_handler));
+
+ EXPECT_CALL(conn_handler, GetDeviceID(kPolicyAppId_, _))
+ .WillOnce(DoAll(SetArgPointee<1>(test_device_id), Return(true)));
+
+ test_app.insert(mock_app_);
+ EXPECT_CALL(*mock_app_, device()).WillOnce(Return(test_device_id));
+ EXPECT_CALL(*mock_app_, policy_app_id()).WillOnce(Return(kPolicyAppId_));
+
+ EXPECT_CALL(*mock_policy_manager_, IsPredataPolicy(kPolicyAppId_))
+ .WillOnce(Return(true));
+
+ EXPECT_CALL(*mock_policy_manager_,
+ ReactOnUserDevConsentForApp(kPolicyAppId_, is_allowed));
+ EXPECT_CALL(*mock_policy_manager_,
+ SendNotificationOnPermissionsUpdated(kPolicyAppId_));
+
+ policy_handler_.OnDeviceConsentChanged(kPolicyAppId_, is_allowed);
+}
+
+TEST_F(PolicyHandlerTest, OnDeviceConsentChanged_ConsentNotAllowed) {
+ const bool is_allowed = false;
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+
+ connection_handler::DeviceHandle test_device_id = 100u;
+ EXPECT_CALL(app_manager_, connection_handler())
+ .WillOnce(ReturnRef(conn_handler));
+
+ // Check expectations
+ EXPECT_CALL(conn_handler, GetDeviceID(kPolicyAppId_, _))
+ .WillOnce(DoAll(SetArgPointee<1>(test_device_id), Return(true)));
+ test_app.insert(mock_app_);
+
+ EXPECT_CALL(*mock_app_, device()).WillOnce(Return(test_device_id));
+ EXPECT_CALL(*mock_app_, policy_app_id()).WillOnce(Return(kPolicyAppId_));
+
+ EXPECT_CALL(*mock_policy_manager_, IsPredataPolicy(kPolicyAppId_))
+ .WillOnce(Return(true));
+
+ EXPECT_CALL(*mock_policy_manager_, ReactOnUserDevConsentForApp(_, _))
+ .Times(0);
+ EXPECT_CALL(*mock_policy_manager_, SendNotificationOnPermissionsUpdated(_))
+ .Times(0);
+
+ policy_handler_.OnDeviceConsentChanged(kPolicyAppId_, is_allowed);
+}
+
+TEST_F(PolicyHandlerTest, OnDeviceConsentChanged_PredatePolicyNotAllowed) {
+ const bool is_allowed = false;
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+
+ connection_handler::DeviceHandle test_device_id = 100u;
+ EXPECT_CALL(app_manager_, connection_handler())
+ .WillOnce(ReturnRef(conn_handler));
+
+ EXPECT_CALL(conn_handler, GetDeviceID(kPolicyAppId_, _))
+ .WillOnce(DoAll(SetArgPointee<1>(test_device_id), Return(true)));
+
+ test_app.insert(mock_app_);
+
+ EXPECT_CALL(*mock_app_, device()).WillOnce(Return(test_device_id));
+ EXPECT_CALL(*mock_app_, policy_app_id()).WillOnce(Return(kPolicyAppId_));
+
+ // App does not have predate policy
+ EXPECT_CALL(*mock_policy_manager_, IsPredataPolicy(kPolicyAppId_))
+ .WillOnce(Return(false));
+
+ EXPECT_CALL(*mock_policy_manager_,
+ ReactOnUserDevConsentForApp(kPolicyAppId_, is_allowed));
+ EXPECT_CALL(*mock_policy_manager_,
+ SendNotificationOnPermissionsUpdated(kPolicyAppId_));
+
+ policy_handler_.OnDeviceConsentChanged(kPolicyAppId_, is_allowed);
+}
+
+TEST_F(PolicyHandlerTest, OnCertificateUpdated) {
+ application_manager_test::MockPolicyHandlerObserver policy_handler_observer;
+ policy_handler_.add_listener(&policy_handler_observer);
+ std::string cert_data = "data";
+ EXPECT_CALL(policy_handler_observer, OnCertificateUpdated(cert_data));
+ policy_handler_.OnCertificateUpdated(cert_data);
+}
+
+TEST_F(PolicyHandlerTest, GetAppIdForSending_WithoutApps) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+
+ EXPECT_CALL(app_manager_, applications()).WillRepeatedly(Return(app_set));
+ // Set does not include any applications
+ EXPECT_CALL(*mock_policy_manager_, GetUserConsentForDevice(_)).Times(0);
+ EXPECT_EQ(0u, policy_handler_.GetAppIdForSending());
+}
+
+TEST_F(PolicyHandlerTest, GetAppIdForSending_GetDefaultMacAddress) {
+ // Arrange
+ EnablePolicyAndPolicyManagerMock();
+
+ // Set does not include any applications
+ EXPECT_CALL(*mock_policy_manager_, GetUserConsentForDevice(_)).Times(0);
+ // Check expectations
+ test_app.insert(mock_app_);
+ EXPECT_CALL(*mock_app_, IsRegistered()).WillOnce(Return(true));
+ EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId_));
+ EXPECT_CALL(app_manager_, connection_handler())
+ .WillOnce(ReturnRef(conn_handler));
+
+ EXPECT_CALL(conn_handler, get_session_observer())
+ .WillOnce(ReturnRef(mock_session_observer));
+
+ EXPECT_CALL(app_manager_, applications()).WillRepeatedly(Return(app_set));
+
+ EXPECT_CALL(*mock_policy_manager_, GetUserConsentForDevice(_))
+ .WillRepeatedly(Return(kDeviceAllowed));
+ // Act
+ EXPECT_EQ(kAppId_, policy_handler_.GetAppIdForSending());
+}
+
+void PolicyHandlerTest::GetAppIDForSending() {
+ EnablePolicyAndPolicyManagerMock();
+ test_app.insert(mock_app_);
+
+ // Check expectations
+ EXPECT_CALL(*mock_app_, app_id()).WillOnce(Return(kAppId_));
+ EXPECT_CALL(*mock_app_, IsRegistered()).WillOnce(Return(true));
+ EXPECT_CALL(mock_session_observer, GetDataOnDeviceID(_, _, _, _, _))
+ .WillOnce(DoAll(SetArgPointee<3>(kMacAddr_), Return(0)));
+
+ EXPECT_CALL(*mock_policy_manager_, GetUserConsentForDevice(kMacAddr_))
+ .WillRepeatedly(Return(kDeviceAllowed));
+}
+
+TEST_F(PolicyHandlerTest, GetAppIdForSending_SetMacAddress) {
+ // Arrange
+ GetAppIDForSending();
+ // Act
+ EXPECT_EQ(kAppId_, policy_handler_.GetAppIdForSending());
+}
+
+TEST_F(PolicyHandlerTest, SendMessageToSDK) {
+ // Precondition
+ BinaryMessage msg;
+ const std::string url = "test_url";
+ EnablePolicyAndPolicyManagerMock();
+ test_app.insert(mock_app_);
+ // Check expectations for get app id
+ GetAppIDForSending();
+ // Expectations
+ EXPECT_CALL(app_manager_, application(kAppId_))
+ .WillRepeatedly(Return(mock_app_));
+ EXPECT_CALL(*mock_app_, policy_app_id()).WillOnce(Return(kPolicyAppId_));
+
+ EXPECT_CALL(*MockMessageHelper::message_helper_mock(),
+ SendPolicySnapshotNotification(kAppId_, msg, url, _));
+ // Act
+ EXPECT_TRUE(policy_handler_.SendMessageToSDK(msg, url));
+}
+
+TEST_F(PolicyHandlerTest, CanUpdate) {
+ GetAppIDForSending();
+ EXPECT_TRUE(policy_handler_.CanUpdate());
+}
+
+} // namespace policy_handler_test
+} // namespace components
+} // namespace test
diff --git a/src/components/application_manager/test/request_controller/request_controller_test.cc b/src/components/application_manager/test/request_controller/request_controller_test.cc
new file mode 100644
index 0000000000..6d08e5bf56
--- /dev/null
+++ b/src/components/application_manager/test/request_controller/request_controller_test.cc
@@ -0,0 +1,186 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "application_manager/request_controller.h"
+#include "application_manager/mock_request.h"
+#include "utils/shared_ptr.h"
+#include "smart_objects/smart_object.h"
+#include "application_manager/commands/command_request_impl.h"
+#include "application_manager/message_helper.h"
+#include "application_manager/application_impl.h"
+#include "utils/make_shared.h"
+#include "application_manager/mock_application_manager.h"
+#include "application_manager/event_engine/event_dispatcher.h"
+#include "resumption/last_state.h"
+#include "application_manager/policies/policy_handler.h"
+#include "application_manager/state_controller.h"
+#include "application_manager/resumption/resume_ctrl.h"
+#include "application_manager/mock_request_controller_settings.h"
+#include "application_manager/mock_application_manager.h"
+
+namespace test {
+namespace components {
+namespace request_controller_test {
+
+using application_manager::request_controller::RequestController;
+using application_manager::request_controller::RequestInfo;
+
+using ::testing::Return;
+using ::testing::ReturnRef;
+
+typedef utils::SharedPtr<application_manager_test::MockRequest> RequestPtr;
+typedef utils::SharedPtr<RequestController> RequestControllerSPtr;
+
+class RequestControllerTestClass : public ::testing::Test {
+ public:
+ RequestControllerTestClass()
+ : request_ctrl_(utils::MakeShared<RequestController>(
+ mock_request_controller_settings_)) {
+ register_request_ = GetMockRequest();
+ }
+
+ RequestController::TResult AddRequest(
+ const RequestInfo::RequestType request_type,
+ const bool RegisterRequest = false,
+ const mobile_apis::HMILevel::eType& hmi_level =
+ mobile_apis::HMILevel::INVALID_ENUM) {
+ RequestPtr request;
+ if (RegisterRequest) {
+ request = register_request_;
+ EXPECT_CALL(*register_request_, default_timeout()).WillOnce(Return(0));
+ } else {
+ request = empty_register_request_;
+ }
+ if (RequestInfo::RequestType::HMIRequest == request_type) {
+ return request_ctrl_->addHMIRequest(request);
+ }
+ return request_ctrl_->addMobileRequest(request, hmi_level);
+ }
+
+ RequestPtr GetMockRequest(const uint32_t id = 1,
+ const uint32_t connection_key = 0) {
+ return utils::MakeShared<application_manager_test::MockRequest>(
+ connection_key, id);
+ }
+ void CallSettings() {
+ EXPECT_CALL(mock_request_controller_settings_,
+ app_hmi_level_none_time_scale())
+ .WillOnce(ReturnRef(kDefaultAppHmiLevelNoneRequestsTimeScale));
+ EXPECT_CALL(mock_request_controller_settings_,
+ app_hmi_level_none_time_scale_max_requests())
+ .WillOnce(ReturnRef(kDefaultAppHmiLevelNoneTimeScaleMaxRequests));
+
+ EXPECT_CALL(mock_request_controller_settings_, app_time_scale())
+ .WillOnce(ReturnRef(kDefaultAppRequestsTimeScale));
+ EXPECT_CALL(mock_request_controller_settings_,
+ app_time_scale_max_requests())
+ .WillOnce(ReturnRef(kDefaultAppTimeScaleMaxRequests));
+
+ EXPECT_CALL(mock_request_controller_settings_, pending_requests_amount())
+ .WillOnce(ReturnRef(kDefaultPendingRequestsAmount));
+ }
+
+ application_manager_test::MockRequestControlerSettings
+ mock_request_controller_settings_;
+ RequestPtr register_request_;
+ RequestPtr empty_register_request_;
+ RequestControllerSPtr request_ctrl_;
+
+ const uint32_t kDefaultAppHmiLevelNoneRequestsTimeScale = 10;
+ const uint32_t kDefaultAppHmiLevelNoneTimeScaleMaxRequests = 100u;
+ const uint32_t kDefaultAppTimeScaleMaxRequests = 0;
+ const uint32_t kDefaultAppRequestsTimeScale = 0;
+ const uint32_t kDefaultPendingRequestsAmount = 0;
+};
+
+TEST_F(RequestControllerTestClass, CheckPosibilitytoAdd_HMI_FULL_SUCCESS) {
+ CallSettings();
+ EXPECT_EQ(RequestController::TResult::SUCCESS,
+ AddRequest(RequestInfo::RequestType::MobileRequest,
+ true,
+ mobile_apis::HMILevel::HMI_FULL));
+}
+
+TEST_F(RequestControllerTestClass, CheckPosibilitytoAdd_HMI_NONE_SUCCESS) {
+ CallSettings();
+ EXPECT_EQ(RequestController::TResult::SUCCESS,
+ AddRequest(RequestInfo::RequestType::MobileRequest,
+ true,
+ mobile_apis::HMILevel::HMI_NONE));
+}
+
+TEST_F(RequestControllerTestClass, IsLowVoltage_SetOnLowVoltage_TRUE) {
+ request_ctrl_->OnLowVoltage();
+ const bool result = true;
+ EXPECT_EQ(result, request_ctrl_->IsLowVoltage());
+}
+
+TEST_F(RequestControllerTestClass, IsLowVoltage_SetOnWakeUp_FALSE) {
+ request_ctrl_->OnWakeUp();
+ const bool result = false;
+ EXPECT_EQ(result, request_ctrl_->IsLowVoltage());
+}
+
+TEST_F(RequestControllerTestClass,
+ AddMobileRequest_SetInvalidData_INVALID_DATA) {
+ EXPECT_EQ(RequestController::INVALID_DATA,
+ AddRequest(RequestInfo::RequestType::MobileRequest,
+ false,
+ mobile_apis::HMILevel::HMI_NONE));
+}
+
+TEST_F(RequestControllerTestClass, addHMIRequest_AddRequest_SUCCESS) {
+ EXPECT_EQ(RequestController::SUCCESS,
+ AddRequest(RequestInfo::RequestType::HMIRequest, true));
+}
+
+TEST_F(RequestControllerTestClass, addHMIRequest_AddInvalidData_INVALID_DATA) {
+ EXPECT_EQ(RequestController::INVALID_DATA,
+ AddRequest(RequestInfo::RequestType::HMIRequest));
+}
+
+TEST_F(RequestControllerTestClass, ZeroValuePendingRequestsAmount) {
+ // Bigger than pending_requests_amount count
+ const uint32_t big_count_of_requests_for_test_ = 10;
+ for (uint32_t i = 0; i < big_count_of_requests_for_test_; ++i) {
+ CallSettings();
+ EXPECT_EQ(RequestController::SUCCESS,
+ AddRequest(RequestInfo::RequestType::MobileRequest,
+ true,
+ mobile_apis::HMILevel::HMI_FULL));
+ }
+}
+
+} // namespace request_controller
+} // namespace components
+} // namespace test
diff --git a/src/components/application_manager/test/request_info_test.cc b/src/components/application_manager/test/request_info_test.cc
index 86103e7998..886736fa97 100644
--- a/src/components/application_manager/test/request_info_test.cc
+++ b/src/components/application_manager/test/request_info_test.cc
@@ -1,242 +1,487 @@
-#include "gtest/gtest.h"
-#include "gmock/gmock.h"
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
#include "application_manager/request_info.h"
-#include "application_manager/message_helper.h"
#include <iostream>
+#include <vector>
+#include <limits>
+#include "gmock/gmock.h"
+#include "utils/shared_ptr.h"
+#include "utils/make_shared.h"
namespace request_info = application_manager::request_controller;
-class MockRequest: public application_manager::commands::Command {
- public:
- MockRequest(uint32_t connection_key,
- uint32_t correlation_id):
- connection_key_(connection_key),
- correlation_id_(correlation_id) {
-
- }
- MOCK_METHOD0(CheckPermissions, bool ());
- MOCK_METHOD0(Init, bool ());
- MOCK_METHOD0(Run, void ());
- MOCK_METHOD0(CleanUp, bool ());
- MOCK_CONST_METHOD0(default_timeout, uint32_t ());
- MOCK_CONST_METHOD0(function_id, int32_t ());
- MOCK_METHOD0(onTimeOut, void ());
- MOCK_METHOD0(AllowedToTerminate, bool ());
- MOCK_METHOD1(SetAllowedToTerminate, void (bool));
-
- uint32_t connection_key_;
- uint32_t correlation_id_;
- virtual uint32_t connection_key() const;
- virtual uint32_t correlation_id() const;
-};
+namespace test {
+namespace components {
+namespace application_manager_test {
+
+class MockRequest : public application_manager::commands::Command {
+ public:
+ MockRequest(uint32_t connection_key, uint32_t correlation_id)
+ : connection_key_(connection_key), correlation_id_(correlation_id) {}
+ MOCK_METHOD0(CheckPermissions, bool());
+ MOCK_METHOD0(Init, bool());
+ MOCK_METHOD0(Run, void());
+ MOCK_METHOD0(CleanUp, bool());
+ MOCK_CONST_METHOD0(default_timeout, uint32_t());
+ MOCK_CONST_METHOD0(function_id, int32_t());
+ MOCK_METHOD0(onTimeOut, void());
+ MOCK_METHOD0(AllowedToTerminate, bool());
+ MOCK_METHOD1(SetAllowedToTerminate, void(bool));
-class TestRequestInfo: public request_info::RequestInfo {
- public:
- TestRequestInfo(request_info::RequestPtr request,
- const RequestType requst_type,
- const TimevalStruct& start_time,
- const uint64_t timeout_sec):
- RequestInfo(request, requst_type, start_time,timeout_sec) {
+ uint32_t connection_key_;
+ uint32_t correlation_id_;
+ virtual uint32_t connection_key() const {
+ return connection_key_;
+ }
+ virtual uint32_t correlation_id() const {
+ return correlation_id_;
+ }
+};
- }
- void SetEndTime(const TimevalStruct& end_time);
+class TestRequestInfo : public request_info::RequestInfo {
+ public:
+ TestRequestInfo(request_info::RequestPtr request,
+ const RequestType requst_type,
+ const TimevalStruct& start_time,
+ const uint64_t timeout_msec)
+ : RequestInfo(request, requst_type, start_time, timeout_msec) {}
+ void SetEndTime(const TimevalStruct& end_time) {
+ end_time_ = end_time;
+ }
};
+
class RequestInfoTest : public ::testing::Test {
- protected:
- virtual void SetUp() {
- //INIT_LOGGER("log4cxx.properties");
- count_of_requests_for_test_ = 1000;
- hmi_connection_key_ = 0;
- mobile_connection_key1_ = 65431;
- mobile_connection_key2_ = 65123;
- default_timeout_ = 10;
- srand(42);
- }
- virtual void TearDown() {
- //DEINIT_LOGGER();
- }
-
- request_info::RequestInfoSet request_info_set_;
- uint32_t count_of_requests_for_test_ ;
- uint32_t hmi_connection_key_;
- uint32_t mobile_connection_key1_;
- uint32_t mobile_connection_key2_;
- uint32_t default_timeout_;
-
- utils::SharedPtr<TestRequestInfo> create_test_info(uint32_t connection_key,
- uint32_t correlation_id,
- request_info::RequestInfo::RequestType requst_type,
- const TimevalStruct& start_time,
- uint64_t timeout_sec) {
- utils::SharedPtr<MockRequest> mock_request(new MockRequest(connection_key,correlation_id));
- TestRequestInfo* test_request_raw = new TestRequestInfo(mock_request,requst_type,
- start_time, timeout_sec);
- utils::SharedPtr<TestRequestInfo> request(test_request_raw);
- return request;
- }
+ protected:
+ virtual void SetUp() OVERRIDE {
+ count_of_requests_for_test_ = 1000;
+ hmi_connection_key_ = 0;
+ mobile_connection_key1_ = 65431;
+ mobile_connection_key2_ = 65123;
+ mobile_correlation_id = 111;
+ default_timeout_ = 10;
+ }
+
+ request_info::RequestInfoSet request_info_set_;
+ uint32_t count_of_requests_for_test_;
+ uint32_t hmi_connection_key_;
+ uint32_t mobile_connection_key1_;
+ uint32_t mobile_connection_key2_;
+ uint32_t default_timeout_;
+ uint32_t mobile_correlation_id;
+
+ utils::SharedPtr<TestRequestInfo> CreateTestInfo(
+ uint32_t connection_key,
+ uint32_t correlation_id,
+ request_info::RequestInfo::RequestType requst_type,
+ const TimevalStruct& start_time,
+ uint64_t timeout_msec) {
+ utils::SharedPtr<MockRequest> mock_request =
+ utils::MakeShared<MockRequest>(connection_key, correlation_id);
+ utils::SharedPtr<TestRequestInfo> request =
+ utils::MakeShared<TestRequestInfo>(
+ mock_request, requst_type, start_time, timeout_msec);
+ return request;
+ }
};
-TEST_F(RequestInfoTest, RequestInfoEqualEndTimeTest) {
- std::list<utils::SharedPtr<TestRequestInfo> > requests;
+TEST_F(RequestInfoTest, RequestInfoEqualEndTime) {
+ std::vector<utils::SharedPtr<TestRequestInfo>> requests;
const TimevalStruct& time = date_time::DateTime::getCurrentTime();
for (uint32_t i = 0; i < count_of_requests_for_test_; ++i) {
- utils::SharedPtr<TestRequestInfo> request =
- create_test_info(rand(), rand(), request_info::RequestInfo::MobileRequest,
- time, default_timeout_);
+ utils::SharedPtr<TestRequestInfo> request = CreateTestInfo(
+ i, i, request_info::RequestInfo::MobileRequest, time, default_timeout_);
request->SetEndTime(time);
EXPECT_TRUE(request_info_set_.Add(request));
}
EXPECT_EQ(count_of_requests_for_test_, request_info_set_.Size());
}
-TEST_F(RequestInfoTest, RequestInfoSetInsertErazeTest) {
+TEST_F(RequestInfoTest, AddRemoveHMIRequests) {
for (uint32_t i = 0; i < count_of_requests_for_test_; ++i) {
utils::SharedPtr<TestRequestInfo> request =
- create_test_info(hmi_connection_key_, i, request_info::RequestInfo::HMIRequest,
- date_time::DateTime::getCurrentTime(), default_timeout_);
- EXPECT_TRUE(request_info_set_.Add(request));
- EXPECT_EQ(1, request_info_set_.RemoveRequest(request));
+ CreateTestInfo(hmi_connection_key_,
+ i,
+ request_info::RequestInfo::HMIRequest,
+ date_time::DateTime::getCurrentTime(),
+ default_timeout_);
+ EXPECT_TRUE(request_info_set_.Add(request));
+ EXPECT_TRUE(request_info_set_.RemoveRequest(request));
}
EXPECT_EQ(0u, request_info_set_.Size());
- std::list<utils::SharedPtr<TestRequestInfo> > requests;
+}
+TEST_F(RequestInfoTest, AddHMIRequests_RemoveAllRequests) {
+ std::vector<utils::SharedPtr<TestRequestInfo>> requests;
+
+ // Add hmi requests
for (uint32_t i = 0; i < count_of_requests_for_test_; ++i) {
- utils::SharedPtr<TestRequestInfo> request =
- create_test_info(hmi_connection_key_, i, request_info::RequestInfo::HMIRequest,
- date_time::DateTime::getCurrentTime(), default_timeout_);
- requests.push_back(request);
- EXPECT_TRUE(request_info_set_.Add(request));
+ utils::SharedPtr<TestRequestInfo> request =
+ CreateTestInfo(hmi_connection_key_,
+ i,
+ request_info::RequestInfo::HMIRequest,
+ date_time::DateTime::getCurrentTime(),
+ default_timeout_);
+ requests.push_back(request);
+ EXPECT_TRUE(request_info_set_.Add(request));
}
+ EXPECT_EQ(count_of_requests_for_test_, request_info_set_.Size());
- std::list<utils::SharedPtr<TestRequestInfo> >::iterator it = requests.begin();
- std::list<utils::SharedPtr<TestRequestInfo> >::iterator end = requests.end();
+ // Delete every request
+ std::vector<utils::SharedPtr<TestRequestInfo>>::iterator req_it =
+ requests.begin();
- for (; it != end; ++it) {
- EXPECT_EQ(1,request_info_set_.RemoveRequest(*it));
+ for (; req_it != requests.end(); ++req_it) {
+ EXPECT_TRUE(request_info_set_.RemoveRequest(*req_it));
}
EXPECT_EQ(0u, request_info_set_.Size());
- it = requests.begin();
- for (; it != end; ++it) {
- EXPECT_TRUE(request_info_set_.Add(*it));
+
+ // Delete requests by connection key
+ req_it = requests.begin();
+ for (; req_it != requests.end(); ++req_it) {
+ EXPECT_TRUE(request_info_set_.Add(*req_it));
}
EXPECT_EQ(count_of_requests_for_test_, request_info_set_.Size());
- EXPECT_EQ(count_of_requests_for_test_, request_info_set_.RemoveByConnectionKey(hmi_connection_key_));
+ EXPECT_EQ(count_of_requests_for_test_,
+ request_info_set_.RemoveByConnectionKey(hmi_connection_key_));
EXPECT_EQ(0u, request_info_set_.Size());
- it = requests.begin();
- for (; it != end; ++it) {
- EXPECT_TRUE(request_info_set_.Add(*it));
+}
+
+TEST_F(RequestInfoTest, CheckRequestsMaxCount) {
+ const uint32_t app_hmi_level_time_scale = 100;
+ const uint32_t hmi_level_count = 1000;
+
+ // Count of added requests is less than max possible
+ std::vector<utils::SharedPtr<TestRequestInfo>> requests;
+ for (uint32_t i = 0; i < hmi_level_count - 1; ++i) {
+ utils::SharedPtr<TestRequestInfo> request =
+ CreateTestInfo(mobile_connection_key1_,
+ i,
+ request_info::RequestInfo::MobileRequest,
+ date_time::DateTime::getCurrentTime(),
+ default_timeout_);
+
+ request->set_hmi_level(mobile_apis::HMILevel::HMI_FULL);
+ requests.push_back(request);
+ EXPECT_TRUE(request_info_set_.Add(request));
}
- EXPECT_EQ(count_of_requests_for_test_, request_info_set_.Size());
+ EXPECT_EQ(hmi_level_count - 1, request_info_set_.Size());
+
+ EXPECT_TRUE(request_info_set_.CheckHMILevelTimeScaleMaxRequest(
+ mobile_apis::HMILevel::HMI_FULL,
+ mobile_connection_key1_,
+ app_hmi_level_time_scale,
+ hmi_level_count));
+
+ // Adding new request is correct
+ utils::SharedPtr<TestRequestInfo> new_request =
+ CreateTestInfo(mobile_connection_key1_,
+ hmi_level_count,
+ request_info::RequestInfo::MobileRequest,
+ date_time::DateTime::getCurrentTime(),
+ default_timeout_);
+ new_request->set_hmi_level(mobile_apis::HMILevel::HMI_FULL);
+ EXPECT_TRUE(request_info_set_.Add(new_request));
+ EXPECT_EQ(hmi_level_count, request_info_set_.Size());
+
+ // Count of added requests is max
+ EXPECT_FALSE(request_info_set_.CheckHMILevelTimeScaleMaxRequest(
+ mobile_apis::HMILevel::HMI_FULL,
+ mobile_connection_key1_,
+ app_hmi_level_time_scale,
+ hmi_level_count));
+
+ utils::SharedPtr<TestRequestInfo> new_request2 =
+ CreateTestInfo(mobile_connection_key1_,
+ hmi_level_count + 1,
+ request_info::RequestInfo::MobileRequest,
+ date_time::DateTime::getCurrentTime(),
+ default_timeout_);
+
+ EXPECT_TRUE(request_info_set_.Add(new_request2));
+}
+
+TEST_F(RequestInfoTest, CheckMaxCountOfRequest) {
+ const uint32_t app_hmi_level_time_scale = 100;
+ const uint32_t hmi_level_count = 1000;
+
+ // Count of added requests is less than max possible
+ std::vector<utils::SharedPtr<TestRequestInfo>> requests;
+ for (uint32_t i = 0; i < hmi_level_count - 1; ++i) {
+ utils::SharedPtr<TestRequestInfo> request =
+ CreateTestInfo(mobile_connection_key1_,
+ i,
+ request_info::RequestInfo::MobileRequest,
+ date_time::DateTime::getCurrentTime(),
+ default_timeout_);
+ request->set_hmi_level(mobile_apis::HMILevel::HMI_FULL);
+ requests.push_back(request);
+ EXPECT_TRUE(request_info_set_.Add(request));
+ }
+ EXPECT_EQ(hmi_level_count - 1, request_info_set_.Size());
+
+ EXPECT_TRUE(request_info_set_.CheckTimeScaleMaxRequest(
+ mobile_connection_key1_, app_hmi_level_time_scale, hmi_level_count));
+
+ // Adding new request is correct
+ utils::SharedPtr<TestRequestInfo> new_request =
+ CreateTestInfo(mobile_connection_key1_,
+ hmi_level_count,
+ request_info::RequestInfo::MobileRequest,
+ date_time::DateTime::getCurrentTime(),
+ default_timeout_);
+ new_request->set_hmi_level(mobile_apis::HMILevel::HMI_FULL);
+ EXPECT_TRUE(request_info_set_.Add(new_request));
+ EXPECT_EQ(hmi_level_count, request_info_set_.Size());
+
+ // Count of added requests is max
+ EXPECT_FALSE(request_info_set_.CheckTimeScaleMaxRequest(
+ mobile_connection_key1_, app_hmi_level_time_scale, hmi_level_count));
+
+ utils::SharedPtr<TestRequestInfo> new_request2 =
+ CreateTestInfo(mobile_connection_key1_,
+ hmi_level_count + 1,
+ request_info::RequestInfo::MobileRequest,
+ date_time::DateTime::getCurrentTime(),
+ default_timeout_);
+
+ EXPECT_TRUE(request_info_set_.Add(new_request2));
+}
+
+TEST_F(RequestInfoTest, AddMobileRequests_RemoveMobileRequests) {
utils::SharedPtr<TestRequestInfo> mobile_request1 =
- create_test_info(mobile_connection_key1_, 12345, request_info::RequestInfo::MobileRequest,
- date_time::DateTime::getCurrentTime(), default_timeout_);
+ CreateTestInfo(mobile_connection_key1_,
+ 12345,
+ request_info::RequestInfo::MobileRequest,
+ date_time::DateTime::getCurrentTime(),
+ default_timeout_);
EXPECT_TRUE(request_info_set_.Add(mobile_request1));
utils::SharedPtr<TestRequestInfo> mobile_request2 =
- create_test_info(mobile_connection_key2_, 54321, request_info::RequestInfo::MobileRequest,
- date_time::DateTime::getCurrentTime(), default_timeout_);
+ CreateTestInfo(mobile_connection_key2_,
+ 54321,
+ request_info::RequestInfo::MobileRequest,
+ date_time::DateTime::getCurrentTime(),
+ default_timeout_);
EXPECT_TRUE(request_info_set_.Add(mobile_request2));
- EXPECT_EQ(count_of_requests_for_test_ + 2, request_info_set_.Size());
+ EXPECT_EQ(2u, request_info_set_.Size());
EXPECT_EQ(2u, request_info_set_.RemoveMobileRequests());
- EXPECT_EQ(count_of_requests_for_test_, request_info_set_.Size());
- EXPECT_TRUE(request_info_set_.Add(mobile_request1));
- EXPECT_TRUE(request_info_set_.Add(mobile_request2));
- EXPECT_EQ(1u, request_info_set_.RemoveByConnectionKey(mobile_connection_key1_));
- EXPECT_EQ(count_of_requests_for_test_ + 1, request_info_set_.Size());
- EXPECT_EQ(count_of_requests_for_test_, request_info_set_.RemoveByConnectionKey(hmi_connection_key_));
- EXPECT_EQ(1u, request_info_set_.Size());
- EXPECT_EQ(1u, request_info_set_.RemoveMobileRequests());
EXPECT_EQ(0u, request_info_set_.Size());
}
-TEST_F(RequestInfoTest, RequestInfoSetFrontTest) {
+TEST_F(RequestInfoTest, AddMobileRequests_RemoveMobileRequestsByConnectionKey) {
+ std::vector<utils::SharedPtr<TestRequestInfo>> requests;
+ const uint32_t count_of_mobile_request1 = 200;
+ const uint32_t count_of_mobile_request2 = 100;
+ for (uint32_t i = 0; i < count_of_mobile_request1; ++i) {
+ utils::SharedPtr<TestRequestInfo> mobile_request1 =
+ CreateTestInfo(mobile_connection_key1_,
+ i,
+ request_info::RequestInfo::MobileRequest,
+ date_time::DateTime::getCurrentTime(),
+ default_timeout_);
+ requests.push_back(mobile_request1);
+ EXPECT_TRUE(request_info_set_.Add(mobile_request1));
+ }
+ EXPECT_EQ(count_of_mobile_request1, request_info_set_.Size());
+
+ for (uint32_t i = 0; i < count_of_mobile_request2; ++i) {
+ utils::SharedPtr<TestRequestInfo> mobile_request2 =
+ CreateTestInfo(mobile_connection_key2_,
+ i,
+ request_info::RequestInfo::MobileRequest,
+ date_time::DateTime::getCurrentTime(),
+ default_timeout_);
+
+ requests.push_back(mobile_request2);
+ EXPECT_TRUE(request_info_set_.Add(mobile_request2));
+ }
+ EXPECT_EQ(count_of_mobile_request1 + count_of_mobile_request2,
+ request_info_set_.Size());
+
+ EXPECT_EQ(count_of_mobile_request1,
+ request_info_set_.RemoveByConnectionKey(mobile_connection_key1_));
+ EXPECT_EQ(count_of_mobile_request2,
+ request_info_set_.RemoveByConnectionKey(mobile_connection_key2_));
+ EXPECT_EQ(0u, request_info_set_.Size());
+}
+
+TEST_F(RequestInfoTest, RequestInfoSetFront) {
for (uint32_t i = 0; i < count_of_requests_for_test_; ++i) {
- utils::SharedPtr<TestRequestInfo> request =
- create_test_info(mobile_connection_key1_, i, request_info::RequestInfo::HMIRequest,
- date_time::DateTime::getCurrentTime(), i);
- request_info_set_.Add(request);
+ utils::SharedPtr<TestRequestInfo> request =
+ CreateTestInfo(mobile_connection_key1_,
+ i,
+ request_info::RequestInfo::HMIRequest,
+ date_time::DateTime::getCurrentTime(),
+ i);
+ request_info_set_.Add(request);
}
for (uint32_t i = 1; i < count_of_requests_for_test_; ++i) {
request_info::RequestInfoPtr request_info = request_info_set_.Front();
EXPECT_TRUE(request_info.valid());
- EXPECT_EQ(0u, request_info->timeout_sec());
request_info = request_info_set_.FrontWithNotNullTimeout();
EXPECT_TRUE(request_info.valid());
- EXPECT_EQ(i, request_info->timeout_sec());
EXPECT_TRUE(request_info_set_.RemoveRequest(request_info));
}
EXPECT_EQ(1u, request_info_set_.Size());
- EXPECT_EQ(1u, request_info_set_.RemoveByConnectionKey(mobile_connection_key1_));
+ EXPECT_EQ(1u,
+ request_info_set_.RemoveByConnectionKey(mobile_connection_key1_));
EXPECT_EQ(0u, request_info_set_.Size());
}
-TEST_F(RequestInfoTest, RequestInfoSetFindTest) {
-
- std::list <std::pair<uint32_t, uint32_t> > appId_coorrId;
+TEST_F(RequestInfoTest, RequestInfoSetFind) {
+ std::vector<std::pair<uint32_t, uint32_t>> appid_connection_id;
for (uint32_t i = 0; i < count_of_requests_for_test_; ++i) {
- appId_coorrId.push_back(std::pair<uint32_t, uint32_t>(rand(),rand()));
+ appid_connection_id.push_back(
+ std::pair<uint32_t, uint32_t>(i, count_of_requests_for_test_ - i));
}
- std::list <std::pair<uint32_t, uint32_t> >::iterator it;
- std::list <std::pair<uint32_t, uint32_t> >::iterator end =
- appId_coorrId.end();;
+ std::vector<std::pair<uint32_t, uint32_t>>::iterator req_it =
+ appid_connection_id.begin();
+ const std::vector<std::pair<uint32_t, uint32_t>>::iterator end =
+ appid_connection_id.end();
- for (it = appId_coorrId.begin(); it != end; ++it) {
+ for (; req_it != end; ++req_it) {
utils::SharedPtr<TestRequestInfo> request =
- create_test_info(it->first, it->second, request_info::RequestInfo::HMIRequest,
- date_time::DateTime::getCurrentTime(), 10);
+ CreateTestInfo(req_it->first,
+ req_it->second,
+ request_info::RequestInfo::HMIRequest,
+ date_time::DateTime::getCurrentTime(),
+ 10);
EXPECT_TRUE(request_info_set_.Add(request));
}
- request_info::RequestInfoPtr request = request_info_set_.Find(rand(),rand());
+ request_info::RequestInfoPtr request = request_info_set_.Find(
+ count_of_requests_for_test_, count_of_requests_for_test_);
EXPECT_FALSE(request.valid());
- for (it = appId_coorrId.begin(); it != end; ++it) {
- request_info::RequestInfoPtr request = request_info_set_.Find(it->first, it->second);
+
+ req_it = appid_connection_id.begin();
+ for (; req_it != end; ++req_it) {
+ request_info::RequestInfoPtr request =
+ request_info_set_.Find(req_it->first, req_it->second);
EXPECT_TRUE(request.valid());
- EXPECT_EQ(1u, request_info_set_.RemoveRequest(request));
- request = request_info_set_.Find(it->first, it->second);
+ EXPECT_TRUE(request_info_set_.RemoveRequest(request));
+ request = request_info_set_.Find(req_it->first, req_it->second);
EXPECT_FALSE(request.valid());
}
EXPECT_EQ(0u, request_info_set_.Size());
}
-TEST_F(RequestInfoTest, RequestInfoSetEqualHashTest) {
+TEST_F(RequestInfoTest, RequestInfoSetEqualHash) {
request_info::RequestInfoSet request_info_set;
const uint32_t connection_key = 65483;
const uint32_t corr_id = 65483;
utils::SharedPtr<TestRequestInfo> request =
- create_test_info(connection_key, corr_id, request_info::RequestInfo::HMIRequest,
- date_time::DateTime::getCurrentTime(), 10);
+ CreateTestInfo(connection_key,
+ corr_id,
+ request_info::RequestInfo::HMIRequest,
+ date_time::DateTime::getCurrentTime(),
+ 10);
EXPECT_TRUE(request_info_set.Add(request));
EXPECT_FALSE(request_info_set.Add(request));
EXPECT_FALSE(request_info_set.Add(request));
EXPECT_EQ(1u, request_info_set.Size());
- request_info::RequestInfoPtr found = request_info_set.Find(connection_key, corr_id);
+ request_info::RequestInfoPtr found =
+ request_info_set.Find(connection_key, corr_id);
EXPECT_TRUE(found.valid());
- EXPECT_EQ(1u, request_info_set.RemoveRequest(found));
+ EXPECT_TRUE(request_info_set.RemoveRequest(found));
EXPECT_EQ(0u, request_info_set.Size());
EXPECT_TRUE(request_info_set.Add(request));
EXPECT_FALSE(request_info_set.Add(request));
- found = request_info_set.FrontWithNotNullTimeout();
+ found = request_info_set.FrontWithNotNullTimeout();
EXPECT_TRUE(found.valid());
- EXPECT_EQ(1u, request_info_set.RemoveRequest(found));
- found = request_info_set.FrontWithNotNullTimeout();
+ EXPECT_TRUE(request_info_set.RemoveRequest(found));
+ found = request_info_set.FrontWithNotNullTimeout();
+ EXPECT_FALSE(found.valid());
+ found = request_info_set.Front();
EXPECT_FALSE(found.valid());
EXPECT_EQ(0u, request_info_set.Size());
}
+TEST_F(RequestInfoTest, EndTimeisExpired) {
+ TimevalStruct time = date_time::DateTime::getCurrentTime();
-uint32_t MockRequest::correlation_id() const {
- return correlation_id_;
-}
+ TimevalStruct not_expired = date_time::DateTime::getCurrentTime();
+ not_expired.tv_usec = std::numeric_limits<time_t>::min();
-uint32_t MockRequest::connection_key() const {
- return connection_key_;
+ TimevalStruct expired = date_time::DateTime::getCurrentTime();
+ expired.tv_usec = std::numeric_limits<time_t>::max();
+
+ utils::SharedPtr<TestRequestInfo> request =
+ CreateTestInfo(mobile_connection_key1_,
+ mobile_correlation_id,
+ request_info::RequestInfo::MobileRequest,
+ time,
+ default_timeout_);
+
+ request->SetEndTime(expired);
+ EXPECT_FALSE(request->isExpired());
+
+ request->SetEndTime(not_expired);
+ EXPECT_TRUE(request->isExpired());
}
+TEST_F(RequestInfoTest, UpdateEndTime) {
+ TimevalStruct time = date_time::DateTime::getCurrentTime();
+ utils::SharedPtr<TestRequestInfo> request =
+ CreateTestInfo(mobile_connection_key1_,
+ mobile_correlation_id,
+ request_info::RequestInfo::MobileRequest,
+ time,
+ default_timeout_);
+ request->SetEndTime(time);
+ request->updateEndTime();
+ TimevalStruct last_time = request->end_time();
+ EXPECT_LE(time.tv_sec, last_time.tv_sec);
+}
+TEST_F(RequestInfoTest, UpdateTimeOut) {
+ TimevalStruct time = date_time::DateTime::getCurrentTime();
+ utils::SharedPtr<TestRequestInfo> request =
+ CreateTestInfo(mobile_connection_key1_,
+ mobile_correlation_id,
+ request_info::RequestInfo::MobileRequest,
+ time,
+ default_timeout_);
+ request->SetEndTime(time);
+ request->updateEndTime();
-void TestRequestInfo::SetEndTime(const TimevalStruct& end_time) {
- end_time_ = end_time;
+ request->updateTimeOut(100);
+ time = date_time::DateTime::getCurrentTime();
+ TimevalStruct last_time = request->end_time();
+ EXPECT_NEAR(time.tv_sec + 100, last_time.tv_sec, 500);
}
+
+} // namespace application_manager_test
+} // namespace components
+} // namespace test
diff --git a/src/components/application_manager/test/resumption/include/application_mock.h b/src/components/application_manager/test/resumption/include/application_mock.h
deleted file mode 100644
index 39c4b33539..0000000000
--- a/src/components/application_manager/test/resumption/include/application_mock.h
+++ /dev/null
@@ -1,266 +0,0 @@
-/*
-* Copyright (c) 2015, Ford Motor Company
-* All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions are met:
-*
-* Redistributions of source code must retain the above copyright notice, this
-* list of conditions and the following disclaimer.
-*
-* Redistributions in binary form must reproduce the above copyright notice,
-* this list of conditions and the following
-* disclaimer in the documentation and/or other materials provided with the
-* distribution.
-*
-* Neither the name of the Ford Motor Company nor the names of its contributors
-* may be used to endorse or promote products derived from this software
-* without specific prior written permission.
-*
-* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-* POSSIBILITY OF SUCH DAMAGE.
-*/
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_APPLICATION_MOCK_H_
-#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_APPLICATION_MOCK_H_
-#include <string>
-#include "gmock/gmock.h"
-#include "application_manager/application.h"
-
-namespace test {
-namespace components {
-namespace resumption_test {
-
-class ApplicationMock : public ::application_manager::Application {
- public:
- MOCK_CONST_METHOD0(active_message, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(curHash, const std::string&());
- MOCK_METHOD0(UpdateHash, void());
- MOCK_CONST_METHOD0(flag_sending_hash_change_after_awake, bool());
- MOCK_METHOD1(set_flag_sending_hash_change_after_awake, void(bool flag));
- MOCK_CONST_METHOD0(is_application_data_changed, bool());
- MOCK_METHOD1(set_is_application_data_changed,
- void(bool state_application_data));
- MOCK_METHOD0(CloseActiveMessage, void());
- MOCK_CONST_METHOD0(IsFullscreen, bool());
- MOCK_METHOD0(ChangeSupportingAppHMIType, void());
- MOCK_CONST_METHOD0(is_navi, bool());
- MOCK_METHOD1(set_is_navi, void(bool allow));
- MOCK_CONST_METHOD0(video_streaming_approved, bool());
- MOCK_METHOD1(set_video_streaming_approved, void(bool state));
- MOCK_CONST_METHOD0(audio_streaming_approved, bool());
- MOCK_METHOD1(set_audio_streaming_approved, void(bool state));
- MOCK_CONST_METHOD0(video_streaming_allowed, bool());
- MOCK_METHOD1(set_video_streaming_allowed, void(bool state));
- MOCK_CONST_METHOD0(audio_streaming_allowed, bool());
- MOCK_METHOD1(set_audio_streaming_allowed, void(bool state));
- MOCK_METHOD1(StartStreaming,
- void(protocol_handler::ServiceType service_type));
- MOCK_METHOD1(StopStreaming, void(protocol_handler::ServiceType service_type));
- MOCK_METHOD1(SuspendStreaming,
- void(protocol_handler::ServiceType service_type));
- MOCK_METHOD1(WakeUpStreaming,
- void(protocol_handler::ServiceType service_type));
- MOCK_CONST_METHOD0(is_voice_communication_supported, bool());
- MOCK_METHOD1(set_voice_communication_supported,
- void(bool is_voice_communication_supported));
- MOCK_CONST_METHOD0(app_allowed, bool());
- MOCK_CONST_METHOD0(has_been_activated, bool());
- MOCK_METHOD1(set_activated, bool(bool is_active));
- MOCK_CONST_METHOD0(version, const ::application_manager::Version&());
- MOCK_METHOD1(set_hmi_application_id, void(uint32_t hmi_app_id));
- MOCK_CONST_METHOD0(hmi_app_id, uint32_t());
- MOCK_CONST_METHOD0(name, const std::string&());
- MOCK_METHOD1(set_folder_name, void(const std::string& folder_name));
- MOCK_CONST_METHOD0(folder_name, const std::string());
- MOCK_CONST_METHOD0(is_media_application, bool());
- MOCK_CONST_METHOD0(hmi_level, const mobile_apis::HMILevel::eType());
- MOCK_CONST_METHOD0(put_file_in_none_count, const uint32_t());
- MOCK_CONST_METHOD0(delete_file_in_none_count, const uint32_t());
- MOCK_CONST_METHOD0(list_files_in_none_count, const uint32_t());
- MOCK_CONST_METHOD0(system_context, const mobile_apis::SystemContext::eType());
- MOCK_CONST_METHOD0(audio_streaming_state,
- const mobile_apis::AudioStreamingState::eType());
- MOCK_CONST_METHOD0(app_icon_path, const std::string&());
- MOCK_CONST_METHOD0(device, connection_handler::DeviceHandle());
- MOCK_METHOD0(tts_speak_state, bool());
- MOCK_CONST_METHOD0(CurrentHmiState,
- ::application_manager::HmiStatePtr());
- MOCK_CONST_METHOD0(RegularHmiState,
- ::application_manager::HmiStatePtr());
- MOCK_CONST_METHOD0(PostponedHmiState,
- ::application_manager::HmiStatePtr());
- MOCK_METHOD1(set_tts_properties_in_none, void(bool active));
- MOCK_METHOD0(tts_properties_in_none, bool());
- MOCK_METHOD1(set_tts_properties_in_full, void(bool active));
- MOCK_METHOD0(tts_properties_in_full, bool());
- MOCK_METHOD1(set_version,
- void(const ::application_manager::Version& version));
- MOCK_METHOD1(set_name, void(const std::string& name));
- MOCK_METHOD1(set_is_media_application, void(bool is_media));
- MOCK_METHOD0(increment_put_file_in_none_count, void());
- MOCK_METHOD0(increment_delete_file_in_none_count, void());
- MOCK_METHOD0(increment_list_files_in_none_count, void());
- MOCK_METHOD1(set_app_icon_path, bool(const std::string& file_name));
- MOCK_METHOD1(set_app_allowed, void(const bool& allowed));
- MOCK_METHOD1(set_device, void(connection_handler::DeviceHandle device));
- MOCK_CONST_METHOD0(get_grammar_id, uint32_t());
- MOCK_METHOD1(set_grammar_id, void(uint32_t value));
- MOCK_METHOD1(
- set_protocol_version,
- void(const ::application_manager::ProtocolVersion& protocol_version));
- MOCK_CONST_METHOD0(protocol_version,
- ::application_manager::ProtocolVersion());
- MOCK_METHOD1(set_is_resuming, void(bool));
- MOCK_CONST_METHOD0(is_resuming, bool());
- MOCK_METHOD1(AddFile, bool(const ::application_manager::AppFile& file));
- MOCK_CONST_METHOD0(getAppFiles, const ::application_manager::AppFilesMap&());
- MOCK_METHOD1(UpdateFile, bool(const ::application_manager::AppFile& file));
- MOCK_METHOD1(DeleteFile, bool(const std::string& file_name));
- MOCK_METHOD1(GetFile, const ::application_manager::AppFile*(
- const std::string& file_name));
- MOCK_METHOD1(SubscribeToButton,
- bool(mobile_apis::ButtonName::eType btn_name));
- MOCK_METHOD1(IsSubscribedToButton,
- bool(mobile_apis::ButtonName::eType btn_name));
- MOCK_METHOD1(UnsubscribeFromButton,
- bool(mobile_apis::ButtonName::eType btn_name));
- MOCK_METHOD1(SubscribeToIVI, bool(uint32_t vehicle_info_type));
- MOCK_CONST_METHOD1(IsSubscribedToIVI, bool(uint32_t vehicle_info_type));
- MOCK_METHOD1(UnsubscribeFromIVI, bool(uint32_t vehicle_info_type));
- MOCK_METHOD0(ResetDataInNone, void());
- MOCK_METHOD2(IsCommandLimitsExceeded,
- bool(mobile_apis::FunctionID::eType cmd_id,
- ::application_manager::TLimitSource source));
- MOCK_METHOD0(usage_report, ::application_manager::UsageStatistics&());
- MOCK_METHOD1(SetRegularState, void(::application_manager::HmiStatePtr state));
- MOCK_METHOD1(SetPostponedState, void(::application_manager::HmiStatePtr state));
- MOCK_METHOD1(AddHMIState, void(::application_manager::HmiStatePtr state));
- MOCK_METHOD1(RemoveHMIState,
- void(::application_manager::HmiState::StateID state_id));
- MOCK_METHOD2(SubscribeToSoftButtons,
- void(int32_t cmd_id,
- const ::application_manager::SoftButtonID& softbuttons_id));
- MOCK_METHOD1(IsSubscribedToSoftButton, bool(const uint32_t softbutton_id));
- MOCK_METHOD1(UnsubscribeFromSoftButtons, void(int32_t cmd_id));
- MOCK_CONST_METHOD0(IsAudioApplication, bool());
- MOCK_METHOD0(LoadPersistentFiles, void());
- // InitialApplicationData methods
- MOCK_CONST_METHOD0(app_types, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(vr_synonyms, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(policy_app_id, std::string());
- MOCK_CONST_METHOD0(tts_name, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(ngn_media_screen_name,
- const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(language, const mobile_apis::Language::eType&());
- MOCK_CONST_METHOD0(ui_language, const mobile_apis::Language::eType&());
- MOCK_METHOD1(set_app_types,
- void(const smart_objects::SmartObject& app_types));
- MOCK_METHOD1(set_vr_synonyms,
- void(const smart_objects::SmartObject& vr_synonyms));
- MOCK_METHOD1(set_policy_app_id, void(const std::string& policy_app_id));
- MOCK_METHOD1(set_tts_name, void(const smart_objects::SmartObject& tts_name));
- MOCK_METHOD1(set_ngn_media_screen_name,
- void(const smart_objects::SmartObject& ngn_name));
- MOCK_METHOD1(set_language,
- void(const mobile_apis::Language::eType& language));
- MOCK_METHOD1(set_ui_language,
- void(const mobile_apis::Language::eType& ui_language));
- // DynamicApplicationData methods
- MOCK_CONST_METHOD0(help_prompt, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(timeout_prompt, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(vr_help_title, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(vr_help, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(tbt_state, const mobile_apis::TBTState::eType&());
- MOCK_CONST_METHOD0(show_command, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(tbt_show_command, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(
- SubscribedButtons,
- DataAccessor< ::application_manager::ButtonSubscriptions >());
- MOCK_CONST_METHOD0(
- SubscribedIVI,
- DataAccessor< ::application_manager::VehicleInfoSubscriptions >());
- MOCK_CONST_METHOD0(keyboard_props, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(menu_title, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(menu_icon, const smart_objects::SmartObject*());
- MOCK_METHOD1(load_global_properties,
- void(const smart_objects::SmartObject& so));
- MOCK_METHOD1(set_help_prompt,
- void(const smart_objects::SmartObject& help_prompt));
- MOCK_METHOD1(set_timeout_prompt,
- void(const smart_objects::SmartObject& timeout_prompt));
- MOCK_METHOD1(set_vr_help_title,
- void(const smart_objects::SmartObject& vr_help_title));
- MOCK_METHOD0(reset_vr_help_title, void());
- MOCK_METHOD1(set_vr_help, void(const smart_objects::SmartObject& vr_help));
- MOCK_METHOD0(reset_vr_help, void());
- MOCK_METHOD1(set_tbt_state,
- void(const mobile_apis::TBTState::eType& tbt_state));
- MOCK_METHOD1(set_show_command,
- void(const smart_objects::SmartObject& show_command));
- MOCK_METHOD1(set_tbt_show_command,
- void(const smart_objects::SmartObject& tbt_show));
- MOCK_METHOD1(set_keyboard_props,
- void(const smart_objects::SmartObject& keyboard_props));
- MOCK_METHOD1(set_menu_title,
- void(const smart_objects::SmartObject& menu_title));
- MOCK_METHOD1(set_menu_icon,
- void(const smart_objects::SmartObject& menu_icon));
- MOCK_CONST_METHOD0(audio_stream_retry_number, uint32_t());
- MOCK_METHOD1(set_audio_stream_retry_number,
- void(const uint32_t& audio_stream_retry_number));
- MOCK_CONST_METHOD0(video_stream_retry_number, uint32_t());
- MOCK_METHOD1(set_video_stream_retry_number,
- void(const uint32_t& video_stream_retry_number));
- MOCK_METHOD2(AddCommand, void(uint32_t cmd_id,
- const smart_objects::SmartObject& command));
- MOCK_METHOD1(RemoveCommand, void(uint32_t cmd_id));
- MOCK_METHOD1(FindCommand, smart_objects::SmartObject*(uint32_t cmd_id));
- MOCK_METHOD2(AddSubMenu,
- void(uint32_t menu_id, const smart_objects::SmartObject& menu));
- MOCK_METHOD1(RemoveSubMenu, void(uint32_t menu_id));
- MOCK_CONST_METHOD1(FindSubMenu,
- smart_objects::SmartObject*(uint32_t menu_id));
- MOCK_METHOD1(IsSubMenuNameAlreadyExist, bool(const std::string& name));
- MOCK_METHOD2(AddChoiceSet,
- void(uint32_t choice_set_id,
- const smart_objects::SmartObject& choice_set));
- MOCK_METHOD1(RemoveChoiceSet, void(uint32_t choice_set_id));
- MOCK_METHOD1(FindChoiceSet,
- smart_objects::SmartObject*(uint32_t choice_set_id));
- MOCK_METHOD3(AddPerformInteractionChoiceSet,
- void(uint32_t correlation_id, uint32_t choice_set_id,
- const smart_objects::SmartObject& choice_set));
- MOCK_METHOD1(DeletePerformInteractionChoiceSet,
- void(uint32_t correlation_id));
- MOCK_CONST_METHOD0(
- performinteraction_choice_set_map,
- DataAccessor< ::application_manager::PerformChoiceSetMap >());
- MOCK_CONST_METHOD0(commands_map,
- DataAccessor< ::application_manager::CommandsMap >());
- MOCK_CONST_METHOD0(sub_menu_map,
- DataAccessor< ::application_manager::SubMenuMap >());
- MOCK_CONST_METHOD0(choice_set_map,
- DataAccessor< ::application_manager::ChoiceSetMap >());
- MOCK_METHOD1(set_perform_interaction_active, void(uint32_t active));
- MOCK_CONST_METHOD0(is_perform_interaction_active, uint32_t());
- MOCK_METHOD1(set_perform_interaction_mode, void(int32_t mode));
- MOCK_CONST_METHOD0(perform_interaction_mode, int32_t());
- MOCK_METHOD1(set_reset_global_properties_active, void(bool active));
- MOCK_CONST_METHOD0(is_reset_global_properties_active, bool());
- MOCK_CONST_METHOD0(app_id, uint32_t());
-};
-
-} // namespace resumption_test
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_APPLICATION_MOCK_H_
diff --git a/src/components/application_manager/test/resumption/include/resumption_data_mock.h b/src/components/application_manager/test/resumption/include/resumption_data_mock.h
deleted file mode 100644
index 2c9285b025..0000000000
--- a/src/components/application_manager/test/resumption/include/resumption_data_mock.h
+++ /dev/null
@@ -1,86 +0,0 @@
-/*
-* Copyright (c) 2015, Ford Motor Company
-* All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions are met:
-*
-* Redistributions of source code must retain the above copyright notice, this
-* list of conditions and the following disclaimer.
-*
-* Redistributions in binary form must reproduce the above copyright notice,
-* this list of conditions and the following
-* disclaimer in the documentation and/or other materials provided with the
-* distribution.
-*
-* Neither the name of the Ford Motor Company nor the names of its contributors
-* may be used to endorse or promote products derived from this software
-* without specific prior written permission.
-*
-* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-* POSSIBILITY OF SUCH DAMAGE.
-*/
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_RESUMPTION_DATA_MOCK_H_
-#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_RESUMPTION_DATA_MOCK_H_
-#include <string>
-#include "gmock/gmock.h"
-#include "application_manager/resumption/resumption_data.h"
-#include "application_manager/application.h"
-
-namespace test {
-namespace components {
-namespace resumption_test {
-namespace app_mngr = application_manager;
-namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
-
-class ResumptionDataMock : public ::resumption::ResumptionData {
- public:
- MOCK_METHOD1(SaveApplication,
- void(app_mngr::ApplicationSharedPtr application));
- MOCK_CONST_METHOD2(GetStoredHMILevel,
- int32_t(const std::string& policy_app_id,
- const std::string& device_id));
- MOCK_CONST_METHOD1(IsHMIApplicationIdExist, bool(uint32_t hmi_app_id));
- MOCK_METHOD2(CheckSavedApplication, bool(const std::string& policy_app_id,
- const std::string& device_id));
- MOCK_CONST_METHOD2(GetHMIApplicationID,
- uint32_t(const std::string& policy_app_id,
- const std::string& device_id));
- MOCK_METHOD0(OnSuspend, void());
- MOCK_CONST_METHOD3(GetHashId,
- bool(const std::string& policy_app_id,
- const std::string& device_id, std::string& hash_id));
- MOCK_METHOD0(OnAwake, void());
- MOCK_CONST_METHOD3(GetSavedApplication,
- bool(const std::string& policy_app_id,
- const std::string& device_id,
- smart_objects::SmartObject& saved_app));
- MOCK_METHOD2(RemoveApplicationFromSaved,
- bool(const std::string& policy_app_id,
- const std::string& device_id));
- MOCK_CONST_METHOD0(GetIgnOffTime, uint32_t());
- MOCK_CONST_METHOD2(IsApplicationSaved,
- ssize_t(const std::string& policy_app_id,
- const std::string& device_id));
- MOCK_CONST_METHOD1(GetDataForLoadResumeData,
- void(smart_objects::SmartObject& saved_data));
- MOCK_METHOD3(UpdateHmiLevel, void(const std::string& policy_app_id,
- const std::string& device_id,
- mobile_apis::HMILevel::eType hmi_level));
- MOCK_METHOD0(Init, bool());
-};
-
-} // namespace resumption_test
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_RESUMPTION_INCLUDE_RESUMPTION_DATA_MOCK_H_
diff --git a/src/components/application_manager/test/resumption/include/resumption_data_test.h b/src/components/application_manager/test/resumption/include/resumption_data_test.h
deleted file mode 100644
index 55767225b5..0000000000
--- a/src/components/application_manager/test/resumption/include/resumption_data_test.h
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <string>
-#include <algorithm>
-#include "gtest/gtest.h"
-#include "application_manager/usage_statistics.h"
-#include "application_mock.h"
-#include "application_manager/application_manager_impl.h"
-#include "utils/data_accessor.h"
-
-namespace test {
-namespace components {
-namespace resumption_test {
-
-using ::testing::NiceMock;
-namespace am = application_manager;
-namespace sm = smart_objects;
-using namespace Json;
-
-using namespace resumption;
-using namespace mobile_apis;
-
-class ResumptionDataTest : public ::testing::Test {
- protected:
- // Check structure in saved application
- void CheckSavedApp(sm::SmartObject& saved_data);
-
- // Set data for resumption
- virtual void PrepareData();
- utils::SharedPtr<NiceMock<ApplicationMock>> app_mock;
-
- HMILevel::eType hmi_level_;
- size_t app_id_;
- size_t hmi_app_id_;
- std::string policy_app_id_;
- size_t ign_off_count_;
- const size_t tts_chunks_count = 4;
-
- size_t grammar_id_;
- std::string hash_;
- bool is_audio_;
- const connection_handler::DeviceHandle device_handle_ = 10;
-
- sm::SmartObject* help_prompt_;
- sm::SmartObject* timeout_prompt_;
- sm::SmartObject* vr_help_;
- sm::SmartObject* vr_help_title_;
- sm::SmartObject* vr_synonyms_;
- sm::SmartObject* keyboard_props_;
- sm::SmartObject* menu_title_;
- sm::SmartObject* menu_icon_;
-
- void SetCommands();
- void SetSubmenues();
- void SetChoiceSet();
- void SetAppFiles();
- void SetGlobalProporties();
- void SetKeyboardProperties();
- void SetMenuTitleAndIcon();
- void SetHelpAndTimeoutPrompt();
- void SetVRHelpTitle();
- void SetSubscriptions();
-
- void CheckCommands(sm::SmartObject& res_list);
- void CheckGlobalProporties(sm::SmartObject& res_list);
- void CheckSubmenues(sm::SmartObject& res_list);
- void CheckChoiceSet(sm::SmartObject& res_list);
- void CheckAppFiles(sm::SmartObject& res_list);
- void CheckKeyboardProperties(sm::SmartObject& res_list);
- void CheckMenuTitle(sm::SmartObject& res_list);
- void CheckMenuIcon(sm::SmartObject& res_list);
- void CheckHelpPrompt(sm::SmartObject& res_list);
- void CheckTimeoutPrompt(sm::SmartObject& res_list);
- void CheckVRHelp(NsSmartDeviceLink::NsSmartObjects::SmartObject& res_list);
- void CheckVRTitle(sm::SmartObject& res_list);
- void CheckSubscriptions(sm::SmartObject& res_list);
-
- const size_t count_of_commands = 5;
- const size_t count_of_choice = 2;
- const size_t count_of_choice_sets = 4;
- const size_t count_of_submenues = 3;
- const size_t count_of_files = 8;
- const size_t count_of_vrhelptitle = 2;
- const std::string device_id_ = "12345";
-
- am::CommandsMap test_commands_map;
- am::SubMenuMap test_submenu_map;
- am::ChoiceSetMap test_choiceset_map;
- am::AppFilesMap app_files_map_;
-
- am::ButtonSubscriptions btn_subscr;
- am::VehicleInfoSubscriptions ivi;
-
- sync_primitives::Lock sublock_;
- sync_primitives::Lock comlock_;
- sync_primitives::Lock setlock_;
- sync_primitives::Lock btnlock_;
- sync_primitives::Lock ivilock_;
-};
-
-} // namespace resumption_test
-} // namespace components
-} // namespace test
diff --git a/src/components/application_manager/test/resumption/resume_ctrl_test.cc b/src/components/application_manager/test/resumption/resume_ctrl_test.cc
index bfd41b0f08..9857072674 100644
--- a/src/components/application_manager/test/resumption/resume_ctrl_test.cc
+++ b/src/components/application_manager/test/resumption/resume_ctrl_test.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -35,14 +35,18 @@
#include <algorithm>
#include "gtest/gtest.h"
#include "application_manager/usage_statistics.h"
-#include "include/application_mock.h"
-#include "include/resumption_data_mock.h"
+#include "application_manager/mock_application.h"
+#include "application_manager/mock_resumption_data.h"
#include "interfaces/MOBILE_API.h"
#include "application_manager/application_manager_impl.h"
#include "application_manager/application.h"
-#include "config_profile/profile.h"
#include "utils/data_accessor.h"
-#include "application_manager/test/mock_message_helper.h"
+#include "utils/make_shared.h"
+#include "application_manager/mock_message_helper.h"
+#include "application_manager/mock_application_manager.h"
+#include "application_manager/mock_application_manager_settings.h"
+#include "application_manager/mock_event_dispatcher.h"
+#include "application_manager/mock_state_controller.h"
namespace test {
namespace components {
@@ -50,48 +54,77 @@ namespace resumption_test {
using ::testing::_;
using ::testing::Return;
+using ::testing::ReturnRef;
using ::testing::DoAll;
using ::testing::SetArgReferee;
using ::testing::Mock;
using ::testing::NiceMock;
using ::testing::AtLeast;
+using namespace application_manager_test;
using namespace resumption;
using namespace mobile_apis::HMILevel;
class ResumeCtrlTest : public ::testing::Test {
- public:
+ protected:
+ ResumeCtrlTest()
+ : kTestAppId_(10u)
+ , kTestPolicyAppId_("test_policy_app_id")
+ , kMacAddress_("12345")
+ , kDefaultTestLevel_(eType::HMI_NONE)
+ , kCorId_(7u)
+ , kTestDevId_(5u)
+ , kTestGrammarId_(10)
+ , kHash_("saved_hash")
+ , kAppResumingTimeout_(30000000u) {}
+
virtual void SetUp() OVERRIDE {
- app_mngr = application_manager::ApplicationManagerImpl::instance();
- // Singleton should not be destroyed
- Mock::AllowLeak(app_mngr);
- mock_storage = new NiceMock<ResumptionDataMock>();
- app_mock = new NiceMock<ApplicationMock>();
- res_ctrl.set_resumption_storage(mock_storage);
- test_audio_state = mobile_apis::AudioStreamingState::NOT_AUDIBLE;
- test_app_id = 10;
- default_testType = eType::HMI_NONE;
- test_dev_id = 5;
- test_policy_app_id = "test_policy_app_id";
- test_grammar_id = 10;
- hash = "saved_hash";
+ ON_CALL(app_mngr_, event_dispatcher())
+ .WillByDefault(ReturnRef(mock_event_dispatcher_));
+ mock_storage =
+ ::utils::MakeShared<NiceMock<resumption_test::MockResumptionData>>(
+ app_mngr_);
+ app_mock = utils::MakeShared<NiceMock<MockApplication>>();
+ res_ctrl = utils::MakeShared<ResumeCtrl>(app_mngr_);
+ res_ctrl->set_resumption_storage(mock_storage);
+
+ ON_CALL(app_mngr_, state_controller())
+ .WillByDefault(ReturnRef(state_controller_));
+ ON_CALL(app_mngr_, get_settings())
+ .WillByDefault(ReturnRef(mock_application_manager_settings_));
+
+ ON_CALL(mock_application_manager_settings_, use_db_for_resumption())
+ .WillByDefault(Return(false));
+ ON_CALL(mock_application_manager_settings_, app_resuming_timeout())
+ .WillByDefault(ReturnRef(kAppResumingTimeout_));
+ }
+ void GetInfoFromApp() {
+ ON_CALL(*app_mock, policy_app_id())
+ .WillByDefault(Return(kTestPolicyAppId_));
+ ON_CALL(*app_mock, mac_address()).WillByDefault(ReturnRef(kMacAddress_));
+ ON_CALL(*app_mock, device()).WillByDefault(Return(kTestDevId_));
+ ON_CALL(*app_mock, app_id()).WillByDefault(Return(kTestAppId_));
}
- protected:
- application_manager::ApplicationManagerImpl* app_mngr;
- ResumeCtrl res_ctrl;
- NiceMock<ResumptionDataMock>* mock_storage;
- NiceMock<ApplicationMock>* app_mock;
- mobile_apis::AudioStreamingState::eType test_audio_state;
+ NiceMock<event_engine_test::MockEventDispatcher> mock_event_dispatcher_;
+ application_manager_test::MockApplicationManagerSettings
+ mock_application_manager_settings_;
+ application_manager_test::MockApplicationManager app_mngr_;
+ MockStateController state_controller_;
+ utils::SharedPtr<ResumeCtrl> res_ctrl;
+ utils::SharedPtr<NiceMock<resumption_test::MockResumptionData>> mock_storage;
+ utils::SharedPtr<NiceMock<MockApplication>> app_mock;
// app_mock.app_id() will return this value
- uint32_t test_app_id;
- std::string test_policy_app_id;
- mobile_apis::HMILevel::eType default_testType;
-
+ const uint32_t kTestAppId_;
+ const std::string kTestPolicyAppId_;
+ const std::string kMacAddress_;
+ const mobile_apis::HMILevel::eType kDefaultTestLevel_;
+ const uint32_t kCorId_;
// app_mock.Device() will return this value
- uint32_t test_dev_id;
- uint32_t test_grammar_id;
- std::string hash;
+ const uint32_t kTestDevId_;
+ const uint32_t kTestGrammarId_;
+ const std::string kHash_;
+ const uint32_t kAppResumingTimeout_;
};
/**
@@ -100,17 +133,20 @@ class ResumeCtrlTest : public ::testing::Test {
TEST_F(ResumeCtrlTest, StartResumption_AppWithGrammarId) {
smart_objects::SmartObject saved_app;
- saved_app[application_manager::strings::hash_id] = hash;
- saved_app[application_manager::strings::grammar_id] = test_grammar_id;
+ saved_app[application_manager::strings::hash_id] = kHash_;
+ saved_app[application_manager::strings::grammar_id] = kTestGrammarId_;
// Check RestoreApplicationData
- EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _))
- .Times(3)
+ GetInfoFromApp();
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_))
+ .WillRepeatedly(Return(kDefaultTestLevel_));
+ EXPECT_CALL(*mock_storage,
+ GetSavedApplication(kTestPolicyAppId_, kMacAddress_, _))
.WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true)));
EXPECT_CALL(*app_mock, UpdateHash());
- EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id));
+ EXPECT_CALL(*app_mock, set_grammar_id(kTestGrammarId_));
- bool res = res_ctrl.StartResumption(app_mock, hash);
+ bool res = res_ctrl->StartResumption(app_mock, kHash_);
EXPECT_TRUE(res);
}
@@ -123,20 +159,23 @@ MATCHER_P4(CheckAppFile, is_persistent, is_download, file_name, file_type, "") {
TEST_F(ResumeCtrlTest, StartResumption_WithoutGrammarId) {
smart_objects::SmartObject saved_app;
- saved_app[application_manager::strings::hash_id] = hash;
+ saved_app[application_manager::strings::hash_id] = kHash_;
+ GetInfoFromApp();
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_))
+ .WillRepeatedly(Return(kDefaultTestLevel_));
// Check RestoreApplicationData
EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _))
- .Times(3)
.WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true)));
EXPECT_CALL(*app_mock, UpdateHash());
- EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id)).Times(0);
+ EXPECT_CALL(*app_mock, set_grammar_id(kTestGrammarId_)).Times(0);
- bool res = res_ctrl.StartResumption(app_mock, hash);
+ bool res = res_ctrl->StartResumption(app_mock, kHash_);
EXPECT_FALSE(res);
}
TEST_F(ResumeCtrlTest, StartResumption_AppWithFiles) {
+ GetInfoFromApp();
smart_objects::SmartObject test_application_files;
smart_objects::SmartObject test_file;
const uint32_t count_of_files = 8;
@@ -164,29 +203,33 @@ TEST_F(ResumeCtrlTest, StartResumption_AppWithFiles) {
}
smart_objects::SmartObject saved_app;
- saved_app[application_manager::strings::hash_id] = hash;
- saved_app[application_manager::strings::grammar_id] = test_grammar_id;
+ saved_app[application_manager::strings::hash_id] = kHash_;
+ saved_app[application_manager::strings::grammar_id] = kTestGrammarId_;
saved_app[application_manager::strings::application_files] =
test_application_files;
// Check RestoreApplicationData
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_))
+ .WillRepeatedly(Return(kDefaultTestLevel_));
EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _))
- .Times(3)
.WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true)));
EXPECT_CALL(*app_mock, UpdateHash());
- EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id));
+ EXPECT_CALL(*app_mock, set_grammar_id(kTestGrammarId_));
for (uint32_t i = 0; i < count_of_files; ++i) {
EXPECT_CALL(*app_mock,
AddFile(CheckAppFile(
- true, true, file_names[i],
+ true,
+ true,
+ file_names[i],
static_cast<mobile_apis::FileType::eType>(file_types[i]))));
}
- bool res = res_ctrl.StartResumption(app_mock, hash);
+ bool res = res_ctrl->StartResumption(app_mock, kHash_);
EXPECT_TRUE(res);
}
TEST_F(ResumeCtrlTest, StartResumption_AppWithSubmenues) {
+ GetInfoFromApp();
smart_objects::SmartObject test_application_submenues;
smart_objects::SmartObject test_submenu;
@@ -197,31 +240,37 @@ TEST_F(ResumeCtrlTest, StartResumption_AppWithSubmenues) {
}
smart_objects::SmartObject saved_app;
- saved_app[application_manager::strings::hash_id] = hash;
- saved_app[application_manager::strings::grammar_id] = test_grammar_id;
+ saved_app[application_manager::strings::hash_id] = kHash_;
+ saved_app[application_manager::strings::grammar_id] = kTestGrammarId_;
saved_app[application_manager::strings::application_submenus] =
test_application_submenues;
// Check RestoreApplicationData
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_))
+ .WillRepeatedly(Return(kDefaultTestLevel_));
EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _))
- .Times(3)
.WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true)));
- EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id));
+ EXPECT_CALL(*app_mock, set_grammar_id(kTestGrammarId_));
for (uint32_t i = 0; i < count_of_submenues; ++i) {
EXPECT_CALL(*app_mock, AddSubMenu(i, test_application_submenues[i]));
}
smart_objects::SmartObjectList requests;
+
+ EXPECT_CALL(app_mngr_, GetNextHMICorrelationID())
+ .WillRepeatedly(Return(kCorId_));
EXPECT_CALL(*application_manager::MockMessageHelper::message_helper_mock(),
- CreateAddSubMenuRequestToHMI(_)).WillRepeatedly(Return(requests));
+ CreateAddSubMenuRequestToHMI(_, kCorId_))
+ .WillRepeatedly(Return(requests));
EXPECT_CALL(*app_mock, UpdateHash());
- bool res = res_ctrl.StartResumption(app_mock, hash);
+ bool res = res_ctrl->StartResumption(app_mock, kHash_);
EXPECT_TRUE(res);
}
TEST_F(ResumeCtrlTest, StartResumption_AppWithCommands) {
+ GetInfoFromApp();
smart_objects::SmartObject test_application_commands;
smart_objects::SmartObject test_commands;
const uint32_t count_of_commands = 20;
@@ -232,17 +281,18 @@ TEST_F(ResumeCtrlTest, StartResumption_AppWithCommands) {
}
smart_objects::SmartObject saved_app;
- saved_app[application_manager::strings::hash_id] = hash;
- saved_app[application_manager::strings::grammar_id] = test_grammar_id;
+ saved_app[application_manager::strings::hash_id] = kHash_;
+ saved_app[application_manager::strings::grammar_id] = kTestGrammarId_;
saved_app[application_manager::strings::application_commands] =
test_application_commands;
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_))
+ .WillRepeatedly(Return(kDefaultTestLevel_));
// Check RestoreApplicationData
EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _))
- .Times(3)
.WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true)));
EXPECT_CALL(*app_mock, UpdateHash());
- EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id));
+ EXPECT_CALL(*app_mock, set_grammar_id(kTestGrammarId_));
for (uint32_t i = 0; i < count_of_commands; ++i) {
EXPECT_CALL(*app_mock, AddCommand(i, test_application_commands[i]));
@@ -250,9 +300,10 @@ TEST_F(ResumeCtrlTest, StartResumption_AppWithCommands) {
smart_objects::SmartObjectList requests;
EXPECT_CALL(*application_manager::MockMessageHelper::message_helper_mock(),
- CreateAddCommandRequestToHMI(_)).WillRepeatedly(Return(requests));
+ CreateAddCommandRequestToHMI(_, _))
+ .WillRepeatedly(Return(requests));
- bool res = res_ctrl.StartResumption(app_mock, hash);
+ bool res = res_ctrl->StartResumption(app_mock, kHash_);
EXPECT_TRUE(res);
}
@@ -280,17 +331,19 @@ TEST_F(ResumeCtrlTest, StartResumption_AppWithChoiceSet) {
}
smart_objects::SmartObject saved_app;
- saved_app[application_manager::strings::hash_id] = hash;
- saved_app[application_manager::strings::grammar_id] = test_grammar_id;
+ saved_app[application_manager::strings::hash_id] = kHash_;
+ saved_app[application_manager::strings::grammar_id] = kTestGrammarId_;
saved_app[application_manager::strings::application_choice_sets] =
application_choice_sets;
// Check RestoreApplicationData
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_))
+ .WillRepeatedly(Return(kDefaultTestLevel_));
+ GetInfoFromApp();
EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _))
- .Times(3)
.WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true)));
EXPECT_CALL(*app_mock, UpdateHash());
- EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id));
+ EXPECT_CALL(*app_mock, set_grammar_id(kTestGrammarId_));
for (uint32_t i = 0; i < count_of_choice_sets; ++i) {
EXPECT_CALL(*app_mock, AddChoiceSet(i, application_choice_sets[i]));
@@ -301,7 +354,7 @@ TEST_F(ResumeCtrlTest, StartResumption_AppWithChoiceSet) {
CreateAddVRCommandRequestFromChoiceToHMI(_))
.WillRepeatedly(Return(requests));
- bool res = res_ctrl.StartResumption(app_mock, hash);
+ bool res = res_ctrl->StartResumption(app_mock, kHash_);
EXPECT_TRUE(res);
}
@@ -309,17 +362,19 @@ TEST_F(ResumeCtrlTest, StartResumption_AppWithGlobalProperties) {
// Prepare Data
smart_objects::SmartObject test_global_properties;
smart_objects::SmartObject saved_app;
- saved_app[application_manager::strings::hash_id] = hash;
- saved_app[application_manager::strings::grammar_id] = test_grammar_id;
+ saved_app[application_manager::strings::hash_id] = kHash_;
+ saved_app[application_manager::strings::grammar_id] = kTestGrammarId_;
saved_app[application_manager::strings::application_global_properties] =
test_global_properties;
// Check RestoreApplicationData
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_))
+ .WillRepeatedly(Return(kDefaultTestLevel_));
+ GetInfoFromApp();
EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _))
- .Times(3)
.WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true)));
- EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id));
+ EXPECT_CALL(*app_mock, set_grammar_id(kTestGrammarId_));
EXPECT_CALL(*application_manager::MockMessageHelper::message_helper_mock(),
SendGlobalPropertiesToHMI(_));
@@ -327,7 +382,7 @@ TEST_F(ResumeCtrlTest, StartResumption_AppWithGlobalProperties) {
EXPECT_CALL(*app_mock, load_global_properties(test_global_properties));
EXPECT_CALL(*app_mock, UpdateHash());
- bool res = res_ctrl.StartResumption(app_mock, hash);
+ bool res = res_ctrl->StartResumption(app_mock, kHash_);
EXPECT_TRUE(res);
}
@@ -345,28 +400,31 @@ TEST_F(ResumeCtrlTest, StartResumption_AppWithSubscribeOnButtons) {
app_buttons;
smart_objects::SmartObject saved_app;
- saved_app[application_manager::strings::hash_id] = hash;
- saved_app[application_manager::strings::grammar_id] = test_grammar_id;
+ saved_app[application_manager::strings::hash_id] = kHash_;
+ saved_app[application_manager::strings::grammar_id] = kTestGrammarId_;
saved_app[application_manager::strings::application_subscribtions] =
test_subscriptions;
// Check RestoreApplicationData
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_))
+ .WillRepeatedly(Return(kDefaultTestLevel_));
+ GetInfoFromApp();
EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _))
- .Times(3)
.WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true)));
- EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id));
+ EXPECT_CALL(*app_mock, set_grammar_id(kTestGrammarId_));
for (uint32_t i = 0; i < count_of_buttons; ++i) {
- EXPECT_CALL(*app_mock, SubscribeToButton(
- static_cast<mobile_apis::ButtonName::eType>(i)));
+ EXPECT_CALL(
+ *app_mock,
+ SubscribeToButton(static_cast<mobile_apis::ButtonName::eType>(i)));
}
EXPECT_CALL(*app_mock, UpdateHash());
EXPECT_CALL(*application_manager::MockMessageHelper::message_helper_mock(),
- SendAllOnButtonSubscriptionNotificationsForApp(_)).Times(2);
+ SendAllOnButtonSubscriptionNotificationsForApp(_, _)).Times(2);
- bool res = res_ctrl.StartResumption(app_mock, hash);
+ bool res = res_ctrl->StartResumption(app_mock, kHash_);
EXPECT_TRUE(res);
}
@@ -386,17 +444,19 @@ TEST_F(ResumeCtrlTest, StartResumption_AppWithSubscriptionToIVI) {
app_vi;
smart_objects::SmartObject saved_app;
- saved_app[application_manager::strings::hash_id] = hash;
- saved_app[application_manager::strings::grammar_id] = test_grammar_id;
+ saved_app[application_manager::strings::hash_id] = kHash_;
+ saved_app[application_manager::strings::grammar_id] = kTestGrammarId_;
saved_app[application_manager::strings::application_subscribtions] =
test_subscriptions;
// Check RestoreApplicationData
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_))
+ .WillRepeatedly(Return(kDefaultTestLevel_));
+ GetInfoFromApp();
EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _))
- .Times(3)
.WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true)));
- EXPECT_CALL(*app_mock, set_grammar_id(test_grammar_id));
+ EXPECT_CALL(*app_mock, set_grammar_id(kTestGrammarId_));
for (size_t i = 0; i < app_vi.length(); ++i) {
EXPECT_CALL(
@@ -404,97 +464,62 @@ TEST_F(ResumeCtrlTest, StartResumption_AppWithSubscriptionToIVI) {
SubscribeToIVI(static_cast<application_manager::VehicleDataType>(i)));
}
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
-
smart_objects::SmartObjectList requests;
EXPECT_CALL(*application_manager::MockMessageHelper::message_helper_mock(),
GetIVISubscriptionRequests(_)).WillRepeatedly(Return(requests));
EXPECT_CALL(*app_mock, UpdateHash());
- bool res = res_ctrl.StartResumption(app_mock, hash);
+ bool res = res_ctrl->StartResumption(app_mock, kHash_);
EXPECT_TRUE(res);
}
TEST_F(ResumeCtrlTest, StartResumptionOnlyHMILevel) {
smart_objects::SmartObject saved_app;
- ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false));
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock));
- ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id));
- EXPECT_CALL(*mock_storage, GetSavedApplication(test_policy_app_id, _, _))
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_))
+ .WillOnce(Return(kDefaultTestLevel_));
+ GetInfoFromApp();
+ EXPECT_CALL(*mock_storage, GetSavedApplication(kTestPolicyAppId_, _, _))
.WillOnce(DoAll(SetArgReferee<2>(saved_app), Return(true)));
-
- EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_))
- .Times(3)
- .WillRepeatedly(Return(default_testType));
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
- EXPECT_CALL(*app_mngr, SetState(test_app_id, default_testType,
- test_audio_state)).Times(2);
- bool res = res_ctrl.StartResumptionOnlyHMILevel(app_mock);
+ bool res = res_ctrl->StartResumptionOnlyHMILevel(app_mock);
EXPECT_TRUE(res);
}
TEST_F(ResumeCtrlTest, StartAppHmiStateResumption_AppInFull) {
- mobile_apis::HMILevel::eType restored_testType = eType::HMI_FULL;
+ mobile_apis::HMILevel::eType restored_test_type = eType::HMI_FULL;
uint32_t ign_off_count = 0;
smart_objects::SmartObject saved_app;
saved_app[application_manager::strings::ign_off_count] = ign_off_count;
- saved_app[application_manager::strings::hmi_level] = restored_testType;
-
- ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(true));
+ saved_app[application_manager::strings::hmi_level] = restored_test_type;
- ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id));
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- EXPECT_CALL(*app_mngr,
- SetHmiState(test_app_id, restored_testType)).Times(AtLeast(1));
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
- EXPECT_CALL(*mock_storage, GetSavedApplication(test_policy_app_id, _, _))
- .Times(2)
+ EXPECT_CALL(state_controller_, SetRegularState(_, restored_test_type))
+ .Times(AtLeast(1));
+ GetInfoFromApp();
+ EXPECT_CALL(*mock_storage, GetSavedApplication(kTestPolicyAppId_, _, _))
.WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true)));
- EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_))
- .WillOnce(Return(default_testType));
-
EXPECT_CALL(*mock_storage, RemoveApplicationFromSaved(_, _))
.WillOnce(Return(true));
- EXPECT_CALL(*app_mngr, GetUserConsentForDevice("12345"))
+ EXPECT_CALL(app_mngr_, GetUserConsentForDevice("12345"))
.WillRepeatedly(Return(policy::kDeviceAllowed));
- EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock));
- EXPECT_CALL(*app_mngr,
- SetState(test_app_id, default_testType, test_audio_state));
- EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_))
- .WillOnce(Return(true));
-
- res_ctrl.StartAppHmiStateResumption(app_mock);
+ res_ctrl->StartAppHmiStateResumption(app_mock);
}
TEST_F(ResumeCtrlTest, StartAppHmiStateResumption_AppInBackground) {
uint32_t ign_off_count = 0;
smart_objects::SmartObject saved_app;
- mobile_apis::HMILevel::eType restored_testType = eType::HMI_BACKGROUND;
+ mobile_apis::HMILevel::eType restored_test_type = eType::HMI_BACKGROUND;
saved_app[application_manager::strings::ign_off_count] = ign_off_count;
- saved_app[application_manager::strings::hmi_level] = restored_testType;
+ saved_app[application_manager::strings::hmi_level] = restored_test_type;
- ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id));
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- EXPECT_CALL(*mock_storage, GetSavedApplication(test_policy_app_id, _, _))
+ EXPECT_CALL(app_mngr_, state_controller()).Times(0);
+ GetInfoFromApp();
+ EXPECT_CALL(*mock_storage, GetSavedApplication(kTestPolicyAppId_, _, _))
.WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true)));
- EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_))
- .WillOnce(Return(default_testType));
-
- EXPECT_CALL(*app_mngr, GetUserConsentForDevice("12345"))
- .WillOnce(Return(policy::kDeviceAllowed));
- EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock));
- EXPECT_CALL(*app_mngr,
- SetState(test_app_id, default_testType, test_audio_state));
- EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_))
- .WillOnce(Return(true));
-
- res_ctrl.StartAppHmiStateResumption(app_mock);
+ res_ctrl->StartAppHmiStateResumption(app_mock);
}
/**
@@ -502,320 +527,153 @@ TEST_F(ResumeCtrlTest, StartAppHmiStateResumption_AppInBackground) {
*/
TEST_F(ResumeCtrlTest, RestoreAppHMIState_RestoreHMILevelFull) {
- mobile_apis::HMILevel::eType restored_testType = eType::HMI_FULL;
+ mobile_apis::HMILevel::eType restored_test_type = eType::HMI_FULL;
smart_objects::SmartObject saved_app;
- saved_app[application_manager::strings::hash_id] = hash;
- saved_app[application_manager::strings::grammar_id] = test_grammar_id;
- saved_app[application_manager::strings::hmi_level] = restored_testType;
+ saved_app[application_manager::strings::hash_id] = kHash_;
+ saved_app[application_manager::strings::grammar_id] = kTestGrammarId_;
+ saved_app[application_manager::strings::hmi_level] = restored_test_type;
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id));
+ EXPECT_CALL(state_controller_, SetRegularState(_, restored_test_type))
+ .Times(AtLeast(1));
+ GetInfoFromApp();
EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _))
.WillOnce(DoAll(SetArgReferee<2>(saved_app), Return(true)));
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- EXPECT_CALL(*app_mngr, GetUserConsentForDevice(""))
+ EXPECT_CALL(app_mngr_, GetUserConsentForDevice("12345"))
.WillOnce(Return(policy::kDeviceAllowed));
- EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_))
- .WillRepeatedly(Return(false));
+ EXPECT_CALL(*app_mock, set_is_resuming(true));
- utils::SharedPtr<application_manager::Application> null_app;
- EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(null_app));
-
- ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false));
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
-
- EXPECT_CALL(*app_mngr,
- SetState(test_app_id, restored_testType, test_audio_state));
-
- bool res = res_ctrl.RestoreAppHMIState(app_mock);
+ bool res = res_ctrl->RestoreAppHMIState(app_mock);
EXPECT_TRUE(res);
}
TEST_F(ResumeCtrlTest, SetupDefaultHMILevel) {
smart_objects::SmartObject saved_app;
- saved_app[application_manager::strings::hmi_level] = default_testType;
+ saved_app[application_manager::strings::hmi_level] = kDefaultTestLevel_;
- EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_))
- .WillRepeatedly(Return(default_testType));
-
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- EXPECT_CALL(*app_mngr, GetUserConsentForDevice("")).Times(0);
- EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_))
- .WillOnce(Return(true));
- EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock));
- EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_))
- .WillOnce(Return(default_testType));
- EXPECT_CALL(*app_mngr,
- SetHmiState(test_app_id, default_testType)).Times(AtLeast(1));
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_))
+ .WillRepeatedly(Return(kDefaultTestLevel_));
+ GetInfoFromApp();
+ EXPECT_CALL(app_mngr_, GetUserConsentForDevice("12345")).Times(0);
- ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false));
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_))
+ .WillOnce(Return(kDefaultTestLevel_));
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
- EXPECT_CALL(*app_mngr, SetState(test_app_id, default_testType,
- test_audio_state)).Times(2);
+ EXPECT_CALL(state_controller_, SetRegularState(_, kDefaultTestLevel_))
+ .Times(AtLeast(1));
- res_ctrl.SetupDefaultHMILevel(app_mock);
+ res_ctrl->SetupDefaultHMILevel(app_mock);
}
/**
* @brief group of tests which check correct SetAppHMIState
*/
-TEST_F(ResumeCtrlTest, SetAppHMIState_HMINone_NotMedia_WithoutCheckPolicy) {
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- EXPECT_CALL(*app_mngr, GetUserConsentForDevice("")).Times(0);
- EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_))
- .WillOnce(Return(true));
- EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock));
- EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_))
- .WillOnce(Return(default_testType));
-
- ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false));
+TEST_F(ResumeCtrlTest, SetAppHMIState_HMINone_WithoutCheckPolicy) {
+ GetInfoFromApp();
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
- EXPECT_CALL(*app_mngr, SetState(test_app_id, default_testType,
- test_audio_state)).Times(2);
+ EXPECT_CALL(app_mngr_, GetUserConsentForDevice("12345")).Times(0);
- bool res = res_ctrl.SetAppHMIState(app_mock, default_testType, false);
+ EXPECT_CALL(*app_mock, set_is_resuming(true));
+ EXPECT_CALL(state_controller_, SetRegularState(_, kDefaultTestLevel_))
+ .Times(AtLeast(1));
+ bool res = res_ctrl->SetAppHMIState(app_mock, kDefaultTestLevel_, false);
EXPECT_TRUE(res);
}
-// TODO(VVeremjova) APPLINK-16718
-TEST_F(ResumeCtrlTest,
- DISABLED_SetAppHMIState_HMILimited_NotMedia_WithoutCheckPolicy) {
- mobile_apis::HMILevel::eType testType = eType::HMI_LIMITED;
-
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
-
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
- ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false));
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
-
- EXPECT_CALL(*app_mngr, GetUserConsentForDevice(""))
- .WillRepeatedly(Return(policy::DeviceConsent::kDeviceAllowed));
- EXPECT_CALL(*app_mngr, SetState(test_app_id, testType, test_audio_state));
+TEST_F(ResumeCtrlTest, SetAppHMIState_HMILimited_WithoutCheckPolicy) {
+ mobile_apis::HMILevel::eType test_type = eType::HMI_LIMITED;
+ GetInfoFromApp();
+ EXPECT_CALL(app_mngr_, GetUserConsentForDevice("12345")).Times(0);
- bool res = res_ctrl.SetAppHMIState(app_mock, testType, false);
+ EXPECT_CALL(*app_mock, set_is_resuming(true));
+ EXPECT_CALL(state_controller_, SetRegularState(_, test_type))
+ .Times(AtLeast(1));
+ bool res = res_ctrl->SetAppHMIState(app_mock, test_type, false);
EXPECT_TRUE(res);
}
-TEST_F(ResumeCtrlTest, SetAppHMIState_HMIFull_NotMedia_WithoutCheckPolicy) {
- mobile_apis::HMILevel::eType testType = eType::HMI_FULL;
- ::testing::InSequence seq;
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_))
- .WillOnce(Return(false));
-
- // Only mocked application is exist
- utils::SharedPtr<application_manager::Application> null_app;
- EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(null_app));
-
- ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false));
-
+TEST_F(ResumeCtrlTest, SetAppHMIState_HMIFull_WithoutCheckPolicy) {
+ mobile_apis::HMILevel::eType test_type = eType::HMI_FULL;
+ GetInfoFromApp();
// GetDefaultHmiLevel should not be called
- EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)).Times(0);
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_)).Times(0);
+ EXPECT_CALL(app_mngr_, GetUserConsentForDevice("12345")).Times(0);
- EXPECT_CALL(*app_mngr, SetState(test_app_id, testType, test_audio_state));
+ EXPECT_CALL(*app_mock, set_is_resuming(true));
+ EXPECT_CALL(state_controller_, SetRegularState(_, test_type))
+ .Times(AtLeast(1));
- EXPECT_CALL(*app_mngr, GetUserConsentForDevice("")).Times(0);
- bool res = res_ctrl.SetAppHMIState(app_mock, testType, false);
+ bool res = res_ctrl->SetAppHMIState(app_mock, test_type, false);
EXPECT_TRUE(res);
}
-TEST_F(ResumeCtrlTest,
- SetAppHMIState_HMIFull_NotMedia_WithoutPolicy_AnotherFullActiveExists) {
- mobile_apis::HMILevel::eType testType = eType::HMI_FULL;
- ::testing::InSequence seq;
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_))
- .WillOnce(Return(false));
-
- EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock));
- EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_))
- .WillOnce(Return(default_testType));
-
- ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false));
-
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
-
- // Expect set default HMI state
- EXPECT_CALL(*app_mngr,
- SetState(test_app_id, default_testType, test_audio_state));
-
- EXPECT_CALL(*app_mngr, GetUserConsentForDevice("")).Times(0);
- bool res = res_ctrl.SetAppHMIState(app_mock, testType, false);
- EXPECT_TRUE(res);
-}
+TEST_F(ResumeCtrlTest, SetAppHMIState_HMIFull_WithPolicy_DevAllowed) {
+ mobile_apis::HMILevel::eType test_type = eType::HMI_FULL;
-TEST_F(ResumeCtrlTest,
- SetAppHMIState_HMIFull_MediaAudio_WithoutPolicy_AnotherActiveAppExists) {
- mobile_apis::HMILevel::eType testType = eType::HMI_FULL;
-
- // In case application is media, audio state will be AUDIBLE
- test_audio_state = mobile_apis::AudioStreamingState::AUDIBLE;
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
-
- // Only our app in FULL
- EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_))
- .WillOnce(Return(false));
-
- // Active app exists
- EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock));
-
- EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)).Times(0);
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
-
- ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(true));
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
-
- mobile_apis::HMILevel::eType expected_testType = eType::HMI_LIMITED;
- EXPECT_CALL(*app_mngr,
- SetState(test_app_id, expected_testType, test_audio_state));
-
- EXPECT_CALL(*app_mngr, GetUserConsentForDevice("")).Times(0);
- bool res = res_ctrl.SetAppHMIState(app_mock, testType, false);
- EXPECT_TRUE(res);
-}
-
-TEST_F(ResumeCtrlTest, SetAppHMIState_HMIFull_Media_WithoutPolicy_FullExists) {
- default_testType = eType::HMI_FULL;
-
- // In case application is media, audio state will be AUDIBLE
- test_audio_state = mobile_apis::AudioStreamingState::AUDIBLE;
- ::testing::InSequence seq;
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_))
- .WillOnce(Return(true));
- EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock));
- EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_))
- .WillOnce(Return(default_testType));
-
- ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(true));
-
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
- EXPECT_CALL(*app_mngr,
- SetState(test_app_id, default_testType, test_audio_state));
-
- EXPECT_CALL(*app_mngr, GetUserConsentForDevice("")).Times(0);
- bool res = res_ctrl.SetAppHMIState(app_mock, default_testType, false);
- EXPECT_TRUE(res);
-}
-
-TEST_F(ResumeCtrlTest, SetAppHMIState_HMIFull_NotMedia_WithPolicy_DevAllowed) {
- mobile_apis::HMILevel::eType testType = eType::HMI_FULL;
-
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
-
- EXPECT_CALL(*app_mngr, GetUserConsentForDevice("12345"))
+ GetInfoFromApp();
+ EXPECT_CALL(app_mngr_, GetUserConsentForDevice("12345"))
.WillOnce(Return(policy::kDeviceAllowed));
- EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_))
- .WillOnce(Return(true));
- EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock));
- EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_))
- .WillOnce(Return(default_testType));
-
- ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false));
-
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
- EXPECT_CALL(*app_mngr,
- SetState(test_app_id, default_testType, test_audio_state));
-
- bool res = res_ctrl.SetAppHMIState(app_mock, testType, true);
- EXPECT_TRUE(res);
-}
-
-TEST_F(ResumeCtrlTest, SetAppHMIState_HMIFull_Media_WithCheckPolicy) {
- mobile_apis::HMILevel::eType testType = eType::HMI_FULL;
-
- // In case application is media, audio state will be AUDIBLE
- test_audio_state = mobile_apis::AudioStreamingState::AUDIBLE;
- ::testing::InSequence seq;
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
-
- // App is allowed
- EXPECT_CALL(*app_mngr, GetUserConsentForDevice("12345"))
- .WillOnce(Return(policy::kDeviceAllowed));
- EXPECT_CALL(*app_mngr, IsAppTypeExistsInFullOrLimited(_))
- .WillOnce(Return(false));
- EXPECT_CALL(*app_mngr, active_application()).WillOnce(Return(app_mock));
- EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_)).Times(0);
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
+ EXPECT_CALL(*app_mock, set_is_resuming(true));
+ EXPECT_CALL(state_controller_, SetRegularState(_, test_type))
+ .Times(AtLeast(1));
- ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(true));
-
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
-
- mobile_apis::HMILevel::eType expected_testType = eType::HMI_LIMITED;
- EXPECT_CALL(*app_mngr,
- SetState(test_app_id, expected_testType, test_audio_state));
-
- bool res = res_ctrl.SetAppHMIState(app_mock, testType, true);
+ bool res = res_ctrl->SetAppHMIState(app_mock, test_type, true);
EXPECT_TRUE(res);
}
-TEST_F(ResumeCtrlTest, SetAppHMIState_HMIFull_Media_WithPolicy_DevDisallowed) {
- mobile_apis::HMILevel::eType testType = eType::HMI_FULL;
+TEST_F(ResumeCtrlTest, SetAppHMIState_HMIFull_WithPolicy_DevDisallowed) {
+ mobile_apis::HMILevel::eType test_type = eType::HMI_FULL;
- ::testing::InSequence seq;
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- EXPECT_CALL(*app_mngr, GetUserConsentForDevice("12345"))
+ GetInfoFromApp();
+ EXPECT_CALL(app_mngr_, GetUserConsentForDevice("12345"))
.WillOnce(Return(policy::kDeviceDisallowed));
- EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_))
- .WillOnce(Return(default_testType));
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(true));
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
- EXPECT_CALL(*app_mngr,
- SetState(test_app_id, default_testType, test_audio_state));
-
- bool res = res_ctrl.SetAppHMIState(app_mock, testType, true);
+ EXPECT_CALL(*app_mock, set_is_resuming(true));
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_))
+ .WillOnce(Return(kDefaultTestLevel_));
+ EXPECT_CALL(state_controller_, SetRegularState(_, kDefaultTestLevel_))
+ .Times(AtLeast(1));
+ bool res = res_ctrl->SetAppHMIState(app_mock, test_type, true);
EXPECT_FALSE(res);
}
TEST_F(ResumeCtrlTest, SaveApplication) {
utils::SharedPtr<application_manager::Application> app_sh_mock =
- new ApplicationMock();
+ ::utils::MakeShared<application_manager_test::MockApplication>();
EXPECT_CALL(*mock_storage, SaveApplication(app_sh_mock));
- res_ctrl.SaveApplication(app_sh_mock);
+ res_ctrl->SaveApplication(app_sh_mock);
}
TEST_F(ResumeCtrlTest, OnAppActivated_ResumptionHasStarted) {
- ::profile::Profile::instance()->config_file_name("smartDeviceLink_test.ini");
-
smart_objects::SmartObject saved_app;
- EXPECT_CALL(*app_mngr, GetDefaultHmiLevel(_))
- .WillOnce(Return(default_testType));
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- ON_CALL(*app_mock, is_media_application()).WillByDefault(Return(false));
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
- EXPECT_CALL(*app_mngr,
- SetState(test_app_id, default_testType, test_audio_state));
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id));
- EXPECT_CALL(*mock_storage, GetSavedApplication(test_policy_app_id, _, _))
+ GetInfoFromApp();
+
+ EXPECT_CALL(app_mngr_, GetDefaultHmiLevel(_))
+ .WillOnce(Return(kDefaultTestLevel_));
+ EXPECT_CALL(*mock_storage, GetSavedApplication(kTestPolicyAppId_, _, _))
.WillOnce(DoAll(SetArgReferee<2>(saved_app), Return(true)));
- ON_CALL(*app_mock, app_id()).WillByDefault(Return(test_app_id));
+ ON_CALL(*app_mock, app_id()).WillByDefault(Return(kTestAppId_));
- bool res = res_ctrl.StartResumptionOnlyHMILevel(app_mock);
+ bool res = res_ctrl->StartResumptionOnlyHMILevel(app_mock);
EXPECT_TRUE(res);
- utils::SharedPtr<ApplicationMock> app_sh_mock = new ApplicationMock();
+ utils::SharedPtr<application_manager_test::MockApplication> app_sh_mock =
+ ::utils::MakeShared<application_manager_test::MockApplication>();
- EXPECT_CALL(*app_sh_mock, app_id()).WillOnce(Return(test_app_id));
- res_ctrl.OnAppActivated(app_sh_mock);
+ EXPECT_CALL(*app_sh_mock, app_id()).WillOnce(Return(kTestAppId_));
+ res_ctrl->OnAppActivated(app_sh_mock);
}
TEST_F(ResumeCtrlTest, OnAppActivated_ResumptionNotActive) {
- utils::SharedPtr<ApplicationMock> app_sh_mock = new ApplicationMock();
+ utils::SharedPtr<application_manager_test::MockApplication> app_sh_mock =
+ ::utils::MakeShared<application_manager_test::MockApplication>();
EXPECT_CALL(*app_sh_mock, app_id()).Times(0);
- res_ctrl.OnAppActivated(app_sh_mock);
+ res_ctrl->OnAppActivated(app_sh_mock);
}
TEST_F(ResumeCtrlTest, IsHMIApplicationIdExist) {
@@ -823,17 +681,17 @@ TEST_F(ResumeCtrlTest, IsHMIApplicationIdExist) {
EXPECT_CALL(*mock_storage, IsHMIApplicationIdExist(hmi_app_id))
.WillOnce(Return(true));
- EXPECT_TRUE(res_ctrl.IsHMIApplicationIdExist(hmi_app_id));
+ EXPECT_TRUE(res_ctrl->IsHMIApplicationIdExist(hmi_app_id));
}
TEST_F(ResumeCtrlTest, GetHMIApplicationID) {
uint32_t hmi_app_id = 10;
std::string device_id = "test_device_id";
- EXPECT_CALL(*mock_storage, GetHMIApplicationID(test_policy_app_id, device_id))
+ EXPECT_CALL(*mock_storage, GetHMIApplicationID(kTestPolicyAppId_, device_id))
.WillOnce(Return(hmi_app_id));
EXPECT_EQ(hmi_app_id,
- res_ctrl.GetHMIApplicationID(test_policy_app_id, device_id));
+ res_ctrl->GetHMIApplicationID(kTestPolicyAppId_, device_id));
}
TEST_F(ResumeCtrlTest, IsApplicationSaved) {
@@ -842,7 +700,7 @@ TEST_F(ResumeCtrlTest, IsApplicationSaved) {
EXPECT_CALL(*mock_storage, IsApplicationSaved(policy_app_id, device_id))
.WillOnce(Return(true));
- EXPECT_TRUE(res_ctrl.IsApplicationSaved(policy_app_id, device_id));
+ EXPECT_TRUE(res_ctrl->IsApplicationSaved(policy_app_id, device_id));
}
TEST_F(ResumeCtrlTest, CheckPersistenceFiles_WithoutCommandAndChoiceSets) {
@@ -851,13 +709,11 @@ TEST_F(ResumeCtrlTest, CheckPersistenceFiles_WithoutCommandAndChoiceSets) {
saved_app[application_manager::strings::ign_off_count] = ign_off_count;
saved_app[application_manager::strings::hmi_level] = HMI_FULL;
- ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id));
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
-
+ GetInfoFromApp();
EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _))
.WillOnce(DoAll(SetArgReferee<2>(saved_app), Return(true)));
- EXPECT_TRUE(res_ctrl.CheckPersistenceFilesForResumption(app_mock));
+ EXPECT_TRUE(res_ctrl->CheckPersistenceFilesForResumption(app_mock));
}
TEST_F(ResumeCtrlTest, CheckPersistenceFilesForResumption_WithCommands) {
@@ -869,17 +725,15 @@ TEST_F(ResumeCtrlTest, CheckPersistenceFilesForResumption_WithCommands) {
saved_app[application_manager::strings::application_commands] =
test_application_commands;
- ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id));
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
-
+ GetInfoFromApp();
EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _))
.WillOnce(DoAll(SetArgReferee<2>(saved_app), Return(true)));
EXPECT_CALL(*application_manager::MockMessageHelper::message_helper_mock(),
- VerifyImageFiles(_, _))
+ VerifyImageFiles(_, _, _))
.WillRepeatedly(Return(mobile_apis::Result::SUCCESS));
- EXPECT_TRUE(res_ctrl.CheckPersistenceFilesForResumption(app_mock));
+ EXPECT_TRUE(res_ctrl->CheckPersistenceFilesForResumption(app_mock));
}
TEST_F(ResumeCtrlTest, CheckPersistenceFilesForResumption_WithChoiceSet) {
@@ -891,45 +745,43 @@ TEST_F(ResumeCtrlTest, CheckPersistenceFilesForResumption_WithChoiceSet) {
saved_app[application_manager::strings::application_choice_sets] =
test_choice_sets;
- ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id));
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
-
+ GetInfoFromApp();
EXPECT_CALL(*mock_storage, GetSavedApplication(_, _, _))
.WillOnce(DoAll(SetArgReferee<2>(saved_app), Return(true)));
- EXPECT_TRUE(res_ctrl.CheckPersistenceFilesForResumption(app_mock));
+ EXPECT_TRUE(res_ctrl->CheckPersistenceFilesForResumption(app_mock));
}
// TODO (VVeremjova) APPLINK-16718
TEST_F(ResumeCtrlTest, DISABLED_OnSuspend) {
EXPECT_CALL(*mock_storage, OnSuspend());
- res_ctrl.OnSuspend();
+ res_ctrl->OnSuspend();
}
TEST_F(ResumeCtrlTest, OnAwake) {
+ uint32_t timeout = 10u;
+ EXPECT_CALL(mock_application_manager_settings_,
+ app_resumption_save_persistent_data_timeout())
+ .WillOnce(ReturnRef(timeout));
EXPECT_CALL(*mock_storage, OnAwake());
- res_ctrl.OnAwake();
+ res_ctrl->OnAwake();
}
TEST_F(ResumeCtrlTest, RemoveApplicationFromSaved) {
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id));
+ GetInfoFromApp();
EXPECT_CALL(*mock_storage, RemoveApplicationFromSaved(_, _))
.WillOnce(Return(true));
- EXPECT_TRUE(res_ctrl.RemoveApplicationFromSaved(app_mock));
+ EXPECT_TRUE(res_ctrl->RemoveApplicationFromSaved(app_mock));
}
-TEST_F(ResumeCtrlTest, CheckApplicationHash) {
+TEST_F(ResumeCtrlTest, CheckApplicationkHash_) {
smart_objects::SmartObject saved_app;
+ saved_app[application_manager::strings::hash_id] = kHash_;
- std::string test_hash = "saved_hash";
- saved_app[application_manager::strings::hash_id] = test_hash;
-
- ON_CALL(*app_mock, device()).WillByDefault(Return(test_dev_id));
- ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(test_policy_app_id));
- EXPECT_CALL(*mock_storage, GetSavedApplication(test_policy_app_id, _, _))
+ GetInfoFromApp();
+ EXPECT_CALL(*mock_storage, GetSavedApplication(kTestPolicyAppId_, _, _))
.WillRepeatedly(DoAll(SetArgReferee<2>(saved_app), Return(true)));
- EXPECT_TRUE(res_ctrl.CheckApplicationHash(app_mock, test_hash));
+ EXPECT_TRUE(res_ctrl->CheckApplicationHash(app_mock, kHash_));
}
} // namespace resumption_test
diff --git a/src/components/application_manager/test/resumption/resumption_data_db_test.cc b/src/components/application_manager/test/resumption/resumption_data_db_test.cc
index a6ced14349..2fc1e5e5ec 100644
--- a/src/components/application_manager/test/resumption/resumption_data_db_test.cc
+++ b/src/components/application_manager/test/resumption/resumption_data_db_test.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -33,15 +33,15 @@
#include <string>
#include <algorithm>
#include "gtest/gtest.h"
-#include "include/application_mock.h"
+#include "application_manager/mock_application.h"
+#include "application_manager/mock_application_manager_settings.h"
#include "interfaces/MOBILE_API.h"
#include "sql_database.h"
#include "sql_query.h"
-
-#include "application_manager/application_manager_impl.h"
-#include "config_profile/profile.h"
+#include "utils/make_shared.h"
#include "utils/file_system.h"
-#include "include/resumption_data_test.h"
+#include "application_manager/resumption_data_test.h"
+#include "application_manager/test_resumption_data_db.h"
#include "application_manager/resumption/resumption_sql_queries.h"
#include "application_manager/resumption/resumption_data_db.h"
@@ -51,6 +51,8 @@ namespace components {
namespace resumption_test {
using ::testing::NiceMock;
+using ::testing::ReturnRef;
+using application_manager_test::MockApplication;
namespace am = application_manager;
using namespace file_system;
@@ -58,17 +60,14 @@ using namespace file_system;
using namespace resumption;
using namespace mobile_apis;
-class TestResumptionDataDB : public ResumptionDataDB {
- public:
- utils::dbms::SQLDatabase* get_db_handle() { return db(); }
-
- TestResumptionDataDB(DbStorage db_storage) : ResumptionDataDB(db_storage) {}
-};
-
+namespace {
+const std::string kPath =
+ file_system::CurrentWorkingDirectory() + "/" + "test_storage";
+}
class ResumptionDataDBTest : public ResumptionDataTest {
protected:
- virtual void SetUp() {
- app_mock = new NiceMock<ApplicationMock>();
+ void SetUp() OVERRIDE {
+ app_mock = utils::MakeShared<NiceMock<MockApplication> >();
policy_app_id_ = "test_policy_app_id";
app_id_ = 10;
is_audio_ = true;
@@ -78,7 +77,7 @@ class ResumptionDataDBTest : public ResumptionDataTest {
ign_off_count_ = 0;
grammar_id_ = 16;
}
- virtual void TearDown() {
+ void TearDown() OVERRIDE {
utils::dbms::SQLQuery query(test_db());
EXPECT_TRUE(query.Prepare(remove_all_tables));
EXPECT_TRUE(query.Exec());
@@ -87,12 +86,11 @@ class ResumptionDataDBTest : public ResumptionDataTest {
static void SetUpTestCase() {
kDatabaseName = "resumption";
if (is_in_file) {
- ::profile::Profile::instance()->config_file_name(
- "smartDeviceLink_test.ini");
- path_ = profile::Profile::instance()->app_storage_folder();
- CreateDirectory("./" + path_);
+ path_ = "test_storage";
+ CreateDirectory(file_system::CurrentWorkingDirectory() + "/" + path_);
+ CreateDirectory(kPath);
test_db_ = new utils::dbms::SQLDatabase(kDatabaseName);
- test_db_->set_path(path_ + "/");
+ test_db_->set_path(kPath + "/");
res_db_ = new TestResumptionDataDB(In_File_Storage);
} else {
res_db_ = new TestResumptionDataDB(In_Memory_Storage);
@@ -110,14 +108,17 @@ class ResumptionDataDBTest : public ResumptionDataTest {
static void TearDownTestCase() {
test_db_->Close();
if (is_in_file) {
- ::profile::Profile::instance()->config_file_name("smartDeviceLink.ini");
RemoveDirectory("./" + path_, true);
}
delete res_db_;
}
- utils::dbms::SQLDatabase* test_db() { return test_db_; }
- std::string path() { return path_; }
+ utils::dbms::SQLDatabase* test_db() {
+ return test_db_;
+ }
+ std::string path() {
+ return path_;
+ }
void SetZeroIgnOffTime() {
utils::dbms::SQLQuery query(test_db());
@@ -128,11 +129,12 @@ class ResumptionDataDBTest : public ResumptionDataTest {
static TestResumptionDataDB* res_db_;
- TestResumptionDataDB* res_db() { return res_db_; }
+ TestResumptionDataDB* res_db() {
+ return res_db_;
+ }
// Check that db includes tables with given elements
void CheckSavedDB();
-
static const bool is_in_file = false;
const std::string tables_exist =
"SELECT COUNT(*) FROM sqlite_master WHERE `type` = 'table';";
@@ -142,6 +144,7 @@ class ResumptionDataDBTest : public ResumptionDataTest {
const std::string remove_all_tables =
"DELETE FROM `resumption`; "
+ "DELETE FROM `subscribedForWayPoints`; "
"DELETE FROM `image`; "
"DELETE FROM `applicationChoiceSet`; "
"DELETE FROM `file`; "
@@ -205,7 +208,7 @@ void ResumptionDataDBTest::CheckSavedDB() {
void ResumptionDataDBTest::CheckExistenceApplication() {
utils::dbms::SQLQuery query(test_db());
EXPECT_TRUE(query.Prepare(kCheckApplication));
- query.Bind(0, device_id_);
+ query.Bind(0, kMacAddress_);
query.Bind(1, policy_app_id_);
EXPECT_TRUE(query.Exec());
EXPECT_EQ(1, query.GetInteger(0));
@@ -225,7 +228,7 @@ void ResumptionDataDBTest::CheckAppData() {
EXPECT_EQ(ign_off_count_, query.GetUInteger(6));
- EXPECT_EQ(device_id_, query.GetString(8));
+ EXPECT_EQ(kMacAddress_, query.GetString(8));
EXPECT_EQ(is_audio_, query.GetBoolean(9));
}
@@ -348,7 +351,7 @@ void ResumptionDataDBTest::CheckSubmenuData() {
EXPECT_TRUE(select_submenu.Prepare(kSelectCountSubMenu));
BindId(select_submenu);
EXPECT_TRUE(select_submenu.Exec());
- EXPECT_EQ(count_of_submenues, select_submenu.GetUInteger(0));
+ EXPECT_EQ(kCountOfSubmenues_, select_submenu.GetUInteger(0));
EXPECT_TRUE(select_submenu.Prepare(kSelectSubMenu));
BindId(select_submenu);
@@ -371,7 +374,7 @@ void ResumptionDataDBTest::CheckCommandsData() {
EXPECT_TRUE(select_commands.Prepare(kSelectCountCommands));
BindId(select_commands);
EXPECT_TRUE(select_commands.Exec());
- EXPECT_EQ(count_of_commands, select_commands.GetUInteger(0));
+ EXPECT_EQ(kCountOfCommands_, select_commands.GetUInteger(0));
EXPECT_TRUE(select_commands.Prepare(kSelectCommands));
BindId(select_commands);
@@ -419,7 +422,7 @@ void ResumptionDataDBTest::CheckChoiceSetData() {
EXPECT_TRUE(select_choice_set.Prepare(kSelectCountChoiceSet));
BindId(select_choice_set);
EXPECT_TRUE(select_choice_set.Exec());
- EXPECT_EQ(count_of_choice_sets, select_choice_set.GetUInteger(0));
+ EXPECT_EQ(kCountOfChoiceSets_, select_choice_set.GetUInteger(0));
EXPECT_TRUE(select_choice_set.Prepare(kSelectChoiceSets));
int64_t app_set_key = 0;
@@ -507,7 +510,7 @@ void ResumptionDataDBTest::CheckAppFilesData() {
EXPECT_TRUE(query.Prepare(kSelectCountFiles));
BindId(query);
EXPECT_TRUE(query.Exec());
- EXPECT_EQ(count_of_files, query.GetUInteger(0));
+ EXPECT_EQ(kCountOfFiles_, query.GetUInteger(0));
EXPECT_TRUE(query.Prepare(kSelectFiles));
BindId(query);
@@ -528,7 +531,7 @@ void ResumptionDataDBTest::CheckAppFilesData() {
void ResumptionDataDBTest::BindId(utils::dbms::SQLQuery& query) {
query.Bind(0, policy_app_id_);
- query.Bind(1, device_id_);
+ query.Bind(1, kMacAddress_);
}
TEST_F(ResumptionDataDBTest, Init) {
@@ -565,11 +568,12 @@ TEST_F(ResumptionDataDBTest, RemoveApplicationFromSaved) {
EXPECT_TRUE(res_db()->Init());
res_db()->SaveApplication(app_mock);
CheckSavedDB();
- EXPECT_TRUE(res_db()->RemoveApplicationFromSaved(policy_app_id_, device_id_));
+ EXPECT_TRUE(
+ res_db()->RemoveApplicationFromSaved(policy_app_id_, kMacAddress_));
sm::SmartObject remove_app;
EXPECT_FALSE(
- res_db()->GetSavedApplication(policy_app_id_, device_id_, remove_app));
+ res_db()->GetSavedApplication(policy_app_id_, kMacAddress_, remove_app));
EXPECT_TRUE(remove_app.empty());
}
@@ -608,7 +612,7 @@ TEST_F(ResumptionDataDBTest, IsApplicationSaved_ApplicationSaved) {
PrepareData();
EXPECT_TRUE(res_db()->Init());
res_db()->SaveApplication(app_mock);
- ssize_t result = res_db()->IsApplicationSaved(policy_app_id_, device_id_);
+ ssize_t result = res_db()->IsApplicationSaved(policy_app_id_, kMacAddress_);
EXPECT_EQ(0, result);
}
@@ -616,8 +620,9 @@ TEST_F(ResumptionDataDBTest, IsApplicationSaved_ApplicationRemoved) {
PrepareData();
EXPECT_TRUE(res_db()->Init());
res_db()->SaveApplication(app_mock);
- EXPECT_TRUE(res_db()->RemoveApplicationFromSaved(policy_app_id_, device_id_));
- ssize_t result = res_db()->IsApplicationSaved(policy_app_id_, device_id_);
+ EXPECT_TRUE(
+ res_db()->RemoveApplicationFromSaved(policy_app_id_, kMacAddress_));
+ ssize_t result = res_db()->IsApplicationSaved(policy_app_id_, kMacAddress_);
EXPECT_EQ(-1, result);
}
@@ -629,7 +634,7 @@ TEST_F(ResumptionDataDBTest, GetSavedApplication) {
sm::SmartObject saved_app;
EXPECT_TRUE(
- res_db()->GetSavedApplication(policy_app_id_, device_id_, saved_app));
+ res_db()->GetSavedApplication(policy_app_id_, kMacAddress_, saved_app));
CheckSavedApp(saved_app);
}
@@ -651,9 +656,10 @@ TEST_F(ResumptionDataDBTest, GetDataForLoadResumeData) {
res_db()->GetDataForLoadResumeData(saved_app);
EXPECT_EQ(policy_app_id_, saved_app[0][am::strings::app_id].asString());
- EXPECT_EQ(device_id_, saved_app[0][am::strings::device_id].asString());
- EXPECT_EQ(hmi_level_, static_cast<HMILevel::eType>(
- saved_app[0][am::strings::hmi_level].asInt()));
+ EXPECT_EQ(kMacAddress_, saved_app[0][am::strings::device_id].asString());
+ EXPECT_EQ(hmi_level_,
+ static_cast<HMILevel::eType>(
+ saved_app[0][am::strings::hmi_level].asInt()));
EXPECT_EQ(ign_off_count_, saved_app[0][am::strings::ign_off_count].asUInt());
}
@@ -664,7 +670,8 @@ TEST_F(ResumptionDataDBTest, GetDataForLoadResumeData_AppRemove) {
EXPECT_TRUE(res_db()->Init());
res_db()->SaveApplication(app_mock);
CheckSavedDB();
- EXPECT_TRUE(res_db()->RemoveApplicationFromSaved(policy_app_id_, device_id_));
+ EXPECT_TRUE(
+ res_db()->RemoveApplicationFromSaved(policy_app_id_, kMacAddress_));
res_db()->GetDataForLoadResumeData(saved_app);
EXPECT_TRUE(saved_app.empty());
}
@@ -675,7 +682,7 @@ TEST_F(ResumptionDataDBTest, UpdateHmiLevel) {
res_db()->SaveApplication(app_mock);
CheckSavedDB();
HMILevel::eType new_hmi_level = HMILevel::HMI_LIMITED;
- res_db()->UpdateHmiLevel(policy_app_id_, device_id_, new_hmi_level);
+ res_db()->UpdateHmiLevel(policy_app_id_, kMacAddress_, new_hmi_level);
hmi_level_ = new_hmi_level;
CheckSavedDB();
}
@@ -703,7 +710,7 @@ TEST_F(ResumptionDataDBTest, GetHMIApplicationID) {
res_db()->SaveApplication(app_mock);
CheckSavedDB();
EXPECT_EQ(hmi_app_id_,
- res_db()->GetHMIApplicationID(policy_app_id_, device_id_));
+ res_db()->GetHMIApplicationID(policy_app_id_, kMacAddress_));
}
TEST_F(ResumptionDataDBTest, GetHMIApplicationID_AppNotSaved) {
@@ -746,7 +753,7 @@ TEST_F(ResumptionDataDBTest, OnSuspendFourTimes) {
res_db()->OnSuspend();
- ssize_t result = res_db()->IsApplicationSaved(policy_app_id_, device_id_);
+ ssize_t result = res_db()->IsApplicationSaved(policy_app_id_, kMacAddress_);
EXPECT_EQ(-1, result);
}
@@ -804,7 +811,7 @@ TEST_F(ResumptionDataDBTest, GetHashId) {
res_db()->SaveApplication(app_mock);
std::string test_hash;
- EXPECT_TRUE(res_db()->GetHashId(policy_app_id_, device_id_, test_hash));
+ EXPECT_TRUE(res_db()->GetHashId(policy_app_id_, kMacAddress_, test_hash));
EXPECT_EQ(hash_, test_hash);
}
@@ -832,6 +839,39 @@ TEST_F(ResumptionDataDBTest, GetIgnOffTime_AfterSuspendAndAwake) {
EXPECT_LE(after_suspend, after_awake);
}
+TEST_F(ResumptionDataDBTest, DropAppResumptionData) {
+ PrepareData();
+ EXPECT_TRUE(res_db()->Init());
+ SetZeroIgnOffTime();
+
+ res_db()->SaveApplication(app_mock);
+
+ EXPECT_TRUE(res_db()->DropAppDataResumption(kMacAddress_, policy_app_id_));
+
+ am::smart_objects::SmartObject app;
+ EXPECT_TRUE(res_db()->GetSavedApplication(policy_app_id_, kMacAddress_, app));
+
+ EXPECT_TRUE(app.keyExists(am::strings::application_commands) &&
+ app[am::strings::application_commands].empty());
+
+ EXPECT_TRUE(app.keyExists(am::strings::application_submenus) &&
+ app[am::strings::application_submenus].empty());
+
+ EXPECT_TRUE(app.keyExists(am::strings::application_choice_sets) &&
+ app[am::strings::application_choice_sets].empty());
+
+ EXPECT_TRUE(app.keyExists(am::strings::application_global_properties) &&
+ app[am::strings::application_global_properties].empty());
+
+ EXPECT_TRUE(app.keyExists(am::strings::application_subscribtions) &&
+ app[am::strings::application_subscribtions].empty());
+
+ EXPECT_TRUE(app.keyExists(am::strings::application_files) &&
+ app[am::strings::application_files].empty());
+
+ EXPECT_FALSE(app.keyExists(am::strings::grammar_id));
+}
+
} // namespace resumption_test
} // namespace components
} // namespace test
diff --git a/src/components/application_manager/test/resumption/resumption_data_json_test.cc b/src/components/application_manager/test/resumption/resumption_data_json_test.cc
index 24a16596eb..0f51d29e0e 100644
--- a/src/components/application_manager/test/resumption/resumption_data_json_test.cc
+++ b/src/components/application_manager/test/resumption/resumption_data_json_test.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -35,14 +35,14 @@
#include "gtest/gtest.h"
#include "application_manager/usage_statistics.h"
-#include "include/application_mock.h"
-#include "include/resumption_data_mock.h"
+#include "application_manager/mock_application.h"
+#include "application_manager/mock_resumption_data.h"
#include "interfaces/MOBILE_API.h"
#include "resumption/last_state.h"
-#include "include/resumption_data_test.h"
-#include "formatters/CFormatterJsonBase.hpp"
-#include "config_profile/profile.h"
+#include "application_manager/resumption_data_test.h"
+#include "formatters/CFormatterJsonBase.h"
+
#include "utils/file_system.h"
#include "application_manager/resumption/resumption_data_json.h"
@@ -64,8 +64,11 @@ namespace Formatters = NsSmartDeviceLink::NsJSONHandler::Formatters;
class ResumptionDataJsonTest : public ResumptionDataTest {
protected:
+ ResumptionDataJsonTest()
+ : last_state_("app_storage_folder", "app_info_storage")
+ , res_json(last_state_, mock_application_manager_) {}
virtual void SetUp() {
- app_mock = new NiceMock<ApplicationMock>();
+ app_mock = new NiceMock<application_manager_test::MockApplication>();
policy_app_id_ = "test_policy_app_id";
app_id_ = 10;
@@ -78,7 +81,7 @@ class ResumptionDataJsonTest : public ResumptionDataTest {
}
void CheckSavedJson() {
- Value& dictionary = LastState::instance()->dictionary;
+ Value& dictionary = last_state_.dictionary;
ASSERT_TRUE(dictionary[am::strings::resumption].isObject());
ASSERT_TRUE(
dictionary[am::strings::resumption][am::strings::resume_app_list]
@@ -94,22 +97,23 @@ class ResumptionDataJsonTest : public ResumptionDataTest {
}
void SetZeroIgnOff() {
- Value& dictionary = LastState::instance()->dictionary;
+ Value& dictionary = last_state_.dictionary;
Value& res = dictionary[am::strings::resumption];
res[am::strings::last_ign_off_time] = 0;
- LastState::instance()->SaveToFileSystem();
+ last_state_.SaveToFileSystem();
}
+
+ resumption::LastState last_state_;
+ ResumptionDataJson res_json;
};
TEST_F(ResumptionDataJsonTest, SaveApplication) {
- ResumptionDataJson res_json;
PrepareData();
res_json.SaveApplication(app_mock);
CheckSavedJson();
}
TEST_F(ResumptionDataJsonTest, SavedApplicationTwice) {
- ResumptionDataJson res_json;
PrepareData();
res_json.SaveApplication(app_mock);
CheckSavedJson();
@@ -118,7 +122,6 @@ TEST_F(ResumptionDataJsonTest, SavedApplicationTwice) {
}
TEST_F(ResumptionDataJsonTest, SavedApplicationTwice_UpdateApp) {
- ResumptionDataJson res_json;
PrepareData();
res_json.SaveApplication(app_mock);
CheckSavedJson();
@@ -129,54 +132,50 @@ TEST_F(ResumptionDataJsonTest, SavedApplicationTwice_UpdateApp) {
}
TEST_F(ResumptionDataJsonTest, RemoveApplicationFromSaved) {
- ResumptionDataJson res_json;
PrepareData();
res_json.SaveApplication(app_mock);
- EXPECT_TRUE(res_json.RemoveApplicationFromSaved(policy_app_id_, device_id_));
+ EXPECT_TRUE(
+ res_json.RemoveApplicationFromSaved(policy_app_id_, kMacAddress_));
// Check that application was deleted
smart_objects::SmartObject remove_app;
EXPECT_FALSE(
- res_json.GetSavedApplication(policy_app_id_, device_id_, remove_app));
+ res_json.GetSavedApplication(policy_app_id_, kMacAddress_, remove_app));
EXPECT_TRUE(remove_app.empty());
}
TEST_F(ResumptionDataJsonTest, RemoveApplicationFromSaved_AppNotSaved) {
- ResumptionDataJson res_json;
EXPECT_FALSE(res_json.RemoveApplicationFromSaved(policy_app_id_, "54321"));
}
TEST_F(ResumptionDataJsonTest, IsApplicationSaved_ApplicationSaved) {
- ResumptionDataJson res_json;
PrepareData();
res_json.SaveApplication(app_mock);
CheckSavedJson();
- ssize_t result = res_json.IsApplicationSaved(policy_app_id_, device_id_);
+ ssize_t result = res_json.IsApplicationSaved(policy_app_id_, kMacAddress_);
EXPECT_EQ(0, result);
}
TEST_F(ResumptionDataJsonTest, IsApplicationSaved_ApplicationRemoved) {
- ResumptionDataJson res_json;
PrepareData();
res_json.SaveApplication(app_mock);
CheckSavedJson();
- EXPECT_TRUE(res_json.RemoveApplicationFromSaved(policy_app_id_, device_id_));
- ssize_t result = res_json.IsApplicationSaved(policy_app_id_, device_id_);
+ EXPECT_TRUE(
+ res_json.RemoveApplicationFromSaved(policy_app_id_, kMacAddress_));
+ ssize_t result = res_json.IsApplicationSaved(policy_app_id_, kMacAddress_);
EXPECT_EQ(-1, result);
}
TEST_F(ResumptionDataJsonTest, GetSavedApplication) {
- ResumptionDataJson res_json;
PrepareData();
res_json.SaveApplication(app_mock);
smart_objects::SmartObject saved_app;
EXPECT_TRUE(
- res_json.GetSavedApplication(policy_app_id_, device_id_, saved_app));
+ res_json.GetSavedApplication(policy_app_id_, kMacAddress_, saved_app));
CheckSavedApp(saved_app);
}
TEST_F(ResumptionDataJsonTest, GetSavedApplication_AppNotSaved) {
- ResumptionDataJson res_json;
smart_objects::SmartObject saved_app;
EXPECT_FALSE(
res_json.GetSavedApplication(policy_app_id_, "54321", saved_app));
@@ -184,7 +183,6 @@ TEST_F(ResumptionDataJsonTest, GetSavedApplication_AppNotSaved) {
}
TEST_F(ResumptionDataJsonTest, GetDataForLoadResumeData) {
- ResumptionDataJson res_json;
PrepareData();
res_json.SaveApplication(app_mock);
CheckSavedJson();
@@ -192,38 +190,37 @@ TEST_F(ResumptionDataJsonTest, GetDataForLoadResumeData) {
res_json.GetDataForLoadResumeData(saved_app);
EXPECT_EQ(policy_app_id_, saved_app[0][am::strings::app_id].asString());
- EXPECT_EQ(device_id_, saved_app[0][am::strings::device_id].asString());
- EXPECT_EQ(hmi_level_, static_cast<HMILevel::eType>(
- saved_app[0][am::strings::hmi_level].asInt()));
+ EXPECT_EQ(kMacAddress_, saved_app[0][am::strings::device_id].asString());
+ EXPECT_EQ(hmi_level_,
+ static_cast<HMILevel::eType>(
+ saved_app[0][am::strings::hmi_level].asInt()));
EXPECT_EQ(ign_off_count_, saved_app[0][am::strings::ign_off_count].asUInt());
}
TEST_F(ResumptionDataJsonTest, GetDataForLoadResumeData_AppRemove) {
- ResumptionDataJson res_json;
smart_objects::SmartObject saved_app;
PrepareData();
res_json.SaveApplication(app_mock);
CheckSavedJson();
- EXPECT_TRUE(res_json.RemoveApplicationFromSaved(policy_app_id_, device_id_));
+ EXPECT_TRUE(
+ res_json.RemoveApplicationFromSaved(policy_app_id_, kMacAddress_));
res_json.GetDataForLoadResumeData(saved_app);
EXPECT_TRUE(saved_app.empty());
}
TEST_F(ResumptionDataJsonTest, UpdateHmiLevel) {
- ResumptionDataJson res_json;
PrepareData();
res_json.SaveApplication(app_mock);
CheckSavedJson();
HMILevel::eType new_hmi_level = HMILevel::HMI_LIMITED;
- res_json.UpdateHmiLevel(policy_app_id_, device_id_, new_hmi_level);
+ res_json.UpdateHmiLevel(policy_app_id_, kMacAddress_, new_hmi_level);
hmi_level_ = new_hmi_level;
CheckSavedJson();
}
TEST_F(ResumptionDataJsonTest, IsHMIApplicationIdExist_AppIsSaved) {
- ResumptionDataJson res_json;
PrepareData();
res_json.SaveApplication(app_mock);
CheckSavedJson();
@@ -231,7 +228,6 @@ TEST_F(ResumptionDataJsonTest, IsHMIApplicationIdExist_AppIsSaved) {
}
TEST_F(ResumptionDataJsonTest, IsHMIApplicationIdExist_AppNotSaved) {
- ResumptionDataJson res_json;
PrepareData();
res_json.SaveApplication(app_mock);
@@ -241,24 +237,20 @@ TEST_F(ResumptionDataJsonTest, IsHMIApplicationIdExist_AppNotSaved) {
}
TEST_F(ResumptionDataJsonTest, GetHMIApplicationID) {
- ResumptionDataJson res_json;
PrepareData();
res_json.SaveApplication(app_mock);
CheckSavedJson();
EXPECT_EQ(hmi_app_id_,
- res_json.GetHMIApplicationID(policy_app_id_, device_id_));
+ res_json.GetHMIApplicationID(policy_app_id_, kMacAddress_));
}
TEST_F(ResumptionDataJsonTest, GetHMIApplicationID_AppNotSaved) {
- ResumptionDataJson res_json;
PrepareData();
res_json.SaveApplication(app_mock);
EXPECT_EQ(0u, res_json.GetHMIApplicationID(policy_app_id_, "other_dev_id"));
}
TEST_F(ResumptionDataJsonTest, OnSuspend) {
- ResumptionDataJson res_json;
- ::profile::Profile::instance()->config_file_name("smartDeviceLink_test.ini");
SetZeroIgnOff();
PrepareData();
@@ -268,18 +260,10 @@ TEST_F(ResumptionDataJsonTest, OnSuspend) {
res_json.OnSuspend();
ign_off_count_++;
CheckSavedJson();
-
- EXPECT_TRUE(FileExists("./test_app_info.dat"));
- EXPECT_TRUE(DirectoryExists("./test_storage"));
- EXPECT_TRUE(RemoveDirectory("./test_storage", true));
- EXPECT_TRUE(DeleteFile("./test_app_info.dat"));
- ::profile::Profile::instance()->config_file_name("smartDeviceLink.ini");
}
TEST_F(ResumptionDataJsonTest, OnSuspendFourTimes) {
- ResumptionDataJson res_json;
PrepareData();
- ::profile::Profile::instance()->config_file_name("smartDeviceLink_test.ini");
SetZeroIgnOff();
res_json.SaveApplication(app_mock);
CheckSavedJson();
@@ -292,20 +276,11 @@ TEST_F(ResumptionDataJsonTest, OnSuspendFourTimes) {
res_json.OnSuspend();
res_json.OnSuspend();
- ssize_t result = res_json.IsApplicationSaved(policy_app_id_, device_id_);
- EXPECT_EQ(-1, result);
-
- EXPECT_TRUE(FileExists("./test_app_info.dat"));
- EXPECT_TRUE(DirectoryExists("./test_storage"));
- EXPECT_TRUE(RemoveDirectory("./test_storage", true));
- EXPECT_TRUE(DeleteFile("./test_app_info.dat"));
- ::profile::Profile::instance()->config_file_name("smartDeviceLink.ini");
+ EXPECT_TRUE(-1 != res_json.IsApplicationSaved(policy_app_id_, kMacAddress_));
}
TEST_F(ResumptionDataJsonTest, OnSuspendOnAwake) {
- ResumptionDataJson res_json;
PrepareData();
- ::profile::Profile::instance()->config_file_name("smartDeviceLink_test.ini");
SetZeroIgnOff();
res_json.SaveApplication(app_mock);
CheckSavedJson();
@@ -317,13 +292,9 @@ TEST_F(ResumptionDataJsonTest, OnSuspendOnAwake) {
res_json.OnAwake();
ign_off_count_ = 0;
CheckSavedJson();
- EXPECT_TRUE(RemoveDirectory("./test_storage", true));
- EXPECT_TRUE(DeleteFile("./test_app_info.dat"));
- ::profile::Profile::instance()->config_file_name("smartDeviceLink.ini");
}
TEST_F(ResumptionDataJsonTest, Awake_AppNotSuspended) {
- ResumptionDataJson res_json;
SetZeroIgnOff();
PrepareData();
res_json.SaveApplication(app_mock);
@@ -335,7 +306,6 @@ TEST_F(ResumptionDataJsonTest, Awake_AppNotSuspended) {
}
TEST_F(ResumptionDataJsonTest, TwiceAwake_AppNotSuspended) {
- ResumptionDataJson res_json;
SetZeroIgnOff();
PrepareData();
res_json.SaveApplication(app_mock);
@@ -351,21 +321,18 @@ TEST_F(ResumptionDataJsonTest, TwiceAwake_AppNotSuspended) {
}
TEST_F(ResumptionDataJsonTest, GetHashId) {
- ResumptionDataJson res_json;
PrepareData();
res_json.SaveApplication(app_mock);
CheckSavedJson();
std::string test_hash;
- EXPECT_TRUE(res_json.GetHashId(policy_app_id_, device_id_, test_hash));
+ EXPECT_TRUE(res_json.GetHashId(policy_app_id_, kMacAddress_, test_hash));
EXPECT_EQ(hash_, test_hash);
}
TEST_F(ResumptionDataJsonTest, GetIgnOffTime_AfterSuspendAndAwake) {
- ResumptionDataJson res_json;
uint32_t last_ign_off_time;
PrepareData();
- ::profile::Profile::instance()->config_file_name("smartDeviceLink_test.ini");
SetZeroIgnOff();
res_json.SaveApplication(app_mock);
CheckSavedJson();
@@ -383,10 +350,38 @@ TEST_F(ResumptionDataJsonTest, GetIgnOffTime_AfterSuspendAndAwake) {
after_awake = res_json.GetIgnOffTime();
EXPECT_LE(after_suspend, after_awake);
+}
+
+TEST_F(ResumptionDataJsonTest, DropAppDataResumption) {
+ PrepareData();
+ SetZeroIgnOff();
+ res_json.SaveApplication(app_mock);
+ CheckSavedJson();
+
+ EXPECT_TRUE(res_json.DropAppDataResumption(kMacAddress_, policy_app_id_));
+
+ smart_objects::SmartObject app;
+ EXPECT_TRUE(res_json.GetSavedApplication(policy_app_id_, kMacAddress_, app));
+
+ EXPECT_TRUE(app.keyExists(am::strings::application_commands) &&
+ app[am::strings::application_commands].empty());
+
+ EXPECT_TRUE(app.keyExists(am::strings::application_submenus) &&
+ app[am::strings::application_submenus].empty());
+
+ EXPECT_TRUE(app.keyExists(am::strings::application_choice_sets) &&
+ app[am::strings::application_choice_sets].empty());
+
+ EXPECT_TRUE(app.keyExists(am::strings::application_global_properties) &&
+ app[am::strings::application_global_properties].empty());
+
+ EXPECT_TRUE(app.keyExists(am::strings::application_subscribtions) &&
+ app[am::strings::application_subscribtions].empty());
+
+ EXPECT_TRUE(app.keyExists(am::strings::application_files) &&
+ app[am::strings::application_files].empty());
- EXPECT_TRUE(RemoveDirectory("./test_storage", true));
- EXPECT_TRUE(DeleteFile("./test_app_info.dat"));
- ::profile::Profile::instance()->config_file_name("smartDeviceLink.ini");
+ EXPECT_FALSE(app.keyExists(am::strings::grammar_id));
}
} // namespace resumption_test
diff --git a/src/components/application_manager/test/resumption/resumption_data_test.cc b/src/components/application_manager/test/resumption/resumption_data_test.cc
index b8054b0d85..8070244bf2 100644
--- a/src/components/application_manager/test/resumption/resumption_data_test.cc
+++ b/src/components/application_manager/test/resumption/resumption_data_test.cc
@@ -35,26 +35,18 @@
#include "gtest/gtest.h"
#include "application_manager/usage_statistics.h"
-#include "include/application_mock.h"
-#include "include/resumption_data_mock.h"
-
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/resumption_data_mock.h"
+#include "utils/custom_string.h"
#include "application_manager/application.h"
#include "utils/data_accessor.h"
#include "application_manager/message_helper.h"
-#include "include/resumption_data_test.h"
-
-std::string application_manager::MessageHelper::GetDeviceMacAddressForHandle(
- const uint32_t device_handle) {
- std::string device_mac_address = "12345";
- return device_mac_address;
-}
+#include "application_manager/resumption_data_test.h"
namespace test {
namespace components {
namespace resumption_test {
-
+namespace custom_str = utils::custom_string;
using ::testing::Return;
using ::testing::ReturnRef;
using ::testing::ReturnPointee;
@@ -66,8 +58,9 @@ void ResumptionDataTest::CheckSavedApp(sm::SmartObject& resume_app_list) {
EXPECT_EQ(hmi_app_id_, resume_app_list[am::strings::hmi_app_id].asUInt());
EXPECT_EQ(ign_off_count_,
resume_app_list[am::strings::ign_off_count].asUInt());
- EXPECT_EQ(hmi_level_, static_cast<HMILevel::eType>(
- resume_app_list[am::strings::hmi_level].asInt()));
+ EXPECT_EQ(hmi_level_,
+ static_cast<HMILevel::eType>(
+ resume_app_list[am::strings::hmi_level].asInt()));
EXPECT_EQ(is_audio_,
resume_app_list[am::strings::is_media_application].asBool());
EXPECT_EQ("12345", resume_app_list[am::strings::device_id].asString());
@@ -83,7 +76,7 @@ void ResumptionDataTest::CheckSavedApp(sm::SmartObject& resume_app_list) {
}
void ResumptionDataTest::CheckCommands(sm::SmartObject& res_list) {
- for (uint32_t i = 0; i < count_of_commands; ++i) {
+ for (uint32_t i = 0; i < kCountOfCommands_; ++i) {
EXPECT_EQ(i, res_list[i][am::strings::cmd_id].asUInt());
std::string name =
(*test_commands_map[i])[am::strings::menu_params]
@@ -118,7 +111,7 @@ void ResumptionDataTest::CheckCommands(sm::SmartObject& res_list) {
icon_type,
res_list[i][am::strings::cmd_icon][am::strings::image_type].asInt());
- for (uint32_t j = 0; j < count_of_choice; ++j) {
+ for (uint32_t j = 0; j < kCountOfChoice_; ++j) {
std::string vr =
(*test_commands_map[i])[am::strings::vr_commands][j].asString();
EXPECT_EQ(vr, res_list[i][am::strings::vr_commands][j].asString());
@@ -127,7 +120,7 @@ void ResumptionDataTest::CheckCommands(sm::SmartObject& res_list) {
}
void ResumptionDataTest::CheckSubmenues(sm::SmartObject& res_list) {
- for (uint32_t i = 0; i < count_of_submenues; ++i) {
+ for (uint32_t i = 0; i < kCountOfSubmenues_; ++i) {
uint32_t test_id =
(*test_submenu_map[i + 10])[am::strings::menu_id].asUInt();
std::string name =
@@ -215,7 +208,7 @@ void ResumptionDataTest::CheckChoiceSet(sm::SmartObject& res_list) {
void ResumptionDataTest::CheckAppFiles(sm::SmartObject& res_list) {
am::AppFile check_file;
- for (uint i = 0; i < count_of_files; ++i) {
+ for (uint i = 0; i < kCountOfFiles_; ++i) {
char numb[12];
std::snprintf(numb, 12, "%d", i);
check_file = app_files_map_["test_file " + std::string(numb)];
@@ -261,13 +254,15 @@ void ResumptionDataTest::CheckKeyboardProperties(sm::SmartObject& res_list) {
res_list[am::strings::limited_character_list][i].asString());
}
- EXPECT_EQ(testlanguage, static_cast<Language::eType>(
- res_list[am::strings::language].asInt()));
+ EXPECT_EQ(
+ testlanguage,
+ static_cast<Language::eType>(res_list[am::strings::language].asInt()));
EXPECT_EQ(testlayout,
static_cast<KeyboardLayout::eType>(
res_list[am::hmi_request::keyboard_layout].asInt()));
- EXPECT_EQ(testmode, static_cast<KeypressMode::eType>(
- res_list[am::strings::key_press_mode].asInt()));
+ EXPECT_EQ(testmode,
+ static_cast<KeypressMode::eType>(
+ res_list[am::strings::key_press_mode].asInt()));
EXPECT_EQ(auto_complete_text,
res_list[am::strings::auto_complete_text].asString());
}
@@ -283,8 +278,9 @@ void ResumptionDataTest::CheckMenuIcon(sm::SmartObject& res_list) {
(*menu_icon_)[am::strings::image_type].asInt());
EXPECT_EQ(value, res_list[am::strings::value].asString());
- EXPECT_EQ(type, static_cast<ImageType::eType>(
- res_list[am::strings::image_type].asInt()));
+ EXPECT_EQ(
+ type,
+ static_cast<ImageType::eType>(res_list[am::strings::image_type].asInt()));
}
void ResumptionDataTest::CheckHelpPrompt(sm::SmartObject& res_list) {
@@ -302,15 +298,16 @@ void ResumptionDataTest::CheckTimeoutPrompt(
SpeechCapabilities::eType speech = static_cast<SpeechCapabilities::eType>(
(*timeout_prompt_)[i][am::strings::type].asInt());
EXPECT_EQ(text, res_list[i][am::strings::text].asString());
- EXPECT_EQ(speech, static_cast<SpeechCapabilities::eType>(
- res_list[i][am::strings::type].asInt()));
+ EXPECT_EQ(speech,
+ static_cast<SpeechCapabilities::eType>(
+ res_list[i][am::strings::type].asInt()));
}
}
void ResumptionDataTest::CheckVRHelp(sm::SmartObject& res_list) {
std::string text;
int position;
- for (uint i = 0; i < count_of_vrhelptitle; ++i) {
+ for (uint i = 0; i < kCountOfVrhelptitle_; ++i) {
text = (*vr_help_)[i][am::strings::text].asString();
EXPECT_EQ(text, res_list[i][am::strings::text].asString());
position = (*vr_help_)[i][am::strings::position].asInt();
@@ -342,6 +339,7 @@ void ResumptionDataTest::PrepareData() {
ON_CALL(*app_mock, is_application_data_changed()).WillByDefault(Return(true));
ON_CALL(*app_mock, policy_app_id()).WillByDefault(Return(policy_app_id_));
+ ON_CALL(*app_mock, mac_address()).WillByDefault(ReturnRef(kMacAddress_));
ON_CALL(*app_mock, curHash()).WillByDefault(ReturnRef(hash_));
ON_CALL(*app_mock, get_grammar_id()).WillByDefault(Return(grammar_id_));
ON_CALL(*app_mock, device()).WillByDefault(Return(device_handle_));
@@ -379,6 +377,7 @@ void ResumptionDataTest::SetGlobalProporties() {
}
void ResumptionDataTest::SetMenuTitleAndIcon() {
+ custom_str::CustomString icon_name("test icon");
sm::SmartObject sm_icon;
sm_icon[am::strings::value] = "test icon";
sm_icon[am::strings::image_type] = ImageType::STATIC;
@@ -415,7 +414,7 @@ void ResumptionDataTest::SetVRHelpTitle() {
vr_help_title = "vr help title";
sm::SmartObject vr_help;
- for (uint i = 0; i < count_of_vrhelptitle; ++i) {
+ for (uint i = 0; i < kCountOfVrhelptitle_; ++i) {
char numb[12];
std::snprintf(numb, 12, "%d", i);
vr_help[i][am::strings::text] = "vr help " + std::string(numb);
@@ -431,7 +430,7 @@ void ResumptionDataTest::SetCommands() {
sm::SmartObject vr_commandsvector;
sm::SmartObject sm_icon;
- for (uint32_t i = 0; i < count_of_commands; ++i) {
+ for (uint32_t i = 0; i < kCountOfCommands_; ++i) {
char numb[12];
std::snprintf(numb, 12, "%d", i);
sm_comm[am::strings::cmd_id] = i;
@@ -440,7 +439,7 @@ void ResumptionDataTest::SetCommands() {
sm_comm[am::strings::menu_params][am::strings::menu_name] =
"Command" + std::string(numb);
- for (uint32_t j = 0; j < count_of_choice; ++j) {
+ for (uint32_t j = 0; j < kCountOfChoice_; ++j) {
char vr[12];
std::snprintf(vr, 12, "%d", i + j);
vr_commandsvector[j] = "VrCommand " + std::string(vr);
@@ -458,7 +457,7 @@ void ResumptionDataTest::SetCommands() {
void ResumptionDataTest::SetSubmenues() {
sm::SmartObject sm_comm;
- for (uint32_t i = 10; i < count_of_submenues + 10; ++i) {
+ for (uint32_t i = 10; i < kCountOfSubmenues_ + 10; ++i) {
char numb[12];
std::snprintf(numb, 12, "%d", i);
sm_comm[am::strings::menu_id] = i;
@@ -476,8 +475,8 @@ void ResumptionDataTest::SetChoiceSet() {
sm::SmartObject sec_icon;
sm::SmartObject app_choice_set;
sm::SmartObject application_choice_sets;
- for (uint32_t i = 0; i < count_of_choice_sets; ++i) {
- for (uint32_t j = 0; j < count_of_choice; ++j) {
+ for (uint32_t i = 0; i < kCountOfChoiceSets_; ++i) {
+ for (uint32_t j = 0; j < kCountOfChoice_; ++j) {
char numb[12];
std::snprintf(numb, 12, "%d", i + j);
@@ -513,7 +512,7 @@ void ResumptionDataTest::SetChoiceSet() {
void ResumptionDataTest::SetAppFiles() {
am::AppFile test_file;
int file_types;
- for (uint i = 0; i < count_of_files; ++i) {
+ for (uint i = 0; i < kCountOfFiles_; ++i) {
char numb[12];
std::snprintf(numb, 12, "%d", i);
file_types = i;
diff --git a/src/components/application_manager/test/resumption_sql_queries_test.cc b/src/components/application_manager/test/resumption_sql_queries_test.cc
new file mode 100644
index 0000000000..08fa0a3eb5
--- /dev/null
+++ b/src/components/application_manager/test/resumption_sql_queries_test.cc
@@ -0,0 +1,3090 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <algorithm>
+#include <vector>
+#include <string>
+#include <sstream>
+#include <utility>
+#include "gtest/gtest.h"
+
+#include "utils/sqlite_wrapper/sql_database.h"
+#include "utils/sqlite_wrapper/sql_query.h"
+#include "utils/file_system.h"
+#include "application_manager/resumption/resumption_sql_queries.h"
+#include "policy/sql_pt_queries.h"
+
+namespace test {
+namespace components {
+namespace resumption_test {
+
+using namespace ::resumption;
+
+using std::string;
+using std::pair;
+using utils::dbms::SQLDatabase;
+using utils::dbms::SQLQuery;
+
+enum AccessoryVRCommand { kVRCommandFromChoice = 0, kVRCommandFromCommand };
+
+const string kDeleteData =
+ "BEGIN; "
+ "DELETE FROM `resumption`; "
+ "DELETE FROM `image`; "
+ "DELETE FROM `applicationChoiceSet`; "
+ "DELETE FROM `file`; "
+ "DELETE FROM `subMenu`; "
+ "DELETE FROM `TTSChunk`; "
+ "DELETE FROM `vrHelpItem`; "
+ "DELETE FROM `tableLimitedCharacterList`; "
+ "DELETE FROM `characterArray`; "
+ "DELETE FROM `choice`; "
+ "DELETE FROM `command`; "
+ "DELETE FROM `globalProperties`; "
+ "DELETE FROM `choiceArray`; "
+ "DELETE FROM `vrCommandsArray`; "
+ "DELETE FROM `helpTimeoutPromptArray`; "
+ "DELETE FROM `vrHelpItemArray`; "
+ "DELETE FROM `application`; "
+ "DELETE FROM `applicationChoiceSetArray`; "
+ "DELETE FROM `applicationCommandsArray`; "
+ "DELETE FROM `applicationFilesArray`; "
+ "DELETE FROM `applicationSubMenuArray`; "
+ "DELETE FROM `applicationSubscribtionsArray`; "
+ "DELETE FROM `_internal_data`; "
+ "COMMIT; "
+ "VACUUM;";
+
+const std::string kJournalOff = "PRAGMA journal_mode = OFF;";
+
+class ResumptionSqlQueriesTest : public ::testing::Test {
+ public:
+ typedef pair<int, string> ValToPosPair;
+
+ protected:
+ std::vector<string> db_schema;
+ static const string kDatabaseName;
+ static SQLDatabase* db_;
+ static const string app_id1;
+ static const string app_id2;
+ static const string device_id;
+ static const string device_id2;
+ static const string test_hash;
+ static const string test_hash2;
+ static const string test_image;
+ static const int connection_key;
+ static const int grammarID;
+ static const int hmiAppID;
+ static const int hmiAppID2;
+ static const int hmiLevel;
+ static const int hmiLevel2;
+ static const int ign_off_count;
+ static const int ign_off_count2;
+ static const int timeStamp;
+ static const int timeStamp2;
+
+ static void SetUpTestCase() {
+ db_ = new SQLDatabase();
+ ASSERT_TRUE(db_->Open());
+ ASSERT_TRUE(db_->IsReadWrite());
+ SQLQuery query(db_);
+ ASSERT_TRUE(query.Exec(kCreateSchema));
+ SQLQuery query_logging_off(db_);
+ ASSERT_TRUE(query_logging_off.Exec(kJournalOff));
+ }
+
+ static void TearDownTestCase() {
+ db_->Close();
+ delete db_;
+ string file_to_delete = kDatabaseName + ".sqlite";
+ file_system::DeleteFile(file_to_delete);
+ }
+ void TearDown() OVERRIDE {
+ DeleteTablesData();
+ }
+
+ void CheckDeleteQuery(const string& count_query,
+ const string& query_to_check,
+ pair<int, string> app_info,
+ pair<int, string> dev_info,
+ const int value_before,
+ const int value_after,
+ const int position_in_result);
+
+ void CheckSelectQuery(const string& query_to_check,
+ const int control_value,
+ const int position_in_result);
+
+ void CheckSelectQuery(const string& query_to_check,
+ const char* control_value,
+ const int position_in_result);
+
+ void CheckSelectQuery(const string& query_to_check,
+ const bool control_value,
+ const int position_in_result);
+
+ void CheckSelectQuery(const string& query_to_check,
+ const string& control_value,
+ const int position_in_result);
+
+ void CheckSelectQuery(const string& query_to_check,
+ pair<int, string> app_info,
+ pair<int, string> dev_info,
+ const int control_value,
+ const int position_in_result);
+
+ void CheckSelectQuery(const string& query_to_check,
+ pair<int, string> app_info,
+ pair<int, string> dev_info,
+ const string& control_value,
+ const int position_in_result);
+
+ string IntToString(const int64_t key) const {
+ std::stringstream ss;
+ ss << key;
+ return ss.str();
+ }
+
+ SQLQuery& FillGlobalPropertiesTable(SQLQuery& query,
+ const string& vrHelpTitle,
+ const string& menuTitle,
+ const int language,
+ const int keyboardLayout,
+ const int keypressMode,
+ const string& autoCompleteText,
+ const int64_t image_key);
+
+ SQLQuery& FillApplicationTable(SQLQuery& query,
+ const int connection_key,
+ const int grammarID,
+ const string& hashID,
+ const int hmiAppID,
+ const int hmiLevel,
+ const int ign_off_count,
+ const int timeStamp,
+ bool isMediaApplication,
+ const string& appID,
+ const string& deviceID,
+ const int64_t glob_prop_key);
+
+ SQLQuery& FillImageTable(SQLQuery& query,
+ const int imageType,
+ const string& value);
+
+ SQLQuery& FillTableLimitedCharacterListTable(
+ SQLQuery& query, const string& limitedCharacterList);
+
+ SQLQuery& FillCharacterArrayTable(SQLQuery& query,
+ const int64_t glob_prop_key,
+ const int64_t lim_char_list_key);
+
+ SQLQuery& FillTTSChunkTable(SQLQuery& query,
+ const int type,
+ const string& text);
+
+ SQLQuery& FillHelpTimeoutPromptArrayTable(SQLQuery& query,
+ const int64_t glob_prop_key,
+ const int64_t tts_chunk_key,
+ const int idhelpPrompt);
+
+ SQLQuery& FillFileTable(SQLQuery& query,
+ const int fileType,
+ bool is_download_complete,
+ bool persistentFile,
+ const string& syncFileName);
+
+ SQLQuery& FillApplicationFilesArrayTable(SQLQuery& query,
+ const int64_t app_key,
+ const int64_t file_key);
+
+ SQLQuery& FillSubMenuTable(SQLQuery& query,
+ const int menuID,
+ const string& menuName,
+ const int position);
+
+ SQLQuery& FillApplicationSubMenuArrayTable(SQLQuery& query,
+ const int app_key,
+ const int sub_menu_key);
+
+ SQLQuery& FillAppSubscriptionsArrayTable(SQLQuery& query,
+ const int vehicleValue,
+ const int ButtonNameValue,
+ const int app_key);
+
+ SQLQuery& FillCommandTable(SQLQuery& query,
+ const int cmdID,
+ const string& menuName,
+ const int parentID,
+ const int position,
+ const int64_t image_key);
+
+ SQLQuery& FillApplicationCommandsArrayTable(SQLQuery& query,
+ const int64_t application_key,
+ const int64_t command_key);
+
+ SQLQuery& FillChoiceTable(SQLQuery& query,
+ const int choiceID,
+ const string& menuName,
+ const string& secondaryText,
+ const string& tertiaryText,
+ const int64_t image_key);
+
+ SQLQuery& FillChoiceArrayTable(SQLQuery& query,
+ const int64_t app_choice_set_key,
+ const int64_t choice_key);
+
+ SQLQuery& FillApplicationChoiceSetTable(SQLQuery& query,
+ const int grammarID,
+ const int interactionChoiceSetID);
+
+ SQLQuery& FillApplicationChoiceSetArrayTable(SQLQuery& query,
+ const int64_t app_choice_set_key,
+ const int64_t app_key);
+
+ SQLQuery& FillVRCommandsArrayTable(SQLQuery& query,
+ const string& vrCommand,
+ AccessoryVRCommand value,
+ const int64_t foreing_key);
+
+ SQLQuery& FillVRHelpItemTable(SQLQuery& query,
+ const string& text,
+ const int position,
+ const int64_t image_key);
+
+ SQLQuery& FillVRHelpItemArrayTable(SQLQuery& query,
+ const int64_t global_prop_key,
+ const int64_t vr_help_item_key);
+
+ void CreateSchema() {
+ SQLQuery query(db());
+ EXPECT_TRUE(query.Exec(kCreateSchema));
+ }
+
+ void DestroySchema() {
+ SQLQuery query(db());
+ EXPECT_TRUE(query.Exec(kDropSchema));
+ }
+
+ void DeleteTablesData() {
+ SQLQuery query(db());
+ EXPECT_TRUE(query.Exec(kDeleteData));
+ }
+
+ SQLDatabase* db() const {
+ return db_;
+ }
+
+ void db_schema_fill() {
+ db_schema.push_back("resumption");
+ db_schema.push_back("image");
+ db_schema.push_back("applicationChoiceSet");
+ db_schema.push_back("file");
+ db_schema.push_back("subMenu");
+ db_schema.push_back("TTSChunk");
+ db_schema.push_back("vrHelpItem");
+ db_schema.push_back("subscribedForWayPoints");
+ db_schema.push_back("tableLimitedCharacterList");
+ db_schema.push_back("characterArray");
+ db_schema.push_back("choice");
+ db_schema.push_back("command");
+ db_schema.push_back("globalProperties");
+ db_schema.push_back("choiceArray");
+ db_schema.push_back("vrCommandsArray");
+ db_schema.push_back("helpTimeoutPromptArray");
+ db_schema.push_back("vrHelpItemArray");
+ db_schema.push_back("application");
+ db_schema.push_back("applicationChoiceSetArray");
+ db_schema.push_back("applicationCommandsArray");
+ db_schema.push_back("applicationFilesArray");
+ db_schema.push_back("applicationSubMenuArray");
+ db_schema.push_back("applicationSubscribtionsArray");
+ db_schema.push_back("_internal_data");
+ std::sort(db_schema.begin(), db_schema.end());
+ }
+};
+
+SQLDatabase* ResumptionSqlQueriesTest::db_ = NULL;
+const string ResumptionSqlQueriesTest::kDatabaseName = "test_database";
+const string ResumptionSqlQueriesTest::app_id1 = "baax";
+const string ResumptionSqlQueriesTest::app_id2 = "caax";
+const string ResumptionSqlQueriesTest::device_id = "ZZZ";
+const string ResumptionSqlQueriesTest::device_id2 = "XXX";
+const string ResumptionSqlQueriesTest::test_hash = "test_hash";
+const string ResumptionSqlQueriesTest::test_hash2 = "test_hash2";
+const string ResumptionSqlQueriesTest::test_image = "test_image";
+const int ResumptionSqlQueriesTest::connection_key = 1;
+const int ResumptionSqlQueriesTest::grammarID = 2;
+const int ResumptionSqlQueriesTest::hmiAppID = 111;
+const int ResumptionSqlQueriesTest::hmiAppID2 = 112;
+const int ResumptionSqlQueriesTest::hmiLevel = 2;
+const int ResumptionSqlQueriesTest::hmiLevel2 = 3;
+const int ResumptionSqlQueriesTest::ign_off_count = 3;
+const int ResumptionSqlQueriesTest::ign_off_count2 = 4;
+const int ResumptionSqlQueriesTest::timeStamp = 2015;
+const int ResumptionSqlQueriesTest::timeStamp2 = 2016;
+
+void ResumptionSqlQueriesTest::CheckDeleteQuery(const string& count_query,
+ const string& query_to_check,
+ pair<int, string> app_info,
+ pair<int, string> dev_info,
+ const int value_before,
+ const int value_after,
+ const int position_in_result) {
+ SQLQuery query(db());
+ EXPECT_TRUE(query.Prepare(count_query));
+ EXPECT_TRUE(query.Exec());
+ EXPECT_EQ(value_before, query.GetInteger(position_in_result));
+ EXPECT_TRUE(query.Reset());
+ // Act
+ SQLQuery query_to_check_request(db());
+ EXPECT_TRUE(query_to_check_request.Prepare(query_to_check));
+ if (!app_info.second.empty()) {
+ query_to_check_request.Bind(app_info.first, app_info.second);
+ }
+ if (!dev_info.second.empty()) {
+ query_to_check_request.Bind(dev_info.first, dev_info.second);
+ }
+ EXPECT_TRUE(query_to_check_request.Exec());
+ // Check after action
+ EXPECT_TRUE(query.Exec());
+ EXPECT_EQ(value_after, query.GetInteger(position_in_result));
+}
+
+void ResumptionSqlQueriesTest::CheckSelectQuery(const string& query_to_check,
+ pair<int, string> app_info,
+ pair<int, string> dev_info,
+ const int control_value,
+ const int position_in_result) {
+ SQLQuery query_to_check_request(db());
+ EXPECT_TRUE(query_to_check_request.Prepare(query_to_check));
+ if (!app_info.second.empty()) {
+ query_to_check_request.Bind(app_info.first, app_info.second);
+ }
+ if (!dev_info.second.empty()) {
+ query_to_check_request.Bind(dev_info.first, dev_info.second);
+ }
+ EXPECT_TRUE(query_to_check_request.Exec());
+ EXPECT_EQ(control_value,
+ query_to_check_request.GetInteger(position_in_result));
+}
+
+void ResumptionSqlQueriesTest::CheckSelectQuery(const string& query_to_check,
+ const int control_value,
+ const int position_in_result) {
+ SQLQuery query_to_check_request(db());
+ EXPECT_TRUE(query_to_check_request.Prepare(query_to_check));
+ EXPECT_TRUE(query_to_check_request.Exec());
+ EXPECT_EQ(control_value,
+ query_to_check_request.GetInteger(position_in_result));
+}
+
+void ResumptionSqlQueriesTest::CheckSelectQuery(const string& query_to_check,
+ const bool control_value,
+ const int position_in_result) {
+ SQLQuery query_to_check_request(db());
+ EXPECT_TRUE(query_to_check_request.Prepare(query_to_check));
+ EXPECT_TRUE(query_to_check_request.Exec());
+ EXPECT_EQ(control_value,
+ query_to_check_request.GetBoolean(position_in_result));
+}
+
+void ResumptionSqlQueriesTest::CheckSelectQuery(const string& query_to_check,
+ const string& control_value,
+ const int position_in_result) {
+ SQLQuery query_to_check_request(db());
+ EXPECT_TRUE(query_to_check_request.Prepare(query_to_check));
+ EXPECT_TRUE(query_to_check_request.Exec());
+ EXPECT_EQ(control_value,
+ query_to_check_request.GetString(position_in_result));
+}
+
+void ResumptionSqlQueriesTest::CheckSelectQuery(const string& query_to_check,
+ const char* control_value,
+ const int position_in_result) {
+ SQLQuery query_to_check_request(db());
+ EXPECT_TRUE(query_to_check_request.Prepare(query_to_check));
+ EXPECT_TRUE(query_to_check_request.Exec());
+ EXPECT_EQ(string(control_value),
+ query_to_check_request.GetString(position_in_result));
+}
+
+void ResumptionSqlQueriesTest::CheckSelectQuery(const string& query_to_check,
+ pair<int, string> app_info,
+ pair<int, string> dev_info,
+ const string& control_value,
+ const int position_in_result) {
+ SQLQuery query_to_check_request(db());
+ EXPECT_TRUE(query_to_check_request.Prepare(query_to_check));
+ if (!app_info.second.empty()) {
+ query_to_check_request.Bind(app_info.first, app_info.second);
+ }
+ if (!dev_info.second.empty()) {
+ query_to_check_request.Bind(dev_info.first, dev_info.second);
+ }
+ EXPECT_TRUE(query_to_check_request.Exec());
+ EXPECT_EQ(control_value,
+ query_to_check_request.GetString(position_in_result));
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillImageTable(SQLQuery& query,
+ const int imageType,
+ const string& value) {
+ EXPECT_TRUE(query.Prepare(kInsertImage));
+ query.Bind(0, imageType);
+ query.Bind(1, value);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillTableLimitedCharacterListTable(
+ SQLQuery& query, const string& limitedCharacterList) {
+ EXPECT_TRUE(query.Prepare(kInsertTableLimitedCharacter));
+ query.Bind(0, limitedCharacterList);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillCharacterArrayTable(
+ SQLQuery& query,
+ const int64_t glob_prop_key,
+ const int64_t lim_char_list_key) {
+ EXPECT_TRUE(query.Prepare(kInsertCharacterArray));
+ query.Bind(0, glob_prop_key);
+ query.Bind(1, lim_char_list_key);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillTTSChunkTable(SQLQuery& query,
+ const int type,
+ const string& text) {
+ EXPECT_TRUE(query.Prepare(kInsertTTSChunk));
+ query.Bind(0, type);
+ query.Bind(1, text);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillHelpTimeoutPromptArrayTable(
+ SQLQuery& query,
+ int64_t glob_prop_key,
+ int64_t tts_chunk_key,
+ const int idhelpPrompt) {
+ EXPECT_TRUE(query.Prepare(kInsertHelpTimeoutPromptArray));
+ query.Bind(0, glob_prop_key);
+ query.Bind(1, tts_chunk_key);
+ query.Bind(2, idhelpPrompt);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillApplicationTable(
+ SQLQuery& query,
+ const int connection_key,
+ const int grammarID,
+ const string& hashID,
+ const int hmiAppID,
+ const int hmiLevel,
+ const int ign_off_count,
+ const int timeStamp,
+ bool isMediaApplication,
+ const string& appID,
+ const string& deviceID,
+ const int64_t glob_prop_key) {
+ EXPECT_TRUE(query.Prepare(kInsertApplication));
+ query.Bind(0, connection_key);
+ query.Bind(1, grammarID);
+ query.Bind(2, hashID);
+ query.Bind(3, hmiAppID);
+ query.Bind(4, hmiLevel);
+ query.Bind(5, ign_off_count);
+ query.Bind(6, timeStamp);
+ query.Bind(7, glob_prop_key);
+ query.Bind(8, isMediaApplication);
+ query.Bind(9, appID);
+ query.Bind(10, deviceID);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillGlobalPropertiesTable(
+ SQLQuery& query,
+ const string& vrHelpTitle,
+ const string& menuTitle,
+ const int language,
+ const int keyboardLayout,
+ const int keypressMode,
+ const string& autoCompleteText,
+ const int64_t image_key) {
+ EXPECT_TRUE(query.Prepare(kInsertGlobalProperties));
+ query.Bind(0, vrHelpTitle);
+ query.Bind(1, menuTitle);
+ query.Bind(2, image_key);
+ query.Bind(3, language);
+ query.Bind(4, keyboardLayout);
+ query.Bind(5, keypressMode);
+ query.Bind(6, autoCompleteText);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillApplicationCommandsArrayTable(
+ SQLQuery& query, const int64_t application_key, const int64_t command_key) {
+ EXPECT_TRUE(query.Prepare(kInsertApplicationCommandArray));
+ query.Bind(0, application_key);
+ query.Bind(1, command_key);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillCommandTable(SQLQuery& query,
+ const int cmdID,
+ const string& menuName,
+ const int parentID,
+ const int position,
+ const int64_t image_key) {
+ EXPECT_TRUE(query.Prepare(kInsertToCommand));
+ query.Bind(0, cmdID);
+ query.Bind(1, image_key);
+ query.Bind(2, menuName);
+ query.Bind(3, parentID);
+ query.Bind(4, position);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillChoiceTable(SQLQuery& query,
+ const int choiceID,
+ const string& menuName,
+ const string& secondaryText,
+ const string& tertiaryText,
+ const int64_t image_key) {
+ EXPECT_TRUE(query.Prepare(kInsertChoice));
+ query.Bind(0, choiceID);
+ query.Bind(1, menuName);
+ query.Bind(2, secondaryText);
+ query.Bind(3, tertiaryText);
+ query.Bind(4, image_key);
+ query.Bind(5, image_key);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillChoiceArrayTable(
+ SQLQuery& query,
+ const int64_t app_choice_set_key,
+ const int64_t choice_key) {
+ EXPECT_TRUE(query.Prepare(kInsertChoiceArray));
+ query.Bind(0, app_choice_set_key);
+ query.Bind(1, choice_key);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillApplicationChoiceSetTable(
+ SQLQuery& query, const int grammarID, const int interactionChoiceSetID) {
+ EXPECT_TRUE(query.Prepare(kInsertApplicationChoiceSet));
+ query.Bind(0, grammarID);
+ query.Bind(1, interactionChoiceSetID);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillApplicationChoiceSetArrayTable(
+ SQLQuery& query, const int64_t app_choice_set_key, const int64_t app_key) {
+ EXPECT_TRUE(query.Prepare(kInsertApplicationChoiceSetArray));
+ query.Bind(0, app_choice_set_key);
+ query.Bind(1, app_key);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillVRCommandsArrayTable(
+ SQLQuery& query,
+ const string& vrCommand,
+ AccessoryVRCommand value,
+ const int64_t foreing_key) {
+ EXPECT_TRUE(query.Prepare(kInsertVrCommand));
+ query.Bind(0, vrCommand);
+ if (AccessoryVRCommand::kVRCommandFromCommand == value) {
+ query.Bind(1, foreing_key);
+ query.Bind(2);
+ } else if (AccessoryVRCommand::kVRCommandFromChoice == value) {
+ query.Bind(1);
+ query.Bind(2, foreing_key);
+ }
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillVRHelpItemTable(
+ SQLQuery& query,
+ const string& text,
+ const int position,
+ const int64_t image_key) {
+ EXPECT_TRUE(query.Prepare(kInsertVRHelpItem));
+ query.Bind(0, text);
+ query.Bind(1, position);
+ query.Bind(2, image_key);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillVRHelpItemArrayTable(
+ SQLQuery& query,
+ const int64_t global_prop_key,
+ const int64_t vr_help_item_key) {
+ EXPECT_TRUE(query.Prepare(kInsertVRHelpItemArray));
+ query.Bind(0, global_prop_key);
+ query.Bind(1, vr_help_item_key);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillApplicationSubMenuArrayTable(
+ SQLQuery& query, const int app_key, const int sub_menu_key) {
+ EXPECT_TRUE(query.Prepare(kInsertToApplicationSubMenuArray));
+ query.Bind(0, app_key);
+ query.Bind(1, sub_menu_key);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillAppSubscriptionsArrayTable(
+ SQLQuery& query,
+ const int vehicleValue,
+ const int ButtonNameValue,
+ const int app_key) {
+ EXPECT_TRUE(query.Prepare(kInsertSubscriptions));
+ query.Bind(0, app_key);
+ query.Bind(1, vehicleValue);
+ query.Bind(2, ButtonNameValue);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillFileTable(SQLQuery& query,
+ const int fileType,
+ bool is_download_complete,
+ bool persistentFile,
+ const string& syncFileName) {
+ EXPECT_TRUE(query.Prepare(kInsertToFile));
+ query.Bind(0, fileType);
+ query.Bind(1, is_download_complete);
+ query.Bind(2, persistentFile);
+ query.Bind(3, syncFileName);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillSubMenuTable(SQLQuery& query,
+ const int menuID,
+ const string& menuName,
+ const int position) {
+ EXPECT_TRUE(query.Prepare(kInsertToSubMenu));
+ query.Bind(0, menuID);
+ query.Bind(1, menuName);
+ query.Bind(2, position);
+ EXPECT_TRUE(query.Exec());
+ return query;
+}
+
+SQLQuery& ResumptionSqlQueriesTest::FillApplicationFilesArrayTable(
+ SQLQuery& query, const int64_t app_key, const int64_t file_key) {
+ SQLQuery query_insert_application_files_array(db());
+ EXPECT_TRUE(query_insert_application_files_array.Prepare(
+ kInsertToApplicationFilesArray));
+ query_insert_application_files_array.Bind(0, app_key);
+ query_insert_application_files_array.Bind(1, file_key);
+ EXPECT_TRUE(query_insert_application_files_array.Exec());
+ return query;
+}
+
+TEST_F(ResumptionSqlQueriesTest, kCreateSchemaTest_ExpectSchemaCreated) {
+ // Arrange
+ SQLQuery query(db());
+ DestroySchema();
+ const std::string kCheckTablesNumber =
+ "SELECT COUNT(*) FROM sqlite_master WHERE `type` = 'table'";
+ // Check schema is not yet created
+ CheckSelectQuery(kCheckTablesNumber, 0, 0);
+ // Act
+ CreateSchema();
+ // Check schema created successfully
+ EXPECT_TRUE(query.Prepare(kCheckTablesNumber) && query.Exec());
+ EXPECT_GT(query.GetInteger(0), 0);
+ ASSERT_TRUE(query.Reset());
+ const std::string query_select_all_tbl_names =
+ "SELECT `tbl_name` FROM sqlite_master WHERE `type` = 'table'";
+ EXPECT_TRUE(query.Prepare(query_select_all_tbl_names));
+ std::vector<std::string> result;
+ db_schema_fill();
+ while (query.Next()) {
+ result.push_back(query.GetString(0));
+ }
+ std::sort(result.begin(), result.end());
+ EXPECT_TRUE(db_schema == result);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kDropSchemaTest_ExpectSchemaDestroyed) {
+ // Arrange
+ const std::string kCheckTablesNumber =
+ "SELECT COUNT(*) FROM sqlite_master WHERE `type` = 'table'";
+ // Act
+ DestroySchema();
+ // Check schema is already destroyed
+ CheckSelectQuery(kCheckTablesNumber, 0, 0);
+ // Restore Created database schema as used as shared source
+ CreateSchema();
+}
+
+TEST_F(ResumptionSqlQueriesTest, kInsertInitData_ExpectInitDataInserted) {
+ // Arrange
+ SQLQuery query_insert_resumption(db());
+ const std::string kCheckInitData = "SELECT COUNT(*) FROM `resumption`";
+ CheckSelectQuery(kCheckInitData, 0, 0);
+ const std::string kCheckInitData2 = "SELECT COUNT(*) FROM `_internal_data`";
+ CheckSelectQuery(kCheckInitData2, 0, 0);
+ // Act
+ EXPECT_TRUE(query_insert_resumption.Exec(kInsertInitData));
+
+ // Checks
+ CheckSelectQuery(kCheckInitData, 1, 0);
+ CheckSelectQuery(kCheckInitData2, 1, 0);
+
+ const std::string kCheckResumptionInitValue =
+ "SELECT last_ign_off_time FROM `resumption`";
+ CheckSelectQuery(kCheckResumptionInitValue, 0, 0);
+ const std::string kCheckInternalDataInitValue =
+ "SELECT db_version_hash FROM `_internal_data`";
+ CheckSelectQuery(kCheckInternalDataInitValue, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kChecksResumptionData_ExpectDataCorrect) {
+ // Arrange
+ CheckSelectQuery(kChecksResumptionData, 0, 0);
+ // Act
+ SQLQuery query_insert_resumption(db());
+ EXPECT_TRUE(query_insert_resumption.Exec(kInsertInitData));
+ // Check
+ CheckSelectQuery(kChecksResumptionData, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectCountHMILevel_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key);
+
+ ValToPosPair p1(0, device_id);
+ ValToPosPair p2(1, app_id1);
+ // Check
+ CheckSelectQuery(kSelectCountHMILevel, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectHMILevel_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key);
+ ValToPosPair p1(0, device_id);
+ ValToPosPair p2(1, app_id1);
+ // Check
+ CheckSelectQuery(kSelectHMILevel, p1, p2, hmiLevel, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kCheckHMIId_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key);
+ ValToPosPair p1(0, IntToString(hmiAppID));
+ ValToPosPair p2(1, "");
+ // Check
+ CheckSelectQuery(kCheckHMIId, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectHMIId_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key);
+ ValToPosPair p1(0, device_id);
+ ValToPosPair p2(1, app_id1);
+ // Check
+ CheckSelectQuery(kSelectHMIId, p1, p2, hmiAppID, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectCountHMIId_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key);
+
+ ValToPosPair p1(0, device_id);
+ ValToPosPair p2(1, app_id1);
+ // Check
+ CheckSelectQuery(kSelectCountHMIId, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kCountHashId_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key);
+
+ ValToPosPair p1(0, device_id);
+ ValToPosPair p2(1, app_id1);
+ // Check
+ CheckSelectQuery(kCountHashId, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectHashId_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key);
+ ValToPosPair p1(0, device_id);
+ ValToPosPair p2(1, app_id1);
+ // Check
+ CheckSelectQuery(kSelectHashId, p1, p2, test_hash, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectIgnOffTime_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery query_insert_init_data(db());
+ // Act
+ EXPECT_TRUE(query_insert_init_data.Exec(kInsertInitData));
+ // Check
+ CheckSelectQuery(kSelectIgnOffTime, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kCheckApplication_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key);
+ ValToPosPair p1(0, device_id);
+ ValToPosPair p2(1, app_id1);
+ // Check
+ CheckSelectQuery(kCheckApplication, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kCountApplications_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key);
+
+ key = FillImageTable(temp_query, 1, "tst_img2").LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash2,
+ hmiAppID2,
+ hmiLevel2,
+ ign_off_count,
+ timeStamp2,
+ false,
+ app_id2,
+ device_id,
+ key);
+ // Check
+ CheckSelectQuery(kCountApplications, 2, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kSelectDataForLoadResumeData_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key);
+ // Checks
+ CheckSelectQuery(kSelectDataForLoadResumeData, hmiLevel, 0);
+ CheckSelectQuery(kSelectDataForLoadResumeData, ign_off_count, 1);
+ CheckSelectQuery(kSelectDataForLoadResumeData, timeStamp, 2);
+ CheckSelectQuery(kSelectDataForLoadResumeData, app_id1, 3);
+ CheckSelectQuery(kSelectDataForLoadResumeData, device_id, 4);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kUpdateHMILevel_ExpectDataUpdated) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key);
+ // Act
+ SQLQuery query_update_hmi_level(db());
+ EXPECT_TRUE(query_update_hmi_level.Prepare(kUpdateHMILevel));
+ query_update_hmi_level.Bind(0, hmiLevel2);
+ query_update_hmi_level.Bind(1, device_id);
+ query_update_hmi_level.Bind(2, app_id1);
+ EXPECT_TRUE(query_update_hmi_level.Exec());
+ ValToPosPair p1(0, device_id);
+ ValToPosPair p2(1, app_id1);
+ // Check
+ CheckSelectQuery(kSelectHMILevel, p1, p2, hmiLevel2, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kUpdateIgnOffCount_ExpectDataUpdated) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key);
+
+ const std::string kSelectIgnOffCount =
+ "SELECT ign_off_count FROM application;";
+ // Check before action
+ CheckSelectQuery(kSelectIgnOffCount, ign_off_count, 0);
+ SQLQuery query(db());
+ // Act
+ EXPECT_TRUE(query.Exec(kUpdateIgnOffCount));
+ // Check after action
+ CheckSelectQuery(kSelectIgnOffCount, ign_off_count - 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kCountApplicationsIgnOff_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key);
+
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash2,
+ hmiAppID2,
+ hmiLevel2,
+ ign_off_count2,
+ timeStamp2,
+ false,
+ app_id2,
+ device_id,
+ key);
+
+ ValToPosPair p1(0, IntToString(4));
+ ValToPosPair p2(1, "");
+ // Check
+ CheckSelectQuery(kCountApplicationsIgnOff, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kSelectApplicationsIgnOffCount_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key);
+
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash2,
+ hmiAppID2,
+ hmiLevel2,
+ ign_off_count2,
+ timeStamp2,
+ false,
+ app_id2,
+ device_id,
+ key);
+
+ ValToPosPair p1(0, IntToString(4));
+ ValToPosPair p2(1, "");
+
+ CheckSelectQuery(kSelectApplicationsIgnOffCount, p1, p2, device_id, 0);
+ CheckSelectQuery(kSelectApplicationsIgnOffCount, p1, p2, app_id2, 1);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kUpdateSuspendData_ExpectDataUpdated) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+ FillApplicationTable(temp_query,
+ 1,
+ 1,
+ test_hash,
+ 111,
+ 1,
+ 3,
+ 45127,
+ false,
+ app_id1,
+ device_id,
+ key);
+
+ // Act
+ SQLQuery query_update_suspend_data(db());
+ EXPECT_TRUE(query_update_suspend_data.Exec(kUpdateSuspendData));
+ // Check
+ const std::string kSelectIgnOffCount =
+ "SELECT ign_off_count FROM `application`;";
+ CheckSelectQuery(kSelectIgnOffCount, 4, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kDeleteFile_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key1 = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key1)
+ .LastInsertId();
+ key1 = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key1).LastInsertId();
+ int64_t key2 =
+ FillFileTable(temp_query, 1, true, true, "tst_name").LastInsertId();
+ FillApplicationFilesArrayTable(temp_query, key1, key2);
+ // Check before action
+ const std::string select_count_file = "SELECT COUNT(*) from `file` ";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(select_count_file, kDeleteFile, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kDeleteApplicationFilesArray_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key1 = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key1)
+ .LastInsertId();
+ key1 = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key1).LastInsertId();
+ int64_t key2 =
+ FillFileTable(temp_query, 1, true, true, "tst_name").LastInsertId();
+ FillApplicationFilesArrayTable(temp_query, key1, key2);
+ // Check
+ const std::string select_count_applicationsFilesArray =
+ "SELECT COUNT(*) from `applicationFilesArray` ";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(select_count_applicationsFilesArray,
+ kDeleteApplicationFilesArray,
+ p1,
+ p2,
+ 1,
+ 0,
+ 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kDeleteSubMenu_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+ key = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key).LastInsertId();
+ int64_t submenu_key =
+ FillSubMenuTable(temp_query, 1, "tst_menuName", 2).LastInsertId();
+
+ FillApplicationSubMenuArrayTable(temp_query, key, submenu_key);
+ // Check
+ const std::string select_count_subMenu = "SELECT COUNT(*) FROM subMenu;";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(select_count_subMenu, kDeleteSubMenu, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kDeleteApplicationSubMenuArray_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key)
+ .LastInsertId();
+ key = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key).LastInsertId();
+
+ int64_t submenu_key =
+ FillSubMenuTable(temp_query, 1, "tst_menuName", 2).LastInsertId();
+
+ FillApplicationSubMenuArrayTable(temp_query, key, submenu_key);
+ // Check
+ const std::string select_count_subMenu =
+ "SELECT COUNT(*) FROM applicationSubMenuArray;";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(
+ select_count_subMenu, kDeleteApplicationSubMenuArray, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kDeleteApplicationSubscribtionsArray_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ key1 = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key1)
+ .LastInsertId();
+ key1 = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key1).LastInsertId();
+ int64_t key2 =
+ FillFileTable(temp_query, 1, true, true, "tst_name").LastInsertId();
+ key1 = FillApplicationFilesArrayTable(temp_query, key1, key2).LastInsertId();
+ FillAppSubscriptionsArrayTable(temp_query, 7, 2, key1);
+ // Check
+ const std::string select_count_applicationSubscribtionsArray =
+ "SELECT COUNT(*) FROM applicationSubscribtionsArray;";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(select_count_applicationSubscribtionsArray,
+ kDeleteApplicationSubscribtionsArray,
+ p1,
+ p2,
+ 1,
+ 0,
+ 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kDeleteImageFromCommands_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ int64_t key2 = FillCommandTable(temp_query, 1, "tst_menu_name", 1, 2, key1)
+ .LastInsertId();
+ key1 = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key1)
+ .LastInsertId();
+ key1 = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key1).LastInsertId();
+ FillApplicationCommandsArrayTable(temp_query, key1, key2);
+ // Check before action
+ const std::string select_count_image = "SELECT COUNT(*) FROM image;";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(
+ select_count_image, kDeleteImageFromCommands, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kDeleteVrCommands_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ int64_t key2 = FillCommandTable(temp_query, 1, "tst_menu_name", 1, 2, key1)
+ .LastInsertId();
+ key1 = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key1)
+ .LastInsertId();
+ key1 = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key1).LastInsertId();
+
+ FillVRCommandsArrayTable(
+ temp_query, "tst_vr_command", kVRCommandFromCommand, key2);
+ FillApplicationCommandsArrayTable(temp_query, key1, key2);
+ // Check
+ const std::string select_count_vrCommandsArray =
+ "SELECT COUNT(*) FROM vrCommandsArray;";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(
+ select_count_vrCommandsArray, kDeleteVrCommands, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kDeleteCommands_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ int64_t key2 = FillCommandTable(temp_query, 1, "tst_menu_name", 1, 2, key1)
+ .LastInsertId();
+
+ key1 = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key1)
+ .LastInsertId();
+ key1 = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key1).LastInsertId();
+
+ FillApplicationCommandsArrayTable(temp_query, key1, key2);
+ // Check
+ const std::string select_count_command = "SELECT COUNT(*) FROM command;";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(select_count_command, kDeleteCommands, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kDeleteApplicationCommandsArray_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ int64_t key2 = FillCommandTable(temp_query, 1, "tst_menu_name", 1, 2, key1)
+ .LastInsertId();
+
+ key1 = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key1)
+ .LastInsertId();
+ key1 = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key1).LastInsertId();
+
+ FillApplicationCommandsArrayTable(temp_query, key1, key2);
+ // Check
+ const std::string select_count_applicationCommandsArray =
+ "SELECT COUNT(*) FROM applicationCommandsArray;";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(select_count_applicationCommandsArray,
+ kDeleteApplicationCommandsArray,
+ p1,
+ p2,
+ 1,
+ 0,
+ 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kDeleteImageFromChoiceSet_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ int64_t key2 = FillChoiceTable(temp_query,
+ 2,
+ "tst_menu_name",
+ "secondary_txt",
+ "tst_tert_text",
+ key1).LastInsertId();
+ int64_t key3 = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key1).LastInsertId();
+ int64_t key4 = FillApplicationChoiceSetTable(temp_query, 1, 2).LastInsertId();
+ FillChoiceArrayTable(temp_query, key4, key2);
+ FillApplicationChoiceSetArrayTable(temp_query, key4, key3);
+
+ // Check
+ const std::string select_count_image = "SELECT COUNT(*) FROM image;";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(
+ select_count_image, kDeleteImageFromChoiceSet, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kDeleteVrCommandsFromChoiceSet_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ int64_t key2 =
+ FillChoiceTable(
+ temp_query, 1, "tst_menu_name", "second_text", "tert_txt", key1)
+ .LastInsertId();
+ key1 = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key1).LastInsertId();
+
+ FillVRCommandsArrayTable(
+ temp_query, "tst_vr_command", kVRCommandFromChoice, key2);
+
+ int64_t key3 = FillApplicationChoiceSetTable(temp_query, 1, 2).LastInsertId();
+
+ FillChoiceArrayTable(temp_query, key3, key2);
+ FillApplicationChoiceSetArrayTable(temp_query, key3, key1);
+ // Check before action
+ const std::string select_count_vrCommandsArray =
+ "SELECT COUNT(*) FROM vrCommandsArray;";
+ // Check
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(select_count_vrCommandsArray,
+ kDeleteVrCommandsFromChoiceSet,
+ p1,
+ p2,
+ 1,
+ 0,
+ 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kDeleteChoice_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ int64_t key2 =
+ FillChoiceTable(
+ temp_query, 1, "tst_menu_name", "second_text", "tert_txt", key1)
+ .LastInsertId();
+ key1 = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key1).LastInsertId();
+ int64_t key3 = FillApplicationChoiceSetTable(temp_query, 1, 2).LastInsertId();
+ FillChoiceArrayTable(temp_query, key3, key2);
+ FillApplicationChoiceSetArrayTable(temp_query, key3, key1);
+
+ // Check before action
+ const std::string select_count_choice = "SELECT COUNT(*) FROM choice;";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(select_count_choice, kDeleteChoice, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kDeleteChoiceArray_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t choice_table_key =
+ FillChoiceTable(
+ temp_query, 1, "tst_menu_name", "second_text", "tert_txt", 0)
+ .LastInsertId();
+
+ int64_t application_choiceset_table_key =
+ FillApplicationChoiceSetTable(temp_query, 1, 2).LastInsertId();
+ int64_t application_table_key = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ 1).LastInsertId();
+ FillApplicationChoiceSetArrayTable(
+ temp_query, application_choiceset_table_key, application_table_key);
+ FillChoiceArrayTable(
+ temp_query, application_choiceset_table_key, choice_table_key);
+ // Check
+ const std::string select_count_choice_array =
+ "SELECT COUNT(*) FROM choiceArray;";
+
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(
+ select_count_choice_array, kDeleteChoiceArray, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kDeleteApplicationChoiceSet_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ 1).LastInsertId();
+
+ int64_t key2 = FillApplicationChoiceSetTable(temp_query, 1, 2).LastInsertId();
+ FillApplicationChoiceSetArrayTable(temp_query, key2, key1);
+
+ // Check before action
+ const std::string select_count_applicationChoiceSet =
+ "SELECT COUNT(*) FROM applicationChoiceSet;";
+
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(select_count_applicationChoiceSet,
+ kDeleteApplicationChoiceSet,
+ p1,
+ p2,
+ 1,
+ 0,
+ 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kDeleteApplicationChoiceSetArray_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ 1).LastInsertId();
+
+ int64_t key2 = FillApplicationChoiceSetTable(temp_query, 1, 2).LastInsertId();
+ FillApplicationChoiceSetArrayTable(temp_query, key2, key1);
+
+ // Check
+ const std::string select_count_applicationChoiceSetArray =
+ "SELECT COUNT(*) FROM applicationChoiceSetArray;";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(select_count_applicationChoiceSetArray,
+ kDeleteApplicationChoiceSetArray,
+ p1,
+ p2,
+ 1,
+ 0,
+ 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kDeleteImageFromGlobalProperties_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ int64_t key2 = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key1)
+ .LastInsertId();
+ key1 = FillVRHelpItemTable(temp_query, "tst_text", 1, key1).LastInsertId();
+ FillVRHelpItemArrayTable(temp_query, key2, key1);
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key2);
+ // Check
+ const std::string select_count_image = "SELECT COUNT(*) FROM image;";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(
+ select_count_image, kDeleteImageFromGlobalProperties, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kDeletevrHelpItem_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ int64_t key2 = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key1)
+ .LastInsertId();
+ key1 = FillVRHelpItemTable(temp_query, "tst_text", 1, key1).LastInsertId();
+ FillVRHelpItemArrayTable(temp_query, key2, key1);
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key2);
+ // Check
+ const std::string select_count_vrhelp_item =
+ "SELECT COUNT(*) FROM vrHelpItem;";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(
+ select_count_vrhelp_item, kDeletevrHelpItem, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kDeletevrHelpItemArray_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t key1 = FillImageTable(temp_query, 1, test_image).LastInsertId();
+ int64_t key2 = FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", key1)
+ .LastInsertId();
+ key1 = FillVRHelpItemTable(temp_query, "tst_text", 1, key1).LastInsertId();
+ FillVRHelpItemArrayTable(temp_query, key2, key1);
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id,
+ key2);
+ // Check
+ const std::string select_count_vrhelp_item_array =
+ "SELECT COUNT(*) FROM vrHelpItemArray;";
+ ValToPosPair p1(0, app_id2);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(
+ select_count_vrhelp_item_array, kDeletevrHelpItemArray, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kDeleteTableLimitedCharacterList_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ string character_list = "abcdefghij";
+ int64_t key1 = FillTableLimitedCharacterListTable(temp_query, character_list)
+ .LastInsertId();
+ int64_t key2 =
+ FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", 0).LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key2);
+ FillCharacterArrayTable(temp_query, key2, key1);
+ // Check
+ const std::string select_count_tableLimitedCharacterList =
+ "SELECT COUNT(*) FROM tableLimitedCharacterList;";
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(select_count_tableLimitedCharacterList,
+ kDeleteTableLimitedCharacterList,
+ p1,
+ p2,
+ 1,
+ 0,
+ 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kDeleteCharacterArray_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ string character_list = "abcdefghij";
+ int64_t key1 = FillTableLimitedCharacterListTable(temp_query, character_list)
+ .LastInsertId();
+ int64_t key2 =
+ FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", 0).LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ key2);
+ FillCharacterArrayTable(temp_query, key2, key1);
+ // Check
+ const std::string select_count_characterArray =
+ "SELECT COUNT(*) FROM characterArray;";
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(
+ select_count_characterArray, kDeleteCharacterArray, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kDeleteTTSChunk_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t tts_chunk_key =
+ FillTTSChunkTable(temp_query, 1, "tst_text").LastInsertId();
+ int64_t glob_prop_key =
+ FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", 0).LastInsertId();
+
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ glob_prop_key);
+
+ FillHelpTimeoutPromptArrayTable(temp_query, glob_prop_key, tts_chunk_key, 1);
+ // Check
+ const std::string select_count_tts_chunk = "SELECT COUNT(*) FROM TTSChunk;";
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(select_count_tts_chunk, kDeleteTTSChunk, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kDeleteFromApplicationTable_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 1);
+ // Check
+ const std::string select_count_application =
+ "SELECT COUNT(*) FROM application;";
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(
+ select_count_application, kDeleteFromApplicationTable, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kDeleteHelpTimeoutPromptArray_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t tts_chunk_key =
+ FillTTSChunkTable(temp_query, 1, "tst_text").LastInsertId();
+ int64_t glob_prop_key =
+ FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", 0).LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ glob_prop_key);
+
+ FillHelpTimeoutPromptArrayTable(temp_query, glob_prop_key, tts_chunk_key, 1);
+ // Check
+ const std::string select_count_helpTimeoutPromptArray =
+ "SELECT COUNT(*) FROM helpTimeoutPromptArray;";
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(select_count_helpTimeoutPromptArray,
+ kDeleteHelpTimeoutPromptArray,
+ p1,
+ p2,
+ 1,
+ 0,
+ 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kDeleteGlobalProperties_ExpectDataDeleted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t glob_prop_key =
+ FillGlobalPropertiesTable(
+ temp_query, "vrHelp", "menuTitle", 1, 1, 2, "auto", 0).LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ glob_prop_key);
+ // Check
+ const std::string select_count_globalProperties =
+ "SELECT COUNT(*) FROM globalProperties;";
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ CheckDeleteQuery(
+ select_count_globalProperties, kDeleteGlobalProperties, p1, p2, 1, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectCountImage_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillImageTable(temp_query, 2, "tst_image");
+ ValToPosPair p1(0, "tst_image");
+ ValToPosPair p2(1, "");
+ // Check
+ CheckSelectQuery(kSelectCountImage, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectPrimaryKeyImage_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t image_key = FillImageTable(temp_query, 2, "tst_image").LastInsertId();
+ ValToPosPair p1(0, "tst_image");
+ ValToPosPair p2(1, "");
+ // Check
+ CheckSelectQuery(kSelectPrimaryKeyImage, p1, p2, image_key, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kInsertImage_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillImageTable(temp_query, 2, "tst_image");
+ const std::string select_count_image = "SELECT COUNT(*) FROM image;";
+ // Check
+ CheckSelectQuery(select_count_image, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kInsertToFile_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillFileTable(temp_query, 1, true, true, "tst_file_name");
+ // Check
+ const std::string select_count_file = "SELECT COUNT(*) FROM file;";
+ CheckSelectQuery(select_count_file, 1, 0);
+ const std::string select_file_name = "SELECT syncFileName FROM file;";
+ CheckSelectQuery(select_file_name, "tst_file_name", 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kInsertToApplicationFilesArray_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillApplicationFilesArrayTable(temp_query, 1, 2);
+ // Checks
+ const std::string select_count_applicationFilesArray =
+ "SELECT COUNT(*) FROM applicationFilesArray;";
+ CheckSelectQuery(select_count_applicationFilesArray, 1, 0);
+ const std::string select_idApplication =
+ "SELECT idApplication FROM applicationFilesArray;";
+ CheckSelectQuery(select_idApplication, 1, 0);
+ const std::string select_idfile = "SELECT idfile FROM applicationFilesArray;";
+ CheckSelectQuery(select_idfile, 2, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kInsertToSubMenu_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillSubMenuTable(temp_query, 1, "tst_menu", 3);
+ // Checks
+ const std::string select_count_subMenu = "SELECT COUNT(*) FROM subMenu;";
+ CheckSelectQuery(select_count_subMenu, 1, 0);
+ const std::string select_menuID = "SELECT menuID FROM subMenu;";
+ CheckSelectQuery(select_menuID, 1, 0);
+ const std::string select_menuName = "SELECT menuName FROM subMenu;";
+ CheckSelectQuery(select_menuName, "tst_menu", 0);
+ const std::string select_position = "SELECT position FROM subMenu;";
+ CheckSelectQuery(select_position, 3, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kInsertToApplicationSubMenuArray_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillApplicationSubMenuArrayTable(temp_query, 2, 5);
+ // Checks
+ const std::string select_count_applicationFilesArray =
+ "SELECT COUNT(*) FROM applicationSubMenuArray;";
+ CheckSelectQuery(select_count_applicationFilesArray, 1, 0);
+ const std::string select_idApplication =
+ "SELECT idApplication FROM applicationSubMenuArray;";
+ CheckSelectQuery(select_idApplication, 2, 0);
+ const std::string select_idsubMenu =
+ "SELECT idsubMenu FROM applicationSubMenuArray;";
+ CheckSelectQuery(select_idsubMenu, 5, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kInsertToCommand_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillCommandTable(temp_query, 1, "tst_menu", 1, 2, 5);
+ // Checks
+ const std::string select_count_command = "SELECT COUNT(*) FROM command;";
+ CheckSelectQuery(select_count_command, 1, 0);
+ const std::string select_cmdID = "SELECT cmdID FROM command;";
+ CheckSelectQuery(select_cmdID, 1, 0);
+ const std::string select_menuName = "SELECT menuName FROM command;";
+ CheckSelectQuery(select_menuName, "tst_menu", 0);
+ const std::string select_parentID = "SELECT parentID FROM command;";
+ CheckSelectQuery(select_parentID, 1, 0);
+ const std::string select_position = "SELECT position FROM command;";
+ CheckSelectQuery(select_position, 2, 0);
+ const std::string select_idimage = "SELECT idimage FROM command;";
+ CheckSelectQuery(select_idimage, 5, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kInsertApplicationCommandArray_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillApplicationCommandsArrayTable(temp_query, 3, 7);
+ // Checks
+ const std::string select_count_applicationCommandsArray =
+ "SELECT COUNT(*) FROM applicationCommandsArray;";
+ CheckSelectQuery(select_count_applicationCommandsArray, 1, 0);
+ const std::string select_idApplication =
+ "SELECT idApplication FROM applicationCommandsArray;";
+ CheckSelectQuery(select_idApplication, 3, 0);
+ const std::string select_idcommand =
+ "SELECT idcommand FROM applicationCommandsArray;";
+ CheckSelectQuery(select_idcommand, 7, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kInsertVrCommandFromChoice_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillVRCommandsArrayTable(temp_query, "vr_cmd", kVRCommandFromChoice, 8);
+ // Checks
+ const std::string select_count_vrCommandsArray =
+ "SELECT COUNT(*) FROM vrCommandsArray;";
+ CheckSelectQuery(select_count_vrCommandsArray, 1, 0);
+ const std::string select_vrCommand = "SELECT vrCommand FROM vrCommandsArray;";
+ CheckSelectQuery(select_vrCommand, "vr_cmd", 0);
+ const std::string select_idcommand = "SELECT idcommand FROM vrCommandsArray;";
+ CheckSelectQuery(select_idcommand, 0, 0);
+ const std::string select_idchoice = "SELECT idchoice FROM vrCommandsArray;";
+ CheckSelectQuery(select_idchoice, 8, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kInsertVrCommandFromCommand_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillVRCommandsArrayTable(temp_query, "vr_cmd", kVRCommandFromCommand, 9);
+ // Checks
+ const std::string select_count_vrCommandsArray =
+ "SELECT COUNT(*) FROM vrCommandsArray;";
+ CheckSelectQuery(select_count_vrCommandsArray, 1, 0);
+ const std::string select_vrCommand = "SELECT vrCommand FROM vrCommandsArray;";
+ CheckSelectQuery(select_vrCommand, "vr_cmd", 0);
+ const std::string select_idcommand = "SELECT idcommand FROM vrCommandsArray;";
+ CheckSelectQuery(select_idcommand, 9, 0);
+ const std::string select_idchoice = "SELECT idchoice FROM vrCommandsArray;";
+ CheckSelectQuery(select_idchoice, 0, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kInsertSubscriptions_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillAppSubscriptionsArrayTable(temp_query, 2, 3, 4);
+ // Checks
+ const std::string select_count_applicationSubscribtionsArray =
+ "SELECT COUNT(*) FROM applicationSubscribtionsArray;";
+ CheckSelectQuery(select_count_applicationSubscribtionsArray, 1, 0);
+ const std::string select_idApplication =
+ "SELECT idApplication FROM applicationSubscribtionsArray;";
+ CheckSelectQuery(select_idApplication, 4, 0);
+ const std::string select_vehicleValue =
+ "SELECT vehicleValue FROM applicationSubscribtionsArray;";
+ CheckSelectQuery(select_vehicleValue, 2, 0);
+ const std::string select_ButtonNameValue =
+ "SELECT ButtonNameValue FROM applicationSubscribtionsArray;";
+ CheckSelectQuery(select_ButtonNameValue, 3, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kInsertChoice_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillChoiceTable(temp_query, 1, "tst_menu", "second_text", "tert_txt", 5);
+ // Checks
+ const std::string select_count_choice = "SELECT COUNT(*) FROM choice;";
+ CheckSelectQuery(select_count_choice, 1, 0);
+
+ const std::string select_choiceID = "SELECT choiceID FROM choice;";
+ CheckSelectQuery(select_choiceID, 1, 0);
+ const std::string select_menuName = "SELECT menuName FROM choice;";
+ CheckSelectQuery(select_menuName, "tst_menu", 0);
+ const std::string select_secondaryText = "SELECT secondaryText FROM choice;";
+ CheckSelectQuery(select_secondaryText, "second_text", 0);
+ const std::string select_tertiaryText = "SELECT tertiaryText FROM choice;";
+ CheckSelectQuery(select_tertiaryText, "tert_txt", 0);
+ const std::string select_idimage = "SELECT idimage FROM choice;";
+ CheckSelectQuery(select_idimage, 5, 0);
+ const std::string select_idsecondaryImage =
+ "SELECT idsecondaryImage FROM choice;";
+ CheckSelectQuery(select_idsecondaryImage, 5, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kInsertApplicationChoiceSet_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillApplicationChoiceSetTable(temp_query, 7, 12);
+ // Checks
+ const std::string select_count_applicationChoiceSet =
+ "SELECT COUNT(*) FROM applicationChoiceSet;";
+ CheckSelectQuery(select_count_applicationChoiceSet, 1, 0);
+
+ const std::string select_grammarID =
+ "SELECT grammarID FROM applicationChoiceSet;";
+ CheckSelectQuery(select_grammarID, 7, 0);
+ const std::string select_interactionChoiceSetID =
+ "SELECT interactionChoiceSetID FROM applicationChoiceSet;";
+ CheckSelectQuery(select_interactionChoiceSetID, 12, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kInsertChoiceArray_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillChoiceArrayTable(temp_query, 3, 5);
+ // Checks
+ const std::string select_count_choiceArray =
+ "SELECT COUNT(*) FROM choiceArray;";
+ CheckSelectQuery(select_count_choiceArray, 1, 0);
+ const std::string select_idapplicationChoiceSet =
+ "SELECT idapplicationChoiceSet FROM choiceArray;";
+ CheckSelectQuery(select_idapplicationChoiceSet, 3, 0);
+ const std::string select_idchoice = "SELECT idchoice FROM choiceArray;";
+ CheckSelectQuery(select_idchoice, 5, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kInsertApplicationChoiceSetArray_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillApplicationChoiceSetArrayTable(temp_query, 3, 5);
+ // Checks
+ const std::string select_count_applicationChoiceSetArray =
+ "SELECT COUNT(*) FROM applicationChoiceSetArray;";
+ CheckSelectQuery(select_count_applicationChoiceSetArray, 1, 0);
+ const std::string select_idapplicationChoiceSet =
+ "SELECT idapplicationChoiceSet FROM applicationChoiceSetArray;";
+ CheckSelectQuery(select_idapplicationChoiceSet, 3, 0);
+ const std::string select_idApplication =
+ "SELECT idApplication FROM applicationChoiceSetArray;";
+ CheckSelectQuery(select_idApplication, 5, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kInsertGlobalProperties_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillGlobalPropertiesTable(
+ temp_query, "vr_title", "menu_title", 2, 1, 3, "auto", 7);
+ // Checks
+ const std::string select_count_globalProperties =
+ "SELECT COUNT(*) FROM globalProperties;";
+ CheckSelectQuery(select_count_globalProperties, 1, 0);
+ const std::string select_vrHelpTitle =
+ "SELECT vrHelpTitle FROM globalProperties;";
+ CheckSelectQuery(select_vrHelpTitle, "vr_title", 0);
+ const std::string select_menuTitle =
+ "SELECT menuTitle FROM globalProperties;";
+ CheckSelectQuery(select_menuTitle, "menu_title", 0);
+ const std::string select_idmenuIcon =
+ "SELECT idmenuIcon FROM globalProperties;";
+ CheckSelectQuery(select_idmenuIcon, 7, 0);
+ const std::string select_language = "SELECT language FROM globalProperties;";
+ CheckSelectQuery(select_language, 2, 0);
+ const std::string select_keyboardLayout =
+ "SELECT keyboardLayout FROM globalProperties;";
+ CheckSelectQuery(select_keyboardLayout, 1, 0);
+ const std::string select_keypressMode =
+ "SELECT keypressMode FROM globalProperties;";
+ CheckSelectQuery(select_keypressMode, 3, 0);
+ const std::string select_autoCompleteText =
+ "SELECT autoCompleteText FROM globalProperties;";
+ CheckSelectQuery(select_autoCompleteText, "auto", 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kInsertTableLimitedCharacter_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ string character_list = "abcdefghijkl";
+ FillTableLimitedCharacterListTable(temp_query, character_list);
+ // Checks
+ const std::string select_count_tableLimitedCharacterList =
+ "SELECT COUNT(*) FROM tableLimitedCharacterList;";
+ CheckSelectQuery(select_count_tableLimitedCharacterList, 1, 0);
+ const std::string select_limitedCharacterList =
+ "SELECT limitedCharacterList FROM tableLimitedCharacterList;";
+ CheckSelectQuery(select_limitedCharacterList, character_list, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kInsertCharacterArray_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillCharacterArrayTable(temp_query, 2, 4);
+ // Checks
+ const std::string select_count_characterArray =
+ "SELECT COUNT(*) FROM characterArray;";
+ CheckSelectQuery(select_count_characterArray, 1, 0);
+ const std::string select_idglobalProperties =
+ "SELECT idglobalProperties FROM characterArray;";
+ CheckSelectQuery(select_idglobalProperties, 2, 0);
+ const std::string select_idtableLimitedCharacterList =
+ "SELECT idtableLimitedCharacterList FROM characterArray;";
+ CheckSelectQuery(select_idtableLimitedCharacterList, 4, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kInsertVRHelpItem_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillVRHelpItemTable(temp_query, "tst_txt", 1, 3);
+ // Checks
+ const std::string select_count_vrHelpItem =
+ "SELECT COUNT(*) FROM vrHelpItem;";
+ CheckSelectQuery(select_count_vrHelpItem, 1, 0);
+ const std::string select_text = "SELECT text FROM vrHelpItem;";
+ CheckSelectQuery(select_text, "tst_txt", 0);
+ const std::string select_position = "SELECT position FROM vrHelpItem;";
+ CheckSelectQuery(select_position, 1, 0);
+ const std::string select_idimage = "SELECT idimage FROM vrHelpItem;";
+ CheckSelectQuery(select_idimage, 3, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kInsertVRHelpItemArray_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillVRHelpItemArrayTable(temp_query, 4, 5);
+ // Checks
+ const std::string select_count_vrHelpItemArray =
+ "SELECT COUNT(*) FROM vrHelpItemArray;";
+ CheckSelectQuery(select_count_vrHelpItemArray, 1, 0);
+ const std::string select_idglobalProperties =
+ "SELECT idglobalProperties FROM vrHelpItemArray;";
+ CheckSelectQuery(select_idglobalProperties, 4, 0);
+ const std::string select_idvrHelpItem =
+ "SELECT idvrHelpItem FROM vrHelpItemArray;";
+ CheckSelectQuery(select_idvrHelpItem, 5, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kInsertHelpTimeoutPromptArray_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillHelpTimeoutPromptArrayTable(temp_query, 1, 2, 3);
+ // Checks
+ const std::string select_count_helpTimeoutPromptArray =
+ "SELECT COUNT(*) FROM helpTimeoutPromptArray;";
+ CheckSelectQuery(select_count_helpTimeoutPromptArray, 1, 0);
+ const std::string select_idglobalProperties =
+ "SELECT idglobalProperties FROM helpTimeoutPromptArray;";
+ CheckSelectQuery(select_idglobalProperties, 1, 0);
+ const std::string select_idtimeoutPrompt =
+ "SELECT idtimeoutPrompt FROM helpTimeoutPromptArray;";
+ CheckSelectQuery(select_idtimeoutPrompt, 2, 0);
+ const std::string select_idhelpPrompt =
+ "SELECT idhelpPrompt FROM helpTimeoutPromptArray;";
+ CheckSelectQuery(select_idhelpPrompt, 3, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kInsertTTSChunk_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillTTSChunkTable(temp_query, 2, "text");
+ // Checks
+ const std::string select_count_kInsertTTSChunk =
+ "SELECT COUNT(*) FROM TTSChunk;";
+ CheckSelectQuery(select_count_kInsertTTSChunk, 1, 0);
+ const std::string select_type = "SELECT type FROM TTSChunk;";
+ CheckSelectQuery(select_type, 2, 0);
+ const std::string select_text = "SELECT text FROM TTSChunk;";
+ CheckSelectQuery(select_text, "text", 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kInsertApplication_ExpectDataInserted) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 9);
+ // Checks
+ const std::string select_count_application =
+ "SELECT COUNT(*) FROM application;";
+ CheckSelectQuery(select_count_application, 1, 0);
+
+ const std::string select_connection_key =
+ "SELECT connection_key FROM application;";
+ CheckSelectQuery(select_connection_key, connection_key, 0);
+ const std::string select_grammarID = "SELECT grammarID FROM application;";
+ CheckSelectQuery(select_grammarID, grammarID, 0);
+ const std::string select_hashID = "SELECT hashID FROM application;";
+ CheckSelectQuery(select_hashID, test_hash, 0);
+ const std::string select_hmiAppID = "SELECT hmiAppID FROM application;";
+ CheckSelectQuery(select_hmiAppID, hmiAppID, 0);
+ const std::string select_hmiLevel = "SELECT hmiLevel FROM application;";
+ CheckSelectQuery(select_hmiLevel, hmiLevel, 0);
+ const std::string select_ign_off_count =
+ "SELECT ign_off_count FROM application;";
+ CheckSelectQuery(select_ign_off_count, ign_off_count, 0);
+ const std::string select_timeStamp = "SELECT timeStamp FROM application;";
+ CheckSelectQuery(select_timeStamp, timeStamp, 0);
+ const std::string select_idglobalProperties =
+ "SELECT idglobalProperties FROM application;";
+ CheckSelectQuery(select_idglobalProperties, 9, 0);
+ const std::string select_isMediaApplication =
+ "SELECT isMediaApplication FROM application;";
+ CheckSelectQuery(select_isMediaApplication, false, 0);
+ const std::string select_appID = "SELECT appID FROM application;";
+ CheckSelectQuery(select_appID, app_id1, 0);
+ const std::string select_deviceID = "SELECT deviceID FROM application;";
+ CheckSelectQuery(select_deviceID, device_id, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectCountFiles_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t app_key = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 9).LastInsertId();
+ int64_t file_key =
+ FillFileTable(temp_query, 1, true, true, "tst_name").LastInsertId();
+ FillApplicationFilesArrayTable(temp_query, app_key, file_key);
+
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ // Check
+ CheckSelectQuery(kSelectCountFiles, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectFiles_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t app_key = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 9).LastInsertId();
+ int64_t file_key =
+ FillFileTable(temp_query, 1, true, true, "tst_name").LastInsertId();
+ FillApplicationFilesArrayTable(temp_query, app_key, file_key);
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ // Check
+ CheckSelectQuery(kSelectFiles, p1, p2, 1, 0);
+ CheckSelectQuery(kSelectFiles, p1, p2, true, 1);
+ CheckSelectQuery(kSelectFiles, p1, p2, true, 2);
+ CheckSelectQuery(kSelectFiles, p1, p2, "tst_name", 3);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectCountSubMenu_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t app_key = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 9).LastInsertId();
+ int64_t submenu_key =
+ FillSubMenuTable(temp_query, 1, "menu_name", 1).LastInsertId();
+ FillApplicationSubMenuArrayTable(temp_query, app_key, submenu_key);
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ // Check
+ CheckSelectQuery(kSelectCountSubMenu, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectSubMenu_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t app_key = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 9).LastInsertId();
+ int64_t submenu_key =
+ FillSubMenuTable(temp_query, 1, "menu_name", 1).LastInsertId();
+
+ FillApplicationSubMenuArrayTable(temp_query, app_key, submenu_key);
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ // Check
+ CheckSelectQuery(kSelectSubMenu, p1, p2, 1, 0);
+ CheckSelectQuery(kSelectSubMenu, p1, p2, "menu_name", 1);
+ CheckSelectQuery(kSelectSubMenu, p1, p2, 1, 2);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectCountCommands_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t app_key = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 9).LastInsertId();
+ int64_t command_key =
+ FillCommandTable(temp_query, 1, "menu_name", 1, 2, 5).LastInsertId();
+ FillApplicationCommandsArrayTable(temp_query, app_key, command_key);
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ // Check
+ CheckSelectQuery(kSelectCountCommands, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectCommandsFromCommand_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t app_key = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 9).LastInsertId();
+ int64_t image_key = FillImageTable(temp_query, 2, "tst_image").LastInsertId();
+
+ FillChoiceTable(
+ temp_query, 1, "menu_name", "sec_text", "tert_text", image_key)
+ .LastInsertId();
+ int64_t command_key =
+ FillCommandTable(temp_query, 1, "menu_name", 1, 2, image_key)
+ .LastInsertId();
+
+ FillApplicationCommandsArrayTable(temp_query, app_key, command_key);
+ FillVRCommandsArrayTable(
+ temp_query, "best", kVRCommandFromCommand, command_key);
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ // Check
+ CheckSelectQuery(kSelectCommands, p1, p2, 1, 0);
+ CheckSelectQuery(kSelectCommands, p1, p2, 1, 1);
+ CheckSelectQuery(kSelectCommands, p1, p2, "menu_name", 2);
+ CheckSelectQuery(kSelectCommands, p1, p2, 1, 3);
+ CheckSelectQuery(kSelectCommands, p1, p2, 2, 4);
+ CheckSelectQuery(kSelectCommands, p1, p2, "tst_image", 5);
+ CheckSelectQuery(kSelectCommands, p1, p2, 2, 6);
+ CheckSelectQuery(kSelectCommands, p1, p2, "best", 7);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectCommandsFromChoice_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t app_key = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 9).LastInsertId();
+ int64_t image_key = FillImageTable(temp_query, 2, "tst_image").LastInsertId();
+
+ int64_t choice_key =
+ FillChoiceTable(
+ temp_query, 1, "menu_name", "sec_text", "tert_text", image_key)
+ .LastInsertId();
+ int64_t command_key =
+ FillCommandTable(temp_query, 1, "menu_name", 1, 2, image_key)
+ .LastInsertId();
+
+ FillApplicationCommandsArrayTable(temp_query, app_key, command_key);
+ FillVRCommandsArrayTable(
+ temp_query, "best", kVRCommandFromChoice, choice_key);
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ const std::string kChecksVrCommandFromSelectCommand =
+ "SELECT COUNT(*) FROM (SELECT `command`.`idcommand`, `cmdID`, "
+ "`menuName`, `parentID`, `position`, `value`, `imageType`, `vrCommand` "
+ "FROM `command` LEFT OUTER JOIN `image` on `command`.`idimage` = "
+ "`image`.`idimage` "
+ "LEFT OUTER JOIN `vrcommandsarray` on `command`.`idcommand` = "
+ "`vrcommandsarray`.`idcommand` "
+ "WHERE `command`.`idcommand` IN (SELECT `idcommand` "
+ "FROM `applicationCommandsArray` "
+ "WHERE `idApplication` = (SELECT `idApplication` "
+ "FROM `application` WHERE `appID` = ? AND `deviceID` = ?))) "
+ "WHERE vrCommand IS NULL";
+ // Check
+ CheckSelectQuery(kSelectCommands, p1, p2, 1, 0);
+ CheckSelectQuery(kSelectCommands, p1, p2, 1, 1);
+ CheckSelectQuery(kSelectCommands, p1, p2, "menu_name", 2);
+ CheckSelectQuery(kSelectCommands, p1, p2, 1, 3);
+ CheckSelectQuery(kSelectCommands, p1, p2, 2, 4);
+ CheckSelectQuery(kSelectCommands, p1, p2, "tst_image", 5);
+ CheckSelectQuery(kSelectCommands, p1, p2, 2, 6);
+ CheckSelectQuery(kChecksVrCommandFromSelectCommand, p1, p2, true, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectCountSubscriptions_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t app_key = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 9).LastInsertId();
+ FillAppSubscriptionsArrayTable(temp_query, 2, 3, app_key);
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ // Check
+ CheckSelectQuery(kSelectCountSubscriptions, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectSubscriptions_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t app_key = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 9).LastInsertId();
+ FillAppSubscriptionsArrayTable(temp_query, 2, 3, app_key);
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ // Check
+ CheckSelectQuery(kSelectSubscriptions, p1, p2, 2, 0);
+ CheckSelectQuery(kSelectSubscriptions, p1, p2, 3, 1);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectCountChoiceSet_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t app_key = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 9).LastInsertId();
+ FillApplicationChoiceSetArrayTable(temp_query, 2, app_key);
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ // Check
+ CheckSelectQuery(kSelectCountChoiceSet, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectChoiceSets_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t app_key = FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 9).LastInsertId();
+ int64_t image_key = FillImageTable(temp_query, 2, "tst_image").LastInsertId();
+ int64_t choice_key =
+ FillChoiceTable(
+ temp_query, 1, "menu_name", "sec_text", "tert_text", image_key)
+ .LastInsertId();
+ int64_t app_choice_set_key =
+ FillApplicationChoiceSetTable(temp_query, 23, 2).LastInsertId();
+
+ FillChoiceArrayTable(temp_query, app_choice_set_key, choice_key);
+ FillApplicationChoiceSetArrayTable(temp_query, app_choice_set_key, app_key);
+ FillVRCommandsArrayTable(
+ temp_query, "best", kVRCommandFromChoice, choice_key);
+
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ // Check
+ CheckSelectQuery(kSelectChoiceSets, p1, p2, 1, 0);
+ CheckSelectQuery(kSelectChoiceSets, p1, p2, 23, 1);
+ CheckSelectQuery(kSelectChoiceSets, p1, p2, 2, 2);
+ CheckSelectQuery(kSelectChoiceSets, p1, p2, 1, 3);
+ CheckSelectQuery(kSelectChoiceSets, p1, p2, 1, 4);
+ CheckSelectQuery(kSelectChoiceSets, p1, p2, "menu_name", 5);
+ CheckSelectQuery(kSelectChoiceSets, p1, p2, "sec_text", 6);
+ CheckSelectQuery(kSelectChoiceSets, p1, p2, "tert_text", 7);
+ CheckSelectQuery(kSelectChoiceSets, p1, p2, 1, 8);
+ CheckSelectQuery(kSelectChoiceSets, p1, p2, 1, 9);
+ CheckSelectQuery(kSelectChoiceSets, p1, p2, "best", 10);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectImage_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t image_key = FillImageTable(temp_query, 2, "tst_image").LastInsertId();
+ // Check
+ ValToPosPair p1(0, IntToString(image_key));
+ ValToPosPair p2(1, "");
+ CheckSelectQuery(kSelectImage, p1, p2, 2, 0);
+ CheckSelectQuery(kSelectImage, p1, p2, "tst_image", 1);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kSelectCountGlobalProperties_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t glob_prop_key =
+ FillGlobalPropertiesTable(
+ temp_query, "tst_vr_title", "tst_menu", 2, 3, 3, "auto", 5)
+ .LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ glob_prop_key).LastInsertId();
+
+ // Check
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ CheckSelectQuery(kSelectCountGlobalProperties, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectGlobalProperties_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t image_key = FillImageTable(temp_query, 2, "tst_image").LastInsertId();
+ int64_t glob_prop_key =
+ FillGlobalPropertiesTable(
+ temp_query, "tst_vr_title", "tst_menu", 2, 3, 3, "auto", image_key)
+ .LastInsertId();
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ glob_prop_key).LastInsertId();
+ FillHelpTimeoutPromptArrayTable(temp_query, glob_prop_key, 3, 7);
+
+ // Check
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ CheckSelectQuery(kSelectGlobalProperties, p1, p2, glob_prop_key, 0);
+ CheckSelectQuery(kSelectGlobalProperties, p1, p2, "tst_vr_title", 1);
+ CheckSelectQuery(kSelectGlobalProperties, p1, p2, "tst_menu", 2);
+ CheckSelectQuery(kSelectGlobalProperties, p1, p2, 1, 3);
+ CheckSelectQuery(kSelectGlobalProperties, p1, p2, 2, 4);
+ CheckSelectQuery(kSelectGlobalProperties, p1, p2, 3, 5);
+ CheckSelectQuery(kSelectGlobalProperties, p1, p2, 3, 6);
+ CheckSelectQuery(kSelectGlobalProperties, p1, p2, "auto", 7);
+ CheckSelectQuery(kSelectGlobalProperties, p1, p2, 7, 8);
+ CheckSelectQuery(kSelectGlobalProperties, p1, p2, 3, 9);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kChecksVrHelpItem_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t image_key = FillImageTable(temp_query, 2, "tst_image").LastInsertId();
+ int64_t glob_prop_key =
+ FillGlobalPropertiesTable(
+ temp_query, "tst_vr_title", "tst_menu", 2, 3, 3, "auto", image_key)
+ .LastInsertId();
+ int64_t vr_help_item_key =
+ FillVRHelpItemTable(temp_query, "tst_text", 2, image_key).LastInsertId();
+ FillVRHelpItemArrayTable(temp_query, glob_prop_key, vr_help_item_key);
+ // Check
+ ValToPosPair p1(0, IntToString(glob_prop_key));
+ ValToPosPair p2(1, "");
+ CheckSelectQuery(kChecksVrHelpItem, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectVrHelpItem_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t image_key = FillImageTable(temp_query, 2, "tst_image").LastInsertId();
+ int64_t glob_prop_key =
+ FillGlobalPropertiesTable(
+ temp_query, "tst_vr_title", "tst_menu", 2, 3, 3, "auto", image_key)
+ .LastInsertId();
+ int64_t vr_help_item_key =
+ FillVRHelpItemTable(temp_query, "tst_text", 2, image_key).LastInsertId();
+ FillVRHelpItemArrayTable(temp_query, glob_prop_key, vr_help_item_key);
+ // Check
+ ValToPosPair p1(0, IntToString(glob_prop_key));
+ ValToPosPair p2(1, "");
+ CheckSelectQuery(kSelectVrHelpItem, p1, p2, "tst_text", 0);
+ CheckSelectQuery(kSelectVrHelpItem, p1, p2, 2, 1);
+ CheckSelectQuery(kSelectVrHelpItem, p1, p2, 2, 2);
+ CheckSelectQuery(kSelectVrHelpItem, p1, p2, "tst_image", 3);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kChecksCharacter_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t glob_prop_key =
+ FillGlobalPropertiesTable(
+ temp_query, "tst_vr_title", "tst_menu", 2, 3, 3, "auto", 2)
+ .LastInsertId();
+ string character_list = "abcdefghijkl";
+ int64_t lim_char_list_key = FillTableLimitedCharacterListTable(
+ temp_query, character_list).LastInsertId();
+ FillCharacterArrayTable(temp_query, glob_prop_key, lim_char_list_key);
+ // Check
+ ValToPosPair p1(0, IntToString(glob_prop_key));
+ ValToPosPair p2(1, "");
+ CheckSelectQuery(kChecksCharacter, p1, p2, 1, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectCharacter_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t glob_prop_key =
+ FillGlobalPropertiesTable(
+ temp_query, "tst_vr_title", "tst_menu", 2, 3, 3, "auto", 2)
+ .LastInsertId();
+ string character_list = "abcdefghijkl";
+ int64_t lim_char_list_key = FillTableLimitedCharacterListTable(
+ temp_query, character_list).LastInsertId();
+ FillCharacterArrayTable(temp_query, glob_prop_key, lim_char_list_key);
+ // Check
+ ValToPosPair p1(0, IntToString(glob_prop_key));
+ ValToPosPair p2(1, "");
+ CheckSelectQuery(kSelectCharacter, p1, p2, character_list, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectAllApps_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 1);
+
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id2,
+ device_id2,
+ 2);
+ // Checks
+ SQLQuery query(db());
+ EXPECT_TRUE(query.Prepare(kSelectAllApps) && query.Exec());
+ EXPECT_EQ(app_id1, query.GetString(0));
+ EXPECT_EQ(device_id, query.GetString(1));
+ EXPECT_TRUE(query.Next());
+ EXPECT_EQ(app_id2, query.GetString(0));
+ EXPECT_EQ(device_id2, query.GetString(1));
+}
+
+TEST_F(ResumptionSqlQueriesTest, kUpdateApplicationData_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ false,
+ app_id1,
+ device_id,
+ 1);
+ string select_hmi_level_and_time_stamp =
+ "SELECT `hmiLevel`, `timeStamp`FROM `application` "
+ "WHERE `appID` = ? AND `deviceID` = ?;";
+
+ // Checks before action
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ CheckSelectQuery(select_hmi_level_and_time_stamp, p1, p2, hmiLevel, 0);
+ CheckSelectQuery(select_hmi_level_and_time_stamp, p1, p2, timeStamp, 1);
+ // Act
+ SQLQuery query(db());
+ EXPECT_TRUE(query.Prepare(kUpdateApplicationData));
+ query.Bind(0, 2);
+ query.Bind(1, 2016);
+ query.Bind(2, app_id1);
+ query.Bind(3, device_id);
+ EXPECT_TRUE(query.Exec());
+ // Checks after action
+ CheckSelectQuery(select_hmi_level_and_time_stamp, p1, p2, 2, 0);
+ CheckSelectQuery(select_hmi_level_and_time_stamp, p1, p2, 2016, 1);
+}
+
+TEST_F(ResumptionSqlQueriesTest,
+ kUpdateDBVersion_kSelectDBVersion_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ EXPECT_TRUE(temp_query.Exec(kInsertInitData));
+ // Checks before action
+ CheckSelectQuery(kSelectDBVersion, 0, 0);
+ // Act
+ SQLQuery query(db());
+ EXPECT_TRUE(query.Prepare(kUpdateDBVersion));
+ query.Bind(0, 2);
+ EXPECT_TRUE(query.Exec());
+ // Checks after action
+ CheckSelectQuery(kSelectDBVersion, 2, 0);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectTTSChunk_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ int64_t tts_chunk_key =
+ FillTTSChunkTable(temp_query, 2, "tst_txt").LastInsertId();
+ ValToPosPair p1(0, IntToString(tts_chunk_key));
+ ValToPosPair p2(1, "");
+ // Checks
+ CheckSelectQuery(kSelectTTSChunk, p1, p2, "tst_txt", 0);
+ CheckSelectQuery(kSelectTTSChunk, p1, p2, 2, 1);
+}
+
+TEST_F(ResumptionSqlQueriesTest, kSelectAppTable_ExpectDataCorrect) {
+ // Arrange
+ SQLQuery temp_query(db());
+ FillApplicationTable(temp_query,
+ connection_key,
+ grammarID,
+ test_hash,
+ hmiAppID,
+ hmiLevel,
+ ign_off_count,
+ timeStamp,
+ true,
+ app_id1,
+ device_id,
+ 1);
+
+ ValToPosPair p1(0, app_id1);
+ ValToPosPair p2(1, device_id);
+ // Checks
+ CheckSelectQuery(kSelectAppTable, p1, p2, app_id1, 0);
+ CheckSelectQuery(kSelectAppTable, p1, p2, connection_key, 1);
+ CheckSelectQuery(kSelectAppTable, p1, p2, grammarID, 2);
+ CheckSelectQuery(kSelectAppTable, p1, p2, test_hash, 3);
+ CheckSelectQuery(kSelectAppTable, p1, p2, hmiAppID, 4);
+ CheckSelectQuery(kSelectAppTable, p1, p2, hmiLevel, 5);
+ CheckSelectQuery(kSelectAppTable, p1, p2, ign_off_count, 6);
+ CheckSelectQuery(kSelectAppTable, p1, p2, timeStamp, 7);
+ CheckSelectQuery(kSelectAppTable, p1, p2, device_id, 8);
+ CheckSelectQuery(kSelectAppTable, p1, p2, true, 9);
+}
+
+} // namespace resumption_test
+} // namespace components
+} // namespace test
diff --git a/src/components/application_manager/test/sdl_preloaded_pt.json b/src/components/application_manager/test/sdl_preloaded_pt.json
new file mode 100644
index 0000000000..d6f34c12fc
--- /dev/null
+++ b/src/components/application_manager/test/sdl_preloaded_pt.json
@@ -0,0 +1,1944 @@
+ {
+ "policy_table": {
+ "module_config": {
+ "preloaded_pt": true,
+ "preloaded_date": "2015-02-12",
+ "exchange_after_x_ignition_cycles": 100,
+ "exchange_after_x_kilometers": 1800,
+ "exchange_after_x_days": 30,
+ "timeout_after_x_seconds": 70,
+ "seconds_between_retries": [1,
+ 5,
+ 25,
+ 125,
+ 625],
+ "endpoints": {
+ "0x07": {
+ "default": ["http://policies.telematics.ford.com/api/policies"]
+ }
+ },
+ "notifications_per_minute_by_priority": {
+ "EMERGENCY": 60,
+ "NAVIGATION": 15,
+ "COMMUNICATION": 6,
+ "NORMAL": 4,
+ "NONE": 0
+ }
+ },
+ "functional_groupings": {
+ "Base-4": {
+ "rpcs": {
+ "AddCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "AddSubMenu": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "Alert": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "ChangeRegistration": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "CreateInteractionChoiceSet": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "DeleteInteractionChoiceSet": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteSubMenu": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "EndAudioPassThru": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "GenericResponse": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ListFiles": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAudioPassThru": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnButtonEvent": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "OnButtonPress": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "OnCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnDriverDistraction": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHashChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "PerformAudioPassThru": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "PerformInteraction": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "PutFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ResetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ScrollableMessage": {
+ "hmi_levels": ["FULL"]
+ },
+ "SetAppIcon": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "SetMediaClockTimer": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "Show": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "Slider": {
+ "hmi_levels": ["FULL"]
+ },
+ "Speak": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "SubscribeButton": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "SystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnsubscribeButton": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "Location-1": {
+ "user_consent_prompt": "Location",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ }
+ }
+ },
+ "Notifications": {
+ "user_consent_prompt": "Notifications",
+ "rpcs": {
+ "Alert": {
+ "hmi_levels": ["BACKGROUND"]
+ }
+ }
+ },
+ "DrivingCharacteristics-3": {
+ "user_consent_prompt": "DrivingCharacteristics",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ }
+ }
+ },
+ "VehicleInfo-3": {
+ "user_consent_prompt": "VehicleInfo",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"]
+ }
+ }
+ },
+ "PropriataryData-1": {
+ "rpcs": {
+ "DiagnosticMessage": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "GetDTCs": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ReadDID": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "Emergency-1": {
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ }
+ }
+ },
+ "Navigation-1": {
+ "rpcs": {
+ "AlertManeuver": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ShowConstantTBT": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "UpdateTurnList": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "DataConsent-2": {
+ "user_consent_prompt": "DataConsent",
+ "rpcs": null
+ },
+ "BaseBeforeDataConsent": {
+ "rpcs": {
+ "ChangeRegistration": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "DeleteFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ListFiles": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHashChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "PutFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetAppIcon": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ }
+ }
+ }
+ },
+ "consumer_friendly_messages": {
+ "version": "001.001.019",
+ "messages": {
+ "AppPermissions": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% benötigt die folgenden Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Wenn Sie Ja drücken, erklären Sie sich damit einverstanden, dass %vehicleMake% nicht für Schäden oder Verletzungen der Privatsphäre haftet, die im Zusammenhang mit der Nutzung Ihrer Benutzerdaten durch %appName% entstehen. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab.",
+ "line1": "Zugriffsanfrage(n)",
+ "line2": "erlauben?"
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. Please press yes to allow or no to deny.",
+ "line1": "Grant Requested",
+ "line2": "Permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. \n\nIf you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "es-en": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?",
+ "textBody": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar. \n\n Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando el uso de los siguientes permisos e información del vehículo: %functionalGroupLabels%. Si pulsa sí, acepta que %vehicleMake% no será responsable de los daños o la pérdida de privacidad relacionados con el uso de sus datos por parte de %appName%. Pulse sí para permitir o no para denegar.",
+ "line1": "¿Conceder permisos",
+ "line2": "solicitados?"
+ },
+ "es-mx": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?"
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)",
+ "textBody": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)"
+ },
+ "it-it": {
+ "tts": "%appName% richiede l'uso delle seguenti informazioni e autorizzazioni sul veicolo: %functionalGroupLabels%. Se si preme Sì, si acconsente che %vehicleMake% non sarà responsabile per danni o perdita di privacy in relazione all'impiego dei dati da parte di %appName%. Premere Sì per consentire e No per negare.",
+ "line1": "Concedi autorizzaz.",
+ "line2": "richiesta(e)?"
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. Als u op Ja drukt, gaat u ermee akkoord dat %vehicleMake% in geen geval aansprakelijk gesteld kan worden voor schade of verlies van privacy als gevolg van het feit dat %appName% gebruik maakt van uw gegevens. Druk op Ja om dit toe te staan of Nee om te weigeren.",
+ "line1": "Aangevraagde",
+ "line2": "permissie(s) verlenen?"
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz pozwoleń: %functionalGroupLabels%. Naciśnięcie TAK oznacza zgodę na fakt, iż %vehicleMake% nie będzie ponosić odpowiedzialności za szkody ani utratę prywatności w związku z wykorzystaniem przez %appName% danych, należących do użytkownika. Naciśnij TAK w celu udzielenia zgody lub NIE w celu odrzucenia żądania.",
+ "line1": "Udzielić żądanych",
+ "line2": "pozwoleń?"
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando o uso das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se pressionar sim, você concorda que a %vehicleMake% não será responsável por danos ou perdas de privacidade relacionados ao uso dos seus dados por %appName%. Pressione sim para permitir ou não para negar.",
+ "line1": "Conceder permissão",
+ "line2": "solicitada?"
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar a utilização das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se premir “Sim”, concorda que %vehicleMake% não será responsável por quaisquer danos ou perda de privacidade relacionada com a utilização dos seus dados por parte de %appName%. Prima “Sim” para permitir ou “Não” para recusar.",
+ "line1": "Conceder permiss.",
+ "line2": "solicitada(s)?"
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Нажатием \"\"да\"\", Вы соглашаетесь, что %vehicleMake% не будет нести ответственность за какие-либо убытки или потерю прайвеси, связанные с использованием Ваших данных компанией %appName%. Нажмите \"\"Да\"\", если Вы согласны, или \"\"Нет\"\" - если не согласны.",
+ "line1": "Предост. заправш.",
+ "line2": "разрешения?"
+ },
+ "sv-se": {
+ "tts": "%appName% begär att få tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Om du trycker Ja godkänner du att %vehicleMake% ska hållas skadeslös för alla skador som kan uppstå eller eventuella integritetsintrång som uppstår när %appName% använder dina data. Tryck Ja för att godkänna eller Nej för att neka.",
+ "line1": "Vill du ge",
+ "line2": "tillstånd?"
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri kullanma isteğinde bulunuyor: %functionalGroupLabels%. Evet'e basarsanız, %appName%'in verilerinizi kullanması sonucunda oluşabilecek hasarlardan veya gizlilik kaybından %vehicleMake%'in sorumlu olmayacağını kabul etmiş olacaksınız. Lütfen kabul etmek için Evet'e veya reddetmek için Hayır'a basın.",
+ "line1": "İstenen izinler",
+ "line2": "verilsin mi?"
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求使用下列车辆信息和权限: %functionalGroupLabels%。如果您按“是”,则表示您同意。 %vehicleMake% 将不会对因 %appName% 使用您的数据而引起的任何损毁或隐私损失负责。 请按“是”允许或按“否”拒绝。",
+ "line1": "是否允许请求的",
+ "line2": "权限?"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。按「是」,表示您同意,如因 %appName% 使用您的資料導致任何損害或損失,%vehicleMake% 將不負賠償責任。同意請按「是」,拒絕請按「否」。",
+ "line1": "允許",
+ "line2": "授權請求?"
+ }
+ }
+ },
+ "AppPermissionsHelp": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% fordert folgende Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Im Einstellungsmenü der mobilen Apps können Sie diese Berechtigungen ändern und sich detaillierte Beschreibungen anhören. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press yes to grant permissions or no to deny."
+ },
+ "es-en": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando los siguientes permisos e información del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y escuchar descripciones detalladas en el menú de configuración de la aplicación móvil. Pulse sí para conceder el permiso o no para denegarlo."
+ },
+ "es-mx": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "it-it": {
+ "tts": "%appName% richiede le seguenti informazioni e autorizzazioni riguardo il veicolo: %functionalGroupLabels%. È possibile modificare tali autorizzazioni e ascoltare descrizioni dettagliate nel menu impostazioni delle app mobili. Premere Sì per concedere le autorizzazioni e No per negarle."
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. U kunt deze toestemmingen wijzigen en gedetailleerde beschrijvingen beluisteren in het instellingenmenu voor mobiele apps. Druk op Ja om permissies te verlenen of op Nee om te weigeren."
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz zezwoleń: %functionalGroupLabels%. W menu ustawień aplikacji mobilnych można zmienić owe zezwolenia i usłyszeć ich szczegółowy opis. Naciśnij TAK, aby wyrazić zgodę lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando as seguintes informações e permissões do veículo: %functionalGroupLabels%. Você pode alterar estas permissões e ouvir descrições detalhadas no menu de configurações de aplicativos móveis. Pressione sim para conceder as permissões ou não para negar."
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar as seguintes informações e permissões do veículo: %functionalGroupLabels%. Pode alterar estas permissões e ouvir descrições detalhadas no menu de definições das aplicações móveis. Prima \"\"Sim\"\" para permitir ou \"\"Não\"\" para recusar."
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Вы можете изменить эти разрешения и прослушать подробные их описания в меню настроек мобильного приложения. Нажмите \"\"да\"\", чтобы предоставить разрешения, или \"\"нет\"\", чтобы не предоставлять."
+ },
+ "sv-se": {
+ "tts": "%appName% begär tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Du kan ändra tillstånden och höra detaljerade beskrivningar i menyn för mobilappsinställningar. Tryck Ja för att ge tillstånd eller Nej för att neka."
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri istiyor: %functionalGroupLabels%. Bu izinleri değiştirebilir ve mobil uygulamalar ayarlar menüsünden ayrıntılı açıklamaları dinleyebilirsiniz. Lütfen izin vermek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求下列车辆信息和权限: %functionalGroupLabels%。您可在移动应用程序设置菜单中更改这些权限,并听取详细说明。请按“是”允许权限或按“否”拒绝。"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。您可在行動應用程式設定清單中更改這些許可,並聆聽詳細說明。給予許可請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsRevoked": {
+ "languages": {
+ "de-de": {
+ "tts": "Die Autorisierungsdaten der App wurden geändert. %appName% hat keinen Zugriff auf %functionalGroupLabels% mehr. Installieren Sie die neueste Version der App auf Ihrem Gerät.."
+ },
+ "en-au": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-gb": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-ie": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-us": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "es-en": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "es-es": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de que tiene la versión más reciente de la aplicación instalada en su dispositivo móvil."
+ },
+ "es-mx": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "fr-ca": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "fr-fr": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "it-it": {
+ "tts": "Le autorizzazioni dell'app sono cambiate. %appName% non è più in grado di accedere a %functionalGroupLabels%. Assicurarsi di avere la versione più recente dell'app installata sul dispositivo mobile."
+ },
+ "nl-nl": {
+ "tts": "De app-autorisaties zijn gewijzigd. %appName% heeft geen toegang meer tot %functionalGroupLabels%. Zorg ervoor dat u de meest recente app-versie op uw mobiele apparaat geïnstalleerd hebt."
+ },
+ "pl-pl": {
+ "tts": "Dane dostępu aplikacji zostały zmienione. %appName% nie ma już dostępu do %functionalGroupLabels%. Sprawdź, czy na telefonie komórkowym zainstalowano najnowszą wersję aplikacji."
+ },
+ "pt-br": {
+ "tts": "As autorizações dos aplicativos foram alteradas. %appName% não pode mais acessar %functionalGroupLabels%. Certifique-se de que a versão mais recente do aplicativo está instalada no seu dispositivo móvel."
+ },
+ "pt-pt": {
+ "tts": "As autorizações das aplicações mudaram. %appName% já não consegue aceder a %functionalGroupLabels%. Certifique-se de que tem a última versão da aplicação no seu dispositivo móvel."
+ },
+ "ru-ru": {
+ "tts": "Авторизации приложения изменены. %appName% больше не имеет доступа к %functionalGroupLabels%. Убедитесь, что на вашем мобильном устройстве установлена самая новая версия приложения."
+ },
+ "sv-se": {
+ "tts": "Appens behörigheter har ändrats. %appName% har inte längre åtkomst till %functionalGroupLabels%. Kontrollera att du har installerat den senaste versionen av appen på mobilenheten."
+ },
+ "tr-tr": {
+ "tts": "Uygulama yetkileri değişti. %appName% artık %functionalGroupLabels%'e erişemeyecek. Lütfen mobil aygıtınızda en son uygulama sürümünün yüklü olduğundan emin olun."
+ },
+ "zh-cn": {
+ "tts": "应用程序授权已变更。 %appName% 将不能再访问 %functionalGroupLabels%。 请确认您的移动设备上安装的应用程序是最新版本。"
+ },
+ "zh-tw": {
+ "tts": "應用程式授權已改變。%appName% 已無法進入 %functionalGroupLabels%。請確認您的行動裝置上安裝了最新版應用程式。"
+ }
+ }
+ },
+ "AppUnauthorized": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% ist nicht autorisiert und wird nicht mit SYNC funktionieren.",
+ "line1": "nicht autorisiert"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized",
+ "textBody": "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "Not Authorized",
+ "textBody": "This version of %appName% is no longer authorized to work with AppLink. Please update to the latest version of %appName%."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada",
+ "textBody": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no está autorizada y no funcionará con SYNC.",
+ "line1": "No autorizada"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada"
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée",
+ "textBody": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è autorizzata e non funziona con il SYNC.",
+ "line1": "non autorizzata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% is niet geautoriseerd en werkt niet met SYNC.",
+ "line1": "niet geautoriseerd"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie posiada autoryzacji i nie będzie działać z SYNC.",
+ "line1": "brak autoryzacji"
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não tem autorização e não funcionará com o SYNC.",
+ "line1": "não autorizado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não está autorizada e não funcionará com o SYNC.",
+ "line1": "não autorizada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не авторизирована и не будет работать с SYNC.",
+ "line1": "не авторизировано"
+ },
+ "sv-se": {
+ "tts": "Den här versionen av %appName% är inte godkänd och fungerar inte med SYNC.",
+ "line1": "är ej godkänd"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümüne izin verilmediğinden SYNC ile çalışamaz.",
+ "line1": "için izin yok"
+ },
+ "zh-cn": {
+ "tts": "此版本的%appName% 未得到授权,无法在SYNC上使用。",
+ "line1": "未得到授权"
+ },
+ "zh-tw": {
+ "tts": "%appName% 的版本未獲得授權,將無法透過 SYNC 使用。",
+ "line1": "無授權"
+ }
+ }
+ },
+ "AppUnsupported": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% wird von SYNC nicht unterstützt.",
+ "line1": "nicht unterstützt"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported",
+ "textBody": "This version of %appName% is not supported by SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "Not Supported",
+ "textBody": "Your version of %appName% is not supported by SYNC."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible",
+ "textBody": "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "No compatible"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible"
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible",
+ "textBody": "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è supportata dal SYNC.",
+ "line1": "non supportata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% wordt niet ondersteund door SYNC.",
+ "line1": "niet ondersteund"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie jest obsługiwana przez system SYNC.",
+ "line1": "aplikacja nie obsług."
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não é suportada pelo SYNC.",
+ "line1": "não suportado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não é suportado pelo SYNC.",
+ "line1": "não suportada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не поддерживается SYNC.",
+ "line1": "не поддерживается"
+ },
+ "sv-se": {
+ "tts": "SYNC har inte stöd för den här versionen av %appName%.",
+ "line1": "stöds ej"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümü SYNC tarafından desteklenmiyor.",
+ "line1": "desteklenmiyor"
+ },
+ "zh-cn": {
+ "tts": "SYNC不支持此版本的%appName%。",
+ "line1": "不受支持"
+ },
+ "zh-tw": {
+ "tts": "SYNC 不支援此版本的%appName% 。",
+ "line1": "不支援"
+ }
+ }
+ },
+ "DataConsent": {
+ "languages": {
+ "en-gb": {
+ "textBody": "Would you like to enable Mobile Apps on SYNC? To use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S. Updates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "en-us": {
+ "line1": "Enable Mobile Apps",
+ "line2": "on SYNC? (Uses Data)",
+ "textBody": "Would you like to enable Mobile Apps on SYNC?\n\nTo use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S.\n\nUpdates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "es-en": {
+ "textBody": "Para usar aplicaciones móviles con SYNC, este debe comunicarse con Ford al menos una vez al mes a través del plan de datos de su dispositivo móvil. Pueden aplicar tarifas normales. SYNC enviará su VIN y el número de módulo de SYNC a Ford de Estados Unidos de América. Las actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario. /r Presione Sí para permitir y No para denegar."
+ },
+ "fr-ca": {
+ "textBody": "Pour utiliser AppLink, SYNC devra communiquer avec Ford au moins une fois par mois en utilisant le forfait de données de votre appareil mobile. Les tarifs réguliers peuvent s’appliquer. SYNC enverra votre NIV et le numéro de votre module SYNC à Ford États-Unis. Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements. /r Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ }
+ }
+ },
+ "DataConsentHelp": {
+ "languages": {
+ "en-us": {
+ "textBody": "Updates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. See your Owner Guide for more information."
+ },
+ "es-en": {
+ "textBody": "Las actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario."
+ },
+ "fr-ca": {
+ "textBody": "Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements."
+ }
+ }
+ },
+ "DisableApps": {
+ "languages": {
+ "de-de": {
+ "tts": "Ausschalten der automatischen Updates führt zum Ausschalten von SYNC mobile Apps. Sie können Ihre mobilen Apps dann nicht mehr mit SYNC nutzen. Bitte drücken Sie Ja zur Bestätigung oder Nein, um abzubrechen.",
+ "line1": "Auto-Update",
+ "line2": "und Mobile Apps deaktivieren"
+ },
+ "en-au": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-gb": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-ie": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-us": {
+ "tts": "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel.",
+ "line1": "Disable Auto-Updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel."
+ },
+ "es-en": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?",
+ "textBody": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "es-es": {
+ "tts": "Si desactiva las actualizaciones automáticas, también se desactivará la sincronización de las aplicaciones móviles. No podrá utilizar ninguna aplicación móvil con SYNC. Pulse sí para confirmar o no para cancelar.",
+ "line1": "¿Desact. actual. auto",
+ "line2": "y apl. móviles?"
+ },
+ "es-mx": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?"
+ },
+ "fr-ca": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?",
+ "textBody": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "fr-fr": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?"
+ },
+ "it-it": {
+ "tts": "Disabilitando gli aggiornamenti automatici si disattiva anche la sincronizzazione delle app mobili. Non sarà possibile usare app mobili con il SYNC. Premere Sì per confermare e No per cancellare.",
+ "line1": "Disabilitare agg. aut.",
+ "line2": "e app mobili?"
+ },
+ "nl-nl": {
+ "tts": "Door automatische updates uit te schakelen, schakelt u ook SYNC-mobiele apps uit. U kunt dan geen mobiele apps meer gebruiken met SYNC. Druk op Ja om te bevestigen of op Nee om te annuleren.",
+ "line1": "Auto-updates en mob.",
+ "line2": "apps uitschakelen?"
+ },
+ "pl-pl": {
+ "tts": "Wyłączenie automatycznych aktualizacji spowoduje także wyłączenie aplikacji mobilnych SYNC. Korzystanie z mobilnych aplikacji za pomocą SYNC będzie niemożliwe. Naciśnij TAK, by potwierdzić lub NIE, by anulować.",
+ "line1": "Wył. automat. aktual.",
+ "line2": "i aplikacje mobilne?"
+ },
+ "pt-br": {
+ "tts": "Se as atualizações automáticas forem desativadas, os aplicativos também serão desativados. Você não poderá usar nenhum aplicativo com o SYNC. Pressione sim para confirmar ou não para cancelar.",
+ "line1": "Desativar atualizações",
+ "line2": "autom. e aplicativos?"
+ },
+ "pt-pt": {
+ "tts": "A desactivação das actualizações automáticas desactiva igualmente as aplicações móveis do SYNC. Não poderá utilizar quaisquer aplicações móveis com o SYNC. Prima \"\"Sim\"\" para confirmar ou \"\"Não\"\" para cancelar.",
+ "line1": "Desact. actual. autom.",
+ "line2": "e aplicações móveis?"
+ },
+ "ru-ru": {
+ "tts": "При отключении автоматических обновлений также будут отключены мобильные приложения sync. Вы не сможете использовать какие-либо мобильные приложения с SYNC. Нажмите \"\"Да\"\" для подтверждения или \"\"Нет\"\" для отмены.",
+ "line1": "Откл. автообновления",
+ "line2": "и мобил. прилож.?"
+ },
+ "sv-se": {
+ "tts": "Om du avaktiverar automatisk uppdatering avaktiverar du även synkning av mobilappar. Du kommer inte längre att kunna använda dina mobilappar med SYNC. Tryck Ja för att bekräfta eller Nej för att avbryta.",
+ "line1": "Avaktiverar autouppdat.",
+ "line2": "och mobilappar?"
+ },
+ "tr-tr": {
+ "tts": "Otomatik güncellemeleri devre dışı bırakırsanız sync mobil uygulamalar da devre dışı kalır. SYNC ile mobil uygulama kullanmanız mümkün olmaz. Lütfen onaylamak için Evet'e veya iptal etmek için Hayır'a basın.",
+ "line1": "Oto. güncelleme ve",
+ "line2": "mobil uygul. kapat?"
+ },
+ "zh-cn": {
+ "tts": "禁用自动更新同时也会禁用SYNC移动应用程序。您将无法在 SYNC 中使用任何移动应用程序。请按“是”确认或按“否”取消。",
+ "line1": "是否禁用自动更新和",
+ "line2": "移动应用程序?"
+ },
+ "zh-tw": {
+ "tts": "停用自動更新也將停用 sync 行動應用程式。您將無法透過 SYNC 使用任何行動應用程式。確認請按「是」,取消請按「否」。",
+ "line1": "停用自動更新",
+ "line2": "和行動應用程式?"
+ }
+ }
+ },
+ "DrivingCharacteristics": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahreigenschaften: Kraftstoffverbrauch, MyKey, Sicherheitsgurtstatus.",
+ "label": "Fahreigenschaften"
+ },
+ "en-au": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-gb": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-ie": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-us": {
+ "tts": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status.",
+ "label": "Driving Characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo",
+ "textBody": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a las siguientes características de conducción: Consumo de combustible, MyKey, Estado cinturones de seguridad.",
+ "label": "Características de conducción"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite",
+ "textBody": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti caratteristiche di guida: Consumo carburante, MyKey, Stato cinture di sicurezza.",
+ "label": "Caratteristiche di guida"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende rijkenmerken: Brandstofverbruik, MyKey, Veiligheidsgordelstatus.",
+ "label": "Rijkenmerken"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji dotyczących jazdy: Zużycie paliwa, MyKey, Stan pasów bezpieczeństwa.",
+ "label": "Informacje dotyczące stylu jazdy"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes características de condução: Consumo de combustível, MyKey, Estado do cinto de segurança.",
+ "label": "Características de condução"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações de condução: Consumo de combustível, MyKey, Estado dos cintos de segurança.",
+ "label": "Características de condução"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим характеристикам движения: Расход топлива, MyKey, Состояние ремней безопасности.",
+ "label": "Характеристики движения"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande köregenskaper: Bränsleförbrukning, MyKey, Bältesstatus.",
+ "label": "Köregenskaper"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu sürüş karakteristiklerine erişebilir: Yakıt tüketimi, MyKey, Emniyet kemeri durumu.",
+ "label": "Sürüş karakteristikleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列行驶特性: 油耗, MyKey, 安全带状态",
+ "label": "行驶特性"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取以下駕駛特性: 油耗, MyKey, 安全帶狀態",
+ "label": "駕駛特性"
+ }
+ }
+ },
+ "Location": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die GPS-Daten und die Geschwindigkeit des Fahrzeugs.",
+ "label": "GPS und Geschwindigkeit"
+ },
+ "en-au": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-gb": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "en-ie": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-us": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad",
+ "textBody": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder al GPS y la velocidad del vehículo.",
+ "label": "GPS y velocidad"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse",
+ "textBody": "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso a GPS e velocità del veicolo.",
+ "label": "GPS e velocità"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot gps en de snelheid van het voertuig.",
+ "label": "Gps en snelheid"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do modułu GPS i prędkości pojazdu.",
+ "label": "GPS i prędkość"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar o GPS e a velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder ao GPS e à velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к GPS и скорости автомобиля.",
+ "label": "GPS и скорость"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt fordonets GPS och hastighetsmätare.",
+ "label": "GPS och hastighet"
+ },
+ "tr-tr": {
+ "tts": "Bu uygulama aracın GPS ve hız bilgilerine erişebilir.",
+ "label": "GPS ve hız"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可以访问车辆 GPS 和车速信息。",
+ "label": "GPS 和车速"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取車輛的GPS和速度。",
+ "label": "GPS和車速"
+ }
+ }
+ },
+ "Notifications": {
+ "languages": {
+ "de-de": {
+ "tts": "Läuft die App im Hintergrund, kann Sie Benachrichtigungen senden.",
+ "label": "Push-Benachrichtigungen"
+ },
+ "en-au": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-gb": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "en-ie": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-us": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push",
+ "textBody": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede enviar notificaciones cuando se está ejecutando en segundo plano.",
+ "label": "Notificaciones push"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push"
+ },
+ "fr-ca": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications instantanées",
+ "textBody": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "fr-fr": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications push"
+ },
+ "it-it": {
+ "tts": "Un'app può inviare notifiche se eseguita in background.",
+ "label": "Notifiche push"
+ },
+ "nl-nl": {
+ "tts": "Een app kan meldingen versturen als deze op de achtergrond actief is.",
+ "label": "Push-meldingen"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może wysyłać powiadomienia, działając w tle.",
+ "label": "Powiadomienia Push"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode enviar notificações quando estiver sendo executado em segundo plano.",
+ "label": "Notificações Push"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue enviar notificações quando está activa em segundo plano.",
+ "label": "Notificações push"
+ },
+ "ru-ru": {
+ "tts": "Если приложение работает в фоновом режиме, оно может отправлять оповещения.",
+ "label": "Оповещения о пересылке"
+ },
+ "sv-se": {
+ "tts": "Appen kan skicka meddelanden när den körs i bakgrunden.",
+ "label": "Push-notiser"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama arka planda çalışırken bildirim gönderebilir.",
+ "label": "Anlık bildirimleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序在后台运行时可推送通知。",
+ "label": "推送通知"
+ },
+ "zh-tw": {
+ "tts": "車輛行進時,應用程式可在背景中傳送通知。",
+ "label": "傳送通知"
+ }
+ }
+ },
+ "SettingDisableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Updates deakt."
+ },
+ "en-au": {
+ "line1": "Disable updates"
+ },
+ "en-gb": {
+ "line1": "Disable updates"
+ },
+ "en-ie": {
+ "line1": "Disable updates"
+ },
+ "en-us": {
+ "line1": "Disable Updates",
+ "textBody": "Disable Updates"
+ },
+ "es-en": {
+ "line1": "Deshab. actual.",
+ "textBody": "Deshab. actual."
+ },
+ "es-es": {
+ "line1": "Desact. actual."
+ },
+ "es-mx": {
+ "line1": "Deshab. actual."
+ },
+ "fr-ca": {
+ "line1": "Désactiver MAJ",
+ "textBody": "Désactiver MAJ"
+ },
+ "fr-fr": {
+ "line1": "Désactiver màj"
+ },
+ "it-it": {
+ "line1": "Disabilita agg."
+ },
+ "nl-nl": {
+ "line1": "Upd. uitschak."
+ },
+ "pl-pl": {
+ "line1": "Wyłącz aktual."
+ },
+ "pt-br": {
+ "line1": "Desat. atualiz."
+ },
+ "pt-pt": {
+ "line1": "Desact. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Откл. обновл."
+ },
+ "sv-se": {
+ "line1": "Inaktivera uppd."
+ },
+ "tr-tr": {
+ "line1": "Güncell. Kapat"
+ },
+ "zh-cn": {
+ "line1": "禁用更新"
+ },
+ "zh-tw": {
+ "line1": "停用更新"
+ }
+ }
+ },
+ "SettingEnableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Apps aktivieren"
+ },
+ "en-au": {
+ "line1": "Enable Apps"
+ },
+ "en-gb": {
+ "line1": "Enable Apps"
+ },
+ "en-ie": {
+ "line1": "Enable Apps"
+ },
+ "en-us": {
+ "line1": "Enable Apps"
+ },
+ "es-en": {
+ "line1": "Hab. aplic."
+ },
+ "es-es": {
+ "line1": "Activar apl."
+ },
+ "es-mx": {
+ "line1": "Hab. aplic."
+ },
+ "fr-ca": {
+ "line1": "Activer app.",
+ "textBody": "Activer app."
+ },
+ "fr-fr": {
+ "line1": "Activer app."
+ },
+ "it-it": {
+ "line1": "Abilita app"
+ },
+ "nl-nl": {
+ "line1": "Apps inschak."
+ },
+ "pl-pl": {
+ "line1": "Włącz aplikacje"
+ },
+ "pt-br": {
+ "line1": "Ativar aplic."
+ },
+ "pt-pt": {
+ "line1": "Activar actualiz."
+ },
+ "ru-ru": {
+ "line1": "Вкл. прилож."
+ },
+ "sv-se": {
+ "line1": "Aktivera appar"
+ },
+ "tr-tr": {
+ "line1": "Uygulamaları aç"
+ },
+ "zh-cn": {
+ "line1": "启用应用程序"
+ },
+ "zh-tw": {
+ "line1": "啟用應用程式"
+ }
+ }
+ },
+ "SettingUpdateAuto": {
+ "languages": {
+ "de-de": {
+ "line1": "Update anford."
+ },
+ "en-au": {
+ "line1": "Request update"
+ },
+ "en-gb": {
+ "line1": "Request update"
+ },
+ "en-ie": {
+ "line1": "Request update"
+ },
+ "en-us": {
+ "line1": "Request Update",
+ "textBody": "Select `Update now` to receive app authorization information for your SYNC-enabled mobile apps. This may enable additional functionality depending on the app and your settings. If your phone has a working data connection, an update should complete in less than 1 minute."
+ },
+ "es-en": {
+ "line1": "Solicit. actualiz.",
+ "textBody": "Solicit. actualiz."
+ },
+ "es-es": {
+ "line1": "Solicitar actual."
+ },
+ "es-mx": {
+ "line1": "Solicit. actualiz."
+ },
+ "fr-ca": {
+ "line1": "Demander MAJ",
+ "textBody": "Demander MAJ"
+ },
+ "fr-fr": {
+ "line1": "Demander màj"
+ },
+ "it-it": {
+ "line1": "Rich. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Upd. aanvragen"
+ },
+ "pl-pl": {
+ "line1": "Zażądaj aktual."
+ },
+ "pt-br": {
+ "line1": "Solicitar atualiz."
+ },
+ "pt-pt": {
+ "line1": "Solicit. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Запрос на обн."
+ },
+ "sv-se": {
+ "line1": "Begär uppdat."
+ },
+ "tr-tr": {
+ "line1": "Güncelleme iste"
+ },
+ "zh-cn": {
+ "line1": "请求更新"
+ },
+ "zh-tw": {
+ "line1": "請求更新"
+ }
+ }
+ },
+ "StatusNeeded": {
+ "languages": {
+ "de-de": {
+ "line1": "Update benötigt"
+ },
+ "en-au": {
+ "line1": "Update needed"
+ },
+ "en-gb": {
+ "line1": "Update needed",
+ "textBody": "Update needed"
+ },
+ "en-ie": {
+ "line1": "Update needed"
+ },
+ "en-us": {
+ "line1": "Update Needed",
+ "textBody": "Update Needed"
+ },
+ "es-en": {
+ "line1": "Actualiz. neces.",
+ "textBody": "Actualiz. neces."
+ },
+ "es-es": {
+ "line1": "Actu. necesaria"
+ },
+ "es-mx": {
+ "line1": "Actualiz. neces."
+ },
+ "fr-ca": {
+ "line1": "Màj requise",
+ "textBody": "Màj requise"
+ },
+ "fr-fr": {
+ "line1": "Mise à jour requise"
+ },
+ "it-it": {
+ "line1": "Necess. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Update nodig"
+ },
+ "pl-pl": {
+ "line1": "Potrzeba aktual."
+ },
+ "pt-br": {
+ "line1": "Atualiz. necess."
+ },
+ "pt-pt": {
+ "line1": "Actual. necess."
+ },
+ "ru-ru": {
+ "line1": "Необх. обновл."
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs"
+ },
+ "tr-tr": {
+ "line1": "Güncellenmeli"
+ },
+ "zh-cn": {
+ "line1": "需要进行更新"
+ },
+ "zh-tw": {
+ "line1": "需更新"
+ }
+ }
+ },
+ "StatusPending": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktualisieren..."
+ },
+ "en-au": {
+ "line1": "Updating..."
+ },
+ "en-gb": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "en-ie": {
+ "line1": "Updating..."
+ },
+ "en-us": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "es-en": {
+ "line1": "Actualizando...",
+ "textBody": "Actualizando..."
+ },
+ "es-es": {
+ "line1": "Actualizando..."
+ },
+ "es-mx": {
+ "line1": "Actualizando..."
+ },
+ "fr-ca": {
+ "line1": "MAJ en cours...",
+ "textBody": "MAJ en cours..."
+ },
+ "fr-fr": {
+ "line1": "Màj en cours..."
+ },
+ "it-it": {
+ "line1": "Aggiornamento"
+ },
+ "nl-nl": {
+ "line1": "Updaten..."
+ },
+ "pl-pl": {
+ "line1": "Aktualizowanie"
+ },
+ "pt-br": {
+ "line1": "Atualizando..."
+ },
+ "pt-pt": {
+ "line1": "A actualizar..."
+ },
+ "ru-ru": {
+ "line1": "Обновление..."
+ },
+ "sv-se": {
+ "line1": "Uppdaterar..."
+ },
+ "tr-tr": {
+ "line1": "Güncelleniyor..."
+ },
+ "zh-cn": {
+ "line1": "正在更新......"
+ },
+ "zh-tw": {
+ "line1": "更新中..."
+ }
+ }
+ },
+ "StatusUpToDate": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktuelle Version"
+ },
+ "en-au": {
+ "line1": "Up-to-date"
+ },
+ "en-gb": {
+ "line1": "Up-to-date",
+ "textBody": "Up-to-date"
+ },
+ "en-ie": {
+ "line1": "Up-to-date"
+ },
+ "en-us": {
+ "line1": "Up-To-Date",
+ "textBody": "Up-To-Date"
+ },
+ "es-en": {
+ "line1": "Actualizado",
+ "textBody": "Actualizado"
+ },
+ "es-es": {
+ "line1": "Actualizada"
+ },
+ "es-mx": {
+ "line1": "Actualizado"
+ },
+ "fr-ca": {
+ "line1": "Déjà à jour",
+ "textBody": "Déjà à jour"
+ },
+ "fr-fr": {
+ "line1": "Déjà à jour"
+ },
+ "it-it": {
+ "line1": "più recente"
+ },
+ "nl-nl": {
+ "line1": "Up-to-date"
+ },
+ "pl-pl": {
+ "line1": "Aktualne"
+ },
+ "pt-br": {
+ "line1": "Atualizado"
+ },
+ "pt-pt": {
+ "line1": "Actualizado"
+ },
+ "ru-ru": {
+ "line1": "Обновлено"
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs ej"
+ },
+ "tr-tr": {
+ "line1": "Güncel"
+ },
+ "zh-cn": {
+ "line1": "最新更新"
+ },
+ "zh-tw": {
+ "line1": "更新最新"
+ }
+ }
+ },
+ "VehicleInfo": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahrzeuginformationen: Kraftstoff-Füllstand, Kraftstoffverbrauch, Motordrehzahl, Kilometerzähler, FIN, Außentemperatur, Gangstellung, Reifenluftdruck.",
+ "label": "Fahrzeuginformationen"
+ },
+ "en-au": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-gb": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure."
+ },
+ "en-ie": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-us": {
+ "tts": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo",
+ "textBody": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a la siguiente información del vehículo: Nivel de combustible, Ahorro de combustible, RPM del motor, Cuentakilómetros, VIN, Temperatura aire exterior, Marcha engranada, Presión de neumáticos.",
+ "label": "Información del vehículo"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus.",
+ "label": "Renseignements du véhicule",
+ "textBody": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Vitesse de moteur, Compteur kilométrique, NIV, Température extérieure, Position de vitesse, Pression des pneus.",
+ "label": "Renseignements du véhicule"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti informazioni del veicolo: Livello carburante, Consumi carburante, Numero giri motore, Contachilometri, VIN, Temperatura esterna, Posizione marcia, Pressione pneumatici.",
+ "label": "Informazioni sul veicolo"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende voertuiginformatie: Brandstofpeil, Brandstofverbruik, Motortoerental, Kilometerteller, VIN, Buitentemperatuur, Versnellingsstand, Bandenspanning.",
+ "label": "Voertuiginformatie"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji o pojeździe: Poziom paliwa, Zużycie paliwa, Obroty silnika, Licznik przebiegu, Numer VIN, Temperatura zewnętrzna, Aktualny bieg, Ciśnienie opon.",
+ "label": "Informacje o pojeździe"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes informações sobre o veículo: Nível de combustível, Economia de combustível, RPM do motor, Hodômetro, VIN, Temperatura externa, Posição das marchas, Pressão dos pneus.",
+ "label": "Informações sobre o veículo"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações do veículo: Nível de combustível, Poupança de combustível, RPM do motor, Conta-quilómetros, VIN, Temperatura exterior, Posição da mudança de velocidade, Pressão dos pneus.",
+ "label": "Informações do veículo"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим данным автомобиля: Уровень топлива, Економия топлива, Число оборотов двигателя, Одометр, Номер VIN, Температура за бортом, Положение передачи, Давление шин.",
+ "label": "Информация об автомобиле"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande fordonsinformation: Bränslenivå, Bränsleekonomi, Motorns varvtal, Vägmätare, VIN, Utetemperatur, Växelläge, Däcktryck.",
+ "label": "Fordonsinformation"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu araç bilgilerine erişebilir: Yakıt seviyesi, Yakıt ekonomisi, Motor devirleri, Kilometre sayacı, VIN, Dış sıcaklık, Vites konumu, Lastik basıncı.",
+ "label": "Araç bilgisi"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列车辆信息 : 燃油量, 燃油经济性, 发动机转速(RPM), 里程表, VIN, 车外温度, 档位, 胎压.",
+ "label": "车辆信息"
+ },
+ "zh-tw": {
+ "tts": "一個應用程式可存取以下車輛資訊 : 燃油存量, 燃油經濟性, 引擎轉速, 里程表, 車輛識別號碼, 車外溫度, 檔位, 胎壓.",
+ "label": "車輛資訊"
+ }
+ }
+ }
+ }
+ },
+ "app_policies": {
+ "default": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["Base-4"],
+ "RequestType": [
+ "QUERY_APPS",
+ "LAUNCH_APP",
+ "PROPRIETARY"
+ ]
+ },
+ "device": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["DataConsent-2"]
+ },
+ "pre_DataConsent": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["BaseBeforeDataConsent"],
+ "RequestType": ["HTTP"]
+ }
+ }
+ }
+ }
diff --git a/src/components/application_manager/test/sdl_pt_update.json b/src/components/application_manager/test/sdl_pt_update.json
new file mode 100644
index 0000000000..a332f92382
--- /dev/null
+++ b/src/components/application_manager/test/sdl_pt_update.json
@@ -0,0 +1,1722 @@
+{
+ "policy_table" : {
+ "app_policies" : {
+ "1766825573" : {
+ "AppHMIType" : [ "MEDIA" ],
+ "certificate" : "akdjfhaliuygrglurng",
+ "default_hmi" : "BACKGROUND",
+ "groups" : [
+ "Notifications",
+ "Location-1",
+ "PropriataryData-1",
+ "Navigation-1",
+ "Base-4",
+ "VehicleInfo-3",
+ "DrivingCharacteristics-3",
+ "Emergency-1"
+ ],
+ "keep_context" : true,
+ "memory_kb" : 1000,
+ "nicknames" : [ "SyncProxyTester" ],
+ "priority" : "EMERGENCY",
+ "steal_focus" : true,
+ "watchdog_timer_ms" : 20000
+ },
+ "default" : {
+ "default_hmi" : "NONE",
+ "groups" : [ "Base-4" ],
+ "keep_context" : false,
+ "memory_kb" : 1000,
+ "priority" : "NONE",
+ "steal_focus" : false,
+ "watchdog_timer_ms" : 20000
+ },
+ "device" : {
+ "default_hmi" : "NONE",
+ "groups" : [ "Base-4" ],
+ "memory_kb" : 1000,
+ "watchdog_timer_ms" : 20000,
+ "keep_context" : false,
+ "priority" : "NONE",
+ "steal_focus" : false
+ },
+ "pre_DataConsent" : {
+ "default_hmi" : "NONE",
+ "groups" : [ "pre_Base-1" ],
+ "keep_context" : false,
+ "memory_kb" : 1000,
+ "priority" : "NONE",
+ "steal_focus" : false,
+ "watchdog_timer_ms" : 20000
+ }
+ },
+ "consumer_friendly_messages" : {
+ "messages" : {
+ "AppPermissions" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Zugriffsanfrage(n)",
+ "line2" : "erlauben?",
+ "tts" : "%appName% benötigt die folgenden Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Wenn Sie Ja drücken, erklären Sie sich damit einverstanden, dass %vehicleMake% nicht für Schäden oder Verletzungen der Privatsphäre haftet, die im Zusammenhang mit der Nutzung Ihrer Benutzerdaten durch %appName% entstehen. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au" : {
+ "line1" : "Grant requested",
+ "line2" : "permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny."
+ },
+ "en-gb" : {
+ "line1" : "Grant requested",
+ "line2" : "permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny."
+ },
+ "en-ie" : {
+ "line1" : "Grant requested",
+ "line2" : "permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny."
+ },
+ "en-us" : {
+ "line1" : "Grant Requested",
+ "line2" : "Permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press yes to allow or no to deny."
+ },
+ "es-en" : {
+ "line1" : "¿Otorgar permiso(s)",
+ "line2" : "solicitado(s)?",
+ "tts" : "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar."
+ },
+ "es-es" : {
+ "line1" : "¿Conceder permisos",
+ "line2" : "solicitados?",
+ "tts" : "%appName% está solicitando el uso de los siguientes permisos e información del vehículo: %functionalGroupLabels%. Si pulsa sí, acepta que %vehicleMake% no será responsable de los daños o la pérdida de privacidad relacionados con el uso de sus datos por parte de %appName%. Pulse sí para permitir o no para denegar."
+ },
+ "es-mx" : {
+ "line1" : "¿Otorgar permiso(s)",
+ "line2" : "solicitado(s)?",
+ "tts" : "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar."
+ },
+ "fr-ca" : {
+ "line1" : "Accorder permission(s)",
+ "line2" : "demandée(s)",
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ },
+ "fr-fr" : {
+ "line1" : "Accorder permission(s)",
+ "line2" : "demandée(s)",
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ },
+ "it-it" : {
+ "line1" : "Concedi autorizzaz.",
+ "line2" : "richiesta(e)?",
+ "tts" : "%appName% richiede l'uso delle seguenti informazioni e autorizzazioni sul veicolo: %functionalGroupLabels%. Se si preme Sì, si acconsente che %vehicleMake% non sarà responsabile per danni o perdita di privacy in relazione all'impiego dei dati da parte di %appName%. Premere Sì per consentire e No per negare."
+ },
+ "nl-nl" : {
+ "line1" : "Aangevraagde",
+ "line2" : "permissie(s) verlenen?",
+ "tts" : "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. Als u op Ja drukt, gaat u ermee akkoord dat %vehicleMake% in geen geval aansprakelijk gesteld kan worden voor schade of verlies van privacy als gevolg van het feit dat %appName% gebruik maakt van uw gegevens. Druk op Ja om dit toe te staan of Nee om te weigeren."
+ },
+ "pl-pl" : {
+ "line1" : "Udzielić żądanych",
+ "line2" : "pozwoleń?",
+ "tts" : "%appName% wymaga następujących informacji o pojeździe oraz pozwoleń: %functionalGroupLabels%. Naciśnięcie TAK oznacza zgodę na fakt, iż %vehicleMake% nie będzie ponosić odpowiedzialności za szkody ani utratę prywatności w związku z wykorzystaniem przez %appName% danych, należących do użytkownika. Naciśnij TAK w celu udzielenia zgody lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br" : {
+ "line1" : "Conceder permissão",
+ "line2" : "solicitada?",
+ "tts" : "%appName% está solicitando o uso das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se pressionar sim, você concorda que a %vehicleMake% não será responsável por danos ou perdas de privacidade relacionados ao uso dos seus dados por %appName%. Pressione sim para permitir ou não para negar."
+ },
+ "pt-pt" : {
+ "line1" : "Conceder permiss.",
+ "line2" : "solicitada(s)?",
+ "tts" : "%appName% está a solicitar a utilização das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se premir “Sim”, concorda que %vehicleMake% não será responsável por quaisquer danos ou perda de privacidade relacionada com a utilização dos seus dados por parte de %appName%. Prima “Sim” para permitir ou “Não” para recusar."
+ },
+ "ru-ru" : {
+ "line1" : "Предост. заправш.",
+ "line2" : "разрешения?",
+ "tts" : "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Нажатием \"\"да\"\", Вы соглашаетесь, что %vehicleMake% не будет нести ответственность за какие-либо убытки или потерю прайвеси, связанные с использованием Ваших данных компанией %appName%. Нажмите \"\"Да\"\", если Вы согласны, или \"\"Нет\"\" - если не согласны."
+ },
+ "sv-se" : {
+ "line1" : "Vill du ge",
+ "line2" : "tillstånd?",
+ "tts" : "%appName% begär att få tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Om du trycker Ja godkänner du att %vehicleMake% ska hållas skadeslös för alla skador som kan uppstå eller eventuella integritetsintrång som uppstår när %appName% använder dina data. Tryck Ja för att godkänna eller Nej för att neka."
+ },
+ "tr-tr" : {
+ "line1" : "İstenen izinler",
+ "line2" : "verilsin mi?",
+ "tts" : "%appName%, şu araç bilgilerini ve izinleri kullanma isteğinde bulunuyor: %functionalGroupLabels%. Evet'e basarsanız, %appName%'in verilerinizi kullanması sonucunda oluşabilecek hasarlardan veya gizlilik kaybından %vehicleMake%'in sorumlu olmayacağını kabul etmiş olacaksınız. Lütfen kabul etmek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn" : {
+ "line1" : "是否允许请求的",
+ "line2" : "权限?",
+ "tts" : "%appName% 正在请求使用下列车辆信息和权限: %functionalGroupLabels%。如果您按“是”,则表示您同意。 %vehicleMake% 将不会对因 %appName% 使用您的数据而引起的任何损毁或隐私损失负责。 请按“是”允许或按“否”拒绝。"
+ },
+ "zh-tw" : {
+ "line1" : "允許",
+ "line2" : "授權請求?",
+ "tts" : "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。按「是」,表示您同意,如因 %appName% 使用您的資料導致任何損害或損失,%vehicleMake% 將不負賠償責任。同意請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsHelp" : {
+ "languages" : {
+ "de-de" : {
+ "tts" : "%appName% fordert folgende Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Im Einstellungsmenü der mobilen Apps können Sie diese Berechtigungen ändern und sich detaillierte Beschreibungen anhören. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-gb" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-ie" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-us" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press yes to grant permissions or no to deny."
+ },
+ "es-en" : {
+ "tts" : "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "es-es" : {
+ "tts" : "%appName% está solicitando los siguientes permisos e información del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y escuchar descripciones detalladas en el menú de configuración de la aplicación móvil. Pulse sí para conceder el permiso o no para denegarlo."
+ },
+ "es-mx" : {
+ "tts" : "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "fr-ca" : {
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "fr-fr" : {
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "it-it" : {
+ "tts" : "%appName% richiede le seguenti informazioni e autorizzazioni riguardo il veicolo: %functionalGroupLabels%. È possibile modificare tali autorizzazioni e ascoltare descrizioni dettagliate nel menu impostazioni delle app mobili. Premere Sì per concedere le autorizzazioni e No per negarle."
+ },
+ "nl-nl" : {
+ "tts" : "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. U kunt deze toestemmingen wijzigen en gedetailleerde beschrijvingen beluisteren in het instellingenmenu voor mobiele apps. Druk op Ja om permissies te verlenen of op Nee om te weigeren."
+ },
+ "pl-pl" : {
+ "tts" : "%appName% wymaga następujących informacji o pojeździe oraz zezwoleń: %functionalGroupLabels%. W menu ustawień aplikacji mobilnych można zmienić owe zezwolenia i usłyszeć ich szczegółowy opis. Naciśnij TAK, aby wyrazić zgodę lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br" : {
+ "tts" : "%appName% está solicitando as seguintes informações e permissões do veículo: %functionalGroupLabels%. Você pode alterar estas permissões e ouvir descrições detalhadas no menu de configurações de aplicativos móveis. Pressione sim para conceder as permissões ou não para negar."
+ },
+ "pt-pt" : {
+ "tts" : "%appName% está a solicitar as seguintes informações e permissões do veículo: %functionalGroupLabels%. Pode alterar estas permissões e ouvir descrições detalhadas no menu de definições das aplicações móveis. Prima \"\"Sim\"\" para permitir ou \"\"Não\"\" para recusar."
+ },
+ "ru-ru" : {
+ "tts" : "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Вы можете изменить эти разрешения и прослушать подробные их описания в меню настроек мобильного приложения. Нажмите \"\"да\"\", чтобы предоставить разрешения, или \"\"нет\"\", чтобы не предоставлять."
+ },
+ "sv-se" : {
+ "tts" : "%appName% begär tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Du kan ändra tillstånden och höra detaljerade beskrivningar i menyn för mobilappsinställningar. Tryck Ja för att ge tillstånd eller Nej för att neka."
+ },
+ "tr-tr" : {
+ "tts" : "%appName%, şu araç bilgilerini ve izinleri istiyor: %functionalGroupLabels%. Bu izinleri değiştirebilir ve mobil uygulamalar ayarlar menüsünden ayrıntılı açıklamaları dinleyebilirsiniz. Lütfen izin vermek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn" : {
+ "tts" : "%appName% 正在请求下列车辆信息和权限: %functionalGroupLabels%。您可在移动应用程序设置菜单中更改这些权限,并听取详细说明。请按“是”允许权限或按“否”拒绝。"
+ },
+ "zh-tw" : {
+ "tts" : "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。您可在行動應用程式設定清單中更改這些許可,並聆聽詳細說明。給予許可請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsRevoked" : {
+ "languages" : {
+ "de-de" : {
+ "tts" : "Die Autorisierungsdaten der App wurden geändert. %appName% hat keinen Zugriff auf %functionalGroupLabels% mehr. Installieren Sie die neueste Version der App auf Ihrem Gerät.."
+ },
+ "en-au" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-gb" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-ie" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-us" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "es-en" : {
+ "tts" : "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "es-es" : {
+ "tts" : "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de que tiene la versión más reciente de la aplicación instalada en su dispositivo móvil."
+ },
+ "es-mx" : {
+ "tts" : "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "fr-ca" : {
+ "tts" : "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "fr-fr" : {
+ "tts" : "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "it-it" : {
+ "tts" : "Le autorizzazioni dell'app sono cambiate. %appName% non è più in grado di accedere a %functionalGroupLabels%. Assicurarsi di avere la versione più recente dell'app installata sul dispositivo mobile."
+ },
+ "nl-nl" : {
+ "tts" : "De app-autorisaties zijn gewijzigd. %appName% heeft geen toegang meer tot %functionalGroupLabels%. Zorg ervoor dat u de meest recente app-versie op uw mobiele apparaat geïnstalleerd hebt."
+ },
+ "pl-pl" : {
+ "tts" : "Dane dostępu aplikacji zostały zmienione. %appName% nie ma już dostępu do %functionalGroupLabels%. Sprawdź, czy na telefonie komórkowym zainstalowano najnowszą wersję aplikacji."
+ },
+ "pt-br" : {
+ "tts" : "As autorizações dos aplicativos foram alteradas. %appName% não pode mais acessar %functionalGroupLabels%. Certifique-se de que a versão mais recente do aplicativo está instalada no seu dispositivo móvel."
+ },
+ "pt-pt" : {
+ "tts" : "As autorizações das aplicações mudaram. %appName% já não consegue aceder a %functionalGroupLabels%. Certifique-se de que tem a última versão da aplicação no seu dispositivo móvel."
+ },
+ "ru-ru" : {
+ "tts" : "Авторизации приложения изменены. %appName% больше не имеет доступа к %functionalGroupLabels%. Убедитесь, что на вашем мобильном устройстве установлена самая новая версия приложения."
+ },
+ "sv-se" : {
+ "tts" : "Appens behörigheter har ändrats. %appName% har inte längre åtkomst till %functionalGroupLabels%. Kontrollera att du har installerat den senaste versionen av appen på mobilenheten."
+ },
+ "tr-tr" : {
+ "tts" : "Uygulama yetkileri değişti. %appName% artık %functionalGroupLabels%'e erişemeyecek. Lütfen mobil aygıtınızda en son uygulama sürümünün yüklü olduğundan emin olun."
+ },
+ "zh-cn" : {
+ "tts" : "应用程序授权已变更。 %appName% 将不能再访问 %functionalGroupLabels%。 请确认您的移动设备上安装的应用程序是最新版本。"
+ },
+ "zh-tw" : {
+ "tts" : "應用程式授權已改變。%appName% 已無法進入 %functionalGroupLabels%。請確認您的行動裝置上安裝了最新版應用程式。"
+ }
+ }
+ },
+ "AppUnauthorized" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "nicht autorisiert",
+ "tts" : "Diese Version von %appName% ist nicht autorisiert und wird nicht mit SYNC funktionieren."
+ },
+ "en-au" : {
+ "line1" : "not authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-gb" : {
+ "line1" : "not authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-ie" : {
+ "line1" : "not authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-us" : {
+ "line1" : "Not Authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "es-en" : {
+ "line1" : "no autorizada",
+ "tts" : "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "es-es" : {
+ "line1" : "No autorizada",
+ "tts" : "Esta versión de %appName% no está autorizada y no funcionará con SYNC."
+ },
+ "es-mx" : {
+ "line1" : "no autorizada",
+ "tts" : "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "fr-ca" : {
+ "line1" : "non autorisée",
+ "tts" : "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "fr-fr" : {
+ "line1" : "non autorisée",
+ "tts" : "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "it-it" : {
+ "line1" : "non autorizzata",
+ "tts" : "Questa versione di %appName% non è autorizzata e non funziona con il SYNC."
+ },
+ "nl-nl" : {
+ "line1" : "niet geautoriseerd",
+ "tts" : "Deze versie van %appName% is niet geautoriseerd en werkt niet met SYNC."
+ },
+ "pl-pl" : {
+ "line1" : "brak autoryzacji",
+ "tts" : "Niniejsza wersja %appName% nie posiada autoryzacji i nie będzie działać z SYNC."
+ },
+ "pt-br" : {
+ "line1" : "não autorizado",
+ "tts" : "Esta versão do %appName% não tem autorização e não funcionará com o SYNC."
+ },
+ "pt-pt" : {
+ "line1" : "não autorizada",
+ "tts" : "Esta versão de %appName% não está autorizada e não funcionará com o SYNC."
+ },
+ "ru-ru" : {
+ "line1" : "не авторизировано",
+ "tts" : "Эта версия %appName% не авторизирована и не будет работать с SYNC."
+ },
+ "sv-se" : {
+ "line1" : "är ej godkänd",
+ "tts" : "Den här versionen av %appName% är inte godkänd och fungerar inte med SYNC."
+ },
+ "tr-tr" : {
+ "line1" : "için izin yok",
+ "tts" : "Bu %appName% sürümüne izin verilmediğinden SYNC ile çalışamaz."
+ },
+ "zh-cn" : {
+ "line1" : "未得到授权",
+ "tts" : "此版本的%appName% 未得到授权,无法在SYNC上使用。"
+ },
+ "zh-tw" : {
+ "line1" : "無授權",
+ "tts" : "%appName% 的版本未獲得授權,將無法透過 SYNC 使用。"
+ }
+ }
+ },
+ "AppUnsupported" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "nicht unterstützt",
+ "tts" : "Diese Version von %appName% wird von SYNC nicht unterstützt."
+ },
+ "en-au" : {
+ "line1" : "not supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "en-gb" : {
+ "line1" : "not supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "en-ie" : {
+ "line1" : "not supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "en-us" : {
+ "line1" : "Not Supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "es-en" : {
+ "line1" : "no compatible",
+ "tts" : "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-es" : {
+ "line1" : "No compatible",
+ "tts" : "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-mx" : {
+ "line1" : "no compatible",
+ "tts" : "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "fr-ca" : {
+ "line1" : "incompatible",
+ "tts" : "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "fr-fr" : {
+ "line1" : "incompatible",
+ "tts" : "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "it-it" : {
+ "line1" : "non supportata",
+ "tts" : "Questa versione di %appName% non è supportata dal SYNC."
+ },
+ "nl-nl" : {
+ "line1" : "niet ondersteund",
+ "tts" : "Deze versie van %appName% wordt niet ondersteund door SYNC."
+ },
+ "pl-pl" : {
+ "line1" : "aplikacja nie obsług.",
+ "tts" : "Niniejsza wersja %appName% nie jest obsługiwana przez system SYNC."
+ },
+ "pt-br" : {
+ "line1" : "não suportado",
+ "tts" : "Esta versão do %appName% não é suportada pelo SYNC."
+ },
+ "pt-pt" : {
+ "line1" : "não suportada",
+ "tts" : "Esta versão de %appName% não é suportado pelo SYNC."
+ },
+ "ru-ru" : {
+ "line1" : "не поддерживается",
+ "tts" : "Эта версия %appName% не поддерживается SYNC."
+ },
+ "sv-se" : {
+ "line1" : "stöds ej",
+ "tts" : "SYNC har inte stöd för den här versionen av %appName%."
+ },
+ "tr-tr" : {
+ "line1" : "desteklenmiyor",
+ "tts" : "Bu %appName% sürümü SYNC tarafından desteklenmiyor."
+ },
+ "zh-cn" : {
+ "line1" : "不受支持",
+ "tts" : "SYNC不支持此版本的%appName%。"
+ },
+ "zh-tw" : {
+ "line1" : "不支援",
+ "tts" : "SYNC 不支援此版本的%appName% 。"
+ }
+ }
+ },
+ "DataConsent" : {
+ "languages" : {
+ "en-us" : {
+ "line1" : "Enable Mobile Apps",
+ "line2" : "on SYNC? (Uses Data)",
+ "tts" : "To use mobile apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device's data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S. Please press yes or no, or help for more information. "
+ }
+ }
+ },
+ "DataConsentHelp" : {
+ "languages" : {
+ "en-us" : {
+ "tts" : "Updates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC mobile apps settings menu. See your Owner Guide for more information. "
+ }
+ }
+ },
+ "DisableApps" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Auto-Update",
+ "line2" : "und Mobile Apps deaktivieren",
+ "tts" : "Ausschalten der automatischen Updates führt zum Ausschalten von SYNC mobile Apps. Sie können Ihre mobilen Apps dann nicht mehr mit SYNC nutzen. Bitte drücken Sie Ja zur Bestätigung oder Nein, um abzubrechen."
+ },
+ "en-au" : {
+ "line1" : "Disable auto-updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-gb" : {
+ "line1" : "Disable auto-updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-ie" : {
+ "line1" : "Disable auto-updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-us" : {
+ "line1" : "Disable Auto-Updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel."
+ },
+ "es-en" : {
+ "line1" : "¿Deshab. actualiz.",
+ "line2" : "autom. y aplic. móv.?",
+ "tts" : "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "es-es" : {
+ "line1" : "¿Desact. actual. auto",
+ "line2" : "y apl. móviles?",
+ "tts" : "Si desactiva las actualizaciones automáticas, también se desactivará la sincronización de las aplicaciones móviles. No podrá utilizar ninguna aplicación móvil con SYNC. Pulse sí para confirmar o no para cancelar."
+ },
+ "es-mx" : {
+ "line1" : "¿Deshab. actualiz.",
+ "line2" : "autom. y aplic. móv.?",
+ "tts" : "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "fr-ca" : {
+ "line1" : "Désactiver màj autom.",
+ "line2" : "et app. mobiles?",
+ "tts" : "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "fr-fr" : {
+ "line1" : "Désactiver màj autom.",
+ "line2" : "et app. mobiles?",
+ "tts" : "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "it-it" : {
+ "line1" : "Disabilitare agg. aut.",
+ "line2" : "e app mobili?",
+ "tts" : "Disabilitando gli aggiornamenti automatici si disattiva anche la sincronizzazione delle app mobili. Non sarà possibile usare app mobili con il SYNC. Premere Sì per confermare e No per cancellare."
+ },
+ "nl-nl" : {
+ "line1" : "Auto-updates en mob.",
+ "line2" : "apps uitschakelen?",
+ "tts" : "Door automatische updates uit te schakelen, schakelt u ook SYNC-mobiele apps uit. U kunt dan geen mobiele apps meer gebruiken met SYNC. Druk op Ja om te bevestigen of op Nee om te annuleren."
+ },
+ "pl-pl" : {
+ "line1" : "Wył. automat. aktual.",
+ "line2" : "i aplikacje mobilne?",
+ "tts" : "Wyłączenie automatycznych aktualizacji spowoduje także wyłączenie aplikacji mobilnych SYNC. Korzystanie z mobilnych aplikacji za pomocą SYNC będzie niemożliwe. Naciśnij TAK, by potwierdzić lub NIE, by anulować."
+ },
+ "pt-br" : {
+ "line1" : "Desativar atualizações",
+ "line2" : "autom. e aplicativos?",
+ "tts" : "Se as atualizações automáticas forem desativadas, os aplicativos também serão desativados. Você não poderá usar nenhum aplicativo com o SYNC. Pressione sim para confirmar ou não para cancelar."
+ },
+ "pt-pt" : {
+ "line1" : "Desact. actual. autom.",
+ "line2" : "e aplicações móveis?",
+ "tts" : "A desactivação das actualizações automáticas desactiva igualmente as aplicações móveis do SYNC. Não poderá utilizar quaisquer aplicações móveis com o SYNC. Prima \"\"Sim\"\" para confirmar ou \"\"Não\"\" para cancelar."
+ },
+ "ru-ru" : {
+ "line1" : "Откл. автообновления",
+ "line2" : "и мобил. прилож.?",
+ "tts" : "При отключении автоматических обновлений также будут отключены мобильные приложения sync. Вы не сможете использовать какие-либо мобильные приложения с SYNC. Нажмите \"\"Да\"\" для подтверждения или \"\"Нет\"\" для отмены."
+ },
+ "sv-se" : {
+ "line1" : "Avaktiverar autouppdat.",
+ "line2" : "och mobilappar?",
+ "tts" : "Om du avaktiverar automatisk uppdatering avaktiverar du även synkning av mobilappar. Du kommer inte längre att kunna använda dina mobilappar med SYNC. Tryck Ja för att bekräfta eller Nej för att avbryta."
+ },
+ "tr-tr" : {
+ "line1" : "Oto. güncelleme ve",
+ "line2" : "mobil uygul. kapat?",
+ "tts" : "Otomatik güncellemeleri devre dışı bırakırsanız sync mobil uygulamalar da devre dışı kalır. SYNC ile mobil uygulama kullanmanız mümkün olmaz. Lütfen onaylamak için Evet'e veya iptal etmek için Hayır'a basın."
+ },
+ "zh-cn" : {
+ "line1" : "是否禁用自动更新和",
+ "line2" : "移动应用程序?",
+ "tts" : "禁用自动更新同时也会禁用SYNC移动应用程序。您将无法在 SYNC 中使用任何移动应用程序。请按“是”确认或按“否”取消。"
+ },
+ "zh-tw" : {
+ "line1" : "停用自動更新",
+ "line2" : "和行動應用程式?",
+ "tts" : "停用自動更新也將停用 sync 行動應用程式。您將無法透過 SYNC 使用任何行動應用程式。確認請按「是」,取消請按「否」。"
+ }
+ }
+ },
+ "DrivingCharacteristics" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "Fahreigenschaften",
+ "tts" : "Eine App hat Zugriff auf die folgenden Fahreigenschaften: Kraftstoffverbrauch, MyKey, Sicherheitsgurtstatus."
+ },
+ "en-au" : {
+ "label" : "Driving characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-gb" : {
+ "label" : "Driving characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-ie" : {
+ "label" : "Driving characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-us" : {
+ "label" : "Driving Characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status."
+ },
+ "es-en" : {
+ "label" : "Características del manejo",
+ "tts" : "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "es-es" : {
+ "label" : "Características de conducción",
+ "tts" : "Una aplicación puede acceder a las siguientes características de conducción: Consumo de combustible, MyKey, Estado cinturones de seguridad."
+ },
+ "es-mx" : {
+ "label" : "Características del manejo",
+ "tts" : "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "fr-ca" : {
+ "label" : "Caractéristiques de conduite",
+ "tts" : "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "fr-fr" : {
+ "label" : "Caractéristiques de conduite",
+ "tts" : "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "it-it" : {
+ "label" : "Caratteristiche di guida",
+ "tts" : "Un'app può avere accesso alle seguenti caratteristiche di guida: Consumo carburante, MyKey, Stato cinture di sicurezza."
+ },
+ "nl-nl" : {
+ "label" : "Rijkenmerken",
+ "tts" : "Een app heeft toegang tot de volgende rijkenmerken: Brandstofverbruik, MyKey, Veiligheidsgordelstatus."
+ },
+ "pl-pl" : {
+ "label" : "Informacje dotyczące stylu jazdy",
+ "tts" : "Aplikacja może uzyskać dostęp do następujących informacji dotyczących jazdy: Zużycie paliwa, MyKey, Stan pasów bezpieczeństwa."
+ },
+ "pt-br" : {
+ "label" : "Características de condução",
+ "tts" : "Um aplicativo pode acessar as seguintes características de condução: Consumo de combustível, MyKey, Estado do cinto de segurança."
+ },
+ "pt-pt" : {
+ "label" : "Características de condução",
+ "tts" : "Uma aplicação consegue aceder às seguintes informações de condução: Consumo de combustível, MyKey, Estado dos cintos de segurança."
+ },
+ "ru-ru" : {
+ "label" : "Характеристики движения",
+ "tts" : "Приложение имеет доступ к следующим характеристикам движения: Расход топлива, MyKey, Состояние ремней безопасности."
+ },
+ "sv-se" : {
+ "label" : "Köregenskaper",
+ "tts" : "Appen kan komma åt följande köregenskaper: Bränsleförbrukning, MyKey, Bältesstatus."
+ },
+ "tr-tr" : {
+ "label" : "Sürüş karakteristikleri",
+ "tts" : "Bir uygulama şu sürüş karakteristiklerine erişebilir: Yakıt tüketimi, MyKey, Emniyet kemeri durumu."
+ },
+ "zh-cn" : {
+ "label" : "行驶特性",
+ "tts" : "移动应用程序可访问下列行驶特性: 油耗, MyKey, 安全带状态"
+ },
+ "zh-tw" : {
+ "label" : "駕駛特性",
+ "tts" : "應用程式可存取以下駕駛特性: 油耗, MyKey, 安全帶狀態"
+ }
+ }
+ },
+ "Location" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "GPS und Geschwindigkeit",
+ "tts" : "Eine App hat Zugriff auf die GPS-Daten und die Geschwindigkeit des Fahrzeugs."
+ },
+ "en-au" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "en-gb" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "en-ie" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "en-us" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "es-en" : {
+ "label" : "GPS y velocidad",
+ "tts" : "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "es-es" : {
+ "label" : "GPS y velocidad",
+ "tts" : "Una aplicación puede acceder al GPS y la velocidad del vehículo."
+ },
+ "es-mx" : {
+ "label" : "GPS y velocidad",
+ "tts" : "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "fr-ca" : {
+ "label" : "GPS et vitesse",
+ "tts" : "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "fr-fr" : {
+ "label" : "GPS et vitesse",
+ "tts" : "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "it-it" : {
+ "label" : "GPS e velocità",
+ "tts" : "Un'app può avere accesso a GPS e velocità del veicolo."
+ },
+ "nl-nl" : {
+ "label" : "Gps en snelheid",
+ "tts" : "Een app heeft toegang tot gps en de snelheid van het voertuig."
+ },
+ "pl-pl" : {
+ "label" : "GPS i prędkość",
+ "tts" : "Aplikacja może uzyskać dostęp do modułu GPS i prędkości pojazdu."
+ },
+ "pt-br" : {
+ "label" : "GPS e velocidade",
+ "tts" : "Um aplicativo pode acessar o GPS e a velocidade do veículo."
+ },
+ "pt-pt" : {
+ "label" : "GPS e velocidade",
+ "tts" : "Uma aplicação consegue aceder ao GPS e à velocidade do veículo."
+ },
+ "ru-ru" : {
+ "label" : "GPS и скорость",
+ "tts" : "Приложение имеет доступ к GPS и скорости автомобиля."
+ },
+ "sv-se" : {
+ "label" : "GPS och hastighet",
+ "tts" : "Appen kan komma åt fordonets GPS och hastighetsmätare."
+ },
+ "tr-tr" : {
+ "label" : "GPS ve hız",
+ "tts" : "Bu uygulama aracın GPS ve hız bilgilerine erişebilir."
+ },
+ "zh-cn" : {
+ "label" : "GPS 和车速",
+ "tts" : "移动应用程序可以访问车辆 GPS 和车速信息。"
+ },
+ "zh-tw" : {
+ "label" : "GPS和車速",
+ "tts" : "應用程式可存取車輛的GPS和速度。"
+ }
+ }
+ },
+ "Notifications" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "Push-Benachrichtigungen",
+ "tts" : "Läuft die App im Hintergrund, kann Sie Benachrichtigungen senden."
+ },
+ "en-au" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "en-gb" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "en-ie" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "en-us" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "es-en" : {
+ "label" : "Notificaciones tipo Push",
+ "tts" : "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "es-es" : {
+ "label" : "Notificaciones push",
+ "tts" : "Una aplicación puede enviar notificaciones cuando se está ejecutando en segundo plano."
+ },
+ "es-mx" : {
+ "label" : "Notificaciones tipo Push",
+ "tts" : "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "fr-ca" : {
+ "label" : "Notifications instantanées",
+ "tts" : "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "fr-fr" : {
+ "label" : "Notifications push",
+ "tts" : "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "it-it" : {
+ "label" : "Notifiche push",
+ "tts" : "Un'app può inviare notifiche se eseguita in background."
+ },
+ "nl-nl" : {
+ "label" : "Push-meldingen",
+ "tts" : "Een app kan meldingen versturen als deze op de achtergrond actief is."
+ },
+ "pl-pl" : {
+ "label" : "Powiadomienia Push",
+ "tts" : "Aplikacja może wysyłać powiadomienia, działając w tle."
+ },
+ "pt-br" : {
+ "label" : "Notificações Push",
+ "tts" : "Um aplicativo pode enviar notificações quando estiver sendo executado em segundo plano."
+ },
+ "pt-pt" : {
+ "label" : "Notificações push",
+ "tts" : "Uma aplicação consegue enviar notificações quando está activa em segundo plano."
+ },
+ "ru-ru" : {
+ "label" : "Оповещения о пересылке",
+ "tts" : "Если приложение работает в фоновом режиме, оно может отправлять оповещения."
+ },
+ "sv-se" : {
+ "label" : "Push-notiser",
+ "tts" : "Appen kan skicka meddelanden när den körs i bakgrunden."
+ },
+ "tr-tr" : {
+ "label" : "Anlık bildirimleri",
+ "tts" : "Bir uygulama arka planda çalışırken bildirim gönderebilir."
+ },
+ "zh-cn" : {
+ "label" : "推送通知",
+ "tts" : "移动应用程序在后台运行时可推送通知。"
+ },
+ "zh-tw" : {
+ "label" : "傳送通知",
+ "tts" : "車輛行進時,應用程式可在背景中傳送通知。"
+ }
+ }
+ },
+ "SettingDisableUpdates" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Updates deakt."
+ },
+ "en-au" : {
+ "line1" : "Disable updates"
+ },
+ "en-gb" : {
+ "line1" : "Disable updates"
+ },
+ "en-ie" : {
+ "line1" : "Disable updates"
+ },
+ "en-us" : {
+ "line1" : "Disable Updates"
+ },
+ "es-en" : {
+ "line1" : "Deshab. actual."
+ },
+ "es-es" : {
+ "line1" : "Desact. actual."
+ },
+ "es-mx" : {
+ "line1" : "Deshab. actual."
+ },
+ "fr-ca" : {
+ "line1" : "Désactiver MAJ"
+ },
+ "fr-fr" : {
+ "line1" : "Désactiver màj"
+ },
+ "it-it" : {
+ "line1" : "Disabilita agg."
+ },
+ "nl-nl" : {
+ "line1" : "Upd. uitschak."
+ },
+ "pl-pl" : {
+ "line1" : "Wyłącz aktual."
+ },
+ "pt-br" : {
+ "line1" : "Desat. atualiz."
+ },
+ "pt-pt" : {
+ "line1" : "Desact. actualiz."
+ },
+ "ru-ru" : {
+ "line1" : "Откл. обновл."
+ },
+ "sv-se" : {
+ "line1" : "Inaktivera uppd."
+ },
+ "tr-tr" : {
+ "line1" : "Güncell. Kapat"
+ },
+ "zh-cn" : {
+ "line1" : "禁用更新"
+ },
+ "zh-tw" : {
+ "line1" : "停用更新"
+ }
+ }
+ },
+ "SettingEnableUpdates" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Apps aktivieren"
+ },
+ "en-au" : {
+ "line1" : "Enable Apps"
+ },
+ "en-gb" : {
+ "line1" : "Enable Apps"
+ },
+ "en-ie" : {
+ "line1" : "Enable Apps"
+ },
+ "en-us" : {
+ "line1" : "Enable Apps"
+ },
+ "es-en" : {
+ "line1" : "Hab. aplic."
+ },
+ "es-es" : {
+ "line1" : "Activar apl."
+ },
+ "es-mx" : {
+ "line1" : "Hab. aplic."
+ },
+ "fr-ca" : {
+ "line1" : "Activer app."
+ },
+ "fr-fr" : {
+ "line1" : "Activer app."
+ },
+ "it-it" : {
+ "line1" : "Abilita app"
+ },
+ "nl-nl" : {
+ "line1" : "Apps inschak."
+ },
+ "pl-pl" : {
+ "line1" : "Włącz aplikacje"
+ },
+ "pt-br" : {
+ "line1" : "Ativar aplic."
+ },
+ "pt-pt" : {
+ "line1" : "Activar actualiz."
+ },
+ "ru-ru" : {
+ "line1" : "Вкл. прилож."
+ },
+ "sv-se" : {
+ "line1" : "Aktivera appar"
+ },
+ "tr-tr" : {
+ "line1" : "Uygulamaları aç"
+ },
+ "zh-cn" : {
+ "line1" : "启用应用程序"
+ },
+ "zh-tw" : {
+ "line1" : "啟用應用程式"
+ }
+ }
+ },
+ "SettingUpdateAuto" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Update anford."
+ },
+ "en-au" : {
+ "line1" : "Request update"
+ },
+ "en-gb" : {
+ "line1" : "Request update"
+ },
+ "en-ie" : {
+ "line1" : "Request update"
+ },
+ "en-us" : {
+ "line1" : "Request Update"
+ },
+ "es-en" : {
+ "line1" : "Solicit. actualiz."
+ },
+ "es-es" : {
+ "line1" : "Solicitar actual."
+ },
+ "es-mx" : {
+ "line1" : "Solicit. actualiz."
+ },
+ "fr-ca" : {
+ "line1" : "Demander MAJ"
+ },
+ "fr-fr" : {
+ "line1" : "Demander màj"
+ },
+ "it-it" : {
+ "line1" : "Rich. aggiorn."
+ },
+ "nl-nl" : {
+ "line1" : "Upd. aanvragen"
+ },
+ "pl-pl" : {
+ "line1" : "Zażądaj aktual."
+ },
+ "pt-br" : {
+ "line1" : "Solicitar atualiz."
+ },
+ "pt-pt" : {
+ "line1" : "Solicit. actualiz."
+ },
+ "ru-ru" : {
+ "line1" : "Запрос на обн."
+ },
+ "sv-se" : {
+ "line1" : "Begär uppdat."
+ },
+ "tr-tr" : {
+ "line1" : "Güncelleme iste"
+ },
+ "zh-cn" : {
+ "line1" : "请求更新"
+ },
+ "zh-tw" : {
+ "line1" : "請求更新"
+ }
+ }
+ },
+ "StatusNeeded" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Update benötigt"
+ },
+ "en-au" : {
+ "line1" : "Update needed"
+ },
+ "en-gb" : {
+ "line1" : "Update needed"
+ },
+ "en-ie" : {
+ "line1" : "Update needed"
+ },
+ "en-us" : {
+ "line1" : "Update Needed"
+ },
+ "es-en" : {
+ "line1" : "Actualiz. neces."
+ },
+ "es-es" : {
+ "line1" : "Actu. necesaria"
+ },
+ "es-mx" : {
+ "line1" : "Actualiz. neces."
+ },
+ "fr-ca" : {
+ "line1" : "Màj requise"
+ },
+ "fr-fr" : {
+ "line1" : "Mise à jour requise"
+ },
+ "it-it" : {
+ "line1" : "Necess. aggiorn."
+ },
+ "nl-nl" : {
+ "line1" : "Update nodig"
+ },
+ "pl-pl" : {
+ "line1" : "Potrzeba aktual."
+ },
+ "pt-br" : {
+ "line1" : "Atualiz. necess."
+ },
+ "pt-pt" : {
+ "line1" : "Actual. necess."
+ },
+ "ru-ru" : {
+ "line1" : "Необх. обновл."
+ },
+ "sv-se" : {
+ "line1" : "Uppdat. krävs"
+ },
+ "tr-tr" : {
+ "line1" : "Güncellenmeli"
+ },
+ "zh-cn" : {
+ "line1" : "需要进行更新"
+ },
+ "zh-tw" : {
+ "line1" : "需更新"
+ }
+ }
+ },
+ "StatusPending" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Aktualisieren..."
+ },
+ "en-au" : {
+ "line1" : "Updating..."
+ },
+ "en-gb" : {
+ "line1" : "Updating..."
+ },
+ "en-ie" : {
+ "line1" : "Updating..."
+ },
+ "en-us" : {
+ "line1" : "Updating..."
+ },
+ "es-en" : {
+ "line1" : "Actualizando..."
+ },
+ "es-es" : {
+ "line1" : "Actualizando..."
+ },
+ "es-mx" : {
+ "line1" : "Actualizando..."
+ },
+ "fr-ca" : {
+ "line1" : "MAJ en cours..."
+ },
+ "fr-fr" : {
+ "line1" : "Màj en cours..."
+ },
+ "it-it" : {
+ "line1" : "Aggiornamento"
+ },
+ "nl-nl" : {
+ "line1" : "Updaten..."
+ },
+ "pl-pl" : {
+ "line1" : "Aktualizowanie"
+ },
+ "pt-br" : {
+ "line1" : "Atualizando..."
+ },
+ "pt-pt" : {
+ "line1" : "A actualizar..."
+ },
+ "ru-ru" : {
+ "line1" : "Обновление..."
+ },
+ "sv-se" : {
+ "line1" : "Uppdaterar..."
+ },
+ "tr-tr" : {
+ "line1" : "Güncelleniyor..."
+ },
+ "zh-cn" : {
+ "line1" : "正在更新......"
+ },
+ "zh-tw" : {
+ "line1" : "更新中..."
+ }
+ }
+ },
+ "StatusUpToDate" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Aktuelle Version"
+ },
+ "en-au" : {
+ "line1" : "Up-to-date"
+ },
+ "en-gb" : {
+ "line1" : "Up-to-date"
+ },
+ "en-ie" : {
+ "line1" : "Up-to-date"
+ },
+ "en-us" : {
+ "line1" : "Up-To-Date"
+ },
+ "es-en" : {
+ "line1" : "Actualizado"
+ },
+ "es-es" : {
+ "line1" : "Actualizada"
+ },
+ "es-mx" : {
+ "line1" : "Actualizado"
+ },
+ "fr-ca" : {
+ "line1" : "Déjà à jour"
+ },
+ "fr-fr" : {
+ "line1" : "Déjà à jour"
+ },
+ "it-it" : {
+ "line1" : "più recente"
+ },
+ "nl-nl" : {
+ "line1" : "Up-to-date"
+ },
+ "pl-pl" : {
+ "line1" : "Aktualne"
+ },
+ "pt-br" : {
+ "line1" : "Atualizado"
+ },
+ "pt-pt" : {
+ "line1" : "Actualizado"
+ },
+ "ru-ru" : {
+ "line1" : "Обновлено"
+ },
+ "sv-se" : {
+ "line1" : "Uppdat. krävs ej"
+ },
+ "tr-tr" : {
+ "line1" : "Güncel"
+ },
+ "zh-cn" : {
+ "line1" : "最新更新"
+ },
+ "zh-tw" : {
+ "line1" : "更新最新"
+ }
+ }
+ },
+ "VehicleInfo" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "Fahrzeuginformationen",
+ "tts" : "Eine App hat Zugriff auf die folgenden Fahrzeuginformationen: Kraftstoff-Füllstand, Kraftstoffverbrauch, Motordrehzahl, Kilometerzähler, FIN, Außentemperatur, Gangstellung, Reifenluftdruck."
+ },
+ "en-au" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure."
+ },
+ "en-gb" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure."
+ },
+ "en-ie" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure."
+ },
+ "en-us" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure."
+ },
+ "es-en" : {
+ "label" : "Información del vehículo",
+ "tts" : "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "es-es" : {
+ "label" : "Información del vehículo",
+ "tts" : "Una aplicación puede acceder a la siguiente información del vehículo: Nivel de combustible, Ahorro de combustible, RPM del motor, Cuentakilómetros, VIN, Temperatura aire exterior, Marcha engranada, Presión de neumáticos."
+ },
+ "es-mx" : {
+ "label" : "Información del vehículo",
+ "tts" : "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "fr-ca" : {
+ "label" : "Renseignements du véhicule",
+ "tts" : "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus."
+ },
+ "fr-fr" : {
+ "label" : "Renseignements du véhicule",
+ "tts" : "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Vitesse de moteur, Compteur kilométrique, NIV, Température extérieure, Position de vitesse, Pression des pneus."
+ },
+ "it-it" : {
+ "label" : "Informazioni sul veicolo",
+ "tts" : "Un'app può avere accesso alle seguenti informazioni del veicolo: Livello carburante, Consumi carburante, Numero giri motore, Contachilometri, VIN, Temperatura esterna, Posizione marcia, Pressione pneumatici."
+ },
+ "nl-nl" : {
+ "label" : "Voertuiginformatie",
+ "tts" : "Een app heeft toegang tot de volgende voertuiginformatie: Brandstofpeil, Brandstofverbruik, Motortoerental, Kilometerteller, VIN, Buitentemperatuur, Versnellingsstand, Bandenspanning."
+ },
+ "pl-pl" : {
+ "label" : "Informacje o pojeździe",
+ "tts" : "Aplikacja może uzyskać dostęp do następujących informacji o pojeździe: Poziom paliwa, Zużycie paliwa, Obroty silnika, Licznik przebiegu, Numer VIN, Temperatura zewnętrzna, Aktualny bieg, Ciśnienie opon."
+ },
+ "pt-br" : {
+ "label" : "Informações sobre o veículo",
+ "tts" : "Um aplicativo pode acessar as seguintes informações sobre o veículo: Nível de combustível, Economia de combustível, RPM do motor, Hodômetro, VIN, Temperatura externa, Posição das marchas, Pressão dos pneus."
+ },
+ "pt-pt" : {
+ "label" : "Informações do veículo",
+ "tts" : "Uma aplicação consegue aceder às seguintes informações do veículo: Nível de combustível, Poupança de combustível, RPM do motor, Conta-quilómetros, VIN, Temperatura exterior, Posição da mudança de velocidade, Pressão dos pneus."
+ },
+ "ru-ru" : {
+ "label" : "Информация об автомобиле",
+ "tts" : "Приложение имеет доступ к следующим данным автомобиля: Уровень топлива, Економия топлива, Число оборотов двигателя, Одометр, Номер VIN, Температура за бортом, Положение передачи, Давление шин."
+ },
+ "sv-se" : {
+ "label" : "Fordonsinformation",
+ "tts" : "Appen kan komma åt följande fordonsinformation: Bränslenivå, Bränsleekonomi, Motorns varvtal, Vägmätare, VIN, Utetemperatur, Växelläge, Däcktryck."
+ },
+ "tr-tr" : {
+ "label" : "Araç bilgisi",
+ "tts" : "Bir uygulama şu araç bilgilerine erişebilir: Yakıt seviyesi, Yakıt ekonomisi, Motor devirleri, Kilometre sayacı, VIN, Dış sıcaklık, Vites konumu, Lastik basıncı."
+ },
+ "zh-cn" : {
+ "label" : "车辆信息",
+ "tts" : "移动应用程序可访问下列车辆信息 : 燃油量, 燃油经济性, 发动机转速(RPM), 里程表, VIN, 车外温度, 档位, 胎压."
+ },
+ "zh-tw" : {
+ "label" : "車輛資訊",
+ "tts" : "一個應用程式可存取以下車輛資訊 : 燃油存量, 燃油經濟性, 引擎轉速, 里程表, 車輛識別號碼, 車外溫度, 檔位, 胎壓."
+ }
+ }
+ }
+ },
+ "version" : "001.001.015"
+ },
+ "functional_groupings" : {
+ "Base-4" : {
+ "rpcs" : {
+ "AddCommand" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "AddSubMenu" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "Alert" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "ChangeRegistration" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "CreateInteractionChoiceSet" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "DeleteCommand" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "DeleteFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "DeleteInteractionChoiceSet" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "DeleteSubMenu" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "EncodedSyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "EndAudioPassThru" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "GenericResponse" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ListFiles" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnAppInterfaceUnregistered" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnAudioPassThru" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "OnButtonEvent" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "OnButtonPress" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "OnCommand" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "OnDriverDistraction" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "OnEncodedSyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnHMIStatus" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnLanguageChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnPermissionsChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnSyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnTBTClientState" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "PerformAudioPassThru" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "PerformInteraction" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "PutFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "RegisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "ResetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ScrollableMessage" : {
+ "hmi_levels" : [ "FULL" ]
+ },
+ "SetAppIcon" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetDisplayLayout" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "SetMediaClockTimer" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "Show" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "Slider" : {
+ "hmi_levels" : [ "FULL" ]
+ },
+ "Speak" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "SubscribeButton" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "SyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "UnregisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "UnsubscribeButton" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ }
+ }
+ },
+ "DrivingCharacteristics-3" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ }
+ },
+ "user_consent_prompt" : "DrivingCharacteristics"
+ },
+ "Emergency-1" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ }
+ }
+ },
+ "Location-1" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ }
+ },
+ "user_consent_prompt" : "Location"
+ },
+ "Navigation-1" : {
+ "rpcs" : {
+ "AlertManeuver" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ShowConstantTBT" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "UpdateTurnList" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ }
+ }
+ },
+ "Notifications" : {
+ "rpcs" : {
+ "Alert" : {
+ "hmi_levels" : [ "BACKGROUND" ]
+ }
+ },
+ "user_consent_prompt" : "Notifications"
+ },
+ "PropriataryData-1" : {
+ "rpcs" : {
+ "DiagnosticMessage" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "GetDTCs" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ReadDID" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ }
+ }
+ },
+ "VehicleInfo-3" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"
+ ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"
+ ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"
+ ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"
+ ]
+ }
+ },
+ "user_consent_prompt" : "VehicleInfo"
+ },
+ "pre_Base-1" : {
+ "rpcs" : {
+ "ChangeRegistration" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "DeleteFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "GenericResponse" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ListFiles" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnAppInterfaceUnregistered" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnLanguageChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnPermissionsChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "PutFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "RegisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "ResetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "SetAppIcon" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetDisplayLayout" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "UnregisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ }
+ }
+ }
+ },
+ "module_config" : {
+ "device_certificates" : {
+ "HUU40DAS7F970UEI17A73JH32L41K32JH4L1K234H3K4" : "aldhfkahfgkafrblgjr"
+ },
+ "endpoints" : {
+ "0x07" : {
+ "default" : [ "http://policies.telematics.ford.com/api/policies" ]
+ }
+ },
+ "exchange_after_x_days" : 30,
+ "exchange_after_x_ignition_cycles" : 100,
+ "exchange_after_x_kilometers" : 1800,
+ "notifications_per_minute_by_priority" : {
+ "COMMUNICATION" : 6,
+ "EMERGENCY" : 60,
+ "NAVIGATION" : 15,
+ "NONE" : 0,
+ "NORMAL" : 4,
+ "VOICECOMM" : 10
+ },
+ "seconds_between_retries" : [ 1, 5, 25, 125, 625 ],
+ "timeout_after_x_seconds" : 60,
+ "vehicle_make" : "Stark Industries",
+ "vehicle_model" : "E-Tron",
+ "vehicle_year" : "1992"
+ }
+ }
+}
diff --git a/src/components/application_manager/test/smartDeviceLink_test.ini b/src/components/application_manager/test/smartDeviceLink_test.ini
new file mode 100644
index 0000000000..c544a6e02d
--- /dev/null
+++ b/src/components/application_manager/test/smartDeviceLink_test.ini
@@ -0,0 +1,39 @@
+[MAIN]
+
+; For resume_ctrl tests
+LogsEnabled = false
+; Contains .json/.ini files
+AppConfigFolder =
+; Contains output files, e.g. .wav. Changed for tests
+AppStorageFolder = test_storage
+; Limitation for a number of ReadDID requests (the 1st value) per (the 2nd value) seconds
+ReadDIDRequest = 5, 1
+
+[AppInfo]
+; The path for applications info storage. Changed for tests
+AppInfoStorage = test_app_info.dat
+
+[Resumption]
+
+# Timeout in milliseconds for resumption Application HMILevel
+# and resolving conflicts in case if multiple applications initiate resumption
+# Time changed for test onAppActivated
+ApplicationResumingTimeout = 30000000
+
+# Timeout in milliseconds for periodical saving resumption persistent data
+AppSavePersistentDataTimeout = 10000
+
+# Timeout in seconds to store hmi_level for media app before ign_off
+ResumptionDelayBeforeIgn = 30;
+
+# Timeout in seconds to restore hmi_level for media app after sdl run
+ResumptionDelayAfterIgn = 30;
+
+# Resumption ctrl uses JSON if UseDBForResumption=false for store data otherwise uses DB
+UseDBForResumption = false
+
+# Number of attempts to open resumption DB
+AttemptsToOpenResumptionDB = 5
+
+# Timeout between attempts during opening DB in milliseconds
+OpenAttemptTimeoutMsResumptionDB = 500
diff --git a/src/components/application_manager/test/smartDeviceLink_test2.ini b/src/components/application_manager/test/smartDeviceLink_test2.ini
new file mode 100644
index 0000000000..a5e09b9e6c
--- /dev/null
+++ b/src/components/application_manager/test/smartDeviceLink_test2.ini
@@ -0,0 +1,28 @@
+; The INI-file consists of different chapters.
+; Each chapter begins with the line containing
+; the name in square brackets. Syntax:
+; [chapter]
+; The chapters consists of a set of items with a
+; assigned value. The syntax is:
+; item=value
+; All white spaces an second encounters of chapters
+; or items will be ignored.
+; Remarks start with semicolon or star as first character.
+; It is allowed for names of chapters and items to
+; contain semicolon and star. Possible syntax is:
+; [ chapter ] ;Remark
+; item = value ;Remark
+
+[MAIN]
+; Contains output files, e.g. .wav
+AppStorageFolder = storage
+
+[Policy]
+EnablePolicy = true
+PreloadedPT = sdl_preloaded_pt.json
+PathToSnapshot = sdl_snapshot.json
+; Number of attempts to open policy DB
+AttemptsToOpenPolicyDB = 5
+; Timeout between attempts during opening DB in milliseconds
+OpenAttemptTimeoutMs = 500
+
diff --git a/src/components/application_manager/test/state_controller/CMakeLists.txt b/src/components/application_manager/test/state_controller/CMakeLists.txt
index 243e6218ed..50dd931309 100644
--- a/src/components/application_manager/test/state_controller/CMakeLists.txt
+++ b/src/components/application_manager/test/state_controller/CMakeLists.txt
@@ -30,20 +30,20 @@
if(BUILD_TESTS)
-set(appMain_DIR ${CMAKE_SOURCE_DIR}/src/appMain)
-
include_directories(
${GMOCK_INCLUDE_DIRECTORY}
- ${COMPONENTS_DIR}/application_manager/test/state_controller/include
+ ${COMPONENTS_DIR}/application_manager/test/include
)
set(LIBRARIES
gmock
ApplicationManager
+ connectionHandler
)
set(SOURCES
state_controller_test.cc
+ ${COMPONENTS_DIR}/application_manager/test/mock_message_helper.cc
)
create_test("state_controller_test" "${SOURCES}" "${LIBRARIES}")
diff --git a/src/components/application_manager/test/state_controller/include/application_manager_mock.h b/src/components/application_manager/test/state_controller/include/application_manager_mock.h
deleted file mode 100644
index 22ff93687a..0000000000
--- a/src/components/application_manager/test/state_controller/include/application_manager_mock.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MANAGER_MOCK_H_
-#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MANAGER_MOCK_H_
-#include <string>
-#include <vector>
-#include "gmock/gmock.h"
-#include "application_manager/application_manager.h"
-#include "application_manager/usage_statistics.h"
-
-namespace state_controller_test {
-namespace am = application_manager;
-
-class ApplicationManagerMock : public application_manager::ApplicationManager {
- public:
- MOCK_METHOD0(Init, bool());
- MOCK_METHOD0(Stop, bool());
-
- MOCK_METHOD1(set_hmi_message_handler,
- void(hmi_message_handler::HMIMessageHandler*));
- MOCK_METHOD1(set_protocol_handler, void(protocol_handler::ProtocolHandler*));
- MOCK_METHOD1(set_connection_handler,
- void(connection_handler::ConnectionHandler*));
- MOCK_CONST_METHOD0(applications, DataAccessor<am::ApplicationSet>());
- MOCK_CONST_METHOD1(application_by_hmi_app,
- am::ApplicationSharedPtr(uint32_t));
- MOCK_CONST_METHOD1(application, am::ApplicationSharedPtr(uint32_t));
-
- MOCK_CONST_METHOD0(active_application, am::ApplicationSharedPtr());
- MOCK_CONST_METHOD1(application_by_policy_id,
- am::ApplicationSharedPtr(const std::string&));
- MOCK_METHOD1(applications_by_button,
- std::vector<am::ApplicationSharedPtr>(uint32_t));
- MOCK_METHOD0(applications_with_navi, std::vector<am::ApplicationSharedPtr>());
- MOCK_CONST_METHOD0(get_limited_media_application, am::ApplicationSharedPtr());
- MOCK_CONST_METHOD0(get_limited_navi_application, am::ApplicationSharedPtr());
- MOCK_CONST_METHOD0(get_limited_voice_application, am::ApplicationSharedPtr());
- MOCK_METHOD2(set_application_id, void(const int32_t, const uint32_t));
- MOCK_METHOD1(application_id, uint32_t(const int32_t));
- MOCK_METHOD3(OnHMILevelChanged, void(uint32_t, mobile_apis::HMILevel::eType,
- mobile_apis::HMILevel::eType));
- MOCK_METHOD1(SendHMIStatusNotification, void(const am::ApplicationSharedPtr));
- MOCK_CONST_METHOD1(GetDefaultHmiLevel, mobile_apis::HMILevel::eType(
- am::ApplicationConstSharedPtr));
- MOCK_METHOD0(hmi_capabilities, am::HMICapabilities&());
- MOCK_METHOD0(is_attenuated_supported, bool());
- MOCK_CONST_METHOD1(IsAppTypeExistsInFullOrLimited, bool(am::ApplicationConstSharedPtr));
-};
-} // namespace state_controller_test
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MANAGER_MOCK_H_
diff --git a/src/components/application_manager/test/state_controller/include/application_mock.h b/src/components/application_manager/test/state_controller/include/application_mock.h
deleted file mode 100644
index 01dafd10f4..0000000000
--- a/src/components/application_manager/test/state_controller/include/application_mock.h
+++ /dev/null
@@ -1,252 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MOCK_H_
-#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MOCK_H_
-
-#include <string>
-
-#include "gmock/gmock.h"
-#include "application_manager/application.h"
-namespace state_controller_test {
-namespace am = application_manager;
-
-class ApplicationMock : public am::Application {
- public:
- MOCK_CONST_METHOD0(active_message, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(curHash, const std::string&());
- MOCK_METHOD0(UpdateHash, void());
- MOCK_CONST_METHOD0(flag_sending_hash_change_after_awake, bool());
- MOCK_METHOD1(set_flag_sending_hash_change_after_awake, void(bool flag));
- MOCK_CONST_METHOD0(is_application_data_changed, bool());
- MOCK_METHOD1(set_is_application_data_changed,
- void(bool state_application_data));
- MOCK_METHOD0(CloseActiveMessage, void());
- MOCK_CONST_METHOD0(IsFullscreen, bool());
- MOCK_METHOD0(ChangeSupportingAppHMIType, void());
- MOCK_CONST_METHOD0(is_navi, bool());
- MOCK_METHOD1(set_is_navi, void(bool allow));
- MOCK_CONST_METHOD0(video_streaming_approved, bool());
- MOCK_METHOD1(set_video_streaming_approved, void(bool state));
- MOCK_CONST_METHOD0(audio_streaming_approved, bool());
- MOCK_METHOD1(set_audio_streaming_approved, void(bool state));
- MOCK_CONST_METHOD0(video_streaming_allowed, bool());
- MOCK_METHOD1(set_video_streaming_allowed, void(bool state));
- MOCK_CONST_METHOD0(audio_streaming_allowed, bool());
- MOCK_METHOD1(set_audio_streaming_allowed, void(bool state));
- MOCK_METHOD1(StartStreaming,
- void(protocol_handler::ServiceType service_type));
- MOCK_METHOD1(StopStreaming, void(protocol_handler::ServiceType service_type));
- MOCK_METHOD1(SuspendStreaming,
- void(protocol_handler::ServiceType service_type));
- MOCK_METHOD1(WakeUpStreaming,
- void(protocol_handler::ServiceType service_type));
- MOCK_CONST_METHOD0(is_voice_communication_supported, bool());
- MOCK_METHOD1(set_voice_communication_supported,
- void(bool is_voice_communication_supported));
- MOCK_CONST_METHOD0(app_allowed, bool());
- MOCK_CONST_METHOD0(has_been_activated, bool());
- MOCK_METHOD1(set_activated, bool(bool is_active));
- MOCK_CONST_METHOD0(version, const am::Version&());
- MOCK_METHOD1(set_hmi_application_id, void(uint32_t hmi_app_id));
-
- MOCK_CONST_METHOD0(hmi_app_id, uint32_t());
- MOCK_CONST_METHOD0(name, const std::string&());
- MOCK_METHOD1(set_folder_name, void(const std::string& folder_name));
- MOCK_CONST_METHOD0(folder_name, const std::string());
- MOCK_CONST_METHOD0(is_media_application, bool());
- MOCK_CONST_METHOD0(hmi_level, const mobile_apis::HMILevel::eType());
- MOCK_CONST_METHOD0(put_file_in_none_count, const uint32_t());
- MOCK_CONST_METHOD0(delete_file_in_none_count, const uint32_t());
- MOCK_CONST_METHOD0(list_files_in_none_count, const uint32_t());
- MOCK_CONST_METHOD0(system_context, const mobile_apis::SystemContext::eType());
- MOCK_CONST_METHOD0(audio_streaming_state,
- const mobile_apis::AudioStreamingState::eType());
- MOCK_CONST_METHOD0(app_icon_path, const std::string&());
- MOCK_CONST_METHOD0(device, connection_handler::DeviceHandle());
- MOCK_METHOD0(tts_speak_state, bool());
- MOCK_CONST_METHOD0(CurrentHmiState, am::HmiStatePtr());
- MOCK_CONST_METHOD0(RegularHmiState, am::HmiStatePtr());
- MOCK_CONST_METHOD0(PostponedHmiState, am::HmiStatePtr());
- MOCK_METHOD1(set_tts_properties_in_none, void(bool active));
- MOCK_METHOD0(tts_properties_in_none, bool());
- MOCK_METHOD1(set_tts_properties_in_full, void(bool active));
- MOCK_METHOD0(tts_properties_in_full, bool());
- MOCK_METHOD1(set_version, void(const am::Version& version));
- MOCK_METHOD1(set_name, void(const std::string& name));
- MOCK_METHOD1(set_is_media_application, void(bool is_media));
- MOCK_METHOD0(increment_put_file_in_none_count, void());
- MOCK_METHOD0(increment_delete_file_in_none_count, void());
- MOCK_METHOD0(increment_list_files_in_none_count, void());
- MOCK_METHOD1(set_app_icon_path, bool(const std::string& file_name));
- MOCK_METHOD1(set_app_allowed, void(const bool& allowed));
- MOCK_METHOD1(set_device, void(connection_handler::DeviceHandle device));
- MOCK_CONST_METHOD0(get_grammar_id, uint32_t());
- MOCK_METHOD1(set_grammar_id, void(uint32_t value));
- MOCK_METHOD1(set_protocol_version,
- void(const am::ProtocolVersion& protocol_version));
- MOCK_CONST_METHOD0(protocol_version, am::ProtocolVersion());
- MOCK_METHOD1(set_is_resuming, void(bool));
- MOCK_CONST_METHOD0(is_resuming, bool());
- MOCK_METHOD1(AddFile, bool(const am::AppFile& file));
- MOCK_CONST_METHOD0(getAppFiles, const am::AppFilesMap&());
- MOCK_METHOD1(UpdateFile, bool(const am::AppFile& file));
- MOCK_METHOD1(DeleteFile, bool(const std::string& file_name));
- MOCK_METHOD1(GetFile, const am::AppFile*(const std::string& file_name));
- MOCK_METHOD1(SubscribeToButton,
- bool(mobile_apis::ButtonName::eType btn_name));
- MOCK_METHOD1(IsSubscribedToButton,
- bool(mobile_apis::ButtonName::eType btn_name));
- MOCK_METHOD1(UnsubscribeFromButton,
- bool(mobile_apis::ButtonName::eType btn_name));
- MOCK_METHOD1(SubscribeToIVI, bool(uint32_t vehicle_info_type));
- MOCK_CONST_METHOD1(IsSubscribedToIVI, bool(uint32_t vehicle_info_type));
- MOCK_METHOD1(UnsubscribeFromIVI, bool(uint32_t vehicle_info_type));
- MOCK_METHOD0(ResetDataInNone, void());
- MOCK_METHOD2(IsCommandLimitsExceeded,
- bool(mobile_apis::FunctionID::eType cmd_id,
- am::TLimitSource source));
- MOCK_METHOD0(usage_report, am::UsageStatistics&());
- MOCK_METHOD1(SetRegularState, void(am::HmiStatePtr state));
- MOCK_METHOD1(SetPostponedState, void(am::HmiStatePtr state));
- MOCK_METHOD1(AddHMIState, void(am::HmiStatePtr state));
- MOCK_METHOD1(RemoveHMIState, void(am::HmiState::StateID state_id));
- MOCK_METHOD2(SubscribeToSoftButtons,
- void(int32_t cmd_id, const am::SoftButtonID& softbuttons_id));
- MOCK_METHOD1(IsSubscribedToSoftButton, bool(const uint32_t softbutton_id));
- MOCK_METHOD1(UnsubscribeFromSoftButtons, void(int32_t cmd_id));
- MOCK_CONST_METHOD0(IsAudioApplication, bool());
- MOCK_METHOD0(LoadPersistentFiles, void());
-
- // InitialApplicationData methods
- MOCK_CONST_METHOD0(app_types, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(vr_synonyms, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(policy_app_id, std::string());
- MOCK_CONST_METHOD0(tts_name, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(ngn_media_screen_name,
- const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(language, const mobile_apis::Language::eType&());
- MOCK_CONST_METHOD0(ui_language, const mobile_apis::Language::eType&());
- MOCK_METHOD1(set_app_types,
- void(const smart_objects::SmartObject& app_types));
- MOCK_METHOD1(set_vr_synonyms,
- void(const smart_objects::SmartObject& vr_synonyms));
- MOCK_METHOD1(set_policy_app_id, void(const std::string& policy_app_id));
- MOCK_METHOD1(set_tts_name, void(const smart_objects::SmartObject& tts_name));
- MOCK_METHOD1(set_ngn_media_screen_name,
- void(const smart_objects::SmartObject& ngn_name));
- MOCK_METHOD1(set_language,
- void(const mobile_apis::Language::eType& language));
- MOCK_METHOD1(set_ui_language,
- void(const mobile_apis::Language::eType& ui_language));
-
- // DynamicApplicationData methods
- MOCK_CONST_METHOD0(help_prompt, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(timeout_prompt, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(vr_help_title, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(vr_help, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(tbt_state, const mobile_apis::TBTState::eType&());
- MOCK_CONST_METHOD0(show_command, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(tbt_show_command, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(SubscribedButtons,
- DataAccessor<am::ButtonSubscriptions>());
- MOCK_CONST_METHOD0(SubscribedIVI,
- DataAccessor<am::VehicleInfoSubscriptions>());
- MOCK_CONST_METHOD0(keyboard_props, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(menu_title, const smart_objects::SmartObject*());
- MOCK_CONST_METHOD0(menu_icon, const smart_objects::SmartObject*());
- MOCK_METHOD1(load_global_properties,
- void(const smart_objects::SmartObject& so));
- MOCK_METHOD1(set_help_prompt,
- void(const smart_objects::SmartObject& help_prompt));
- MOCK_METHOD1(set_timeout_prompt,
- void(const smart_objects::SmartObject& timeout_prompt));
- MOCK_METHOD1(set_vr_help_title,
- void(const smart_objects::SmartObject& vr_help_title));
- MOCK_METHOD0(reset_vr_help_title, void());
- MOCK_METHOD1(set_vr_help, void(const smart_objects::SmartObject& vr_help));
- MOCK_METHOD0(reset_vr_help, void());
- MOCK_METHOD1(set_tbt_state,
- void(const mobile_apis::TBTState::eType& tbt_state));
- MOCK_METHOD1(set_show_command,
- void(const smart_objects::SmartObject& show_command));
- MOCK_METHOD1(set_tbt_show_command,
- void(const smart_objects::SmartObject& tbt_show));
- MOCK_METHOD1(set_keyboard_props,
- void(const smart_objects::SmartObject& keyboard_props));
- MOCK_METHOD1(set_menu_title,
- void(const smart_objects::SmartObject& menu_title));
- MOCK_METHOD1(set_menu_icon,
- void(const smart_objects::SmartObject& menu_icon));
- MOCK_CONST_METHOD0(audio_stream_retry_number, uint32_t());
- MOCK_METHOD1(set_audio_stream_retry_number,
- void(const uint32_t& audio_stream_retry_number));
- MOCK_CONST_METHOD0(video_stream_retry_number, uint32_t());
- MOCK_METHOD1(set_video_stream_retry_number,
- void(const uint32_t& video_stream_retry_number));
- MOCK_METHOD2(AddCommand, void(uint32_t cmd_id,
- const smart_objects::SmartObject& command));
- MOCK_METHOD1(RemoveCommand, void(uint32_t cmd_id));
- MOCK_METHOD1(FindCommand, smart_objects::SmartObject*(uint32_t cmd_id));
- MOCK_METHOD2(AddSubMenu,
- void(uint32_t menu_id, const smart_objects::SmartObject& menu));
- MOCK_METHOD1(RemoveSubMenu, void(uint32_t menu_id));
- MOCK_CONST_METHOD1(FindSubMenu,
- smart_objects::SmartObject*(uint32_t menu_id));
- MOCK_METHOD1(IsSubMenuNameAlreadyExist, bool(const std::string& name));
- MOCK_METHOD2(AddChoiceSet,
- void(uint32_t choice_set_id,
- const smart_objects::SmartObject& choice_set));
- MOCK_METHOD1(RemoveChoiceSet, void(uint32_t choice_set_id));
- MOCK_METHOD1(FindChoiceSet,
- smart_objects::SmartObject*(uint32_t choice_set_id));
- MOCK_METHOD3(AddPerformInteractionChoiceSet,
- void(uint32_t correlation_id, uint32_t choice_set_id,
- const smart_objects::SmartObject& choice_set));
- MOCK_METHOD1(DeletePerformInteractionChoiceSet,
- void(uint32_t correlation_id));
- MOCK_CONST_METHOD0(performinteraction_choice_set_map,
- DataAccessor<am::PerformChoiceSetMap>());
- MOCK_CONST_METHOD0(commands_map, DataAccessor<am::CommandsMap>());
- MOCK_CONST_METHOD0(sub_menu_map, DataAccessor<am::SubMenuMap>());
- MOCK_CONST_METHOD0(choice_set_map, DataAccessor<am::ChoiceSetMap>());
- MOCK_METHOD1(set_perform_interaction_active, void(uint32_t active));
- MOCK_CONST_METHOD0(is_perform_interaction_active, uint32_t());
- MOCK_METHOD1(set_perform_interaction_mode, void(int32_t mode));
- MOCK_CONST_METHOD0(perform_interaction_mode, int32_t());
- MOCK_METHOD1(set_reset_global_properties_active, void(bool active));
- MOCK_CONST_METHOD0(is_reset_global_properties_active, bool());
- MOCK_CONST_METHOD0(app_id, uint32_t());
-};
-
-} // namespace state_controller_test
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_APPLICATION_MOCK_H_
diff --git a/src/components/application_manager/test/state_controller/include/state_controller_mock.h b/src/components/application_manager/test/state_controller/include/state_controller_mock.h
deleted file mode 100644
index b9f7dd30dd..0000000000
--- a/src/components/application_manager/test/state_controller/include/state_controller_mock.h
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATE_CONTROLLER_MOCK
-#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATE_CONTROLLER_MOCK
-
-#include "gmock/gmock.h"
-#include "application_manager/application.h"
-#include "application_manager/hmi_state.h"
-#include "application_manager/state_controller.h"
-#include "application_manager/application_manager.h"
-#include "interfaces/MOBILE_API.h"
-
-namespace state_controller_test {
-namespace am = application_manager;
-
-class StateControllerMock :public am::StateController {
- public:
- MOCK_METHOD2(SetRegularState, void (
- am::ApplicationSharedPtr, const mobile_apis::AudioStreamingState::eType));
- MOCK_METHOD2(SetRegularState, void (
- am::ApplicationSharedPtr, const mobile_apis::SystemContext::eType));
- MOCK_METHOD3(OnStateChanged, void (
- am::ApplicationSharedPtr, am::HmiStatePtr, am::HmiStatePtr));
- MOCK_METHOD1(ApplyStatesForApp, void (am::ApplicationSharedPtr));
- MOCK_METHOD0(OnNaviStreamingStarted, void ());
- MOCK_METHOD0(OnNaviStreamingStopped, void ());
-};
-
-}
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATE_CONTROLLER_MOCK
diff --git a/src/components/application_manager/test/state_controller/include/statistics_manager_mock.h b/src/components/application_manager/test/state_controller/include/statistics_manager_mock.h
deleted file mode 100644
index 4e2dae78d1..0000000000
--- a/src/components/application_manager/test/state_controller/include/statistics_manager_mock.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATISTICS_MANAGER_MOCK_H_
-#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATISTICS_MANAGER_MOCK_H_
-
-#include <string>
-#include "gmock/gmock.h"
-#include "usage_statistics/statistics_manager.h"
-
-namespace state_controller_test {
-namespace us = usage_statistics;
-
-class StatisticsManagerMock : public us::StatisticsManager {
- public:
- MOCK_METHOD1(Increment, void (us::GlobalCounterId));
- MOCK_METHOD2(Increment, void (const std::string&, us::AppCounterId));
- MOCK_METHOD3(Set, void (const std::string&, us::AppInfoId, const std::string&));
- MOCK_METHOD3(Add, void (const std::string&, us::AppStopwatchId, int32_t));
-};
-
-} // namespace state_controller_test
-#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_STATE_CONTROLLER_INCLUDE_STATISTICS_MANAGER_MOCK_H_
diff --git a/src/components/application_manager/test/state_controller/state_controller_test.cc b/src/components/application_manager/test/state_controller/state_controller_test.cc
index 488d12b502..f19a0896d1 100644
--- a/src/components/application_manager/test/state_controller/state_controller_test.cc
+++ b/src/components/application_manager/test/state_controller/state_controller_test.cc
@@ -30,21 +30,35 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include <gtest/gtest.h>
+#include "gtest/gtest.h"
#include "application_manager/hmi_state.h"
-#include "application_manager/state_controller.h"
+#include "application_manager/state_controller_impl.h"
#include "application_manager/usage_statistics.h"
-#include "application_manager_mock.h"
-#include "application_mock.h"
-#include "statistics_manager_mock.h"
+#include "application_manager/application_manager_impl.h"
+#include "application_manager/mock_application.h"
+#include "connection_handler/mock_connection_handler_settings.h"
+#include "connection_handler/connection_handler_impl.h"
+#include "transport_manager/mock_transport_manager.h"
+#include "application_manager/statistics_manager_mock.h"
#include "utils/lock.h"
#include "utils/data_accessor.h"
#include "utils/make_shared.h"
#include "application_manager/message_helper.h"
#include "application_manager/event_engine/event.h"
#include "application_manager/smart_object_keys.h"
+#include "application_manager/mock_message_helper.h"
+#include "policy/mock_policy_settings.h"
+#include "protocol_handler/mock_session_observer.h"
+#include "connection_handler/mock_connection_handler.h"
+#include "application_manager/policies/mock_policy_handler_interface.h"
+#include "application_manager/mock_event_dispatcher.h"
+#include "application_manager/resumption/resume_ctrl.h"
+#include "application_manager/mock_application_manager.h"
namespace am = application_manager;
+using am::HmiState;
+using am::HmiStatePtr;
+using am::UsageStatistics;
using ::testing::_;
using ::testing::Return;
using ::testing::ReturnRef;
@@ -53,30 +67,12 @@ using ::testing::Mock;
using ::testing::NiceMock;
using ::testing::InSequence;
using ::testing::Truly;
+using ::testing::AtLeast;
-class MessageHelperMock {
- public:
- MOCK_METHOD3(SendActivateAppToHMI,
- uint32_t(uint32_t const app_id,
- hmi_apis::Common_HMILevel::eType level,
- bool send_policy_priority));
- MOCK_METHOD1(SendOnResumeAudioSourceToHMI, void(const uint32_t app_id));
-};
-
-static MessageHelperMock* message_helper_mock_;
-
-uint32_t application_manager::MessageHelper::SendActivateAppToHMI(
- uint32_t const app_id, hmi_apis::Common_HMILevel::eType level,
- bool send_policy_priority) {
- return message_helper_mock_->SendActivateAppToHMI(app_id, level,
- send_policy_priority);
-}
-
-void application_manager::MessageHelper::SendOnResumeAudioSourceToHMI(
- const uint32_t app_id) {
- message_helper_mock_->SendOnResumeAudioSourceToHMI(app_id);
-}
+static application_manager::MockMessageHelper* message_helper_mock_;
+namespace test {
+namespace components {
namespace state_controller_test {
struct HmiStatesComparator {
@@ -88,14 +84,14 @@ struct HmiStatesComparator {
mobile_apis::HMILevel::eType hmi_level,
mobile_apis::AudioStreamingState::eType audio_streaming_state,
mobile_apis::SystemContext::eType system_context)
- : hmi_level_(hmi_level),
- audio_streaming_state_(audio_streaming_state),
- system_context_(system_context) {}
+ : hmi_level_(hmi_level)
+ , audio_streaming_state_(audio_streaming_state)
+ , system_context_(system_context) {}
HmiStatesComparator(am::HmiStatePtr state_ptr)
- : hmi_level_(state_ptr->hmi_level()),
- audio_streaming_state_(state_ptr->audio_streaming_state()),
- system_context_(state_ptr->system_context()) {}
+ : hmi_level_(state_ptr->hmi_level())
+ , audio_streaming_state_(state_ptr->audio_streaming_state())
+ , system_context_(state_ptr->system_context()) {}
bool operator()(am::HmiStatePtr state_ptr) const {
return state_ptr->hmi_level() == hmi_level_ &&
@@ -107,8 +103,7 @@ struct HmiStatesComparator {
struct HmiStatesIDComparator {
am::HmiState::StateID state_id_;
- HmiStatesIDComparator(am::HmiState::StateID state_id)
- : state_id_(state_id) {}
+ HmiStatesIDComparator(am::HmiState::StateID state_id) : state_id_(state_id) {}
bool operator()(am::HmiStatePtr state_ptr) const {
return state_ptr->state_id() == state_id_;
@@ -122,53 +117,66 @@ struct HmiStatesIDComparator {
#define NAVI true
#define NOT_NAVI false
-class StateControllerTest : public ::testing::Test {
+enum ApplicationType {
+ APP_TYPE_NON_MEDIA,
+ APP_TYPE_NAVI,
+ APP_TYPE_MEDIA,
+ APP_TYPE_ATTENUATED
+};
+
+class StateControllerImplTest : public ::testing::Test {
public:
- StateControllerTest()
- : ::testing::Test(),
- usage_stat("0", utils::SharedPtr<us::StatisticsManager>(
- new StatisticsManagerMock)),
- applications_(application_set_, applications_lock_),
- state_ctrl_(&app_manager_mock_) {}
- NiceMock<ApplicationManagerMock> app_manager_mock_;
+ StateControllerImplTest()
+ : ::testing::Test()
+ , usage_stat("0",
+ utils::SharedPtr<usage_statistics::StatisticsManager>(
+
+ new state_controller_test::MockStatisticsManager))
+ , applications_(application_set_, applications_lock_) {}
+ NiceMock<application_manager_test::MockApplicationManager> app_manager_mock_;
+ NiceMock<policy_test::MockPolicyHandlerInterface> policy_interface_;
+ NiceMock<connection_handler_test::MockConnectionHandler>
+ mock_connection_handler_;
+ NiceMock<protocol_handler_test::MockSessionObserver> mock_session_observer_;
am::UsageStatistics usage_stat;
+ NiceMock<event_engine_test::MockEventDispatcher> mock_event_dispatcher_;
am::ApplicationSet application_set_;
mutable sync_primitives::Lock applications_lock_;
DataAccessor<am::ApplicationSet> applications_;
- am::StateController state_ctrl_;
+ utils::SharedPtr<am::StateControllerImpl> state_ctrl_;
am::ApplicationSharedPtr simple_app_;
- NiceMock<ApplicationMock>* simple_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* simple_app_ptr_;
uint32_t simple_app_id_ = 1721;
am::ApplicationSharedPtr navi_app_;
- NiceMock<ApplicationMock>* navi_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* navi_app_ptr_;
uint32_t navi_app_id_ = 1762;
am::ApplicationSharedPtr media_app_;
- NiceMock<ApplicationMock>* media_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* media_app_ptr_;
uint32_t media_app_id_ = 1801;
am::ApplicationSharedPtr vc_app_;
- NiceMock<ApplicationMock>* vc_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* vc_app_ptr_;
uint32_t vc_app_id_ = 1825;
am::ApplicationSharedPtr media_navi_app_;
- NiceMock<ApplicationMock>* media_navi_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* media_navi_app_ptr_;
uint32_t media_navi_app_id_ = 1855;
am::ApplicationSharedPtr media_vc_app_;
- NiceMock<ApplicationMock>* media_vc_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* media_vc_app_ptr_;
uint32_t media_vc_app_id_ = 1881;
am::ApplicationSharedPtr navi_vc_app_;
- NiceMock<ApplicationMock>* navi_vc_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* navi_vc_app_ptr_;
uint32_t navi_vc_app_id_ = 1894;
am::ApplicationSharedPtr media_navi_vc_app_;
- NiceMock<ApplicationMock>* media_navi_vc_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* media_navi_vc_app_ptr_;
uint32_t media_navi_vc_app_id_ = 1922;
std::vector<am::HmiStatePtr> valid_states_for_audio_app_;
@@ -177,6 +185,12 @@ class StateControllerTest : public ::testing::Test {
std::vector<am::HmiStatePtr> invalid_states_for_not_audio_app;
std::vector<am::HmiStatePtr> invalid_states_for_audio_app;
std::vector<am::HmiState::StateID> valid_state_ids_;
+ std::vector<am::ApplicationSharedPtr> applications_list_;
+
+ connection_handler_test::MockConnectionHandlerSettings
+ mock_connection_handler__settings;
+ transport_manager_test::MockTransportManager mock_transport_manager;
+ connection_handler::ConnectionHandlerImpl* conn_handler;
am::HmiStatePtr createHmiState(
mobile_apis::HMILevel::eType hmi_level,
@@ -187,18 +201,382 @@ class StateControllerTest : public ::testing::Test {
namespace SystemContext = mobile_apis::SystemContext;
am::HmiStatePtr state =
- utils::MakeShared<am::HmiState>(simple_app_id_, &app_manager_mock_);
+ utils::MakeShared<am::HmiState>(simple_app_id_, app_manager_mock_);
state->set_hmi_level(hmi_level);
state->set_audio_streaming_state(aidio_ss);
state->set_system_context(system_context);
return state;
}
+ /**
+ * @brief Prepare list of resultant HMI states for testing HMIState
+ * @param result_hmi state will contain resultant HMI states.
+ */
+ void PrepareCommonStateResults(
+ std::vector<am::HmiStatePtr>& result_hmi_state) {
+ namespace HMILevel = mobile_apis::HMILevel;
+ namespace AudioStreamingState = mobile_apis::AudioStreamingState;
+ namespace SystemContext = mobile_apis::SystemContext;
+ result_hmi_state.push_back(createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_VRSESSION));
+ result_hmi_state.push_back(createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MENU));
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_HMI_OBSCURED));
+ result_hmi_state.push_back(createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_ALERT));
+ result_hmi_state.push_back(createHmiState(HMILevel::HMI_BACKGROUND,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ }
+
+ /**
+ * @brief Prepare list of resultant HMI states for testing HMIState, for
+ * case when SDL supports attenuated mode
+ * @param result_hmi state will contain resultant HMI states.
+ */
+ void PrepareStateResultsForAttenuated(
+ std::vector<am::HmiStatePtr>& result_hmi_state) {
+ namespace HMILevel = mobile_apis::HMILevel;
+ namespace AudioStreamingState = mobile_apis::AudioStreamingState;
+ namespace SystemContext = mobile_apis::SystemContext;
+ PrepareCommonStateResults(result_hmi_state);
+ result_hmi_state.push_back(createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::ATTENUATED,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::ATTENUATED,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::ATTENUATED,
+ SystemContext::SYSCTXT_MAIN));
+ }
+
+ /**
+ * @brief Prepare list of resultant HMI states for testing HMIState, for
+ * case if phone call mode is active
+ * @param result_hmi state will contain resultant HMI states.
+ */
+ void PreparePhoneCallHMIStateResults(
+ std::vector<am::HmiStatePtr>& result_hmi_state, ApplicationType app_t) {
+ namespace HMILevel = mobile_apis::HMILevel;
+ namespace AudioStreamingState = mobile_apis::AudioStreamingState;
+ namespace SystemContext = mobile_apis::SystemContext;
+
+ switch (app_t) {
+ case APP_TYPE_NON_MEDIA: {
+ PrepareCommonStateResults(result_hmi_state);
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ break;
+ }
+ case APP_TYPE_MEDIA: {
+ PrepareCommonStateResults(result_hmi_state);
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_BACKGROUND,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_BACKGROUND,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_BACKGROUND,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_BACKGROUND,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ break;
+ }
+ case APP_TYPE_NAVI: {
+ PrepareCommonStateResults(result_hmi_state);
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ break;
+ }
+ default: { break; }
+ }
+ }
+
+ /**
+ * @brief Prepare list of resultant HMI states for testing HMIState, for
+ * case if VR or TTS mode is active
+ * @param result_hmi state will contain resultant HMI states.
+ */
+ void PrepareVRTTSHMIStateResults(
+ std::vector<am::HmiStatePtr>& result_hmi_state, ApplicationType app_t) {
+ namespace HMILevel = mobile_apis::HMILevel;
+ namespace AudioStreamingState = mobile_apis::AudioStreamingState;
+ namespace SystemContext = mobile_apis::SystemContext;
+ switch (app_t) {
+ case APP_TYPE_NON_MEDIA: {
+ PrepareCommonStateResults(result_hmi_state);
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ break;
+ }
+ case APP_TYPE_MEDIA:
+ case APP_TYPE_NAVI: {
+ PrepareCommonStateResults(result_hmi_state);
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ break;
+ }
+ case APP_TYPE_ATTENUATED: {
+ PrepareStateResultsForAttenuated(result_hmi_state);
+ break;
+ }
+ default: { break; }
+ }
+ }
+
+ /**
+ * @brief Prepare list of resultant HMI states for testing HMIState, for
+ * case if navi streaming mode is active
+ * @param result_hmi state will contain resultant HMI states.
+ */
+ void PrepareNaviStreamingHMIStateResults(
+ std::vector<am::HmiStatePtr>& result_hmi_state, ApplicationType app_t) {
+ namespace HMILevel = mobile_apis::HMILevel;
+ namespace AudioStreamingState = mobile_apis::AudioStreamingState;
+ namespace SystemContext = mobile_apis::SystemContext;
+ switch (app_t) {
+ case APP_TYPE_NON_MEDIA: {
+ PrepareCommonStateResults(result_hmi_state);
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ break;
+ }
+ case APP_TYPE_MEDIA: {
+ PrepareCommonStateResults(result_hmi_state);
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::ATTENUATED,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ break;
+ }
+ case APP_TYPE_NAVI: {
+ result_hmi_state = valid_states_for_audio_app_;
+ break;
+ }
+ default: { break; }
+ }
+ }
+
+ /**
+ * @brief Prepare list of resultant HMI states for testing HMIState, for
+ * case if navi streaming mode and TTS mode are active and SDL supports
+ * attenuated mode
+ * @param result_hmi state will contain resultant HMI states.
+ */
+ void PrepareNaviStreamTTSStateResult(
+ std::vector<am::HmiStatePtr>& result_hmi_state, ApplicationType app_t) {
+ namespace HMILevel = mobile_apis::HMILevel;
+ namespace AudioStreamingState = mobile_apis::AudioStreamingState;
+ namespace SystemContext = mobile_apis::SystemContext;
+ switch (app_t) {
+ case APP_TYPE_NON_MEDIA: {
+ PrepareCommonStateResults(result_hmi_state);
+ result_hmi_state.push_back(
+ createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ break;
+ }
+ case APP_TYPE_MEDIA:
+ case APP_TYPE_NAVI: {
+ PrepareStateResultsForAttenuated(result_hmi_state);
+ break;
+ }
+ default: { break; }
+ }
+ }
+
+ ApplicationType AppType(uint32_t app_id) {
+ // TODO(AOleynik): Currently there is ongoing discussion regarding mixed
+ // application properties, i.e. is_media_application flag from RAI and
+ // AppHMITypes (NAVIGATION, etc.). Most likely logic should be changed
+ // after conclusion on APPLINK-20231
+ std::vector<am::ApplicationSharedPtr>::iterator app = std::find_if(
+ applications_list_.begin(),
+ applications_list_.end(),
+ [app_id](am::ApplicationSharedPtr a) { return app_id == a->app_id(); });
+
+ if (app == applications_list_.end()) {
+ return APP_TYPE_NON_MEDIA;
+ }
+
+ if ((*app)->is_navi()) {
+ return APP_TYPE_NAVI;
+ }
+ if ((*app)->is_media_application()) {
+ return APP_TYPE_MEDIA;
+ }
+ return APP_TYPE_NON_MEDIA;
+ }
+
+ void TestSetState(am::ApplicationSharedPtr app,
+ am::HmiStatePtr hmi_state,
+ ApplicationType app_t,
+ void (StateControllerImplTest::*call_back)(
+ std::vector<am::HmiStatePtr>&, ApplicationType)) {
+ InsertApplication(app);
+ std::vector<am::HmiStatePtr> result_hmi_state;
+ (this->*call_back)(result_hmi_state, app_t);
+ std::vector<am::HmiStatePtr>::iterator it_begin;
+ std::vector<am::HmiStatePtr>::iterator it_end;
+ if (APP_TYPE_NON_MEDIA == app_t) {
+ it_begin = valid_states_for_not_audio_app_.begin();
+ it_end = valid_states_for_not_audio_app_.end();
+ ASSERT_TRUE(result_hmi_state.size() ==
+ valid_states_for_not_audio_app_.size());
+ } else {
+ it_begin = valid_states_for_audio_app_.begin();
+ it_end = valid_states_for_audio_app_.end();
+ ASSERT_TRUE(result_hmi_state.size() ==
+ valid_states_for_audio_app_.size());
+ }
+ std::vector<am::HmiStatePtr>::iterator it_result_begin =
+ result_hmi_state.begin();
+ for (; it_begin != it_end; ++it_begin, ++it_result_begin) {
+ hmi_state->set_parent(*it_begin);
+ HmiStatesComparator st_comp(hmi_state);
+ ASSERT_TRUE(st_comp(*it_result_begin));
+ }
+ }
+
+ void TestSetSeveralState(
+ am::ApplicationSharedPtr app,
+ am::HmiStatePtr first_hmi_state,
+ am::HmiStatePtr second_hmi_state,
+ ApplicationType app_t,
+ void (StateControllerImplTest::*call_back)(std::vector<am::HmiStatePtr>&,
+ ApplicationType)) {
+ InsertApplication(app);
+ std::vector<am::HmiStatePtr> result_hmi_state;
+ (this->*call_back)(result_hmi_state, app_t);
+ std::vector<am::HmiStatePtr>::iterator it_begin;
+ std::vector<am::HmiStatePtr>::iterator it_end;
+ if (APP_TYPE_NON_MEDIA == app_t) {
+ it_begin = valid_states_for_not_audio_app_.begin();
+ it_end = valid_states_for_not_audio_app_.end();
+ ASSERT_TRUE(result_hmi_state.size() ==
+ valid_states_for_not_audio_app_.size());
+ } else {
+ it_begin = valid_states_for_audio_app_.begin();
+ it_end = valid_states_for_audio_app_.end();
+ ASSERT_TRUE(result_hmi_state.size() ==
+ valid_states_for_audio_app_.size());
+ }
+ std::vector<am::HmiStatePtr>::iterator it_result_begin =
+ result_hmi_state.begin();
+ for (; it_begin != it_end; ++it_begin, ++it_result_begin) {
+ first_hmi_state->set_parent(*it_begin);
+ second_hmi_state->set_parent(first_hmi_state);
+ HmiStatesComparator st_comp(second_hmi_state);
+ ASSERT_TRUE(st_comp(*it_result_begin))
+ << second_hmi_state->audio_streaming_state() << "."
+ << second_hmi_state->hmi_level() << "."
+ << second_hmi_state->system_context() << "_"
+ << (*it_result_begin)->audio_streaming_state() << "."
+ << (*it_result_begin)->hmi_level() << "."
+ << (*it_result_begin)->system_context() << "_";
+ }
+ }
+
+ template <typename T, typename Q>
+ void TestMixState(void (StateControllerImplTest::*call_back_result)(
+ std::vector<am::HmiStatePtr>&, ApplicationType)) {
+ std::vector<am::ApplicationSharedPtr>::iterator it_begin =
+ applications_list_.begin();
+ std::vector<am::ApplicationSharedPtr>::iterator it_end =
+ applications_list_.end();
+ ApplicationType app_type;
+ uint32_t app_id;
+ am::ApplicationSharedPtr app;
+ for (; it_begin != it_end; ++it_begin) {
+ app_id = (*it_begin)->app_id();
+ app_type = AppType(app_id);
+ app = (*it_begin);
+ am::HmiStatePtr state_first =
+ utils::MakeShared<T>(app_id, app_manager_mock_);
+ am::HmiStatePtr state_second =
+ utils::MakeShared<Q>(app_id, app_manager_mock_);
+ TestSetSeveralState(
+ app, state_first, state_second, app_type, call_back_result);
+ TestSetSeveralState(
+ app, state_second, state_first, app_type, call_back_result);
+ }
+ }
+
protected:
- am::ApplicationSharedPtr ConfigureApp(NiceMock<ApplicationMock>** app_mock,
- uint32_t app_id, bool media, bool navi,
- bool vc) {
- *app_mock = new NiceMock<ApplicationMock>;
+ am::ApplicationSharedPtr ConfigureApp(
+ NiceMock<application_manager_test::MockApplication>** app_mock,
+ uint32_t app_id,
+ bool media,
+ bool navi,
+ bool vc) {
+ *app_mock = new NiceMock<application_manager_test::MockApplication>;
Mock::AllowLeak(*app_mock); // WorkAround for gogletest bug
am::ApplicationSharedPtr app(*app_mock);
@@ -222,114 +600,146 @@ class StateControllerTest : public ::testing::Test {
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
// Valid states for not audio app
- message_helper_mock_ = new MessageHelperMock;
+ message_helper_mock_ =
+ application_manager::MockMessageHelper::message_helper_mock();
valid_states_for_not_audio_app_.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
SystemContext::SYSCTXT_MAIN));
valid_states_for_not_audio_app_.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
SystemContext::SYSCTXT_VRSESSION));
valid_states_for_not_audio_app_.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
SystemContext::SYSCTXT_MENU));
valid_states_for_not_audio_app_.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
SystemContext::SYSCTXT_HMI_OBSCURED));
valid_states_for_not_audio_app_.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
SystemContext::SYSCTXT_ALERT));
- valid_states_for_not_audio_app_.push_back(createHmiState(
- HMILevel::HMI_BACKGROUND, AudioStreamingState::NOT_AUDIBLE,
- SystemContext::SYSCTXT_MAIN));
valid_states_for_not_audio_app_.push_back(
- createHmiState(HMILevel::HMI_FULL, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::HMI_BACKGROUND,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ valid_states_for_not_audio_app_.push_back(
+ createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::NOT_AUDIBLE,
SystemContext::SYSCTXT_MAIN));
// Valid states audio app
valid_states_for_audio_app_.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
SystemContext::SYSCTXT_MAIN));
valid_states_for_audio_app_.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
SystemContext::SYSCTXT_VRSESSION));
valid_states_for_audio_app_.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
SystemContext::SYSCTXT_MENU));
valid_states_for_audio_app_.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
SystemContext::SYSCTXT_HMI_OBSCURED));
valid_states_for_audio_app_.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
SystemContext::SYSCTXT_ALERT));
- valid_states_for_audio_app_.push_back(createHmiState(
- HMILevel::HMI_BACKGROUND, AudioStreamingState::NOT_AUDIBLE,
- SystemContext::SYSCTXT_MAIN));
valid_states_for_audio_app_.push_back(
- createHmiState(HMILevel::HMI_LIMITED, AudioStreamingState::AUDIBLE,
+ createHmiState(HMILevel::HMI_BACKGROUND,
+ AudioStreamingState::NOT_AUDIBLE,
SystemContext::SYSCTXT_MAIN));
valid_states_for_audio_app_.push_back(
- createHmiState(HMILevel::HMI_LIMITED, AudioStreamingState::ATTENUATED,
+ createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::AUDIBLE,
SystemContext::SYSCTXT_MAIN));
valid_states_for_audio_app_.push_back(
- createHmiState(HMILevel::HMI_FULL, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::ATTENUATED,
SystemContext::SYSCTXT_MAIN));
valid_states_for_audio_app_.push_back(
- createHmiState(HMILevel::HMI_FULL, AudioStreamingState::AUDIBLE,
+ createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ valid_states_for_audio_app_.push_back(
+ createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::AUDIBLE,
SystemContext::SYSCTXT_MAIN));
// Common Invalid States
common_invalid_states_.push_back(
- createHmiState(HMILevel::INVALID_ENUM, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::INVALID_ENUM,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ common_invalid_states_.push_back(
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::INVALID_ENUM,
SystemContext::SYSCTXT_MAIN));
common_invalid_states_.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::INVALID_ENUM,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::INVALID_ENUM));
+ common_invalid_states_.push_back(
+ createHmiState(HMILevel::INVALID_ENUM,
+ AudioStreamingState::INVALID_ENUM,
SystemContext::SYSCTXT_MAIN));
common_invalid_states_.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::INVALID_ENUM,
SystemContext::INVALID_ENUM));
- common_invalid_states_.push_back(createHmiState(
- HMILevel::INVALID_ENUM, AudioStreamingState::INVALID_ENUM,
- SystemContext::SYSCTXT_MAIN));
common_invalid_states_.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::INVALID_ENUM,
+ createHmiState(HMILevel::INVALID_ENUM,
+ AudioStreamingState::INVALID_ENUM,
SystemContext::INVALID_ENUM));
- common_invalid_states_.push_back(createHmiState(
- HMILevel::INVALID_ENUM, AudioStreamingState::INVALID_ENUM,
- SystemContext::INVALID_ENUM));
- common_invalid_states_.push_back(createHmiState(
- HMILevel::INVALID_ENUM, AudioStreamingState::INVALID_ENUM,
- SystemContext::INVALID_ENUM));
+
// Invalid States for audio apps
invalid_states_for_audio_app.push_back(
- createHmiState(HMILevel::HMI_LIMITED, AudioStreamingState::NOT_AUDIBLE,
+ createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN));
+ invalid_states_for_audio_app.push_back(
+ createHmiState(HMILevel::HMI_BACKGROUND,
+ AudioStreamingState::AUDIBLE,
SystemContext::SYSCTXT_MAIN));
invalid_states_for_audio_app.push_back(
- createHmiState(HMILevel::HMI_BACKGROUND, AudioStreamingState::AUDIBLE,
+ createHmiState(HMILevel::HMI_BACKGROUND,
+ AudioStreamingState::ATTENUATED,
SystemContext::SYSCTXT_MAIN));
- invalid_states_for_audio_app.push_back(createHmiState(
- HMILevel::HMI_BACKGROUND, AudioStreamingState::ATTENUATED,
- SystemContext::SYSCTXT_MAIN));
invalid_states_for_audio_app.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::AUDIBLE,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::AUDIBLE,
SystemContext::SYSCTXT_MAIN));
invalid_states_for_audio_app.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::ATTENUATED,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::ATTENUATED,
SystemContext::SYSCTXT_MAIN));
invalid_states_for_audio_app.push_back(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::ATTENUATED,
+ createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::ATTENUATED,
SystemContext::SYSCTXT_MAIN));
// Invalid States for not audio apps
invalid_states_for_not_audio_app.push_back(
- createHmiState(HMILevel::HMI_LIMITED, AudioStreamingState::ATTENUATED,
+ createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::ATTENUATED,
SystemContext::SYSCTXT_MAIN));
invalid_states_for_not_audio_app.push_back(
- createHmiState(HMILevel::HMI_LIMITED, AudioStreamingState::AUDIBLE,
+ createHmiState(HMILevel::HMI_LIMITED,
+ AudioStreamingState::AUDIBLE,
SystemContext::SYSCTXT_MAIN));
invalid_states_for_not_audio_app.push_back(
- createHmiState(HMILevel::HMI_FULL, AudioStreamingState::ATTENUATED,
+ createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::ATTENUATED,
SystemContext::SYSCTXT_MAIN));
invalid_states_for_not_audio_app.push_back(
- createHmiState(HMILevel::HMI_FULL, AudioStreamingState::AUDIBLE,
+ createHmiState(HMILevel::HMI_FULL,
+ AudioStreamingState::AUDIBLE,
SystemContext::SYSCTXT_MAIN));
// Valid state ids
@@ -341,21 +751,29 @@ class StateControllerTest : public ::testing::Test {
}
void ConfigureApps() {
- simple_app_ = ConfigureApp(&simple_app_ptr_, simple_app_id_, NOT_MEDIA,
- NOT_NAVI, NOT_VC);
+ simple_app_ = ConfigureApp(
+ &simple_app_ptr_, simple_app_id_, NOT_MEDIA, NOT_NAVI, NOT_VC);
media_app_ =
ConfigureApp(&media_app_ptr_, media_app_id_, MEDIA, NOT_NAVI, NOT_VC);
navi_app_ =
ConfigureApp(&navi_app_ptr_, navi_app_id_, NOT_MEDIA, NAVI, NOT_VC);
vc_app_ = ConfigureApp(&vc_app_ptr_, vc_app_id_, NOT_MEDIA, NOT_NAVI, VC);
- media_navi_app_ = ConfigureApp(&media_navi_app_ptr_, media_navi_app_id_,
- MEDIA, NAVI, NOT_VC);
+ media_navi_app_ = ConfigureApp(
+ &media_navi_app_ptr_, media_navi_app_id_, MEDIA, NAVI, NOT_VC);
media_vc_app_ =
ConfigureApp(&media_vc_app_ptr_, media_vc_app_id_, MEDIA, NOT_NAVI, VC);
navi_vc_app_ =
ConfigureApp(&navi_vc_app_ptr_, navi_vc_app_id_, NOT_MEDIA, NAVI, VC);
- media_navi_vc_app_ = ConfigureApp(&media_navi_vc_app_ptr_,
- media_navi_vc_app_id_, MEDIA, NAVI, VC);
+ media_navi_vc_app_ = ConfigureApp(
+ &media_navi_vc_app_ptr_, media_navi_vc_app_id_, MEDIA, NAVI, VC);
+ applications_list_.push_back(simple_app_);
+ applications_list_.push_back(media_app_);
+ applications_list_.push_back(navi_app_);
+ applications_list_.push_back(vc_app_);
+ applications_list_.push_back(media_navi_app_);
+ applications_list_.push_back(media_vc_app_);
+ applications_list_.push_back(navi_vc_app_);
+ applications_list_.push_back(media_navi_vc_app_);
}
void CheckAppConfiguration() {
ASSERT_EQ(simple_app_.get(), simple_app_ptr_);
@@ -413,20 +831,55 @@ class StateControllerTest : public ::testing::Test {
ASSERT_TRUE(media_navi_vc_app_->is_voice_communication_supported());
}
- void SetUp() {
+ virtual void SetUp() OVERRIDE {
+ ON_CALL(app_manager_mock_, event_dispatcher())
+ .WillByDefault(ReturnRef(mock_event_dispatcher_));
+ state_ctrl_ = utils::MakeShared<am::StateControllerImpl>(app_manager_mock_);
+
ON_CALL(app_manager_mock_, applications())
.WillByDefault(Return(applications_));
ConfigureApps();
CheckAppConfiguration();
FillStatesLists();
+ SetConnection();
+ }
+
+ void TearDown() OVERRIDE {
+ delete conn_handler;
}
- void TearDown() { delete message_helper_mock_; }
+ void SetConnection() {
+ conn_handler = new connection_handler::ConnectionHandlerImpl(
+ mock_connection_handler__settings, mock_transport_manager);
+ ON_CALL(app_manager_mock_, connection_handler())
+ .WillByDefault(ReturnRef(*conn_handler));
+ }
+
+ void SetBCActivateAppRequestToHMI(
+ const hmi_apis::Common_HMILevel::eType hmi_lvl, uint32_t corr_id) {
+ ON_CALL(mock_connection_handler_, get_session_observer())
+ .WillByDefault(ReturnRef(mock_session_observer_));
+ ON_CALL(app_manager_mock_, connection_handler())
+ .WillByDefault(ReturnRef(mock_connection_handler_));
+ ON_CALL(app_manager_mock_, GetPolicyHandler())
+ .WillByDefault(ReturnRef(policy_interface_));
+ smart_objects::SmartObjectSPtr bc_activate_app_request =
+ new smart_objects::SmartObject();
+ (*bc_activate_app_request)[am::strings::params]
+ [am::strings::correlation_id] = corr_id;
+ ON_CALL(*message_helper_mock_,
+ GetBCActivateAppRequestToHMI(_, _, _, hmi_lvl, _, _))
+ .WillByDefault(Return(bc_activate_app_request));
+
+ ON_CALL(app_manager_mock_, ManageHMICommand(bc_activate_app_request))
+ .WillByDefault(Return(true));
+ }
- void ExpectSuccesfullSetHmiState(am::ApplicationSharedPtr app,
- NiceMock<ApplicationMock>* app_mock,
- am::HmiStatePtr old_state,
- am::HmiStatePtr new_state) {
+ void ExpectSuccesfullSetHmiState(
+ am::ApplicationSharedPtr app,
+ NiceMock<application_manager_test::MockApplication>* app_mock,
+ am::HmiStatePtr old_state,
+ am::HmiStatePtr new_state) {
EXPECT_CALL(*app_mock, CurrentHmiState())
.WillOnce(Return(old_state))
.WillOnce(Return(new_state));
@@ -434,15 +887,18 @@ class StateControllerTest : public ::testing::Test {
SetRegularState(Truly(HmiStatesComparator(new_state))));
if (!HmiStatesComparator(old_state)(new_state)) {
EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(app));
- EXPECT_CALL(app_manager_mock_,
- OnHMILevelChanged(app->app_id(), old_state->hmi_level(),
- new_state->hmi_level()));
+ EXPECT_CALL(
+ app_manager_mock_,
+ OnHMILevelChanged(
+ app->app_id(), old_state->hmi_level(), new_state->hmi_level()));
}
}
void ExpectAppChangeHmiStateDueToConflictResolving(
- am::ApplicationSharedPtr app, NiceMock<ApplicationMock>* app_mock,
- am::HmiStatePtr old_state, am::HmiStatePtr new_state) {
+ am::ApplicationSharedPtr app,
+ NiceMock<application_manager_test::MockApplication>* app_mock,
+ am::HmiStatePtr old_state,
+ am::HmiStatePtr new_state) {
EXPECT_CALL(*app_mock, RegularHmiState())
.WillOnce(Return(old_state))
.WillOnce(Return(old_state));
@@ -450,7 +906,8 @@ class StateControllerTest : public ::testing::Test {
}
void ExpectAppWontChangeHmiStateDueToConflictResolving(
- am::ApplicationSharedPtr app, NiceMock<ApplicationMock>* app_mock,
+ am::ApplicationSharedPtr app,
+ NiceMock<application_manager_test::MockApplication>* app_mock,
am::HmiStatePtr state) {
EXPECT_CALL(*app_mock, RegularHmiState()).WillOnce(Return(state));
EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(app)).Times(0);
@@ -495,7 +952,7 @@ class StateControllerTest : public ::testing::Test {
}
void CheckStateApplyingForApplication(
- NiceMock<ApplicationMock>& application,
+ NiceMock<application_manager_test::MockApplication>& application,
std::vector<am::HmiState::StateID>& state_ids) {
using smart_objects::SmartObject;
using am::event_engine::Event;
@@ -507,39 +964,43 @@ class StateControllerTest : public ::testing::Test {
for (uint32_t i = 0; i < state_ids.size(); ++i) {
am::HmiState::StateID state_id = state_ids[i];
EXPECT_CALL(application,
- AddHMIState(Truly(HmiStatesIDComparator(state_id)))).Times(1);
+ AddHMIState(Truly(HmiStatesIDComparator(state_id)))).Times(1);
switch (state_id) {
case am::HmiState::StateID::STATE_ID_VR_SESSION: {
Event vr_start_event(FunctionID::VR_Started);
- state_ctrl_.on_event(vr_start_event);
+ state_ctrl_->on_event(vr_start_event);
break;
}
case am::HmiState::StateID::STATE_ID_TTS_SESSION: {
Event tts_start_event(FunctionID::TTS_Started);
- state_ctrl_.on_event(tts_start_event);
+ state_ctrl_->on_event(tts_start_event);
break;
}
case am::HmiState::StateID::STATE_ID_PHONE_CALL: {
- Event phone_call_event(
- FunctionID::BasicCommunication_OnPhoneCall);
+ Event phone_call_event(FunctionID::BasicCommunication_OnEventChanged);
SmartObject message;
- message[am::strings::msg_params][am::hmi_notification::is_active] = true;
+ message[am::strings::msg_params][am::hmi_notification::is_active] =
+ true;
+ message[am::strings::msg_params][am::hmi_notification::event_name] =
+ hmi_apis::Common_EventTypes::PHONE_CALL;
phone_call_event.set_smart_object(message);
- state_ctrl_.on_event(phone_call_event);
+ state_ctrl_->on_event(phone_call_event);
break;
}
case am::HmiState::StateID::STATE_ID_SAFETY_MODE: {
- Event emergency_event(
- FunctionID::BasicCommunication_OnEmergencyEvent);
+ Event emergency_event(FunctionID::BasicCommunication_OnEventChanged);
SmartObject message;
- message[am::strings::msg_params][am::hmi_response::enabled] = true;
+ message[am::strings::msg_params][am::hmi_notification::is_active] =
+ true;
+ message[am::strings::msg_params][am::hmi_notification::event_name] =
+ hmi_apis::Common_EventTypes::EMERGENCY_EVENT;
emergency_event.set_smart_object(message);
- state_ctrl_.on_event(emergency_event);
+ state_ctrl_->on_event(emergency_event);
break;
}
case am::HmiState::StateID::STATE_ID_NAVI_STREAMING: {
- state_ctrl_.OnNaviStreamingStarted();
+ state_ctrl_->OnNaviStreamingStarted();
break;
}
default:
@@ -553,37 +1014,45 @@ class StateControllerTest : public ::testing::Test {
am::HmiState::StateID state_id = state_ids[i];
EXPECT_CALL(application, RemoveHMIState(state_id)).Times(1);
+ EXPECT_CALL(application, PostponedHmiState())
+ .WillOnce(Return(NoneNotAudibleState()));
+ EXPECT_CALL(application, RemovePostponedState());
+
switch (state_id) {
case am::HmiState::StateID::STATE_ID_VR_SESSION: {
Event vr_stop_event(FunctionID::VR_Stopped);
- state_ctrl_.on_event(vr_stop_event);
+ state_ctrl_->on_event(vr_stop_event);
break;
}
case am::HmiState::StateID::STATE_ID_TTS_SESSION: {
Event tts_stop_event(FunctionID::TTS_Stopped);
- state_ctrl_.on_event(tts_stop_event);
+ state_ctrl_->on_event(tts_stop_event);
break;
}
case am::HmiState::StateID::STATE_ID_PHONE_CALL: {
- Event phone_call_event(
- FunctionID::BasicCommunication_OnPhoneCall);
+ Event phone_call_event(FunctionID::BasicCommunication_OnEventChanged);
SmartObject message;
- message[am::strings::msg_params][am::hmi_notification::is_active] = false;
+ message[am::strings::msg_params][am::hmi_notification::is_active] =
+ false;
+ message[am::strings::msg_params][am::hmi_notification::event_name] =
+ hmi_apis::Common_EventTypes::PHONE_CALL;
phone_call_event.set_smart_object(message);
- state_ctrl_.on_event(phone_call_event);
+ state_ctrl_->on_event(phone_call_event);
break;
}
case am::HmiState::StateID::STATE_ID_SAFETY_MODE: {
- Event emergency_event(
- FunctionID::BasicCommunication_OnEmergencyEvent);
+ Event emergency_event(FunctionID::BasicCommunication_OnEventChanged);
SmartObject message;
- message[am::strings::msg_params][am::hmi_response::enabled] = false;
+ message[am::strings::msg_params][am::hmi_notification::is_active] =
+ false;
+ message[am::strings::msg_params][am::hmi_notification::event_name] =
+ hmi_apis::Common_EventTypes::EMERGENCY_EVENT;
emergency_event.set_smart_object(message);
- state_ctrl_.on_event(emergency_event);
+ state_ctrl_->on_event(emergency_event);
break;
}
case am::HmiState::StateID::STATE_ID_NAVI_STREAMING: {
- state_ctrl_.OnNaviStreamingStopped();
+ state_ctrl_->OnNaviStreamingStopped();
break;
}
default:
@@ -595,37 +1064,38 @@ class StateControllerTest : public ::testing::Test {
}
};
-TEST_F(StateControllerTest, OnStateChangedWithEqualStates) {
+TEST_F(StateControllerImplTest, OnStateChangedWithEqualStates) {
EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(_)).Times(0);
EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0);
EXPECT_CALL(*simple_app_ptr_, ResetDataInNone()).Times(0);
for (uint32_t i = 0; i < valid_states_for_not_audio_app_.size(); ++i) {
- state_ctrl_.OnStateChanged(simple_app_,
- valid_states_for_not_audio_app_[i],
- valid_states_for_not_audio_app_[i]);
+ state_ctrl_->OnStateChanged(simple_app_,
+ valid_states_for_not_audio_app_[i],
+ valid_states_for_not_audio_app_[i]);
}
}
-TEST_F(StateControllerTest, OnStateChangedWithDifferentStates) {
+TEST_F(StateControllerImplTest, OnStateChangedWithDifferentStates) {
for (uint32_t i = 0; i < valid_states_for_not_audio_app_.size(); ++i) {
for (uint32_t j = 0; j < valid_states_for_not_audio_app_.size(); ++j) {
HmiStatesComparator comp(valid_states_for_not_audio_app_[i]);
if (!comp(valid_states_for_not_audio_app_[j])) {
- EXPECT_CALL(app_manager_mock_,
- SendHMIStatusNotification(simple_app_)).Times(1);
- EXPECT_CALL(app_manager_mock_,
- OnHMILevelChanged(
- simple_app_id_,
- valid_states_for_not_audio_app_[i]->hmi_level(),
- valid_states_for_not_audio_app_[j]->hmi_level())).Times(1);
+ EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(simple_app_))
+ .Times(1);
+ EXPECT_CALL(
+ app_manager_mock_,
+ OnHMILevelChanged(simple_app_id_,
+ valid_states_for_not_audio_app_[i]->hmi_level(),
+ valid_states_for_not_audio_app_[j]->hmi_level()))
+ .Times(1);
if (mobile_apis::HMILevel::HMI_NONE ==
valid_states_for_not_audio_app_[j]->hmi_level()) {
EXPECT_CALL(*simple_app_ptr_, ResetDataInNone()).Times(1);
}
- state_ctrl_.OnStateChanged(simple_app_,
- valid_states_for_not_audio_app_[i],
- valid_states_for_not_audio_app_[j]);
+ state_ctrl_->OnStateChanged(simple_app_,
+ valid_states_for_not_audio_app_[i],
+ valid_states_for_not_audio_app_[j]);
EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(_)).Times(0);
EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0);
@@ -635,7 +1105,7 @@ TEST_F(StateControllerTest, OnStateChangedWithDifferentStates) {
}
}
-TEST_F(StateControllerTest, OnStateChangedToNone) {
+TEST_F(StateControllerImplTest, OnStateChangedToNone) {
using namespace am;
using namespace mobile_apis;
@@ -647,249 +1117,168 @@ TEST_F(StateControllerTest, OnStateChangedToNone) {
SystemContext::SYSCTXT_MAIN);
EXPECT_CALL(*simple_app_ptr_, ResetDataInNone()).Times(0);
- state_ctrl_.OnStateChanged(simple_app_, none_state, not_none_state);
+ state_ctrl_->OnStateChanged(simple_app_, none_state, not_none_state);
EXPECT_CALL(*simple_app_ptr_, ResetDataInNone()).Times(1);
- state_ctrl_.OnStateChanged(simple_app_, not_none_state, none_state);
+ state_ctrl_->OnStateChanged(simple_app_, not_none_state, none_state);
}
-TEST_F(StateControllerTest, MoveSimpleAppToValidStates) {
- using am::HmiState;
- using am::HmiStatePtr;
- using am::UsageStatistics;
+TEST_F(StateControllerImplTest, MoveSimpleAppToValidStates) {
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
- HmiStatePtr initial_state =
- createHmiState(HMILevel::INVALID_ENUM, AudioStreamingState::INVALID_ENUM,
- SystemContext::INVALID_ENUM);
+ HmiStatePtr initial_state = createHmiState(HMILevel::INVALID_ENUM,
+ AudioStreamingState::INVALID_ENUM,
+ SystemContext::INVALID_ENUM);
for (std::vector<HmiStatePtr>::iterator it =
valid_states_for_not_audio_app_.begin();
- it != valid_states_for_not_audio_app_.end(); ++it) {
+ it != valid_states_for_not_audio_app_.end();
+ ++it) {
HmiStatePtr state_to_setup = *it;
EXPECT_CALL(*simple_app_ptr_, CurrentHmiState())
.WillOnce(Return(initial_state))
.WillOnce(Return(state_to_setup));
EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(simple_app_));
EXPECT_CALL(app_manager_mock_,
- OnHMILevelChanged(simple_app_id_, initial_state->hmi_level(),
+ OnHMILevelChanged(simple_app_id_,
+ initial_state->hmi_level(),
state_to_setup->hmi_level()));
EXPECT_CALL(*simple_app_ptr_,
SetRegularState(Truly(HmiStatesComparator(state_to_setup))));
- state_ctrl_.SetRegularState<false>(simple_app_, state_to_setup);
+ state_ctrl_->SetRegularState(simple_app_, state_to_setup, false);
initial_state = state_to_setup;
}
}
-TEST_F(StateControllerTest, MoveAudioAppAppToValidStates) {
- using am::HmiState;
- using am::HmiStatePtr;
- using am::UsageStatistics;
+TEST_F(StateControllerImplTest, MoveAudioNotResumeAppToValidStates) {
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
am::ApplicationSharedPtr audio_app = media_navi_vc_app_;
- NiceMock<ApplicationMock>* audio_app_mock = media_navi_vc_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* audio_app_mock =
+ media_navi_vc_app_ptr_;
- HmiStatePtr initial_state =
- createHmiState(HMILevel::INVALID_ENUM, AudioStreamingState::INVALID_ENUM,
- SystemContext::INVALID_ENUM);
+ HmiStatePtr initial_state = createHmiState(HMILevel::INVALID_ENUM,
+ AudioStreamingState::INVALID_ENUM,
+ SystemContext::INVALID_ENUM);
for (std::vector<HmiStatePtr>::iterator it =
valid_states_for_audio_app_.begin();
- it != valid_states_for_audio_app_.end(); ++it) {
+ it != valid_states_for_audio_app_.end();
+ ++it) {
HmiStatePtr state_to_setup = *it;
EXPECT_CALL(*audio_app_mock, CurrentHmiState())
.WillOnce(Return(initial_state))
.WillOnce(Return(state_to_setup));
EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(audio_app));
- EXPECT_CALL(
- app_manager_mock_,
- OnHMILevelChanged(audio_app->app_id(), initial_state->hmi_level(),
- state_to_setup->hmi_level()));
+ EXPECT_CALL(app_manager_mock_,
+ OnHMILevelChanged(audio_app->app_id(),
+ initial_state->hmi_level(),
+ state_to_setup->hmi_level()));
EXPECT_CALL(*audio_app_mock,
SetRegularState(Truly(HmiStatesComparator(state_to_setup))));
- state_ctrl_.SetRegularState<false>(media_navi_vc_app_, state_to_setup);
+ state_ctrl_->SetRegularState(media_navi_vc_app_, state_to_setup, false);
initial_state = state_to_setup;
}
}
-/*
-TEST_F(StateControllerTest, MoveAppFromValidStateToInvalid) {
- using am::HmiState;
- using am::HmiStatePtr;
- using am::UsageStatistics;
- namespace HMILevel = mobile_apis::HMILevel;
- namespace AudioStreamingState = mobile_apis::AudioStreamingState;
- namespace SystemContext = mobile_apis::SystemContext;
-
- for (std::vector<HmiStatePtr>::iterator valid_state_it =
- valid_states_for_not_audio_app_.begin();
- valid_state_it != valid_states_for_not_audio_app_.end();
- ++valid_state_it) {
- for (std::vector<HmiStatePtr>::iterator invalid_state_it =
- common_invalid_states_.begin();
- invalid_state_it != common_invalid_states_.end(); ++invalid_state_it) {
- HmiStatePtr initial_state = *valid_state_it;
- HmiStatePtr invalid_state = *invalid_state_it;
- EXPECT_CALL(*simple_app_ptr_, CurrentHmiState())
- .WillOnce(Return(initial_state));
- EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0);
- EXPECT_CALL(*simple_app_ptr_, SetRegularState(_)).Times(0);
- state_ctrl_.SetRegularState<false>(simple_app_, invalid_state);
- }
- }
-
- NiceMock<ApplicationMock>* audio_app_mock = media_navi_vc_app_ptr_;
- am::ApplicationSharedPtr audio_app = media_navi_vc_app_;
- for (std::vector<HmiStatePtr>::iterator valid_state_it =
- valid_states_for_audio_app_.begin();
- valid_state_it != valid_states_for_audio_app_.end(); ++valid_state_it) {
- for (std::vector<HmiStatePtr>::iterator invalid_state_it =
- invalid_states_for_audio_app.begin();
- invalid_state_it != invalid_states_for_audio_app.end();
- ++invalid_state_it) {
- HmiStatePtr initial_state = *valid_state_it;
- HmiStatePtr invalid_state = *invalid_state_it;
- EXPECT_CALL(*audio_app_mock, CurrentHmiState())
- .WillOnce(Return(initial_state));
- EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0);
- EXPECT_CALL(*audio_app_mock, SetRegularState(_)).Times(0);
- state_ctrl_.SetRegularState<false>(audio_app, invalid_state);
- }
- }
- for (std::vector<HmiStatePtr>::iterator valid_state_it =
- valid_states_for_not_audio_app_.begin();
- valid_state_it != valid_states_for_not_audio_app_.end();
- ++valid_state_it) {
- for (std::vector<HmiStatePtr>::iterator invalid_state_it =
- invalid_states_for_not_audio_app.begin();
- invalid_state_it != invalid_states_for_not_audio_app.end();
- ++invalid_state_it) {
- HmiStatePtr initial_state = *valid_state_it;
- HmiStatePtr invalid_state = *invalid_state_it;
- EXPECT_CALL(*simple_app_ptr_, CurrentHmiState())
- .WillOnce(Return(initial_state));
- EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0);
- EXPECT_CALL(*simple_app_ptr_, SetRegularState(_)).Times(0);
- state_ctrl_.SetRegularState<false>(simple_app_, invalid_state);
- }
- }
-}
-
-TEST_F(StateControllerTest, MoveAppFromInValidStateToValid) {
- using am::HmiState;
- using am::HmiStatePtr;
- using am::UsageStatistics;
+TEST_F(StateControllerImplTest, MoveAudioResumeAppToValidStates) {
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
- NiceMock<ApplicationMock>* audio_app_mock = media_navi_vc_app_ptr_;
am::ApplicationSharedPtr audio_app = media_navi_vc_app_;
- HmiStatePtr invalid_state =
- createHmiState(HMILevel::INVALID_ENUM, AudioStreamingState::INVALID_ENUM,
- SystemContext::INVALID_ENUM);
+ NiceMock<application_manager_test::MockApplication>* audio_app_mock =
+ media_navi_vc_app_ptr_;
+
+ HmiStatePtr initial_state = createHmiState(HMILevel::INVALID_ENUM,
+ AudioStreamingState::INVALID_ENUM,
+ SystemContext::INVALID_ENUM);
+ // Set all valid states for audio app
for (std::vector<HmiStatePtr>::iterator it =
valid_states_for_audio_app_.begin();
- it != valid_states_for_audio_app_.end(); ++it) {
- HmiStatePtr initial_state = *it;
+ it != valid_states_for_audio_app_.end();
+ ++it) {
+ HmiStatePtr state_to_setup = *it;
+ HmiStatePtr state_to_check = state_to_setup;
+ // First time current state is initial, then it changes to setup state
EXPECT_CALL(*audio_app_mock, CurrentHmiState())
- .WillOnce(Return(initial_state));
- EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0);
- EXPECT_CALL(*audio_app_mock, SetRegularState(_)).Times(0);
- state_ctrl_.SetRegularState<false>(audio_app, invalid_state);
- }
+ .WillOnce(Return(initial_state))
+ .WillOnce(Return(state_to_setup));
+ // Audio resume app when HMI level is LIMITED or FULL gets audible state
+ if (state_to_setup->hmi_level() == HMILevel::HMI_LIMITED) {
+ EXPECT_CALL(*audio_app_mock, is_resuming()).WillRepeatedly(Return(true));
+ EXPECT_CALL(*message_helper_mock_,
+ SendOnResumeAudioSourceToHMI(media_navi_vc_app_id_, _));
+ state_to_check->set_audio_streaming_state(AudioStreamingState::AUDIBLE);
- for (std::vector<HmiStatePtr>::iterator it =
- valid_states_for_not_audio_app_.begin();
- it != valid_states_for_not_audio_app_.end(); ++it) {
- HmiStatePtr initial_state = *it;
- EXPECT_CALL(*simple_app_ptr_, CurrentHmiState())
- .WillOnce(Return(initial_state));
- EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0);
- EXPECT_CALL(*simple_app_ptr_, SetRegularState(_)).Times(0);
- state_ctrl_.SetRegularState<false>(simple_app_, invalid_state);
+ } else {
+ if (state_to_setup->hmi_level() == HMILevel::HMI_FULL) {
+ state_to_check->set_audio_streaming_state(AudioStreamingState::AUDIBLE);
+ }
+ EXPECT_CALL(*audio_app_mock, is_resuming()).WillRepeatedly(Return(true));
+ }
+ EXPECT_CALL(app_manager_mock_, active_application())
+ .WillRepeatedly(Return(am::ApplicationSharedPtr()));
+ EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(audio_app))
+ .Times(AtLeast(0));
+ EXPECT_CALL(app_manager_mock_,
+ OnHMILevelChanged(audio_app->app_id(),
+ initial_state->hmi_level(),
+ state_to_setup->hmi_level()))
+ .Times(AtLeast(0));
+
+ // Check that we set correct state
+ EXPECT_CALL(*audio_app_mock,
+ SetRegularState(Truly(HmiStatesComparator(state_to_check))));
+ state_ctrl_->SetRegularState(media_navi_vc_app_, state_to_setup, false);
+ initial_state = state_to_setup;
}
}
-TEST_F(StateControllerTest, MoveAppFromInValidStateToInvalid) {
+TEST_F(StateControllerImplTest, MoveAppFromValidStateToInvalid) {
using am::HmiState;
using am::HmiStatePtr;
- using am::UsageStatistics;
- namespace HMILevel = mobile_apis::HMILevel;
- namespace AudioStreamingState = mobile_apis::AudioStreamingState;
- namespace SystemContext = mobile_apis::SystemContext;
- NiceMock<ApplicationMock>* audio_app_mock = media_navi_vc_app_ptr_;
- am::ApplicationSharedPtr audio_app = media_navi_vc_app_;
- HmiStatePtr initial_invalid_state =
- createHmiState(HMILevel::INVALID_ENUM, AudioStreamingState::INVALID_ENUM,
- SystemContext::INVALID_ENUM);
-
- am::ApplicationConstSharedPtr const_audio_app(audio_app);
-
- for (std::vector<HmiStatePtr>::iterator it =
- invalid_states_for_audio_app.begin();
- it != invalid_states_for_audio_app.end(); ++it) {
- HmiStatePtr state_to_setup = *it;
- HmiStatePtr default_state =
- createHmiState(HMILevel::HMI_LIMITED, AudioStreamingState::AUDIBLE,
- SystemContext::SYSCTXT_MAIN);
- EXPECT_CALL(app_manager_mock_, GetDefaultHmiLevel(const_audio_app))
- .WillOnce(Return(HMILevel::HMI_LIMITED));
- EXPECT_CALL(*audio_app_mock, CurrentHmiState())
- .WillOnce(Return(initial_invalid_state))
- .WillOnce(Return(initial_invalid_state))
- .WillOnce(Return(default_state));
- EXPECT_CALL(app_manager_mock_,
- OnHMILevelChanged(audio_app->app_id(),
- initial_invalid_state->hmi_level(),
- default_state->hmi_level()));
- EXPECT_CALL(*audio_app_mock,
- SetRegularState(Truly(HmiStatesComparator(default_state))));
- state_ctrl_.SetRegularState<false>(audio_app, state_to_setup);
+ for (std::vector<HmiStatePtr>::iterator invalid_state_it =
+ common_invalid_states_.begin();
+ invalid_state_it != common_invalid_states_.end();
+ ++invalid_state_it) {
+ HmiStatePtr invalid_state = *invalid_state_it;
+ EXPECT_CALL(*simple_app_ptr_, CurrentHmiState()).Times(0);
+ EXPECT_CALL(*simple_app_ptr_, is_resuming()).Times(0);
+ EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0);
+ EXPECT_CALL(*simple_app_ptr_, SetRegularState(_)).Times(0);
+ state_ctrl_->SetRegularState(simple_app_, invalid_state, false);
}
- for (std::vector<HmiStatePtr>::iterator it =
- invalid_states_for_not_audio_app.begin();
- it != invalid_states_for_not_audio_app.end(); ++it) {
- HmiStatePtr state_to_setup = *it;
- HmiStatePtr default_state = createHmiState(HMILevel::HMI_BACKGROUND,
- AudioStreamingState::NOT_AUDIBLE,
- SystemContext::SYSCTXT_MAIN);
- am::ApplicationConstSharedPtr const_simple_app(simple_app_);
- EXPECT_CALL(app_manager_mock_, GetDefaultHmiLevel(const_simple_app))
- .WillOnce(Return(HMILevel::HMI_BACKGROUND));
- EXPECT_CALL(*simple_app_ptr_, CurrentHmiState())
- .WillOnce(Return(initial_invalid_state))
- .WillOnce(Return(initial_invalid_state))
- .WillOnce(Return(default_state));
- EXPECT_CALL(app_manager_mock_,
- OnHMILevelChanged(simple_app_ptr_->app_id(),
- initial_invalid_state->hmi_level(),
- default_state->hmi_level()));
- EXPECT_CALL(*simple_app_ptr_,
- SetRegularState(Truly(HmiStatesComparator(default_state))));
- state_ctrl_.SetRegularState<false>(simple_app_, state_to_setup);
+ for (std::vector<HmiStatePtr>::iterator invalid_state_it =
+ common_invalid_states_.begin();
+ invalid_state_it != common_invalid_states_.end();
+ ++invalid_state_it) {
+ HmiStatePtr invalid_state = *invalid_state_it;
+ EXPECT_CALL(*media_navi_vc_app_ptr_, CurrentHmiState()).Times(0);
+ EXPECT_CALL(*media_navi_vc_app_ptr_, is_resuming()).Times(0);
+ EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(_, _, _)).Times(0);
+ EXPECT_CALL(*media_navi_vc_app_ptr_, SetRegularState(_)).Times(0);
+ state_ctrl_->SetRegularState(media_navi_vc_app_, invalid_state, false);
}
}
-*/
-TEST_F(StateControllerTest, SetFullToSimpleAppWhileAnotherSimpleAppIsInFull) {
- using am::HmiState;
- using am::HmiStatePtr;
+
+TEST_F(StateControllerImplTest,
+ SetFullToSimpleAppWhileAnotherSimpleAppIsInFull) {
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
am::ApplicationSharedPtr app_in_full;
- NiceMock<ApplicationMock>* app_in_full_mock;
+ NiceMock<application_manager_test::MockApplication>* app_in_full_mock;
am::ApplicationSharedPtr app_moved_to_full;
- NiceMock<ApplicationMock>* app_moved_to_full_mock;
+ NiceMock<application_manager_test::MockApplication>* app_moved_to_full_mock;
app_in_full =
ConfigureApp(&app_in_full_mock, 1761, NOT_MEDIA, NOT_NAVI, NOT_VC);
@@ -899,244 +1288,261 @@ TEST_F(StateControllerTest, SetFullToSimpleAppWhileAnotherSimpleAppIsInFull) {
InsertApplication(app_in_full);
InsertApplication(app_moved_to_full);
- ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock,
- BackgroundState(), FullNotAudibleState());
+ ExpectSuccesfullSetHmiState(app_moved_to_full,
+ app_moved_to_full_mock,
+ BackgroundState(),
+ FullNotAudibleState());
ExpectAppChangeHmiStateDueToConflictResolving(
app_in_full, app_in_full_mock, FullNotAudibleState(), BackgroundState());
- state_ctrl_.SetRegularState<false>(app_moved_to_full, FullNotAudibleState());
+ state_ctrl_->SetRegularState(app_moved_to_full, FullNotAudibleState(), false);
}
-TEST_F(StateControllerTest, SetFullToSimpleAppWhileAudioAppAppIsInFull) {
- using am::HmiState;
- using am::HmiStatePtr;
+TEST_F(StateControllerImplTest, SetFullToSimpleAppWhileAudioAppAppIsInFull) {
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
am::ApplicationSharedPtr app_in_full = media_navi_vc_app_;
- NiceMock<ApplicationMock>* app_in_full_mock = media_navi_vc_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* app_in_full_mock =
+ media_navi_vc_app_ptr_;
am::ApplicationSharedPtr app_moved_to_full = simple_app_;
- NiceMock<ApplicationMock>* app_moved_to_full_mock = simple_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* app_moved_to_full_mock =
+ simple_app_ptr_;
InsertApplication(app_in_full);
InsertApplication(app_moved_to_full);
- ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock,
- BackgroundState(), FullNotAudibleState());
+ ExpectSuccesfullSetHmiState(app_moved_to_full,
+ app_moved_to_full_mock,
+ BackgroundState(),
+ FullNotAudibleState());
ExpectAppChangeHmiStateDueToConflictResolving(
app_in_full, app_in_full_mock, FullAudibleState(), LimitedState());
- state_ctrl_.SetRegularState<false>(app_moved_to_full, FullNotAudibleState());
+ state_ctrl_->SetRegularState(app_moved_to_full, FullNotAudibleState(), false);
}
-TEST_F(StateControllerTest,
+TEST_F(StateControllerImplTest,
SetFullToAudioAppAppWhileAnotherTypeAudioAppAppIsInFull) {
- using am::HmiState;
- using am::HmiStatePtr;
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
am::ApplicationSharedPtr app_in_full = media_app_;
- NiceMock<ApplicationMock>* app_in_full_mock = media_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* app_in_full_mock =
+ media_app_ptr_;
am::ApplicationSharedPtr app_moved_to_full = navi_app_;
- NiceMock<ApplicationMock>* app_moved_to_full_mock = navi_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* app_moved_to_full_mock =
+ navi_app_ptr_;
InsertApplication(app_in_full);
InsertApplication(app_moved_to_full);
- ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock,
- BackgroundState(), FullAudibleState());
+ ExpectSuccesfullSetHmiState(app_moved_to_full,
+ app_moved_to_full_mock,
+ BackgroundState(),
+ FullAudibleState());
ExpectAppChangeHmiStateDueToConflictResolving(
app_in_full, app_in_full_mock, FullAudibleState(), LimitedState());
- state_ctrl_.SetRegularState<false>(app_moved_to_full, FullAudibleState());
+ state_ctrl_->SetRegularState(app_moved_to_full, FullAudibleState(), false);
}
-TEST_F(StateControllerTest,
+TEST_F(StateControllerImplTest,
SetFullToAudioAppAppWhileSameTypeAudioAppAppIsInFull) {
- using am::HmiState;
- using am::HmiStatePtr;
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
- NiceMock<ApplicationMock>* app_in_full_mock;
+ NiceMock<application_manager_test::MockApplication>* app_in_full_mock;
am::ApplicationSharedPtr app_in_full =
ConfigureApp(&app_in_full_mock, 1761, MEDIA, NOT_NAVI, NOT_VC);
- NiceMock<ApplicationMock>* app_moved_to_full_mock;
+ NiceMock<application_manager_test::MockApplication>* app_moved_to_full_mock;
am::ApplicationSharedPtr app_moved_to_full =
ConfigureApp(&app_moved_to_full_mock, 1796, MEDIA, NOT_NAVI, NOT_VC);
InsertApplication(app_in_full);
InsertApplication(app_moved_to_full);
- ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock,
- BackgroundState(), FullAudibleState());
+ ExpectSuccesfullSetHmiState(app_moved_to_full,
+ app_moved_to_full_mock,
+ BackgroundState(),
+ FullAudibleState());
ExpectAppChangeHmiStateDueToConflictResolving(
app_in_full, app_in_full_mock, FullAudibleState(), BackgroundState());
- state_ctrl_.SetRegularState<false>(app_moved_to_full, FullAudibleState());
+ state_ctrl_->SetRegularState(app_moved_to_full, FullAudibleState(), false);
}
-TEST_F(StateControllerTest,
+TEST_F(StateControllerImplTest,
SetFullToAudioAppAppWhileSameTypeAudioAppAppIsInLimited) {
- using am::HmiState;
- using am::HmiStatePtr;
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
- NiceMock<ApplicationMock>* app_in_limited_mock;
+ NiceMock<application_manager_test::MockApplication>* app_in_limited_mock;
am::ApplicationSharedPtr app_in_limited =
ConfigureApp(&app_in_limited_mock, 1761, NOT_MEDIA, NAVI, NOT_VC);
- NiceMock<ApplicationMock>* app_moved_to_full_mock;
+ NiceMock<application_manager_test::MockApplication>* app_moved_to_full_mock;
am::ApplicationSharedPtr app_moved_to_full =
ConfigureApp(&app_moved_to_full_mock, 1796, NOT_MEDIA, NAVI, VC);
InsertApplication(app_in_limited);
InsertApplication(app_moved_to_full);
- ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock,
- BackgroundState(), FullAudibleState());
+ ExpectSuccesfullSetHmiState(app_moved_to_full,
+ app_moved_to_full_mock,
+ BackgroundState(),
+ FullAudibleState());
ExpectAppChangeHmiStateDueToConflictResolving(
app_in_limited, app_in_limited_mock, LimitedState(), BackgroundState());
- state_ctrl_.SetRegularState<false>(app_moved_to_full, FullAudibleState());
+ state_ctrl_->SetRegularState(app_moved_to_full, FullAudibleState(), false);
}
-TEST_F(StateControllerTest,
+TEST_F(StateControllerImplTest,
SetLimitedToAudioAppAppWhileSameTypeAudioAppAppIsInLimited) {
- using am::HmiState;
- using am::HmiStatePtr;
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
- NiceMock<ApplicationMock>* app_in_limited_mock;
+ NiceMock<application_manager_test::MockApplication>* app_in_limited_mock;
am::ApplicationSharedPtr app_in_limited =
ConfigureApp(&app_in_limited_mock, 1761, NOT_MEDIA, NOT_NAVI, VC);
- NiceMock<ApplicationMock>* app_moved_to_limited_mock;
+ NiceMock<application_manager_test::MockApplication>*
+ app_moved_to_limited_mock;
am::ApplicationSharedPtr app_moved_to_limited =
ConfigureApp(&app_moved_to_limited_mock, 1796, NOT_MEDIA, NOT_NAVI, VC);
InsertApplication(app_in_limited);
InsertApplication(app_moved_to_limited);
- ExpectSuccesfullSetHmiState(app_moved_to_limited, app_moved_to_limited_mock,
- BackgroundState(), LimitedState());
+ ExpectSuccesfullSetHmiState(app_moved_to_limited,
+ app_moved_to_limited_mock,
+ BackgroundState(),
+ LimitedState());
ExpectAppChangeHmiStateDueToConflictResolving(
app_in_limited, app_in_limited_mock, LimitedState(), BackgroundState());
- state_ctrl_.SetRegularState<false>(app_moved_to_limited, LimitedState());
+ state_ctrl_->SetRegularState(app_moved_to_limited, LimitedState(), false);
}
-TEST_F(StateControllerTest,
+TEST_F(StateControllerImplTest,
SetLimitedToAudioAppAppWhileOtherTypeAudioAppAppIsInLimited) {
- using am::HmiState;
- using am::HmiStatePtr;
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
am::ApplicationSharedPtr app_in_limited = navi_app_;
- NiceMock<ApplicationMock>* app_in_limited_mock = navi_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* app_in_limited_mock =
+ navi_app_ptr_;
am::ApplicationSharedPtr app_moved_to_limited = vc_app_;
- NiceMock<ApplicationMock>* app_moved_to_limited_mock = vc_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>*
+ app_moved_to_limited_mock = vc_app_ptr_;
InsertApplication(app_in_limited);
InsertApplication(app_moved_to_limited);
- ExpectSuccesfullSetHmiState(app_moved_to_limited, app_moved_to_limited_mock,
- BackgroundState(), LimitedState());
+ ExpectSuccesfullSetHmiState(app_moved_to_limited,
+ app_moved_to_limited_mock,
+ BackgroundState(),
+ LimitedState());
ExpectAppWontChangeHmiStateDueToConflictResolving(
app_in_limited, app_in_limited_mock, LimitedState());
- state_ctrl_.SetRegularState<false>(app_moved_to_limited, LimitedState());
+ state_ctrl_->SetRegularState(app_moved_to_limited, LimitedState(), false);
}
-TEST_F(StateControllerTest,
+TEST_F(StateControllerImplTest,
SetLimitedToAudioAppAppWhileOtherTypeAudioAppAppIsInFull) {
- using am::HmiState;
- using am::HmiStatePtr;
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
am::ApplicationSharedPtr app_in_full = navi_app_;
- NiceMock<ApplicationMock>* app_in_full_mock = navi_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* app_in_full_mock =
+ navi_app_ptr_;
am::ApplicationSharedPtr app_moved_to_limited = vc_app_;
- NiceMock<ApplicationMock>* app_moved_to_limited_mock = vc_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>*
+ app_moved_to_limited_mock = vc_app_ptr_;
InsertApplication(app_in_full);
InsertApplication(app_moved_to_limited);
- ExpectSuccesfullSetHmiState(app_moved_to_limited, app_moved_to_limited_mock,
- BackgroundState(), LimitedState());
+ ExpectSuccesfullSetHmiState(app_moved_to_limited,
+ app_moved_to_limited_mock,
+ BackgroundState(),
+ LimitedState());
ExpectAppWontChangeHmiStateDueToConflictResolving(
app_in_full, app_in_full_mock, FullAudibleState());
- state_ctrl_.SetRegularState<false>(app_moved_to_limited, LimitedState());
+ state_ctrl_->SetRegularState(app_moved_to_limited, LimitedState(), false);
}
-TEST_F(StateControllerTest, SetFullToSimpleAppWhile2AudioAppsInLimited) {
- using am::HmiState;
- using am::HmiStatePtr;
+TEST_F(StateControllerImplTest, SetFullToSimpleAppWhile2AudioAppsInLimited) {
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
am::ApplicationSharedPtr app_moved_to_full = simple_app_;
- NiceMock<ApplicationMock>* app_moved_to_full_mock = simple_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* app_moved_to_full_mock =
+ simple_app_ptr_;
am::ApplicationSharedPtr limited_app1 = media_app_;
- NiceMock<ApplicationMock>* limited_app1_mock = media_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* limited_app1_mock =
+ media_app_ptr_;
am::ApplicationSharedPtr limited_app2 = navi_vc_app_;
- NiceMock<ApplicationMock>* limited_app2_mock = navi_vc_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* limited_app2_mock =
+ navi_vc_app_ptr_;
InsertApplication(app_moved_to_full);
InsertApplication(limited_app1);
InsertApplication(limited_app2);
- ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock,
- BackgroundState(), FullNotAudibleState());
+ ExpectSuccesfullSetHmiState(app_moved_to_full,
+ app_moved_to_full_mock,
+ BackgroundState(),
+ FullNotAudibleState());
ExpectAppWontChangeHmiStateDueToConflictResolving(
limited_app1, limited_app1_mock, LimitedState());
ExpectAppWontChangeHmiStateDueToConflictResolving(
limited_app2, limited_app2_mock, LimitedState());
- state_ctrl_.SetRegularState<false>(app_moved_to_full, FullNotAudibleState());
+ state_ctrl_->SetRegularState(app_moved_to_full, FullNotAudibleState(), false);
}
-TEST_F(StateControllerTest,
+TEST_F(StateControllerImplTest,
SetFullToSimpleAppWhile1AudioAppInLimitedAnd1AudioAppInFull) {
- using am::HmiState;
- using am::HmiStatePtr;
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
am::ApplicationSharedPtr app_moved_to_full = simple_app_;
- NiceMock<ApplicationMock>* app_moved_to_full_mock = simple_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* app_moved_to_full_mock =
+ simple_app_ptr_;
am::ApplicationSharedPtr limited_app = media_app_;
- NiceMock<ApplicationMock>* limited_app_mock = media_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* limited_app_mock =
+ media_app_ptr_;
am::ApplicationSharedPtr full_app = navi_vc_app_;
- NiceMock<ApplicationMock>* full_app_mock = navi_vc_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* full_app_mock =
+ navi_vc_app_ptr_;
InsertApplication(app_moved_to_full);
InsertApplication(limited_app);
InsertApplication(full_app);
- ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock,
- BackgroundState(), FullNotAudibleState());
+ ExpectSuccesfullSetHmiState(app_moved_to_full,
+ app_moved_to_full_mock,
+ BackgroundState(),
+ FullNotAudibleState());
ExpectAppWontChangeHmiStateDueToConflictResolving(
limited_app, limited_app_mock, LimitedState());
@@ -1144,25 +1550,24 @@ TEST_F(StateControllerTest,
ExpectAppChangeHmiStateDueToConflictResolving(
full_app, full_app_mock, FullAudibleState(), LimitedState());
- state_ctrl_.SetRegularState<false>(app_moved_to_full, FullNotAudibleState());
+ state_ctrl_->SetRegularState(app_moved_to_full, FullNotAudibleState(), false);
}
-TEST_F(StateControllerTest,
+TEST_F(StateControllerImplTest,
SetFullToSimpleAppWhile1AudioAppInLimitedAnd1SimpleAppInFull) {
- using am::HmiState;
- using am::HmiStatePtr;
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
- NiceMock<ApplicationMock>* app_moved_to_full_mock;
+ NiceMock<application_manager_test::MockApplication>* app_moved_to_full_mock;
am::ApplicationSharedPtr app_moved_to_full =
ConfigureApp(&app_moved_to_full_mock, 1761, NOT_MEDIA, NOT_NAVI, NOT_VC);
am::ApplicationSharedPtr limited_app = media_app_;
- NiceMock<ApplicationMock>* limited_app_mock = media_app_ptr_;
+ NiceMock<application_manager_test::MockApplication>* limited_app_mock =
+ media_app_ptr_;
- NiceMock<ApplicationMock>* full_app_mock;
+ NiceMock<application_manager_test::MockApplication>* full_app_mock;
am::ApplicationSharedPtr full_app =
ConfigureApp(&full_app_mock, 1796, NOT_MEDIA, NOT_NAVI, NOT_VC);
@@ -1170,8 +1575,10 @@ TEST_F(StateControllerTest,
InsertApplication(limited_app);
InsertApplication(full_app);
- ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock,
- BackgroundState(), FullNotAudibleState());
+ ExpectSuccesfullSetHmiState(app_moved_to_full,
+ app_moved_to_full_mock,
+ BackgroundState(),
+ FullNotAudibleState());
ExpectAppWontChangeHmiStateDueToConflictResolving(
limited_app, limited_app_mock, LimitedState());
@@ -1179,27 +1586,25 @@ TEST_F(StateControllerTest,
ExpectAppChangeHmiStateDueToConflictResolving(
full_app, full_app_mock, FullNotAudibleState(), BackgroundState());
- state_ctrl_.SetRegularState<false>(app_moved_to_full, FullNotAudibleState());
+ state_ctrl_->SetRegularState(app_moved_to_full, FullNotAudibleState(), false);
}
TEST_F(
- StateControllerTest,
+ StateControllerImplTest,
SetFullToAudioAppWhile1AudioAppWithSameTypeInLimitedAnd1SimpleAppInFull) {
- using am::HmiState;
- using am::HmiStatePtr;
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
- NiceMock<ApplicationMock>* app_moved_to_full_mock;
+ NiceMock<application_manager_test::MockApplication>* app_moved_to_full_mock;
am::ApplicationSharedPtr app_moved_to_full =
ConfigureApp(&app_moved_to_full_mock, 1761, MEDIA, NOT_NAVI, NOT_VC);
- NiceMock<ApplicationMock>* limited_app_mock;
+ NiceMock<application_manager_test::MockApplication>* limited_app_mock;
am::ApplicationSharedPtr limited_app =
ConfigureApp(&limited_app_mock, 1762, MEDIA, NOT_NAVI, NOT_VC);
- NiceMock<ApplicationMock>* full_app_mock;
+ NiceMock<application_manager_test::MockApplication>* full_app_mock;
am::ApplicationSharedPtr full_app =
ConfigureApp(&full_app_mock, 1796, NOT_MEDIA, NOT_NAVI, NOT_VC);
@@ -1207,8 +1612,10 @@ TEST_F(
InsertApplication(limited_app);
InsertApplication(full_app);
- ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock,
- BackgroundState(), FullAudibleState());
+ ExpectSuccesfullSetHmiState(app_moved_to_full,
+ app_moved_to_full_mock,
+ BackgroundState(),
+ FullAudibleState());
ExpectAppChangeHmiStateDueToConflictResolving(
limited_app, limited_app_mock, LimitedState(), BackgroundState());
@@ -1216,27 +1623,25 @@ TEST_F(
ExpectAppChangeHmiStateDueToConflictResolving(
full_app, full_app_mock, FullNotAudibleState(), BackgroundState());
- state_ctrl_.SetRegularState<false>(app_moved_to_full, FullAudibleState());
+ state_ctrl_->SetRegularState(app_moved_to_full, FullAudibleState(), false);
}
TEST_F(
- StateControllerTest,
+ StateControllerImplTest,
SetFullToAudioAppWhileAudioAppWithSameTypeInLimitedAndAudioAppWithOtherTypeInFull) {
- using am::HmiState;
- using am::HmiStatePtr;
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
- NiceMock<ApplicationMock>* app_moved_to_full_mock;
+ NiceMock<application_manager_test::MockApplication>* app_moved_to_full_mock;
am::ApplicationSharedPtr app_moved_to_full =
ConfigureApp(&app_moved_to_full_mock, 1761, MEDIA, NOT_NAVI, NOT_VC);
- NiceMock<ApplicationMock>* limited_app_mock;
+ NiceMock<application_manager_test::MockApplication>* limited_app_mock;
am::ApplicationSharedPtr limited_app =
ConfigureApp(&limited_app_mock, 1762, MEDIA, NOT_NAVI, NOT_VC);
- NiceMock<ApplicationMock>* full_app_mock;
+ NiceMock<application_manager_test::MockApplication>* full_app_mock;
am::ApplicationSharedPtr full_app =
ConfigureApp(&full_app_mock, 1796, NOT_MEDIA, NAVI, NOT_VC);
@@ -1244,8 +1649,10 @@ TEST_F(
InsertApplication(limited_app);
InsertApplication(full_app);
- ExpectSuccesfullSetHmiState(app_moved_to_full, app_moved_to_full_mock,
- BackgroundState(), FullAudibleState());
+ ExpectSuccesfullSetHmiState(app_moved_to_full,
+ app_moved_to_full_mock,
+ BackgroundState(),
+ FullAudibleState());
ExpectAppChangeHmiStateDueToConflictResolving(
limited_app, limited_app_mock, LimitedState(), BackgroundState());
@@ -1253,13 +1660,11 @@ TEST_F(
ExpectAppChangeHmiStateDueToConflictResolving(
full_app, full_app_mock, FullAudibleState(), LimitedState());
- state_ctrl_.SetRegularState<false>(app_moved_to_full, FullAudibleState());
+ state_ctrl_->SetRegularState(app_moved_to_full, FullAudibleState(), false);
}
-TEST_F(StateControllerTest,
+TEST_F(StateControllerImplTest,
SetFullToAudioAppWhile3AudioAppsWithSameTypeInLimited) {
- using am::HmiState;
- using am::HmiStatePtr;
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
@@ -1268,21 +1673,21 @@ TEST_F(StateControllerTest,
InsertApplication(media_app_);
InsertApplication(navi_app_);
InsertApplication(vc_app_);
- ExpectSuccesfullSetHmiState(media_navi_vc_app_, media_navi_vc_app_ptr_,
- BackgroundState(), FullAudibleState());
+ ExpectSuccesfullSetHmiState(media_navi_vc_app_,
+ media_navi_vc_app_ptr_,
+ BackgroundState(),
+ FullAudibleState());
ExpectAppChangeHmiStateDueToConflictResolving(
media_app_, media_app_ptr_, LimitedState(), BackgroundState());
ExpectAppChangeHmiStateDueToConflictResolving(
navi_app_, navi_app_ptr_, LimitedState(), BackgroundState());
ExpectAppChangeHmiStateDueToConflictResolving(
vc_app_, vc_app_ptr_, LimitedState(), BackgroundState());
- state_ctrl_.SetRegularState<false>(media_navi_vc_app_, FullAudibleState());
+ state_ctrl_->SetRegularState(media_navi_vc_app_, FullAudibleState(), false);
}
-TEST_F(StateControllerTest,
+TEST_F(StateControllerImplTest,
SetFullToAudioAppWhile2AudioAppsWithSameTypeInLimitedAndOneInFull) {
- using am::HmiState;
- using am::HmiStatePtr;
namespace HMILevel = mobile_apis::HMILevel;
namespace AudioStreamingState = mobile_apis::AudioStreamingState;
namespace SystemContext = mobile_apis::SystemContext;
@@ -1291,18 +1696,21 @@ TEST_F(StateControllerTest,
InsertApplication(media_app_);
InsertApplication(navi_app_);
InsertApplication(vc_app_);
- ExpectSuccesfullSetHmiState(media_navi_vc_app_, media_navi_vc_app_ptr_,
- BackgroundState(), FullAudibleState());
+ ExpectSuccesfullSetHmiState(media_navi_vc_app_,
+ media_navi_vc_app_ptr_,
+ BackgroundState(),
+ FullAudibleState());
ExpectAppChangeHmiStateDueToConflictResolving(
media_app_, media_app_ptr_, LimitedState(), BackgroundState());
ExpectAppChangeHmiStateDueToConflictResolving(
navi_app_, navi_app_ptr_, LimitedState(), BackgroundState());
ExpectAppChangeHmiStateDueToConflictResolving(
vc_app_, vc_app_ptr_, FullAudibleState(), BackgroundState());
- state_ctrl_.SetRegularState<false>(media_navi_vc_app_, FullAudibleState());
+ state_ctrl_->SetRegularState(media_navi_vc_app_, FullAudibleState(), false);
}
-TEST_F(StateControllerTest, ActivateAppSuccessReceivedFromHMI) {
+// TODO {AKozoriz} Changed logic in state_controller
+TEST_F(StateControllerImplTest, DISABLED_ActivateAppSuccessReceivedFromHMI) {
using namespace hmi_apis;
using namespace mobile_apis;
@@ -1318,45 +1726,48 @@ TEST_F(StateControllerTest, ActivateAppSuccessReceivedFromHMI) {
StateLevelPair(LimitedState(), Common_HMILevel::LIMITED));
hmi_states.push_back(
StateLevelPair(BackgroundState(), Common_HMILevel::BACKGROUND));
- hmi_states.push_back(StateLevelPair(
- createHmiState(HMILevel::HMI_NONE, AudioStreamingState::NOT_AUDIBLE,
- SystemContext::SYSCTXT_MAIN),
- Common_HMILevel::NONE));
+ hmi_states.push_back(
+ StateLevelPair(createHmiState(HMILevel::HMI_NONE,
+ AudioStreamingState::NOT_AUDIBLE,
+ SystemContext::SYSCTXT_MAIN),
+ Common_HMILevel::NONE));
std::vector<StateLevelPair> initial_hmi_states = hmi_states;
std::vector<StateLevelPair>::iterator it = hmi_states.begin();
std::vector<StateLevelPair>::iterator it2 = initial_hmi_states.begin();
+ smart_objects::SmartObjectSPtr bc_activate_app_request =
+ new smart_objects::SmartObject();
+ (*bc_activate_app_request)[am::strings::params][am::strings::correlation_id] =
+ corr_id;
+
for (; it != hmi_states.end(); ++it) {
- for (; it2 != initial_hmi_states.end(); ++it2) {
- am::HmiStatePtr hmi_state = it->first;
- am::HmiStatePtr initial_hmi_state = it->first;
- Common_HMILevel::eType hmi_level = it->second;
+ am::HmiStatePtr hmi_state = it->first;
+ am::HmiStatePtr initial_hmi_state = it->first;
+ Common_HMILevel::eType hmi_level = it->second;
- EXPECT_CALL(*message_helper_mock_,
- SendActivateAppToHMI(media_app_->app_id(), hmi_level, _))
- .WillOnce(Return(corr_id));
- EXPECT_CALL(app_manager_mock_, application_id(corr_id))
- .WillOnce(Return(hmi_app_id));
- EXPECT_CALL(app_manager_mock_, application_by_hmi_app(hmi_app_id))
- .WillOnce(Return(media_app_));
- ExpectSuccesfullSetHmiState(media_app_, media_app_ptr_, initial_hmi_state,
- hmi_state);
- state_ctrl_.SetRegularState<true>(media_app_, hmi_state);
- smart_objects::SmartObject message;
- message[am::strings::params][am::hmi_response::code] =
- Common_Result::SUCCESS;
- message[am::strings::params][am::strings::correlation_id] = corr_id;
- am::event_engine::Event event(
- hmi_apis::FunctionID::BasicCommunication_ActivateApp);
- event.set_smart_object(message);
- state_ctrl_.on_event(event);
- }
+ SetBCActivateAppRequestToHMI(hmi_level, corr_id);
+ ON_CALL(app_manager_mock_, ManageHMICommand(bc_activate_app_request))
+ .WillByDefault(Return(true));
+
+ EXPECT_CALL(app_manager_mock_, application_id(corr_id))
+ .WillOnce(Return(hmi_app_id));
+ EXPECT_CALL(app_manager_mock_, application_by_hmi_app(hmi_app_id))
+ .WillOnce(Return(media_app_));
+ ExpectSuccesfullSetHmiState(
+ media_app_, media_app_ptr_, initial_hmi_state, hmi_state);
+ state_ctrl_->SetRegularState(media_app_, hmi_state, true);
+ smart_objects::SmartObject message;
+ message[am::strings::params][am::hmi_response::code] =
+ Common_Result::SUCCESS;
+ message[am::strings::params][am::strings::correlation_id] = corr_id;
+ am::event_engine::Event event(
+ hmi_apis::FunctionID::BasicCommunication_ActivateApp);
+ event.set_smart_object(message);
+ state_ctrl_->on_event(event);
}
}
-/*
-TEST_F(StateControllerTest, ActivateAppErrorReceivedFromHMI) {
+
+std::vector<hmi_apis::Common_Result::eType> hmi_result() {
using namespace hmi_apis;
- const uint32_t corr_id = 314;
- const uint32_t hmi_app_id = 2718;
std::vector<Common_Result::eType> hmi_results;
hmi_results.push_back(Common_Result::ABORTED);
hmi_results.push_back(Common_Result::APPLICATION_NOT_REGISTERED);
@@ -1383,45 +1794,45 @@ TEST_F(StateControllerTest, ActivateAppErrorReceivedFromHMI) {
hmi_results.push_back(Common_Result::USER_DISALLOWED);
hmi_results.push_back(Common_Result::WARNINGS);
hmi_results.push_back(Common_Result::WRONG_LANGUAGE);
+ return hmi_results;
+}
+
+TEST_F(StateControllerImplTest, SendEventBCActivateApp_HMIReceivesError) {
+ using namespace hmi_apis;
+ const uint32_t corr_id = 314;
+ const uint32_t hmi_app_id = 2718;
+ std::vector<Common_Result::eType> hmi_results = hmi_result();
std::vector<Common_Result::eType>::iterator it = hmi_results.begin();
for (; it != hmi_results.end(); ++it) {
- EXPECT_CALL(
- *message_helper_mock_,
- SendActivateAppToHMI(simple_app_->app_id(), Common_HMILevel::FULL, _))
- .WillOnce(Return(corr_id));
EXPECT_CALL(app_manager_mock_, application_id(corr_id))
.WillOnce(Return(hmi_app_id));
EXPECT_CALL(app_manager_mock_, application_by_hmi_app(hmi_app_id))
.WillOnce(Return(simple_app_));
- EXPECT_CALL(*simple_app_ptr_, RegularHmiState())
- .WillOnce(Return(BackgroundState()));
- EXPECT_CALL(*simple_app_ptr_, CurrentHmiState())
- .WillOnce(Return(BackgroundState()))
- .WillOnce(Return(BackgroundState()));
- EXPECT_CALL(*simple_app_ptr_,
- SetRegularState(Truly(HmiStatesComparator(BackgroundState()))));
+
+ EXPECT_CALL(*simple_app_ptr_, RegularHmiState()).Times(0);
+ EXPECT_CALL(*simple_app_ptr_, CurrentHmiState()).Times(0);
+ EXPECT_CALL(*simple_app_ptr_, SetRegularState(_)).Times(0);
+
EXPECT_CALL(app_manager_mock_, SendHMIStatusNotification(simple_app_))
.Times(0);
EXPECT_CALL(app_manager_mock_,
OnHMILevelChanged(simple_app_->app_id(), _, _)).Times(0);
- state_ctrl_.SetRegularState<true>(simple_app_, FullNotAudibleState());
+
smart_objects::SmartObject message;
message[am::strings::params][am::hmi_response::code] = *it;
message[am::strings::params][am::strings::correlation_id] = corr_id;
am::event_engine::Event event(FunctionID::BasicCommunication_ActivateApp);
event.set_smart_object(message);
- state_ctrl_.on_event(event);
+ state_ctrl_->on_event(event);
}
}
-*/
-TEST_F(StateControllerTest, ActivateAppInvalidCorrelationId) {
+
+TEST_F(StateControllerImplTest, ActivateAppInvalidCorrelationId) {
using namespace hmi_apis;
const uint32_t corr_id = 314;
const uint32_t hmi_app_id = 2718;
- EXPECT_CALL(*message_helper_mock_,
- SendActivateAppToHMI(simple_app_->app_id(), Common_HMILevel::FULL,
- _)).WillOnce(Return(hmi_app_id));
+
EXPECT_CALL(app_manager_mock_, application_id(corr_id))
.WillOnce(Return(hmi_app_id));
EXPECT_CALL(app_manager_mock_, application_by_hmi_app(hmi_app_id))
@@ -1431,53 +1842,642 @@ TEST_F(StateControllerTest, ActivateAppInvalidCorrelationId) {
.Times(0);
EXPECT_CALL(app_manager_mock_, OnHMILevelChanged(simple_app_->app_id(), _, _))
.Times(0);
- state_ctrl_.SetRegularState<true>(simple_app_, FullNotAudibleState());
+ SetBCActivateAppRequestToHMI(Common_HMILevel::FULL, corr_id);
+ state_ctrl_->SetRegularState(simple_app_, FullNotAudibleState(), true);
smart_objects::SmartObject message;
message[am::strings::params][am::hmi_response::code] = Common_Result::SUCCESS;
message[am::strings::params][am::strings::correlation_id] = corr_id;
am::event_engine::Event event(FunctionID::BasicCommunication_ActivateApp);
event.set_smart_object(message);
- state_ctrl_.on_event(event);
+ state_ctrl_->on_event(event);
}
-/*
-TEST_F(StateControllerTest, ApplyTempStatesForSimpleApp) {
+
+TEST_F(StateControllerImplTest, ApplyTempStatesForSimpleApp) {
InsertApplication(simple_app_);
CheckStateApplyingForApplication(*simple_app_ptr_, valid_state_ids_);
}
-TEST_F(StateControllerTest, ApplyTempStatesForMediaApp) {
+TEST_F(StateControllerImplTest, ApplyTempStatesForMediaApp) {
InsertApplication(media_app_);
CheckStateApplyingForApplication(*media_app_ptr_, valid_state_ids_);
}
-TEST_F(StateControllerTest, ApplyTempStatesForNaviApp) {
+TEST_F(StateControllerImplTest, ApplyTempStatesForNaviApp) {
InsertApplication(navi_app_);
CheckStateApplyingForApplication(*navi_app_ptr_, valid_state_ids_);
}
-TEST_F(StateControllerTest, ApplyTempStatesForVCApp) {
+TEST_F(StateControllerImplTest, ApplyTempStatesForVCApp) {
InsertApplication(vc_app_);
CheckStateApplyingForApplication(*vc_app_ptr_, valid_state_ids_);
}
-TEST_F(StateControllerTest, ApplyTempStatesForMediaNaviApp) {
+TEST_F(StateControllerImplTest, ApplyTempStatesForMediaNaviApp) {
InsertApplication(media_navi_app_);
CheckStateApplyingForApplication(*media_navi_app_ptr_, valid_state_ids_);
}
-TEST_F(StateControllerTest, ApplyTempStatesForMediaVCApp) {
+TEST_F(StateControllerImplTest, ApplyTempStatesForMediaVCApp) {
InsertApplication(media_vc_app_);
CheckStateApplyingForApplication(*media_vc_app_ptr_, valid_state_ids_);
}
-TEST_F(StateControllerTest, ApplyTempStatesForNaviVCApp) {
+TEST_F(StateControllerImplTest, ApplyTempStatesForNaviVCApp) {
InsertApplication(navi_vc_app_);
CheckStateApplyingForApplication(*navi_vc_app_ptr_, valid_state_ids_);
}
-TEST_F(StateControllerTest, ApplyTempStatesForMediaNaviVCApp) {
+TEST_F(StateControllerImplTest, ApplyTempStatesForMediaNaviVCApp) {
InsertApplication(media_navi_vc_app_);
CheckStateApplyingForApplication(*media_navi_vc_app_ptr_, valid_state_ids_);
}
-*/
+
+TEST_F(StateControllerImplTest, SetStatePhoneCallForNonMediaApplication) {
+ am::HmiStatePtr state_phone_call = utils::MakeShared<am::PhoneCallHmiState>(
+ simple_app_id_, app_manager_mock_);
+ TestSetState(simple_app_,
+ state_phone_call,
+ APP_TYPE_NON_MEDIA,
+ &StateControllerImplTest::PreparePhoneCallHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, SetStatePhoneCallForMediaApplication) {
+ am::HmiStatePtr state_phone_call = utils::MakeShared<am::PhoneCallHmiState>(
+ media_app_id_, app_manager_mock_);
+ TestSetState(media_app_,
+ state_phone_call,
+ APP_TYPE_MEDIA,
+ &StateControllerImplTest::PreparePhoneCallHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, SetStatePhoneCallForMediaNaviApplication) {
+ am::HmiStatePtr state_phone_call = utils::MakeShared<am::PhoneCallHmiState>(
+ media_navi_app_id_, app_manager_mock_);
+ TestSetState(media_navi_app_,
+ state_phone_call,
+ APP_TYPE_NAVI,
+ &StateControllerImplTest::PreparePhoneCallHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, SetVRStateForNonMediaApplication) {
+ am::HmiStatePtr state_vr =
+ utils::MakeShared<am::VRHmiState>(simple_app_id_, app_manager_mock_);
+ TestSetState(simple_app_,
+ state_vr,
+ APP_TYPE_NON_MEDIA,
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, SetVRStateForMediaApplication) {
+ am::HmiStatePtr state_vr =
+ utils::MakeShared<am::VRHmiState>(media_app_id_, app_manager_mock_);
+ TestSetState(media_app_,
+ state_vr,
+ APP_TYPE_MEDIA,
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, SetVRStateForMediaNaviVoiceApplication) {
+ am::HmiStatePtr state_vr = utils::MakeShared<am::VRHmiState>(
+ media_navi_vc_app_id_, app_manager_mock_);
+ TestSetState(media_navi_vc_app_,
+ state_vr,
+ APP_TYPE_MEDIA,
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ SetTTSStateForNonMediaApplicationAttenuatedNotSupported) {
+ am::HmiStatePtr state_tts =
+ utils::MakeShared<am::TTSHmiState>(simple_app_id_, app_manager_mock_);
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(false));
+ TestSetState(simple_app_,
+ state_tts,
+ APP_TYPE_NON_MEDIA,
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ SetTTSStateForNonMediaApplicationAttenuatedSupported) {
+ am::HmiStatePtr state_tts =
+ utils::MakeShared<am::TTSHmiState>(simple_app_id_, app_manager_mock_);
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(true));
+ TestSetState(simple_app_,
+ state_tts,
+ APP_TYPE_NON_MEDIA,
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ SetTTSStateForMediaApplicationAttenuatedNotSupported) {
+ am::HmiStatePtr state_tts =
+ utils::MakeShared<am::TTSHmiState>(media_app_id_, app_manager_mock_);
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(false));
+ TestSetState(media_app_,
+ state_tts,
+ APP_TYPE_MEDIA,
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ SetTTSStateForMediaApplicationAttenuatedSupported) {
+ am::HmiStatePtr state_tts =
+ utils::MakeShared<am::TTSHmiState>(media_app_id_, app_manager_mock_);
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(true));
+ TestSetState(media_app_,
+ state_tts,
+ APP_TYPE_ATTENUATED,
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ SetTTSStateForMediaNaviVCApplicationAttenuatedNotSupported) {
+ am::HmiStatePtr state_tts = utils::MakeShared<am::TTSHmiState>(
+ media_navi_vc_app_id_, app_manager_mock_);
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(false));
+ TestSetState(media_navi_vc_app_,
+ state_tts,
+ APP_TYPE_MEDIA,
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ SetTTSStateForMediaNaviVCApplicationAttenuatedSupported) {
+ am::HmiStatePtr state_tts = utils::MakeShared<am::TTSHmiState>(
+ media_navi_vc_app_id_, app_manager_mock_);
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(true));
+ TestSetState(media_navi_vc_app_,
+ state_tts,
+ APP_TYPE_ATTENUATED,
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, SetNaviStreamingStateForNonMediaApplication) {
+ am::HmiStatePtr state_navi_streming =
+ utils::MakeShared<am::NaviStreamingHmiState>(simple_app_id_,
+ app_manager_mock_);
+ TestSetState(simple_app_,
+ state_navi_streming,
+ APP_TYPE_NON_MEDIA,
+ &StateControllerImplTest::PrepareNaviStreamingHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ SetNaviStreamingStateMediaApplicationAttenuatedNotSupported) {
+ am::HmiStatePtr state_navi_streming =
+ utils::MakeShared<am::NaviStreamingHmiState>(media_app_id_,
+ app_manager_mock_);
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(false));
+ TestSetState(media_app_,
+ state_navi_streming,
+ APP_TYPE_MEDIA,
+ &StateControllerImplTest::PrepareNaviStreamingHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ SetNaviStreamingStateMediaApplicationAttenuatedSupported) {
+ am::HmiStatePtr state_navi_streming =
+ utils::MakeShared<am::NaviStreamingHmiState>(media_app_id_,
+ app_manager_mock_);
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(true));
+ TestSetState(media_app_,
+ state_navi_streming,
+ APP_TYPE_ATTENUATED,
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ SetNaviStreamingStateVCApplicationAttenuatedNotSupported) {
+ am::HmiStatePtr state_navi_streming =
+ utils::MakeShared<am::NaviStreamingHmiState>(vc_app_id_,
+ app_manager_mock_);
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(false));
+ TestSetState(vc_app_,
+ state_navi_streming,
+ APP_TYPE_MEDIA,
+ &StateControllerImplTest::PrepareNaviStreamingHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ SetNaviStreamingStateVCApplicationAttenuatedSupported) {
+ am::HmiStatePtr state_navi_streming =
+ utils::MakeShared<am::NaviStreamingHmiState>(vc_app_id_,
+ app_manager_mock_);
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(true));
+ TestSetState(vc_app_,
+ state_navi_streming,
+ APP_TYPE_ATTENUATED,
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, SetNaviStreamingStateNaviApplication) {
+ am::HmiStatePtr state_navi_streming =
+ utils::MakeShared<am::NaviStreamingHmiState>(navi_app_id_,
+ app_manager_mock_);
+ TestSetState(navi_app_,
+ state_navi_streming,
+ APP_TYPE_NAVI,
+ &StateControllerImplTest::PrepareNaviStreamingHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, SetNaviStreamingStateMediaNaviApplication) {
+ am::HmiStatePtr state_navi_streming =
+ utils::MakeShared<am::NaviStreamingHmiState>(media_navi_app_id_,
+ app_manager_mock_);
+ TestSetState(media_navi_app_,
+ state_navi_streming,
+ APP_TYPE_NAVI,
+ &StateControllerImplTest::PrepareNaviStreamingHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, SetSafetyModeStateForNonMediaApplication) {
+ am::HmiStatePtr state_safety_mode = utils::MakeShared<am::SafetyModeHmiState>(
+ simple_app_id_, app_manager_mock_);
+ TestSetState(simple_app_,
+ state_safety_mode,
+ APP_TYPE_NON_MEDIA,
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, SetSafetyModeStateForMediaApplication) {
+ am::HmiStatePtr state_safety_mode =
+ utils::MakeShared<am::VRHmiState>(media_app_id_, app_manager_mock_);
+ TestSetState(media_app_,
+ state_safety_mode,
+ APP_TYPE_MEDIA,
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ SetSafetyModeStateForMediaNaviVoiceApplication) {
+ am::HmiStatePtr state_safety_mode = utils::MakeShared<am::VRHmiState>(
+ media_navi_vc_app_id_, app_manager_mock_);
+ TestSetState(media_navi_vc_app_,
+ state_safety_mode,
+ APP_TYPE_MEDIA,
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, MixVRWithPhoneCall) {
+ TestMixState<am::PhoneCallHmiState, am::VRHmiState>(
+ &StateControllerImplTest::PreparePhoneCallHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, MixTTSWithPhoneCallAttenuatedNotSupported) {
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(false));
+
+ TestMixState<am::PhoneCallHmiState, am::TTSHmiState>(
+ &StateControllerImplTest::PreparePhoneCallHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, MixTTSWithPhoneCallAttenuatedSupported) {
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(true));
+
+ TestMixState<am::PhoneCallHmiState, am::TTSHmiState>(
+ &StateControllerImplTest::PreparePhoneCallHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ MixNaviStreamingWithPhoneCallAttenuatedNotSupported) {
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(false));
+
+ TestMixState<am::PhoneCallHmiState, am::NaviStreamingHmiState>(
+ &StateControllerImplTest::PreparePhoneCallHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ MixNaviStreamingWithPhoneCallAttenuatedSupported) {
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(true));
+
+ TestMixState<am::PhoneCallHmiState, am::NaviStreamingHmiState>(
+ &StateControllerImplTest::PreparePhoneCallHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, MixSafetyModeWithPhoneCall) {
+ TestMixState<am::PhoneCallHmiState, am::SafetyModeHmiState>(
+ &StateControllerImplTest::PreparePhoneCallHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, MixTTSWithVRAttenuatedNotSupported) {
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(false));
+
+ TestMixState<am::VRHmiState, am::TTSHmiState>(
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, MixTTSWithVRAttenuatedSupported) {
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(true));
+
+ TestMixState<am::VRHmiState, am::TTSHmiState>(
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, MixNaviStreamingWithVRAttenuatedNotSupported) {
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(false));
+
+ TestMixState<am::VRHmiState, am::NaviStreamingHmiState>(
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, MixNaviStreamingWithVRAttenuatedSupported) {
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(true));
+
+ TestMixState<am::VRHmiState, am::NaviStreamingHmiState>(
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, MixSafetyModeStreamingWithVR) {
+ TestMixState<am::VRHmiState, am::SafetyModeHmiState>(
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ MixNaviStreamingWithTTSAttenueatedNotSupported) {
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(false));
+
+ TestMixState<am::TTSHmiState, am::NaviStreamingHmiState>(
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, MixNaviStreamingWithTTSAttenueatedSupported) {
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(true));
+
+ TestMixState<am::TTSHmiState, am::NaviStreamingHmiState>(
+ &StateControllerImplTest::PrepareNaviStreamTTSStateResult);
+}
+
+TEST_F(StateControllerImplTest, MixSafetyModeWithTTSAttenueatedNotSupported) {
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(false));
+
+ TestMixState<am::TTSHmiState, am::SafetyModeHmiState>(
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, MixSafetyModeWithTTSAttenueatedSupported) {
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(true));
+
+ TestMixState<am::TTSHmiState, am::SafetyModeHmiState>(
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ MixSafetyModeWithNaviStreamingAttenueatedNotSupported) {
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(false));
+
+ TestMixState<am::SafetyModeHmiState, am::NaviStreamingHmiState>(
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest,
+ MixSafetyModeWithNaviStreamingAttenueatedSupported) {
+ EXPECT_CALL(app_manager_mock_, is_attenuated_supported())
+ .WillRepeatedly(Return(true));
+
+ TestMixState<am::SafetyModeHmiState, am::NaviStreamingHmiState>(
+ &StateControllerImplTest::PrepareVRTTSHMIStateResults);
+}
+
+TEST_F(StateControllerImplTest, SetRegularStateWithNewHmiLvl) {
+ using namespace mobile_apis;
+
+ HMILevel::eType set_lvl = HMILevel::HMI_NONE;
+ EXPECT_CALL(*simple_app_ptr_, RegularHmiState())
+ .WillOnce(Return(BackgroundState()));
+
+ EXPECT_CALL(*simple_app_ptr_, CurrentHmiState())
+ .WillOnce(Return(BackgroundState()))
+ .WillOnce(Return(BackgroundState()));
+
+ state_ctrl_->SetRegularState(simple_app_, set_lvl);
+
+ set_lvl = HMILevel::HMI_LIMITED;
+ EXPECT_CALL(*simple_app_ptr_, RegularHmiState())
+ .WillOnce(Return(BackgroundState()));
+
+ EXPECT_CALL(*simple_app_ptr_, CurrentHmiState())
+ .WillOnce(Return(BackgroundState()))
+ .WillOnce(Return(BackgroundState()));
+ state_ctrl_->SetRegularState(simple_app_, set_lvl);
+
+ set_lvl = HMILevel::HMI_FULL;
+ EXPECT_CALL(*simple_app_ptr_, RegularHmiState())
+ .WillOnce(Return(BackgroundState()));
+
+ const uint32_t corr_id = 314;
+ SetBCActivateAppRequestToHMI(
+ static_cast<hmi_apis::Common_HMILevel::eType>(set_lvl), corr_id);
+
+ state_ctrl_->SetRegularState(simple_app_, set_lvl);
+
+ set_lvl = HMILevel::HMI_BACKGROUND;
+ EXPECT_CALL(*simple_app_ptr_, RegularHmiState())
+ .WillOnce(Return(BackgroundState()));
+
+ EXPECT_CALL(*simple_app_ptr_, CurrentHmiState())
+ .WillOnce(Return(BackgroundState()))
+ .WillOnce(Return(BackgroundState()));
+
+ state_ctrl_->SetRegularState(simple_app_, set_lvl);
+}
+
+TEST_F(StateControllerImplTest, SetRegularStateWithAudioStateAudible) {
+ using namespace mobile_apis;
+
+ HmiStatePtr check_state = createHmiState(HMILevel::HMI_BACKGROUND,
+ AudioStreamingState::AUDIBLE,
+ SystemContext::SYSCTXT_MAIN);
+ EXPECT_CALL(*simple_app_ptr_, RegularHmiState())
+ .WillRepeatedly(Return(BackgroundState()));
+
+ EXPECT_CALL(*simple_app_ptr_, CurrentHmiState())
+ .WillOnce(Return(check_state))
+ .WillOnce(Return(check_state));
+ EXPECT_CALL(*simple_app_ptr_,
+ SetRegularState(Truly(HmiStatesComparator(check_state))));
+
+ state_ctrl_->SetRegularState(simple_app_, AudioStreamingState::AUDIBLE);
+}
+
+TEST_F(StateControllerImplTest,
+ SetRegularStateToMediaAndNonMediaApps_VRStarted_SetPostponedState) {
+ using namespace mobile_apis;
+
+ // Precondition
+ am::event_engine::Event event(hmi_apis::FunctionID::VR_Started);
+ state_ctrl_->on_event(event);
+
+ HmiStatePtr check_state = FullNotAudibleState();
+
+ // Non-media app can't have LIMITED-AUDIO state
+ EXPECT_CALL(*simple_app_ptr_, is_resuming()).WillRepeatedly(Return(true));
+ EXPECT_CALL(*simple_app_ptr_, CurrentHmiState()).Times(0);
+ EXPECT_CALL(*simple_app_ptr_, SetRegularState(_)).Times(0);
+ EXPECT_CALL(app_manager_mock_, GetDefaultHmiLevel(_))
+ .WillRepeatedly(Return(mobile_apis::HMILevel::HMI_NONE));
+ EXPECT_CALL(app_manager_mock_, active_application())
+ .WillRepeatedly(Return(am::ApplicationSharedPtr()));
+ EXPECT_CALL(*simple_app_ptr_,
+ SetPostponedState(Truly(HmiStatesComparator(check_state))));
+ state_ctrl_->SetRegularState(simple_app_, check_state, false);
+
+ check_state = LimitedState();
+ EXPECT_CALL(*media_app_ptr_, is_resuming()).WillRepeatedly(Return(true));
+ EXPECT_CALL(*media_app_ptr_, CurrentHmiState()).Times(0);
+ EXPECT_CALL(*media_app_ptr_, SetRegularState(_)).Times(0);
+ EXPECT_CALL(*media_app_ptr_,
+ SetPostponedState(Truly(HmiStatesComparator(check_state))));
+ state_ctrl_->SetRegularState(media_app_, check_state, false);
+}
+
+TEST_F(StateControllerImplTest, SetRegularStateMediaToNonMediaApp_VR_Stopped) {
+ using namespace mobile_apis;
+
+ // Precondition
+ am::event_engine::Event prev_event(hmi_apis::FunctionID::VR_Started);
+ state_ctrl_->on_event(prev_event);
+
+ am::event_engine::Event next_event(hmi_apis::FunctionID::VR_Stopped);
+ state_ctrl_->on_event(next_event);
+
+ // Set state of non-media app after vr has stopped
+ HmiStatePtr check_state = FullNotAudibleState();
+
+ // Non-media app can't have LIMITED-AUDIO state
+ EXPECT_CALL(*simple_app_ptr_, CurrentHmiState())
+ .WillOnce(Return(check_state))
+ .WillOnce(Return(check_state));
+
+ EXPECT_CALL(*simple_app_ptr_, is_resuming()).WillRepeatedly(Return(false));
+
+ EXPECT_CALL(*message_helper_mock_,
+ SendOnResumeAudioSourceToHMI(simple_app_id_, _)).Times(0);
+ EXPECT_CALL(*simple_app_ptr_,
+ SetPostponedState(Truly(HmiStatesComparator(check_state))))
+ .Times(0);
+ EXPECT_CALL(*simple_app_ptr_,
+ SetRegularState(Truly(HmiStatesComparator(check_state))));
+ state_ctrl_->SetRegularState(simple_app_, check_state, false);
+
+ // Set state of media app after vr has stopped
+ check_state = LimitedState();
+
+ EXPECT_CALL(*media_app_ptr_, CurrentHmiState())
+ .WillOnce(Return(check_state))
+ .WillOnce(Return(check_state));
+
+ EXPECT_CALL(*media_app_ptr_, is_resuming()).WillRepeatedly(Return(true));
+
+ EXPECT_CALL(*message_helper_mock_,
+ SendOnResumeAudioSourceToHMI(media_app_id_, _));
+ EXPECT_CALL(*media_app_ptr_,
+ SetPostponedState(Truly(HmiStatesComparator(check_state))))
+ .Times(0);
+ EXPECT_CALL(*media_app_ptr_,
+ SetRegularState(Truly(HmiStatesComparator(check_state))));
+ state_ctrl_->SetRegularState(media_app_, check_state, false);
+}
+
+TEST_F(StateControllerImplTest,
+ SetRegStateForMediaAndNonMediaApps_OnEmergencyEvent_SetPostponedState) {
+ using namespace hmi_apis;
+ using namespace smart_objects;
+ using namespace am::event_engine;
+
+ // Precondition
+ Event event(FunctionID::BasicCommunication_OnEventChanged);
+ SmartObject message;
+ message[am::strings::msg_params][am::hmi_notification::is_active] = true;
+ message[am::strings::msg_params][am::hmi_notification::event_name] =
+ Common_EventTypes::EMERGENCY_EVENT;
+
+ event.set_smart_object(message);
+ state_ctrl_->on_event(event);
+
+ // Non-media app can't have LIMITED-AUDIO state
+ HmiStatePtr check_state = FullNotAudibleState();
+ EXPECT_CALL(*simple_app_ptr_, is_resuming()).WillRepeatedly(Return(true));
+
+ EXPECT_CALL(*simple_app_ptr_, RegularHmiState()).Times(0);
+ EXPECT_CALL(*simple_app_ptr_, CurrentHmiState()).Times(0);
+ EXPECT_CALL(*simple_app_ptr_, SetRegularState(_)).Times(0);
+ EXPECT_CALL(app_manager_mock_, GetDefaultHmiLevel(_))
+ .WillRepeatedly(Return(mobile_apis::HMILevel::HMI_NONE));
+ EXPECT_CALL(app_manager_mock_, active_application())
+ .WillRepeatedly(Return(am::ApplicationSharedPtr()));
+ EXPECT_CALL(*simple_app_ptr_,
+ SetPostponedState(Truly(HmiStatesComparator(check_state))));
+ state_ctrl_->SetRegularState(simple_app_, check_state, false);
+
+ // Set media app
+ check_state = LimitedState();
+ EXPECT_CALL(*media_app_ptr_, is_resuming()).WillRepeatedly(Return(true));
+
+ EXPECT_CALL(*media_app_ptr_, RegularHmiState()).Times(0);
+ EXPECT_CALL(*media_app_ptr_, CurrentHmiState()).Times(0);
+ EXPECT_CALL(*media_app_ptr_, SetRegularState(_)).Times(0);
+
+ EXPECT_CALL(*media_app_ptr_,
+ SetPostponedState(Truly(HmiStatesComparator(check_state))));
+ state_ctrl_->SetRegularState(media_app_, check_state, false);
+}
+
+TEST_F(StateControllerImplTest,
+ SetStateForMediaApp_BCOnPhoneCall_SetPostponedState) {
+ using namespace hmi_apis;
+ using namespace smart_objects;
+ using namespace am::event_engine;
+
+ // Precondition
+ Event event(FunctionID::BasicCommunication_OnEventChanged);
+ SmartObject message;
+ message[am::strings::msg_params][am::hmi_notification::is_active] = true;
+ message[am::strings::msg_params][am::hmi_notification::event_name] =
+ hmi_apis::Common_EventTypes::PHONE_CALL;
+
+ event.set_smart_object(message);
+ state_ctrl_->on_event(event);
+
+ am::HmiStatePtr check_state = FullAudibleState();
+
+ EXPECT_CALL(*media_app_ptr_, is_resuming()).WillRepeatedly(Return(true));
+
+ EXPECT_CALL(*media_app_ptr_, is_media_application())
+ .WillRepeatedly(Return(true));
+
+ EXPECT_CALL(app_manager_mock_, IsAppTypeExistsInFullOrLimited(_))
+ .WillRepeatedly(Return(false));
+
+ EXPECT_CALL(app_manager_mock_, active_application())
+ .WillRepeatedly(Return(am::ApplicationSharedPtr()));
+
+ EXPECT_CALL(*media_app_ptr_,
+ SetPostponedState(Truly(HmiStatesComparator(check_state))));
+ state_ctrl_->SetRegularState(media_app_, check_state, false);
+}
+
} // namespace state_controller_test
+} // namespace components
+} // namespace test
diff --git a/src/components/application_manager/test/usage_statistics_test.cc b/src/components/application_manager/test/usage_statistics_test.cc
new file mode 100644
index 0000000000..b5d1da0992
--- /dev/null
+++ b/src/components/application_manager/test/usage_statistics_test.cc
@@ -0,0 +1,174 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "application_manager/usage_statistics.h"
+#include <memory>
+#include "gmock/gmock.h"
+#include "smart_objects/enum_schema_item.h"
+#include "policy/mock_statistics_manager.h"
+#include "mock_app_stopwatch.h"
+#include "utils/make_shared.h"
+#include "utils/shared_ptr.h"
+
+namespace test {
+namespace components {
+namespace usage_statistics_test {
+
+using namespace mobile_apis; // For Language enums
+using namespace NsSmartDeviceLink::NsSmartObjects; // For EnumToCString &
+ // EnumConversionHelper
+using namespace usage_statistics;
+using testing::_;
+
+namespace {
+
+std::string LanguageIdToString(Language::eType lang_id) {
+ const char* str;
+ const bool ok =
+ EnumConversionHelper<Language::eType>::EnumToCString(lang_id, &str);
+ return ok ? str : "unknown";
+}
+
+// Constant values used in tests
+const Language::eType kTestLanguageId = Language::eType::DE_DE;
+const usage_statistics::AppStopwatchId kTestAppStopwatchId =
+ usage_statistics::AppStopwatchId::SECONDS_HMI_NONE;
+const std::string kAppId = "SPT";
+
+} // namespace
+
+class UsageStatisticsTest : public testing::Test {
+ public:
+ UsageStatisticsTest()
+ : mock_statistics_manager_sptr_(
+ utils::MakeShared<MockStatisticsManager>())
+ , usage_statistics_test_object1_sptr_(
+ new application_manager::UsageStatistics(
+ kAppId, mock_statistics_manager_sptr_))
+ , language_(LanguageIdToString(kTestLanguageId)) {}
+
+ protected:
+ utils::SharedPtr<MockStatisticsManager> mock_statistics_manager_sptr_;
+ std::auto_ptr<application_manager::UsageStatistics>
+ usage_statistics_test_object1_sptr_;
+ const std::string language_;
+};
+
+TEST_F(UsageStatisticsTest, RecordHmiStateChanged_CallMethod_ExpectMethodCall) {
+ // Arrange
+ std::auto_ptr<MockAppStopwatch> mock_app_stopwatch_object(
+ new MockAppStopwatch);
+
+ // Checks
+ EXPECT_CALL(*mock_app_stopwatch_object, Start(kTestAppStopwatchId));
+ EXPECT_CALL(*mock_app_stopwatch_object, Switch(kTestAppStopwatchId));
+
+ // Act
+ std::auto_ptr<application_manager::UsageStatistics>
+ usage_statistics_test_object2_sptr_(
+ new application_manager::UsageStatistics(
+ kAppId,
+ mock_statistics_manager_sptr_,
+ mock_app_stopwatch_object.release()));
+ usage_statistics_test_object2_sptr_->RecordHmiStateChanged(
+ HMILevel::eType::HMI_NONE);
+}
+
+TEST_F(UsageStatisticsTest,
+ RecordAppRegistrationGuiLanguage_CallMethod_ExpectSetMethodCall) {
+ // Expectation
+ EXPECT_CALL(*mock_statistics_manager_sptr_, Set(kAppId, _, language_));
+ // Act
+ usage_statistics_test_object1_sptr_->RecordAppRegistrationGuiLanguage(
+ kTestLanguageId);
+}
+
+TEST_F(UsageStatisticsTest,
+ RecordAppRegistrationVuiLanguage_CallMethod_ExpectSetMethodCall) {
+ // Expectation
+ EXPECT_CALL(*mock_statistics_manager_sptr_, Set(kAppId, _, language_));
+ // Act
+ usage_statistics_test_object1_sptr_->RecordAppRegistrationVuiLanguage(
+ kTestLanguageId);
+}
+
+TEST_F(UsageStatisticsTest,
+ RecordRpcSentInHMINone_CallMethod_ExpectIncrementMethodCall) {
+ // Expectation
+ EXPECT_CALL(*mock_statistics_manager_sptr_, Increment(kAppId, _));
+ // Act
+ usage_statistics_test_object1_sptr_->RecordRpcSentInHMINone();
+}
+
+TEST_F(UsageStatisticsTest,
+ RecordPolicyRejectedRpcCall_CallMethod_ExpectIncrementMethodCall) {
+ // Expectation
+ EXPECT_CALL(*mock_statistics_manager_sptr_, Increment(kAppId, _));
+ // Act
+ usage_statistics_test_object1_sptr_->RecordPolicyRejectedRpcCall();
+}
+
+TEST_F(UsageStatisticsTest,
+ RecordAppUserSelection_CallMethod_ExpectIncrementMethodCall) {
+ // Expectation
+ EXPECT_CALL(*mock_statistics_manager_sptr_, Increment(kAppId, _));
+ // Act
+ usage_statistics_test_object1_sptr_->RecordAppUserSelection();
+}
+
+TEST_F(UsageStatisticsTest,
+ RecordRunAttemptsWhileRevoked_CallMethod_ExpectIncrementMethodCall) {
+ // Expectation
+ EXPECT_CALL(*mock_statistics_manager_sptr_, Increment(kAppId, _));
+ // Act
+ usage_statistics_test_object1_sptr_->RecordRunAttemptsWhileRevoked();
+}
+
+TEST_F(UsageStatisticsTest,
+ RecordRemovalsForBadBehavior_CallMethod_ExpectIncrementMethodCall) {
+ // Expectation
+ EXPECT_CALL(*mock_statistics_manager_sptr_, Increment(kAppId, _));
+ // Act
+ usage_statistics_test_object1_sptr_->RecordRemovalsForBadBehavior();
+}
+
+TEST_F(UsageStatisticsTest,
+ RecordTLSError_CallMethod_ExpectIncrementMethodCall) {
+ // Expectation
+ EXPECT_CALL(*mock_statistics_manager_sptr_, Increment(kAppId, _));
+ // Act
+ usage_statistics_test_object1_sptr_->RecordTLSError();
+}
+
+} // namespace usage_statistics_test
+} // namespace components
+} // namespace test
diff --git a/src/components/application_manager/test/zero_request_amount_test.cc b/src/components/application_manager/test/zero_request_amount_test.cc
new file mode 100644
index 0000000000..0f52639575
--- /dev/null
+++ b/src/components/application_manager/test/zero_request_amount_test.cc
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <string>
+#include <algorithm>
+#include "gtest/gtest.h"
+
+#include "application_manager/request_controller.h"
+#include "application_manager/commands/command_request_impl.h"
+#include "application_manager/application_manager_impl.h"
+#include "application_manager/message_helper.h"
+#include "application_manager/commands/mobile/put_file_request.h"
+#include "application_manager/commands/mobile/register_app_interface_request.h"
+#include "application_manager/commands/mobile/unregister_app_interface_request.h"
+#include "smart_objects/smart_object.h"
+#include "interfaces/MOBILE_API.h"
+
+namespace test {
+namespace components {
+namespace application {
+using namespace ::profile;
+
+using namespace application_manager::request_controller;
+using namespace application_manager;
+using namespace NsSmartDeviceLink::NsSmartObjects;
+
+commands::Command* RegisterApplication() {
+ SmartObjectSPtr resultsmart =
+ application_manager::MessageHelper::CreateModuleInfoSO(1);
+ SmartObject& test_message = *resultsmart;
+ uint32_t connection_key = 0;
+ test_message[strings::params][strings::connection_key] = connection_key;
+ test_message[strings::msg_params][strings::language_desired] = 0;
+ test_message[strings::msg_params][strings::hmi_display_language_desired] = 0;
+ commands::Command* testregCommand =
+ new commands::RegisterAppInterfaceRequest(resultsmart);
+ return testregCommand;
+}
+
+commands::Command* UnregisterApplication() {
+ SmartObjectSPtr resultsmart =
+ application_manager::MessageHelper::CreateModuleInfoSO(2);
+ commands::Command* testregCommand =
+ new commands::UnregisterAppInterfaceRequest(resultsmart);
+ return testregCommand;
+}
+
+commands::Command* PutFileCommand(uint32_t& correlation_id,
+ uint32_t& connection_key) {
+ SmartObjectSPtr resultsmart =
+ application_manager::MessageHelper::CreateModuleInfoSO(32);
+ SmartObject& test_message = *resultsmart;
+ test_message[strings::params][strings::correlation_id] = correlation_id;
+ test_message[strings::params][strings::connection_key] = connection_key;
+ test_message[strings::msg_params][strings::sync_file_name] = "file.png";
+ test_message[strings::msg_params][strings::file_type] =
+ mobile_apis::FileType::GRAPHIC_PNG;
+
+ commands::Command* testCommand = new commands::PutFileRequest(resultsmart);
+ return testCommand;
+}
+
+TEST(RequestControlTest, ZeroValuePendingRequestsAmount) {
+ // Default value
+ const uint32_t big_count_of_requests_for_test_ =
+ 10; // bigger than pending_requests_amount
+ uint32_t correlation_id = 0;
+ uint32_t connection_key = 0;
+ RequestController::TResult result;
+ RequestController request_ctrl_;
+
+ commands::Command* reg = RegisterApplication();
+ request_ctrl_.addMobileRequest(reg, mobile_apis::HMILevel::HMI_FULL);
+
+ for (uint32_t i = 0; i < big_count_of_requests_for_test_; ++i) {
+ correlation_id = i;
+ commands::Command* testCommand =
+ PutFileCommand(correlation_id, connection_key);
+ result = request_ctrl_.addMobileRequest(testCommand,
+ mobile_apis::HMILevel::HMI_FULL);
+ EXPECT_EQ(RequestController::SUCCESS, result);
+ }
+
+ commands::Command* unreg = UnregisterApplication();
+ request_ctrl_.addMobileRequest(unreg, mobile_apis::HMILevel::HMI_FULL);
+}
+
+TEST(RequestControlTest, ZeroValueAppRequestsTimeScale) {
+ // Default value
+ const uint32_t big_count_of_requests_for_test_ =
+ 10; // bigger than pending_requests_amount
+ uint32_t correlation_id = 0;
+ uint32_t connection_key = 0;
+ RequestController::TResult result;
+ RequestController request_ctrl_;
+
+ commands::Command* reg = RegisterApplication();
+ request_ctrl_.addMobileRequest(reg, mobile_apis::HMILevel::HMI_FULL);
+
+ for (uint32_t i = 0; i < big_count_of_requests_for_test_; ++i) {
+ correlation_id = i;
+ commands::Command* testCommand =
+ PutFileCommand(correlation_id, connection_key);
+ result = request_ctrl_.addMobileRequest(testCommand,
+ mobile_apis::HMILevel::HMI_FULL);
+ EXPECT_EQ(RequestController::SUCCESS, result);
+ }
+
+ commands::Command* unreg = UnregisterApplication();
+ request_ctrl_.addMobileRequest(unreg, mobile_apis::HMILevel::HMI_FULL);
+}
+
+TEST(RequestControlTest, ZeroValueAppTimeScaleMaxRequests) {
+ // Default value
+ const uint32_t big_count_of_requests_for_test_ =
+ 10; // bigger than pending_requests_amount
+ uint32_t correlation_id = 0;
+ uint32_t connection_key = 0;
+ RequestController::TResult result;
+ RequestController request_ctrl_;
+
+ commands::Command* reg = RegisterApplication();
+ request_ctrl_.addMobileRequest(reg, mobile_apis::HMILevel::HMI_FULL);
+
+ for (uint32_t i = 0; i < big_count_of_requests_for_test_; ++i) {
+ correlation_id = i;
+ commands::Command* testCommand =
+ PutFileCommand(correlation_id, connection_key);
+ result = request_ctrl_.addMobileRequest(testCommand,
+ mobile_apis::HMILevel::HMI_FULL);
+ EXPECT_EQ(RequestController::SUCCESS, result);
+ }
+
+ commands::Command* unreg = UnregisterApplication();
+ request_ctrl_.addMobileRequest(unreg, mobile_apis::HMILevel::HMI_FULL);
+}
+
+} // namespace application
+} // namespace components
+} // namespace test
diff --git a/src/components/config_profile/CMakeLists.txt b/src/components/config_profile/CMakeLists.txt
index fe6f373b3a..107fd58127 100644
--- a/src/components/config_profile/CMakeLists.txt
+++ b/src/components/config_profile/CMakeLists.txt
@@ -45,4 +45,4 @@ target_link_libraries("ConfigProfile" Utils)
if(BUILD_TESTS)
add_subdirectory(test)
-endif() \ No newline at end of file
+endif()
diff --git a/src/components/config_profile/include/config_profile/ini_file.h b/src/components/config_profile/include/config_profile/ini_file.h
index 1b6248246c..3f3ddddf48 100644
--- a/src/components/config_profile/include/config_profile/ini_file.h
+++ b/src/components/config_profile/include/config_profile/ini_file.h
@@ -37,7 +37,7 @@
namespace profile {
-#define INI_FILE_VER 1000
+#define INI_FILE_VER 1000
#if !defined TRUE
#define TRUE 1
@@ -56,12 +56,12 @@ namespace profile {
/*
* @brief Global defines
*/
-#define INI_LINE_LEN 512
-#define INI_FILE_TEMP_NAME "ini.tmp"
+#define INI_LINE_LEN 512
+#define INI_FILE_TEMP_NAME "ini.tmp"
-#define INI_FLAG_UPDATE 0x00
-#define INI_FLAG_ITEM_UP_CREA 0x01
-#define INI_FLAG_FILE_UP_CREA 0x10
+#define INI_FLAG_UPDATE 0x00
+#define INI_FLAG_ITEM_UP_CREA 0x01
+#define INI_FLAG_FILE_UP_CREA 0x10
/*
* @brief Global typedefs
@@ -90,28 +90,27 @@ extern "C" {
*
* @return NULL if file or desired entry not found, otherwise pointer to fname
*/
-extern char* ini_write_inst(const char *fname,
- uint8_t flag);
+extern char* ini_write_inst(const char* fname, uint8_t flag);
/*
* @brief Read a certain item of the specified chapter of a ini-file
*
* @return NULL if file or desired entry not found, otherwise pointer to value
*/
-extern char* ini_read_value(const char *fname,
- const char *chapter,
- const char *item,
- char *value);
+extern char* ini_read_value(const char* fname,
+ const char* chapter,
+ const char* item,
+ char* value);
/*
* @brief Write a certain item of the specified chapter of a ini-file
*
* @return NULL if file not found, otherwise pointer to value
*/
-extern char ini_write_value(const char *fname,
- const char *chapter,
- const char *item,
- const char *value,
+extern char ini_write_value(const char* fname,
+ const char* chapter,
+ const char* item,
+ const char* value,
uint8_t flag);
/*
@@ -120,9 +119,9 @@ extern char ini_write_value(const char *fname,
*
* @return NULL if desired entry not found, otherwise pointer to value
*/
-extern Ini_search_id ini_parse_line(const char *line,
- const char *tag,
- char *value);
+extern Ini_search_id ini_parse_line(const char* line,
+ const char* tag,
+ char* value);
#ifdef __cplusplus
}
diff --git a/src/components/config_profile/include/config_profile/profile.h b/src/components/config_profile/include/config_profile/profile.h
index 6a43cafdd3..5abf8a9f78 100644
--- a/src/components/config_profile/include/config_profile/profile.h
+++ b/src/components/config_profile/include/config_profile/profile.h
@@ -38,693 +38,780 @@
#include <vector>
#include <list>
#include "utils/macro.h"
-#include "utils/singleton.h"
+#include "protocol_handler/protocol_handler_settings.h"
+#include "connection_handler/connection_handler_settings.h"
+#include "hmi_message_handler/hmi_message_handler_settings.h"
+#include "media_manager/media_manager_settings.h"
+#include "transport_manager/transport_manager_settings.h"
+#include "application_manager/application_manager_settings.h"
+#include "policy/policy_settings.h"
namespace profile {
/**
* The Profile class
*/
-class Profile : public utils::Singleton<Profile> {
- public:
- // Methods section
-
- /**
- * Destructor
- *
- * Unimplemented to avoid misusing
- *
- */
- virtual ~Profile();
-
- /**
- * @brief Returns sdl version represented
- * by git commit or value specified by user
- */
- const std::string& sdl_version() const;
-
- /**
- * @brief Returns true if HMI should be started, otherwise false
- */
- bool launch_hmi() const;
+class Profile : public protocol_handler::ProtocolHandlerSettings,
+ public connection_handler::ConnectionHandlerSettings,
+ public hmi_message_handler::HMIMessageHandlerSettings,
+ public media_manager::MediaManagerSettings,
+ public policy::PolicySettings,
+ public transport_manager::TransportManagerSettings,
+ public application_manager::ApplicationManagerSettings {
+ public:
+ // Methods section
+
+ /**
+ * Default constructor
+ *
+ * Unimplemented to avoid misusing
+ *
+ */
+ Profile();
+
+ /**
+ * Destructor
+ *
+ * Unimplemented to avoid misusing
+ *
+ */
+ virtual ~Profile();
+
+ /**
+ * @brief Returns sdl version represented
+ * by git commit or value specified by user
+ */
+ const std::string& sdl_version() const OVERRIDE;
+
+ /**
+ * @brief Returns true if HMI should be started, otherwise false
+ */
+ bool launch_hmi() const OVERRIDE;
#ifdef WEB_HMI
- /**
- * @brief Returns link to web hmi
- */
- std::string link_to_web_hmi() const;
-#endif // WEB_HMI
- /**
- * @brief Returns application configuration path
- */
- const std::string& app_config_folder() const;
-
- /**
- * @brief Returns application storage path
- */
- const std::string& app_storage_folder() const;
-
- /**
- * @brief Return application resourse folder
- */
- const std::string& app_resourse_folder() const;
-
- /**
- * @brief Returns true, if SDL 4.0 is enabled
- */
- bool enable_protocol_4() const;
-
- /**
- * @brief Returns application icons folder path
- */
- const std::string& app_icons_folder() const;
-
- /**
- * @brief Returns application icons folder maximum size
- */
- const uint32_t& app_icons_folder_max_size() const;
-
- /**
- * @brief Returns application icons amount to remove from icon folder,
- * if maximum size exceeded
- */
- const uint32_t& app_icons_amount_to_remove() const;
-
- /**
- * @brief Returns the path to the config file
- */
- const std::string& config_file_name() const;
-
- /**
- * @brief Sets the path to the config file
- */
- void config_file_name(const std::string& fileName);
-
- /**
- * @brief Returns server address
- */
- const std::string& server_address() const;
-
- /**
- * @brief Returns server port
- */
- const uint16_t& server_port() const;
-
- /**
- * @brief Returns port for video streaming
- */
- const uint16_t& video_streaming_port() const;
-
- /**
- * @brief Returns port for audio streaming
- */
- const uint16_t& audio_streaming_port() const;
-
- /**
- * @brief Returns streaming timeout
- */
- uint32_t stop_streaming_timeout() const;
-
- /**
- * @brief Returns port for time reports
- */
- const uint16_t& time_testing_port() const;
-
- /**
- * @brief Returns hmi capabilities file name
- */
- const std::string& hmi_capabilities_file_name() const;
-
- /**
- * @brief Returns help promt vector
- */
- const std::vector<std::string>& help_prompt() const;
-
- /**
- * @brief Returns help promt vector
- */
- const std::vector<std::string>& time_out_promt() const;
-
- /**
- * @brief Returns vr commands default for all apps
- * such as Help.
- */
- const std::vector<std::string>& vr_commands() const;
-
- /**
- * @brief Maximum command id available for mobile app
- */
- const uint32_t& max_cmd_id() const;
-
- /**
- * @brief Default timeout for waiting for response to mobile app
- */
- const uint32_t& default_timeout() const;
-
- /**
- * @brief Default timeout for waiting for resuming
- */
- const uint32_t& app_resuming_timeout() const;
- const uint32_t& app_resumption_save_persistent_data_timeout() const;
-
- /**
- * @brief Returns desirable thread stack size
- */
- const uint64_t& thread_min_stack_size() const;
-
- /**
- * @brief Returns true if audio mixing is supported
- */
- bool is_mixing_audio_supported() const;
-
- /**
- * @brief Returns true if video re-decoding enabled
- */
- bool is_redecoding_enabled() const;
-
- /**
- * @brief Returns title for Vr Help
- */
- const std::string& vr_help_title() const;
-
- /**
- * @brief Returns application directory quota size
- */
- const uint32_t& app_dir_quota() const;
-
- /**
- * @brief Returns the video server type
- */
- const std::string& video_server_type() const;
-
- /**
- * @brief Returns the audio server type
- */
- const std::string& audio_server_type() const;
-
- /**
- * @brief Returns the video pipe path
- */
- const std::string& named_video_pipe_path() const;
-
- /**
- * @brief Returns the audio pipe path
- */
- const std::string& named_audio_pipe_path() const;
-
- /**
- * @brief Returns time scale for max amount of requests for application
- * in hmi level none.
- */
- const uint32_t& app_hmi_level_none_time_scale() const;
-
- /**
- * @brief Returns path to testing file to which redirects video stream
- */
- const std::string& video_stream_file() const;
-
- /**
- * @brief Returns path to testing file to which redirects audio stream
- */
- const std::string& audio_stream_file() const;
-
- /**
- * @brief Returns timeout for SDL to wait for the next package of raw data
- * over audio service
- */
- const std::uint32_t audio_data_stopped_timeout() const;
-
- /**
- * @brief Returns timeout for SDL to wait for the next package of raw data
- * over video service
- */
- const std::uint32_t video_data_stopped_timeout() const;
-
- /**
- * @brief Returns allowable max amount of requests per time scale for
- * application in hmi level none
- *
- */
- const uint32_t& app_hmi_level_none_time_scale_max_requests() const;
-
- /**
- * @brief Returns application time scale for max amount of requests per it.
- */
- const uint32_t& app_time_scale() const;
-
- /**
- * @brief Returns allowable max amount of requests per application
- * time scale
- */
- const uint32_t& app_time_scale_max_requests() const;
-
- /**
- * @brief Returns allowable amount of the system pending requests
- */
- const uint32_t& pending_requests_amount() const;
-
- /**
- * @brief Returns Max allowed number of PutFile requests for one
- * application in NONE
- */
- const uint32_t& put_file_in_none() const;
-
- /**
- * @brief Returns Max allowed number of DeleteFile requests for one
- * application in NONE
- */
- const uint32_t& delete_file_in_none() const;
-
- /**
- * @brief Returns Max allowed number of ListFiles requests for one
- * application in NONE
- */
- const uint32_t& list_files_in_none() const;
-
- /*
- * @brief Returns file name for storing applications data
- */
- const std::string& app_info_storage() const;
-
- /*
- * @brief Heartbeat timeout before closing connection
- */
- int32_t heart_beat_timeout() const;
-
- /*
- * @brief Path to preloaded policy file
- */
- const std::string& preloaded_pt_file() const;
-
- /**
- * @brief Path to policies snapshot file
- * @return file path
- */
- const std::string& policies_snapshot_file_name() const;
-
- /**
- * @brief Should Policy be turned off? (Library not loaded)
- * @return Flag
- */
- bool enable_policy() const;
-
- /*
- * @brief Timeout in transport manager before disconnect
+ /**
+ * @brief Returns link to web hmi
*/
- uint32_t transport_manager_disconnect_timeout() const;
-
- /*
- * @brief Returns true if last state singleton is used
- */
- bool use_last_state() const;
-
- /**
- * @brief Returns supported diagnostic modes
- */
- const std::vector<uint32_t>& supported_diag_modes() const;
-
- /**
- * @brief Returns system files folder path
- */
- const std::string& system_files_path() const;
-
- /**
- * @brief Returns port for TCP transport adapter
- */
- uint16_t transport_manager_tcp_adapter_port() const;
-
- /**
- * @brief Returns value of timeout after which sent
- * tts global properties for VCA
- */
- uint16_t tts_global_properties_timeout() const;
-
- /**
- * @brief Reads a string value from the profile
- *
- * @param value Result value
- * @param default_value Value to use key wasn't found
- * @param pSection The section to read the value in
- * @param pKey The key whose value needs to be read out
- *
- * @return FALSE if could not read the value out of the profile
- * (then the value is equal \c default_value)
- */
- bool ReadStringValue(std::string* value,
- const char* default_value,
- const char* const pSection,
- const char* const pKey) const;
-
- /**
- * @brief Reads an int32_t value from the profile
- *
- * @param value Result value
- * @param default_value Value to use key wasn't found
- * @param pSection The section to read the value in
- * @param pKey The key whose value needs to be read out
- *
- * @return FALSE if could not read the value out of the profile
- * (then the value is equal \c default_value)
- */
- bool ReadIntValue(int32_t* value,
- int32_t default_value,
- const char* const pSection,
- const char* const pKey) const;
- /**
- * @brief Reads an bool value from the profile
- *
- * @param value Result value
- * @param default_value Value to use key wasn't found
- * @param pSection The section to read the value in
- * @param pKey The key whose value needs to be read out
- *
- * @return FALSE if could not read the value out of the profile
- * (then the value is equal \c default_value)
- */
- bool ReadBoolValue(bool *value,
- const bool default_value,
- const char * const pSection,
- const char * const pKey) const;
- /**
- * @brief Reads an container of string values from the profile,
- * which handle as "Value1, Value2, Value3"
- *
- * @param pSection The section to read the value in
- * @param pKey The key whose value needs to be read out
- * @param out_result Pointer to bool value for result reading Section
- * (could be NULL)
- *
- * @return container of values or empty continer
- * if could not read the value out of the profile
- */
- std::list<std::string> ReadStringContainer(
- const char * const pSection,
- const char * const pKey,
- bool* out_result) const;
- /**
- * @brief Reads an container of hex int values from the profile,
- * which handle as "0x01, 0xA0, 0XFF"
- *
- * @param pSection The section to read the value in
- * @param pKey The key whose value needs to be read out
- * @param out_result Pointer to bool value for result reading Section
- * (could be NULL)
- *
- * @return container of values or empty continer
- * if could not read the value out of the profile
- */
- std::list<int> ReadIntContainer(const char * const pSection,
- const char * const pKey,
- bool* out_result) const;
+ std::string link_to_web_hmi() const;
+#endif // WEB_HMI
+ /**
+ * @brief Returns application configuration path
+ */
+ const std::string& app_config_folder() const;
+
+ /**
+ * @brief Returns application storage path
+ */
+ const std::string& app_storage_folder() const;
+
+ /**
+ * @brief Return application resourse folder
+ */
+ const std::string& app_resource_folder() const;
+
+ /**
+ * @brief Returns true, if SDL 4.0 is enabled
+ */
+ bool enable_protocol_4() const OVERRIDE;
+
+ /**
+ * @brief Returns application icons folder path
+ */
+ const std::string& app_icons_folder() const OVERRIDE;
+
+ /**
+ * @brief Returns application icons folder maximum size
+ */
+ const uint32_t& app_icons_folder_max_size() const OVERRIDE;
+
+ /**
+ * @brief Returns application icons amount to remove from icon folder,
+ * if maximum size exceeded
+ */
+ const uint32_t& app_icons_amount_to_remove() const OVERRIDE;
+
+ /**
+ * @brief Returns the path to the config file
+ */
+ const std::string& config_file_name() const;
+
+ /**
+ * @brief Sets the path to the config file
+ */
+ void config_file_name(const std::string& fileName);
+
+ /**
+ * @brief Returns server address
+ */
+ const std::string& server_address() const;
+
+ /**
+ * @brief Returns server port
+ */
+ const uint16_t& server_port() const;
+
+ /**
+ * @brief Returns port for video streaming
+ */
+ const uint16_t video_streaming_port() const OVERRIDE;
+
+ /**
+ * @brief Returns port for audio streaming
+ */
+ const uint16_t audio_streaming_port() const;
- /**
- * @brief Returns delimiter for SDL-generated TTS chunks
- * @return TTS delimiter
- */
- const std::string& tts_delimiter() const;
+ /**
+ * @brief Returns streaming timeout
+ */
+ uint32_t stop_streaming_timeout() const;
- /**
- * @brief Returns recording file source name
- */
- const std::string& recording_file_source() const;
+ /**
+ * @brief Returns port for time reports
+ */
+ const uint16_t& time_testing_port() const;
+
+ /**
+ * @brief Returns hmi capabilities file name
+ */
+ const std::string& hmi_capabilities_file_name() const;
+
+ /**
+ * @brief Returns help promt vector
+ */
+ const std::vector<std::string>& help_prompt() const;
+
+ /**
+ * @brief Returns help promt vector
+ */
+ const std::vector<std::string>& time_out_promt() const;
+
+ /**
+ * @brief Returns vr commands default for all apps
+ * such as Help.
+ */
+ const std::vector<std::string>& vr_commands() const;
+
+ /**
+ * @brief Maximum command id available for mobile app
+ */
+ const uint32_t& max_cmd_id() const;
+
+ /**
+ * @brief Default timeout for waiting for response to mobile app
+ */
+ const uint32_t& default_timeout() const;
+
+ /**
+ * @brief Default timeout for waiting for resuming
+ */
+ const uint32_t& app_resuming_timeout() const;
+ const uint32_t& app_resumption_save_persistent_data_timeout() const;
+
+ /**
+ * @brief Returns desirable thread stack size
+ */
+ const uint64_t& thread_min_stack_size() const;
+
+ /**
+ * @brief Returns true if audio mixing is supported
+ */
+ bool is_mixing_audio_supported() const;
- /**
- * @brief Returns recording file name
- */
- const std::string& recording_file_name() const;
+ /**
+ * @brief Returns true if video re-decoding enabled
+ */
+ bool is_redecoding_enabled() const;
- const std::string& mme_db_name() const;
+ /**
+ * @brief Returns title for Vr Help
+ */
+ const std::string& vr_help_title() const;
- const std::string& event_mq_name() const;
+ /**
+ * @brief Returns application directory quota size
+ */
+ const uint32_t& app_dir_quota() const;
- const std::string& ack_mq_name() const;
+ /**
+ * @brief Returns the video server type
+ */
+ const std::string& video_server_type() const;
- uint32_t application_list_update_timeout() const;
+ /**
+ * @brief Returns the audio server type
+ */
+ const std::string& audio_server_type() const;
- const std::pair<uint32_t, int32_t>& read_did_frequency() const;
+ /**
+ * @brief Returns the video pipe path
+ */
+ const std::string& named_video_pipe_path() const;
- const std::pair<uint32_t, int32_t>& get_vehicle_data_frequency() const;
+ /**
+ * @brief Returns the audio pipe path
+ */
+ const std::string& named_audio_pipe_path() const;
- const std::pair<uint32_t, int32_t>& start_stream_retry_amount() const;
+ /**
+ * @brief Returns time scale for max amount of requests for application
+ * in hmi level none.
+ */
+ const uint32_t& app_hmi_level_none_time_scale() const;
- /**
- * @brief Returns max allowed threads number for handling mobile requests
- */
- uint32_t thread_pool_size() const;
+ /**
+ * @brief Returns path to testing file to which redirects video stream
+ */
+ const std::string& video_stream_file() const;
- uint32_t default_hub_protocol_index() const;
+ /**
+ * @brief Returns path to testing file to which redirects audio stream
+ */
+ const std::string& audio_stream_file() const;
- const std::string& iap_legacy_protocol_mask() const;
+ /**
+ * @brief Returns timeout for SDL to wait for the next package of raw data
+ * over audio service
+ */
+ const std::uint32_t audio_data_stopped_timeout() const;
- const std::string& iap_hub_protocol_mask() const;
+ /**
+ * @brief Returns timeout for SDL to wait for the next package of raw data
+ * over video service
+ */
+ const std::uint32_t video_data_stopped_timeout() const;
- const std::string& iap_pool_protocol_mask() const;
+ /**
+ * @brief Returns allowable max amount of requests per time scale for
+ * application in hmi level none
+ *
+ */
+ const uint32_t& app_hmi_level_none_time_scale_max_requests() const;
- const std::string& iap_system_config() const;
+ /**
+ * @brief Returns application time scale for max amount of requests per it.
+ */
+ const uint32_t& app_time_scale() const;
- const std::string& iap2_system_config() const;
+ /**
+ * @brief Returns allowable max amount of requests per application
+ * time scale
+ */
+ const uint32_t& app_time_scale_max_requests() const;
- int iap2_hub_connect_attempts() const;
+ /**
+ * @brief Returns allowable amount of the system pending requests
+ */
+ const uint32_t& pending_requests_amount() const;
- /**
- * @return seconds
- */
- int iap_hub_connection_wait_timeout() const;
+ /**
+ * @brief Returns Max allowed number of PutFile requests for one
+ * application in NONE
+ */
+ const uint32_t& put_file_in_none() const OVERRIDE;
- /*
- * ProtocolHandler section
- */
- size_t maximum_payload_size() const;
+ /**
+ * @brief Returns Max allowed number of DeleteFile requests for one
+ * application in NONE
+ */
+ const uint32_t& delete_file_in_none() const OVERRIDE;
- size_t message_frequency_count() const;
+ /**
+ * @brief Returns Max allowed number of ListFiles requests for one
+ * application in NONE
+ */
+ const uint32_t& list_files_in_none() const OVERRIDE;
- size_t message_frequency_time() const;
+ /*
+ * @brief Returns file name for storing applications data
+ */
+ const std::string& app_info_storage() const;
- bool malformed_message_filtering() const;
+ /*
+ * @brief Path to preloaded policy file
+ */
+ const std::string& preloaded_pt_file() const;
- size_t malformed_frequency_count() const;
+ /**
+ * @brief Path to policies snapshot file
+ * @return file path
+ */
+ const std::string& policies_snapshot_file_name() const;
- size_t malformed_frequency_time() const;
+ /**
+ * @brief Should Policy be turned off? (Library not loaded)
+ * @return Flag
+ */
+ bool enable_policy() const;
- uint16_t attempts_to_open_policy_db() const;
+ // TransportManageSettings interface
- uint16_t open_attempt_timeout_ms() const;
+ bool use_last_state() const OVERRIDE;
- uint32_t resumption_delay_before_ign() const;
+ uint32_t transport_manager_disconnect_timeout() const OVERRIDE;
- uint32_t resumption_delay_after_ign() const;
+ uint16_t transport_manager_tcp_adapter_port() const OVERRIDE;
- uint32_t hash_string_size() const;
+ // TransportManageMMESettings interface
- /*
- * @brief Updates all related values from ini file
- */
- void UpdateValues();
+ const std::string& event_mq_name() const OVERRIDE;
+ const std::string& ack_mq_name() const OVERRIDE;
- private:
- /**
- * Default constructor
- *
- * Unimplemented to avoid misusing
- *
- */
- Profile();
+ uint32_t iap2_hub_connect_attempts() const OVERRIDE;
+ uint32_t default_hub_protocol_index() const OVERRIDE;
- /**
- * @brief Reads a boolean value from the profile
- *
- * @param value The value to return
- * @param pSection The section to read the value in
- * @param pKey The key whose value needs to be read out
- *
- * @return FALSE if could not read the value out of the profile
- * (then the value is not changed)
- */
- bool ReadValue(bool* value,
- const char* const pSection,
- const char* const pKey) const;
+ const std::string& iap_legacy_protocol_mask() const OVERRIDE;
- /**
- * @brief Reads a string value from the profile and interpret it
- * as \c true on "true" value or as \c false on any other value
- *
- * @param value The value to return
- * @param pSection The section to read the value in
- * @param pKey The key whose value needs to be read out
- *
- * @return FALSE if could not read the value out of the profile
- * (then the value is not changed)
- */
- bool ReadValue(std::string* value,
- const char* const pSection,
- const char* const pKey) const;
-
- /**
- * @brief Reads a pair of ints value from the profile
- *
- * @param value Result value
- * @param default_value Value to use key wasn't found
- * @param pSection The section to read the value in
- * @param pKey The key whose value needs to be read out
- *
- * @return FALSE if could not read the value out of the profile
- * (then the value is not changed)
- */
- bool ReadUintIntPairValue(std::pair<uint32_t, int32_t>* value,
- const std::pair<uint32_t, uint32_t>& default_value,
- const char* const pSection,
- const char* const pKey) const;
-
- /**
- * @brief Reads an uint16/32/64_t value from the profile
- *
- * @param value Result value
- * @param default_value Value to use key wasn't found
- * @param pSection The section to read the value in
- * @param pKey The key whose value needs to be read out
- *
- * @return FALSE if could not read the value out of the profile
- * (then the value is changed to default)
- */
- bool ReadUIntValue(uint16_t* value,
- uint16_t default_value,
- const char* const pSection,
- const char* const pKey) const;
+ const std::string& iap_hub_protocol_mask() const OVERRIDE;
- bool ReadUIntValue(uint32_t* value,
- uint32_t default_value,
- const char* const pSection,
- const char* const pKey) const;
+ const std::string& iap_pool_protocol_mask() const OVERRIDE;
- bool ReadUIntValue(uint64_t* value,
- uint64_t default_value,
+ const std::string& iap_system_config() const OVERRIDE;
+
+ const std::string& iap2_system_config() const OVERRIDE;
+
+ uint32_t iap_hub_connection_wait_timeout() const OVERRIDE;
+ // TransportManageSettings interface end
+
+ /**
+ * @brief Returns supported diagnostic modes
+ */
+ const std::vector<uint32_t>& supported_diag_modes() const OVERRIDE;
+
+ /**
+ * @brief Returns system files folder path
+ */
+ const std::string& system_files_path() const OVERRIDE;
+
+ /**
+ * @brief Returns value of timeout after which sent
+ * tts global properties for VCA
+ */
+ uint16_t tts_global_properties_timeout() const OVERRIDE;
+
+#ifdef ENABLE_SECURITY
+ /**
+ * @brief Returns name of Security Manager protocol
+ */
+ const std::string& security_manager_protocol_name() const;
+
+ /**
+ * @brief Returns SSL mode
+ */
+ const std::string& ssl_mode() const;
+
+ /**
+ * @brief Returns key path to pem file
+ */
+ const std::string& key_path() const;
+
+ /**
+ * @brief Returns certificate path to pem file
+ */
+ const std::string& cert_path() const;
+
+ /**
+ * @brief Returns ca certificate path to pem file
+ */
+ const std::string& ca_cert_path() const;
+
+ /**
+ * @brief Returns ciphers
+ */
+ const std::string& ciphers_list() const;
+
+ /**
+ * @brief Returns true if Mobile app certificate is verified
+ */
+ bool verify_peer() const;
+
+ /**
+ * @brief Return hours amount when PTU should be triggered
+ */
+ size_t update_before_hours() const;
+
+#endif // ENABLE_SECURITY
+ /**
+ * @brief Reads a string value from the profile
+ *
+ * @param value Result value
+ * @param default_value Value to use key wasn't found
+ * @param pSection The section to read the value in
+ * @param pKey The key whose value needs to be read out
+ *
+ * @return FALSE if could not read the value out of the profile
+ * (then the value is equal \c default_value)
+ */
+ bool ReadStringValue(std::string* value,
+ const char* default_value,
const char* const pSection,
const char* const pKey) const;
- /**
- * @brief Checks, if path is relative
- * @param path Path
- * @return true, if is relative, otherwise - false
- */
- bool IsRelativePath(const std::string& path);
-
- /**
- * @brief Makes relative path absolute
- * @param path Path
- */
- void MakeAbsolutePath(std::string& path);
-
- /**
- * @brief Converts input string to number
- * @param input Input string
- * @param output Output number
- * @return true, if successfully converted, otherwise - false
- */
- bool StringToNumber(const std::string& input, uint64_t& output) const;
-
-private:
- std::string sdl_version_;
- bool launch_hmi_;
+ /**
+ * @brief Reads an int32_t value from the profile
+ *
+ * @param value Result value
+ * @param default_value Value to use key wasn't found
+ * @param pSection The section to read the value in
+ * @param pKey The key whose value needs to be read out
+ *
+ * @return FALSE if could not read the value out of the profile
+ * (then the value is equal \c default_value)
+ */
+ bool ReadIntValue(int32_t* value,
+ int32_t default_value,
+ const char* const pSection,
+ const char* const pKey) const;
+ /**
+ * @brief Reads an bool value from the profile
+ *
+ * @param value Result value
+ * @param default_value Value to use key wasn't found
+ * @param pSection The section to read the value in
+ * @param pKey The key whose value needs to be read out
+ *
+ * @return FALSE if could not read the value out of the profile
+ * (then the value is equal \c default_value)
+ */
+ bool ReadBoolValue(bool* value,
+ const bool default_value,
+ const char* const pSection,
+ const char* const pKey) const;
+ /**
+ * @brief Reads an container of string values from the profile,
+ * which handle as "Value1, Value2, Value3"
+ *
+ * @param pSection The section to read the value in
+ * @param pKey The key whose value needs to be read out
+ * @param out_result Pointer to bool value for result reading Section
+ * (could be NULL)
+ *
+ * @return container of values or empty continer
+ * if could not read the value out of the profile
+ */
+ std::vector<std::string> ReadStringContainer(const char* const pSection,
+ const char* const pKey,
+ bool* out_result) const;
+ /**
+ * @brief Reads an container of hex int values from the profile,
+ * which handle as "0x01, 0xA0, 0XFF"
+ *
+ * @param pSection The section to read the value in
+ * @param pKey The key whose value needs to be read out
+ * @param out_result Pointer to bool value for result reading Section
+ * (could be NULL)
+ *
+ * @return container of values or empty continer
+ * if could not read the value out of the profile
+ */
+ std::vector<int> ReadIntContainer(const char* const pSection,
+ const char* const pKey,
+ bool* out_result) const;
+
+ /**
+ * @brief Returns delimiter for SDL-generated TTS chunks
+ * @return TTS delimiter
+ */
+ const std::string& tts_delimiter() const OVERRIDE;
+
+ /**
+ * @brief Returns recording file name
+ */
+ const std::string& recording_file_name() const OVERRIDE;
+
+ uint32_t application_list_update_timeout() const OVERRIDE;
+
+ /**
+ * @brief Returns max allowed threads number for handling mobile requests
+ */
+ uint32_t thread_pool_size() const;
+
+ /*
+ * ProtocolHandler section
+ */
+ size_t maximum_payload_size() const OVERRIDE;
+
+ size_t message_frequency_count() const OVERRIDE;
+
+ size_t message_frequency_time() const OVERRIDE;
+
+ bool malformed_message_filtering() const OVERRIDE;
+
+ size_t malformed_frequency_count() const OVERRIDE;
+
+ size_t malformed_frequency_time() const OVERRIDE;
+
+ uint32_t multiframe_waiting_timeout() const OVERRIDE;
+
+ uint32_t heart_beat_timeout() const OVERRIDE;
+
+ uint16_t max_supported_protocol_version() const OVERRIDE;
+
+#ifdef ENABLE_SECURITY
+ const std::vector<int>& force_protected_service() const OVERRIDE;
+
+ const std::vector<int>& force_unprotected_service() const OVERRIDE;
+#endif // ENABLE_SECURITY
+ // ProtocolHandler section end
+
+ uint16_t attempts_to_open_policy_db() const;
+
+ uint16_t open_attempt_timeout_ms() const;
+
+ uint32_t resumption_delay_before_ign() const;
+
+ uint32_t resumption_delay_after_ign() const;
+
+ uint32_t hash_string_size() const;
+
+ bool logs_enabled() const;
+
+ /**
+ * @brief Returns true if resumption ctrl uses db, returns false if
+ * resumption ctrl uses JSON.
+ */
+ bool use_db_for_resumption() const;
+
+ /**
+ * @brief Returns amount of attempts for opening resumption db
+ */
+ uint16_t attempts_to_open_resumption_db() const;
+
+ /**
+ * @brief Returns timeout between attempts
+ */
+ uint16_t open_attempt_timeout_ms_resumption_db() const;
+
+ /*
+ * @brief Updates all related values from ini file
+ */
+ void UpdateValues();
+
+ const uint32_t& list_files_response_size() const OVERRIDE;
+
+ const std::string& recording_file_source() const OVERRIDE;
+
+ const std::pair<uint32_t, int32_t>& read_did_frequency() const OVERRIDE;
+
+ const std::pair<uint32_t, int32_t>& get_vehicle_data_frequency()
+ const OVERRIDE;
+
+ const std::pair<uint32_t, int32_t>& start_stream_retry_amount()
+ const OVERRIDE;
+
+ private:
+ /**
+ * @brief Reads a string value from the profile and interpret it
+ * as \c true on "true" value or as \c false on any other value
+ *
+ * @param value The value to return
+ * @param pSection The section to read the value in
+ * @param pKey The key whose value needs to be read out
+ *
+ * @return FALSE if could not read the value out of the profile
+ * (then the value is not changed)
+ */
+ bool ReadValue(std::string* value,
+ const char* const pSection,
+ const char* const pKey) const;
+
+ /**
+ * @brief Reads a boolean value from the profile
+ *
+ * @param value The value to return
+ * @param pSection The section to read the value in
+ * @param pKey The key whose value needs to be read out
+ *
+ * @return FALSE if could not read the value out of the profile
+ * (then the value is not changed)
+ */
+ bool ReadValue(bool* value,
+ const char* const pSection,
+ const char* const pKey) const;
+
+ /**
+ * @brief Reads a pair of ints value from the profile
+ *
+ * @param value Result value
+ * @param default_value Value to use key wasn't found
+ * @param pSection The section to read the value in
+ * @param pKey The key whose value needs to be read out
+ *
+ * @return FALSE if could not read the value out of the profile
+ * (then the value is not changed)
+ */
+ bool ReadUintIntPairValue(std::pair<uint32_t, int32_t>* value,
+ const std::pair<uint32_t, uint32_t>& default_value,
+ const char* const pSection,
+ const char* const pKey) const;
+
+ /**
+ * @brief Reads an uint16/32/64_t value from the profile
+ *
+ * @param value Result value
+ * @param default_value Value to use key wasn't found
+ * @param pSection The section to read the value in
+ * @param pKey The key whose value needs to be read out
+ *
+ * @return FALSE if could not read the value out of the profile
+ * (then the value is changed to default)
+ */
+ bool ReadUIntValue(uint16_t* value,
+ uint16_t default_value,
+ const char* const pSection,
+ const char* const pKey) const;
+
+ bool ReadUIntValue(uint32_t* value,
+ uint32_t default_value,
+ const char* const pSection,
+ const char* const pKey) const;
+
+ bool ReadUIntValue(uint64_t* value,
+ uint64_t default_value,
+ const char* const pSection,
+ const char* const pKey) const;
+
+ /**
+ * @brief Checks, if path is relative
+ * @param path Path
+ * @return true, if is relative, otherwise - false
+ */
+ bool IsRelativePath(const std::string& path);
+
+ /**
+ * @brief Makes relative path absolute
+ * @param path Path
+ */
+ void MakeAbsolutePath(std::string& path);
+
+ /**
+ * @brief Converts input string to number
+ * @param input Input string
+ * @param output Output number
+ * @return true, if successfully converted, otherwise - false
+ */
+ bool StringToNumber(const std::string& input, uint64_t& output) const;
+
+ private:
+ std::string sdl_version_;
+ bool launch_hmi_;
#ifdef WEB_HMI
- std::string link_to_web_hmi_;
-#endif // WEB_HMI
- std::string app_config_folder_;
- std::string app_storage_folder_;
- std::string app_resourse_folder_;
- bool enable_protocol_4_;
- std::string app_icons_folder_;
- uint32_t app_icons_folder_max_size_;
- uint32_t app_icons_amount_to_remove_;
- std::string config_file_name_;
- std::string server_address_;
- uint16_t server_port_;
- uint16_t video_streaming_port_;
- uint16_t audio_streaming_port_;
- uint32_t stop_streaming_timeout_;
- uint16_t time_testing_port_;
- std::string hmi_capabilities_file_name_;
- std::vector<std::string> help_prompt_;
- std::vector<std::string> time_out_promt_;
- std::vector<std::string> vr_commands_;
- uint64_t min_tread_stack_size_;
- bool is_mixing_audio_supported_;
- bool is_redecoding_enabled_;
- uint32_t max_cmd_id_;
- uint32_t default_timeout_;
- uint32_t app_resuming_timeout_;
- uint32_t app_resumption_save_persistent_data_timeout_;
- std::string vr_help_title_;
- uint32_t app_dir_quota_;
- std::string video_consumer_type_;
- std::string audio_consumer_type_;
- std::string named_video_pipe_path_;
- std::string named_audio_pipe_path_;
- uint32_t app_hmi_level_none_time_scale_max_requests_;
- uint32_t app_hmi_level_none_requests_time_scale_;
- std::string video_stream_file_;
- std::string audio_stream_file_;
- uint32_t app_time_scale_max_requests_;
- uint32_t app_requests_time_scale_;
- uint32_t pending_requests_amount_;
- uint32_t put_file_in_none_;
- uint32_t delete_file_in_none_;
- uint32_t list_files_in_none_;
- std::string app_info_storage_;
- uint32_t heart_beat_timeout_;
- std::string preloaded_pt_file_;
- std::string policy_snapshot_file_name_;
- bool enable_policy_;
- uint32_t transport_manager_disconnect_timeout_;
- bool use_last_state_;
- std::vector<uint32_t> supported_diag_modes_;
- std::string system_files_path_;
- uint16_t transport_manager_tcp_adapter_port_;
- std::string tts_delimiter_;
- std::uint32_t audio_data_stopped_timeout_;
- std::uint32_t video_data_stopped_timeout_;
- std::string mme_db_name_;
- std::string event_mq_name_;
- std::string ack_mq_name_;
- std::string recording_file_source_;
- std::string recording_file_name_;
- uint32_t application_list_update_timeout_;
- uint32_t max_thread_pool_size_;
- uint32_t default_hub_protocol_index_;
- /*
- * first value is count of request
- * second is time scale
- */
- std::pair<uint32_t, int32_t> read_did_frequency_;
-
- /*
- * first value is count of request
- * second is time scale
- */
- std::pair<uint32_t, int32_t> get_vehicle_data_frequency_;
-
- /**
- * first value is count of retries for start stream
- * second for timer
- */
- std::pair<uint32_t, int32_t> start_stream_retry_amount_;
-
- std::string iap_legacy_protocol_mask_;
- std::string iap_hub_protocol_mask_;
- std::string iap_pool_protocol_mask_;
- std::string iap_system_config_;
- std::string iap2_system_config_;
- int iap2_hub_connect_attempts_;
- int iap_hub_connection_wait_timeout_;
- uint16_t tts_global_properties_timeout_;
- uint16_t attempts_to_open_policy_db_;
- uint16_t open_attempt_timeout_ms_;
- uint32_t resumption_delay_before_ign_;
- uint32_t resumption_delay_after_ign_;
- uint32_t hash_string_size_;
-
- FRIEND_BASE_SINGLETON_CLASS(Profile);
- DISALLOW_COPY_AND_ASSIGN(Profile);
+ std::string link_to_web_hmi_;
+#endif // WEB_HMI
+ std::string app_config_folder_;
+ std::string app_storage_folder_;
+ std::string app_resource_folder_;
+ bool enable_protocol_4_;
+ std::string app_icons_folder_;
+ uint32_t app_icons_folder_max_size_;
+ uint32_t app_icons_amount_to_remove_;
+ std::string config_file_name_;
+ std::string server_address_;
+ uint16_t server_port_;
+ uint16_t video_streaming_port_;
+ uint16_t audio_streaming_port_;
+ uint32_t stop_streaming_timeout_;
+ uint16_t time_testing_port_;
+ std::string hmi_capabilities_file_name_;
+ std::vector<std::string> help_prompt_;
+ std::vector<std::string> time_out_promt_;
+ std::vector<std::string> vr_commands_;
+ uint64_t min_tread_stack_size_;
+ bool is_mixing_audio_supported_;
+ bool is_redecoding_enabled_;
+ uint32_t max_cmd_id_;
+ uint32_t default_timeout_;
+ uint32_t app_resuming_timeout_;
+ uint32_t app_resumption_save_persistent_data_timeout_;
+ std::string vr_help_title_;
+ uint32_t app_dir_quota_;
+ std::string video_consumer_type_;
+ std::string audio_consumer_type_;
+ std::string named_video_pipe_path_;
+ std::string named_audio_pipe_path_;
+ uint32_t app_hmi_level_none_time_scale_max_requests_;
+ uint32_t app_hmi_level_none_requests_time_scale_;
+ std::string video_stream_file_;
+ std::string audio_stream_file_;
+ uint32_t app_time_scale_max_requests_;
+ uint32_t app_requests_time_scale_;
+ uint32_t pending_requests_amount_;
+ uint32_t put_file_in_none_;
+ uint32_t delete_file_in_none_;
+ uint32_t list_files_in_none_;
+ uint32_t list_files_response_size_;
+ std::string app_info_storage_;
+ uint32_t heart_beat_timeout_;
+ uint16_t max_supported_protocol_version_;
+ std::string preloaded_pt_file_;
+ std::string policy_snapshot_file_name_;
+ bool enable_policy_;
+ uint32_t transport_manager_disconnect_timeout_;
+ bool use_last_state_;
+ std::vector<uint32_t> supported_diag_modes_;
+ std::string system_files_path_;
+ uint16_t transport_manager_tcp_adapter_port_;
+ std::string tts_delimiter_;
+ std::uint32_t audio_data_stopped_timeout_;
+ std::uint32_t video_data_stopped_timeout_;
+ std::string mme_db_name_;
+ std::string event_mq_name_;
+ std::string ack_mq_name_;
+ std::string recording_file_source_;
+ std::string recording_file_name_;
+ uint32_t application_list_update_timeout_;
+ uint32_t max_thread_pool_size_;
+ uint32_t default_hub_protocol_index_;
+#ifdef ENABLE_SECURITY
+ std::string cert_path_;
+ std::string ca_cert_path_;
+ std::string ssl_mode_;
+ std::string key_path_;
+ std::string ciphers_list_;
+ bool verify_peer_;
+ uint32_t update_before_hours_;
+ std::string security_manager_protocol_name_;
+ std::vector<int> force_protected_service_;
+ std::vector<int> force_unprotected_service_;
+#endif
+
+ /*
+ * first value is count of request
+ * second is time scale
+ */
+ std::pair<uint32_t, int32_t> read_did_frequency_;
+
+ /*
+ * first value is count of request
+ * second is time scale
+ */
+ std::pair<uint32_t, int32_t> get_vehicle_data_frequency_;
+
+ /**
+ * first value is count of retries for start stream
+ * second for timer
+ */
+ std::pair<uint32_t, int32_t> start_stream_retry_amount_;
+
+ std::string iap_legacy_protocol_mask_;
+ std::string iap_hub_protocol_mask_;
+ std::string iap_pool_protocol_mask_;
+ std::string iap_system_config_;
+ std::string iap2_system_config_;
+ int iap2_hub_connect_attempts_;
+ int iap_hub_connection_wait_timeout_;
+ uint16_t tts_global_properties_timeout_;
+ uint16_t attempts_to_open_policy_db_;
+ uint16_t open_attempt_timeout_ms_;
+ uint32_t resumption_delay_before_ign_;
+ uint32_t resumption_delay_after_ign_;
+ uint32_t hash_string_size_;
+ bool logs_enabled_;
+ bool use_db_for_resumption_;
+ uint16_t attempts_to_open_resumption_db_;
+ uint16_t open_attempt_timeout_ms_resumption_db_;
+
+ DISALLOW_COPY_AND_ASSIGN(Profile);
};
} // namespace profile
diff --git a/src/components/config_profile/src/ini_file.cc b/src/components/config_profile/src/ini_file.cc
index 236dd1ae2b..d6d72060e8 100644
--- a/src/components/config_profile/src/ini_file.cc
+++ b/src/components/config_profile/src/ini_file.cc
@@ -42,19 +42,19 @@
#ifndef _WIN32
#include <unistd.h>
#else
-#define PATH_MAX _MAX_PATH
+#define PATH_MAX _MAX_PATH
#endif
#ifdef __linux__
-#define USE_MKSTEMP 1
+#define USE_MKSTEMP 1
#endif
#include <string>
namespace profile {
-char* ini_write_inst(const char *fname, uint8_t flag) {
- FILE *fp = 0;
+char* ini_write_inst(const char* fname, uint8_t flag) {
+ FILE* fp = 0;
if (NULL == fname)
return NULL;
@@ -89,15 +89,17 @@ char* ini_write_inst(const char *fname, uint8_t flag) {
return const_cast<char*>(fname);
}
-char* ini_read_value(const char *fname,
- const char *chapter, const char *item, char *value) {
- FILE *fp = 0;
- bool chapter_found = false;
- char line[INI_LINE_LEN] = "";
- char val[INI_LINE_LEN] = "";
- char tag[INI_LINE_LEN] = "";
-
- Ini_search_id result;
+char* ini_read_value(const char* fname,
+ const char* chapter,
+ const char* item,
+ char* value) {
+ FILE* fp = 0;
+ bool chapter_found = false;
+ char line[INI_LINE_LEN] = "";
+ char val[INI_LINE_LEN] = "";
+ char tag[INI_LINE_LEN] = "";
+
+ Ini_search_id result;
*line = '\0';
*val = '\0';
*tag = '\0';
@@ -146,19 +148,21 @@ char* ini_read_value(const char *fname,
return NULL;
}
-char ini_write_value(const char *fname,
- const char *chapter, const char *item,
- const char *value, uint8_t flag) {
- FILE *rd_fp, *wr_fp = 0;
- uint16_t i, cr_count;
- int32_t wr_result;
- bool chapter_found = false;
- bool value_written = false;
- char line[INI_LINE_LEN] = "";
- char val[INI_LINE_LEN] = "";
- char tag[INI_LINE_LEN] = "";
- char temp_fname[PATH_MAX] = "";
- Ini_search_id result;
+char ini_write_value(const char* fname,
+ const char* chapter,
+ const char* item,
+ const char* value,
+ uint8_t flag) {
+ FILE* rd_fp, * wr_fp = 0;
+ uint16_t i, cr_count;
+ int32_t wr_result;
+ bool chapter_found = false;
+ bool value_written = false;
+ char line[INI_LINE_LEN] = "";
+ char val[INI_LINE_LEN] = "";
+ char tag[INI_LINE_LEN] = "";
+ char temp_fname[PATH_MAX] = "";
+ Ini_search_id result;
*line = '\0';
*val = '\0';
*tag = '\0';
@@ -177,12 +181,10 @@ char ini_write_value(const char *fname,
#if USE_MKSTEMP
{
- char *temp_str;
+ const char* temp_str = "./";
int32_t fd = -1;
- temp_str = static_cast<char*>(getenv("TMPDIR"));
if (temp_str) {
- snprintf(temp_fname, PATH_MAX,
- "%s/ini.XXXXXX", temp_str);
+ snprintf(temp_fname, PATH_MAX, "%s/ini.XXXXXX", temp_str);
fd = mkstemp(temp_fname);
if (-1 == fd) {
@@ -201,16 +203,17 @@ char ini_write_value(const char *fname,
#else // #if USE_MKSTEMP
tmpnam(temp_fname);
if (0 == (wr_fp = fopen(temp_fname, "w"))) {
- fclose(rd_fp);
- return FALSE;
+ fclose(rd_fp);
+ return FALSE;
}
-#endif // #else #if USE_MKSTEMP
+#endif // #else #if USE_MKSTEMP
snprintf(tag, INI_LINE_LEN, "%s", chapter);
- for (uint32_t i = 0; i < strlen (tag); i++)
+ for (uint32_t i = 0; i < strlen(tag); i++)
tag[i] = toupper(tag[i]);
- wr_result = 1; cr_count = 0;
+ wr_result = 1;
+ cr_count = 0;
while ((NULL != fgets(line, INI_LINE_LEN, rd_fp)) && (0 < wr_result)) {
// Now start the line parsing
result = ini_parse_line(line, tag, val);
@@ -221,7 +224,7 @@ char ini_write_value(const char *fname,
chapter_found = true;
// coding style
snprintf(tag, INI_LINE_LEN, "%s", item);
- for (uint32_t i = 0; i < strlen (tag); i++)
+ for (uint32_t i = 0; i < strlen(tag); i++)
tag[i] = toupper(tag[i]);
}
} else {
@@ -242,7 +245,7 @@ char ini_write_value(const char *fname,
continue;
}
}
- } /* if (!value_written) */
+ } /* if (!value_written) */
if (0 == strcmp(val, "\n")) {
cr_count++;
@@ -263,7 +266,6 @@ char ini_write_value(const char *fname,
}
fprintf(wr_fp, "\n");
-
fclose(wr_fp);
fclose(rd_fp);
@@ -276,10 +278,10 @@ char ini_write_value(const char *fname,
return (value_written);
}
-Ini_search_id ini_parse_line(const char *line, const char *tag, char *value) {
- const char *line_ptr;
- char *temp_ptr;
- char temp_str[INI_LINE_LEN] = "";
+Ini_search_id ini_parse_line(const char* line, const char* tag, char* value) {
+ const char* line_ptr;
+ char* temp_ptr;
+ char temp_str[INI_LINE_LEN] = "";
*temp_str = '\0';
snprintf(value, INI_LINE_LEN, "%s", line);
@@ -287,13 +289,12 @@ Ini_search_id ini_parse_line(const char *line, const char *tag, char *value) {
/* cut leading spaces */
line_ptr = line;
for (uint32_t i = 0; i < strlen(line); i++) {
- if ((line[i] == ' ') ||
- (line[i] == 9) || // TAB
- (line[i] == 10) || // LF
- (line[i] == 13)) { // CR
+ if ((line[i] == ' ') || (line[i] == 9) || // TAB
+ (line[i] == 10) || // LF
+ (line[i] == 13)) { // CR
line_ptr++;
} else {
- break;
+ break;
}
}
if ('\0' == *line_ptr) {
@@ -301,7 +302,7 @@ Ini_search_id ini_parse_line(const char *line, const char *tag, char *value) {
return INI_NOTHING;
}
- if ((*line_ptr == ';') || (*line_ptr == '*')) /* remark */
+ if ((*line_ptr == ';') || (*line_ptr == '*')) /* remark */
return INI_REMARK;
if (*line_ptr == '[' && strrchr(line_ptr, ']') != NULL) {
@@ -310,13 +311,12 @@ Ini_search_id ini_parse_line(const char *line, const char *tag, char *value) {
/* cut leading stuff */
uint16_t len = strlen(line_ptr);
for (int32_t i = 0; i < len; i++) {
- if ((*line_ptr == ' ') ||
- (*line_ptr == 9) || // TAB
- (*line_ptr == 10) || // LF
- (*line_ptr == 13)) { // CR
+ if ((*line_ptr == ' ') || (*line_ptr == 9) || // TAB
+ (*line_ptr == 10) || // LF
+ (*line_ptr == 13)) { // CR
line_ptr++;
} else {
- break;
+ break;
}
}
if (*line_ptr == '\0')
@@ -332,13 +332,12 @@ Ini_search_id ini_parse_line(const char *line, const char *tag, char *value) {
/* cut trailing stuff */
for (int32_t i = strlen(temp_str) - 1; i > 0; i--) {
- if ((temp_str[i] == ' ') ||
- (temp_str[i] == 9) || // TAB
- (temp_str[i] == 10) || // LF
- (temp_str[i] == 13)) { // CR
+ if ((temp_str[i] == ' ') || (temp_str[i] == 9) || // TAB
+ (temp_str[i] == 10) || // LF
+ (temp_str[i] == 13)) { // CR
temp_str[i] = '\0';
} else {
- break;
+ break;
}
}
@@ -356,11 +355,10 @@ Ini_search_id ini_parse_line(const char *line, const char *tag, char *value) {
strncpy(temp_str, line_ptr, (strchr(line_ptr, '=') - line_ptr));
/* cut trailing stuff */
for (int32_t i = strlen(temp_str) - 1; i > 0; i--) {
- if ((temp_str[i] == '=') ||
- (temp_str[i] == ' ') ||
- (temp_str[i] == 9) || // TAB
- (temp_str[i] == 10) || // LF
- (temp_str[i] == 13)) { // CR
+ if ((temp_str[i] == '=') || (temp_str[i] == ' ') ||
+ (temp_str[i] == 9) || // TAB
+ (temp_str[i] == 10) || // LF
+ (temp_str[i] == 13)) { // CR
temp_str[i] = '\0';
} else {
break;
@@ -369,17 +367,16 @@ Ini_search_id ini_parse_line(const char *line, const char *tag, char *value) {
snprintf(value, INI_LINE_LEN, "%s", temp_str);
- for (uint32_t i = 0; i < strlen (temp_str); i++)
+ for (uint32_t i = 0; i < strlen(temp_str); i++)
temp_str[i] = toupper(temp_str[i]);
if (strcmp(temp_str, tag) == 0) {
line_ptr = strchr(line_ptr, '=') + 1;
uint16_t len = strlen(line_ptr);
/* cut trailing stuff */
for (uint32_t i = 0; i < len; i++) {
- if ((*line_ptr == ' ') ||
- (*line_ptr == 9) || // TAB
- (*line_ptr == 10) || // LF
- (*line_ptr == 13)) { // CR
+ if ((*line_ptr == ' ') || (*line_ptr == 9) || // TAB
+ (*line_ptr == 10) || // LF
+ (*line_ptr == 13)) { // CR
line_ptr++;
} else {
break;
@@ -391,11 +388,10 @@ Ini_search_id ini_parse_line(const char *line, const char *tag, char *value) {
if (value[0] != '\0') {
/* cut trailing stuff */
for (int32_t i = strlen(value) - 1; i > 0; i--) {
- if ((value[i] == ' ') ||
- (value[i] == ';') ||
- (value[i] == 9) || // TAB
- (value[i] == 10) || // LF
- (value[i] == 13)) { // CR
+ if ((value[i] == ' ') || (value[i] == ';') ||
+ (value[i] == 9) || // TAB
+ (value[i] == 10) || // LF
+ (value[i] == 13)) { // CR
value[i] = '\0';
} else {
break;
diff --git a/src/components/config_profile/src/profile.cc b/src/components/config_profile/src/profile.cc
index 700c52fff8..4eacbe88ec 100644
--- a/src/components/config_profile/src/profile.cc
+++ b/src/components/config_profile/src/profile.cc
@@ -43,22 +43,34 @@
#include "utils/threads/thread.h"
#include "utils/file_system.h"
+#ifdef ENABLE_SECURITY
+#include <openssl/ssl.h>
+#endif // ENABLE_SECURITY
+
namespace {
-#define LOG_UPDATED_VALUE(value, key, section) {\
- LOG4CXX_INFO(logger_, "Setting value '" << value\
- << "' for key '" << key\
- << "' in section '" << section << "'.");\
-}
+#define LOG_UPDATED_VALUE(value, key, section) \
+ { \
+ LOG4CXX_INFO(logger_, \
+ "Setting value '" << value << "' for key '" << key \
+ << "' in section '" << section << "'."); \
+ }
-#define LOG_UPDATED_BOOL_VALUE(value, key, section) {\
- LOG4CXX_INFO(logger_, "Setting value '" << std::boolalpha << value\
- << "' for key '" << key\
- << "' in section '" << section << "'.");\
-}
+#define LOG_UPDATED_BOOL_VALUE(value, key, section) \
+ { \
+ LOG4CXX_INFO(logger_, \
+ "Setting value '" << std::boolalpha << value << "' for key '" \
+ << key << "' in section '" << section \
+ << "'."); \
+ }
const char* kDefaultConfigFileName = "smartDeviceLink.ini";
const char* kMainSection = "MAIN";
+#ifdef ENABLE_SECURITY
+const char* kSecuritySection = "Security Manager";
+const char* kForceProtectedService = "ForceProtectedService";
+const char* kForceUnprotectedService = "ForceUnprotectedService";
+#endif
const char* kPolicySection = "Policy";
const char* kHmiSection = "HMI";
const char* kAppInfoSection = "AppInfo";
@@ -83,15 +95,18 @@ const char* kServerAddressKey = "ServerAddress";
const char* kAppInfoStorageKey = "AppInfoStorage";
const char* kAppStorageFolderKey = "AppStorageFolder";
const char* kAppResourseFolderKey = "AppResourceFolder";
+const char* kLogsEnabledKey = "LogsEnabled";
const char* kAppConfigFolderKey = "AppConfigFolder";
const char* kEnableProtocol4Key = "EnableProtocol4";
const char* kAppIconsFolderKey = "AppIconsFolder";
const char* kAppIconsFolderMaxSizeKey = "AppIconsFolderMaxSize";
const char* kAppIconsAmountToRemoveKey = "AppIconsAmountToRemove";
const char* kLaunchHMIKey = "LaunchHMI";
+
+const char* kDefaultSDLVersion = "";
#ifdef WEB_HMI
const char* kLinkToWebHMI = "LinkToWebHMI";
-#endif // WEB_HMI
+#endif // WEB_HMI
const char* kStartStreamRetry = "StartStreamRetry";
const char* kEnableRedecodingKey = "EnableRedecoding";
const char* kVideoStreamConsumerKey = "VideoStreamConsumer";
@@ -100,6 +115,18 @@ const char* kNamedVideoPipePathKey = "NamedVideoPipePath";
const char* kNamedAudioPipePathKey = "NamedAudioPipePath";
const char* kVideoStreamFileKey = "VideoStreamFile";
const char* kAudioStreamFileKey = "AudioStreamFile";
+
+#ifdef ENABLE_SECURITY
+const char* kSecurityProtocolKey = "Protocol";
+const char* kSecurityCertificatePathKey = "CertificatePath";
+const char* kSecurityCACertificatePathKey = "CACertificatePath";
+const char* kSecuritySSLModeKey = "SSLMode";
+const char* kSecurityKeyPathKey = "KeyPath";
+const char* kSecurityCipherListKey = "CipherList";
+const char* kSecurityVerifyPeerKey = "VerifyPeer";
+const char* kBeforeUpdateHours = "UpdateBeforeHours";
+#endif
+
const char* kAudioDataStoppedTimeoutKey = "AudioDataStoppedTimeout";
const char* kVideoDataStoppedTimeoutKey = "VideoDataStoppedTimeout";
const char* kMixingAudioSupportedKey = "MixingAudioSupported";
@@ -109,6 +136,7 @@ const char* kHelpTitleKey = "HelpTitle";
const char* kHelpCommandKey = "HelpCommand";
const char* kSystemFilesPathKey = "SystemFilesPath";
const char* kHeartBeatTimeoutKey = "HeartBeatTimeout";
+const char* kMaxSupportedProtocolVersionKey = "MaxSupportedProtocolVersion";
const char* kUseLastStateKey = "UseLastState";
const char* kTCPAdapterPortKey = "TCPAdapterPort";
const char* kServerPortKey = "ServerPort";
@@ -121,6 +149,7 @@ const char* kMaxCmdIdKey = "MaxCmdID";
const char* kPutFileRequestKey = "PutFileRequest";
const char* kDeleteFileRequestKey = "DeleteFileRequest";
const char* kListFilesRequestKey = "ListFilesRequest";
+const char* kListFilesResponseSizeKey = "ListFilesResponseSize";
const char* kDefaultTimeoutKey = "DefaultTimeout";
const char* kAppResumingTimeoutKey = "ApplicationResumingTimeout";
const char* kAppSavePersistentDataTimeoutKey = "AppSavePersistentDataTimeout";
@@ -140,7 +169,6 @@ const char* kTTSDelimiterKey = "TTSDelimiter";
const char* kRecordingFileNameKey = "RecordingFileName";
const char* kRecordingFileSourceKey = "RecordingFileSource";
const char* kEnablePolicy = "EnablePolicy";
-const char* kMmeDatabaseNameKey = "MMEDatabase";
const char* kEventMQKey = "EventMQ";
const char* kAckMQKey = "AckMQ";
const char* kApplicationListUpdateTimeoutKey = "ApplicationListUpdateTimeout";
@@ -161,12 +189,17 @@ const char* kFrequencyTime = "FrequencyTime";
const char* kMalformedMessageFiltering = "MalformedMessageFiltering";
const char* kMalformedFrequencyCount = "MalformedFrequencyCount";
const char* kMalformedFrequencyTime = "MalformedFrequencyTime";
+const char* kExpectedConsecutiveFramesTimeout =
+ "ExpectedConsecutiveFramesTimeout";
const char* kHashStringSizeKey = "HashStringSize";
+const char* kUseDBForResumptionKey = "UseDBForResumption";
+const char* kAttemptsToOpenResumptionDBKey = "AttemptsToOpenResumptionDB";
+const char* kOpenAttemptTimeoutMsResumptionDBKey =
+ "OpenAttemptTimeoutMsResumptionDB";
#ifdef WEB_HMI
const char* kDefaultLinkToWebHMI = "HMI/index.html";
-#endif // WEB_HMI
-const char* kDefaultSDLVersion = "";
+#endif // WEB_HMI
const char* kDefaultPoliciesSnapshotFileName = "sdl_snapshot.json";
const char* kDefaultHmiCapabilitiesFileName = "hmi_capabilities.json";
const char* kDefaultPreloadedPTFileName = "sdl_preloaded_pt.json";
@@ -176,7 +209,6 @@ const char* kDefaultSystemFilesPath = "/tmp/fs/mp/images/ivsu_cache";
const char* kDefaultTtsDelimiter = ",";
const uint32_t kDefaultAudioDataStoppedTimeout = 1000;
const uint32_t kDefaultVideoDataStoppedTimeout = 1000;
-const char* kDefaultMmeDatabaseName = "/dev/qdb/mediaservice_db";
const char* kDefaultEventMQ = "/dev/mqueue/ToSDLCoreUSBAdapter";
const char* kDefaultAckMQ = "/dev/mqueue/FromSDLCoreUSBAdapter";
const char* kDefaultRecordingFileSourceName = "audio.8bit.wav";
@@ -188,8 +220,16 @@ const char* kDefaultPoolProtocolMask = "com.smartdevicelink.prot";
const char* kDefaultIAPSystemConfig = "/fs/mp/etc/mm/ipod.cfg";
const char* kDefaultIAP2SystemConfig = "/fs/mp/etc/mm/iap2.cfg";
+#ifdef ENABLE_SECURITY
+const char* kDefaultSecurityProtocol = "TLSv1.2";
+const char* kDefaultSSLMode = "CLIENT";
+const bool kDefaultVerifyPeer = false;
+const uint32_t kDefaultBeforeUpdateHours = 24;
+#endif // ENABLE_SECURITY
+
const uint32_t kDefaultHubProtocolIndex = 0;
const uint32_t kDefaultHeartBeatTimeout = 0;
+const uint16_t kDefaultMaxSupportedProtocolVersion = 3;
const uint16_t kDefautTransportManagerTCPPort = 12345;
const uint16_t kDefaultServerPort = 8087;
const uint16_t kDefaultVideoStreamingPort = 5050;
@@ -201,11 +241,12 @@ const uint32_t kDefaultPutFileRequestInNone = 5;
const uint32_t kDefaultDeleteFileRequestInNone = 5;
const uint32_t kDefaultListFilesRequestInNone = 5;
const uint32_t kDefaultTimeout = 10000;
-const uint32_t kDefaultAppResumingTimeout = 3;
-const uint32_t kDefaultAppSavePersistentDataTimeout = 10;
+const uint32_t kDefaultAppResumingTimeout = 3000;
+const uint32_t kDefaultAppSavePersistentDataTimeout = 10000;
const uint32_t kDefaultResumptionDelayBeforeIgn = 30;
const uint32_t kDefaultResumptionDelayAfterIgn = 30;
const uint32_t kDefaultHashStringSize = 32;
+const uint32_t kDefaultListFilesResponseSize = 1000;
const uint32_t kDefaultDirQuota = 104857600;
const uint32_t kDefaultAppTimeScaleMaxRequests = 0;
@@ -215,12 +256,13 @@ const uint32_t kDefaultAppHmiLevelNoneRequestsTimeScale = 10;
const uint32_t kDefaultPendingRequestsAmount = 0;
const uint32_t kDefaultTransportManagerDisconnectTimeout = 0;
const uint32_t kDefaultApplicationListUpdateTimeout = 1;
-const std::pair<uint32_t, uint32_t> kReadDIDFrequency = { 5, 1 };
-const std::pair<uint32_t, uint32_t> kGetVehicleDataFrequency = { 5, 1 };
-const std::pair<uint32_t, uint32_t> kStartStreamRetryAmount = { 3, 1 };
+const std::pair<uint32_t, uint32_t> kReadDIDFrequency = {5, 1};
+const std::pair<uint32_t, uint32_t> kGetVehicleDataFrequency = {5, 1};
+const std::pair<uint32_t, uint32_t> kStartStreamRetryAmount = {3, 1};
const uint32_t kDefaultMaxThreadPoolSize = 2;
const int kDefaultIAP2HubConnectAttempts = 0;
-const int kDefaultIAPHubConnectionWaitTimeout = 10;
+const int kDefaultIAPHubConnectionWaitTimeout = 10000;
+const int kDefaultIAPArmEventTimeout = 500;
const uint16_t kDefaultTTSGlobalPropertiesTimeout = 20;
// TCP MTU - header size = 1500 - 12
const size_t kDefaultMaximumPayloadSize = 1500 - 12;
@@ -229,11 +271,13 @@ const size_t kDefaultFrequencyTime = 1000;
const bool kDefaulMalformedMessageFiltering = true;
const size_t kDefaultMalformedFrequencyCount = 10;
const size_t kDefaultMalformedFrequencyTime = 1000;
+const uint32_t kDefaultExpectedConsecutiveFramesTimeout = 10000;
const uint16_t kDefaultAttemptsToOpenPolicyDB = 5;
-const uint16_t kDefaultOpenAttemptTimeoutMsKey = 500;
-const uint32_t kDefaultAppIconsFolderMaxSize = 1048576;
+const uint16_t kDefaultOpenAttemptTimeoutMs = 500;
+const uint32_t kDefaultAppIconsFolderMaxSize = 104857600;
const uint32_t kDefaultAppIconsAmountToRemove = 1;
-
+const uint16_t kDefaultAttemptsToOpenResumptionDB = 5;
+const uint16_t kDefaultOpenAttemptTimeoutMsResumptionDB = 500;
} // namespace
namespace profile {
@@ -241,82 +285,84 @@ namespace profile {
CREATE_LOGGERPTR_GLOBAL(logger_, "Profile")
Profile::Profile()
- : sdl_version_(kDefaultSDLVersion),
- launch_hmi_(true),
+ : sdl_version_(kDefaultSDLVersion)
+ , launch_hmi_(true)
+ ,
#ifdef WEB_HMI
- link_to_web_hmi_(kDefaultLinkToWebHMI),
-#endif // WEB_HMI
- app_config_folder_(),
- app_storage_folder_(),
- app_resourse_folder_(),
- enable_protocol_4_(false),
- app_icons_folder_(),
- app_icons_folder_max_size_(kDefaultAppIconsFolderMaxSize),
- app_icons_amount_to_remove_(kDefaultAppIconsAmountToRemove),
- config_file_name_(kDefaultConfigFileName),
- server_address_(kDefaultServerAddress),
- server_port_(kDefaultServerPort),
- video_streaming_port_(kDefaultVideoStreamingPort),
- audio_streaming_port_(kDefaultAudioStreamingPort),
- time_testing_port_(kDefaultTimeTestingPort),
- hmi_capabilities_file_name_(kDefaultHmiCapabilitiesFileName),
- help_prompt_(),
- time_out_promt_(),
- min_tread_stack_size_(threads::Thread::kMinStackSize),
- is_mixing_audio_supported_(false),
- is_redecoding_enabled_(false),
- max_cmd_id_(kDefaultMaxCmdId),
- default_timeout_(kDefaultTimeout),
- app_resuming_timeout_(kDefaultAppResumingTimeout),
- app_dir_quota_(kDefaultDirQuota),
- app_hmi_level_none_time_scale_max_requests_(
- kDefaultAppHmiLevelNoneTimeScaleMaxRequests),
- app_hmi_level_none_requests_time_scale_(
- kDefaultAppHmiLevelNoneRequestsTimeScale),
- app_time_scale_max_requests_(kDefaultAppTimeScaleMaxRequests),
- app_requests_time_scale_(kDefaultAppRequestsTimeScale),
- pending_requests_amount_(kDefaultPendingRequestsAmount),
- put_file_in_none_(kDefaultPutFileRequestInNone),
- delete_file_in_none_(kDefaultDeleteFileRequestInNone),
- list_files_in_none_(kDefaultListFilesRequestInNone),
- app_info_storage_(kDefaultAppInfoFileName),
- heart_beat_timeout_(kDefaultHeartBeatTimeout),
- policy_snapshot_file_name_(kDefaultPoliciesSnapshotFileName),
- enable_policy_(false),
- transport_manager_disconnect_timeout_(
- kDefaultTransportManagerDisconnectTimeout),
- use_last_state_(false),
- supported_diag_modes_(),
- system_files_path_(kDefaultSystemFilesPath),
- transport_manager_tcp_adapter_port_(kDefautTransportManagerTCPPort),
- tts_delimiter_(kDefaultTtsDelimiter),
- audio_data_stopped_timeout_(kDefaultAudioDataStoppedTimeout),
- video_data_stopped_timeout_(kDefaultVideoDataStoppedTimeout),
- mme_db_name_(kDefaultMmeDatabaseName),
- event_mq_name_(kDefaultEventMQ),
- ack_mq_name_(kDefaultAckMQ),
- recording_file_source_(kDefaultRecordingFileSourceName),
- recording_file_name_(kDefaultRecordingFileName),
- application_list_update_timeout_(kDefaultApplicationListUpdateTimeout),
- iap_legacy_protocol_mask_(kDefaultLegacyProtocolMask),
- iap_hub_protocol_mask_(kDefaultHubProtocolMask),
- iap_pool_protocol_mask_(kDefaultPoolProtocolMask),
- iap_system_config_(kDefaultIAPSystemConfig),
- iap2_system_config_(kDefaultIAP2SystemConfig),
- iap2_hub_connect_attempts_(kDefaultIAP2HubConnectAttempts),
- iap_hub_connection_wait_timeout_(kDefaultIAPHubConnectionWaitTimeout),
- tts_global_properties_timeout_(kDefaultTTSGlobalPropertiesTimeout),
- attempts_to_open_policy_db_(kDefaultAttemptsToOpenPolicyDB),
- open_attempt_timeout_ms_(kDefaultAttemptsToOpenPolicyDB),
- hash_string_size_(kDefaultHashStringSize) {
- ReadStringValue(&sdl_version_, kDefaultSDLVersion,
- kMainSection, kSDLVersionKey);
-}
-
-
-
-Profile::~Profile() {
-}
+ link_to_web_hmi_(kDefaultLinkToWebHMI)
+ ,
+#endif // WEB_HMI
+ app_config_folder_()
+ , app_storage_folder_()
+ , app_resource_folder_()
+ , enable_protocol_4_(false)
+ , app_icons_folder_()
+ , app_icons_folder_max_size_(kDefaultAppIconsFolderMaxSize)
+ , app_icons_amount_to_remove_(kDefaultAppIconsAmountToRemove)
+ , config_file_name_(kDefaultConfigFileName)
+ , server_address_(kDefaultServerAddress)
+ , server_port_(kDefaultServerPort)
+ , video_streaming_port_(kDefaultVideoStreamingPort)
+ , audio_streaming_port_(kDefaultAudioStreamingPort)
+ , time_testing_port_(kDefaultTimeTestingPort)
+ , hmi_capabilities_file_name_(kDefaultHmiCapabilitiesFileName)
+ , help_prompt_()
+ , time_out_promt_()
+ , min_tread_stack_size_(threads::Thread::kMinStackSize)
+ , is_mixing_audio_supported_(false)
+ , is_redecoding_enabled_(false)
+ , max_cmd_id_(kDefaultMaxCmdId)
+ , default_timeout_(kDefaultTimeout)
+ , app_resuming_timeout_(kDefaultAppResumingTimeout)
+ , app_dir_quota_(kDefaultDirQuota)
+ , app_hmi_level_none_time_scale_max_requests_(
+ kDefaultAppHmiLevelNoneTimeScaleMaxRequests)
+ , app_hmi_level_none_requests_time_scale_(
+ kDefaultAppHmiLevelNoneRequestsTimeScale)
+ , app_time_scale_max_requests_(kDefaultAppTimeScaleMaxRequests)
+ , app_requests_time_scale_(kDefaultAppRequestsTimeScale)
+ , pending_requests_amount_(kDefaultPendingRequestsAmount)
+ , put_file_in_none_(kDefaultPutFileRequestInNone)
+ , delete_file_in_none_(kDefaultDeleteFileRequestInNone)
+ , list_files_in_none_(kDefaultListFilesRequestInNone)
+ , list_files_response_size_(kDefaultListFilesResponseSize)
+ , app_info_storage_(kDefaultAppInfoFileName)
+ , heart_beat_timeout_(kDefaultHeartBeatTimeout)
+ , max_supported_protocol_version_(kDefaultMaxSupportedProtocolVersion)
+ , policy_snapshot_file_name_(kDefaultPoliciesSnapshotFileName)
+ , enable_policy_(false)
+ , transport_manager_disconnect_timeout_(
+ kDefaultTransportManagerDisconnectTimeout)
+ , use_last_state_(false)
+ , supported_diag_modes_()
+ , system_files_path_(kDefaultSystemFilesPath)
+ , transport_manager_tcp_adapter_port_(kDefautTransportManagerTCPPort)
+ , tts_delimiter_(kDefaultTtsDelimiter)
+ , audio_data_stopped_timeout_(kDefaultAudioDataStoppedTimeout)
+ , video_data_stopped_timeout_(kDefaultVideoDataStoppedTimeout)
+ , event_mq_name_(kDefaultEventMQ)
+ , ack_mq_name_(kDefaultAckMQ)
+ , recording_file_source_(kDefaultRecordingFileSourceName)
+ , recording_file_name_(kDefaultRecordingFileName)
+ , application_list_update_timeout_(kDefaultApplicationListUpdateTimeout)
+ , iap_legacy_protocol_mask_(kDefaultLegacyProtocolMask)
+ , iap_hub_protocol_mask_(kDefaultHubProtocolMask)
+ , iap_pool_protocol_mask_(kDefaultPoolProtocolMask)
+ , iap_system_config_(kDefaultIAPSystemConfig)
+ , iap2_system_config_(kDefaultIAP2SystemConfig)
+ , iap2_hub_connect_attempts_(kDefaultIAP2HubConnectAttempts)
+ , iap_hub_connection_wait_timeout_(kDefaultIAPHubConnectionWaitTimeout)
+ , tts_global_properties_timeout_(kDefaultTTSGlobalPropertiesTimeout)
+ , attempts_to_open_policy_db_(kDefaultAttemptsToOpenPolicyDB)
+ , open_attempt_timeout_ms_(kDefaultAttemptsToOpenPolicyDB)
+ , hash_string_size_(kDefaultHashStringSize)
+ , use_db_for_resumption_(false)
+ , attempts_to_open_resumption_db_(kDefaultAttemptsToOpenResumptionDB)
+ , open_attempt_timeout_ms_resumption_db_(
+ kDefaultOpenAttemptTimeoutMsResumptionDB) {
+}
+
+Profile::~Profile() {}
void Profile::config_file_name(const std::string& fileName) {
if (false == fileName.empty()) {
@@ -341,7 +387,7 @@ bool Profile::launch_hmi() const {
std::string Profile::link_to_web_hmi() const {
return link_to_web_hmi_;
}
-#endif // WEB_HMI
+#endif // WEB_HMI
const std::string& Profile::app_config_folder() const {
return app_config_folder_;
@@ -351,23 +397,23 @@ const std::string& Profile::app_storage_folder() const {
return app_storage_folder_;
}
-const std::string& Profile::app_resourse_folder() const {
- return app_resourse_folder_;
+const std::string& Profile::app_resource_folder() const {
+ return app_resource_folder_;
}
bool Profile::enable_protocol_4() const {
return enable_protocol_4_;
}
-const std::string&Profile::app_icons_folder() const {
+const std::string& Profile::app_icons_folder() const {
return app_icons_folder_;
}
-const uint32_t&Profile::app_icons_folder_max_size() const {
+const uint32_t& Profile::app_icons_folder_max_size() const {
return app_icons_folder_max_size_;
}
-const uint32_t&Profile::app_icons_amount_to_remove() const {
+const uint32_t& Profile::app_icons_amount_to_remove() const {
return app_icons_amount_to_remove_;
}
@@ -415,11 +461,11 @@ const uint16_t& Profile::server_port() const {
return server_port_;
}
-const uint16_t& Profile::video_streaming_port() const {
+const uint16_t Profile::video_streaming_port() const {
return video_streaming_port_;
}
-const uint16_t& Profile::audio_streaming_port() const {
+const uint16_t Profile::audio_streaming_port() const {
return audio_streaming_port_;
}
@@ -511,14 +557,22 @@ const uint32_t& Profile::list_files_in_none() const {
return list_files_in_none_;
}
+const uint32_t& Profile::list_files_response_size() const {
+ return list_files_response_size_;
+}
+
const std::string& Profile::app_info_storage() const {
return app_info_storage_;
}
-int32_t Profile::heart_beat_timeout() const {
+uint32_t Profile::heart_beat_timeout() const {
return heart_beat_timeout_;
}
+uint16_t Profile::max_supported_protocol_version() const {
+ return max_supported_protocol_version_;
+}
+
const std::string& Profile::preloaded_pt_file() const {
return preloaded_pt_file_;
}
@@ -558,15 +612,10 @@ const std::string& Profile::tts_delimiter() const {
const std::string& Profile::recording_file_source() const {
return recording_file_source_;
}
-
-const std::string&Profile::recording_file_name() const {
+const std::string& Profile::recording_file_name() const {
return recording_file_name_;
}
-const std::string& Profile::mme_db_name() const {
- return mme_db_name_;
-}
-
const std::string& Profile::event_mq_name() const {
return event_mq_name_;
}
@@ -583,7 +632,8 @@ const std::pair<uint32_t, int32_t>& Profile::read_did_frequency() const {
return read_did_frequency_;
}
-const std::pair<uint32_t, int32_t>& Profile::get_vehicle_data_frequency() const {
+const std::pair<uint32_t, int32_t>& Profile::get_vehicle_data_frequency()
+ const {
return get_vehicle_data_frequency_;
}
@@ -619,55 +669,75 @@ const std::string& Profile::iap2_system_config() const {
return iap2_system_config_;
}
-int Profile::iap2_hub_connect_attempts() const {
+uint32_t Profile::iap2_hub_connect_attempts() const {
return iap2_hub_connect_attempts_;
}
-int Profile::iap_hub_connection_wait_timeout() const {
+uint32_t Profile::iap_hub_connection_wait_timeout() const {
return iap_hub_connection_wait_timeout_;
}
size_t Profile::maximum_payload_size() const {
size_t maximum_payload_size = 0;
- ReadUIntValue(&maximum_payload_size, kDefaultMaximumPayloadSize,
- kProtocolHandlerSection, kMaximumPayloadSizeKey);
+ ReadUIntValue(&maximum_payload_size,
+ kDefaultMaximumPayloadSize,
+ kProtocolHandlerSection,
+ kMaximumPayloadSizeKey);
return maximum_payload_size;
}
size_t Profile::message_frequency_count() const {
size_t message_frequency_count = 0;
- ReadUIntValue(&message_frequency_count, kDefaultFrequencyCount,
- kProtocolHandlerSection, kFrequencyCount);
+ ReadUIntValue(&message_frequency_count,
+ kDefaultFrequencyCount,
+ kProtocolHandlerSection,
+ kFrequencyCount);
return message_frequency_count;
}
size_t Profile::message_frequency_time() const {
size_t message_frequency_time = 0;
- ReadUIntValue(&message_frequency_time, kDefaultFrequencyTime,
- kProtocolHandlerSection, kFrequencyTime);
+ ReadUIntValue(&message_frequency_time,
+ kDefaultFrequencyTime,
+ kProtocolHandlerSection,
+ kFrequencyTime);
return message_frequency_time;
}
bool Profile::malformed_message_filtering() const {
bool malformed_message_filtering = 0;
- ReadBoolValue(&malformed_message_filtering, kDefaulMalformedMessageFiltering,
- kProtocolHandlerSection, kMalformedMessageFiltering);
+ ReadBoolValue(&malformed_message_filtering,
+ kDefaulMalformedMessageFiltering,
+ kProtocolHandlerSection,
+ kMalformedMessageFiltering);
return malformed_message_filtering;
}
size_t Profile::malformed_frequency_count() const {
size_t malformed_frequency_count = 0;
- ReadUIntValue(&malformed_frequency_count, kDefaultMalformedFrequencyCount,
- kProtocolHandlerSection, kMalformedFrequencyCount);
+ ReadUIntValue(&malformed_frequency_count,
+ kDefaultMalformedFrequencyCount,
+ kProtocolHandlerSection,
+ kMalformedFrequencyCount);
return malformed_frequency_count;
}
size_t Profile::malformed_frequency_time() const {
size_t malformed_frequency_time = 0;
- ReadUIntValue(&malformed_frequency_time, kDefaultMalformedFrequencyTime,
- kProtocolHandlerSection, kMalformedFrequencyTime);
+ ReadUIntValue(&malformed_frequency_time,
+ kDefaultMalformedFrequencyTime,
+ kProtocolHandlerSection,
+ kMalformedFrequencyTime);
return malformed_frequency_time;
}
+uint32_t Profile::multiframe_waiting_timeout() const {
+ uint32_t multiframe_waiting_timeout = 0;
+ ReadUIntValue(&multiframe_waiting_timeout,
+ kDefaultExpectedConsecutiveFramesTimeout,
+ kProtocolHandlerSection,
+ kExpectedConsecutiveFramesTimeout);
+ return multiframe_waiting_timeout;
+}
uint16_t Profile::attempts_to_open_policy_db() const {
return attempts_to_open_policy_db_;
@@ -693,12 +763,71 @@ uint16_t Profile::tts_global_properties_timeout() const {
return tts_global_properties_timeout_;
}
+#ifdef ENABLE_SECURITY
+
+const std::string& Profile::cert_path() const {
+ return cert_path_;
+}
+
+const std::string& Profile::ca_cert_path() const {
+ return ca_cert_path_;
+}
+
+const std::string& Profile::ssl_mode() const {
+ return ssl_mode_;
+}
+
+const std::string& Profile::key_path() const {
+ return key_path_;
+}
+
+const std::string& Profile::ciphers_list() const {
+ return ciphers_list_;
+}
+
+bool Profile::verify_peer() const {
+ return verify_peer_;
+}
+
+size_t Profile::update_before_hours() const {
+ return update_before_hours_;
+}
+
+const std::string& Profile::security_manager_protocol_name() const {
+ return security_manager_protocol_name_;
+}
+
+const std::vector<int>& Profile::force_protected_service() const {
+ return force_protected_service_;
+}
+
+const std::vector<int>& Profile::force_unprotected_service() const {
+ return force_unprotected_service_;
+}
+#endif // ENABLE_SECURITY
+
+bool Profile::logs_enabled() const {
+ return logs_enabled_;
+}
+
+bool Profile::use_db_for_resumption() const {
+ return use_db_for_resumption_;
+}
+
+uint16_t Profile::attempts_to_open_resumption_db() const {
+ return attempts_to_open_resumption_db_;
+}
+
+uint16_t Profile::open_attempt_timeout_ms_resumption_db() const {
+ return open_attempt_timeout_ms_resumption_db_;
+}
+
void Profile::UpdateValues() {
LOG4CXX_AUTO_TRACE(logger_);
// SDL version
- ReadStringValue(&sdl_version_, kDefaultSDLVersion,
- kMainSection, kSDLVersionKey);
+ ReadStringValue(
+ &sdl_version_, kDefaultSDLVersion, kMainSection, kSDLVersionKey);
LOG_UPDATED_VALUE(sdl_version_, kSDLVersionKey, kMainSection);
@@ -711,19 +840,63 @@ void Profile::UpdateValues() {
launch_hmi_ = false;
}
- LOG_UPDATED_BOOL_VALUE(launch_hmi_, kLaunchHMIKey, kHmiSection);
+ LOG_UPDATED_BOOL_VALUE(launch_hmi_, kLaunchHMIKey, kHmiSection);
#ifdef WEB_HMI
// Link to web HMI parameter
- ReadStringValue(&link_to_web_hmi_, kDefaultLinkToWebHMI,
- kHmiSection, kLinkToWebHMI);
+ ReadStringValue(
+ &link_to_web_hmi_, kDefaultLinkToWebHMI, kHmiSection, kLinkToWebHMI);
LOG_UPDATED_BOOL_VALUE(link_to_web_hmi_, kLinkToWebHMI, kHmiSection);
-#endif // WEB_HMI
+#endif // WEB_HMI
+
+#ifdef ENABLE_SECURITY
+
+ force_protected_service_ =
+ ReadIntContainer(kSecuritySection, kForceProtectedService, NULL);
+
+ force_unprotected_service_ =
+ ReadIntContainer(kSecuritySection, kForceUnprotectedService, NULL);
+
+ ReadStringValue(&security_manager_protocol_name_,
+ kDefaultSecurityProtocol,
+ kSecuritySection,
+ kSecurityProtocolKey);
+
+ ReadStringValue(
+ &cert_path_, "", kSecuritySection, kSecurityCertificatePathKey);
+ ReadStringValue(
+ &ca_cert_path_, "", kSecuritySection, kSecurityCACertificatePathKey);
+
+ ReadStringValue(
+ &ssl_mode_, kDefaultSSLMode, kSecuritySection, kSecuritySSLModeKey);
+
+ ReadStringValue(&key_path_, "", kSecuritySection, kSecurityKeyPathKey);
+
+ ReadStringValue(
+ &ciphers_list_, SSL_TXT_ALL, kSecuritySection, kSecurityCipherListKey);
+
+ ReadBoolValue(&verify_peer_,
+ kDefaultVerifyPeer,
+ kSecuritySection,
+ kSecurityVerifyPeerKey);
+
+ ReadUIntValue(&update_before_hours_,
+ kDefaultBeforeUpdateHours,
+ kSecuritySection,
+ kBeforeUpdateHours);
+
+#endif // ENABLE_SECURITY
+
+ // Logs enabled
+ ReadBoolValue(&logs_enabled_, false, kMainSection, kLogsEnabledKey);
+
+ LOG_UPDATED_BOOL_VALUE(logs_enabled_, kLogsEnabledKey, kMainSection);
// Application config folder
ReadStringValue(&app_config_folder_,
file_system::CurrentWorkingDirectory().c_str(),
- kMainSection, kAppConfigFolderKey);
+ kMainSection,
+ kAppConfigFolderKey);
if (IsRelativePath(app_config_folder_)) {
MakeAbsolutePath(app_config_folder_);
@@ -734,7 +907,8 @@ void Profile::UpdateValues() {
// Application storage folder
ReadStringValue(&app_storage_folder_,
file_system::CurrentWorkingDirectory().c_str(),
- kMainSection, kAppStorageFolderKey);
+ kMainSection,
+ kAppStorageFolderKey);
if (IsRelativePath(app_storage_folder_)) {
MakeAbsolutePath(app_storage_folder_);
@@ -743,16 +917,16 @@ void Profile::UpdateValues() {
LOG_UPDATED_VALUE(app_storage_folder_, kAppStorageFolderKey, kMainSection);
// Application resourse folder
- ReadStringValue(&app_resourse_folder_,
+ ReadStringValue(&app_resource_folder_,
file_system::CurrentWorkingDirectory().c_str(),
- kMainSection, kAppResourseFolderKey);
+ kMainSection,
+ kAppResourseFolderKey);
- if (IsRelativePath(app_resourse_folder_)) {
- MakeAbsolutePath(app_resourse_folder_);
+ if (IsRelativePath(app_resource_folder_)) {
+ MakeAbsolutePath(app_resource_folder_);
}
- LOG_UPDATED_VALUE(app_resourse_folder_, kAppResourseFolderKey,
- kMainSection);
+ LOG_UPDATED_VALUE(app_resource_folder_, kAppResourseFolderKey, kMainSection);
// Enable protocol ver.4 parameter
std::string enable_protocol_4_value;
@@ -768,95 +942,108 @@ void Profile::UpdateValues() {
// Application icon folder
ReadStringValue(&app_icons_folder_,
file_system::CurrentWorkingDirectory().c_str(),
- kSDL4Section, kAppIconsFolderKey);
+ kSDL4Section,
+ kAppIconsFolderKey);
if (IsRelativePath(app_icons_folder_)) {
MakeAbsolutePath(app_icons_folder_);
}
- LOG_UPDATED_VALUE(app_icons_folder_, kAppIconsFolderKey,
- kSDL4Section);
+ LOG_UPDATED_VALUE(app_icons_folder_, kAppIconsFolderKey, kSDL4Section);
// Application icon folder maximum size
- ReadUIntValue(&app_icons_folder_max_size_, kDefaultAppIconsFolderMaxSize,
- kSDL4Section, kAppIconsFolderMaxSizeKey);
+ ReadUIntValue(&app_icons_folder_max_size_,
+ kDefaultAppIconsFolderMaxSize,
+ kSDL4Section,
+ kAppIconsFolderMaxSizeKey);
if (app_icons_folder_max_size_ < kDefaultAppIconsFolderMaxSize) {
app_icons_folder_max_size_ = kDefaultAppIconsFolderMaxSize;
}
- LOG_UPDATED_VALUE(app_icons_folder_max_size_, kAppIconsFolderMaxSizeKey,
- kSDL4Section);
+ LOG_UPDATED_VALUE(
+ app_icons_folder_max_size_, kAppIconsFolderMaxSizeKey, kSDL4Section);
// Application icon folder maximum size
- ReadUIntValue(&app_icons_amount_to_remove_, kDefaultAppIconsAmountToRemove,
- kSDL4Section, kAppIconsAmountToRemoveKey);
+ ReadUIntValue(&app_icons_amount_to_remove_,
+ kDefaultAppIconsAmountToRemove,
+ kSDL4Section,
+ kAppIconsAmountToRemoveKey);
- LOG_UPDATED_VALUE(app_icons_amount_to_remove_, kAppIconsAmountToRemoveKey,
- kSDL4Section);
+ LOG_UPDATED_VALUE(
+ app_icons_amount_to_remove_, kAppIconsAmountToRemoveKey, kSDL4Section);
// Application info file name
- ReadStringValue(&app_info_storage_, kDefaultAppInfoFileName,
+ ReadStringValue(&app_info_storage_,
+ kDefaultAppInfoFileName,
kAppInfoSection,
kAppInfoStorageKey);
- LOG_UPDATED_VALUE(app_info_storage_, kAppInfoStorageKey,
- kAppInfoSection);
+ LOG_UPDATED_VALUE(app_info_storage_, kAppInfoStorageKey, kAppInfoSection);
// Server address
- ReadStringValue(&server_address_, kDefaultServerAddress, kHmiSection,
- kServerAddressKey);
+ ReadStringValue(
+ &server_address_, kDefaultServerAddress, kHmiSection, kServerAddressKey);
LOG_UPDATED_VALUE(server_address_, kServerAddressKey, kHmiSection);
// HMI capabilities
- ReadStringValue(&hmi_capabilities_file_name_ ,
+ ReadStringValue(&hmi_capabilities_file_name_,
kDefaultHmiCapabilitiesFileName,
- kMainSection, kHmiCapabilitiesKey);
+ kMainSection,
+ kHmiCapabilitiesKey);
- hmi_capabilities_file_name_ = app_config_folder_ + "/" +
- hmi_capabilities_file_name_;
+ hmi_capabilities_file_name_ =
+ app_config_folder_ + "/" + hmi_capabilities_file_name_;
- LOG_UPDATED_VALUE(hmi_capabilities_file_name_, kHmiCapabilitiesKey,
- kMainSection);
+ LOG_UPDATED_VALUE(
+ hmi_capabilities_file_name_, kHmiCapabilitiesKey, kMainSection);
// Server port
- ReadUIntValue(&server_port_, kDefaultServerPort, kHmiSection,
- kServerPortKey);
+ ReadUIntValue(&server_port_, kDefaultServerPort, kHmiSection, kServerPortKey);
LOG_UPDATED_VALUE(server_port_, kServerPortKey, kHmiSection);
// Video streaming port
- ReadUIntValue(&video_streaming_port_, kDefaultVideoStreamingPort,
- kHmiSection, kVideoStreamingPortKey);
+ ReadUIntValue(&video_streaming_port_,
+ kDefaultVideoStreamingPort,
+ kHmiSection,
+ kVideoStreamingPortKey);
- LOG_UPDATED_VALUE(video_streaming_port_, kVideoStreamingPortKey,
- kHmiSection);
+ LOG_UPDATED_VALUE(video_streaming_port_, kVideoStreamingPortKey, kHmiSection);
// Audio streaming port
- ReadUIntValue(&audio_streaming_port_, kDefaultAudioStreamingPort,
- kHmiSection, kAudioStreamingPortKey);
+ ReadUIntValue(&audio_streaming_port_,
+ kDefaultAudioStreamingPort,
+ kHmiSection,
+ kAudioStreamingPortKey);
- LOG_UPDATED_VALUE(audio_streaming_port_, kAudioStreamingPortKey,
- kHmiSection);
+ LOG_UPDATED_VALUE(audio_streaming_port_, kAudioStreamingPortKey, kHmiSection);
// Streaming timeout
- ReadUIntValue(&stop_streaming_timeout_, kDefaultStopStreamingTimeout,
- kMediaManagerSection, kStopStreamingTimeout);
+ ReadUIntValue(&stop_streaming_timeout_,
+ kDefaultStopStreamingTimeout,
+ kMediaManagerSection,
+ kStopStreamingTimeout);
- stop_streaming_timeout_ = std::max(kDefaultStopStreamingTimeout, stop_streaming_timeout_);
+ stop_streaming_timeout_ =
+ std::max(kDefaultStopStreamingTimeout, stop_streaming_timeout_);
- LOG_UPDATED_VALUE(stop_streaming_timeout_, kStopStreamingTimeout,
- kHmiSection);
+ LOG_UPDATED_VALUE(
+ stop_streaming_timeout_, kStopStreamingTimeout, kHmiSection);
// Time testing port
- ReadUIntValue(&time_testing_port_, kDefaultTimeTestingPort, kMainSection,
+ ReadUIntValue(&time_testing_port_,
+ kDefaultTimeTestingPort,
+ kMainSection,
kTimeTestingPortKey);
LOG_UPDATED_VALUE(time_testing_port_, kTimeTestingPortKey, kMainSection);
// Minimum thread stack size
- ReadUIntValue(&min_tread_stack_size_, threads::Thread::kMinStackSize,
- kMainSection, kThreadStackSizeKey);
+ ReadUIntValue(&min_tread_stack_size_,
+ threads::Thread::kMinStackSize,
+ kMainSection,
+ kThreadStackSizeKey);
if (min_tread_stack_size_ < threads::Thread::kMinStackSize) {
min_tread_stack_size_ = threads::Thread::kMinStackSize;
@@ -865,94 +1052,107 @@ void Profile::UpdateValues() {
LOG_UPDATED_VALUE(min_tread_stack_size_, kThreadStackSizeKey, kMainSection);
// Start stream retry frequency
- ReadUintIntPairValue(&start_stream_retry_amount_, kStartStreamRetryAmount,
- kMediaManagerSection, kStartStreamRetry);
+ ReadUintIntPairValue(&start_stream_retry_amount_,
+ kStartStreamRetryAmount,
+ kMediaManagerSection,
+ kStartStreamRetry);
// Redecoding parameter
std::string redecoding_value;
- if (ReadValue(&redecoding_value, kMediaManagerSection, kEnableRedecodingKey)
- && 0 == strcmp("true", redecoding_value.c_str())) {
+ if (ReadValue(
+ &redecoding_value, kMediaManagerSection, kEnableRedecodingKey) &&
+ 0 == strcmp("true", redecoding_value.c_str())) {
is_redecoding_enabled_ = true;
} else {
is_redecoding_enabled_ = false;
}
- LOG_UPDATED_BOOL_VALUE(is_redecoding_enabled_, kEnableRedecodingKey,
- kMediaManagerSection);
+ LOG_UPDATED_BOOL_VALUE(
+ is_redecoding_enabled_, kEnableRedecodingKey, kMediaManagerSection);
// Video consumer type
- ReadStringValue(&video_consumer_type_, "", kMediaManagerSection,
- kVideoStreamConsumerKey);
+ ReadStringValue(
+ &video_consumer_type_, "", kMediaManagerSection, kVideoStreamConsumerKey);
- LOG_UPDATED_VALUE(video_consumer_type_, kVideoStreamConsumerKey,
- kMediaManagerSection);
+ LOG_UPDATED_VALUE(
+ video_consumer_type_, kVideoStreamConsumerKey, kMediaManagerSection);
// Audio stream consumer
- ReadStringValue(&audio_consumer_type_, "", kMediaManagerSection,
- kAudioStreamConsumerKey);
+ ReadStringValue(
+ &audio_consumer_type_, "", kMediaManagerSection, kAudioStreamConsumerKey);
- LOG_UPDATED_VALUE(audio_consumer_type_, kAudioStreamConsumerKey,
- kMediaManagerSection);
+ LOG_UPDATED_VALUE(
+ audio_consumer_type_, kAudioStreamConsumerKey, kMediaManagerSection);
// Named video pipe path
- ReadStringValue(&named_video_pipe_path_, "", kMediaManagerSection,
+ ReadStringValue(&named_video_pipe_path_,
+ "",
+ kMediaManagerSection,
kNamedVideoPipePathKey);
named_video_pipe_path_ = app_storage_folder_ + "/" + named_video_pipe_path_;
- LOG_UPDATED_VALUE(named_video_pipe_path_, kNamedVideoPipePathKey,
- kMediaManagerSection);
+ LOG_UPDATED_VALUE(
+ named_video_pipe_path_, kNamedVideoPipePathKey, kMediaManagerSection);
// Named audio pipe path
- ReadStringValue(&named_audio_pipe_path_, "", kMediaManagerSection,
+ ReadStringValue(&named_audio_pipe_path_,
+ "",
+ kMediaManagerSection,
kNamedAudioPipePathKey);
named_audio_pipe_path_ = app_storage_folder_ + "/" + named_audio_pipe_path_;
- LOG_UPDATED_VALUE(named_audio_pipe_path_, kNamedAudioPipePathKey,
- kMediaManagerSection);
+ LOG_UPDATED_VALUE(
+ named_audio_pipe_path_, kNamedAudioPipePathKey, kMediaManagerSection);
// Video stream file
- ReadStringValue(&video_stream_file_, "", kMediaManagerSection,
- kVideoStreamFileKey);
+ ReadStringValue(
+ &video_stream_file_, "", kMediaManagerSection, kVideoStreamFileKey);
video_stream_file_ = app_storage_folder_ + "/" + video_stream_file_;
- LOG_UPDATED_VALUE(video_stream_file_, kVideoStreamFileKey,
- kMediaManagerSection);
+ LOG_UPDATED_VALUE(
+ video_stream_file_, kVideoStreamFileKey, kMediaManagerSection);
// Audio stream file
- ReadStringValue(&audio_stream_file_, "", kMediaManagerSection,
- kAudioStreamFileKey);
+ ReadStringValue(
+ &audio_stream_file_, "", kMediaManagerSection, kAudioStreamFileKey);
audio_stream_file_ = app_storage_folder_ + "/" + audio_stream_file_;
- LOG_UPDATED_VALUE(audio_stream_file_, kAudioStreamFileKey,
- kMediaManagerSection);
+ LOG_UPDATED_VALUE(
+ audio_stream_file_, kAudioStreamFileKey, kMediaManagerSection);
- ReadUIntValue(&audio_data_stopped_timeout_, kDefaultAudioDataStoppedTimeout,
- kMediaManagerSection, kAudioDataStoppedTimeoutKey);
+ ReadUIntValue(&audio_data_stopped_timeout_,
+ kDefaultAudioDataStoppedTimeout,
+ kMediaManagerSection,
+ kAudioDataStoppedTimeoutKey);
- LOG_UPDATED_VALUE(audio_data_stopped_timeout_, kAudioDataStoppedTimeoutKey,
+ LOG_UPDATED_VALUE(audio_data_stopped_timeout_,
+ kAudioDataStoppedTimeoutKey,
kMediaManagerSection);
- ReadUIntValue(&video_data_stopped_timeout_, kDefaultVideoDataStoppedTimeout,
- kMediaManagerSection, kVideoDataStoppedTimeoutKey);
+ ReadUIntValue(&video_data_stopped_timeout_,
+ kDefaultVideoDataStoppedTimeout,
+ kMediaManagerSection,
+ kVideoDataStoppedTimeoutKey);
- LOG_UPDATED_VALUE(video_data_stopped_timeout_, kVideoDataStoppedTimeoutKey,
+ LOG_UPDATED_VALUE(video_data_stopped_timeout_,
+ kVideoDataStoppedTimeoutKey,
kMediaManagerSection);
// Mixing audio parameter
std::string mixing_audio_value;
- if (ReadValue(&mixing_audio_value, kMainSection, kMixingAudioSupportedKey)
- && 0 == strcmp("true", mixing_audio_value.c_str())) {
+ if (ReadValue(&mixing_audio_value, kMainSection, kMixingAudioSupportedKey) &&
+ 0 == strcmp("true", mixing_audio_value.c_str())) {
is_mixing_audio_supported_ = true;
} else {
is_mixing_audio_supported_ = false;
}
- LOG_UPDATED_BOOL_VALUE(is_mixing_audio_supported_, kMixingAudioSupportedKey,
- kMainSection);
+ LOG_UPDATED_BOOL_VALUE(
+ is_mixing_audio_supported_, kMixingAudioSupportedKey, kMainSection);
// Maximum command id value
ReadUIntValue(&max_cmd_id_, kDefaultMaxCmdId, kMainSection, kMaxCmdIdKey);
@@ -960,29 +1160,47 @@ void Profile::UpdateValues() {
LOG_UPDATED_VALUE(max_cmd_id_, kMaxCmdIdKey, kMainSection);
// PutFile restrictions
- ReadUIntValue(&put_file_in_none_, kDefaultPutFileRequestInNone,
- kFilesystemRestrictionsSection, kPutFileRequestKey);
+ ReadUIntValue(&put_file_in_none_,
+ kDefaultPutFileRequestInNone,
+ kFilesystemRestrictionsSection,
+ kPutFileRequestKey);
- LOG_UPDATED_VALUE(put_file_in_none_, kPutFileRequestKey,
- kFilesystemRestrictionsSection);
+ LOG_UPDATED_VALUE(
+ put_file_in_none_, kPutFileRequestKey, kFilesystemRestrictionsSection);
// DeleteFileRestrictions
- ReadUIntValue(&delete_file_in_none_, kDefaultDeleteFileRequestInNone,
- kFilesystemRestrictionsSection, kDeleteFileRequestKey);
+ ReadUIntValue(&delete_file_in_none_,
+ kDefaultDeleteFileRequestInNone,
+ kFilesystemRestrictionsSection,
+ kDeleteFileRequestKey);
- LOG_UPDATED_VALUE(delete_file_in_none_, kDeleteFileRequestKey,
+ LOG_UPDATED_VALUE(delete_file_in_none_,
+ kDeleteFileRequestKey,
kFilesystemRestrictionsSection);
// ListFiles restrictions
- ReadUIntValue(&list_files_in_none_, kDefaultListFilesRequestInNone,
- kFilesystemRestrictionsSection, kListFilesRequestKey);
+ ReadUIntValue(&list_files_in_none_,
+ kDefaultListFilesRequestInNone,
+ kFilesystemRestrictionsSection,
+ kListFilesRequestKey);
- LOG_UPDATED_VALUE(list_files_in_none_, kListFilesRequestKey,
+ LOG_UPDATED_VALUE(list_files_in_none_,
+ kListFilesRequestKey,
+ kFilesystemRestrictionsSection);
+
+ // ListFiles request size
+ ReadUIntValue(&list_files_response_size_,
+ kDefaultListFilesResponseSize,
+ kFilesystemRestrictionsSection,
+ kListFilesResponseSizeKey);
+
+ LOG_UPDATED_VALUE(list_files_response_size_,
+ kListFilesResponseSizeKey,
kFilesystemRestrictionsSection);
// Default timeout
- ReadUIntValue(&default_timeout_, kDefaultTimeout, kMainSection,
- kDefaultTimeoutKey);
+ ReadUIntValue(
+ &default_timeout_, kDefaultTimeout, kMainSection, kDefaultTimeoutKey);
if (default_timeout_ == 0) {
default_timeout_ = kDefaultTimeout;
@@ -991,25 +1209,29 @@ void Profile::UpdateValues() {
LOG_UPDATED_VALUE(default_timeout_, kDefaultTimeoutKey, kMainSection);
// Application resuming timeout
- ReadUIntValue(&app_resuming_timeout_, kDefaultAppResumingTimeout,
- kResumptionSection, kAppResumingTimeoutKey);
+ ReadUIntValue(&app_resuming_timeout_,
+ kDefaultAppResumingTimeout,
+ kResumptionSection,
+ kAppResumingTimeoutKey);
if (app_resuming_timeout_ == 0) {
app_resuming_timeout_ = kDefaultAppResumingTimeout;
}
// Save resumption info to File System
- LOG_UPDATED_VALUE(app_resuming_timeout_, kAppSavePersistentDataTimeoutKey,
+ LOG_UPDATED_VALUE(app_resuming_timeout_,
+ kAppSavePersistentDataTimeoutKey,
kResumptionSection);
ReadUIntValue(&app_resumption_save_persistent_data_timeout_,
kDefaultAppSavePersistentDataTimeout,
- kResumptionSection, kAppSavePersistentDataTimeoutKey);
+ kResumptionSection,
+ kAppSavePersistentDataTimeoutKey);
if (app_resuming_timeout_ == 0) {
app_resuming_timeout_ = kDefaultAppSavePersistentDataTimeout;
}
- LOG_UPDATED_VALUE(app_resuming_timeout_, kAppResumingTimeoutKey,
- kResumptionSection);
+ LOG_UPDATED_VALUE(
+ app_resuming_timeout_, kAppResumingTimeoutKey, kResumptionSection);
// Open attempt timeout in ms
ReadUIntValue(&resumption_delay_before_ign_,
kDefaultResumptionDelayBeforeIgn,
@@ -1017,7 +1239,8 @@ void Profile::UpdateValues() {
kResumptionDelayBeforeIgnKey);
LOG_UPDATED_VALUE(resumption_delay_before_ign_,
- kResumptionDelayBeforeIgnKey, kResumptionSection);
+ kResumptionDelayBeforeIgnKey,
+ kResumptionSection);
// Open attempt timeout in ms
ReadUIntValue(&resumption_delay_after_ign_,
@@ -1026,11 +1249,12 @@ void Profile::UpdateValues() {
kResumptionDelayAfterIgnKey);
LOG_UPDATED_VALUE(resumption_delay_after_ign_,
- kResumptionDelayAfterIgnKey, kResumptionSection);
+ kResumptionDelayAfterIgnKey,
+ kResumptionSection);
// Application directory quota
- ReadUIntValue(&app_dir_quota_, kDefaultDirQuota, kMainSection,
- kAppDirectoryQuotaKey);
+ ReadUIntValue(
+ &app_dir_quota_, kDefaultDirQuota, kMainSection, kAppDirectoryQuotaKey);
if (app_dir_quota_ == 0) {
app_dir_quota_ = kDefaultDirQuota;
@@ -1040,68 +1264,62 @@ void Profile::UpdateValues() {
// TTS delimiter
// Should be gotten before any TTS prompts, since it should be appended back
- ReadStringValue(&tts_delimiter_, kDefaultTtsDelimiter,
- kGlobalPropertiesSection, kTTSDelimiterKey);
+ ReadStringValue(&tts_delimiter_,
+ kDefaultTtsDelimiter,
+ kGlobalPropertiesSection,
+ kTTSDelimiterKey);
- LOG_UPDATED_VALUE(tts_delimiter_, kTTSDelimiterKey,
- kGlobalPropertiesSection);
+ LOG_UPDATED_VALUE(tts_delimiter_, kTTSDelimiterKey, kGlobalPropertiesSection);
// Help prompt
help_prompt_.clear();
std::string help_prompt_value;
- if (ReadValue(&help_prompt_value, kGlobalPropertiesSection,
- kHelpPromptKey)) {
+ if (ReadValue(&help_prompt_value, kGlobalPropertiesSection, kHelpPromptKey)) {
char* str = NULL;
str = strtok(const_cast<char*>(help_prompt_value.c_str()), ",");
while (str != NULL) {
// Default prompt should have delimiter included for each item
const std::string prompt_item = std::string(str) + tts_delimiter_;
help_prompt_.push_back(prompt_item);
- LOG_UPDATED_VALUE(prompt_item, kHelpPromptKey,
- kGlobalPropertiesSection);
+ LOG_UPDATED_VALUE(prompt_item, kHelpPromptKey, kGlobalPropertiesSection);
str = strtok(NULL, ",");
}
} else {
help_prompt_value.clear();
- LOG_UPDATED_VALUE(help_prompt_value, kHelpPromptKey,
- kGlobalPropertiesSection);
+ LOG_UPDATED_VALUE(
+ help_prompt_value, kHelpPromptKey, kGlobalPropertiesSection);
}
-
-
// Timeout prompt
time_out_promt_.clear();
std::string timeout_prompt_value;
- if (ReadValue(&timeout_prompt_value, kGlobalPropertiesSection,
- kTimeoutPromptKey)) {
+ if (ReadValue(
+ &timeout_prompt_value, kGlobalPropertiesSection, kTimeoutPromptKey)) {
char* str = NULL;
str = strtok(const_cast<char*>(timeout_prompt_value.c_str()), ",");
while (str != NULL) {
// Default prompt should have delimiter included for each item
const std::string prompt_item = std::string(str) + tts_delimiter_;
time_out_promt_.push_back(prompt_item);
- LOG_UPDATED_VALUE(prompt_item, kTimeoutPromptKey,
- kGlobalPropertiesSection);
+ LOG_UPDATED_VALUE(
+ prompt_item, kTimeoutPromptKey, kGlobalPropertiesSection);
str = strtok(NULL, ",");
}
} else {
timeout_prompt_value.clear();
- LOG_UPDATED_VALUE(timeout_prompt_value, kTimeoutPromptKey,
- kGlobalPropertiesSection);
+ LOG_UPDATED_VALUE(
+ timeout_prompt_value, kTimeoutPromptKey, kGlobalPropertiesSection);
}
// Voice recognition help title
- ReadStringValue(&vr_help_title_, "", kGlobalPropertiesSection,
- kHelpTitleKey);
+ ReadStringValue(&vr_help_title_, "", kGlobalPropertiesSection, kHelpTitleKey);
- LOG_UPDATED_VALUE(vr_help_title_, kHelpTitleKey,
- kGlobalPropertiesSection);
+ LOG_UPDATED_VALUE(vr_help_title_, kHelpTitleKey, kGlobalPropertiesSection);
// Voice recognition help command
vr_commands_.clear();
std::string vr_help_command_value;
- if (ReadValue(&vr_help_command_value, kVrCommandsSection,
- kHelpCommandKey)) {
+ if (ReadValue(&vr_help_command_value, kVrCommandsSection, kHelpCommandKey)) {
char* str = NULL;
str = strtok(const_cast<char*>(vr_help_command_value.c_str()), ",");
while (str != NULL) {
@@ -1112,17 +1330,18 @@ void Profile::UpdateValues() {
}
} else {
vr_help_command_value.clear();
- LOG_UPDATED_VALUE(vr_help_command_value, kHelpCommandKey,
- kVrCommandsSection);
+ LOG_UPDATED_VALUE(
+ vr_help_command_value, kHelpCommandKey, kVrCommandsSection);
}
- //TTS GlobalProperties timeout
+ // TTS GlobalProperties timeout
ReadUIntValue(&tts_global_properties_timeout_,
kDefaultTTSGlobalPropertiesTimeout,
kGlobalPropertiesSection,
kTTSGlobalPropertiesTimeoutKey);
- LOG_UPDATED_VALUE(tts_global_properties_timeout_, kTTSGlobalPropertiesTimeoutKey,
+ LOG_UPDATED_VALUE(tts_global_properties_timeout_,
+ kTTSGlobalPropertiesTimeoutKey,
kGlobalPropertiesSection);
// Application time scale maximum requests
@@ -1131,15 +1350,17 @@ void Profile::UpdateValues() {
kMainSection,
kAppTimeScaleMaxRequestsKey);
- LOG_UPDATED_VALUE(app_time_scale_max_requests_, kAppTimeScaleMaxRequestsKey,
- kMainSection);
+ LOG_UPDATED_VALUE(
+ app_time_scale_max_requests_, kAppTimeScaleMaxRequestsKey, kMainSection);
// Application time scale
- ReadUIntValue(&app_requests_time_scale_, kDefaultAppRequestsTimeScale,
- kMainSection, kAppRequestsTimeScaleKey);
+ ReadUIntValue(&app_requests_time_scale_,
+ kDefaultAppRequestsTimeScale,
+ kMainSection,
+ kAppRequestsTimeScaleKey);
- LOG_UPDATED_VALUE(app_requests_time_scale_, kAppRequestsTimeScaleKey,
- kMainSection);
+ LOG_UPDATED_VALUE(
+ app_requests_time_scale_, kAppRequestsTimeScaleKey, kMainSection);
// Application HMI level NONE time scale maximum requests
ReadUIntValue(&app_hmi_level_none_time_scale_max_requests_,
@@ -1162,21 +1383,25 @@ void Profile::UpdateValues() {
kMainSection);
// Amount of pending requests
- ReadUIntValue(&pending_requests_amount_, kDefaultPendingRequestsAmount,
- kMainSection, kPendingRequestsAmoundKey);
+ ReadUIntValue(&pending_requests_amount_,
+ kDefaultPendingRequestsAmount,
+ kMainSection,
+ kPendingRequestsAmoundKey);
if (pending_requests_amount_ == 0) {
pending_requests_amount_ = kDefaultPendingRequestsAmount;
}
- LOG_UPDATED_VALUE(pending_requests_amount_, kPendingRequestsAmoundKey,
- kMainSection);
+ LOG_UPDATED_VALUE(
+ pending_requests_amount_, kPendingRequestsAmoundKey, kMainSection);
// Supported diagnostic modes
supported_diag_modes_.clear();
std::string supported_diag_modes_value;
std::string correct_diag_modes;
- if (ReadStringValue(&supported_diag_modes_value, "", kMainSection,
+ if (ReadStringValue(&supported_diag_modes_value,
+ "",
+ kMainSection,
kSupportedDiagModesKey)) {
char* str = NULL;
str = strtok(const_cast<char*>(supported_diag_modes_value.c_str()), ",");
@@ -1195,13 +1420,17 @@ void Profile::UpdateValues() {
LOG_UPDATED_VALUE(correct_diag_modes, kSupportedDiagModesKey, kMainSection);
// System files path
- ReadStringValue(&system_files_path_, kDefaultSystemFilesPath, kMainSection,
+ ReadStringValue(&system_files_path_,
+ kDefaultSystemFilesPath,
+ kMainSection,
kSystemFilesPathKey);
LOG_UPDATED_VALUE(system_files_path_, kSystemFilesPathKey, kMainSection);
// Heartbeat timeout
- ReadUIntValue(&heart_beat_timeout_, kDefaultHeartBeatTimeout, kMainSection,
+ ReadUIntValue(&heart_beat_timeout_,
+ kDefaultHeartBeatTimeout,
+ kMainSection,
kHeartBeatTimeoutKey);
LOG_UPDATED_VALUE(heart_beat_timeout_, kHeartBeatTimeoutKey, kMainSection);
@@ -1223,29 +1452,19 @@ void Profile::UpdateValues() {
kTransportManagerSection,
kTCPAdapterPortKey);
- LOG_UPDATED_VALUE(transport_manager_tcp_adapter_port_, kTCPAdapterPortKey,
+ LOG_UPDATED_VALUE(transport_manager_tcp_adapter_port_,
+ kTCPAdapterPortKey,
kTransportManagerSection);
- // MME database name
- ReadStringValue(&mme_db_name_,
- kDefaultMmeDatabaseName,
- kTransportManagerSection,
- kMmeDatabaseNameKey);
-
- LOG_UPDATED_VALUE(mme_db_name_, kMmeDatabaseNameKey, kTransportManagerSection);
// Event MQ
- ReadStringValue(&event_mq_name_,
- kDefaultEventMQ,
- kTransportManagerSection,
- kEventMQKey);
+ ReadStringValue(
+ &event_mq_name_, kDefaultEventMQ, kTransportManagerSection, kEventMQKey);
LOG_UPDATED_VALUE(event_mq_name_, kEventMQKey, kTransportManagerSection);
// Ack MQ
- ReadStringValue(&ack_mq_name_,
- kDefaultAckMQ,
- kTransportManagerSection,
- kAckMQKey);
+ ReadStringValue(
+ &ack_mq_name_, kDefaultAckMQ, kTransportManagerSection, kAckMQKey);
LOG_UPDATED_VALUE(ack_mq_name_, kAckMQKey, kTransportManagerSection);
@@ -1260,22 +1479,28 @@ void Profile::UpdateValues() {
kTransportManagerSection);
// Recording file
- ReadStringValue(&recording_file_name_, kDefaultRecordingFileName,
- kMediaManagerSection, kRecordingFileNameKey);
+ ReadStringValue(&recording_file_name_,
+ kDefaultRecordingFileName,
+ kMediaManagerSection,
+ kRecordingFileNameKey);
- LOG_UPDATED_VALUE(recording_file_name_, kRecordingFileNameKey, kMediaManagerSection);
+ LOG_UPDATED_VALUE(
+ recording_file_name_, kRecordingFileNameKey, kMediaManagerSection);
// Recording file source
- ReadStringValue(&recording_file_source_, kDefaultRecordingFileSourceName,
- kMediaManagerSection, kRecordingFileSourceKey);
+ ReadStringValue(&recording_file_source_,
+ kDefaultRecordingFileSourceName,
+ kMediaManagerSection,
+ kRecordingFileSourceKey);
- LOG_UPDATED_VALUE(recording_file_source_, kRecordingFileSourceKey,
- kMediaManagerSection);
+ LOG_UPDATED_VALUE(
+ recording_file_source_, kRecordingFileSourceKey, kMediaManagerSection);
// Policy preloaded file
ReadStringValue(&preloaded_pt_file_,
kDefaultPreloadedPTFileName,
- kPolicySection, kPreloadedPTKey);
+ kPolicySection,
+ kPreloadedPTKey);
preloaded_pt_file_ = app_config_folder_ + '/' + preloaded_pt_file_;
@@ -1284,10 +1509,11 @@ void Profile::UpdateValues() {
// Policy snapshot file
ReadStringValue(&policy_snapshot_file_name_,
kDefaultPoliciesSnapshotFileName,
- kPolicySection, kPathToSnapshotKey);
+ kPolicySection,
+ kPathToSnapshotKey);
- LOG_UPDATED_VALUE(policy_snapshot_file_name_, kPathToSnapshotKey,
- kPolicySection);
+ LOG_UPDATED_VALUE(
+ policy_snapshot_file_name_, kPathToSnapshotKey, kPolicySection);
// Attempts number for opening policy DB
ReadUIntValue(&attempts_to_open_policy_db_,
@@ -1295,17 +1521,17 @@ void Profile::UpdateValues() {
kPolicySection,
kAttemptsToOpenPolicyDBKey);
- LOG_UPDATED_VALUE(attempts_to_open_policy_db_,
- kAttemptsToOpenPolicyDBKey, kPolicySection);
+ LOG_UPDATED_VALUE(
+ attempts_to_open_policy_db_, kAttemptsToOpenPolicyDBKey, kPolicySection);
// Open attempt timeout in ms
ReadUIntValue(&open_attempt_timeout_ms_,
- kDefaultOpenAttemptTimeoutMsKey,
+ kDefaultOpenAttemptTimeoutMs,
kPolicySection,
kOpenAttemptTimeoutMsKey);
- LOG_UPDATED_VALUE(open_attempt_timeout_ms_,
- kOpenAttemptTimeoutMsKey, kPolicySection);
+ LOG_UPDATED_VALUE(
+ open_attempt_timeout_ms_, kOpenAttemptTimeoutMsKey, kPolicySection);
// Turn Policy Off?
std::string enable_policy_string;
@@ -1316,6 +1542,18 @@ void Profile::UpdateValues() {
enable_policy_ = false;
}
+ // Max protocol version
+ ReadUIntValue(&max_supported_protocol_version_,
+ kDefaultMaxSupportedProtocolVersion,
+ kProtocolHandlerSection,
+ kMaxSupportedProtocolVersionKey);
+
+ // if .ini file contains protocol version less than 2 or more than 3
+ // max_supported_protocol_version_ = 3
+ if (max_supported_protocol_version_ < 2) {
+ max_supported_protocol_version_ = 3;
+ }
+
LOG_UPDATED_BOOL_VALUE(enable_policy_, kEnablePolicy, kPolicySection);
ReadUIntValue(&application_list_update_timeout_,
@@ -1324,13 +1562,18 @@ void Profile::UpdateValues() {
kApplicationListUpdateTimeoutKey);
LOG_UPDATED_VALUE(application_list_update_timeout_,
- kApplicationListUpdateTimeoutKey, kMainSection);
+ kApplicationListUpdateTimeoutKey,
+ kMainSection);
- ReadUintIntPairValue(&read_did_frequency_, kReadDIDFrequency,
- kMainSection, kReadDIDFrequencykey);
+ ReadUintIntPairValue(&read_did_frequency_,
+ kReadDIDFrequency,
+ kMainSection,
+ kReadDIDFrequencykey);
- ReadUintIntPairValue(&get_vehicle_data_frequency_, kGetVehicleDataFrequency,
- kMainSection, kGetVehicleDataFrequencyKey);
+ ReadUintIntPairValue(&get_vehicle_data_frequency_,
+ kGetVehicleDataFrequency,
+ kMainSection,
+ kGetVehicleDataFrequencyKey);
ReadUIntValue(&max_thread_pool_size_,
kDefaultMaxThreadPoolSize,
@@ -1340,14 +1583,16 @@ void Profile::UpdateValues() {
max_thread_pool_size_ = kDefaultMaxThreadPoolSize;
}
LOG_UPDATED_VALUE(max_thread_pool_size_,
- kDefaultMaxThreadPoolSize, kApplicationManagerSection);
+ kDefaultMaxThreadPoolSize,
+ kApplicationManagerSection);
ReadStringValue(&iap_legacy_protocol_mask_,
kDefaultLegacyProtocolMask,
kIAPSection,
kLegacyProtocolMaskKey);
- LOG_UPDATED_VALUE(iap_legacy_protocol_mask_, kLegacyProtocolMaskKey, kIAPSection);
+ LOG_UPDATED_VALUE(
+ iap_legacy_protocol_mask_, kLegacyProtocolMaskKey, kIAPSection);
ReadStringValue(&iap_hub_protocol_mask_,
kDefaultHubProtocolMask,
@@ -1382,7 +1627,8 @@ void Profile::UpdateValues() {
kIAPSection,
kIAP2HubConnectAttemptskey);
- LOG_UPDATED_VALUE(iap2_hub_connect_attempts_, kIAP2HubConnectAttemptskey, kIAPSection);
+ LOG_UPDATED_VALUE(
+ iap2_hub_connect_attempts_, kIAP2HubConnectAttemptskey, kIAPSection);
ReadIntValue(&iap_hub_connection_wait_timeout_,
kDefaultIAPHubConnectionWaitTimeout,
@@ -1390,59 +1636,91 @@ void Profile::UpdateValues() {
kIAPHubConnectionWaitTimeoutKey);
LOG_UPDATED_VALUE(iap_hub_connection_wait_timeout_,
- kIAPHubConnectionWaitTimeoutKey, kIAPSection);
+ kIAPHubConnectionWaitTimeoutKey,
+ kIAPSection);
- ReadUIntValue(&default_hub_protocol_index_, kDefaultHubProtocolIndex, kIAPSection, kDefaultHubProtocolIndexKey);
+ ReadUIntValue(&default_hub_protocol_index_,
+ kDefaultHubProtocolIndex,
+ kIAPSection,
+ kDefaultHubProtocolIndexKey);
- LOG_UPDATED_VALUE(default_hub_protocol_index_, kDefaultHubProtocolIndexKey, kIAPSection);
+ LOG_UPDATED_VALUE(
+ default_hub_protocol_index_, kDefaultHubProtocolIndexKey, kIAPSection);
- ReadUIntValue(&hash_string_size_,
+ ReadUIntValue(&hash_string_size_,
kDefaultHashStringSize,
kApplicationManagerSection,
kHashStringSizeKey);
- LOG_UPDATED_VALUE(hash_string_size_,
- kHashStringSizeKey,
- kApplicationManagerSection);
+ LOG_UPDATED_VALUE(
+ hash_string_size_, kHashStringSizeKey, kApplicationManagerSection);
+
+ ReadBoolValue(&use_db_for_resumption_,
+ false,
+ kResumptionSection,
+ kUseDBForResumptionKey);
+
+ LOG_UPDATED_BOOL_VALUE(
+ use_db_for_resumption_, kUseDBForResumptionKey, kResumptionSection);
+
+ ReadUIntValue(&attempts_to_open_resumption_db_,
+ kDefaultAttemptsToOpenResumptionDB,
+ kResumptionSection,
+ kAttemptsToOpenResumptionDBKey);
+
+ LOG_UPDATED_VALUE(attempts_to_open_resumption_db_,
+ kAttemptsToOpenResumptionDBKey,
+ kResumptionSection);
+
+ ReadUIntValue(&open_attempt_timeout_ms_resumption_db_,
+ kDefaultOpenAttemptTimeoutMsResumptionDB,
+ kResumptionSection,
+ kOpenAttemptTimeoutMsResumptionDBKey);
+
+ LOG_UPDATED_VALUE(open_attempt_timeout_ms_resumption_db_,
+ kOpenAttemptTimeoutMsResumptionDBKey,
+ kResumptionSection);
}
-bool Profile::ReadValue(bool* value, const char* const pSection,
+bool Profile::ReadValue(bool* value,
+ const char* const pSection,
const char* const pKey) const {
DCHECK(value);
bool ret = false;
char buf[INI_LINE_LEN + 1];
*buf = '\0';
- if ((0 != ini_read_value(config_file_name_.c_str(), pSection, pKey, buf))
- && ('\0' != *buf)) {
- const int32_t tmpVal = atoi(buf);
- if (0 == tmpVal) {
- *value = false;
- } else {
+ if ((0 != ini_read_value(config_file_name_.c_str(), pSection, pKey, buf)) &&
+ ('\0' != *buf)) {
+ const int32_t tmpVal = atoi(buf);
+ if ((0 == strcmp("true", buf)) || (0 != tmpVal)) {
*value = true;
+ } else {
+ *value = false;
}
-
ret = true;
}
return ret;
}
-bool Profile::ReadValue(std::string* value, const char* const pSection,
+bool Profile::ReadValue(std::string* value,
+ const char* const pSection,
const char* const pKey) const {
DCHECK(value);
bool ret = false;
char buf[INI_LINE_LEN + 1];
*buf = '\0';
- if ((0 != ini_read_value(config_file_name_.c_str(), pSection, pKey, buf))
- && ('\0' != *buf)) {
+ if ((0 != ini_read_value(config_file_name_.c_str(), pSection, pKey, buf)) &&
+ ('\0' != *buf)) {
*value = buf;
ret = true;
}
return ret;
}
-bool Profile::ReadStringValue(std::string* value, const char* default_value,
+bool Profile::ReadStringValue(std::string* value,
+ const char* default_value,
const char* const pSection,
const char* const pKey) const {
DCHECK(value);
@@ -1453,7 +1731,8 @@ bool Profile::ReadStringValue(std::string* value, const char* default_value,
return true;
}
-bool Profile::ReadIntValue(int32_t* value, const int32_t default_value,
+bool Profile::ReadIntValue(int32_t* value,
+ const int32_t default_value,
const char* const pSection,
const char* const pKey) const {
DCHECK(value);
@@ -1466,24 +1745,26 @@ bool Profile::ReadIntValue(int32_t* value, const int32_t default_value,
return true;
}
-bool Profile::ReadUintIntPairValue(std::pair<uint32_t, int32_t>* value,
+bool Profile::ReadUintIntPairValue(
+ std::pair<uint32_t, int32_t>* value,
const std::pair<uint32_t, uint32_t>& default_value,
- const char *const pSection,
- const char *const pKey) const {
+ const char* const pSection,
+ const char* const pKey) const {
std::string string_value;
if (!ReadValue(&string_value, pSection, pKey)) {
*value = default_value;
return false;
}
std::string first_str = string_value.substr(0, string_value.find(","));
- std::string second_str = string_value.substr(string_value.find(",") + 1,
- string_value.size() - first_str.size());
+ std::string second_str = string_value.substr(
+ string_value.find(",") + 1, string_value.size() - first_str.size());
(*value).first = strtoul(first_str.c_str(), NULL, 10);
(*value).second = strtoul(second_str.c_str(), NULL, 10);
return true;
}
-bool Profile::ReadBoolValue(bool* value, const bool default_value,
+bool Profile::ReadBoolValue(bool* value,
+ const bool default_value,
const char* const pSection,
const char* const pKey) const {
DCHECK(value);
@@ -1498,38 +1779,41 @@ int32_t hex_to_int(const std::string& value) {
}
}
-std::list<int> Profile::ReadIntContainer(
- const char * const pSection, const char * const pKey,
- bool *out_result) const {
- const std::list<std::string> string_list =
+std::vector<int> Profile::ReadIntContainer(const char* const pSection,
+ const char* const pKey,
+ bool* out_result) const {
+ const std::vector<std::string> string_list =
ReadStringContainer(pSection, pKey, out_result);
- std::list<int> value_list;
+ std::vector<int> value_list;
value_list.resize(string_list.size());
- std::transform(string_list.begin(), string_list.end(),
- value_list.begin(), hex_to_int);
+ std::transform(
+ string_list.begin(), string_list.end(), value_list.begin(), hex_to_int);
return value_list;
}
-std::list<std::string> Profile::ReadStringContainer(
- const char * const pSection, const char * const pKey,
- bool *out_result) const {
+std::vector<std::string> Profile::ReadStringContainer(
+ const char* const pSection,
+ const char* const pKey,
+ bool* out_result) const {
std::string string;
const bool result = ReadValue(&string, pSection, pKey);
if (out_result)
*out_result = result;
- std::list < std::string > value_container;
+ std::vector<std::string> value_container;
if (result) {
std::istringstream iss(string);
std::string temp_str;
while (iss) {
- if (!getline( iss, temp_str, ',' )) break;
+ if (!getline(iss, temp_str, ','))
+ break;
value_container.push_back(temp_str);
}
}
return value_container;
}
-bool Profile::ReadUIntValue(uint16_t* value, uint16_t default_value,
+bool Profile::ReadUIntValue(uint16_t* value,
+ uint16_t default_value,
const char* const pSection,
const char* const pKey) const {
std::string string_value;
@@ -1542,13 +1826,17 @@ bool Profile::ReadUIntValue(uint16_t* value, uint16_t default_value,
*value = default_value;
return false;
}
-
+ if (user_value > (std::numeric_limits<uint16_t>::max)()) {
+ *value = default_value;
+ return false;
+ }
*value = static_cast<uint16_t>(user_value);
return true;
}
}
-bool Profile::ReadUIntValue(uint32_t* value, uint32_t default_value,
+bool Profile::ReadUIntValue(uint32_t* value,
+ uint32_t default_value,
const char* const pSection,
const char* const pKey) const {
std::string string_value;
@@ -1558,7 +1846,11 @@ bool Profile::ReadUIntValue(uint32_t* value, uint32_t default_value,
} else {
uint64_t user_value;
if (!StringToNumber(string_value, user_value)) {
- *value = default_value;
+ *value = default_value;
+ return false;
+ }
+ if (user_value > (std::numeric_limits<uint32_t>::max)()) {
+ *value = default_value;
return false;
}
@@ -1567,7 +1859,8 @@ bool Profile::ReadUIntValue(uint32_t* value, uint32_t default_value,
}
}
-bool Profile::ReadUIntValue(uint64_t* value, uint64_t default_value,
+bool Profile::ReadUIntValue(uint64_t* value,
+ uint64_t default_value,
const char* const pSection,
const char* const pKey) const {
std::string string_value;
@@ -1613,4 +1906,4 @@ void Profile::MakeAbsolutePath(std::string& path) {
path = file_system::CurrentWorkingDirectory() + "/" + path;
}
-}// namespace profile
+} // namespace profile
diff --git a/src/components/config_profile/test/CMakeLists.txt b/src/components/config_profile/test/CMakeLists.txt
index e474d3fc20..1246bff066 100644
--- a/src/components/config_profile/test/CMakeLists.txt
+++ b/src/components/config_profile/test/CMakeLists.txt
@@ -31,9 +31,7 @@
if(BUILD_TESTS)
include_directories (
- ${CMAKE_SOURCE_DIR}/src/3rd_party-static/gmock-1.7.0/include
- ${CMAKE_SOURCE_DIR}/src/3rd_party-static/gmock-1.7.0/gtest/include
- ${COMPONENTS_DIR}/include/utils
+ ${GMOCK_INCLUDE_DIRECTORY}
${COMPONENTS_DIR}/config_profile/include
)
diff --git a/src/components/config_profile/test/ini_file_test.cc b/src/components/config_profile/test/ini_file_test.cc
index 10d500df74..2f256c8b51 100644
--- a/src/components/config_profile/test/ini_file_test.cc
+++ b/src/components/config_profile/test/ini_file_test.cc
@@ -24,7 +24,7 @@
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * FERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
@@ -40,238 +40,234 @@ namespace profile {
using namespace ::profile;
-TEST(IniFileTest, DISABLED_WriteItemReadItem) {
+TEST(IniFileTest, WriteItemReadItem) {
// Write line in chapter
- const char * fname = "./test_ini_file.ini";
- const char *chapter = "Chapter";
- const char * item = "Test_item";
- const char * value = "test_value";
- const bool write_result = ini_write_value(fname, chapter, item, value,
- INI_FLAG_ITEM_UP_CREA);
+ const char* fname = "./test_ini_file.ini";
+ const char* chapter = "Chapter";
+ const char* item = "Test_item";
+ const char* value = "test_value";
+ const bool write_result =
+ ini_write_value(fname, chapter, item, value, INI_FLAG_ITEM_UP_CREA);
EXPECT_TRUE(write_result);
-
- // Read value from file
- char search_value[INI_LINE_LEN] = "";
+ char search_value[INI_LINE_LEN] = {0};
const bool read_result = ini_read_value(fname, chapter, item, search_value);
+ const char* res = search_value;
EXPECT_TRUE(read_result);
- EXPECT_EQ(*search_value, *value);
+ EXPECT_STREQ(res, value);
EXPECT_TRUE(file_system::DeleteFile("./test_ini_file.ini"));
}
-TEST(IniFileTest, DISABLED_WriteItemWithoutValueReadItem) {
+TEST(IniFileTest, WriteItemWithoutValueReadItem) {
// Write line in chapter
- const char * fname = "./test_ini_file.ini";
- const char *chapter = "Chapter";
- const char * test_item = "Test_item";
- const char * value = "";
- const bool write_result = ini_write_value(fname, chapter, test_item, value,
- INI_FLAG_ITEM_UP_CREA);
+ const char* fname = "./test_ini_file.ini";
+ const char* chapter = "Chapter";
+ const char* test_item = "Test_item";
+ const char* value = "";
+ const bool write_result =
+ ini_write_value(fname, chapter, test_item, value, INI_FLAG_ITEM_UP_CREA);
EXPECT_TRUE(write_result);
// Read value from file
- char search_value[INI_LINE_LEN] = "";
- const bool read_result = ini_read_value(fname, chapter, test_item, search_value);
-
+ char search_value[INI_LINE_LEN] = {0};
+ const bool read_result =
+ ini_read_value(fname, chapter, test_item, search_value);
+ const char* res = search_value;
EXPECT_TRUE(read_result);
- EXPECT_EQ(*search_value, *value);
+ EXPECT_STREQ(res, value);
EXPECT_TRUE(file_system::DeleteFile("./test_ini_file.ini"));
}
-TEST(IniFileTest, DISABLED_WriteSameItemInDifferentChapters) {
+TEST(IniFileTest, WriteSameItemInDifferentChapters) {
// Write line in chapter
- const char * fname = "./test_ini_file.ini";
- const char *chapter1 = "Chapter1";
- const char * test_item = "Test_item";
- const char * value = "test_value";
- const bool write_result = ini_write_value(fname, chapter1, test_item, value,
- INI_FLAG_ITEM_UP_CREA);
+ const char* fname = "./test_ini_file.ini";
+ const char* chapter1 = "Chapter1";
+ const char* test_item = "Test_item";
+ const char* value = "test_value";
+ const bool write_result =
+ ini_write_value(fname, chapter1, test_item, value, INI_FLAG_ITEM_UP_CREA);
EXPECT_TRUE(write_result);
-
- char search_value[INI_LINE_LEN] = "";
- const bool read_result = ini_read_value(fname, chapter1, test_item, search_value);
-
+ char search_value[INI_LINE_LEN] = {0};
+ const bool read_result =
+ ini_read_value(fname, chapter1, test_item, search_value);
+ const char* res = search_value;
EXPECT_TRUE(read_result);
- EXPECT_EQ(*search_value, *value);
+ EXPECT_STREQ(res, value);
// Create new chapter and write the same value
- const char *chapter2 = "Chapter2";
+ const char* chapter2 = "Chapter2";
- const bool write_result2 = ini_write_value(fname, chapter2, test_item, value,
- INI_FLAG_ITEM_UP_CREA);
+ const bool write_result2 =
+ ini_write_value(fname, chapter2, test_item, value, INI_FLAG_ITEM_UP_CREA);
EXPECT_TRUE(write_result2);
char value2[INI_LINE_LEN] = "test_value";
const bool read_result2 = ini_read_value(fname, chapter2, test_item, value2);
-
+ const char* res2 = value2;
EXPECT_TRUE(read_result2);
- EXPECT_EQ(*value2, *value);
-
+ EXPECT_STREQ(res2, res);
EXPECT_TRUE(file_system::DeleteFile("./test_ini_file.ini"));
}
-TEST(IniFileTest, DISABLED_RewriteItem) {
+TEST(IniFileTest, RewriteItem) {
// Write line in chapter
- const char * fname = "./test_ini_file.ini";
- const char *chapter = "Chapter";
- const char * item = "Test_item";
- const char * value = "test_value";
- bool write_result = ini_write_value(fname, chapter, item, value,
- INI_FLAG_ITEM_UP_CREA);
+ const char* fname = "./test_ini_file.ini";
+ const char* chapter = "Chapter";
+ const char* item = "Test_item";
+ const char* value = "test_value";
+ bool write_result =
+ ini_write_value(fname, chapter, item, value, INI_FLAG_ITEM_UP_CREA);
EXPECT_TRUE(write_result);
-
- char search_value[INI_LINE_LEN] = "";
+ char search_value[INI_LINE_LEN] = {0};
bool read_result = ini_read_value(fname, chapter, item, search_value);
-
+ const char* res = search_value;
EXPECT_TRUE(read_result);
- EXPECT_EQ(*search_value, *value);
+ EXPECT_STREQ(res, value);
// Write item again
- const char * newvalue = "new_test_value";
- write_result = ini_write_value(fname, chapter, item, newvalue,
- INI_FLAG_ITEM_UP_CREA);
+ const char* newvalue = "new_test_value";
+ write_result =
+ ini_write_value(fname, chapter, item, newvalue, INI_FLAG_ITEM_UP_CREA);
EXPECT_TRUE(write_result);
-
- char new_search_value[INI_LINE_LEN] = "";
+ char new_search_value[INI_LINE_LEN] = {0};
read_result = ini_read_value(fname, chapter, item, new_search_value);
-
+ const char* new_res = new_search_value;
EXPECT_TRUE(read_result);
- EXPECT_EQ(*new_search_value, *newvalue);
+ EXPECT_STREQ(new_res, newvalue);
EXPECT_TRUE(file_system::DeleteFile("./test_ini_file.ini"));
}
-TEST(IniFileTest, DISABLED_WriteTwoItemsInOneChapter) {
+TEST(IniFileTest, WriteTwoItemsInOneChapter) {
// Write line in chapter
- const char * fname = "./test_ini_file.ini";
- const char *chapter = "Chapter";
- const char * item = "Test_item";
- const char * value1 = "test_value";
+ const char* fname = "./test_ini_file.ini";
+ const char* chapter = "Chapter";
+ const char* item = "Test_item";
+ const char* value1 = "test_value";
- bool write_result = ini_write_value(fname, chapter, item, value1,
- INI_FLAG_ITEM_UP_CREA);
+ bool write_result =
+ ini_write_value(fname, chapter, item, value1, INI_FLAG_ITEM_UP_CREA);
EXPECT_TRUE(write_result);
// Write another line in the same chapter
- const char * item2 = "Test_item2";
- const char * value2 = "test_value2";
+ const char* item2 = "Test_item2";
+ const char* value2 = "test_value2";
- write_result = ini_write_value(fname, chapter, item2, value2,
- INI_FLAG_ITEM_UP_CREA);
+ write_result =
+ ini_write_value(fname, chapter, item2, value2, INI_FLAG_ITEM_UP_CREA);
EXPECT_TRUE(write_result);
// Search both values
- char search_value[INI_LINE_LEN] = "";
+ char search_value[INI_LINE_LEN] = {0};
bool read_result = ini_read_value(fname, chapter, item, search_value);
-
+ const char* res = search_value;
EXPECT_TRUE(read_result);
- EXPECT_EQ(*search_value, *value1);
+ EXPECT_STREQ(res, value1);
- char search_value2[INI_LINE_LEN] = "";
+ char search_value2[INI_LINE_LEN] = {0};
read_result = ini_read_value(fname, chapter, item2, search_value2);
-
+ const char* res2 = search_value2;
EXPECT_TRUE(read_result);
- EXPECT_EQ(*search_value2, *value2);
-
+ EXPECT_STREQ(res2, value2);
EXPECT_TRUE(file_system::DeleteFile("./test_ini_file.ini"));
}
TEST(IniFileTest, WriteEmptyItemWithValueReadItem) {
- const char * fname = "./test_ini_file.ini";
- const char *chapter = "Chapter";
- const char * test_item = "";
- const char * value = "test_value";
- bool result = ini_write_value(fname, chapter, test_item, value,
- INI_FLAG_ITEM_UP_CREA);
+ const char* fname = "./test_ini_file.ini";
+ const char* chapter = "Chapter";
+ const char* test_item = "";
+ const char* value = "test_value";
+ bool result =
+ ini_write_value(fname, chapter, test_item, value, INI_FLAG_ITEM_UP_CREA);
EXPECT_FALSE(result);
}
TEST(IniFileTest, WriteEmptyItemWithEmptyValue_ExpectFalse) {
// Write empty line in chapter
- const char * fname = "./test_ini_file.ini";
- const char *chapter = "Chapter";
- const char * test_item = "";
- const char * value = "";
- bool result = ini_write_value(fname, chapter, test_item, value,
- INI_FLAG_ITEM_UP_CREA);
+ const char* fname = "./test_ini_file.ini";
+ const char* chapter = "Chapter";
+ const char* test_item = "";
+ const char* value = "";
+ bool result =
+ ini_write_value(fname, chapter, test_item, value, INI_FLAG_ITEM_UP_CREA);
EXPECT_FALSE(result);
}
TEST(IniFileTest, WriteItemInEmptyChapter_ExpectFalse) {
// Write line in empty chapter
- const char * fname = "./test_ini_file.ini";
- const char *chapter = "";
- const char * test_item = "Test_item";
- const char * value = "test_value";
- bool result = ini_write_value(fname, chapter, test_item, value,
- INI_FLAG_ITEM_UP_CREA);
+ const char* fname = "./test_ini_file.ini";
+ const char* chapter = "";
+ const char* test_item = "Test_item";
+ const char* value = "test_value";
+ bool result =
+ ini_write_value(fname, chapter, test_item, value, INI_FLAG_ITEM_UP_CREA);
EXPECT_FALSE(result);
}
-TEST(IniFileTest,ParseEmptyLine) {
- char line[INI_LINE_LEN] = "";
- char val[INI_LINE_LEN] = "";
- char tag[INI_LINE_LEN] = "HMI";
+TEST(IniFileTest, ParseEmptyLine) {
+ char line[INI_LINE_LEN] = {0};
+ char val[INI_LINE_LEN] = {0};
+ const char* tag = "HMI";
Ini_search_id result;
result = ini_parse_line(line, tag, val);
EXPECT_EQ(INI_NOTHING, result);
}
-TEST(IniFileTest,ParseChapter) {
- char line[INI_LINE_LEN] = "[HMI]";
- char val[INI_LINE_LEN] = "";
- char tag[INI_LINE_LEN] = "HMI";
+TEST(IniFileTest, ParseChapter) {
+ const char* line = "[HMI]";
+ char val[INI_LINE_LEN] = {0};
+ const char* tag = "HMI";
Ini_search_id result;
result = ini_parse_line(line, tag, val);
EXPECT_EQ(INI_RIGHT_CHAPTER, result);
}
-TEST(IniFileTest,ParseChapterTagEmpty) {
- char line[INI_LINE_LEN] = "[HMI]";
- char val[INI_LINE_LEN] = "";
- char tag[INI_LINE_LEN] = "";
+TEST(IniFileTest, ParseChapterTagEmpty) {
+ const char* line = "[HMI]";
+ char val[INI_LINE_LEN] = {0};
+ char tag[INI_LINE_LEN] = {0};
Ini_search_id result;
result = ini_parse_line(line, tag, val);
EXPECT_EQ(INI_WRONG_CHAPTER, result);
}
-TEST(IniFileTest,ParseChapterWithUppercaseTag) {
- char line[INI_LINE_LEN] = "[Security Manager]";
- char val[INI_LINE_LEN] = "";
- char tag[INI_LINE_LEN] = "SECURITY MANAGER";
+TEST(IniFileTest, ParseChapterWithUppercaseTag) {
+ const char* line = "[Security Manager]";
+ char val[INI_LINE_LEN] = {0};
+ const char* tag = "SECURITY MANAGER";
Ini_search_id result;
result = ini_parse_line(line, tag, val);
EXPECT_EQ(INI_RIGHT_CHAPTER, result);
}
-TEST(IniFileTest,ParseChapterWithLowcaseTag) {
- char line[INI_LINE_LEN] = "[Security Manager]";
- char val[INI_LINE_LEN] = "";
- char tag[INI_LINE_LEN] = "Security Manager";
+TEST(IniFileTest, ParseChapterWithLowcaseTag) {
+ const char* line = "[Security Manager]";
+ char val[INI_LINE_LEN] = {0};
+ const char* tag = "Security Manager";
Ini_search_id result;
result = ini_parse_line(line, tag, val);
EXPECT_EQ(INI_WRONG_CHAPTER, result);
}
-TEST(IniFileTest,ParseWithWrongChapter) {
- char line[INI_LINE_LEN] = "[HMI]";
- char val[INI_LINE_LEN] = "";
- char tag[INI_LINE_LEN] = "MAIN";
+TEST(IniFileTest, ParseWithWrongChapter) {
+ const char* line = "[HMI]";
+ char val[INI_LINE_LEN] = {0};
+ const char* tag = "MAIN";
Ini_search_id result;
result = ini_parse_line(line, tag, val);
EXPECT_EQ(INI_WRONG_CHAPTER, result);
}
-TEST(IniFileTest,ParseLineWithItem) {
+TEST(IniFileTest, ParseLineWithItem) {
char line[INI_LINE_LEN] = "LaunchHMI = true";
char val[INI_LINE_LEN] = "";
char tag[INI_LINE_LEN] = "LAUNCHHMI";
@@ -284,50 +280,49 @@ TEST(IniFileTest,ParseLineWithItem) {
EXPECT_EQ(*check_val, *val);
}
-TEST(IniFileTest,ParseLineWithoutItem) {
- char line[INI_LINE_LEN] = "LaunchHMI = ";
- char val[INI_LINE_LEN] = "";
- char tag[INI_LINE_LEN] = "LAUNCHHMI";
+TEST(IniFileTest, ParseLineWithoutItem) {
+ const char* line = "LaunchHMI = ";
+ char val[INI_LINE_LEN] = {0};
+ const char* tag = "LAUNCHHMI";
Ini_search_id result;
result = ini_parse_line(line, tag, val);
+ const char* res = val;
+ const char* check_val = "";
EXPECT_EQ(INI_RIGHT_ITEM, result);
-
- char check_val[INI_LINE_LEN] = "";
- EXPECT_EQ(*check_val, *val);
+ EXPECT_STREQ(check_val, res);
}
-TEST(IniFileTest,ParseLineWithEmptytag) {
- char line[INI_LINE_LEN] = "LaunchHMI = true";
- char val[INI_LINE_LEN] = "";
- char tag[INI_LINE_LEN] = "";
+TEST(IniFileTest, ParseLineWithEmptytag) {
+ const char* line = "LaunchHMI = true";
+ char val[INI_LINE_LEN] = {0};
+ char tag[INI_LINE_LEN] = {0};
Ini_search_id result;
result = ini_parse_line(line, tag, val);
EXPECT_EQ(INI_WRONG_ITEM, result);
}
-TEST(IniFileTest,ParseLineWithLowcaseTag) {
- char line[INI_LINE_LEN] = "LaunchHMI = true";
- char val[INI_LINE_LEN] = "";
- char tag[INI_LINE_LEN] = "LaunchHmi";
+TEST(IniFileTest, ParseLineWithLowcaseTag) {
+ const char* line = "LaunchHMI = true";
+ char val[INI_LINE_LEN] = {0};
+ const char* tag = "LaunchHmi";
Ini_search_id result;
result = ini_parse_line(line, tag, val);
EXPECT_EQ(INI_WRONG_ITEM, result);
}
-TEST(IniFileTest,ParseLineWithComment) {
- char line[INI_LINE_LEN] = "; [HMI]";
- char val[INI_LINE_LEN] = "";
- char tag[INI_LINE_LEN] = "HMI";
+TEST(IniFileTest, ParseLineWithComment) {
+ const char* line = "; [HMI]";
+ char val[INI_LINE_LEN] = {0};
+ const char* tag = "HMI";
Ini_search_id result;
result = ini_parse_line(line, tag, val);
+ const char* res = val;
EXPECT_EQ(INI_REMARK, result);
-
- char check_val[INI_LINE_LEN] = ";";
- EXPECT_EQ(*check_val, *val);
+ EXPECT_STREQ(line, res);
}
} // namespace profile
diff --git a/src/components/config_profile/test/profile_test.cc b/src/components/config_profile/test/profile_test.cc
index 9d9eca755f..59ebb2820b 100644
--- a/src/components/config_profile/test/profile_test.cc
+++ b/src/components/config_profile/test/profile_test.cc
@@ -30,9 +30,11 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
+#include <algorithm>
+#include <vector>
+
#include "gtest/gtest.h"
#include "config_profile/profile.h"
-#include <algorithm>
#include "utils/file_system.h"
#include "utils/threads/thread.h"
@@ -44,746 +46,684 @@ using namespace ::profile;
class ProfileTest : public ::testing::Test {
protected:
- virtual void SetUp() {
- profile::Profile::destroy();
- }
- virtual void TearDown() {
- profile::Profile::destroy();
- }
-
+ profile::Profile profile_;
};
-TEST_F(ProfileTest, SingletonProfile) {
- Profile::instance();
- EXPECT_TRUE(Profile::exists());
- profile::Profile::destroy();
- EXPECT_FALSE(Profile::exists());
-}
-
TEST_F(ProfileTest, UpdateConfigWithDefaultFile) {
// Default value
uint32_t thread_min_stack_size = threads::Thread::kMinStackSize;
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
- EXPECT_FALSE(profile::Profile::instance()->enable_policy());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
+ EXPECT_FALSE(profile_.enable_policy());
std::string vr_help_title_ = "";
- EXPECT_EQ(vr_help_title_, Profile::instance()->vr_help_title());
- EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name());
+ EXPECT_EQ(vr_help_title_, profile_.vr_help_title());
+ EXPECT_EQ("smartDeviceLink.ini", profile_.config_file_name());
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// Value was updated
thread_min_stack_size = 20480;
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
- EXPECT_TRUE(profile::Profile::instance()->enable_policy());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
+ EXPECT_TRUE(profile_.enable_policy());
vr_help_title_ = "Available Vr Commands List";
- EXPECT_EQ(vr_help_title_, Profile::instance()->vr_help_title());
+ EXPECT_EQ(vr_help_title_, profile_.vr_help_title());
}
TEST_F(ProfileTest, SetConfigFileWithoutCallUpdate) {
// Default value
uint32_t thread_min_stack_size = threads::Thread::kMinStackSize;
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
- EXPECT_FALSE(profile::Profile::instance()->enable_policy());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
+ EXPECT_FALSE(profile_.enable_policy());
std::string vr_help_title_ = "";
- EXPECT_EQ(vr_help_title_, Profile::instance()->vr_help_title());
- EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name());
+ EXPECT_EQ(vr_help_title_, profile_.vr_help_title());
+ EXPECT_EQ("smartDeviceLink.ini", profile_.config_file_name());
- Profile::instance()->config_file_name("smartDeviceLink.ini");
- EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink.ini");
+ EXPECT_EQ("smartDeviceLink.ini", profile_.config_file_name());
// Value was updated
thread_min_stack_size = 20480;
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
- EXPECT_TRUE(profile::Profile::instance()->enable_policy());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
+ EXPECT_TRUE(profile_.enable_policy());
vr_help_title_ = "Available Vr Commands List";
- EXPECT_EQ(vr_help_title_, Profile::instance()->vr_help_title());
+ EXPECT_EQ(vr_help_title_, profile_.vr_help_title());
}
TEST_F(ProfileTest, SetConfigFileWithUpdate) {
// Default value
uint32_t thread_min_stack_size = threads::Thread::kMinStackSize;
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
- Profile::instance()->config_file_name("smartDeviceLink.ini");
- EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
+ profile_.config_file_name("smartDeviceLink.ini");
+ EXPECT_EQ("smartDeviceLink.ini", profile_.config_file_name());
// Value was updated
thread_min_stack_size = 20480;
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
// Update config file again
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// Value should be the same
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
}
TEST_F(ProfileTest, UpdateManyTimesDefaultFile) {
- //using for check logger's work - core dump when this test was started and log4cxx exists in test derictory
- Profile::instance()->config_file_name("smartDeviceLink.ini");
- EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name());
+ // using for check logger's work - core dump when this test was started and
+ // log4cxx exists in test derictory
+ profile_.config_file_name("smartDeviceLink.ini");
+ EXPECT_EQ("smartDeviceLink.ini", profile_.config_file_name());
// Update config many times
for (int i = 0; i < 10; i++) {
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
}
}
TEST_F(ProfileTest, UpdateIntValues) {
// Default value
- EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name());
+ EXPECT_EQ("smartDeviceLink.ini", profile_.config_file_name());
uint32_t thread_min_stack_size = threads::Thread::kMinStackSize;
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
// Set config file with default name
- Profile::instance()->config_file_name("smartDeviceLink.ini");
- EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink.ini");
+ EXPECT_EQ("smartDeviceLink.ini", profile_.config_file_name());
// Value changes
thread_min_stack_size = 20480;
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
// Update config file again
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// Values are same
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
// Set new config file
- Profile::instance()->config_file_name("smartDeviceLink_test.ini");
- EXPECT_EQ("smartDeviceLink_test.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_test.ini");
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
// Value changes
thread_min_stack_size = 21000;
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
// Update config file again
- profile::Profile::instance()->UpdateValues();
- EXPECT_EQ("smartDeviceLink_test.ini",
- Profile::instance()->config_file_name());
+ profile_.UpdateValues();
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
// Value should be the same
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
// Set config file with default name again
- Profile::instance()->config_file_name("smartDeviceLink.ini");
- EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink.ini");
+ EXPECT_EQ("smartDeviceLink.ini", profile_.config_file_name());
// Value should be changed
thread_min_stack_size = 20480;
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
}
TEST_F(ProfileTest, UpdateBoolValues) {
// Default values
- EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name());
- EXPECT_TRUE(profile::Profile::instance()->launch_hmi());
- EXPECT_FALSE(profile::Profile::instance()->enable_policy());
+ EXPECT_EQ("smartDeviceLink.ini", profile_.config_file_name());
+ EXPECT_TRUE(profile_.launch_hmi());
+ EXPECT_FALSE(profile_.enable_policy());
// Set config file
- Profile::instance()->config_file_name("smartDeviceLink.ini");
+ profile_.config_file_name("smartDeviceLink.ini");
// Check values
- EXPECT_TRUE(profile::Profile::instance()->launch_hmi());
- EXPECT_TRUE(profile::Profile::instance()->enable_policy());
- EXPECT_FALSE(profile::Profile::instance()->is_redecoding_enabled());
+ EXPECT_TRUE(profile_.launch_hmi());
+ EXPECT_TRUE(profile_.enable_policy());
+ EXPECT_FALSE(profile_.is_redecoding_enabled());
// Update config file again
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// Values are same
- EXPECT_TRUE(profile::Profile::instance()->launch_hmi());
- EXPECT_TRUE(profile::Profile::instance()->enable_policy());
- EXPECT_FALSE(profile::Profile::instance()->is_redecoding_enabled());
+ EXPECT_TRUE(profile_.launch_hmi());
+ EXPECT_TRUE(profile_.enable_policy());
+ EXPECT_FALSE(profile_.is_redecoding_enabled());
// Change config file
- Profile::instance()->config_file_name("smartDeviceLink_test.ini");
- EXPECT_EQ("smartDeviceLink_test.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_test.ini");
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
// Parameters after updating
- EXPECT_FALSE(profile::Profile::instance()->launch_hmi());
- EXPECT_FALSE(profile::Profile::instance()->enable_policy());
- EXPECT_TRUE(profile::Profile::instance()->is_redecoding_enabled());
+ EXPECT_FALSE(profile_.launch_hmi());
+ EXPECT_FALSE(profile_.enable_policy());
+ EXPECT_TRUE(profile_.is_redecoding_enabled());
// Update config file
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// Parameters are same
- EXPECT_FALSE(profile::Profile::instance()->launch_hmi());
- EXPECT_FALSE(profile::Profile::instance()->enable_policy());
- EXPECT_TRUE(profile::Profile::instance()->is_redecoding_enabled());
+ EXPECT_FALSE(profile_.launch_hmi());
+ EXPECT_FALSE(profile_.enable_policy());
+ EXPECT_TRUE(profile_.is_redecoding_enabled());
}
TEST_F(ProfileTest, UpdateStringValue) {
// Default values
- std::string config_folder = "";
+ std::string recording_file_name = "record.wav";
std::string tts_delimiter_ = "";
std::string vr_help_title_ = "";
+ std::string app_resource_folder = "";
std::string server_address = "127.0.0.1";
- std::string app_resourse_folder = "";
- EXPECT_EQ(config_folder, Profile::instance()->app_resourse_folder());
- EXPECT_EQ(server_address, profile::Profile::instance()->server_address());
- Profile::instance()->config_file_name("smartDeviceLink.ini");
- EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name());
+ EXPECT_EQ(recording_file_name, profile_.recording_file_name());
+ EXPECT_EQ(server_address, profile_.server_address());
+
+ profile_.config_file_name("smartDeviceLink.ini");
+ EXPECT_EQ("smartDeviceLink.ini", profile_.config_file_name());
// Check values
- config_folder = file_system::CurrentWorkingDirectory();
- EXPECT_EQ(config_folder, Profile::instance()->app_resourse_folder());
+ app_resource_folder = file_system::CurrentWorkingDirectory();
+ EXPECT_EQ(app_resource_folder, profile_.app_resource_folder());
tts_delimiter_ = ",";
- EXPECT_EQ(tts_delimiter_, Profile::instance()->tts_delimiter());
+ EXPECT_EQ(tts_delimiter_, profile_.tts_delimiter());
vr_help_title_ = "Available Vr Commands List";
- EXPECT_EQ(vr_help_title_, Profile::instance()->vr_help_title());
-
- EXPECT_EQ(server_address, profile::Profile::instance()->server_address());
- app_resourse_folder = file_system::CurrentWorkingDirectory();
- EXPECT_EQ(app_resourse_folder, Profile::instance()->app_resourse_folder());
+ EXPECT_EQ(vr_help_title_, profile_.vr_help_title());
+ EXPECT_EQ(server_address, profile_.server_address());
// Update config file
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// Values are the same
- EXPECT_EQ(config_folder, Profile::instance()->app_resourse_folder());
- EXPECT_EQ(tts_delimiter_, Profile::instance()->tts_delimiter());
- EXPECT_EQ(vr_help_title_, Profile::instance()->vr_help_title());
- EXPECT_EQ(server_address, profile::Profile::instance()->server_address());
- EXPECT_EQ(app_resourse_folder, Profile::instance()->app_resourse_folder());
+ EXPECT_EQ(tts_delimiter_, profile_.tts_delimiter());
+ EXPECT_EQ(vr_help_title_, profile_.vr_help_title());
+ EXPECT_EQ(server_address, profile_.server_address());
}
TEST_F(ProfileTest, UpdateInt_ValueAppearsInFileTwice) {
// Default values
uint32_t server_port = 8087;
- EXPECT_EQ(server_port, Profile::instance()->server_port());
+ EXPECT_EQ(server_port, profile_.server_port());
// Change config file
- Profile::instance()->config_file_name("smartDeviceLink_test.ini");
- EXPECT_EQ("smartDeviceLink_test.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_test.ini");
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
// Update config file
// First server_port = 8088
server_port = 8088;
- EXPECT_EQ(server_port, Profile::instance()->server_port());
+ EXPECT_EQ(server_port, profile_.server_port());
}
TEST_F(ProfileTest, UpdateBool_ValueAppearsInFileTwice) {
// Default values
- EXPECT_FALSE(Profile::instance()->is_mixing_audio_supported());
+ EXPECT_FALSE(profile_.is_mixing_audio_supported());
// Change config file
- Profile::instance()->config_file_name("smartDeviceLink_test.ini");
- EXPECT_EQ("smartDeviceLink_test.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_test.ini");
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
// Update config file
// First value is false
- EXPECT_FALSE(profile::Profile::instance()->is_mixing_audio_supported());
+ EXPECT_FALSE(profile_.is_mixing_audio_supported());
}
TEST_F(ProfileTest, UpdateVectorOfString_ValueAppearsInFileTwice) {
// Default values
- std::vector < std::string > time_out_promt;
- EXPECT_EQ(time_out_promt, Profile::instance()->time_out_promt());
+ std::vector<std::string> time_out_promt;
+ EXPECT_EQ(time_out_promt, profile_.time_out_promt());
// Change config file
- Profile::instance()->config_file_name("smartDeviceLink_test.ini");
- EXPECT_EQ("smartDeviceLink_test.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_test.ini");
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
// Update config file
time_out_promt.push_back("Please say a command,");
- EXPECT_EQ(time_out_promt, Profile::instance()->time_out_promt());
+ EXPECT_EQ(time_out_promt, profile_.time_out_promt());
}
TEST_F(ProfileTest, UpdateString_ValueAppearsInFileTwice) {
// Default values
std::string recording_file_name = "record.wav";
- EXPECT_EQ(recording_file_name, Profile::instance()->recording_file_name());
+ EXPECT_EQ(recording_file_name, profile_.recording_file_name());
// Change config file
- Profile::instance()->config_file_name("smartDeviceLink_test.ini");
- EXPECT_EQ("smartDeviceLink_test.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_test.ini");
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
// Update config file
recording_file_name = "video.wav";
- EXPECT_EQ(recording_file_name, Profile::instance()->recording_file_name());
+ EXPECT_EQ(recording_file_name, profile_.recording_file_name());
}
TEST_F(ProfileTest, UpdatePairsValue) {
// Default values
- std::pair < uint32_t, int32_t > value;
+ std::pair<uint32_t, int32_t> value;
value.first = 0;
value.second = 0;
- EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency());
+ EXPECT_EQ(value, profile_.get_vehicle_data_frequency());
- Profile::instance()->config_file_name("smartDeviceLink.ini");
- EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink.ini");
+ EXPECT_EQ("smartDeviceLink.ini", profile_.config_file_name());
value.first = 5;
value.second = 1;
- EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency());
+ EXPECT_EQ(value, profile_.get_vehicle_data_frequency());
// Update config file
- profile::Profile::instance()->UpdateValues();
- EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency());
+ profile_.UpdateValues();
+ EXPECT_EQ(value, profile_.get_vehicle_data_frequency());
}
// Section with negative tests
TEST_F(ProfileTest, PairsValueEmpty) {
// Default values
- std::pair < uint32_t, int32_t > value;
+ std::pair<uint32_t, int32_t> value;
value.first = 0;
value.second = 0;
- EXPECT_EQ(value, Profile::instance()->read_did_frequency());
+ EXPECT_EQ(value, profile_.read_did_frequency());
- Profile::instance()->config_file_name("smartDeviceLink_invalid_pairs.ini");
- EXPECT_EQ("smartDeviceLink_invalid_pairs.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_invalid_pairs.ini");
+ EXPECT_EQ("smartDeviceLink_invalid_pairs.ini", profile_.config_file_name());
// Default values
value.first = 5;
value.second = 1;
- EXPECT_EQ(value, Profile::instance()->read_did_frequency());
+ EXPECT_EQ(value, profile_.read_did_frequency());
// Update config file
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// Values are same
- EXPECT_EQ(value, Profile::instance()->read_did_frequency());
+ EXPECT_EQ(value, profile_.read_did_frequency());
}
TEST_F(ProfileTest, CharValueInPairInsteadOfInt) {
- std::pair < uint32_t, int32_t > value;
+ std::pair<uint32_t, int32_t> value;
value.first = 0;
value.second = 0;
- EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency());
+ EXPECT_EQ(value, profile_.get_vehicle_data_frequency());
- Profile::instance()->config_file_name("smartDeviceLink_invalid_string.ini");
- EXPECT_EQ("smartDeviceLink_invalid_string.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_invalid_string.ini");
+ EXPECT_EQ("smartDeviceLink_invalid_string.ini", profile_.config_file_name());
- EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency());
+ EXPECT_EQ(value, profile_.get_vehicle_data_frequency());
// Update config file
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// Values are same
- EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency());
+ EXPECT_EQ(value, profile_.get_vehicle_data_frequency());
}
TEST_F(ProfileTest, EmptyValuesInPair) {
- Profile::instance()->config_file_name("smartDeviceLink_invalid_pairs.ini");
- EXPECT_EQ("smartDeviceLink_invalid_pairs.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_invalid_pairs.ini");
+ EXPECT_EQ("smartDeviceLink_invalid_pairs.ini", profile_.config_file_name());
- std::pair < uint32_t, int32_t > value;
+ std::pair<uint32_t, int32_t> value;
value.first = 0;
value.second = 0;
- EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency());
+ EXPECT_EQ(value, profile_.get_vehicle_data_frequency());
// Update config file
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// Values are same
- EXPECT_EQ(value, Profile::instance()->get_vehicle_data_frequency());
+ EXPECT_EQ(value, profile_.get_vehicle_data_frequency());
}
-TEST_F(ProfileTest, DISABLED_IntInsteadOfPair) {
+TEST_F(ProfileTest, IntInsteadOfPair) {
// Default values
- std::pair < uint32_t, int32_t > value;
+ std::pair<uint32_t, int32_t> value;
value.first = 0;
value.second = 0;
- EXPECT_EQ(value, Profile::instance()->start_stream_retry_amount());
+ EXPECT_EQ(value, profile_.start_stream_retry_amount());
- Profile::instance()->config_file_name("smartDeviceLink_invalid_pairs.ini");
- EXPECT_EQ("smartDeviceLink_invalid_pairs.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_invalid_pairs.ini");
+ EXPECT_EQ("smartDeviceLink_invalid_pairs.ini", profile_.config_file_name());
// Ini file includes only one element
value.first = 9;
- value.second = 1000;
- EXPECT_EQ(value, Profile::instance()->start_stream_retry_amount());
+ value.second = 0;
+ EXPECT_EQ(value, profile_.start_stream_retry_amount());
// Update config file
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// Values are same
- EXPECT_EQ(value, Profile::instance()->start_stream_retry_amount());
+ EXPECT_EQ(value, profile_.start_stream_retry_amount());
}
TEST_F(ProfileTest, WrongIntValue) {
// Default value
- int32_t heart_beat_timeout = 0;
- EXPECT_EQ(heart_beat_timeout, Profile::instance()->heart_beat_timeout());
+ uint32_t heart_beat_timeout = 0;
+ EXPECT_EQ(heart_beat_timeout, profile_.heart_beat_timeout());
// Change config file
- Profile::instance()->config_file_name("smartDeviceLink_invalid_int.ini");
- EXPECT_EQ("smartDeviceLink_invalid_int.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_invalid_int.ini");
+ EXPECT_EQ("smartDeviceLink_invalid_int.ini", profile_.config_file_name());
// Value in file includes letters. Check that value is default
heart_beat_timeout = 0;
- EXPECT_EQ(heart_beat_timeout, Profile::instance()->heart_beat_timeout());
+ EXPECT_EQ(heart_beat_timeout, profile_.heart_beat_timeout());
// Update config file
- profile::Profile::instance()->UpdateValues();
- EXPECT_EQ(heart_beat_timeout, Profile::instance()->heart_beat_timeout());
+ profile_.UpdateValues();
+ EXPECT_EQ(heart_beat_timeout, profile_.heart_beat_timeout());
}
-TEST_F(ProfileTest, DISABLED_WrongMaxIntValue) {
+TEST_F(ProfileTest, WrongMaxIntValue) {
// Default value
uint32_t maxvalue = 2000000000;
- EXPECT_EQ(maxvalue, Profile::instance()->max_cmd_id());
+ EXPECT_EQ(maxvalue, profile_.max_cmd_id());
// Change config file
- Profile::instance()->config_file_name("smartDeviceLink_invalid_int.ini");
- EXPECT_EQ("smartDeviceLink_invalid_int.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_invalid_int.ini");
+ EXPECT_EQ("smartDeviceLink_invalid_int.ini", profile_.config_file_name());
// Value in file is more than could be saved.
// Check that value is default
- EXPECT_EQ(maxvalue, Profile::instance()->max_cmd_id());
+ EXPECT_EQ(maxvalue, profile_.max_cmd_id());
// Update config file
- profile::Profile::instance()->UpdateValues();
- EXPECT_EQ(maxvalue, Profile::instance()->max_cmd_id());
+ profile_.UpdateValues();
+ EXPECT_EQ(maxvalue, profile_.max_cmd_id());
}
-TEST_F(ProfileTest, DISABLED_WrongMinIntValue) {
+TEST_F(ProfileTest, WrongMinIntValue) {
// Default value
uint32_t minvalue = threads::Thread::kMinStackSize;
- EXPECT_EQ(minvalue, Profile::instance()->thread_min_stack_size());
+ EXPECT_EQ(minvalue, profile_.thread_min_stack_size());
uint16_t server_port = 8087;
- EXPECT_EQ(server_port, Profile::instance()->server_port());
+ EXPECT_EQ(server_port, profile_.server_port());
// Change config file
- Profile::instance()->config_file_name("smartDeviceLink_invalid_int.ini");
- EXPECT_EQ("smartDeviceLink_invalid_int.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_invalid_int.ini");
+ EXPECT_EQ("smartDeviceLink_invalid_int.ini", profile_.config_file_name());
- //File include 0, value should be lefted as default
- EXPECT_EQ(minvalue, Profile::instance()->thread_min_stack_size());
- //File include -1, value should be lefted as default
- EXPECT_EQ(server_port, Profile::instance()->server_port());
+ // File include 0, value should be lefted as default
+ EXPECT_EQ(minvalue, profile_.thread_min_stack_size());
+ // File include -1, value should be lefted as default
+ EXPECT_EQ(server_port, profile_.server_port());
// Update config file
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// Default value should be lefted
- EXPECT_EQ(minvalue, Profile::instance()->thread_min_stack_size());
- EXPECT_EQ(server_port, Profile::instance()->server_port());
+ EXPECT_EQ(minvalue, profile_.thread_min_stack_size());
+ EXPECT_EQ(server_port, profile_.server_port());
}
-TEST_F(ProfileTest, DISABLED_CheckCorrectValueWhenOtherValueInvalid) {
+TEST_F(ProfileTest, CheckCorrectValueWhenOtherValueInvalid) {
// Default value
uint32_t maxvalue = 2000000000;
- EXPECT_EQ(maxvalue, Profile::instance()->max_cmd_id());
+ EXPECT_EQ(maxvalue, profile_.max_cmd_id());
uint32_t thread_min_stack_size = threads::Thread::kMinStackSize;
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
// Change config file
- Profile::instance()->config_file_name("smartDeviceLink_test.ini");
- EXPECT_EQ("smartDeviceLink_test.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_test.ini");
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
// Check that value is default
maxvalue = 2000000000;
- EXPECT_EQ(maxvalue, Profile::instance()->max_cmd_id());
+ EXPECT_EQ(maxvalue, profile_.max_cmd_id());
// Other value is correct
thread_min_stack_size = 21000;
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
// Update config file
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// In file the number is bigger than can be, default value should be lefted
- EXPECT_EQ(maxvalue, Profile::instance()->max_cmd_id());
- EXPECT_EQ(thread_min_stack_size,
- Profile::instance()->thread_min_stack_size());
+ EXPECT_EQ(maxvalue, profile_.max_cmd_id());
+ EXPECT_EQ(thread_min_stack_size, profile_.thread_min_stack_size());
}
TEST_F(ProfileTest, PairsValueInsteadOfInt) {
// Set new config file
- Profile::instance()->config_file_name("smartDeviceLink_invalid_int.ini");
- EXPECT_EQ("smartDeviceLink_invalid_int.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_invalid_int.ini");
+ EXPECT_EQ("smartDeviceLink_invalid_int.ini", profile_.config_file_name());
// Get first number
uint32_t list_files_in_none = 5;
- EXPECT_EQ(list_files_in_none, Profile::instance()->list_files_in_none());
+ EXPECT_EQ(list_files_in_none, profile_.list_files_in_none());
// Update config file
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// Values are same
- EXPECT_EQ(list_files_in_none, Profile::instance()->list_files_in_none());
+ EXPECT_EQ(list_files_in_none, profile_.list_files_in_none());
}
-TEST_F(ProfileTest, DISABLED_StringValueIncludeSlashesAndRussianLetters) {
+TEST_F(ProfileTest, StringValueIncludeSlashesAndRussianLetters) {
// Default values
std::string config_folder = "";
- EXPECT_EQ(config_folder, Profile::instance()->app_resourse_folder());
+ EXPECT_EQ(config_folder, profile_.app_resource_folder());
std::string tts_delimiter_ = "";
- std::string app_resourse_folder = "";
std::string app_storage_folder = "";
+ std::string current_dir = file_system::CurrentWorkingDirectory();
- Profile::instance()->config_file_name("smartDeviceLink_invalid_string.ini");
- EXPECT_EQ("smartDeviceLink_invalid_string.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_invalid_string.ini");
+ EXPECT_EQ("smartDeviceLink_invalid_string.ini", profile_.config_file_name());
// Check values
- config_folder = "///";
- EXPECT_EQ(config_folder, Profile::instance()->app_config_folder());
tts_delimiter_ = "coma and point";
- EXPECT_EQ(tts_delimiter_, Profile::instance()->tts_delimiter());
+ EXPECT_EQ(tts_delimiter_, profile_.tts_delimiter());
std::string server_address = "127.0.0.1 + слово";
- EXPECT_EQ(server_address, profile::Profile::instance()->server_address());
- app_resourse_folder = "new folder/";
- EXPECT_EQ(app_resourse_folder, Profile::instance()->app_resourse_folder());
- app_storage_folder = "\" \"";
- EXPECT_EQ(app_storage_folder, Profile::instance()->app_storage_folder());
+ EXPECT_EQ(server_address, profile_.server_address());
+ app_storage_folder = "/\" \"";
+ EXPECT_EQ(current_dir + app_storage_folder, profile_.app_storage_folder());
// Update config file
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// Values are the same
- EXPECT_EQ(config_folder, Profile::instance()->app_config_folder());
- EXPECT_EQ(tts_delimiter_, Profile::instance()->tts_delimiter());
- EXPECT_EQ(server_address, profile::Profile::instance()->server_address());
- EXPECT_EQ(app_resourse_folder, Profile::instance()->app_resourse_folder());
+ EXPECT_EQ(tts_delimiter_, profile_.tts_delimiter());
+ EXPECT_EQ(server_address, profile_.server_address());
}
TEST_F(ProfileTest, StringUpperBoundValue) {
// Default values
std::string vr_help_title = "";
std::string recording_file_name = "record.wav";
- EXPECT_EQ(vr_help_title, Profile::instance()->vr_help_title());
- EXPECT_EQ(recording_file_name, Profile::instance()->recording_file_name());
+ EXPECT_EQ(vr_help_title, profile_.vr_help_title());
+ EXPECT_EQ(recording_file_name, profile_.recording_file_name());
- Profile::instance()->config_file_name("smartDeviceLink_invalid_string.ini");
- EXPECT_EQ("smartDeviceLink_invalid_string.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_invalid_string.ini");
+ EXPECT_EQ("smartDeviceLink_invalid_string.ini", profile_.config_file_name());
// Total count of elements in ini file's string will be less 512
vr_help_title =
- "0/0/0/1/2345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890abc!def@ghi";
- EXPECT_EQ(vr_help_title, Profile::instance()->vr_help_title());
- EXPECT_NE(vr_help_title, Profile::instance()->recording_file_name());
+ "0/0/0/1/"
+ "2345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~"
+ "STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:"
+ "yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!"
+ "def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,"
+ "01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_"
+ "GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$"
+ "mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890abc!"
+ "def@ghi";
+ EXPECT_EQ(vr_help_title, profile_.vr_help_title());
+ EXPECT_NE(vr_help_title, profile_.recording_file_name());
recording_file_name =
- "0/0/0/1/2345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890abc";
- EXPECT_EQ(recording_file_name, Profile::instance()->recording_file_name());
+ "0/0/0/1/"
+ "2345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~"
+ "STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:"
+ "yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!"
+ "def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,"
+ "01234567890a00012345678'90abc!def@ghi#jkl$mno%pqr^stu*vwx:yz()ABC-DEF_"
+ "GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890a00012345678'90abc!def@ghi#jkl$"
+ "mno%pqr^stu*vwx:yz()ABC-DEF_GHIJKL+MNO|PQR~STU{}WXY[]Z,01234567890abc";
+ EXPECT_EQ(recording_file_name, profile_.recording_file_name());
// Update config file
- profile::Profile::instance()->UpdateValues();
+ profile_.UpdateValues();
// Values are the same
- EXPECT_EQ(vr_help_title, Profile::instance()->vr_help_title());
- EXPECT_EQ(recording_file_name, Profile::instance()->recording_file_name());
+ EXPECT_EQ(vr_help_title, profile_.vr_help_title());
+ EXPECT_EQ(recording_file_name, profile_.recording_file_name());
}
TEST_F(ProfileTest, CapitalLetterInBoolValue) {
// Default values
- EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name());
- EXPECT_TRUE(profile::Profile::instance()->launch_hmi());
- EXPECT_FALSE(profile::Profile::instance()->enable_policy());
+ EXPECT_EQ("smartDeviceLink.ini", profile_.config_file_name());
+ EXPECT_TRUE(profile_.launch_hmi());
+ EXPECT_FALSE(profile_.enable_policy());
// Set config file
- Profile::instance()->config_file_name("smartDeviceLink.ini");
+ profile_.config_file_name("smartDeviceLink.ini");
// Check values
- EXPECT_TRUE(profile::Profile::instance()->launch_hmi());
- EXPECT_TRUE(profile::Profile::instance()->enable_policy());
- EXPECT_FALSE(profile::Profile::instance()->is_redecoding_enabled());
+ EXPECT_TRUE(profile_.launch_hmi());
+ EXPECT_TRUE(profile_.enable_policy());
+ EXPECT_FALSE(profile_.is_redecoding_enabled());
// Change config file
- Profile::instance()->config_file_name("smartDeviceLink_invalid_boolean.ini");
- EXPECT_EQ("smartDeviceLink_invalid_boolean.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_invalid_boolean.ini");
+ EXPECT_EQ("smartDeviceLink_invalid_boolean.ini", profile_.config_file_name());
// Parameters after updating
// Parameter launch_hmi = True
- EXPECT_FALSE(profile::Profile::instance()->launch_hmi());
+ EXPECT_FALSE(profile_.launch_hmi());
// EnablePolicy = TRUE
- EXPECT_FALSE(profile::Profile::instance()->enable_policy());
+ EXPECT_FALSE(profile_.enable_policy());
// EnableRedecoding = FALSE
- EXPECT_FALSE(profile::Profile::instance()->is_redecoding_enabled());
+ EXPECT_FALSE(profile_.is_redecoding_enabled());
}
TEST_F(ProfileTest, CheckReadStringValue) {
// Set new config file
- Profile::instance()->config_file_name("smartDeviceLink_test.ini");
- EXPECT_EQ("smartDeviceLink_test.ini",
- Profile::instance()->config_file_name());
-
- std::string app_resourse_folder_;
- profile::Profile::instance()->ReadStringValue(
- &app_resourse_folder_, file_system::CurrentWorkingDirectory().c_str(),
- "MAIN", "AppResourceFolder");
+ profile_.config_file_name("smartDeviceLink_test.ini");
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
+
+ std::string app_storage_folder_;
+ profile_.ReadStringValue(
+ &app_storage_folder_, "", "MAIN", "AppStorageFolder");
// Get default value
- EXPECT_EQ(app_resourse_folder_, file_system::CurrentWorkingDirectory());
+ EXPECT_EQ("storage", app_storage_folder_);
// Get value from file
std::string server_address;
- profile::Profile::instance()->ReadStringValue(&server_address, "", "HMI",
- "ServerAddress");
+ profile_.ReadStringValue(&server_address, "", "HMI", "ServerAddress");
EXPECT_EQ("127.0.0.1", server_address);
}
-TEST_F(ProfileTest, DISABLED_CheckReadBoolValue) {
+TEST_F(ProfileTest, CheckReadBoolValue) {
// Set new config file
- Profile::instance()->config_file_name("smartDeviceLink_test.ini");
- EXPECT_EQ("smartDeviceLink_test.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_test.ini");
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
bool enable_policy;
- profile::Profile::instance()->ReadBoolValue(&enable_policy, false, "Policy",
- "EnablePolicy");
+ profile_.ReadBoolValue(&enable_policy, false, "Policy", "EnablePolicy");
EXPECT_FALSE(enable_policy);
- // Change config back
- profile::Profile::destroy();
- EXPECT_EQ("smartDeviceLink.ini", Profile::instance()->config_file_name());
-
- //get default value
- bool launch_hmi;
- profile::Profile::instance()->ReadBoolValue(&launch_hmi, true, "HMI",
- "LaunchHMI");
- EXPECT_TRUE(launch_hmi);
+ bool use_last_state;
+ profile_.ReadBoolValue(&use_last_state, true, "MAIN", "UseLastState");
+ EXPECT_TRUE(use_last_state);
}
TEST_F(ProfileTest, CheckReadIntValue) {
// Set new config file
- Profile::instance()->config_file_name("smartDeviceLink_test.ini");
- EXPECT_EQ("smartDeviceLink_test.ini",
- Profile::instance()->config_file_name());
+ profile_.config_file_name("smartDeviceLink_test.ini");
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
int server_port = 0;
- profile::Profile::instance()->ReadIntValue(&server_port, 0, "HMI",
- "ServerPort");
+ profile_.ReadIntValue(&server_port, 0, "HMI", "ServerPort");
EXPECT_EQ(8088, server_port);
}
-//TEST_F(ProfileTest, CheckIntContainer) {
-// // Set new config file
-// Profile::instance()->config_file_name("smartDeviceLink_test.ini");
-// EXPECT_EQ("smartDeviceLink_test.ini",
-// Profile::instance()->config_file_name());
-
-// bool isread = false;
-// std::vector<int> diagmodes_list =
-// profile::Profile::instance()->ReadIntContainer("MAIN",
-// "SupportedDiagModes",
-// &isread);
-// EXPECT_TRUE(isread);
-
-// std::vector<int>::iterator diag_mode = std::find(diagmodes_list.begin(),
-// diagmodes_list.end(), 0x12);
-
-// // This element doesn't appear in list
-// EXPECT_EQ(diag_mode, diagmodes_list.end());
-
-// // List includes 0x01
-// diag_mode = std::find(diagmodes_list.begin(), diagmodes_list.end(), 0x01);
-// EXPECT_EQ(diag_mode, diagmodes_list.begin());
-
-// // List includes 0x03
-// std::vector<int>::iterator element_mode = diagmodes_list.begin();
-// element_mode++;
-// element_mode++;
-
-// diag_mode = std::find(diagmodes_list.begin(), diagmodes_list.end(), 0x03);
-// EXPECT_EQ(diag_mode, element_mode);
-//}
-
-//TEST_F(ProfileTest, CheckVectorContainer) {
-// Profile::instance()->config_file_name("smartDeviceLink_test.ini");
-// EXPECT_EQ("smartDeviceLink_test.ini",
-// Profile::instance()->config_file_name());
-
-// // Get diag_modes after updating
-// const std::vector<uint32_t> &diag_modes = profile::Profile::instance()
-// ->supported_diag_modes();
-
-// bool isread = false;
-// std::vector<int> diagmodes_list =
-// profile::Profile::instance()->ReadIntContainer("MAIN",
-// "SupportedDiagModes",
-// &isread);
-// EXPECT_TRUE(isread);
-// // Compare with result of ReadIntContainer
-// ASSERT_EQ(diag_modes.size(), diagmodes_list.size());
-// bool isEqual = true;
-// std::vector<int>::iterator iter = diagmodes_list.begin();
-
-// for (std::vector<uint32_t>::const_iterator it = diag_modes.begin();
-// it != diag_modes.end(); it++) {
-
-// if ((uint32_t)(*iter) != (*it)) {
-// isEqual = false;
-// break;
-// }
-// iter++;
-// }
-// EXPECT_TRUE(isEqual);
-//}
-
-//TEST_F(ProfileTest, CheckStringContainer) {
-// // Set new config file
-// Profile::instance()->config_file_name("smartDeviceLink_test.ini");
-// EXPECT_EQ("smartDeviceLink_test.ini",
-// Profile::instance()->config_file_name());
-
-// bool isread = false;
-// std::vector < std::string > diagmodes_list = profile::Profile::instance()
-// ->ReadStringContainer("MAIN", "SupportedDiagModes", &isread);
-// EXPECT_TRUE(isread);
-
-// std::vector<std::string>::iterator diag_mode =
-// std::find(diagmodes_list.begin(), diagmodes_list.end(), "0x12");
-
-// // This element doesn't appear in list
-// EXPECT_EQ(diag_mode, diagmodes_list.end());
-
-// // List includes 0x01
-// diag_mode = std::find(diagmodes_list.begin(), diagmodes_list.end(), "0x01");
-// EXPECT_EQ(diag_mode, diagmodes_list.begin());
-
-// // List includes 0x03
-// std::vector<std::string>::iterator element_mode = diagmodes_list.begin();
-// element_mode++;
-// element_mode++;
-// diag_mode = std::find(diagmodes_list.begin(), diagmodes_list.end(), " 0x03");
-// EXPECT_EQ(diag_mode, element_mode);
-//}
-
-//#ifdef ENABLE_SECURITY
-//TEST_F(ProfileTest, CheckIntContainerInSecurityData) {
-// // Set new config file
-// Profile::instance()->config_file_name("smartDeviceLink_test.ini");
-// EXPECT_EQ("smartDeviceLink_test.ini",
-// Profile::instance()->config_file_name());
-
-// std::vector<int> force_unprotected_list =
-// profile::Profile::instance()->ReadIntContainer(
-// "Security Manager", "ForceUnprotectedService", NULL);
-
-// std::vector<int> force_protected_list =
-// profile::Profile::instance()->ReadIntContainer(
-// "Security Manager", "ForceProtectedService", NULL);
-
-// std::vector<int>::iterator res_unprotect = std::find(force_unprotected_list.begin(), force_unprotected_list.end(), 0x07);
-// std::vector<int>::iterator res_protect = std::find(force_protected_list.begin(), force_protected_list.end(), 0x07);
-// // This element doesn't appear in both lists
-// EXPECT_EQ(res_unprotect, force_unprotected_list.end() );
-// EXPECT_EQ(res_protect, force_protected_list.end() );
-
-// // Both lists include 0
-// res_unprotect = std::find(force_unprotected_list.begin(), force_unprotected_list.end(), 0);
-// res_protect = std::find(force_protected_list.begin(), force_protected_list.end(), 0);
-// EXPECT_EQ(res_unprotect, force_unprotected_list.begin() );
-// EXPECT_EQ(res_protect, force_protected_list.begin() );
-//}
-//#endif
-
-} // namespace profile
-} // namespace components
-} // namespace test
+TEST_F(ProfileTest, CheckIntContainer) {
+ // Set new config file
+ profile_.config_file_name("smartDeviceLink_test.ini");
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
+
+ bool isread = false;
+ std::vector<int> diagmodes_list =
+ profile_.ReadIntContainer("MAIN", "SupportedDiagModes", &isread);
+ EXPECT_TRUE(isread);
+
+ std::vector<int>::iterator diag_mode =
+ std::find(diagmodes_list.begin(), diagmodes_list.end(), 0x12);
+
+ // This element doesn't appear in list
+ EXPECT_EQ(diag_mode, diagmodes_list.end());
+
+ // List includes 0x01
+ diag_mode = std::find(diagmodes_list.begin(), diagmodes_list.end(), 0x01);
+ EXPECT_EQ(diag_mode, diagmodes_list.begin());
+
+ // List includes 0x03
+ std::vector<int>::iterator element_mode = diagmodes_list.begin();
+ element_mode++;
+ element_mode++;
+
+ diag_mode = std::find(diagmodes_list.begin(), diagmodes_list.end(), 0x03);
+ EXPECT_EQ(diag_mode, element_mode);
+}
+
+TEST_F(ProfileTest, CheckVectorContainer) {
+ profile_.config_file_name("smartDeviceLink_test.ini");
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
+
+ // Get diag_modes after updating
+ const std::vector<uint32_t>& diag_modes = profile_.supported_diag_modes();
+
+ bool isread = false;
+ std::vector<int> diagmodes_list =
+ profile_.ReadIntContainer("MAIN", "SupportedDiagModes", &isread);
+ EXPECT_TRUE(isread);
+ // Compare with result of ReadIntContainer
+ ASSERT_EQ(diag_modes.size(), diagmodes_list.size());
+ bool isEqual = true;
+ std::vector<int>::iterator iter = diagmodes_list.begin();
+
+ for (std::vector<uint32_t>::const_iterator it = diag_modes.begin();
+ it != diag_modes.end();
+ it++) {
+ if ((uint32_t)(*iter) != (*it)) {
+ isEqual = false;
+ break;
+ }
+ iter++;
+ }
+ EXPECT_TRUE(isEqual);
+}
+
+TEST_F(ProfileTest, CheckStringContainer) {
+ // Set new config file
+ profile_.config_file_name("smartDeviceLink_test.ini");
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
+
+ bool isread = false;
+ std::vector<std::string> diagmodes_list =
+ profile_.ReadStringContainer("MAIN", "SupportedDiagModes", &isread);
+ EXPECT_TRUE(isread);
+
+ std::vector<std::string>::iterator diag_mode =
+ std::find(diagmodes_list.begin(), diagmodes_list.end(), "0x12");
+
+ // This element doesn't appear in list
+ EXPECT_EQ(diag_mode, diagmodes_list.end());
+
+ // List includes 0x01
+ diag_mode = std::find(diagmodes_list.begin(), diagmodes_list.end(), "0x01");
+ EXPECT_EQ(diag_mode, diagmodes_list.begin());
+
+ // List includes 0x03
+ std::vector<std::string>::iterator element_mode = diagmodes_list.begin();
+ element_mode++;
+ element_mode++;
+ diag_mode = std::find(diagmodes_list.begin(), diagmodes_list.end(), " 0x03");
+ EXPECT_EQ(diag_mode, element_mode);
+}
+
+#ifdef ENABLE_SECURITY
+TEST_F(ProfileTest, CheckIntContainerInSecurityData) {
+ // Set new config file
+ profile_.config_file_name("smartDeviceLink_test.ini");
+ EXPECT_EQ("smartDeviceLink_test.ini", profile_.config_file_name());
+
+ std::vector<int> force_unprotected_list = profile_.ReadIntContainer(
+ "Security Manager", "ForceUnprotectedService", NULL);
+
+ std::vector<int> force_protected_list = profile_.ReadIntContainer(
+ "Security Manager", "ForceProtectedService", NULL);
+
+ std::vector<int>::iterator res_unprotect = std::find(
+ force_unprotected_list.begin(), force_unprotected_list.end(), 0x07);
+ std::vector<int>::iterator res_protect =
+ std::find(force_protected_list.begin(), force_protected_list.end(), 0x07);
+ // This element doesn't appear in both lists
+ EXPECT_EQ(res_unprotect, force_unprotected_list.end());
+ EXPECT_EQ(res_protect, force_protected_list.end());
+
+ // Both lists include 0
+ res_unprotect = std::find(
+ force_unprotected_list.begin(), force_unprotected_list.end(), 0);
+ res_protect =
+ std::find(force_protected_list.begin(), force_protected_list.end(), 0);
+ EXPECT_EQ(res_unprotect, force_unprotected_list.begin());
+ EXPECT_EQ(res_protect, force_protected_list.begin());
+}
+#endif
+
+} // namespace profile
+} // namespace components
+} // namespace test
diff --git a/src/components/connection_handler/CMakeLists.txt b/src/components/connection_handler/CMakeLists.txt
index 657c90d108..dc1b2d24d6 100644
--- a/src/components/connection_handler/CMakeLists.txt
+++ b/src/components/connection_handler/CMakeLists.txt
@@ -34,7 +34,6 @@ set(CH_SRC_DIR ${COMPONENTS_DIR}/connection_handler/src)
include_directories (
include
${COMPONENTS_DIR}/protocol_handler/include/
- ${COMPONENTS_DIR}/config_profile/include/
${COMPONENTS_DIR}/utils/include/
${ENCRYPTION_INCLUDE_DIRECTORY}
${LOG4CXX_INCLUDE_DIRECTORY}
@@ -48,7 +47,6 @@ set (SOURCES
)
set(LIBRARIES
- ConfigProfile
ProtocolLibrary
)
@@ -57,4 +55,4 @@ target_link_libraries(connectionHandler encryption)
if(BUILD_TESTS)
add_subdirectory(test)
-endif() \ No newline at end of file
+endif()
diff --git a/src/components/connection_handler/include/connection_handler/connection.h b/src/components/connection_handler/include/connection_handler/connection.h
index d20ddc1c00..aafc562505 100644
--- a/src/components/connection_handler/include/connection_handler/connection.h
+++ b/src/components/connection_handler/include/connection_handler/connection.h
@@ -73,13 +73,10 @@ struct Service {
protocol_handler::ServiceType service_type;
bool is_protected_;
Service()
- : service_type(protocol_handler::kInvalidServiceType),
- is_protected_(false) {
- }
+ : service_type(protocol_handler::kInvalidServiceType)
+ , is_protected_(false) {}
explicit Service(protocol_handler::ServiceType service_type)
- : service_type(service_type),
- is_protected_(false) {
- }
+ : service_type(service_type), is_protected_(false) {}
bool operator==(const protocol_handler::ServiceType service_type) const {
return this->service_type == service_type;
}
@@ -94,23 +91,26 @@ struct Session {
ServiceList service_list;
uint8_t protocol_version;
#ifdef ENABLE_SECURITY
- security_manager::SSLContext *ssl_context;
+ security_manager::SSLContext* ssl_context;
#endif // ENABLE_SECURITY
Session()
- : service_list()
+ : service_list()
#ifdef ENABLE_SECURITY
- , ssl_context(NULL)
+ , ssl_context(NULL)
#endif // ENABLE_SECURITY
- {}
- explicit Session(const ServiceList &services, uint8_t protocol_version)
- : service_list(services),
- protocol_version(protocol_version)
+ {
+ }
+ explicit Session(const ServiceList& services, uint8_t protocol_version)
+ : service_list(services)
+ , protocol_version(protocol_version)
#ifdef ENABLE_SECURITY
, ssl_context(NULL)
#endif // ENABLE_SECURITY
- {}
- Service *FindService(const protocol_handler::ServiceType &service_type);
- const Service *FindService(const protocol_handler::ServiceType &service_type) const;
+ {
+ }
+ Service* FindService(const protocol_handler::ServiceType& service_type);
+ const Service* FindService(
+ const protocol_handler::ServiceType& service_type) const;
};
/**
@@ -128,8 +128,8 @@ class Connection {
*/
Connection(ConnectionHandle connection_handle,
DeviceHandle connection_device_handle,
- ConnectionHandler *connection_handler,
- int32_t heartbeat_timeout);
+ ConnectionHandler* connection_handler,
+ uint32_t heartbeat_timeout);
/**
* @brief Destructor
@@ -146,7 +146,7 @@ class Connection {
* @brief Returns connection device handle
* @return ConnectionDeviceHandle
*/
- DeviceHandle connection_device_handle();
+ DeviceHandle connection_device_handle() const;
/**
* @brief Adds session to connection
@@ -187,8 +187,7 @@ class Connection {
* @param context SSL for connection
* @return \c true in case of service is protected or \c false otherwise
*/
- int SetSSLContext(uint8_t session_id,
- security_manager::SSLContext *context);
+ int SetSSLContext(uint8_t session_id, security_manager::SSLContext* context);
/**
* @brief Gets crypto context of session, use service_type to get NULL
* SSLContext for not protected services or ControlService (0x0)
@@ -197,23 +196,22 @@ class Connection {
* @param service_type Type of service
* @return \ref SSLContext of connection
*/
- security_manager::SSLContext *GetSSLContext(
- const uint8_t session_id,
- const protocol_handler::ServiceType &service_type) const;
+ security_manager::SSLContext* GetSSLContext(
+ const uint8_t session_id,
+ const protocol_handler::ServiceType& service_type) const;
/**
* @brief Set protection flag to service in session by key
* to get current SSLContext of connection
* @param session_id Identifier of the session
* @param service_type Type of service
*/
- void SetProtectionFlag(
- const uint8_t session_id,
- const protocol_handler::ServiceType &service_type);
+ void SetProtectionFlag(const uint8_t session_id,
+ const protocol_handler::ServiceType& service_type);
#endif // ENABLE_SECURITY
- /**
- * @brief Returns map of sessions which have been opened in
- * current connection.
- */
+ /**
+ * @brief Returns map of sessions which have been opened in
+ * current connection.
+ */
const SessionMap session_map() const;
/**
@@ -242,16 +240,17 @@ class Connection {
/**
* @brief Sets heart beat timeout
- * @param timeout in seconds
+ * @param timeout in milliseconds
*/
- void SetHeartBeatTimeout(int32_t timeout, uint8_t session_id);
+ void SetHeartBeatTimeout(uint32_t timeout, uint8_t session_id);
/**
* @brief changes protocol version in session
* @param session_id session id
* @param protocol_version protocol version registered application
*/
- void UpdateProtocolVersionSession(uint8_t session_id, uint8_t protocol_version);
+ void UpdateProtocolVersionSession(uint8_t session_id,
+ uint8_t protocol_version);
/**
* @brief checks if session supports heartbeat
@@ -267,14 +266,13 @@ class Connection {
* @return TRUE if session exists otherwise
* return FALSE
*/
- bool ProtocolVersion(uint8_t session_id, uint8_t& protocol_version);
-
+ bool ProtocolVersion(uint8_t session_id, uint8_t& protocol_version);
private:
/**
* @brief Current connection handler.
*/
- ConnectionHandler *connection_handler_;
+ ConnectionHandler* connection_handler_;
/**
* @brief Current connection handle.
@@ -289,7 +287,7 @@ class Connection {
/**
* @brief session/services map
*/
- SessionMap session_map_;
+ SessionMap session_map_;
mutable sync_primitives::Lock session_map_lock_;
@@ -297,7 +295,8 @@ class Connection {
* @brief monitor that closes connection if there is no traffic over it
*/
HeartBeatMonitor* heartbeat_monitor_;
- threads::Thread *heart_beat_monitor_thread_;
+ uint32_t heartbeat_timeout_;
+ threads::Thread* heart_beat_monitor_thread_;
DISALLOW_COPY_AND_ASSIGN(Connection);
};
diff --git a/src/components/connection_handler/include/connection_handler/connection_handler.h b/src/components/connection_handler/include/connection_handler/connection_handler.h
index 4a79658878..cb22b87bbb 100644
--- a/src/components/connection_handler/include/connection_handler/connection_handler.h
+++ b/src/components/connection_handler/include/connection_handler/connection_handler.h
@@ -33,6 +33,7 @@
#ifndef SRC_COMPONENTS_CONNECTION_HANDLER_INCLUDE_CONNECTION_HANDLER_CONNECTION_HANDLER_H_
#define SRC_COMPONENTS_CONNECTION_HANDLER_INCLUDE_CONNECTION_HANDLER_CONNECTION_HANDLER_H_
+#include "connection_handler/connection_handler_settings.h"
#include "transport_manager/transport_manager_listener.h"
#include "protocol_handler/session_observer.h"
#include "connection_handler/device.h"
@@ -45,14 +46,9 @@
*/
namespace connection_handler {
- enum CloseSessionReason {
- kCommon = 0,
- kFlood,
- kMalformed,
- kUnauthorizedApp
- };
+enum CloseSessionReason { kCommon = 0, kFlood, kMalformed, kUnauthorizedApp };
- class ConnectionHandlerObserver;
+class ConnectionHandlerObserver;
/**
* \class ConnectionHandler
@@ -65,14 +61,7 @@ class ConnectionHandler {
* \param observer Pointer to observer object.
**/
virtual void set_connection_handler_observer(
- ConnectionHandlerObserver *observer) = 0;
-
- /**
- * \brief Sets pointer to TransportManager.
- * \param transportManager Pointer to TransportManager object.
- **/
- virtual void set_transport_manager(
- transport_manager::TransportManager *transport_manager) = 0;
+ ConnectionHandlerObserver* observer) = 0;
virtual void StartTransportManager() = 0;
@@ -88,7 +77,8 @@ class ConnectionHandler {
virtual void CloseRevokedConnection(uint32_t connection_key) = 0;
/**
- * \brief Close all associated sessions and close the connection pointed by handle
+ * \brief Close all associated sessions and close the connection pointed by
+ * handle
*/
virtual void CloseConnection(ConnectionHandle connection_handle) = 0;
@@ -103,8 +93,8 @@ class ConnectionHandler {
* @param mac_address
* @return true if successfully
*/
- virtual bool GetDeviceID(const std::string &mac_address,
- DeviceHandle *device_handle) = 0;
+ virtual bool GetDeviceID(const std::string& mac_address,
+ DeviceHandle* device_handle) = 0;
/**
* Close session associated with the key
@@ -118,13 +108,13 @@ class ConnectionHandler {
uint8_t session_id,
CloseSessionReason close_reason) = 0;
- /**
- * @brief SendEndService allows to end up specific service.
- *
- * @param key application identifier whose service should be closed.
- *
- * @param service_type the service that should be closed.
- */
+ /**
+ * @brief SendEndService allows to end up specific service.
+ *
+ * @param key application identifier whose service should be closed.
+ *
+ * @param service_type the service that should be closed.
+ */
virtual void SendEndService(uint32_t key, uint8_t service_type) = 0;
/**
@@ -138,15 +128,22 @@ class ConnectionHandler {
* \brief Send heartbeat to mobile app
*/
virtual void SendHeartBeat(ConnectionHandle connection_handle,
- uint8_t session_id) = 0;
+ uint8_t session_id) = 0;
/**
* Sets heart beat timeout for specified session
* @param connection_key pair of connection and session id
- * @param timeout in seconds
+ * @param timeout in milliseconds
*/
virtual void SetHeartBeatTimeout(uint32_t connection_key,
- int32_t timeout) = 0;
+ uint32_t timeout) = 0;
+
+ /**
+ * \brief Keep connection associated with the key from being closed by
+ * heartbeat monitor
+ */
+ virtual void KeepConnectionAlive(uint32_t connection_key,
+ uint8_t session_id) = 0;
/**
* \brief binds protocol version with session
@@ -158,12 +155,42 @@ class ConnectionHandler {
virtual void BindProtocolVersionWithSession(uint32_t connection_key,
uint8_t protocol_version) = 0;
+ /**
+ * \brief information about given Connection Key.
+ * \param key Unique key used by other components as session identifier
+ * \param app_id Returned: ApplicationID
+ * \param sessions_list Returned: List of session keys
+ * \param device_id Returned: DeviceID
+ * \return int32_t -1 in case of error or 0 in case of success
+ */
+ virtual int32_t GetDataOnSessionKey(uint32_t key,
+ uint32_t* app_id,
+ std::list<int32_t>* sessions_list,
+ uint32_t* device_id) const = 0;
+ /**
+ * @brief GetConnectedDevicesMAC allows to obtain MAC adresses for all
+ * currently connected devices.
+ *
+ * @param device_macs collection of MAC adresses for connected devices.
+ */
+ virtual void GetConnectedDevicesMAC(
+ std::vector<std::string>& device_macs) const = 0;
+
+ /**
+ * \brief Connection handler settings getter
+ * \return pointer to connection handler settings class
+ */
+ virtual const ConnectionHandlerSettings& get_settings() const = 0;
+
+ virtual const protocol_handler::SessionObserver& get_session_observer() = 0;
+
+ virtual DevicesDiscoveryStarter& get_device_discovery_starter() = 0;
+
protected:
/**
* \brief Destructor
*/
- virtual ~ConnectionHandler() {
- }
+ virtual ~ConnectionHandler() {}
};
} // namespace connection_handler
diff --git a/src/components/connection_handler/include/connection_handler/connection_handler_impl.h b/src/components/connection_handler/include/connection_handler/connection_handler_impl.h
index 4ead673663..d061e55491 100644
--- a/src/components/connection_handler/include/connection_handler/connection_handler_impl.h
+++ b/src/components/connection_handler/include/connection_handler/connection_handler_impl.h
@@ -46,11 +46,11 @@
#include "connection_handler/connection.h"
#include "connection_handler/devices_discovery_starter.h"
#include "connection_handler/connection_handler.h"
+
#include "utils/logger.h"
#include "utils/macro.h"
#include "utils/lock.h"
#include "utils/stl_utils.h"
-#include "utils/singleton.h"
#include "utils/rwlock.h"
/**
@@ -65,53 +65,51 @@ namespace connection_handler {
* stores information regarding connections
* and sessions and provides it to AppManager.
*/
-class ConnectionHandlerImpl : public ConnectionHandler,
- public transport_manager::TransportManagerListenerEmpty,
- public protocol_handler::SessionObserver,
- public DevicesDiscoveryStarter,
- public utils::Singleton<ConnectionHandlerImpl> {
+class ConnectionHandlerImpl
+ : public ConnectionHandler,
+ public transport_manager::TransportManagerListenerEmpty,
+ public protocol_handler::SessionObserver,
+ public DevicesDiscoveryStarter {
public:
/**
+ * @brief ConnectionHandlerImpl
+ */
+ ConnectionHandlerImpl(const ConnectionHandlerSettings& settings,
+ transport_manager::TransportManager& tm);
+ /**
* \brief Destructor
*/
- virtual ~ConnectionHandlerImpl();
+ ~ConnectionHandlerImpl();
- void Stop();
+ void Stop();
/**
* \brief Sets observer pointer for connection_handler.
* \param observer Pointer to observer object.
*/
- virtual void set_connection_handler_observer(
- ConnectionHandlerObserver *observer);
-
- /**
- * \brief Sets pointer to TransportManager.
- * \param transport_mngr Pointer to TransportManager object.
- **/
- virtual void set_transport_manager(
- transport_manager::TransportManager *transport_mngr);
+ void set_connection_handler_observer(
+ ConnectionHandlerObserver* observer) OVERRIDE;
/**
* \brief Sets pointer to ProtocolHandler.
* \param protocol_handler Pointer to ProtocolHandler object.
**/
void set_protocol_handler(
- protocol_handler::ProtocolHandler *protocol_handler);
+ protocol_handler::ProtocolHandler* protocol_handler);
/**
* \brief Connects to all services of device
* \param deviceHandle Handle of device to connect to
*/
- virtual void ConnectToDevice(connection_handler::DeviceHandle device_handle);
+ void ConnectToDevice(connection_handler::DeviceHandle device_handle) OVERRIDE;
- virtual void ConnectToAllDevices();
+ void ConnectToAllDevices() OVERRIDE;
- virtual void StartTransportManager();
+ void StartTransportManager() OVERRIDE;
- virtual void OnDeviceListUpdated(
- const std::vector<transport_manager::DeviceInfo> &);
+ void OnDeviceListUpdated(
+ const std::vector<transport_manager::DeviceInfo>&) OVERRIDE;
- virtual void OnFindNewApplicationsRequest();
+ void OnFindNewApplicationsRequest() OVERRIDE;
/**
* \brief Available devices list updated.
@@ -121,87 +119,93 @@ class ConnectionHandlerImpl : public ConnectionHandler,
*
* \param DeviceList New list of available devices.
**/
- virtual void OnDeviceFound(const transport_manager::DeviceInfo &device_info);
- virtual void OnDeviceAdded(const transport_manager::DeviceInfo &device_info);
- virtual void OnDeviceRemoved(const transport_manager::DeviceInfo &device_info);
+ void OnDeviceFound(const transport_manager::DeviceInfo& device_info) OVERRIDE;
+ void OnDeviceAdded(const transport_manager::DeviceInfo& device_info) OVERRIDE;
+ void OnDeviceRemoved(
+ const transport_manager::DeviceInfo& device_info) OVERRIDE;
- virtual void OnScanDevicesFinished();
- virtual void OnScanDevicesFailed(
- const transport_manager::SearchDeviceError &error);
+ void OnScanDevicesFinished() OVERRIDE;
+ void OnScanDevicesFailed(
+ const transport_manager::SearchDeviceError& error) OVERRIDE;
/**
* \brief Notifies about established connection.
*
* \param connection_id ID of new connection.
**/
- virtual void OnConnectionEstablished(
- const transport_manager::DeviceInfo &device_info,
- const transport_manager::ConnectionUID &connection_id);
- virtual void OnConnectionFailed(
- const transport_manager::DeviceInfo &device_info,
- const transport_manager::ConnectError &error);
- virtual void OnConnectionClosed(
- transport_manager::ConnectionUID connection_id);
- virtual void OnConnectionClosedFailure(
- transport_manager::ConnectionUID connection_id,
- const transport_manager::DisconnectError &error);
- virtual void OnUnexpectedDisconnect(
- transport_manager::ConnectionUID connection_id,
- const transport_manager::CommunicationError &error);
- virtual void OnDeviceConnectionLost(
- const connection_handler::DeviceHandle &device,
- const transport_manager::DisconnectDeviceError &error);
+ void OnConnectionEstablished(
+ const transport_manager::DeviceInfo& device_info,
+ const transport_manager::ConnectionUID connection_id) OVERRIDE;
+ void OnConnectionFailed(
+ const transport_manager::DeviceInfo& device_info,
+ const transport_manager::ConnectError& error) OVERRIDE;
+ void OnConnectionClosed(
+ transport_manager::ConnectionUID connection_id) OVERRIDE;
+ void OnConnectionClosedFailure(
+ transport_manager::ConnectionUID connection_id,
+ const transport_manager::DisconnectError& error) OVERRIDE;
+ void OnUnexpectedDisconnect(
+ transport_manager::ConnectionUID connection_id,
+ const transport_manager::CommunicationError& error) OVERRIDE;
+ void OnDeviceConnectionLost(
+ const connection_handler::DeviceHandle& device,
+ const transport_manager::DisconnectDeviceError& error) OVERRIDE;
/**
* \brief Informs about failure during DisconnectDevice procedure of TM
* \param device Information about disconnected device
* \param error Information about possible reason of loosing connection
*/
- virtual void OnDisconnectFailed(
- const connection_handler::DeviceHandle &device,
- const transport_manager::DisconnectDeviceError &error);
+ void OnDisconnectFailed(
+ const connection_handler::DeviceHandle& device,
+ const transport_manager::DisconnectDeviceError& error) OVERRIDE;
/**
* \brief Callback function used by ProtocolHandler
* when Mobile Application initiates start of new session.
- * \param connection_handle Connection identifier within which session has to be started.
+ * \param connection_handle Connection identifier within which session has to
+ * be started.
* \param session_id Identifier of the session to be started
* \param service_type Type of service
* \param is_protected would be service protected
* \param hash_id pointer for session hash identifier
* \return uint32_t Id (number) of new session if successful, otherwise 0.
*/
- virtual uint32_t OnSessionStartedCallback(const transport_manager::ConnectionUID &connection_handle,
- const uint8_t session_id,
- const protocol_handler::ServiceType &service_type,
- const bool is_protected, uint32_t* hash_id);
+ virtual uint32_t OnSessionStartedCallback(
+ const transport_manager::ConnectionUID connection_handle,
+ const uint8_t session_id,
+ const protocol_handler::ServiceType& service_type,
+ const bool is_protected,
+ uint32_t* hash_id);
/**
* \brief Callback function used by ProtocolHandler
* when Mobile Application initiates session ending.
* \param connection_handle Connection identifier within which session exists
* \param sessionId Identifier of the session to be ended
- * \param hashCode Hash used only in second version of SmartDeviceLink protocol.
+ * \param hashCode Hash used only in second version of SmartDeviceLink
+ * protocol.
* If not equal to hash assigned to session on start then operation fails.
* \return uint32_t 0 if operation fails, session key otherwise
*/
- virtual uint32_t OnSessionEndedCallback(
- const transport_manager::ConnectionUID &connection_handle,
- const uint8_t session_id, const uint32_t &hashCode,
- const protocol_handler::ServiceType &service_type);
+ uint32_t OnSessionEndedCallback(
+ const transport_manager::ConnectionUID connection_handle,
+ const uint8_t session_id,
+ const uint32_t& hashCode,
+ const protocol_handler::ServiceType& service_type) OVERRIDE;
/**
* \brief Callback function used by ProtocolHandler
* when Mobile Application start message flood
* \param connection_key used by other components as application identifier
*/
- void OnApplicationFloodCallBack(const uint32_t &connection_key) OVERRIDE;
+ void OnApplicationFloodCallBack(const uint32_t& connection_key) OVERRIDE;
/**
* \brief Callback function used by ProtocolHandler
* when Mobile Application sends malformed message
* \param connection_key used by other components as application identifier
*/
- void OnMalformedMessageCallback(const uint32_t &connection_key) OVERRIDE;
+ void OnMalformedMessageCallback(const uint32_t& connection_key) OVERRIDE;
/**
* \brief Creates unique identifier of session (can be used as hash)
@@ -211,31 +215,20 @@ class ConnectionHandlerImpl : public ConnectionHandler,
* \param sessionId Identifier of the session
* \return int32_t Unique key for session
*/
- virtual uint32_t KeyFromPair(
- transport_manager::ConnectionUID connection_handle,
- uint8_t session_id);
+ uint32_t KeyFromPair(transport_manager::ConnectionUID connection_handle,
+ uint8_t session_id) const OVERRIDE;
/**
- * \brief Returns connection identifier and session number from given session key
+ * \brief Returns connection identifier and session number from given session
+ * key
* \param key Unique key used by other components as session identifier
- * \param connection_handle Returned: Connection identifier within which session exists
+ * \param connection_handle Returned: Connection identifier within which
+ * session exists
* \param sessionId Returned: Number of session
*/
- virtual void PairFromKey(uint32_t key,
- transport_manager::ConnectionUID *connection_handle,
- uint8_t *session_id);
-
- /**
- * \brief information about given Connection Key.
- * \param key Unique key used by other components as session identifier
- * \param app_id Returned: ApplicationID
- * \param sessions_list Returned: List of session keys
- * \param device_id Returned: DeviceID
- * \return int32_t -1 in case of error or 0 in case of success
- */
- virtual int32_t GetDataOnSessionKey(uint32_t key, uint32_t *app_id = 0,
- std::list<int32_t> *sessions_list = NULL,
- uint32_t *device_id = 0);
+ void PairFromKey(uint32_t key,
+ transport_manager::ConnectionUID* connection_handle,
+ uint8_t* session_id) const OVERRIDE;
/**
* \brief information about device
@@ -246,11 +239,21 @@ class ConnectionHandlerImpl : public ConnectionHandler,
* \param connection_type Returned: type of connection (USB, BT, etc.)
* \return int32_t -1 in case of error or 0 in case of success
*/
- virtual int32_t GetDataOnDeviceID(connection_handler::DeviceHandle device_handle,
- std::string *device_name = NULL,
- std::list<uint32_t> *applications_list = NULL,
- std::string *mac_address = NULL,
- std::string* connection_type = NULL);
+ int32_t GetDataOnDeviceID(connection_handler::DeviceHandle device_handle,
+ std::string* device_name = NULL,
+ std::list<uint32_t>* applications_list = NULL,
+ std::string* mac_address = NULL,
+ std::string* connection_type = NULL) const OVERRIDE;
+
+ /**
+ * @brief GetConnectedDevicesMAC allows to obtain MAC adresses for all
+ * currently connected devices.
+ *
+ * @param device_macs collection of MAC adresses for connected devices.
+ */
+ void GetConnectedDevicesMAC(
+ std::vector<std::string>& device_macs) const OVERRIDE;
+
#ifdef ENABLE_SECURITY
/**
* \brief Sets crypto context of connection
@@ -258,9 +261,8 @@ class ConnectionHandlerImpl : public ConnectionHandler,
* \param context SSLContext to be set
* \return \c SecurityQuery::ProtectSessionResult value
*/
- int SetSSLContext(
- const uint32_t &key,
- security_manager::SSLContext *context) OVERRIDE;
+ int SetSSLContext(const uint32_t& key,
+ security_manager::SSLContext* context) OVERRIDE;
/**
* \brief Gets crypto context of connection, use service_type to get NULL
@@ -270,17 +272,20 @@ class ConnectionHandlerImpl : public ConnectionHandler,
* \param service_type Type of service
* \return \ref SSLContext of connection
*/
- security_manager::SSLContext *GetSSLContext(
- const uint32_t &key,
- const protocol_handler::ServiceType &service_type) OVERRIDE;
+ security_manager::SSLContext* GetSSLContext(
+ const uint32_t& key,
+ const protocol_handler::ServiceType& service_type) OVERRIDE;
/**
* \brief Set protection flag to service in session by key
* \param key Unique key used by other components as session identifier
* \param service_type Type of service
*/
void SetProtectionFlag(
- const uint32_t &key,
- const protocol_handler::ServiceType &service_type) OVERRIDE;
+ const uint32_t& key,
+ const protocol_handler::ServiceType& service_type) OVERRIDE;
+
+ security_manager::SSLContext::HandshakeContext GetHandshakeContext(
+ uint32_t key) const OVERRIDE;
#endif // ENABLE_SECURITY
/**
@@ -289,40 +294,40 @@ class ConnectionHandlerImpl : public ConnectionHandler,
* \param device_handle
* \return true on sucess otherwise false.
*/
- virtual bool GetDeviceID(const std::string &mac_address,
- DeviceHandle *device_handle);
+ bool GetDeviceID(const std::string& mac_address,
+ DeviceHandle* device_handle) OVERRIDE;
/**
* \brief Method which should start devices discovering
*/
- virtual void StartDevicesDiscovery();
+ void StartDevicesDiscovery() OVERRIDE;
/**
* @brief Close the connection revoked by Policy
* @param connection_key pair of connection and session id
*/
- virtual void CloseRevokedConnection(uint32_t connection_key);
+ void CloseRevokedConnection(uint32_t connection_key) OVERRIDE;
/**
* @brief Close the connection pointed by handle
* @param connection_handle Connection unique id
*/
- virtual void CloseConnection(ConnectionHandle connection_handle) OVERRIDE;
+ void CloseConnection(ConnectionHandle connection_handle) OVERRIDE;
/**
* \brief Close session associated with the key
* \param key Unique key used by other components as session identifier
*/
- virtual void CloseSession(uint32_t key, CloseSessionReason close_reason);
+ void CloseSession(uint32_t key, CloseSessionReason close_reason) OVERRIDE;
/**
* \brief Function used by HearbeatMonitior to close session on HB timeout
* \param connection_handle Connection handler within which session exists
* \param session_id Identifier of the session to be ended
*/
- virtual void CloseSession(ConnectionHandle connection_handle,
- uint8_t session_id,
- CloseSessionReason close_reason);
+ void CloseSession(ConnectionHandle connection_handle,
+ uint8_t session_id,
+ CloseSessionReason close_reason) OVERRIDE;
/**
* \brief Function used by OnApplicationFloodCallback and
@@ -331,20 +336,20 @@ class ConnectionHandlerImpl : public ConnectionHandler,
* \param connection_handle Connection identifier within which session exists
* \param close_reason The reason of connection closing
*/
- virtual void CloseConnectionSessions(
- ConnectionHandle connection_handle, CloseSessionReason close_reason);
+ virtual void CloseConnectionSessions(ConnectionHandle connection_handle,
+ CloseSessionReason close_reason);
/**
* \brief Return count of session for specified connection
* \param connection_key pair of connection handle and session id
*/
- virtual uint32_t GetConnectionSessionsCount(uint32_t connection_key);
+ uint32_t GetConnectionSessionsCount(uint32_t connection_key) OVERRIDE;
/**
* \brief Send heartbeat message to mobile app
*/
- virtual void SendHeartBeat(ConnectionHandle connection_handle,
- uint8_t session_id);
+ void SendHeartBeat(ConnectionHandle connection_handle,
+ uint8_t session_id) OVERRIDE;
/**
* @brief SendEndService allows to end up specific service.
@@ -353,25 +358,25 @@ class ConnectionHandlerImpl : public ConnectionHandler,
*
* @param service_type the service that should be closed.
*/
- virtual void SendEndService(uint32_t key,
- uint8_t service_type);
+ void SendEndService(uint32_t key, uint8_t service_type) OVERRIDE;
/**
* \brief Start heartbeat for specified session
*
* \param connection_key pair of connection and session id
*/
- virtual void StartSessionHeartBeat(uint32_t connection_key);
+ void StartSessionHeartBeat(uint32_t connection_key) OVERRIDE;
/**
* Sets heart beat timeout for specified session
* @param connection_key pair of connection and session id
- * @param timeout in seconds
+ * @param timeout in milliseconds
*/
- virtual void SetHeartBeatTimeout(uint32_t connection_key, int32_t timeout);
+ void SetHeartBeatTimeout(uint32_t connection_key, uint32_t timeout) OVERRIDE;
/**
- * \brief Keep connection associated with the key from being closed by heartbeat monitor
+ * \brief Keep connection associated with the key from being closed by
+ * heartbeat monitor
*/
void KeepConnectionAlive(uint32_t connection_key, uint8_t session_id);
@@ -382,18 +387,20 @@ class ConnectionHandlerImpl : public ConnectionHandler,
* \param protocol_version contains protocol version of
* \registered application.
*/
- virtual void BindProtocolVersionWithSession(uint32_t connection_key,
- uint8_t protocol_version);
+ void BindProtocolVersionWithSession(uint32_t connection_key,
+ uint8_t protocol_version) OVERRIDE;
/**
- * \brief returns TRUE if session supports sending HEART BEAT ACK to mobile side
- * \param connection_handle Connection identifier whithin which session exists
+ * \brief returns TRUE if session supports sending HEART BEAT ACK to mobile
+ * side
+ * \param connection_handle Connection identifier whithin which session
+ * exists
* \param sessionId Identifier of the session
- * \return TRUE if session has protocol version which supports heartbeat otherwise returns FALSE
+ * \return TRUE if session has protocol version which supports heartbeat
+ * otherwise returns FALSE
*/
- virtual bool IsHeartBeatSupported(
- transport_manager::ConnectionUID connection_handle,
- uint8_t session_id);
+ bool IsHeartBeatSupported(transport_manager::ConnectionUID connection_handle,
+ uint8_t session_id) const OVERRIDE;
/**
* @brief returns protocol version which application supports
@@ -402,14 +409,21 @@ class ConnectionHandlerImpl : public ConnectionHandler,
* @param method writes value protocol version to protocol_version
* @return TRUE if session and connection exist otherwise returns FALSE
*/
- virtual bool ProtocolVersionUsed(uint32_t connection_id,
- uint8_t session_id, uint8_t& protocol_version);
- private:
- /**
- * \brief Default class constructor
- */
- ConnectionHandlerImpl();
+ bool ProtocolVersionUsed(uint32_t connection_id,
+ uint8_t session_id,
+ uint8_t& protocol_version) const OVERRIDE;
+
+ int32_t GetDataOnSessionKey(uint32_t key,
+ uint32_t* app_id,
+ std::list<int32_t>* sessions_list,
+ uint32_t* device_id) const OVERRIDE;
+
+ const ConnectionHandlerSettings& get_settings() const OVERRIDE;
+ const protocol_handler::SessionObserver& get_session_observer();
+ DevicesDiscoveryStarter& get_device_discovery_starter();
+
+ private:
/**
* \brief Disconnect application.
*
@@ -418,20 +432,20 @@ class ConnectionHandlerImpl : public ConnectionHandler,
**/
void RemoveConnection(const ConnectionHandle connection_handle);
- void OnConnectionEnded(
- const transport_manager::ConnectionUID &connection_id);
+ void OnConnectionEnded(const transport_manager::ConnectionUID connection_id);
+ const ConnectionHandlerSettings& settings_;
/**
* \brief Pointer to observer
*/
- ConnectionHandlerObserver *connection_handler_observer_;
+ ConnectionHandlerObserver* connection_handler_observer_;
/**
* \brief Pointer to TransportManager
*/
- transport_manager::TransportManager *transport_manager_;
+ transport_manager::TransportManager& transport_manager_;
- protocol_handler::ProtocolHandler *protocol_handler_;
+ protocol_handler::ProtocolHandler* protocol_handler_;
/**
* \brief List of devices
@@ -446,7 +460,7 @@ class ConnectionHandlerImpl : public ConnectionHandler,
/**
* \brief Lock for applications list
*/
- mutable sync_primitives::Lock connection_list_lock_;
+ mutable sync_primitives::RWLock connection_list_lock_;
mutable sync_primitives::RWLock connection_handler_observer_lock_;
/**
@@ -457,13 +471,13 @@ class ConnectionHandlerImpl : public ConnectionHandler,
#ifdef BUILD_TESTS
// Methods for test usage
public:
- ConnectionList &getConnectionList();
+ const DeviceMap& getDeviceList();
+ ConnectionList& getConnectionList();
void addDeviceConnection(
- const transport_manager::DeviceInfo &device_info,
- const transport_manager::ConnectionUID &connection_id);
+ const transport_manager::DeviceInfo& device_info,
+ const transport_manager::ConnectionUID connection_id);
#endif
private:
- FRIEND_BASE_SINGLETON_CLASS(ConnectionHandlerImpl);
DISALLOW_COPY_AND_ASSIGN(ConnectionHandlerImpl);
};
} // namespace connection_handler
diff --git a/src/components/connection_handler/include/connection_handler/connection_handler_observer.h b/src/components/connection_handler/include/connection_handler/connection_handler_observer.h
index 556a2dc4e2..54b8d3a92e 100644
--- a/src/components/connection_handler/include/connection_handler/connection_handler_observer.h
+++ b/src/components/connection_handler/include/connection_handler/connection_handler_observer.h
@@ -38,6 +38,10 @@
#include "connection_handler/connection_handler.h"
#include "protocol/service_type.h"
+#ifdef ENABLE_SECURITY
+#include "security_manager/ssl_context.h"
+#endif // ENABLE_SECURITY
+
/**
* \namespace connection_handler
* \brief SmartDeviceLink connection_handler namespace.
@@ -49,7 +53,7 @@ namespace connection_handler {
* \brief ConnectionHandlerObserver class
*/
class ConnectionHandlerObserver {
- public:
+ public:
/**
* \brief Available devices list updated.
*
@@ -59,7 +63,7 @@ class ConnectionHandlerObserver {
* \param DeviceList New list of available devices.
**/
virtual void OnDeviceListUpdated(
- const connection_handler::DeviceMap &device_list) = 0;
+ const connection_handler::DeviceMap& device_list) = 0;
/**
* @brief Reaction to "Find new applications" request
@@ -74,19 +78,20 @@ class ConnectionHandlerObserver {
* \param DeviceHandle Handle of removed device.
**/
virtual void RemoveDevice(
- const connection_handler::DeviceHandle &device_handle) = 0;
+ const connection_handler::DeviceHandle& device_handle) = 0;
/**
* \brief Callback function used by connection_handler
* when Mobile Application initiates start of new service.
- * \param deviceHandle Device identifier within which session has to be started.
+ * \param deviceHandle Device identifier within which session has to be
+ * started.
* \param sessionKey Key of started session.
* \param type Established service type
*/
virtual bool OnServiceStartedCallback(
- const connection_handler::DeviceHandle &device_handle,
- const int32_t &session_key,
- const protocol_handler::ServiceType &type) = 0;
+ const connection_handler::DeviceHandle& device_handle,
+ const int32_t& session_key,
+ const protocol_handler::ServiceType& type) = 0;
/**
* \brief Callback function used by connection_handler
@@ -100,12 +105,15 @@ class ConnectionHandlerObserver {
const protocol_handler::ServiceType& type,
const connection_handler::CloseSessionReason& close_reason) = 0;
+#ifdef ENABLE_SECURITY
+ virtual security_manager::SSLContext::HandshakeContext GetHandshakeContext(
+ uint32_t key) const = 0;
+#endif // ENABLE_SECURITY
protected:
/**
* \brief Destructor
*/
- virtual ~ConnectionHandlerObserver() {
- }
+ virtual ~ConnectionHandlerObserver() {}
};
} // namespace connection_handler
diff --git a/src/components/connection_handler/include/connection_handler/device.h b/src/components/connection_handler/include/connection_handler/device.h
index c37c4cc62c..cee0bf8875 100644
--- a/src/components/connection_handler/include/connection_handler/device.h
+++ b/src/components/connection_handler/include/connection_handler/device.h
@@ -58,8 +58,10 @@ class Device {
/**
* \brief Class constructor
*/
- Device(DeviceHandle device_handle, const std::string &user_friendly_name,
- const std::string &mac_address = "", const std::string& connection_type = "");
+ Device(DeviceHandle device_handle,
+ const std::string& user_friendly_name,
+ const std::string& mac_address = "",
+ const std::string& connection_type = "");
/**
* \brief Returns device handle
diff --git a/src/components/connection_handler/include/connection_handler/devices_discovery_starter.h b/src/components/connection_handler/include/connection_handler/devices_discovery_starter.h
index bd5885a273..0bb3da0772 100644
--- a/src/components/connection_handler/include/connection_handler/devices_discovery_starter.h
+++ b/src/components/connection_handler/include/connection_handler/devices_discovery_starter.h
@@ -49,7 +49,7 @@ class DevicesDiscoveryStarter {
/**
* \brief Method which should start devices discoveryng
*/
- virtual void StartDevicesDiscovery()=0;
+ virtual void StartDevicesDiscovery() = 0;
/**
* \brief Connects to all services of device
@@ -64,8 +64,7 @@ class DevicesDiscoveryStarter {
/**
* \brief Destructor
*/
- virtual ~DevicesDiscoveryStarter() {
- }
+ virtual ~DevicesDiscoveryStarter() {}
};
} // namespace connection_handler
diff --git a/src/components/connection_handler/include/connection_handler/heartbeat_monitor.h b/src/components/connection_handler/include/connection_handler/heartbeat_monitor.h
index 0233e269dd..f6ef9a9829 100644
--- a/src/components/connection_handler/include/connection_handler/heartbeat_monitor.h
+++ b/src/components/connection_handler/include/connection_handler/heartbeat_monitor.h
@@ -48,10 +48,9 @@ class Connection;
/*
* Starts hearbeat timer for session and when it elapses closes it
*/
-class HeartBeatMonitor: public threads::ThreadDelegate {
+class HeartBeatMonitor : public threads::ThreadDelegate {
public:
- HeartBeatMonitor(int32_t heartbeat_timeout_seconds,
- Connection *connection);
+ HeartBeatMonitor(uint32_t heartbeat_timeout_mseconds, Connection* connection);
/**
* Thread procedure.
@@ -73,34 +72,38 @@ class HeartBeatMonitor: public threads::ThreadDelegate {
* \brief Thread exit procedure.
*/
virtual void exitThreadMain();
-
- void set_heartbeat_timeout_seconds(int32_t timeout, uint8_t session_id);
+ /**
+ * @brief Update heart beat timeout for session
+ * @param timeout contains timeout for updating
+ * @param session_id contain id session for which update timeout
+ * timeout
+ **/
+ void set_heartbeat_timeout_milliseconds(uint32_t timeout, uint8_t session_id);
private:
-
- // \brief Heartbeat timeout, should be read from profile
- int32_t default_heartbeat_timeout_;
+ // \brief Heartbeat timeout
+ uint32_t default_heartbeat_timeout_;
// \brief Connection that must be closed when timeout elapsed
- Connection *connection_;
+ Connection* connection_;
- //Default HeartBeat cycle timeout (in miliseconds)
+ // Default HeartBeat cycle timeout (in miliseconds)
static const int32_t kDefaultCycleTimeout = 100;
class SessionState {
- public:
- explicit SessionState(int32_t heartbeat_timeout_seconds = 0);
- void UpdateTimeout(int32_t heartbeat_timeout_seconds);
- void PrepareToClose();
- bool IsReadyToClose() const;
- void KeepAlive();
- bool HasTimeoutElapsed();
- private:
- void RefreshExpiration();
-
- int32_t heartbeat_timeout_seconds_;
- TimevalStruct heartbeat_expiration;
- bool is_heartbeat_sent;
-
+ public:
+ explicit SessionState(uint32_t heartbeat_timeout_mseconds = 0);
+ void UpdateTimeout(uint32_t heartbeat_timeout_mseconds);
+ void PrepareToClose();
+ bool IsReadyToClose() const;
+ void KeepAlive();
+ bool HasTimeoutElapsed();
+
+ private:
+ void RefreshExpiration();
+
+ uint32_t heartbeat_timeout_mseconds_;
+ TimevalStruct heartbeat_expiration_;
+ bool is_heartbeat_sent_;
};
// \brief monitored sessions collection
@@ -108,7 +111,7 @@ class HeartBeatMonitor: public threads::ThreadDelegate {
typedef std::map<uint8_t, SessionState> SessionMap;
SessionMap sessions_;
- sync_primitives::Lock sessions_list_lock_; // recurcive
+ sync_primitives::Lock sessions_list_lock_; // recurcive
sync_primitives::Lock main_thread_lock_;
mutable sync_primitives::Lock heartbeat_timeout_seconds_lock_;
sync_primitives::ConditionalVariable heartbeat_monitor_;
@@ -120,6 +123,6 @@ class HeartBeatMonitor: public threads::ThreadDelegate {
DISALLOW_COPY_AND_ASSIGN(HeartBeatMonitor);
};
-} // namespace connection_handler
+} // namespace connection_handler
#endif // SRC_COMPONENTS_CONNECTION_HANDLER_INCLUDE_HEARTBEAT_MONITOR_H_
diff --git a/src/components/connection_handler/src/connection.cc b/src/components/connection_handler/src/connection.cc
index de8c7edb03..7bb54d4493 100644
--- a/src/components/connection_handler/src/connection.cc
+++ b/src/components/connection_handler/src/connection.cc
@@ -37,7 +37,6 @@
#include "connection_handler/connection.h"
#include "connection_handler/connection_handler.h"
#include "protocol_handler/protocol_packet.h"
-#include "config_profile/profile.h"
#include "utils/logger.h"
#include "utils/macro.h"
@@ -46,7 +45,6 @@
#include "security_manager/security_manager.h"
#endif // ENABLE_SECURITY
-
/**
* \namespace connection_handler
* \brief SmartDeviceLink ConnectionHandler namespace.
@@ -55,19 +53,21 @@ namespace connection_handler {
CREATE_LOGGERPTR_GLOBAL(logger_, "ConnectionHandler")
-Service *Session::FindService(const protocol_handler::ServiceType &service_type) {
+Service* Session::FindService(
+ const protocol_handler::ServiceType& service_type) {
ServiceList::iterator service_it =
std::find(service_list.begin(), service_list.end(), service_type);
- if(service_it != service_list.end()){
+ if (service_it != service_list.end()) {
return &(*service_it);
}
return NULL;
}
-const Service *Session::FindService(const protocol_handler::ServiceType &service_type) const {
+const Service* Session::FindService(
+ const protocol_handler::ServiceType& service_type) const {
ServiceList::const_iterator service_it =
std::find(service_list.begin(), service_list.end(), service_type);
- if(service_it != service_list.end()){
+ if (service_it != service_list.end()) {
return &(*service_it);
}
return NULL;
@@ -75,18 +75,19 @@ const Service *Session::FindService(const protocol_handler::ServiceType &service
Connection::Connection(ConnectionHandle connection_handle,
DeviceHandle connection_device_handle,
- ConnectionHandler *connection_handler,
- int32_t heartbeat_timeout)
- : connection_handler_(connection_handler),
- connection_handle_(connection_handle),
- connection_device_handle_(connection_device_handle),
- session_map_lock_(true) {
+ ConnectionHandler* connection_handler,
+ uint32_t heartbeat_timeout)
+ : connection_handler_(connection_handler)
+ , connection_handle_(connection_handle)
+ , connection_device_handle_(connection_device_handle)
+ , session_map_lock_(true)
+ , heartbeat_timeout_(heartbeat_timeout) {
LOG4CXX_AUTO_TRACE(logger_);
DCHECK(connection_handler_);
- heartbeat_monitor_ = new HeartBeatMonitor(heartbeat_timeout, this);
- heart_beat_monitor_thread_ = threads::CreateThread("HeartBeatMonitor",
- heartbeat_monitor_);
+ heartbeat_monitor_ = new HeartBeatMonitor(heartbeat_timeout_, this);
+ heart_beat_monitor_thread_ =
+ threads::CreateThread("HeartBeatMonitor", heartbeat_monitor_);
heart_beat_monitor_thread_->start();
}
@@ -103,7 +104,7 @@ Connection::~Connection() {
// Returns 0 if that key not found
namespace {
template <class T>
-uint32_t findGap(const std::map<unsigned char, T> &map) {
+uint32_t findGap(const std::map<unsigned char, T>& map) {
for (uint32_t i = 1; i <= UCHAR_MAX; ++i) {
if (map.find(i) == map.end()) {
return i;
@@ -143,7 +144,7 @@ bool Connection::AddNewService(uint8_t session_id,
const bool request_protection) {
// Ignore wrong services
if (protocol_handler::kControl == service_type ||
- protocol_handler::kInvalidServiceType == service_type ) {
+ protocol_handler::kInvalidServiceType == service_type) {
LOG4CXX_WARN(logger_, "Wrong service " << static_cast<int>(service_type));
return false;
}
@@ -154,19 +155,23 @@ bool Connection::AddNewService(uint8_t session_id,
LOG4CXX_WARN(logger_, "Session not found in this connection!");
return false;
}
- Session &session = session_it->second;
- Service *service = session.FindService(service_type);
+ Session& session = session_it->second;
+ Service* service = session.FindService(service_type);
// if service already exists
if (service) {
#ifdef ENABLE_SECURITY
- if(!request_protection) {
- LOG4CXX_WARN(logger_, "Session " << static_cast<int>(session_id) <<
- " already has unprotected service "<< static_cast<int>(service_type));
+ if (!request_protection) {
+ LOG4CXX_WARN(logger_,
+ "Session " << static_cast<int>(session_id)
+ << " already has unprotected service "
+ << static_cast<int>(service_type));
return false;
}
if (service->is_protected_) {
- LOG4CXX_WARN(logger_, "Session " << static_cast<int>(session_id) <<
- " already has protected service "<< static_cast<int>(service_type));
+ LOG4CXX_WARN(logger_,
+ "Session " << static_cast<int>(session_id)
+ << " already has protected service "
+ << static_cast<int>(service_type));
return false;
}
// For unproteced service could be start protection
@@ -187,18 +192,18 @@ inline bool is_incorrect_for_remove_service(
// Control type is internal part of session
protocol_handler::kControl == service_type ||
// RPC and bulk service is necessary part of session
- protocol_handler::kRpc == service_type ||
+ protocol_handler::kRpc == service_type ||
protocol_handler::kBulk == service_type ||
// Invalid service is not part of session
protocol_handler::kInvalidServiceType == service_type;
}
-bool Connection::RemoveService(
- uint8_t session_id, protocol_handler::ServiceType service_type) {
+bool Connection::RemoveService(uint8_t session_id,
+ protocol_handler::ServiceType service_type) {
// Ignore wrong and required for Session services
if (is_incorrect_for_remove_service(service_type)) {
- LOG4CXX_WARN(logger_, "Could not remove service "
- << static_cast<int>(service_type));
+ LOG4CXX_WARN(logger_,
+ "Could not remove service " << static_cast<int>(service_type));
return false;
}
sync_primitives::AutoLock lock(session_map_lock_);
@@ -209,12 +214,13 @@ bool Connection::RemoveService(
return false;
}
- ServiceList &service_list = session_it->second.service_list;
+ ServiceList& service_list = session_it->second.service_list;
ServiceList::iterator service_it =
find(service_list.begin(), service_list.end(), service_type);
if (service_list.end() == service_it) {
- LOG4CXX_WARN(logger_, "Session " << session_id << " didn't established"
- " service " << service_type);
+ LOG4CXX_WARN(logger_,
+ "Session " << session_id << " didn't established"
+ " service " << service_type);
return false;
}
service_list.erase(service_it);
@@ -223,20 +229,21 @@ bool Connection::RemoveService(
#ifdef ENABLE_SECURITY
int Connection::SetSSLContext(uint8_t session_id,
- security_manager::SSLContext *context) {
+ security_manager::SSLContext* context) {
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.find(session_id);
if (session_it == session_map_.end()) {
LOG4CXX_WARN(logger_, "Session not found in this connection!");
return security_manager::SecurityManager::ERROR_INTERNAL;
}
- Session &session = session_it->second;
+ Session& session = session_it->second;
session.ssl_context = context;
return security_manager::SecurityManager::ERROR_SUCCESS;
}
-security_manager::SSLContext *Connection::GetSSLContext(
- const uint8_t session_id, const protocol_handler::ServiceType &service_type) const {
+security_manager::SSLContext* Connection::GetSSLContext(
+ const uint8_t session_id,
+ const protocol_handler::ServiceType& service_type) const {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::const_iterator session_it = session_map_.find(session_id);
@@ -244,11 +251,11 @@ security_manager::SSLContext *Connection::GetSSLContext(
LOG4CXX_WARN(logger_, "Session not found in this connection!");
return NULL;
}
- const Session &session = session_it->second;
+ const Session& session = session_it->second;
// for control services return current SSLContext value
if (protocol_handler::kControl == service_type)
return session.ssl_context;
- const Service *service = session.FindService(service_type);
+ const Service* service = session.FindService(service_type);
if (!service) {
LOG4CXX_WARN(logger_, "Service not found in this session!");
return NULL;
@@ -260,7 +267,8 @@ security_manager::SSLContext *Connection::GetSSLContext(
}
void Connection::SetProtectionFlag(
- const uint8_t session_id, const protocol_handler::ServiceType &service_type) {
+ const uint8_t session_id,
+ const protocol_handler::ServiceType& service_type) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.find(session_id);
@@ -268,8 +276,8 @@ void Connection::SetProtectionFlag(
LOG4CXX_WARN(logger_, "Session not found in this connection!");
return;
}
- Session &session = session_it->second;
- Service *service = session.FindService(service_type);
+ Session& session = session_it->second;
+ Service* service = session.FindService(service_type);
if (!service) {
LOG4CXX_WARN(logger_, "Service not found in this session!");
return;
@@ -277,11 +285,11 @@ void Connection::SetProtectionFlag(
service->is_protected_ = true;
// Rpc and bulk shall be protected as one service
if (service->service_type == protocol_handler::kRpc) {
- Service *service_bulk = session.FindService(protocol_handler::kBulk);
+ Service* service_bulk = session.FindService(protocol_handler::kBulk);
DCHECK(service_bulk);
service_bulk->is_protected_ = true;
} else if (service->service_type == protocol_handler::kBulk) {
- Service *service_rpc = session.FindService(protocol_handler::kRpc);
+ Service* service_rpc = session.FindService(protocol_handler::kRpc);
DCHECK(service_rpc);
service_rpc->is_protected_ = true;
}
@@ -292,7 +300,7 @@ ConnectionHandle Connection::connection_handle() const {
return connection_handle_;
}
-DeviceHandle Connection::connection_device_handle() {
+DeviceHandle Connection::connection_device_handle() const {
return connection_device_handle_;
}
@@ -313,25 +321,24 @@ void Connection::CloseSession(uint8_t session_id) {
size = session_map_.size();
}
- connection_handler_->CloseSession(connection_handle_,
- session_id,
- connection_handler::kCommon);
+ connection_handler_->CloseSession(
+ connection_handle_, session_id, connection_handler::kCommon);
- //Close connection if it is last session
+ // Close connection if it is last session
if (1 == size) {
connection_handler_->CloseConnection(connection_handle_);
}
}
-void Connection::UpdateProtocolVersionSession(
- uint8_t session_id, uint8_t protocol_version) {
+void Connection::UpdateProtocolVersionSession(uint8_t session_id,
+ uint8_t protocol_version) {
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.find(session_id);
if (session_map_.end() == session_it) {
LOG4CXX_WARN(logger_, "Session not found in this connection!");
return;
}
- Session &session = session_it->second;
+ Session& session = session_it->second;
session.protocol_version = protocol_version;
}
@@ -343,20 +350,21 @@ bool Connection::SupportHeartBeat(uint8_t session_id) {
LOG4CXX_WARN(logger_, "Session not found in this connection!");
return false;
}
- Session &session = session_it->second;
-
- return ((::protocol_handler::PROTOCOL_VERSION_3 == session.protocol_version ||
- ::protocol_handler::PROTOCOL_VERSION_4 == session.protocol_version) &&
- (profile::Profile::instance()->heart_beat_timeout()));
+ Session& session = session_it->second;
+ return (
+ (::protocol_handler::PROTOCOL_VERSION_3 == session.protocol_version ||
+ ::protocol_handler::PROTOCOL_VERSION_4 == session.protocol_version) &&
+ (0 != heartbeat_timeout_));
}
-bool Connection::ProtocolVersion(uint8_t session_id, uint8_t& protocol_version) {
+bool Connection::ProtocolVersion(uint8_t session_id,
+ uint8_t& protocol_version) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(session_map_lock_);
SessionMap::iterator session_it = session_map_.find(session_id);
if (session_map_.end() == session_it) {
LOG4CXX_WARN(logger_, "Session not found in this connection!");
- return false;
+ return false;
}
protocol_version = (session_it->second).protocol_version;
return true;
@@ -374,8 +382,8 @@ void Connection::KeepAlive(uint8_t session_id) {
heartbeat_monitor_->KeepAlive(session_id);
}
-void Connection::SetHeartBeatTimeout(int32_t timeout, uint8_t session_id) {
- heartbeat_monitor_->set_heartbeat_timeout_seconds(timeout, session_id);
+void Connection::SetHeartBeatTimeout(uint32_t timeout, uint8_t session_id) {
+ heartbeat_monitor_->set_heartbeat_timeout_milliseconds(timeout, session_id);
}
} // namespace connection_handler
diff --git a/src/components/connection_handler/src/connection_handler_impl.cc b/src/components/connection_handler/src/connection_handler_impl.cc
index 0fdb0c68bf..d8c05e6e6e 100644
--- a/src/components/connection_handler/src/connection_handler_impl.cc
+++ b/src/components/connection_handler/src/connection_handler_impl.cc
@@ -38,18 +38,11 @@
#include "connection_handler/connection_handler_impl.h"
#include "transport_manager/info.h"
-#include "config_profile/profile.h"
#ifdef ENABLE_SECURITY
#include "security_manager/security_manager.h"
#endif // ENABLE_SECURITY
-namespace {
-int32_t HeartBeatTimeout() {
- return profile::Profile::instance()->heart_beat_timeout();
-}
-} // namespace
-
/**
* \namespace connection_handler
* \brief SmartDeviceLink ConnectionHandler namespace.
@@ -67,14 +60,16 @@ transport_manager::ConnectionUID ConnectionUIDFromHandle(
return transport_manager::ConnectionUID(handle);
}
-ConnectionHandlerImpl::ConnectionHandlerImpl()
- : connection_handler_observer_(NULL),
- transport_manager_(NULL),
- protocol_handler_(NULL),
- connection_list_lock_(true),
- connection_handler_observer_lock_(),
- connection_list_deleter_(&connection_list_) {
-}
+ConnectionHandlerImpl::ConnectionHandlerImpl(
+ const ConnectionHandlerSettings& settings,
+ transport_manager::TransportManager& tm)
+ : settings_(settings)
+ , connection_handler_observer_(NULL)
+ , transport_manager_(tm)
+ , protocol_handler_(NULL)
+ , connection_list_lock_()
+ , connection_handler_observer_lock_()
+ , connection_list_deleter_(&connection_list_) {}
ConnectionHandlerImpl::~ConnectionHandlerImpl() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -90,9 +85,10 @@ void ConnectionHandlerImpl::Stop() {
}
void ConnectionHandlerImpl::set_connection_handler_observer(
- ConnectionHandlerObserver *observer) {
- LOG4CXX_DEBUG(logger_, "ConnectionHandlerImpl::set_connection_handler_observer() "
- << observer);
+ ConnectionHandlerObserver* observer) {
+ LOG4CXX_DEBUG(logger_,
+ "ConnectionHandlerImpl::set_connection_handler_observer() "
+ << observer);
sync_primitives::AutoWriteLock write_lock(connection_handler_observer_lock_);
if (!observer) {
LOG4CXX_WARN(logger_, "Set Null pointer to observer.");
@@ -100,21 +96,11 @@ void ConnectionHandlerImpl::set_connection_handler_observer(
connection_handler_observer_ = observer;
}
-void ConnectionHandlerImpl::set_transport_manager(
- transport_manager::TransportManager *transport_mngr) {
- LOG4CXX_DEBUG(logger_, "ConnectionHandlerImpl::set_transport_manager() "
- << transport_mngr);
- if (!transport_mngr) {
- LOG4CXX_ERROR(logger_, "Null pointer to TransportManager.");
- return;
- }
- transport_manager_ = transport_mngr;
-}
-
void ConnectionHandlerImpl::set_protocol_handler(
- protocol_handler::ProtocolHandler *protocol_handler) {
- LOG4CXX_DEBUG(logger_, "ConnectionHandlerImpl::set_protocol_handler()"
- << protocol_handler);
+ protocol_handler::ProtocolHandler* protocol_handler) {
+ LOG4CXX_DEBUG(logger_,
+ "ConnectionHandlerImpl::set_protocol_handler()"
+ << protocol_handler);
if (!protocol_handler) {
LOG4CXX_WARN(logger_, "Set Null pointer to protocol handler.");
}
@@ -143,13 +129,14 @@ void ConnectionHandlerImpl::OnDeviceFound(
}
void ConnectionHandlerImpl::OnDeviceAdded(
- const transport_manager::DeviceInfo &device_info) {
+ const transport_manager::DeviceInfo& device_info) {
LOG4CXX_AUTO_TRACE(logger_);
device_list_.insert(
- DeviceMap::value_type(
- device_info.device_handle(),
- Device(device_info.device_handle(), device_info.name(),
- device_info.mac_address(), device_info.connection_type())));
+ DeviceMap::value_type(device_info.device_handle(),
+ Device(device_info.device_handle(),
+ device_info.name(),
+ device_info.mac_address(),
+ device_info.connection_type())));
sync_primitives::AutoReadLock read_lock(connection_handler_observer_lock_);
if (connection_handler_observer_) {
connection_handler_observer_->OnDeviceListUpdated(device_list_);
@@ -157,7 +144,7 @@ void ConnectionHandlerImpl::OnDeviceAdded(
}
void ConnectionHandlerImpl::OnDeviceRemoved(
- const transport_manager::DeviceInfo &device_info) {
+ const transport_manager::DeviceInfo& device_info) {
LOG4CXX_AUTO_TRACE(logger_);
// Device has been removed. Perform all needed actions.
// 1. Delete all the connections and sessions of this device
@@ -166,9 +153,10 @@ void ConnectionHandlerImpl::OnDeviceRemoved(
std::vector<ConnectionHandle> connections_to_remove;
{
- sync_primitives::AutoLock lock(connection_list_lock_);
+ sync_primitives::AutoReadLock lock(connection_list_lock_);
for (ConnectionList::iterator it = connection_list_.begin();
- it != connection_list_.end(); ++it) {
+ it != connection_list_.end();
+ ++it) {
if (device_info.device_handle() ==
(*it).second->connection_device_handle()) {
connections_to_remove.push_back((*it).first);
@@ -185,7 +173,6 @@ void ConnectionHandlerImpl::OnDeviceRemoved(
sync_primitives::AutoReadLock read_lock(connection_handler_observer_lock_);
if (connection_handler_observer_) {
connection_handler_observer_->RemoveDevice(device_info.device_handle());
- connection_handler_observer_->OnDeviceListUpdated(device_list_);
}
}
@@ -194,13 +181,13 @@ void ConnectionHandlerImpl::OnScanDevicesFinished() {
}
void ConnectionHandlerImpl::OnScanDevicesFailed(
- const transport_manager::SearchDeviceError &error) {
+ const transport_manager::SearchDeviceError& error) {
LOG4CXX_WARN(logger_, "Scan devices failed. " << error.text());
}
void ConnectionHandlerImpl::OnConnectionEstablished(
- const transport_manager::DeviceInfo &device_info,
- const transport_manager::ConnectionUID &connection_id) {
+ const transport_manager::DeviceInfo& device_info,
+ const transport_manager::ConnectionUID connection_id) {
LOG4CXX_AUTO_TRACE(logger_);
DeviceMap::iterator it = device_list_.find(device_info.device_handle());
@@ -208,18 +195,20 @@ void ConnectionHandlerImpl::OnConnectionEstablished(
LOG4CXX_ERROR(logger_, "Unknown device!");
return;
}
- LOG4CXX_DEBUG(logger_, "Add Connection #" << connection_id << " to the list.");
- sync_primitives::AutoLock lock(connection_list_lock_);
- connection_list_.insert(
- ConnectionList::value_type(
- connection_id,
- new Connection(connection_id, device_info.device_handle(), this,
- HeartBeatTimeout())));
+ LOG4CXX_DEBUG(logger_,
+ "Add Connection #" << connection_id << " to the list.");
+ sync_primitives::AutoWriteLock lock(connection_list_lock_);
+ connection_list_.insert(ConnectionList::value_type(
+ connection_id,
+ new Connection(connection_id,
+ device_info.device_handle(),
+ this,
+ get_settings().heart_beat_timeout())));
}
void ConnectionHandlerImpl::OnConnectionFailed(
- const transport_manager::DeviceInfo &device_info,
- const transport_manager::ConnectError &error) {
+ const transport_manager::DeviceInfo& device_info,
+ const transport_manager::ConnectError& error) {
// TODO(PV): implement
LOG4CXX_ERROR(logger_, "Failed connecting.");
}
@@ -233,87 +222,79 @@ void ConnectionHandlerImpl::OnConnectionClosed(
void ConnectionHandlerImpl::OnConnectionClosedFailure(
transport_manager::ConnectionUID connection_id,
- const transport_manager::DisconnectError &error) {
+ const transport_manager::DisconnectError& error) {
// TODO(PV): implement
LOG4CXX_ERROR(logger_, "ConnectionHandlerImpl::OnConnectionClosedFailure");
}
void ConnectionHandlerImpl::OnUnexpectedDisconnect(
transport_manager::ConnectionUID connection_id,
- const transport_manager::CommunicationError &error) {
- LOG4CXX_ERROR(logger_, "ConnectionHandlerImpl::OnUnexpectedDisconnect");
+ const transport_manager::CommunicationError& error) {
+ LOG4CXX_AUTO_TRACE(logger_);
OnConnectionEnded(connection_id);
}
void ConnectionHandlerImpl::OnDeviceConnectionLost(
- const transport_manager::DeviceHandle &device,
- const transport_manager::DisconnectDeviceError &error) {
+ const transport_manager::DeviceHandle& device,
+ const transport_manager::DisconnectDeviceError& error) {
// TODO(PV): implement
LOG4CXX_ERROR(logger_, "Lost connection with device " << device);
}
void ConnectionHandlerImpl::OnDisconnectFailed(
- const transport_manager::DeviceHandle &device,
- const transport_manager::DisconnectDeviceError &error) {
+ const transport_manager::DeviceHandle& device,
+ const transport_manager::DisconnectDeviceError& error) {
// TODO(PV): implement
LOG4CXX_ERROR(logger_, "Trying to Disconnect device failed.");
}
void ConnectionHandlerImpl::RemoveConnection(
const ConnectionHandle connection_handle) {
- LOG4CXX_INFO(logger_, "ConnectionHandlerImpl::RemoveConnection()");
+ LOG4CXX_AUTO_TRACE(logger_);
OnConnectionEnded(connection_handle);
}
#ifdef ENABLE_SECURITY
-namespace {
-bool AllowProtection(const protocol_handler::ServiceType &service_type,
- const bool is_protected) {
- if (is_protected) {
- // Check deliver-specific services (which shall not be protected)
- const std::list<int> force_unprotected_list =
- profile::Profile::instance()->ReadIntContainer(
- "Security Manager", "ForceUnprotectedService", NULL);
- if (std::find(force_unprotected_list.begin(), force_unprotected_list.end(), service_type) !=
- force_unprotected_list.end()) {
- LOG4CXX_ERROR(logger_, "Service " << static_cast<int>(service_type)
- << " is forbidden to be protected");
- return false;
- }
- } else {
- // Check deliver-specific services (which shall be protected)
- const std::list<int> force_protected_list =
- profile::Profile::instance()->ReadIntContainer(
- "Security Manager", "ForceProtectedService", NULL);
- if (std::find(force_protected_list.begin(), force_protected_list.end(), service_type) !=
- force_protected_list.end()) {
- LOG4CXX_ERROR(logger_, "Service " << static_cast<int>(service_type)
- << " shall be protected");
- return false;
- }
+bool AllowProtection(const ConnectionHandlerSettings& settings,
+ const protocol_handler::ServiceType& service_type,
+ const bool is_protected) {
+ const std::vector<int>& force_unprotected_list =
+ is_protected ? settings.force_unprotected_service()
+ : settings.force_protected_service();
+
+ if (std::find(force_unprotected_list.begin(),
+ force_unprotected_list.end(),
+ service_type) != force_unprotected_list.end()) {
+ LOG4CXX_ERROR(logger_,
+ "Service " << static_cast<int>(service_type)
+ << " shall be protected");
+ return false;
}
+ LOG4CXX_DEBUG(logger_,
+ "Service " << static_cast<int>(service_type) << " allowed");
return true;
}
-} // namespace
#endif // ENABLE_SECURITY
uint32_t ConnectionHandlerImpl::OnSessionStartedCallback(
- const transport_manager::ConnectionUID &connection_handle,
- const uint8_t session_id, const protocol_handler::ServiceType &service_type,
- const bool is_protected, uint32_t* hash_id) {
+ const transport_manager::ConnectionUID connection_handle,
+ const uint8_t session_id,
+ const protocol_handler::ServiceType& service_type,
+ const bool is_protected,
+ uint32_t* hash_id) {
LOG4CXX_AUTO_TRACE(logger_);
if (hash_id) {
*hash_id = protocol_handler::HASH_ID_WRONG;
}
#ifdef ENABLE_SECURITY
- if (!AllowProtection(service_type, is_protected)) {
+ if (!AllowProtection(get_settings(), service_type, is_protected)) {
return 0;
}
#endif // ENABLE_SECURITY
- sync_primitives::AutoLock lock(connection_list_lock_);
+ sync_primitives::AutoReadLock lock(connection_list_lock_);
ConnectionList::iterator it = connection_list_.find(connection_handle);
if (connection_list_.end() == it) {
LOG4CXX_ERROR(logger_, "Unknown connection!");
@@ -321,7 +302,7 @@ uint32_t ConnectionHandlerImpl::OnSessionStartedCallback(
}
uint32_t new_session_id = 0;
- Connection *connection = it->second;
+ Connection* connection = it->second;
if ((0 == session_id) && (protocol_handler::kRpc == service_type)) {
new_session_id = connection->AddNewSession();
if (0 == new_session_id) {
@@ -333,12 +314,13 @@ uint32_t ConnectionHandlerImpl::OnSessionStartedCallback(
}
} else { // Could be create new service or protected exists one
if (!connection->AddNewService(session_id, service_type, is_protected)) {
- LOG4CXX_ERROR(logger_, "Couldn't establish "
+ LOG4CXX_ERROR(logger_,
+ "Couldn't establish "
#ifdef ENABLE_SECURITY
- << (is_protected ? "protected" : "non-protected")
+ << (is_protected ? "protected" : "non-protected")
#endif // ENABLE_SECURITY
- << " service " << static_cast<int>(service_type)
- << " for session " << static_cast<int>(session_id));
+ << " service " << static_cast<int>(service_type)
+ << " for session " << static_cast<int>(session_id));
return 0;
}
new_session_id = session_id;
@@ -350,8 +332,10 @@ uint32_t ConnectionHandlerImpl::OnSessionStartedCallback(
if (connection_handler_observer_) {
const uint32_t session_key = KeyFromPair(connection_handle, new_session_id);
const bool success = connection_handler_observer_->OnServiceStartedCallback(
- connection->connection_device_handle(), session_key, service_type);
+ connection->connection_device_handle(), session_key, service_type);
if (!success) {
+ LOG4CXX_WARN(logger_,
+ "Service starting forbidden by connection_handler_observer");
if (protocol_handler::kRpc == service_type) {
connection->RemoveSession(new_session_id);
} else {
@@ -364,7 +348,7 @@ uint32_t ConnectionHandlerImpl::OnSessionStartedCallback(
}
void ConnectionHandlerImpl::OnApplicationFloodCallBack(
- const uint32_t &connection_key) {
+ const uint32_t& connection_key) {
LOG4CXX_AUTO_TRACE(logger_);
transport_manager::ConnectionUID connection_handle = 0;
@@ -381,7 +365,7 @@ void ConnectionHandlerImpl::OnApplicationFloodCallBack(
}
void ConnectionHandlerImpl::OnMalformedMessageCallback(
- const uint32_t &connection_key) {
+ const uint32_t& connection_key) {
LOG4CXX_AUTO_TRACE(logger_);
transport_manager::ConnectionUID connection_handle = 0;
@@ -389,17 +373,18 @@ void ConnectionHandlerImpl::OnMalformedMessageCallback(
PairFromKey(connection_key, &connection_handle, &session_id);
LOG4CXX_INFO(logger_, "Disconnect malformed messaging application");
- CloseConnectionSessions(connection_handle, kCommon);
+ CloseConnectionSessions(connection_handle, kMalformed);
CloseConnection(connection_handle);
}
uint32_t ConnectionHandlerImpl::OnSessionEndedCallback(
- const uint32_t &connection_handle, const uint8_t session_id,
- const uint32_t &hashCode,
- const protocol_handler::ServiceType &service_type) {
+ const transport_manager::ConnectionUID connection_handle,
+ const uint8_t session_id,
+ const uint32_t& hashCode,
+ const protocol_handler::ServiceType& service_type) {
LOG4CXX_AUTO_TRACE(logger_);
- connection_list_lock_.Acquire();
+ connection_list_lock_.AcquireForReading();
ConnectionList::iterator it = connection_list_.find(connection_handle);
if (connection_list_.end() == it) {
LOG4CXX_WARN(logger_, "Unknown connection!");
@@ -408,32 +393,37 @@ uint32_t ConnectionHandlerImpl::OnSessionEndedCallback(
std::pair<int32_t, Connection*> connection_item = *it;
connection_list_lock_.Release();
- Connection *connection = connection_item.second;
+ Connection* connection = connection_item.second;
const uint32_t session_key = KeyFromPair(connection_handle, session_id);
if (protocol_handler::kRpc == service_type) {
- LOG4CXX_INFO(logger_, "Session " << static_cast<uint32_t>(session_id)
- << " to be removed");
+ LOG4CXX_INFO(logger_,
+ "Session " << static_cast<uint32_t>(session_id)
+ << " to be removed");
// old version of protocol doesn't support hash
if (protocol_handler::HASH_ID_NOT_SUPPORTED != hashCode) {
if (protocol_handler::HASH_ID_WRONG == hashCode ||
session_key != hashCode) {
- LOG4CXX_WARN(logger_, "Wrong hash_id for session "
- << static_cast<uint32_t>(session_id));
+ LOG4CXX_WARN(logger_,
+ "Wrong hash_id for session "
+ << static_cast<uint32_t>(session_id));
return 0;
}
}
if (!connection->RemoveSession(session_id)) {
- LOG4CXX_WARN(logger_, "Couldn't remove session "
- << static_cast<uint32_t>(session_id));
+ LOG4CXX_WARN(logger_,
+ "Couldn't remove session "
+ << static_cast<uint32_t>(session_id));
return 0;
}
} else {
- LOG4CXX_INFO(logger_, "Service " << static_cast<uint32_t>(service_type)
- << " to be removed");
+ LOG4CXX_INFO(logger_,
+ "Service " << static_cast<uint32_t>(service_type)
+ << " to be removed");
if (!connection->RemoveService(session_id, service_type)) {
- LOG4CXX_WARN(logger_, "Couldn't remove service "
- << static_cast<uint32_t>(service_type));
+ LOG4CXX_WARN(logger_,
+ "Couldn't remove service "
+ << static_cast<uint32_t>(service_type));
return 0;
}
}
@@ -447,100 +437,110 @@ uint32_t ConnectionHandlerImpl::OnSessionEndedCallback(
}
uint32_t ConnectionHandlerImpl::KeyFromPair(
- transport_manager::ConnectionUID connection_handle, uint8_t session_id) {
+ transport_manager::ConnectionUID connection_handle,
+ uint8_t session_id) const {
const uint32_t key = connection_handle | (session_id << 16);
- LOG4CXX_DEBUG(logger_, "Key for ConnectionHandle:"
- << static_cast<uint32_t>(connection_handle)
- << " Session:" << static_cast<uint32_t>(session_id)
- << " is: " << static_cast<uint32_t>(key));
+ LOG4CXX_DEBUG(logger_,
+ "Key for ConnectionHandle:"
+ << static_cast<uint32_t>(connection_handle)
+ << " Session:" << static_cast<uint32_t>(session_id)
+ << " is: " << static_cast<uint32_t>(key));
if (protocol_handler::HASH_ID_WRONG == key) {
- LOG4CXX_ERROR(logger_, "Connection key is WRONG_HASH_ID "
+ LOG4CXX_ERROR(logger_,
+ "Connection key is WRONG_HASH_ID "
"(session id shall be greater 0)");
}
return key;
}
-void ConnectionHandlerImpl::PairFromKey(uint32_t key,
- uint32_t *connection_handle,
- uint8_t *session_id) {
+void ConnectionHandlerImpl::PairFromKey(
+ uint32_t key,
+ transport_manager::ConnectionUID* connection_handle,
+ uint8_t* session_id) const {
*connection_handle = key & 0xFF00FFFF;
*session_id = key >> 16;
- LOG4CXX_DEBUG(logger_, "ConnectionHandle:"
- << static_cast<int32_t>(*connection_handle)
- << " Session:" << static_cast<int32_t>(*session_id)
- << " for key:" << static_cast<int32_t>(key));
+ LOG4CXX_DEBUG(
+ logger_,
+ "ConnectionHandle:" << static_cast<int32_t>(*connection_handle)
+ << " Session:" << static_cast<int32_t>(*session_id)
+ << " for key:" << static_cast<int32_t>(key));
}
int32_t ConnectionHandlerImpl::GetDataOnSessionKey(
- uint32_t key, uint32_t *app_id, std::list<int32_t> *sessions_list,
- uint32_t *device_id) {
+ uint32_t key,
+ uint32_t* app_id,
+ std::list<int32_t>* sessions_list,
+ uint32_t* device_id) const {
LOG4CXX_AUTO_TRACE(logger_);
- int32_t result = -1;
+ const int32_t error_result = -1;
transport_manager::ConnectionUID conn_handle = 0;
uint8_t session_id = 0;
PairFromKey(key, &conn_handle, &session_id);
- ConnectionList::iterator it = connection_list_.find(conn_handle);
+ ConnectionList::const_iterator it = connection_list_.find(conn_handle);
if (connection_list_.end() == it) {
- LOG4CXX_ERROR(logger_, "Unknown connection!");
- return result;
+ LOG4CXX_ERROR(logger_, "Connection not found for key: " << key);
+ return error_result;
+ }
+
+ const Connection& connection = *it->second;
+ const SessionMap session_map = connection.session_map();
+ if (0 == session_id || session_map.end() == session_map.find(session_id)) {
+ LOG4CXX_ERROR(logger_,
+ "Session not found in connection: "
+ << static_cast<int32_t>(conn_handle));
+ return error_result;
}
- Connection &connection = *it->second;
if (device_id) {
*device_id = connection.connection_device_handle();
}
-
+ if (app_id) {
+ *app_id = KeyFromPair(conn_handle, session_id);
+ }
if (sessions_list) {
sessions_list->clear();
- }
- if (0 == session_id) {
- LOG4CXX_WARN(
- logger_,
- "No sessions in connection " << static_cast<int32_t>(conn_handle));
- if (app_id) {
- *app_id = 0;
- }
- } else {
- if (app_id) {
- *app_id = KeyFromPair(conn_handle, session_id);
+ SessionMap::const_iterator session_it = session_map.begin();
+ for (; session_map.end() != session_it; ++session_it) {
+ sessions_list->push_back(KeyFromPair(conn_handle, it->first));
}
+ }
- LOG4CXX_INFO(logger_, "Connection "
- << static_cast<int32_t>(conn_handle)
- << " has " << connection.session_map().size()
- << " sessions.");
+ LOG4CXX_INFO(logger_,
+ "Connection " << static_cast<int32_t>(conn_handle) << " has "
+ << session_map.size() << " sessions.");
+ return 0;
+}
- if (sessions_list) {
- const SessionMap session_map = connection.session_map();
- for (SessionMap::const_iterator session_it = session_map.begin();
- session_map.end() != session_it; ++session_it) {
- sessions_list->push_back(KeyFromPair(conn_handle, it->first));
- }
- }
+const ConnectionHandlerSettings& ConnectionHandlerImpl::get_settings() const {
+ return settings_;
+}
- result = 0;
- }
+const protocol_handler::SessionObserver&
+ConnectionHandlerImpl::get_session_observer() {
+ return *this;
+}
- return result;
+DevicesDiscoveryStarter& ConnectionHandlerImpl::get_device_discovery_starter() {
+ return *this;
}
struct CompareMAC {
- explicit CompareMAC(const std::string &mac) : mac_(mac) {}
- bool operator() (const DeviceMap::value_type &device) {
+ explicit CompareMAC(const std::string& mac) : mac_(mac) {}
+ bool operator()(const DeviceMap::value_type& device) {
return strcasecmp(device.second.mac_address().c_str(), mac_.c_str()) == 0;
}
+
private:
std::string mac_;
};
-bool ConnectionHandlerImpl::GetDeviceID(const std::string &mac_address,
- DeviceHandle *device_handle) {
- DeviceMap::const_iterator it = std::find_if(device_list_.begin(),
- device_list_.end(),
- CompareMAC(mac_address));
+bool ConnectionHandlerImpl::GetDeviceID(const std::string& mac_address,
+ DeviceHandle* device_handle) {
+ DeviceMap::const_iterator it = std::find_if(
+ device_list_.begin(), device_list_.end(), CompareMAC(mac_address));
if (it != device_list_.end()) {
if (device_handle) {
*device_handle = it->first;
@@ -552,13 +552,14 @@ bool ConnectionHandlerImpl::GetDeviceID(const std::string &mac_address,
int32_t ConnectionHandlerImpl::GetDataOnDeviceID(
DeviceHandle device_handle,
- std::string *device_name,
- std::list<uint32_t> *applications_list, std::string *mac_address,
- std::string* connection_type ) {
+ std::string* device_name,
+ std::list<uint32_t>* applications_list,
+ std::string* mac_address,
+ std::string* connection_type) const {
LOG4CXX_AUTO_TRACE(logger_);
int32_t result = -1;
- DeviceMap::iterator it = device_list_.find(device_handle);
+ DeviceMap::const_iterator it = device_list_.find(device_handle);
if (device_list_.end() == it) {
LOG4CXX_ERROR(logger_, "Device not found!");
return result;
@@ -572,16 +573,19 @@ int32_t ConnectionHandlerImpl::GetDataOnDeviceID(
}
if (applications_list) {
applications_list->clear();
- sync_primitives::AutoLock connection_list_lock(connection_list_lock_);
- for (ConnectionList::iterator itr = connection_list_.begin();
- itr != connection_list_.end(); ++itr) {
+ sync_primitives::AutoReadLock connection_list_lock(connection_list_lock_);
+ for (ConnectionList::const_iterator itr = connection_list_.begin();
+ itr != connection_list_.end();
+ ++itr) {
if (device_handle == (*itr).second->connection_device_handle()) {
- const SessionMap &session_map = (itr->second)->session_map();
+ const SessionMap& session_map = (itr->second)->session_map();
for (SessionMap::const_iterator session_it = session_map.begin();
- session_map.end() != session_it; ++session_it) {
- const transport_manager::ConnectionUID &connection_handle = itr->first;
+ session_map.end() != session_it;
+ ++session_it) {
+ const transport_manager::ConnectionUID connection_handle = itr->first;
const uint32_t session_id = session_it->first;
- const uint32_t application_id = KeyFromPair(connection_handle, session_id);
+ const uint32_t application_id =
+ KeyFromPair(connection_handle, session_id);
applications_list->push_back(application_id);
}
}
@@ -596,67 +600,80 @@ int32_t ConnectionHandlerImpl::GetDataOnDeviceID(
return result;
}
+
+void ConnectionHandlerImpl::GetConnectedDevicesMAC(
+ std::vector<std::string>& device_macs) const {
+ DeviceMap::const_iterator first = device_list_.begin();
+ DeviceMap::const_iterator last = device_list_.end();
+
+ while (first != last) {
+ device_macs.push_back((*first).second.mac_address());
+ ++first;
+ }
+}
+
#ifdef ENABLE_SECURITY
int ConnectionHandlerImpl::SetSSLContext(
- const uint32_t &key, security_manager::SSLContext *context) {
+ const uint32_t& key, security_manager::SSLContext* context) {
LOG4CXX_AUTO_TRACE(logger_);
transport_manager::ConnectionUID connection_handle = 0;
uint8_t session_id = 0;
PairFromKey(key, &connection_handle, &session_id);
- sync_primitives::AutoLock lock(connection_list_lock_);
+ sync_primitives::AutoReadLock lock(connection_list_lock_);
ConnectionList::iterator it = connection_list_.find(connection_handle);
if (connection_list_.end() == it) {
LOG4CXX_ERROR(logger_, "Unknown connection!");
return security_manager::SecurityManager::ERROR_INTERNAL;
}
- Connection &connection = *it->second;
+ Connection& connection = *it->second;
return connection.SetSSLContext(session_id, context);
}
-security_manager::SSLContext *ConnectionHandlerImpl::GetSSLContext(
- const uint32_t &key, const protocol_handler::ServiceType &service_type) {
+security_manager::SSLContext* ConnectionHandlerImpl::GetSSLContext(
+ const uint32_t& key, const protocol_handler::ServiceType& service_type) {
LOG4CXX_AUTO_TRACE(logger_);
transport_manager::ConnectionUID connection_handle = 0;
uint8_t session_id = 0;
PairFromKey(key, &connection_handle, &session_id);
- sync_primitives::AutoLock lock(connection_list_lock_);
+ sync_primitives::AutoReadLock lock(connection_list_lock_);
ConnectionList::iterator it = connection_list_.find(connection_handle);
if (connection_list_.end() == it) {
LOG4CXX_ERROR(logger_, "Unknown connection!");
return NULL;
}
- Connection &connection = *it->second;
+ Connection& connection = *it->second;
return connection.GetSSLContext(session_id, service_type);
}
void ConnectionHandlerImpl::SetProtectionFlag(
- const uint32_t &key, const protocol_handler::ServiceType &service_type) {
+ const uint32_t& key, const protocol_handler::ServiceType& service_type) {
LOG4CXX_AUTO_TRACE(logger_);
transport_manager::ConnectionUID connection_handle = 0;
uint8_t session_id = 0;
PairFromKey(key, &connection_handle, &session_id);
- sync_primitives::AutoLock lock(connection_list_lock_);
+ sync_primitives::AutoReadLock lock(connection_list_lock_);
ConnectionList::iterator it = connection_list_.find(connection_handle);
if (connection_list_.end() == it) {
LOG4CXX_ERROR(logger_, "Unknown connection!");
return;
}
- Connection &connection = *it->second;
+ Connection& connection = *it->second;
connection.SetProtectionFlag(session_id, service_type);
}
+
+security_manager::SSLContext::HandshakeContext
+ConnectionHandlerImpl::GetHandshakeContext(uint32_t key) const {
+ return connection_handler_observer_->GetHandshakeContext(key);
+}
#endif // ENABLE_SECURITY
void ConnectionHandlerImpl::StartDevicesDiscovery() {
LOG4CXX_AUTO_TRACE(logger_);
- if (NULL == transport_manager_) {
- LOG4CXX_ERROR(logger_, "Null pointer to TransportManager.");
- return;
- }
- transport_manager_->SearchDevices();
+ transport_manager_.SearchDevices();
sync_primitives::AutoReadLock read_lock(connection_handler_observer_lock_);
if (connection_handler_observer_) {
connection_handler_observer_->OnDeviceListUpdated(device_list_);
@@ -668,37 +685,29 @@ void ConnectionHandlerImpl::ConnectToDevice(
connection_handler::DeviceMap::const_iterator it_in;
it_in = device_list_.find(device_handle);
if (device_list_.end() != it_in) {
- LOG4CXX_INFO_EXT(logger_,
- "Connecting to device with handle " << device_handle);
- if (transport_manager_) {
- if (transport_manager::E_SUCCESS
- != transport_manager_->ConnectDevice(device_handle)) {
- LOG4CXX_WARN(logger_, "Can't connect to device");
- }
+ LOG4CXX_INFO(logger_, "Connecting to device with handle " << device_handle);
+ if (transport_manager::E_SUCCESS !=
+ transport_manager_.ConnectDevice(device_handle)) {
+ LOG4CXX_WARN(logger_, "Can't connect to device");
} else {
- LOG4CXX_ERROR(logger_, "Null pointer to TransportManager.");
+ LOG4CXX_ERROR(
+ logger_,
+ "Application Manager wanted to connect to non-existing device");
}
- } else {
- LOG4CXX_ERROR(
- logger_, "Application Manager wanted to connect to non-existing device");
}
}
void ConnectionHandlerImpl::ConnectToAllDevices() {
- for (DeviceMap::iterator i = device_list_.begin(); i != device_list_.end(); ++i) {
+ for (DeviceMap::iterator i = device_list_.begin(); i != device_list_.end();
+ ++i) {
connection_handler::DeviceHandle device_handle = i->first;
ConnectToDevice(device_handle);
}
}
void ConnectionHandlerImpl::StartTransportManager() {
- LOG4CXX_INFO(logger_, "ConnectionHandlerImpl::StartTransportManager()");
- if (NULL == transport_manager_) {
- LOG4CXX_ERROR(logger_, "Null pointer to TransportManager.");
- return;
- }
-
- transport_manager_->Visibility(true);
+ LOG4CXX_AUTO_TRACE(logger_);
+ transport_manager_.Visibility(true);
}
void ConnectionHandlerImpl::CloseRevokedConnection(uint32_t connection_key) {
@@ -714,15 +723,11 @@ void ConnectionHandlerImpl::CloseRevokedConnection(uint32_t connection_key) {
void ConnectionHandlerImpl::CloseConnection(
ConnectionHandle connection_handle) {
LOG4CXX_AUTO_TRACE(logger_);
- if (!transport_manager_) {
- LOG4CXX_ERROR(logger_, "Null pointer to TransportManager.");
- return;
- }
transport_manager::ConnectionUID connection_uid =
ConnectionUIDFromHandle(connection_handle);
- transport_manager_->DisconnectForce(connection_uid);
+ transport_manager_.DisconnectForce(connection_uid);
- sync_primitives::AutoLock connection_list_lock(connection_list_lock_);
+ sync_primitives::AutoWriteLock connection_list_lock(connection_list_lock_);
ConnectionList::iterator connection_list_itr =
connection_list_.find(connection_uid);
@@ -733,11 +738,12 @@ void ConnectionHandlerImpl::CloseConnection(
uint32_t ConnectionHandlerImpl::GetConnectionSessionsCount(
uint32_t connection_key) {
+ LOG4CXX_AUTO_TRACE(logger_);
uint32_t connection_handle = 0;
uint8_t session_id = 0;
PairFromKey(connection_key, &connection_handle, &session_id);
- sync_primitives::AutoLock lock(connection_list_lock_);
+ sync_primitives::AutoReadLock lock(connection_list_lock_);
ConnectionList::iterator itr = connection_list_.find(connection_handle);
if (connection_list_.end() != itr) {
@@ -760,7 +766,8 @@ void ConnectionHandlerImpl::CloseSession(ConnectionHandle connection_handle,
uint8_t session_id,
CloseSessionReason close_reason) {
LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(logger_, "Closing session with id: " << session_id);
+ LOG4CXX_DEBUG(logger_,
+ "Closing session with id: " << static_cast<int>(session_id));
// In case of malformed message the connection should be broke up without
// any other notification to mobile.
@@ -769,11 +776,11 @@ void ConnectionHandlerImpl::CloseSession(ConnectionHandle connection_handle,
}
transport_manager::ConnectionUID connection_id =
- ConnectionUIDFromHandle(connection_handle);
+ ConnectionUIDFromHandle(connection_handle);
SessionMap session_map;
{
- sync_primitives::AutoLock connection_list_lock(connection_list_lock_);
+ sync_primitives::AutoReadLock connection_list_lock(connection_list_lock_);
ConnectionList::iterator connection_list_itr =
connection_list_.find(connection_id);
@@ -781,8 +788,8 @@ void ConnectionHandlerImpl::CloseSession(ConnectionHandle connection_handle,
session_map = connection_list_itr->second->session_map();
connection_list_itr->second->RemoveSession(session_id);
} else {
- LOG4CXX_ERROR(logger_, "Connection with id: " << connection_id
- << " not found");
+ LOG4CXX_ERROR(logger_,
+ "Connection with id: " << connection_id << " not found");
return;
}
}
@@ -796,40 +803,42 @@ void ConnectionHandlerImpl::CloseSession(ConnectionHandle connection_handle,
SessionMap::const_iterator session_map_itr = session_map.find(session_id);
if (session_map_itr != session_map.end()) {
const uint32_t session_key = KeyFromPair(connection_id, session_id);
- const Session &session = session_map_itr->second;
- const ServiceList &service_list = session.service_list;
+ const Session& session = session_map_itr->second;
+ const ServiceList& service_list = session.service_list;
- ServiceList::const_iterator service_list_itr = service_list.begin();
- for (;service_list_itr != service_list.end(); ++service_list_itr) {
+ ServiceList::const_reverse_iterator service_list_itr =
+ service_list.rbegin();
+ for (; service_list_itr != service_list.rend(); ++service_list_itr) {
const protocol_handler::ServiceType service_type =
service_list_itr->service_type;
connection_handler_observer_->OnServiceEndedCallback(
session_key, service_type, close_reason);
}
} else {
- LOG4CXX_ERROR(logger_, "Session with id: "
- << session_id << " not found");
+ LOG4CXX_ERROR(logger_, "Session with id: " << session_id << " not found");
return;
}
- LOG4CXX_DEBUG(logger_, "Session with id: " << session_id
- << " has been closed successfully");
+
+ LOG4CXX_DEBUG(logger_,
+ "Session with id: " << session_id
+ << " has been closed successfully");
}
void ConnectionHandlerImpl::CloseConnectionSessions(
ConnectionHandle connection_handle, CloseSessionReason close_reason) {
-
LOG4CXX_AUTO_TRACE(logger_);
transport_manager::ConnectionUID connection_id =
ConnectionUIDFromHandle(connection_handle);
- LOG4CXX_DEBUG(logger_, "Closing all sessions for connection with id: "
- << connection_id);
+ LOG4CXX_DEBUG(
+ logger_,
+ "Closing all sessions for connection with id: " << connection_id);
typedef std::vector<uint8_t> SessionIdVector;
SessionIdVector session_id_vector;
{
- sync_primitives::AutoLock connection_list_lock(connection_list_lock_);
+ sync_primitives::AutoReadLock connection_list_lock(connection_list_lock_);
ConnectionList::iterator connection_list_itr =
connection_list_.find(connection_id);
@@ -837,41 +846,43 @@ void ConnectionHandlerImpl::CloseConnectionSessions(
const SessionMap session_map = connection_list_itr->second->session_map();
SessionMap::const_iterator session_map_itr = session_map.begin();
- for (;session_map_itr != session_map.end(); ++session_map_itr) {
+ for (; session_map_itr != session_map.end(); ++session_map_itr) {
session_id_vector.push_back(session_map_itr->first);
}
} else {
- LOG4CXX_ERROR(logger_, "Connection with id: " << connection_id
- << " not found");
+ LOG4CXX_ERROR(logger_,
+ "Connection with id: " << connection_id << " not found");
return;
}
}
SessionIdVector::const_iterator session_id_itr = session_id_vector.begin();
- for(;session_id_itr != session_id_vector.end(); ++session_id_itr) {
+ for (; session_id_itr != session_id_vector.end(); ++session_id_itr) {
CloseSession(connection_handle, *session_id_itr, close_reason);
}
session_id_vector.clear();
- LOG4CXX_DEBUG(logger_, "All sessions for connection with id: " << connection_id
- << " have been closed successfully");
+ LOG4CXX_DEBUG(logger_,
+ "All sessions for connection with id: "
+ << connection_id << " have been closed successfully");
}
-void ConnectionHandlerImpl::SendEndService(uint32_t key,
- uint8_t service_type) {
+void ConnectionHandlerImpl::SendEndService(uint32_t key, uint8_t service_type) {
if (protocol_handler_) {
uint32_t connection_handle = 0;
uint8_t session_id = 0;
PairFromKey(key, &connection_handle, &session_id);
- protocol_handler_->SendEndService(connection_handle, session_id, service_type);
+ protocol_handler_->SendEndService(
+ connection_handle, session_id, service_type);
}
}
void ConnectionHandlerImpl::StartSessionHeartBeat(uint32_t connection_key) {
+ LOG4CXX_AUTO_TRACE(logger_);
uint32_t connection_handle = 0;
uint8_t session_id = 0;
PairFromKey(connection_key, &connection_handle, &session_id);
- sync_primitives::AutoLock lock(connection_list_lock_);
+ sync_primitives::AutoReadLock lock(connection_list_lock_);
ConnectionList::iterator it = connection_list_.find(connection_handle);
if (connection_list_.end() != it) {
it->second->StartHeartBeat(session_id);
@@ -879,11 +890,12 @@ void ConnectionHandlerImpl::StartSessionHeartBeat(uint32_t connection_key) {
}
void ConnectionHandlerImpl::SetHeartBeatTimeout(uint32_t connection_key,
- int32_t timeout) {
+ uint32_t timeout) {
+ LOG4CXX_AUTO_TRACE(logger_);
uint32_t connection_handle = 0;
uint8_t session_id = 0;
PairFromKey(connection_key, &connection_handle, &session_id);
- sync_primitives::AutoLock lock(connection_list_lock_);
+ sync_primitives::AutoReadLock lock(connection_list_lock_);
ConnectionList::iterator it = connection_list_.find(connection_handle);
if (connection_list_.end() != it) {
it->second->SetHeartBeatTimeout(timeout, session_id);
@@ -901,8 +913,8 @@ void ConnectionHandlerImpl::SendHeartBeat(ConnectionHandle connection_handle,
void ConnectionHandlerImpl::KeepConnectionAlive(uint32_t connection_key,
uint8_t session_id) {
- sync_primitives::AutoLock lock(connection_list_lock_);
-
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoReadLock lock(connection_list_lock_);
ConnectionList::iterator it = connection_list_.find(connection_key);
if (connection_list_.end() != it) {
it->second->KeepAlive(session_id);
@@ -910,11 +922,11 @@ void ConnectionHandlerImpl::KeepConnectionAlive(uint32_t connection_key,
}
void ConnectionHandlerImpl::OnConnectionEnded(
- const transport_manager::ConnectionUID &connection_id) {
- LOG4CXX_INFO(logger_, "Delete Connection: " << static_cast<int32_t>(connection_id)
- << " from the list.");
-
- connection_list_lock_.Acquire();
+ const transport_manager::ConnectionUID connection_id) {
+ LOG4CXX_INFO(logger_,
+ "Delete Connection: " << static_cast<int32_t>(connection_id)
+ << " from the list.");
+ connection_list_lock_.AcquireForWriting();
ConnectionList::iterator itr = connection_list_.find(connection_id);
if (connection_list_.end() == itr) {
LOG4CXX_ERROR(logger_, "Connection not found!");
@@ -929,11 +941,15 @@ void ConnectionHandlerImpl::OnConnectionEnded(
const SessionMap session_map = connection->session_map();
for (SessionMap::const_iterator session_it = session_map.begin();
- session_map.end() != session_it; ++session_it) {
- const uint32_t session_key = KeyFromPair(connection_id, session_it->first);
- const ServiceList &service_list = session_it->second.service_list;
- for (ServiceList::const_iterator service_it = service_list.begin(), end =
- service_list.end(); service_it != end; ++service_it) {
+ session_map.end() != session_it;
+ ++session_it) {
+ const uint32_t session_key =
+ KeyFromPair(connection_id, session_it->first);
+ const ServiceList& service_list = session_it->second.service_list;
+ for (ServiceList::const_iterator service_it = service_list.begin(),
+ end = service_list.end();
+ service_it != end;
+ ++service_it) {
connection_handler_observer_->OnServiceEndedCallback(
session_key, service_it->service_type, CloseSessionReason::kCommon);
}
@@ -948,7 +964,7 @@ void ConnectionHandlerImpl::BindProtocolVersionWithSession(
uint8_t session_id = 0;
PairFromKey(connection_key, &connection_handle, &session_id);
- sync_primitives::AutoLock lock(connection_list_lock_);
+ sync_primitives::AutoReadLock lock(connection_list_lock_);
ConnectionList::iterator it = connection_list_.find(connection_handle);
if (connection_list_.end() != it) {
it->second->UpdateProtocolVersionSession(session_id, protocol_version);
@@ -956,11 +972,12 @@ void ConnectionHandlerImpl::BindProtocolVersionWithSession(
}
bool ConnectionHandlerImpl::IsHeartBeatSupported(
- transport_manager::ConnectionUID connection_handle,uint8_t session_id) {
+ transport_manager::ConnectionUID connection_handle,
+ uint8_t session_id) const {
LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock lock(connection_list_lock_);
+ sync_primitives::AutoReadLock lock(connection_list_lock_);
uint32_t connection = static_cast<uint32_t>(connection_handle);
- ConnectionList::iterator it = connection_list_.find(connection);
+ ConnectionList::const_iterator it = connection_list_.find(connection);
if (connection_list_.end() == it) {
LOG4CXX_WARN(logger_, "Connection not found !");
return false;
@@ -968,11 +985,13 @@ bool ConnectionHandlerImpl::IsHeartBeatSupported(
return it->second->SupportHeartBeat(session_id);
}
-bool ConnectionHandlerImpl::ProtocolVersionUsed(uint32_t connection_id,
- uint8_t session_id, uint8_t& protocol_version) {
+bool ConnectionHandlerImpl::ProtocolVersionUsed(
+ uint32_t connection_id,
+ uint8_t session_id,
+ uint8_t& protocol_version) const {
LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock lock(connection_list_lock_);
- ConnectionList::iterator it = connection_list_.find(connection_id);
+ sync_primitives::AutoReadLock lock(connection_list_lock_);
+ ConnectionList::const_iterator it = connection_list_.find(connection_id);
if (connection_list_.end() != it) {
return it->second->ProtocolVersion(session_id, protocol_version);
}
@@ -981,13 +1000,17 @@ bool ConnectionHandlerImpl::ProtocolVersionUsed(uint32_t connection_id,
}
#ifdef BUILD_TESTS
-ConnectionList &ConnectionHandlerImpl::getConnectionList() {
+ConnectionList& ConnectionHandlerImpl::getConnectionList() {
return connection_list_;
}
+const DeviceMap& ConnectionHandlerImpl::getDeviceList() {
+ return device_list_;
+}
+
void ConnectionHandlerImpl::addDeviceConnection(
- const transport_manager::DeviceInfo &device_info,
- const transport_manager::ConnectionUID &connection_id) {
+ const transport_manager::DeviceInfo& device_info,
+ const transport_manager::ConnectionUID connection_id) {
// Add Device
OnDeviceAdded(device_info);
// Add connection
diff --git a/src/components/connection_handler/src/device.cc b/src/components/connection_handler/src/device.cc
index 40a048654a..0ecb439172 100644
--- a/src/components/connection_handler/src/device.cc
+++ b/src/components/connection_handler/src/device.cc
@@ -46,23 +46,25 @@ namespace connection_handler {
CREATE_LOGGERPTR_GLOBAL(logger_, "ConnectionHandler")
Device::Device(DeviceHandle device_handle,
- const std::string &user_friendly_name,
- const std::string &mac_address, const std::string& connection_type)
- : device_handle_(device_handle),
- user_friendly_name_(user_friendly_name),
- mac_address_(mac_address),
- connection_type_(connection_type){
- LOG4CXX_INFO(logger_, "Device MAC address is: " << mac_address_);
- mac_address_ = encryption::MakeHash(mac_address);
- LOG4CXX_INFO(logger_, "Device MAC address hash is: " << mac_address_);
+ const std::string& user_friendly_name,
+ const std::string& mac_address,
+ const std::string& connection_type)
+ : device_handle_(device_handle)
+ , user_friendly_name_(user_friendly_name)
+ , mac_address_(mac_address)
+ , connection_type_(connection_type) {
+ mac_address_ = encryption::MakeHash(mac_address);
+ LOG4CXX_DEBUG(logger_,
+ "Device: MAC address - " << mac_address << ", hash - "
+ << mac_address_);
}
DeviceHandle Device::device_handle() const {
- return device_handle_;
+ return device_handle_;
}
std::string Device::user_friendly_name() const {
- return user_friendly_name_;
+ return user_friendly_name_;
}
std::string Device::mac_address() const {
diff --git a/src/components/connection_handler/src/heartbeat_monitor.cc b/src/components/connection_handler/src/heartbeat_monitor.cc
index 2349e0589f..f3a2322810 100644
--- a/src/components/connection_handler/src/heartbeat_monitor.cc
+++ b/src/components/connection_handler/src/heartbeat_monitor.cc
@@ -43,43 +43,46 @@ using namespace sync_primitives;
CREATE_LOGGERPTR_GLOBAL(logger_, "HeartBeatMonitor")
-HeartBeatMonitor::HeartBeatMonitor(int32_t heartbeat_timeout_seconds,
- Connection *connection)
- : default_heartbeat_timeout_(heartbeat_timeout_seconds),
- connection_(connection),
- sessions_list_lock_(true),
- run_(true) {
-}
+HeartBeatMonitor::HeartBeatMonitor(uint32_t heartbeat_timeout_mseconds,
+ Connection* connection)
+ : default_heartbeat_timeout_(heartbeat_timeout_mseconds)
+ , connection_(connection)
+ , sessions_list_lock_(true)
+ , run_(true) {}
void HeartBeatMonitor::Process() {
- AutoLock auto_lock(sessions_list_lock_);
-
+ sessions_list_lock_.Acquire();
SessionMap::iterator it = sessions_.begin();
while (it != sessions_.end()) {
- SessionState &state = it->second;
+ SessionState& state = it->second;
if (state.HasTimeoutElapsed()) {
const uint8_t session_id = it->first;
if (state.IsReadyToClose()) {
LOG4CXX_WARN(logger_, "Will close session");
+ sessions_list_lock_.Release();
+ RemoveSession(session_id);
connection_->CloseSession(session_id);
+ sessions_list_lock_.Acquire();
it = sessions_.begin();
continue;
} else {
LOG4CXX_DEBUG(logger_,
- "Send heart beat into session with id " << static_cast<int32_t>(session_id));
+ "Send heart beat into session with id "
+ << static_cast<int32_t>(session_id));
state.PrepareToClose();
connection_->SendHeartBeat(it->first);
}
}
++it;
}
+ sessions_list_lock_.Release();
}
void HeartBeatMonitor::threadMain() {
AutoLock main_lock(main_thread_lock_);
- LOG4CXX_DEBUG(
- logger_,
- "Start heart beat monitor. Timeout is " << default_heartbeat_timeout_);
+ LOG4CXX_DEBUG(logger_,
+ "Start heart beat monitor. Timeout is "
+ << default_heartbeat_timeout_);
while (run_) {
heartbeat_monitor_.WaitFor(main_lock, kDefaultCycleTimeout);
Process();
@@ -87,45 +90,50 @@ void HeartBeatMonitor::threadMain() {
}
void HeartBeatMonitor::AddSession(uint8_t session_id) {
- LOG4CXX_DEBUG(logger_, "Add session with id " << static_cast<int32_t>(session_id));
+ LOG4CXX_DEBUG(logger_,
+ "Add session with id " << static_cast<int32_t>(session_id));
AutoLock auto_lock(sessions_list_lock_);
if (sessions_.end() != sessions_.find(session_id)) {
- LOG4CXX_WARN(
- logger_,
- "Session with id " << static_cast<int32_t>(session_id) << " already exists");
+ LOG4CXX_WARN(logger_,
+ "Session with id " << static_cast<int32_t>(session_id)
+ << " already exists");
return;
}
- sessions_.insert(std::make_pair(session_id,
- SessionState(default_heartbeat_timeout_)));
+ sessions_.insert(
+ std::make_pair(session_id, SessionState(default_heartbeat_timeout_)));
LOG4CXX_INFO(logger_, "Start heartbeat for session " << session_id);
}
void HeartBeatMonitor::RemoveSession(uint8_t session_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
AutoLock auto_lock(sessions_list_lock_);
LOG4CXX_DEBUG(logger_,
- "Remove session with id " << static_cast<int>(session_id));
+ "Remove session with id " << static_cast<int>(session_id));
if (sessions_.erase(session_id) == 0) {
LOG4CXX_WARN(logger_,
- "Remove session with id " << static_cast<int>(session_id) <<
- " was unsuccessful");
+ "Remove session with id " << static_cast<int>(session_id)
+ << " was unsuccessful");
}
}
void HeartBeatMonitor::KeepAlive(uint8_t session_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
AutoLock auto_lock(sessions_list_lock_);
if (sessions_.end() != sessions_.find(session_id)) {
- LOG4CXX_INFO( logger_, "Resetting heart beat timer for session with id " <<
- static_cast<int32_t>(session_id));
+ LOG4CXX_INFO(logger_,
+ "Resetting heart beat timer for session with id "
+ << static_cast<int32_t>(session_id));
sessions_[session_id].KeepAlive();
}
}
void HeartBeatMonitor::exitThreadMain() {
- // FIXME (dchmerev@luxoft.com): thread requested to stop should stop as soon as possible,
+ // FIXME (dchmerev@luxoft.com): thread requested to stop should stop as soon
+ // as possible,
// not running one more iteration before actual stop
LOG4CXX_AUTO_TRACE(logger_);
AutoLock main_lock(main_thread_lock_);
@@ -133,10 +141,11 @@ void HeartBeatMonitor::exitThreadMain() {
heartbeat_monitor_.NotifyOne();
}
-void HeartBeatMonitor::set_heartbeat_timeout_seconds(int32_t timeout,
- uint8_t session_id) {
- LOG4CXX_DEBUG(logger_, "Set new heart beat timeout " << timeout <<
- "For session: " << session_id);
+void HeartBeatMonitor::set_heartbeat_timeout_milliseconds(uint32_t timeout,
+ uint8_t session_id) {
+ LOG4CXX_DEBUG(logger_,
+ "Set new heart beat timeout " << timeout
+ << "For session: " << session_id);
AutoLock session_locker(sessions_list_lock_);
if (sessions_.end() != sessions_.find(session_id)) {
@@ -144,46 +153,49 @@ void HeartBeatMonitor::set_heartbeat_timeout_seconds(int32_t timeout,
}
}
-HeartBeatMonitor::SessionState::SessionState(int32_t heartbeat_timeout_seconds)
- : heartbeat_timeout_seconds_(heartbeat_timeout_seconds),
- is_heartbeat_sent(false) {
+HeartBeatMonitor::SessionState::SessionState(
+ uint32_t heartbeat_timeout_mseconds)
+ : heartbeat_timeout_mseconds_(heartbeat_timeout_mseconds)
+ , is_heartbeat_sent_(false) {
LOG4CXX_AUTO_TRACE(logger_);
RefreshExpiration();
}
-void HeartBeatMonitor::SessionState::RefreshExpiration () {
- LOG4CXX_DEBUG(logger_, "Refresh expiration: " << heartbeat_timeout_seconds_);
- heartbeat_expiration = date_time::DateTime::getCurrentTime();
- heartbeat_expiration.tv_sec += heartbeat_timeout_seconds_;
+void HeartBeatMonitor::SessionState::RefreshExpiration() {
+ LOG4CXX_DEBUG(logger_, "Refresh expiration: " << heartbeat_timeout_mseconds_);
+ using namespace date_time;
+ TimevalStruct time = DateTime::getCurrentTime();
+ DateTime::AddMilliseconds(time, heartbeat_timeout_mseconds_);
+ heartbeat_expiration_ = time;
}
void HeartBeatMonitor::SessionState::UpdateTimeout(
- int32_t heartbeat_timeout_seconds) {
- LOG4CXX_DEBUG(logger_, "Update timout with value " <<
- heartbeat_timeout_seconds_);
- heartbeat_timeout_seconds_ = heartbeat_timeout_seconds;
+ uint32_t heartbeat_timeout_mseconds) {
+ LOG4CXX_DEBUG(logger_,
+ "Update timout with value " << heartbeat_timeout_mseconds_);
+ heartbeat_timeout_mseconds_ = heartbeat_timeout_mseconds;
RefreshExpiration();
}
void HeartBeatMonitor::SessionState::PrepareToClose() {
- is_heartbeat_sent = true;
+ is_heartbeat_sent_ = true;
LOG4CXX_DEBUG(logger_, "Prepare to close");
RefreshExpiration();
}
bool HeartBeatMonitor::SessionState::IsReadyToClose() const {
- return is_heartbeat_sent;
+ return is_heartbeat_sent_;
}
void HeartBeatMonitor::SessionState::KeepAlive() {
- is_heartbeat_sent = false;
- LOG4CXX_DEBUG(logger_, "keep alive");
+ LOG4CXX_AUTO_TRACE(logger_);
+ is_heartbeat_sent_ = false;
RefreshExpiration();
}
bool HeartBeatMonitor::SessionState::HasTimeoutElapsed() {
TimevalStruct now = date_time::DateTime::getCurrentTime();
- return date_time::DateTime::Greater(now, heartbeat_expiration);
+ return date_time::DateTime::Greater(now, heartbeat_expiration_);
}
} // namespace connection_handler
diff --git a/src/components/connection_handler/test/CMakeLists.txt b/src/components/connection_handler/test/CMakeLists.txt
index 7c0e1b2a98..32da4bdcd8 100644
--- a/src/components/connection_handler/test/CMakeLists.txt
+++ b/src/components/connection_handler/test/CMakeLists.txt
@@ -35,26 +35,22 @@ set(appMain_DIR ${CMAKE_SOURCE_DIR}/src/appMain)
include_directories(
${GMOCK_INCLUDE_DIRECTORY}
${COMPONENTS_DIR}/connection_handler/include
- ${COMPONENTS_DIR}/security_manager/test/include
- ${COMPONENTS_DIR}/protocol_handler/test/include
- ${COMPONENTS_DIR}/security_manager/include
${COMPONENTS_DIR}/connection_handler/test/include
- ${COMPONENTS_DIR}/transport_manager/test/include
+ ${COMPONENTS_DIR}/resumption/include
+ ${JSONCPP_INCLUDE_DIRECTORY}
)
set(LIBRARIES
gmock
connectionHandler
- ConfigProfile
ProtocolHandler
- TransportManager
)
set(SOURCES
- #connection_handler_impl_test.cc
+ connection_handler_impl_test.cc
connection_test.cc
device_test.cc
- #heart_beat_monitor_test.cc
+ heart_beat_monitor_test.cc
)
file(COPY ${appMain_DIR}/smartDeviceLink.ini DESTINATION "./")
diff --git a/src/components/connection_handler/test/connection_handler_impl_test.cc b/src/components/connection_handler/test/connection_handler_impl_test.cc
index 94e4c816fa..3a8aaa70b4 100644
--- a/src/components/connection_handler/test/connection_handler_impl_test.cc
+++ b/src/components/connection_handler/test/connection_handler_impl_test.cc
@@ -30,38 +30,60 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include <gtest/gtest.h>
+#include "gtest/gtest.h"
#include <fstream>
-#include <cstdint>
+#include <stdint.h>
+#include <vector>
#include "connection_handler/connection_handler_impl.h"
#include "protocol/common.h"
-#include "config_profile/profile.h"
// TODO(EZamakhov): move security test
-#include "security_manager_mock.h"
-#include "protocol_handler_mock.h"
-#include "connection_handler_observer_mock.h"
-#include "transport_manager_mock.h"
+#include "security_manager/mock_security_manager.h"
+#include "security_manager/mock_ssl_context.h"
+#include "protocol_handler/mock_protocol_handler.h"
+#include "connection_handler/connection_handler_observer_mock.h"
+#include "connection_handler/mock_connection_handler_settings.h"
+#include "transport_manager/mock_transport_manager.h"
+#include "encryption/hashing.h"
namespace test {
namespace components {
-namespace connection_handle_test {
+namespace connection_handler_test {
using namespace ::connection_handler;
using ::protocol_handler::ServiceType;
using namespace ::protocol_handler;
using ::testing::_;
using ::testing::InSequence;
+using ::testing::Mock;
+using ::testing::Return;
+using ::testing::ReturnRefOfCopy;
+
// For service types and PROTECTION_ON/OFF
+enum UnnamedService { kServedService1 = 0x06, kServedService2 = 0x08 };
+
class ConnectionHandlerTest : public ::testing::Test {
protected:
void SetUp() OVERRIDE {
- connection_handler_ = ConnectionHandlerImpl::instance();
+ connection_handler_ = new ConnectionHandlerImpl(
+ mock_connection_handler_settings, mock_transport_manager);
uid_ = 1u;
connection_key_ = connection_handler_->KeyFromPair(0, 0u);
+ protected_services_.clear();
+ unprotected_services_.clear();
+ SetSpecificServices();
}
void TearDown() OVERRIDE {
- ConnectionHandlerImpl::destroy();
+ delete connection_handler_;
+ }
+
+ void SetSpecificServices() {
+#ifdef ENABLE_SECURITY
+ ON_CALL(mock_connection_handler_settings, force_protected_service())
+ .WillByDefault(ReturnRefOfCopy(protected_services_));
+ ON_CALL(mock_connection_handler_settings, force_unprotected_service())
+ .WillByDefault(ReturnRefOfCopy(unprotected_services_));
+#endif // ENABLE_SECURITY
}
// Additional SetUp
void AddTestDeviceConnection() {
@@ -71,19 +93,18 @@ class ConnectionHandlerTest : public ::testing::Test {
device_name_ = "test_name";
mac_address_ = "test_address";
- const transport_manager::DeviceInfo device_info(device_handle_,
- mac_address_,
- device_name_,
- connection_type_);
+ const transport_manager::DeviceInfo device_info(
+ device_handle_, mac_address_, device_name_, connection_type_);
// Add Device and connection
+ ON_CALL(mock_connection_handler_settings, heart_beat_timeout())
+ .WillByDefault(Return(1000u));
connection_handler_->addDeviceConnection(device_info, uid_);
connection_key_ = connection_handler_->KeyFromPair(uid_, 0u);
// Remove all specific services
- SetSpecificServices("", "");
}
void AddTestSession() {
start_session_id_ = connection_handler_->OnSessionStartedCallback(
- uid_, 0, kRpc, PROTECTION_OFF, &out_hash_id_);
+ uid_, 0, kRpc, PROTECTION_OFF, &out_hash_id_);
EXPECT_NE(0u, start_session_id_);
EXPECT_EQ(SessionHash(uid_, start_session_id_), out_hash_id_);
connection_key_ = connection_handler_->KeyFromPair(uid_, start_session_id_);
@@ -102,27 +123,12 @@ class ConnectionHandlerTest : public ::testing::Test {
EXPECT_EQ(session_id, start_session_id_);
}
- // Additional SetUp
- void SetSpecificServices(const std::string& protect, const std::string& not_protect) {
- const char* config_file = "config.ini";
- std::ofstream file_config(config_file);
- ASSERT_TRUE(file_config.is_open());
- const std::string non("NON");
- file_config << "[Security Manager]" << std::endl
- << "; Force protected services (could be id's from 0x01 to 0xFF)"
- << std::endl << "ForceProtectedService = "
- << (protect.empty() ? non : protect) << std::endl
- << "; Force unprotected services" << std::endl
- << "ForceUnprotectedService = "
- << (not_protect.empty() ? non : not_protect) << std::endl;
- file_config.close();
- profile::Profile::instance()->config_file_name(config_file);
- }
// Check Service Wrapper
// If session_id is NULL - check that there is no sessions in connection
void CheckSessionExists(const int connectionId, const int session_id) {
// Check all tree to find Session and check own protected value
- const ConnectionList& connection_list = connection_handler_->getConnectionList();
+ const ConnectionList& connection_list =
+ connection_handler_->getConnectionList();
ASSERT_FALSE(connection_list.empty());
ConnectionList::const_iterator conn_it = connection_list.find(connectionId);
ASSERT_NE(conn_it, connection_list.end());
@@ -139,17 +145,21 @@ class ConnectionHandlerTest : public ::testing::Test {
const ServiceList& service_list = session.service_list;
ASSERT_FALSE(service_list.empty());
// Check RPC and bulk services in session
- ASSERT_NE(service_list.end(), std::find(service_list.begin(), service_list.end(), kRpc));
- ASSERT_NE(service_list.end(), std::find(service_list.begin(), service_list.end(), kBulk));
+ ASSERT_NE(service_list.end(),
+ std::find(service_list.begin(), service_list.end(), kRpc));
+ ASSERT_NE(service_list.end(),
+ std::find(service_list.begin(), service_list.end(), kBulk));
}
}
// Check Service Wrapper
- void CheckServiceExists(const int connectionId, const int session_id,
+ void CheckServiceExists(const int connectionId,
+ const int session_id,
const ::protocol_handler::ServiceType serviceId,
const bool exists) {
// Check all trees to find Service and check own protected value
- const ConnectionList& connection_list = connection_handler_->getConnectionList();
+ const ConnectionList& connection_list =
+ connection_handler_->getConnectionList();
ASSERT_FALSE(connection_list.empty());
ConnectionList::const_iterator conn_it = connection_list.find(connectionId);
ASSERT_NE(conn_it, connection_list.end());
@@ -162,7 +172,8 @@ class ConnectionHandlerTest : public ::testing::Test {
const Session& session = sess_it->second;
const ServiceList& service_list = session.service_list;
ASSERT_FALSE(service_list.empty());
- ServiceList::const_iterator serv_it = std::find(service_list.begin(), service_list.end(), serviceId);
+ ServiceList::const_iterator serv_it =
+ std::find(service_list.begin(), service_list.end(), serviceId);
if (exists) {
ASSERT_NE(serv_it, service_list.end());
} else {
@@ -170,12 +181,14 @@ class ConnectionHandlerTest : public ::testing::Test {
}
}
// Check Service Wrapper
- void CheckService(const int connectionId, const int session_id,
+ void CheckService(const int connectionId,
+ const int session_id,
const ::protocol_handler::ServiceType serviceId,
const ::security_manager::SSLContext* ssl_context,
const bool is_protected) {
// Check all tree to find Service and check own protected value
- const ConnectionList& connection_list = connection_handler_->getConnectionList();
+ const ConnectionList& connection_list =
+ connection_handler_->getConnectionList();
ASSERT_FALSE(connection_list.empty());
ConnectionList::const_iterator conn_it = connection_list.find(connectionId);
ASSERT_NE(conn_it, connection_list.end());
@@ -191,7 +204,8 @@ class ConnectionHandlerTest : public ::testing::Test {
#endif // ENABLE_SECURITY
const ServiceList& service_list = session.service_list;
ASSERT_FALSE(service_list.empty());
- ServiceList::const_iterator serv_it = std::find(service_list.begin(), service_list.end(), serviceId);
+ ServiceList::const_iterator serv_it =
+ std::find(service_list.begin(), service_list.end(), serviceId);
ASSERT_NE(serv_it, service_list.end());
const Service& service = *serv_it;
@@ -199,28 +213,36 @@ class ConnectionHandlerTest : public ::testing::Test {
#ifdef ENABLE_SECURITY
if (is_protected) {
// Emulate success protection - check enable service flag
- const uint32_t connection_key_ = connection_handler_->KeyFromPair(
- connectionId, session_id);
+ const uint32_t connection_key_ =
+ connection_handler_->KeyFromPair(connectionId, session_id);
connection_handler_->SetProtectionFlag(connection_key_, serviceId);
}
#endif // ENABLE_SECURITY
}
- void ChangeProtocol(const int connectionId, const int session_id, const uint8_t protocol_version) {
+ void ChangeProtocol(const int connectionId,
+ const int session_id,
+ const uint8_t protocol_version) {
ConnectionList connection_list = connection_handler_->getConnectionList();
- ConnectionList::const_iterator conn_it = (connection_handler_->getConnectionList()).find(connectionId);
+ ConnectionList::const_iterator conn_it =
+ (connection_handler_->getConnectionList()).find(connectionId);
ASSERT_NE(conn_it, connection_list.end());
- Connection * connection = conn_it->second;
+ Connection* connection = conn_it->second;
ASSERT_TRUE(connection != NULL);
connection->UpdateProtocolVersionSession(session_id, protocol_version);
uint8_t check_protocol_version;
- EXPECT_TRUE(connection->ProtocolVersion(session_id, check_protocol_version));
- EXPECT_EQ(check_protocol_version,protocol_version);
-
+ EXPECT_TRUE(
+ connection->ProtocolVersion(session_id, check_protocol_version));
+ EXPECT_EQ(check_protocol_version, protocol_version);
}
ConnectionHandlerImpl* connection_handler_;
+ testing::NiceMock<transport_manager_test::MockTransportManager>
+ mock_transport_manager;
+ testing::NiceMock<MockConnectionHandlerSettings>
+ mock_connection_handler_settings;
+ protocol_handler_test::MockProtocolHandler mock_protocol_handler_;
transport_manager::DeviceHandle device_handle_;
transport_manager::ConnectionUID uid_;
uint32_t connection_key_;
@@ -231,13 +253,17 @@ class ConnectionHandlerTest : public ::testing::Test {
std::string device_name_;
std::string mac_address_;
+ const uint32_t heartbeat_timeout = 100u;
+ std::vector<int> protected_services_;
+ std::vector<int> unprotected_services_;
};
TEST_F(ConnectionHandlerTest, StartSession_NoConnection) {
// Null sessionId for start new session
const uint8_t sessionID = 0;
// Start new session with RPC service
- const uint32_t result_fail = connection_handler_->OnSessionStartedCallback(uid_, sessionID, kRpc, PROTECTION_ON, &out_hash_id_);
+ const uint32_t result_fail = connection_handler_->OnSessionStartedCallback(
+ uid_, sessionID, kRpc, PROTECTION_ON, &out_hash_id_);
// Unknown connection error is '0'
EXPECT_EQ(0u, result_fail);
EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id_);
@@ -251,12 +277,23 @@ TEST_F(ConnectionHandlerTest, StartSession) {
AddTestSession();
}
+TEST_F(ConnectionHandlerTest, AddConnection_StopConnection) {
+ // Add virtual device and connection
+ AddTestDeviceConnection();
+ EXPECT_FALSE(connection_handler_->getConnectionList().empty());
+ // Stop connection
+ connection_handler_->Stop();
+ EXPECT_TRUE(connection_handler_->getConnectionList().empty());
+}
+
TEST_F(ConnectionHandlerTest, GetConnectionSessionsCount) {
AddTestDeviceConnection();
- EXPECT_EQ(0u, connection_handler_->GetConnectionSessionsCount(connection_key_));
+ EXPECT_EQ(0u,
+ connection_handler_->GetConnectionSessionsCount(connection_key_));
AddTestSession();
- EXPECT_EQ(1u, connection_handler_->GetConnectionSessionsCount(connection_key_));
+ EXPECT_EQ(1u,
+ connection_handler_->GetConnectionSessionsCount(connection_key_));
}
TEST_F(ConnectionHandlerTest, GetAppIdOnSessionKey) {
@@ -266,51 +303,82 @@ TEST_F(ConnectionHandlerTest, GetAppIdOnSessionKey) {
uint32_t app_id = 0;
const uint32_t testid = SessionHash(uid_, start_session_id_);
- EXPECT_EQ(0, connection_handler_->GetDataOnSessionKey(connection_key_, &app_id, NULL, NULL));
+ EXPECT_EQ(0,
+ connection_handler_->GetDataOnSessionKey(
+ connection_key_, &app_id, NULL, NULL));
EXPECT_EQ(testid, app_id);
}
-TEST_F(ConnectionHandlerTest,GetDeviceID) {
+TEST_F(ConnectionHandlerTest, GetAppIdOnSessionKey_SessionNotStarted) {
+ AddTestDeviceConnection();
+
+ uint32_t app_id = 0;
+ EXPECT_EQ(-1,
+ connection_handler_->GetDataOnSessionKey(
+ connection_key_, &app_id, NULL, NULL));
+}
+
+TEST_F(ConnectionHandlerTest, GetDeviceID) {
AddTestDeviceConnection();
AddTestSession();
DeviceHandle test_handle;
- const DeviceMap & devmap = connection_handler_->getDeviceList();
+ const DeviceMap& devmap = connection_handler_->getDeviceList();
DeviceMap::const_iterator pos = devmap.find(device_handle_);
ASSERT_NE(pos, devmap.end());
- const Device & devres = pos->second;
+ const Device& devres = pos->second;
std::string test_mac_address = devres.mac_address();
EXPECT_TRUE(connection_handler_->GetDeviceID(test_mac_address, &test_handle));
EXPECT_EQ(device_handle_, test_handle);
}
-TEST_F(ConnectionHandlerTest,GetDeviceName) {
+TEST_F(ConnectionHandlerTest, GetDeviceName) {
AddTestDeviceConnection();
AddTestSession();
std::string test_device_name;
DeviceHandle handle = 0;
- EXPECT_EQ(0, connection_handler_->GetDataOnDeviceID(handle, &test_device_name));
+ EXPECT_EQ(0,
+ connection_handler_->GetDataOnDeviceID(handle, &test_device_name));
EXPECT_EQ(device_name_, test_device_name);
}
-TEST_F(ConnectionHandlerTest,GetConnectionType) {
+TEST_F(ConnectionHandlerTest, GetConnectionType) {
AddTestDeviceConnection();
AddTestSession();
const DeviceHandle handle = 0;
std::string test_connection_type;
- EXPECT_EQ(0, connection_handler_->GetDataOnDeviceID(handle, NULL, NULL, NULL, &test_connection_type));
+ EXPECT_EQ(0,
+ connection_handler_->GetDataOnDeviceID(
+ handle, NULL, NULL, NULL, &test_connection_type));
EXPECT_EQ(connection_type_, test_connection_type);
}
+TEST_F(ConnectionHandlerTest, GetApplicationsOnDevice) {
+ AddTestDeviceConnection();
+ AddTestSession();
+
+ const DeviceHandle handle = 0;
+ std::list<uint32_t> applications_list;
+ EXPECT_EQ(
+ 0,
+ connection_handler_->GetDataOnDeviceID(handle, NULL, &applications_list));
+
+ uint32_t test_id = connection_handler_->KeyFromPair(uid_, start_session_id_);
+ EXPECT_EQ(1u, applications_list.size());
+
+ EXPECT_EQ(test_id, applications_list.front());
+}
+
TEST_F(ConnectionHandlerTest, GetDefaultProtocolVersion) {
AddTestDeviceConnection();
AddTestSession();
uint8_t protocol_version = 0;
- EXPECT_TRUE(connection_handler_->ProtocolVersionUsed(uid_, start_session_id_, protocol_version));
+ EXPECT_TRUE(connection_handler_->ProtocolVersionUsed(
+ uid_, start_session_id_, protocol_version));
EXPECT_EQ(PROTOCOL_VERSION_2, protocol_version);
}
@@ -321,7 +389,8 @@ TEST_F(ConnectionHandlerTest, GetProtocolVersion) {
ChangeProtocol(uid_, start_session_id_, PROTOCOL_VERSION_3);
uint8_t protocol_version = 0;
- EXPECT_TRUE(connection_handler_->ProtocolVersionUsed(uid_, start_session_id_, protocol_version));
+ EXPECT_TRUE(connection_handler_->ProtocolVersionUsed(
+ uid_, start_session_id_, protocol_version));
EXPECT_EQ(PROTOCOL_VERSION_3, protocol_version);
}
@@ -330,12 +399,15 @@ TEST_F(ConnectionHandlerTest, GetProtocolVersionAfterBinding) {
AddTestDeviceConnection();
AddTestSession();
uint8_t protocol_version = 0;
- EXPECT_TRUE(connection_handler_->ProtocolVersionUsed(uid_, start_session_id_, protocol_version));
+ EXPECT_TRUE(connection_handler_->ProtocolVersionUsed(
+ uid_, start_session_id_, protocol_version));
EXPECT_EQ(PROTOCOL_VERSION_2, protocol_version);
- connection_handler_->BindProtocolVersionWithSession(connection_key_, PROTOCOL_VERSION_3);
+ connection_handler_->BindProtocolVersionWithSession(connection_key_,
+ PROTOCOL_VERSION_3);
- EXPECT_TRUE(connection_handler_->ProtocolVersionUsed(uid_, start_session_id_, protocol_version));
+ EXPECT_TRUE(connection_handler_->ProtocolVersionUsed(
+ uid_, start_session_id_, protocol_version));
EXPECT_EQ(PROTOCOL_VERSION_3, protocol_version);
}
@@ -353,49 +425,51 @@ TEST_F(ConnectionHandlerTest, GetPairFromKey) {
TEST_F(ConnectionHandlerTest, IsHeartBeatSupported) {
AddTestDeviceConnection();
AddTestSession();
-
ChangeProtocol(uid_, start_session_id_, PROTOCOL_VERSION_3);
- EXPECT_TRUE(connection_handler_->IsHeartBeatSupported(uid_, start_session_id_));
+ EXPECT_TRUE(
+ connection_handler_->IsHeartBeatSupported(uid_, start_session_id_));
}
-TEST_F(ConnectionHandlerTest,SendEndServiceWithoutSetProtocolHandler) {
+TEST_F(ConnectionHandlerTest, SendEndServiceWithoutSetProtocolHandler) {
AddTestDeviceConnection();
AddTestSession();
- protocol_handler_test::ProtocolHandlerMock mock_protocol_handler;
-
- EXPECT_CALL(mock_protocol_handler, SendEndService(_,_,kRpc)).Times(0);
+ EXPECT_CALL(mock_protocol_handler_, SendEndService(_, _, kRpc)).Times(0);
connection_handler_->SendEndService(connection_key_, kRpc);
}
-TEST_F(ConnectionHandlerTest,SendEndService) {
+TEST_F(ConnectionHandlerTest, SendEndService) {
AddTestDeviceConnection();
AddTestSession();
- protocol_handler_test::ProtocolHandlerMock mock_protocol_handler;
-
- connection_handler_->set_protocol_handler(&mock_protocol_handler);
- EXPECT_CALL(mock_protocol_handler, SendEndService(_,_,kRpc));
+ connection_handler_->set_protocol_handler(&mock_protocol_handler_);
+ EXPECT_CALL(mock_protocol_handler_, SendEndService(_, _, kRpc));
connection_handler_->SendEndService(connection_key_, kRpc);
}
-TEST_F(ConnectionHandlerTest,OnFindNewApplicationsRequest) {
+TEST_F(ConnectionHandlerTest, OnFindNewApplicationsRequest) {
AddTestDeviceConnection();
AddTestSession();
- connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer;
- connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer);
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
EXPECT_CALL(mock_connection_handler_observer, OnFindNewApplicationsRequest());
connection_handler_->OnFindNewApplicationsRequest();
}
-TEST_F(ConnectionHandlerTest,OnFindNewApplicationsRequestWithoutObserver) {
- connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer;
- EXPECT_CALL(mock_connection_handler_observer, OnFindNewApplicationsRequest()).Times(0);
+TEST_F(ConnectionHandlerTest, OnFindNewApplicationsRequestWithoutObserver) {
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ EXPECT_CALL(mock_connection_handler_observer, OnFindNewApplicationsRequest())
+ .Times(0);
connection_handler_->OnFindNewApplicationsRequest();
}
-TEST_F(ConnectionHandlerTest,OnFindNewApplicationsRequestWithoutSession) {
- connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer;
- connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer);
+TEST_F(ConnectionHandlerTest, OnFindNewApplicationsRequestWithoutSession) {
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
EXPECT_CALL(mock_connection_handler_observer, OnFindNewApplicationsRequest());
connection_handler_->OnFindNewApplicationsRequest();
@@ -406,18 +480,24 @@ TEST_F(ConnectionHandlerTest, OnMalformedMessageCallback) {
AddTestSession();
AddTestService(kAudio);
AddTestService(kMobileNav);
- connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer;
- connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer);
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
InSequence seq;
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kMobileNav, kMalformed)).Times(1);
+ OnServiceEndedCallback(connection_key_, kMobileNav, kMalformed))
+ .Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kAudio, kMalformed)).Times(1);
+ OnServiceEndedCallback(connection_key_, kAudio, kMalformed))
+ .Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kBulk, kMalformed)).Times(1);
+ OnServiceEndedCallback(connection_key_, kBulk, kMalformed))
+ .Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kRpc, kMalformed)).Times(1);
+ OnServiceEndedCallback(connection_key_, kRpc, kMalformed))
+ .Times(1);
connection_handler_->OnMalformedMessageCallback(uid_);
}
@@ -426,53 +506,288 @@ TEST_F(ConnectionHandlerTest, OnApplicationFloodCallBack) {
AddTestSession();
AddTestService(kAudio);
AddTestService(kMobileNav);
- connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer;
- connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer);
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
- protocol_handler_test::ProtocolHandlerMock mock_protocol_handler;
- connection_handler_->set_protocol_handler(&mock_protocol_handler);
-
- EXPECT_CALL(mock_protocol_handler, SendEndSession(uid_,start_session_id_));
+ connection_handler_->set_protocol_handler(&mock_protocol_handler_);
+ EXPECT_CALL(mock_protocol_handler_, SendEndSession(uid_, start_session_id_))
+ .Times(1);
InSequence seq;
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kMobileNav, kCommon)).Times(1);
+ OnServiceEndedCallback(connection_key_, kMobileNav, kCommon));
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kAudio, kCommon)).Times(1);
+ OnServiceEndedCallback(connection_key_, kAudio, kCommon));
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kBulk, kCommon)).Times(1);
+ OnServiceEndedCallback(connection_key_, kBulk, kCommon));
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kRpc, kCommon)).Times(1);
+ OnServiceEndedCallback(connection_key_, kRpc, kCommon));
connection_handler_->OnApplicationFloodCallBack(uid_);
}
+TEST_F(ConnectionHandlerTest, OnApplicationFloodCallBack_SessionFound) {
+ // Precondition
+ AddTestDeviceConnection();
+ AddTestSession();
+ AddTestService(kAudio);
+ AddTestService(kMobileNav);
+
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
+
+ connection_handler_->set_protocol_handler(&mock_protocol_handler_);
+ EXPECT_CALL(mock_protocol_handler_, SendEndSession(uid_, start_session_id_));
+ InSequence seq;
+ EXPECT_CALL(mock_connection_handler_observer,
+ OnServiceEndedCallback(connection_key_, kMobileNav, kFlood));
+ EXPECT_CALL(mock_connection_handler_observer,
+ OnServiceEndedCallback(connection_key_, kAudio, kFlood));
+ EXPECT_CALL(mock_connection_handler_observer,
+ OnServiceEndedCallback(connection_key_, kBulk, kFlood));
+ EXPECT_CALL(mock_connection_handler_observer,
+ OnServiceEndedCallback(connection_key_, kRpc, kFlood));
+
+ connection_handler_->OnApplicationFloodCallBack(connection_key_);
+}
+
TEST_F(ConnectionHandlerTest, StartDevicesDiscovery) {
AddTestDeviceConnection();
AddTestSession();
- transport_manager_test::TransportManagerMock mock_transport_manager;
- connection_handler_->set_transport_manager(&mock_transport_manager);
- connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer;
- connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer);
+
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
EXPECT_CALL(mock_transport_manager, SearchDevices());
EXPECT_CALL(mock_connection_handler_observer, OnDeviceListUpdated(_));
connection_handler_->StartDevicesDiscovery();
}
+MATCHER_P(CheckDevList, check_device_map, "") {
+ DeviceMap device_list = arg;
+ if (device_list.size() != check_device_map.size()) {
+ return false;
+ }
+ DeviceMap::const_iterator it = device_list.begin();
+ DeviceMap::const_iterator end = device_list.end();
+
+ DeviceMap::const_iterator check_it = check_device_map.begin();
+ for (; it != end; ++it, ++check_it) {
+ if (it->first != check_it->first) {
+ return false;
+ }
+ if ((*it).second.device_handle() != (*check_it).second.device_handle()) {
+ return false;
+ }
+ if ((*it).second.mac_address() != (*check_it).second.mac_address()) {
+ return false;
+ }
+ if ((*it).second.connection_type() !=
+ (*check_it).second.connection_type()) {
+ return false;
+ }
+ }
+ return true;
+}
+
+TEST_F(ConnectionHandlerTest, UpdateDeviceList) {
+ // Precondition
+ AddTestDeviceConnection();
+ AddTestSession();
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
+
+ connection_type_ = "BTMAC";
+ device_name_ = "test_name";
+ mac_address_ = "test_address";
+ const transport_manager::DeviceInfo added_info(
+ 0, "test_address", "test_name", "BTMAC");
+ connection_handler_->OnDeviceAdded(added_info);
+
+ // Prepare map with DeviceInfo that sets in OnDeviceListUpdated
+ const transport_manager::DeviceInfo unused_parameter(
+ 0, "mac_address_", "device_name_", "connection_type_");
+ std::vector<transport_manager::DeviceInfo> unused_info;
+ unused_info.push_back(unused_parameter);
+ DeviceMap map_with_unused_var;
+ map_with_unused_var.insert(
+ DeviceMap::value_type(unused_parameter.device_handle(),
+ Device(unused_parameter.device_handle(),
+ unused_parameter.name(),
+ unused_parameter.mac_address(),
+ unused_parameter.connection_type())));
+
+ // Only previously added devices is updated
+ EXPECT_CALL(
+ mock_connection_handler_observer,
+ OnDeviceListUpdated(CheckDevList(connection_handler_->getDeviceList())));
+
+ // New value that sets in OnDeviceListUpdated does not add
+ EXPECT_CALL(mock_connection_handler_observer,
+ OnDeviceListUpdated(CheckDevList(map_with_unused_var))).Times(0);
+
+ connection_handler_->OnDeviceListUpdated(unused_info);
+}
+
+TEST_F(ConnectionHandlerTest, GetConnectedDevicesMAC) {
+ // Precondition
+ const std::string mac_address1 = "test_address1";
+ const std::string mac_address2 = "test_address2";
+
+ const transport_manager::DeviceInfo device1(
+ 0, mac_address1, device_name_, connection_type_);
+ const transport_manager::DeviceInfo device2(
+ 1, mac_address2, device_name_, connection_type_);
+ connection_handler_->OnDeviceAdded(device1);
+ connection_handler_->OnDeviceAdded(device2);
+
+ // Expect mac adress was hashed and saved
+ const std::string check_mac1 = encryption::MakeHash(mac_address1);
+ const std::string check_mac2 = encryption::MakeHash(mac_address2);
+ std::vector<std::string> device_macs;
+ connection_handler_->GetConnectedDevicesMAC(device_macs);
+ ASSERT_EQ(2u, device_macs.size());
+ EXPECT_EQ(check_mac1, device_macs.at(0));
+ EXPECT_EQ(check_mac2, device_macs.at(1));
+}
+
TEST_F(ConnectionHandlerTest, StartTransportManager) {
AddTestDeviceConnection();
AddTestSession();
- transport_manager_test::TransportManagerMock mock_transport_manager;
- connection_handler_->set_transport_manager(&mock_transport_manager);
+
EXPECT_CALL(mock_transport_manager, Visibility(true));
connection_handler_->StartTransportManager();
}
+TEST_F(ConnectionHandlerTest, OnDeviceRemoved_ServiceNotStarted) {
+ // Precondition
+ const uint32_t dev_handle1 = 1;
+ const uint32_t dev_handle2 = 2;
+
+ const transport_manager::DeviceInfo device1(
+ dev_handle1, mac_address_, device_name_, connection_type_);
+ const transport_manager::DeviceInfo device2(
+ dev_handle2, mac_address_, device_name_, connection_type_);
+ connection_handler_->OnDeviceAdded(device1);
+ connection_handler_->OnDeviceAdded(device2);
+
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
+
+ EXPECT_CALL(mock_connection_handler_observer, RemoveDevice(dev_handle1));
+ EXPECT_CALL(mock_connection_handler_observer, OnServiceEndedCallback(_, _, _))
+ .Times(0);
+ connection_handler_->OnDeviceRemoved(device1);
+}
+
+TEST_F(ConnectionHandlerTest, OnDeviceRemoved_ServiceStarted) {
+ // Precondition
+ AddTestDeviceConnection();
+ AddTestSession();
+
+ const transport_manager::DeviceInfo device1(
+ device_handle_, mac_address_, device_name_, connection_type_);
+
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
+
+ EXPECT_CALL(mock_connection_handler_observer, RemoveDevice(device_handle_));
+
+ EXPECT_CALL(mock_connection_handler_observer,
+ OnServiceEndedCallback(connection_key_, kBulk, kCommon));
+ EXPECT_CALL(mock_connection_handler_observer,
+ OnServiceEndedCallback(connection_key_, kRpc, kCommon));
+ connection_handler_->OnDeviceRemoved(device1);
+}
+
+TEST_F(ConnectionHandlerTest, OnConnectionClosed) {
+ AddTestDeviceConnection();
+ AddTestSession();
+
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
+
+ EXPECT_CALL(mock_connection_handler_observer,
+ OnServiceEndedCallback(connection_key_, kBulk, kCommon));
+ EXPECT_CALL(mock_connection_handler_observer,
+ OnServiceEndedCallback(connection_key_, kRpc, kCommon));
+
+ connection_handler_->OnConnectionClosed(uid_);
+}
+
+TEST_F(ConnectionHandlerTest, OnUnexpectedDisconnect) {
+ AddTestDeviceConnection();
+ AddTestSession();
+
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
+ transport_manager::CommunicationError err;
+ EXPECT_CALL(mock_connection_handler_observer,
+ OnServiceEndedCallback(
+ connection_key_, kBulk, CloseSessionReason::kCommon));
+ EXPECT_CALL(mock_connection_handler_observer,
+ OnServiceEndedCallback(
+ connection_key_, kRpc, CloseSessionReason::kCommon));
+
+ connection_handler_->OnUnexpectedDisconnect(uid_, err);
+}
+
+TEST_F(ConnectionHandlerTest, ConnectToDevice) {
+ // Precondition
+ const uint32_t dev_handle1 = 1;
+ const uint32_t dev_handle2 = 2;
+
+ const transport_manager::DeviceInfo device1(
+ dev_handle1, mac_address_, device_name_, connection_type_);
+ const transport_manager::DeviceInfo device2(
+ dev_handle2, mac_address_, device_name_, connection_type_);
+ connection_handler_->OnDeviceAdded(device1);
+ connection_handler_->OnDeviceAdded(device2);
+
+ EXPECT_CALL(mock_transport_manager, ConnectDevice(dev_handle1))
+ .WillOnce(Return(transport_manager::E_SUCCESS));
+ EXPECT_CALL(mock_transport_manager, ConnectDevice(dev_handle2)).Times(0);
+ connection_handler_->ConnectToDevice(dev_handle1);
+}
+
+TEST_F(ConnectionHandlerTest, ConnectToAllDevices) {
+ // Precondition
+ const uint32_t dev_handle1 = 1;
+ const uint32_t dev_handle2 = 2;
+
+ const transport_manager::DeviceInfo device1(
+ dev_handle1, mac_address_, device_name_, connection_type_);
+ const transport_manager::DeviceInfo device2(
+ dev_handle2, mac_address_, device_name_, connection_type_);
+ connection_handler_->OnDeviceAdded(device1);
+ connection_handler_->OnDeviceAdded(device2);
+
+ EXPECT_CALL(mock_transport_manager, ConnectDevice(dev_handle1))
+ .WillOnce(Return(transport_manager::E_SUCCESS));
+ EXPECT_CALL(mock_transport_manager, ConnectDevice(dev_handle2))
+ .WillOnce(Return(transport_manager::E_SUCCESS));
+ connection_handler_->ConnectToAllDevices();
+}
+
TEST_F(ConnectionHandlerTest, CloseConnection) {
AddTestDeviceConnection();
AddTestSession();
- transport_manager_test::TransportManagerMock mock_transport_manager;
- connection_handler_->set_transport_manager(&mock_transport_manager);
+
EXPECT_CALL(mock_transport_manager, DisconnectForce(uid_));
connection_handler_->CloseConnection(uid_);
}
@@ -480,8 +795,7 @@ TEST_F(ConnectionHandlerTest, CloseConnection) {
TEST_F(ConnectionHandlerTest, CloseRevokedConnection) {
AddTestDeviceConnection();
AddTestSession();
- transport_manager_test::TransportManagerMock mock_transport_manager;
- connection_handler_->set_transport_manager(&mock_transport_manager);
+
EXPECT_CALL(mock_transport_manager, DisconnectForce(uid_));
connection_handler_->CloseRevokedConnection(connection_key_);
}
@@ -491,24 +805,27 @@ TEST_F(ConnectionHandlerTest, CloseSessionWithCommonReason) {
AddTestSession();
AddTestService(kAudio);
AddTestService(kMobileNav);
- connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer;
- connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer);
-
- protocol_handler_test::ProtocolHandlerMock mock_protocol_handler;
- connection_handler_->set_protocol_handler(&mock_protocol_handler);
-
- EXPECT_CALL(mock_protocol_handler, SendEndSession(uid_,start_session_id_));
-
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
+
+ connection_handler_->set_protocol_handler(&mock_protocol_handler_);
+ EXPECT_CALL(mock_protocol_handler_, SendEndSession(uid_, start_session_id_))
+ .Times(1);
InSequence seq;
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kMobileNav, kCommon)).Times(1);
+ OnServiceEndedCallback(connection_key_, kMobileNav, kCommon))
+ .Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kAudio, kCommon)).Times(1);
+ OnServiceEndedCallback(connection_key_, kAudio, kCommon))
+ .Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kBulk, kCommon)).Times(1);
+ OnServiceEndedCallback(connection_key_, kBulk, kCommon)).Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kRpc, kCommon)).Times(1);
+ OnServiceEndedCallback(connection_key_, kRpc, kCommon)).Times(1);
connection_handler_->CloseSession(connection_key_, kCommon);
+ Mock::AsyncVerifyAndClearExpectations(10000);
}
TEST_F(ConnectionHandlerTest, CloseSessionWithFloodReason) {
@@ -516,24 +833,27 @@ TEST_F(ConnectionHandlerTest, CloseSessionWithFloodReason) {
AddTestSession();
AddTestService(kAudio);
AddTestService(kMobileNav);
- connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer;
- connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer);
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
- protocol_handler_test::ProtocolHandlerMock mock_protocol_handler;
- connection_handler_->set_protocol_handler(&mock_protocol_handler);
-
- EXPECT_CALL(mock_protocol_handler, SendEndSession(uid_,start_session_id_));
+ connection_handler_->set_protocol_handler(&mock_protocol_handler_);
+ EXPECT_CALL(mock_protocol_handler_, SendEndSession(uid_, start_session_id_))
+ .Times(1);
InSequence seq;
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kMobileNav, kFlood)).Times(1);
+ OnServiceEndedCallback(connection_key_, kMobileNav, kFlood))
+ .Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kAudio, kFlood)).Times(1);
+ OnServiceEndedCallback(connection_key_, kAudio, kFlood)).Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kBulk, kFlood)).Times(1);
+ OnServiceEndedCallback(connection_key_, kBulk, kFlood)).Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kRpc, kFlood)).Times(1);
+ OnServiceEndedCallback(connection_key_, kRpc, kFlood)).Times(1);
connection_handler_->CloseSession(connection_key_, kFlood);
+ Mock::AsyncVerifyAndClearExpectations(10000);
}
TEST_F(ConnectionHandlerTest, CloseSessionWithMalformedMessage) {
@@ -541,24 +861,30 @@ TEST_F(ConnectionHandlerTest, CloseSessionWithMalformedMessage) {
AddTestSession();
AddTestService(kAudio);
AddTestService(kMobileNav);
- connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer;
- connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer);
-
- protocol_handler_test::ProtocolHandlerMock mock_protocol_handler;
- connection_handler_->set_protocol_handler(&mock_protocol_handler);
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
- EXPECT_CALL(mock_protocol_handler, SendEndSession(uid_,start_session_id_)).Times(0);
+ connection_handler_->set_protocol_handler(&mock_protocol_handler_);
+ EXPECT_CALL(mock_protocol_handler_, SendEndSession(uid_, start_session_id_))
+ .Times(0);
InSequence seq;
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kMobileNav, kMalformed)).Times(1);
+ OnServiceEndedCallback(connection_key_, kMobileNav, kMalformed))
+ .Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kAudio, kMalformed)).Times(1);
+ OnServiceEndedCallback(connection_key_, kAudio, kMalformed))
+ .Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kBulk, kMalformed)).Times(1);
+ OnServiceEndedCallback(connection_key_, kBulk, kMalformed))
+ .Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kRpc, kMalformed)).Times(1);
+ OnServiceEndedCallback(connection_key_, kRpc, kMalformed))
+ .Times(1);
connection_handler_->CloseSession(connection_key_, kMalformed);
+ Mock::AsyncVerifyAndClearExpectations(10000);
}
TEST_F(ConnectionHandlerTest, CloseConnectionSessionsWithMalformedMessage) {
@@ -566,24 +892,30 @@ TEST_F(ConnectionHandlerTest, CloseConnectionSessionsWithMalformedMessage) {
AddTestSession();
AddTestService(kAudio);
AddTestService(kMobileNav);
- connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer;
- connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer);
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
- protocol_handler_test::ProtocolHandlerMock mock_protocol_handler;
- connection_handler_->set_protocol_handler(&mock_protocol_handler);
-
- EXPECT_CALL(mock_protocol_handler, SendEndSession(uid_,start_session_id_)).Times(0);
+ connection_handler_->set_protocol_handler(&mock_protocol_handler_);
+ EXPECT_CALL(mock_protocol_handler_, SendEndSession(uid_, start_session_id_))
+ .Times(0);
InSequence seq;
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kMobileNav, kMalformed)).Times(1);
+ OnServiceEndedCallback(connection_key_, kMobileNav, kMalformed))
+ .Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kAudio, kMalformed)).Times(1);
+ OnServiceEndedCallback(connection_key_, kAudio, kMalformed))
+ .Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kBulk, kMalformed)).Times(1);
+ OnServiceEndedCallback(connection_key_, kBulk, kMalformed))
+ .Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kRpc, kMalformed)).Times(1);
+ OnServiceEndedCallback(connection_key_, kRpc, kMalformed))
+ .Times(1);
connection_handler_->CloseConnectionSessions(uid_, kMalformed);
+ Mock::AsyncVerifyAndClearExpectations(10000);
}
TEST_F(ConnectionHandlerTest, CloseConnectionSessionsWithCommonReason) {
@@ -591,24 +923,28 @@ TEST_F(ConnectionHandlerTest, CloseConnectionSessionsWithCommonReason) {
AddTestSession();
AddTestService(kAudio);
AddTestService(kMobileNav);
- connection_handler_test::ConnectionHandlerObserverMock mock_connection_handler_observer;
- connection_handler_->set_connection_handler_observer(&mock_connection_handler_observer);
-
- protocol_handler_test::ProtocolHandlerMock mock_protocol_handler;
- connection_handler_->set_protocol_handler(&mock_protocol_handler);
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
- EXPECT_CALL(mock_protocol_handler, SendEndSession(uid_,start_session_id_));
+ connection_handler_->set_protocol_handler(&mock_protocol_handler_);
+ EXPECT_CALL(mock_protocol_handler_, SendEndSession(uid_, start_session_id_))
+ .Times(1);
InSequence seq;
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kMobileNav, kCommon)).Times(1);
+ OnServiceEndedCallback(connection_key_, kMobileNav, kCommon))
+ .Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kAudio, kCommon)).Times(1);
+ OnServiceEndedCallback(connection_key_, kAudio, kCommon))
+ .Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kBulk, kCommon)).Times(1);
+ OnServiceEndedCallback(connection_key_, kBulk, kCommon)).Times(1);
EXPECT_CALL(mock_connection_handler_observer,
- OnServiceEndedCallback(connection_key_,kRpc, kCommon)).Times(1);
+ OnServiceEndedCallback(connection_key_, kRpc, kCommon)).Times(1);
connection_handler_->CloseConnectionSessions(uid_, kCommon);
+ Mock::AsyncVerifyAndClearExpectations(10000);
}
TEST_F(ConnectionHandlerTest, StartService_withServices) {
@@ -618,7 +954,7 @@ TEST_F(ConnectionHandlerTest, StartService_withServices) {
// Start Audio service
const uint32_t start_audio = connection_handler_->OnSessionStartedCallback(
- uid_, start_session_id_, kAudio, PROTECTION_OFF, &out_hash_id_);
+ uid_, start_session_id_, kAudio, PROTECTION_OFF, &out_hash_id_);
EXPECT_EQ(start_session_id_, start_audio);
CheckServiceExists(uid_, start_session_id_, kAudio, true);
EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_);
@@ -634,8 +970,8 @@ TEST_F(ConnectionHandlerTest, StartService_withServices) {
TEST_F(ConnectionHandlerTest, ServiceStop_UnExistSession) {
AddTestDeviceConnection();
- const uint32_t end_session_result = connection_handler_->OnSessionEndedCallback(
- uid_, 0u, 0u, kAudio);
+ const uint32_t end_session_result =
+ connection_handler_->OnSessionEndedCallback(uid_, 0u, 0u, kAudio);
EXPECT_EQ(0u, end_session_result);
CheckSessionExists(uid_, 0);
}
@@ -643,8 +979,9 @@ TEST_F(ConnectionHandlerTest, ServiceStop_UnExistSession) {
TEST_F(ConnectionHandlerTest, ServiceStop_UnExistService) {
AddTestDeviceConnection();
AddTestSession();
- const uint32_t end_session_result = connection_handler_->OnSessionEndedCallback(
- uid_, start_session_id_, 0u, kAudio);
+ const uint32_t end_session_result =
+ connection_handler_->OnSessionEndedCallback(
+ uid_, start_session_id_, 0u, kAudio);
EXPECT_EQ(0u, end_session_result);
CheckServiceExists(uid_, start_session_id_, kAudio, false);
}
@@ -656,12 +993,13 @@ TEST_F(ConnectionHandlerTest, ServiceStop) {
for (uint32_t some_hash_id = 0; some_hash_id < 0xFF; ++some_hash_id) {
// Start audio service
const uint32_t start_audio = connection_handler_->OnSessionStartedCallback(
- uid_, start_session_id_, kAudio, PROTECTION_OFF, &out_hash_id_);
+ uid_, start_session_id_, kAudio, PROTECTION_OFF, &out_hash_id_);
EXPECT_EQ(start_session_id_, start_audio);
EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_);
- const uint32_t end_session_result = connection_handler_->OnSessionEndedCallback(
- uid_, start_session_id_, some_hash_id, kAudio);
+ const uint32_t end_session_result =
+ connection_handler_->OnSessionEndedCallback(
+ uid_, start_session_id_, some_hash_id, kAudio);
EXPECT_EQ(connection_key_, end_session_result);
CheckServiceExists(uid_, start_session_id_, kAudio, false);
}
@@ -675,13 +1013,14 @@ TEST_F(ConnectionHandlerTest, SessionStop_CheckHash) {
const uint32_t hash = connection_key_;
const uint32_t wrong_hash = hash + 1;
- const uint32_t end_audio_wrong_hash = connection_handler_->OnSessionEndedCallback(
- uid_, start_session_id_, wrong_hash, kRpc);
+ const uint32_t end_audio_wrong_hash =
+ connection_handler_->OnSessionEndedCallback(
+ uid_, start_session_id_, wrong_hash, kRpc);
EXPECT_EQ(0u, end_audio_wrong_hash);
CheckSessionExists(uid_, start_session_id_);
const uint32_t end_audio = connection_handler_->OnSessionEndedCallback(
- uid_, start_session_id_, hash, kRpc);
+ uid_, start_session_id_, hash, kRpc);
EXPECT_EQ(connection_key_, end_audio);
CheckSessionExists(uid_, 0);
}
@@ -695,26 +1034,53 @@ TEST_F(ConnectionHandlerTest, SessionStop_CheckSpecificHash) {
const uint32_t wrong_hash = protocol_handler::HASH_ID_WRONG;
const uint32_t hash = protocol_handler::HASH_ID_NOT_SUPPORTED;
- const uint32_t end_audio_wrong_hash = connection_handler_->OnSessionEndedCallback(
- uid_, start_session_id_, wrong_hash, kRpc);
+ const uint32_t end_audio_wrong_hash =
+ connection_handler_->OnSessionEndedCallback(
+ uid_, start_session_id_, wrong_hash, kRpc);
EXPECT_EQ(0u, end_audio_wrong_hash);
CheckSessionExists(uid_, start_session_id_);
const uint32_t end_audio = connection_handler_->OnSessionEndedCallback(
- uid_, start_session_id_, hash, kRpc);
+ uid_, start_session_id_, hash, kRpc);
EXPECT_EQ(connection_key_, end_audio);
CheckSessionExists(uid_, 0);
}
}
-TEST_F(ConnectionHandlerTest, SessionStarted_StartSession_SecureSpecific_Unprotect) {
+TEST_F(ConnectionHandlerTest, SessionStarted_WithRpc) {
+ // Add virtual device and connection
+ AddTestDeviceConnection();
+ // Expect that rpc service has started
+ connection_handler_test::ConnectionHandlerObserverMock
+ mock_connection_handler_observer;
+ connection_handler_->set_connection_handler_observer(
+ &mock_connection_handler_observer);
+ uint32_t session_key =
+ connection_handler_->KeyFromPair(uid_, start_session_id_);
+ EXPECT_CALL(mock_connection_handler_observer,
+ OnServiceStartedCallback(device_handle_, session_key, kRpc))
+ .WillOnce(Return(true));
+
+ // Start new session with RPC service
+ uint32_t new_session_id = connection_handler_->OnSessionStartedCallback(
+ uid_, 0, kRpc, PROTECTION_OFF, &out_hash_id_);
+
+ EXPECT_NE(0u, new_session_id);
+}
+
+TEST_F(ConnectionHandlerTest,
+ SessionStarted_StartSession_SecureSpecific_Unprotect) {
+ EXPECT_CALL(mock_connection_handler_settings, heart_beat_timeout())
+ .WillOnce(Return(heartbeat_timeout));
// Add virtual device and connection
AddTestDeviceConnection();
// Forbid start kRPC without encryption
- SetSpecificServices("0x07", "");
+ protected_services_.push_back(kRpc);
+ SetSpecificServices();
// Start new session with RPC service
- const uint32_t session_id_fail = connection_handler_->OnSessionStartedCallback(
- uid_, 0, kRpc, PROTECTION_OFF, &out_hash_id_);
+ const uint32_t session_id_fail =
+ connection_handler_->OnSessionStartedCallback(
+ uid_, 0, kRpc, PROTECTION_OFF, &out_hash_id_);
#ifdef ENABLE_SECURITY
EXPECT_EQ(0u, session_id_fail);
EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id_);
@@ -724,23 +1090,31 @@ TEST_F(ConnectionHandlerTest, SessionStarted_StartSession_SecureSpecific_Unprote
#endif // ENABLE_SECURITY
// Allow start kRPC without encryption
- SetSpecificServices("0x00, Non", "");
+ protected_services_.clear();
+ protected_services_.push_back(kControl);
+ SetSpecificServices();
// Start new session with RPC service
const uint32_t session_id = connection_handler_->OnSessionStartedCallback(
- uid_, 0, kRpc, PROTECTION_OFF, &out_hash_id_);
+ uid_, 0, kRpc, PROTECTION_OFF, &out_hash_id_);
EXPECT_NE(0u, session_id);
CheckService(uid_, session_id, kRpc, NULL, PROTECTION_OFF);
EXPECT_EQ(SessionHash(uid_, session_id), out_hash_id_);
}
-TEST_F(ConnectionHandlerTest, SessionStarted_StartSession_SecureSpecific_Protect) {
+TEST_F(ConnectionHandlerTest,
+ SessionStarted_StartSession_SecureSpecific_Protect) {
// Add virtual device and connection
AddTestDeviceConnection();
// Forbid start kRPC with encryption
- SetSpecificServices("", "0x06, 0x07, 0x08, Non");
+ unprotected_services_.push_back(UnnamedService::kServedService1);
+ unprotected_services_.push_back(kRpc);
+ unprotected_services_.push_back(UnnamedService::kServedService2);
+ unprotected_services_.push_back(kControl);
+ SetSpecificServices();
// Start new session with RPC service
- const uint32_t session_id_fail = connection_handler_->OnSessionStartedCallback(
- uid_, 0, kRpc, PROTECTION_ON, NULL);
+ const uint32_t session_id_fail =
+ connection_handler_->OnSessionStartedCallback(
+ uid_, 0, kRpc, PROTECTION_ON, NULL);
#ifdef ENABLE_SECURITY
EXPECT_EQ(0u, session_id_fail);
#else
@@ -748,10 +1122,12 @@ TEST_F(ConnectionHandlerTest, SessionStarted_StartSession_SecureSpecific_Protect
#endif // ENABLE_SECURITY
// Allow start kRPC with encryption
- SetSpecificServices("", "0x00, 0x05, Non");
+ unprotected_services_.clear();
+ unprotected_services_.push_back(kControl);
+ SetSpecificServices();
// Start new session with RPC service
const uint32_t session_id = connection_handler_->OnSessionStartedCallback(
- uid_, 0, kRpc, PROTECTION_ON, &out_hash_id_);
+ uid_, 0, kRpc, PROTECTION_ON, &out_hash_id_);
EXPECT_NE(0u, session_id);
EXPECT_EQ(SessionHash(uid_, session_id), out_hash_id_);
@@ -759,67 +1135,75 @@ TEST_F(ConnectionHandlerTest, SessionStarted_StartSession_SecureSpecific_Protect
CheckService(uid_, session_id, kRpc, NULL, PROTECTION_OFF);
}
-TEST_F(ConnectionHandlerTest, SessionStarted_StartService_SecureSpecific_Unprotect) {
+TEST_F(ConnectionHandlerTest,
+ SessionStarted_StartService_SecureSpecific_Unprotect) {
AddTestDeviceConnection();
AddTestSession();
- // Audio is 0x0A
- ASSERT_EQ(0x0A, kAudio);
-
// Forbid start kAudio without encryption
- SetSpecificServices("0x06, 0x0A, 0x08, Non", "");
+ protected_services_.push_back(UnnamedService::kServedService1);
+ protected_services_.push_back(kAudio);
+ protected_services_.push_back(UnnamedService::kServedService2);
+ protected_services_.push_back(kControl);
+ SetSpecificServices();
// Start new session with Audio service
const uint32_t session_id2 = connection_handler_->OnSessionStartedCallback(
- uid_, start_session_id_, kAudio, PROTECTION_OFF, NULL);
+ uid_, start_session_id_, kAudio, PROTECTION_OFF, NULL);
#ifdef ENABLE_SECURITY
EXPECT_EQ(0u, session_id2);
#else
EXPECT_EQ(1u, session_id2);
#endif // ENABLE_SECURITY
// Allow start kAudio without encryption
- SetSpecificServices("0x06, 0x0B, 0x08, Non", "");
+ protected_services_.clear();
+ protected_services_.push_back(UnnamedService::kServedService1);
+ protected_services_.push_back(kMobileNav);
+ protected_services_.push_back(UnnamedService::kServedService2);
+ protected_services_.push_back(kControl);
+ SetSpecificServices();
const uint32_t session_id3 = connection_handler_->OnSessionStartedCallback(
- uid_, start_session_id_, kAudio, PROTECTION_OFF, &out_hash_id_);
- // Returned original session id
+ uid_, start_session_id_, kAudio, PROTECTION_OFF, &out_hash_id_);
+// Returned original session id
#ifdef ENABLE_SECURITY
EXPECT_EQ(start_session_id_, session_id3);
EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_);
- CheckService(uid_, session_id3, kRpc,
- NULL,
- PROTECTION_OFF);
+ CheckService(uid_, session_id3, kRpc, NULL, PROTECTION_OFF);
#else
EXPECT_EQ(0u, session_id3);
EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id_);
#endif // ENABLE_SECURITY
}
-TEST_F(ConnectionHandlerTest, SessionStarted_StartService_SecureSpecific_Protect) {
+TEST_F(ConnectionHandlerTest,
+ SessionStarted_StartService_SecureSpecific_Protect) {
AddTestDeviceConnection();
AddTestSession();
- // Audio is 0x0A
- ASSERT_EQ(0x0A, kAudio);
// Forbid start kAudio with encryption
- SetSpecificServices("", "0x06, 0x0A, 0x08, Non");
+ unprotected_services_.push_back(UnnamedService::kServedService1);
+ unprotected_services_.push_back(kAudio);
+ unprotected_services_.push_back(UnnamedService::kServedService2);
+ unprotected_services_.push_back(kControl);
+ SetSpecificServices();
// Start new session with Audio service
- const uint32_t session_id_reject = connection_handler_->OnSessionStartedCallback(
- uid_, start_session_id_, kAudio, PROTECTION_ON, NULL);
+ const uint32_t session_id_reject =
+ connection_handler_->OnSessionStartedCallback(
+ uid_, start_session_id_, kAudio, PROTECTION_ON, NULL);
#ifdef ENABLE_SECURITY
EXPECT_EQ(0u, session_id_reject);
#else
EXPECT_EQ(1u, session_id_reject);
#endif // ENABLE_SECURITY
// Allow start kAudio with encryption
- SetSpecificServices("", "Non");
+ unprotected_services_.clear();
+ SetSpecificServices();
const uint32_t session_id3 = connection_handler_->OnSessionStartedCallback(
- uid_, start_session_id_, kAudio, PROTECTION_ON, &out_hash_id_);
- // Returned original session id
+ uid_, start_session_id_, kAudio, PROTECTION_ON, &out_hash_id_);
+// Returned original session id
#ifdef ENABLE_SECURITY
EXPECT_EQ(start_session_id_, session_id3);
EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_);
- CheckService(uid_, session_id3, kAudio,
- NULL,
- PROTECTION_ON);
+ CheckService(uid_, session_id3, kAudio, NULL, PROTECTION_ON);
#else
EXPECT_EQ(0u, session_id3);
EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id_);
@@ -833,14 +1217,12 @@ TEST_F(ConnectionHandlerTest, SessionStarted_DealyProtect) {
// Start RPC protection
const uint32_t session_id_new = connection_handler_->OnSessionStartedCallback(
- uid_, start_session_id_, kRpc, PROTECTION_ON, &out_hash_id_);
+ uid_, start_session_id_, kRpc, PROTECTION_ON, &out_hash_id_);
#ifdef ENABLE_SECURITY
EXPECT_EQ(start_session_id_, session_id_new);
// Post protection nedd no hash
EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_);
- CheckService(uid_, start_session_id_, kRpc,
- NULL,
- PROTECTION_ON);
+ CheckService(uid_, start_session_id_, kRpc, NULL, PROTECTION_ON);
#else
EXPECT_EQ(0u, session_id_new);
// Post protection nedd no hash
@@ -850,20 +1232,18 @@ TEST_F(ConnectionHandlerTest, SessionStarted_DealyProtect) {
// Start Audio session without protection
const uint32_t session_id2 = connection_handler_->OnSessionStartedCallback(
- uid_, start_session_id_, kAudio, PROTECTION_OFF, &out_hash_id_);
+ uid_, start_session_id_, kAudio, PROTECTION_OFF, &out_hash_id_);
EXPECT_EQ(start_session_id_, session_id2);
EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_);
CheckService(uid_, start_session_id_, kAudio, NULL, PROTECTION_OFF);
// Start Audio protection
const uint32_t session_id3 = connection_handler_->OnSessionStartedCallback(
- uid_, start_session_id_, kAudio, PROTECTION_ON, &out_hash_id_);
+ uid_, start_session_id_, kAudio, PROTECTION_ON, &out_hash_id_);
#ifdef ENABLE_SECURITY
EXPECT_EQ(start_session_id_, session_id3);
EXPECT_EQ(protocol_handler::HASH_ID_NOT_SUPPORTED, out_hash_id_);
- CheckService(uid_, start_session_id_, kAudio,
- NULL,
- PROTECTION_ON);
+ CheckService(uid_, start_session_id_, kAudio, NULL, PROTECTION_ON);
#else
EXPECT_EQ(0u, session_id3);
EXPECT_EQ(protocol_handler::HASH_ID_WRONG, out_hash_id_);
@@ -876,12 +1256,10 @@ TEST_F(ConnectionHandlerTest, SessionStarted_DealyProtectBulk) {
AddTestSession();
const uint32_t session_id_new = connection_handler_->OnSessionStartedCallback(
- uid_, start_session_id_, kBulk, PROTECTION_ON, NULL);
+ uid_, start_session_id_, kBulk, PROTECTION_ON, NULL);
#ifdef ENABLE_SECURITY
EXPECT_EQ(start_session_id_, session_id_new);
- CheckService(uid_, start_session_id_, kRpc,
- NULL,
- PROTECTION_ON);
+ CheckService(uid_, start_session_id_, kRpc, NULL, PROTECTION_ON);
#else
EXPECT_EQ(0u, session_id_new);
CheckService(uid_, start_session_id_, kRpc, NULL, PROTECTION_OFF);
@@ -892,40 +1270,41 @@ TEST_F(ConnectionHandlerTest, SessionStarted_DealyProtectBulk) {
TEST_F(ConnectionHandlerTest, SetSSLContext_Null) {
// No SSLContext on start up
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
EXPECT_EQ(::security_manager::SecurityManager::ERROR_INTERNAL,
- connection_handler_->SetSSLContext(connection_key_, NULL));
+ connection_handler_->SetSSLContext(connection_key_, NULL));
// No SSLContext after error
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
AddTestDeviceConnection();
EXPECT_EQ(::security_manager::SecurityManager::ERROR_INTERNAL,
- connection_handler_->SetSSLContext(connection_key_, NULL));
+ connection_handler_->SetSSLContext(connection_key_, NULL));
// No SSLContext after error
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
AddTestSession();
EXPECT_EQ(::security_manager::SecurityManager::ERROR_SUCCESS,
- connection_handler_->SetSSLContext(connection_key_, NULL));
+ connection_handler_->SetSSLContext(connection_key_, NULL));
// NULL SSLContext after success
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
}
+
TEST_F(ConnectionHandlerTest, SetSSLContext) {
// No SSLContext on start up
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
- testing::StrictMock<security_manager_test::SSLContextMock> mock_ssl_context;
+ testing::StrictMock<security_manager_test::MockSSLContext> mock_ssl_context;
// Error on no connection
EXPECT_EQ(
connection_handler_->SetSSLContext(connection_key_, &mock_ssl_context),
::security_manager::SecurityManager::ERROR_INTERNAL);
// No SSLContext after error
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
AddTestDeviceConnection();
// Error on no session
@@ -934,7 +1313,7 @@ TEST_F(ConnectionHandlerTest, SetSSLContext) {
::security_manager::SecurityManager::ERROR_INTERNAL);
// No SSLContext after error
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
AddTestSession();
// Success
EXPECT_EQ(
@@ -942,24 +1321,24 @@ TEST_F(ConnectionHandlerTest, SetSSLContext) {
::security_manager::SecurityManager::ERROR_SUCCESS);
// SSLContext set on Success
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl),
- &mock_ssl_context);
+ &mock_ssl_context);
// Null SSLContext for unprotected services
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kRpc),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kBulk),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kAudio),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kMobileNav),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
}
TEST_F(ConnectionHandlerTest, GetSSLContext_ByProtectedService) {
// No SSLContext on start up
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
- testing::StrictMock<security_manager_test::SSLContextMock> mock_ssl_context;
+ testing::StrictMock<security_manager_test::MockSSLContext> mock_ssl_context;
AddTestDeviceConnection();
AddTestSession();
EXPECT_EQ(
@@ -967,11 +1346,11 @@ TEST_F(ConnectionHandlerTest, GetSSLContext_ByProtectedService) {
::security_manager::SecurityManager::ERROR_SUCCESS);
// kControl service mean - return for all connection
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl),
- &mock_ssl_context);
+ &mock_ssl_context);
// kAudio is not exists yet
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kAudio),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
// Open kAudio service
const uint32_t session_id = connection_handler_->OnSessionStartedCallback(
uid_, start_session_id_, kAudio, PROTECTION_ON, NULL);
@@ -980,21 +1359,22 @@ TEST_F(ConnectionHandlerTest, GetSSLContext_ByProtectedService) {
// kAudio is not exists yet
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kAudio),
- &mock_ssl_context);
+ &mock_ssl_context);
}
+
TEST_F(ConnectionHandlerTest, GetSSLContext_ByDealyProtectedRPC) {
- testing::StrictMock<security_manager_test::SSLContextMock> mock_ssl_context;
+ testing::StrictMock<security_manager_test::MockSSLContext> mock_ssl_context;
AddTestDeviceConnection();
AddTestSession();
EXPECT_EQ(
connection_handler_->SetSSLContext(connection_key_, &mock_ssl_context),
::security_manager::SecurityManager::ERROR_SUCCESS);
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl),
- &mock_ssl_context);
+ &mock_ssl_context);
// kRpc is not protected
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kRpc),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
// Protect kRpc (Bulk will be protect also)
const uint32_t session_id = connection_handler_->OnSessionStartedCallback(
@@ -1004,24 +1384,25 @@ TEST_F(ConnectionHandlerTest, GetSSLContext_ByDealyProtectedRPC) {
// kRpc is protected
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kRpc),
- &mock_ssl_context);
+ &mock_ssl_context);
// kBulk is protected
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kBulk),
- &mock_ssl_context);
+ &mock_ssl_context);
}
+
TEST_F(ConnectionHandlerTest, GetSSLContext_ByDealyProtectedBulk) {
- testing::StrictMock<security_manager_test::SSLContextMock> mock_ssl_context;
+ testing::StrictMock<security_manager_test::MockSSLContext> mock_ssl_context;
AddTestDeviceConnection();
AddTestSession();
EXPECT_EQ(
connection_handler_->SetSSLContext(connection_key_, &mock_ssl_context),
::security_manager::SecurityManager::ERROR_SUCCESS);
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kControl),
- &mock_ssl_context);
+ &mock_ssl_context);
// kRpc is not protected
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kRpc),
- reinterpret_cast<security_manager::SSLContext *>(NULL));
+ reinterpret_cast<security_manager::SSLContext*>(NULL));
// Protect Bulk (kRpc will be protected also)
const uint32_t session_id = connection_handler_->OnSessionStartedCallback(
@@ -1031,13 +1412,22 @@ TEST_F(ConnectionHandlerTest, GetSSLContext_ByDealyProtectedBulk) {
// kRpc is protected
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kRpc),
- &mock_ssl_context);
+ &mock_ssl_context);
// kBulk is protected
EXPECT_EQ(connection_handler_->GetSSLContext(connection_key_, kBulk),
- &mock_ssl_context);
+ &mock_ssl_context);
}
#endif // ENABLE_SECURITY
-} // namespace connection_handle_test
+TEST_F(ConnectionHandlerTest, SendHeartBeat) {
+ // Add virtual device and connection
+ AddTestDeviceConnection();
+ AddTestSession();
+ connection_handler_->set_protocol_handler(&mock_protocol_handler_);
+ EXPECT_CALL(mock_protocol_handler_, SendHeartBeat(uid_, start_session_id_));
+ connection_handler_->SendHeartBeat(uid_, start_session_id_);
+}
+
+} // namespace connection_handler_test
} // namespace components
} // namespace test
diff --git a/src/components/connection_handler/test/connection_test.cc b/src/components/connection_handler/test/connection_test.cc
index a1e9307ce3..e36e9aa65c 100644
--- a/src/components/connection_handler/test/connection_test.cc
+++ b/src/components/connection_handler/test/connection_test.cc
@@ -30,14 +30,18 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include <gtest/gtest.h>
#include <algorithm>
+
+#include "gtest/gtest.h"
+
#include "protocol/common.h"
#include "connection_handler/connection.h"
#include "connection_handler/connection_handler_impl.h"
#include "protocol/service_type.h"
-#include "utils/shared_ptr.h"
-#include "security_manager_mock.h"
+#include "connection_handler/mock_connection_handler_settings.h"
+#include "transport_manager/mock_transport_manager.h"
+#include "security_manager/mock_security_manager.h"
+#include "security_manager/mock_ssl_context.h"
#define EXPECT_RETURN_TRUE true
#define EXPECT_RETURN_FALSE false
@@ -46,24 +50,25 @@
namespace test {
namespace components {
-namespace connection_handle {
+namespace connection_handler_test {
using namespace ::connection_handler;
using namespace ::protocol_handler;
class ConnectionTest : public ::testing::Test {
protected:
void SetUp() OVERRIDE {
- connection_handler_ = ConnectionHandlerImpl::instance();
+ connection_handler_ = new ConnectionHandlerImpl(
+ mock_connection_handler_settings, transport_manager_mock);
const ConnectionHandle connectionHandle = 0;
- const DeviceHandle device_handle = 0;
- connection_.reset(
- new Connection(connectionHandle, device_handle, connection_handler_,
- 10000));
+ const DeviceHandle device_handle = 0u;
+ const uint32_t heart_beat = 10000u;
+ connection_ = new Connection(
+ connectionHandle, device_handle, connection_handler_, heart_beat);
}
void TearDown() OVERRIDE {
- connection_.reset();
- ConnectionHandlerImpl::destroy();
+ delete connection_;
+ delete connection_handler_;
}
void StartSession() {
session_id = connection_->AddNewSession();
@@ -72,17 +77,17 @@ class ConnectionTest : public ::testing::Test {
EXPECT_FALSE(sessionMap.empty());
const ServiceList serviceList = sessionMap.begin()->second.service_list;
EXPECT_FALSE(serviceList.empty());
- const ServiceList::const_iterator it = std::find(serviceList.begin(),
- serviceList.end(),
- protocol_handler::kRpc);
- EXPECT_NE(it, serviceList.end());
+ const ServiceList::const_iterator it =
+ std::find(serviceList.begin(), serviceList.end(), kRpc);
+ const bool found_result = (it != serviceList.end());
+ EXPECT_TRUE(found_result);
}
- void AddNewService(const protocol_handler::ServiceType service_type,
+ void AddNewService(const ServiceType service_type,
const bool protection,
const bool expect_add_new_service_call_result,
const bool expect_exist_service) {
- const bool result = connection_->AddNewService(session_id, service_type,
- protection);
+ const bool result =
+ connection_->AddNewService(session_id, service_type, protection);
EXPECT_EQ(result, expect_add_new_service_call_result);
#ifdef ENABLE_SECURITY
@@ -94,9 +99,8 @@ class ConnectionTest : public ::testing::Test {
EXPECT_FALSE(session_map.empty());
const ServiceList newServiceList = session_map.begin()->second.service_list;
EXPECT_FALSE(newServiceList.empty());
- const ServiceList::const_iterator it = std::find(newServiceList.begin(),
- newServiceList.end(),
- service_type);
+ const ServiceList::const_iterator it =
+ std::find(newServiceList.begin(), newServiceList.end(), service_type);
const bool found_result = it != newServiceList.end();
EXPECT_EQ(expect_exist_service, found_result);
#ifdef ENABLE_SECURITY
@@ -107,7 +111,7 @@ class ConnectionTest : public ::testing::Test {
#endif // ENABLE_SECURITY
}
- void RemoveService(const protocol_handler::ServiceType service_type,
+ void RemoveService(const ServiceType service_type,
const bool expect_remove_service_result,
const bool expect_exist_service) {
const bool result = connection_->RemoveService(session_id, service_type);
@@ -115,22 +119,23 @@ class ConnectionTest : public ::testing::Test {
const SessionMap newSessionMap = connection_->session_map();
EXPECT_FALSE(newSessionMap.empty());
- const ServiceList newServiceList = newSessionMap.begin()->second
- .service_list;
+ const ServiceList newServiceList =
+ newSessionMap.begin()->second.service_list;
EXPECT_FALSE(newServiceList.empty());
- const ServiceList::const_iterator it = std::find(newServiceList.begin(),
- newServiceList.end(),
- service_type);
- const bool found_result = it != newServiceList.end();
+ const ServiceList::const_iterator it =
+ std::find(newServiceList.begin(), newServiceList.end(), service_type);
+ const bool found_result = (it != newServiceList.end());
EXPECT_EQ(expect_exist_service, found_result);
}
- ::utils::SharedPtr<Connection> connection_;
+ Connection* connection_;
+ MockConnectionHandlerSettings mock_connection_handler_settings;
+ testing::StrictMock<transport_manager_test::MockTransportManager>
+ transport_manager_mock;
ConnectionHandlerImpl* connection_handler_;
uint32_t session_id;
};
-
TEST_F(ConnectionTest, Session_TryGetProtocolVersionWithoutSession) {
uint8_t protocol_version;
EXPECT_FALSE(connection_->ProtocolVersion(session_id, protocol_version));
@@ -140,14 +145,14 @@ TEST_F(ConnectionTest, Session_GetDefaultProtocolVersion) {
StartSession();
uint8_t protocol_version;
EXPECT_TRUE(connection_->ProtocolVersion(session_id, protocol_version));
- EXPECT_EQ(protocol_version, ::protocol_handler::PROTOCOL_VERSION_2);
+ EXPECT_EQ(static_cast<uint8_t>(PROTOCOL_VERSION_2), protocol_version);
}
TEST_F(ConnectionTest, Session_UpdateProtocolVersion) {
StartSession();
- uint8_t protocol_version = ::protocol_handler::PROTOCOL_VERSION_3;
+ uint8_t protocol_version = static_cast<uint8_t>(PROTOCOL_VERSION_3);
connection_->UpdateProtocolVersionSession(session_id, protocol_version);
EXPECT_TRUE(connection_->ProtocolVersion(session_id, protocol_version));
- EXPECT_EQ(protocol_version, ::protocol_handler::PROTOCOL_VERSION_3);
+ EXPECT_EQ(static_cast<uint8_t>(PROTOCOL_VERSION_3), protocol_version);
}
TEST_F(ConnectionTest, HeartBeat_NotSupported) {
@@ -155,44 +160,64 @@ TEST_F(ConnectionTest, HeartBeat_NotSupported) {
StartSession();
uint8_t protocol_version;
EXPECT_TRUE(connection_->ProtocolVersion(session_id, protocol_version));
- EXPECT_EQ(protocol_version, ::protocol_handler::PROTOCOL_VERSION_2);
+ EXPECT_EQ(static_cast<uint8_t>(PROTOCOL_VERSION_2), protocol_version);
// Assert
EXPECT_FALSE(connection_->SupportHeartBeat(session_id));
}
-TEST_F(ConnectionTest, DISABLED_HeartBeat_Supported) {
+TEST_F(ConnectionTest, HeartBeat_Protocol3_Supported) {
// Arrange
StartSession();
-
- // Check if protocol version is 3
- uint8_t protocol_version = ::protocol_handler::PROTOCOL_VERSION_3;
+ // Check execution if protocol version is 3
+ const uint8_t protocol_version = static_cast<uint8_t>(PROTOCOL_VERSION_3);
connection_->UpdateProtocolVersionSession(session_id, protocol_version);
- EXPECT_EQ(protocol_version, ::protocol_handler::PROTOCOL_VERSION_3);
+ EXPECT_TRUE(connection_->SupportHeartBeat(session_id));
+}
- // Assert
+TEST_F(ConnectionTest, HeartBeat_Protocol4_PositiveHeartBeat_Supported) {
+ // Arrange
+ StartSession();
+ // Check execution if protocol version is 4
+ const uint8_t protocol_version = static_cast<uint8_t>(PROTOCOL_VERSION_4);
+ connection_->UpdateProtocolVersionSession(session_id, protocol_version);
EXPECT_TRUE(connection_->SupportHeartBeat(session_id));
}
+TEST_F(ConnectionTest, HeartBeat_Protocol4_ZeroHeartBeat_NotSupported) {
+ // Correctc of connection (need connection with heartbeat=0)
+ delete connection_;
+ connection_ = 0;
+
+ const ConnectionHandle connectionHandle = 0;
+ const DeviceHandle device_handle = 0u;
+ const uint32_t heart_beat = 0u;
+ connection_ = new Connection(
+ connectionHandle, device_handle, connection_handler_, heart_beat);
+ StartSession();
+ // Check execution if protocol version is 4
+ const uint8_t protocol_version = static_cast<uint8_t>(PROTOCOL_VERSION_4);
+ connection_->UpdateProtocolVersionSession(session_id, protocol_version);
+ EXPECT_FALSE(connection_->SupportHeartBeat(session_id));
+}
+
// Try to add service without session
TEST_F(ConnectionTest, Session_AddNewServiceWithoutSession) {
- EXPECT_EQ(
- connection_->AddNewService(session_id, protocol_handler::kAudio, true),
- EXPECT_RETURN_FALSE);
- EXPECT_EQ(
- connection_->AddNewService(session_id, protocol_handler::kAudio, false),
- EXPECT_RETURN_FALSE);
- EXPECT_EQ(
- connection_->AddNewService(session_id, protocol_handler::kMobileNav, true),
- EXPECT_RETURN_FALSE);
- EXPECT_EQ(
- connection_->AddNewService(session_id, protocol_handler::kMobileNav, false),
- EXPECT_RETURN_FALSE);
+ EXPECT_EQ(connection_->AddNewService(session_id, kAudio, true),
+ EXPECT_RETURN_FALSE);
+ EXPECT_EQ(connection_->AddNewService(session_id, kAudio, false),
+ EXPECT_RETURN_FALSE);
+ EXPECT_EQ(connection_->AddNewService(session_id, kMobileNav, true),
+ EXPECT_RETURN_FALSE);
+ EXPECT_EQ(connection_->AddNewService(session_id, kMobileNav, false),
+ EXPECT_RETURN_FALSE);
}
// Try to remove service without session
TEST_F(ConnectionTest, Session_RemoveServiceWithoutSession) {
- EXPECT_EQ(connection_->RemoveService(session_id, protocol_handler::kAudio),
+ EXPECT_EQ(connection_->RemoveService(session_id, kAudio),
+ EXPECT_RETURN_FALSE);
+ EXPECT_EQ(connection_->RemoveService(session_id, kMobileNav),
EXPECT_RETURN_FALSE);
EXPECT_EQ(
connection_->RemoveService(session_id, protocol_handler::kMobileNav),
@@ -201,70 +226,67 @@ TEST_F(ConnectionTest, Session_RemoveServiceWithoutSession) {
// Try to remove RPC
TEST_F(ConnectionTest, Session_RemoveRPCBulk) {
StartSession();
- EXPECT_EQ(connection_->RemoveService(session_id, protocol_handler::kRpc),
- EXPECT_RETURN_FALSE);
- EXPECT_EQ(connection_->RemoveService(session_id, protocol_handler::kBulk),
- EXPECT_RETURN_FALSE);
+ EXPECT_EQ(connection_->RemoveService(session_id, kRpc), EXPECT_RETURN_FALSE);
+ EXPECT_EQ(connection_->RemoveService(session_id, kBulk), EXPECT_RETURN_FALSE);
}
// Control Service could not be started anyway
TEST_F(ConnectionTest, Session_AddControlService) {
StartSession();
-
- AddNewService(protocol_handler::kControl, PROTECTION_OFF, EXPECT_RETURN_FALSE,
- EXPECT_SERVICE_NOT_EXISTS);
- AddNewService(protocol_handler::kControl, PROTECTION_ON, EXPECT_RETURN_FALSE,
- EXPECT_SERVICE_NOT_EXISTS);
+ AddNewService(
+ kControl, PROTECTION_OFF, EXPECT_RETURN_FALSE, EXPECT_SERVICE_NOT_EXISTS);
+ AddNewService(
+ kControl, PROTECTION_ON, EXPECT_RETURN_FALSE, EXPECT_SERVICE_NOT_EXISTS);
}
// Invalid Services couldnot be started anyway
TEST_F(ConnectionTest, Session_AddInvalidService) {
StartSession();
- AddNewService(protocol_handler::kInvalidServiceType, PROTECTION_OFF,
- EXPECT_RETURN_FALSE, EXPECT_SERVICE_NOT_EXISTS);
- AddNewService(protocol_handler::kInvalidServiceType, PROTECTION_ON,
- EXPECT_RETURN_FALSE, EXPECT_SERVICE_NOT_EXISTS);
+ AddNewService(kInvalidServiceType,
+ PROTECTION_OFF,
+ EXPECT_RETURN_FALSE,
+ EXPECT_SERVICE_NOT_EXISTS);
+ AddNewService(kInvalidServiceType,
+ PROTECTION_ON,
+ EXPECT_RETURN_FALSE,
+ EXPECT_SERVICE_NOT_EXISTS);
}
// RPC and Bulk Services could be only delay protected
TEST_F(ConnectionTest, Session_AddRPCBulkServices) {
StartSession();
- AddNewService(protocol_handler::kRpc, PROTECTION_OFF,
- EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kRpc, PROTECTION_OFF, EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
// Bulk shall not be added and shall be PROTECTION_OFF
- AddNewService(protocol_handler::kBulk, PROTECTION_OFF,
- EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kBulk, PROTECTION_OFF, EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
#ifdef ENABLE_SECURITY
- AddNewService(protocol_handler::kRpc, PROTECTION_ON,
- EXPECT_RETURN_TRUE,
- EXPECT_SERVICE_EXISTS);
+ AddNewService(kRpc, PROTECTION_ON, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
#else
- AddNewService(protocol_handler::kRpc, PROTECTION_ON,
- EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kRpc, PROTECTION_ON, EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
#endif // ENABLE_SECURITY
// Bulk shall not be added and shall be PROTECTION_ON
- AddNewService(protocol_handler::kBulk, PROTECTION_ON,
- EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kBulk, PROTECTION_ON, EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
}
TEST_F(ConnectionTest, Session_AddAllOtherService_Unprotected) {
StartSession();
-
- AddNewService(protocol_handler::kAudio, PROTECTION_OFF,
- EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
- AddNewService(protocol_handler::kMobileNav, PROTECTION_OFF,
- EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kAudio, PROTECTION_OFF, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kMobileNav, PROTECTION_OFF, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
}
TEST_F(ConnectionTest, Session_AddAllOtherService_Protected) {
StartSession();
-
- AddNewService(protocol_handler::kAudio, PROTECTION_ON,
- EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
- AddNewService(protocol_handler::kMobileNav, PROTECTION_ON,
- EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kAudio, PROTECTION_ON, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kMobileNav, PROTECTION_ON, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
}
TEST_F(ConnectionTest, FindAddedService) {
@@ -272,82 +294,79 @@ TEST_F(ConnectionTest, FindAddedService) {
// Arrange
SessionMap currentSessionMap = connection_->session_map();
- Service * sessionWithService = currentSessionMap.find(session_id)->second
- .FindService(protocol_handler::kAudio);
+ Service* sessionWithService =
+ currentSessionMap.find(session_id)->second.FindService(kAudio);
EXPECT_EQ(NULL, sessionWithService);
// Act
- AddNewService(protocol_handler::kAudio, PROTECTION_OFF,
- EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kAudio, PROTECTION_OFF, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
currentSessionMap = connection_->session_map();
// Expect that service is existing
- sessionWithService = currentSessionMap.find(session_id)->second.FindService(
- protocol_handler::kAudio);
+ sessionWithService =
+ currentSessionMap.find(session_id)->second.FindService(kAudio);
EXPECT_TRUE(sessionWithService != NULL);
}
TEST_F(ConnectionTest, Session_RemoveAddedService) {
StartSession();
- AddNewService(protocol_handler::kAudio, PROTECTION_OFF,
- EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kAudio, PROTECTION_OFF, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
- EXPECT_EQ(connection_->RemoveService(session_id, protocol_handler::kAudio),
- EXPECT_RETURN_TRUE);
+ EXPECT_EQ(connection_->RemoveService(session_id, kAudio), EXPECT_RETURN_TRUE);
// Try delete nonexisting service
- EXPECT_EQ(connection_->RemoveService(session_id, protocol_handler::kAudio),
+ EXPECT_EQ(connection_->RemoveService(session_id, kAudio),
EXPECT_RETURN_FALSE);
}
TEST_F(ConnectionTest, Session_AddAllOtherService_DelayProtected1) {
StartSession();
- AddNewService(protocol_handler::kAudio, PROTECTION_OFF,
- EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kAudio, PROTECTION_OFF, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
- AddNewService(protocol_handler::kMobileNav, PROTECTION_OFF,
- EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kMobileNav, PROTECTION_OFF, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
#ifdef ENABLE_SECURITY
- AddNewService(protocol_handler::kAudio, PROTECTION_ON,
- EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kAudio, PROTECTION_ON, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
- AddNewService(protocol_handler::kMobileNav, PROTECTION_ON,
- EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kMobileNav, PROTECTION_ON, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
#else
- AddNewService(protocol_handler::kAudio, PROTECTION_ON,
- EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kAudio, PROTECTION_ON, EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
- AddNewService(protocol_handler::kMobileNav, PROTECTION_ON,
- EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kMobileNav, PROTECTION_ON, EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
#endif // ENABLE_SECURITY
}
// Use other order
TEST_F(ConnectionTest, Session_AddAllOtherService_DelayProtected2) {
StartSession();
-
- AddNewService(protocol_handler::kAudio, PROTECTION_OFF,
- EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kAudio, PROTECTION_OFF, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
#ifdef ENABLE_SECURITY
- AddNewService(protocol_handler::kAudio, PROTECTION_ON,
- EXPECT_RETURN_TRUE,
- EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kAudio, PROTECTION_ON, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
#else
- AddNewService(protocol_handler::kAudio, PROTECTION_ON,
- EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kAudio, PROTECTION_ON, EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
#endif // ENABLE_SECURITY
- AddNewService(protocol_handler::kMobileNav, PROTECTION_OFF,
- EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kMobileNav, PROTECTION_OFF, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
#ifdef ENABLE_SECURITY
- AddNewService(protocol_handler::kMobileNav, PROTECTION_ON,
- EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kMobileNav, PROTECTION_ON, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
#else
- AddNewService(protocol_handler::kMobileNav, PROTECTION_ON,
- EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
+ AddNewService(
+ kMobileNav, PROTECTION_ON, EXPECT_RETURN_FALSE, EXPECT_SERVICE_EXISTS);
#endif // ENABLE_SECURITY
}
@@ -360,86 +379,84 @@ TEST_F(ConnectionTest, RemoveSession) {
#ifdef ENABLE_SECURITY
TEST_F(ConnectionTest, SetSSLContextWithoutSession) {
- //random value. Session was not started
+ // random value. Session was not started
uint8_t session_id = 10;
- security_manager_test::SSLContextMock mock_ssl_context;
+ security_manager_test::MockSSLContext mock_ssl_context;
int setResult = connection_->SetSSLContext(session_id, &mock_ssl_context);
- EXPECT_EQ(security_manager::SecurityManager::ERROR_INTERNAL,setResult);
+ EXPECT_EQ(security_manager::SecurityManager::ERROR_INTERNAL, setResult);
}
TEST_F(ConnectionTest, GetSSLContextWithoutSession) {
- //random value. Session was not started
+ // random value. Session was not started
uint8_t session_id = 10;
- EXPECT_EQ(NULL,connection_->GetSSLContext(session_id,protocol_handler::kMobileNav));
+ EXPECT_EQ(NULL, connection_->GetSSLContext(session_id, kMobileNav));
}
TEST_F(ConnectionTest, SetGetSSLContext) {
StartSession();
- EXPECT_EQ(NULL,connection_->GetSSLContext(session_id,protocol_handler::kMobileNav));
- AddNewService(protocol_handler::kMobileNav, PROTECTION_ON,
- EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
+ EXPECT_EQ(NULL, connection_->GetSSLContext(session_id, kMobileNav));
+ AddNewService(
+ kMobileNav, PROTECTION_ON, EXPECT_RETURN_TRUE, EXPECT_SERVICE_EXISTS);
- EXPECT_EQ(NULL,connection_->GetSSLContext(session_id,protocol_handler::kMobileNav));
+ EXPECT_EQ(NULL, connection_->GetSSLContext(session_id, kMobileNav));
- security_manager_test::SSLContextMock mock_ssl_context;
- //Set SSLContext
+ security_manager_test::MockSSLContext mock_ssl_context;
+ // Set SSLContext
int setResult = connection_->SetSSLContext(session_id, &mock_ssl_context);
- EXPECT_EQ(security_manager::SecurityManager::ERROR_SUCCESS,setResult);
+ EXPECT_EQ(security_manager::SecurityManager::ERROR_SUCCESS, setResult);
- security_manager::SSLContext *result = connection_->GetSSLContext(session_id,protocol_handler::kMobileNav);
- EXPECT_EQ(result,&mock_ssl_context);
+ security_manager::SSLContext* result =
+ connection_->GetSSLContext(session_id, kMobileNav);
+ EXPECT_EQ(result, &mock_ssl_context);
}
TEST_F(ConnectionTest, SetProtectionFlagForRPC) {
StartSession();
// Arrange
SessionMap currentSessionMap = connection_->session_map();
- Service * service_rpc = currentSessionMap.find(session_id)->second
- .FindService(protocol_handler::kRpc);
+ Service* service_rpc =
+ currentSessionMap.find(session_id)->second.FindService(kRpc);
EXPECT_FALSE(service_rpc->is_protected_);
- Service * service_bulk = currentSessionMap.find(session_id)->second
- .FindService(protocol_handler::kBulk);
+ Service* service_bulk =
+ currentSessionMap.find(session_id)->second.FindService(kBulk);
EXPECT_FALSE(service_bulk->is_protected_);
// Expect that service protection is enabled
- connection_->SetProtectionFlag(session_id, protocol_handler::kRpc);
+ connection_->SetProtectionFlag(session_id, kRpc);
currentSessionMap = connection_->session_map();
- service_bulk = currentSessionMap.find(session_id)->second
- .FindService(protocol_handler::kBulk);
+ service_bulk = currentSessionMap.find(session_id)->second.FindService(kBulk);
EXPECT_TRUE(service_bulk->is_protected_);
- service_rpc = currentSessionMap.find(session_id)->second
- .FindService(protocol_handler::kRpc);
+ service_rpc = currentSessionMap.find(session_id)->second.FindService(kRpc);
EXPECT_TRUE(service_rpc->is_protected_);
}
-
TEST_F(ConnectionTest, SetProtectionFlagForBulk) {
StartSession();
// Arrange
SessionMap currentSessionMap = connection_->session_map();
- Service * service_rpc = currentSessionMap.find(session_id)->second
- .FindService(protocol_handler::kRpc);
+ Service* service_rpc =
+ currentSessionMap.find(session_id)->second.FindService(kRpc);
EXPECT_FALSE(service_rpc->is_protected_);
- Service * service_bulk = currentSessionMap.find(session_id)->second
- .FindService(protocol_handler::kBulk);
+ Service* service_bulk =
+ currentSessionMap.find(session_id)->second.FindService(kBulk);
EXPECT_FALSE(service_bulk->is_protected_);
// Expect that service protection is enabled
- connection_->SetProtectionFlag(session_id, protocol_handler::kBulk);
+ connection_->SetProtectionFlag(session_id, kBulk);
currentSessionMap = connection_->session_map();
- service_bulk = currentSessionMap.find(session_id)->second.FindService(protocol_handler::kBulk);
+ service_bulk = currentSessionMap.find(session_id)->second.FindService(kBulk);
EXPECT_TRUE(service_bulk->is_protected_);
- service_rpc = currentSessionMap.find(session_id)->second.FindService(protocol_handler::kRpc);
+ service_rpc = currentSessionMap.find(session_id)->second.FindService(kRpc);
EXPECT_TRUE(service_rpc->is_protected_);
}
@@ -448,4 +465,3 @@ TEST_F(ConnectionTest, SetProtectionFlagForBulk) {
} // namespace connection_handle
} // namespace components
} // namespace test
-
diff --git a/src/components/connection_handler/test/device_test.cc b/src/components/connection_handler/test/device_test.cc
index dc1a51faf1..ea9aa746b5 100644
--- a/src/components/connection_handler/test/device_test.cc
+++ b/src/components/connection_handler/test/device_test.cc
@@ -55,7 +55,8 @@ TEST(ConnectionDevice, CompareDevicesWithDifferentMacAddresses) {
std::string hash_mac_address = test_device.mac_address();
std::string test_next_mac_address = "test_address_";
- Device next_test_device(device_handle, device_name, test_next_mac_address, connection_type);
+ Device next_test_device(
+ device_handle, device_name, test_next_mac_address, connection_type);
EXPECT_NE(test_next_mac_address, next_test_device.mac_address());
std::string hash_next_mac_address = next_test_device.mac_address();
@@ -77,4 +78,3 @@ TEST(ConnectionDevice, MacAddressHash) {
} // namespace connection_handle
} // namespace components
} // namespace test
-
diff --git a/src/components/connection_handler/test/heart_beat_monitor_test.cc b/src/components/connection_handler/test/heart_beat_monitor_test.cc
index 710977c643..2c928fe458 100644
--- a/src/components/connection_handler/test/heart_beat_monitor_test.cc
+++ b/src/components/connection_handler/test/heart_beat_monitor_test.cc
@@ -32,12 +32,11 @@
#include <string>
#include <iostream>
-//#include <stdio.h>
-#include "gmock/gmock.h"
+#include "gtest/gtest.h"
#include "connection_handler/heartbeat_monitor.h"
#include "connection_handler/connection.h"
#include "connection_handler/connection_handler.h"
-#include "config_profile/profile.h"
+#include "connection_handler/mock_connection_handler.h"
namespace {
const int32_t MILLISECONDS_IN_SECOND = 1000;
@@ -50,91 +49,42 @@ namespace components {
namespace connection_handler_test {
using ::testing::_;
-class ConnectionHandlerMock : public connection_handler::ConnectionHandler {
+class HeartBeatMonitorTest : public testing::Test {
public:
- MOCK_METHOD1(set_connection_handler_observer,
- void(connection_handler::ConnectionHandlerObserver*));
- MOCK_METHOD1(set_transport_manager,
- void(transport_manager::TransportManager*));
- MOCK_METHOD0(StartTransportManager,
- void());
- MOCK_METHOD1(ConnectToDevice,
- void(connection_handler::DeviceHandle device_handle));
- MOCK_METHOD0(ConnectToAllDevices,
- void());
- MOCK_METHOD1(CloseRevokedConnection, void(uint32_t connection_key));
- MOCK_METHOD1(CloseConnection,
- void(connection_handler::ConnectionHandle connection_handle));
- MOCK_METHOD1(GetConnectionSessionsCount, uint32_t(uint32_t connection_key));
- MOCK_METHOD2(GetDeviceID,
- bool(const std::string& mac_address,
- connection_handler::DeviceHandle* device_handle));
- MOCK_CONST_METHOD1(GetConnectedDevicesMAC, void(std::vector<std::string> &device_macs));
- MOCK_METHOD2(CloseSession,
- void(uint32_t key,
- connection_handler::CloseSessionReason close_reason));
- MOCK_METHOD3(CloseSession,
- void(connection_handler::ConnectionHandle connection_handle,
- uint8_t session_id,
- connection_handler::CloseSessionReason close_reason));
- MOCK_METHOD2(SendEndService,
- void(uint32_t key, uint8_t service_type));
-
- MOCK_METHOD1(StartSessionHeartBeat,
- void(uint32_t key));
- MOCK_METHOD2(SendHeartBeat,
- void(connection_handler::ConnectionHandle connection_handle,
- uint8_t session_id));
- MOCK_METHOD2(SetHeartBeatTimeout, void(uint32_t connection_key,
- uint32_t timeout));
- MOCK_METHOD2(BindProtocolVersionWithSession,
- void(uint32_t connection_key,
- uint8_t protocol_version));
- MOCK_METHOD4(GetDataOnSessionKey,
- int32_t(uint32_t key, uint32_t* app_id,
- std::list<int32_t>* sessions_list,
- uint32_t* device_id));
-};
+ HeartBeatMonitorTest() : conn(NULL) {
+ kTimeout = 5000u;
+ }
-class HeartBeatMonitorTest : public testing::Test {
-public:
- HeartBeatMonitorTest():
- conn(NULL) {
- profile::Profile::instance()->config_file_name("smartDeviceLink.ini");
- kTimeout = profile::Profile::instance()->heart_beat_timeout();
- }
-
-protected:
- testing::NiceMock<ConnectionHandlerMock> connection_handler_mock;
+ protected:
+ testing::NiceMock<MockConnectionHandler> connection_handler_mock;
connection_handler::Connection* conn;
uint32_t kTimeout;
- static const connection_handler::ConnectionHandle kConnectionHandle = 0xABCDEF;
+ static const connection_handler::ConnectionHandle kConnectionHandle =
+ 0xABCDEF;
virtual void SetUp() {
- conn = new connection_handler::Connection(kConnectionHandle, 0,
- &connection_handler_mock,
- kTimeout);
+ conn = new connection_handler::Connection(
+ kConnectionHandle, 0, &connection_handler_mock, kTimeout);
}
- virtual void TearDown() {
+ void TearDown() OVERRIDE {
delete conn;
}
-
};
-ACTION_P2(RemoveSession, conn, session_id){
+ACTION_P2(RemoveSession, conn, session_id) {
conn->RemoveSession(session_id);
}
TEST_F(HeartBeatMonitorTest, TimerNotStarted) {
-
- // Whithout StartHeartBeat nothing to be call
+ // Whithout StartHeartBeat nothing to be call
EXPECT_CALL(connection_handler_mock, CloseSession(_, _)).Times(0);
EXPECT_CALL(connection_handler_mock, CloseConnection(_)).Times(0);
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0);
conn->AddNewSession();
- usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND);
+ testing::Mock::AsyncVerifyAndClearExpectations(
+ kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND);
}
TEST_F(HeartBeatMonitorTest, TimerNotElapsed) {
@@ -144,19 +94,21 @@ TEST_F(HeartBeatMonitorTest, TimerNotElapsed) {
const uint32_t session = conn->AddNewSession();
conn->StartHeartBeat(session);
- usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
+ testing::Mock::AsyncVerifyAndClearExpectations(
+ kTimeout * MICROSECONDS_IN_MILLISECONDS - MICROSECONDS_IN_SECOND);
}
TEST_F(HeartBeatMonitorTest, TimerElapsed) {
const uint32_t session = conn->AddNewSession();
- EXPECT_CALL(connection_handler_mock, CloseSession(_, session,_))
- .WillOnce(RemoveSession(conn, session));
+ EXPECT_CALL(connection_handler_mock, CloseSession(_, session, _))
+ .WillOnce(RemoveSession(conn, session));
EXPECT_CALL(connection_handler_mock, CloseConnection(_));
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, session));
conn->StartHeartBeat(session);
- usleep(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND);
+ testing::Mock::AsyncVerifyAndClearExpectations(
+ 2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND);
}
TEST_F(HeartBeatMonitorTest, KeptAlive) {
@@ -179,8 +131,8 @@ TEST_F(HeartBeatMonitorTest, NotKeptAlive) {
const uint32_t session = conn->AddNewSession();
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, session));
- EXPECT_CALL(connection_handler_mock, CloseSession(_, session,_))
- .WillOnce(RemoveSession(conn, session));
+ EXPECT_CALL(connection_handler_mock, CloseSession(_, session, _))
+ .WillOnce(RemoveSession(conn, session));
EXPECT_CALL(connection_handler_mock, CloseConnection(_));
conn->StartHeartBeat(session);
@@ -197,17 +149,18 @@ TEST_F(HeartBeatMonitorTest, TwoSessionsElapsed) {
const uint32_t kSession1 = conn->AddNewSession();
const uint32_t kSession2 = conn->AddNewSession();
- EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession1,_))
- .WillOnce(RemoveSession(conn, kSession1));
- EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession2,_))
- .WillOnce(RemoveSession(conn, kSession2));
+ EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession1, _))
+ .WillOnce(RemoveSession(conn, kSession1));
+ EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession2, _))
+ .WillOnce(RemoveSession(conn, kSession2));
EXPECT_CALL(connection_handler_mock, CloseConnection(_));
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession1));
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession2));
conn->StartHeartBeat(kSession1);
conn->StartHeartBeat(kSession2);
- usleep(2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND);
+ testing::Mock::AsyncVerifyAndClearExpectations(
+ 2 * kTimeout * MICROSECONDS_IN_MILLISECONDS + MICROSECONDS_IN_SECOND);
}
TEST_F(HeartBeatMonitorTest, IncreaseHeartBeatTimeout) {
@@ -217,19 +170,19 @@ TEST_F(HeartBeatMonitorTest, IncreaseHeartBeatTimeout) {
EXPECT_CALL(connection_handler_mock, CloseConnection(_)).Times(0);
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, _)).Times(0);
-
const uint32_t kNewTimeout = kTimeout + MICROSECONDS_IN_MILLISECONDS;
conn->StartHeartBeat(kSession);
conn->SetHeartBeatTimeout(kNewTimeout, kSession);
// new timeout greater by old timeout so mock object shouldn't be invoked
- usleep(kTimeout * MICROSECONDS_IN_MILLISECONDS);
+ testing::Mock::AsyncVerifyAndClearExpectations(kTimeout *
+ MICROSECONDS_IN_MILLISECONDS);
}
TEST_F(HeartBeatMonitorTest, DecreaseHeartBeatTimeout) {
const uint32_t kSession = conn->AddNewSession();
- EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession,_))
- .WillOnce(RemoveSession(conn, kSession));
+ EXPECT_CALL(connection_handler_mock, CloseSession(_, kSession, _))
+ .WillOnce(RemoveSession(conn, kSession));
EXPECT_CALL(connection_handler_mock, CloseConnection(_));
EXPECT_CALL(connection_handler_mock, SendHeartBeat(_, kSession));
@@ -237,9 +190,10 @@ TEST_F(HeartBeatMonitorTest, DecreaseHeartBeatTimeout) {
conn->StartHeartBeat(kSession);
conn->SetHeartBeatTimeout(kNewTimeout, kSession);
// new timeout less than old timeout so mock object should be invoked
- usleep(kTimeout * 2 * MICROSECONDS_IN_MILLISECONDS);
+ testing::Mock::AsyncVerifyAndClearExpectations(kTimeout * 2 *
+ MICROSECONDS_IN_MILLISECONDS);
}
-} // namespace connection_handler_test
-} // namespace components
-} // namespace test
+} // namespace connection_handler_test
+} // namespace components
+} // namespace test
diff --git a/src/components/connection_handler/test/include/connection_handler/connection_handler_observer_mock.h b/src/components/connection_handler/test/include/connection_handler/connection_handler_observer_mock.h
new file mode 100644
index 0000000000..aa22f1aa1c
--- /dev/null
+++ b/src/components/connection_handler/test/include/connection_handler/connection_handler_observer_mock.h
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_CONNECTION_HANDLER_TEST_INCLUDE_CONNECTION_HANDLER_OBSERVER_MOCK_H_
+#define SRC_COMPONENTS_CONNECTION_HANDLER_TEST_INCLUDE_CONNECTION_HANDLER_OBSERVER_MOCK_H_
+
+#include "gmock/gmock.h"
+#include <string>
+#include "connection_handler/connection_handler_observer.h"
+
+namespace test {
+namespace components {
+namespace connection_handler_test {
+
+/*
+ * MOCK implementation of ::connection_handler::ConnectionHandlerObserver
+ * interface
+ */
+class ConnectionHandlerObserverMock
+ : public ::connection_handler::ConnectionHandlerObserver {
+ public:
+ MOCK_METHOD1(OnDeviceListUpdated,
+ void(const connection_handler::DeviceMap& device_list));
+ MOCK_METHOD0(OnFindNewApplicationsRequest, void());
+ MOCK_METHOD1(RemoveDevice,
+ void(const connection_handler::DeviceHandle& device_handle));
+ MOCK_METHOD3(OnServiceStartedCallback,
+ bool(const connection_handler::DeviceHandle& device_handle,
+ const int32_t& session_key,
+ const protocol_handler::ServiceType& type));
+ MOCK_METHOD3(
+ OnServiceEndedCallback,
+ void(const int32_t& session_key,
+ const protocol_handler::ServiceType& type,
+ const connection_handler::CloseSessionReason& close_reason));
+ MOCK_CONST_METHOD1(
+ GetHandshakeContext,
+ security_manager::SSLContext::HandshakeContext(uint32_t key));
+};
+} // namespace connection_handler_test
+} // namespace components
+} // namespace test
+#endif // SRC_COMPONENTS_CONNECTION_HANDLER_TEST_INCLUDE_CONNECTION_HANDLER_OBSERVER_MOCK_H_
diff --git a/src/components/connection_handler/test/include/connection_handler_observer_mock.h b/src/components/connection_handler/test/include/connection_handler_observer_mock.h
deleted file mode 100644
index 9a74375262..0000000000
--- a/src/components/connection_handler/test/include/connection_handler_observer_mock.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_CONNECTION_HANDLER_TEST_INCLUDE_CONNECTION_HANDLER_OBSERVER_MOCK_H_
-#define SRC_COMPONENTS_CONNECTION_HANDLER_TEST_INCLUDE_CONNECTION_HANDLER_OBSERVER_MOCK_H_
-
-#include <gmock/gmock.h>
-#include <string>
-#include "connection_handler/connection_handler_observer.h"
-
-namespace test {
-namespace components {
-namespace connection_handler_test {
-
-/*
- * MOCK implementation of ::connection_handler::ConnectionHandlerObserver interface
- */
-class ConnectionHandlerObserverMock : public ::connection_handler::ConnectionHandlerObserver {
- public:
- MOCK_METHOD1(OnDeviceListUpdated,
- void(const connection_handler::DeviceMap &device_list));
- MOCK_METHOD0(OnFindNewApplicationsRequest,void());
- MOCK_METHOD1(RemoveDevice,
- void(const connection_handler::DeviceHandle &device_handle));
- MOCK_METHOD3(OnServiceStartedCallback,
- bool(const connection_handler::DeviceHandle &device_handle,
- const int32_t &session_key,
- const protocol_handler::ServiceType &type));
- MOCK_METHOD3(OnServiceEndedCallback,
- void(const int32_t &session_key,
- const protocol_handler::ServiceType &type,
- const connection_handler::CloseSessionReason& close_reason));
- MOCK_CONST_METHOD1(GetHandshakeContext,
- security_manager::SSLContext::HandshakeContext(
- uint32_t key));
-
-};
-} // namespace connection_handler_test
-} // namespace components
-} // namespace test
-#endif //SRC_COMPONENTS_CONNECTION_HANDLER_TEST_INCLUDE_CONNECTION_HANDLER_OBSERVER_MOCK_H_
diff --git a/src/components/dbus/include/dbus/dbus_adapter.h b/src/components/dbus/include/dbus/dbus_adapter.h
index ec59fa421e..3877649e10 100644
--- a/src/components/dbus/include/dbus/dbus_adapter.h
+++ b/src/components/dbus/include/dbus/dbus_adapter.h
@@ -85,7 +85,9 @@ class DBusAdapter {
* \param name pair interface and name of method for call
* \param obj params for call
*/
- void MethodCall(uint id, const MessageId func_id, const MessageName& name,
+ void MethodCall(uint id,
+ const MessageId func_id,
+ const MessageName& name,
const smart_objects::SmartObject& obj);
/**
@@ -95,7 +97,8 @@ class DBusAdapter {
* \param name pair interface and name of signal for call
* \param obj params for signal
*/
- void Signal(const MessageId func_id, const MessageName& name,
+ void Signal(const MessageId func_id,
+ const MessageName& name,
const smart_objects::SmartObject& obj);
/**
@@ -103,7 +106,9 @@ class DBusAdapter {
* \param id id message
* \param obj params for return
*/
- void MethodReturn(uint id, const MessageId func_id, const MessageName& name,
+ void MethodReturn(uint id,
+ const MessageId func_id,
+ const MessageName& name,
const smart_objects::SmartObject& obj);
/**
@@ -219,7 +224,8 @@ class DBusAdapter {
* \param args map of arguments
* \return true if success
*/
- bool SetArguments(DBusMessage* msg, const ListArgs& rules,
+ bool SetArguments(DBusMessage* msg,
+ const ListArgs& rules,
const smart_objects::SmartObject& args);
/**
@@ -278,7 +284,7 @@ class DBusAdapter {
bool SetOptionalValue(
DBusMessageIter* iter,
const ford_message_descriptions::ParameterDescription* rules,
- const smart_objects::SmartObject &param);
+ const smart_objects::SmartObject& param);
/**
* \brief gets arguments from message
@@ -287,7 +293,7 @@ class DBusAdapter {
* \param message response message (output)
* \return true if success
*/
- bool GetHeader(DBusMessageIter* iter, int *code, std::string *message);
+ bool GetHeader(DBusMessageIter* iter, int* code, std::string* message);
/**
* \brief gets arguments from message with header
@@ -296,7 +302,8 @@ class DBusAdapter {
* \param args map of arguments
* \return true if success
*/
- bool GetArguments(DBusMessageIter* iter, const ListArgs& rules,
+ bool GetArguments(DBusMessageIter* iter,
+ const ListArgs& rules,
smart_objects::SmartObject& args);
/**
@@ -309,7 +316,7 @@ class DBusAdapter {
bool GetOneArgument(
DBusMessageIter* iter,
const ford_message_descriptions::ParameterDescription* rules,
- smart_objects::SmartObject &args);
+ smart_objects::SmartObject& args);
/**
* \brief gets value for argument
@@ -355,7 +362,7 @@ class DBusAdapter {
bool GetOptionalValue(
DBusMessageIter* iter,
const ford_message_descriptions::ParameterDescription* rules,
- smart_objects::SmartObject &param);
+ smart_objects::SmartObject& param);
/**
* \brief processes request on introspect
diff --git a/src/components/dbus/include/dbus/dbus_message.h b/src/components/dbus/include/dbus/dbus_message.h
index 42ec68b3bf..10f419f445 100644
--- a/src/components/dbus/include/dbus/dbus_message.h
+++ b/src/components/dbus/include/dbus/dbus_message.h
@@ -46,7 +46,7 @@ enum ContainerType {
};
class MessageRefKeeper {
-public:
+ public:
MessageRefKeeper();
MessageRefKeeper(DBusMessage* message);
~MessageRefKeeper();
@@ -55,7 +55,8 @@ public:
DBusMessage* get() const;
DBusMessage* Pass();
void swap(MessageRefKeeper& other);
-private:
+
+ private:
DBusMessage* raw_message_;
};
@@ -65,6 +66,7 @@ class MessageRef {
~MessageRef();
std::string GetInterface() const;
std::string GetMember() const;
+
protected:
MessageRefKeeper raw_message_ref_;
friend class MessageReader;
@@ -96,29 +98,30 @@ class MessageReader {
bool NextIsDictEntry() const;
// Readers
- bool TakeBool();
- uint8_t TakeByte();
- int16_t TakeInt16();
+ bool TakeBool();
+ uint8_t TakeByte();
+ int16_t TakeInt16();
uint16_t TakeUint16();
- int32_t TakeInt32();
+ int32_t TakeInt32();
uint32_t TakeUint32();
- int64_t TakeInt64();
+ int64_t TakeInt64();
uint64_t TakeUint64();
- double TakeDouble();
+ double TakeDouble();
std::string TakeString();
MessageReader TakeArrayReader();
MessageReader TakeStructReader();
MessageReader TakeDictEntryReader();
+
private:
typedef int DataType;
// Container reader constructor
- MessageReader(MessageReader* reader,
- DataType container_data_type);
+ MessageReader(MessageReader* reader, DataType container_data_type);
void MoveToNext();
void MarkFailed();
DataType NextValueType() const;
void ReadNextValue(DataType type, void* value);
+
private:
// Fields
MessageReader* parent_reader_;
@@ -146,13 +149,15 @@ class MessageWriter {
void PutUint64(uint64_t value);
void PutDouble(double value);
void PutString(const std::string& value);
+
private:
typedef int DataType;
// Main constructor
void WriteAndCheck(DataType value_type, const void* value);
void CloseWriter();
+
private:
- //Fields
+ // Fields
bool has_opened_subcontainer_;
MessageWriter* parent_writer_;
DBusMessageIter iterator_;
@@ -166,11 +171,9 @@ MessageRef MethodCall(const char* bus_name,
const char* path,
const char* interface,
const char* method);
-MessageRef Signal(const char *path,
- const char *interface,
- const char *name);
-} // namespace dbus
+MessageRef Signal(const char* path, const char* interface, const char* name);
+} // namespace dbus
#include "dbus/dbus_message_inl.h"
-#endif // DBUS_DBUS_MESSAGE_H
+#endif // DBUS_DBUS_MESSAGE_H
diff --git a/src/components/dbus/include/dbus/dbus_message_inl.h b/src/components/dbus/include/dbus/dbus_message_inl.h
index 714e66ea33..1a10f828de 100644
--- a/src/components/dbus/include/dbus/dbus_message_inl.h
+++ b/src/components/dbus/include/dbus/dbus_message_inl.h
@@ -161,14 +161,11 @@ inline std::string MessageReader::TakeString() {
return value;
}
-
inline MessageReader::DataType MessageReader::NextValueType() const {
DBusMessageIter* iter = const_cast<DBusMessageIter*>(&iterator_);
return failed_ ? DBUS_TYPE_INVALID : dbus_message_iter_get_arg_type(iter);
}
-
-
// Message writer methods
inline void MessageWriter::PutBool(bool value) {
dbus_bool_t dbus_value = value;
@@ -212,7 +209,6 @@ inline void MessageWriter::PutString(const std::string& value) {
WriteAndCheck(DBUS_TYPE_STRING, &pointer);
}
-
} // namespace dbus
-#endif // DBUS_MESSAGE_INL_H
+#endif // DBUS_MESSAGE_INL_H
diff --git a/src/components/dbus/include/dbus/message_descriptions.h b/src/components/dbus/include/dbus/message_descriptions.h
index 18c27ce0d6..a9e7a5e141 100644
--- a/src/components/dbus/include/dbus/message_descriptions.h
+++ b/src/components/dbus/include/dbus/message_descriptions.h
@@ -38,12 +38,13 @@
namespace ford_message_descriptions {
-enum ParameterType {Integer, Boolean, Float, String, Struct, Enum, Array};
+enum ParameterType { Integer, Boolean, Float, String, Struct, Enum, Array };
struct ParameterDescription {
const char* name;
const ParameterType type;
- const bool obligatory; // TODO (dchmerev@luxoft.com): rename to 'mandatory' as in HMI API description
+ const bool obligatory; // TODO (dchmerev@luxoft.com): rename to 'mandatory'
+ // as in HMI API description
};
struct ArrayDescription {
@@ -70,4 +71,3 @@ extern const MessageDescription* message_descriptions[];
} // namespace ford_message_descriptions
#endif // SRC_COMPONENTS_DBUS_INCLUDE_DBUS_MESSAGE_DESCRIPTIONS_H_
-
diff --git a/src/components/dbus/include/dbus/schema.h b/src/components/dbus/include/dbus/schema.h
index 2a5f6f3615..e269bd2596 100644
--- a/src/components/dbus/include/dbus/schema.h
+++ b/src/components/dbus/include/dbus/schema.h
@@ -48,7 +48,7 @@ struct Description;
typedef hmi_apis::FunctionID::eType MessageId;
typedef hmi_apis::messageType::eType MessageType;
-typedef std::pair<std::string, std::string> MessageName; // interface, message
+typedef std::pair<std::string, std::string> MessageName; // interface, message
typedef std::vector<const ParameterDescription*> ListArgs;
typedef std::vector<const Description*> Messages;
diff --git a/src/components/dbus/src/dbus_adapter.cc b/src/components/dbus/src/dbus_adapter.cc
index 5f38e3d80f..b4f4b86dd2 100644
--- a/src/components/dbus/src/dbus_adapter.cc
+++ b/src/components/dbus/src/dbus_adapter.cc
@@ -46,8 +46,9 @@ namespace dbus {
CREATE_LOGGERPTR_GLOBAL(logger_, "HMIMessageHandler")
-std::vector<std::string> &split(const std::string& s, char delim,
- std::vector<std::string> &elems) {
+std::vector<std::string>& split(const std::string& s,
+ char delim,
+ std::vector<std::string>& elems) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
@@ -60,12 +61,12 @@ DBusAdapter::DBusAdapter(const std::string& sdlServiceName,
const std::string& sdlObjectPath,
const std::string& hmiServiceName,
const std::string& hmiObjectPath)
- : sdl_service_name_(sdlServiceName),
- sdl_object_path_(sdlObjectPath),
- hmi_service_name_(hmiServiceName),
- hmi_object_path_(hmiObjectPath),
- conn_(NULL),
- schema_(new DBusSchema(ford_message_descriptions::message_descriptions)) {
+ : sdl_service_name_(sdlServiceName)
+ , sdl_object_path_(sdlObjectPath)
+ , hmi_service_name_(hmiServiceName)
+ , hmi_object_path_(hmiObjectPath)
+ , conn_(NULL)
+ , schema_(new DBusSchema(ford_message_descriptions::message_descriptions)) {
}
DBusAdapter::~DBusAdapter() {
@@ -87,18 +88,17 @@ bool DBusAdapter::Init() {
dbus_error_free(&err);
return false;
}
- ret = dbus_bus_request_name(conn_, sdl_service_name_.c_str(),
- DBUS_NAME_FLAG_DO_NOT_QUEUE,
- &err);
+ ret = dbus_bus_request_name(
+ conn_, sdl_service_name_.c_str(), DBUS_NAME_FLAG_DO_NOT_QUEUE, &err);
if (ret == -1 || dbus_error_is_set(&err)) {
LOG4CXX_ERROR(logger_, "DBus: Can't request name " << err.name);
dbus_error_free(&err);
return false;
}
if (DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER != ret) {
- LOG4CXX_ERROR(
- logger_,
- "DBus: Service '" << sdl_service_name_ << "' is already running");
+ LOG4CXX_ERROR(logger_,
+ "DBus: Service '" << sdl_service_name_
+ << "' is already running");
return false;
}
@@ -131,7 +131,8 @@ bool DBusAdapter::Process(smart_objects::SmartObject& obj) {
return false;
}
-void DBusAdapter::MethodReturn(uint id, const MessageId func_id,
+void DBusAdapter::MethodReturn(uint id,
+ const MessageId func_id,
const MessageName& name,
const smart_objects::SmartObject& obj) {
LOG4CXX_DEBUG(logger_, "Method return " << name.first << "." << name.second);
@@ -158,8 +159,8 @@ void DBusAdapter::MethodReturn(uint id, const MessageId func_id,
return;
}
- const ListArgs& args = schema_->getListArgs(func_id,
- hmi_apis::messageType::response);
+ const ListArgs& args =
+ schema_->getListArgs(func_id, hmi_apis::messageType::response);
if (!SetArguments(reply, args, obj)) {
LOG4CXX_ERROR(logger_, "DBus: Failed call method (Signature is wrong)");
dbus_message_unref(reply);
@@ -180,7 +181,8 @@ void DBusAdapter::MethodReturn(uint id, const MessageId func_id,
LOG4CXX_INFO(logger_, "DBus: Success return method");
}
-void DBusAdapter::Error(uint id, const std::string& name,
+void DBusAdapter::Error(uint id,
+ const std::string& name,
const std::string& description) {
LOG4CXX_DEBUG(logger_, "Error " << name << ": " << description);
if (conn_ == NULL) {
@@ -214,7 +216,8 @@ void DBusAdapter::Error(uint id, const std::string& name,
LOG4CXX_INFO(logger_, "DBus: Success error");
}
-void DBusAdapter::MethodCall(uint id, const MessageId func_id,
+void DBusAdapter::MethodCall(uint id,
+ const MessageId func_id,
const MessageName& name,
const smart_objects::SmartObject& obj) {
LOG4CXX_DEBUG(logger_, "Method call " << name.first << "." << name.second);
@@ -230,15 +233,17 @@ void DBusAdapter::MethodCall(uint id, const MessageId func_id,
DBusMessage* msg;
msg = dbus_message_new_method_call(
- hmi_service_name_.c_str(), hmi_object_path_.c_str(),
- (hmi_service_name_ + "." + name.first).c_str(), name.second.c_str());
+ hmi_service_name_.c_str(),
+ hmi_object_path_.c_str(),
+ (hmi_service_name_ + "." + name.first).c_str(),
+ name.second.c_str());
if (NULL == msg) {
LOG4CXX_WARN(logger_, "DBus: Failed call method (Message Null)");
return;
}
- const ListArgs& args = schema_->getListArgs(func_id,
- hmi_apis::messageType::request);
+ const ListArgs& args =
+ schema_->getListArgs(func_id, hmi_apis::messageType::request);
if (!SetArguments(msg, args, obj)) {
LOG4CXX_ERROR(logger_, "DBus: Failed call method (Signature is wrong)");
dbus_message_unref(msg);
@@ -256,7 +261,8 @@ void DBusAdapter::MethodCall(uint id, const MessageId func_id,
LOG4CXX_INFO(logger_, "DBus: Success call method");
}
-void DBusAdapter::Signal(const MessageId func_id, const MessageName& name,
+void DBusAdapter::Signal(const MessageId func_id,
+ const MessageName& name,
const smart_objects::SmartObject& obj) {
LOG4CXX_DEBUG(logger_, "Signal " << name.first << "." << name.second);
if (conn_ == NULL) {
@@ -269,7 +275,7 @@ void DBusAdapter::Signal(const MessageId func_id, const MessageName& name,
return;
}
- DBusMessage *msg;
+ DBusMessage* msg;
msg = dbus_message_new_signal(sdl_object_path_.c_str(),
(sdl_service_name_ + "." + name.first).c_str(),
name.second.c_str());
@@ -278,8 +284,8 @@ void DBusAdapter::Signal(const MessageId func_id, const MessageName& name,
return;
}
- const ListArgs& args = schema_->getListArgs(
- func_id, hmi_apis::messageType::notification);
+ const ListArgs& args =
+ schema_->getListArgs(func_id, hmi_apis::messageType::notification);
if (!SetArguments(msg, args, obj)) {
LOG4CXX_ERROR(logger_, "DBus: Failed call method (Signature is wrong)");
dbus_message_unref(msg);
@@ -306,8 +312,8 @@ bool DBusAdapter::ProcessMethodCall(DBusMessage* msg,
std::string interface = dbus_message_get_interface(msg);
LOG4CXX_INFO(logger_, "DBus: name of method " << interface << " " << method);
- if (interface == "org.freedesktop.DBus.Introspectable"
- && method == "Introspect") {
+ if (interface == "org.freedesktop.DBus.Introspectable" &&
+ method == "Introspect") {
LOG4CXX_INFO(logger_, "DBus: INTROSPECT");
Introspect(msg);
return false;
@@ -331,11 +337,11 @@ bool DBusAdapter::ProcessMethodCall(DBusMessage* msg,
obj[sos::S_PARAMS][sos::S_CORRELATION_ID] = serial;
obj[sos::S_PARAMS][sos::S_FUNCTION_ID] = m_id;
obj[sos::S_PARAMS][sos::S_MESSAGE_TYPE] = hmi_apis::messageType::request;
- obj[sos::S_MSG_PARAMS] = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ obj[sos::S_MSG_PARAMS] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
- const ListArgs args = schema_->getListArgs(name,
- hmi_apis::messageType::request);
+ const ListArgs args =
+ schema_->getListArgs(name, hmi_apis::messageType::request);
DBusMessageIter iter;
dbus_message_iter_init(msg, &iter);
@@ -348,7 +354,7 @@ bool DBusAdapter::ProcessMethodCall(DBusMessage* msg,
bool DBusAdapter::ProcessMethodReturn(DBusMessage* msg,
smart_objects::SmartObject& obj) {
- LOG4CXX_INFO(logger_, "ProcessMethodReturn");
+ LOG4CXX_AUTO_TRACE(logger_);
dbus_uint32_t reply_serial = dbus_message_get_reply_serial(msg);
std::pair<uint, MessageId> ids = GetRequestToHMI(reply_serial);
if (ids.second == hmi_apis::FunctionID::INVALID_ENUM) {
@@ -356,18 +362,18 @@ bool DBusAdapter::ProcessMethodReturn(DBusMessage* msg,
return false;
}
- obj[sos::S_MSG_PARAMS] = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ obj[sos::S_MSG_PARAMS] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
- ListArgs args = schema_->getListArgs(ids.second,
- hmi_apis::messageType::response);
+ ListArgs args =
+ schema_->getListArgs(ids.second, hmi_apis::messageType::response);
DBusMessageIter iter;
dbus_message_iter_init(msg, &iter);
int code = 0;
std::string message;
smart_objects::SmartObject description(smart_objects::SmartType_Map);
- bool ret = GetHeader(&iter, &code, &message)
- && GetArguments(&iter, args, description);
+ bool ret = GetHeader(&iter, &code, &message) &&
+ GetArguments(&iter, args, description);
if (ret) {
obj[sos::S_PARAMS][sos::S_CORRELATION_ID] = ids.first;
@@ -402,13 +408,13 @@ bool DBusAdapter::ProcessError(DBusMessage* msg,
if ((error_name = dbus_message_get_error_name(msg)) != NULL) {
smart_objects::SmartObject name(smart_objects::SmartType_String);
name = error_name;
- ford_message_descriptions::ParameterDescription rule = { "description",
- ford_message_descriptions::String, true };
+ ford_message_descriptions::ParameterDescription rule = {
+ "description", ford_message_descriptions::String, true};
ListArgs args;
args.push_back(&rule);
smart_objects::SmartObject description(smart_objects::SmartType_Map);
- description[rule.name] = smart_objects::SmartObject(
- smart_objects::SmartType_String);
+ description[rule.name] =
+ smart_objects::SmartObject(smart_objects::SmartType_String);
DBusMessageIter iter;
dbus_message_iter_init(msg, &iter);
@@ -421,13 +427,15 @@ bool DBusAdapter::ProcessError(DBusMessage* msg,
hmi_apis::messageType::error_response;
obj[sos::S_PARAMS][sos::kCode] = name.asInt();
obj[sos::S_PARAMS][sos::kMessage] = description[rule.name].asString();
- obj[sos::S_MSG_PARAMS] = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ obj[sos::S_MSG_PARAMS] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
obj[sos::S_PARAMS]["data"]["method"] = method.first + "." + method.second;
- LOG4CXX_WARN(
- logger_,
- "DBus: Call of method " << method.first << "." << method.second << " returned error " << name.asInt() << ": " << description[rule.name].asString());
+ LOG4CXX_WARN(logger_,
+ "DBus: Call of method " << method.first << "." << method.second
+ << " returned error " << name.asInt()
+ << ": "
+ << description[rule.name].asString());
} else {
LOG4CXX_ERROR(logger_, "DBus: Type message isn't error");
}
@@ -453,11 +461,11 @@ bool DBusAdapter::ProcessSignal(DBusMessage* msg,
obj[sos::S_PARAMS][sos::S_FUNCTION_ID] = m_id;
obj[sos::S_PARAMS][sos::S_MESSAGE_TYPE] = hmi_apis::messageType::notification;
- obj[sos::S_MSG_PARAMS] = smart_objects::SmartObject(
- smart_objects::SmartType_Map);
+ obj[sos::S_MSG_PARAMS] =
+ smart_objects::SmartObject(smart_objects::SmartType_Map);
- const ListArgs args = schema_->getListArgs(
- name, hmi_apis::messageType::notification);
+ const ListArgs args =
+ schema_->getListArgs(name, hmi_apis::messageType::notification);
DBusMessageIter iter;
dbus_message_iter_init(msg, &iter);
@@ -466,7 +474,8 @@ bool DBusAdapter::ProcessSignal(DBusMessage* msg,
return ret;
}
-bool DBusAdapter::SetArguments(DBusMessage* msg, const ListArgs& rules,
+bool DBusAdapter::SetArguments(DBusMessage* msg,
+ const ListArgs& rules,
const smart_objects::SmartObject& args) {
DBusMessageIter iter;
dbus_message_iter_init_append(msg, &iter);
@@ -500,7 +509,8 @@ bool DBusAdapter::SetValue(
DBusMessageIter* iter,
const ford_message_descriptions::ParameterDescription* rules,
const smart_objects::SmartObject& param) {
- // LOG4CXX_DEBUG(logger_, "DBus: Set param " << rules->name << " = " << param.asString());
+ // LOG4CXX_DEBUG(logger_, "DBus: Set param " << rules->name << " = " <<
+ // param.asString());
int type = 0;
void* value = 0;
dbus_int32_t integerValue = 0;
@@ -511,13 +521,15 @@ bool DBusAdapter::SetValue(
case ford_message_descriptions::ParameterType::Array:
return SetArrayValue(
iter,
- reinterpret_cast<const ford_message_descriptions::ArrayDescription*>(rules),
+ reinterpret_cast<const ford_message_descriptions::ArrayDescription*>(
+ rules),
param);
break;
case ford_message_descriptions::ParameterType::Struct:
return SetStructValue(
iter,
- reinterpret_cast<const ford_message_descriptions::StructDescription*>(rules),
+ reinterpret_cast<const ford_message_descriptions::StructDescription*>(
+ rules),
param);
break;
case ford_message_descriptions::ParameterType::Enum:
@@ -542,8 +554,7 @@ bool DBusAdapter::SetValue(
value = &stringValue;
break;
default:
- LOG4CXX_ERROR(logger_, "DBus: Unknown type of argument")
- ;
+ LOG4CXX_ERROR(logger_, "DBus: Unknown type of argument");
return false;
}
return dbus_message_iter_append_basic(iter, type, value);
@@ -552,22 +563,22 @@ bool DBusAdapter::SetValue(
bool DBusAdapter::SetOptionalValue(
DBusMessageIter* iter,
const ford_message_descriptions::ParameterDescription* rules,
- const smart_objects::SmartObject &param) {
+ const smart_objects::SmartObject& param) {
DBusMessageIter sub_iter;
- if (!dbus_message_iter_open_container(iter, DBUS_TYPE_STRUCT, NULL,
- &sub_iter)) {
+ if (!dbus_message_iter_open_container(
+ iter, DBUS_TYPE_STRUCT, NULL, &sub_iter)) {
LOG4CXX_ERROR(
logger_,
"DBus: Can't open container type (STRUCT) for optional parameter");
return false;
}
- ford_message_descriptions::ParameterDescription flagRules = { "flag",
- ford_message_descriptions::Boolean, true };
- smart_objects::SmartObject flag(
- param.getType() != smart_objects::SmartType_Invalid);
- if (!SetValue(&sub_iter, &flagRules, flag)
- || !SetValue(&sub_iter, rules, param)) {
+ ford_message_descriptions::ParameterDescription flagRules = {
+ "flag", ford_message_descriptions::Boolean, true};
+ smart_objects::SmartObject flag(param.getType() !=
+ smart_objects::SmartType_Invalid);
+ if (!SetValue(&sub_iter, &flagRules, flag) ||
+ !SetValue(&sub_iter, rules, param)) {
return false;
}
@@ -585,15 +596,14 @@ bool DBusAdapter::SetArrayValue(
const ford_message_descriptions::ArrayDescription* rules,
const smart_objects::SmartObject& param) {
smart_objects::SmartType type = param.getType();
- if (type != smart_objects::SmartType_Array
- && type != smart_objects::SmartType_Invalid) {
+ if (type != smart_objects::SmartType_Array &&
+ type != smart_objects::SmartType_Invalid) {
LOG4CXX_ERROR(logger_, "DBus: SmartObject is not a map");
return false;
}
DBusMessageIter sub_iter;
- if (!dbus_message_iter_open_container(iter, DBUS_TYPE_ARRAY,
- rules->element_dbus_signature,
- &sub_iter)) {
+ if (!dbus_message_iter_open_container(
+ iter, DBUS_TYPE_ARRAY, rules->element_dbus_signature, &sub_iter)) {
LOG4CXX_ERROR(logger_, "DBus: Can't open container type (ARRAY)");
return false;
}
@@ -615,22 +625,22 @@ bool DBusAdapter::SetStructValue(
const ford_message_descriptions::StructDescription* rules,
const smart_objects::SmartObject& structure) {
smart_objects::SmartType type = structure.getType();
- if (type != smart_objects::SmartType_Map
- && type != smart_objects::SmartType_Invalid) {
+ if (type != smart_objects::SmartType_Map &&
+ type != smart_objects::SmartType_Invalid) {
LOG4CXX_ERROR(logger_, "DBus: SmartObject is not a map");
return false;
}
DBusMessageIter sub_iter;
- if (!dbus_message_iter_open_container(iter, DBUS_TYPE_STRUCT, NULL,
- &sub_iter)) {
+ if (!dbus_message_iter_open_container(
+ iter, DBUS_TYPE_STRUCT, NULL, &sub_iter)) {
LOG4CXX_ERROR(logger_, "DBus: Can't open container type (STRUCT)");
return false;
}
const ParameterDescription** entry;
entry = rules->parameters;
while (*entry != NULL) {
- const smart_objects::SmartObject& param = structure.getElement(
- (*entry)->name);
+ const smart_objects::SmartObject& param =
+ structure.getElement((*entry)->name);
if (!SetOneArgument(&sub_iter, *entry, param)) {
return false;
}
@@ -643,7 +653,8 @@ bool DBusAdapter::SetStructValue(
return true;
}
-bool DBusAdapter::GetHeader(DBusMessageIter* iter, int* code,
+bool DBusAdapter::GetHeader(DBusMessageIter* iter,
+ int* code,
std::string* message) {
// Get code of response
dbus_int32_t intValue;
@@ -673,9 +684,10 @@ bool DBusAdapter::GetHeader(DBusMessageIter* iter, int* code,
return true;
}
-bool DBusAdapter::GetArguments(DBusMessageIter* iter, const ListArgs& rules,
+bool DBusAdapter::GetArguments(DBusMessageIter* iter,
+ const ListArgs& rules,
smart_objects::SmartObject& args) {
- LOG4CXX_TRACE(logger_, "GetArguments");
+ LOG4CXX_AUTO_TRACE(logger_);
size_t size = rules.size();
for (size_t i = 0; i < size; ++i) {
@@ -714,7 +726,8 @@ bool DBusAdapter::GetValue(
return GetArrayValue(
iter,
// FIXME (dchmerev@luxoft.com): not portable, danger cast.
- reinterpret_cast<const ford_message_descriptions::ArrayDescription*>(rules),
+ reinterpret_cast<
+ const ford_message_descriptions::ArrayDescription*>(rules),
param);
} else {
LOG4CXX_ERROR(logger_, "DBus: Not expected type of argument");
@@ -725,7 +738,8 @@ bool DBusAdapter::GetValue(
if (type == DBUS_TYPE_STRUCT) {
return GetStructValue(
iter,
- reinterpret_cast<const ford_message_descriptions::StructDescription*>(rules),
+ reinterpret_cast<
+ const ford_message_descriptions::StructDescription*>(rules),
param);
} else {
LOG4CXX_ERROR(logger_, "DBus: Not expected type of argument");
@@ -739,7 +753,8 @@ bool DBusAdapter::GetValue(
dbus_message_iter_get_basic(iter, &integerValue);
smart_objects::SmartObject value(integerValue);
param = value;
- LOG4CXX_DEBUG(logger_, "DBus: " << rules->name << " = " << integerValue);
+ LOG4CXX_DEBUG(logger_,
+ "DBus: " << rules->name << " = " << integerValue);
} else {
LOG4CXX_ERROR(logger_, "DBus: Not expected type of argument");
return false;
@@ -763,9 +778,9 @@ bool DBusAdapter::GetValue(
dbus_message_iter_get_basic(iter, &booleanValue);
smart_objects::SmartObject value(static_cast<bool>(booleanValue));
param = value;
- LOG4CXX_DEBUG(
- logger_,
- "DBus: " << rules->name << " = " << std::boolalpha << booleanValue);
+ LOG4CXX_DEBUG(logger_,
+ "DBus: " << rules->name << " = " << std::boolalpha
+ << booleanValue);
} else {
LOG4CXX_ERROR(logger_, "DBus: Not expected type of argument");
return false;
@@ -786,8 +801,7 @@ bool DBusAdapter::GetValue(
}
break;
default:
- LOG4CXX_ERROR(logger_, "DBus: Unknown type of argument")
- ;
+ LOG4CXX_ERROR(logger_, "DBus: Unknown type of argument");
return false;
}
return true;
@@ -817,7 +831,6 @@ bool DBusAdapter::GetStructValue(
DBusMessageIter* iter,
const ford_message_descriptions::StructDescription* rules,
smart_objects::SmartObject& param) {
-
DBusMessageIter sub_iter;
dbus_message_iter_recurse(iter, &sub_iter);
const ParameterDescription** entry;
@@ -840,14 +853,16 @@ bool DBusAdapter::GetOptionalValue(
smart_objects::SmartObject& param) {
int type = dbus_message_iter_get_arg_type(iter);
if (type != DBUS_TYPE_STRUCT) {
- LOG4CXX_WARN(logger_, "DBus: Not expected type of argument. It is not optional parameter.");
+ LOG4CXX_WARN(
+ logger_,
+ "DBus: Not expected type of argument. It is not optional parameter.");
return false;
}
DBusMessageIter sub_iter;
dbus_message_iter_recurse(iter, &sub_iter);
- ford_message_descriptions::ParameterDescription flagRules = { "flag",
- ford_message_descriptions::Boolean, true };
+ ford_message_descriptions::ParameterDescription flagRules = {
+ "flag", ford_message_descriptions::Boolean, true};
smart_objects::SmartObject flag;
if (!GetValue(&sub_iter, &flagRules, flag)) {
return false;
@@ -877,7 +892,7 @@ void DBusAdapter::SaveRequestToHMI(uint32_t serial,
}
void DBusAdapter::Introspect(DBusMessage* msg) {
- DBusMessage *reply;
+ DBusMessage* reply;
dbus_uint32_t serial = dbus_message_get_serial(msg);
reply = dbus_message_new_method_return(msg);
@@ -907,7 +922,7 @@ DBusMessage* DBusAdapter::GetRequestFromHMI(uint32_t serial) {
std::map<uint32_t, DBusMessage*>::iterator it;
it = requests_from_hmi_.find(serial);
if (it != requests_from_hmi_.end()) {
- DBusMessage *msg = it->second;
+ DBusMessage* msg = it->second;
requests_from_hmi_.erase(it);
LOG4CXX_DEBUG(logger_, "D-Bus message: " << msg);
return msg;
diff --git a/src/components/dbus/src/dbus_message.cc b/src/components/dbus/src/dbus_message.cc
index 702e44f801..b8a55896ce 100644
--- a/src/components/dbus/src/dbus_message.cc
+++ b/src/components/dbus/src/dbus_message.cc
@@ -38,12 +38,10 @@
namespace dbus {
-MessageRefKeeper::MessageRefKeeper()
- : raw_message_(NULL) {
-}
+MessageRefKeeper::MessageRefKeeper() : raw_message_(NULL) {}
MessageRefKeeper::MessageRefKeeper(DBusMessage* message)
- : raw_message_(message) {
+ : raw_message_(message) {
assert(raw_message_);
dbus_message_ref(raw_message_);
}
@@ -55,7 +53,7 @@ MessageRefKeeper::~MessageRefKeeper() {
}
MessageRefKeeper::MessageRefKeeper(const MessageRefKeeper& other)
- : raw_message_(other.raw_message_) {
+ : raw_message_(other.raw_message_) {
assert(raw_message_);
dbus_message_ref(raw_message_);
}
@@ -79,13 +77,9 @@ void MessageRefKeeper::swap(MessageRefKeeper& other) {
std::swap(raw_message_, other.raw_message_);
}
+MessageRef::MessageRef(DBusMessage* message) : raw_message_ref_(message) {}
-MessageRef::MessageRef(DBusMessage* message)
- : raw_message_ref_(message) {
-}
-
-MessageRef::~MessageRef(){
-}
+MessageRef::~MessageRef() {}
std::string MessageRef::GetInterface() const {
return dbus_message_get_interface(raw_message_ref_.get());
@@ -97,11 +91,9 @@ std::string MessageRef::GetMember() const {
// Message writer
MessageReader::MessageReader(const MessageRef& message)
- : parent_reader_(NULL),
- failed_(false) {
+ : parent_reader_(NULL), failed_(false) {
dbus_bool_t success =
- dbus_message_iter_init(message.raw_message_ref_.get(),
- &iterator_);
+ dbus_message_iter_init(message.raw_message_ref_.get(), &iterator_);
if (!success) {
MarkFailed();
}
@@ -109,8 +101,7 @@ MessageReader::MessageReader(const MessageRef& message)
MessageReader::MessageReader(MessageReader* reader,
DataType container_data_type)
- : parent_reader_(reader),
- failed_(reader->has_failed()) {
+ : parent_reader_(reader), failed_(reader->has_failed()) {
assert(parent_reader_);
if (!failed_) {
if (reader->NextValueType() != container_data_type) {
@@ -122,12 +113,10 @@ MessageReader::MessageReader(MessageReader* reader,
}
}
-
bool MessageReader::NextIsDictEntry() const {
return NextValueType() == DBUS_TYPE_DICT_ENTRY;
}
-
MessageReader MessageReader::TakeArrayReader() {
return MessageReader(this, DBUS_TYPE_ARRAY);
}
@@ -156,8 +145,7 @@ void MessageReader::MarkFailed() {
}
}
-void MessageReader::ReadNextValue(MessageReader::DataType type,
- void* value) {
+void MessageReader::ReadNextValue(MessageReader::DataType type, void* value) {
assert(value);
if (NextValueType() != type) {
MarkFailed();
@@ -169,28 +157,21 @@ void MessageReader::ReadNextValue(MessageReader::DataType type,
// DbusMessageWriter
MessageWriter::MessageWriter(const MessageRef& message)
- : has_opened_subcontainer_(false),
- parent_writer_(NULL) {
- dbus_message_iter_init_append(message.raw_message_ref_.get(),
- &iterator_);
-}
-
-MessageWriter::MessageWriter(
- MessageWriter* parent,
- ContainerType container_type,
- const char* array_signature)
- : has_opened_subcontainer_(false),
- parent_writer_(parent) {
+ : has_opened_subcontainer_(false), parent_writer_(NULL) {
+ dbus_message_iter_init_append(message.raw_message_ref_.get(), &iterator_);
+}
+
+MessageWriter::MessageWriter(MessageWriter* parent,
+ ContainerType container_type,
+ const char* array_signature)
+ : has_opened_subcontainer_(false), parent_writer_(parent) {
assert(parent_writer_);
// Only array writers require array_signature
- assert((container_type == kArray && array_signature != NULL)
- || (container_type != kArray && array_signature == NULL));
+ assert((container_type == kArray && array_signature != NULL) ||
+ (container_type != kArray && array_signature == NULL));
assert(!parent_writer_->has_opened_subcontainer_);
- bool enough_memory =
- dbus_message_iter_open_container(&parent_writer_->iterator_,
- container_type,
- array_signature,
- &iterator_);
+ bool enough_memory = dbus_message_iter_open_container(
+ &parent_writer_->iterator_, container_type, array_signature, &iterator_);
assert(enough_memory);
parent_writer_->has_opened_subcontainer_ = true;
}
@@ -202,8 +183,8 @@ MessageWriter::~MessageWriter() {
}
}
-void MessageWriter::WriteAndCheck(
- MessageWriter::DataType value_type, const void* value) {
+void MessageWriter::WriteAndCheck(MessageWriter::DataType value_type,
+ const void* value) {
assert(!has_opened_subcontainer_);
dbus_bool_t enough_memory =
dbus_message_iter_append_basic(&iterator_, value_type, value);
@@ -214,8 +195,7 @@ void MessageWriter::CloseWriter() {
assert(parent_writer_);
assert(parent_writer_->has_opened_subcontainer_);
dbus_bool_t enough_memory =
- dbus_message_iter_close_container(&parent_writer_->iterator_,
- &iterator_);
+ dbus_message_iter_close_container(&parent_writer_->iterator_, &iterator_);
assert(enough_memory);
parent_writer_->has_opened_subcontainer_ = false;
}
@@ -226,18 +206,12 @@ MessageRef MethodCall(const char* bus_name,
const char* path,
const char* interface,
const char* method) {
- return MessageRef(dbus_message_new_method_call(
- bus_name,
- path,
- interface,
- method));
+ return MessageRef(
+ dbus_message_new_method_call(bus_name, path, interface, method));
}
-MessageRef Signal(const char* path,
- const char* interface,
- const char* name) {
+MessageRef Signal(const char* path, const char* interface, const char* name) {
return MessageRef(dbus_message_new_signal(path, interface, name));
}
-
-} // namespace dbus
+} // namespace dbus
diff --git a/src/components/dbus/src/dbus_message_controller.cc b/src/components/dbus/src/dbus_message_controller.cc
index 56efe67905..166037e900 100644
--- a/src/components/dbus/src/dbus_message_controller.cc
+++ b/src/components/dbus/src/dbus_message_controller.cc
@@ -41,22 +41,30 @@ DBusMessageController::DBusMessageController(const std::string& sdlServiceName,
const std::string& sdlObjectPath,
const std::string& hmiServiceName,
const std::string& hmiObjectPath)
- : DBusAdapter(sdlServiceName, sdlObjectPath,
- hmiServiceName, hmiObjectPath) {}
+ : DBusAdapter(
+ sdlServiceName, sdlObjectPath, hmiServiceName, hmiObjectPath) {}
void DBusMessageController::SubscribeTo(const std::string& interface,
const std::string& signal) {
std::string rule = "type='signal'";
- rule.append(", sender='").append(hmi_service_name_).append("'")
- .append(", path='").append(hmi_object_path_).append("'")
- .append(", interface='").append(hmi_service_name_).append(".")
- .append(interface).append("'")
- .append(", member='").append(signal).append("'");
+ rule.append(", sender='")
+ .append(hmi_service_name_)
+ .append("'")
+ .append(", path='")
+ .append(hmi_object_path_)
+ .append("'")
+ .append(", interface='")
+ .append(hmi_service_name_)
+ .append(".")
+ .append(interface)
+ .append("'")
+ .append(", member='")
+ .append(signal)
+ .append("'");
DBusAdapter::AddMatch(rule);
}
-DBusMessageController::~DBusMessageController() {
-}
+DBusMessageController::~DBusMessageController() {}
void* DBusMessageController::MethodForReceiverThread(void*) {
while (true) {
diff --git a/src/components/dbus/src/schema.cc b/src/components/dbus/src/schema.cc
index 157479928d..3107d9ce6c 100644
--- a/src/components/dbus/src/schema.cc
+++ b/src/components/dbus/src/schema.cc
@@ -44,35 +44,32 @@ struct Description {
};
struct IsId : public std::unary_function<const Description*, bool> {
- explicit IsId(MessageId id)
- : id_(id) {
- }
+ explicit IsId(MessageId id) : id_(id) {}
bool operator()(const Description* desc) {
return desc->id == id_;
}
+
private:
MessageId id_;
};
struct IsName : public std::unary_function<const Description*, bool> {
- explicit IsName(const MessageName& name)
- : name_(name) {
- }
+ explicit IsName(const MessageName& name) : name_(name) {}
bool operator()(const Description* desc) {
return desc->name == name_;
}
+
private:
MessageName name_;
};
struct IsIdType : public std::unary_function<const Description*, bool> {
explicit IsIdType(const MessageId& id, const MessageType& type)
- : id_(id),
- type_(type) {
- }
+ : id_(id), type_(type) {}
bool operator()(const Description* desc) {
return desc->id == id_ && desc->type == type_;
}
+
private:
MessageId id_;
MessageType type_;
@@ -80,12 +77,11 @@ struct IsIdType : public std::unary_function<const Description*, bool> {
struct IsNameType : public std::unary_function<const Description*, bool> {
explicit IsNameType(const MessageName& name, const MessageType& type)
- : name_(name),
- type_(type) {
- }
+ : name_(name), type_(type) {}
bool operator()(const Description* desc) {
return desc->name == name_ && desc->type == type_;
}
+
private:
MessageName name_;
MessageType type_;
@@ -94,7 +90,7 @@ struct IsNameType : public std::unary_function<const Description*, bool> {
DBusSchema::DBusSchema(const MessageDescription** array) {
const MessageDescription** msg = array;
while (*msg != NULL) {
- Description *desc = new Description();
+ Description* desc = new Description();
desc->id = (*msg)->function_id;
desc->name = std::make_pair((*msg)->interface, (*msg)->name);
desc->type = (*msg)->message_type;
@@ -110,8 +106,8 @@ DBusSchema::DBusSchema(const MessageDescription** array) {
}
MessageName DBusSchema::getMessageName(MessageId id) const {
- Messages::const_iterator it = std::find_if(msgs_.begin(), msgs_.end(),
- IsId(id));
+ Messages::const_iterator it =
+ std::find_if(msgs_.begin(), msgs_.end(), IsId(id));
if (msgs_.end() != it) {
return (*it)->name;
}
@@ -119,8 +115,8 @@ MessageName DBusSchema::getMessageName(MessageId id) const {
}
MessageId DBusSchema::getMessageId(const MessageName& name) const {
- Messages::const_iterator it = std::find_if(msgs_.begin(), msgs_.end(),
- IsName(name));
+ Messages::const_iterator it =
+ std::find_if(msgs_.begin(), msgs_.end(), IsName(name));
if (msgs_.end() != it) {
return (*it)->id;
}
@@ -128,8 +124,8 @@ MessageId DBusSchema::getMessageId(const MessageName& name) const {
}
ListArgs DBusSchema::getListArgs(MessageId id, MessageType type) const {
- Messages::const_iterator it = std::find_if(msgs_.begin(), msgs_.end(),
- IsIdType(id, type));
+ Messages::const_iterator it =
+ std::find_if(msgs_.begin(), msgs_.end(), IsIdType(id, type));
if (msgs_.end() != it) {
return (*it)->args;
}
@@ -138,8 +134,8 @@ ListArgs DBusSchema::getListArgs(MessageId id, MessageType type) const {
ListArgs DBusSchema::getListArgs(const MessageName& name,
MessageType type) const {
- Messages::const_iterator it = std::find_if(msgs_.begin(), msgs_.end(),
- IsNameType(name, type));
+ Messages::const_iterator it =
+ std::find_if(msgs_.begin(), msgs_.end(), IsNameType(name, type));
if (msgs_.end() != it) {
return (*it)->args;
}
diff --git a/src/components/dbus/test/test_dbus_adapter.cc b/src/components/dbus/test/test_dbus_adapter.cc
index c5922dfdcb..74a6de1aa9 100644
--- a/src/components/dbus/test/test_dbus_adapter.cc
+++ b/src/components/dbus/test/test_dbus_adapter.cc
@@ -42,20 +42,18 @@ namespace test {
namespace components {
namespace dbus {
-class DBusAdapterTest : public ::testing::Test {
-};
+class DBusAdapterTest : public ::testing::Test {};
TEST_F(DBusAdapterTest, Initialization) {
const std::string kSdlServiceName = "test.ford.sdl.core";
const std::string kSdlObjectPath = "/";
const std::string kHmiServiceName = "test.ford.sdl.hmi";
const std::string kHmiObjectPath = "/";
- ::dbus::DBusAdapter adapter(kSdlServiceName, kSdlObjectPath,
- kHmiServiceName, kHmiObjectPath);
+ ::dbus::DBusAdapter adapter(
+ kSdlServiceName, kSdlObjectPath, kHmiServiceName, kHmiObjectPath);
EXPECT_TRUE(adapter.Init());
}
} // namespace dbus
} // namespace components
} // namespace test
-
diff --git a/src/components/dbus/test/test_dbus_message_controller.cc b/src/components/dbus/test/test_dbus_message_controller.cc
index f0056db4c9..5c5d4e69d5 100644
--- a/src/components/dbus/test/test_dbus_message_controller.cc
+++ b/src/components/dbus/test/test_dbus_message_controller.cc
@@ -66,13 +66,9 @@ class DBusMessageControllerTest : public ::testing::Test {
MockDBusMessageController* controller_;
MockSubscriber* subscriber_;
- static void SetUpTestCase() {
+ static void SetUpTestCase() {}
- }
-
- static void TearDownTestCase() {
-
- }
+ static void TearDownTestCase() {}
virtual void SetUp() {
const std::string kService = "sdl.core.test_api";
@@ -83,7 +79,7 @@ class DBusMessageControllerTest : public ::testing::Test {
ASSERT_TRUE(subscriber_->Start());
}
- virtual void TearDown() {
+ void TearDown() OVERRIDE {
delete controller_;
delete subscriber_;
}
@@ -94,7 +90,8 @@ class DBusMessageControllerTest : public ::testing::Test {
timespec elapsed;
clock_gettime(CLOCK_REALTIME, &elapsed);
elapsed.tv_sec += seconds;
- return pthread_cond_timedwait(&test_cond, &test_mutex, &elapsed) != ETIMEDOUT;
+ return pthread_cond_timedwait(&test_cond, &test_mutex, &elapsed) !=
+ ETIMEDOUT;
}
};
@@ -110,12 +107,10 @@ TEST_F(DBusMessageControllerTest, Receive) {
TEST_F(DBusMessageControllerTest, DISABLED_Send) {
const std::string kText = "Test message for signal DBus";
-// EXPECT_CALL(*subscriber_, Receive(kText)).Times(1);
+ // EXPECT_CALL(*subscriber_, Receive(kText)).Times(1);
controller_->Send(kText);
}
} // namespace hmi_message_handler
} // namespace components
} // namespace test
-
-
diff --git a/src/components/dbus/test/test_schema.cc b/src/components/dbus/test/test_schema.cc
index ecbd4b1bfd..37831279b9 100644
--- a/src/components/dbus/test/test_schema.cc
+++ b/src/components/dbus/test/test_schema.cc
@@ -103,7 +103,8 @@ TEST_F(DBusSchemaTest, GetListArg) {
const MessageId kIdWrong = static_cast<const MessageId>(test_negative_value);
const MessageName kNameWrong("TestInterface", "TestMessage");
- const MessageType kTypeWrong = static_cast<const MessageType>(test_negative_value);
+ const MessageType kTypeWrong =
+ static_cast<const MessageType>(test_negative_value);
const ListArgs kExpListWrong;
argsName = schema_->getListArgs(kNameWrong, kTypeWrong);
EXPECT_EQ(kExpListWrong, argsName);
@@ -115,5 +116,3 @@ TEST_F(DBusSchemaTest, GetListArg) {
} // namespace dbus
} // namespace components
} // namespace test
-
-
diff --git a/src/components/formatters/CMakeLists.txt b/src/components/formatters/CMakeLists.txt
index 3dd7dc9366..1858342ff3 100644
--- a/src/components/formatters/CMakeLists.txt
+++ b/src/components/formatters/CMakeLists.txt
@@ -38,16 +38,17 @@ include_directories (
${JSONCPP_INCLUDE_DIRECTORY}
${MESSAGE_BROKER_INCLUDE_DIRECTORY}
${COMPONENTS_DIR}/smart_objects/include
+ ${COMPONENTS_DIR}/utils/include
)
set (SOURCES
- ${FORMATTERS_SRC_DIR}/CSmartFactory.cpp
+ ${FORMATTERS_SRC_DIR}/CSmartFactory.cc
)
set (FORMATTER_SOURCES
- ${FORMATTERS_SRC_DIR}/CFormatterJsonBase.cpp
- ${FORMATTERS_SRC_DIR}/CFormatterJsonSDLRPCv1.cpp
- ${FORMATTERS_SRC_DIR}/CFormatterJsonSDLRPCv2.cpp
+ ${FORMATTERS_SRC_DIR}/CFormatterJsonBase.cc
+ ${FORMATTERS_SRC_DIR}/CFormatterJsonSDLRPCv1.cc
+ ${FORMATTERS_SRC_DIR}/CFormatterJsonSDLRPCv2.cc
${FORMATTERS_SRC_DIR}/formatter_json_rpc.cc
${FORMATTERS_SRC_DIR}/meta_formatter.cc
${FORMATTERS_SRC_DIR}/generic_json_formatter.cc
diff --git a/src/components/formatters/include/formatters/CFormatterJsonBase.h b/src/components/formatters/include/formatters/CFormatterJsonBase.h
new file mode 100644
index 0000000000..be4ee3e2cc
--- /dev/null
+++ b/src/components/formatters/include/formatters/CFormatterJsonBase.h
@@ -0,0 +1,119 @@
+/**
+ * @file CFormatterJsonBase.hpp
+ * @brief CFormatterJsonBase header file.
+ */
+// Copyright (c) 2013, Ford Motor Company
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// Redistributions of source code must retain the above copyright notice, this
+// list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided with the
+// distribution.
+//
+// Neither the name of the Ford Motor Company nor the names of its contributors
+// may be used to endorse or promote products derived from this software
+// without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef __CFORMATTERJSONBASE_HPP__
+#define __CFORMATTERJSONBASE_HPP__
+
+#include "smart_objects/smart_object.h"
+#include "json/json.h"
+
+namespace NsSmartDeviceLink {
+namespace NsJSONHandler {
+namespace Formatters {
+
+namespace meta_formatter_error_code {
+/**
+ * @brief Error codes of MetaFormatter represented as bitmask
+ **/
+typedef long tMetaFormatterErrorCode;
+
+/**
+ * @brief OK, no error
+ */
+static const tMetaFormatterErrorCode kErrorOk = 0x0;
+
+/**
+ * @brief origin smart object is not function
+ */
+static const tMetaFormatterErrorCode kErrorObjectIsNotFunction = 0x01;
+
+/**
+ * @brief smart shema describes object which is not function
+ */
+static const tMetaFormatterErrorCode kErrorSchemaIsNotFunction = 0x02;
+
+/**
+ * @brief result smart object has invalid type (SmartType_Invalid)
+ * before passing to MetaFormatter, i.e. result object can not
+ * be changed, i.e. result object can not be built
+ *
+ */
+static const tMetaFormatterErrorCode kErrorFailedCreateObjectBySchema = 0x04;
+}
+
+/**
+ * @brief The base class for all JSON based formatters.
+ */
+class CFormatterJsonBase {
+ private:
+ /**
+ * @brief Constructor.
+ */
+ CFormatterJsonBase();
+
+ /**
+ * @brief Copy constructor.
+ *
+ * @param obj Object to copy.
+ */
+ CFormatterJsonBase(const CFormatterJsonBase& obj);
+
+ protected:
+ public:
+ /**
+ * @brief The method constructs a SmartObject from the input JSON object
+ *
+ * @param value Input JSON object.
+ * @param obj The resulting SmartObject.
+ */
+ static void jsonValueToObj(
+ const Json::Value& value,
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& obj);
+
+ /**
+ * @brief The method constructs a JSON object from the input SmartObject
+ *
+ * @param obj Input SmartObject. Can contain a complex structure of objects.
+ * @param value The resulting JSON object. It has the same structure as the
+ *input SmartObject.
+ */
+ static void objToJsonValue(
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& obj,
+ Json::Value& value);
+};
+}
+}
+} // namespace NsSmartDeviceLink::NsJSONHandler::Formatters
+
+#endif // __CFORMATTERJSONBASE_HPP__
diff --git a/src/components/formatters/include/formatters/CFormatterJsonBase.hpp b/src/components/formatters/include/formatters/CFormatterJsonBase.hpp
deleted file mode 100644
index ef57d9b1b9..0000000000
--- a/src/components/formatters/include/formatters/CFormatterJsonBase.hpp
+++ /dev/null
@@ -1,122 +0,0 @@
-/**
- * @file CFormatterJsonBase.hpp
- * @brief CFormatterJsonBase header file.
- */
-// Copyright (c) 2013, Ford Motor Company
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// Redistributions of source code must retain the above copyright notice, this
-// list of conditions and the following disclaimer.
-//
-// Redistributions in binary form must reproduce the above copyright notice,
-// this list of conditions and the following
-// disclaimer in the documentation and/or other materials provided with the
-// distribution.
-//
-// Neither the name of the Ford Motor Company nor the names of its contributors
-// may be used to endorse or promote products derived from this software
-// without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-#ifndef __CFORMATTERJSONBASE_HPP__
-#define __CFORMATTERJSONBASE_HPP__
-
-#include "smart_objects/smart_object.h"
-#include "json/json.h"
-
-namespace NsSmartDeviceLink {
-namespace NsJSONHandler {
-namespace Formatters {
-
-namespace meta_formatter_error_code {
- /**
- * @brief Error codes of MetaFormatter represented as bitmask
- **/
- typedef long tMetaFormatterErrorCode ;
-
- /**
- * @brief OK, no error
- */
- static const tMetaFormatterErrorCode kErrorOk = 0x0;
-
- /**
- * @brief origin smart object is not function
- */
- static const tMetaFormatterErrorCode kErrorObjectIsNotFunction = 0x01;
-
- /**
- * @brief smart shema describes object which is not function
- */
- static const tMetaFormatterErrorCode kErrorSchemaIsNotFunction = 0x02;
-
- /**
- * @brief result smart object has invalid type (SmartType_Invalid)
- * before passing to MetaFormatter, i.e. result object can not
- * be changed, i.e. result object can not be built
- *
- */
- static const tMetaFormatterErrorCode kErrorFailedCreateObjectBySchema = 0x04;
-}
-
- /**
- * @brief The base class for all JSON based formatters.
- */
- class CFormatterJsonBase
- {
- private:
-
- /**
- * @brief Constructor.
- */
- CFormatterJsonBase();
-
- /**
- * @brief Copy constructor.
- *
- * @param obj Object to copy.
- */
- CFormatterJsonBase(const CFormatterJsonBase &obj);
-
- protected:
-
-
- public:
-
- /**
- * @brief The method constructs a SmartObject from the input JSON object
- *
- * @param value Input JSON object.
- * @param obj The resulting SmartObject.
- */
- static void jsonValueToObj(const Json::Value &value,
- NsSmartDeviceLink::NsSmartObjects::SmartObject &obj);
-
- /**
- * @brief The method constructs a JSON object from the input SmartObject
- *
- * @param obj Input SmartObject. Can contain a complex structure of objects.
- * @param value The resulting JSON object. It has the same structure as the input SmartObject.
- */
- static void objToJsonValue(const NsSmartDeviceLink::NsSmartObjects::SmartObject &obj,
- Json::Value &value);
- };
-
-}
-}
-} // namespace NsSmartDeviceLink::NsJSONHandler::Formatters
-
-#endif // __CFORMATTERJSONBASE_HPP__
diff --git a/src/components/formatters/include/formatters/CFormatterJsonSDLRPCv1.h b/src/components/formatters/include/formatters/CFormatterJsonSDLRPCv1.h
new file mode 100644
index 0000000000..e78a115f6c
--- /dev/null
+++ b/src/components/formatters/include/formatters/CFormatterJsonSDLRPCv1.h
@@ -0,0 +1,239 @@
+// Copyright (c) 2013, Ford Motor Company
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// Redistributions of source code must retain the above copyright notice, this
+// list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided with the
+// distribution.
+//
+// Neither the name of the Ford Motor Company nor the names of its contributors
+// may be used to endorse or promote products derived from this software
+// without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+#ifndef __SMARTDEVICELINKCORE_JSONHANDLER_FORMATTERS__CFORMATTERJSONSDLRPCV1_HPP__
+#define __SMARTDEVICELINKCORE_JSONHANDLER_FORMATTERS__CFORMATTERJSONSDLRPCV1_HPP__
+
+#include "json/json.h"
+
+#include "smart_objects/smart_object.h"
+#include "smart_objects/enum_schema_item.h"
+
+#include "CFormatterJsonBase.h"
+
+#include "formatters/CSmartFactory.h"
+#include "formatters/meta_formatter.h"
+
+namespace NsSmartDeviceLink {
+namespace NsJSONHandler {
+namespace Formatters {
+
+/**
+ * @brief Class is used to convert SmartObjects to JSON string and vice versa.
+ *
+ * JSON strings is in SDLRPCv1 format.
+ */
+class CFormatterJsonSDLRPCv1 : public CFormatterJsonBase {
+ private:
+ /**
+ * @brief Hidden constructor.
+ *
+ * The class contains only static methods. Should not be instantiated.
+ */
+ CFormatterJsonSDLRPCv1();
+
+ /**
+ * @brief Hidden copy constructor.
+ *
+ * The class contains only static methods. Should not be instantiated.
+ */
+ CFormatterJsonSDLRPCv1(const CFormatterJsonSDLRPCv1&);
+
+ /**
+ * @brief Extracts a message type from the SmartObject
+ */
+ static const std::string getMessageType(
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& obj);
+
+ /**
+ * @brief Extracts a message type from the root JSON object.
+ *
+ * @return Type or empty string if there's no type in the JSON object.
+ */
+ static const std::string getMessageType(const Json::Value& root);
+
+ // SDLRPCv1 string consts
+
+ /**
+ * @brief String constant for REQUEST.
+ */
+ static const std::string S_REQUEST;
+
+ /**
+ * @brief String constant for RESPONSE.
+ */
+ static const std::string S_RESPONSE;
+
+ /**
+ * @brief String constant for NOTIFICATION.
+ */
+ static const std::string S_NOTIFICATION;
+
+ /**
+ * @brief String constant for PARAMETERS.
+ */
+ static const std::string S_PARAMETERS;
+
+ /**
+ * @brief String constant for NAME.
+ */
+ static const std::string S_NAME;
+
+ /**
+ * @brief String constant for CORRELATION_ID.
+ */
+ static const std::string S_CORRELATION_ID;
+
+ public:
+ static const int32_t kSuccess;
+ static const int32_t kParsingError;
+ static const int32_t kFunctionIdNotFound;
+ static const int32_t kMessageTypeNotFound;
+ static const int32_t kCorrelationIdNotFound;
+
+ typedef NsSmartDeviceLink::NsJSONHandler::Formatters::
+ meta_formatter_error_code::tMetaFormatterErrorCode
+ tMetaFormatterErrorCode;
+
+ /**
+ * @brief Creates a JSON string from a SmartObject.
+ *
+ * @param obj input SmartObject
+ * @param outStr resulting JSON string
+ * @return true if success, false otherwise
+ */
+ static bool toString(
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& obj,
+ std::string& outStr);
+
+ /**
+ * @brief Creates a SmartObject from a JSON string.
+ *
+ * @param str input JSON string
+ * @param out The resulting SmartObject
+ * @return true if success, otherwise - false
+ */
+ template <typename FunctionId, typename MessageType>
+ static int32_t fromString(
+ const std::string& str,
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& out);
+
+ /**
+ * @brief Converts to string the smart object against the given schema
+ *
+ * @param object Original smart object
+ * @param schema Smart schema which describes 'fake' smart object to be
+ *formatted
+ * @param outStr Resulting JSON string
+ * @return formatting error code
+ */
+ static tMetaFormatterErrorCode MetaFormatToString(
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& object,
+ const NsSmartDeviceLink::NsSmartObjects::CSmartSchema& schema,
+ std::string& outStr);
+};
+
+// ----------------------------------------------------------------------------
+
+template <typename FunctionId, typename MessageType>
+int32_t Formatters::CFormatterJsonSDLRPCv1::fromString(
+ const std::string& str,
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& out) {
+ int32_t result = kSuccess;
+
+ try {
+ Json::Value root;
+ Json::Reader reader;
+ std::string type;
+
+ if (false == reader.parse(str, root)) {
+ result = kParsingError | kMessageTypeNotFound | kFunctionIdNotFound |
+ kCorrelationIdNotFound;
+ }
+
+ if (kSuccess == result) {
+ type = getMessageType(root);
+ if (true == type.empty()) {
+ result =
+ kMessageTypeNotFound | kFunctionIdNotFound | kCorrelationIdNotFound;
+ }
+ }
+
+ FunctionId functionId = FunctionId::INVALID_ENUM;
+ MessageType messageType = MessageType::INVALID_ENUM;
+
+ if (kSuccess == result) {
+ if (!NsSmartObjects::EnumConversionHelper<MessageType>::StringToEnum(
+ type, &messageType)) {
+ // If MessageType is not found than FunctionId and CorrelationId can not
+ // be found either
+ result =
+ kMessageTypeNotFound | kFunctionIdNotFound | kCorrelationIdNotFound;
+ }
+ }
+
+ if (kSuccess == result) {
+ if (!NsSmartObjects::EnumConversionHelper<FunctionId>::StringToEnum(
+ root[type][S_NAME].asString(), &functionId)) {
+ result = kFunctionIdNotFound;
+ functionId = FunctionId::INVALID_ENUM;
+ }
+ }
+
+ namespace S = NsSmartDeviceLink::NsJSONHandler::strings;
+
+ if (!(result & kMessageTypeNotFound)) {
+ jsonValueToObj(root[type][S_PARAMETERS], out[S::S_MSG_PARAMS]);
+
+ out[S::S_PARAMS][S::S_MESSAGE_TYPE] = messageType;
+ out[S::S_PARAMS][S::S_FUNCTION_ID] = functionId;
+ if (true == root[type][S_CORRELATION_ID].empty()) {
+ if (type !=
+ S_NOTIFICATION) { // Notification may not have CorrelationId
+ result |= kCorrelationIdNotFound;
+ out[S::S_PARAMS][S::S_CORRELATION_ID] = -1;
+ }
+ } else {
+ out[S::S_PARAMS][S::S_CORRELATION_ID] =
+ root[type][S_CORRELATION_ID].asInt();
+ }
+ out[S::S_PARAMS][S::S_PROTOCOL_TYPE] = 0;
+ out[S::S_PARAMS][S::S_PROTOCOL_VERSION] = 1;
+ }
+ } catch (...) {
+ result = kParsingError;
+ }
+
+ return result;
+}
+}
+}
+} // namespace NsSmartDeviceLink::NsJSONHandler::Formatters
+
+#endif // __SMARTDEVICELINKCORE_JSONHANDLER_FORMATTERS__CFORMATTERJSONSDLRPCV1_HPP__
diff --git a/src/components/formatters/include/formatters/CFormatterJsonSDLRPCv1.hpp b/src/components/formatters/include/formatters/CFormatterJsonSDLRPCv1.hpp
deleted file mode 100644
index 03454395b0..0000000000
--- a/src/components/formatters/include/formatters/CFormatterJsonSDLRPCv1.hpp
+++ /dev/null
@@ -1,235 +0,0 @@
-// Copyright (c) 2013, Ford Motor Company
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// Redistributions of source code must retain the above copyright notice, this
-// list of conditions and the following disclaimer.
-//
-// Redistributions in binary form must reproduce the above copyright notice,
-// this list of conditions and the following
-// disclaimer in the documentation and/or other materials provided with the
-// distribution.
-//
-// Neither the name of the Ford Motor Company nor the names of its contributors
-// may be used to endorse or promote products derived from this software
-// without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-#ifndef __SMARTDEVICELINKCORE_JSONHANDLER_FORMATTERS__CFORMATTERJSONSDLRPCV1_HPP__
-#define __SMARTDEVICELINKCORE_JSONHANDLER_FORMATTERS__CFORMATTERJSONSDLRPCV1_HPP__
-
-#include "json/json.h"
-
-#include "smart_objects/smart_object.h"
-#include "smart_objects/enum_schema_item.h"
-
-#include "CFormatterJsonBase.hpp"
-
-#include "formatters/CSmartFactory.hpp"
-#include "formatters/meta_formatter.h"
-
-namespace NsSmartDeviceLink {
-namespace NsJSONHandler {
-namespace Formatters {
-
-/**
- * @brief Class is used to convert SmartObjects to JSON string and vice versa.
- *
- * JSON strings is in SDLRPCv1 format.
- */
-class CFormatterJsonSDLRPCv1 : public CFormatterJsonBase {
- private:
- /**
- * @brief Hidden constructor.
- *
- * The class contains only static methods. Should not be instantiated.
- */
- CFormatterJsonSDLRPCv1();
-
- /**
- * @brief Hidden copy constructor.
- *
- * The class contains only static methods. Should not be instantiated.
- */
- CFormatterJsonSDLRPCv1(const CFormatterJsonSDLRPCv1&);
-
- /**
- * @brief Extracts a message type from the SmartObject
- */
- static const std::string getMessageType(
- const NsSmartDeviceLink::NsSmartObjects::SmartObject& obj);
-
- /**
- * @brief Extracts a message type from the root JSON object.
- *
- * @return Type or empty string if there's no type in the JSON object.
- */
- static const std::string getMessageType(const Json::Value& root);
-
- // SDLRPCv1 string consts
-
- /**
- * @brief String constant for REQUEST.
- */
- static const std::string S_REQUEST;
-
- /**
- * @brief String constant for RESPONSE.
- */
- static const std::string S_RESPONSE;
-
- /**
- * @brief String constant for NOTIFICATION.
- */
- static const std::string S_NOTIFICATION;
-
- /**
- * @brief String constant for PARAMETERS.
- */
- static const std::string S_PARAMETERS;
-
- /**
- * @brief String constant for NAME.
- */
- static const std::string S_NAME;
-
- /**
- * @brief String constant for CORRELATION_ID.
- */
- static const std::string S_CORRELATION_ID;
-
- public:
-
- static const int32_t kSuccess;
- static const int32_t kParsingError;
- static const int32_t kFunctionIdNotFound;
- static const int32_t kMessageTypeNotFound;
- static const int32_t kCorrelationIdNotFound;
-
- typedef NsSmartDeviceLink::NsJSONHandler::Formatters::meta_formatter_error_code::tMetaFormatterErrorCode tMetaFormatterErrorCode;
-
- /**
- * @brief Creates a JSON string from a SmartObject.
- *
- * @param obj input SmartObject
- * @param outStr resulting JSON string
- * @return true if success, false otherwise
- */
- static bool toString(
- const NsSmartDeviceLink::NsSmartObjects::SmartObject &obj,
- std::string& outStr);
-
- /**
- * @brief Creates a SmartObject from a JSON string.
- *
- * @param str input JSON string
- * @param out The resulting SmartObject
- * @return true if success, otherwise - false
- */
- template<typename FunctionId, typename MessageType>
- static int32_t fromString(const std::string &str,
- NsSmartDeviceLink::NsSmartObjects::SmartObject &out);
-
- /**
- * @brief Converts to string the smart object against the given schema
- *
- * @param object Original smart object
- * @param schema Smart schema which describes 'fake' smart object to be formatted
- * @param outStr Resulting JSON string
- * @return formatting error code
- */
- static tMetaFormatterErrorCode MetaFormatToString(
- const NsSmartDeviceLink::NsSmartObjects::SmartObject& object,
- const NsSmartDeviceLink::NsSmartObjects::CSmartSchema& schema,
- std::string& outStr);
-
-};
-
-// ----------------------------------------------------------------------------
-
-template<typename FunctionId, typename MessageType>
-int32_t Formatters::CFormatterJsonSDLRPCv1::fromString(
- const std::string& str,
- NsSmartDeviceLink::NsSmartObjects::SmartObject& out) {
- int32_t result = kSuccess;
-
- try {
- Json::Value root;
- Json::Reader reader;
- std::string type;
-
- if (false == reader.parse(str, root)) {
- result = kParsingError | kMessageTypeNotFound | kFunctionIdNotFound
- | kCorrelationIdNotFound;
- }
-
- if (kSuccess == result) {
- type = getMessageType(root);
- if (true == type.empty()) {
- result = kMessageTypeNotFound | kFunctionIdNotFound
- | kCorrelationIdNotFound;
- }
- }
-
- FunctionId functionId = FunctionId::INVALID_ENUM;
- MessageType messageType = MessageType::INVALID_ENUM;
-
- if (kSuccess == result) {
- if (!NsSmartObjects::EnumConversionHelper<MessageType>::StringToEnum(type, &messageType)) {
- // If MessageType is not found than FunctionId and CorrelationId can not be found either
- result = kMessageTypeNotFound | kFunctionIdNotFound
- | kCorrelationIdNotFound;
- }
- }
-
- if (kSuccess == result) {
- if (!NsSmartObjects::EnumConversionHelper<FunctionId>::StringToEnum(root[type][S_NAME].asString(),
- &functionId)) {
- result = kFunctionIdNotFound;
- functionId = FunctionId::INVALID_ENUM;
- }
- }
-
- namespace S = NsSmartDeviceLink::NsJSONHandler::strings;
-
- if (!(result & kMessageTypeNotFound)) {
- jsonValueToObj(root[type][S_PARAMETERS], out[S::S_MSG_PARAMS]);
-
- out[S::S_PARAMS][S::S_MESSAGE_TYPE] = messageType;
- out[S::S_PARAMS][S::S_FUNCTION_ID] = functionId;
- if (true == root[type][S_CORRELATION_ID].empty()) {
- if (type != S_NOTIFICATION) { // Notification may not have CorrelationId
- result |= kCorrelationIdNotFound;
- out[S::S_PARAMS][S::S_CORRELATION_ID] = -1;
- }
- } else {
- out[S::S_PARAMS][S::S_CORRELATION_ID] = root[type][S_CORRELATION_ID]
- .asInt();
- }
- out[S::S_PARAMS][S::S_PROTOCOL_TYPE] = 0;
- out[S::S_PARAMS][S::S_PROTOCOL_VERSION] = 1;
- }
- } catch (...) {
- result = kParsingError;
- }
-
- return result;
-}
-
-}
-}
-} // namespace NsSmartDeviceLink::NsJSONHandler::Formatters
-
-#endif // __SMARTDEVICELINKCORE_JSONHANDLER_FORMATTERS__CFORMATTERJSONSDLRPCV1_HPP__
diff --git a/src/components/formatters/include/formatters/CFormatterJsonSDLRPCv2.h b/src/components/formatters/include/formatters/CFormatterJsonSDLRPCv2.h
new file mode 100644
index 0000000000..a260ecd080
--- /dev/null
+++ b/src/components/formatters/include/formatters/CFormatterJsonSDLRPCv2.h
@@ -0,0 +1,187 @@
+// Copyright (c) 2013, Ford Motor Company
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// Redistributions of source code must retain the above copyright notice, this
+// list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided with the
+// distribution.
+//
+// Neither the name of the Ford Motor Company nor the names of its contributors
+// may be used to endorse or promote products derived from this software
+// without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef __SMARTDEVICELINKCORE_JSONHANDLER_FORMATTERS__CFORMATTERJSONSDLRPCV2_HPP__
+#define __SMARTDEVICELINKCORE_JSONHANDLER_FORMATTERS__CFORMATTERJSONSDLRPCV2_HPP__
+
+#include "json/json.h"
+
+#include "smart_objects/smart_object.h"
+
+#include "CFormatterJsonBase.h"
+#include "formatters/CSmartFactory.h"
+
+namespace NsSmartDeviceLink {
+namespace NsJSONHandler {
+namespace Formatters {
+
+/**
+ * @brief Class is used to convert SmartObjects to JSON string and vice versa.
+ *
+ * JSON strings is in SDLRPCv2 format.
+ */
+class CFormatterJsonSDLRPCv2 : public CFormatterJsonBase {
+ private:
+ /**
+ * @brief Hidden constructor.
+ *
+ * The class contains only static methods. Should not be instantiated.
+ */
+ CFormatterJsonSDLRPCv2();
+
+ /**
+ * @brief Hidden copy constructor.
+ *
+ * The class contains only static methods. Should not be instantiated.
+ */
+ CFormatterJsonSDLRPCv2(const CFormatterJsonSDLRPCv2&);
+
+ public:
+ typedef NsSmartDeviceLink::NsJSONHandler::Formatters::
+ meta_formatter_error_code::tMetaFormatterErrorCode
+ tMetaFormatterErrorCode;
+
+ /**
+ * @brief Creates a JSON string from a SmartObject.
+ *
+ * @param obj input SmartObject
+ * @param outStr resulting JSON string
+ * @return true if success, false otherwise
+ */
+ static bool toString(
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& obj,
+ std::string& outStr);
+
+ /**
+ * @brief Creates a SmartObject from a JSON string.
+ *
+ * @param str Input JSON string in SDLRPCv2 format
+ * @param out Output SmartObject
+ * @param functionId The corresponding field in SmartObject is filled with
+ *this param.
+ * @param messageType The corresponding field in SmartObject is filled with
+ *this param.
+ * @return true if success, otherwise - false
+ */
+ template <typename FunctionId, typename MessageType>
+ static bool fromString(const std::string& str,
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& out,
+ FunctionId functionId,
+ MessageType messageType);
+
+ /**
+ * @brief Creates a SmartObject from a JSON string.
+ *
+ * Version with CorrelationID.
+ *
+ * @param str Input JSON string in SDLRPCv2 format
+ * @param out Output SmartObject
+ * @param functionId The corresponding field in SmartObject is filled with
+ *this param.
+ * @param messageType The corresponding field in SmartObject is filled with
+ *this param.
+ * @param correlatioId It's like sequence number. The corresponding field in
+ *SmartObject
+ * is filled with this param.
+ * @return true if success, otherwise - false
+ */
+ template <typename FunctionId, typename MessageType>
+ static bool fromString(const std::string& str,
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& out,
+ FunctionId functionId,
+ MessageType messageType,
+ int32_t correlationId);
+
+ /**
+ * @brief Converts to string the smart object against the given schema
+ *
+ * @param object Original smart object
+ * @param schema Smart schema which describes 'fake' smart object to be
+ *formatted
+ * @param outStr Resulting JSON string
+ * @return formatting error code
+ */
+ static tMetaFormatterErrorCode MetaFormatToString(
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& object,
+ const NsSmartDeviceLink::NsSmartObjects::CSmartSchema& schema,
+ std::string& outStr);
+};
+
+template <typename FunctionId, typename MessageType>
+inline bool CFormatterJsonSDLRPCv2::fromString(
+ const std::string& str,
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& out,
+ FunctionId functionId,
+ MessageType messageType) {
+ bool result = true;
+
+ try {
+ Json::Value root;
+ Json::Reader reader;
+
+ namespace strings = NsSmartDeviceLink::NsJSONHandler::strings;
+ bool result = reader.parse(str, root);
+
+ if (true == result) {
+ out[strings::S_PARAMS][strings::S_MESSAGE_TYPE] = messageType;
+ out[strings::S_PARAMS][strings::S_FUNCTION_ID] = functionId;
+ out[strings::S_PARAMS][strings::S_PROTOCOL_TYPE] = 0;
+ out[strings::S_PARAMS][strings::S_PROTOCOL_VERSION] = 2;
+
+ jsonValueToObj(root, out[strings::S_MSG_PARAMS]);
+ }
+ } catch (...) {
+ result = false;
+ }
+
+ return result;
+}
+
+template <typename FunctionId, typename MessageType>
+inline bool CFormatterJsonSDLRPCv2::fromString(
+ const std::string& str,
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& out,
+ FunctionId functionId,
+ MessageType messageType,
+ int32_t correlationId) {
+ bool result = fromString(str, out, functionId, messageType);
+ namespace strings = NsSmartDeviceLink::NsJSONHandler::strings;
+
+ if (true == result) {
+ out[strings::S_PARAMS][strings::S_CORRELATION_ID] = correlationId;
+ }
+
+ return result;
+}
+}
+}
+} // namespace NsSmartDeviceLink::NsJSONHandler::Formatters
+
+#endif // __SMARTDEVICELINKCORE_JSONHANDLER_FORMATTERS__CFORMATTERJSONSDLRPCV2_HPP__
diff --git a/src/components/formatters/include/formatters/CFormatterJsonSDLRPCv2.hpp b/src/components/formatters/include/formatters/CFormatterJsonSDLRPCv2.hpp
deleted file mode 100644
index 3b4e206515..0000000000
--- a/src/components/formatters/include/formatters/CFormatterJsonSDLRPCv2.hpp
+++ /dev/null
@@ -1,176 +0,0 @@
-// Copyright (c) 2013, Ford Motor Company
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// Redistributions of source code must retain the above copyright notice, this
-// list of conditions and the following disclaimer.
-//
-// Redistributions in binary form must reproduce the above copyright notice,
-// this list of conditions and the following
-// disclaimer in the documentation and/or other materials provided with the
-// distribution.
-//
-// Neither the name of the Ford Motor Company nor the names of its contributors
-// may be used to endorse or promote products derived from this software
-// without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-#ifndef __SMARTDEVICELINKCORE_JSONHANDLER_FORMATTERS__CFORMATTERJSONSDLRPCV2_HPP__
-#define __SMARTDEVICELINKCORE_JSONHANDLER_FORMATTERS__CFORMATTERJSONSDLRPCV2_HPP__
-
-#include "json/json.h"
-
-#include "smart_objects/smart_object.h"
-
-#include "CFormatterJsonBase.hpp"
-#include "formatters/CSmartFactory.hpp"
-
-namespace NsSmartDeviceLink {
-namespace NsJSONHandler {
-namespace Formatters {
-
-/**
- * @brief Class is used to convert SmartObjects to JSON string and vice versa.
- *
- * JSON strings is in SDLRPCv2 format.
- */
-class CFormatterJsonSDLRPCv2 : public CFormatterJsonBase {
- private:
-
- /**
- * @brief Hidden constructor.
- *
- * The class contains only static methods. Should not be instantiated.
- */
- CFormatterJsonSDLRPCv2();
-
- /**
- * @brief Hidden copy constructor.
- *
- * The class contains only static methods. Should not be instantiated.
- */
- CFormatterJsonSDLRPCv2(const CFormatterJsonSDLRPCv2&);
-
- public:
-
- typedef NsSmartDeviceLink::NsJSONHandler::Formatters::meta_formatter_error_code::tMetaFormatterErrorCode tMetaFormatterErrorCode;
-
- /**
- * @brief Creates a JSON string from a SmartObject.
- *
- * @param obj input SmartObject
- * @param outStr resulting JSON string
- * @return true if success, false otherwise
- */
- static bool toString(
- const NsSmartDeviceLink::NsSmartObjects::SmartObject &obj,
- std::string& outStr);
-
- /**
- * @brief Creates a SmartObject from a JSON string.
- *
- * @param str Input JSON string in SDLRPCv2 format
- * @param out Output SmartObject
- * @param functionId The corresponding field in SmartObject is filled with this param.
- * @param messageType The corresponding field in SmartObject is filled with this param.
- * @return true if success, otherwise - false
- */
- template<typename FunctionId, typename MessageType>
- static bool fromString(const std::string &str,
- NsSmartDeviceLink::NsSmartObjects::SmartObject &out,
- FunctionId functionId, MessageType messageType);
-
- /**
- * @brief Creates a SmartObject from a JSON string.
- *
- * Version with CorrelationID.
- *
- * @param str Input JSON string in SDLRPCv2 format
- * @param out Output SmartObject
- * @param functionId The corresponding field in SmartObject is filled with this param.
- * @param messageType The corresponding field in SmartObject is filled with this param.
- * @param correlatioId It's like sequence number. The corresponding field in SmartObject
- * is filled with this param.
- * @return true if success, otherwise - false
- */
- template<typename FunctionId, typename MessageType>
- static bool fromString(const std::string &str,
- NsSmartDeviceLink::NsSmartObjects::SmartObject &out,
- FunctionId functionId, MessageType messageType,
- int32_t correlationId);
-
- /**
- * @brief Converts to string the smart object against the given schema
- *
- * @param object Original smart object
- * @param schema Smart schema which describes 'fake' smart object to be formatted
- * @param outStr Resulting JSON string
- * @return formatting error code
- */
- static tMetaFormatterErrorCode MetaFormatToString(
- const NsSmartDeviceLink::NsSmartObjects::SmartObject& object,
- const NsSmartDeviceLink::NsSmartObjects::CSmartSchema& schema,
- std::string& outStr);
-};
-
-template<typename FunctionId, typename MessageType>
-inline bool CFormatterJsonSDLRPCv2::fromString(
- const std::string& str, NsSmartDeviceLink::NsSmartObjects::SmartObject& out,
- FunctionId functionId, MessageType messageType) {
- bool result = true;
-
- try {
- Json::Value root;
- Json::Reader reader;
-
- namespace strings = NsSmartDeviceLink::NsJSONHandler::strings;
- bool result = reader.parse(str, root);
-
- if (true == result) {
- out[strings::S_PARAMS][strings::S_MESSAGE_TYPE] = messageType;
- out[strings::S_PARAMS][strings::S_FUNCTION_ID] = functionId;
- out[strings::S_PARAMS][strings::S_PROTOCOL_TYPE] = 0;
- out[strings::S_PARAMS][strings::S_PROTOCOL_VERSION] = 2;
-
- jsonValueToObj(root, out[strings::S_MSG_PARAMS]);
- }
- } catch (...) {
- result = false;
- }
-
- return result;
-}
-
-template<typename FunctionId, typename MessageType>
-inline bool CFormatterJsonSDLRPCv2::fromString(
- const std::string& str, NsSmartDeviceLink::NsSmartObjects::SmartObject& out,
- FunctionId functionId, MessageType messageType, int32_t correlationId) {
-
- bool result = fromString(str, out, functionId, messageType);
- namespace strings = NsSmartDeviceLink::NsJSONHandler::strings;
-
- if (true == result) {
- out[strings::S_PARAMS][strings::S_CORRELATION_ID] = correlationId;
- }
-
- return result;
-}
-
-}
-}
-} // namespace NsSmartDeviceLink::NsJSONHandler::Formatters
-
-#endif // __SMARTDEVICELINKCORE_JSONHANDLER_FORMATTERS__CFORMATTERJSONSDLRPCV2_HPP__
diff --git a/src/components/formatters/include/formatters/CSmartFactory.h b/src/components/formatters/include/formatters/CSmartFactory.h
new file mode 100644
index 0000000000..223d22fbbe
--- /dev/null
+++ b/src/components/formatters/include/formatters/CSmartFactory.h
@@ -0,0 +1,410 @@
+/**
+ * @file CSmartFactory.hpp
+ * @brief CSmartFactory header file.
+ */
+// Copyright (c) 2013, Ford Motor Company
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// Redistributions of source code must retain the above copyright notice, this
+// list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided with the
+// distribution.
+//
+// Neither the name of the Ford Motor Company nor the names of its contributors
+// may be used to endorse or promote products derived from this software
+// without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#ifndef __CSMARTFACTORY_HPP__
+#define __CSMARTFACTORY_HPP__
+
+#include "smart_objects/smart_object.h"
+#include "smart_objects/smart_schema.h"
+#include <map>
+#include <string>
+
+namespace NsSmartDeviceLink {
+namespace NsJSONHandler {
+/**
+ * @brief String constants used by SmartFactory.
+ */
+namespace strings {
+/**
+ * @brief String constant for MSG_PARAMS.
+ */
+extern const std::string S_MSG_PARAMS;
+
+/**
+ * @brief String constant for PARAMS.
+ */
+extern const std::string S_PARAMS;
+
+/**
+ * @brief String constant for FUNCTION_ID.
+ */
+extern const std::string S_FUNCTION_ID;
+
+/**
+ * @brief String constant for MESSAGE_TYPE.
+ */
+extern const std::string S_MESSAGE_TYPE;
+
+/**
+ * @brief String constant for PROTOCOL_VERSION.
+ */
+extern const std::string S_PROTOCOL_VERSION;
+
+/**
+ * @brief String constant for PROTOCOL_TYPE.
+ */
+extern const std::string S_PROTOCOL_TYPE;
+
+/**
+ * @brief String constant for CORRELATION_ID.
+ */
+extern const std::string S_CORRELATION_ID;
+
+/**
+ * @brief String constant for "code" param name.
+ */
+extern const std::string kCode;
+
+/**
+ * @brief String constant for "message" param name.
+ */
+extern const std::string kMessage;
+}
+
+/**
+ * @brief Smart Schema key.
+ *
+ * @tparam FunctionIdEnum Type of function ID enum.
+ * @tparam MessageTypeEnum Type of messageType enum.
+ */
+template <class FunctionIdEnum, class MessageTypeEnum>
+struct SmartSchemaKey {
+ /**
+ * @brief Value of function ID for the key.
+ */
+ FunctionIdEnum functionId;
+
+ /**
+ * @brief Value of messageType for the key.
+ */
+ MessageTypeEnum messageType;
+
+ /**
+ * @brief Constructor.
+ *
+ * @param functionIdParam Value of function ID.
+ * @param messageTypeParam Value of message type.
+ */
+ SmartSchemaKey(FunctionIdEnum functionIdParam,
+ MessageTypeEnum messageTypeParam);
+};
+
+/**
+ * @brief Smart Factory.
+ *
+ * This class is used as base class for generated factories.
+ * Clients should use methods of this class to access all
+ * SmartSchema validation features.
+ *
+ * @tparam FunctionIdEnum Type of function ID enum.
+ * @tparam MessageTypeEnum Type of messageType enum.
+ * @tparam StructIdEnum Type of StructId enum.
+ */
+template <class FunctionIdEnum, class MessageTypeEnum, class StructIdEnum>
+class CSmartFactory {
+ public:
+ /**
+ * @brief Constructor.
+ */
+ CSmartFactory(void);
+
+ /**
+ * @brief Attach schema to the function SmartObject.
+ *
+ * @param object SmartObject to attach schema for.
+ *
+ * @param RemoveFakeParameters contains true if need
+ * to remove fake parameters from smart object otherwise contains false.
+ *
+ * @return True if operation was successful or false otherwise.
+ */
+ bool attachSchema(NsSmartDeviceLink::NsSmartObjects::SmartObject& object,
+ const bool RemoveFakeParameters);
+
+ /**
+ * @brief Attach schema to the struct SmartObject.
+ *
+ * @param struct_id Identifier of the struct.
+ * @param object SmartObject to attach schema for.
+ *
+ * @return True if operation was successful of false otherwise.
+ */
+ bool AttachSchema(const StructIdEnum struct_id,
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& object);
+
+ /**
+ * @brief Create new SmartObject with attached function SmartSchema.
+ *
+ * @param function_id FunctionID of the function.
+ * @param message_type messageType of the function.
+ *
+ * @return If function succeeded it returns new SmartObject with
+ * map type and attached SmartSchema. Client can use such
+ * object to store specific function and perform validation.
+ * Otherwise (if SmartSchema was not attached to the
+ * SmartObject) function returns empty SmartObject with
+ * null type.
+ */
+ NsSmartDeviceLink::NsSmartObjects::SmartObject CreateSmartObject(
+ const FunctionIdEnum function_id, const MessageTypeEnum message_type);
+
+ /**
+ * @brief Create new SmartObject with attached struct SmartSchema.
+ *
+ * @param struct_id Identifier of the struct.
+ *
+ * @return If function succeeded it returns new SmartObject with
+ * map type and attached SmartSchema. Client can use such
+ * object to store specific struct and perform validation.
+ * Otherwise (if SmartSchema was not attached to the
+ * SmartObject) function returns empty SmartObject with
+ * null type.
+ */
+ NsSmartDeviceLink::NsSmartObjects::SmartObject CreateSmartObject(
+ const StructIdEnum struct_id);
+
+ /**
+ * @brief Get SmartSchema for specific function.
+ *
+ * @param function_id FunctionID of the function.
+ * @param message_type messageType of the function.
+ * @param[out] result This value will be copy of the desired
+ * function SmartSchema if it found (this
+ * function returns true) or unmodified if
+ * SmartSchema is not found (this function
+ * returns false).
+ *
+ * @return True if function schema for specified input parameters
+ * is found or false otherwise.
+ */
+ bool GetSchema(const FunctionIdEnum function_id,
+ const MessageTypeEnum message_type,
+ NsSmartDeviceLink::NsSmartObjects::CSmartSchema& result);
+
+ /**
+ * @brief Get SmartSchema for specific struct.
+ *
+ * @param struct_id Identifier of the struct.
+ *
+ * @param[out] result This value will be copy of the desired
+ * struct SmartSchema if it found (this
+ * function returns true) or unmodified if
+ * SmartSchema is not found (this function
+ * returns false).
+ *
+ * @return True if struct schema for specified input parameter is
+ * found or false otherwise.
+ */
+ bool GetSchema(const StructIdEnum struct_id,
+ NsSmartDeviceLink::NsSmartObjects::CSmartSchema& result);
+
+ protected:
+ /**
+ * @brief Defines map of SmartSchemaKeys to the SmartSchemes.
+ *
+ * This container type should be used to store SmartSchemes of
+ * functions.
+ */
+ typedef std::map<SmartSchemaKey<FunctionIdEnum, MessageTypeEnum>,
+ NsSmartDeviceLink::NsSmartObjects::CSmartSchema>
+ FuncionsSchemesMap;
+
+ /**
+ * @brief Defines map of StructIdEnum to the SmartSchemes.
+ *
+ * This container type should be used to store SmartSchemes of
+ * structs.
+ */
+ typedef std::map<StructIdEnum,
+ NsSmartDeviceLink::NsSmartObjects::CSmartSchema>
+ StructsSchemesMap;
+
+ /**
+ * @brief Map of all function schemes for this factory.
+ */
+ FuncionsSchemesMap functions_schemes_;
+
+ /**
+ * @brief Map of all struct shemes for this factory.
+ */
+ StructsSchemesMap structs_schemes_;
+};
+
+template <class FunctionIdEnum, class MessageTypeEnum, class StructIdEnum>
+CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::CSmartFactory(
+ void)
+ : functions_schemes_(), structs_schemes_() {}
+
+template <class FunctionIdEnum, class MessageTypeEnum, class StructIdEnum>
+bool CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::attachSchema(
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& object,
+ const bool RemoveFakeParameters) {
+ if (false == object.keyExists(strings::S_PARAMS))
+ return false;
+ if (false == object[strings::S_PARAMS].keyExists(strings::S_MESSAGE_TYPE))
+ return false;
+ if (false == object[strings::S_PARAMS].keyExists(strings::S_FUNCTION_ID))
+ return false;
+
+ MessageTypeEnum msgtype(
+ (MessageTypeEnum)
+ object[strings::S_PARAMS][strings::S_MESSAGE_TYPE].asInt());
+ FunctionIdEnum fid(
+ (FunctionIdEnum)
+ object[strings::S_PARAMS][strings::S_FUNCTION_ID].asInt());
+
+ SmartSchemaKey<FunctionIdEnum, MessageTypeEnum> key(fid, msgtype);
+
+ typename FuncionsSchemesMap::iterator schemaIterator =
+ functions_schemes_.find(key);
+
+ if (schemaIterator == functions_schemes_.end()) {
+ // Schema was not found
+ return false;
+ }
+
+ object.setSchema(schemaIterator->second);
+ schemaIterator->second.applySchema(object, RemoveFakeParameters);
+
+ return true;
+}
+
+template <class FunctionIdEnum, class MessageTypeEnum, class StructIdEnum>
+bool CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::AttachSchema(
+ const StructIdEnum struct_id,
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& object) {
+ typename StructsSchemesMap::iterator structs_iterator =
+ structs_schemes_.find(struct_id);
+
+ if (structs_iterator == structs_schemes_.end()) {
+ return false;
+ }
+
+ object.setSchema(structs_iterator->second);
+ structs_iterator->second.applySchema(object, false);
+
+ return true;
+}
+
+template <class FunctionIdEnum, class MessageTypeEnum, class StructIdEnum>
+NsSmartDeviceLink::NsSmartObjects::SmartObject
+CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::CreateSmartObject(
+ const FunctionIdEnum function_id, const MessageTypeEnum message_type) {
+ SmartSchemaKey<FunctionIdEnum, MessageTypeEnum> key(function_id,
+ message_type);
+
+ typename FuncionsSchemesMap::iterator schema_iterator =
+ functions_schemes_.find(key);
+
+ if (schema_iterator != functions_schemes_.end()) {
+ NsSmartDeviceLink::NsSmartObjects::SmartObject function_object(
+ NsSmartDeviceLink::NsSmartObjects::SmartType_Map);
+ function_object.setSchema(schema_iterator->second);
+ schema_iterator->second.applySchema(function_object, false);
+ return function_object;
+ }
+
+ return NsSmartDeviceLink::NsSmartObjects::SmartObject();
+}
+
+template <class FunctionIdEnum, class MessageTypeEnum, class StructIdEnum>
+NsSmartDeviceLink::NsSmartObjects::SmartObject
+CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::CreateSmartObject(
+ const StructIdEnum struct_id) {
+ NsSmartDeviceLink::NsSmartObjects::SmartObject struct_object(
+ NsSmartDeviceLink::NsSmartObjects::SmartType_Map);
+ if (AttachSchema(struct_id, struct_object)) {
+ return struct_object;
+ }
+
+ return NsSmartDeviceLink::NsSmartObjects::SmartObject();
+}
+
+template <class FunctionIdEnum, class MessageTypeEnum, class StructIdEnum>
+bool CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::GetSchema(
+ const FunctionIdEnum function_id,
+ const MessageTypeEnum message_type,
+ NsSmartDeviceLink::NsSmartObjects::CSmartSchema& result) {
+ SmartSchemaKey<FunctionIdEnum, MessageTypeEnum> key(function_id,
+ message_type);
+
+ typename FuncionsSchemesMap::iterator schema_iterator =
+ functions_schemes_.find(key);
+
+ if (schema_iterator != functions_schemes_.end()) {
+ result = schema_iterator->second;
+ return true;
+ }
+
+ return false;
+}
+
+template <class FunctionIdEnum, class MessageTypeEnum, class StructIdEnum>
+bool CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::GetSchema(
+ const StructIdEnum struct_id,
+ NsSmartDeviceLink::NsSmartObjects::CSmartSchema& result) {
+ typename StructsSchemesMap::iterator structs_iterator =
+ structs_schemes_.find(struct_id);
+
+ if (structs_iterator != structs_schemes_.end()) {
+ result = structs_iterator->second;
+ return true;
+ }
+
+ return false;
+}
+
+template <class FunctionIdEnum, class MessageTypeEnum>
+SmartSchemaKey<FunctionIdEnum, MessageTypeEnum>::SmartSchemaKey(
+ FunctionIdEnum functionIdParam, MessageTypeEnum messageTypeParam)
+ : functionId(functionIdParam), messageType(messageTypeParam) {}
+
+template <class FunctionIdEnum, class MessageTypeEnum>
+bool operator<(const SmartSchemaKey<FunctionIdEnum, MessageTypeEnum>& l,
+ const SmartSchemaKey<FunctionIdEnum, MessageTypeEnum>& r) {
+ if (l.functionId < r.functionId)
+ return true;
+ if (l.functionId > r.functionId)
+ return false;
+
+ if (l.messageType < r.messageType)
+ return true;
+ if (l.messageType > r.messageType)
+ return false;
+
+ return false;
+}
+}
+}
+#endif //__CSMARTFACTORY_HPP__
diff --git a/src/components/formatters/include/formatters/CSmartFactory.hpp b/src/components/formatters/include/formatters/CSmartFactory.hpp
deleted file mode 100644
index 55f9a30385..0000000000
--- a/src/components/formatters/include/formatters/CSmartFactory.hpp
+++ /dev/null
@@ -1,428 +0,0 @@
-/**
- * @file CSmartFactory.hpp
- * @brief CSmartFactory header file.
- */
-// Copyright (c) 2013, Ford Motor Company
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// Redistributions of source code must retain the above copyright notice, this
-// list of conditions and the following disclaimer.
-//
-// Redistributions in binary form must reproduce the above copyright notice,
-// this list of conditions and the following
-// disclaimer in the documentation and/or other materials provided with the
-// distribution.
-//
-// Neither the name of the Ford Motor Company nor the names of its contributors
-// may be used to endorse or promote products derived from this software
-// without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-#ifndef __CSMARTFACTORY_HPP__
-#define __CSMARTFACTORY_HPP__
-
-#include "smart_objects/smart_object.h"
-#include "smart_objects/smart_schema.h"
-#include <map>
-#include <string>
-
-namespace NsSmartDeviceLink
-{
- namespace NsJSONHandler
- {
- /**
- * @brief String constants used by SmartFactory.
- */
- namespace strings
- {
- /**
- * @brief String constant for MSG_PARAMS.
- */
- extern const std::string S_MSG_PARAMS;
-
- /**
- * @brief String constant for PARAMS.
- */
- extern const std::string S_PARAMS;
-
- /**
- * @brief String constant for FUNCTION_ID.
- */
- extern const std::string S_FUNCTION_ID;
-
- /**
- * @brief String constant for MESSAGE_TYPE.
- */
- extern const std::string S_MESSAGE_TYPE;
-
- /**
- * @brief String constant for PROTOCOL_VERSION.
- */
- extern const std::string S_PROTOCOL_VERSION;
-
- /**
- * @brief String constant for PROTOCOL_TYPE.
- */
- extern const std::string S_PROTOCOL_TYPE;
-
- /**
- * @brief String constant for CORRELATION_ID.
- */
- extern const std::string S_CORRELATION_ID;
-
- /**
- * @brief String constant for "code" param name.
- */
- extern const std::string kCode;
-
- /**
- * @brief String constant for "message" param name.
- */
- extern const std::string kMessage;
- }
-
- /**
- * @brief Smart Schema key.
- *
- * @tparam FunctionIdEnum Type of function ID enum.
- * @tparam MessageTypeEnum Type of messageType enum.
- */
- template <class FunctionIdEnum, class MessageTypeEnum>
- struct SmartSchemaKey
- {
- /**
- * @brief Value of function ID for the key.
- */
- FunctionIdEnum functionId;
-
- /**
- * @brief Value of messageType for the key.
- */
- MessageTypeEnum messageType;
-
- /**
- * @brief Constructor.
- *
- * @param functionIdParam Value of function ID.
- * @param messageTypeParam Value of message type.
- */
- SmartSchemaKey(FunctionIdEnum functionIdParam, MessageTypeEnum messageTypeParam);
- };
-
- /**
- * @brief Smart Factory.
- *
- * This class is used as base class for generated factories.
- * Clients should use methods of this class to access all
- * SmartSchema validation features.
- *
- * @tparam FunctionIdEnum Type of function ID enum.
- * @tparam MessageTypeEnum Type of messageType enum.
- * @tparam StructIdEnum Type of StructId enum.
- */
- template <class FunctionIdEnum, class MessageTypeEnum, class StructIdEnum>
- class CSmartFactory
- {
- public:
-
- /**
- * @brief Constructor.
- */
- CSmartFactory(void);
-
- /**
- * @brief Attach schema to the function SmartObject.
- *
- * @param object SmartObject to attach schema for.
- *
- * @param RemoveFakeParameters contains true if need
- * to remove fake parameters from smart object otherwise contains false.
- *
- * @return True if operation was successful or false otherwise.
- */
- bool attachSchema(NsSmartDeviceLink::NsSmartObjects::SmartObject& object,
- const bool RemoveFakeParameters);
-
- /**
- * @brief Attach schema to the struct SmartObject.
- *
- * @param struct_id Identifier of the struct.
- * @param object SmartObject to attach schema for.
- *
- * @return True if operation was successful of false otherwise.
- */
- bool AttachSchema(const StructIdEnum struct_id,
- NsSmartDeviceLink::NsSmartObjects::SmartObject &object);
-
-
- /**
- * @brief Create new SmartObject with attached function SmartSchema.
- *
- * @param function_id FunctionID of the function.
- * @param message_type messageType of the function.
- *
- * @return If function succeeded it returns new SmartObject with
- * map type and attached SmartSchema. Client can use such
- * object to store specific function and perform validation.
- * Otherwise (if SmartSchema was not attached to the
- * SmartObject) function returns empty SmartObject with
- * null type.
- */
- NsSmartDeviceLink::NsSmartObjects::SmartObject CreateSmartObject(
- const FunctionIdEnum function_id,
- const MessageTypeEnum message_type);
-
- /**
- * @brief Create new SmartObject with attached struct SmartSchema.
- *
- * @param struct_id Identifier of the struct.
- *
- * @return If function succeeded it returns new SmartObject with
- * map type and attached SmartSchema. Client can use such
- * object to store specific struct and perform validation.
- * Otherwise (if SmartSchema was not attached to the
- * SmartObject) function returns empty SmartObject with
- * null type.
- */
- NsSmartDeviceLink::NsSmartObjects::SmartObject CreateSmartObject(
- const StructIdEnum struct_id);
-
- /**
- * @brief Get SmartSchema for specific function.
- *
- * @param function_id FunctionID of the function.
- * @param message_type messageType of the function.
- * @param[out] result This value will be copy of the desired
- * function SmartSchema if it found (this
- * function returns true) or unmodified if
- * SmartSchema is not found (this function
- * returns false).
- *
- * @return True if function schema for specified input parameters
- * is found or false otherwise.
- */
- bool GetSchema(
- const FunctionIdEnum function_id,
- const MessageTypeEnum message_type,
- NsSmartDeviceLink::NsSmartObjects::CSmartSchema &result);
-
- /**
- * @brief Get SmartSchema for specific struct.
- *
- * @param struct_id Identifier of the struct.
- *
- * @param[out] result This value will be copy of the desired
- * struct SmartSchema if it found (this
- * function returns true) or unmodified if
- * SmartSchema is not found (this function
- * returns false).
- *
- * @return True if struct schema for specified input parameter is
- * found or false otherwise.
- */
- bool GetSchema(
- const StructIdEnum struct_id,
- NsSmartDeviceLink::NsSmartObjects::CSmartSchema &result);
-
- protected:
-
- /**
- * @brief Defines map of SmartSchemaKeys to the SmartSchemes.
- *
- * This container type should be used to store SmartSchemes of
- * functions.
- */
- typedef std::map<SmartSchemaKey<FunctionIdEnum, MessageTypeEnum>,
- NsSmartDeviceLink::NsSmartObjects::CSmartSchema>
- FuncionsSchemesMap;
-
- /**
- * @brief Defines map of StructIdEnum to the SmartSchemes.
- *
- * This container type should be used to store SmartSchemes of
- * structs.
- */
- typedef std::map<StructIdEnum,
- NsSmartDeviceLink::NsSmartObjects::CSmartSchema>
- StructsSchemesMap;
-
- /**
- * @brief Map of all function schemes for this factory.
- */
- FuncionsSchemesMap functions_schemes_;
-
- /**
- * @brief Map of all struct shemes for this factory.
- */
- StructsSchemesMap structs_schemes_;
- };
-
- template <class FunctionIdEnum, class MessageTypeEnum, class StructIdEnum>
- CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::CSmartFactory(void)
- : functions_schemes_(),
- structs_schemes_()
- {
- }
-
- template <class FunctionIdEnum, class MessageTypeEnum, class StructIdEnum>
- bool CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::
- attachSchema(NsSmartDeviceLink::NsSmartObjects::SmartObject &object,
- const bool RemoveFakeParameters)
- {
- if(false == object.keyExists(strings::S_PARAMS)) return false;
- if(false == object[strings::S_PARAMS].keyExists(strings::S_MESSAGE_TYPE)) return false;
- if(false == object[strings::S_PARAMS].keyExists(strings::S_FUNCTION_ID)) return false;
-
- MessageTypeEnum msgtype((MessageTypeEnum)object[strings::S_PARAMS][strings::S_MESSAGE_TYPE].asInt());
- FunctionIdEnum fid((FunctionIdEnum)object[strings::S_PARAMS][strings::S_FUNCTION_ID].asInt());
-
- SmartSchemaKey<FunctionIdEnum, MessageTypeEnum> key(fid, msgtype);
-
- typename FuncionsSchemesMap::iterator schemaIterator = functions_schemes_.find(key);
-
- if(schemaIterator == functions_schemes_.end())
- {
- // Schema was not found
- return false;
- }
-
- object.setSchema(schemaIterator->second);
- schemaIterator->second.applySchema(object, RemoveFakeParameters);
-
- return true;
- }
-
- template <class FunctionIdEnum,
- class MessageTypeEnum,
- class StructIdEnum>
- bool CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::
- AttachSchema(
- const StructIdEnum struct_id,
- NsSmartDeviceLink::NsSmartObjects::SmartObject &object) {
- typename StructsSchemesMap::iterator structs_iterator =
- structs_schemes_.find(struct_id);
-
- if (structs_iterator == structs_schemes_.end()) {
- return false;
- }
-
- object.setSchema(structs_iterator->second);
- structs_iterator->second.applySchema(object, false);
-
- return true;
- }
-
- template <class FunctionIdEnum,
- class MessageTypeEnum,
- class StructIdEnum>
- NsSmartDeviceLink::NsSmartObjects::SmartObject
- CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::
- CreateSmartObject(
- const FunctionIdEnum function_id,
- const MessageTypeEnum message_type) {
- SmartSchemaKey<FunctionIdEnum, MessageTypeEnum> key(
- function_id, message_type);
-
- typename FuncionsSchemesMap::iterator schema_iterator =
- functions_schemes_.find(key);
-
- if(schema_iterator != functions_schemes_.end()) {
- NsSmartDeviceLink::NsSmartObjects::SmartObject function_object(
- NsSmartDeviceLink::NsSmartObjects::SmartType_Map);
- function_object.setSchema(schema_iterator->second);
- schema_iterator->second.applySchema(function_object, false);
- return function_object;
- }
-
- return NsSmartDeviceLink::NsSmartObjects::SmartObject();
- }
-
- template <class FunctionIdEnum,
- class MessageTypeEnum,
- class StructIdEnum>
- NsSmartDeviceLink::NsSmartObjects::SmartObject
- CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::
- CreateSmartObject(const StructIdEnum struct_id) {
- NsSmartDeviceLink::NsSmartObjects::SmartObject struct_object(
- NsSmartDeviceLink::NsSmartObjects::SmartType_Map);
- if (AttachSchema(struct_id, struct_object)) {
- return struct_object;
- }
-
- return NsSmartDeviceLink::NsSmartObjects::SmartObject();
- }
-
- template <class FunctionIdEnum,
- class MessageTypeEnum,
- class StructIdEnum>
- bool CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::
- GetSchema(const FunctionIdEnum function_id,
- const MessageTypeEnum message_type,
- NsSmartDeviceLink::NsSmartObjects::CSmartSchema &result) {
- SmartSchemaKey<FunctionIdEnum, MessageTypeEnum> key(function_id,
- message_type);
-
- typename FuncionsSchemesMap::iterator schema_iterator =
- functions_schemes_.find(key);
-
- if(schema_iterator != functions_schemes_.end()) {
- result = schema_iterator->second;
- return true;
- }
-
- return false;
- }
-
- template <class FunctionIdEnum,
- class MessageTypeEnum,
- class StructIdEnum>
- bool CSmartFactory<FunctionIdEnum, MessageTypeEnum, StructIdEnum>::
- GetSchema(const StructIdEnum struct_id,
- NsSmartDeviceLink::NsSmartObjects::CSmartSchema &result) {
- typename StructsSchemesMap::iterator structs_iterator =
- structs_schemes_.find(struct_id);
-
- if(structs_iterator != structs_schemes_.end()) {
- result = structs_iterator->second;
- return true;
- }
-
- return false;
- }
-
- template <class FunctionIdEnum, class MessageTypeEnum>
- SmartSchemaKey<FunctionIdEnum, MessageTypeEnum>::SmartSchemaKey(FunctionIdEnum functionIdParam, MessageTypeEnum messageTypeParam)
- : functionId(functionIdParam)
- , messageType(messageTypeParam)
- {
-
- }
-
- template <class FunctionIdEnum, class MessageTypeEnum>
- bool operator<(const SmartSchemaKey< FunctionIdEnum, MessageTypeEnum >& l, const SmartSchemaKey< FunctionIdEnum, MessageTypeEnum >& r)
- {
- if (l.functionId < r.functionId) return true;
- if (l.functionId > r.functionId) return false;
-
- if (l.messageType < r.messageType) return true;
- if (l.messageType > r.messageType) return false;
-
- return false;
- }
- }
-}
-#endif //__CSMARTFACTORY_HPP__
diff --git a/src/components/formatters/include/formatters/formatter_json_rpc.h b/src/components/formatters/include/formatters/formatter_json_rpc.h
index d4653ef565..db122fa1a2 100644
--- a/src/components/formatters/include/formatters/formatter_json_rpc.h
+++ b/src/components/formatters/include/formatters/formatter_json_rpc.h
@@ -42,8 +42,8 @@
#include "smart_objects/enum_schema_item.h"
#include "json/json.h"
-#include "CFormatterJsonBase.hpp"
-#include "formatters/CSmartFactory.hpp"
+#include "CFormatterJsonBase.h"
+#include "formatters/CSmartFactory.h"
namespace NsSmartDeviceLink {
namespace NsJSONHandler {
@@ -52,415 +52,415 @@ namespace Formatters {
/**
* @brief Formatter for JSON RPC format.
*/
-class FormatterJsonRpc: public CFormatterJsonBase {
- public:
- /**
- * @brief No errors occurred during the parsing of the input JSON string.
- */
- static const int32_t kSuccess = 0;
-
- /**
- * @brief Input JSON string cannot be parsed.
- */
- static const int32_t kParsingError = 1;
-
- /**
- * @brief Input JSON string has invalid format.
- */
- static const int32_t kInvalidFormat = 2;
-
- /**
- * @brief Method in input JSON string is not
- * specified or specified incorrectly.
- */
- static const int32_t kMethodNotSpecified = 4;
-
- /**
- * @brief Method is unknown.
- */
- static const int32_t kUnknownMethod = 8;
-
- /**
- * @brief Message type is unknown.
- */
- static const int32_t kUnknownMessageType = 16;
-
- /**
- * @brief Id of request or response is invalid.
- */
- static const int32_t kInvalidId = 32;
-
- /**
- * @brief Response code is not available.
- */
- static const int32_t kResponseCodeNotAvailable = 64;
-
- /**
- * @brief Message for error response is not available.
- */
- static const int32_t kErrorResponseMessageNotAvailable = 128;
-
- /**
- * @brief Creates a JSON string from a SmartObject.
- *
- * @param obj Input SmartObject.
- * @param out_str Resulting JSON string.
- *
- * @return true if success, false otherwise.
- */
- static bool ToString(const NsSmartObjects::SmartObject& obj,
- std::string& out_str);
-
- /**
- * @brief Creates a SmartObject from a JSON string.
- *
- * @tparam FunctionId Type of function id enumeration.
- * @tparam MessageType Type of message type enumeration.
- *
- * @param str input JSON string.
- * @param out The resulting SmartObject.
- *
- * @return An integer that is a bitwise-or of all error codes occurred
- * during the parsing of the input string. 0 if no errors occurred.
- */
- template <typename FunctionId, typename MessageType>
- static int32_t FromString(const std::string& str,
- NsSmartObjects::SmartObject& out);
-
- private:
- /**
- * @brief Request.
- */
- static const char* kRequest;
-
- /**
- * @brief Response.
- */
- static const char* kResponse;
-
- /**
- * @brief Notification.
- */
- static const char* kNotification;
-
- /**
- * @brief Error reponse.
- */
- static const char* kErrorResponse;
-
- /**
- * @brief Name of "jsonrpc" message field.
- */
- static const char* kJsonRpc;
-
- /**
- * @brief Expected value of "jsonrpc" message field ("2.0").
- */
- static const char* kJsonRpcExpectedValue;
-
- /**
- * @brief Name of "id" message field.
- */
- static const char* kId;
-
- /**
- * @brief Name of "method" field.
- */
- static const char* kMethod;
-
- /**
- * @brief Name of "params" field.
- */
- static const char* kParams;
-
- /**
- * @brief Name of "result" field.
- */
- static const char* kResult;
-
- /**
- * @brief Name of "error" field.
- */
- static const char* kError;
-
- /**
- * @brief Name of "code" field.
- */
- static const char* kCode;
-
- /**
- * @brief Name of "data" field.
- */
- static const char* kData;
-
- /**
- * @brief Name of "message" field.
- */
- static const char* kMessage;
-
- /**
- * @brief Constructor.
- */
- FormatterJsonRpc();
-
- /**
- * @brief Copy constructor.
- *
- * @param unused Unused parameter.
- */
- FormatterJsonRpc(const FormatterJsonRpc& unused);
-
- /**
- * @brief Parse function id.
- *
- * @tparam FunctionId Type of function id enumeration.
- *
- * @param method_value JSON value with function id.
- * @param out The resulting SmartObject.
- *
- * @return An integer that is a bitwise-or of all error codes occurred
- * during the parsing of the function id. 0 if no errors occurred.
- */
- template <typename FunctionId>
- static int32_t ParseFunctionId(const Json::Value& method_value,
- NsSmartObjects::SmartObject& out);
-
- /**
- * @brief Set method.
- *
- * Try to extract function id from the message object and set the "method"
- * field of the container.
- *
- * @param params Message parameters object.
- * @param method_container Container for the "method" field.
- *
- * @return true if function id was extracted successfully and set as a
- * value of "method" field.
- */
- static bool SetMethod(const NsSmartObjects::SmartObject& params,
- Json::Value& method_container);
-
- /**
- * @brief Set id.
- *
- * Try to extract request/response id from the message object and set the
- * "id" field of the container.
- *
- * @param params Message parameters object.
- * @param id_container Container for the "id" field.
- *
- * @return true if request/response id was extracted successfully and set
- * as a value of "id" field.
- */
- static bool SetId(const NsSmartObjects::SmartObject& params,
- Json::Value& id_container);
-
- /**
- * @brief Set message
- *
- * Try to extract message from response error object and set "message" field for the container
- *
- * @param params Message parameters object.
- * @param id_container Container of the "message" field
- *
- * @return true if message string was extracted successfully and set
- * as a value of "message" field.
- */
- static bool SetMessage(const NsSmartObjects::SmartObject& params,
- Json::Value& id_container);
+class FormatterJsonRpc : public CFormatterJsonBase {
+ public:
+ /**
+ * @brief No errors occurred during the parsing of the input JSON string.
+ */
+ static const int32_t kSuccess = 0;
+
+ /**
+ * @brief Input JSON string cannot be parsed.
+ */
+ static const int32_t kParsingError = 1;
+
+ /**
+ * @brief Input JSON string has invalid format.
+ */
+ static const int32_t kInvalidFormat = 2;
+
+ /**
+ * @brief Method in input JSON string is not
+ * specified or specified incorrectly.
+ */
+ static const int32_t kMethodNotSpecified = 4;
+
+ /**
+ * @brief Method is unknown.
+ */
+ static const int32_t kUnknownMethod = 8;
+
+ /**
+ * @brief Message type is unknown.
+ */
+ static const int32_t kUnknownMessageType = 16;
+
+ /**
+ * @brief Id of request or response is invalid.
+ */
+ static const int32_t kInvalidId = 32;
+
+ /**
+ * @brief Response code is not available.
+ */
+ static const int32_t kResponseCodeNotAvailable = 64;
+
+ /**
+ * @brief Message for error response is not available.
+ */
+ static const int32_t kErrorResponseMessageNotAvailable = 128;
+
+ /**
+ * @brief Creates a JSON string from a SmartObject.
+ *
+ * @param obj Input SmartObject.
+ * @param out_str Resulting JSON string.
+ *
+ * @return true if success, false otherwise.
+ */
+ static bool ToString(const NsSmartObjects::SmartObject& obj,
+ std::string& out_str);
+
+ /**
+ * @brief Creates a SmartObject from a JSON string.
+ *
+ * @tparam FunctionId Type of function id enumeration.
+ * @tparam MessageType Type of message type enumeration.
+ *
+ * @param str input JSON string.
+ * @param out The resulting SmartObject.
+ *
+ * @return An integer that is a bitwise-or of all error codes occurred
+ * during the parsing of the input string. 0 if no errors occurred.
+ */
+ template <typename FunctionId, typename MessageType>
+ static int32_t FromString(const std::string& str,
+ NsSmartObjects::SmartObject& out);
+
+ private:
+ /**
+ * @brief Request.
+ */
+ static const char* kRequest;
+
+ /**
+ * @brief Response.
+ */
+ static const char* kResponse;
+
+ /**
+ * @brief Notification.
+ */
+ static const char* kNotification;
+
+ /**
+ * @brief Error reponse.
+ */
+ static const char* kErrorResponse;
+
+ /**
+ * @brief Name of "jsonrpc" message field.
+ */
+ static const char* kJsonRpc;
+
+ /**
+ * @brief Expected value of "jsonrpc" message field ("2.0").
+ */
+ static const char* kJsonRpcExpectedValue;
+
+ /**
+ * @brief Name of "id" message field.
+ */
+ static const char* kId;
+
+ /**
+ * @brief Name of "method" field.
+ */
+ static const char* kMethod;
+
+ /**
+ * @brief Name of "params" field.
+ */
+ static const char* kParams;
+
+ /**
+ * @brief Name of "result" field.
+ */
+ static const char* kResult;
+
+ /**
+ * @brief Name of "error" field.
+ */
+ static const char* kError;
+
+ /**
+ * @brief Name of "code" field.
+ */
+ static const char* kCode;
+
+ /**
+ * @brief Name of "data" field.
+ */
+ static const char* kData;
+
+ /**
+ * @brief Name of "message" field.
+ */
+ static const char* kMessage;
+
+ /**
+ * @brief Constructor.
+ */
+ FormatterJsonRpc();
+
+ /**
+ * @brief Copy constructor.
+ *
+ * @param unused Unused parameter.
+ */
+ FormatterJsonRpc(const FormatterJsonRpc& unused);
+
+ /**
+ * @brief Parse function id.
+ *
+ * @tparam FunctionId Type of function id enumeration.
+ *
+ * @param method_value JSON value with function id.
+ * @param out The resulting SmartObject.
+ *
+ * @return An integer that is a bitwise-or of all error codes occurred
+ * during the parsing of the function id. 0 if no errors occurred.
+ */
+ template <typename FunctionId>
+ static int32_t ParseFunctionId(const Json::Value& method_value,
+ NsSmartObjects::SmartObject& out);
+
+ /**
+ * @brief Set method.
+ *
+ * Try to extract function id from the message object and set the "method"
+ * field of the container.
+ *
+ * @param params Message parameters object.
+ * @param method_container Container for the "method" field.
+ *
+ * @return true if function id was extracted successfully and set as a
+ * value of "method" field.
+ */
+ static bool SetMethod(const NsSmartObjects::SmartObject& params,
+ Json::Value& method_container);
+
+ /**
+ * @brief Set id.
+ *
+ * Try to extract request/response id from the message object and set the
+ * "id" field of the container.
+ *
+ * @param params Message parameters object.
+ * @param id_container Container for the "id" field.
+ *
+ * @return true if request/response id was extracted successfully and set
+ * as a value of "id" field.
+ */
+ static bool SetId(const NsSmartObjects::SmartObject& params,
+ Json::Value& id_container);
+
+ /**
+ * @brief Set message
+ *
+ * Try to extract message from response error object and set "message" field
+ *for the container
+ *
+ * @param params Message parameters object.
+ * @param id_container Container of the "message" field
+ *
+ * @return true if message string was extracted successfully and set
+ * as a value of "message" field.
+ */
+ static bool SetMessage(const NsSmartObjects::SmartObject& params,
+ Json::Value& id_container);
};
template <typename FunctionId, typename MessageType>
int32_t FormatterJsonRpc::FromString(const std::string& str,
- NsSmartObjects::SmartObject& out) {
+ NsSmartObjects::SmartObject& out) {
int32_t result = kSuccess;
try {
- Json::Value root;
- Json::Reader reader;
- namespace strings = NsSmartDeviceLink::NsJSONHandler::strings;
+ Json::Value root;
+ Json::Reader reader;
+ namespace strings = NsSmartDeviceLink::NsJSONHandler::strings;
- if (false == reader.parse(str, root)) {
- result = kParsingError | kMethodNotSpecified | kUnknownMethod |
- kUnknownMessageType;
- } else {
- if (false == root.isMember(kJsonRpc)) {
- result |= kInvalidFormat;
+ if (false == reader.parse(str, root)) {
+ result = kParsingError | kMethodNotSpecified | kUnknownMethod |
+ kUnknownMessageType;
} else {
- const Json::Value& jsonRpcValue = root[kJsonRpc];
-
- if ((false == jsonRpcValue.isString()) ||
- (jsonRpcValue.asString() != kJsonRpcExpectedValue)) {
+ if (false == root.isMember(kJsonRpc)) {
result |= kInvalidFormat;
+ } else {
+ const Json::Value& jsonRpcValue = root[kJsonRpc];
+
+ if ((false == jsonRpcValue.isString()) ||
+ (jsonRpcValue.asString() != kJsonRpcExpectedValue)) {
+ result |= kInvalidFormat;
+ }
}
- }
- std::string message_type_string;
- Json::Value response_value;
- bool response_value_found = false;
- bool is_error_response = false;
+ std::string message_type_string;
+ Json::Value response_value;
+ bool response_value_found = false;
+ bool is_error_response = false;
- if (false == root.isMember(kId)) {
- message_type_string = kNotification;
+ if (false == root.isMember(kId)) {
+ message_type_string = kNotification;
- if (false == root.isMember(kMethod)) {
- result |= kMethodNotSpecified | kUnknownMethod;
- } else {
- result |= ParseFunctionId<FunctionId>(root[kMethod], out);
- }
- out[strings::S_MSG_PARAMS]
- = NsSmartObjects::SmartObject(NsSmartObjects::SmartType_Map);
- } else {
- const Json::Value& id_value = root[kId];
-
- if (true == id_value.isString()) {
- out[strings::S_PARAMS][strings::S_CORRELATION_ID] =
- id_value.asString();
- } else if (true == id_value.isInt()) {
- out[strings::S_PARAMS][strings::S_CORRELATION_ID] =
- id_value.asInt();
- } else if (true == id_value.isDouble()) {
- out[strings::S_PARAMS][strings::S_CORRELATION_ID] =
- id_value.asDouble();
- } else if (true == id_value.isNull()) {
- out[strings::S_PARAMS][strings::S_CORRELATION_ID] =
- NsSmartObjects::SmartObject(NsSmartObjects::SmartType_Null);
- } else {
- result |= kInvalidFormat | kInvalidId;
- }
-
- if (true == root.isMember(kMethod)) {
- message_type_string = kRequest;
- result |= ParseFunctionId<FunctionId>(root[kMethod], out);
- out[strings::S_MSG_PARAMS]
- = NsSmartObjects::SmartObject(NsSmartObjects::SmartType_Map);
+ if (false == root.isMember(kMethod)) {
+ result |= kMethodNotSpecified | kUnknownMethod;
+ } else {
+ result |= ParseFunctionId<FunctionId>(root[kMethod], out);
+ }
+ out[strings::S_MSG_PARAMS] =
+ NsSmartObjects::SmartObject(NsSmartObjects::SmartType_Map);
} else {
- Json::Value method_container;
- bool method_container_found = false;
-
- if (true == root.isMember(kResult)) {
- out[strings::S_MSG_PARAMS]
- = NsSmartObjects::SmartObject(NsSmartObjects::SmartType_Map);
-
- message_type_string = kResponse;
- response_value = root[kResult];
- response_value_found = true;
- method_container = root[kResult];
- method_container_found = true;
- } else if (true == root.isMember(kError)) {
- out[strings::S_MSG_PARAMS]
- = NsSmartObjects::SmartObject(NsSmartObjects::SmartType_Map);
- message_type_string = kErrorResponse;
- response_value = root[kError];
- response_value_found = true;
- is_error_response = true;
-
- if (true == response_value.isObject()) {
- if (true == response_value.isMember(kData)) {
- method_container = response_value[kData];
- method_container_found = true;
- }
- }
+ const Json::Value& id_value = root[kId];
+
+ if (true == id_value.isString()) {
+ out[strings::S_PARAMS][strings::S_CORRELATION_ID] =
+ id_value.asString();
+ } else if (true == id_value.isInt()) {
+ out[strings::S_PARAMS][strings::S_CORRELATION_ID] = id_value.asInt();
+ } else if (true == id_value.isDouble()) {
+ out[strings::S_PARAMS][strings::S_CORRELATION_ID] =
+ id_value.asDouble();
+ } else if (true == id_value.isNull()) {
+ out[strings::S_PARAMS][strings::S_CORRELATION_ID] =
+ NsSmartObjects::SmartObject(NsSmartObjects::SmartType_Null);
} else {
- result |= kUnknownMessageType;
+ result |= kInvalidFormat | kInvalidId;
}
- if (false == method_container_found) {
- result |= kMethodNotSpecified | kUnknownMethod;
- } else if (false == method_container.isObject()) {
- result |= kInvalidFormat | kMethodNotSpecified | kUnknownMethod;
+ if (true == root.isMember(kMethod)) {
+ message_type_string = kRequest;
+ result |= ParseFunctionId<FunctionId>(root[kMethod], out);
+ out[strings::S_MSG_PARAMS] =
+ NsSmartObjects::SmartObject(NsSmartObjects::SmartType_Map);
} else {
- if (false == method_container.isMember(kMethod)) {
+ Json::Value method_container;
+ bool method_container_found = false;
+
+ if (true == root.isMember(kResult)) {
+ out[strings::S_MSG_PARAMS] =
+ NsSmartObjects::SmartObject(NsSmartObjects::SmartType_Map);
+
+ message_type_string = kResponse;
+ response_value = root[kResult];
+ response_value_found = true;
+ method_container = root[kResult];
+ method_container_found = true;
+ } else if (true == root.isMember(kError)) {
+ out[strings::S_MSG_PARAMS] =
+ NsSmartObjects::SmartObject(NsSmartObjects::SmartType_Map);
+ message_type_string = kErrorResponse;
+ response_value = root[kError];
+ response_value_found = true;
+ is_error_response = true;
+
+ if (true == response_value.isObject()) {
+ if (true == response_value.isMember(kData)) {
+ method_container = response_value[kData];
+ method_container_found = true;
+ }
+ }
+ } else {
+ result |= kUnknownMessageType;
+ }
+
+ if (false == method_container_found) {
result |= kMethodNotSpecified | kUnknownMethod;
+ } else if (false == method_container.isObject()) {
+ result |= kInvalidFormat | kMethodNotSpecified | kUnknownMethod;
} else {
- result |= ParseFunctionId<FunctionId>(method_container[kMethod],
- out);
+ if (false == method_container.isMember(kMethod)) {
+ result |= kMethodNotSpecified | kUnknownMethod;
+ } else {
+ result |=
+ ParseFunctionId<FunctionId>(method_container[kMethod], out);
+ }
}
}
}
- }
- if (0 == (result & kUnknownMessageType)) {
- MessageType message_type;
+ if (0 == (result & kUnknownMessageType)) {
+ MessageType message_type;
- if (!NsSmartObjects::EnumConversionHelper<MessageType>::StringToEnum(
- message_type_string, &message_type)) {
- result |= kUnknownMessageType;
- } else {
- out[strings::S_PARAMS][strings::S_MESSAGE_TYPE] = message_type;
+ if (!NsSmartObjects::EnumConversionHelper<MessageType>::StringToEnum(
+ message_type_string, &message_type)) {
+ result |= kUnknownMessageType;
+ } else {
+ out[strings::S_PARAMS][strings::S_MESSAGE_TYPE] = message_type;
+ }
}
- }
- if (true == root.isMember(kParams)) {
- const Json::Value& params_value = root[kParams];
-
- if (false == params_value.isObject()) {
- result |= kInvalidFormat;
- } else {
- jsonValueToObj(root[kParams], out[strings::S_MSG_PARAMS]);
- }
- } else if (true == root.isMember(kResult)) {
- const Json::Value& result_value = root[kResult];
+ if (true == root.isMember(kParams)) {
+ const Json::Value& params_value = root[kParams];
- if (false == result_value.isObject()) {
- result |= kInvalidFormat;
- } else {
- jsonValueToObj(root[kResult], out[strings::S_MSG_PARAMS]);
- }
- } else if (true == is_error_response) {
- jsonValueToObj(response_value[kData], out[strings::S_PARAMS][kData]);
- }
+ if (false == params_value.isObject()) {
+ result |= kInvalidFormat;
+ } else {
+ jsonValueToObj(root[kParams], out[strings::S_MSG_PARAMS]);
+ }
+ } else if (true == root.isMember(kResult)) {
+ const Json::Value& result_value = root[kResult];
- if ((kResponse == message_type_string) ||
- (kErrorResponse == message_type_string)) {
- if (true == out.keyExists(strings::S_MSG_PARAMS)) {
- out[strings::S_MSG_PARAMS].erase(kMethod);
- out[strings::S_MSG_PARAMS].erase(kCode);
+ if (false == result_value.isObject()) {
+ result |= kInvalidFormat;
+ } else {
+ jsonValueToObj(root[kResult], out[strings::S_MSG_PARAMS]);
+ }
+ } else if (true == is_error_response) {
+ jsonValueToObj(response_value[kData], out[strings::S_PARAMS][kData]);
}
- if (false == response_value_found) {
- result |= kResponseCodeNotAvailable;
- } else {
- if (false == response_value.isObject()) {
- result |= kInvalidFormat | kResponseCodeNotAvailable;
+ if ((kResponse == message_type_string) ||
+ (kErrorResponse == message_type_string)) {
+ if (true == out.keyExists(strings::S_MSG_PARAMS)) {
+ out[strings::S_MSG_PARAMS].erase(kMethod);
+ out[strings::S_MSG_PARAMS].erase(kCode);
+ }
- if (true == is_error_response) {
- result |= kErrorResponseMessageNotAvailable;
- }
+ if (false == response_value_found) {
+ result |= kResponseCodeNotAvailable;
} else {
- if (false == response_value.isMember(kCode)) {
- result |= kResponseCodeNotAvailable;
- } else {
- const Json::Value& code_value = response_value[kCode];
-
- if (false == code_value.isInt()) {
- result |= kInvalidFormat | kResponseCodeNotAvailable;
- } else {
- out[strings::S_PARAMS][strings::kCode] = code_value.asInt();
- }
- }
+ if (false == response_value.isObject()) {
+ result |= kInvalidFormat | kResponseCodeNotAvailable;
- if (true == is_error_response) {
- if (false == response_value.isMember(kMessage)) {
+ if (true == is_error_response) {
result |= kErrorResponseMessageNotAvailable;
+ }
+ } else {
+ if (false == response_value.isMember(kCode)) {
+ result |= kResponseCodeNotAvailable;
} else {
- const Json::Value& message_value = response_value[kMessage];
+ const Json::Value& code_value = response_value[kCode];
- if (false == message_value.isString()) {
+ if (false == code_value.isInt()) {
+ result |= kInvalidFormat | kResponseCodeNotAvailable;
+ } else {
+ out[strings::S_PARAMS][strings::kCode] = code_value.asInt();
+ }
+ }
+
+ if (true == is_error_response) {
+ if (false == response_value.isMember(kMessage)) {
result |= kErrorResponseMessageNotAvailable;
} else {
- out[strings::S_PARAMS][strings::kMessage] =
- message_value.asString();
+ const Json::Value& message_value = response_value[kMessage];
+
+ if (false == message_value.isString()) {
+ result |= kErrorResponseMessageNotAvailable;
+ } else {
+ out[strings::S_PARAMS][strings::kMessage] =
+ message_value.asString();
+ }
}
}
}
}
}
}
- }
- out[strings::S_PARAMS][strings::S_PROTOCOL_TYPE] = 1;
- out[strings::S_PARAMS][strings::S_PROTOCOL_VERSION] = 2;
- } catch(...) {
+ out[strings::S_PARAMS][strings::S_PROTOCOL_TYPE] = 1;
+ out[strings::S_PARAMS][strings::S_PROTOCOL_VERSION] = 2;
+ } catch (...) {
result = kParsingError;
}
@@ -469,7 +469,7 @@ int32_t FormatterJsonRpc::FromString(const std::string& str,
template <typename FunctionId>
int32_t FormatterJsonRpc::ParseFunctionId(const Json::Value& method_value,
- NsSmartObjects::SmartObject& out) {
+ NsSmartObjects::SmartObject& out) {
int32_t result = kSuccess;
if (false == method_value.isString()) {
@@ -478,7 +478,7 @@ int32_t FormatterJsonRpc::ParseFunctionId(const Json::Value& method_value,
FunctionId function_id;
if (!NsSmartObjects::EnumConversionHelper<FunctionId>::CStringToEnum(
- method_value.asCString(), &function_id)) {
+ method_value.asCString(), &function_id)) {
result |= kUnknownMethod;
} else {
namespace strings = NsSmartDeviceLink::NsJSONHandler::strings;
@@ -494,4 +494,4 @@ int32_t FormatterJsonRpc::ParseFunctionId(const Json::Value& method_value,
} // namespace NsJSONHandler
} // namespace NsSmartDeviceLink
-#endif // SMARTDEVICELINK_COMPONENTS_JSONHANDLER_INCLUDE_FORMATTERS_FORMATTER_JSON_RPC_H_
+#endif // SMARTDEVICELINK_COMPONENTS_JSONHANDLER_INCLUDE_FORMATTERS_FORMATTER_JSON_RPC_H_
diff --git a/src/components/formatters/include/formatters/generic_json_formatter.h b/src/components/formatters/include/formatters/generic_json_formatter.h
index a4b3f3f712..580a49d73a 100644
--- a/src/components/formatters/include/formatters/generic_json_formatter.h
+++ b/src/components/formatters/include/formatters/generic_json_formatter.h
@@ -35,14 +35,14 @@
#ifndef SMARTDEVICELINK_COMPONENTS_FORMATTERS_INCLUDE_FORMATTERS_GENERIC_JSON_FORMATTER_H_
#define SMARTDEVICELINK_COMPONENTS_FORMATTERS_INCLUDE_FORMATTERS_GENERIC_JSON_FORMATTER_H_
-#include "CFormatterJsonBase.hpp"
+#include "CFormatterJsonBase.h"
namespace NsSmartDeviceLink {
namespace NsJSONHandler {
namespace Formatters {
-class GenericJsonFormatter: public CFormatterJsonBase {
-public:
+class GenericJsonFormatter : public CFormatterJsonBase {
+ public:
/**
* @brief Creates a JSON string from a SmartObject.
*
@@ -64,8 +64,8 @@ public:
NsSmartObjects::SmartObject& out);
};
-} // namespace Formatters
-} // namespace NsJSONHandler
-} // namespace NsSmartDeviceLink
+} // namespace Formatters
+} // namespace NsJSONHandler
+} // namespace NsSmartDeviceLink
-#endif // SMARTDEVICELINK_COMPONENTS_FORMATTERS_INCLUDE_FORMATTERS_GENERIC_JSON_FORMATTER_H_
+#endif // SMARTDEVICELINK_COMPONENTS_FORMATTERS_INCLUDE_FORMATTERS_GENERIC_JSON_FORMATTER_H_
diff --git a/src/components/formatters/include/formatters/meta_formatter.h b/src/components/formatters/include/formatters/meta_formatter.h
index f9fd6fad72..65b8c19863 100644
--- a/src/components/formatters/include/formatters/meta_formatter.h
+++ b/src/components/formatters/include/formatters/meta_formatter.h
@@ -44,7 +44,8 @@ namespace NsJSONHandler {
namespace Formatters {
/**
- * @brief Formats to string the smart object against given schema for given formatter
+ * @brief Formats to string the smart object against given schema for given
+ *formatter
*
* Sample usage:
* CSmartFactory factory;
@@ -54,7 +55,6 @@ namespace Formatters {
*/
class CMetaFormatter {
public:
-
/**
* @brief Creates smart object by the given schema having copied
* matched tree elements from original object.
@@ -66,13 +66,13 @@ class CMetaFormatter {
* @return true if successful, false - otherwise
*/
static bool CreateObjectByPattern(
- const NsSmartDeviceLink::NsSmartObjects::SmartObject& object,
- const NsSmartDeviceLink::NsSmartObjects::CSmartSchema& schema,
- NsSmartDeviceLink::NsSmartObjects::SmartObject& result_object);
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& object,
+ const NsSmartDeviceLink::NsSmartObjects::CSmartSchema& schema,
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& result_object);
};
-}// namespace NsSmartDeviceLink
-}// namespace NsSmartDeviceLink::NsJSONHandler
-}// namespace NsSmartDeviceLink::NsJSONHandler::Formatters
+} // namespace NsSmartDeviceLink
+} // namespace NsSmartDeviceLink::NsJSONHandler
+} // namespace NsSmartDeviceLink::NsJSONHandler::Formatters
-#endif // __SMARTDEVICELINKCORE_JSONHANDLER_FORMATTERS_METAFORMATTER_H__
+#endif // __SMARTDEVICELINKCORE_JSONHANDLER_FORMATTERS_METAFORMATTER_H__
diff --git a/src/components/formatters/src/CFormatterJsonBase.cc b/src/components/formatters/src/CFormatterJsonBase.cc
new file mode 100644
index 0000000000..0a85a93d21
--- /dev/null
+++ b/src/components/formatters/src/CFormatterJsonBase.cc
@@ -0,0 +1,123 @@
+/**
+ * @file CFormatterJsonBase.cpp
+ * @brief CFormatterJsonBase source file.
+ */
+// Copyright (c) 2013, Ford Motor Company
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// Redistributions of source code must retain the above copyright notice, this
+// list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided with the
+// distribution.
+//
+// Neither the name of the Ford Motor Company nor the names of its contributors
+// may be used to endorse or promote products derived from this software
+// without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+#include "json/json.h"
+#include "formatters/CFormatterJsonBase.h"
+#include "utils/convert_utils.h"
+
+void NsSmartDeviceLink::NsJSONHandler::Formatters::CFormatterJsonBase::
+ jsonValueToObj(const Json::Value& value,
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& obj) {
+ try {
+ if (value.type() == Json::objectValue) {
+ obj = NsSmartDeviceLink::NsSmartObjects::SmartObject(
+ NsSmartDeviceLink::NsSmartObjects::SmartType_Map);
+
+ Json::Value::Members members = value.getMemberNames();
+
+ for (uint32_t i = 0; i < members.size(); i++) {
+ jsonValueToObj(value[members[i]], obj[members[i]]);
+ }
+ } else if (value.type() == Json::arrayValue) {
+ obj = NsSmartDeviceLink::NsSmartObjects::SmartObject(
+ NsSmartDeviceLink::NsSmartObjects::SmartType_Array);
+
+ for (uint32_t i = 0; i < value.size(); i++) {
+ jsonValueToObj(value[i], obj[i]);
+ }
+ } else if (value.type() == Json::intValue) {
+ obj = utils::ConvertLongLongIntToInt64(value.asInt64());
+ } else if (value.type() == Json::uintValue) {
+ obj = utils::ConvertLongLongUIntToUInt64(value.asUInt64());
+ } else if (value.type() == Json::realValue) {
+ obj = value.asDouble();
+ } else if (value.type() == Json::booleanValue) {
+ obj = value.asBool();
+ } else if (value.type() == Json::stringValue) {
+ obj = value.asString();
+ }
+ } catch (...) {
+ }
+}
+
+// ----------------------------------------------------------------------------
+
+void NsSmartDeviceLink::NsJSONHandler::Formatters::CFormatterJsonBase::
+ objToJsonValue(const NsSmartDeviceLink::NsSmartObjects::SmartObject& obj,
+ Json::Value& item) {
+ try {
+ if (NsSmartDeviceLink::NsSmartObjects::SmartType_Array == obj.getType()) {
+ item = Json::arrayValue;
+
+ for (uint32_t i = 0; i < obj.length(); i++) {
+ Json::Value value(Json::nullValue);
+
+ objToJsonValue(obj.getElement(i), value);
+
+ item.append(value);
+ }
+ } else if (NsSmartDeviceLink::NsSmartObjects::SmartType_Map ==
+ obj.getType()) {
+ item = Json::objectValue;
+ std::set<std::string> keys = obj.enumerate();
+
+ for (std::set<std::string>::const_iterator key = keys.begin();
+ key != keys.end();
+ key++) {
+ Json::Value value(Json::nullValue);
+
+ objToJsonValue(obj.getElement(*key), value);
+
+ item[*key] = value;
+ }
+ } else if (NsSmartDeviceLink::NsSmartObjects::SmartType_Boolean ==
+ obj.getType()) {
+ item = obj.asBool();
+ } else if (NsSmartDeviceLink::NsSmartObjects::SmartType_Integer ==
+ obj.getType()) {
+ item = utils::ConvertInt64ToLongLongInt(obj.asInt());
+ } else if (NsSmartDeviceLink::NsSmartObjects::SmartType_UInteger ==
+ obj.getType()) {
+ item = utils::ConvertUInt64ToLongLongUInt(obj.asUInt());
+ } else if (NsSmartDeviceLink::NsSmartObjects::SmartType_Double ==
+ obj.getType()) {
+ item = obj.asDouble();
+ } else if (NsSmartDeviceLink::NsSmartObjects::SmartType_Null ==
+ obj.getType()) {
+ item = Json::nullValue;
+ } else {
+ item = obj.asString();
+ }
+ } catch (...) {
+ }
+}
diff --git a/src/components/formatters/src/CFormatterJsonBase.cpp b/src/components/formatters/src/CFormatterJsonBase.cpp
deleted file mode 100644
index 64a60e4f8f..0000000000
--- a/src/components/formatters/src/CFormatterJsonBase.cpp
+++ /dev/null
@@ -1,118 +0,0 @@
-/**
- * @file CFormatterJsonBase.cpp
- * @brief CFormatterJsonBase source file.
- */
-// Copyright (c) 2013, Ford Motor Company
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// Redistributions of source code must retain the above copyright notice, this
-// list of conditions and the following disclaimer.
-//
-// Redistributions in binary form must reproduce the above copyright notice,
-// this list of conditions and the following
-// disclaimer in the documentation and/or other materials provided with the
-// distribution.
-//
-// Neither the name of the Ford Motor Company nor the names of its contributors
-// may be used to endorse or promote products derived from this software
-// without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-#include "json/json.h"
-
-#include "formatters/CFormatterJsonBase.hpp"
-
-void NsSmartDeviceLink::NsJSONHandler::Formatters::CFormatterJsonBase::jsonValueToObj(
- const Json::Value& value,
- NsSmartDeviceLink::NsSmartObjects::SmartObject& obj) {
- try {
- if (value.type() == Json::objectValue) {
- obj = NsSmartDeviceLink::NsSmartObjects::SmartObject(
- NsSmartDeviceLink::NsSmartObjects::SmartType_Map);
-
- Json::Value::Members members = value.getMemberNames();
-
- for (uint32_t i = 0; i < members.size(); i++) {
- jsonValueToObj(value[members[i]], obj[members[i]]);
- }
- } else if (value.type() == Json::arrayValue) {
- obj = NsSmartDeviceLink::NsSmartObjects::SmartObject(
- NsSmartDeviceLink::NsSmartObjects::SmartType_Array);
-
- for (uint32_t i = 0; i < value.size(); i++) {
- jsonValueToObj(value[i], obj[i]);
- }
- } else if (value.type() == Json::intValue
- || value.type() == Json::uintValue) {
- obj = value.asInt();
- } else if (value.type() == Json::realValue) {
- obj = value.asDouble();
- } else if (value.type() == Json::booleanValue) {
- obj = value.asBool();
- } else if (value.type() == Json::stringValue) {
- obj = value.asString();
- }
- } catch (...) {
- }
-}
-
-// ----------------------------------------------------------------------------
-
-void NsSmartDeviceLink::NsJSONHandler::Formatters::CFormatterJsonBase::objToJsonValue(
- const NsSmartDeviceLink::NsSmartObjects::SmartObject &obj,
- Json::Value &item) {
- try {
- if (NsSmartDeviceLink::NsSmartObjects::SmartType_Array == obj.getType()) {
- item = Json::arrayValue;
-
- for (uint32_t i = 0; i < obj.length(); i++) {
- Json::Value value(Json::nullValue);
-
- objToJsonValue(obj.getElement(i), value);
-
- item.append(value);
- }
- } else if (NsSmartDeviceLink::NsSmartObjects::SmartType_Map
- == obj.getType()) {
- item = Json::objectValue;
- std::set<std::string> keys = obj.enumerate();
-
- for (std::set<std::string>::const_iterator key = keys.begin();
- key != keys.end(); key++) {
- Json::Value value(Json::nullValue);
-
- objToJsonValue(obj.getElement(*key), value);
-
- item[*key] = value;
- }
- } else if (NsSmartDeviceLink::NsSmartObjects::SmartType_Boolean
- == obj.getType()) {
- item = obj.asBool();
- } else if (NsSmartDeviceLink::NsSmartObjects::SmartType_Integer
- == obj.getType()) {
- item = obj.asInt();
- } else if (NsSmartDeviceLink::NsSmartObjects::SmartType_Double
- == obj.getType()) {
- item = obj.asDouble();
- } else if (NsSmartDeviceLink::NsSmartObjects::SmartType_Null
- == obj.getType()) {
- item = Json::nullValue;
- } else {
- item = obj.asString();
- }
- } catch (...) {
- }
-}
diff --git a/src/components/formatters/src/CFormatterJsonSDLRPCv1.cc b/src/components/formatters/src/CFormatterJsonSDLRPCv1.cc
new file mode 100644
index 0000000000..b776b9abd8
--- /dev/null
+++ b/src/components/formatters/src/CFormatterJsonSDLRPCv1.cc
@@ -0,0 +1,165 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "formatters/CFormatterJsonSDLRPCv1.h"
+#include "formatters/meta_formatter.h"
+#include "utils/convert_utils.h"
+
+namespace strings = NsSmartDeviceLink::NsJSONHandler::strings;
+namespace smart_objects_ns = NsSmartDeviceLink::NsSmartObjects;
+
+namespace NsSmartDeviceLink {
+namespace NsJSONHandler {
+namespace Formatters {
+
+// ----------------------------------------------------------------------------
+
+const std::string CFormatterJsonSDLRPCv1::S_REQUEST("request");
+const std::string CFormatterJsonSDLRPCv1::S_RESPONSE("response");
+const std::string CFormatterJsonSDLRPCv1::S_NOTIFICATION("notification");
+const std::string CFormatterJsonSDLRPCv1::S_PARAMETERS("parameters");
+const std::string CFormatterJsonSDLRPCv1::S_NAME("name");
+const std::string CFormatterJsonSDLRPCv1::S_CORRELATION_ID("correlationID");
+
+const int32_t CFormatterJsonSDLRPCv1::kSuccess = 0;
+const int32_t CFormatterJsonSDLRPCv1::kParsingError = 1 << 0;
+const int32_t CFormatterJsonSDLRPCv1::kFunctionIdNotFound = 1 << 1;
+const int32_t CFormatterJsonSDLRPCv1::kMessageTypeNotFound = 1 << 2;
+const int32_t CFormatterJsonSDLRPCv1::kCorrelationIdNotFound = 1 << 3;
+// ----------------------------------------------------------------------------
+
+const std::string CFormatterJsonSDLRPCv1::getMessageType(
+ const smart_objects_ns::SmartObject& obj) {
+ return obj.getElement(strings::S_PARAMS)
+ .getElement(strings::S_MESSAGE_TYPE)
+ .asString();
+}
+
+// ----------------------------------------------------------------------------
+
+const std::string CFormatterJsonSDLRPCv1::getMessageType(
+ const Json::Value& root) {
+ std::string type;
+
+ if (true == root.isMember(S_REQUEST)) {
+ type = S_REQUEST;
+ } else if (true == root.isMember(S_RESPONSE)) {
+ type = S_RESPONSE;
+ } else if (true == root.isMember(S_NOTIFICATION)) {
+ type = S_NOTIFICATION;
+ } else {
+ }
+
+ return type;
+}
+
+// ----------------------------------------------------------------------------
+
+bool CFormatterJsonSDLRPCv1::toString(const smart_objects_ns::SmartObject& obj,
+ std::string& outStr) {
+ bool result = false;
+ try {
+ Json::Value root(Json::objectValue);
+ Json::Value params(Json::objectValue);
+
+ smart_objects_ns::SmartObject formattedObj(obj);
+ formattedObj.getSchema().unapplySchema(
+ formattedObj); // converts enums(as int32_t) to strings
+
+ objToJsonValue(formattedObj.getElement(strings::S_MSG_PARAMS), params);
+
+ std::string type = getMessageType(formattedObj);
+ root[type] = Json::Value(Json::objectValue);
+ root[type][S_PARAMETERS] = params;
+
+ if (formattedObj[strings::S_PARAMS].keyExists(strings::S_CORRELATION_ID)) {
+ root[type][S_CORRELATION_ID] = utils::ConvertInt64ToLongLongInt(
+ formattedObj[strings::S_PARAMS][strings::S_CORRELATION_ID].asInt());
+ }
+
+ root[type][S_NAME] =
+ formattedObj[strings::S_PARAMS][strings::S_FUNCTION_ID].asString();
+
+ outStr = root.toStyledString();
+
+ result = true;
+ } catch (...) {
+ result = false;
+ }
+
+ return result;
+}
+
+// ----------------------------------------------------------------------------
+
+CFormatterJsonSDLRPCv1::tMetaFormatterErrorCode
+CFormatterJsonSDLRPCv1::MetaFormatToString(
+ const smart_objects_ns::SmartObject& object,
+ const smart_objects_ns::CSmartSchema& schema,
+ std::string& outStr) {
+ meta_formatter_error_code::tMetaFormatterErrorCode result_code =
+ meta_formatter_error_code::kErrorOk;
+
+ smart_objects_ns::SmartObject tmp_object;
+
+ if (false ==
+ CMetaFormatter::CreateObjectByPattern(object, schema, tmp_object)) {
+ result_code |= meta_formatter_error_code::kErrorFailedCreateObjectBySchema;
+ return result_code;
+ }
+
+ // determine whether smart objects are functions
+ // (in terms of SDLRPC communication)
+ bool is_root_object_created_by_schema =
+ ((tmp_object.getType() == smart_objects_ns::SmartType_Map) &&
+ tmp_object.keyExists(strings::S_PARAMS) &&
+ tmp_object.keyExists(strings::S_MSG_PARAMS));
+
+ bool is_root_object =
+ ((object.getType() == smart_objects_ns::SmartType_Map) &&
+ object.keyExists(strings::S_PARAMS) &&
+ object.keyExists(strings::S_MSG_PARAMS));
+
+ if (false == is_root_object) {
+ result_code |= meta_formatter_error_code::kErrorObjectIsNotFunction;
+ }
+ if (false == is_root_object_created_by_schema) {
+ result_code |= meta_formatter_error_code::kErrorSchemaIsNotFunction;
+ }
+
+ CFormatterJsonSDLRPCv1::toString(tmp_object, outStr);
+
+ return result_code;
+}
+}
+}
+}
diff --git a/src/components/formatters/src/CFormatterJsonSDLRPCv1.cpp b/src/components/formatters/src/CFormatterJsonSDLRPCv1.cpp
deleted file mode 100644
index 407a001883..0000000000
--- a/src/components/formatters/src/CFormatterJsonSDLRPCv1.cpp
+++ /dev/null
@@ -1,157 +0,0 @@
-// Copyright (c) 2013, Ford Motor Company
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// Redistributions of source code must retain the above copyright notice, this
-// list of conditions and the following disclaimer.
-//
-// Redistributions in binary form must reproduce the above copyright notice,
-// this list of conditions and the following
-// disclaimer in the documentation and/or other materials provided with the
-// distribution.
-//
-// Neither the name of the Ford Motor Company nor the names of its contributors
-// may be used to endorse or promote products derived from this software
-// without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-#include "formatters/CFormatterJsonSDLRPCv1.hpp"
-#include "formatters/meta_formatter.h"
-
-namespace strings = NsSmartDeviceLink::NsJSONHandler::strings;
-namespace smart_objects_ns = NsSmartDeviceLink::NsSmartObjects;
-
-namespace NsSmartDeviceLink {
-namespace NsJSONHandler {
-namespace Formatters {
-
-// ----------------------------------------------------------------------------
-
-const std::string CFormatterJsonSDLRPCv1::S_REQUEST("request");
-const std::string CFormatterJsonSDLRPCv1::S_RESPONSE("response");
-const std::string CFormatterJsonSDLRPCv1::S_NOTIFICATION("notification");
-const std::string CFormatterJsonSDLRPCv1::S_PARAMETERS("parameters");
-const std::string CFormatterJsonSDLRPCv1::S_NAME("name");
-const std::string CFormatterJsonSDLRPCv1::S_CORRELATION_ID("correlationID");
-
-const int32_t CFormatterJsonSDLRPCv1::kSuccess = 0;
-const int32_t CFormatterJsonSDLRPCv1::kParsingError = 1 << 0;
-const int32_t CFormatterJsonSDLRPCv1::kFunctionIdNotFound = 1 << 1;
-const int32_t CFormatterJsonSDLRPCv1::kMessageTypeNotFound = 1 << 2;
-const int32_t CFormatterJsonSDLRPCv1::kCorrelationIdNotFound = 1 << 3;
-// ----------------------------------------------------------------------------
-
-const std::string CFormatterJsonSDLRPCv1::getMessageType(
- const smart_objects_ns::SmartObject& obj) {
- return obj.getElement(strings::S_PARAMS).getElement(strings::S_MESSAGE_TYPE)
- .asString();
-}
-
-// ----------------------------------------------------------------------------
-
-const std::string CFormatterJsonSDLRPCv1::getMessageType(
- const Json::Value& root) {
- std::string type;
-
- if (true == root.isMember(S_REQUEST)) {
- type = S_REQUEST;
- } else if (true == root.isMember(S_RESPONSE)) {
- type = S_RESPONSE;
- } else if (true == root.isMember(S_NOTIFICATION)) {
- type = S_NOTIFICATION;
- } else {
- }
-
- return type;
-}
-
-// ----------------------------------------------------------------------------
-
-bool CFormatterJsonSDLRPCv1::toString(const smart_objects_ns::SmartObject& obj,
- std::string& outStr) {
- bool result = false;
- try {
- Json::Value root(Json::objectValue);
- Json::Value params(Json::objectValue);
-
- smart_objects_ns::SmartObject formattedObj(obj);
- formattedObj.getSchema().unapplySchema(formattedObj); // converts enums(as int32_t) to strings
-
- objToJsonValue(formattedObj.getElement(strings::S_MSG_PARAMS), params);
-
- std::string type = getMessageType(formattedObj);
- root[type] = Json::Value(Json::objectValue);
- root[type][S_PARAMETERS] = params;
-
- if (formattedObj[strings::S_PARAMS].keyExists(strings::S_CORRELATION_ID)) {
- root[type][S_CORRELATION_ID] =
- formattedObj[strings::S_PARAMS][strings::S_CORRELATION_ID].asInt();
- }
-
- root[type][S_NAME] = formattedObj[strings::S_PARAMS][strings::S_FUNCTION_ID]
- .asString();
-
- outStr = root.toStyledString();
-
- result = true;
- } catch (...) {
- result = false;
- }
-
- return result;
-}
-
-// ----------------------------------------------------------------------------
-
-CFormatterJsonSDLRPCv1::tMetaFormatterErrorCode CFormatterJsonSDLRPCv1::MetaFormatToString(
- const smart_objects_ns::SmartObject& object,
- const smart_objects_ns::CSmartSchema& schema, std::string& outStr) {
- meta_formatter_error_code::tMetaFormatterErrorCode result_code =
- meta_formatter_error_code::kErrorOk;
-
- smart_objects_ns::SmartObject tmp_object;
-
- if (false
- == CMetaFormatter::CreateObjectByPattern(object, schema, tmp_object)) {
- result_code |= meta_formatter_error_code::kErrorFailedCreateObjectBySchema;
- return result_code;
- }
-
- // determine whether smart objects are functions
- // (in terms of SDLRPC communication)
- bool is_root_object_created_by_schema = ((tmp_object.getType()
- == smart_objects_ns::SmartType_Map)
- && tmp_object.keyExists(strings::S_PARAMS)
- && tmp_object.keyExists(strings::S_MSG_PARAMS));
-
- bool is_root_object = ((object.getType() == smart_objects_ns::SmartType_Map)
- && object.keyExists(strings::S_PARAMS)
- && object.keyExists(strings::S_MSG_PARAMS));
-
- if (false == is_root_object) {
- result_code |= meta_formatter_error_code::kErrorObjectIsNotFunction;
- }
- if (false == is_root_object_created_by_schema) {
- result_code |= meta_formatter_error_code::kErrorSchemaIsNotFunction;
- }
-
- CFormatterJsonSDLRPCv1::toString(tmp_object, outStr);
-
- return result_code;
-}
-
-}
-}
-}
diff --git a/src/components/formatters/src/CFormatterJsonSDLRPCv2.cc b/src/components/formatters/src/CFormatterJsonSDLRPCv2.cc
new file mode 100644
index 0000000000..9e177ea4a8
--- /dev/null
+++ b/src/components/formatters/src/CFormatterJsonSDLRPCv2.cc
@@ -0,0 +1,108 @@
+// Copyright (c) 2013, Ford Motor Company
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// Redistributions of source code must retain the above copyright notice, this
+// list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided with the
+// distribution.
+//
+// Neither the name of the Ford Motor Company nor the names of its contributors
+// may be used to endorse or promote products derived from this software
+// without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#include "formatters/CFormatterJsonSDLRPCv2.h"
+#include "formatters/meta_formatter.h"
+
+namespace smart_objects_ns = NsSmartDeviceLink::NsSmartObjects;
+namespace strings = NsSmartDeviceLink::NsJSONHandler::strings;
+
+namespace NsSmartDeviceLink {
+namespace NsJSONHandler {
+namespace Formatters {
+
+// ----------------------------------------------------------------------------
+
+bool CFormatterJsonSDLRPCv2::toString(const smart_objects_ns::SmartObject& obj,
+ std::string& outStr) {
+ bool result = true;
+ try {
+ Json::Value root(Json::objectValue);
+
+ smart_objects_ns::SmartObject formattedObj(obj);
+ formattedObj.getSchema().unapplySchema(
+ formattedObj); // converts enums(as int32_t) to strings
+
+ objToJsonValue(formattedObj.getElement(strings::S_MSG_PARAMS), root);
+
+ outStr = root.toStyledString();
+
+ result = true;
+ } catch (...) {
+ result = false;
+ }
+
+ return result;
+}
+
+// ----------------------------------------------------------------------------
+
+CFormatterJsonSDLRPCv2::tMetaFormatterErrorCode
+CFormatterJsonSDLRPCv2::MetaFormatToString(
+ const smart_objects_ns::SmartObject& object,
+ const smart_objects_ns::CSmartSchema& schema,
+ std::string& outStr) {
+ meta_formatter_error_code::tMetaFormatterErrorCode result_code =
+ meta_formatter_error_code::kErrorOk;
+
+ smart_objects_ns::SmartObject tmp_object;
+
+ if (false ==
+ CMetaFormatter::CreateObjectByPattern(object, schema, tmp_object)) {
+ result_code |= meta_formatter_error_code::kErrorFailedCreateObjectBySchema;
+ return result_code;
+ }
+
+ // determine whether smart objects are functions
+ // (in terms of SDLRPC communication)
+ bool is_root_object_created_by_schema =
+ ((tmp_object.getType() == smart_objects_ns::SmartType_Map) &&
+ tmp_object.keyExists(strings::S_PARAMS) &&
+ tmp_object.keyExists(strings::S_MSG_PARAMS));
+
+ bool is_root_object =
+ ((object.getType() == smart_objects_ns::SmartType_Map) &&
+ object.keyExists(strings::S_PARAMS) &&
+ object.keyExists(strings::S_MSG_PARAMS));
+
+ if (false == is_root_object) {
+ result_code |= meta_formatter_error_code::kErrorObjectIsNotFunction;
+ }
+ if (false == is_root_object_created_by_schema) {
+ result_code |= meta_formatter_error_code::kErrorSchemaIsNotFunction;
+ }
+
+ CFormatterJsonSDLRPCv2::toString(tmp_object, outStr);
+
+ return result_code;
+}
+}
+}
+}
diff --git a/src/components/formatters/src/CFormatterJsonSDLRPCv2.cpp b/src/components/formatters/src/CFormatterJsonSDLRPCv2.cpp
deleted file mode 100644
index d76e28911c..0000000000
--- a/src/components/formatters/src/CFormatterJsonSDLRPCv2.cpp
+++ /dev/null
@@ -1,106 +0,0 @@
-// Copyright (c) 2013, Ford Motor Company
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// Redistributions of source code must retain the above copyright notice, this
-// list of conditions and the following disclaimer.
-//
-// Redistributions in binary form must reproduce the above copyright notice,
-// this list of conditions and the following
-// disclaimer in the documentation and/or other materials provided with the
-// distribution.
-//
-// Neither the name of the Ford Motor Company nor the names of its contributors
-// may be used to endorse or promote products derived from this software
-// without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-#include "formatters/CFormatterJsonSDLRPCv2.hpp"
-#include "formatters/meta_formatter.h"
-
-namespace smart_objects_ns = NsSmartDeviceLink::NsSmartObjects;
-namespace strings = NsSmartDeviceLink::NsJSONHandler::strings;
-
-namespace NsSmartDeviceLink {
-namespace NsJSONHandler {
-namespace Formatters {
-
-// ----------------------------------------------------------------------------
-
-bool CFormatterJsonSDLRPCv2::toString(const smart_objects_ns::SmartObject& obj,
- std::string& outStr) {
- bool result = true;
- try {
- Json::Value root(Json::objectValue);
-
- smart_objects_ns::SmartObject formattedObj(obj);
- formattedObj.getSchema().unapplySchema(formattedObj); // converts enums(as int32_t) to strings
-
- objToJsonValue(formattedObj.getElement(strings::S_MSG_PARAMS), root);
-
- outStr = root.toStyledString();
-
- result = true;
- } catch (...) {
- result = false;
- }
-
- return result;
-}
-
-// ----------------------------------------------------------------------------
-
-CFormatterJsonSDLRPCv2::tMetaFormatterErrorCode CFormatterJsonSDLRPCv2::MetaFormatToString(
- const smart_objects_ns::SmartObject& object,
- const smart_objects_ns::CSmartSchema& schema, std::string& outStr) {
-
- meta_formatter_error_code::tMetaFormatterErrorCode result_code =
- meta_formatter_error_code::kErrorOk;
-
- smart_objects_ns::SmartObject tmp_object;
-
- if (false
- == CMetaFormatter::CreateObjectByPattern(object, schema, tmp_object)) {
- result_code |= meta_formatter_error_code::kErrorFailedCreateObjectBySchema;
- return result_code;
- }
-
- // determine whether smart objects are functions
- // (in terms of SDLRPC communication)
- bool is_root_object_created_by_schema = ((tmp_object.getType()
- == smart_objects_ns::SmartType_Map)
- && tmp_object.keyExists(strings::S_PARAMS)
- && tmp_object.keyExists(strings::S_MSG_PARAMS));
-
- bool is_root_object = ((object.getType() == smart_objects_ns::SmartType_Map)
- && object.keyExists(strings::S_PARAMS)
- && object.keyExists(strings::S_MSG_PARAMS));
-
- if (false == is_root_object) {
- result_code |= meta_formatter_error_code::kErrorObjectIsNotFunction;
- }
- if (false == is_root_object_created_by_schema) {
- result_code |= meta_formatter_error_code::kErrorSchemaIsNotFunction;
- }
-
- CFormatterJsonSDLRPCv2::toString(tmp_object, outStr);
-
- return result_code;
-}
-
-}
-}
-}
diff --git a/src/components/formatters/src/CSmartFactory.cc b/src/components/formatters/src/CSmartFactory.cc
new file mode 100644
index 0000000000..6b0808fbfa
--- /dev/null
+++ b/src/components/formatters/src/CSmartFactory.cc
@@ -0,0 +1,52 @@
+/**
+ * @file CSmartFactory.cpp
+ * @brief CSmartFactory source file.
+ */
+// Copyright (c) 2013, Ford Motor Company
+// All rights reserved.
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// Redistributions of source code must retain the above copyright notice, this
+// list of conditions and the following disclaimer.
+//
+// Redistributions in binary form must reproduce the above copyright notice,
+// this list of conditions and the following
+// disclaimer in the documentation and/or other materials provided with the
+// distribution.
+//
+// Neither the name of the Ford Motor Company nor the names of its contributors
+// may be used to endorse or promote products derived from this software
+// without specific prior written permission.
+//
+// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
+// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+// POSSIBILITY OF SUCH DAMAGE.
+
+#include "formatters/CSmartFactory.h"
+
+const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_MSG_PARAMS(
+ "msg_params");
+const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_PARAMS("params");
+const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_FUNCTION_ID(
+ "function_id");
+const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_MESSAGE_TYPE(
+ "message_type");
+const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_PROTOCOL_VERSION(
+ "protocol_version");
+const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_PROTOCOL_TYPE(
+ "protocol_type");
+const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_CORRELATION_ID(
+ "correlation_id");
+const std::string NsSmartDeviceLink::NsJSONHandler::strings::kCode("code");
+const std::string NsSmartDeviceLink::NsJSONHandler::strings::kMessage(
+ "message");
diff --git a/src/components/formatters/src/CSmartFactory.cpp b/src/components/formatters/src/CSmartFactory.cpp
deleted file mode 100644
index 363db7696e..0000000000
--- a/src/components/formatters/src/CSmartFactory.cpp
+++ /dev/null
@@ -1,46 +0,0 @@
-/**
- * @file CSmartFactory.cpp
- * @brief CSmartFactory source file.
- */
-// Copyright (c) 2013, Ford Motor Company
-// All rights reserved.
-//
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are met:
-//
-// Redistributions of source code must retain the above copyright notice, this
-// list of conditions and the following disclaimer.
-//
-// Redistributions in binary form must reproduce the above copyright notice,
-// this list of conditions and the following
-// disclaimer in the documentation and/or other materials provided with the
-// distribution.
-//
-// Neither the name of the Ford Motor Company nor the names of its contributors
-// may be used to endorse or promote products derived from this software
-// without specific prior written permission.
-//
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 'A PARTICULAR PURPOSE
-// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-// POSSIBILITY OF SUCH DAMAGE.
-
-#include "formatters/CSmartFactory.hpp"
-
-const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_MSG_PARAMS("msg_params");
-const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_PARAMS("params");
-const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_FUNCTION_ID("function_id");
-const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_MESSAGE_TYPE("message_type");
-const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_PROTOCOL_VERSION("protocol_version");
-const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_PROTOCOL_TYPE("protocol_type");
-const std::string NsSmartDeviceLink::NsJSONHandler::strings::S_CORRELATION_ID("correlation_id");
-const std::string NsSmartDeviceLink::NsJSONHandler::strings::kCode("code");
-const std::string NsSmartDeviceLink::NsJSONHandler::strings::kMessage(
- "message");
diff --git a/src/components/formatters/src/formatter_json_rpc.cc b/src/components/formatters/src/formatter_json_rpc.cc
index 012962bbb2..e349ced4d6 100644
--- a/src/components/formatters/src/formatter_json_rpc.cc
+++ b/src/components/formatters/src/formatter_json_rpc.cc
@@ -33,6 +33,7 @@
// POSSIBILITY OF SUCH DAMAGE.
#include "formatters/formatter_json_rpc.h"
+#include "utils/convert_utils.h"
namespace NsSmartDeviceLink {
namespace NsJSONHandler {
@@ -40,23 +41,23 @@ namespace Formatters {
namespace strings = NsJSONHandler::strings;
-const char *FormatterJsonRpc::kRequest = "request";
-const char *FormatterJsonRpc::kResponse = "response";
-const char *FormatterJsonRpc::kNotification = "notification";
-const char *FormatterJsonRpc::kErrorResponse = "error_response";
-const char *FormatterJsonRpc::kJsonRpc = "jsonrpc";
-const char *FormatterJsonRpc::kJsonRpcExpectedValue = "2.0";
-const char *FormatterJsonRpc::kId = "id";
-const char *FormatterJsonRpc::kMethod = "method";
-const char *FormatterJsonRpc::kParams = "params";
-const char *FormatterJsonRpc::kResult = "result";
-const char *FormatterJsonRpc::kError = "error";
-const char *FormatterJsonRpc::kCode = "code";
-const char *FormatterJsonRpc::kData = "data";
-const char *FormatterJsonRpc::kMessage = "message";
-
-bool FormatterJsonRpc::ToString(const NsSmartObjects::SmartObject &obj,
- std::string &out_str) {
+const char* FormatterJsonRpc::kRequest = "request";
+const char* FormatterJsonRpc::kResponse = "response";
+const char* FormatterJsonRpc::kNotification = "notification";
+const char* FormatterJsonRpc::kErrorResponse = "error_response";
+const char* FormatterJsonRpc::kJsonRpc = "jsonrpc";
+const char* FormatterJsonRpc::kJsonRpcExpectedValue = "2.0";
+const char* FormatterJsonRpc::kId = "id";
+const char* FormatterJsonRpc::kMethod = "method";
+const char* FormatterJsonRpc::kParams = "params";
+const char* FormatterJsonRpc::kResult = "result";
+const char* FormatterJsonRpc::kError = "error";
+const char* FormatterJsonRpc::kCode = "code";
+const char* FormatterJsonRpc::kData = "data";
+const char* FormatterJsonRpc::kMessage = "message";
+
+bool FormatterJsonRpc::ToString(const NsSmartObjects::SmartObject& obj,
+ std::string& out_str) {
bool result = true;
try {
Json::Value root(Json::objectValue);
@@ -70,8 +71,8 @@ bool FormatterJsonRpc::ToString(const NsSmartObjects::SmartObject &obj,
bool is_message_params = formatted_object.keyExists(strings::S_MSG_PARAMS);
bool empty_message_params = true;
if (true == is_message_params) {
- const NsSmartObjects::SmartObject &msg_params = formatted_object
- .getElement(strings::S_MSG_PARAMS);
+ const NsSmartObjects::SmartObject& msg_params =
+ formatted_object.getElement(strings::S_MSG_PARAMS);
result = (NsSmartObjects::SmartType_Map == msg_params.getType());
if (true == result) {
@@ -85,13 +86,13 @@ bool FormatterJsonRpc::ToString(const NsSmartObjects::SmartObject &obj,
if (false == formatted_object.keyExists(strings::S_PARAMS)) {
result = false;
} else {
- const NsSmartObjects::SmartObject &params = formatted_object.getElement(
- strings::S_PARAMS);
+ const NsSmartObjects::SmartObject& params =
+ formatted_object.getElement(strings::S_PARAMS);
if (NsSmartObjects::SmartType_Map != params.getType()) {
result = false;
} else {
- const NsSmartObjects::SmartObject &message_type_object = params
- .getElement(strings::S_MESSAGE_TYPE);
+ const NsSmartObjects::SmartObject& message_type_object =
+ params.getElement(strings::S_MESSAGE_TYPE);
if (NsSmartObjects::SmartType_String != message_type_object.getType()) {
result = false;
@@ -112,13 +113,14 @@ bool FormatterJsonRpc::ToString(const NsSmartObjects::SmartObject &obj,
if (false == params.keyExists(strings::kCode)) {
result = false;
} else {
- const NsSmartObjects::SmartObject &code = params.getElement(
- strings::kCode);
+ const NsSmartObjects::SmartObject& code =
+ params.getElement(strings::kCode);
if (NsSmartObjects::SmartType_Integer != code.getType()) {
result = false;
} else {
- root[kResult][kCode] = code.asInt();
+ root[kResult][kCode] =
+ utils::ConvertInt64ToLongLongInt(code.asInt());
}
}
} else if (kNotification == message_type) {
@@ -129,12 +131,13 @@ bool FormatterJsonRpc::ToString(const NsSmartObjects::SmartObject &obj,
result = result && SetMethod(params, root[kError][kData]);
result = result && SetMessage(params, root[kError]);
- const NsSmartObjects::SmartObject &code = params.getElement(
- strings::kCode);
+ const NsSmartObjects::SmartObject& code =
+ params.getElement(strings::kCode);
if (NsSmartObjects::SmartType_Integer != code.getType()) {
result = false;
} else {
- root[kError][kCode] = code.asInt();
+ root[kError][kCode] =
+ utils::ConvertInt64ToLongLongInt(code.asInt());
}
}
}
@@ -148,12 +151,12 @@ bool FormatterJsonRpc::ToString(const NsSmartObjects::SmartObject &obj,
return result;
}
-bool FormatterJsonRpc::SetMethod(const NsSmartObjects::SmartObject &params,
- Json::Value &method_container) {
+bool FormatterJsonRpc::SetMethod(const NsSmartObjects::SmartObject& params,
+ Json::Value& method_container) {
bool result = false;
if (true == params.keyExists(strings::S_FUNCTION_ID)) {
- const NsSmartObjects::SmartObject &function_id =
+ const NsSmartObjects::SmartObject& function_id =
params.getElement(strings::S_FUNCTION_ID);
if (NsSmartObjects::SmartType_String == function_id.getType()) {
@@ -165,16 +168,16 @@ bool FormatterJsonRpc::SetMethod(const NsSmartObjects::SmartObject &params,
return result;
}
-bool FormatterJsonRpc::SetId(const NsSmartObjects::SmartObject &params,
- Json::Value &id_container) {
+bool FormatterJsonRpc::SetId(const NsSmartObjects::SmartObject& params,
+ Json::Value& id_container) {
bool result = false;
if (true == params.keyExists(strings::S_CORRELATION_ID)) {
- const NsSmartObjects::SmartObject &id = params.getElement(
- strings::S_CORRELATION_ID);
+ const NsSmartObjects::SmartObject& id =
+ params.getElement(strings::S_CORRELATION_ID);
if (NsSmartObjects::SmartType_Integer == id.getType()) {
- id_container[kId] = id.asUInt();
+ id_container[kId] = utils::ConvertUInt64ToLongLongUInt(id.asUInt());
result = true;
}
}
@@ -182,16 +185,16 @@ bool FormatterJsonRpc::SetId(const NsSmartObjects::SmartObject &params,
return result;
}
-bool FormatterJsonRpc::SetMessage(const NsSmartObjects::SmartObject &params,
- Json::Value &message_container) {
+bool FormatterJsonRpc::SetMessage(const NsSmartObjects::SmartObject& params,
+ Json::Value& message_container) {
bool result = false;
if (true == params.keyExists(strings::kMessage)) {
- const NsSmartObjects::SmartObject &message = params.getElement(
- strings::kMessage);
+ const NsSmartObjects::SmartObject& message =
+ params.getElement(strings::kMessage);
if (NsSmartObjects::SmartType_String == message.getType()) {
- message_container[kMessage] = message.asString();
+ message_container[kMessage] = message.asString();
result = true;
}
}
diff --git a/src/components/formatters/src/generic_json_formatter.cc b/src/components/formatters/src/generic_json_formatter.cc
index 6cc2266193..7789a915c2 100644
--- a/src/components/formatters/src/generic_json_formatter.cc
+++ b/src/components/formatters/src/generic_json_formatter.cc
@@ -58,6 +58,6 @@ bool GenericJsonFormatter::FromString(const std::string& str,
return result;
}
-} // namespace Formatters
-} // namespace NsJSONHandler
-} // namespace NsSmartDeviceLink
+} // namespace Formatters
+} // namespace NsJSONHandler
+} // namespace NsSmartDeviceLink
diff --git a/src/components/formatters/src/meta_formatter.cc b/src/components/formatters/src/meta_formatter.cc
index 8b24fd4b0e..fafb84e938 100644
--- a/src/components/formatters/src/meta_formatter.cc
+++ b/src/components/formatters/src/meta_formatter.cc
@@ -47,14 +47,13 @@ bool formatter_ns::CMetaFormatter::CreateObjectByPattern(
const NsSmartDeviceLink::NsSmartObjects::SmartObject& object,
const NsSmartDeviceLink::NsSmartObjects::CSmartSchema& schema,
NsSmartDeviceLink::NsSmartObjects::SmartObject& result_object) {
-
if (smart_objects_ns::SmartType_Invalid == result_object.getType()) {
return false;
}
-
+
schema.BuildObjectBySchema(object, result_object);
result_object.setSchema(schema);
return true;
-}
+}
diff --git a/src/components/formatters/test/CFormatterJsonBase_test.cc b/src/components/formatters/test/CFormatterJsonBase_test.cc
index 9efbfdcf77..ff1f60b8df 100644
--- a/src/components/formatters/test/CFormatterJsonBase_test.cc
+++ b/src/components/formatters/test/CFormatterJsonBase_test.cc
@@ -35,7 +35,7 @@
#include "json/value.h"
#include "gtest/gtest.h"
#include "json/reader.h"
-#include "formatters/CFormatterJsonBase.hpp"
+#include "formatters/CFormatterJsonBase.h"
#include "formatters/generic_json_formatter.h"
namespace test {
@@ -100,10 +100,12 @@ TEST(CFormatterJsonBaseTest, JSonSignedMaxIntValueToSmartObj_ExpectSuccessful) {
EXPECT_EQ(ival, object.asInt());
}
-TEST(CFormatterJsonBaseTest, DISABLED_JSonUnsignedMaxIntValueToSmartObj_ExpectSuccessful) {
+TEST(CFormatterJsonBaseTest,
+ JSonUnsignedMaxIntValueToSmartObj_ExpectSuccessful) {
// Arrange value
Json::UInt ui_val = Json::Value::maxUInt;
- Json::Value json_value(ui_val); // Json value from maximum possible unsigned int
+ Json::Value json_value(
+ ui_val); // Json value from maximum possible unsigned int
SmartObject object;
// Convert json to smart object
CFormatterJsonBase::jsonValueToObj(json_value, object);
@@ -111,15 +113,26 @@ TEST(CFormatterJsonBaseTest, DISABLED_JSonUnsignedMaxIntValueToSmartObj_ExpectSu
EXPECT_EQ(ui_val, object.asUInt());
}
-TEST(CFormatterJsonBaseTest, JSonSignedMaxInt64ValueToSmartObj_ExpectFailed) {
+TEST(CFormatterJsonBaseTest, JSonSignedMaxInt64ValueToSmartObj_ExpectSuccess) {
// Arrange value
Json::Int64 ival = Json::Value::maxInt64;
Json::Value json_value(ival); // Json value from maximum possible signed int
SmartObject object;
// Convert json to smart object
CFormatterJsonBase::jsonValueToObj(json_value, object);
+ // Check conversion was successful
+ EXPECT_EQ(ival, object.asInt());
+}
+
+TEST(CFormatterJsonBaseTest, JSonUnsignedMaxInt64ValueToSmartObj_ExpectFailed) {
+ // Arrange value
+ Json::UInt64 ival = Json::Value::maxUInt64;
+ Json::Value json_value(ival); // Json value from max possible unsigned int
+ SmartObject object;
+ // Convert json to smart object
+ CFormatterJsonBase::jsonValueToObj(json_value, object);
// Check conversion was not successful as there is no such conversion
- EXPECT_EQ(invalid_int64_value, object.asInt64());
+ EXPECT_EQ(invalid_int64_value, object.asInt());
}
TEST(CFormatterJsonBaseTest, JSonBoolValueToSmartObj_ExpectSuccessful) {
@@ -151,7 +164,8 @@ TEST(CFormatterJsonBaseTest, JSonCStringValueToSmartObj_ExpectSuccessful) {
TEST(CFormatterJsonBaseTest, JSonArrayValueToSmartObj_ExpectSuccessful) {
// Arrange value
- const char* json_array = "[\"test1\", \"test2\", \"test3\"]"; // Array in json format
+ const char* json_array =
+ "[\"test1\", \"test2\", \"test3\"]"; // Array in json format
Json::Value json_value; // Json value from array. Will be initialized later
SmartObject object;
Json::Reader reader; // Json reader - Needed for correct parsing
@@ -162,18 +176,21 @@ TEST(CFormatterJsonBaseTest, JSonArrayValueToSmartObj_ExpectSuccessful) {
// Check conversion was successful
EXPECT_TRUE(json_value.isArray());
EXPECT_EQ(3u, object.asArray()->size());
- SmartArray *ptr = NULL; // Smart Array pointer;
+ SmartArray* ptr = NULL; // Smart Array pointer;
EXPECT_NE(ptr, object.asArray());
}
TEST(CFormatterJsonBaseTest, JSonObjectValueToSmartObj_ExpectSuccessful) {
// Arrange value
const char* json_object =
- "{ \"json_test_object\": [\"test1\", \"test2\", \"test3\"], \"json_test_object2\": [\"test11\", \"test12\", \"test13\" ]}"; // Json object
+ "{ \"json_test_object\": [\"test1\", \"test2\", \"test3\"], "
+ "\"json_test_object2\": [\"test11\", \"test12\", \"test13\" ]}";
Json::Value json_value; // Json value from object. Will be initialized later
SmartObject object;
Json::Reader reader; // Json reader - Needed for correct parsing
- ASSERT_TRUE(reader.parse(json_object, json_value)); // If parsing not successful - no sense to continue
+ ASSERT_TRUE(reader.parse(
+ json_object,
+ json_value)); // If parsing not successful - no sense to continue
CFormatterJsonBase::jsonValueToObj(json_value, object);
// Check conversion was successful
EXPECT_TRUE(json_value.isObject());
@@ -193,7 +210,7 @@ TEST(CFormatterJsonBaseTest, JSonObjectValueToSmartObj_ExpectSuccessful) {
EXPECT_EQ(*it, *it1);
++it1;
}
- ASSERT(it == mems.end() && it1 == keys.end());
+ EXPECT_TRUE(it == mems.end() && it1 == keys.end());
}
TEST(CFormatterJsonBaseTest, StringSmartObjectToJSon_ExpectSuccessful) {
@@ -240,7 +257,7 @@ TEST(CFormatterJsonBaseTest, MinIntSmartObjectToJSon_ExpectSuccessful) {
EXPECT_EQ(ival, json_value.asInt());
}
-TEST(CFormatterJsonBaseTest, DISABLED_UnsignedMaxIntSmartObjectToJSon_ExpectSuccessful) {
+TEST(CFormatterJsonBaseTest, UnsignedMaxIntSmartObjectToJSon_ExpectSuccessful) {
// Arrange value
Json::UInt ui_val = Json::Value::maxUInt;
Json::Value json_value; // Json value from maximum unsigned int
@@ -280,13 +297,15 @@ TEST(CFormatterJsonBaseTest, CStringSmartObjectToJSon_ExpectSuccessful) {
TEST(CFormatterJsonBaseTest, ArraySmartObjectToJSon_ExpectSuccessful) {
// Arrange value
- const char* json_array = "[\"test1\", \"test2\", \"test3\"]"; // Array in json format
+ const char* json_array =
+ "[\"test1\", \"test2\", \"test3\"]"; // Array in json format
Json::Value json_value; // Json value from array. Will be initialized later
- Json::Value result; // Json value from array. Will be initialized later
+ Json::Value result; // Json value from array. Will be initialized later
SmartObject object;
Json::Reader reader; // Json reader - Needed for correct parsing
// Parse array to json value
- ASSERT_TRUE(reader.parse(json_array, json_value)); // Convert json array to SmartObject
+ ASSERT_TRUE(reader.parse(json_array,
+ json_value)); // Convert json array to SmartObject
// Convert json array to SmartObject
CFormatterJsonBase::jsonValueToObj(json_value, object);
// Convert SmartObject to JSon
@@ -299,13 +318,18 @@ TEST(CFormatterJsonBaseTest, ArraySmartObjectToJSon_ExpectSuccessful) {
TEST(CFormatterJsonBaseTest, JSonObjectValueToObj_ExpectSuccessful) {
// Arrange value
const char* json_object =
- "{ \"json_test_object\": [\"test1\", \"test2\", \"test3\"], \"json_test_object2\": [\"test11\", \"test12\", \"test13\" ]}"; // Json object
- Json::Value json_value; // Json value from json object. Will be initialized later
- Json::Value result; // Json value from Smart object. Will keep conversion result
+ "{ \"json_test_object\": [\"test1\", \"test2\", \"test3\"], "
+ "\"json_test_object2\": [\"test11\", \"test12\", \"test13\" ]}";
+ Json::Value
+ json_value; // Json value from json object. Will be initialized later
+ Json::Value
+ result; // Json value from Smart object. Will keep conversion result
SmartObject object;
Json::Reader reader; // Json reader - Needed for correct parsing
// Parse json object to correct json value
- ASSERT_TRUE(reader.parse(json_object, json_value)); // If parsing not successful - no sense to continue
+ ASSERT_TRUE(reader.parse(
+ json_object,
+ json_value)); // If parsing not successful - no sense to continue
// Convert json array to SmartObject
CFormatterJsonBase::jsonValueToObj(json_value, object);
// Convert SmartObject to JSon
@@ -329,7 +353,7 @@ TEST(CFormatterJsonBaseTest, JSonObjectValueToObj_ExpectSuccessful) {
EXPECT_EQ(*it, *it1);
++it1;
}
- ASSERT(it == mems.end() && it1 == keys.end());
+ EXPECT_TRUE(it == mems.end() && it1 == keys.end());
}
} // namespace formatters
diff --git a/src/components/formatters/test/CMakeLists.txt b/src/components/formatters/test/CMakeLists.txt
index b9966c8670..d245626dae 100644
--- a/src/components/formatters/test/CMakeLists.txt
+++ b/src/components/formatters/test/CMakeLists.txt
@@ -37,7 +37,7 @@ include_directories(
${COMPONENTS_DIR}/formatters/include
${COMPONENTS_DIR}/formatters/test/include
${CMAKE_BINARY_DIR}/src/components/interfaces
- ${CMAKE_SOURCE_DIR}/src/3rd_party-static/jsoncpp/include
+ ${JSONCPP_INCLUDE_DIRECTORY}
)
set(LIBRARIES
diff --git a/src/components/formatters/test/CSmartFactory_test.cc b/src/components/formatters/test/CSmartFactory_test.cc
index 41a77f1f1e..f98af88328 100644
--- a/src/components/formatters/test/CSmartFactory_test.cc
+++ b/src/components/formatters/test/CSmartFactory_test.cc
@@ -30,8 +30,8 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include "SmartFactoryTestHelper.h"
-#include "formatters/CSmartFactory.hpp"
+#include "formatters/SmartFactoryTestHelper.h"
+#include "formatters/CSmartFactory.h"
#include "gtest/gtest.h"
namespace test {
@@ -51,7 +51,8 @@ TEST(CSmartFactoryTest, CreateSmartFactory_ExpectCreated) {
EXPECT_EQ(2u, test_factory.structs_schemes().size());
}
-TEST(CSmartFactoryTest, CreateSmartObjWithSchema1_ExpectCreatedObjectToCorrespondSmSchema1) {
+TEST(CSmartFactoryTest,
+ CreateSmartObjWithSchema1_ExpectCreatedObjectToCorrespondSmSchema1) {
CSmartFactoryTest test_factory;
// Create SmartObject with attached SmartChmema
SmartObject obj = test_factory.CreateSmartObject(FunctionIdTest::Function1,
@@ -70,7 +71,8 @@ TEST(CSmartFactoryTest, CreateSmartObjWithSchema1_ExpectCreatedObjectToCorrespon
EXPECT_TRUE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObjWithNotExistedSchema_ExpectCreatedObjectNotValid) {
+TEST(CSmartFactoryTest,
+ CreateSmartObjWithNotExistedSchema_ExpectCreatedObjectNotValid) {
CSmartFactoryTest test_factory;
// Create SmartObject with attached SmartChmema
SmartObject obj = test_factory.CreateSmartObject(
@@ -81,7 +83,9 @@ TEST(CSmartFactoryTest, CreateSmartObjWithNotExistedSchema_ExpectCreatedObjectNo
EXPECT_TRUE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObjectWithSchema1_MissedOneField_ExpectCreatedNotCorrespondSmartSchema) {
+TEST(
+ CSmartFactoryTest,
+ CreateSmartObjectWithSchema1_MissedOneField_ExpectCreatedNotCorrespondSmartSchema) {
CSmartFactoryTest test_factory;
// Create SmartObject with attached SmartChmema
SmartObject obj = test_factory.CreateSmartObject(FunctionIdTest::Function1,
@@ -99,7 +103,9 @@ TEST(CSmartFactoryTest, CreateSmartObjectWithSchema1_MissedOneField_ExpectCreate
EXPECT_FALSE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObjectWithSchema1_AddOutOfRangeValue_ExpectCreatedNotCorrespondSmartSchema) {
+TEST(
+ CSmartFactoryTest,
+ CreateSmartObjectWithSchema1_AddOutOfRangeValue_ExpectCreatedNotCorrespondSmartSchema) {
CSmartFactoryTest test_factory;
// Create SmartObject with attached SmartChmema
SmartObject obj = test_factory.CreateSmartObject(FunctionIdTest::Function1,
@@ -118,7 +124,9 @@ TEST(CSmartFactoryTest, CreateSmartObjectWithSchema1_AddOutOfRangeValue_ExpectCr
EXPECT_FALSE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObjectWithSchema1_AddInvalidValue_ExpectCreatedNotCorrespondSmartSchema) {
+TEST(
+ CSmartFactoryTest,
+ CreateSmartObjectWithSchema1_AddInvalidValue_ExpectCreatedNotCorrespondSmartSchema) {
CSmartFactoryTest test_factory;
// Create SmartObject with attached SmartChmema
SmartObject obj = test_factory.CreateSmartObject(FunctionIdTest::Function1,
@@ -137,7 +145,8 @@ TEST(CSmartFactoryTest, CreateSmartObjectWithSchema1_AddInvalidValue_ExpectCreat
EXPECT_FALSE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_ExpectCreatedObjectCorrespondsSmSchema1) {
+TEST(CSmartFactoryTest,
+ CreateSmartObj_AttachSchema1_ExpectCreatedObjectCorrespondsSmSchema1) {
CSmartFactoryTest test_factory;
// Create empty SmartObject without any schema
SmartObject obj;
@@ -158,7 +167,9 @@ TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_ExpectCreatedObjectCorrespo
EXPECT_TRUE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_MissOneField_ExpectCreatedObjectNotCorrespondsSmSchema1) {
+TEST(
+ CSmartFactoryTest,
+ CreateSmartObj_AttachSchema1_MissOneField_ExpectCreatedObjectNotCorrespondsSmSchema1) {
CSmartFactoryTest test_factory;
// Create empty SmartObject without any schema
SmartObject obj;
@@ -178,7 +189,8 @@ TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_MissOneField_ExpectCreatedO
EXPECT_FALSE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObj_AttachNotExistedSchema_ExpectSmSchemaNotAttached) {
+TEST(CSmartFactoryTest,
+ CreateSmartObj_AttachNotExistedSchema_ExpectSmSchemaNotAttached) {
CSmartFactoryTest test_factory;
// Create empty SmartObject without any schema
SmartObject obj;
@@ -190,7 +202,9 @@ TEST(CSmartFactoryTest, CreateSmartObj_AttachNotExistedSchema_ExpectSmSchemaNotA
EXPECT_TRUE(SmartType::SmartType_Map == obj.getType());
}
-TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_AddInvalidValue_ExpectCreatedObjectNotCorrespondsSmSchema1) {
+TEST(
+ CSmartFactoryTest,
+ CreateSmartObj_AttachSchema1_AddInvalidValue_ExpectCreatedObjectNotCorrespondsSmSchema1) {
CSmartFactoryTest test_factory;
// Create empty SmartObject without any schema
SmartObject obj;
@@ -211,7 +225,8 @@ TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_AddInvalidValue_ExpectCreat
EXPECT_FALSE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_ExpectCreatedObjectCorrespondsSmSchema) {
+TEST(CSmartFactoryTest,
+ CreateSmartObj_AttachSchema1_ExpectCreatedObjectCorrespondsSmSchema) {
CSmartFactoryTest test_factory;
// Create empty SmartObject without any schema
SmartObject obj;
@@ -225,7 +240,9 @@ TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_ExpectCreatedObjectCorrespo
EXPECT_TRUE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_OneMandatoryFieldMissed_ExpectCreatedObjectNotCorrespondsSmSchema) {
+TEST(
+ CSmartFactoryTest,
+ CreateSmartObj_AttachSchema1_OneMandatoryFieldMissed_ExpectCreatedObjectNotCorrespondsSmSchema) {
CSmartFactoryTest test_factory;
// Create empty SmartObject without any schema
SmartObject obj;
@@ -238,7 +255,8 @@ TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema1_OneMandatoryFieldMissed_Exp
EXPECT_FALSE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema2_ExpectCreatedObjectCorrespondsSmSchema) {
+TEST(CSmartFactoryTest,
+ CreateSmartObj_AttachSchema2_ExpectCreatedObjectCorrespondsSmSchema) {
CSmartFactoryTest test_factory;
// Create empty SmartObject without any schema
SmartObject obj;
@@ -252,7 +270,8 @@ TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema2_ExpectCreatedObjectCorrespo
EXPECT_TRUE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema_ExpectCreatedObjectCorrespondsSmSchema) {
+TEST(CSmartFactoryTest,
+ CreateSmartObj_AttachSchema_ExpectCreatedObjectCorrespondsSmSchema) {
CSmartFactoryTest test_factory;
// Create empty SmartObject without any schema
SmartObject obj;
@@ -269,11 +288,13 @@ TEST(CSmartFactoryTest, CreateSmartObj_AttachSchema_ExpectCreatedObjectCorrespon
EXPECT_TRUE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId_ExpectCreatedObjectCorrespondsSmSchema) {
+TEST(
+ CSmartFactoryTest,
+ CreateSmartObj_WithSchemaFromStructId_ExpectCreatedObjectCorrespondsSmSchema) {
CSmartFactoryTest test_factory;
// Create empty SmartObject with schema correspopnding StructId
- SmartObject obj = test_factory.CreateSmartObject(
- StructIdentifiersTest::Common_1);
+ SmartObject obj =
+ test_factory.CreateSmartObject(StructIdentifiersTest::Common_1);
// Add fields
obj["text"] = "test";
obj["position"] = 200;
@@ -288,11 +309,13 @@ TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId_ExpectCreatedObjec
EXPECT_TRUE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId_MissedOneField_ExpectCreatedObjectNotCorrespondsSmSchema) {
+TEST(
+ CSmartFactoryTest,
+ CreateSmartObj_WithSchemaFromStructId_MissedOneField_ExpectCreatedObjectNotCorrespondsSmSchema) {
CSmartFactoryTest test_factory;
// Create empty SmartObject with schema correspopnding StructId
- SmartObject obj = test_factory.CreateSmartObject(
- StructIdentifiersTest::Common_1);
+ SmartObject obj =
+ test_factory.CreateSmartObject(StructIdentifiersTest::Common_1);
// Add fields. One missed.
obj["text"] = "test";
obj["image"]["text"] = "test2";
@@ -306,11 +329,13 @@ TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId_MissedOneField_Exp
EXPECT_FALSE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId2_ExpectCreatedObjectCorrespondsSmSchema) {
+TEST(
+ CSmartFactoryTest,
+ CreateSmartObj_WithSchemaFromStructId2_ExpectCreatedObjectCorrespondsSmSchema) {
CSmartFactoryTest test_factory;
// Create empty SmartObject with schema correspopnding StructId
- SmartObject obj = test_factory.CreateSmartObject(
- StructIdentifiersTest::Common_2);
+ SmartObject obj =
+ test_factory.CreateSmartObject(StructIdentifiersTest::Common_2);
// Add fields
obj["text"] = "test";
obj["position"] = 200;
@@ -325,11 +350,13 @@ TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId2_ExpectCreatedObje
EXPECT_TRUE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId2_MissedOneField_ExpectCreatedObjectNotCorrespondsSmSchema) {
+TEST(
+ CSmartFactoryTest,
+ CreateSmartObj_WithSchemaFromStructId2_MissedOneField_ExpectCreatedObjectNotCorrespondsSmSchema) {
CSmartFactoryTest test_factory;
// Create empty SmartObject with schema correspopnding StructId
- SmartObject obj = test_factory.CreateSmartObject(
- StructIdentifiersTest::Common_2);
+ SmartObject obj =
+ test_factory.CreateSmartObject(StructIdentifiersTest::Common_2);
// Add fields. One missed.
obj["text"] = "test";
obj["image"]["text"] = "test2";
@@ -340,11 +367,13 @@ TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId2_MissedOneField_Ex
EXPECT_FALSE(obj.isValid());
}
-TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId2_InvalidValueAdded_ExpectCreatedObjectNotCorrespondsSmSchema) {
+TEST(
+ CSmartFactoryTest,
+ CreateSmartObj_WithSchemaFromStructId2_InvalidValueAdded_ExpectCreatedObjectNotCorrespondsSmSchema) {
CSmartFactoryTest test_factory;
// Create empty SmartObject with schema correspopnding StructId
- SmartObject obj = test_factory.CreateSmartObject(
- StructIdentifiersTest::Common_2);
+ SmartObject obj =
+ test_factory.CreateSmartObject(StructIdentifiersTest::Common_2);
// Add fields. One missed.
obj["text"] = 111;
obj["position"] = 200;
@@ -359,32 +388,34 @@ TEST(CSmartFactoryTest, CreateSmartObj_WithSchemaFromStructId2_InvalidValueAdded
TEST(CSmartFactoryTest, GetSchemaWithSmartFactory_ExpectReceivedSchema) {
CSmartFactoryTest test_factory;
CSmartSchema schema;
- EXPECT_TRUE(
- test_factory.GetSchema(FunctionIdTest::Function1,
- MessageTypeTest::request, schema));
+ EXPECT_TRUE(test_factory.GetSchema(
+ FunctionIdTest::Function1, MessageTypeTest::request, schema));
}
-TEST(CSmartFactoryTest, GetNotExistedSchemaWithSmartFactory_ExpectNotReceivedSchema) {
+TEST(CSmartFactoryTest,
+ GetNotExistedSchemaWithSmartFactory_ExpectNotReceivedSchema) {
CSmartFactoryTest test_factory;
CSmartSchema schema;
- EXPECT_FALSE(
- test_factory.GetSchema(FunctionIdTest::Function1,
- MessageTypeTest::INVALID_ENUM, schema));
+ EXPECT_FALSE(test_factory.GetSchema(
+ FunctionIdTest::Function1, MessageTypeTest::INVALID_ENUM, schema));
}
-TEST(CSmartFactoryTest, GetSchemaWithSmartFactoryWithStructId1_ExpectReceivedSchema) {
+TEST(CSmartFactoryTest,
+ GetSchemaWithSmartFactoryWithStructId1_ExpectReceivedSchema) {
CSmartFactoryTest test_factory;
CSmartSchema schema;
EXPECT_TRUE(test_factory.GetSchema(StructIdentifiersTest::Common_1, schema));
}
-TEST(CSmartFactoryTest, GetSchemaWithSmartFactoryWithStructId2_ExpectReceivedSchema) {
+TEST(CSmartFactoryTest,
+ GetSchemaWithSmartFactoryWithStructId2_ExpectReceivedSchema) {
CSmartFactoryTest test_factory;
CSmartSchema schema;
EXPECT_TRUE(test_factory.GetSchema(StructIdentifiersTest::Common_2, schema));
}
-TEST(CSmartFactoryTest, GetNotExistedSchemaWithSmartFactoryWithStructId_ExpectNotReceivedSchema) {
+TEST(CSmartFactoryTest,
+ GetNotExistedSchemaWithSmartFactoryWithStructId_ExpectNotReceivedSchema) {
CSmartFactoryTest test_factory;
CSmartSchema schema;
EXPECT_FALSE(
@@ -394,4 +425,3 @@ TEST(CSmartFactoryTest, GetNotExistedSchemaWithSmartFactoryWithStructId_ExpectNo
} // namespace formatters
} // namespace components
} // namespace test
-
diff --git a/src/components/formatters/test/cFormatterJsonSDLRPCv1_test.cc b/src/components/formatters/test/cFormatterJsonSDLRPCv1_test.cc
index 55b7f886fd..91701c8aab 100644
--- a/src/components/formatters/test/cFormatterJsonSDLRPCv1_test.cc
+++ b/src/components/formatters/test/cFormatterJsonSDLRPCv1_test.cc
@@ -32,8 +32,8 @@
#include "gtest/gtest.h"
-#include "formatters/CFormatterJsonSDLRPCv1.hpp"
-#include "create_smartSchema.h"
+#include "formatters/CFormatterJsonSDLRPCv1.h"
+#include "formatters/create_smartSchema.h"
namespace test {
namespace components {
@@ -89,7 +89,8 @@ TEST(CFormatterJsonSDLRPCv1Test, SmObjWithRequestWithoutMsgNotValid_ToString) {
EXPECT_EQ(expectOutputJsonString, jsonString);
}
-TEST(CFormatterJsonSDLRPCv1Test, SmObjWithRequestWithEmptyMsgWithTestSchemaToString) {
+TEST(CFormatterJsonSDLRPCv1Test,
+ SmObjWithRequestWithEmptyMsgWithTestSchemaToString) {
SmartObject srcObj;
CSmartSchema schema = initObjectSchema();
srcObj.setSchema(schema);
@@ -121,7 +122,8 @@ TEST(CFormatterJsonSDLRPCv1Test, SmObjWithRequestWithEmptyMsgWithTestSchemaToStr
EXPECT_EQ(expectOutputJsonString, jsonString);
}
-TEST(CFormatterJsonSDLRPCv1Test, SmObjWithRequestWithNonemptyMsgWithTestSchemaToString) {
+TEST(CFormatterJsonSDLRPCv1Test,
+ SmObjWithRequestWithNonemptyMsgWithTestSchemaToString) {
SmartObject srcObj;
CSmartSchema schema = initObjectSchema();
srcObj.setSchema(schema);
@@ -278,7 +280,8 @@ TEST(CFormatterJsonSDLRPCv1Test, SmObjWithResponseToString) {
EXPECT_EQ(expectOutputJsonString, jsonString);
}
-TEST(CFormatterJsonSDLRPCv1Test, SmObjWithResponseWithoutSchemaWithoutParamsToString) {
+TEST(CFormatterJsonSDLRPCv1Test,
+ SmObjWithResponseWithoutSchemaWithoutParamsToString) {
SmartObject srcObj;
srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::response;
std::string jsonString;
@@ -326,7 +329,8 @@ TEST(CFormatterJsonSDLRPCv1Test, StringRequestToSmObj) {
obj.setSchema(schema);
bool result = CFormatterJsonSDLRPCv1::fromString<FunctionIDTest::eType,
- MessageTypeTest::eType>(inputJsonString, obj);
+ MessageTypeTest::eType>(
+ inputJsonString, obj);
EXPECT_EQ(CFormatterJsonSDLRPCv1::kSuccess, result);
EXPECT_EQ(Errors::eType::OK, obj.validate());
@@ -369,7 +373,8 @@ TEST(CFormatterJsonSDLRPCv1Test, StringRequestWithoutNameToSmartObject) {
SmartObject obj;
bool result = CFormatterJsonSDLRPCv1::fromString<FunctionIDTest::eType,
- MessageTypeTest::eType>(inputJsonString, obj);
+ MessageTypeTest::eType>(
+ inputJsonString, obj);
EXPECT_EQ(CFormatterJsonSDLRPCv1::kParsingError, result);
@@ -410,7 +415,8 @@ TEST(CFormatterJsonSDLRPCv1Test, StringRequestWithIncorrectCorIDToSmartObject) {
SmartObject obj;
bool result = CFormatterJsonSDLRPCv1::fromString<FunctionIDTest::eType,
- MessageTypeTest::eType>(inputJsonString, obj);
+ MessageTypeTest::eType>(
+ inputJsonString, obj);
EXPECT_EQ(CFormatterJsonSDLRPCv1::kParsingError, result);
EXPECT_EQ(obj[S_PARAMS][S_MESSAGE_TYPE], MessageTypeTest::request);
@@ -440,7 +446,8 @@ TEST(CFormatterJsonSDLRPCv1Test, StringResponceToSmartObject) {
obj.setSchema(schema);
bool result = CFormatterJsonSDLRPCv1::fromString<FunctionIDTest::eType,
- MessageTypeTest::eType>(inputJsonString, obj);
+ MessageTypeTest::eType>(
+ inputJsonString, obj);
EXPECT_EQ(CFormatterJsonSDLRPCv1::kSuccess, result);
EXPECT_EQ(obj[S_PARAMS][S_MESSAGE_TYPE], MessageTypeTest::response);
EXPECT_EQ(obj[S_PARAMS][S_FUNCTION_ID], 0);
@@ -467,7 +474,8 @@ TEST(CFormatterJsonSDLRPCv1Test, StringNotificationToSmartObject) {
obj.setSchema(schema);
bool result = CFormatterJsonSDLRPCv1::fromString<FunctionIDTest::eType,
- MessageTypeTest::eType>(inputJsonString, obj);
+ MessageTypeTest::eType>(
+ inputJsonString, obj);
EXPECT_EQ(CFormatterJsonSDLRPCv1::kSuccess, result);
EXPECT_EQ(Errors::eType::OK, obj.validate());
EXPECT_EQ(obj[S_PARAMS][S_MESSAGE_TYPE], MessageTypeTest::notification);
@@ -497,6 +505,6 @@ TEST(CFormatterJsonSDLRPCv1Test, MetaFormatToString) {
EXPECT_EQ(meta_formatter_error_code::kErrorOk, result);
}
-} // namespace formatters
-} // namespace components
-} // namespace test
+} // namespace formatters
+} // namespace components
+} // namespace test
diff --git a/src/components/formatters/test/cFormatterJsonSDLRPCv2_test.cc b/src/components/formatters/test/cFormatterJsonSDLRPCv2_test.cc
index 814cff4ab7..feb7dd3129 100644
--- a/src/components/formatters/test/cFormatterJsonSDLRPCv2_test.cc
+++ b/src/components/formatters/test/cFormatterJsonSDLRPCv2_test.cc
@@ -31,8 +31,8 @@
*/
#include "gtest/gtest.h"
-#include "create_smartSchema.h"
-#include "formatters/CFormatterJsonSDLRPCv2.hpp"
+#include "formatters/create_smartSchema.h"
+#include "formatters/CFormatterJsonSDLRPCv2.h"
namespace test {
namespace components {
@@ -75,7 +75,8 @@ TEST(CFormatterJsonSDLRPCv2Test, SmObjWithRequestWithoutMsgNotValid_ToString) {
EXPECT_EQ(expectOutputJsonString, jsonString);
}
-TEST(CFormatterJsonSDLRPCv2Test, SmObjWithRequestWithEmptyMsgWithTestSchemaToString) {
+TEST(CFormatterJsonSDLRPCv2Test,
+ SmObjWithRequestWithEmptyMsgWithTestSchemaToString) {
SmartObject srcObj;
CSmartSchema schema = initObjectSchema();
srcObj.setSchema(schema);
@@ -100,7 +101,8 @@ TEST(CFormatterJsonSDLRPCv2Test, SmObjWithRequestWithEmptyMsgWithTestSchemaToStr
EXPECT_EQ(expectOutputJsonString, jsonString);
}
-TEST(CFormatterJsonSDLRPCv2Test, SmObjWithRequestWithNonemptyMsgWithTestSchemaToString) {
+TEST(CFormatterJsonSDLRPCv2Test,
+ SmObjWithRequestWithNonemptyMsgWithTestSchemaToString) {
SmartObject srcObj;
CSmartSchema schema = initObjectSchema();
srcObj.setSchema(schema);
@@ -216,7 +218,8 @@ TEST(CFormatterJsonSDLRPCv2Test, SmObjWithResponseToString) {
EXPECT_EQ(expectOutputJsonString, jsonString);
}
-TEST(CFormatterJsonSDLRPCv2Test, SmObjWithResponseWithoutSchemaWithoutParamsToString) {
+TEST(CFormatterJsonSDLRPCv2Test,
+ SmObjWithResponseWithoutSchemaWithoutParamsToString) {
SmartObject srcObj;
srcObj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::response;
std::string jsonString;
@@ -252,9 +255,11 @@ TEST(CFormatterJsonSDLRPCv2Test, StringRequestWithoutCorIdToSmObj) {
obj.setSchema(schema);
bool result = CFormatterJsonSDLRPCv2::fromString<FunctionIDTest::eType,
- MessageTypeTest::eType>(inputJsonString, obj,
- FunctionIDTest::RegisterAppInterface,
- MessageTypeTest::request);
+ MessageTypeTest::eType>(
+ inputJsonString,
+ obj,
+ FunctionIDTest::RegisterAppInterface,
+ MessageTypeTest::request);
EXPECT_EQ(true, result);
EXPECT_EQ(Errors::eType::MISSING_MANDATORY_PARAMETER, obj.validate());
@@ -294,9 +299,12 @@ TEST(CFormatterJsonSDLRPCv2Test, StringRequestWithCorIdToSmObj) {
obj.setSchema(schema);
int32_t corId = 10;
bool result = CFormatterJsonSDLRPCv2::fromString<FunctionIDTest::eType,
- MessageTypeTest::eType>(inputJsonString, obj,
- FunctionIDTest::RegisterAppInterface,
- MessageTypeTest::request, corId);
+ MessageTypeTest::eType>(
+ inputJsonString,
+ obj,
+ FunctionIDTest::RegisterAppInterface,
+ MessageTypeTest::request,
+ corId);
EXPECT_EQ(true, result);
EXPECT_EQ(Errors::eType::OK, obj.validate());
@@ -328,9 +336,12 @@ TEST(CFormatterJsonSDLRPCv2Test, StringResponceWithCorIdToSmartObject) {
obj.setSchema(schema);
int32_t corId = 10;
bool result = CFormatterJsonSDLRPCv2::fromString<FunctionIDTest::eType,
- MessageTypeTest::eType>(inputJsonString, obj,
- FunctionIDTest::RegisterAppInterface,
- MessageTypeTest::response, corId);
+ MessageTypeTest::eType>(
+ inputJsonString,
+ obj,
+ FunctionIDTest::RegisterAppInterface,
+ MessageTypeTest::response,
+ corId);
EXPECT_EQ(true, result);
EXPECT_EQ(obj[S_PARAMS][S_MESSAGE_TYPE], MessageTypeTest::response);
@@ -354,9 +365,12 @@ TEST(CFormatterJsonSDLRPCv2Test, StringNotificationToSmartObject) {
obj.setSchema(schema);
int32_t corId = 10;
bool result = CFormatterJsonSDLRPCv2::fromString<FunctionIDTest::eType,
- MessageTypeTest::eType>(inputJsonString, obj,
- FunctionIDTest::SetGlobalProperties,
- MessageTypeTest::notification, corId);
+ MessageTypeTest::eType>(
+ inputJsonString,
+ obj,
+ FunctionIDTest::SetGlobalProperties,
+ MessageTypeTest::notification,
+ corId);
EXPECT_EQ(true, result);
EXPECT_EQ(Errors::eType::OK, obj.validate());
EXPECT_EQ(obj[S_PARAMS][S_MESSAGE_TYPE], MessageTypeTest::notification);
diff --git a/src/components/formatters/test/formatter_json_rpc_test.cc b/src/components/formatters/test/formatter_json_rpc_test.cc
index 9047d6790a..c2b0d73394 100644
--- a/src/components/formatters/test/formatter_json_rpc_test.cc
+++ b/src/components/formatters/test/formatter_json_rpc_test.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -31,21 +31,65 @@
*/
#include <algorithm>
+#include "formatters/formatter_json_rpc.h"
+#include <string>
+#include <set>
+#include <algorithm>
+#include <json/writer.h>
#include "gtest/gtest.h"
#include "formatters/formatter_json_rpc.h"
-#include "formatters/CSmartFactory.hpp"
+#include <string>
+#include <set>
+#include "gtest/gtest.h"
+#include "formatters/CSmartFactory.h"
#include "HMI_API_schema.h"
#include "MOBILE_API_schema.h"
namespace test {
namespace components {
-namespace formatters {
+namespace formatters_test {
using namespace NsSmartDeviceLink::NsSmartObjects;
using namespace NsSmartDeviceLink::NsJSONHandler::Formatters;
using namespace NsSmartDeviceLink::NsJSONHandler::strings;
-TEST(FormatterJsonRPCTest, CorrectRPCv1_request_SmartObjectToString_EXPECT_SUCCESS) {
+void CompactJson(std::string& str) {
+ Json::Value root;
+ Json::Reader reader;
+ reader.parse(str, root);
+ Json::FastWriter writer;
+ str = writer.write(root);
+ if (str[str.size() - 1] == '\n') {
+ str.erase(str.size() - 1, 1);
+ }
+}
+
+namespace {
+const int64_t big_64int = 100000000000;
+const std::string str_with_big_int64 = "100000000000";
+} // namespace
+
+TEST(FormatterJsonRPCTest, CheckCompactJson) {
+ std::string before_compact(
+ "{\n \"jsonrpc\" : \"2.0\",\n \"method\" : "
+ "\"BasicCommunication.OnSystemRequest\","
+ "\n \"params\" : {\n \"fileName\" : \"file \n Name\",\n "
+ "\"length\" : 100000000000,\n"
+ "\"offset\" : 100000000000,\n \"requestType\" : \"PROPRIETARY\"\n "
+ "}\n}\n");
+ std::string after_compact = before_compact;
+ CompactJson(after_compact);
+
+ EXPECT_NE(before_compact, after_compact);
+
+ std::string expected(
+ "{\"jsonrpc\":\"2.0\",\"method\":\"BasicCommunication.OnSystemRequest\","
+ "\"params\":{\"fileName\":\"file \\n Name\",\"length\":100000000000,"
+ "\"offset\":100000000000,\"requestType\":\"PROPRIETARY\"}}");
+ EXPECT_EQ(expected, after_compact);
+}
+
+TEST(FormatterJsonRPCTest, CorrectRPCv1Request_ToString_Success) {
// Create SmartObject
SmartObject obj;
obj[S_PARAMS][S_FUNCTION_ID] = hmi_apis::FunctionID::VR_IsReady;
@@ -59,15 +103,15 @@ TEST(FormatterJsonRPCTest, CorrectRPCv1_request_SmartObjectToString_EXPECT_SUCCE
EXPECT_TRUE(factory.attachSchema(obj, false));
std::string result;
- // Convert SmrtObject to Json string
+ // Convert SmartObject to Json string
EXPECT_TRUE(FormatterJsonRpc::ToString(obj, result));
- EXPECT_EQ(
- std::string(
- "{\n \"id\" : 4444,\n \"jsonrpc\" : \"2.0\",\n \"method\" : \"VR.IsReady\"\n}\n"),
- result);
+ CompactJson(result);
+ const std::string json_string(
+ "{\"id\":4444,\"jsonrpc\":\"2.0\",\"method\":\"VR.IsReady\"}");
+ EXPECT_EQ(json_string, result);
}
-TEST(FormatterJsonRPCTest, CorrectRPCv2_request_SmartObjectToString_EXPECT_SUCCESS) {
+TEST(FormatterJsonRPCTest, CorrectRPCv2Request_ToString_Success) {
// Create SmartObject
SmartObject obj;
obj[S_PARAMS][S_FUNCTION_ID] = mobile_apis::FunctionID::AddCommandID;
@@ -79,15 +123,45 @@ TEST(FormatterJsonRPCTest, CorrectRPCv2_request_SmartObjectToString_EXPECT_SUCCE
EXPECT_TRUE(factory.attachSchema(obj, false));
std::string result;
- // Convert SmrtObject to Json string
+ // Convert SmartObject to Json string
+ EXPECT_TRUE(FormatterJsonRpc::ToString(obj, result));
+ CompactJson(result);
+ const std::string json_string(
+ "{\"id\":4444,\"jsonrpc\":\"2.0\",\"method\":\"AddCommandID\"}");
+ EXPECT_EQ(json_string, result);
+}
+
+TEST(FormatterJsonRPCTest, UpperBoundValuesInSystemRequest_ToString_Success) {
+ // Create SmartObject
+ SmartObject obj;
+ obj[S_PARAMS][S_FUNCTION_ID] =
+ hmi_apis::FunctionID::BasicCommunication_OnSystemRequest;
+ obj[S_PARAMS][S_MESSAGE_TYPE] = hmi_apis::messageType::notification;
+ obj[S_PARAMS][S_PROTOCOL_VERSION] = 2;
+ obj[S_PARAMS][S_PROTOCOL_TYPE] = 1;
+ obj[S_PARAMS][S_CORRELATION_ID] = 4444;
+ obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map);
+ obj[S_MSG_PARAMS]["requestType"] = hmi_apis::Common_RequestType::PROPRIETARY;
+ obj[S_MSG_PARAMS]["fileName"] = "fileName";
+ obj[S_MSG_PARAMS]["length"] = big_64int;
+ obj[S_MSG_PARAMS]["offset"] = big_64int;
+ // Attach Schema
+
+ hmi_apis::HMI_API factory;
+ EXPECT_TRUE(factory.attachSchema(obj, false));
+ EXPECT_EQ(Errors::OK, obj.validate());
+ std::string result;
+ // Convert SmartObject to Json string
EXPECT_TRUE(FormatterJsonRpc::ToString(obj, result));
- EXPECT_EQ(
- std::string(
- "{\n \"id\" : 4444,\n \"jsonrpc\" : \"2.0\",\n \"method\" : \"AddCommandID\"\n}\n"),
- result);
+ CompactJson(result);
+ const std::string json_string(
+ "{\"jsonrpc\":\"2.0\",\"method\":\"BasicCommunication.OnSystemRequest\","
+ "\"params\":{\"fileName\":\"fileName\",\"length\":100000000000,"
+ "\"offset\":100000000000,\"requestType\":\"PROPRIETARY\"}}");
+ EXPECT_EQ(json_string, result);
}
-TEST(FormatterJsonRPCTest, CorrectRPCv1_notification_SmartObjectToString_EXPECT_SUCCESS) {
+TEST(FormatterJsonRPCTest, CorrectRPCv1Notification_ToString_Success) {
// Create SmartObject
SmartObject obj;
std::string result;
@@ -100,20 +174,139 @@ TEST(FormatterJsonRPCTest, CorrectRPCv1_notification_SmartObjectToString_EXPECT_
// Attach Schema
hmi_apis::HMI_API factory;
EXPECT_TRUE(factory.attachSchema(obj, false));
- // Convert SmrtObject to Json string
+ // Convert SmartObject to Json string
+ EXPECT_TRUE(FormatterJsonRpc::ToString(obj, result));
+ CompactJson(result);
+ const std::string json_string(
+ "{\"jsonrpc\":\"2.0\",\"method\":\"Buttons.OnButtonPress\",\"params\":{}"
+ "}");
+ EXPECT_EQ(json_string, result);
+}
+
+TEST(FormatterJsonRPCTest, CorrectResponseToString_Success) {
+ // Create SmartObject
+ SmartObject obj;
+ obj[S_PARAMS][S_FUNCTION_ID] = hmi_apis::FunctionID::VR_AddCommand;
+ obj[S_PARAMS][S_MESSAGE_TYPE] = hmi_apis::messageType::response;
+ obj[S_PARAMS][S_CORRELATION_ID] = 4440;
+ obj[S_PARAMS][kCode] = hmi_apis::Common_Result::SUCCESS;
+ obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map);
+ // Attach Schema
+ hmi_apis::HMI_API factory;
+ EXPECT_TRUE(factory.attachSchema(obj, false));
+
+ std::string result;
+ // Convert SmartObject to Json string
+ EXPECT_TRUE(FormatterJsonRpc::ToString(obj, result));
+ CompactJson(result);
+ const std::string json_string(
+ "{\"id\":4440,\"jsonrpc\":\"2.0\",\"result\":{\"code\":0,\"method\":\"VR."
+ "AddCommand\"}}");
+ EXPECT_EQ(json_string, result);
+}
+
+TEST(FormatterJsonRPCTest, ErrorResponse_ToString_Success) {
+ // Create SmartObject
+ SmartObject obj;
+ obj[S_PARAMS][S_FUNCTION_ID] = hmi_apis::FunctionID::VR_AddCommand;
+ obj[S_PARAMS][S_MESSAGE_TYPE] = hmi_apis::messageType::error_response;
+ obj[S_PARAMS][S_CORRELATION_ID] = 4440;
+ obj[S_PARAMS][kCode] = hmi_apis::Common_Result::GENERIC_ERROR;
+ obj[S_PARAMS][kMessage] = "Some error";
+ obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map);
+ // Attach Schema
+ hmi_apis::HMI_API factory;
+ EXPECT_TRUE(factory.attachSchema(obj, false));
+
+ std::string result;
+ // Convert SmartObject to Json string
+ EXPECT_TRUE(FormatterJsonRpc::ToString(obj, result));
+ CompactJson(result);
+
+ const std::string json_string(
+ "{\"error\":{\"code\":22,\"data\":{\"method\":\"VR.AddCommand\"},"
+ "\"message\":\"Some error\"},\"id\":4440,\"jsonrpc\":\"2.0\"}");
+ EXPECT_EQ(json_string, result);
+}
+
+TEST(FormatterJsonRPCTest, ResponseWithoutCorID_ToString_Fail) {
+ // Create SmartObject
+ SmartObject obj;
+ obj[S_PARAMS][S_FUNCTION_ID] = hmi_apis::FunctionID::VR_AddCommand;
+ obj[S_PARAMS][S_MESSAGE_TYPE] = hmi_apis::messageType::response;
+ obj[S_PARAMS][S_PROTOCOL_VERSION] = 2;
+ obj[S_PARAMS][S_PROTOCOL_TYPE] = 1;
+ obj[S_PARAMS][S_CORRELATION_ID] = 4444;
+ obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map);
+ // Attach Schema
+ hmi_apis::HMI_API factory;
+ EXPECT_TRUE(factory.attachSchema(obj, false));
+
+ std::string result;
+ // Convert SmartObject to Json string will finish wrong
+ EXPECT_FALSE(FormatterJsonRpc::ToString(obj, result));
+}
+
+TEST(FormatterJsonRPCTest, RequestWithoutMSGParams_ToString_Success) {
+ // Create SmartObject
+ SmartObject obj;
+ obj[S_PARAMS][S_FUNCTION_ID] = mobile_apis::FunctionID::AddCommandID;
+ obj[S_PARAMS][S_MESSAGE_TYPE] = mobile_apis::messageType::request;
+ obj[S_PARAMS][S_CORRELATION_ID] = 4444;
+ // Attach Schema
+ mobile_apis::MOBILE_API factory;
+ EXPECT_TRUE(factory.attachSchema(obj, false));
+
+ std::string result;
+ // Convert SmartObject to Json string
EXPECT_TRUE(FormatterJsonRpc::ToString(obj, result));
- EXPECT_EQ(
- std::string(
- "{\n \"jsonrpc\" : \"2.0\",\n \"method\" : \"Buttons.OnButtonPress\",\n \"params\" : {}\n}\n"),
- result);
+ CompactJson(result);
+ const std::string json_string(
+ "{\"id\":4444,\"jsonrpc\":\"2.0\",\"method\":\"AddCommandID\"}");
+ EXPECT_EQ(json_string, result);
+}
+
+TEST(FormatterJsonRPCTest, RequestWithoutCorID_ToString_Fail) {
+ // Create SmartObject
+ SmartObject obj;
+ obj[S_PARAMS][S_FUNCTION_ID] = mobile_apis::FunctionID::AddCommandID;
+ obj[S_PARAMS][S_MESSAGE_TYPE] = mobile_apis::messageType::request;
+ obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map);
+ // Attach Schema
+ mobile_apis::MOBILE_API factory;
+ EXPECT_TRUE(factory.attachSchema(obj, false));
+
+ std::string result;
+ // Converting SmartObject to Json string is failed
+ EXPECT_FALSE(FormatterJsonRpc::ToString(obj, result));
+ CompactJson(result);
+
+ const std::string json_string(
+ "{\"jsonrpc\":\"2.0\",\"method\":\"AddCommandID\"}");
+ EXPECT_EQ(json_string, result);
}
-TEST(FormatterJsonRPCTest, InvalidRPC_SmartObjectToString_EXPECT_FALSE) {
+TEST(FormatterJsonRPCTest, RequestWithoutType_ToString_Fail) {
// Create SmartObject
SmartObject obj;
+ obj[S_PARAMS][S_FUNCTION_ID] = mobile_apis::FunctionID::AddCommandID;
+ obj[S_MSG_PARAMS] = SmartObject(SmartType::SmartType_Map);
+ // Attach Schema is impossible
+ mobile_apis::MOBILE_API factory;
+ EXPECT_FALSE(factory.attachSchema(obj, false));
+
+ std::string result;
+ // Converting SmartObject to Json string is failed
+ EXPECT_FALSE(FormatterJsonRpc::ToString(obj, result));
+ EXPECT_EQ(std::string("{\n \"jsonrpc\" : \"2.0\"\n}\n"), result);
+}
+
+TEST(FormatterJsonRPCTest, InvalidRPC_ToString_False) {
+ // Create SmartObject with notification id and response message type
+ SmartObject obj;
std::string result;
obj[S_PARAMS][S_FUNCTION_ID] =
- hmi_apis::FunctionID::BasicCommunication_OnReady;
+ hmi_apis::FunctionID::BasicCommunication_OnReady;
obj[S_PARAMS][S_MESSAGE_TYPE] = hmi_apis::messageType::response;
obj[S_PARAMS][S_PROTOCOL_VERSION] = 2;
obj[S_PARAMS][S_PROTOCOL_TYPE] = 1;
@@ -128,72 +321,110 @@ TEST(FormatterJsonRPCTest, InvalidRPC_SmartObjectToString_EXPECT_FALSE) {
EXPECT_EQ(std::string("{\n \"jsonrpc\" : \"2.0\"\n}\n"), result);
}
-TEST(FormatterJsonRPCTest, FromStringNotificationToSmartObj_ExpectSuccess) {
+TEST(FormatterJsonRPCTest, Notification_ToSmartObject_Success) {
// Source Json string
const std::string json_string(
- "{\n \"jsonrpc\" : \"2.0\",\n \"method\" : \"BasicCommunication.OnReady\",\n \"params\" : {}\n}\n");
+ "{\n \"jsonrpc\" : \"2.0\",\n \"method\" : "
+ "\"BasicCommunication.OnReady\",\n \"params\" : {}\n}\n");
// Smart Object to keep result
SmartObject obj;
// Convert json string to smart object
- EXPECT_EQ(
- 0,
- (FormatterJsonRpc::FromString<hmi_apis::FunctionID::eType,
- hmi_apis::messageType::eType>(json_string, obj)));
+ int32_t result = FormatterJsonRpc::FromString<hmi_apis::FunctionID::eType,
+ hmi_apis::messageType::eType>(
+ json_string, obj);
+ EXPECT_EQ(0, result);
// Get keys collection from Smart Object
std::set<std::string> keys = obj["params"].enumerate();
EXPECT_EQ(4u, keys.size());
}
-TEST(FormatterJsonRPCTest, FromStringToSmartObjInvalidFormat_ExpectFalse) {
+TEST(FormatterJsonRPCTest, InvalidFormatToSmartObject_False) {
// Source Json string
const std::string json_string(
- "{\n \"method\" : \"BasicCommunication.OnReady\",\n \"params\" : {}\n}\n");
+ "{\n \"method\" : \"BasicCommunication.OnReady\",\n \"params\" : "
+ "{}\n}\n");
// Smart Object to keep result
SmartObject obj;
// Convert json string to smart object
- EXPECT_EQ(
- 2,
- (FormatterJsonRpc::FromString<hmi_apis::FunctionID::eType,
- hmi_apis::messageType::eType>(json_string, obj)));
+ int32_t result = FormatterJsonRpc::FromString<hmi_apis::FunctionID::eType,
+ hmi_apis::messageType::eType>(
+ json_string, obj);
+ EXPECT_EQ(2, result);
// Get keys collection from Smart Object
std::set<std::string> keys = obj["params"].enumerate();
EXPECT_EQ(4u, keys.size());
}
-TEST(FormatterJsonRPCTest, FromStringRequestToSmartObj_ExpectSuccess) {
+TEST(FormatterJsonRPCTest, RequestToSmartObject_Success) {
// Source Json string
const std::string json_string(
- "{\n \"id\" : 4444,\n \"jsonrpc\" : \"2.0\",\n \"method\" : \"VR.IsReady\"\n}\n");
+ "{\n \"id\" : 4444,\n \"jsonrpc\" : \"2.0\",\n \"method\" : "
+ "\"VR.IsReady\"\n}\n");
// Smart Object to keep result
SmartObject obj;
// Convert json string to smart object
- EXPECT_EQ(
- 0,
- (FormatterJsonRpc::FromString<hmi_apis::FunctionID::eType,
- hmi_apis::messageType::eType>(json_string, obj)));
+ int32_t result = FormatterJsonRpc::FromString<hmi_apis::FunctionID::eType,
+ hmi_apis::messageType::eType>(
+ json_string, obj);
+ int32_t function_id = hmi_apis::FunctionID::VR_IsReady;
+ EXPECT_EQ(0, result);
// Get keys collection from Smart Object
std::set<std::string> keys = obj["params"].enumerate();
- std::set<std::string>::iterator it1 = keys.begin();
EXPECT_EQ(5u, keys.size());
+ EXPECT_EQ(4444, obj["params"]["correlation_id"].asInt());
+ EXPECT_EQ(function_id, obj["params"]["function_id"].asInt());
+ EXPECT_EQ(0, obj["params"]["message_type"].asInt());
+ EXPECT_EQ(1, obj["params"]["protocol_type"].asInt());
+ EXPECT_EQ(2, obj["params"]["protocol_version"].asInt());
}
-TEST(FormatterJsonRPCTest, FromStringResponseToSmartObj_ExpectSuccess) {
+TEST(FormatterJsonRPCTest, ResponseToSmartObject_Success) {
// Source Json string
const std::string json_string(
- "{\n \"id\" : 4444,\n \"jsonrpc\" : \"2.0\",\n \"method\" : \"VR.IsReady\"\n}\n");
+ "{\"id\":4440,\"jsonrpc\":\"2.0\",\"result\":{\"code\":0,\"method\":\"VR."
+ "AddCommand\"}}");
// Smart Object to keep result
SmartObject obj;
// Convert json string to smart object
- EXPECT_EQ(
- 0,
- (FormatterJsonRpc::FromString<hmi_apis::FunctionID::eType,
- hmi_apis::messageType::eType>(json_string, obj)));
+ int32_t result = FormatterJsonRpc::FromString<hmi_apis::FunctionID::eType,
+ hmi_apis::messageType::eType>(
+ json_string, obj);
+
+ int32_t function_id = hmi_apis::FunctionID::VR_AddCommand;
+
+ EXPECT_EQ(0, result);
// Get keys collection from Smart Object
std::set<std::string> keys = obj["params"].enumerate();
- std::set<std::string>::iterator it1 = keys.begin();
- EXPECT_EQ(5u, keys.size());
+ EXPECT_EQ(6u, keys.size());
+ EXPECT_EQ(0, obj["params"]["code"].asInt());
+ EXPECT_EQ(4440, obj["params"]["correlation_id"].asInt());
+ EXPECT_EQ(function_id, obj["params"]["function_id"].asInt());
+ EXPECT_EQ(1, obj["params"]["message_type"].asInt());
+ EXPECT_EQ(1, obj["params"]["protocol_type"].asInt());
+ EXPECT_EQ(2, obj["params"]["protocol_version"].asInt());
+}
+
+TEST(FormatterJsonRPCTest, StringWithUpperBoundValueToSmartObject_Success) {
+ // Source Json string
+ const std::string json_string(
+ "{\"jsonrpc\":\"2.0\",\"method\":\"BasicCommunication.OnSystemRequest\","
+ "\"params\":{\"fileName\":\"filename\",\"length\":100000000000,"
+ "\"requestType\":\"PROPRIETARY\"}}");
+ // Smart Object to keep result
+ SmartObject obj;
+ // Convert json string to smart object
+
+ int32_t res = FormatterJsonRpc::FromString<hmi_apis::FunctionID::eType,
+ hmi_apis::messageType::eType>(
+ json_string, obj);
+ // Get keys collection from Smart Object
+ EXPECT_EQ(0, res);
+ EXPECT_EQ(big_64int, obj["msg_params"]["length"].asInt());
+ EXPECT_EQ(str_with_big_int64, obj["msg_params"]["length"].asString());
+ std::set<std::string> keys = obj["params"].enumerate();
+ EXPECT_EQ(4u, keys.size());
}
-} // namespace formatters
+} // namespace formatters_test
} // namespace components
} // namespace test
diff --git a/src/components/formatters/test/generic_json_formatter_test.cc b/src/components/formatters/test/generic_json_formatter_test.cc
index 51da8c91ff..41ecfd9ee3 100644
--- a/src/components/formatters/test/generic_json_formatter_test.cc
+++ b/src/components/formatters/test/generic_json_formatter_test.cc
@@ -76,18 +76,20 @@ TEST(GenericJsonFormatter, ToString) {
obj["subobject"]["arrayField"][1] = 'c';
obj["subobject"]["arrayField"][2][0] = 10.0;
formatters::GenericJsonFormatter::ToString(obj, result);
- ASSERT_STREQ("{\n"
- " \"intField\" : 100500,\n"
- " \"stringField\" : \"s\",\n"
- " \"subobject\" : {\n"
- " \"arrayField\" : [\n"
- " 0,\n"
- " \"c\",\n"
- " [ 10.0 ]\n"
- " ],\n"
- " \"boolField\" : false\n"
- " }\n"
- "}\n", result.c_str());
+ ASSERT_STREQ(
+ "{\n"
+ " \"intField\" : 100500,\n"
+ " \"stringField\" : \"s\",\n"
+ " \"subobject\" : {\n"
+ " \"arrayField\" : [\n"
+ " 0,\n"
+ " \"c\",\n"
+ " [ 10.0 ]\n"
+ " ],\n"
+ " \"boolField\" : false\n"
+ " }\n"
+ "}\n",
+ result.c_str());
}
TEST(GenericJsonFormatter, FromString) {
@@ -120,8 +122,8 @@ TEST(GenericJsonFormatter, FromString) {
ASSERT_EQ(smartobj::SmartType_String, result.getType());
ASSERT_STREQ("str", result.asString().c_str());
- ASSERT_TRUE(formatters::GenericJsonFormatter::FromString("[true, null, 10]",
- result));
+ ASSERT_TRUE(
+ formatters::GenericJsonFormatter::FromString("[true, null, 10]", result));
ASSERT_EQ(smartobj::SmartType_Array, result.getType());
ASSERT_EQ(smartobj::SmartType_Boolean, result.getElement(0U).getType());
ASSERT_EQ(true, result.getElement(0U).asBool());
@@ -129,15 +131,15 @@ TEST(GenericJsonFormatter, FromString) {
ASSERT_EQ(smartobj::SmartType_Integer, result.getElement(2U).getType());
ASSERT_EQ(10, result.getElement(2U).asInt());
- ASSERT_TRUE(
- formatters::GenericJsonFormatter::FromString("{"
- " \"intField\": 100500,"
- " \"subobject\": {"
- " \"arrayField\": [1, null],"
- " \"strField\": \"str\""
- " }"
- "}",
- result));
+ ASSERT_TRUE(formatters::GenericJsonFormatter::FromString(
+ "{"
+ " \"intField\": 100500,"
+ " \"subobject\": {"
+ " \"arrayField\": [1, null],"
+ " \"strField\": \"str\""
+ " }"
+ "}",
+ result));
ASSERT_EQ(smartobj::SmartType_Map, result.getType());
ASSERT_EQ(smartobj::SmartType_Integer,
result.getElement("intField").getType());
@@ -146,17 +148,27 @@ TEST(GenericJsonFormatter, FromString) {
ASSERT_EQ(smartobj::SmartType_Array,
result.getElement("subobject").getElement("arrayField").getType());
ASSERT_EQ(smartobj::SmartType_Integer,
- result.getElement("subobject").getElement("arrayField").getElement(0U).getType());
- ASSERT_EQ(1, result.getElement("subobject").getElement("arrayField").getElement(0U).asInt());
+ result.getElement("subobject")
+ .getElement("arrayField")
+ .getElement(0U)
+ .getType());
+ ASSERT_EQ(1,
+ result.getElement("subobject")
+ .getElement("arrayField")
+ .getElement(0U)
+ .asInt());
ASSERT_EQ(smartobj::SmartType_Null,
- result.getElement("subobject").getElement("arrayField").getElement(1U).getType());
+ result.getElement("subobject")
+ .getElement("arrayField")
+ .getElement(1U)
+ .getType());
ASSERT_EQ(smartobj::SmartType_String,
result.getElement("subobject").getElement("strField").getType());
ASSERT_STREQ(
- "str",
- result.getElement("subobject").getElement("strField").asString().c_str());
+ "str",
+ result.getElement("subobject").getElement("strField").asString().c_str());
}
-} // formatters
-} // components
-} // test
+} // formatters
+} // components
+} // test
diff --git a/src/components/formatters/test/include/SmartFactoryTestHelper.h b/src/components/formatters/test/include/SmartFactoryTestHelper.h
deleted file mode 100644
index ca7021b844..0000000000
--- a/src/components/formatters/test/include/SmartFactoryTestHelper.h
+++ /dev/null
@@ -1,167 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_SMARTFACTORYTESTHELPER_H_
-#define SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_SMARTFACTORYTESTHELPER_H_
-
-#include <map>
-#include <set>
-
-#include "formatters/CSmartFactory.hpp"
-#include "HMI_API_schema.h"
-#include "smart_objects/always_true_schema_item.h"
-#include "smart_objects/always_false_schema_item.h"
-#include "smart_objects/array_schema_item.h"
-#include "smart_objects/bool_schema_item.h"
-#include "smart_objects/object_schema_item.h"
-#include "smart_objects/string_schema_item.h"
-#include "smart_objects/enum_schema_item.h"
-#include "smart_objects/number_schema_item.h"
-#include "smart_objects/schema_item_parameter.h"
-
-namespace test {
-namespace components {
-namespace formatters {
-
-using namespace NsSmartDeviceLink::NsSmartObjects;
-using namespace NsSmartDeviceLink::NsJSONHandler;
-using namespace NsSmartDeviceLink::NsJSONHandler::strings;
-using namespace hmi_apis;
-
-namespace TestType {
-enum eType {
- INVALID_ENUM = -1,
- APPLICATION_NOT_REGISTERED = 0,
- SUCCESS,
- TOO_MANY_PENDING_REQUESTS,
- REJECTED,
- INVALID_DATA,
- OUT_OF_MEMORY,
- ABORTED,
- USER_DISALLOWED,
- GENERIC_ERROR,
- DISALLOWED
-};
-} // namespace TestType
-
-namespace FunctionIdTest {
-enum eType {
- INVALID_ENUM = -1,
- Function1,
- Function2,
- Function3
-};
-} // namespace FunctionIdTest
-
-namespace MessageTypeTest {
-enum eType {
- INVALID_ENUM = -1,
- request,
- response,
- notification,
- error_response
-};
-} // namespace MessageTypeTest
-
-namespace StructIdentifiersTest {
-enum eType {
- INVALID_ENUM = -1,
- Common_1,
- Common_2,
- Common_3
-};
-} // namespace StructIdentifiersTest
-
-class CSmartFactoryTest : public CSmartFactory<FunctionIdTest::eType,
- MessageTypeTest::eType, StructIdentifiersTest::eType> {
- public:
- CSmartFactoryTest();
- std::map<SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>,
- CSmartSchema> function_schemes() {
- return functions_schemes_;
- }
- std::map<StructIdentifiersTest::eType, CSmartSchema> structs_schemes() {
- return structs_schemes_;
- }
- protected:
- typedef std::map<const StructIdentifiersTest::eType,
- utils::SharedPtr<ISchemaItem> > TStructsSchemaItems;
-
- static utils::SharedPtr<ISchemaItem> ProvideObjectSchemaItemForStruct(
- TStructsSchemaItems &struct_schema_items,
- const StructIdentifiersTest::eType struct_id);
-
- void InitStructSchemes(TStructsSchemaItems &struct_schema_items);
-
- void InitFunctionSchemes(
- const TStructsSchemaItems &struct_schema_items,
- const std::set<FunctionIdTest::eType> &function_id_items,
- const std::set<MessageTypeTest::eType> &message_type_items);
-
- static CSmartSchema InitFunction_Function1_request(
- const std::set<FunctionIdTest::eType> &function_id_items,
- const std::set<MessageTypeTest::eType> &message_type_items);
-
- static CSmartSchema InitFunction_Function1_response(
- const TStructsSchemaItems &struct_schema_items,
- const std::set<FunctionIdTest::eType> &function_id_items,
- const std::set<MessageTypeTest::eType> &message_type_items);
-
- static CSmartSchema InitFunction_Function2_request(
- const std::set<FunctionIdTest::eType> &function_id_items,
- const std::set<MessageTypeTest::eType> &message_type_items);
-
- static CSmartSchema InitFunction_Function2_response(
- const TStructsSchemaItems &struct_schema_items,
- const std::set<FunctionIdTest::eType> &function_id_items,
- const std::set<MessageTypeTest::eType> &message_type_items);
-
- static CSmartSchema InitFunction_Function3_request(
- const std::set<FunctionIdTest::eType> &function_id_items,
- const std::set<MessageTypeTest::eType> &message_type_items);
-
- static CSmartSchema InitFunction_Function3_response(
- const TStructsSchemaItems &struct_schema_items,
- const std::set<FunctionIdTest::eType> &function_id_items,
- const std::set<MessageTypeTest::eType> &message_type_items);
-
- static utils::SharedPtr<ISchemaItem> InitStructSchemaItem_Common_1(
- TStructsSchemaItems &struct_schema_items);
-
- static utils::SharedPtr<ISchemaItem> InitStructSchemaItem_Common_2();
-};
-
-} // namespace formatters
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_SMARTFACTORYTESTHELPER_H_
diff --git a/src/components/formatters/test/include/create_smartSchema.h b/src/components/formatters/test/include/create_smartSchema.h
deleted file mode 100644
index c3bc2651e5..0000000000
--- a/src/components/formatters/test/include/create_smartSchema.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_CREATESMARTSCHEMA_H_
-#define SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_CREATESMARTSCHEMA_H_
-
-#include "formatters/CFormatterJsonSDLRPCv1.hpp"
-#include "SmartFactoryTestHelper.h"
-
-namespace test {
-namespace components {
-namespace formatters {
-
-using namespace NsSmartDeviceLink::NsJSONHandler::strings;
-using namespace NsSmartDeviceLink::NsJSONHandler::Formatters;
-using namespace NsSmartDeviceLink::NsSmartObjects;
-
-namespace FunctionIDTest {
-enum eType {
- INVALID_ENUM = -1,
- RegisterAppInterface,
- UnregisterAppInterface,
- SetGlobalProperties,
-};
-}
-
-namespace Language {
-enum eType {
- INVALID_ENUM = -1,
- EN_EU,
- RU_RU
-};
-}
-namespace AppTypeTest {
-enum eType {
- INVALID_ENUM = -1,
- SYSTEM,
- MEDIA
-};
-}
-namespace SpeechCapabilities {
-enum eType {
- INVALID_ENUM = -1,
- SC_TEXT,
-};
-}
-
-namespace StructIdentifiers {
-enum eType {
- INVALID_ENUM = -1,
- Struct1,
- Struct2
-};
-}
-
-CSmartSchema initObjectSchema();
-CSmartSchema initSchemaForMetaFormatter();
-
-} // namespace formatters
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_CREATESMARTSCHEMA_H_
diff --git a/src/components/formatters/test/include/formatters/SmartFactoryTestHelper.h b/src/components/formatters/test/include/formatters/SmartFactoryTestHelper.h
new file mode 100644
index 0000000000..d195fe1833
--- /dev/null
+++ b/src/components/formatters/test/include/formatters/SmartFactoryTestHelper.h
@@ -0,0 +1,160 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_SMARTFACTORYTESTHELPER_H_
+#define SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_SMARTFACTORYTESTHELPER_H_
+
+#include <map>
+#include <set>
+
+#include "formatters/CSmartFactory.h"
+#include "HMI_API_schema.h"
+#include "smart_objects/always_true_schema_item.h"
+#include "smart_objects/always_false_schema_item.h"
+#include "smart_objects/array_schema_item.h"
+#include "smart_objects/bool_schema_item.h"
+#include "smart_objects/object_schema_item.h"
+#include "smart_objects/string_schema_item.h"
+#include "smart_objects/enum_schema_item.h"
+#include "smart_objects/number_schema_item.h"
+#include "smart_objects/schema_item_parameter.h"
+
+namespace test {
+namespace components {
+namespace formatters {
+
+using namespace NsSmartDeviceLink::NsSmartObjects;
+using namespace NsSmartDeviceLink::NsJSONHandler;
+using namespace NsSmartDeviceLink::NsJSONHandler::strings;
+using namespace hmi_apis;
+
+namespace TestType {
+enum eType {
+ INVALID_ENUM = -1,
+ APPLICATION_NOT_REGISTERED = 0,
+ SUCCESS,
+ TOO_MANY_PENDING_REQUESTS,
+ REJECTED,
+ INVALID_DATA,
+ OUT_OF_MEMORY,
+ ABORTED,
+ USER_DISALLOWED,
+ GENERIC_ERROR,
+ DISALLOWED
+};
+} // namespace TestType
+
+namespace FunctionIdTest {
+enum eType { INVALID_ENUM = -1, Function1, Function2, Function3 };
+} // namespace FunctionIdTest
+
+namespace MessageTypeTest {
+enum eType {
+ INVALID_ENUM = -1,
+ request,
+ response,
+ notification,
+ error_response
+};
+} // namespace MessageTypeTest
+
+namespace StructIdentifiersTest {
+enum eType { INVALID_ENUM = -1, Common_1, Common_2, Common_3 };
+} // namespace StructIdentifiersTest
+
+class CSmartFactoryTest : public CSmartFactory<FunctionIdTest::eType,
+ MessageTypeTest::eType,
+ StructIdentifiersTest::eType> {
+ public:
+ CSmartFactoryTest();
+ std::map<SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>,
+ CSmartSchema>
+ function_schemes() {
+ return functions_schemes_;
+ }
+ std::map<StructIdentifiersTest::eType, CSmartSchema> structs_schemes() {
+ return structs_schemes_;
+ }
+
+ protected:
+ typedef std::map<const StructIdentifiersTest::eType,
+ utils::SharedPtr<ISchemaItem> > TStructsSchemaItems;
+
+ static utils::SharedPtr<ISchemaItem> ProvideObjectSchemaItemForStruct(
+ TStructsSchemaItems& struct_schema_items,
+ const StructIdentifiersTest::eType struct_id);
+
+ void InitStructSchemes(TStructsSchemaItems& struct_schema_items);
+
+ void InitFunctionSchemes(
+ const TStructsSchemaItems& struct_schema_items,
+ const std::set<FunctionIdTest::eType>& function_id_items,
+ const std::set<MessageTypeTest::eType>& message_type_items);
+
+ static CSmartSchema InitFunction_Function1_request(
+ const std::set<FunctionIdTest::eType>& function_id_items,
+ const std::set<MessageTypeTest::eType>& message_type_items);
+
+ static CSmartSchema InitFunction_Function1_response(
+ const TStructsSchemaItems& struct_schema_items,
+ const std::set<FunctionIdTest::eType>& function_id_items,
+ const std::set<MessageTypeTest::eType>& message_type_items);
+
+ static CSmartSchema InitFunction_Function2_request(
+ const std::set<FunctionIdTest::eType>& function_id_items,
+ const std::set<MessageTypeTest::eType>& message_type_items);
+
+ static CSmartSchema InitFunction_Function2_response(
+ const TStructsSchemaItems& struct_schema_items,
+ const std::set<FunctionIdTest::eType>& function_id_items,
+ const std::set<MessageTypeTest::eType>& message_type_items);
+
+ static CSmartSchema InitFunction_Function3_request(
+ const std::set<FunctionIdTest::eType>& function_id_items,
+ const std::set<MessageTypeTest::eType>& message_type_items);
+
+ static CSmartSchema InitFunction_Function3_response(
+ const TStructsSchemaItems& struct_schema_items,
+ const std::set<FunctionIdTest::eType>& function_id_items,
+ const std::set<MessageTypeTest::eType>& message_type_items);
+
+ static utils::SharedPtr<ISchemaItem> InitStructSchemaItem_Common_1(
+ TStructsSchemaItems& struct_schema_items);
+
+ static utils::SharedPtr<ISchemaItem> InitStructSchemaItem_Common_2();
+};
+
+} // namespace formatters
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_SMARTFACTORYTESTHELPER_H_
diff --git a/src/components/formatters/test/include/formatters/create_smartSchema.h b/src/components/formatters/test/include/formatters/create_smartSchema.h
new file mode 100644
index 0000000000..3514b7fe94
--- /dev/null
+++ b/src/components/formatters/test/include/formatters/create_smartSchema.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_CREATESMARTSCHEMA_H_
+#define SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_CREATESMARTSCHEMA_H_
+
+#include "formatters/CFormatterJsonSDLRPCv1.h"
+#include "SmartFactoryTestHelper.h"
+
+namespace test {
+namespace components {
+namespace formatters {
+
+using namespace NsSmartDeviceLink::NsJSONHandler::strings;
+using namespace NsSmartDeviceLink::NsJSONHandler::Formatters;
+using namespace NsSmartDeviceLink::NsSmartObjects;
+
+namespace FunctionIDTest {
+enum eType {
+ INVALID_ENUM = -1,
+ RegisterAppInterface,
+ UnregisterAppInterface,
+ SetGlobalProperties,
+};
+}
+
+namespace Language {
+enum eType { INVALID_ENUM = -1, EN_EU, RU_RU };
+}
+namespace AppTypeTest {
+enum eType { INVALID_ENUM = -1, SYSTEM, MEDIA };
+}
+namespace SpeechCapabilities {
+enum eType {
+ INVALID_ENUM = -1,
+ SC_TEXT,
+};
+}
+
+namespace StructIdentifiers {
+enum eType { INVALID_ENUM = -1, Struct1, Struct2 };
+}
+
+CSmartSchema initObjectSchema();
+CSmartSchema initSchemaForMetaFormatter();
+
+} // namespace formatters
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_CREATESMARTSCHEMA_H_
diff --git a/src/components/formatters/test/include/formatters/meta_formatter_test_helper.h b/src/components/formatters/test/include/formatters/meta_formatter_test_helper.h
new file mode 100644
index 0000000000..1494c75c4b
--- /dev/null
+++ b/src/components/formatters/test/include/formatters/meta_formatter_test_helper.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_METAFORMATTERTESTHELPER_H_
+#define SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_METAFORMATTERTESTHELPER_H_
+
+#include "gtest/gtest.h"
+
+#include "smart_objects/smart_object.h"
+#include "formatters/CFormatterJsonSDLRPCv1.h"
+#include "formatters/CSmartFactory.h"
+#include "create_smartSchema.h"
+
+namespace test {
+namespace components {
+namespace formatters {
+
+class CMetaFormatterTestHelper : public ::testing::Test {
+ protected:
+ virtual void SetUp();
+
+ virtual void TearDown();
+
+ void AnyObjectToJsonString(
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& obj,
+ std::string& result_string);
+
+ void FillObjectIdenticalToSchema(
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& obj);
+
+ void FillObjectIdenticalToSchemaWithoutNoMandatoriesParams(
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& obj);
+
+ void CompareObjects(
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& first,
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& second);
+
+ void FillObjectWithDefaultValues(
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& obj);
+
+ void FillObjectWithoutSomeMandatoryFields(
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& obj);
+
+ // Members
+ std::set<FunctionIDTest::eType> function_id_items_;
+ std::set<MessageTypeTest::eType> message_type_items_;
+};
+
+} // namespace formatters
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_METAFORMATTERTESTHELPER_H_
diff --git a/src/components/formatters/test/include/meta_formatter_test_helper.h b/src/components/formatters/test/include/meta_formatter_test_helper.h
deleted file mode 100644
index e2be3beb64..0000000000
--- a/src/components/formatters/test/include/meta_formatter_test_helper.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_METAFORMATTERTESTHELPER_H_
-#define SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_METAFORMATTERTESTHELPER_H_
-
-#include "gtest/gtest.h"
-
-#include "smart_objects/smart_object.h"
-#include "formatters/CFormatterJsonSDLRPCv1.hpp"
-#include "formatters/CSmartFactory.hpp"
-#include "create_smartSchema.h"
-
-namespace test {
-namespace components {
-namespace formatters {
-
-class CMetaFormatterTestHelper : public ::testing::Test {
- protected:
-
- virtual void SetUp();
-
- virtual void TearDown();
-
- void AnyObjectToJsonString(
- const NsSmartDeviceLink::NsSmartObjects::SmartObject& obj,
- std::string& result_string);
-
- void FillObjectIdenticalToSchema(
- NsSmartDeviceLink::NsSmartObjects::SmartObject& obj);
-
- void FillObjectIdenticalToSchemaWithoutNoMandatoriesParams(
- NsSmartDeviceLink::NsSmartObjects::SmartObject& obj);
-
- void CompareObjects(
- const NsSmartDeviceLink::NsSmartObjects::SmartObject& first,
- const NsSmartDeviceLink::NsSmartObjects::SmartObject& second);
-
- void FillObjectWithDefaultValues(
- NsSmartDeviceLink::NsSmartObjects::SmartObject& obj);
-
- void FillObjectWithoutSomeMandatoryFields(
- NsSmartDeviceLink::NsSmartObjects::SmartObject& obj);
-
- // Members
- std::set<FunctionIDTest::eType> function_id_items_;
- std::set<MessageTypeTest::eType> message_type_items_;
-};
-
-} // namespace formatters
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_FORMATTERS_TEST_INCLUDE_METAFORMATTERTESTHELPER_H_
diff --git a/src/components/formatters/test/meta_formatter_test.cc b/src/components/formatters/test/meta_formatter_test.cc
index 17c2506ac6..27f5e70e8f 100644
--- a/src/components/formatters/test/meta_formatter_test.cc
+++ b/src/components/formatters/test/meta_formatter_test.cc
@@ -32,17 +32,19 @@
#include "gtest/gtest.h"
#include "formatters/meta_formatter.h"
-#include "meta_formatter_test_helper.h"
+#include "formatters/meta_formatter_test_helper.h"
namespace test {
namespace components {
namespace formatters {
-TEST_F(CMetaFormatterTestHelper, inputObjectIdenticalToSchemaWithAndWithoutMandatoryParams) {
+TEST_F(CMetaFormatterTestHelper,
+ inputObjectIdenticalToSchemaWithAndWithoutMandatoryParams) {
Json::Value value;
Json::Reader reader;
- CSmartFactory<FunctionIDTest::eType, MessageTypeTest::eType,
- StructIdentifiers::eType> factory_;
+ CSmartFactory<FunctionIDTest::eType,
+ MessageTypeTest::eType,
+ StructIdentifiers::eType> factory_;
SmartObject object1 = factory_.CreateSmartObject(
FunctionIDTest::RegisterAppInterface, MessageTypeTest::request);
@@ -59,31 +61,32 @@ TEST_F(CMetaFormatterTestHelper, inputObjectIdenticalToSchemaWithAndWithoutManda
FillObjectIdenticalToSchema(object1);
FillObjectIdenticalToSchemaWithoutNoMandatoriesParams(object2);
bool creationresult;
- creationresult = CMetaFormatter::CreateObjectByPattern(object1, schema,
- result_object1);
+ creationresult =
+ CMetaFormatter::CreateObjectByPattern(object1, schema, result_object1);
EXPECT_TRUE(creationresult);
- creationresult = CMetaFormatter::CreateObjectByPattern(object2, schema,
- result_object2);
+ creationresult =
+ CMetaFormatter::CreateObjectByPattern(object2, schema, result_object2);
EXPECT_TRUE(creationresult);
// Uncomment code to print objects in console
-// std::string formatted_string;
-// CFormatterJsonSDLRPCv1::toString(object1, formatted_string);
-// printf("object1 %s\n", formatted_string.c_str());
-//
-// CFormatterJsonSDLRPCv1::toString(result_object1, formatted_string);
-// printf("result_object1 %s\n", formatted_string.c_str());
-//
-// CFormatterJsonSDLRPCv1::toString(object2, formatted_string);
-// printf("object2 %s\n", formatted_string.c_str());
-//
-// CFormatterJsonSDLRPCv1::toString(result_object2, formatted_string);
-// printf("result_object2 %s\n", formatted_string.c_str());
+ // std::string formatted_string;
+ // CFormatterJsonSDLRPCv1::toString(object1, formatted_string);
+ // printf("object1 %s\n", formatted_string.c_str());
+ //
+ // CFormatterJsonSDLRPCv1::toString(result_object1, formatted_string);
+ // printf("result_object1 %s\n", formatted_string.c_str());
+ //
+ // CFormatterJsonSDLRPCv1::toString(object2, formatted_string);
+ // printf("object2 %s\n", formatted_string.c_str());
+ //
+ // CFormatterJsonSDLRPCv1::toString(result_object2, formatted_string);
+ // printf("result_object2 %s\n", formatted_string.c_str());
CompareObjects(object1, result_object1);
CompareObjects(object2, result_object2);
- // Enums must be unapplied (converted to string) in order to be compared against strings
+ // Enums must be unapplied (converted to string) in order to be compared
+ // against strings
result_object1.getSchema().unapplySchema(result_object1);
EXPECT_EQ("request", result_object1[S_PARAMS][S_MESSAGE_TYPE].asString());
EXPECT_EQ("RegisterAppInterface",
@@ -102,25 +105,24 @@ TEST_F(CMetaFormatterTestHelper, NormalSchemaWithEmptyObject) {
// Get schema
CSmartSchema schema = initSchemaForMetaFormatter();
- bool create_object_result = CMetaFormatter::CreateObjectByPattern(
- object, schema, result_object);
+ bool create_object_result =
+ CMetaFormatter::CreateObjectByPattern(object, schema, result_object);
EXPECT_TRUE(create_object_result);
FillObjectWithDefaultValues(expected_object);
CompareObjects(expected_object, result_object);
-// Uncomment code to print objects in console
-// std::string str;
-// AnyObjectToJsonString(result_object, str);
-// printf("result_object(default) %s", str.c_str());
-// AnyObjectToJsonString(expected_object, str);
-// printf("expected_object %s", str.c_str());
-
-
+ // Uncomment code to print objects in console
+ // std::string str;
+ // AnyObjectToJsonString(result_object, str);
+ // printf("result_object(default) %s", str.c_str());
+ // AnyObjectToJsonString(expected_object, str);
+ // printf("expected_object %s", str.c_str());
}
-TEST_F(CMetaFormatterTestHelper, NormalSchemaWithObjectWithoutSomeMandatoryFields) {
+TEST_F(CMetaFormatterTestHelper,
+ NormalSchemaWithObjectWithoutSomeMandatoryFields) {
SmartObject object;
SmartObject result_object;
@@ -137,58 +139,61 @@ TEST_F(CMetaFormatterTestHelper, NormalSchemaWithObjectWithoutSomeMandatoryField
EXPECT_EQ(
0, result_object[S_MSG_PARAMS]["syncMsgVersion"]["minorVersion"].asInt());
-// Uncomment code to print object in console
-// std::string str;
-// AnyObjectToJsonString(result_object, str);
-// printf("result_object %s", str.c_str());
-
+ // Uncomment code to print object in console
+ // std::string str;
+ // AnyObjectToJsonString(result_object, str);
+ // printf("result_object %s", str.c_str());
}
TEST_F(CMetaFormatterTestHelper, ObjectWithEmptyMap) {
std::map<std::string, CObjectSchemaItem::SMember> schemaMembersMap;
- CSmartSchema map_schema = CSmartSchema(
- CObjectSchemaItem::create(schemaMembersMap));
+ CSmartSchema map_schema =
+ CSmartSchema(CObjectSchemaItem::create(schemaMembersMap));
SmartObject object;
SmartObject result_object_empty_map;
SmartObject object_empty_map = SmartObject(SmartType_Map);
- CMetaFormatter::CreateObjectByPattern(object_empty_map, map_schema,
- result_object_empty_map);
- EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())<< "smartObject is not map type";
- EXPECT_EQ(0u, result_object_empty_map.length())<< "non empty map";
-
- CMetaFormatter::CreateObjectByPattern(object, map_schema,
- result_object_empty_map);
- EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())<< "smartObject is not map type";
- EXPECT_EQ(0u, result_object_empty_map.length())<< "non empty map";
+ CMetaFormatter::CreateObjectByPattern(
+ object_empty_map, map_schema, result_object_empty_map);
+ EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())
+ << "smartObject is not map type";
+ EXPECT_EQ(0u, result_object_empty_map.length()) << "non empty map";
+
+ CMetaFormatter::CreateObjectByPattern(
+ object, map_schema, result_object_empty_map);
+ EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())
+ << "smartObject is not map type";
+ EXPECT_EQ(0u, result_object_empty_map.length()) << "non empty map";
object["field1"] = 0;
object["field2"] = SmartObject();
- CMetaFormatter::CreateObjectByPattern(object, map_schema,
- result_object_empty_map);
- EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())<< "smartObject is not map type";
- EXPECT_EQ(0u, result_object_empty_map.length())<< "non empty map";
+ CMetaFormatter::CreateObjectByPattern(
+ object, map_schema, result_object_empty_map);
+ EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())
+ << "smartObject is not map type";
+ EXPECT_EQ(0u, result_object_empty_map.length()) << "non empty map";
// Fill object with any values. Result must be the same
FillObjectIdenticalToSchema(object);
- CMetaFormatter::CreateObjectByPattern(object, map_schema,
- result_object_empty_map);
- EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())<< "smartObject is not map type";
- EXPECT_EQ(0u, result_object_empty_map.length())<< "non empty map";
+ CMetaFormatter::CreateObjectByPattern(
+ object, map_schema, result_object_empty_map);
+ EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())
+ << "smartObject is not map type";
+ EXPECT_EQ(0u, result_object_empty_map.length()) << "non empty map";
// Fill object with any values. Result must be the same
FillObjectIdenticalToSchemaWithoutNoMandatoriesParams(object);
- CMetaFormatter::CreateObjectByPattern(object, map_schema,
- result_object_empty_map);
- EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())<< "smartObject is not map type";
- EXPECT_EQ(0u, result_object_empty_map.length())<< "non empty map";
-
-// Uncomment code to print object in console
-// std::string str;
-// AnyObjectToJsonString(result_object_empty_map, str);
-// printf("result_object(empty map) %s", str.c_str());
-
+ CMetaFormatter::CreateObjectByPattern(
+ object, map_schema, result_object_empty_map);
+ EXPECT_EQ(SmartType_Map, result_object_empty_map.getType())
+ << "smartObject is not map type";
+ EXPECT_EQ(0u, result_object_empty_map.length()) << "non empty map";
+
+ // Uncomment code to print object in console
+ // std::string str;
+ // AnyObjectToJsonString(result_object_empty_map, str);
+ // printf("result_object(empty map) %s", str.c_str());
}
TEST_F(CMetaFormatterTestHelper, ObjectWithEmptyArray) {
@@ -199,38 +204,42 @@ TEST_F(CMetaFormatterTestHelper, ObjectWithEmptyArray) {
SmartObject object_empty_aray = SmartObject(SmartType_Array);
- CMetaFormatter::CreateObjectByPattern(object_empty_aray, array_schema,
- result_object_empty_array);
- EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())<< "smartObject is not array type";
- EXPECT_EQ(0u, result_object_empty_array.length())<< "non empty array";
+ CMetaFormatter::CreateObjectByPattern(
+ object_empty_aray, array_schema, result_object_empty_array);
+ EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())
+ << "smartObject is not array type";
+ EXPECT_EQ(0u, result_object_empty_array.length()) << "non empty array";
- CMetaFormatter::CreateObjectByPattern(object, array_schema,
- result_object_empty_array);
- EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())<< "smartObject is not array type";
- EXPECT_EQ(0u, result_object_empty_array.length())<< "non empty array";
+ CMetaFormatter::CreateObjectByPattern(
+ object, array_schema, result_object_empty_array);
+ EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())
+ << "smartObject is not array type";
+ EXPECT_EQ(0u, result_object_empty_array.length()) << "non empty array";
// Fill object with any values. Result must be the same
FillObjectIdenticalToSchema(object);
- CMetaFormatter::CreateObjectByPattern(object, array_schema,
- result_object_empty_array);
- EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())<< "smartObject is not array type";
- EXPECT_EQ(0u, result_object_empty_array.length())<< "non empty array";
+ CMetaFormatter::CreateObjectByPattern(
+ object, array_schema, result_object_empty_array);
+ EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())
+ << "smartObject is not array type";
+ EXPECT_EQ(0u, result_object_empty_array.length()) << "non empty array";
// Fill object with any values. Result must be the same
FillObjectWithoutSomeMandatoryFields(object);
- CMetaFormatter::CreateObjectByPattern(object, array_schema,
- result_object_empty_array);
- EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())<< "smartObject is not array type";
- EXPECT_EQ(0u, result_object_empty_array.length())<< "non empty array";
-
-// Uncomment code to print object in console
-// std::string str;
-// AnyObjectToJsonString(result_object_empty_array, str);
-// printf("result_object(empty array) %s", str.c_str());
-
+ CMetaFormatter::CreateObjectByPattern(
+ object, array_schema, result_object_empty_array);
+ EXPECT_EQ(SmartType_Array, result_object_empty_array.getType())
+ << "smartObject is not array type";
+ EXPECT_EQ(0u, result_object_empty_array.length()) << "non empty array";
+
+ // Uncomment code to print object in console
+ // std::string str;
+ // AnyObjectToJsonString(result_object_empty_array, str);
+ // printf("result_object(empty array) %s", str.c_str());
}
-TEST_F(CMetaFormatterTestHelper, ObjectWithEmptyArrayAndEmptyMapWithOtherParameters) {
+TEST_F(CMetaFormatterTestHelper,
+ ObjectWithEmptyArrayAndEmptyMapWithOtherParameters) {
// Arrange
SmartObject result_object;
SmartObject object;
@@ -254,8 +263,8 @@ TEST_F(CMetaFormatterTestHelper, ObjectWithEmptyArrayAndEmptyMapWithOtherParamet
TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(1),
TSchemaItemParameter<int>(2)),
false);
- paramsMembersMap[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), false);
+ paramsMembersMap[S_PROTOCOL_TYPE] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), false);
std::map<std::string, CObjectSchemaItem::SMember> schemaMembersMap;
@@ -286,7 +295,8 @@ TEST_F(CMetaFormatterTestHelper, ObjectWithEmptyArrayAndEmptyMapWithOtherParamet
schemaMembersMap["non_mandatory_string"] = CObjectSchemaItem::SMember(
CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(500),
+ TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(500),
TSchemaItemParameter<std::string>("ignoredDefValue")),
false);
@@ -313,13 +323,12 @@ TEST_F(CMetaFormatterTestHelper, ObjectWithEmptyArrayAndEmptyMapWithOtherParamet
CMetaFormatter::CreateObjectByPattern(object, schema, result_object);
-// Uncomment code to print object in console
-// std::string str;
-// AnyObjectToJsonString(object, str);
-// printf("object %s", str.c_str());
-// AnyObjectToJsonString(result_object, str);
-// printf("result_object %s", str.c_str());
-
+ // Uncomment code to print object in console
+ // std::string str;
+ // AnyObjectToJsonString(object, str);
+ // printf("object %s", str.c_str());
+ // AnyObjectToJsonString(result_object, str);
+ // printf("result_object %s", str.c_str());
// Assert
EXPECT_EQ(500, result_object[S_PARAMS][S_FUNCTION_ID].asInt());
diff --git a/src/components/formatters/test/src/SmartFactoryTestHelper.cc b/src/components/formatters/test/src/SmartFactoryTestHelper.cc
index 8f601afc29..2dd76f85f8 100644
--- a/src/components/formatters/test/src/SmartFactoryTestHelper.cc
+++ b/src/components/formatters/test/src/SmartFactoryTestHelper.cc
@@ -30,27 +30,38 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include "SmartFactoryTestHelper.h"
+#include "formatters/SmartFactoryTestHelper.h"
using namespace test::components::formatters;
-template<>
-const EnumConversionHelper<TestType::eType>::EnumToCStringMap EnumConversionHelper<
- test::components::formatters::TestType::eType>::enum_to_cstring_map_ =
- EnumConversionHelper<test::components::formatters::TestType::eType>::InitEnumToCStringMap();
-
-template<>
-const EnumConversionHelper<TestType::eType>::CStringToEnumMap EnumConversionHelper<
- test::components::formatters::TestType::eType>::cstring_to_enum_map_ =
- EnumConversionHelper<test::components::formatters::TestType::eType>::InitCStringToEnumMap();
-
-template<>
+template <>
+const EnumConversionHelper<TestType::eType>::EnumToCStringMap
+ EnumConversionHelper<
+ test::components::formatters::TestType::eType>::enum_to_cstring_map_ =
+ EnumConversionHelper<test::components::formatters::TestType::eType>::
+ InitEnumToCStringMap();
+
+template <>
+const EnumConversionHelper<TestType::eType>::CStringToEnumMap
+ EnumConversionHelper<
+ test::components::formatters::TestType::eType>::cstring_to_enum_map_ =
+ EnumConversionHelper<test::components::formatters::TestType::eType>::
+ InitCStringToEnumMap();
+
+template <>
const char* const EnumConversionHelper<TestType::eType>::cstring_values_[] = {
- "APPLICATION_NOT_REGISTERED", "SUCCESS", "TOO_MANY_PENDING_REQUESTS",
- "REJECTED", "INVALID_DATA", "OUT_OF_MEMORY", "ABORTED", "USER_DISALLOWED",
- "GENERIC_ERROR", "DISALLOWED" };
-
-template<>
+ "APPLICATION_NOT_REGISTERED",
+ "SUCCESS",
+ "TOO_MANY_PENDING_REQUESTS",
+ "REJECTED",
+ "INVALID_DATA",
+ "OUT_OF_MEMORY",
+ "ABORTED",
+ "USER_DISALLOWED",
+ "GENERIC_ERROR",
+ "DISALLOWED"};
+
+template <>
const TestType::eType EnumConversionHelper<TestType::eType>::enum_values_[] = {
test::components::formatters::TestType::APPLICATION_NOT_REGISTERED,
test::components::formatters::TestType::SUCCESS,
@@ -61,51 +72,64 @@ const TestType::eType EnumConversionHelper<TestType::eType>::enum_values_[] = {
test::components::formatters::TestType::ABORTED,
test::components::formatters::TestType::USER_DISALLOWED,
test::components::formatters::TestType::GENERIC_ERROR,
- test::components::formatters::TestType::DISALLOWED };
-
-template<>
-const EnumConversionHelper<FunctionIdTest::eType>::EnumToCStringMap EnumConversionHelper<
- test::components::formatters::FunctionIdTest::eType>::enum_to_cstring_map_ =
- EnumConversionHelper<test::components::formatters::FunctionIdTest::eType>::InitEnumToCStringMap();
-
-template<>
-const EnumConversionHelper<FunctionIdTest::eType>::CStringToEnumMap EnumConversionHelper<
- test::components::formatters::FunctionIdTest::eType>::cstring_to_enum_map_ =
- EnumConversionHelper<test::components::formatters::FunctionIdTest::eType>::InitCStringToEnumMap();
-
-template<>
-const char* const EnumConversionHelper<FunctionIdTest::eType>::cstring_values_[] =
- { "Function1", "Function2", "Function3" };
-
-template<>
-const FunctionIdTest::eType EnumConversionHelper<FunctionIdTest::eType>::enum_values_[] =
- { test::components::formatters::FunctionIdTest::Function1,
+ test::components::formatters::TestType::DISALLOWED};
+
+template <>
+const EnumConversionHelper<FunctionIdTest::eType>::EnumToCStringMap
+ EnumConversionHelper<test::components::formatters::FunctionIdTest::eType>::
+ enum_to_cstring_map_ = EnumConversionHelper<
+ test::components::formatters::FunctionIdTest::eType>::
+ InitEnumToCStringMap();
+
+template <>
+const EnumConversionHelper<FunctionIdTest::eType>::CStringToEnumMap
+ EnumConversionHelper<test::components::formatters::FunctionIdTest::eType>::
+ cstring_to_enum_map_ = EnumConversionHelper<
+ test::components::formatters::FunctionIdTest::eType>::
+ InitCStringToEnumMap();
+
+template <>
+const char* const
+ EnumConversionHelper<FunctionIdTest::eType>::cstring_values_[] = {
+ "Function1", "Function2", "Function3"};
+
+template <>
+const FunctionIdTest::eType
+ EnumConversionHelper<FunctionIdTest::eType>::enum_values_[] = {
+ test::components::formatters::FunctionIdTest::Function1,
test::components::formatters::FunctionIdTest::Function2,
- test::components::formatters::FunctionIdTest::Function3 };
-
-template<>
-const EnumConversionHelper<MessageTypeTest::eType>::EnumToCStringMap EnumConversionHelper<
- test::components::formatters::MessageTypeTest::eType>::enum_to_cstring_map_ =
- EnumConversionHelper<test::components::formatters::MessageTypeTest::eType>::InitEnumToCStringMap();
-
-template<>
-const EnumConversionHelper<MessageTypeTest::eType>::CStringToEnumMap EnumConversionHelper<
- test::components::formatters::MessageTypeTest::eType>::cstring_to_enum_map_ =
- EnumConversionHelper<test::components::formatters::MessageTypeTest::eType>::InitCStringToEnumMap();
-
-template<>
-const char* const EnumConversionHelper<MessageTypeTest::eType>::cstring_values_[] =
- { "request", "response", "notification" };
-
-template<>
-const MessageTypeTest::eType EnumConversionHelper<MessageTypeTest::eType>::enum_values_[] =
- { test::components::formatters::MessageTypeTest::request,
+ test::components::formatters::FunctionIdTest::Function3};
+
+template <>
+const EnumConversionHelper<MessageTypeTest::eType>::EnumToCStringMap
+ EnumConversionHelper<test::components::formatters::MessageTypeTest::eType>::
+ enum_to_cstring_map_ = EnumConversionHelper<
+ test::components::formatters::MessageTypeTest::eType>::
+ InitEnumToCStringMap();
+
+template <>
+const EnumConversionHelper<MessageTypeTest::eType>::CStringToEnumMap
+ EnumConversionHelper<test::components::formatters::MessageTypeTest::eType>::
+ cstring_to_enum_map_ = EnumConversionHelper<
+ test::components::formatters::MessageTypeTest::eType>::
+ InitCStringToEnumMap();
+
+template <>
+const char* const
+ EnumConversionHelper<MessageTypeTest::eType>::cstring_values_[] = {
+ "request", "response", "notification"};
+
+template <>
+const MessageTypeTest::eType
+ EnumConversionHelper<MessageTypeTest::eType>::enum_values_[] = {
+ test::components::formatters::MessageTypeTest::request,
test::components::formatters::MessageTypeTest::response,
- test::components::formatters::MessageTypeTest::notification };
+ test::components::formatters::MessageTypeTest::notification};
CSmartFactoryTest::CSmartFactoryTest()
- : CSmartFactory<FunctionIdTest::eType, MessageTypeTest::eType,
- StructIdentifiersTest::eType>() {
+ : CSmartFactory<FunctionIdTest::eType,
+ MessageTypeTest::eType,
+ StructIdentifiersTest::eType>() {
TStructsSchemaItems struct_schema_items;
InitStructSchemes(struct_schema_items);
std::set<FunctionIdTest::eType> function_id_items;
@@ -118,51 +142,49 @@ CSmartFactoryTest::CSmartFactoryTest()
message_type_items.insert(MessageTypeTest::response);
message_type_items.insert(MessageTypeTest::notification);
message_type_items.insert(MessageTypeTest::error_response);
- InitFunctionSchemes(struct_schema_items, function_id_items,
- message_type_items);
+ InitFunctionSchemes(
+ struct_schema_items, function_id_items, message_type_items);
}
void CSmartFactoryTest::InitStructSchemes(
- TStructsSchemaItems &struct_schema_items) {
+ TStructsSchemaItems& struct_schema_items) {
utils::SharedPtr<ISchemaItem> struct_schema_item_Common_1 =
InitStructSchemaItem_Common_1(struct_schema_items);
- struct_schema_items.insert(
- std::make_pair(StructIdentifiersTest::Common_1,
- struct_schema_item_Common_1));
+ struct_schema_items.insert(std::make_pair(StructIdentifiersTest::Common_1,
+ struct_schema_item_Common_1));
structs_schemes_.insert(
std::make_pair(StructIdentifiersTest::Common_1,
CSmartSchema(struct_schema_item_Common_1)));
utils::SharedPtr<ISchemaItem> struct_schema_item_Common_2 =
InitStructSchemaItem_Common_2();
- struct_schema_items.insert(
- std::make_pair(StructIdentifiersTest::Common_2,
- struct_schema_item_Common_2));
+ struct_schema_items.insert(std::make_pair(StructIdentifiersTest::Common_2,
+ struct_schema_item_Common_2));
structs_schemes_.insert(
std::make_pair(StructIdentifiersTest::Common_2,
CSmartSchema(struct_schema_item_Common_2)));
}
void CSmartFactoryTest::InitFunctionSchemes(
- const TStructsSchemaItems &struct_schema_items,
- const std::set<FunctionIdTest::eType> &function_id_items,
- const std::set<MessageTypeTest::eType> &message_type_items) {
+ const TStructsSchemaItems& struct_schema_items,
+ const std::set<FunctionIdTest::eType>& function_id_items,
+ const std::set<MessageTypeTest::eType>& message_type_items) {
CObjectSchemaItem::Members params_members;
params_members[S_FUNCTION_ID] = CObjectSchemaItem::SMember(
TEnumSchemaItem<FunctionIdTest::eType>::create(function_id_items), true);
params_members[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember(
TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items),
true);
- params_members[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[S_CORRELATION_ID] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[kCode] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[kMessage] = CObjectSchemaItem::SMember(
- CStringSchemaItem::create(), true);
+ params_members[S_PROTOCOL_VERSION] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[S_PROTOCOL_TYPE] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[S_CORRELATION_ID] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[kCode] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[kMessage] =
+ CObjectSchemaItem::SMember(CStringSchemaItem::create(), true);
CObjectSchemaItem::Members root_members_map;
root_members_map[NsSmartDeviceLink::NsJSONHandler::strings::S_PARAMS] =
@@ -172,68 +194,52 @@ void CSmartFactoryTest::InitFunctionSchemes(
CSmartSchema error_response_schema(
CObjectSchemaItem::create(root_members_map));
- functions_schemes_.insert(
- std::make_pair(
- SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
- FunctionIdTest::Function1, MessageTypeTest::error_response),
- error_response_schema));
- functions_schemes_.insert(
- std::make_pair(
- SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
- FunctionIdTest::Function1, MessageTypeTest::request),
- InitFunction_Function1_request(function_id_items,
- message_type_items)));
- functions_schemes_.insert(
- std::make_pair(
- SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
- FunctionIdTest::Function1, MessageTypeTest::response),
- InitFunction_Function1_response(struct_schema_items,
- function_id_items,
- message_type_items)));
-
- functions_schemes_.insert(
- std::make_pair(
- SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
- FunctionIdTest::Function2, MessageTypeTest::error_response),
- error_response_schema));
- functions_schemes_.insert(
- std::make_pair(
- SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
- FunctionIdTest::Function2, MessageTypeTest::request),
- InitFunction_Function2_request(function_id_items,
- message_type_items)));
- functions_schemes_.insert(
- std::make_pair(
- SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
- FunctionIdTest::Function2, MessageTypeTest::response),
- InitFunction_Function2_response(struct_schema_items,
- function_id_items,
- message_type_items)));
-
- functions_schemes_.insert(
- std::make_pair(
- SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
- FunctionIdTest::Function3, MessageTypeTest::error_response),
- error_response_schema));
- functions_schemes_.insert(
- std::make_pair(
- SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
- FunctionIdTest::Function3, MessageTypeTest::request),
- InitFunction_Function3_request(function_id_items,
- message_type_items)));
- functions_schemes_.insert(
- std::make_pair(
- SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
- FunctionIdTest::Function3, MessageTypeTest::response),
- InitFunction_Function3_response(struct_schema_items,
- function_id_items,
- message_type_items)));
+ functions_schemes_.insert(std::make_pair(
+ SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
+ FunctionIdTest::Function1, MessageTypeTest::error_response),
+ error_response_schema));
+ functions_schemes_.insert(std::make_pair(
+ SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
+ FunctionIdTest::Function1, MessageTypeTest::request),
+ InitFunction_Function1_request(function_id_items, message_type_items)));
+ functions_schemes_.insert(std::make_pair(
+ SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
+ FunctionIdTest::Function1, MessageTypeTest::response),
+ InitFunction_Function1_response(
+ struct_schema_items, function_id_items, message_type_items)));
+
+ functions_schemes_.insert(std::make_pair(
+ SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
+ FunctionIdTest::Function2, MessageTypeTest::error_response),
+ error_response_schema));
+ functions_schemes_.insert(std::make_pair(
+ SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
+ FunctionIdTest::Function2, MessageTypeTest::request),
+ InitFunction_Function2_request(function_id_items, message_type_items)));
+ functions_schemes_.insert(std::make_pair(
+ SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
+ FunctionIdTest::Function2, MessageTypeTest::response),
+ InitFunction_Function2_response(
+ struct_schema_items, function_id_items, message_type_items)));
+
+ functions_schemes_.insert(std::make_pair(
+ SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
+ FunctionIdTest::Function3, MessageTypeTest::error_response),
+ error_response_schema));
+ functions_schemes_.insert(std::make_pair(
+ SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
+ FunctionIdTest::Function3, MessageTypeTest::request),
+ InitFunction_Function3_request(function_id_items, message_type_items)));
+ functions_schemes_.insert(std::make_pair(
+ SmartSchemaKey<FunctionIdTest::eType, MessageTypeTest::eType>(
+ FunctionIdTest::Function3, MessageTypeTest::response),
+ InitFunction_Function3_response(
+ struct_schema_items, function_id_items, message_type_items)));
}
CSmartSchema CSmartFactoryTest::InitFunction_Function1_request(
- const std::set<FunctionIdTest::eType> &function_id_items,
- const std::set<MessageTypeTest::eType> &message_type_items) {
-
+ const std::set<FunctionIdTest::eType>& function_id_items,
+ const std::set<MessageTypeTest::eType>& message_type_items) {
CObjectSchemaItem::Members schema_members;
CObjectSchemaItem::Members params_members;
@@ -242,12 +248,12 @@ CSmartSchema CSmartFactoryTest::InitFunction_Function1_request(
params_members[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember(
TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items),
true);
- params_members[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[S_CORRELATION_ID] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
+ params_members[S_PROTOCOL_VERSION] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[S_PROTOCOL_TYPE] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[S_CORRELATION_ID] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
CObjectSchemaItem::Members root_members_map;
root_members_map[S_MSG_PARAMS] = CObjectSchemaItem::SMember(
@@ -259,17 +265,17 @@ CSmartSchema CSmartFactoryTest::InitFunction_Function1_request(
}
CSmartSchema CSmartFactoryTest::InitFunction_Function1_response(
- const TStructsSchemaItems &struct_schema_items,
- const std::set<FunctionIdTest::eType> &function_id_items,
- const std::set<MessageTypeTest::eType> &message_type_items) {
+ const TStructsSchemaItems& struct_schema_items,
+ const std::set<FunctionIdTest::eType>& function_id_items,
+ const std::set<MessageTypeTest::eType>& message_type_items) {
// Function parameter available.
- utils::SharedPtr<ISchemaItem> available_SchemaItem = CBoolSchemaItem::create(
- TSchemaItemParameter<bool>());
+ utils::SharedPtr<ISchemaItem> available_SchemaItem =
+ CBoolSchemaItem::create(TSchemaItemParameter<bool>());
CObjectSchemaItem::Members schema_members;
- schema_members["available"] = CObjectSchemaItem::SMember(available_SchemaItem,
- true);
+ schema_members["available"] =
+ CObjectSchemaItem::SMember(available_SchemaItem, true);
CObjectSchemaItem::Members params_members;
params_members[S_FUNCTION_ID] = CObjectSchemaItem::SMember(
@@ -277,14 +283,14 @@ CSmartSchema CSmartFactoryTest::InitFunction_Function1_response(
params_members[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember(
TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items),
true);
- params_members[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[S_CORRELATION_ID] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[kCode] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
+ params_members[S_PROTOCOL_VERSION] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[S_PROTOCOL_TYPE] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[S_CORRELATION_ID] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[kCode] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
CObjectSchemaItem::Members root_members_map;
root_members_map[S_MSG_PARAMS] = CObjectSchemaItem::SMember(
@@ -296,8 +302,8 @@ CSmartSchema CSmartFactoryTest::InitFunction_Function1_response(
}
CSmartSchema CSmartFactoryTest::InitFunction_Function2_request(
- const std::set<FunctionIdTest::eType> &function_id_items,
- const std::set<MessageTypeTest::eType> &message_type_items) {
+ const std::set<FunctionIdTest::eType>& function_id_items,
+ const std::set<MessageTypeTest::eType>& message_type_items) {
CObjectSchemaItem::Members schema_members;
CObjectSchemaItem::Members params_members;
@@ -306,12 +312,12 @@ CSmartSchema CSmartFactoryTest::InitFunction_Function2_request(
params_members[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember(
TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items),
true);
- params_members[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[S_CORRELATION_ID] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
+ params_members[S_PROTOCOL_VERSION] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[S_PROTOCOL_TYPE] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[S_CORRELATION_ID] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
CObjectSchemaItem::Members root_members_map;
root_members_map[S_MSG_PARAMS] = CObjectSchemaItem::SMember(
@@ -323,17 +329,17 @@ CSmartSchema CSmartFactoryTest::InitFunction_Function2_request(
}
CSmartSchema CSmartFactoryTest::InitFunction_Function2_response(
- const TStructsSchemaItems &struct_schema_items,
- const std::set<FunctionIdTest::eType> &function_id_items,
- const std::set<MessageTypeTest::eType> &message_type_items) {
+ const TStructsSchemaItems& struct_schema_items,
+ const std::set<FunctionIdTest::eType>& function_id_items,
+ const std::set<MessageTypeTest::eType>& message_type_items) {
// Function parameter available.
- utils::SharedPtr<ISchemaItem> available_SchemaItem = CBoolSchemaItem::create(
- TSchemaItemParameter<bool>());
+ utils::SharedPtr<ISchemaItem> available_SchemaItem =
+ CBoolSchemaItem::create(TSchemaItemParameter<bool>());
CObjectSchemaItem::Members schema_members;
- schema_members["available"] = CObjectSchemaItem::SMember(available_SchemaItem,
- true);
+ schema_members["available"] =
+ CObjectSchemaItem::SMember(available_SchemaItem, true);
CObjectSchemaItem::Members params_members;
params_members[S_FUNCTION_ID] = CObjectSchemaItem::SMember(
@@ -341,14 +347,14 @@ CSmartSchema CSmartFactoryTest::InitFunction_Function2_response(
params_members[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember(
TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items),
true);
- params_members[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[S_CORRELATION_ID] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[kCode] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
+ params_members[S_PROTOCOL_VERSION] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[S_PROTOCOL_TYPE] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[S_CORRELATION_ID] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[kCode] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
CObjectSchemaItem::Members root_members_map;
root_members_map[S_MSG_PARAMS] = CObjectSchemaItem::SMember(
@@ -360,8 +366,8 @@ CSmartSchema CSmartFactoryTest::InitFunction_Function2_response(
}
CSmartSchema CSmartFactoryTest::InitFunction_Function3_request(
- const std::set<FunctionIdTest::eType> &function_id_items,
- const std::set<MessageTypeTest::eType> &message_type_items) {
+ const std::set<FunctionIdTest::eType>& function_id_items,
+ const std::set<MessageTypeTest::eType>& message_type_items) {
CObjectSchemaItem::Members schema_members;
CObjectSchemaItem::Members params_members;
@@ -370,12 +376,12 @@ CSmartSchema CSmartFactoryTest::InitFunction_Function3_request(
params_members[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember(
TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items),
true);
- params_members[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[S_CORRELATION_ID] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
+ params_members[S_PROTOCOL_VERSION] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[S_PROTOCOL_TYPE] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[S_CORRELATION_ID] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
CObjectSchemaItem::Members root_members_map;
root_members_map[S_MSG_PARAMS] = CObjectSchemaItem::SMember(
@@ -387,19 +393,19 @@ CSmartSchema CSmartFactoryTest::InitFunction_Function3_request(
}
CSmartSchema CSmartFactoryTest::InitFunction_Function3_response(
- const TStructsSchemaItems &struct_schema_items,
- const std::set<FunctionIdTest::eType> &function_id_items,
- const std::set<MessageTypeTest::eType> &message_type_items) {
+ const TStructsSchemaItems& struct_schema_items,
+ const std::set<FunctionIdTest::eType>& function_id_items,
+ const std::set<MessageTypeTest::eType>& message_type_items) {
// Function parameter available.
//
// Must be true if VR is present and ready to communicate with SDL.
- utils::SharedPtr<ISchemaItem> available_SchemaItem = CBoolSchemaItem::create(
- TSchemaItemParameter<bool>());
+ utils::SharedPtr<ISchemaItem> available_SchemaItem =
+ CBoolSchemaItem::create(TSchemaItemParameter<bool>());
CObjectSchemaItem::Members schema_members;
- schema_members["available"] = CObjectSchemaItem::SMember(available_SchemaItem,
- true);
+ schema_members["available"] =
+ CObjectSchemaItem::SMember(available_SchemaItem, true);
CObjectSchemaItem::Members params_members;
params_members[S_FUNCTION_ID] = CObjectSchemaItem::SMember(
@@ -407,14 +413,14 @@ CSmartSchema CSmartFactoryTest::InitFunction_Function3_response(
params_members[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember(
TEnumSchemaItem<MessageTypeTest::eType>::create(message_type_items),
true);
- params_members[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[S_CORRELATION_ID] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
- params_members[kCode] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
+ params_members[S_PROTOCOL_VERSION] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[S_PROTOCOL_TYPE] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[S_CORRELATION_ID] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ params_members[kCode] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
CObjectSchemaItem::Members root_members_map;
root_members_map[S_MSG_PARAMS] = CObjectSchemaItem::SMember(
@@ -426,13 +432,14 @@ CSmartSchema CSmartFactoryTest::InitFunction_Function3_response(
}
utils::SharedPtr<ISchemaItem> CSmartFactoryTest::InitStructSchemaItem_Common_1(
- TStructsSchemaItems &struct_schema_items) {
+ TStructsSchemaItems& struct_schema_items) {
// Struct member text.
//
// Text to display
- utils::SharedPtr<ISchemaItem> text_SchemaItem = CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(1), TSchemaItemParameter<size_t>(500),
- TSchemaItemParameter<std::string>());
+ utils::SharedPtr<ISchemaItem> text_SchemaItem =
+ CStringSchemaItem::create(TSchemaItemParameter<size_t>(1),
+ TSchemaItemParameter<size_t>(500),
+ TSchemaItemParameter<std::string>());
// Struct member image.
//
@@ -454,8 +461,8 @@ utils::SharedPtr<ISchemaItem> CSmartFactoryTest::InitStructSchemaItem_Common_1(
CObjectSchemaItem::Members schema_members;
schema_members["text"] = CObjectSchemaItem::SMember(text_SchemaItem, true);
- schema_members["position"] = CObjectSchemaItem::SMember(position_SchemaItem,
- true);
+ schema_members["position"] =
+ CObjectSchemaItem::SMember(position_SchemaItem, true);
CObjectSchemaItem::Members root_members_map;
root_members_map[""] = CObjectSchemaItem::SMember(
@@ -465,13 +472,15 @@ utils::SharedPtr<ISchemaItem> CSmartFactoryTest::InitStructSchemaItem_Common_1(
return CObjectSchemaItem::create(schema_members);
}
-utils::SharedPtr<ISchemaItem> CSmartFactoryTest::InitStructSchemaItem_Common_2() {
+utils::SharedPtr<ISchemaItem>
+CSmartFactoryTest::InitStructSchemaItem_Common_2() {
// Struct member text.
//
// Text to display
- utils::SharedPtr<ISchemaItem> text_SchemaItem = CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(1), TSchemaItemParameter<size_t>(500),
- TSchemaItemParameter<std::string>());
+ utils::SharedPtr<ISchemaItem> text_SchemaItem =
+ CStringSchemaItem::create(TSchemaItemParameter<size_t>(1),
+ TSchemaItemParameter<size_t>(500),
+ TSchemaItemParameter<std::string>());
// Struct member position.
//
// Position to display item
@@ -482,20 +491,20 @@ utils::SharedPtr<ISchemaItem> CSmartFactoryTest::InitStructSchemaItem_Common_2()
CObjectSchemaItem::Members schema_members;
schema_members["text"] = CObjectSchemaItem::SMember(text_SchemaItem, true);
- schema_members["position"] = CObjectSchemaItem::SMember(position_SchemaItem,
- true);
+ schema_members["position"] =
+ CObjectSchemaItem::SMember(position_SchemaItem, true);
return CObjectSchemaItem::create(schema_members);
}
-utils::SharedPtr<ISchemaItem> CSmartFactoryTest::ProvideObjectSchemaItemForStruct(
- TStructsSchemaItems &struct_schema_items,
+utils::SharedPtr<ISchemaItem>
+CSmartFactoryTest::ProvideObjectSchemaItemForStruct(
+ TStructsSchemaItems& struct_schema_items,
const StructIdentifiersTest::eType struct_id) {
- const TStructsSchemaItems::const_iterator it = struct_schema_items.find(
- struct_id);
+ const TStructsSchemaItems::const_iterator it =
+ struct_schema_items.find(struct_id);
if (it != struct_schema_items.end()) {
return it->second;
}
return NsSmartDeviceLink::NsSmartObjects::CAlwaysFalseSchemaItem::create();
}
-
diff --git a/src/components/formatters/test/src/create_smartSchema.cc b/src/components/formatters/test/src/create_smartSchema.cc
index 9d44567dcd..75663d4488 100644
--- a/src/components/formatters/test/src/create_smartSchema.cc
+++ b/src/components/formatters/test/src/create_smartSchema.cc
@@ -30,7 +30,7 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include "create_smartSchema.h"
+#include "formatters/create_smartSchema.h"
namespace test {
namespace components {
namespace formatters {
@@ -39,82 +39,105 @@ using namespace NsSmartDeviceLink::NsJSONHandler::strings;
using namespace NsSmartDeviceLink::NsJSONHandler::Formatters;
using namespace NsSmartDeviceLink::NsSmartObjects;
-template<>
-const EnumConversionHelper<FunctionIDTest::eType>::EnumToCStringMap EnumConversionHelper<
- test::components::formatters::FunctionIDTest::eType>::enum_to_cstring_map_ =
- EnumConversionHelper<test::components::formatters::FunctionIDTest::eType>::InitEnumToCStringMap();
-
-template<>
-const EnumConversionHelper<FunctionIDTest::eType>::CStringToEnumMap EnumConversionHelper<
- test::components::formatters::FunctionIDTest::eType>::cstring_to_enum_map_ =
- EnumConversionHelper<test::components::formatters::FunctionIDTest::eType>::InitCStringToEnumMap();
-
-template<>
-const char* const EnumConversionHelper<FunctionIDTest::eType>::cstring_values_[] =
- { "RegisterAppInterface", "UnregisterAppInterface", "SetGlobalProperties" };
-
-template<>
-const FunctionIDTest::eType EnumConversionHelper<FunctionIDTest::eType>::enum_values_[] =
- { test::components::formatters::FunctionIDTest::RegisterAppInterface,
+template <>
+const EnumConversionHelper<FunctionIDTest::eType>::EnumToCStringMap
+ EnumConversionHelper<test::components::formatters::FunctionIDTest::eType>::
+ enum_to_cstring_map_ = EnumConversionHelper<
+ test::components::formatters::FunctionIDTest::eType>::
+ InitEnumToCStringMap();
+
+template <>
+const EnumConversionHelper<FunctionIDTest::eType>::CStringToEnumMap
+ EnumConversionHelper<test::components::formatters::FunctionIDTest::eType>::
+ cstring_to_enum_map_ = EnumConversionHelper<
+ test::components::formatters::FunctionIDTest::eType>::
+ InitCStringToEnumMap();
+
+template <>
+const char* const
+ EnumConversionHelper<FunctionIDTest::eType>::cstring_values_[] = {
+ "RegisterAppInterface",
+ "UnregisterAppInterface",
+ "SetGlobalProperties"};
+
+template <>
+const FunctionIDTest::eType
+ EnumConversionHelper<FunctionIDTest::eType>::enum_values_[] = {
+ test::components::formatters::FunctionIDTest::RegisterAppInterface,
test::components::formatters::FunctionIDTest::UnregisterAppInterface,
- test::components::formatters::FunctionIDTest::SetGlobalProperties };
-
-template<>
-const EnumConversionHelper<Language::eType>::EnumToCStringMap EnumConversionHelper<
- test::components::formatters::Language::eType>::enum_to_cstring_map_ =
- EnumConversionHelper<test::components::formatters::Language::eType>::InitEnumToCStringMap();
-
-template<>
-const EnumConversionHelper<Language::eType>::CStringToEnumMap EnumConversionHelper<
- test::components::formatters::Language::eType>::cstring_to_enum_map_ =
- EnumConversionHelper<test::components::formatters::Language::eType>::InitCStringToEnumMap();
-
-template<>
-const char* const EnumConversionHelper<Language::eType>::cstring_values_[] =
- { "EN_EU", "RU_RU"};
-
-template<>
-const Language::eType EnumConversionHelper<Language::eType>::enum_values_[] =
- { test::components::formatters::Language::EN_EU,
- test::components::formatters::Language::RU_RU};
-
-template<>
-const EnumConversionHelper<SpeechCapabilities::eType>::EnumToCStringMap EnumConversionHelper<
- test::components::formatters::SpeechCapabilities::eType>::enum_to_cstring_map_ =
- EnumConversionHelper<test::components::formatters::SpeechCapabilities::eType>::InitEnumToCStringMap();
-
-template<>
-const EnumConversionHelper<SpeechCapabilities::eType>::CStringToEnumMap EnumConversionHelper<
- test::components::formatters::SpeechCapabilities::eType>::cstring_to_enum_map_ =
- EnumConversionHelper<test::components::formatters::SpeechCapabilities::eType>::InitCStringToEnumMap();
-
-template<>
-const char* const EnumConversionHelper<SpeechCapabilities::eType>::cstring_values_[] =
- { "SC_TEXT"};
-
-template<>
-const SpeechCapabilities::eType EnumConversionHelper<SpeechCapabilities::eType>::enum_values_[] =
- { test::components::formatters::SpeechCapabilities::SC_TEXT};
-
-template<>
-const EnumConversionHelper<AppTypeTest::eType>::EnumToCStringMap EnumConversionHelper<
- test::components::formatters::AppTypeTest::eType>::enum_to_cstring_map_ =
- EnumConversionHelper<test::components::formatters::AppTypeTest::eType>::InitEnumToCStringMap();
-
-template<>
-const EnumConversionHelper<AppTypeTest::eType>::CStringToEnumMap EnumConversionHelper<
- test::components::formatters::AppTypeTest::eType>::cstring_to_enum_map_ =
- EnumConversionHelper<test::components::formatters::AppTypeTest::eType>::InitCStringToEnumMap();
-
-template<>
+ test::components::formatters::FunctionIDTest::SetGlobalProperties};
+
+template <>
+const EnumConversionHelper<Language::eType>::EnumToCStringMap
+ EnumConversionHelper<
+ test::components::formatters::Language::eType>::enum_to_cstring_map_ =
+ EnumConversionHelper<test::components::formatters::Language::eType>::
+ InitEnumToCStringMap();
+
+template <>
+const EnumConversionHelper<Language::eType>::CStringToEnumMap
+ EnumConversionHelper<
+ test::components::formatters::Language::eType>::cstring_to_enum_map_ =
+ EnumConversionHelper<test::components::formatters::Language::eType>::
+ InitCStringToEnumMap();
+
+template <>
+const char* const EnumConversionHelper<Language::eType>::cstring_values_[] = {
+ "EN_EU", "RU_RU"};
+
+template <>
+const Language::eType EnumConversionHelper<Language::eType>::enum_values_[] = {
+ test::components::formatters::Language::EN_EU,
+ test::components::formatters::Language::RU_RU};
+
+template <>
+const EnumConversionHelper<SpeechCapabilities::eType>::EnumToCStringMap
+ EnumConversionHelper<test::components::formatters::SpeechCapabilities::
+ eType>::enum_to_cstring_map_ =
+ EnumConversionHelper<test::components::formatters::SpeechCapabilities::
+ eType>::InitEnumToCStringMap();
+
+template <>
+const EnumConversionHelper<SpeechCapabilities::eType>::CStringToEnumMap
+ EnumConversionHelper<test::components::formatters::SpeechCapabilities::
+ eType>::cstring_to_enum_map_ =
+ EnumConversionHelper<test::components::formatters::SpeechCapabilities::
+ eType>::InitCStringToEnumMap();
+
+template <>
+const char* const
+ EnumConversionHelper<SpeechCapabilities::eType>::cstring_values_[] = {
+ "SC_TEXT"};
+
+template <>
+const SpeechCapabilities::eType
+ EnumConversionHelper<SpeechCapabilities::eType>::enum_values_[] = {
+ test::components::formatters::SpeechCapabilities::SC_TEXT};
+
+template <>
+const EnumConversionHelper<AppTypeTest::eType>::EnumToCStringMap
+ EnumConversionHelper<test::components::formatters::AppTypeTest::eType>::
+ enum_to_cstring_map_ = EnumConversionHelper<
+ test::components::formatters::AppTypeTest::eType>::
+ InitEnumToCStringMap();
+
+template <>
+const EnumConversionHelper<AppTypeTest::eType>::CStringToEnumMap
+ EnumConversionHelper<test::components::formatters::AppTypeTest::eType>::
+ cstring_to_enum_map_ = EnumConversionHelper<
+ test::components::formatters::AppTypeTest::eType>::
+ InitCStringToEnumMap();
+
+template <>
const char* const EnumConversionHelper<AppTypeTest::eType>::cstring_values_[] =
- { "SYSTEM", "MEDIA"};
+ {"SYSTEM", "MEDIA"};
-template<>
-const AppTypeTest::eType EnumConversionHelper<AppTypeTest::eType>::enum_values_[] =
- { test::components::formatters::AppTypeTest::SYSTEM,
- test::components::formatters::AppTypeTest::MEDIA,
- };
+template <>
+const AppTypeTest::eType
+ EnumConversionHelper<AppTypeTest::eType>::enum_values_[] = {
+ test::components::formatters::AppTypeTest::SYSTEM,
+ test::components::formatters::AppTypeTest::MEDIA,
+};
CSmartSchema initObjectSchema() {
std::set<TestType::eType> resultCode_allowedEnumSubsetValues;
@@ -147,50 +170,52 @@ CSmartSchema initObjectSchema() {
messageType_allowedEnumSubsetValues.insert(MessageTypeTest::notification);
// Create result item
- ISchemaItemPtr success_SchemaItem = CBoolSchemaItem::create(
- TSchemaItemParameter<bool>());
+ ISchemaItemPtr success_SchemaItem =
+ CBoolSchemaItem::create(TSchemaItemParameter<bool>());
ISchemaItemPtr resultCode_SchemaItem =
TEnumSchemaItem<TestType::eType>::create(
resultCode_allowedEnumSubsetValues,
TSchemaItemParameter<TestType::eType>());
// Create info value with min 0 length and max 1000
- ISchemaItemPtr info_SchemaItem = CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000),
- TSchemaItemParameter<std::string>());
+ ISchemaItemPtr info_SchemaItem =
+ CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(1000),
+ TSchemaItemParameter<std::string>());
- ISchemaItemPtr tryAgainTime_SchemaItem = TNumberSchemaItem<int>::create(
- TSchemaItemParameter<int>(0), TSchemaItemParameter<int>(2000000000),
- TSchemaItemParameter<int>());
+ ISchemaItemPtr tryAgainTime_SchemaItem =
+ TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(0),
+ TSchemaItemParameter<int>(2000000000),
+ TSchemaItemParameter<int>());
// Map of parameters
std::map<std::string, CObjectSchemaItem::SMember> schemaMembersMap;
- schemaMembersMap["success"] = CObjectSchemaItem::SMember(success_SchemaItem,
- false);
- schemaMembersMap["resultCode"] = CObjectSchemaItem::SMember(
- resultCode_SchemaItem, false);
+ schemaMembersMap["success"] =
+ CObjectSchemaItem::SMember(success_SchemaItem, false);
+ schemaMembersMap["resultCode"] =
+ CObjectSchemaItem::SMember(resultCode_SchemaItem, false);
schemaMembersMap["info"] = CObjectSchemaItem::SMember(info_SchemaItem, false);
- schemaMembersMap["tryAgainTime"] = CObjectSchemaItem::SMember(
- tryAgainTime_SchemaItem, false);
+ schemaMembersMap["tryAgainTime"] =
+ CObjectSchemaItem::SMember(tryAgainTime_SchemaItem, false);
std::map<std::string, CObjectSchemaItem::SMember> paramsMembersMap;
- paramsMembersMap[S_FUNCTION_ID] = CObjectSchemaItem::SMember(
- TEnumSchemaItem<FunctionIDTest::eType>::create(
- functionId_allowedEnumSubsetValues),
- true);
+ paramsMembersMap[S_FUNCTION_ID] =
+ CObjectSchemaItem::SMember(TEnumSchemaItem<FunctionIDTest::eType>::create(
+ functionId_allowedEnumSubsetValues),
+ true);
paramsMembersMap[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember(
TEnumSchemaItem<MessageTypeTest::eType>::create(
messageType_allowedEnumSubsetValues),
true);
- paramsMembersMap[S_CORRELATION_ID] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
+ paramsMembersMap[S_CORRELATION_ID] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
paramsMembersMap[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember(
TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(1),
TSchemaItemParameter<int>(2)),
true);
- paramsMembersMap[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
+ paramsMembersMap[S_PROTOCOL_TYPE] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
std::map<std::string, CObjectSchemaItem::SMember> rootMembersMap;
rootMembersMap[S_MSG_PARAMS] = CObjectSchemaItem::SMember(
@@ -200,7 +225,6 @@ CSmartSchema initObjectSchema() {
return CSmartSchema(CObjectSchemaItem::create(rootMembersMap));
};
-
CSmartSchema initSchemaForMetaFormatter() {
std::set<TestType::eType> resultCode_allowedEnumSubsetValues;
resultCode_allowedEnumSubsetValues.insert(
@@ -229,13 +253,14 @@ CSmartSchema initSchemaForMetaFormatter() {
languageDesired_allowedEnumSubsetValues.insert(Language::RU_RU);
languageDesired_allowedEnumSubsetValues.insert(Language::EN_EU);
-
std::set<AppTypeTest::eType> appType_allowedEnumSubsetValues;
appType_allowedEnumSubsetValues.insert(AppTypeTest::SYSTEM);
appType_allowedEnumSubsetValues.insert(AppTypeTest::MEDIA);
- std::set<SpeechCapabilities::eType> speechCapabilities_allowedEnumSubsetValues;
- speechCapabilities_allowedEnumSubsetValues.insert(SpeechCapabilities::SC_TEXT);
+ std::set<SpeechCapabilities::eType>
+ speechCapabilities_allowedEnumSubsetValues;
+ speechCapabilities_allowedEnumSubsetValues.insert(
+ SpeechCapabilities::SC_TEXT);
// Possible message types
std::set<MessageTypeTest::eType> messageType_allowedEnumSubsetValues;
@@ -244,21 +269,25 @@ CSmartSchema initSchemaForMetaFormatter() {
messageType_allowedEnumSubsetValues.insert(MessageTypeTest::notification);
// Create param items
- ISchemaItemPtr appID_SchemaItem = CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000),
- TSchemaItemParameter<std::string>());
- ISchemaItemPtr appName_SchemaItem = CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000),
- TSchemaItemParameter<std::string>());
- ISchemaItemPtr isMediaApplication_SchemaItem = CBoolSchemaItem::create(
- TSchemaItemParameter<bool>());
- ISchemaItemPtr ngnMediaScreenAppName_SchemaItem = CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000),
- TSchemaItemParameter<std::string>());
-
- ISchemaItemPtr ttsNameItem_SchemaItem = CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000),
- TSchemaItemParameter<std::string>());
+ ISchemaItemPtr appID_SchemaItem =
+ CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(1000),
+ TSchemaItemParameter<std::string>());
+ ISchemaItemPtr appName_SchemaItem =
+ CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(1000),
+ TSchemaItemParameter<std::string>());
+ ISchemaItemPtr isMediaApplication_SchemaItem =
+ CBoolSchemaItem::create(TSchemaItemParameter<bool>());
+ ISchemaItemPtr ngnMediaScreenAppName_SchemaItem =
+ CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(1000),
+ TSchemaItemParameter<std::string>());
+
+ ISchemaItemPtr ttsNameItem_SchemaItem =
+ CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(1000),
+ TSchemaItemParameter<std::string>());
ISchemaItemPtr ttstype_SchemaItem =
TEnumSchemaItem<SpeechCapabilities::eType>::create(
@@ -266,10 +295,9 @@ CSmartSchema initSchemaForMetaFormatter() {
TSchemaItemParameter<SpeechCapabilities::eType>());
std::map<std::string, CObjectSchemaItem::SMember> ttsMap;
- ttsMap["text"]=CObjectSchemaItem::SMember(ttsNameItem_SchemaItem,
- false);
- ttsMap["type"]=CObjectSchemaItem::SMember(ttstype_SchemaItem,
- false);;
+ ttsMap["text"] = CObjectSchemaItem::SMember(ttsNameItem_SchemaItem, false);
+ ttsMap["type"] = CObjectSchemaItem::SMember(ttstype_SchemaItem, false);
+ ;
ISchemaItemPtr hmiDisplayLanguageDesired_SchemaItem =
TEnumSchemaItem<Language::eType>::create(
@@ -281,9 +309,10 @@ CSmartSchema initSchemaForMetaFormatter() {
languageDesired_allowedEnumSubsetValues,
TSchemaItemParameter<Language::eType>());
- ISchemaItemPtr vrElementSchemaItem = CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000),
- TSchemaItemParameter<std::string>());
+ ISchemaItemPtr vrElementSchemaItem =
+ CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(1000),
+ TSchemaItemParameter<std::string>());
ISchemaItemPtr appTypeElementSchemaItem =
TEnumSchemaItem<AppTypeTest::eType>::create(
@@ -294,75 +323,81 @@ CSmartSchema initSchemaForMetaFormatter() {
ISchemaItemPtr ttsName_SchemaItem =
CArraySchemaItem::create(ttsElementSchemaItem,
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000));
+ TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(1000));
ISchemaItemPtr vrSynonyms_SchemaItem =
CArraySchemaItem::create(vrElementSchemaItem,
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000));
+ TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(1000));
ISchemaItemPtr appType_SchemaItem =
CArraySchemaItem::create(appTypeElementSchemaItem,
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000));
-
+ TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(1000));
ISchemaItemPtr majorVersion_SchemaItem = TNumberSchemaItem<int>::create();
ISchemaItemPtr minorVersion_SchemaItem = TNumberSchemaItem<int>::create();
- ISchemaItemPtr syncMsg_SchemaItem =CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000),
- TSchemaItemParameter<std::string>());
+ ISchemaItemPtr syncMsg_SchemaItem =
+ CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(1000),
+ TSchemaItemParameter<std::string>());
ISchemaItemPtr syncMsgVersion_SchemaItem =
CArraySchemaItem::create(syncMsg_SchemaItem,
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000));
+ TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(1000));
// Creation map for syncMsgVersion
std::map<std::string, CObjectSchemaItem::SMember> schemaSyncMsgVersionMap;
- schemaSyncMsgVersionMap["majorVersion"]=CObjectSchemaItem::SMember(majorVersion_SchemaItem,
- false);
- schemaSyncMsgVersionMap["minorVersion"]=CObjectSchemaItem::SMember(minorVersion_SchemaItem,
- false);;
+ schemaSyncMsgVersionMap["majorVersion"] =
+ CObjectSchemaItem::SMember(majorVersion_SchemaItem, false);
+ schemaSyncMsgVersionMap["minorVersion"] =
+ CObjectSchemaItem::SMember(minorVersion_SchemaItem, false);
+ ;
// Map of parameters
std::map<std::string, CObjectSchemaItem::SMember> schemaMembersMap;
- schemaMembersMap["appID"] = CObjectSchemaItem::SMember(appID_SchemaItem,
- false);
- schemaMembersMap["appName"] = CObjectSchemaItem::SMember(appName_SchemaItem,
- false);
- schemaMembersMap["appType"] = CObjectSchemaItem::SMember(appType_SchemaItem,
- false);
- schemaMembersMap["hmiDisplayLanguageDesired"] = CObjectSchemaItem::SMember(hmiDisplayLanguageDesired_SchemaItem,
- false);
- schemaMembersMap["isMediaApplication"] = CObjectSchemaItem::SMember(isMediaApplication_SchemaItem,
- false);
- schemaMembersMap["languageDesired"] = CObjectSchemaItem::SMember(languageDesired_SchemaItem,
- false);
- schemaMembersMap["ngnMediaScreenAppName"] = CObjectSchemaItem::SMember(ngnMediaScreenAppName_SchemaItem,
- false);
- schemaMembersMap["syncMsgVersion"] = CObjectSchemaItem::SMember(CObjectSchemaItem::create(schemaSyncMsgVersionMap),
- false);
- schemaMembersMap["ttsName"] = CObjectSchemaItem::SMember(ttsName_SchemaItem,
- false);
- schemaMembersMap["vrSynonyms"] = CObjectSchemaItem::SMember(vrSynonyms_SchemaItem, false);
+ schemaMembersMap["appID"] =
+ CObjectSchemaItem::SMember(appID_SchemaItem, false);
+ schemaMembersMap["appName"] =
+ CObjectSchemaItem::SMember(appName_SchemaItem, false);
+ schemaMembersMap["appType"] =
+ CObjectSchemaItem::SMember(appType_SchemaItem, false);
+ schemaMembersMap["hmiDisplayLanguageDesired"] =
+ CObjectSchemaItem::SMember(hmiDisplayLanguageDesired_SchemaItem, false);
+ schemaMembersMap["isMediaApplication"] =
+ CObjectSchemaItem::SMember(isMediaApplication_SchemaItem, false);
+ schemaMembersMap["languageDesired"] =
+ CObjectSchemaItem::SMember(languageDesired_SchemaItem, false);
+ schemaMembersMap["ngnMediaScreenAppName"] =
+ CObjectSchemaItem::SMember(ngnMediaScreenAppName_SchemaItem, false);
+ schemaMembersMap["syncMsgVersion"] = CObjectSchemaItem::SMember(
+ CObjectSchemaItem::create(schemaSyncMsgVersionMap), false);
+ schemaMembersMap["ttsName"] =
+ CObjectSchemaItem::SMember(ttsName_SchemaItem, false);
+ schemaMembersMap["vrSynonyms"] =
+ CObjectSchemaItem::SMember(vrSynonyms_SchemaItem, false);
std::map<std::string, CObjectSchemaItem::SMember> paramsMembersMap;
- paramsMembersMap[S_FUNCTION_ID] = CObjectSchemaItem::SMember(
- TEnumSchemaItem<FunctionIDTest::eType>::create(
- functionId_allowedEnumSubsetValues),
- true);
+ paramsMembersMap[S_FUNCTION_ID] =
+ CObjectSchemaItem::SMember(TEnumSchemaItem<FunctionIDTest::eType>::create(
+ functionId_allowedEnumSubsetValues),
+ true);
paramsMembersMap[S_MESSAGE_TYPE] = CObjectSchemaItem::SMember(
TEnumSchemaItem<MessageTypeTest::eType>::create(
messageType_allowedEnumSubsetValues),
true);
- paramsMembersMap[S_CORRELATION_ID] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
+ paramsMembersMap[S_CORRELATION_ID] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
paramsMembersMap[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember(
TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(1),
TSchemaItemParameter<int>(2)),
true);
- paramsMembersMap[S_PROTOCOL_TYPE] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
+ paramsMembersMap[S_PROTOCOL_TYPE] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
std::map<std::string, CObjectSchemaItem::SMember> rootMembersMap;
rootMembersMap[S_MSG_PARAMS] = CObjectSchemaItem::SMember(
@@ -372,8 +407,6 @@ CSmartSchema initSchemaForMetaFormatter() {
return CSmartSchema(CObjectSchemaItem::create(rootMembersMap));
};
-
-
} // namespace formatters
} // namespace components
} // namespace test
diff --git a/src/components/formatters/test/src/meta_formatter_test_helper.cc b/src/components/formatters/test/src/meta_formatter_test_helper.cc
index 3445d948bb..a963c08a52 100644
--- a/src/components/formatters/test/src/meta_formatter_test_helper.cc
+++ b/src/components/formatters/test/src/meta_formatter_test_helper.cc
@@ -30,7 +30,7 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "gtest/gtest.h"
-#include "meta_formatter_test_helper.h"
+#include "formatters/meta_formatter_test_helper.h"
namespace test {
namespace components {
@@ -58,7 +58,6 @@ void CMetaFormatterTestHelper::TearDown() {
void CMetaFormatterTestHelper::AnyObjectToJsonString(
const SmartObject& obj, std::string& result_string) {
-
Json::Value params(Json::objectValue);
SmartObject formattedObj(obj);
@@ -71,7 +70,6 @@ void CMetaFormatterTestHelper::AnyObjectToJsonString(
//-----------------------------------------------------------
void CMetaFormatterTestHelper::FillObjectIdenticalToSchema(SmartObject& obj) {
-
obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request;
obj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface;
obj[S_PARAMS][S_CORRELATION_ID] = 12;
@@ -95,8 +93,8 @@ void CMetaFormatterTestHelper::FillObjectIdenticalToSchema(SmartObject& obj) {
}
//-----------------------------------------------------------
-void CMetaFormatterTestHelper::FillObjectIdenticalToSchemaWithoutNoMandatoriesParams(
- SmartObject& obj) {
+void CMetaFormatterTestHelper::
+ FillObjectIdenticalToSchemaWithoutNoMandatoriesParams(SmartObject& obj) {
obj[S_PARAMS][S_MESSAGE_TYPE] = MessageTypeTest::request;
obj[S_PARAMS][S_FUNCTION_ID] = FunctionIDTest::RegisterAppInterface;
obj[S_PARAMS][S_CORRELATION_ID] = 12;
@@ -113,16 +111,15 @@ void CMetaFormatterTestHelper::FillObjectIdenticalToSchemaWithoutNoMandatoriesPa
obj[S_MSG_PARAMS]["appID"] = "APP ID";
// Commented not mandatory params for check creation object without them
-// obj[S_MSG_PARAMS]["ttsName"][0]["text"] = "ABC";
-// obj[S_MSG_PARAMS]["ttsName"][0]["type"] =
-// SpeechCapabilities::SC_TEXT;
-
-// obj[S_MSG_PARAMS]["vrSynonyms"][0] = "Synonym1";
-// obj[S_MSG_PARAMS]["vrSynonyms"][1] = "Synonym2";
+ // obj[S_MSG_PARAMS]["ttsName"][0]["text"] = "ABC";
+ // obj[S_MSG_PARAMS]["ttsName"][0]["type"] =
+ // SpeechCapabilities::SC_TEXT;
-// obj[S_MSG_PARAMS]["appType"][0] = AppTypeTest::SYSTEM; // not mandatory
-// obj[S_MSG_PARAMS]["appType"][1] = AppTypeTest::MEDIA;
+ // obj[S_MSG_PARAMS]["vrSynonyms"][0] = "Synonym1";
+ // obj[S_MSG_PARAMS]["vrSynonyms"][1] = "Synonym2";
+ // obj[S_MSG_PARAMS]["appType"][0] = AppTypeTest::SYSTEM; // not mandatory
+ // obj[S_MSG_PARAMS]["appType"][1] = AppTypeTest::MEDIA;
}
void CMetaFormatterTestHelper::FillObjectWithoutSomeMandatoryFields(
@@ -133,10 +130,10 @@ void CMetaFormatterTestHelper::FillObjectWithoutSomeMandatoryFields(
obj[S_PARAMS][S_PROTOCOL_VERSION] = 1;
obj[S_PARAMS][S_PROTOCOL_TYPE] = 0;
-// Commented mandatory params for check creation object without them
-// obj[S_PARAMS][S_CORRELATION_ID] = 12;
-// obj[S_MSG_PARAMS]["syncMsgVersion"]["majorVersion"] = 2;
-// obj[S_MSG_PARAMS]["syncMsgVersion"]["minorVersion"] = 10;
+ // Commented mandatory params for check creation object without them
+ // obj[S_PARAMS][S_CORRELATION_ID] = 12;
+ // obj[S_MSG_PARAMS]["syncMsgVersion"]["majorVersion"] = 2;
+ // obj[S_MSG_PARAMS]["syncMsgVersion"]["minorVersion"] = 10;
obj[S_MSG_PARAMS]["appName"] = "APP NAME";
obj[S_MSG_PARAMS]["ttsName"][0]["text"] = "ABC";
@@ -156,7 +153,6 @@ void CMetaFormatterTestHelper::FillObjectWithoutSomeMandatoryFields(
void CMetaFormatterTestHelper::CompareObjects(const SmartObject& first,
const SmartObject& second) {
-
if (SmartType_Array == first.getType()) {
ASSERT_EQ(SmartType_Array, second.getType());
for (size_t i = 0; i < first.length(); i++) {
@@ -164,10 +160,11 @@ void CMetaFormatterTestHelper::CompareObjects(const SmartObject& first,
}
} else if (SmartType_Map == first.getType()) {
ASSERT_EQ(SmartType_Map, second.getType());
- std::set < std::string > keys = first.enumerate();
+ std::set<std::string> keys = first.enumerate();
for (std::set<std::string>::const_iterator key = keys.begin();
- key != keys.end(); key++) {
+ key != keys.end();
+ key++) {
CompareObjects(first.getElement(*key), second.getElement(*key));
}
} else if (SmartType_Boolean == first.getType()) {
@@ -181,14 +178,13 @@ void CMetaFormatterTestHelper::CompareObjects(const SmartObject& first,
} else if (SmartType_Null == first.getType()) {
ASSERT_EQ(SmartType_Null, second.getType());
} else {
- FAIL()<< "Unknown SmartObject type: " << first.getType();
+ FAIL() << "Unknown SmartObject type: " << first.getType();
}
}
//-----------------------------------------------------------
void CMetaFormatterTestHelper::FillObjectWithDefaultValues(SmartObject& obj) {
-
obj[S_PARAMS][S_MESSAGE_TYPE] = -1;
obj[S_PARAMS][S_FUNCTION_ID] = -1;
obj[S_PARAMS][S_CORRELATION_ID] = 0;
@@ -204,17 +200,16 @@ void CMetaFormatterTestHelper::FillObjectWithDefaultValues(SmartObject& obj) {
obj[S_MSG_PARAMS]["hmiDisplayLanguageDesired"] = -1;
obj[S_MSG_PARAMS]["appID"] = "";
-// Commented params for check creation object with only default values
-// obj[S_MSG_PARAMS]["ttsName"][0]["text"] = "ABC";
-// obj[S_MSG_PARAMS]["ttsName"][0]["type"] =
-// SpeechCapabilities::SC_TEXT;
-
-// obj[S_MSG_PARAMS]["vrSynonyms"][0] = "Synonym1";
-// obj[S_MSG_PARAMS]["vrSynonyms"][1] = "Synonym2";
+ // Commented params for check creation object with only default values
+ // obj[S_MSG_PARAMS]["ttsName"][0]["text"] = "ABC";
+ // obj[S_MSG_PARAMS]["ttsName"][0]["type"] =
+ // SpeechCapabilities::SC_TEXT;
-// obj[S_MSG_PARAMS]["appType"][0] = AppTypeTest::SYSTEM;
-// obj[S_MSG_PARAMS]["appType"][1] = AppTypeTest::MEDIA;
+ // obj[S_MSG_PARAMS]["vrSynonyms"][0] = "Synonym1";
+ // obj[S_MSG_PARAMS]["vrSynonyms"][1] = "Synonym2";
+ // obj[S_MSG_PARAMS]["appType"][0] = AppTypeTest::SYSTEM;
+ // obj[S_MSG_PARAMS]["appType"][1] = AppTypeTest::MEDIA;
}
} // namespace formatters
diff --git a/src/components/hmi_message_handler/CMakeLists.txt b/src/components/hmi_message_handler/CMakeLists.txt
index 9559b6b00f..aa10729458 100644
--- a/src/components/hmi_message_handler/CMakeLists.txt
+++ b/src/components/hmi_message_handler/CMakeLists.txt
@@ -35,7 +35,6 @@ include_directories (
${COMPONENTS_DIR}/utils/include/
${COMPONENTS_DIR}/smart_objects/include/
${COMPONENTS_DIR}/formatters/include/
- ${COMPONENTS_DIR}/config_profile/include/
${COMPONENTS_DIR}/media_manager/include/
${COMPONENTS_DIR}/protocol_handler/include
${JSONCPP_INCLUDE_DIRECTORY}
@@ -55,7 +54,7 @@ ENDIF ()
set (SOURCES
${COMPONENTS_DIR}/hmi_message_handler/src/hmi_message_handler_impl.cc
${COMPONENTS_DIR}/hmi_message_handler/src/messagebroker_adapter.cc
- ${COMPONENTS_DIR}/hmi_message_handler/src/hmi_message_adapter.cc
+ ${COMPONENTS_DIR}/hmi_message_handler/src/hmi_message_adapter_impl.cc
${COMPONENTS_DIR}/hmi_message_handler/src/mqueue_adapter.cc
${DBUS_SOURCE}
)
@@ -76,6 +75,6 @@ endif()
# Tests temporary are inactivated. For details please check
# Readme.txt in test directory of hmi_message_handler
-#if(BUILD_TESTS)
-# add_subdirectory(test)
-#endif()
+if(BUILD_TESTS)
+ add_subdirectory(test)
+endif()
diff --git a/src/components/hmi_message_handler/include/hmi_message_handler/dbus_message_adapter.h b/src/components/hmi_message_handler/include/hmi_message_handler/dbus_message_adapter.h
index 7d33e93332..4dc74f71e8 100644
--- a/src/components/hmi_message_handler/include/hmi_message_handler/dbus_message_adapter.h
+++ b/src/components/hmi_message_handler/include/hmi_message_handler/dbus_message_adapter.h
@@ -34,7 +34,7 @@
#define SRC_COMPONENTS_HMI_MESSAGE_HANDLER_INCLUDE_HMI_MESSAGE_HANDLER_DBUS_MESSAGE_ADAPTER_H_
#include <string>
-#include "hmi_message_handler/hmi_message_adapter.h"
+#include "hmi_message_handler/hmi_message_adapter_impl.h"
#include "dbus/dbus_message_controller.h"
#include "smart_objects/smart_object.h"
@@ -45,9 +45,8 @@ namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
/**
* \brief adapter for DBus
*/
-class DBusMessageAdapter
- : public HMIMessageAdapter,
- public dbus::DBusMessageController {
+class DBusMessageAdapter : public HMIMessageAdapterImpl,
+ public dbus::DBusMessageController {
public:
typedef utils::SharedPtr<application_manager::Message> MessageSharedPointer;
explicit DBusMessageAdapter(HMIMessageHandler* hmi_msg_handler);
@@ -69,7 +68,7 @@ class DBusMessageAdapter
* \brief sends request to HMI
* \param obj request
*/
- void Request(const smart_objects::SmartObject &obj);
+ void Request(const smart_objects::SmartObject& obj);
/**
* \brief sends notification to HMI
@@ -81,7 +80,7 @@ class DBusMessageAdapter
* \brief sends response to HMI
* \param obj response
*/
- void Response(const smart_objects::SmartObject &obj);
+ void Response(const smart_objects::SmartObject& obj);
/**
* \brief sends error response to HMI
@@ -93,7 +92,7 @@ class DBusMessageAdapter
* \brief sends message to core
* \param obj
*/
- void SendMessageToCore(const smart_objects::SmartObject &obj);
+ void SendMessageToCore(const smart_objects::SmartObject& obj);
};
} // namespace hmi_message_handler
diff --git a/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_adapter.h b/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_adapter.h
index 5ed37031ea..d2a3a5b907 100644
--- a/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_adapter.h
+++ b/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_adapter.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Ford Motor Company
+ * Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -33,7 +33,7 @@
#ifndef SRC_COMPONENTS_HMI_MESSAGE_HANDLER_INCLUDE_HMI_MESSAGE_HANDLER_HMI_MESSAGE_ADAPTER_H_
#define SRC_COMPONENTS_HMI_MESSAGE_HANDLER_INCLUDE_HMI_MESSAGE_HANDLER_HMI_MESSAGE_ADAPTER_H_
-#include "hmi_message_handler/hmi_message_handler.h"
+#include "hmi_message_handler/hmi_message_sender.h"
namespace hmi_message_handler {
/**
@@ -43,37 +43,16 @@ namespace hmi_message_handler {
* SDL with HMI has to implement this interface.
*/
class HMIMessageAdapter : public HMIMessageSender {
- public:
- /**
- * \brief Constructor
- * \param handler Pointer to implementation of HMIMessageHandler abstract class
- * to notify it about receiving message or error on sending message.
- */
- explicit HMIMessageAdapter(HMIMessageHandler* handler);
-
- /**
- * \brief Destructor
- */
- virtual ~HMIMessageAdapter();
-
protected:
/**
* \brief Interface for subscriptions.
* Each class implementing interface should use it according to
* standarts of transport for which it is to be an adapter.
- * For example, Adapter for MessageBroker will use it to subscribe to notifications
+ * For example, Adapter for MessageBroker will use it to subscribe to
+ * notifications
* from HMI.
*/
virtual void SubscribeTo() = 0;
- inline virtual HMIMessageHandler* handler() const {
- return handler_;
- }
-
- private:
- /**
- *\brief Pointer on handler to notify it about receiving message/error.
- */
- mutable HMIMessageHandler* handler_;
};
} // namespace hmi_message_handler
diff --git a/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_adapter_impl.h b/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_adapter_impl.h
new file mode 100644
index 0000000000..bd118032d6
--- /dev/null
+++ b/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_adapter_impl.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_HMI_MESSAGE_HANDLER_INCLUDE_HMI_MESSAGE_HANDLER_HMI_MESSAGE_ADAPTER_IMPL_H_
+#define SRC_COMPONENTS_HMI_MESSAGE_HANDLER_INCLUDE_HMI_MESSAGE_HANDLER_HMI_MESSAGE_ADAPTER_IMPL_H_
+
+#include "hmi_message_handler/hmi_message_adapter.h"
+#include "hmi_message_handler/hmi_message_handler.h"
+
+namespace hmi_message_handler {
+
+class HMIMessageAdapterImpl : public HMIMessageAdapter {
+ public:
+ /**
+ * \brief Constructor
+ * \param handler Pointer to implementation of HMIMessageHandler abstract
+ * class
+ * to notify it about receiving message or error on sending message.
+ */
+ explicit HMIMessageAdapterImpl(HMIMessageHandler* handler);
+
+ /**
+ * \brief Destructor
+ */
+ virtual ~HMIMessageAdapterImpl();
+
+ protected:
+ virtual HMIMessageHandler* handler() const {
+ return handler_;
+ }
+
+ private:
+ /**
+ *\brief Pointer on handler to notify it about receiving message/error.
+ */
+ HMIMessageHandler* handler_;
+};
+
+} // namespace hmi_message_handler
+
+#endif // SRC_COMPONENTS_HMI_MESSAGE_HANDLER_INCLUDE_HMI_MESSAGE_HANDLER_HMI_MESSAGE_ADAPTER_IMPL_H_
diff --git a/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_handler.h b/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_handler.h
index 3e06c65085..217075e89f 100644
--- a/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_handler.h
+++ b/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_handler.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -35,6 +35,7 @@
#include "hmi_message_handler/hmi_message_sender.h"
#include "hmi_message_handler/hmi_message_observer.h"
+#include "hmi_message_handler/hmi_message_handler_settings.h"
namespace hmi_message_handler {
@@ -49,6 +50,12 @@ class HMIMessageHandler : public HMIMessageObserver, public HMIMessageSender {
virtual ~HMIMessageHandler() {}
virtual void AddHMIMessageAdapter(HMIMessageAdapter* adapter) = 0;
virtual void RemoveHMIMessageAdapter(HMIMessageAdapter* adapter) = 0;
+
+ /**
+ * \brief Hmi message handler settings getter
+ * \return pointer to hmi message handler settings class
+ */
+ virtual const HMIMessageHandlerSettings& get_settings() const = 0;
};
} // namespace hmi_message_handler
diff --git a/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_handler_impl.h b/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_handler_impl.h
index d638f370d8..3b829b0f27 100644
--- a/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_handler_impl.h
+++ b/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_handler_impl.h
@@ -36,16 +36,15 @@
#include <set>
#include "hmi_message_handler/hmi_message_adapter.h"
#include "hmi_message_handler/hmi_message_handler.h"
+#include "hmi_message_handler/hmi_message_handler_settings.h"
#include "utils/macro.h"
#include "utils/message_queue.h"
#include "utils/prioritized_queue.h"
#include "utils/threads/message_loop_thread.h"
#include "utils/threads/thread.h"
-#include "utils/singleton.h"
namespace hmi_message_handler {
-
namespace impl {
/*
* These dummy classes are here to locally impose strong typing on different
@@ -54,35 +53,41 @@ namespace impl {
* TODO(ik): replace these with globally defined message types
* when we have them.
*/
-struct MessageFromHmi: public MessageSharedPointer {
- MessageFromHmi(const MessageSharedPointer& message)
+struct MessageFromHmi : public MessageSharedPointer {
+ MessageFromHmi() {}
+ explicit MessageFromHmi(const MessageSharedPointer& message)
: MessageSharedPointer(message) {}
// PrioritizedQueue requres this method to decide which priority to assign
- size_t PriorityOrder() const { return (*this)->Priority().OrderingValue(); }
+ size_t PriorityOrder() const {
+ return (*this)->Priority().OrderingValue();
+ }
};
-struct MessageToHmi: public MessageSharedPointer {
- MessageToHmi(const MessageSharedPointer& message)
+struct MessageToHmi : public MessageSharedPointer {
+ MessageToHmi() {}
+ explicit MessageToHmi(const MessageSharedPointer& message)
: MessageSharedPointer(message) {}
// PrioritizedQueue requres this method to decide which priority to assign
- size_t PriorityOrder() const { return (*this)->Priority().OrderingValue(); }
+ size_t PriorityOrder() const {
+ return (*this)->Priority().OrderingValue();
+ }
};
-typedef threads::MessageLoopThread<
- utils::PrioritizedQueue<MessageFromHmi> > FromHmiQueue;
-typedef threads::MessageLoopThread<
- utils::PrioritizedQueue<MessageToHmi> > ToHmiQueue;
+typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageFromHmi> >
+ FromHmiQueue;
+typedef threads::MessageLoopThread<utils::PrioritizedQueue<MessageToHmi> >
+ ToHmiQueue;
}
class ToHMIThreadImpl;
class FromHMIThreadImpl;
-class HMIMessageHandlerImpl
- : public HMIMessageHandler,
- public impl::FromHmiQueue::Handler,
- public impl::ToHmiQueue::Handler,
- public utils::Singleton<HMIMessageHandlerImpl> {
+class HMIMessageHandlerImpl : public HMIMessageHandler,
+ public impl::FromHmiQueue::Handler,
+ public impl::ToHmiQueue::Handler {
public:
+ explicit HMIMessageHandlerImpl(const HMIMessageHandlerSettings& settings);
+
~HMIMessageHandlerImpl();
void OnMessageReceived(MessageSharedPointer message);
void SendMessageToHMI(MessageSharedPointer message);
@@ -91,18 +96,28 @@ class HMIMessageHandlerImpl
void AddHMIMessageAdapter(HMIMessageAdapter* adapter);
void RemoveHMIMessageAdapter(HMIMessageAdapter* adapter);
- private:
- HMIMessageHandlerImpl();
+ virtual const HMIMessageHandlerSettings& get_settings() const OVERRIDE;
+
+#ifdef BUILD_TESTS
+ std::set<HMIMessageAdapter*> message_adapters() const {
+ return message_adapters_;
+ }
+ HMIMessageObserver* observer() const {
+ return observer_;
+ }
+#endif // BUILD_TESTS
+ private:
// threads::MessageLoopThread<*>::Handler implementations
// CALLED ON messages_from_hmi_ THREAD!
virtual void Handle(const impl::MessageFromHmi message) OVERRIDE;
// CALLED ON messages_to_hmi_ THREAD!
virtual void Handle(const impl::MessageToHmi message) OVERRIDE;
- private:
+ private:
+ const HMIMessageHandlerSettings& settings_;
HMIMessageObserver* observer_;
mutable sync_primitives::Lock observer_locker_;
std::set<HMIMessageAdapter*> message_adapters_;
@@ -115,7 +130,6 @@ class HMIMessageHandlerImpl
impl::FromHmiQueue messages_from_hmi_;
DISALLOW_COPY_AND_ASSIGN(HMIMessageHandlerImpl);
- FRIEND_BASE_SINGLETON_CLASS(HMIMessageHandlerImpl);
};
} // namespace hmi_message_handler
diff --git a/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_sender.h b/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_sender.h
index d704a4df65..f00b493aa1 100644
--- a/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_sender.h
+++ b/src/components/hmi_message_handler/include/hmi_message_handler/hmi_message_sender.h
@@ -36,13 +36,12 @@
#include "application_manager/message.h"
namespace hmi_message_handler {
- typedef utils::SharedPtr<application_manager::Message> MessageSharedPointer;
+typedef utils::SharedPtr<application_manager::Message> MessageSharedPointer;
class HMIMessageSender {
public:
virtual void SendMessageToHMI(MessageSharedPointer message) = 0;
};
-
}
#endif // SRC_COMPONENTS_HMI_MESSAGE_HANDLER_INCLUDE_HMI_MESSAGE_HANDLER_HMI_MESSAGE_SENDER_H_
diff --git a/src/components/hmi_message_handler/include/hmi_message_handler/messagebroker_adapter.h b/src/components/hmi_message_handler/include/hmi_message_handler/messagebroker_adapter.h
index 4580b18ee1..f582cb2b81 100644
--- a/src/components/hmi_message_handler/include/hmi_message_handler/messagebroker_adapter.h
+++ b/src/components/hmi_message_handler/include/hmi_message_handler/messagebroker_adapter.h
@@ -36,24 +36,26 @@
#include <string>
#include "mb_controller.hpp"
-#include "hmi_message_handler/hmi_message_adapter.h"
+#include "hmi_message_handler/hmi_message_adapter_impl.h"
#include "utils/threads/thread_validator.h"
namespace hmi_message_handler {
-class MessageBrokerAdapter : public HMIMessageAdapter,
- public NsMessageBroker::CMessageBrokerController,
- public threads::SingleThreadValidator {
+class MessageBrokerAdapter : public HMIMessageAdapterImpl,
+ public NsMessageBroker::CMessageBrokerController,
+ public threads::SingleThreadValidator {
public:
- MessageBrokerAdapter(HMIMessageHandler* handler_param, const std::string&
- server_address, uint16_t port);
+ MessageBrokerAdapter(HMIMessageHandler* handler_param,
+ const std::string& server_address,
+ uint16_t port);
~MessageBrokerAdapter();
void SendMessageToHMI(MessageSharedPointer message);
/*Methods from CMessageBrokerController*/
/**
* \brief Called on receiving response message from RPCBus.
- * \param method Name of corresponding request method that was sent previously to RPCBus.
+ * \param method Name of corresponding request method that was sent previously
+ * to RPCBus.
* \param root Received Json object.
*/
void processResponse(std::string method, Json::Value& root);
diff --git a/src/components/hmi_message_handler/include/hmi_message_handler/mqueue_adapter.h b/src/components/hmi_message_handler/include/hmi_message_handler/mqueue_adapter.h
index 126ea3a66e..69634ea00e 100644
--- a/src/components/hmi_message_handler/include/hmi_message_handler/mqueue_adapter.h
+++ b/src/components/hmi_message_handler/include/hmi_message_handler/mqueue_adapter.h
@@ -36,7 +36,7 @@
#include <memory>
#include <mqueue.h>
#include "utils/threads/thread.h"
-#include "hmi_message_handler/hmi_message_adapter.h"
+#include "hmi_message_handler/hmi_message_adapter_impl.h"
namespace hmi_message_handler {
@@ -45,7 +45,7 @@ class ReceiverThreadDelegate;
/**
* \brief HMI message adapter for mqueue
*/
-class MqueueAdapter : public HMIMessageAdapter {
+class MqueueAdapter : public HMIMessageAdapterImpl {
public:
MqueueAdapter(HMIMessageHandler* hmi_message_handler);
virtual ~MqueueAdapter();
diff --git a/src/components/hmi_message_handler/src/dbus_message_adapter.cc b/src/components/hmi_message_handler/src/dbus_message_adapter.cc
index 7c540ad0c2..6a5bda5bfb 100644
--- a/src/components/hmi_message_handler/src/dbus_message_adapter.cc
+++ b/src/components/hmi_message_handler/src/dbus_message_adapter.cc
@@ -33,7 +33,7 @@
#include "hmi_message_handler/dbus_message_adapter.h"
#include <sstream>
#include "utils/logger.h"
-#include "formatters/CSmartFactory.hpp"
+#include "formatters/CSmartFactory.h"
namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
namespace sos = NsSmartDeviceLink::NsJSONHandler::strings;
@@ -43,29 +43,31 @@ namespace hmi_message_handler {
CREATE_LOGGERPTR_GLOBAL(logger_, "HMIMessageHandler")
const std::string DBusMessageAdapter::SDL_SERVICE_NAME = "com.ford.sdl.core";
-const std::string DBusMessageAdapter::SDL_OBJECT_PATH = "/";
+const std::string DBusMessageAdapter::SDL_OBJECT_PATH = "/";
const std::string DBusMessageAdapter::HMI_SERVICE_NAME = "com.ford.sdl.hmi";
-const std::string DBusMessageAdapter::HMI_OBJECT_PATH = "/";
-
-std::vector<std::string> &split(const std::string &s, char delim,
- std::vector<std::string> &elems) {
- std::stringstream ss(s);
- std::string item;
- while (std::getline(ss, item, delim)) {
- elems.push_back(item);
- }
- return elems;
+const std::string DBusMessageAdapter::HMI_OBJECT_PATH = "/";
+
+std::vector<std::string>& split(const std::string& s,
+ char delim,
+ std::vector<std::string>& elems) {
+ std::stringstream ss(s);
+ std::string item;
+ while (std::getline(ss, item, delim)) {
+ elems.push_back(item);
+ }
+ return elems;
}
DBusMessageAdapter::DBusMessageAdapter(HMIMessageHandler* hmi_msg_handler)
- : HMIMessageAdapter(hmi_msg_handler),
- DBusMessageController(SDL_SERVICE_NAME, SDL_OBJECT_PATH,
- HMI_SERVICE_NAME, HMI_OBJECT_PATH) {
+ : HMIMessageAdapterImpl(hmi_msg_handler)
+ , DBusMessageController(SDL_SERVICE_NAME,
+ SDL_OBJECT_PATH,
+ HMI_SERVICE_NAME,
+ HMI_OBJECT_PATH) {
LOG4CXX_INFO(logger_, "Created DBusMessageAdapter");
}
-DBusMessageAdapter::~DBusMessageAdapter() {
-}
+DBusMessageAdapter::~DBusMessageAdapter() {}
void DBusMessageAdapter::SendMessageToHMI(MessageSharedPointer message) {
LOG4CXX_INFO(logger_, "DBusMessageAdapter::sendMessageToHMI");
@@ -108,16 +110,22 @@ void DBusMessageAdapter::SubscribeTo() {
DBusMessageController::SubscribeTo("VR", "OnLanguageChange");
DBusMessageController::SubscribeTo("BasicCommunication", "OnReady");
DBusMessageController::SubscribeTo("BasicCommunication", "OnAppDeactivated");
- DBusMessageController::SubscribeTo("BasicCommunication", "OnStartDeviceDiscovery");
- DBusMessageController::SubscribeTo("BasicCommunication", "OnUpdateDeviceList");
- DBusMessageController::SubscribeTo("BasicCommunication", "OnFindApplications");
+ DBusMessageController::SubscribeTo("BasicCommunication",
+ "OnStartDeviceDiscovery");
+ DBusMessageController::SubscribeTo("BasicCommunication",
+ "OnUpdateDeviceList");
+ DBusMessageController::SubscribeTo("BasicCommunication",
+ "OnFindApplications");
DBusMessageController::SubscribeTo("BasicCommunication", "OnAppActivated");
DBusMessageController::SubscribeTo("BasicCommunication", "OnExitApplication");
- DBusMessageController::SubscribeTo("BasicCommunication", "OnExitAllApplications");
+ DBusMessageController::SubscribeTo("BasicCommunication",
+ "OnExitAllApplications");
DBusMessageController::SubscribeTo("BasicCommunication", "OnDeviceChosen");
- DBusMessageController::SubscribeTo("BasicCommunication", "OnIgnitionCycleOver");
+ DBusMessageController::SubscribeTo("BasicCommunication",
+ "OnIgnitionCycleOver");
DBusMessageController::SubscribeTo("BasicCommunication", "OnSystemRequest");
- DBusMessageController::SubscribeTo("BasicCommunication", "OnSystemInfoChanged");
+ DBusMessageController::SubscribeTo("BasicCommunication",
+ "OnSystemInfoChanged");
DBusMessageController::SubscribeTo("BasicCommunication", "OnPhoneCall");
DBusMessageController::SubscribeTo("BasicCommunication", "OnEmergencyEvent");
DBusMessageController::SubscribeTo("TTS", "Started");
@@ -144,7 +152,8 @@ void DBusMessageAdapter::SubscribeTo() {
DBusMessageController::SubscribeTo("VehicleInfo", "OnAccPedalPosition");
DBusMessageController::SubscribeTo("VehicleInfo", "OnSteeringWheelAngle");
DBusMessageController::SubscribeTo("VehicleInfo", "OnMyKey");
- DBusMessageController::SubscribeTo("Navigation", "OnTBTClientState");
+ DBusMessageController::SubscribeTo("Navigation", "OnTBTClientState");
+ DBusMessageController::SubscribeTo("Navigation", "OnWayPointChange");
DBusMessageController::SubscribeTo("SDL", "OnAllowSDLFunctionality");
DBusMessageController::SubscribeTo("SDL", "OnReceivedPolicyUpdate");
DBusMessageController::SubscribeTo("SDL", "OnPolicyUpdate");
@@ -156,7 +165,8 @@ void DBusMessageAdapter::SubscribeTo() {
LOG4CXX_INFO(logger_, "Subscribed to notifications.");
}
-void DBusMessageAdapter::SendMessageToCore(const smart_objects::SmartObject& obj) {
+void DBusMessageAdapter::SendMessageToCore(
+ const smart_objects::SmartObject& obj) {
LOG4CXX_AUTO_TRACE(logger_);
if (!handler()) {
@@ -164,7 +174,13 @@ void DBusMessageAdapter::SendMessageToCore(const smart_objects::SmartObject& obj
return;
}
- MessageSharedPointer message = new application_manager::Message(protocol_handler::MessagePriority::kDefault);//todo: ykazakov constant is a temp solution to finish merge MessagePriority::FromServiceType(message.servicetype) shall be used instead
+ MessageSharedPointer message = new application_manager::Message(
+ protocol_handler::MessagePriority::kDefault); // todo: ykazakov constant
+ // is a temp solution to
+ // finish
+ // merge
+ // MessagePriority::FromServiceType(message.servicetype)
+ // shall be used instead
message->set_protocol_version(application_manager::ProtocolVersion::kHMI);
message->set_smart_object(obj);
handler()->OnMessageReceived(message);
@@ -172,7 +188,7 @@ void DBusMessageAdapter::SendMessageToCore(const smart_objects::SmartObject& obj
}
void DBusMessageAdapter::Request(const smart_objects::SmartObject& obj) {
- LOG4CXX_DEBUG(logger_, "Request");
+ LOG4CXX_AUTO_TRACE(logger_);
dbus::MessageId func_id = static_cast<dbus::MessageId>(
obj[sos::S_PARAMS][sos::S_FUNCTION_ID].asInt());
dbus::MessageName name = get_schema().getMessageName(func_id);
@@ -180,8 +196,8 @@ void DBusMessageAdapter::Request(const smart_objects::SmartObject& obj) {
MethodCall(id, func_id, name, obj[sos::S_MSG_PARAMS]);
}
-void DBusMessageAdapter::Notification(const smart_objects::SmartObject &obj) {
- LOG4CXX_DEBUG(logger_, "Notification");
+void DBusMessageAdapter::Notification(const smart_objects::SmartObject& obj) {
+ LOG4CXX_AUTO_TRACE(logger_);
dbus::MessageId func_id = static_cast<dbus::MessageId>(
obj[sos::S_PARAMS][sos::S_FUNCTION_ID].asInt());
dbus::MessageName name = get_schema().getMessageName(func_id);
@@ -189,15 +205,15 @@ void DBusMessageAdapter::Notification(const smart_objects::SmartObject &obj) {
}
void DBusMessageAdapter::Response(const smart_objects::SmartObject& obj) {
- LOG4CXX_DEBUG(logger_, "Response");
+ LOG4CXX_AUTO_TRACE(logger_);
dbus::MessageId func_id = static_cast<dbus::MessageId>(
- obj[sos::S_PARAMS][sos::S_FUNCTION_ID].asInt());
+ obj[sos::S_PARAMS][sos::S_FUNCTION_ID].asInt());
dbus::MessageName name = get_schema().getMessageName(func_id);
uint id = obj[sos::S_PARAMS][sos::S_CORRELATION_ID].asInt();
MethodReturn(id, func_id, name, obj[sos::S_MSG_PARAMS]);
}
-void DBusMessageAdapter::ErrorResponse(const smart_objects::SmartObject &obj) {
+void DBusMessageAdapter::ErrorResponse(const smart_objects::SmartObject& obj) {
LOG4CXX_DEBUG(logger_, "Error");
std::string error = obj[sos::S_PARAMS][sos::kCode].asString();
std::string description = obj[sos::S_PARAMS][sos::kMessage].asString();
diff --git a/src/components/hmi_message_handler/src/hmi_message_adapter.cc b/src/components/hmi_message_handler/src/hmi_message_adapter.cc
deleted file mode 100644
index d8c280bea7..0000000000
--- a/src/components/hmi_message_handler/src/hmi_message_adapter.cc
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "hmi_message_handler/hmi_message_adapter.h"
-
-namespace hmi_message_handler {
-HMIMessageAdapter::HMIMessageAdapter(HMIMessageHandler* handler)
- : handler_(handler) {
-}
-
-HMIMessageAdapter::~HMIMessageAdapter() {
- handler_ = 0;
-}
-
-} // namespace hmi_message_handler
diff --git a/src/components/hmi_message_handler/src/hmi_message_adapter_impl.cc b/src/components/hmi_message_handler/src/hmi_message_adapter_impl.cc
new file mode 100644
index 0000000000..48874618a0
--- /dev/null
+++ b/src/components/hmi_message_handler/src/hmi_message_adapter_impl.cc
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "hmi_message_handler/hmi_message_adapter_impl.h"
+
+namespace hmi_message_handler {
+HMIMessageAdapterImpl::HMIMessageAdapterImpl(HMIMessageHandler* handler)
+ : handler_(handler) {}
+
+HMIMessageAdapterImpl::~HMIMessageAdapterImpl() {
+ handler_ = 0;
+}
+
+} // namespace hmi_message_handler
diff --git a/src/components/hmi_message_handler/src/hmi_message_handler_impl.cc b/src/components/hmi_message_handler/src/hmi_message_handler_impl.cc
index 887d145617..4e0d8e45ba 100644
--- a/src/components/hmi_message_handler/src/hmi_message_handler_impl.cc
+++ b/src/components/hmi_message_handler/src/hmi_message_handler_impl.cc
@@ -31,35 +31,34 @@
*/
#include "hmi_message_handler/hmi_message_handler_impl.h"
-#include "config_profile/profile.h"
#include "utils/logger.h"
namespace hmi_message_handler {
CREATE_LOGGERPTR_GLOBAL(logger_, "HMIMessageHandler")
-HMIMessageHandlerImpl::HMIMessageHandlerImpl()
- : observer_(NULL),
- messages_to_hmi_("HMH ToHMI", this,
- threads::ThreadOptions(
- profile::Profile::instance()->thread_min_stack_size())),
- messages_from_hmi_("HMH FromHMI", this,
- threads::ThreadOptions(
- profile::Profile::instance()->thread_min_stack_size())) {
-}
+HMIMessageHandlerImpl::HMIMessageHandlerImpl(
+ const HMIMessageHandlerSettings& settings)
+ : settings_(settings)
+ , observer_(NULL)
+ , messages_to_hmi_(
+ "HMH ToHMI",
+ this,
+ threads::ThreadOptions(get_settings().thread_min_stack_size()))
+ , messages_from_hmi_(
+ "HMH FromHMI",
+ this,
+ threads::ThreadOptions(get_settings().thread_min_stack_size())) {}
HMIMessageHandlerImpl::~HMIMessageHandlerImpl() {
- LOG4CXX_INFO(logger_, "HMIMessageHandlerImpl::~HMIMessageHandlerImpl()");
- sync_primitives::AutoLock lock(observer_locker_);
- observer_ = NULL;
- if (!message_adapters_.empty()) {
- LOG4CXX_WARN(logger_, "Not all HMIMessageAdapter have unsubscribed from"
- " HMIMessageHandlerImpl");
- }
+ LOG4CXX_AUTO_TRACE(logger_);
+ messages_to_hmi_.Shutdown();
+ messages_from_hmi_.Shutdown();
+ set_message_observer(NULL);
}
void HMIMessageHandlerImpl::OnMessageReceived(MessageSharedPointer message) {
- LOG4CXX_INFO(logger_, "HMIMessageHandlerImpl::OnMessageReceived()");
+ LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(observer_locker_);
if (!observer_) {
LOG4CXX_WARN(logger_, "No HMI message observer set!");
@@ -74,12 +73,13 @@ void HMIMessageHandlerImpl::SendMessageToHMI(MessageSharedPointer message) {
}
void HMIMessageHandlerImpl::set_message_observer(HMIMessageObserver* observer) {
- LOG4CXX_INFO(logger_, "HMIMessageHandlerImpl::SetMessageObserver()");
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(observer_locker_);
observer_ = observer;
}
void HMIMessageHandlerImpl::OnErrorSending(MessageSharedPointer message) {
- LOG4CXX_INFO(logger_, "HMIMessageHandlerImpl::OnErrorSending()");
+ LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(observer_locker_);
if (!observer_) {
LOG4CXX_WARN(logger_, "No HMI message observer set!");
@@ -89,16 +89,26 @@ void HMIMessageHandlerImpl::OnErrorSending(MessageSharedPointer message) {
}
void HMIMessageHandlerImpl::AddHMIMessageAdapter(HMIMessageAdapter* adapter) {
- LOG4CXX_INFO(logger_, "HMIMessageHandlerImpl::AddHMIMessageAdapter()");
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!adapter) {
+ LOG4CXX_WARN(logger_, "HMIMessageAdapter is not valid!");
+ return;
+ }
message_adapters_.insert(adapter);
}
void HMIMessageHandlerImpl::RemoveHMIMessageAdapter(
HMIMessageAdapter* adapter) {
- LOG4CXX_INFO(logger_, "HMIMessageHandlerImpl::RemoveHMIMessageAdapter()");
- if (adapter != NULL) {
- message_adapters_.erase(adapter);
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!adapter) {
+ LOG4CXX_WARN(logger_, "HMIMessageAdapter is not valid!");
+ return;
}
+ message_adapters_.erase(adapter);
+}
+
+const HMIMessageHandlerSettings& HMIMessageHandlerImpl::get_settings() const {
+ return settings_;
}
void HMIMessageHandlerImpl::Handle(const impl::MessageFromHmi message) {
@@ -111,16 +121,13 @@ void HMIMessageHandlerImpl::Handle(const impl::MessageFromHmi message) {
observer_->OnMessageReceived(message);
LOG4CXX_INFO(logger_, "Message from hmi given away.");
-
}
void HMIMessageHandlerImpl::Handle(const impl::MessageToHmi message) {
- for (std::set<HMIMessageAdapter*>::iterator it =
- message_adapters_.begin();
- it != message_adapters_.end();
- ++it) {
+ for (std::set<HMIMessageAdapter*>::iterator it = message_adapters_.begin();
+ it != message_adapters_.end();
+ ++it) {
(*it)->SendMessageToHMI(message);
}
}
-
} // namespace hmi_message_handler
diff --git a/src/components/hmi_message_handler/src/messagebroker_adapter.cc b/src/components/hmi_message_handler/src/messagebroker_adapter.cc
index 654fe747a6..27cf9df8cd 100644
--- a/src/components/hmi_message_handler/src/messagebroker_adapter.cc
+++ b/src/components/hmi_message_handler/src/messagebroker_adapter.cc
@@ -33,7 +33,6 @@
#include <string>
#include "hmi_message_handler/messagebroker_adapter.h"
-#include "config_profile/profile.h"
#include "utils/logger.h"
namespace hmi_message_handler {
@@ -43,29 +42,28 @@ CREATE_LOGGERPTR_GLOBAL(logger_, "HMIMessageHandler")
typedef NsMessageBroker::CMessageBrokerController MessageBrokerController;
MessageBrokerAdapter::MessageBrokerAdapter(HMIMessageHandler* handler_param,
- const std::string& server_address,
- uint16_t port)
- : HMIMessageAdapter(handler_param),
- MessageBrokerController(server_address, port, "SDL") {
- LOG4CXX_INFO(logger_, "Created MessageBrokerAdapter");
+ const std::string& server_address,
+ uint16_t port)
+ : HMIMessageAdapterImpl(handler_param)
+ , MessageBrokerController(server_address, port, "SDL") {
+ LOG4CXX_TRACE(logger_, "Created MessageBrokerAdapter");
}
-
-MessageBrokerAdapter::~MessageBrokerAdapter() {
-}
+MessageBrokerAdapter::~MessageBrokerAdapter() {}
void MessageBrokerAdapter::SendMessageToHMI(
- hmi_message_handler::MessageSharedPointer message) {
- LOG4CXX_INFO(logger_, "MessageBrokerAdapter::sendMessageToHMI");
- /*if (!message) {
- // TODO(PV): LOG
- return;
- }*/
+ hmi_message_handler::MessageSharedPointer message) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ if (!message.valid()) {
+ LOG4CXX_ERROR(logger_, "Can`t send not valid message");
+ return;
+ }
Json::Reader reader;
Json::Value json_value;
if (!reader.parse(message->json_message(), json_value, false)) {
- // TODO(PV): LOG4CXX_ERROR(mLogger, "Received invalid json string.");
+ LOG4CXX_ERROR(logger_, "Received invalid json string.");
return;
}
@@ -73,7 +71,7 @@ void MessageBrokerAdapter::SendMessageToHMI(
}
void MessageBrokerAdapter::processResponse(std::string method,
- Json::Value& root) {
+ Json::Value& root) {
LOG4CXX_AUTO_TRACE(logger_);
ProcessRecievedFromMB(root);
}
@@ -95,7 +93,8 @@ void MessageBrokerAdapter::SubscribeTo() {
MessageBrokerController::subscribeTo("UI.OnCommand");
MessageBrokerController::subscribeTo("VR.OnCommand");
MessageBrokerController::subscribeTo("BasicCommunication.OnReady");
- MessageBrokerController::subscribeTo("BasicCommunication.OnExitAllApplications");
+ MessageBrokerController::subscribeTo(
+ "BasicCommunication.OnExitAllApplications");
MessageBrokerController::subscribeTo("UI.OnDriverDistraction");
MessageBrokerController::subscribeTo("UI.OnSystemContext");
MessageBrokerController::subscribeTo("UI.OnAppActivated");
@@ -104,27 +103,30 @@ void MessageBrokerAdapter::SubscribeTo() {
MessageBrokerController::subscribeTo("UI.OnResetTimeout");
MessageBrokerController::subscribeTo("TTS.OnResetTimeout");
MessageBrokerController::subscribeTo("BasicCommunication.OnAppDeactivated");
- MessageBrokerController::subscribeTo("BasicCommunication.OnStartDeviceDiscovery");
+ MessageBrokerController::subscribeTo(
+ "BasicCommunication.OnStartDeviceDiscovery");
MessageBrokerController::subscribeTo("BasicCommunication.OnUpdateDeviceList");
MessageBrokerController::subscribeTo("BasicCommunication.OnFindApplications");
MessageBrokerController::subscribeTo("BasicCommunication.OnAppActivated");
MessageBrokerController::subscribeTo("BasicCommunication.OnExitApplication");
- MessageBrokerController::subscribeTo("BasicCommunication.OnExitAllApplications");
+ MessageBrokerController::subscribeTo(
+ "BasicCommunication.OnExitAllApplications");
MessageBrokerController::subscribeTo("BasicCommunication.OnDeviceChosen");
- MessageBrokerController::subscribeTo("BasicCommunication.OnPhoneCall");
- MessageBrokerController::subscribeTo("BasicCommunication.OnEmergencyEvent");
MessageBrokerController::subscribeTo("UI.OnLanguageChange");
MessageBrokerController::subscribeTo("VR.OnLanguageChange");
MessageBrokerController::subscribeTo("TTS.OnLanguageChange");
MessageBrokerController::subscribeTo("VehicleInfo.OnVehicleData");
MessageBrokerController::subscribeTo("Navigation.OnTBTClientState");
+ MessageBrokerController::subscribeTo("Navigation.OnWayPointChange");
MessageBrokerController::subscribeTo("TTS.Started");
MessageBrokerController::subscribeTo("TTS.Stopped");
MessageBrokerController::subscribeTo("VR.Started");
MessageBrokerController::subscribeTo("VR.Stopped");
MessageBrokerController::subscribeTo("BasicCommunication.OnSystemRequest");
- MessageBrokerController::subscribeTo("BasicCommunication.OnIgnitionCycleOver");
- MessageBrokerController::subscribeTo("BasicCommunication.OnSystemInfoChanged");
+ MessageBrokerController::subscribeTo(
+ "BasicCommunication.OnIgnitionCycleOver");
+ MessageBrokerController::subscribeTo(
+ "BasicCommunication.OnSystemInfoChanged");
MessageBrokerController::subscribeTo("SDL.OnAppPermissionConsent");
MessageBrokerController::subscribeTo("SDL.OnAllowSDLFunctionality");
MessageBrokerController::subscribeTo("SDL.OnReceivedPolicyUpdate");
@@ -132,6 +134,7 @@ void MessageBrokerAdapter::SubscribeTo() {
MessageBrokerController::subscribeTo("SDL.AddStatisticsInfo");
MessageBrokerController::subscribeTo("SDL.OnDeviceStateChanged");
MessageBrokerController::subscribeTo("SDL.OnPolicyUpdate");
+ MessageBrokerController::subscribeTo("BasicCommunication.OnEventChanged");
LOG4CXX_INFO(logger_, "Subscribed to notifications.");
}
@@ -162,8 +165,10 @@ void MessageBrokerAdapter::ProcessRecievedFromMB(Json::Value& root) {
// Messages from HMI (sent through message broker) have no priority so far
// assign default priority
- hmi_message_handler::MessageSharedPointer message = hmi_message_handler::MessageSharedPointer(new application_manager::Message(
- protocol_handler::MessagePriority::kDefault));
+ hmi_message_handler::MessageSharedPointer message =
+ hmi_message_handler::MessageSharedPointer(
+ new application_manager::Message(
+ protocol_handler::MessagePriority::kDefault));
// message->set_message_type()
message->set_json_message(message_string);
message->set_protocol_version(application_manager::ProtocolVersion::kHMI);
diff --git a/src/components/hmi_message_handler/src/mqueue_adapter.cc b/src/components/hmi_message_handler/src/mqueue_adapter.cc
index 825c27c048..4cfebbe9e8 100644
--- a/src/components/hmi_message_handler/src/mqueue_adapter.cc
+++ b/src/components/hmi_message_handler/src/mqueue_adapter.cc
@@ -47,8 +47,8 @@ class ReceiverThreadDelegate : public threads::ThreadDelegate {
public:
ReceiverThreadDelegate(mqd_t mqueue_descriptor,
HMIMessageHandler* hmi_message_handler)
- : mqueue_descriptor_(mqueue_descriptor),
- hmi_message_handler_(hmi_message_handler) {}
+ : mqueue_descriptor_(mqueue_descriptor)
+ , hmi_message_handler_(hmi_message_handler) {}
private:
virtual void threadMain() {
@@ -75,31 +75,33 @@ class ReceiverThreadDelegate : public threads::ThreadDelegate {
};
MqueueAdapter::MqueueAdapter(HMIMessageHandler* hmi_message_handler)
- : HMIMessageAdapter(hmi_message_handler),
- sdl_to_hmi_mqueue_(-1),
- hmi_to_sdl_mqueue_(-1),
- receiver_thread_(NULL) {
+ : HMIMessageAdapterImpl(hmi_message_handler)
+ , sdl_to_hmi_mqueue_(-1)
+ , hmi_to_sdl_mqueue_(-1)
+ , receiver_thread_(NULL) {
mq_attr mq_attributes;
mq_attributes.mq_maxmsg = kMqueueSize;
mq_attributes.mq_msgsize = kMqueueMessageSize;
sdl_to_hmi_mqueue_ =
mq_open(kSdlToHmiQueue, O_CREAT | O_RDWR, S_IRWXU, &mq_attributes);
if (-1 == sdl_to_hmi_mqueue_) {
- LOG4CXX_ERROR(logger_, "Could not open message queue "
- << kSdlToHmiQueue << ", error " << errno);
+ LOG4CXX_ERROR(logger_,
+ "Could not open message queue " << kSdlToHmiQueue
+ << ", error " << errno);
return;
}
hmi_to_sdl_mqueue_ =
mq_open(kHmiToSdlQueue, O_CREAT | O_RDWR, S_IRWXU, &mq_attributes);
if (-1 == hmi_to_sdl_mqueue_) {
- LOG4CXX_ERROR(logger_, "Could not open message queue "
- << kHmiToSdlQueue << ", error " << errno);
+ LOG4CXX_ERROR(logger_,
+ "Could not open message queue " << kHmiToSdlQueue
+ << ", error " << errno);
return;
}
- receiver_thread_delegate_ = new ReceiverThreadDelegate(hmi_to_sdl_mqueue_,
- hmi_message_handler);
- receiver_thread_ = threads::CreateThread("MqueueAdapter",
- receiver_thread_delegate_);
+ receiver_thread_delegate_ =
+ new ReceiverThreadDelegate(hmi_to_sdl_mqueue_, hmi_message_handler);
+ receiver_thread_ =
+ threads::CreateThread("MqueueAdapter", receiver_thread_delegate_);
receiver_thread_->start();
}
@@ -107,8 +109,10 @@ MqueueAdapter::~MqueueAdapter() {
receiver_thread_->join();
delete receiver_thread_delegate_;
threads::DeleteThread(receiver_thread_);
- if (-1 != hmi_to_sdl_mqueue_) mq_close(hmi_to_sdl_mqueue_);
- if (-1 != sdl_to_hmi_mqueue_) mq_close(sdl_to_hmi_mqueue_);
+ if (-1 != hmi_to_sdl_mqueue_)
+ mq_close(hmi_to_sdl_mqueue_);
+ if (-1 != sdl_to_hmi_mqueue_)
+ mq_close(sdl_to_hmi_mqueue_);
mq_unlink(kHmiToSdlQueue);
mq_unlink(kSdlToHmiQueue);
}
diff --git a/src/components/hmi_message_handler/test/CMakeLists.txt b/src/components/hmi_message_handler/test/CMakeLists.txt
index 4a97e299f0..98e9fd5653 100644
--- a/src/components/hmi_message_handler/test/CMakeLists.txt
+++ b/src/components/hmi_message_handler/test/CMakeLists.txt
@@ -33,17 +33,23 @@ if(BUILD_TESTS)
include_directories (
${GMOCK_INCLUDE_DIRECTORY}
${COMPONENTS_DIR}/hmi_message_handler/include
+ ${COMPONENTS_DIR}/hmi_message_handler/test/include
)
set(LIBRARIES
gmock
ApplicationManager
HMIMessageHandler
+ jsoncpp
+ MessageBrokerClient
+ MessageBrokerServer
+ ConfigProfile
)
-set(SOURCES
- ${COMPONENTS_DIR}/hmi_message_handler/test/mqueue_adapter_test.cc
-)
+set(SOURCES
+${COMPONENTS_DIR}/hmi_message_handler/test/hmi_message_handler_impl_test.cc
+${COMPONENTS_DIR}/hmi_message_handler/test/hmi_message_adapter_test.cc
+)
if(${QT_HMI})
list (APPEND SOURCES
diff --git a/src/components/hmi_message_handler/test/dbus_message_adapter_test.cc b/src/components/hmi_message_handler/test/dbus_message_adapter_test.cc
index 6699f788dd..ac9a36aa16 100644
--- a/src/components/hmi_message_handler/test/dbus_message_adapter_test.cc
+++ b/src/components/hmi_message_handler/test/dbus_message_adapter_test.cc
@@ -38,15 +38,14 @@ namespace Json {
class Value;
}
-class MockDBusMessageController :
- public ::dbus::DBusMessageController {
+class MockDBusMessageController : public ::dbus::DBusMessageController {
public:
MockDBusMessageController(const std::string& serviceName,
const std::string& path,
- const std::string& hmiserviceName,
- const std::string& hmipath)
- : DBusMessageController(serviceName, path, hmiserviceName,hmipath),
- thread_() {}
+ const std::string& hmiserviceName,
+ const std::string& hmipath)
+ : DBusMessageController(serviceName, path, hmiserviceName, hmipath)
+ , thread_() {}
virtual void processResponse(std::string method, Json::Value& root) {}
virtual void processRequest(Json::Value& root) {}
@@ -54,13 +53,15 @@ class MockDBusMessageController :
bool Init() {
return ::dbus::DBusMessageController::Init() &&
- pthread_create(&thread_, 0, &Run, this) == 0;
+ pthread_create(&thread_, 0, &Run, this) == 0;
}
+
private:
pthread_t thread_;
static void* Run(void* data) {
if (NULL != data) {
- static_cast<MockDBusMessageController*>(data)->MethodForReceiverThread(nullptr);
+ static_cast<MockDBusMessageController*>(data)
+ ->MethodForReceiverThread(nullptr);
}
return 0;
}
diff --git a/src/components/hmi_message_handler/test/hmi_message_adapter_test.cc b/src/components/hmi_message_handler/test/hmi_message_adapter_test.cc
new file mode 100644
index 0000000000..b0f63c6a0c
--- /dev/null
+++ b/src/components/hmi_message_handler/test/hmi_message_adapter_test.cc
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "utils/shared_ptr.h"
+#include "utils/make_shared.h"
+
+#include "hmi_message_handler/hmi_message_handler_impl.h"
+#include "hmi_message_handler/mock_hmi_message_adapter_impl.h"
+#include "hmi_message_handler/mock_hmi_message_handler_settings.h"
+
+namespace test {
+namespace components {
+namespace hmi_message_handler_test {
+
+using ::testing::ReturnRef;
+using hmi_message_handler::HMIMessageHandlerImpl;
+
+typedef utils::SharedPtr<MockHMIMessageAdapterImpl>
+ MockHMIMessageAdapterImplSPtr;
+
+TEST(HMIMessageAdapterImplTest, Handler_CorrectPointer_CorrectReturnedPointer) {
+ testing::NiceMock<MockHMIMessageHandlerSettings>
+ mock_hmi_message_handler_settings;
+ const uint64_t stack_size = 1000u;
+ ON_CALL(mock_hmi_message_handler_settings, thread_min_stack_size())
+ .WillByDefault(ReturnRef(stack_size));
+ HMIMessageHandler* message_handler =
+ new hmi_message_handler::HMIMessageHandlerImpl(
+ mock_hmi_message_handler_settings);
+ ;
+
+ MockHMIMessageAdapterImplSPtr message_adapter_impl =
+ utils::MakeShared<MockHMIMessageAdapterImpl>(message_handler);
+
+ EXPECT_EQ(message_handler, message_adapter_impl->get_handler());
+
+ delete message_handler;
+ message_handler = NULL;
+}
+
+TEST(HMIMessageAdapterImplTest, Handler_NULLPointer_CorrectReturnedPointer) {
+ HMIMessageHandler* message_handler = NULL;
+ MockHMIMessageAdapterImplSPtr message_adapter_impl =
+ utils::MakeShared<MockHMIMessageAdapterImpl>(message_handler);
+
+ EXPECT_EQ(NULL, message_adapter_impl->get_handler());
+}
+
+} // namespace hmi_message_helper_test
+} // namespace components
+} // namespace test
diff --git a/src/components/hmi_message_handler/test/hmi_message_handler_impl_test.cc b/src/components/hmi_message_handler/test/hmi_message_handler_impl_test.cc
new file mode 100644
index 0000000000..06cca74ba9
--- /dev/null
+++ b/src/components/hmi_message_handler/test/hmi_message_handler_impl_test.cc
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "application_manager/message.h"
+#include "hmi_message_handler/hmi_message_handler_impl.h"
+#include "hmi_message_handler/messagebroker_adapter.h"
+#include "hmi_message_handler/mock_hmi_message_observer.h"
+#include "hmi_message_handler/mock_hmi_message_handler_settings.h"
+#include "utils/make_shared.h"
+
+namespace test {
+namespace components {
+namespace hmi_message_handler_test {
+
+using ::testing::ReturnRef;
+class HMIMessageHandlerImplTest : public ::testing::Test {
+ public:
+ HMIMessageHandlerImplTest()
+ : mb_adapter_(NULL)
+ , hmi_handler_(NULL)
+ , mock_hmi_message_observer_(NULL) {}
+
+ protected:
+ hmi_message_handler::MessageBrokerAdapter* mb_adapter_;
+ hmi_message_handler::HMIMessageHandlerImpl* hmi_handler_;
+ hmi_message_handler::MockHMIMessageObserver* mock_hmi_message_observer_;
+ testing::NiceMock<MockHMIMessageHandlerSettings>
+ mock_hmi_message_handler_settings;
+ const uint64_t stack_size = 1000u;
+
+ virtual void SetUp() OVERRIDE {
+ ON_CALL(mock_hmi_message_handler_settings, thread_min_stack_size())
+ .WillByDefault(ReturnRef(stack_size));
+ hmi_handler_ = new hmi_message_handler::HMIMessageHandlerImpl(
+ mock_hmi_message_handler_settings);
+ mb_adapter_ = new hmi_message_handler::MessageBrokerAdapter(
+ hmi_handler_, "localhost", 22);
+ mock_hmi_message_observer_ =
+ new hmi_message_handler::MockHMIMessageObserver();
+ hmi_handler_->set_message_observer(mock_hmi_message_observer_);
+ EXPECT_TRUE(NULL != hmi_handler_->observer());
+ }
+
+ void TearDown() OVERRIDE {
+ hmi_handler_->set_message_observer(NULL);
+ delete mock_hmi_message_observer_;
+ delete hmi_handler_;
+ delete mb_adapter_;
+ }
+};
+
+TEST_F(HMIMessageHandlerImplTest,
+ OnErrorSending_EmptyMessage_OnErrorSendingProceeded) {
+ // Arrange
+ hmi_message_handler::MessageSharedPointer empty_message;
+ EXPECT_CALL(*mock_hmi_message_observer_, OnErrorSending(empty_message));
+ // Act
+ hmi_handler_->OnErrorSending(empty_message);
+}
+
+TEST_F(HMIMessageHandlerImplTest,
+ OnErrorSending_NotEmptyMessage_ExpectOnErrorSendingProceeded) {
+ // Arrange
+ utils::SharedPtr<application_manager::Message> message(
+ utils::MakeShared<application_manager::Message>(
+ protocol_handler::MessagePriority::FromServiceType(
+ protocol_handler::ServiceType::kControl)));
+
+ EXPECT_CALL(*mock_hmi_message_observer_, OnErrorSending(message));
+ // Act
+ hmi_handler_->OnErrorSending(message);
+}
+
+TEST_F(HMIMessageHandlerImplTest,
+ AddHMIMessageAdapter_AddExistedAdapter_ExpectAdded) {
+ // Check before action
+ EXPECT_TRUE(hmi_handler_->message_adapters().empty());
+ // Act
+ hmi_handler_->AddHMIMessageAdapter(mb_adapter_);
+ // Check after action
+ EXPECT_EQ(1u, hmi_handler_->message_adapters().size());
+}
+
+TEST_F(HMIMessageHandlerImplTest,
+ AddHMIMessageAdapter_AddUnexistedAdapter_ExpectNotAdded) {
+ // Check before action
+ EXPECT_TRUE(hmi_handler_->message_adapters().empty());
+ // Act
+ mb_adapter_ = NULL;
+ hmi_handler_->AddHMIMessageAdapter(mb_adapter_);
+ // Check adapter not added
+ EXPECT_TRUE(hmi_handler_->message_adapters().empty());
+}
+
+TEST_F(HMIMessageHandlerImplTest, RemoveHMIMessageAdapter_ExpectRemoved) {
+ // Arrange
+ hmi_handler_->AddHMIMessageAdapter(mb_adapter_);
+ // Act
+ hmi_handler_->RemoveHMIMessageAdapter(mb_adapter_);
+ // Check after action
+ EXPECT_TRUE(hmi_handler_->message_adapters().empty());
+}
+
+} // namespace hmi_message_handler_test
+} // namespace components
+} // namespace test
diff --git a/src/components/hmi_message_handler/test/include/hmi_message_handler/mock_dbus_message_controller.h b/src/components/hmi_message_handler/test/include/hmi_message_handler/mock_dbus_message_controller.h
index 7512f2ab19..eb449f7121 100644
--- a/src/components/hmi_message_handler/test/include/hmi_message_handler/mock_dbus_message_controller.h
+++ b/src/components/hmi_message_handler/test/include/hmi_message_handler/mock_dbus_message_controller.h
@@ -36,15 +36,14 @@
#include <pthread.h>
#include "hmi_message_handler/dbus_message_controller.h"
-class MockDBusMessageController :
- public ::hmi_message_handler::DBusMessageController {
+class MockDBusMessageController
+ : public ::hmi_message_handler::DBusMessageController {
public:
MOCK_METHOD1(Recv, void(std::string&));
MockDBusMessageController(const std::string& serviceName,
const std::string& path)
- : DBusMessageController(serviceName, path),
- thread_() {}
+ : DBusMessageController(serviceName, path), thread_() {}
virtual void processResponse(std::string method, Json::Value& root) {}
virtual void processRequest(Json::Value& root) {}
@@ -52,17 +51,18 @@ class MockDBusMessageController :
bool Init() {
return ::hmi_message_handler::DBusMessageController::Init() &&
- pthread_create(&thread_, 0, &Run, this) == 0;
+ pthread_create(&thread_, 0, &Run, this) == 0;
}
+
private:
pthread_t thread_;
static void* Run(void* data) {
if (NULL != data) {
- static_cast<MockDBusMessageController*>(data)->MethodForReceiverThread(nullptr);
+ static_cast<MockDBusMessageController*>(data)
+ ->MethodForReceiverThread(nullptr);
}
return 0;
}
};
-
#endif // TEST_COMPONENTS_HMI_MESSAGE_HANDLER_INCLUDE_HMI_MESSAGE_HANDLER_MOCK_DBUS_MESSAGE_CONTROLLER_H_
diff --git a/src/components/hmi_message_handler/test/include/hmi_message_handler/mock_hmi_message_adapter_impl.h b/src/components/hmi_message_handler/test/include/hmi_message_handler/mock_hmi_message_adapter_impl.h
new file mode 100644
index 0000000000..0ec82b7862
--- /dev/null
+++ b/src/components/hmi_message_handler/test/include/hmi_message_handler/mock_hmi_message_adapter_impl.h
@@ -0,0 +1,60 @@
+/*
+* Copyright (c) 2015, Ford Motor Company
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are met:
+*
+* Redistributions of source code must retain the above copyright notice, this
+* list of conditions and the following disclaimer.
+*
+* Redistributions in binary form must reproduce the above copyright notice,
+* this list of conditions and the following
+* disclaimer in the documentation and/or other materials provided with the
+* distribution.
+*
+* Neither the name of the Ford Motor Company nor the names of its contributors
+* may be used to endorse or promote products derived from this software
+* without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+* POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include "gmock/gmock.h"
+#include "hmi_message_handler/hmi_message_adapter_impl.h"
+#include "hmi_message_handler/hmi_message_handler.h"
+
+namespace test {
+namespace components {
+namespace hmi_message_handler_test {
+
+using hmi_message_handler::HMIMessageAdapterImpl;
+using hmi_message_handler::HMIMessageHandler;
+using hmi_message_handler::MessageSharedPointer;
+
+class MockHMIMessageAdapterImpl : public HMIMessageAdapterImpl {
+ public:
+ MockHMIMessageAdapterImpl(HMIMessageHandler* handler)
+ : HMIMessageAdapterImpl(handler) {}
+
+ MOCK_METHOD0(SubscribeTo, void());
+ MOCK_METHOD1(SendMessageToHMI, void(MessageSharedPointer SPtr));
+
+ HMIMessageHandler* get_handler() {
+ return HMIMessageAdapterImpl::handler();
+ }
+};
+
+} // namespace hmi_message_handler_test
+} // namespace components
+} // namespace test
diff --git a/src/components/hmi_message_handler/test/include/hmi_message_handler/mock_hmi_message_observer.h b/src/components/hmi_message_handler/test/include/hmi_message_handler/mock_hmi_message_observer.h
new file mode 100644
index 0000000000..09a8935ae7
--- /dev/null
+++ b/src/components/hmi_message_handler/test/include/hmi_message_handler/mock_hmi_message_observer.h
@@ -0,0 +1,57 @@
+/*
+* Copyright (c) 2015, Ford Motor Company
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are met:
+*
+* Redistributions of source code must retain the above copyright notice, this
+* list of conditions and the following disclaimer.
+*
+* Redistributions in binary form must reproduce the above copyright notice,
+* this list of conditions and the following
+* disclaimer in the documentation and/or other materials provided with the
+* distribution.
+*
+* Neither the name of the Ford Motor Company nor the names of its contributors
+* may be used to endorse or promote products derived from this software
+* without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+* POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef SRC_COMPONENTS_HMI_MESSAGE_HANDLER_TEST_INCLUDE_HMI_MESSAGE_HANDLER_MOCK_HMI_MESSAGE_OBSERVER_H_
+#define SRC_COMPONENTS_HMI_MESSAGE_HANDLER_TEST_INCLUDE_HMI_MESSAGE_HANDLER_MOCK_HMI_MESSAGE_OBSERVER_H_
+
+#include "gmock/gmock.h"
+#include "utils/shared_ptr.h"
+#include "utils/singleton.h"
+#include "hmi_message_handler/hmi_message_observer.h"
+#include "application_manager/message.h"
+
+namespace hmi_message_handler {
+
+using ::hmi_message_handler::HMIMessageObserver;
+
+class MockHMIMessageObserver : public HMIMessageObserver,
+ public utils::Singleton<MockHMIMessageObserver> {
+ public:
+ MOCK_METHOD1(OnMessageReceived,
+ void(utils::SharedPtr<application_manager::Message> message));
+ MOCK_METHOD1(OnErrorSending,
+ void(utils::SharedPtr<application_manager::Message> message));
+ virtual ~MockHMIMessageObserver() {}
+};
+} // namespace hmi_message_handler
+
+#endif // SRC_COMPONENTS_HMI_MESSAGE_HANDLER_TEST_INCLUDE_HMI_MESSAGE_HANDLER_MOCK_HMI_MESSAGE_OBSERVER_H_
diff --git a/src/components/hmi_message_handler/test/include/mock_subscriber.h b/src/components/hmi_message_handler/test/include/mock_subscriber.h
deleted file mode 100644
index 27e7cad1be..0000000000
--- a/src/components/hmi_message_handler/test/include/mock_subscriber.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
-* Copyright (c) 2014, Ford Motor Company
-* All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions are met:
-*
-* Redistributions of source code must retain the above copyright notice, this
-* list of conditions and the following disclaimer.
-*
-* Redistributions in binary form must reproduce the above copyright notice,
-* this list of conditions and the following
-* disclaimer in the documentation and/or other materials provided with the
-* distribution.
-*
-* Neither the name of the Ford Motor Company nor the names of its contributors
-* may be used to endorse or promote products derived from this software
-* without specific prior written permission.
-*
-* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-* POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#ifndef SRC_COMPONENTS_HMI_MESSAGE_HANDLER_TEST_INCLUDE_MOCK_SUBSCRIBER_H_
-#define SRC_COMPONENTS_HMI_MESSAGE_HANDLER_TEST_INCLUDE_MOCK_SUBSCRIBER_H_
-
-#include <string>
-
-struct DBusConnection;
-
-namespace test {
-namespace components {
-namespace hmi_message_handler {
-
-class MockSubscriber {
- public:
- MockSubscriber(const std::string &nameService, const std::string & path);
- virtual ~MockSubscriber();
- virtual void Receive();
- bool Start();
- void Send(const std::string& message);
-
- private:
- std::string nameService_;
- std::string path_;
- DBusConnection* conn_;
-};
-
-} // namespace hmi_message_handler
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_HMI_MESSAGE_HANDLER_TEST_INCLUDE_MOCK_SUBSCRIBER_H_
diff --git a/src/components/hmi_message_handler/test/mock_subscriber.cc b/src/components/hmi_message_handler/test/mock_subscriber.cc
index 3f1235bea9..c52d47b008 100644
--- a/src/components/hmi_message_handler/test/mock_subscriber.cc
+++ b/src/components/hmi_message_handler/test/mock_subscriber.cc
@@ -33,27 +33,21 @@
#include <dbus/dbus.h>
#include "include/mock_subscriber.h"
-
namespace test {
namespace components {
namespace hmi_message_handler {
-MockSubscriber::MockSubscriber(
- const std::string & nameService, const std::string & path)
- : nameService_(nameService),
- path_(path),
- conn_(NULL) {
-}
+MockSubscriber::MockSubscriber(const std::string& nameService,
+ const std::string& path)
+ : nameService_(nameService), path_(path), conn_(NULL) {}
-MockSubscriber::~MockSubscriber() {
-}
+MockSubscriber::~MockSubscriber() {}
-void MockSubscriber::Receive() {
-}
+void MockSubscriber::Receive() {}
bool MockSubscriber::Start() {
DBusError err;
- //int ret;
+ // int ret;
dbus_error_init(&err);
conn_ = dbus_bus_get(DBUS_BUS_SESSION, &err);
if (dbus_error_is_set(&err)) {
@@ -61,19 +55,18 @@ bool MockSubscriber::Start() {
return false;
}
-
std::string rule = "type='signal',interface='" + nameService_ + "'";
dbus_bus_add_match(conn_, rule.c_str(), &err);
dbus_connection_flush(conn_);
if (dbus_error_is_set(&err)) {
- dbus_error_free(&err);
+ dbus_error_free(&err);
return false;
}
return true;
}
void MockSubscriber::Send(const std::string& message) {
- // int a = message.length();
+ // int a = message.length();
}
} // namespace hmi_message_handler
diff --git a/src/components/hmi_message_handler/test/mqueue_adapter_test.cc b/src/components/hmi_message_handler/test/mqueue_adapter_test.cc
index 87fb3a3539..e5c5d2a396 100644
--- a/src/components/hmi_message_handler/test/mqueue_adapter_test.cc
+++ b/src/components/hmi_message_handler/test/mqueue_adapter_test.cc
@@ -51,8 +51,8 @@ class MockHandler : public HMIMessageHandler {
MOCK_METHOD1(SendMessageToHMI, void(MessageSharedPointer message));
};
-//TODO{ALeshin}: APPLINK-10846
-//TEST(MqueueAdapter, Send) {
+// TODO{ALeshin}: APPLINK-10846
+// TEST(MqueueAdapter, Send) {
// MockHandler handler;
// HMIMessageAdapter* adapter = new MqueueAdapter(&handler);
@@ -71,8 +71,8 @@ class MockHandler : public HMIMessageHandler {
// delete adapter;
//}
-//TODO{ALeshin}: APPLINK-10846
-//TEST(MqueueAdapter, Receive) {
+// TODO{ALeshin}: APPLINK-10846
+// TEST(MqueueAdapter, Receive) {
// MockHandler handler;
// HMIMessageAdapter* adapter = new MqueueAdapter(&handler);
diff --git a/src/components/include/application_manager/application_manager_settings.h b/src/components/include/application_manager/application_manager_settings.h
new file mode 100644
index 0000000000..b429da88c2
--- /dev/null
+++ b/src/components/include/application_manager/application_manager_settings.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_APPLICATION_MANAGER_APPLICATION_MANAGER_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_APPLICATION_MANAGER_APPLICATION_MANAGER_SETTINGS_H_
+
+#include "application_manager/request_controller_settings.h"
+
+#include <stdint.h>
+#include <string>
+
+namespace application_manager {
+class ApplicationManagerSettings : public RequestControlerSettings {
+ public:
+ virtual const uint32_t video_data_stopped_timeout() const = 0;
+ virtual const std::uint32_t audio_data_stopped_timeout() const = 0;
+ virtual const std::pair<uint32_t, int32_t>& read_did_frequency() const = 0;
+ virtual const std::pair<uint32_t, int32_t>& get_vehicle_data_frequency()
+ const = 0;
+ virtual uint32_t hash_string_size() const = 0;
+ virtual const std::string& app_storage_folder() const = 0;
+ virtual const uint32_t& app_dir_quota() const = 0;
+ virtual uint32_t stop_streaming_timeout() const = 0;
+ virtual uint32_t application_list_update_timeout() const = 0;
+ virtual uint32_t heart_beat_timeout() const = 0;
+ virtual const std::string& recording_file_name() const = 0;
+ virtual const std::string& system_files_path() const = 0;
+ virtual bool is_mixing_audio_supported() const = 0;
+ virtual uint16_t tts_global_properties_timeout() const = 0;
+ virtual uint16_t max_supported_protocol_version() const = 0;
+ virtual const uint32_t& default_timeout() const = 0;
+ virtual const uint32_t& max_cmd_id() const = 0;
+ virtual bool launch_hmi() const = 0;
+ virtual const uint32_t& delete_file_in_none() const = 0;
+ virtual const std::vector<uint32_t>& supported_diag_modes() const = 0;
+ virtual const uint32_t& list_files_in_none() const = 0;
+ virtual const std::string& tts_delimiter() const = 0;
+ virtual const uint32_t& put_file_in_none() const = 0;
+ virtual const std::string& sdl_version() const = 0;
+ virtual const std::vector<std::string>& time_out_promt() const = 0;
+ virtual const std::string& hmi_capabilities_file_name() const = 0;
+ virtual const std::string& video_server_type() const = 0;
+ virtual const std::string& audio_server_type() const = 0;
+ virtual const std::string& server_address() const = 0;
+ virtual const uint16_t video_streaming_port() const = 0;
+ virtual const uint16_t audio_streaming_port() const = 0;
+ virtual const std::string& named_video_pipe_path() const = 0;
+ virtual const std::string& named_audio_pipe_path() const = 0;
+ virtual const std::string& video_stream_file() const = 0;
+ virtual const std::string& audio_stream_file() const = 0;
+
+ virtual bool use_db_for_resumption() const = 0;
+ virtual const uint32_t& app_resumption_save_persistent_data_timeout()
+ const = 0;
+ virtual uint32_t resumption_delay_before_ign() const = 0;
+ virtual uint32_t resumption_delay_after_ign() const = 0;
+ virtual const uint32_t& app_resuming_timeout() const = 0;
+ virtual uint16_t attempts_to_open_resumption_db() const = 0;
+ virtual uint16_t open_attempt_timeout_ms_resumption_db() const = 0;
+ virtual void config_file_name(const std::string& fileName) = 0;
+ virtual const std::pair<uint32_t, int32_t>& start_stream_retry_amount()
+ const = 0;
+ virtual const std::string& app_icons_folder() const = 0;
+ virtual const uint32_t& app_icons_folder_max_size() const = 0;
+ virtual const uint32_t& app_icons_amount_to_remove() const = 0;
+ virtual const uint32_t& list_files_response_size() const = 0;
+};
+} // namespace application_manager
+
+#endif // SRC_COMPONENTS_INCLUDE_APPLICATION_MANAGER_APPLICATION_MANAGER_SETTINGS_H_
diff --git a/src/components/include/application_manager/policies/policy_handler_interface.h b/src/components/include/application_manager/policies/policy_handler_interface.h
new file mode 100644
index 0000000000..8fdb56b6df
--- /dev/null
+++ b/src/components/include/application_manager/policies/policy_handler_interface.h
@@ -0,0 +1,390 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_APPLICATION_MANAGER_POLICIES_POLICY_HANDLER_INTERFACE_H_
+#define SRC_COMPONENTS_INCLUDE_APPLICATION_MANAGER_POLICIES_POLICY_HANDLER_INTERFACE_H_
+
+#include <string>
+#include <map>
+#include <set>
+#include <vector>
+#include <queue>
+#include "interfaces/MOBILE_API.h"
+#include "policy/policy_types.h"
+#include "application_manager/policies/policy_handler_observer.h"
+#include "policy/usage_statistics/statistics_manager.h"
+#include "utils/custom_string.h"
+#include "policy/policy_settings.h"
+#include "smart_objects/smart_object.h"
+
+namespace policy {
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+class PolicyHandlerInterface {
+ public:
+ virtual ~PolicyHandlerInterface() {}
+
+ virtual bool LoadPolicyLibrary() = 0;
+ virtual bool PolicyEnabled() const = 0;
+ virtual bool InitPolicyTable() = 0;
+ virtual bool ResetPolicyTable() = 0;
+ virtual bool ClearUserConsent() = 0;
+ virtual bool SendMessageToSDK(const BinaryMessage& pt_string,
+ const std::string& url) = 0;
+ virtual bool ReceiveMessageFromSDK(const std::string& file,
+ const BinaryMessage& pt_string) = 0;
+ virtual bool UnloadPolicyLibrary() = 0;
+ virtual void OnPermissionsUpdated(const std::string& policy_app_id,
+ const Permissions& permissions,
+ const HMILevel& default_hmi) = 0;
+
+ virtual void OnPermissionsUpdated(const std::string& policy_app_id,
+ const Permissions& permissions) = 0;
+
+ virtual bool GetPriority(const std::string& policy_app_id,
+ std::string* priority) const = 0;
+ virtual void CheckPermissions(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ const RPCParams& rpc_params,
+ CheckPermissionResult& result) = 0;
+
+ virtual uint32_t GetNotificationsNumber(
+ const std::string& priority) const = 0;
+ virtual DeviceConsent GetUserConsentForDevice(
+ const std::string& device_id) const = 0;
+ virtual bool GetDefaultHmi(const std::string& policy_app_id,
+ std::string* default_hmi) const = 0;
+ virtual bool GetInitialAppData(const std::string& application_id,
+ StringArray* nicknames = NULL,
+ StringArray* app_hmi_types = NULL) = 0;
+ virtual void GetServiceUrls(const std::string& service_type,
+ EndpointUrls& end_points) = 0;
+ virtual std::string GetLockScreenIconUrl() const = 0;
+ virtual void ResetRetrySequence() = 0;
+ virtual uint32_t NextRetryTimeout() = 0;
+ virtual int TimeoutExchange() = 0;
+ virtual void OnExceededTimeout() = 0;
+ virtual void OnSystemReady() = 0;
+ virtual void PTUpdatedAt(Counters counter, int value) = 0;
+ virtual void add_listener(PolicyHandlerObserver* listener) = 0;
+ virtual void remove_listener(PolicyHandlerObserver* listener) = 0;
+
+ virtual utils::SharedPtr<usage_statistics::StatisticsManager>
+ GetStatisticManager() const = 0;
+
+ virtual void SendOnAppPermissionsChanged(
+ const AppPermissions& permissions,
+ const std::string& policy_app_id) const = 0;
+
+ /**
+ * @brief CheckSystemAction allows to check whether certain system
+ * action is enabled.
+ *
+ * @param system_action system action to check.
+ *
+ * @return true if specified system action is enabled, false otherwise.
+ */
+ virtual bool CheckSystemAction(mobile_apis::SystemAction::eType system_action,
+ const std::string& policy_app_id) const = 0;
+
+ /**
+ * Lets client to notify PolicyHandler that more kilometers expired
+ * @param kms New value of odometer
+ */
+ virtual void KmsChanged(int kms) = 0;
+
+ /**
+ * @brief Gather information for application and sends it to HMI
+ * @param connection_key Connection key for application
+ */
+ virtual void OnActivateApp(uint32_t connection_key,
+ uint32_t correlation_id) = 0;
+
+ /**
+ * @brief Process user consent on mobile data connection access
+ * @param Device id or empty string, if concern to all SDL functionality
+ * @param User consent from response
+ */
+ virtual void OnAllowSDLFunctionalityNotification(
+ bool is_allowed, const std::string& device_id) = 0;
+
+ /**
+ * @brief Increment counter for ignition cycles
+ */
+ virtual void OnIgnitionCycleOver() = 0;
+
+ virtual void OnPendingPermissionChange(const std::string& policy_app_id) = 0;
+
+ /**
+ * Initializes PT exchange at user request
+ * @param correlation_id correlation id of request
+ */
+ virtual void PTExchangeAtUserRequest(uint32_t correlation_id) = 0;
+
+ /**
+ * @brief Add's device to policy table
+ * @param device_id Device mac address
+ * @param connection_type Device connection type
+ */
+ virtual void AddDevice(const std::string& device_id,
+ const std::string& connection_type) = 0;
+
+ /**
+ * @brief Save device info for specific device to policy table
+ * @param device_id Device mac address
+ * @param device_info Device params
+ */
+ virtual void SetDeviceInfo(const std::string& device_id,
+ const DeviceInfo& device_info) = 0;
+
+ /**
+ * @brief Store user-changed permissions consent to DB
+ * @param connection_key Connection key of application or 0, if permissions
+ * should be applied to all applications
+ * @param permissions User-changed group permissions consent
+ */
+ virtual void OnAppPermissionConsent(const uint32_t connection_key,
+ const PermissionConsent& permissions) = 0;
+
+ /**
+ * @brief Get appropriate message parameters and send them with response
+ * to HMI
+ * @param message_codes RPC message codes
+ * @param language Language
+ * @param correlation_id correlation id of request
+ */
+ virtual void OnGetUserFriendlyMessage(
+ const std::vector<std::string>& message_codes,
+ const std::string& language,
+ uint32_t correlation_id) = 0;
+
+ /**
+ * @brief Get list of permissions for application/device binded to
+ * connection key from request and send response
+ * @param connection_key Connection key for specific application or 0 for all
+ * currently registered applications
+ * @param correlation_id Correlation id from request
+ */
+ virtual void OnGetListOfPermissions(const uint32_t connection_key,
+ const uint32_t correlation_id) = 0;
+
+ /**
+ * @brief Get current policy table update state and send response
+ * @param correlation_id Correlation id from request
+ */
+ virtual void OnGetStatusUpdate(const uint32_t correlation_id) = 0;
+
+ /**
+ * @brief Send notification to HMI with changed policy update status
+ * @param status Current policy update state
+ */
+ virtual void OnUpdateStatusChanged(const std::string& status) = 0;
+
+ /**
+ * @brief Update currently used device id in policies manager for given
+ * application
+ * @param policy_app_id Application id
+ */
+ virtual std::string OnCurrentDeviceIdUpdateRequired(
+ const std::string& policy_app_id) = 0;
+
+ /**
+ * @brief Set parameters from OnSystemInfoChanged to policy table
+ * @param language System language
+ */
+ virtual void OnSystemInfoChanged(const std::string& language) = 0;
+
+ /**
+ * @brief Save data from GetSystemInfo request to policy table
+ * @param ccpu_version CCPU version
+ * @param wers_country_code WERS country code
+ * @param language System language
+ */
+ virtual void OnGetSystemInfo(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language) = 0;
+
+ /**
+ * @brief Send request to HMI to get update on system parameters
+ */
+ virtual void OnSystemInfoUpdateRequired() = 0;
+
+ /**
+ * @brief Sends GetVehicleData request in case when Vechicle info is ready.
+ */
+ virtual void OnVIIsReady() = 0;
+
+ /**
+ * @brief Allows to update vechicle data info.
+ * @param SmartObject which contains all needed information.
+ */
+ virtual void OnVehicleDataUpdated(
+ const smart_objects::SmartObject& message) = 0;
+
+ /**
+ * Removes device
+ * @param device_id id of device
+ */
+ virtual void RemoveDevice(const std::string& device_id) = 0;
+
+ /**
+ * Adds statistics info
+ * @param type type of info
+ */
+ virtual void AddStatisticsInfo(int type) = 0;
+
+ /**
+ * Handles system error
+ * @param code code of error
+ */
+ virtual void OnSystemError(int code) = 0;
+
+ /**
+ * @brief Choose application id to be used for snapshot sending
+ * @return Application id or 0, if there are no applications registered
+ */
+ virtual uint32_t GetAppIdForSending() const = 0;
+
+ virtual utils::custom_string::CustomString GetAppName(
+ const std::string& policy_app_id) = 0;
+
+ virtual void OnUpdateHMIAppType(
+ std::map<std::string, StringArray> app_hmi_types) = 0;
+
+ virtual void OnCertificateUpdated(const std::string& certificate_data) = 0;
+
+ virtual bool CanUpdate() = 0;
+
+ virtual void OnDeviceConsentChanged(const std::string& device_id,
+ const bool is_allowed) = 0;
+
+ virtual void OnPTExchangeNeeded() = 0;
+
+ virtual void GetAvailableApps(std::queue<std::string>& apps) = 0;
+
+ /**
+ * @brief Allows to add new or update existed application during
+ * registration process
+ * @param application_id The policy aplication id.
+ */
+ virtual void AddApplication(const std::string& application_id) = 0;
+
+ /**
+ * Checks whether application is revoked
+ * @param app_id id application
+ * @return true if application is revoked
+ */
+ virtual bool IsApplicationRevoked(const std::string& app_id) = 0;
+
+ /**
+ * @brief Notifies policy manager, that PTS was sent out
+ */
+ virtual void OnUpdateRequestSentToMobile() = 0;
+
+ /**
+ * Returns heart beat timeout
+ * @param app_id application id
+ * @return if timeout was set then value in milliseconds greater zero
+ * otherwise heart beat for specific application isn't set
+ */
+ virtual uint32_t HeartBeatTimeout(const std::string& app_id) const = 0;
+
+ /**
+ * @brief Handler on applications search started
+ */
+ virtual void OnAppsSearchStarted() = 0;
+
+ /**
+ * @brief Handler on applications search completed
+ */
+ virtual void OnAppsSearchCompleted() = 0;
+
+ /**
+ * @brief OnAppRegisteredOnMobile allows to handle event when application were
+ * succesfully registered on mobile device.
+ * It will send OnAppPermissionSend notification and will try to start PTU.
+ *
+ * @param application_id registered application.
+ */
+ virtual void OnAppRegisteredOnMobile(const std::string& application_id) = 0;
+
+ /**
+ * @brief Checks if certain request type is allowed for application
+ * @param policy_app_id Unique applicaion id
+ * @param type Request type
+ * @return true, if allowed, otherwise - false
+ */
+ virtual bool IsRequestTypeAllowed(
+ const std::string& policy_app_id,
+ mobile_apis::RequestType::eType type) const = 0;
+
+ /**
+ * @brief Gets application request types
+ * @param policy_app_id Unique application id
+ * @return request types
+ */
+ virtual const std::vector<std::string> GetAppRequestTypes(
+ const std::string& policy_app_id) const = 0;
+
+ /**
+ * @brief Gets vehicle information
+ * @return Structure with vehicle information
+ */
+ virtual const VehicleInfo GetVehicleInfo() const = 0;
+
+ virtual void Increment(usage_statistics::GlobalCounterId type) = 0;
+ virtual void Increment(const std::string& app_id,
+ usage_statistics::AppCounterId type) = 0;
+ virtual void Set(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value) = 0;
+ virtual void Add(const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int32_t timespan_seconds) = 0;
+
+#ifdef ENABLE_SECURITY
+ virtual std::string RetrieveCertificate() const = 0;
+#endif // ENABLE_SECURITY
+
+ virtual const PolicySettings& get_settings() const = 0;
+ virtual const std::string RemoteAppsUrl() const = 0;
+
+ private:
+ virtual void OnAppPermissionConsentInternal(
+ const uint32_t connection_key, PermissionConsent& permissions) = 0;
+
+ friend class AppPermissionDelegate;
+};
+
+} // namespace policy
+
+#endif // SRC_COMPONENTS_INCLUDE_APPLICATION_MANAGER_POLICIES_POLICY_HANDLER_INTERFACE_H_
diff --git a/src/components/include/application_manager/request_controller_settings.h b/src/components/include/application_manager/request_controller_settings.h
new file mode 100644
index 0000000000..297b3f7ba1
--- /dev/null
+++ b/src/components/include/application_manager/request_controller_settings.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_APPLICATION_MANAGER_REQUEST_CONTROLLER_SETTINGS_H
+#define SRC_COMPONENTS_INCLUDE_APPLICATION_MANAGER_REQUEST_CONTROLLER_SETTINGS_H
+
+namespace application_manager {
+class RequestControlerSettings {
+ public:
+ virtual uint32_t thread_pool_size() const = 0;
+ virtual const uint32_t& app_hmi_level_none_time_scale() const = 0;
+ virtual const uint32_t& app_hmi_level_none_time_scale_max_requests()
+ const = 0;
+ virtual const uint32_t& app_time_scale() const = 0;
+ virtual const uint32_t& app_time_scale_max_requests() const = 0;
+ virtual const uint32_t& pending_requests_amount() const = 0;
+};
+} // namespace application_manager
+#endif // SRC_COMPONENTS_INCLUDE_APPLICATION_MANAGER_REQUEST_CONTROLLER_SETTINGS_H
diff --git a/src/components/include/application_manager/state_controller.h b/src/components/include/application_manager/state_controller.h
new file mode 100644
index 0000000000..2fe0492b42
--- /dev/null
+++ b/src/components/include/application_manager/state_controller.h
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_APPLICATION_MANAGER_STATE_CONTROLLER_H_
+#define SRC_COMPONENTS_INCLUDE_APPLICATION_MANAGER_STATE_CONTROLLER_H_
+
+#include "stdint.h"
+#include "application_manager/request_controller_settings.h"
+#include "application_manager/application_manager.h"
+#include "application_manager/application.h"
+
+namespace application_manager {
+class StateController {
+ public:
+ virtual void SetRegularState(ApplicationSharedPtr app,
+ HmiStatePtr state,
+ const bool SendActivateApp) = 0;
+
+ virtual void SetRegularState(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const mobile_apis::AudioStreamingState::eType audio_state,
+ const bool SendActivateApp) = 0;
+
+ virtual void SetRegularState(ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const bool SendActivateApp) = 0;
+ virtual void SetRegularState(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const mobile_apis::AudioStreamingState::eType audio_state,
+ const mobile_apis::SystemContext::eType system_context,
+ const bool SendActivateApp) = 0;
+
+ virtual void SetRegularState(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level) = 0;
+
+ virtual void SetRegularState(
+ ApplicationSharedPtr app,
+ const mobile_apis::AudioStreamingState::eType audio_state) = 0;
+
+ virtual void SetRegularState(
+ ApplicationSharedPtr app,
+ const mobile_apis::SystemContext::eType system_context) = 0;
+
+ virtual void SetRegularState(ApplicationSharedPtr app, HmiStatePtr state) = 0;
+
+ virtual void OnApplicationRegistered(
+ ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType default_level) = 0;
+
+ virtual int64_t SendBCActivateApp(ApplicationConstSharedPtr app,
+ hmi_apis::Common_HMILevel::eType level,
+ bool send_policy_priority) = 0;
+
+ virtual void OnNaviStreamingStarted() = 0;
+ virtual void OnNaviStreamingStopped() = 0;
+ virtual void OnStateChanged(ApplicationSharedPtr app,
+ HmiStatePtr old_state,
+ HmiStatePtr new_state) = 0;
+
+ virtual bool IsStateActive(HmiState::StateID state_id) const = 0;
+};
+} // namespace application_manager
+
+#endif // SRC_COMPONENTS_INCLUDE_APPLICATION_MANAGER_STATE_CONTROLLER_H_
diff --git a/src/components/include/connection_handler/connection_handler_settings.h b/src/components/include/connection_handler/connection_handler_settings.h
new file mode 100644
index 0000000000..a0984b5320
--- /dev/null
+++ b/src/components/include/connection_handler/connection_handler_settings.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_CONNECTION_HANDLER_CONNECTION_HANDLER_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_CONNECTION_HANDLER_CONNECTION_HANDLER_SETTINGS_H_
+#include <stdint.h>
+#include <vector>
+
+namespace connection_handler {
+
+/**
+ * \class ConnectionHandlerSettings
+ * \brief Interface for connection handler component settings.
+ */
+class ConnectionHandlerSettings {
+ public:
+ virtual ~ConnectionHandlerSettings() {}
+
+ virtual uint32_t heart_beat_timeout() const = 0;
+#ifdef ENABLE_SECURITY
+ virtual const std::vector<int>& force_protected_service() const = 0;
+ virtual const std::vector<int>& force_unprotected_service() const = 0;
+#endif // ENABLE_SECURITY
+};
+
+} // namespace connection_handler
+#endif // SRC_COMPONENTS_INCLUDE_CONNECTION_HANDLER_CONNECTION_HANDLER_SETTINGS_H_
diff --git a/src/components/include/hmi_message_handler/hmi_message_handler_settings.h b/src/components/include/hmi_message_handler/hmi_message_handler_settings.h
new file mode 100644
index 0000000000..5386869555
--- /dev/null
+++ b/src/components/include/hmi_message_handler/hmi_message_handler_settings.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_HMI_MESSAGE_HANDLER_HMI_MESSAGE_HANDLER_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_HMI_MESSAGE_HANDLER_HMI_MESSAGE_HANDLER_SETTINGS_H_
+
+#include <stdint.h>
+
+namespace hmi_message_handler {
+/**
+ * \class HMIMessageHandlerSettings
+ * \brief Interface for hmi message handler component settings.
+ */
+class HMIMessageHandlerSettings {
+ public:
+ virtual ~HMIMessageHandlerSettings() {}
+
+ virtual const uint64_t& thread_min_stack_size() const = 0;
+};
+} // namespace hmi_message_handler
+#endif // SRC_COMPONENTS_INCLUDE_HMI_MESSAGE_HANDLER_HMI_MESSAGE_HANDLER_SETTINGS_H_
diff --git a/src/components/include/media_manager/media_manager_settings.h b/src/components/include/media_manager/media_manager_settings.h
new file mode 100644
index 0000000000..e48a74b08d
--- /dev/null
+++ b/src/components/include/media_manager/media_manager_settings.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2016 Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_MEDIA_MANAGER_MEDIA_MANAGER_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_MEDIA_MANAGER_MEDIA_MANAGER_SETTINGS_H_
+#include <string>
+#include <stdint.h>
+
+namespace media_manager {
+
+/**
+ * \class MediaManagerSettings
+ * \brief Interface for media manager component settings.
+ */
+class MediaManagerSettings {
+ public:
+ virtual ~MediaManagerSettings() {}
+
+ virtual const std::string& video_server_type() const = 0;
+ virtual const std::string& audio_server_type() const = 0;
+ virtual const std::string& server_address() const = 0;
+ virtual const uint16_t video_streaming_port() const = 0;
+ virtual const uint16_t audio_streaming_port() const = 0;
+ virtual const std::string& named_video_pipe_path() const = 0;
+ virtual const std::string& named_audio_pipe_path() const = 0;
+ virtual const std::string& video_stream_file() const = 0;
+ virtual const std::string& audio_stream_file() const = 0;
+ virtual const std::string& app_storage_folder() const = 0;
+ virtual const std::string& app_resource_folder() const = 0;
+ virtual const std::string& recording_file_source() const = 0;
+};
+
+} // namespace media_manager
+#endif // SRC_COMPONENTS_INCLUDE_MEDIA_MANAGER_MEDIA_MANAGER_SETTINGS_H_
diff --git a/src/components/include/policy/policy_settings.h b/src/components/include/policy/policy_settings.h
new file mode 100644
index 0000000000..7e5b7d6f93
--- /dev/null
+++ b/src/components/include/policy/policy_settings.h
@@ -0,0 +1,42 @@
+#ifndef POLICY_HANDLER_SETTINGS_H
+#define POLICY_HANDLER_SETTINGS_H
+#include <string>
+#include <stdint.h>
+
+namespace policy {
+class PolicySettings {
+ public:
+ /**
+ * @brief Should Policy be turned off? (Library not loaded)
+ * @return Flag
+ */
+ virtual bool enable_policy() const = 0;
+ /*
+ * @brief Path to preloaded policy file
+ */
+ virtual const std::string& preloaded_pt_file() const = 0;
+
+ /**
+ * @brief Returns application storage path
+ */
+ virtual const std::string& app_storage_folder() const = 0;
+
+ virtual uint16_t attempts_to_open_policy_db() const = 0;
+
+ virtual uint16_t open_attempt_timeout_ms() const = 0;
+
+ /**
+ * @brief Path to policies snapshot file
+ * @return file path
+ */
+ virtual const std::string& policies_snapshot_file_name() const = 0;
+
+ /**
+ * @brief Returns system files folder path
+ */
+ virtual const std::string& system_files_path() const = 0;
+
+ virtual ~PolicySettings() {}
+};
+} // namespace policy
+#endif // POLICY_HANDLER_SETTINGS_H
diff --git a/src/components/include/policy/policy_types.h b/src/components/include/policy/policy_types.h
new file mode 100644
index 0000000000..f03278619c
--- /dev/null
+++ b/src/components/include/policy/policy_types.h
@@ -0,0 +1,318 @@
+/*
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_TYPES_H_
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_TYPES_H_
+
+#include <string>
+#include <vector>
+#include <map>
+#include <set>
+#include "utils/shared_ptr.h"
+#include "utils/helpers.h"
+
+namespace policy {
+
+// TODO(PV): specify errors
+enum PolicyErrorEnum {};
+
+const std::string kDefaultDeviceMacAddress = "00:00:00:00:00:00";
+const std::string kDefaultDeviceName = "MyDevice";
+const std::string kDefaultDeviceConnectionType = "UNKNOWN";
+
+/**
+ * @brief Constants for special ids in application policies section of
+ * policy table
+ */
+const std::string kPreDataConsentId = "pre_DataConsent";
+const std::string kDefaultId = "default";
+const std::string kDeviceId = "device";
+
+/*
+ * @brief Status of policy table update
+ */
+enum PolicyTableStatus {
+ StatusUpToDate = 0,
+ StatusUpdatePending,
+ StatusUpdateRequired,
+ StatusUnknown
+};
+
+// Code generator uses String class name, so this typedef was renamed to PTSring
+typedef std::string PTString;
+typedef std::vector<uint8_t> BinaryMessage;
+typedef utils::SharedPtr<BinaryMessage> BinaryMessageSptr;
+
+typedef std::string HMILevel;
+typedef std::string Parameter;
+typedef std::string RpcName;
+typedef std::vector<std::string> RPCParams;
+
+typedef std::map<std::string, std::set<policy::HMILevel> > HMIPermissions;
+typedef std::map<std::string, std::set<policy::Parameter> >
+ ParameterPermissions;
+
+struct RpcPermissions {
+ HMIPermissions hmi_permissions;
+ ParameterPermissions parameter_permissions;
+};
+
+typedef std::map<RpcName, RpcPermissions> Permissions;
+
+/**
+ * @brief Typedef for use with AllowApp request/notification
+ */
+typedef std::vector<std::string> PermissionsList;
+
+/**
+ * @brief Typedef for getting initial application data, e.g. nickname list
+ */
+typedef std::vector<std::string> StringArray;
+
+enum PermitResult { kRpcAllowed = 0, kRpcDisallowed, kRpcUserDisallowed };
+
+/**
+ * @struct Stores result of check:
+ * if HMI Level was allowed for RPC to work in
+ * and list of parameters allowed for RPC if specified in PT.
+ */
+struct CheckPermissionResult {
+ CheckPermissionResult() : hmi_level_permitted(kRpcDisallowed) {}
+
+ PermitResult hmi_level_permitted;
+ std::vector<PTString> list_of_allowed_params;
+ std::vector<PTString> list_of_disallowed_params;
+ std::vector<PTString> list_of_undefined_params;
+};
+
+/**
+ @struct Holds Url string and optional policy app id.
+ */
+struct EndpointData {
+ explicit EndpointData(const std::string& url_string = "")
+ : app_id("default") {
+ if (false == url_string.empty()) {
+ url.push_back(url_string);
+ }
+ }
+ std::vector<std::string> url;
+ std::string app_id;
+};
+
+typedef std::vector<EndpointData> EndpointUrls;
+
+/**
+ * @brief Struct contains device data to be used for dialogs, generation of IDs
+ */
+struct DeviceParams {
+ DeviceParams()
+ : device_name(kDefaultDeviceName)
+ , device_mac_address(kDefaultDeviceMacAddress)
+ , device_connection_type(kDefaultDeviceConnectionType)
+ , device_handle(0) {}
+
+ std::string device_name;
+ std::string device_mac_address;
+ std::string device_connection_type;
+ uint32_t device_handle;
+};
+
+/**
+ * @brief User consent for device data usage
+ */
+enum DeviceConsent {
+ kDeviceAllowed = 0,
+ kDeviceDisallowed,
+ kDeviceHasNoConsent
+};
+
+/**
+ * @brief Struct contains parameters, which can be received during application
+ * registration and should be stored in policy table
+ */
+struct DeviceInfo {
+ DeviceInfo() : max_number_rfcom_ports(0) {}
+
+ std::string hardware;
+ std::string firmware_rev;
+ std::string os;
+ std::string os_ver;
+ std::string carrier;
+ uint32_t max_number_rfcom_ports;
+ std::string connection_type;
+
+ void AdoptDeviceType(const std::string& deviceType) {
+ connection_type = "USB_serial_number";
+ using namespace helpers;
+ static const std::string bluetooth("BLUETOOTH");
+ static const std::string wifi("WIFI");
+ if (Compare<std::string, EQ, ONE>(deviceType, bluetooth, wifi)) {
+ connection_type.assign("BTMAC");
+ }
+ }
+};
+
+/**
+ * @brief User consent for functional group
+ */
+enum GroupConsent { kGroupAllowed = 0, kGroupDisallowed, kGroupUndefined };
+
+/**
+ * @brief Contains user permission for RPC functional group with specific name
+ * and id from DB
+ */
+struct FunctionalGroupPermission {
+ FunctionalGroupPermission() : group_id(0), state(kGroupUndefined) {}
+
+ bool operator==(const FunctionalGroupPermission& rhs) {
+ if (this->group_id == rhs.group_id &&
+ this->group_alias == rhs.group_alias &&
+ this->group_name == rhs.group_name) {
+ return true;
+ }
+ return false;
+ }
+
+ std::string group_alias;
+ std::string group_name;
+ int32_t group_id;
+ GroupConsent state;
+};
+
+/**
+ * @brief Stores data to be sent to HMI on application permissions change
+ */
+struct AppPermissions {
+ AppPermissions(const std::string& app_id)
+ : application_id(app_id)
+ , isAppPermissionsRevoked(false)
+ , appRevoked(false)
+ , appPermissionsConsentNeeded(false)
+ , appUnauthorized(false)
+ , requestTypeChanged(false) {}
+
+ std::string application_id;
+ bool isAppPermissionsRevoked;
+ std::vector<policy::FunctionalGroupPermission> appRevokedPermissions;
+ bool appRevoked;
+ bool appPermissionsConsentNeeded;
+ bool appUnauthorized;
+ bool isSDLAllowed;
+ std::string priority;
+ DeviceParams deviceInfo;
+ bool requestTypeChanged;
+ std::vector<std::string> requestType;
+};
+
+/**
+ * @brief Contains parameters for user-defined consent for appication
+ * functional groups on given device
+ */
+struct PermissionConsent {
+ std::string device_id;
+ std::string policy_app_id;
+ std::vector<FunctionalGroupPermission> group_permissions;
+ std::string consent_source;
+};
+
+/**
+ * @brief Contain data for GetUserFriendyMessage response
+ */
+struct UserFriendlyMessage {
+ std::string message_code;
+};
+
+/**
+ * @brief Types of functional groups in policy table
+ */
+enum GroupType {
+ kTypeDefault = 0, // groups assigned to 'default' permissions section
+ kTypeAllowed, // groups allowed by user for specific application
+ kTypeDisallowed, // groups disallowed by user for specific application
+ kTypeUnconsented, // groups disallowed by default but consent may be changed
+ // by user
+ kTypePreconsented, // groups allowed for specific application without
+ // user consent by default (could be changed by user)
+ kTypeGeneral, // groups assigned to specific application
+ kTypePreDataConsented, // groups assigned to 'pre_DataConsent' permissions
+ // section
+ kTypeDevice // groups assigned to 'device' permissions section
+};
+
+/**
+ * @brief Array of functional group id from DB
+ */
+typedef std::vector<int32_t> FunctionalGroupIDs;
+
+/**
+ * @brief Array of functional group ids sorted by types
+ */
+typedef std::map<GroupType, FunctionalGroupIDs> FunctionalIdType;
+
+/**
+ * @brief Array of functional group ids binded to user_consent_prompt (e.g.
+ * VehicleData) and group name (e.g. VehicleData-4)
+ */
+typedef std::map<uint32_t, std::pair<std::string, std::string> >
+ FunctionalGroupNames;
+
+/**
+ * @brief Array of device ids, which are an identifiers in policy table
+ */
+typedef std::vector<std::string> DeviceIds;
+
+/**
+ * @brief Counters that calculated on receiving of succesful update
+ */
+enum Counters { KILOMETERS, DAYS_AFTER_EPOCH };
+
+/**
+ * @struct Vehicle information
+ */
+struct VehicleInfo {
+ std::string vehicle_make;
+ std::string vehicle_model;
+ std::string vehicle_year;
+};
+
+/**
+ * @brief The MetaInfo information
+ */
+struct MetaInfo {
+ std::string ccpu_version;
+ std::string wers_country_code;
+ std::string language;
+};
+
+} // namespace policy
+
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_TYPES_H_
diff --git a/src/components/include/policy/usage_statistics/statistics_manager.h b/src/components/include/policy/usage_statistics/statistics_manager.h
new file mode 100644
index 0000000000..2b2c875d11
--- /dev/null
+++ b/src/components/include/policy/usage_statistics/statistics_manager.h
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_POLICY_USAGE_STATISTICS_STATISTICS_MANAGER_H_
+#define SRC_COMPONENTS_INCLUDE_POLICY_USAGE_STATISTICS_STATISTICS_MANAGER_H_
+
+#include <stdint.h>
+#include <string>
+
+namespace usage_statistics {
+
+enum GlobalCounterId { IAP_BUFFER_FULL, SYNC_OUT_OF_MEMORY, SYNC_REBOOTS };
+
+enum AppInfoId { LANGUAGE_GUI, LANGUAGE_VUI };
+
+enum AppStopwatchId {
+ SECONDS_HMI_FULL,
+ SECONDS_HMI_LIMITED,
+ SECONDS_HMI_BACKGROUND,
+ SECONDS_HMI_NONE
+};
+
+enum AppCounterId {
+ USER_SELECTIONS,
+ REJECTIONS_SYNC_OUT_OF_MEMORY,
+ REJECTIONS_NICKNAME_MISMATCH,
+ REJECTIONS_DUPLICATE_NAME,
+ REJECTED_RPC_CALLS,
+ RPCS_IN_HMI_NONE,
+ REMOVALS_MISBEHAVED,
+ RUN_ATTEMPTS_WHILE_REVOKED,
+ COUNT_OF_TLS_ERRORS,
+};
+
+class StatisticsManager {
+ public:
+ virtual ~StatisticsManager() {}
+ virtual void Increment(GlobalCounterId type) = 0;
+ virtual void Increment(const std::string& app_id, AppCounterId type) = 0;
+ virtual void Set(const std::string& app_id,
+ AppInfoId type,
+ const std::string& value) = 0;
+ virtual void Add(const std::string& app_id,
+ AppStopwatchId type,
+ int32_t timespan_seconds) = 0;
+};
+
+} // namespace usage_statistics
+
+#endif // SRC_COMPONENTS_INCLUDE_POLICY_USAGE_STATISTICS_STATISTICS_MANAGER_H_
diff --git a/src/components/include/protocol/common.h b/src/components/include/protocol/common.h
index 91bc53652c..ce4c4adf6f 100644
--- a/src/components/include/protocol/common.h
+++ b/src/components/include/protocol/common.h
@@ -79,12 +79,14 @@ enum {
*@brief Constant: number of protocol version (4).
* This protocol is compatibility with version 3
* Support SSL with Encryption, Video and Audio services
- * Support ControlFrame, End Service to/from mobile support, HeartBeat feature,
+ * Support ControlFrame, End Service to/from mobile support, HeartBeat
+ *feature,
* SDL4.0 feature.
*/
PROTOCOL_VERSION_4 = 0x04,
/**
- *\brief Maximum value of packet version field (size 4-bit) specified AppLink Protocol v.7
+ *\brief Maximum value of packet version field (size 4-bit) specified AppLink
+ *Protocol v.7
*/
PROTOCOL_VERSION_MAX = 0x0F
};
@@ -93,7 +95,7 @@ enum {
*\brief Flag of protection packet
* 1-bit field of AppLink protocol packet
*/
-const bool PROTECTION_ON = true;
+const bool PROTECTION_ON = true;
const bool PROTECTION_OFF = false;
/**
@@ -184,7 +186,8 @@ enum {
*/
FRAME_DATA_LAST_CONSECUTIVE = 0x00,
/**
- *\brief Maximum of consecutive frame numbers after which count has to roll over to 0x01
+ *\brief Maximum of consecutive frame numbers after which count has to roll
+ *over to 0x01
*/
FRAME_DATA_MAX_CONSECUTIVE = 0xFF,
diff --git a/src/components/include/protocol/message_priority.h b/src/components/include/protocol/message_priority.h
index baed0d89c4..c672af3a37 100644
--- a/src/components/include/protocol/message_priority.h
+++ b/src/components/include/protocol/message_priority.h
@@ -50,16 +50,17 @@ class MessagePriority {
static MessagePriority FromServiceType(ServiceType service_type);
// Trivial inline copy constructor
- MessagePriority(const MessagePriority &that);
+ MessagePriority(const MessagePriority& that);
// Ordering value which is used by queues to order messages
// Higher value means higher prioirty
size_t OrderingValue() const;
+
private:
// Constructor is private to prevent creation
// of random priorities in the code please use static constructor if you
// need priority value
- explicit MessagePriority(int32_t value): value_(value) {}
+ explicit MessagePriority(int32_t value) : value_(value) {}
size_t value_;
};
} // namespace protocol_handler
diff --git a/src/components/include/protocol/raw_message.h b/src/components/include/protocol/raw_message.h
index f9a035e174..99cb73ce67 100644
--- a/src/components/include/protocol/raw_message.h
+++ b/src/components/include/protocol/raw_message.h
@@ -54,8 +54,10 @@ class RawMessage {
* \param dataSize Message size
* \param payload_size Received data size
*/
- RawMessage(uint32_t connection_key, uint32_t protocol_version,
- const uint8_t *const data_param, uint32_t data_size,
+ RawMessage(uint32_t connection_key,
+ uint32_t protocol_version,
+ const uint8_t* const data_param,
+ uint32_t data_size,
uint8_t type = ServiceType::kRpc,
uint32_t payload_size = 0);
/**
@@ -74,11 +76,11 @@ class RawMessage {
/**
* \brief Getter for message string data
*/
- uint8_t *data() const;
+ uint8_t* data() const;
/**
* \brief Getter for message size
*/
- size_t data_size() const;
+ size_t data_size() const;
/**
* \brief Getter for actual data size
*/
@@ -104,7 +106,7 @@ class RawMessage {
private:
uint32_t connection_key_;
- uint8_t *data_;
+ uint8_t* data_;
size_t data_size_;
uint32_t protocol_version_;
ServiceType service_type_;
@@ -112,6 +114,6 @@ class RawMessage {
bool waiting_;
DISALLOW_COPY_AND_ASSIGN(RawMessage);
};
-typedef utils::SharedPtr<RawMessage> RawMessagePtr;
+typedef utils::SharedPtr<RawMessage> RawMessagePtr;
} // namespace protocol_handler
#endif // SRC_COMPONENTS_INCLUDE_PROTOCOL_RAW_MESSAGE_H_
diff --git a/src/components/include/protocol/rpc_type.h b/src/components/include/protocol/rpc_type.h
index 5419bb5fce..db4a808cfd 100644
--- a/src/components/include/protocol/rpc_type.h
+++ b/src/components/include/protocol/rpc_type.h
@@ -40,8 +40,8 @@ namespace protocol_handler {
// AppLink protocol 4.1.3 RpcType field
enum RpcType {
- kRpcTypeRequest = 0x0,
- kRpcTypeResponse = 0x1,
+ kRpcTypeRequest = 0x0,
+ kRpcTypeResponse = 0x1,
kRpcTypeNotification = 0x2,
kRpcTypeReserved
};
@@ -51,8 +51,8 @@ RpcType RpcTypeFromByte(uint8_t byte);
// Check and convert RpcType to byte value ready to be transmitted
uint8_t RpcTypeToByte(RpcType type);
-const char *RpcTypeToString(RpcType type);
+const char* RpcTypeToString(RpcType type);
-std::ostream &operator<<(std::ostream &os, RpcType rpc_type);
+std::ostream& operator<<(std::ostream& os, RpcType rpc_type);
} // namespace protocol_handler
#endif // SRC_COMPONENTS_INCLUDE_PROTOCOL_RPC_TYPE_H_
diff --git a/src/components/include/protocol/service_type.h b/src/components/include/protocol/service_type.h
index b5870e0af1..803b8106b8 100644
--- a/src/components/include/protocol/service_type.h
+++ b/src/components/include/protocol/service_type.h
@@ -66,11 +66,11 @@ const uint8_t SERVICE_TYPE_BULK = 0x0F;
Navi for video streaming, bulk for PutFile.
*/
enum ServiceType {
- kControl = SERVICE_TYPE_CONTROL,
- kRpc = SERVICE_TYPE_RPC,
- kAudio = SERVICE_TYPE_AUDIO,
+ kControl = SERVICE_TYPE_CONTROL,
+ kRpc = SERVICE_TYPE_RPC,
+ kAudio = SERVICE_TYPE_AUDIO,
kMobileNav = SERVICE_TYPE_NAVI,
- kBulk = SERVICE_TYPE_BULK,
+ kBulk = SERVICE_TYPE_BULK,
kInvalidServiceType
};
diff --git a/src/components/include/protocol_handler/protocol_handler.h b/src/components/include/protocol_handler/protocol_handler.h
index 9bb77ae483..183db21532 100644
--- a/src/components/include/protocol_handler/protocol_handler.h
+++ b/src/components/include/protocol_handler/protocol_handler.h
@@ -33,6 +33,7 @@
#define SRC_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_PROTOCOL_HANDLER_H_
#include "protocol/common.h"
+#include "protocol_handler/protocol_handler_settings.h"
/**
*\namespace protocol_handlerHandler
@@ -41,7 +42,7 @@
namespace protocol_handler {
class ProtocolObserver;
-
+class SessionObserver;
/**
* \class ProtocolHandler
* \brief Interface for component parsing protocol header
@@ -54,14 +55,14 @@ class ProtocolHandler {
* \param observer Pointer to object of the class implementing
* IProtocolObserver
*/
- virtual void AddProtocolObserver(ProtocolObserver *observer) = 0;
+ virtual void AddProtocolObserver(ProtocolObserver* observer) = 0;
/**
* \brief Removes pointer to higher layer handler for message exchange
* \param observer Pointer to object of the class implementing
* IProtocolObserver.
*/
- virtual void RemoveProtocolObserver(ProtocolObserver *observer) = 0;
+ virtual void RemoveProtocolObserver(ProtocolObserver* observer) = 0;
/**
* \brief Method for sending message to Mobile Application.
@@ -100,13 +101,18 @@ class ProtocolHandler {
virtual void SendEndService(int32_t connection_id,
uint8_t session_id,
uint8_t service_type) = 0;
+ /**
+ * \brief Protocol handler settings getter
+ * \return pointer to protocol handler settings class
+ */
+ virtual const ProtocolHandlerSettings& get_settings() const = 0;
+ virtual SessionObserver& get_session_observer() = 0;
protected:
/**
* \brief Destructor
*/
- virtual ~ProtocolHandler() {
- }
+ virtual ~ProtocolHandler() {}
};
} // namespace protocol_handler
#endif // SRC_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_PROTOCOL_HANDLER_H_
diff --git a/src/components/include/protocol_handler/protocol_handler_settings.h b/src/components/include/protocol_handler/protocol_handler_settings.h
new file mode 100644
index 0000000000..987b0ac449
--- /dev/null
+++ b/src/components/include/protocol_handler/protocol_handler_settings.h
@@ -0,0 +1,47 @@
+#ifndef SRC_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_PROTOCOL_HANDLER_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_PROTOCOL_HANDLER_SETTINGS_H_
+
+#include <cstdint>
+#include <string>
+#include <vector>
+
+namespace protocol_handler {
+/**
+ * \class ProtocolHandlerSettings
+ * \brief Interface for protocol handler component settings.
+ */
+class ProtocolHandlerSettings {
+ public:
+ virtual ~ProtocolHandlerSettings() {}
+
+ virtual size_t maximum_payload_size() const = 0;
+ virtual size_t message_frequency_count() const = 0;
+ virtual size_t message_frequency_time() const = 0;
+ virtual bool malformed_message_filtering() const = 0;
+ virtual size_t malformed_frequency_count() const = 0;
+ virtual size_t malformed_frequency_time() const = 0;
+ /*
+ * @brief Heartbeat timeout before closing connection
+ */
+ virtual uint32_t heart_beat_timeout() const = 0;
+
+ virtual uint16_t max_supported_protocol_version() const = 0;
+ /*
+ * @brief Protocol version, from .ini file.
+ */
+ virtual bool enable_protocol_4() const = 0;
+
+ virtual uint32_t multiframe_waiting_timeout() const = 0;
+#ifdef ENABLE_SECURITY
+ /**
+ * @brief Returns force protected services
+ */
+ virtual const std::vector<int>& force_protected_service() const = 0;
+ /**
+ * @brief Returns force unprotected services
+ */
+ virtual const std::vector<int>& force_unprotected_service() const = 0;
+#endif // ENABLE_SECURITY
+};
+} // namespace protocol_handler
+#endif // SRC_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_PROTOCOL_HANDLER_SETTINGS_H_
diff --git a/src/components/include/protocol_handler/protocol_observer.h b/src/components/include/protocol_handler/protocol_observer.h
index 3879a4057e..ca60052cc4 100644
--- a/src/components/include/protocol_handler/protocol_observer.h
+++ b/src/components/include/protocol_handler/protocol_observer.h
@@ -55,13 +55,13 @@ class ProtocolObserver {
*/
virtual void OnMessageReceived(const RawMessagePtr message) = 0;
- virtual void OnMobileMessageSent(const RawMessagePtr message) = 0;
+ virtual void OnMobileMessageSent(const RawMessagePtr message) = 0;
+
protected:
/**
* \brief Destructor
*/
- virtual ~ProtocolObserver() {
- }
+ virtual ~ProtocolObserver() {}
};
} // namespace protocol_handler
diff --git a/src/components/include/protocol_handler/session_observer.h b/src/components/include/protocol_handler/session_observer.h
index 355c62e646..5e630c6c74 100644
--- a/src/components/include/protocol_handler/session_observer.h
+++ b/src/components/include/protocol_handler/session_observer.h
@@ -39,26 +39,25 @@
#ifdef ENABLE_SECURITY
#include "security_manager/ssl_context.h"
#endif // ENABLE_SECURITY
-/**
- *\namespace protocol_handlerHandler
- *\brief Namespace for SmartDeviceLink ProtocolHandler related functionality.
- */
+ /**
+ *\namespace protocol_handlerHandler
+ *\brief Namespace for SmartDeviceLink ProtocolHandler related functionality.
+ */
namespace protocol_handler {
/**
* \brief HASH_ID constants.
* Hint: Shall not intersect with connection identifiers for correct handling
* these constants (Session identifier shall be greater than zero)
*/
-enum {
- HASH_ID_NOT_SUPPORTED = 0,
- HASH_ID_WRONG = 0xFFFF0000
-};
+enum { HASH_ID_NOT_SUPPORTED = 0, HASH_ID_WRONG = 0xFFFF0000 };
+
/**
* \class SessionObserver
* \brief Interface for making a bridge between ProtocolHandler and
* ConnectionHandler components.
*/
-// TODO(EZamakhov): Reconsider rename callbacks and SessionObserver to SessionManager
+// TODO(EZamakhov): Reconsider rename callbacks and SessionObserver to
+// SessionManager
// TODO(EZamakhov): Reconsider rename KeyFromPair and PairFromKey
class SessionObserver {
public:
@@ -75,39 +74,42 @@ class SessionObserver {
* \return uint32_t Id (number) of new session if successful, otherwise 0.
*/
virtual uint32_t OnSessionStartedCallback(
- const transport_manager::ConnectionUID &connection_handle,
- const uint8_t sessionId,
- const protocol_handler::ServiceType &service_type,
- const bool is_protected, uint32_t* hash_id) = 0;
+ const transport_manager::ConnectionUID connection_handle,
+ const uint8_t sessionId,
+ const protocol_handler::ServiceType& service_type,
+ const bool is_protected,
+ uint32_t* hash_id) = 0;
+
/**
* \brief Callback function used by ProtocolHandler
* when Mobile Application initiates session ending.
* \param connection_handle Connection identifier within which session exists
* \param sessionId Identifier of the session to be ended
- * \param hashCode Hash used only in second version of SmartDeviceLink protocol.
+ * \param hashCode Hash used only in second version of SmartDeviceLink
+ * protocol.
* If not equal to hash assigned to session on start then operation fails.
* \param service_type Type of service
* \return uint32_t 0 if operation fails, session key otherwise
*/
virtual uint32_t OnSessionEndedCallback(
- const transport_manager::ConnectionUID &connection_handle,
+ const transport_manager::ConnectionUID connection_handle,
const uint8_t sessionId,
- const uint32_t &hashCode,
- const protocol_handler::ServiceType &service_type) = 0;
+ const uint32_t& hashCode,
+ const protocol_handler::ServiceType& service_type) = 0;
/**
* \brief Callback function used by ProtocolHandler
* when Mobile Application start message flood
* \param connection_key used by other components as application identifier
*/
- virtual void OnApplicationFloodCallBack(const uint32_t &connection_key) = 0;
+ virtual void OnApplicationFloodCallBack(const uint32_t& connection_key) = 0;
/**
* \brief Callback function used by ProtocolHandler
* when Mobile Application sends malformed message
* \param connection_key used by other components as application identifier
*/
- virtual void OnMalformedMessageCallback(const uint32_t &connection_key) = 0;
+ virtual void OnMalformedMessageCallback(const uint32_t& connection_key) = 0;
/**
* \brief Creates unique identifier of session (can be used as hash)
@@ -118,8 +120,8 @@ class SessionObserver {
* \return uint32_t Unique key for session
*/
virtual uint32_t KeyFromPair(
- transport_manager::ConnectionUID connection_handle,
- uint8_t session_id) = 0;
+ transport_manager::ConnectionUID connection_handle,
+ uint8_t session_id) const = 0;
/**
* \brief Returns connection identifier and session number from given
@@ -128,10 +130,9 @@ class SessionObserver {
* \param connection_handle Connection identifier within which session exists
* \param sessionId Returned: Number of session
*/
- virtual void PairFromKey(
- uint32_t key,
- transport_manager::ConnectionUID *connection_handle,
- uint8_t *sessionId) = 0;
+ virtual void PairFromKey(uint32_t key,
+ transport_manager::ConnectionUID* connection_handle,
+ uint8_t* sessionId) const = 0;
/**
* \brief information about given Connection Key.
@@ -142,9 +143,9 @@ class SessionObserver {
* \return int32_t -1 in case of error or 0 in case of success
*/
virtual int32_t GetDataOnSessionKey(uint32_t key,
- uint32_t *app_id,
- std::list<int32_t> *sessions_list,
- uint32_t *device_id) = 0;
+ uint32_t* app_id,
+ std::list<int32_t>* sessions_list,
+ uint32_t* device_id) const = 0;
/**
* \brief information about device
@@ -155,21 +156,24 @@ class SessionObserver {
* \param connection_type Returned: type of connection (USB, BT, etc.)
* \return int32_t -1 in case of error or 0 in case of success
*/
- virtual int32_t GetDataOnDeviceID(uint32_t device_handle,
- std::string *device_name,
- std::list<uint32_t> *applications_list,
- std::string *mac_address,
- std::string *connection_type) = 0;
+ virtual int32_t GetDataOnDeviceID(
+ transport_manager::DeviceHandle device_handle,
+ std::string* device_name = NULL,
+ std::list<uint32_t>* applications_list = NULL,
+ std::string* mac_address = NULL,
+ std::string* connection_type = NULL) const = 0;
/**
- * \brief returns TRUE if session supports sending HEARTBEAT ACK to mobile side
+ * \brief returns TRUE if session supports sending HEARTBEAT ACK to mobile
+ * side
* \param connection_handle Connection identifier whithin which session exists
* \param session_id Identifier of the session
- * \return TRUE if session has protocol version which supports heartbeat otherwise returns FALSE
+ * \return TRUE if session has protocol version which supports heartbeat
+ * otherwise returns FALSE
*/
- virtual bool IsHeartBeatSupported(
- transport_manager::ConnectionUID connection_handle,
- uint8_t session_id) = 0;
+ virtual bool IsHeartBeatSupported(
+ transport_manager::ConnectionUID connection_handle,
+ uint8_t session_id) const = 0;
/**
* @brief returns protocol version which application supports
@@ -179,8 +183,8 @@ class SessionObserver {
* @return TRUE if session and connection exist otherwise returns FALSE
*/
virtual bool ProtocolVersionUsed(uint32_t connection_id,
- uint8_t session_id, uint8_t& protocol_version) = 0;
-
+ uint8_t session_id,
+ uint8_t& protocol_version) const = 0;
#ifdef ENABLE_SECURITY
/**
@@ -189,9 +193,8 @@ class SessionObserver {
* \param context SSLContext to be set
* \return \c SecurityQuery::ProtectSessionResult value
*/
- virtual int SetSSLContext(
- const uint32_t &key,
- security_manager::SSLContext *context) = 0;
+ virtual int SetSSLContext(const uint32_t& key,
+ security_manager::SSLContext* context) = 0;
/**
* \brief Gets crypto context of connection, use service_type to get NULL
* SSLContext for not protected services or ControlService (0x0)
@@ -200,9 +203,9 @@ class SessionObserver {
* \param service_type Type of service
* \return \ref SSLContext of connection
*/
- virtual security_manager::SSLContext *GetSSLContext(
- const uint32_t &key,
- const protocol_handler::ServiceType &service_type) = 0;
+ virtual security_manager::SSLContext* GetSSLContext(
+ const uint32_t& key,
+ const protocol_handler::ServiceType& service_type) = 0;
/**
* \brief Set protection flag to service in session by key
* to get current SSLContext of connection
@@ -210,16 +213,18 @@ class SessionObserver {
* \param service_type Type of service
*/
virtual void SetProtectionFlag(
- const uint32_t &key,
- const protocol_handler::ServiceType &service_type) = 0;
+ const uint32_t& key,
+ const protocol_handler::ServiceType& service_type) = 0;
+
+ virtual security_manager::SSLContext::HandshakeContext GetHandshakeContext(
+ uint32_t key) const = 0;
#endif // ENABLE_SECURITY
protected:
/**
* \brief Destructor
*/
- virtual ~SessionObserver() {
- }
+ virtual ~SessionObserver() {}
};
} // namespace protocol_handler
#endif // SRC_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_SESSION_OBSERVER_H_
diff --git a/src/components/include/security_manager/crypto_manager.h b/src/components/include/security_manager/crypto_manager.h
index 00c3833e62..9b11a8e4ae 100644
--- a/src/components/include/security_manager/crypto_manager.h
+++ b/src/components/include/security_manager/crypto_manager.h
@@ -30,42 +30,50 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef SRC_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_CRYPTO_MANAGER_H_
-#define SRC_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_CRYPTO_MANAGER_H_
+#ifndef SRC_COMPONENTS_INCLUDE_SECURITY_MANAGER_CRYPTO_MANAGER_H_
+#define SRC_COMPONENTS_INCLUDE_SECURITY_MANAGER_CRYPTO_MANAGER_H_
-#include <string>
+#include "application_manager/policies/policy_handler_observer.h"
+#include "security_manager/security_manager_settings.h"
/**
* \class security_manager::CryptoManager
* \brief Class factory, producing instances of \ref SSLContext
*
- * \fn security_manager::SSLContext *security_manager::CryptoManager::CreateSSLContext()
+ * \fn security_manager::SSLContext
+ **security_manager::CryptoManager::CreateSSLContext()
* \brief Creates an instance of \ref SSLContext class
*
- * \fn void security_manager::CryptoManager::ReleaseSSLContext(security_manager::SSLContext *context)
+ * \fn void
+ *security_manager::CryptoManager::ReleaseSSLContext(security_manager::SSLContext
+ **context)
* \brief Frees \ref SSLContext instance
*/
namespace security_manager {
class SSLContext;
-enum Mode { CLIENT, SERVER };
-enum Protocol { SSLv3, TLSv1, TLSv1_1, TLSv1_2};
-
-class CryptoManager {
+class CryptoManager : public policy::PolicyHandlerObserver {
public:
- virtual bool Init(Mode mode,
- Protocol protocol,
- const std::string &cert_filename,
- const std::string &key_filename,
- const std::string &ciphers_list,
- bool verify_peer) = 0;
- virtual void Finish() = 0;
- virtual SSLContext *CreateSSLContext() = 0;
- virtual void ReleaseSSLContext(SSLContext *context) = 0;
+ /**
+ * @brief Init allows to initialize cryptomanager with certain values.
+ *
+ * @return true in case initialization was succesfull, false otherwise.
+ */
+ virtual bool Init() = 0;
+ virtual SSLContext* CreateSSLContext() = 0;
+ virtual bool OnCertificateUpdated(const std::string& data) = 0;
+ virtual void ReleaseSSLContext(SSLContext* context) = 0;
virtual std::string LastError() const = 0;
- virtual ~CryptoManager() { }
+
+ virtual bool IsCertificateUpdateRequired() const = 0;
+ /**
+ * \brief Crypto manager settings getter
+ * \return pointer to crypto manager settings class
+ */
+ virtual const CryptoManagerSettings& get_settings() const = 0;
+ virtual ~CryptoManager() {}
};
} // namespace security_manager
-#endif // SRC_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_CRYPTO_MANAGER_H_
+#endif // SRC_COMPONENTS_INCLUDE_SECURITY_MANAGER_CRYPTO_MANAGER_H_
diff --git a/src/components/include/security_manager/security_manager.h b/src/components/include/security_manager/security_manager.h
index 252ec610a8..8ed0ff2912 100644
--- a/src/components/include/security_manager/security_manager.h
+++ b/src/components/include/security_manager/security_manager.h
@@ -40,83 +40,87 @@
#include "protocol_handler/protocol_observer.h"
#include "protocol_handler/session_observer.h"
-#include "security_manager/crypto_manager.h"
#include "security_manager/security_manager_listener.h"
namespace security_manager {
+
+class CryptoManager;
/**
- * \brief SecurityManager interface implements protocol_handler::ProtocolObserver
+ * \brief SecurityManager interface implements
+ * protocol_handler::ProtocolObserver
* and provide interface for handling Security queries from mobile side
*/
-class SecurityManager
- : public protocol_handler::ProtocolObserver {
+class SecurityManager : public protocol_handler::ProtocolObserver {
public:
/**
* \brief InternalErrors is 1 byte identifier of internal error
* Handle as binary data in Ford Protocol
*/
enum InternalErrors {
- ERROR_SUCCESS = 0x00,
- ERROR_INVALID_QUERY_SIZE = 0x01, // wrong size of query data
- ERROR_INVALID_QUERY_ID = 0x02, // unknown query id
- ERROR_NOT_SUPPORTED = 0x03, // SDL does not support encryption
- ERROR_SERVICE_ALREADY_PROTECTED = 0x04,
- ERROR_SERVICE_NOT_PROTECTED = 0x05, // got handshake or encrypted data
+ ERROR_SUCCESS = 0x00,
+ ERROR_INVALID_QUERY_SIZE = 0x01, // wrong size of query data
+ ERROR_INVALID_QUERY_ID = 0x02, // unknown query id
+ ERROR_NOT_SUPPORTED = 0x03, // SDL does not support encryption
+ ERROR_SERVICE_ALREADY_PROTECTED = 0x04,
+ ERROR_SERVICE_NOT_PROTECTED = 0x05, // got handshake or encrypted data
// for not protected service
- ERROR_DECRYPTION_FAILED = 0x06,
- ERROR_ENCRYPTION_FAILED = 0x07,
- ERROR_SSL_INVALID_DATA = 0x08,
- ERROR_INTERNAL = 0xFF,
- ERROR_UNKWOWN_INTERNAL_ERROR = 0xFE // error valeu for testing
+ ERROR_DECRYPTION_FAILED = 0x06,
+ ERROR_ENCRYPTION_FAILED = 0x07,
+ ERROR_SSL_INVALID_DATA = 0x08,
+ ERROR_INTERNAL = 0xFF,
+ ERROR_UNKNOWN_INTERNAL_ERROR = 0xFE // error value for testing
};
/**
* \brief Sets pointer for Connection Handler layer for managing sessions
* \param session_observer pointer to object of the class implementing
*/
virtual void set_session_observer(
- protocol_handler::SessionObserver *observer) = 0;
+ protocol_handler::SessionObserver* observer) = 0;
/**
* \brief Sets pointer for Protocol Handler layer for sending
* \param protocol_handler pointer to object of the class implementing
*/
virtual void set_protocol_handler(
- protocol_handler::ProtocolHandler *protocol_handler_) = 0;
+ protocol_handler::ProtocolHandler* protocol_handler_) = 0;
/**
* \brief Sets pointer for CryptoManager for handling SSLContext
* \param crypto_manager pointer to object of the class implementing
*/
- virtual void set_crypto_manager(CryptoManager *crypto_manager) = 0;
+ virtual void set_crypto_manager(CryptoManager* crypto_manager) = 0;
/**
* \brief Sends InternalError with text message to mobile application
- * \param connection_key Unique key used by other components as session identifier
+ * \param connection_key Unique key used by other components as session
+ * identifier
* \param error_id unique error identifier
* \param erorr_text SSL impelmentation error text
* \param seq_number received from Mobile Application
*/
virtual void SendInternalError(const uint32_t connection_key,
- const uint8_t &error_id,
- const std::string &erorr_text,
+ const uint8_t& error_id,
+ const std::string& erorr_text,
const uint32_t seq_number) = 0;
/**
* \brief Sends InternalError override methode for sending without seq_number
- * \param connection_key Unique key used by other components as session identifier
+ * \param connection_key Unique key used by other components as session
+ * identifier
* \param error_id unique error identifier
* \param erorr_text SSL impelmentation error text
*/
void SendInternalError(const uint32_t connection_key,
- const uint8_t &error_id,
- const std::string &erorr_text) {
+ const uint8_t& error_id,
+ const std::string& erorr_text) {
SendInternalError(connection_key, error_id, erorr_text, 0);
}
/**
* \brief Create new SSLContext for connection or return exists
* Do not notify listeners, send security error on occure
- * \param connection_key Unique key used by other components as session identifier
+ * \param connection_key Unique key used by other components as session
+ * identifier
* @return new \c SSLContext or \c NULL on any error
*/
- virtual SSLContext *CreateSSLContext(const uint32_t &connection_key) = 0;
+ virtual SSLContext* CreateSSLContext(const uint32_t& connection_key) = 0;
/**
* \brief Start handshake as SSL client
@@ -126,8 +130,8 @@ class SecurityManager
/**
* \brief Add/Remove for SecurityManagerListener
*/
- virtual void AddListener(SecurityManagerListener *const listener) = 0;
- virtual void RemoveListener(SecurityManagerListener *const listener) = 0;
+ virtual void AddListener(SecurityManagerListener* const listener) = 0;
+ virtual void RemoveListener(SecurityManagerListener* const listener) = 0;
};
} // namespace security_manager
#endif // SRC_COMPONENTS_INCLUDE_SECURITY_MANAGER_SECURITY_MANAGER_H_
diff --git a/src/components/include/security_manager/security_manager_listener.h b/src/components/include/security_manager/security_manager_listener.h
index 14a5dc3281..577c7c4378 100644
--- a/src/components/include/security_manager/security_manager_listener.h
+++ b/src/components/include/security_manager/security_manager_listener.h
@@ -37,12 +37,17 @@ class SecurityManagerListener {
public:
/**
* \brief Notification about protection result
- * \param connection_key Unique key used by other components as session identifier
+ * \param connection_key Unique key used by other components as session
+ * identifier
* \param success result of connection protection
* \return \c true on success notification or \c false otherwise
*/
virtual bool OnHandshakeDone(uint32_t connection_key,
- bool success) = 0;
+ SSLContext::HandshakeResult result) = 0;
+ /**
+ * @brief Notify listeners that certificate update is required.
+ */
+ virtual void OnCertificateUpdateRequired() = 0;
virtual ~SecurityManagerListener() {}
};
} // namespace security_manager
diff --git a/src/components/include/security_manager/security_manager_settings.h b/src/components/include/security_manager/security_manager_settings.h
new file mode 100644
index 0000000000..70f0452ef2
--- /dev/null
+++ b/src/components/include/security_manager/security_manager_settings.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_SUCURITY_MANAGER_SUCURITY_MANAGER_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_SUCURITY_MANAGER_SUCURITY_MANAGER_SETTINGS_H_
+
+namespace security_manager {
+enum Mode { CLIENT, SERVER };
+enum Protocol { SSLv3, TLSv1, TLSv1_1, TLSv1_2 };
+/**
+ * \class ConnectionHandlerSettings
+ * \brief Interface for connection handler component settings.
+ */
+class CryptoManagerSettings {
+ public:
+ virtual ~CryptoManagerSettings() {}
+
+ virtual Mode security_manager_mode() const = 0;
+ virtual Protocol security_manager_protocol_name() const = 0;
+ virtual bool verify_peer() const = 0;
+ virtual const std::string& certificate_data() const = 0;
+ virtual const std::string& ciphers_list() const = 0;
+ virtual const std::string& ca_cert_path() const = 0;
+ virtual size_t update_before_hours() const = 0;
+ virtual size_t maximum_payload_size() const = 0;
+};
+
+} // namespace security_manager
+#endif // SRC_COMPONENTS_INCLUDE_SUCURITY_MANAGER_SUCURITY_MANAGER_SETTINGS_H_
diff --git a/src/components/include/security_manager/security_query.h b/src/components/include/security_manager/security_query.h
new file mode 100644
index 0000000000..71d148b909
--- /dev/null
+++ b/src/components/include/security_manager/security_query.h
@@ -0,0 +1,194 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_SECURITY_QUERY_H_
+#define SRC_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_SECURITY_QUERY_H_
+
+#include <stdint.h>
+#include <cstddef>
+#include <vector>
+#include <string>
+#include "utils/shared_ptr.h"
+
+namespace security_manager {
+/**
+ * \brief SecurityQuery is wrapper for handling Mobile messages
+ * as security queries
+ */
+class SecurityQuery {
+ public:
+ /**
+ * \brief QueryType is 1 byte type of income query
+ * Equal RPC Type (Ford Binary Header Definition)
+ */
+ enum QueryType {
+ REQUEST = 0x00,
+ RESPONSE = 0x10,
+ NOTIFICATION = 0x20,
+ INVALID_QUERY_TYPE = 0xFF
+ };
+ /**
+ * \brief QueryId is 3 byte identifier of income query
+ * Equal RPC Function ID (Ford Binary Header Definition)
+ */
+ enum QueryId {
+ SEND_HANDSHAKE_DATA = 0x1,
+ SEND_INTERNAL_ERROR = 0x2,
+ INVALID_QUERY_ID = 0xFFFFFF
+ };
+ /**
+ * \brief QueryHeader is 12 byte header of security query
+ * Equal Ford Binary Header Definition
+ */
+ struct QueryHeader {
+ QueryHeader();
+ QueryHeader(uint8_t queryType,
+ uint32_t queryId,
+ uint32_t seqNumber = 0,
+ uint32_t jsonSize = 0);
+ // TODO(EZamakhov): check bitfield correctness on other endianness platform
+ uint32_t query_type : 8;
+ uint32_t query_id : 24; // API function identifier
+ uint32_t seq_number; // request sequential number
+ uint32_t json_size;
+ };
+
+ /**
+ * \brief Constructor
+ */
+ SecurityQuery();
+ /**
+ * \brief Constructor with header and connection_key
+ * \param connection_key Unique key used by other components as session
+ * identifier
+ * \param header QueryHeader
+ */
+ SecurityQuery(const QueryHeader& header, const uint32_t connection_key);
+ /**
+ * \brief Constructor with header, connection_key and query binary data
+ * \param connection_key Unique key used by other components as session
+ * identifier
+ * \param raw_data pointer to binary data array
+ * \param raw_data_size size of binary data array
+ * \param header QueryHeader
+ */
+ SecurityQuery(const QueryHeader& header,
+ const uint32_t connection_key,
+ const uint8_t* const raw_data,
+ const size_t raw_data_size);
+ /**
+ * \brief Serialize income from Mobile Application data
+ * as query with header and binary data or json message
+ * \param raw_data pointer to binary data array
+ * \param raw_data_size size of binary data array
+ * \return \c true on correct parse and \c false on wrong size of data
+ */
+ bool SerializeQuery(const uint8_t* const raw_data,
+ const size_t raw_data_size);
+ /**
+ * \brief Deserialize query for sending to Mobile Application
+ * \return \c vector of uint8_t data (serialized header data and send_data))
+ */
+ const std::vector<uint8_t> DeserializeQuery() const;
+ /**
+ * \brief Set binary data. (No header modification)
+ * \param binary_data pointer to binary data array
+ * \param bin_data_size size of binary data array
+ */
+ void set_data(const uint8_t* const binary_data, const size_t bin_data_size);
+ /**
+ * \brief Set json data. (No header modification)
+ * \param json_message string with json error
+ */
+ void set_json_message(const std::string& json_message);
+ /**
+ * \brief Set connection key
+ * \param connection_key Unique key used by other components as session
+ * identifier
+ */
+ void set_connection_key(const uint32_t connection_key);
+ /**
+ * \brief Set query header
+ * \param header of query
+ */
+ void set_header(const QueryHeader& header);
+ /**
+ * \brief Get query header
+ * \return header of query
+ */
+ const QueryHeader& get_header() const;
+ /**
+ * \brief Get query binary data (without header data)
+ * \return const pointer to const binary data
+ */
+ const uint8_t* get_data() const;
+ /**
+ * \brief Get query binary data size
+ * \return size of binary data
+ */
+ size_t get_data_size() const;
+ /**
+ * \brief Get json string data (without header data)
+ * \return const pointer to const binary data
+ */
+ const std::string& get_json_message() const;
+ /**
+ * \brief Get connection key
+ * \return Unique key used by other components as session identifier
+ */
+ uint32_t get_connection_key() const;
+
+ private:
+ /**
+ *\brief 12 byte header of security query
+ * Equal Ford Binary Header Definition
+ */
+ QueryHeader header_;
+ /**
+ *\brief nique key used by other components as session identifier
+ */
+ uint32_t connection_key_;
+ /**
+ *\brief Binary data of query (without header info)
+ */
+ std::vector<uint8_t> data_;
+ /**
+ *\brief JSON (string) value of query
+ */
+ std::string json_message_;
+};
+/**
+*\brief SmartPointer wrapper
+*/
+typedef utils::SharedPtr<SecurityQuery> SecurityQueryPtr;
+} // namespace security_manager
+#endif // SRC_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_SECURITY_QUERY_H_
diff --git a/src/components/include/security_manager/ssl_context.h b/src/components/include/security_manager/ssl_context.h
index e3f1dadc4f..86997edbd9 100644
--- a/src/components/include/security_manager/ssl_context.h
+++ b/src/components/include/security_manager/ssl_context.h
@@ -35,6 +35,9 @@
#include <cstddef> // for size_t typedef
#include <string>
+#include <ctype.h>
+#include <algorithm>
+#include "utils/custom_string.h"
// TODO(EZamakhov): update brief info
/**
@@ -53,33 +56,59 @@
*
* \param in_data [in] data sent by other side
* \param in_data_size [in] size of data in \ref in_data buffer
- * \param out_data [out] response of SSL context if there is one. If not, equals NULL
+ * \param out_data [out] response of SSL context if there is one. If not,
+ * equals NULL
* \param out_data_size [out] length of response. On no response, equals 0
*/
namespace security_manager {
+namespace custom_str = utils::custom_string;
class SSLContext {
public:
enum HandshakeResult {
- Handshake_Result_Success = 0x0,
- Handshake_Result_Fail = 0x1,
- Handshake_Result_AbnormalFail = 0x2
+ Handshake_Result_Success,
+ Handshake_Result_Fail,
+ Handshake_Result_AbnormalFail,
+ Handshake_Result_CertExpired,
+ Handshake_Result_NotYetValid,
+ Handshake_Result_CertNotSigned,
+ Handshake_Result_AppIDMismatch,
+ Handshake_Result_AppNameMismatch,
};
+
+ struct HandshakeContext {
+ HandshakeContext() : expected_sn(""), expected_cn("") {}
+
+ HandshakeContext(const custom_str::CustomString& exp_sn,
+ const custom_str::CustomString& exp_cn)
+ : expected_sn(exp_sn), expected_cn(exp_cn) {}
+
+ custom_str::CustomString expected_sn;
+ custom_str::CustomString expected_cn;
+ };
+
virtual HandshakeResult StartHandshake(const uint8_t** const out_data,
- size_t *out_data_size) = 0;
- virtual HandshakeResult DoHandshakeStep(const uint8_t *const in_data,
+ size_t* out_data_size) = 0;
+ virtual HandshakeResult DoHandshakeStep(const uint8_t* const in_data,
size_t in_data_size,
const uint8_t** const out_data,
- size_t *out_data_size) = 0;
- virtual bool Encrypt(const uint8_t *const in_data, size_t in_data_size,
- const uint8_t ** const out_data, size_t *out_data_size) = 0;
- virtual bool Decrypt(const uint8_t *const in_data, size_t in_data_size,
- const uint8_t ** const out_data, size_t *out_data_size) = 0;
- virtual bool IsInitCompleted() const = 0;
- virtual bool IsHandshakePending() const = 0;
+ size_t* out_data_size) = 0;
+ virtual bool Encrypt(const uint8_t* const in_data,
+ size_t in_data_size,
+ const uint8_t** const out_data,
+ size_t* out_data_size) = 0;
+ virtual bool Decrypt(const uint8_t* const in_data,
+ size_t in_data_size,
+ const uint8_t** const out_data,
+ size_t* out_data_size) = 0;
+ virtual bool IsInitCompleted() const = 0;
+ virtual bool IsHandshakePending() const = 0;
virtual size_t get_max_block_size(size_t mtu) const = 0;
virtual std::string LastError() const = 0;
- virtual ~SSLContext() { }
+
+ virtual void ResetConnection() = 0;
+ virtual void SetHandshakeContext(const HandshakeContext& hsh_ctx) = 0;
+ virtual ~SSLContext() {}
};
} // namespace security_manager
#endif // SRC_COMPONENTS_INCLUDE_SECURITY_MANAGER_SSL_CONTEXT_H_
diff --git a/src/components/include/telemetry_monitor/telemetry_observable.h b/src/components/include/telemetry_monitor/telemetry_observable.h
new file mode 100644
index 0000000000..bafa916925
--- /dev/null
+++ b/src/components/include/telemetry_monitor/telemetry_observable.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TELEMETRY_MONITOR_RESOURCE_OBSERVEABLE_H
+#define SRC_COMPONENTS_INCLUDE_TELEMETRY_MONITOR_RESOURCE_OBSERVEABLE_H
+namespace telemetry_monitor {
+
+template <class TelemetryObserver>
+class TelemetryObservable {
+ public:
+ virtual void SetTelemetryObserver(TelemetryObserver* observer) = 0;
+};
+} // namespace telemetry_monitor
+#endif // SRC_COMPONENTS_INCLUDE_TELEMETRY_MONITOR_RESOURCE_OBSERVEABLE_H
diff --git a/src/components/include/test/application_manager/mock_application_manager_settings.h b/src/components/include/test/application_manager/mock_application_manager_settings.h
new file mode 100644
index 0000000000..b1c32c982b
--- /dev/null
+++ b/src/components/include/test/application_manager/mock_application_manager_settings.h
@@ -0,0 +1,122 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_MOCK_APPLICATION_MANAGER_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_MOCK_APPLICATION_MANAGER_SETTINGS_H_
+
+#include <string>
+#include "gmock/gmock.h"
+#include "application_manager/application_manager_settings.h"
+
+namespace test {
+namespace components {
+namespace application_manager_test {
+
+class MockApplicationManagerSettings
+ : public application_manager::ApplicationManagerSettings {
+ public:
+ MOCK_CONST_METHOD0(video_data_stopped_timeout, const uint32_t());
+ MOCK_CONST_METHOD0(audio_data_stopped_timeout, const std::uint32_t());
+ // The following line won't really compile, as the return
+ // type has multiple template arguments. To fix it, use a
+ // typedef for the return type.
+ MOCK_CONST_METHOD0(read_did_frequency, const std::pair<uint32_t, int32_t>&());
+ // The following line won't really compile, as the return
+ // type has multiple template arguments. To fix it, use a
+ // typedef for the return type.
+ MOCK_CONST_METHOD0(get_vehicle_data_frequency,
+ const std::pair<uint32_t, int32_t>&());
+ MOCK_CONST_METHOD0(hash_string_size, uint32_t());
+ MOCK_CONST_METHOD0(app_storage_folder, const std::string&());
+ MOCK_CONST_METHOD0(app_dir_quota, const uint32_t&());
+ MOCK_CONST_METHOD0(stop_streaming_timeout, uint32_t());
+ MOCK_CONST_METHOD0(application_list_update_timeout, uint32_t());
+ MOCK_CONST_METHOD0(heart_beat_timeout, uint32_t());
+ MOCK_CONST_METHOD0(recording_file_name, const std::string&());
+ MOCK_CONST_METHOD0(system_files_path, const std::string&());
+ MOCK_CONST_METHOD0(is_mixing_audio_supported, bool());
+ MOCK_CONST_METHOD0(tts_global_properties_timeout, uint16_t());
+ MOCK_CONST_METHOD0(max_supported_protocol_version, uint16_t());
+ MOCK_CONST_METHOD0(default_timeout, const uint32_t&());
+ MOCK_CONST_METHOD0(max_cmd_id, const uint32_t&());
+ MOCK_CONST_METHOD0(launch_hmi, bool());
+ MOCK_CONST_METHOD0(delete_file_in_none, const uint32_t&());
+ MOCK_CONST_METHOD0(supported_diag_modes, const std::vector<uint32_t>&());
+ MOCK_CONST_METHOD0(list_files_in_none, const uint32_t&());
+ MOCK_CONST_METHOD0(tts_delimiter, const std::string&());
+ MOCK_CONST_METHOD0(put_file_in_none, const uint32_t&());
+ MOCK_CONST_METHOD0(sdl_version, const std::string&());
+ MOCK_CONST_METHOD0(time_out_promt, const std::vector<std::string>&());
+ MOCK_CONST_METHOD0(hmi_capabilities_file_name, const std::string&());
+ MOCK_CONST_METHOD0(video_server_type, const std::string&());
+ MOCK_CONST_METHOD0(audio_server_type, const std::string&());
+ MOCK_CONST_METHOD0(server_address, const std::string&());
+ MOCK_CONST_METHOD0(video_streaming_port, const uint16_t());
+ MOCK_CONST_METHOD0(audio_streaming_port, const uint16_t());
+ MOCK_CONST_METHOD0(named_video_pipe_path, const std::string&());
+ MOCK_CONST_METHOD0(named_audio_pipe_path, const std::string&());
+ MOCK_CONST_METHOD0(video_stream_file, const std::string&());
+ MOCK_CONST_METHOD0(audio_stream_file, const std::string&());
+ MOCK_CONST_METHOD0(use_db_for_resumption, bool());
+ MOCK_CONST_METHOD0(app_resumption_save_persistent_data_timeout,
+ const uint32_t&());
+ MOCK_CONST_METHOD0(resumption_delay_before_ign, uint32_t());
+ MOCK_CONST_METHOD0(resumption_delay_after_ign, uint32_t());
+ MOCK_CONST_METHOD0(app_resuming_timeout, const uint32_t&());
+ MOCK_CONST_METHOD0(attempts_to_open_resumption_db, uint16_t());
+ MOCK_CONST_METHOD0(open_attempt_timeout_ms_resumption_db, uint16_t());
+ MOCK_METHOD1(config_file_name, void(const std::string& fileName));
+ // The following line won't really compile, as the return
+ // type has multiple template arguments. To fix it, use a
+ // typedef for the return type.
+ MOCK_CONST_METHOD0(start_stream_retry_amount,
+ const std::pair<uint32_t, int32_t>&());
+ MOCK_CONST_METHOD0(app_icons_folder, const std::string&());
+ MOCK_CONST_METHOD0(app_icons_folder_max_size, const uint32_t&());
+ MOCK_CONST_METHOD0(app_icons_amount_to_remove, const uint32_t&());
+ MOCK_CONST_METHOD0(list_files_response_size, const uint32_t&());
+
+ // request controller settings section
+ MOCK_CONST_METHOD0(thread_pool_size, uint32_t());
+ MOCK_CONST_METHOD0(app_hmi_level_none_time_scale, const uint32_t&());
+ MOCK_CONST_METHOD0(app_hmi_level_none_time_scale_max_requests,
+ const uint32_t&());
+ MOCK_CONST_METHOD0(app_time_scale, const uint32_t&());
+ MOCK_CONST_METHOD0(app_time_scale_max_requests, const uint32_t&());
+ MOCK_CONST_METHOD0(pending_requests_amount, const uint32_t&());
+};
+
+} // namespace application_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_MOCK_APPLICATION_MANAGER_SETTINGS_H_
diff --git a/src/components/include/test/application_manager/mock_request_controller_settings.h b/src/components/include/test/application_manager/mock_request_controller_settings.h
new file mode 100644
index 0000000000..fe848f4a75
--- /dev/null
+++ b/src/components/include/test/application_manager/mock_request_controller_settings.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_MOCK_REQUEST_CONTROLLER_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_MOCK_REQUEST_CONTROLLER_SETTINGS_H_
+
+#include <map>
+#include <string>
+#include <vector>
+
+#include "gmock/gmock.h"
+#include "application_manager/request_controller_settings.h"
+
+namespace test {
+namespace components {
+namespace application_manager_test {
+
+class MockRequestControlerSettings
+ : public application_manager::RequestControlerSettings {
+ public:
+ MOCK_CONST_METHOD0(thread_pool_size, uint32_t());
+ MOCK_CONST_METHOD0(app_hmi_level_none_time_scale, const uint32_t&());
+ MOCK_CONST_METHOD0(app_hmi_level_none_time_scale_max_requests,
+ const uint32_t&());
+ MOCK_CONST_METHOD0(app_time_scale, const uint32_t&());
+ MOCK_CONST_METHOD0(app_time_scale_max_requests, const uint32_t&());
+ MOCK_CONST_METHOD0(pending_requests_amount, const uint32_t&());
+};
+
+} // namespace application_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_MOCK_REQUEST_CONTROLLER_SETTINGS_H_
diff --git a/src/components/include/test/application_manager/mock_state_controller.h b/src/components/include/test/application_manager/mock_state_controller.h
new file mode 100644
index 0000000000..9f8d94599b
--- /dev/null
+++ b/src/components/include/test/application_manager/mock_state_controller.h
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_MOCK_STATE_CONTROLLER_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_MOCK_STATE_CONTROLLER_H_
+
+#include "gmock/gmock.h"
+#include "application_manager/application.h"
+#include "application_manager/hmi_state.h"
+#include "application_manager/state_controller.h"
+#include "interfaces/MOBILE_API.h"
+#include "application_manager/application.h"
+
+namespace test {
+namespace components {
+namespace application_manager_test {
+namespace am = application_manager;
+
+class MockStateController : public am::StateController {
+ public:
+ MOCK_METHOD3(SetRegularState,
+ void(am::ApplicationSharedPtr app,
+ am::HmiStatePtr state,
+ const bool SendActivateApp));
+ MOCK_METHOD4(SetRegularState,
+ void(am::ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const mobile_apis::AudioStreamingState::eType audio_state,
+ const bool SendActivateApp));
+ MOCK_METHOD3(SetRegularState,
+ void(am::ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const bool SendActivateApp));
+ MOCK_METHOD5(SetRegularState,
+ void(am::ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level,
+ const mobile_apis::AudioStreamingState::eType audio_state,
+ const mobile_apis::SystemContext::eType system_context,
+ const bool SendActivateApp));
+ MOCK_METHOD2(SetRegularState,
+ void(am::ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType hmi_level));
+ MOCK_METHOD2(SetRegularState,
+ void(am::ApplicationSharedPtr app,
+ const mobile_apis::AudioStreamingState::eType audio_state));
+ MOCK_METHOD2(SetRegularState,
+ void(am::ApplicationSharedPtr app,
+ const mobile_apis::SystemContext::eType system_context));
+ MOCK_METHOD2(SetRegularState,
+ void(am::ApplicationSharedPtr app, am::HmiStatePtr state));
+ MOCK_METHOD2(OnApplicationRegistered,
+ void(am::ApplicationSharedPtr app,
+ const mobile_apis::HMILevel::eType default_level));
+ MOCK_METHOD3(SendBCActivateApp,
+ int64_t(am::ApplicationConstSharedPtr app,
+ hmi_apis::Common_HMILevel::eType level,
+ bool send_policy_priority));
+ MOCK_METHOD0(OnNaviStreamingStarted, void());
+ MOCK_METHOD0(OnNaviStreamingStopped, void());
+ MOCK_METHOD3(OnStateChanged,
+ void(am::ApplicationSharedPtr app,
+ am::HmiStatePtr old_state,
+ am::HmiStatePtr new_state));
+ MOCK_CONST_METHOD1(IsStateActive, bool(am::HmiState::StateID state_id));
+};
+
+} // namespace application_manager_test
+} // namespace components
+} // namespace test
+#endif // SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_MOCK_STATE_CONTROLLER_H_
diff --git a/src/components/include/test/application_manager/policies/mock_policy_handler_interface.h b/src/components/include/test/application_manager/policies/mock_policy_handler_interface.h
new file mode 100644
index 0000000000..a4498f5934
--- /dev/null
+++ b/src/components/include/test/application_manager/policies/mock_policy_handler_interface.h
@@ -0,0 +1,212 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_POLICY_HANDLER_INTERFACE_H_
+#define SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_POLICY_HANDLER_INTERFACE_H_
+
+#include "application_manager/policies/policy_handler_interface.h"
+#include "gmock/gmock.h"
+#include "policy/policy_types.h"
+
+namespace test {
+namespace components {
+namespace policy_test {
+
+namespace smart_objects = NsSmartDeviceLink::NsSmartObjects;
+class MockPolicyHandlerInterface : public policy::PolicyHandlerInterface {
+ public:
+ MOCK_METHOD0(LoadPolicyLibrary, bool());
+ MOCK_CONST_METHOD0(PolicyEnabled, bool());
+ MOCK_METHOD0(InitPolicyTable, bool());
+ MOCK_METHOD0(ResetPolicyTable, bool());
+ MOCK_METHOD0(ClearUserConsent, bool());
+ MOCK_METHOD2(SendMessageToSDK,
+ bool(const policy::BinaryMessage& pt_string,
+ const std::string& url));
+ MOCK_METHOD2(ReceiveMessageFromSDK,
+ bool(const std::string& file,
+ const policy::BinaryMessage& pt_string));
+ MOCK_METHOD0(UnloadPolicyLibrary, bool());
+ MOCK_METHOD3(OnPermissionsUpdated,
+ void(const std::string& policy_app_id,
+ const policy::Permissions& permissions,
+ const policy::HMILevel& default_hmi));
+ MOCK_METHOD2(OnPermissionsUpdated,
+ void(const std::string& policy_app_id,
+ const policy::Permissions& permissions));
+ MOCK_METHOD3(OnSnapshotCreated,
+ void(const policy::BinaryMessage& pt_string,
+ const std::vector<int>& retry_delay_seconds,
+ int timeout_exchange));
+ MOCK_CONST_METHOD2(GetPriority,
+ bool(const std::string& policy_app_id,
+ std::string* priority));
+ MOCK_METHOD5(CheckPermissions,
+ void(const policy::PTString& app_id,
+ const policy::PTString& hmi_level,
+ const policy::PTString& rpc,
+ const policy::RPCParams& rpc_params,
+ policy::CheckPermissionResult& result));
+ MOCK_CONST_METHOD1(GetNotificationsNumber,
+ uint32_t(const std::string& priority));
+ MOCK_CONST_METHOD1(GetUserConsentForDevice,
+ policy::DeviceConsent(const std::string& device_id));
+ MOCK_CONST_METHOD2(GetDefaultHmi,
+ bool(const std::string& policy_app_id,
+ std::string* default_hmi));
+
+ MOCK_METHOD3(GetInitialAppData,
+ bool(const std::string& application_id,
+ policy::StringArray* nicknames,
+ policy::StringArray* app_hmi_types));
+ MOCK_METHOD2(GetInitialAppData,
+ bool(const std::string& application_id,
+ policy::StringArray* nicknames));
+ MOCK_METHOD1(GetInitialAppData, bool(const std::string& application_id));
+ MOCK_METHOD2(GetUpdateUrls,
+ void(int service_type, policy::EndpointUrls& end_points));
+ MOCK_CONST_METHOD0(GetLockScreenIconUrl, std::string());
+ MOCK_METHOD0(ResetRetrySequence, void());
+ MOCK_METHOD0(NextRetryTimeout, uint32_t());
+ MOCK_METHOD0(TimeoutExchange, int());
+ MOCK_METHOD0(OnExceededTimeout, void());
+ MOCK_METHOD0(OnSystemReady, void());
+ MOCK_METHOD2(PTUpdatedAt, void(policy::Counters counter, int value));
+ MOCK_METHOD1(add_listener, void(policy::PolicyHandlerObserver* listener));
+ MOCK_METHOD1(remove_listener, void(policy::PolicyHandlerObserver* listener));
+ MOCK_CONST_METHOD0(GetStatisticManager,
+ utils::SharedPtr<usage_statistics::StatisticsManager>());
+ MOCK_CONST_METHOD2(CheckSystemAction,
+ bool(mobile_apis::SystemAction::eType system_action,
+ const std::string& policy_app_id));
+ MOCK_METHOD1(KmsChanged, void(int kms));
+ MOCK_METHOD2(OnActivateApp,
+ void(uint32_t connection_key, uint32_t correlation_id));
+ MOCK_METHOD2(OnAllowSDLFunctionalityNotification,
+ void(bool is_allowed, const std::string& device_id));
+ MOCK_METHOD0(OnIgnitionCycleOver, void());
+ MOCK_METHOD1(OnPendingPermissionChange,
+ void(const std::string& policy_app_id));
+ MOCK_METHOD1(PTExchangeAtUserRequest, void(uint32_t correlation_id));
+ MOCK_METHOD2(AddDevice,
+ void(const std::string& device_id,
+ const std::string& connection_type));
+ MOCK_METHOD2(SetDeviceInfo,
+ void(const std::string& device_id,
+ const policy::DeviceInfo& device_info));
+ MOCK_METHOD2(OnAppPermissionConsent,
+ void(const uint32_t connection_key,
+ const policy::PermissionConsent& permissions));
+ MOCK_METHOD3(OnGetUserFriendlyMessage,
+ void(const std::vector<std::string>& message_codes,
+ const std::string& language,
+ uint32_t correlation_id));
+ MOCK_METHOD2(OnGetListOfPermissions,
+ void(const uint32_t connection_key,
+ const uint32_t correlation_id));
+ MOCK_METHOD1(OnGetStatusUpdate, void(const uint32_t correlation_id));
+ MOCK_METHOD1(OnUpdateStatusChanged, void(const std::string& status));
+ MOCK_METHOD1(OnCurrentDeviceIdUpdateRequired,
+ std::string(const std::string& policy_app_id));
+ MOCK_METHOD1(OnSystemInfoChanged, void(const std::string& language));
+ MOCK_METHOD3(OnGetSystemInfo,
+ void(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language));
+ MOCK_METHOD0(OnSystemInfoUpdateRequired, void());
+ MOCK_METHOD0(OnVIIsReady, void());
+ MOCK_METHOD1(OnVehicleDataUpdated,
+ void(const smart_objects::SmartObject& message));
+ MOCK_METHOD1(RemoveDevice, void(const std::string& device_id));
+ MOCK_METHOD1(AddStatisticsInfo, void(int type));
+ MOCK_METHOD1(OnSystemError, void(int code));
+ MOCK_CONST_METHOD0(GetAppIdForSending, uint32_t());
+ MOCK_METHOD1(
+ GetAppName,
+ utils::custom_string::CustomString(const std::string& policy_app_id));
+ MOCK_METHOD1(OnUpdateHMIAppType,
+ void(std::map<std::string, policy::StringArray> app_hmi_types));
+ MOCK_METHOD1(OnCertificateUpdated, void(const std::string& certificate_data));
+ MOCK_METHOD1(OnCertificateDecrypted, void(bool is_succeeded));
+ MOCK_METHOD0(CanUpdate, bool());
+ MOCK_METHOD2(OnDeviceConsentChanged,
+ void(const std::string& device_id, bool is_allowed));
+ MOCK_CONST_METHOD2(SendOnAppPermissionsChanged,
+ void(const policy::AppPermissions& permissions,
+ const std::string& policy_app_id));
+ MOCK_METHOD0(OnPTExchangeNeeded, void());
+ MOCK_METHOD1(GetAvailableApps, void(std::queue<std::string>& apps));
+ MOCK_METHOD1(AddApplication, void(const std::string& application_id));
+ MOCK_METHOD1(IsApplicationRevoked, bool(const std::string& app_id));
+ MOCK_METHOD0(OnUpdateRequestSentToMobile, void());
+ MOCK_CONST_METHOD1(HeartBeatTimeout, uint32_t(const std::string& app_id));
+ MOCK_METHOD0(OnAppsSearchStarted, void());
+ MOCK_METHOD0(OnAppsSearchCompleted, void());
+ MOCK_METHOD1(OnAppRegisteredOnMobile,
+ void(const std::string& application_id));
+ MOCK_CONST_METHOD2(IsRequestTypeAllowed,
+ bool(const std::string& policy_app_id,
+ mobile_apis::RequestType::eType type));
+ MOCK_CONST_METHOD1(
+ GetAppRequestTypes,
+ const std::vector<std::string>(const std::string& policy_app_id));
+ MOCK_CONST_METHOD0(GetVehicleInfo, const policy::VehicleInfo());
+ MOCK_METHOD1(Increment, void(usage_statistics::GlobalCounterId type));
+ MOCK_METHOD2(Increment,
+ void(const std::string& app_id,
+ usage_statistics::AppCounterId type));
+ MOCK_METHOD3(Set,
+ void(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value));
+ MOCK_METHOD3(Add,
+ void(const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int32_t timespan_seconds));
+ MOCK_CONST_METHOD0(RetrieveCertificate, std::string());
+ MOCK_CONST_METHOD0(get_settings, const policy::PolicySettings&());
+ MOCK_CONST_METHOD0(RemoteAppsUrl, const std::string());
+ MOCK_METHOD2(GetServiceUrls,
+ void(const std::string& service_type,
+ policy::EndpointUrls& end_points));
+
+ private:
+ MOCK_METHOD2(OnAppPermissionConsentInternal,
+ void(const uint32_t connection_key,
+ policy::PermissionConsent& permissions));
+};
+
+} // namespace policy_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_APPLICATION_MANAGER_TEST_INCLUDE_APPLICATION_MANAGER_MOCK_POLICY_HANDLER_INTERFACE_H_
diff --git a/src/components/include/test/application_manager/policies/mock_policy_handler_observer.h b/src/components/include/test/application_manager/policies/mock_policy_handler_observer.h
new file mode 100644
index 0000000000..cc0f73126b
--- /dev/null
+++ b/src/components/include/test/application_manager/policies/mock_policy_handler_observer.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_POLICIES_MOCK_POLICY_HANDLER_OBSERVER_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_POLICIES_MOCK_POLICY_HANDLER_OBSERVER_H_
+
+#include <map>
+#include <string>
+#include <vector>
+
+#include "gmock/gmock.h"
+#include "application_manager/policies/policy_handler_observer.h"
+
+namespace test {
+namespace components {
+namespace application_manager_test {
+
+class MockPolicyHandlerObserver : public ::policy::PolicyHandlerObserver {
+ public:
+ MOCK_METHOD1(OnUpdateHMIAppType,
+ void(std::map<std::string, std::vector<std::string> >));
+ MOCK_METHOD1(OnCertificateUpdated, bool(const std::string&));
+};
+} // namespace application_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_APPLICATION_MANAGER_POLICIES_MOCK_POLICY_HANDLER_OBSERVER_H_
diff --git a/src/components/include/test/connection_handler/mock_connection_handler.h b/src/components/include/test/connection_handler/mock_connection_handler.h
new file mode 100644
index 0000000000..eac82cc177
--- /dev/null
+++ b/src/components/include/test/connection_handler/mock_connection_handler.h
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_CONNECTION_HANDLER_MOCK_CONNECTION_HANDLER_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_CONNECTION_HANDLER_MOCK_CONNECTION_HANDLER_H_
+
+#include <string>
+#include <list>
+#include <vector>
+
+#include "gmock/gmock.h"
+#include "connection_handler/connection_handler.h"
+#include "connection_handler/connection_handler_observer.h"
+#include "connection_handler/devices_discovery_starter.h"
+#include "connection_handler/connection_handler_settings.h"
+
+namespace test {
+namespace components {
+namespace connection_handler_test {
+
+using connection_handler::ConnectionHandle;
+using connection_handler::DeviceHandle;
+using connection_handler::CloseSessionReason;
+using connection_handler::DevicesDiscoveryStarter;
+
+class MockConnectionHandler : public connection_handler::ConnectionHandler {
+ public:
+ MOCK_METHOD1(set_connection_handler_observer,
+ void(connection_handler::ConnectionHandlerObserver* observer));
+ MOCK_METHOD0(StartTransportManager, void());
+ MOCK_METHOD1(ConnectToDevice,
+ void(connection_handler::DeviceHandle device_handle));
+ MOCK_METHOD0(ConnectToAllDevices, void());
+ MOCK_METHOD1(CloseRevokedConnection, void(uint32_t connection_key));
+ MOCK_METHOD1(CloseConnection, void(ConnectionHandle connection_handle));
+ MOCK_METHOD1(GetConnectionSessionsCount, uint32_t(uint32_t connection_key));
+ MOCK_METHOD2(GetDeviceID,
+ bool(const std::string& mac_address,
+ DeviceHandle* device_handle));
+ MOCK_METHOD2(CloseSession,
+ void(uint32_t key, CloseSessionReason close_reason));
+ MOCK_METHOD3(CloseSession,
+ void(ConnectionHandle connection_handle,
+ uint8_t session_id,
+ CloseSessionReason close_reason));
+ MOCK_METHOD2(SendEndService, void(uint32_t key, uint8_t service_type));
+ MOCK_METHOD1(StartSessionHeartBeat, void(uint32_t connection_key));
+ MOCK_METHOD2(SendHeartBeat,
+ void(ConnectionHandle connection_handle, uint8_t session_id));
+ MOCK_METHOD2(SetHeartBeatTimeout,
+ void(uint32_t connection_key, uint32_t timeout));
+ MOCK_METHOD2(KeepConnectionAlive,
+ void(uint32_t connection_key, uint8_t session_id));
+ MOCK_METHOD2(BindProtocolVersionWithSession,
+ void(uint32_t connection_key, uint8_t protocol_version));
+ MOCK_CONST_METHOD4(GetDataOnSessionKey,
+ int32_t(uint32_t key,
+ uint32_t* app_id,
+ std::list<int32_t>* sessions_list,
+ uint32_t* device_id));
+ MOCK_CONST_METHOD0(get_settings,
+ const connection_handler::ConnectionHandlerSettings&());
+ MOCK_METHOD0(get_session_observer,
+ const protocol_handler::SessionObserver&());
+ MOCK_METHOD0(get_device_discovery_starter, DevicesDiscoveryStarter&());
+ MOCK_CONST_METHOD1(GetConnectedDevicesMAC,
+ void(std::vector<std::string>& macs));
+};
+
+} // namespace connection_handler_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_CONNECTION_HANDLER_MOCK_CONNECTION_HANDLER_H_
diff --git a/src/components/include/test/connection_handler/mock_connection_handler_settings.h b/src/components/include/test/connection_handler/mock_connection_handler_settings.h
new file mode 100644
index 0000000000..c813455698
--- /dev/null
+++ b/src/components/include/test/connection_handler/mock_connection_handler_settings.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_CONNECTION_HANDLER_MOCK_CONNECTION_HANDLER_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_CONNECTION_HANDLER_MOCK_CONNECTION_HANDLER_SETTINGS_H_
+
+#include <vector>
+#include "gmock/gmock.h"
+#include "connection_handler/connection_handler_settings.h"
+
+namespace test {
+namespace components {
+namespace connection_handler_test {
+
+class MockConnectionHandlerSettings
+ : public connection_handler::ConnectionHandlerSettings {
+ public:
+ MOCK_CONST_METHOD0(heart_beat_timeout, uint32_t());
+ MOCK_CONST_METHOD0(force_protected_service, const std::vector<int>&());
+ MOCK_CONST_METHOD0(force_unprotected_service, const std::vector<int>&());
+};
+
+} // namespace connection_handler_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_CONNECTION_HANDLER_MOCK_CONNECTION_HANDLER_SETTINGS_H_
diff --git a/src/components/include/test/hmi_message_handler/mock_hmi_message_handler.h b/src/components/include/test/hmi_message_handler/mock_hmi_message_handler.h
new file mode 100644
index 0000000000..19aa92f932
--- /dev/null
+++ b/src/components/include/test/hmi_message_handler/mock_hmi_message_handler.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_HMI_MESSAGE_HANDLER_MOCK_HMI_MESSAGE_HANDLER_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_HMI_MESSAGE_HANDLER_MOCK_HMI_MESSAGE_HANDLER_H_
+
+#include "gmock/gmock.h"
+#include "hmi_message_handler/hmi_message_handler.h"
+
+namespace test {
+namespace components {
+namespace hmi_message_handler_test {
+
+using hmi_message_handler::HMIMessageAdapter;
+
+class MockHMIMessageHandler : public ::hmi_message_handler::HMIMessageHandler {
+ public:
+ MOCK_METHOD1(AddHMIMessageAdapter, void(HMIMessageAdapter* adapter));
+ MOCK_METHOD1(RemoveHMIMessageAdapter, void(HMIMessageAdapter* adapter));
+};
+} // namespace hmi_message_handler_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_HMI_MESSAGE_HANDLER_MOCK_HMI_MESSAGE_HANDLER_H_
diff --git a/src/components/include/test/hmi_message_handler/mock_hmi_message_handler_settings.h b/src/components/include/test/hmi_message_handler/mock_hmi_message_handler_settings.h
new file mode 100644
index 0000000000..a3f73ac965
--- /dev/null
+++ b/src/components/include/test/hmi_message_handler/mock_hmi_message_handler_settings.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_HMI_MESSAGE_HANDLER_MOCK_HMI_MESSAGE_HANDLER_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_HMI_MESSAGE_HANDLER_MOCK_HMI_MESSAGE_HANDLER_SETTINGS_H_
+
+#include <stdint.h>
+#include "gmock/gmock.h"
+#include "hmi_message_handler/hmi_message_handler_settings.h"
+
+namespace test {
+namespace components {
+namespace hmi_message_handler_test {
+
+class MockHMIMessageHandlerSettings
+ : public ::hmi_message_handler::HMIMessageHandlerSettings {
+ public:
+ MOCK_CONST_METHOD0(thread_min_stack_size, const uint64_t&());
+};
+} // namespace hmi_message_handler_test
+} // namespace components
+} // namespace test
+#endif // SRC_COMPONENTS_INCLUDE_HMI_MESSAGE_HANDLER_MOCK_HMI_MESSAGE_HANDLER_SETTINGS_H_
diff --git a/src/components/include/test/media_manager/mock_media_manager_settings.h b/src/components/include/test/media_manager/mock_media_manager_settings.h
new file mode 100644
index 0000000000..5ef9e276b2
--- /dev/null
+++ b/src/components/include/test/media_manager/mock_media_manager_settings.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef SRC_COMPONENTS_INCLUDE__TEST_MEDIA_MANAGER_MOCK_MEDIA_MANAGER_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE__TEST_MEDIA_MANAGER_MOCK_MEDIA_MANAGER_SETTINGS_H_
+
+#include <gmock/gmock.h>
+#include <string>
+#include "media_manager/media_manager_settings.h"
+
+namespace test {
+namespace components {
+namespace media_manager_test {
+
+class MockMediaManagerSettings : public ::media_manager::MediaManagerSettings {
+ public:
+ MOCK_CONST_METHOD0(video_server_type, const std::string&());
+ MOCK_CONST_METHOD0(audio_server_type, const std::string&());
+ MOCK_CONST_METHOD0(server_address, const std::string&());
+ MOCK_CONST_METHOD0(video_streaming_port, const std::uint16_t());
+ MOCK_CONST_METHOD0(audio_streaming_port, const std::uint16_t());
+ MOCK_CONST_METHOD0(named_video_pipe_path, const std::string&());
+ MOCK_CONST_METHOD0(named_audio_pipe_path, const std::string&());
+ MOCK_CONST_METHOD0(video_stream_file, const std::string&());
+ MOCK_CONST_METHOD0(audio_stream_file, const std::string&());
+ MOCK_CONST_METHOD0(app_storage_folder, const std::string&());
+ MOCK_CONST_METHOD0(app_resource_folder, const std::string&());
+ MOCK_CONST_METHOD0(recording_file_source, const std::string&());
+};
+
+} // namespace media_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE__TEST_MEDIA_MANAGER_MOCK_MEDIA_MANAGER_SETTINGS_H_
diff --git a/src/components/include/test/policy/mock_policy_manager.h b/src/components/include/test/policy/mock_policy_manager.h
new file mode 100644
index 0000000000..a6169cdebc
--- /dev/null
+++ b/src/components/include/test/policy/mock_policy_manager.h
@@ -0,0 +1,185 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_POLICY_MOCK_POLICY_MANAGER_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_POLICY_MOCK_POLICY_MANAGER_H_
+
+#include <string>
+#include <vector>
+#include "gmock/gmock.h"
+#include "policy/policy_listener.h"
+#include "policy/policy_types.h"
+#include "policy/usage_statistics/statistics_manager.h"
+
+#include "rpc_base/rpc_base.h"
+#include "policy/policy_manager.h"
+
+namespace policy_table = ::rpc::policy_table_interface_base;
+
+using namespace policy;
+
+namespace test {
+namespace components {
+namespace policy_manager_test {
+
+class MockPolicyManager : public PolicyManager {
+ public:
+ MOCK_METHOD1(set_listener, void(PolicyListener* listener));
+ MOCK_METHOD2(InitPT,
+ bool(const std::string& file_name,
+ const PolicySettings* settings));
+ MOCK_METHOD2(LoadPT,
+ bool(const std::string& file, const BinaryMessage& pt_content));
+ MOCK_METHOD1(ResetPT, bool(const std::string& file_name));
+ MOCK_CONST_METHOD1(GetUpdateUrl, std::string(int service_type));
+ MOCK_METHOD2(GetUpdateUrls, void(int service_type, EndpointUrls& end_points));
+ MOCK_METHOD0(RequestPTUpdate, bool());
+ MOCK_METHOD5(CheckPermissions,
+ void(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ const RPCParams& rpc_params,
+ CheckPermissionResult& result));
+ MOCK_METHOD0(ResetUserConsent, bool());
+ MOCK_CONST_METHOD0(GetPolicyTableStatus, std::string());
+ MOCK_METHOD1(KmsChanged, void(int kilometers));
+ MOCK_METHOD0(IncrementIgnitionCycles, void());
+ MOCK_METHOD0(ForcePTExchange, std::string());
+ MOCK_METHOD0(ResetRetrySequence, void());
+ MOCK_METHOD0(NextRetryTimeout, uint32_t());
+ MOCK_METHOD0(TimeoutExchange, int());
+ MOCK_METHOD0(RetrySequenceDelaysSeconds, const std::vector<int>());
+ MOCK_METHOD0(OnExceededTimeout, void());
+ MOCK_METHOD0(OnUpdateStarted, void());
+ MOCK_CONST_METHOD1(GetUserConsentForDevice,
+ DeviceConsent(const std::string& device_id));
+ MOCK_METHOD3(
+ GetUserConsentForApp,
+ void(const std::string& device_id,
+ const std::string& policy_app_id,
+ std::vector<policy::FunctionalGroupPermission>& permissions));
+ MOCK_METHOD2(SetUserConsentForDevice,
+ void(const std::string& device_id, const bool is_allowed));
+ MOCK_METHOD2(ReactOnUserDevConsentForApp,
+ bool(const std::string app_id, bool is_device_allowed));
+ MOCK_METHOD2(PTUpdatedAt, void(policy::Counters counter, int value));
+
+ MOCK_METHOD3(GetInitialAppData,
+ bool(const std::string&,
+ policy::StringArray*,
+ policy::StringArray*));
+
+ MOCK_METHOD2(AddDevice,
+ void(const std::string& device_id,
+ const std::string& connection_type));
+ MOCK_METHOD2(SetDeviceInfo,
+ void(const std::string& device_id,
+ const policy::DeviceInfo& device_info));
+ MOCK_METHOD1(SetUserConsentForApp,
+ void(const policy::PermissionConsent& permissions));
+ MOCK_CONST_METHOD2(GetDefaultHmi,
+ bool(const std::string& policy_app_id,
+ std::string* default_hmi));
+ MOCK_CONST_METHOD2(GetPriority,
+ bool(const std::string& policy_app_id,
+ std::string* priority));
+ MOCK_METHOD2(GetUserFriendlyMessages,
+ std::vector<policy::UserFriendlyMessage>(
+ const std::vector<std::string>& message_code,
+ const std::string& language));
+ MOCK_CONST_METHOD1(IsApplicationRevoked, bool(const std::string& app_id));
+ MOCK_METHOD3(
+ GetPermissionsForApp,
+ void(const std::string& device_id,
+ const std::string& policy_app_id,
+ std::vector<policy::FunctionalGroupPermission>& permissions));
+ MOCK_METHOD1(GetAppPermissionsChanges,
+ policy::AppPermissions(const std::string& policy_app_id));
+ MOCK_METHOD1(RemovePendingPermissionChanges, void(const std::string& app_id));
+ MOCK_CONST_METHOD1(GetCurrentDeviceId,
+ std::string&(const std::string& policy_app_id));
+ MOCK_METHOD1(SetSystemLanguage, void(const std::string& language));
+ MOCK_METHOD3(SetSystemInfo,
+ void(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language));
+ MOCK_METHOD1(SendNotificationOnPermissionsUpdated,
+ void(const std::string& application_id));
+ MOCK_METHOD1(MarkUnpairedDevice, void(const std::string& device_id));
+ MOCK_METHOD1(AddApplication, void(const std::string& application_id));
+ MOCK_METHOD0(CleanupUnpairedDevices, bool());
+ MOCK_CONST_METHOD1(CanAppKeepContext, bool(const std::string& app_id));
+ MOCK_CONST_METHOD1(CanAppStealFocus, bool(const std::string& app_id));
+ MOCK_METHOD0(OnSystemReady, void());
+ MOCK_CONST_METHOD1(GetNotificationsNumber,
+ uint32_t(const std::string& priority));
+ MOCK_METHOD1(SetVINValue, void(const std::string& value));
+ MOCK_METHOD1(IsPredataPolicy, bool(const std::string& policy_app_id));
+ MOCK_CONST_METHOD1(HeartBeatTimeout, uint32_t(const std::string& app_id));
+ MOCK_METHOD1(SaveUpdateStatusRequired, void(bool is_update_needed));
+ MOCK_METHOD0(OnAppsSearchStarted, void());
+ MOCK_METHOD0(OnAppsSearchCompleted, void());
+ MOCK_METHOD1(OnAppRegisteredOnMobile,
+ void(const std::string& application_id));
+ MOCK_CONST_METHOD1(
+ GetAppRequestTypes,
+ const std::vector<std::string>(const std::string policy_app_id));
+ MOCK_CONST_METHOD0(GetVehicleInfo, const policy::VehicleInfo());
+ MOCK_CONST_METHOD0(GetMetaInfo, const policy::MetaInfo());
+ MOCK_CONST_METHOD0(RetrieveCertificate, std::string());
+ MOCK_METHOD1(SetDecryptedCertificate, void(const std::string&));
+ MOCK_METHOD0(ExceededIgnitionCycles, bool());
+ MOCK_METHOD0(ExceededDays, bool());
+ MOCK_METHOD0(StartPTExchange, void());
+ MOCK_METHOD1(Increment, void(usage_statistics::GlobalCounterId type));
+ MOCK_METHOD2(Increment,
+ void(const std::string& app_id,
+ usage_statistics::AppCounterId type));
+ MOCK_METHOD3(Set,
+ void(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value));
+ MOCK_METHOD3(Add,
+ void(const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int32_t timespan_seconds));
+ MOCK_CONST_METHOD0(get_settings, const PolicySettings&());
+ MOCK_METHOD1(set_settings, void(const PolicySettings* get_settings));
+ MOCK_CONST_METHOD0(GetLockScreenIconUrl, std::string());
+ MOCK_METHOD2(GetServiceUrls,
+ void(const std::string& service_type, EndpointUrls& end_points));
+};
+} // namespace policy_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_POLICY_MOCK_POLICY_MANAGER_H_
diff --git a/src/components/include/test/policy/mock_policy_settings.h b/src/components/include/test/policy/mock_policy_settings.h
new file mode 100644
index 0000000000..438e697c51
--- /dev/null
+++ b/src/components/include/test/policy/mock_policy_settings.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_POLICY_MOCK_POLICY_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_POLICY_MOCK_POLICY_SETTINGS_H_
+
+#include "gmock/gmock.h"
+#include <string>
+#include "policy/policy_settings.h"
+
+namespace test {
+namespace components {
+namespace policy_handler_test {
+
+class MockPolicySettings : public ::policy::PolicySettings {
+ public:
+ MOCK_CONST_METHOD0(enable_policy, bool());
+ MOCK_CONST_METHOD0(preloaded_pt_file, const std::string&());
+ MOCK_CONST_METHOD0(app_storage_folder, const std::string&());
+ MOCK_CONST_METHOD0(attempts_to_open_policy_db, uint16_t());
+ MOCK_CONST_METHOD0(open_attempt_timeout_ms, uint16_t());
+ MOCK_CONST_METHOD0(policies_snapshot_file_name, const std::string&());
+ MOCK_CONST_METHOD0(system_files_path, const std::string&());
+};
+
+} // namespace policy_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_POLICY_MOCK_POLICY_SETTINGS_H_
diff --git a/src/components/include/test/policy/mock_statistics_manager.h b/src/components/include/test/policy/mock_statistics_manager.h
new file mode 100644
index 0000000000..e58adea124
--- /dev/null
+++ b/src/components/include/test/policy/mock_statistics_manager.h
@@ -0,0 +1,63 @@
+/* Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_POLICY_USAGE_STATISTICS_MOCK_STATISTICS_MANAGER_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_POLICY_USAGE_STATISTICS_MOCK_STATISTICS_MANAGER_H_
+
+#include <string>
+
+#include "gmock/gmock.h"
+#include "policy/usage_statistics/statistics_manager.h"
+
+namespace test {
+namespace components {
+namespace usage_statistics_test {
+
+class MockStatisticsManager : public usage_statistics::StatisticsManager {
+ public:
+ MOCK_METHOD1(Increment, void(usage_statistics::GlobalCounterId type));
+ MOCK_METHOD2(Increment,
+ void(const std::string& app_id,
+ usage_statistics::AppCounterId type));
+ MOCK_METHOD3(Set,
+ void(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value));
+ MOCK_METHOD3(Add,
+ void(const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int32_t timespan_seconds));
+};
+
+} // namespace usage_statistics_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_POLICY_USAGE_STATISTICS_MOCK_STATISTICS_MANAGER_H_
diff --git a/src/components/include/test/policy/usage_statistics/mock_app_stopwatch.h b/src/components/include/test/policy/usage_statistics/mock_app_stopwatch.h
new file mode 100644
index 0000000000..481d887cb2
--- /dev/null
+++ b/src/components/include/test/policy/usage_statistics/mock_app_stopwatch.h
@@ -0,0 +1,54 @@
+/* Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_POLICY_USAGE_STATISTICS_MOCK_APP_STOPWATCH_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_POLICY_USAGE_STATISTICS_MOCK_APP_STOPWATCH_H_
+
+#include "gmock/gmock.h"
+#include "policy/usage_statistics/app_stopwatch.h"
+#include "policy/usage_statistics/statistics_manager.h"
+
+namespace test {
+namespace components {
+namespace usage_statistics_test {
+
+class MockAppStopwatch : public usage_statistics::AppStopwatch {
+ public:
+ MOCK_METHOD1(Start, void(usage_statistics::AppStopwatchId stopwatch_type));
+ MOCK_METHOD1(Switch, void(usage_statistics::AppStopwatchId stopwatch_type));
+ MOCK_METHOD0(WriteTime, void());
+};
+
+} // namespace usage_statistics_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_POLICY_USAGE_STATISTICS_MOCK_APP_STOPWATCH_H_
diff --git a/src/components/include/test/policy/usage_statistics/mock_statistics_manager.h b/src/components/include/test/policy/usage_statistics/mock_statistics_manager.h
new file mode 100644
index 0000000000..e58adea124
--- /dev/null
+++ b/src/components/include/test/policy/usage_statistics/mock_statistics_manager.h
@@ -0,0 +1,63 @@
+/* Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_POLICY_USAGE_STATISTICS_MOCK_STATISTICS_MANAGER_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_POLICY_USAGE_STATISTICS_MOCK_STATISTICS_MANAGER_H_
+
+#include <string>
+
+#include "gmock/gmock.h"
+#include "policy/usage_statistics/statistics_manager.h"
+
+namespace test {
+namespace components {
+namespace usage_statistics_test {
+
+class MockStatisticsManager : public usage_statistics::StatisticsManager {
+ public:
+ MOCK_METHOD1(Increment, void(usage_statistics::GlobalCounterId type));
+ MOCK_METHOD2(Increment,
+ void(const std::string& app_id,
+ usage_statistics::AppCounterId type));
+ MOCK_METHOD3(Set,
+ void(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value));
+ MOCK_METHOD3(Add,
+ void(const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int32_t timespan_seconds));
+};
+
+} // namespace usage_statistics_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_POLICY_USAGE_STATISTICS_MOCK_STATISTICS_MANAGER_H_
diff --git a/src/components/include/test/protocol_handler/mock_protocol_handler.h b/src/components/include/test/protocol_handler/mock_protocol_handler.h
new file mode 100644
index 0000000000..44287edd4d
--- /dev/null
+++ b/src/components/include/test/protocol_handler/mock_protocol_handler.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_PROTOCOL_HANDLER_MOCK_PROTOCOL_HANDLER_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_PROTOCOL_HANDLER_MOCK_PROTOCOL_HANDLER_H_
+
+#include "gmock/gmock.h"
+#include "protocol_handler/protocol_packet.h"
+#include "protocol_handler/protocol_handler.h"
+#include "protocol_handler/protocol_handler_settings.h"
+#include "protocol_handler/session_observer.h"
+
+namespace test {
+namespace components {
+namespace protocol_handler_test {
+
+class MockProtocolHandler : public ::protocol_handler::ProtocolHandler {
+ public:
+ MOCK_METHOD2(SendMessageToMobileApp,
+ void(const ::protocol_handler::RawMessagePtr message,
+ bool final_message));
+ MOCK_METHOD1(AddProtocolObserver,
+ void(::protocol_handler::ProtocolObserver* observer));
+ MOCK_METHOD1(RemoveProtocolObserver,
+ void(::protocol_handler::ProtocolObserver* observer));
+ MOCK_METHOD2(SendFramesNumber,
+ void(uint32_t connection_key, int32_t number_of_frames));
+ MOCK_METHOD2(SendHeartBeat, void(int32_t connection_id, uint8_t session_id));
+ MOCK_METHOD2(SendEndSession, void(int32_t connection_id, uint8_t session_id));
+ MOCK_METHOD3(SendEndService,
+ void(int32_t connection_id,
+ uint8_t session_id,
+ uint8_t service_type));
+ MOCK_CONST_METHOD0(get_settings,
+ const ::protocol_handler::ProtocolHandlerSettings&());
+ MOCK_METHOD0(get_session_observer, protocol_handler::SessionObserver&());
+};
+} // namespace protocol_handler_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_PROTOCOL_HANDLER_MOCK_PROTOCOL_HANDLER_H_
diff --git a/src/components/include/test/protocol_handler/mock_protocol_handler_settings.h b/src/components/include/test/protocol_handler/mock_protocol_handler_settings.h
new file mode 100644
index 0000000000..d12e7899e0
--- /dev/null
+++ b/src/components/include/test/protocol_handler/mock_protocol_handler_settings.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_PROTOCOL_HANDLER_MOCK_PROTOCOL_HANDLER_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_PROTOCOL_HANDLER_MOCK_PROTOCOL_HANDLER_SETTINGS_H_
+
+#include "gmock/gmock.h"
+#include "protocol_handler/protocol_handler_settings.h"
+
+namespace test {
+namespace components {
+namespace protocol_handler_test {
+
+class MockProtocolHandlerSettings
+ : public protocol_handler::ProtocolHandlerSettings {
+ public:
+ MOCK_CONST_METHOD0(maximum_payload_size, size_t());
+ MOCK_CONST_METHOD0(message_frequency_count, size_t());
+ MOCK_CONST_METHOD0(message_frequency_time, size_t());
+ MOCK_CONST_METHOD0(malformed_message_filtering, bool());
+ MOCK_CONST_METHOD0(malformed_frequency_count, size_t());
+ MOCK_CONST_METHOD0(malformed_frequency_time, size_t());
+ MOCK_CONST_METHOD0(heart_beat_timeout, uint32_t());
+ MOCK_CONST_METHOD0(max_supported_protocol_version, uint16_t());
+ MOCK_CONST_METHOD0(enable_protocol_4, bool());
+ MOCK_CONST_METHOD0(multiframe_waiting_timeout, uint32_t());
+#ifdef ENABLE_SECURITY
+ MOCK_CONST_METHOD0(force_protected_service, const std::vector<int>&());
+ MOCK_CONST_METHOD0(force_unprotected_service, const std::vector<int>&());
+#endif
+};
+
+} // namespace protocol_handler_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_PROTOCOL_HANDLER_MOCK_PROTOCOL_HANDLER_SETTINGS_H_
diff --git a/src/components/include/test/protocol_handler/mock_session_observer.h b/src/components/include/test/protocol_handler/mock_session_observer.h
new file mode 100644
index 0000000000..994c78b961
--- /dev/null
+++ b/src/components/include/test/protocol_handler/mock_session_observer.h
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef TEST_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_SESSION_OBSERVER_MOCK_H_
+#define TEST_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_SESSION_OBSERVER_MOCK_H_
+
+#include <gmock/gmock.h>
+#include <string>
+#include <list>
+#include "protocol_handler/session_observer.h"
+
+namespace test {
+namespace components {
+namespace protocol_handler_test {
+/*
+ * MOCK implementation of ::protocol_handler::SessionObserver interface
+ */
+class MockSessionObserver : public ::protocol_handler::SessionObserver {
+ public:
+ MOCK_METHOD5(
+ OnSessionStartedCallback,
+ uint32_t(const transport_manager::ConnectionUID connection_handle,
+ const uint8_t sessionId,
+ const protocol_handler::ServiceType& service_type,
+ const bool is_protected,
+ uint32_t* hash_id));
+ MOCK_METHOD4(
+ OnSessionEndedCallback,
+ uint32_t(const transport_manager::ConnectionUID connection_handle,
+ const uint8_t sessionId,
+ const uint32_t& hashCode,
+ const protocol_handler::ServiceType& service_type));
+ MOCK_METHOD1(OnApplicationFloodCallBack,
+ void(const uint32_t& connection_key));
+ MOCK_METHOD1(OnMalformedMessageCallback,
+ void(const uint32_t& connection_key));
+ MOCK_CONST_METHOD2(
+ KeyFromPair,
+ uint32_t(transport_manager::ConnectionUID connection_handle,
+ uint8_t session_id));
+ MOCK_CONST_METHOD3(PairFromKey,
+ void(uint32_t key,
+ transport_manager::ConnectionUID* connection_handle,
+ uint8_t* sessionId));
+ MOCK_CONST_METHOD4(GetDataOnSessionKey,
+ int32_t(uint32_t key,
+ uint32_t* app_id,
+ std::list<int32_t>* sessions_list,
+ uint32_t* device_id));
+ MOCK_CONST_METHOD5(GetDataOnDeviceID,
+ int32_t(uint32_t device_handle,
+ std::string* device_name,
+ std::list<uint32_t>* applications_list,
+ std::string* mac_address,
+ std::string* connection_type));
+ MOCK_CONST_METHOD2(IsHeartBeatSupported,
+ bool(transport_manager::ConnectionUID connection_handle,
+ uint8_t session_id));
+ MOCK_CONST_METHOD3(ProtocolVersionUsed,
+ bool(uint32_t connection_id,
+ uint8_t session_id,
+ uint8_t& protocol_version));
+
+#ifdef ENABLE_SECURITY
+ MOCK_METHOD2(SetSSLContext,
+ int(const uint32_t& key, security_manager::SSLContext* context));
+ MOCK_METHOD2(GetSSLContext,
+ security_manager::SSLContext*(
+ const uint32_t& key,
+ const protocol_handler::ServiceType& service_type));
+ MOCK_METHOD2(SetProtectionFlag,
+ void(const uint32_t& key,
+ const protocol_handler::ServiceType& service_type));
+ MOCK_CONST_METHOD1(
+ GetHandshakeContext,
+ security_manager::SSLContext::HandshakeContext(uint32_t key));
+#endif // ENABLE_SECURITY
+};
+} // namespace protocol_handler_test
+} // namespace components
+} // namespace test
+#endif // TEST_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_SESSION_OBSERVER_MOCK_H_
diff --git a/src/components/include/test/security_manager/mock_crypto_manager.h b/src/components/include/test/security_manager/mock_crypto_manager.h
new file mode 100644
index 0000000000..55c364bd89
--- /dev/null
+++ b/src/components/include/test/security_manager/mock_crypto_manager.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_CRYPTO_MANAGER_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_CRYPTO_MANAGER_H_
+
+#include <string>
+
+#include "gmock/gmock.h"
+#include "security_manager/crypto_manager.h"
+
+namespace test {
+namespace components {
+namespace security_manager_test {
+
+class MockCryptoManager : public ::security_manager::CryptoManager {
+ public:
+ MOCK_METHOD0(Init, bool());
+ MOCK_CONST_METHOD0(is_initialized, bool());
+ MOCK_CONST_METHOD0(get_settings,
+ const ::security_manager::CryptoManagerSettings&());
+ MOCK_METHOD1(OnCertificateUpdated, bool(const std::string&));
+ MOCK_METHOD0(CreateSSLContext, ::security_manager::SSLContext*());
+ MOCK_METHOD1(ReleaseSSLContext, void(::security_manager::SSLContext*));
+ MOCK_CONST_METHOD0(LastError, std::string());
+ MOCK_CONST_METHOD0(IsCertificateUpdateRequired, bool());
+};
+} // namespace security_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_CRYPTO_MANAGER_H_
diff --git a/src/components/include/test/security_manager/mock_security_manager.h b/src/components/include/test/security_manager/mock_security_manager.h
new file mode 100644
index 0000000000..e3d95cd94f
--- /dev/null
+++ b/src/components/include/test/security_manager/mock_security_manager.h
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_SECURITY_MANAGER_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_SECURITY_MANAGER_H_
+
+#include <string>
+#include <list>
+#include "gmock/gmock.h"
+#include "utils/byte_order.h"
+#include "security_manager/security_manager.h"
+#include "security_manager/security_query.h"
+
+namespace test {
+namespace components {
+namespace security_manager_test {
+
+class MockSecurityManager : public ::security_manager::SecurityManager {
+ public:
+ MOCK_METHOD1(set_session_observer,
+ void(::protocol_handler::SessionObserver*));
+ MOCK_METHOD1(set_protocol_handler,
+ void(::protocol_handler::ProtocolHandler*));
+ MOCK_METHOD1(set_crypto_manager, void(::security_manager::CryptoManager*));
+ MOCK_METHOD4(
+ SendInternalError,
+ void(const uint32_t, const uint8_t&, const std::string&, const uint32_t));
+ MOCK_METHOD1(CreateSSLContext,
+ ::security_manager::SSLContext*(const uint32_t&));
+ MOCK_METHOD1(StartHandshake, void(uint32_t));
+ MOCK_METHOD1(AddListener, void(::security_manager::SecurityManagerListener*));
+ MOCK_METHOD1(RemoveListener,
+ void(::security_manager::SecurityManagerListener*));
+ // protocol_handler::ProtocolObserver part
+ MOCK_METHOD1(OnMessageReceived,
+ void(const ::protocol_handler::RawMessagePtr));
+ MOCK_METHOD1(OnMobileMessageSent,
+ void(const ::protocol_handler::RawMessagePtr));
+};
+
+/*
+ * Matcher for RawMessages
+ * Check binary data of RawMessages
+ */
+MATCHER_P(RawMessageEqSize,
+ exp_data_size,
+ std::string(negation ? "is not" : "is") + " RawMessages ") {
+ const size_t arg_data_size = arg->data_size();
+ if (arg_data_size != exp_data_size) {
+ *result_listener << "Got " << arg_data_size << " bytes "
+ << " expected " << exp_data_size << " bytes";
+ return false;
+ }
+ return true;
+}
+MATCHER_P2(RawMessageEq,
+ exp_data,
+ exp_data_size,
+ std::string(negation ? "is not" : "is") + " RawMessages ") {
+ const size_t arg_data_size = arg->data_size();
+ if (arg_data_size != exp_data_size) {
+ *result_listener << "Got " << arg_data_size << " bytes "
+ << " expected " << exp_data_size << " bytes";
+ return false;
+ }
+ const uint8_t* arg_data = arg->data();
+ for (uint32_t i = 0; i < arg_data_size; ++i) {
+ if (arg_data[i] != exp_data[i]) {
+ *result_listener << "Fail in " << i << " byte";
+ return false;
+ }
+ }
+ return true;
+}
+
+/*
+ * Matcher for Handshake data
+ */
+MATCHER_P2(HandshakeStepEq,
+ exp_data,
+ exp_data_size,
+ std::string(negation ? "is not" : "is") + " Handshake ") {
+ const uint8_t* arg_data = arg;
+ for (uint32_t i = 0; i < exp_data_size; ++i) {
+ if (arg_data[i] != exp_data[i]) {
+ *result_listener << "Fail in " << i << " byte";
+ return false;
+ }
+ }
+ return true;
+}
+
+/*
+ * Matcher for checking RawMessage with InternalError Query
+ * Check error id
+ */
+MATCHER_P(InternalErrorWithErrId,
+ expectedErrorId,
+ std::string(negation ? "is not" : "is") +
+ " InternalError with selected error") {
+ const size_t header_size =
+ sizeof(security_manager::SecurityQuery::QueryHeader);
+ if (arg->data_size() <= header_size) {
+ *result_listener << "Size " << arg->data_size()
+ << " bytes less or equal sizeof(QueryHeader)="
+ << header_size;
+ return false;
+ }
+ const uint8_t* data = arg->data();
+ const uint8_t query_type = data[0];
+ if (security_manager::SecurityQuery::NOTIFICATION != query_type) {
+ *result_listener << "RawMessage is not notification, type=0x" << std::hex
+ << static_cast<int>(query_type);
+ return false;
+ }
+ // Read Big-Endian number
+ const uint32_t query_id = data[1] << 16 | data[2] << 8 | data[3];
+ if (security_manager::SecurityQuery::SEND_INTERNAL_ERROR != query_id) {
+ *result_listener << "Notification is not InternalError, id=0x" << std::hex
+ << query_id;
+ return false;
+ }
+ const uint32_t json_size =
+ data[8] << 24 | data[9] << 16 | data[10] << 8 | data[11];
+ if (header_size + json_size >= arg->data_size()) {
+ *result_listener << "InternalError contains only JSON data.";
+ return false;
+ }
+ // Read err_id as bin data number
+ const uint8_t* err_id =
+ reinterpret_cast<const uint8_t*>(data + header_size + json_size);
+ if (expectedErrorId != *err_id) {
+ *result_listener << "InternalError id " << static_cast<int>(*err_id)
+ << " and not equal error " << expectedErrorId;
+ return false;
+ }
+ return true;
+}
+
+} // namespace security_manager_test
+} // namespace components
+} // namespace test
+ /*
+ * Matcher for checking QueryHeader equal in GTests
+ */
+::testing::AssertionResult QueryHeader_EQ(
+ const char* m_expr,
+ const char* n_expr,
+ const ::security_manager::SecurityQuery::QueryHeader& q1,
+ const ::security_manager::SecurityQuery::QueryHeader& q2);
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_SECURITY_MANAGER_H_
diff --git a/src/components/include/test/security_manager/mock_security_manager_listener.h b/src/components/include/test/security_manager/mock_security_manager_listener.h
new file mode 100644
index 0000000000..9e5dd03698
--- /dev/null
+++ b/src/components/include/test/security_manager/mock_security_manager_listener.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_SECURITY_MANAGER_LISTENER_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_SECURITY_MANAGER_LISTENER_H_
+
+#include "gmock/gmock.h"
+#include "security_manager/security_manager_listener.h"
+#include "security_manager/ssl_context.h"
+
+namespace test {
+namespace components {
+namespace security_manager_test {
+
+class MockSecurityManagerListener
+ : public ::security_manager::SecurityManagerListener {
+ public:
+ MOCK_METHOD2(OnHandshakeDone,
+ bool(uint32_t connection_key,
+ ::security_manager::SSLContext::HandshakeResult result));
+ MOCK_METHOD0(OnCertificateUpdateRequired, void());
+};
+} // namespace security_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_SECURITY_MANAGER_LISTENER_H_
diff --git a/src/components/include/test/security_manager/mock_security_manager_settings.h b/src/components/include/test/security_manager/mock_security_manager_settings.h
new file mode 100644
index 0000000000..6ac194ced4
--- /dev/null
+++ b/src/components/include/test/security_manager/mock_security_manager_settings.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_SECURITY_MANAGER_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_SECURITY_MANAGER_SETTINGS_H_
+
+#include "gmock/gmock.h"
+#include "security_manager/security_manager_settings.h"
+
+namespace test {
+namespace components {
+namespace security_manager_test {
+
+class MockCryptoManagerSettings
+ : public ::security_manager::CryptoManagerSettings {
+ public:
+ MOCK_CONST_METHOD0(security_manager_mode, ::security_manager::Mode());
+ MOCK_CONST_METHOD0(security_manager_protocol_name,
+ ::security_manager::Protocol());
+ MOCK_CONST_METHOD0(verify_peer, bool());
+ MOCK_CONST_METHOD0(certificate_data, const std::string&());
+ MOCK_CONST_METHOD0(ciphers_list, const std::string&());
+ MOCK_CONST_METHOD0(ca_cert_path, const std::string&());
+ MOCK_CONST_METHOD0(update_before_hours, size_t());
+ MOCK_CONST_METHOD0(maximum_payload_size, size_t());
+};
+
+} // namespace security_manager_test
+} // namespace components
+} // namespace test
+#endif // SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_SECURITY_MANAGER_SETTINGS_H_
diff --git a/src/components/include/test/security_manager/mock_ssl_context.h b/src/components/include/test/security_manager/mock_ssl_context.h
new file mode 100644
index 0000000000..6b6a26a226
--- /dev/null
+++ b/src/components/include/test/security_manager/mock_ssl_context.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_SSL_CONTEXT_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_SSL_CONTEXT_H_
+
+#include <string>
+
+#include "gmock/gmock.h"
+#include "security_manager/ssl_context.h"
+
+namespace test {
+namespace components {
+namespace security_manager_test {
+
+class MockSSLContext : public ::security_manager::SSLContext {
+ public:
+ MOCK_METHOD2(StartHandshake,
+ HandshakeResult(const uint8_t** const out_data,
+ size_t* out_data_size));
+ MOCK_METHOD4(DoHandshakeStep,
+ HandshakeResult(const uint8_t* const in_data,
+ size_t in_data_size,
+ const uint8_t** const out_data,
+ size_t* out_data_size));
+ MOCK_METHOD4(Encrypt,
+ bool(const uint8_t* const in_data,
+ size_t in_data_size,
+ const uint8_t** const out_data,
+ size_t* out_data_size));
+ MOCK_METHOD4(Decrypt,
+ bool(const uint8_t* const in_data,
+ size_t in_data_size,
+ const uint8_t** const out_data,
+ size_t* out_data_size));
+ MOCK_CONST_METHOD0(IsInitCompleted, bool());
+ MOCK_CONST_METHOD0(IsHandshakePending, bool());
+ MOCK_CONST_METHOD1(get_max_block_size, size_t(size_t mtu));
+ MOCK_CONST_METHOD0(LastError, std::string());
+ MOCK_METHOD0(ResetConnection, void());
+ MOCK_METHOD1(SetHandshakeContext, void(const HandshakeContext& hsh_ctx));
+};
+} // namespace security_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_SECURITY_MANAGER_MOCK_SSL_CONTEXT_H_
diff --git a/src/components/include/test/telemetry_monitor/mock_telemetry_observable.h b/src/components/include/test/telemetry_monitor/mock_telemetry_observable.h
new file mode 100644
index 0000000000..9ba4528ecf
--- /dev/null
+++ b/src/components/include/test/telemetry_monitor/mock_telemetry_observable.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TELEMETRY_MONITOR_TEST_MOCK_TELEMETRY_OBSERVEABLE_H
+#define SRC_COMPONENTS_INCLUDE_TELEMETRY_MONITOR_TEST_MOCK_TELEMETRY_OBSERVEABLE_H
+
+#include "gmock/gmock.h"
+#include "telemetry_monitor/telemetry_observable.h"
+#include "application_manager/telemetry_observer.h"
+
+namespace test {
+namespace components {
+namespace telemetry_monitor_test {
+
+class MockTelemetryObservable : public telemetry_monitor::TelemetryObservable<
+ application_manager::AMTelemetryObserver> {
+ public:
+ MOCK_METHOD1(SetTelemetryObserver,
+ void(application_manager::AMTelemetryObserver* observer));
+};
+
+} // namespace telemetry_monitor_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TELEMETRY_MONITOR_TEST_MOCK_TELEMETRY_OBSERVEABLE_H
diff --git a/src/components/include/test/telemetry_monitor/mock_telemetry_observer.h b/src/components/include/test/telemetry_monitor/mock_telemetry_observer.h
new file mode 100644
index 0000000000..e638048126
--- /dev/null
+++ b/src/components/include/test/telemetry_monitor/mock_telemetry_observer.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_MOCK_TIME_METRIC_OBSERVER_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_MOCK_TIME_METRIC_OBSERVER_H_
+
+#include <string>
+#include "gmock/gmock.h"
+#include "transport_manager/telemetry_observer.h"
+#include "protocol/raw_message.h"
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+class TMTelemetryObserverMock
+ : public ::transport_manager::TMTelemetryObserver {
+ public:
+ MOCK_METHOD1(StartRawMsg, void(const protocol_handler::RawMessage* ptr));
+ MOCK_METHOD1(StopRawMsg, void(const protocol_handler::RawMessage* ptr));
+};
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_MOCK_TIME_METRIC_OBSERVER_H_
diff --git a/src/components/include/test/transport_manager/mock_transport_manager.h b/src/components/include/test/transport_manager/mock_transport_manager.h
new file mode 100644
index 0000000000..618e85a4fa
--- /dev/null
+++ b/src/components/include/test/transport_manager/mock_transport_manager.h
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_TRANSPORT_MANAGER_MOCK_TRANSPORT_MANAGER_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_TRANSPORT_MANAGER_MOCK_TRANSPORT_MANAGER_H_
+
+#include "gmock/gmock.h"
+#include <string>
+#include "transport_manager/transport_manager.h"
+#include "transport_manager/transport_adapter/transport_adapter_event.h"
+#include "telemetry_monitor/telemetry_observable.h"
+#include "resumption/last_state.h"
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+using ::transport_manager::DeviceHandle;
+using ::transport_manager::ConnectionUID;
+using ::transport_manager::transport_adapter::TransportAdapter;
+using ::transport_manager::TransportAdapterEvent;
+using ::transport_manager::TransportManagerListener;
+/*
+ * MOCK implementation of ::transport_manager::TransportManager interface
+ */
+class MockTransportManager : public ::transport_manager::TransportManager,
+ public ::telemetry_monitor::TelemetryObservable<
+ transport_manager::TMTelemetryObserver> {
+ public:
+ MOCK_METHOD1(Init, int(resumption::LastState& last_state));
+ MOCK_METHOD0(Reinit, int());
+ MOCK_METHOD0(SearchDevices, int());
+ MOCK_METHOD1(ConnectDevice, int(const DeviceHandle));
+ MOCK_METHOD1(DisconnectDevice, int(const DeviceHandle));
+ MOCK_METHOD1(Disconnect, int(const ConnectionUID));
+ MOCK_METHOD1(DisconnectForce, int(const ConnectionUID));
+ MOCK_METHOD1(SendMessageToDevice,
+ int(const ::protocol_handler::RawMessagePtr));
+ MOCK_METHOD1(ReceiveEventFromDevice, int(const TransportAdapterEvent&));
+ MOCK_METHOD1(AddTransportAdapter, int(TransportAdapter* adapter));
+ MOCK_METHOD1(AddEventListener, int(TransportManagerListener* listener));
+ MOCK_METHOD0(Stop, int());
+ MOCK_METHOD1(RemoveDevice, int(const DeviceHandle));
+ MOCK_CONST_METHOD1(Visibility, int(const bool&));
+ MOCK_METHOD1(SetTelemetryObserver,
+ void(transport_manager::TMTelemetryObserver* observer));
+};
+
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+#endif // SRC_COMPONENTS_INCLUDE_TEST_TRANSPORT_MANAGER_MOCK_TRANSPORT_MANAGER_H_
diff --git a/src/components/include/test/transport_manager/mock_transport_manager_mme_settings.h b/src/components/include/test/transport_manager/mock_transport_manager_mme_settings.h
new file mode 100644
index 0000000000..9e868977d3
--- /dev/null
+++ b/src/components/include/test/transport_manager/mock_transport_manager_mme_settings.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_TRANSPORT_MANAGER_MOCK_TRANSPORT_MANAGER_MME_SETTINGS_H
+#define SRC_COMPONENTS_INCLUDE_TEST_TRANSPORT_MANAGER_MOCK_TRANSPORT_MANAGER_MME_SETTINGS_H
+
+#include "gmock/gmock.h"
+#include "protocol_handler/protocol_handler.h"
+#include "transport_manager/transport_manager_mme_settings.h"
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+class MockTransportManagerMMESettings
+ : public ::transport_manager::TransportManagerMMESettings {
+ public:
+ MOCK_CONST_METHOD0(event_mq_name, const std::string&());
+ MOCK_CONST_METHOD0(ack_mq_name, const std::string&());
+ MOCK_CONST_METHOD0(iap2_hub_connect_attempts, uint32_t());
+ MOCK_CONST_METHOD0(default_hub_protocol_index, uint32_t());
+ MOCK_CONST_METHOD0(iap_legacy_protocol_mask, const std::string&());
+ MOCK_CONST_METHOD0(iap_hub_protocol_mask, const std::string&());
+ MOCK_CONST_METHOD0(iap_pool_protocol_mask, const std::string&());
+ MOCK_CONST_METHOD0(iap_system_config, const std::string&());
+ MOCK_CONST_METHOD0(iap2_system_config, const std::string&());
+ MOCK_CONST_METHOD0(iap_hub_connection_wait_timeout, uint32_t());
+};
+
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_TRANSPORT_MANAGER_MOCK_TRANSPORT_MANAGER_MME_SETTINGS_H
diff --git a/src/components/include/test/transport_manager/mock_transport_manager_settings.h b/src/components/include/test/transport_manager/mock_transport_manager_settings.h
new file mode 100644
index 0000000000..a879723475
--- /dev/null
+++ b/src/components/include/test/transport_manager/mock_transport_manager_settings.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_TRANSPORT_MANAGER_MOCK_TRANSPORT_MANAGER_SETTINGS_H
+#define SRC_COMPONENTS_INCLUDE_TEST_TRANSPORT_MANAGER_MOCK_TRANSPORT_MANAGER_SETTINGS_H
+
+#include "gmock/gmock.h"
+#include "protocol_handler/protocol_handler.h"
+#include "transport_manager/transport_manager_settings.h"
+#include "mock_transport_manager_mme_settings.h"
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+class MockTransportManagerSettings
+ : public ::transport_manager::TransportManagerSettings {
+ public:
+ MOCK_CONST_METHOD0(use_last_state, bool());
+ MOCK_CONST_METHOD0(transport_manager_disconnect_timeout, uint32_t());
+ MOCK_CONST_METHOD0(transport_manager_tcp_adapter_port, uint16_t());
+
+ // from mme settings
+ MOCK_CONST_METHOD0(event_mq_name, const std::string&());
+ MOCK_CONST_METHOD0(ack_mq_name, const std::string&());
+ MOCK_CONST_METHOD0(iap2_hub_connect_attempts, uint32_t());
+ MOCK_CONST_METHOD0(default_hub_protocol_index, uint32_t());
+ MOCK_CONST_METHOD0(iap_legacy_protocol_mask, const std::string&());
+ MOCK_CONST_METHOD0(iap_hub_protocol_mask, const std::string&());
+ MOCK_CONST_METHOD0(iap_pool_protocol_mask, const std::string&());
+ MOCK_CONST_METHOD0(iap_system_config, const std::string&());
+ MOCK_CONST_METHOD0(iap2_system_config, const std::string&());
+ MOCK_CONST_METHOD0(iap_hub_connection_wait_timeout, uint32_t());
+};
+
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_TRANSPORT_MANAGER_MOCK_TRANSPORT_MANAGER_SETTINGS_H
diff --git a/src/components/include/transport_manager/error.h b/src/components/include/transport_manager/error.h
index 7e2349eac2..022ddf0e38 100644
--- a/src/components/include/transport_manager/error.h
+++ b/src/components/include/transport_manager/error.h
@@ -84,32 +84,27 @@ typedef utils::SharedPtr<BaseError> BaseErrorPtr;
/**
* @brief Error that originates during device search.
*/
-class SearchDeviceError : public BaseError {
-};
+class SearchDeviceError : public BaseError {};
/**
* @brief Error that originates during connection.
*/
-class ConnectError : public BaseError {
-};
+class ConnectError : public BaseError {};
/**
* @brief Error that originates during disconnection.
*/
-class DisconnectError : public BaseError {
-};
+class DisconnectError : public BaseError {};
/**
* @brief Error that originates during device disconnection.
*/
-class DisconnectDeviceError : public BaseError {
-};
+class DisconnectDeviceError : public BaseError {};
/**
* @brief Error that originates during data receive..
*/
-class DataReceiveError : public BaseError {
-};
+class DataReceiveError : public BaseError {};
/**
* @brief Error that originates during data send.
@@ -132,15 +127,12 @@ class DataSendError : public BaseError {
/**
* @brief Error that originates during data sending timeout.
*/
-class DataSendTimeoutError : public DataSendError {
-};
-
+class DataSendTimeoutError : public DataSendError {};
/**
* @brief Error that originates during communication.
*/
-class CommunicationError : public BaseError {
-};
+class CommunicationError : public BaseError {};
} // namespace transport_manager
#endif // SRC_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_ERROR_H_
diff --git a/src/components/include/transport_manager/info.h b/src/components/include/transport_manager/info.h
index 66e9df97a3..fb06b39045 100644
--- a/src/components/include/transport_manager/info.h
+++ b/src/components/include/transport_manager/info.h
@@ -65,9 +65,7 @@ class Info {
*
* @param name Info class object name.
*/
- explicit Info(std::string name)
- : name_(name) {
- }
+ explicit Info(std::string name) : name_(name) {}
/**
* @brief Return string with name.
@@ -110,13 +108,14 @@ class DeviceInfo : public Info {
* @param mac_address MAC address of device.
* @param name Name of device.
*/
- DeviceInfo(DeviceHandle device_handle, std::string mac_address,
- std::string name, const ConnectionType& connection_type)
- : Info(name),
- mac_address_(mac_address),
- device_handle_(device_handle),
- connection_type_(connection_type) {
- }
+ DeviceInfo(DeviceHandle device_handle,
+ std::string mac_address,
+ std::string name,
+ const ConnectionType& connection_type)
+ : Info(name)
+ , mac_address_(mac_address)
+ , device_handle_(device_handle)
+ , connection_type_(connection_type) {}
/**
* @brief Return mac_address.
@@ -143,10 +142,10 @@ class DeviceInfo : public Info {
/**
* @brief Overloaded operator "==".
*/
- friend bool operator ==(const DeviceInfo& first, const DeviceInfo& second);
+ friend bool operator==(const DeviceInfo& first, const DeviceInfo& second);
// Needed for std::set container
- bool operator <(const DeviceInfo& than) const {
+ bool operator<(const DeviceInfo& than) const {
return device_handle_ < than.device_handle_;
}
};
@@ -154,10 +153,10 @@ class DeviceInfo : public Info {
/**
* @brief Assign fields of one DeviceInfo class to another.
*/
-inline bool operator ==(const DeviceInfo& first, const DeviceInfo& second) {
- return first.name_ == second.name_
- && first.mac_address_ == second.mac_address_
- && first.device_handle_ == second.device_handle_;
+inline bool operator==(const DeviceInfo& first, const DeviceInfo& second) {
+ return first.name_ == second.name_ &&
+ first.mac_address_ == second.mac_address_ &&
+ first.device_handle_ == second.device_handle_;
}
} // namespace transport_manager
#endif // SRC_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_INFO_H_
diff --git a/src/components/include/transport_manager/transport_adapter/device.h b/src/components/include/transport_manager/transport_adapter/device.h
index e7bca5a46b..a1dd7b9bcf 100644
--- a/src/components/include/transport_manager/transport_adapter/device.h
+++ b/src/components/include/transport_manager/transport_adapter/device.h
@@ -54,9 +54,9 @@ class Device {
* @param unique_device_id device unique identifier.
**/
Device(const std::string& name, const DeviceUID& unique_device_id)
- : name_(name),
- unique_device_id_(unique_device_id),
- keep_on_disconnect_(false) {}
+ : name_(name)
+ , unique_device_id_(unique_device_id)
+ , keep_on_disconnect_(false) {}
/**
* @brief Destructor.
**/
@@ -76,7 +76,7 @@ class Device {
virtual ApplicationList GetApplicationList() const = 0;
- virtual void Stop() { }
+ virtual void Stop() {}
inline const DeviceUID& unique_device_id() const {
return unique_device_id_;
@@ -116,12 +116,13 @@ class Device {
DeviceUID unique_device_id_;
/**
- * @brief If true, device will remain in list even if all its connections finished.
+ * @brief If true, device will remain in list even if all its connections
+ *finished.
**/
bool keep_on_disconnect_;
};
typedef utils::SharedPtr<Device> DeviceSptr;
-typedef std::vector<DeviceSptr> DeviceVector;
+typedef std::vector<DeviceSptr> DeviceVector;
} // namespace transport_adapter
} // namespace transport_manager
#endif // SRC_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_ADAPTER_DEVICE_H_
diff --git a/src/components/include/transport_manager/transport_adapter/transport_adapter.h b/src/components/include/transport_manager/transport_adapter/transport_adapter.h
index 9a820f4cf9..3ff1aa6eee 100644
--- a/src/components/include/transport_manager/transport_adapter/transport_adapter.h
+++ b/src/components/include/transport_manager/transport_adapter/transport_adapter.h
@@ -50,24 +50,16 @@
namespace transport_manager {
-class TMMetricObserver;
+class TMTelemetryObserver;
namespace transport_adapter {
class TransportAdapterListener;
// TODO(EZamakhov): cahnge to DeviceUID
-//typedef std::string DeviceType;
-
-enum DeviceType {
- AOA,
- PASA_AOA,
- BLUETOOTH,
- PASA_BLUETOOTH,
- MME,
- TCP,
- UNKNOWN
-};
+// typedef std::string DeviceType;
+
+enum DeviceType { AOA, PASA_AOA, BLUETOOTH, PASA_BLUETOOTH, MME, TCP, UNKNOWN };
typedef std::map<DeviceType, std::string> DeviceTypes;
@@ -87,14 +79,7 @@ class TransportAdapter {
/**
* @enum Available types of errors.
*/
- enum Error {
- OK,
- FAIL,
- NOT_SUPPORTED,
- ALREADY_EXISTS,
- BAD_STATE,
- BAD_PARAM
- };
+ enum Error { OK, FAIL, NOT_SUPPORTED, ALREADY_EXISTS, BAD_STATE, BAD_PARAM };
public:
/**
@@ -211,6 +196,15 @@ class TransportAdapter {
virtual Error StopClientListening() = 0;
/**
+ * @brief Remove marked as FINALISING connection from accounting.
+ *
+ * @param device_handle Device unique identifier.
+ * @param app_handle Handle of application.
+ */
+ virtual void RemoveFinalizedConnection(
+ const DeviceUID& device_handle, const ApplicationHandle& app_handle) = 0;
+
+ /**
* @brief Disconnect from specified session.
*
* @param device_handle Handle of device to Disconnect from.
@@ -260,8 +254,8 @@ class TransportAdapter {
*
* @return Container(vector) that holds application unique identifiers.
*/
- virtual ApplicationList GetApplicationList(const DeviceUID& device_handle)
- const = 0;
+ virtual ApplicationList GetApplicationList(
+ const DeviceUID& device_handle) const = 0;
/**
* @brief Return name of device.
@@ -272,14 +266,14 @@ class TransportAdapter {
*/
virtual std::string DeviceName(const DeviceUID& device_id) const = 0;
-#ifdef TIME_TESTER
+#ifdef TELEMETRY_MONITOR
/**
* @brief Return Time metric observer
*
* @param return pointer to Time metric observer
*/
- virtual TMMetricObserver* GetTimeMetricObserver() = 0;
-#endif // TIME_TESTER
+ virtual TMTelemetryObserver* GetTelemetryObserver() = 0;
+#endif // TELEMETRY_MONITOR
};
} // namespace transport_adapter
} // namespace transport_manager
diff --git a/src/components/include/transport_manager/transport_adapter/transport_adapter_event.h b/src/components/include/transport_manager/transport_adapter/transport_adapter_event.h
index 525a69fbb7..7879a136b2 100644
--- a/src/components/include/transport_manager/transport_adapter/transport_adapter_event.h
+++ b/src/components/include/transport_manager/transport_adapter/transport_adapter_event.h
@@ -41,6 +41,7 @@ namespace transport_manager {
class TransportAdapterEvent {
public:
+ TransportAdapterEvent() {}
/**
* @brief Constructor.
*
@@ -55,14 +56,14 @@ class TransportAdapterEvent {
transport_adapter::TransportAdapter* adapter,
const DeviceUID& device_handle,
const ApplicationHandle& application_id,
- ::protocol_handler::RawMessagePtr data, BaseErrorPtr error)
- : event_type(type),
- application_id(application_id),
- device_uid(device_handle),
- transport_adapter(adapter),
- event_data(data),
- event_error(error) {
- }
+ ::protocol_handler::RawMessagePtr data,
+ BaseErrorPtr error)
+ : event_type(type)
+ , application_id(application_id)
+ , device_uid(device_handle)
+ , transport_adapter(adapter)
+ , event_data(data)
+ , event_error(error) {}
/**
* @brief Value that describe event type.
*/
diff --git a/src/components/include/transport_manager/transport_manager.h b/src/components/include/transport_manager/transport_manager.h
index 25745e7485..718f9e12aa 100644
--- a/src/components/include/transport_manager/transport_manager.h
+++ b/src/components/include/transport_manager/transport_manager.h
@@ -38,6 +38,10 @@
#include "transport_manager/transport_adapter/transport_adapter_event.h"
#include "protocol/common.h"
+namespace resumption {
+class LastState;
+}
+
namespace transport_manager {
class TransportAdapterEvent;
@@ -56,7 +60,7 @@ class TransportManager {
* @brief Initialize transport manager.
* @return Error code.
*/
- virtual int Init() = 0;
+ virtual int Init(resumption::LastState& last_state) = 0;
/**
* @brief Reinitializes transport manager
@@ -78,7 +82,7 @@ class TransportManager {
*
* @return Code error.
**/
- virtual int ConnectDevice(const DeviceHandle& device_id) = 0;
+ virtual int ConnectDevice(const DeviceHandle device_id) = 0;
/**
* @brief Disconnect from all applications connected on device.
@@ -87,7 +91,7 @@ class TransportManager {
*
* @return Code error.
**/
- virtual int DisconnectDevice(const DeviceHandle& device_id) = 0;
+ virtual int DisconnectDevice(const DeviceHandle device_id) = 0;
/**
* @brief Disconnect from applications connected on device by connection
@@ -97,14 +101,14 @@ class TransportManager {
*
* @return Code error.
**/
- virtual int Disconnect(const ConnectionUID& connection_id) = 0;
+ virtual int Disconnect(const ConnectionUID connection_id) = 0;
/**
* @brief Disconnect and clear all unprocessed data.
*
* @param connection Connection unique identifier.
*/
- virtual int DisconnectForce(const ConnectionUID& connection_id) = 0;
+ virtual int DisconnectForce(const ConnectionUID connection_id) = 0;
/**
* @brief Post new message in queue for massages destined to device.
@@ -113,7 +117,8 @@ class TransportManager {
*
* @return Code error.
**/
- virtual int SendMessageToDevice(const protocol_handler::RawMessagePtr message) = 0;
+ virtual int SendMessageToDevice(
+ const protocol_handler::RawMessagePtr message) = 0;
/**
* @brief Post event in the event queue.
@@ -132,7 +137,7 @@ class TransportManager {
* @return Error code.
**/
virtual int AddTransportAdapter(
- transport_adapter::TransportAdapter* transport_adapter) = 0;
+ transport_adapter::TransportAdapter* transport_adapter) = 0;
/**
* @brief Post listener to the container of transport manager listeners.
@@ -157,7 +162,7 @@ class TransportManager {
*
* @return Code error.
**/
- virtual int RemoveDevice(const DeviceHandle& device_handle) = 0;
+ virtual int RemoveDevice(const DeviceHandle device_handle) = 0;
/**
* @brief Turns on or off visibility of SDL to mobile devices
diff --git a/src/components/include/transport_manager/transport_manager_listener.h b/src/components/include/transport_manager/transport_manager_listener.h
index 0684e8f22f..e9f49e3152 100644
--- a/src/components/include/transport_manager/transport_manager_listener.h
+++ b/src/components/include/transport_manager/transport_manager_listener.h
@@ -46,8 +46,7 @@ class TransportManagerListener {
/**
* @brief Destructor.
*/
- virtual ~TransportManagerListener() {
- }
+ virtual ~TransportManagerListener() {}
/**
* @brief Reaction to the event, when the list of devices is updated.
@@ -78,7 +77,8 @@ class TransportManagerListener {
/**
* @brief Reaction to the event, when scanning of devices is failed.
*
- * @param error Error information about possible reason of scanning of devices failure.
+ * @param error Error information about possible reason of scanning of devices
+ *failure.
*/
virtual void OnScanDevicesFailed(const SearchDeviceError& error) = 0;
@@ -89,7 +89,7 @@ class TransportManagerListener {
* @param connection_id connection unique identifier.
*/
virtual void OnConnectionEstablished(const DeviceInfo& device_info,
- const ConnectionUID& connection_id) = 0;
+ const ConnectionUID connection_id) = 0;
/**
* @brief Reaction to the event, when connection to the device is failed.
@@ -105,15 +105,16 @@ class TransportManagerListener {
*
* @param connection_id Connection unique identifier.
*/
- virtual void OnConnectionClosed(ConnectionUID connection_id) = 0;
+ virtual void OnConnectionClosed(const ConnectionUID connection_id) = 0;
/**
- * @brief Called when connection is closed unexpectedly, i.e. disconnect was not requested
+ * @brief Called when connection is closed unexpectedly, i.e. disconnect was
+ *not requested
*
* @param connection_id Connection ID.
* @param error Error information.
*/
- virtual void OnUnexpectedDisconnect(ConnectionUID connection_id,
+ virtual void OnUnexpectedDisconnect(const ConnectionUID connection_id,
const CommunicationError& error) = 0;
/**
@@ -122,7 +123,7 @@ class TransportManagerListener {
* @param connection_id Connection unique identifier.
* @param error Error information about possible reason of failure.
*/
- virtual void OnConnectionClosedFailure(ConnectionUID connection_id,
+ virtual void OnConnectionClosedFailure(const ConnectionUID connection_id,
const DisconnectError& error) = 0;
/**
@@ -134,9 +135,11 @@ class TransportManagerListener {
const DisconnectDeviceError& error) = 0;
/**
- * \brief Inform about failure during DisconnectDevice procedure of transport manager.
+ * \brief Inform about failure during DisconnectDevice procedure of transport
+ * manager.
* \param device Handle of device.
- * \param error Error information about possible reason of disconnecting failure.
+ * \param error Error information about possible reason of disconnecting
+ * failure.
*/
virtual void OnDisconnectFailed(const DeviceHandle& device,
const DisconnectDeviceError& error) = 0;
@@ -145,30 +148,34 @@ class TransportManagerListener {
*
* @param message Received message
**/
- virtual void OnTMMessageReceived(const ::protocol_handler::RawMessagePtr message) = 0;
+ virtual void OnTMMessageReceived(
+ const ::protocol_handler::RawMessagePtr message) = 0;
/**
- * @brief Reaction to the event, when receiving of massage for transport manager is failed.
+ * @brief Reaction to the event, when receiving of massage for transport
+ *manager is failed.
*
* @param connection_id connection unique identifier.
* @param error Error information about possible reason of failure.
*/
- virtual void OnTMMessageReceiveFailed(ConnectionUID connection_id,
- const DataReceiveError& error) = 0;
+ virtual void OnTMMessageReceiveFailed(const DataReceiveError& error) = 0;
/**
* @brief Reaction to the event, when transport manager sent a massage.
*/
- virtual void OnTMMessageSend(const ::protocol_handler::RawMessagePtr message) = 0;
+ virtual void OnTMMessageSend(
+ const ::protocol_handler::RawMessagePtr message) = 0;
/**
- * @brief Reaction to the event, when sending of massage by transport manager is failed.
+ * @brief Reaction to the event, when sending of massage by transport manager
+ *is failed.
*
* @param error Error information about possible reason of failure.
* @param message Smart pointer to the raw massage.
*/
- virtual void OnTMMessageSendFailed(const DataSendError& error,
- const ::protocol_handler::RawMessagePtr message) = 0;
+ virtual void OnTMMessageSendFailed(
+ const DataSendError& error,
+ const ::protocol_handler::RawMessagePtr message) = 0;
};
} // namespace transport_manager
#endif // SRC_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_LISTENER_H_
diff --git a/src/components/include/transport_manager/transport_manager_listener_empty.h b/src/components/include/transport_manager/transport_manager_listener_empty.h
index f481f57ff5..c5eb0be37c 100644
--- a/src/components/include/transport_manager/transport_manager_listener_empty.h
+++ b/src/components/include/transport_manager/transport_manager_listener_empty.h
@@ -48,44 +48,38 @@ class TransportManagerListenerEmpty : public TransportManagerListener {
/**
* @Destructor.
*/
- virtual ~TransportManagerListenerEmpty() {}
+ ~TransportManagerListenerEmpty() {}
/**
* @brief Reaction to the event, when the list of devices is updated.
*
* @param Container that holds information about devices.
*/
- virtual void OnDeviceListUpdated(const std::vector<DeviceInfo>&) {
- }
+ void OnDeviceListUpdated(const std::vector<DeviceInfo>&) OVERRIDE {}
- virtual void OnFindNewApplicationsRequest() {
- }
+ void OnFindNewApplicationsRequest() OVERRIDE {}
/**
* @brief Reaction to the event, when the device is found.
*
* @param device_info Variable that hold information about device.
*/
- virtual void OnDeviceFound(const DeviceInfo& device_info) {
- }
- virtual void OnDeviceAdded(const DeviceInfo& device_info) {
- }
- virtual void OnDeviceRemoved(const DeviceInfo& device_info) {
- }
+ void OnDeviceFound(const DeviceInfo& device_info) OVERRIDE {}
+ void OnDeviceAdded(const DeviceInfo& device_info) OVERRIDE {}
+ void OnDeviceRemoved(const DeviceInfo& device_info) OVERRIDE {}
/**
* @brief Reaction to the event, when scanning of devices is finished.
*/
- virtual void OnScanDevicesFinished() {
- }
+ void OnScanDevicesFinished() OVERRIDE {}
/**
* @brief Reaction to the event, when scanning of devices is failed.
*
- * @param error Error information about possible reason of scanning of devices failure.
+ * @param error Error information about possible reason of scanning of devices
+ *failure.
*/
- virtual void OnScanDevicesFailed(const SearchDeviceError& error) {
- }
+ void OnScanDevicesFailed(const SearchDeviceError& error) OVERRIDE {}
/**
* @brief Reaction to the event, when connection is established.
@@ -93,9 +87,8 @@ class TransportManagerListenerEmpty : public TransportManagerListener {
* @param devcie_info Variable that hold information about device.
* @param connection_id connection unique identifier.
*/
- virtual void OnConnectionEstablished(const DeviceInfo& device_info,
- const ConnectionUID& connection_id) {
- }
+ void OnConnectionEstablished(const DeviceInfo& device_info,
+ const ConnectionUID connection_id) OVERRIDE {}
/**
* @brief Reaction to the event, when connection to the device is failed.
@@ -103,21 +96,18 @@ class TransportManagerListenerEmpty : public TransportManagerListener {
* @param device_info Variable that hold information about device.
* @param error Error information about possible reason of connect failure.
*/
- virtual void OnConnectionFailed(const DeviceInfo& device_info,
- const ConnectError& error) {
- }
+ void OnConnectionFailed(const DeviceInfo& device_info,
+ const ConnectError& error) OVERRIDE {}
/**
* @brief Reaction to the event, when connection is closed.
*
* @param connection_id Connection unique identifier.
*/
- virtual void OnConnectionClosed(ConnectionUID connection_id) {
- }
+ void OnConnectionClosed(ConnectionUID connection_id) OVERRIDE {}
- virtual void OnUnexpectedDisconnect(ConnectionUID connection_id,
- const CommunicationError& error) {
- }
+ void OnUnexpectedDisconnect(ConnectionUID connection_id,
+ const CommunicationError& error) OVERRIDE {}
/**
* @brief Reaction to the event, when connection close is failed.
@@ -125,9 +115,8 @@ class TransportManagerListenerEmpty : public TransportManagerListener {
* @param connection_id Connection unique identifier.
* @param error Error information about possible reason of failure.
*/
- virtual void OnConnectionClosedFailure(ConnectionUID connection_id,
- const DisconnectError& error) {
- }
+ void OnConnectionClosedFailure(ConnectionUID connection_id,
+ const DisconnectError& error) OVERRIDE {}
/**
* @brief Reaction to the event, when connection with the device is lost.
@@ -135,9 +124,8 @@ class TransportManagerListenerEmpty : public TransportManagerListener {
* @param device Handle of device.
* @param error Error information about possible reason of lost connection.
*/
- virtual void OnDeviceConnectionLost(const DeviceHandle& device,
- const DisconnectDeviceError& error) {
- }
+ void OnDeviceConnectionLost(const DeviceHandle& device,
+ const DisconnectDeviceError& error) OVERRIDE {}
/**
* @brief Reaction to the event, when Disconnect is failed.
@@ -145,9 +133,8 @@ class TransportManagerListenerEmpty : public TransportManagerListener {
* @param device Handle of device.
* @param error Error information about possible reason of Disconnect failure.
*/
- virtual void OnDisconnectFailed(const DeviceHandle& device,
- const DisconnectDeviceError& error) {
- }
+ void OnDisconnectFailed(const DeviceHandle& device,
+ const DisconnectDeviceError& error) OVERRIDE {}
/**
* @brief Reaction to the event, when transport manager received a massage.
@@ -155,34 +142,34 @@ class TransportManagerListenerEmpty : public TransportManagerListener {
* @param message Smart pointer to the raw massage.
* @param connection_id Connection unique identifier.
*/
- virtual void OnTMMessageReceived(const ::protocol_handler::RawMessagePtr message) {
- }
+ void OnTMMessageReceived(
+ const ::protocol_handler::RawMessagePtr message) OVERRIDE {}
/**
- * @brief Reaction to the event, when receiving of massage for transport manager is failed.
+ * @brief Reaction to the event, when receiving of massage for transport
+ *manager is failed.
*
* @param connection_id connection unique identifier.
* @param error Error information about possible reason of failure.
*/
- virtual void OnTMMessageReceiveFailed(ConnectionUID connection_id,
- const DataReceiveError& error) {
- }
+ void OnTMMessageReceiveFailed(const DataReceiveError& error) OVERRIDE {}
/**
* @brief Reaction to the event, when transport manager sent a massage.
*/
- virtual void OnTMMessageSend(const ::protocol_handler::RawMessagePtr message) {
- }
+ void OnTMMessageSend(
+ const ::protocol_handler::RawMessagePtr message) OVERRIDE {}
/**
- * @brief Reaction to the event, when sending of massage by transport manager is failed.
+ * @brief Reaction to the event, when sending of massage by transport manager
+ *is failed.
*
* @param error Error information about possible reason of failure.
* @param message Smart pointer to the raw massage.
*/
- virtual void OnTMMessageSendFailed(const DataSendError& error,
- const ::protocol_handler::RawMessagePtr message) {
- }
+ void OnTMMessageSendFailed(
+ const DataSendError& error,
+ const ::protocol_handler::RawMessagePtr message) OVERRIDE {}
};
} // namespace transport_manager
#endif // SRC_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_LISTENER_EMPTY_H_
diff --git a/src/components/include/transport_manager/transport_manager_mme_settings.h b/src/components/include/transport_manager/transport_manager_mme_settings.h
new file mode 100644
index 0000000000..efe26468ab
--- /dev/null
+++ b/src/components/include/transport_manager/transport_manager_mme_settings.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_MME_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_MME_SETTINGS_H_
+
+#include <stdint.h>
+#include <string>
+#include <vector>
+
+namespace transport_manager {
+class TransportManagerMMESettings {
+ public:
+ virtual const std::string& event_mq_name() const = 0;
+
+ virtual const std::string& ack_mq_name() const = 0;
+
+ virtual uint32_t iap2_hub_connect_attempts() const = 0;
+
+ virtual uint32_t default_hub_protocol_index() const = 0;
+
+ virtual const std::string& iap_legacy_protocol_mask() const = 0;
+
+ virtual const std::string& iap_hub_protocol_mask() const = 0;
+
+ virtual const std::string& iap_pool_protocol_mask() const = 0;
+
+ virtual const std::string& iap_system_config() const = 0;
+
+ virtual const std::string& iap2_system_config() const = 0;
+
+ virtual uint32_t iap_hub_connection_wait_timeout() const = 0;
+};
+}
+
+#endif // SRC_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_MME_SETTINGS_H_
diff --git a/src/components/include/transport_manager/transport_manager_settings.h b/src/components/include/transport_manager/transport_manager_settings.h
new file mode 100644
index 0000000000..f33c5344e0
--- /dev/null
+++ b/src/components/include/transport_manager/transport_manager_settings.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_SETTINGS_H_
+#define SRC_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_SETTINGS_H_
+
+#include "transport_manager/transport_manager_mme_settings.h"
+namespace transport_manager {
+class TransportManagerSettings : public TransportManagerMMESettings {
+ public:
+ /**
+ * @brief Returns true if last state singleton is used
+ */
+ virtual bool use_last_state() const = 0;
+
+ /**
+ * @brief Timeout in transport manager before disconnect
+ */
+ virtual uint32_t transport_manager_disconnect_timeout() const = 0;
+
+ /**
+ * @brief Returns port for TCP transport adapter
+ */
+ virtual uint16_t transport_manager_tcp_adapter_port() const = 0;
+};
+} // namespace transport_manager
+#endif // SRC_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_SETTINGS_H_
diff --git a/src/components/include/utils/atomic_object.h b/src/components/include/utils/atomic_object.h
new file mode 100644
index 0000000000..257fcfbe3a
--- /dev/null
+++ b/src/components/include/utils/atomic_object.h
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_UTILS_ATOMIC_OBJECT_H_
+#define SRC_COMPONENTS_INCLUDE_UTILS_ATOMIC_OBJECT_H_
+
+#include "utils/rwlock.h"
+#include "utils/conditional_variable.h"
+#include "utils/macro.h"
+
+namespace sync_primitives {
+
+/**
+ * @brief Allows to safely change stored value from different threads.
+ *
+ * The usage example:
+ *
+ * threads::Atomic<int> i;
+ *
+ * i = 5; // here SDL is able to guarantee that this value will be safely
+ * // assigned even in multi threaded environment.
+ */
+template <typename T>
+class Atomic {
+ public:
+ /**
+ * @brief Atomic allows to construct atomic object.
+ * The operation is not atomic.
+ *
+ * @param value the value to initialize object with.
+ */
+ Atomic(const T& value) : value_(value) {}
+
+ /**
+ * @brief operator = thread safe setter for stored value.
+ *
+ * @param val value to assign.
+ *
+ * @return mofified value.
+ */
+ T& operator=(const T& val) {
+ sync_primitives::AutoWriteLock lock(rw_lock_);
+ value_ = val;
+ return value_;
+ }
+
+ /**
+ * @brief operator T thread safe getter
+ *
+ * return stored value.
+ */
+ operator T() const {
+ sync_primitives::AutoReadLock lock(rw_lock_);
+ return value_;
+ }
+
+ /**
+ * @brief operator T thread safe getter
+ *
+ * return stored value.
+ */
+ template <typename U>
+ operator U() const {
+ sync_primitives::AutoReadLock lock(rw_lock_);
+ return static_cast<U>(value_);
+ }
+
+ private:
+ T value_;
+ mutable sync_primitives::RWLock rw_lock_;
+};
+
+typedef Atomic<int> atomic_int;
+typedef Atomic<int32_t> atomic_int32;
+typedef Atomic<uint32_t> atomic_uint32;
+typedef Atomic<int64_t> atomic_int64;
+typedef Atomic<uint64_t> atomic_uint64;
+typedef Atomic<size_t> atomic_size_t;
+typedef Atomic<bool> atomic_bool;
+
+} // namespace sync_primitives
+
+#endif // SRC_COMPONENTS_INCLUDE_UTILS_ATOMIC_OBJECT_H_
diff --git a/src/components/include/utils/auto_trace.h b/src/components/include/utils/auto_trace.h
index 87b6554808..36ff3be281 100644
--- a/src/components/include/utils/auto_trace.h
+++ b/src/components/include/utils/auto_trace.h
@@ -40,10 +40,8 @@ namespace logger {
class AutoTrace {
public:
- AutoTrace(
- log4cxx::LoggerPtr logger,
- const log4cxx::spi::LocationInfo& location
- );
+ AutoTrace(log4cxx::LoggerPtr logger,
+ const log4cxx::spi::LocationInfo& location);
~AutoTrace();
private:
diff --git a/src/components/include/utils/conditional_variable.h b/src/components/include/utils/conditional_variable.h
index 1f0a7e62de..f54a22e993 100644
--- a/src/components/include/utils/conditional_variable.h
+++ b/src/components/include/utils/conditional_variable.h
@@ -83,7 +83,8 @@ class ConditionalVariable {
// Wait forever or up to milliseconds time limit
bool Wait(AutoLock& auto_lock);
bool Wait(Lock& lock);
- WaitStatus WaitFor(AutoLock& auto_lock, int32_t milliseconds);
+ WaitStatus WaitFor(AutoLock& auto_lock, uint32_t milliseconds);
+
private:
impl::PlatformConditionalVariable cond_var_;
diff --git a/src/components/include/utils/custom_string.h b/src/components/include/utils/custom_string.h
new file mode 100644
index 0000000000..7b21e7a64d
--- /dev/null
+++ b/src/components/include/utils/custom_string.h
@@ -0,0 +1,218 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_UTILS_CUSTOM_STRING_H_
+#define SRC_COMPONENTS_INCLUDE_UTILS_CUSTOM_STRING_H_
+
+#include <string>
+
+namespace utils {
+namespace custom_string {
+/* UTF8 formats:
+ * UTF8 1 byte consists from one-byte sequence
+ * bit representation of one character: 0xxxxxxx
+ * UTF8 2 bytes consists from two-byte sequence
+ * bit representation of one character: 110xxxxx 10xxxxxx
+ * UTF8 3 bytes consists from three-byte sequence
+ * bit representation of one character: 1110xxxx 10xxxxxx 10xxxxxx
+ * UTF8 4 bytes consists from four-byte sequence
+ * bit representation of one character: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
+ */
+enum UTFFormat {
+ kByteOfUTF8 = 0x80, // 10xxxxxx
+ kHigestByteOfUTF8Byte2 = 0xc0, // 110xxxxx
+ kHigestByteOfUTF8Byte3 = 0xe0, // 1110xxxx
+ kHigestByteOfUTF8Byte4 = 0xf0 // 11110xxx
+};
+
+class CustomString {
+ public:
+ /**
+ * @brief Constructs empty object.
+ */
+ CustomString();
+
+ /**
+ * @brief Constructs object with copy of str.
+ * @param Contains string for new object.
+ */
+ explicit CustomString(const std::string& str);
+
+ /**
+ * @brief Constructs object with copy of str.
+ * @param Contains pointer to string for new object.
+ */
+ explicit CustomString(const char* str);
+
+ /**
+ * @brief Constructs object with n consecutive copies of character c.
+ * @param Contains amount of copies of character for new object.
+ * @param Contains character for new object.
+ */
+ CustomString(size_t n, char c);
+
+ /**
+ * @brief Returns the length of the string, in terms of characters.
+ */
+ size_t size() const;
+
+ /**
+ * @brief Returns the length of the string, in terms of characters.
+ */
+ size_t length() const;
+
+ /**
+ * @brief Returns the length of the string, in terms of bytes.
+ */
+ size_t length_bytes() const;
+
+ /**
+ * @brief Returns TRUE if CustomString contains ASCII string
+ * otherwise returns FALSE.
+ */
+ bool is_ascii_string() const;
+
+ /**
+ * @brief Returns TRUE if CustomString contains empty string
+ * otherwise returns FALSE.
+ */
+ bool empty() const;
+
+ /**
+ * @brief Compares the value of the string (case sensitive).
+ * @param Contains string for comparing
+ * @return Returns TRUE if strings is equal otherwise returns FALSE.
+ */
+ bool operator==(const CustomString& str) const;
+
+ /**
+ * @brief Compares the value of the string (case sensitive).
+ * @param Contains string for comparing
+ * @return Returns TRUE if strings is equal otherwise returns FALSE.
+ */
+ bool operator==(const std::string& str) const;
+
+ /**
+ * @brief Assigns a new value to the string
+ * @param Contains string for assignment
+ * @return Returns result of assignment
+ */
+ CustomString& operator=(const char* str);
+
+ /**
+ * @brief Concatenates string from CustomString with string from argument.
+ * @param Contains string for concatenation.
+ * @return Returns result of concatenation.
+ */
+ CustomString operator+(const CustomString& str) const;
+
+ /**
+ * @brief Concatenates string from CustomString with string from argument.
+ * @param Contains string for concatenation.
+ * @return Returns result of concatenation.
+ */
+ CustomString operator+(const std::string& str) const;
+
+ /**
+ * @brief Returns the character at position pos in the string.
+ * Need to use with ASCII string.
+ * @param pos value with the position of a character within the string.
+ */
+ char at(size_t pos) const;
+
+ /**
+ * @brief Compares the value of the string (case sensitive).
+ * @param Contains string for comparing
+ * @return Returns 0 if strings is equal otherwise
+ * returns "<0" or ">0".
+ */
+ int compare(const char* str) const;
+
+ /**
+ * @brief Compares the value of the string (case sensitive).
+ * @param Contains string for comparing
+ * @return Returns 0 if strings is equal otherwise
+ * returns "<0" or ">0".
+ */
+ int compare(const std::string& str) const;
+
+ /**
+ * @brief Compares the value of the string (case insensitive).
+ * @param Contains string for comparing
+ * @return Returns TRUE if strings is equal otherwise returns FALSE.
+ */
+ bool CompareIgnoreCase(const CustomString& str) const;
+
+ /**
+ * @brief Compares the value of the string (case insensitive).
+ * @param Contains string for comparing
+ * @return Returns TRUE if strings is equal otherwise returns FALSE.
+ */
+ bool CompareIgnoreCase(const char* str) const;
+
+ /**
+ * @brief Returns a pointer to string from CustomString.
+ */
+ const char* c_str() const;
+
+ /**
+ * @brief Converts string to unicode string.
+ * @return Returns unicode string.
+ */
+ std::wstring ToWString() const;
+
+ /**
+ * @brief Returns copy of string as multibyte string.
+ */
+ std::string AsMBString() const;
+
+ /**
+ * @brief Converts string to lower case unicode string.
+ * @return Returns unicode string.
+ */
+ std::wstring ToWStringLowerCase() const;
+
+ private:
+ /**
+ * @brief Initiates members of CustomString
+ */
+ void InitData();
+
+ std::string mb_string_;
+ size_t amount_characters_;
+ bool is_ascii_string_;
+};
+
+} // namespace custom_string
+} // namespace utils
+
+#endif // SRC_COMPONENTS_INCLUDE_UTILS_CUSTOM_STRING_H_
diff --git a/src/components/include/utils/data_accessor.h b/src/components/include/utils/data_accessor.h
index 344d6e34a8..9be28a638b 100644
--- a/src/components/include/utils/data_accessor.h
+++ b/src/components/include/utils/data_accessor.h
@@ -36,26 +36,24 @@
#include "utils/shared_ptr.h"
// This class is for thread-safe access to data
-template<class T>
+template <class T>
class DataAccessor {
public:
DataAccessor(const T& data, const sync_primitives::Lock& lock)
- : data_(data),
- lock_(const_cast<sync_primitives::Lock&>(lock)),
- counter_( new uint32_t(0)) {
+ : data_(data)
+ , lock_(const_cast<sync_primitives::Lock&>(lock))
+ , counter_(new uint32_t(0)) {
lock_.Acquire();
}
DataAccessor(const DataAccessor<T>& other)
- : data_(other.data_),
- lock_(other.lock_),
- counter_(other.counter_) {
+ : data_(other.data_), lock_(other.lock_), counter_(other.counter_) {
++(*counter_);
}
~DataAccessor() {
if (0 == *counter_) {
- lock_.Release();
+ lock_.Release();
} else {
--(*counter_);
}
@@ -63,9 +61,9 @@ class DataAccessor {
const T& GetData() const {
return data_;
}
- private:
- void *operator new(size_t size);
+ private:
+ void* operator new(size_t size);
const T& data_;
sync_primitives::Lock& lock_;
utils::SharedPtr<uint32_t> counter_;
diff --git a/src/components/include/utils/date_time.h b/src/components/include/utils/date_time.h
index c8cef32ef4..f8f8e3d6ce 100644
--- a/src/components/include/utils/date_time.h
+++ b/src/components/include/utils/date_time.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -40,17 +40,18 @@ typedef struct timeval TimevalStruct;
namespace date_time {
-enum TimeCompare {
- LESS,
- EQUAL,
- GREATER
-};
+enum TimeCompare { LESS, EQUAL, GREATER };
class DateTime {
public:
static const int32_t MILLISECONDS_IN_SECOND = 1000;
- static const int32_t MICROSECONDS_IN_MILLISECONDS = 1000;
- static const int32_t MICROSECONDS_IN_SECOND = 1000 * 1000;
+ static const int32_t MICROSECONDS_IN_MILLISECOND = 1000;
+ static const int32_t NANOSECONDS_IN_MICROSECOND = 1000;
+ static const int32_t SECONDS_IN_HOUR = 3600;
+ static const int32_t MICROSECONDS_IN_SECOND =
+ MILLISECONDS_IN_SECOND * MICROSECONDS_IN_MILLISECOND;
+ static const int32_t NANOSECONDS_IN_MILLISECOND =
+ MICROSECONDS_IN_MILLISECOND * NANOSECONDS_IN_MICROSECOND;
static TimevalStruct getCurrentTime();
@@ -69,6 +70,14 @@ class DateTime {
static int64_t calculateTimeDiff(const TimevalStruct& time1,
const TimevalStruct& time2);
+ /**
+ * @brief Adds milliseconds to time struct
+ * @param time contains time struct
+ * @param milliseconds contains value which need to
+ * add to time struct
+ **/
+ static void AddMilliseconds(TimevalStruct& time, uint32_t milliseconds);
+
static TimevalStruct Sub(const TimevalStruct& time1,
const TimevalStruct& time2);
@@ -78,9 +87,14 @@ class DateTime {
static bool Greater(const TimevalStruct& time1, const TimevalStruct& time2);
static bool Less(const TimevalStruct& time1, const TimevalStruct& time2);
static bool Equal(const TimevalStruct& time1, const TimevalStruct& time2);
+
+ private:
+ static TimevalStruct ConvertionUsecs(const TimevalStruct& time);
};
} // namespace date_time
bool operator<(const TimevalStruct& time1, const TimevalStruct& time2);
bool operator==(const TimevalStruct& time1, const TimevalStruct& time2);
+const TimevalStruct operator-(const TimevalStruct& time1,
+ const TimevalStruct& time2);
#endif // SRC_COMPONENTS_INCLUDE_UTILS_DATE_TIME_H_
diff --git a/src/components/include/utils/lock.h b/src/components/include/utils/lock.h
index 29bd467143..e615a58f9d 100644
--- a/src/components/include/utils/lock.h
+++ b/src/components/include/utils/lock.h
@@ -49,19 +49,21 @@ namespace impl {
#if defined(OS_POSIX)
typedef pthread_mutex_t PlatformMutex;
#endif
-} // namespace impl
-
+} // namespace impl
class SpinMutex {
public:
- SpinMutex()
- : state_(0) { }
+ SpinMutex() : state_(0) {}
void Lock() {
+ // Comment below add exception for lint error
+ // Reason: FlexeLint doesn't know about compiler's built-in instructions
+ /*lint -e1055*/
if (atomic_post_set(&state_) == 0) {
return;
}
- for(;;) {
+ for (;;) {
sched_yield();
+ /*lint -e1055*/
if (state_ == 0 && atomic_post_set(&state_) == 0) {
return;
}
@@ -70,8 +72,8 @@ class SpinMutex {
void Unlock() {
state_ = 0;
}
- ~SpinMutex() {
- }
+ ~SpinMutex() {}
+
private:
volatile unsigned int state_;
};
@@ -92,7 +94,7 @@ class SpinMutex {
class Lock {
public:
Lock();
- Lock(bool is_mutex_recursive);
+ Lock(bool is_recursive);
~Lock();
// Ackquire the lock. Must be called only once on a thread.
@@ -113,7 +115,8 @@ class Lock {
#ifndef NDEBUG
/**
- * @brief Basic debugging aid, a flag that signals wether this lock is currently taken
+ * @brief Basic debugging aid, a flag that signals wether this lock is
+ * currently taken
* Allows detection of abandoned and recursively captured mutexes
*/
uint32_t lock_taken_;
@@ -130,6 +133,7 @@ class Lock {
void AssertTakenAndMarkFree() {}
#endif
+ void Init(bool is_recursive);
friend class ConditionalVariable;
DISALLOW_COPY_AND_ASSIGN(Lock);
@@ -138,11 +142,17 @@ class Lock {
// This class is used to automatically acquire and release the a lock
class AutoLock {
public:
- explicit AutoLock(Lock& lock)
- : lock_(lock) { lock_.Acquire(); }
- ~AutoLock() { lock_.Release(); }
+ explicit AutoLock(Lock& lock) : lock_(lock) {
+ lock_.Acquire();
+ }
+ ~AutoLock() {
+ lock_.Release();
+ }
+
private:
- Lock& GetLock(){ return lock_; }
+ Lock& GetLock() {
+ return lock_;
+ }
Lock& lock_;
private:
@@ -154,9 +164,16 @@ class AutoLock {
// This class is used to temporarly unlock autolocked lock
class AutoUnlock {
public:
- explicit AutoUnlock(AutoLock& lock)
- : lock_(lock.GetLock()) { lock_.Release(); }
- ~AutoUnlock() { lock_.Acquire(); }
+ explicit AutoUnlock(Lock& lock) : lock_(lock) {
+ lock_.Release();
+ }
+ explicit AutoUnlock(AutoLock& lock) : lock_(lock.GetLock()) {
+ lock_.Release();
+ }
+ ~AutoUnlock() {
+ lock_.Acquire();
+ }
+
private:
Lock& lock_;
diff --git a/src/components/include/utils/logger.h b/src/components/include/utils/logger.h
index 50d194245c..11a2f1f0d9 100644
--- a/src/components/include/utils/logger.h
+++ b/src/components/include/utils/logger.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,157 +30,145 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-
-
-#ifndef SRC_COMPONENTS_UTILS_INCLUDE_UTILS_LOGGER_H_
-#define SRC_COMPONENTS_UTILS_INCLUDE_UTILS_LOGGER_H_
+#ifndef SRC_COMPONENTS_INCLUDE_UTILS_LOGGER_H_
+#define SRC_COMPONENTS_INCLUDE_UTILS_LOGGER_H_
#ifdef ENABLE_LOG
- #include <errno.h>
- #include <string.h>
- #include <sstream>
- #include <log4cxx/propertyconfigurator.h>
- #include <log4cxx/spi/loggingevent.h>
- #include "utils/push_log.h"
- #include "utils/logger_status.h"
- #include "utils/auto_trace.h"
+#include <errno.h>
+#include <string.h>
+#include <sstream>
+#include <log4cxx/propertyconfigurator.h>
+#include <log4cxx/spi/loggingevent.h>
+#include "utils/push_log.h"
+#include "utils/logger_status.h"
+#include "utils/auto_trace.h"
#endif // ENABLE_LOG
#ifdef ENABLE_LOG
- #define CREATE_LOGGERPTR_GLOBAL(logger_var, logger_name) \
- namespace { \
- CREATE_LOGGERPTR_LOCAL(logger_var, logger_name); \
- }
-
- #define CREATE_LOGGERPTR_LOCAL(logger_var, logger_name) \
- log4cxx::LoggerPtr logger_var = log4cxx::LoggerPtr(log4cxx::Logger::getLogger(logger_name));
-
- #define INIT_LOGGER(file_name) \
- log4cxx::PropertyConfigurator::configure(file_name);
-
- // Logger deinitilization function and macro, need to stop log4cxx writing
- // without this deinitilization log4cxx threads continue using some instances destroyed by exit()
- void deinit_logger ();
- #define DEINIT_LOGGER() deinit_logger()
-
- #define LOG4CXX_IS_TRACE_ENABLED(logger) logger->isTraceEnabled()
-
- log4cxx_time_t time_now();
-
- #define LOG_WITH_LEVEL(loggerPtr, logLevel, logEvent) \
- do { \
- if (logger::logger_status != logger::DeletingLoggerThread) { \
- if (loggerPtr->isEnabledFor(logLevel)) { \
- std::stringstream accumulator; \
- accumulator << logEvent; \
- logger::push_log(loggerPtr, logLevel, accumulator.str(), time_now(), \
- LOG4CXX_LOCATION, ::log4cxx::spi::LoggingEvent::getCurrentThreadName()); \
- } \
- } \
- } while (false)
-
- #undef LOG4CXX_INFO
- #define LOG4CXX_INFO(loggerPtr, logEvent) LOG_WITH_LEVEL(loggerPtr, ::log4cxx::Level::getInfo(), logEvent)
-
- #define LOG4CXX_INFO_EXT(logger, logEvent) LOG4CXX_INFO(logger, __PRETTY_FUNCTION__ << ": " << logEvent)
- #define LOG4CXX_INFO_STR_EXT(logger, logEvent) LOG4CXX_INFO_STR(logger, __PRETTY_FUNCTION__ << ": " << logEvent)
-
- #define LOG4CXX_TRACE_EXT(logger, logEvent) LOG4CXX_TRACE(logger, __PRETTY_FUNCTION__ << ": " << logEvent)
- #define LOG4CXX_TRACE_STR_EXT(logger, logEvent) LOG4CXX_TRACE_STR(logger, __PRETTY_FUNCTION__ << ": " << logEvent)
-
- #undef LOG4CXX_DEBUG
- #define LOG4CXX_DEBUG(loggerPtr, logEvent) LOG_WITH_LEVEL(loggerPtr, ::log4cxx::Level::getDebug(), logEvent)
-
- #define LOG4CXX_DEBUG_EXT(logger, logEvent) LOG4CXX_DEBUG(logger, __PRETTY_FUNCTION__ << ": " << logEvent)
- #define LOG4CXX_DEBUG_STR_EXT(logger, logEvent) LOG4CXX_DEBUG_STR(logger, __PRETTY_FUNCTION__ << ": " << logEvent)
+#define CREATE_LOGGERPTR_GLOBAL(logger_var, logger_name) \
+ namespace { \
+ CREATE_LOGGERPTR_LOCAL(logger_var, logger_name); \
+ }
- #undef LOG4CXX_WARN
- #define LOG4CXX_WARN(loggerPtr, logEvent) LOG_WITH_LEVEL(loggerPtr, ::log4cxx::Level::getWarn(), logEvent)
+#define CREATE_LOGGERPTR_LOCAL(logger_var, logger_name) \
+ log4cxx::LoggerPtr logger_var = \
+ log4cxx::LoggerPtr(log4cxx::Logger::getLogger(logger_name));
- #define LOG4CXX_WARN_EXT(logger, logEvent) LOG4CXX_WARN(logger, __PRETTY_FUNCTION__ << ": " << logEvent)
- #define LOG4CXX_WARN_STR_EXT(logger, logEvent) LOG4CXX_WARN_STR(logger, __PRETTY_FUNCTION__ << ": " << logEvent)
+#define INIT_LOGGER(file_name, logs_enabled) \
+ log4cxx::PropertyConfigurator::configure(file_name); \
+ logger::set_logs_enabled(logs_enabled);
- #undef LOG4CXX_ERROR
- #define LOG4CXX_ERROR(loggerPtr, logEvent) LOG_WITH_LEVEL(loggerPtr, ::log4cxx::Level::getError(), logEvent)
+// Logger deinitilization function and macro, need to stop log4cxx writing
+// without this deinitilization log4cxx threads continue using some instances
+// destroyed by exit()
+void deinit_logger();
+#define DEINIT_LOGGER() deinit_logger()
- #define LOG4CXX_ERROR_EXT(logger, logEvent) LOG4CXX_ERROR(logger, __PRETTY_FUNCTION__ << ": " << logEvent)
- #define LOG4CXX_ERROR_STR_EXT(logger, logEvent) LOG4CXX_ERROR_STR(logger, __PRETTY_FUNCTION__ << ": " << logEvent)
+// special macros to dump logs from queue
+// it's need, for example, when crash happend
+#define FLUSH_LOGGER() logger::flush_logger()
- #undef LOG4CXX_FATAL
- #define LOG4CXX_FATAL(loggerPtr, logEvent) LOG_WITH_LEVEL(loggerPtr, ::log4cxx::Level::getFatal(), logEvent)
+#define LOG4CXX_IS_TRACE_ENABLED(logger) logger->isTraceEnabled()
- #define LOG4CXX_FATAL_EXT(logger, logEvent) LOG4CXX_FATAL(logger, __PRETTY_FUNCTION__ << ": " << logEvent)
- #define LOG4CXX_FATAL_STR_EXT(logger, logEvent) LOG4CXX_FATAL_STR(logger, __PRETTY_FUNCTION__ << ": " << logEvent)
+log4cxx_time_t time_now();
- #undef LOG4CXX_TRACE
- #define LOG4CXX_TRACE(loggerPtr, logEvent) LOG_WITH_LEVEL(loggerPtr, ::log4cxx::Level::getTrace(), logEvent)
+#define LOG_WITH_LEVEL(loggerPtr, logLevel, logEvent) \
+ do { \
+ if (logger::logs_enabled()) { \
+ if (logger::logger_status != logger::DeletingLoggerThread) { \
+ if (loggerPtr->isEnabledFor(logLevel)) { \
+ std::stringstream accumulator; \
+ accumulator << logEvent; \
+ logger::push_log( \
+ loggerPtr, \
+ logLevel, \
+ accumulator.str(), \
+ time_now(), \
+ LOG4CXX_LOCATION, \
+ ::log4cxx::spi::LoggingEvent::getCurrentThreadName()); \
+ } \
+ } \
+ } \
+ } while (false)
- #define LOG4CXX_AUTO_TRACE_WITH_NAME_SPECIFIED(loggerPtr, auto_trace) logger::AutoTrace auto_trace(loggerPtr, LOG4CXX_LOCATION)
- #define LOG4CXX_AUTO_TRACE(loggerPtr) LOG4CXX_AUTO_TRACE_WITH_NAME_SPECIFIED(loggerPtr, SDL_local_auto_trace_object)
+#undef LOG4CXX_TRACE
+#define LOG4CXX_TRACE(loggerPtr, logEvent) \
+ LOG_WITH_LEVEL(loggerPtr, ::log4cxx::Level::getTrace(), logEvent)
- #define LOG4CXX_ERROR_WITH_ERRNO(logger, message) \
- LOG4CXX_ERROR(logger, message << ", error code " << errno << " (" << strerror(errno) << ")")
+#define LOG4CXX_AUTO_TRACE_WITH_NAME_SPECIFIED(loggerPtr, auto_trace) \
+ logger::AutoTrace auto_trace(loggerPtr, LOG4CXX_LOCATION)
+#define LOG4CXX_AUTO_TRACE(loggerPtr) \
+ LOG4CXX_AUTO_TRACE_WITH_NAME_SPECIFIED(loggerPtr, SDL_local_auto_trace_object)
- #define LOG4CXX_WARN_WITH_ERRNO(logger, message) \
- LOG4CXX_WARN(logger, message << ", error code " << errno << " (" << strerror(errno) << ")")
+#undef LOG4CXX_DEBUG
+#define LOG4CXX_DEBUG(loggerPtr, logEvent) \
+ LOG_WITH_LEVEL(loggerPtr, ::log4cxx::Level::getDebug(), logEvent)
-#else // ENABLE_LOG is OFF
+#undef LOG4CXX_INFO
+#define LOG4CXX_INFO(loggerPtr, logEvent) \
+ LOG_WITH_LEVEL(loggerPtr, ::log4cxx::Level::getInfo(), logEvent)
- #define CREATE_LOGGERPTR_GLOBAL(logger_var, logger_name)
+#undef LOG4CXX_WARN
+#define LOG4CXX_WARN(loggerPtr, logEvent) \
+ LOG_WITH_LEVEL(loggerPtr, ::log4cxx::Level::getWarn(), logEvent)
- #define CREATE_LOGGERPTR_LOCAL(logger_var, logger_name)
+#undef LOG4CXX_ERROR
+#define LOG4CXX_ERROR(loggerPtr, logEvent) \
+ LOG_WITH_LEVEL(loggerPtr, ::log4cxx::Level::getError(), logEvent)
- #define INIT_LOGGER(file_name)
+#undef LOG4CXX_FATAL
+#define LOG4CXX_FATAL(loggerPtr, logEvent) \
+ LOG_WITH_LEVEL(loggerPtr, ::log4cxx::Level::getFatal(), logEvent)
- #define DEINIT_LOGGER(file_name)
+#define LOG4CXX_ERROR_WITH_ERRNO(loggerPtr, message) \
+ LOG4CXX_ERROR(loggerPtr, \
+ message << ", error code " << errno << " (" << strerror(errno) \
+ << ")")
- #define LOG4CXX_IS_TRACE_ENABLED(logger) false
+#define LOG4CXX_WARN_WITH_ERRNO(loggerPtr, message) \
+ LOG4CXX_WARN(loggerPtr, \
+ message << ", error code " << errno << " (" << strerror(errno) \
+ << ")")
- #undef LOG4CXX_INFO
- #define LOG4CXX_INFO(x,y)
+#else // ENABLE_LOG is OFF
- #undef LOG4CXX_WARN
- #define LOG4CXX_WARN(x,y)
+#define CREATE_LOGGERPTR_GLOBAL(logger_var, logger_name)
- #undef LOG4CXX_ERROR
- #define LOG4CXX_ERROR(x,y)
+#define CREATE_LOGGERPTR_LOCAL(logger_var, logger_name)
- #undef LOG4CXX_ERROR_WITH_ERRNO
- #define LOG4CXX_ERROR_WITH_ERRNO(x,y)
+#define INIT_LOGGER(file_name)
- #undef LOG4CXX_WARN_WITH_ERRNO
- #define LOG4CXX_WARN_WITH_ERRNO(x,y)
+#define DEINIT_LOGGER(file_name)
- #undef LOG4CXX_TRACE
- #define LOG4CXX_TRACE(x,y)
+#define LOG4CXX_IS_TRACE_ENABLED(logger) false
- #undef LOG4CXX_DEBUG
- #define LOG4CXX_DEBUG(x,y)
+#undef LOG4CXX_TRACE
+#define LOG4CXX_TRACE(x, y)
- #undef LOG4CXX_FATAL
- #define LOG4CXX_FATAL(x,y)
+#define LOG4CXX_AUTO_TRACE_WITH_NAME_SPECIFIED(loggerPtr, auto_trace)
+#define LOG4CXX_AUTO_TRACE(loggerPtr)
- #define LOG4CXX_INFO_EXT(logger, logEvent)
- #define LOG4CXX_INFO_STR_EXT(logger, logEvent)
+#undef LOG4CXX_DEBUG
+#define LOG4CXX_DEBUG(x, y)
- #define LOG4CXX_TRACE_EXT(logger, logEvent)
- #define LOG4CXX_TRACE_STR_EXT(logger, logEvent)
+#undef LOG4CXX_INFO
+#define LOG4CXX_INFO(x, y)
- #define LOG4CXX_DEBUG_EXT(logger, logEvent)
- #define LOG4CXX_DEBUG_STR_EXT(logger, logEvent)
+#undef LOG4CXX_WARN
+#define LOG4CXX_WARN(x, y)
- #define LOG4CXX_WARN_EXT(logger, logEvent)
- #define LOG4CXX_WARN_STR_EXT(logger, logEvent)
+#undef LOG4CXX_ERROR
+#define LOG4CXX_ERROR(x, y)
- #define LOG4CXX_ERROR_EXT(logger, logEvent)
- #define LOG4CXX_ERROR_STR_EXT(logger, logEvent)
+#undef LOG4CXX_ERROR_WITH_ERRNO
+#define LOG4CXX_ERROR_WITH_ERRNO(x, y)
- #define LOG4CXX_FATAL_EXT(logger, logEvent)
- #define LOG4CXX_FATAL_STR_EXT(logger, logEvent)
+#undef LOG4CXX_WARN_WITH_ERRNO
+#define LOG4CXX_WARN_WITH_ERRNO(x, y)
- #define LOG4CXX_AUTO_TRACE_WITH_NAME_SPECIFIED(loggerPtr, auto_trace)
- #define LOG4CXX_AUTO_TRACE(loggerPtr)
+#undef LOG4CXX_FATAL
+#define LOG4CXX_FATAL(x, y)
#endif // ENABLE_LOG
-#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_LOGGER_H_
+#endif // SRC_COMPONENTS_INCLUDE_UTILS_LOGGER_H_
diff --git a/src/components/include/utils/macro.h b/src/components/include/utils/macro.h
index bfd13411f4..0e029e4b06 100644
--- a/src/components/include/utils/macro.h
+++ b/src/components/include/utils/macro.h
@@ -39,8 +39,8 @@
#endif
#include "logger.h"
-
-
+// A macro to set some action for variable to avoid "unused variable" warning
+#define UNUSED(x) (void) x;
// A macro to disallow the copy constructor and operator= functions
// This should be used in the private: declarations for a class
#define DISALLOW_COPY_AND_ASSIGN(TypeName) \
@@ -59,51 +59,60 @@
friend utils::deleters::Deleter<TypeName>::~Deleter()
#ifdef DEBUG
- #define ASSERT(condition) \
- do { \
- DEINIT_LOGGER(); \
- assert(condition); \
- } while (false)
+#define ASSERT(condition) \
+ FLUSH_LOGGER(); \
+ do { \
+ DEINIT_LOGGER(); \
+ assert(condition); \
+ } while (false)
#else // RELEASE
- #define ASSERT(condition) \
- fprintf(stderr, "Failed condition \"" #condition "\" [%s:%d][%s]\n\n", \
- __FILE__, __LINE__, __FUNCTION__)
+#define ASSERT(condition) \
+ fprintf(stderr, \
+ "Failed condition \"" #condition "\" [%s:%d][%s]\n\n", \
+ __FILE__, \
+ __LINE__, \
+ __FUNCTION__)
#endif
-#define DCHECK(condition) \
- if (!(condition)) { \
- CREATE_LOGGERPTR_LOCAL(logger_, "assert"); \
- LOG4CXX_FATAL(logger_, "DCHECK failed with \"" << #condition \
- << "\" [" << __FUNCTION__ << "][" << __FILE__ << ':' << __LINE__ << ']'); \
- ASSERT((condition)); \
+#define DCHECK(condition) \
+ if (!(condition)) { \
+ CREATE_LOGGERPTR_LOCAL(logger_, "Utils"); \
+ LOG4CXX_FATAL(logger_, \
+ "DCHECK failed with \"" << #condition << "\" [" \
+ << __FUNCTION__ << "][" << __FILE__ \
+ << ':' << __LINE__ << ']'); \
+ ASSERT((condition)); \
}
/*
* Will cauch assert on debug version,
* Will return return_value in release build
*/
-#define DCHECK_OR_RETURN(condition, return_value) \
- if (!(condition)) { \
- CREATE_LOGGERPTR_LOCAL(logger_, "assert"); \
- LOG4CXX_FATAL(logger_, "DCHECK failed with \"" << #condition \
- << "\" [" << __FUNCTION__ << "][" << __FILE__ << ':' << __LINE__ << ']' ); \
- ASSERT((condition)); \
- return (return_value); \
+#define DCHECK_OR_RETURN(condition, return_value) \
+ if (!(condition)) { \
+ CREATE_LOGGERPTR_LOCAL(logger_, "Utils"); \
+ LOG4CXX_FATAL(logger_, \
+ "DCHECK failed with \"" << #condition << "\" [" \
+ << __FUNCTION__ << "][" << __FILE__ \
+ << ':' << __LINE__ << ']'); \
+ ASSERT((condition)); \
+ return (return_value); \
}
/*
* Will cauch assert on debug version,
* Will return return_value in release build
*/
-#define DCHECK_OR_RETURN_VOID(condition) \
- if (!(condition)) { \
- CREATE_LOGGERPTR_LOCAL(logger_, "assert"); \
- LOG4CXX_FATAL(logger_, "DCHECK failed with \"" << #condition \
- << "\" [" << __FUNCTION__ << "][" << __FILE__ << ':' << __LINE__ << ']' ); \
- ASSERT((condition)); \
- return ; \
+#define DCHECK_OR_RETURN_VOID(condition) \
+ if (!(condition)) { \
+ CREATE_LOGGERPTR_LOCAL(logger_, "Utils"); \
+ LOG4CXX_FATAL(logger_, \
+ "DCHECK failed with \"" << #condition << "\" [" \
+ << __FUNCTION__ << "][" << __FILE__ \
+ << ':' << __LINE__ << ']'); \
+ ASSERT((condition)); \
+ return; \
}
-
#define NOTREACHED() DCHECK(!"Unreachable code")
// Allows to perform static check that virtual function from base class is
@@ -120,11 +129,11 @@
* @brief Calculate size of na array
* @param arr array, which size need to calculate
*/
-#define ARRAYSIZE(arr) sizeof (arr) / sizeof(*arr)
+#define ARRAYSIZE(arr) sizeof(arr) / sizeof(*arr)
#ifdef BUILD_TESTS
-#define FRIEND_TEST(test_case_name, test_name)\
-friend class test_case_name##_##test_name##_Test
+#define FRIEND_TEST(test_case_name, test_name) \
+ friend class test_case_name##_##test_name##_Test
#endif
#endif // SRC_COMPONENTS_INCLUDE_UTILS_MACRO_H_
diff --git a/src/components/include/utils/make_shared.h b/src/components/include/utils/make_shared.h
index dc817e362d..9d40d646a6 100644
--- a/src/components/include/utils/make_shared.h
+++ b/src/components/include/utils/make_shared.h
@@ -48,61 +48,144 @@
* SharedPtr<A> shared2(MakeShared<A>(5, 5.5);
* SharedPtr<A> shared3(MakeShared<A>(5, 5.5, std::string("MyStr"));
*
- * The profit in using MakeShared instead of simple allocation with operator new is evident.
- * Firstly it allows us to centralize allocation place, secondly it allows us to use
+ * The profit in using MakeShared instead of simple allocation with operator new
+ *is evident.
+ * Firstly it allows us to centralize allocation place, secondly it allows us to
+ *use
* safe operator new overloading (no throwable one).
*/
namespace utils {
-template <typename T> class SharedPtr;
+template <typename T>
+class SharedPtr;
namespace {
template <typename T>
- SharedPtr<T>Initialize(T* object) {
- return object == NULL ? SharedPtr<T>() : SharedPtr<T>(object);
- }
+SharedPtr<T> Initialize(T* object) {
+ return object == NULL ? SharedPtr<T>() : SharedPtr<T>(object);
+}
}
-template<typename T>
+template <typename T>
SharedPtr<T> MakeShared() {
T* t = new (std::nothrow) T;
return Initialize(t);
}
-template<typename T, typename Arg1>
+template <typename T, typename Arg1>
+SharedPtr<T> MakeShared(Arg1& arg1) {
+ T* t = new (std::nothrow) T(arg1);
+ return Initialize(t);
+}
+
+template <typename T, typename Arg1, typename Arg2>
+SharedPtr<T> MakeShared(Arg1& arg1, Arg2& arg2) {
+ T* t = new (std::nothrow) T(arg1, arg2);
+ return Initialize(t);
+}
+
+template <typename T, typename Arg1, typename Arg2, typename Arg3>
+SharedPtr<T> MakeShared(Arg1& arg1, Arg2& arg2, Arg3& arg3) {
+ T* t = new (std::nothrow) T(arg1, arg2, arg3);
+ return Initialize(t);
+}
+
+template <typename T,
+ typename Arg1,
+ typename Arg2,
+ typename Arg3,
+ typename Arg4>
+SharedPtr<T> MakeShared(Arg1& arg1, Arg2& arg2, Arg3& arg3, Arg4& arg4) {
+ T* t = new (std::nothrow) T(arg1, arg2, arg3, arg4);
+ return Initialize(t);
+}
+
+template <typename T,
+ typename Arg1,
+ typename Arg2,
+ typename Arg3,
+ typename Arg4,
+ typename Arg5>
+SharedPtr<T> MakeShared(
+ Arg1& arg1, Arg2& arg2, Arg3& arg3, Arg4& arg4, Arg5& arg5) {
+ T* t = new (std::nothrow) T(arg1, arg2, arg3, arg4, arg5);
+ return Initialize(t);
+}
+
+template <typename T,
+ typename Arg1,
+ typename Arg2,
+ typename Arg3,
+ typename Arg4,
+ typename Arg5,
+ typename Arg6>
+SharedPtr<T> MakeShared(
+ Arg1& arg1, Arg2& arg2, Arg3& arg3, Arg4& arg4, Arg5& arg5, Arg6& arg6) {
+ T* t = new (std::nothrow) T(arg1, arg2, arg3, arg4, arg5, arg6);
+ return Initialize(t);
+}
+
+template <typename T, typename Arg1>
SharedPtr<T> MakeShared(const Arg1& arg1) {
- T* t = new (std::nothrow) T(arg1);
- return Initialize(t);
+ T* t = new (std::nothrow) T(arg1);
+ return Initialize(t);
}
-template<typename T, typename Arg1, typename Arg2>
+template <typename T, typename Arg1, typename Arg2>
SharedPtr<T> MakeShared(const Arg1& arg1, const Arg2& arg2) {
- T* t = new (std::nothrow) T(arg1, arg2);
- return Initialize(t);
+ T* t = new (std::nothrow) T(arg1, arg2);
+ return Initialize(t);
}
-template<typename T, typename Arg1, typename Arg2, typename Arg3>
+template <typename T, typename Arg1, typename Arg2, typename Arg3>
SharedPtr<T> MakeShared(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3) {
- T* t = new (std::nothrow) T(arg1, arg2, arg3);
- return Initialize(t);
+ T* t = new (std::nothrow) T(arg1, arg2, arg3);
+ return Initialize(t);
}
-template<typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4>
-SharedPtr<T> MakeShared(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4) {
- T* t = new (std::nothrow) T(arg1, arg2, arg3, arg4);
- return Initialize(t);
+template <typename T,
+ typename Arg1,
+ typename Arg2,
+ typename Arg3,
+ typename Arg4>
+SharedPtr<T> MakeShared(const Arg1& arg1,
+ const Arg2& arg2,
+ const Arg3& arg3,
+ const Arg4& arg4) {
+ T* t = new (std::nothrow) T(arg1, arg2, arg3, arg4);
+ return Initialize(t);
}
-template<typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5>
-SharedPtr<T> MakeShared(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5) {
- T* t = new (std::nothrow) T(arg1, arg2, arg3, arg4, arg5);
- return Initialize(t);
+template <typename T,
+ typename Arg1,
+ typename Arg2,
+ typename Arg3,
+ typename Arg4,
+ typename Arg5>
+SharedPtr<T> MakeShared(const Arg1& arg1,
+ const Arg2& arg2,
+ const Arg3& arg3,
+ const Arg4& arg4,
+ const Arg5& arg5) {
+ T* t = new (std::nothrow) T(arg1, arg2, arg3, arg4, arg5);
+ return Initialize(t);
}
-template<typename T, typename Arg1, typename Arg2, typename Arg3, typename Arg4, typename Arg5, typename Arg6>
-SharedPtr<T> MakeShared(const Arg1& arg1, const Arg2& arg2, const Arg3& arg3, const Arg4& arg4, const Arg5& arg5, const Arg6& arg6) {
- T* t = new (std::nothrow) T(arg1, arg2, arg3, arg4, arg5, arg6);
- return Initialize(t);
+template <typename T,
+ typename Arg1,
+ typename Arg2,
+ typename Arg3,
+ typename Arg4,
+ typename Arg5,
+ typename Arg6>
+SharedPtr<T> MakeShared(const Arg1& arg1,
+ const Arg2& arg2,
+ const Arg3& arg3,
+ const Arg4& arg4,
+ const Arg5& arg5,
+ const Arg6& arg6) {
+ T* t = new (std::nothrow) T(arg1, arg2, arg3, arg4, arg5, arg6);
+ return Initialize(t);
}
-} // namespace utils;
-#endif // SRC_COMPONENTS_INCLUDE_UTILS_MAKE_SHARED_H_
+} // namespace utils;
+#endif // SRC_COMPONENTS_INCLUDE_UTILS_MAKE_SHARED_H_
diff --git a/src/components/include/utils/message_queue.h b/src/components/include/utils/message_queue.h
index e0b3336728..093aa4cac2 100644
--- a/src/components/include/utils/message_queue.h
+++ b/src/components/include/utils/message_queue.h
@@ -34,10 +34,10 @@
#define SRC_COMPONENTS_INCLUDE_UTILS_MESSAGE_QUEUE_H_
#include <queue>
+#include <algorithm>
#include "utils/conditional_variable.h"
#include "utils/lock.h"
-#include "utils/logger.h"
#include "utils/prioritized_queue.h"
/**
@@ -47,151 +47,171 @@
namespace utils {
-template<typename T, class Q = std::queue<T> > class MessageQueue {
- public:
- typedef Q Queue;
- /**
- * \brief Default constructor
- */
- MessageQueue();
-
- /**
- * \brief Destructor
- */
- ~MessageQueue();
-
- /**
- * \brief Returns size of the queue.
- * \return Size of the queue.
- */
- size_t size() const;
-
- /**
- * \brief If queue is empty.
- * \return Is queue empty.
- */
- bool empty() const;
-
- /**
- * \brief Tells if queue is being shut down
- */
- bool IsShuttingDown() const;
-
- /**
- * \brief Adds element to the queue.
- * \param element Element to be added to the queue.n
- */
- void push(const T& element);
-
- /**
- * \brief Removes element from the queue and returns it.
- * \return To element of the queue.
- */
- T pop();
-
- /**
- * \brief Conditional wait.
- */
- void wait();
-
- /**
- * \brief Shutdown the queue.
- * This leads to waking up everyone waiting on the queue
- * Queue being shut down can be drained ( with pop() )
- * But nothing must be added to the queue after it began
- * shutting down
- */
- void Shutdown();
-
- /**
- * \brief Clears queue.
- */
- void Reset();
-
- private:
- /**
- *\brief Queue
- */
- Queue queue_;
- volatile bool shutting_down_;
-
- /**
- *\brief Platform specific syncronisation variable
- */
- mutable sync_primitives::Lock queue_lock_;
- sync_primitives::ConditionalVariable queue_new_items_;
+template <typename T, class Q = std::queue<T> >
+class MessageQueue {
+ public:
+ typedef Q Queue;
+ /**
+ * \brief Default constructor
+ */
+ MessageQueue();
+
+ /**
+ * \brief Destructor
+ */
+ ~MessageQueue();
+
+ /**
+ * \brief Returns size of the queue.
+ * \return Size of the queue.
+ */
+ size_t size() const;
+
+ /**
+ * \brief If queue is empty.
+ * \return Is queue empty.
+ */
+ bool empty() const;
+
+ /**
+ * \brief Tells if queue is being shut down
+ */
+ bool IsShuttingDown() const;
+
+ /**
+ * \brief Adds element to the queue.
+ * \param element Element to be added to the queue.n
+ */
+ void push(const T& element);
+
+ /**
+ * \brief Removes element from the queue and returns it
+ * \param element Element to be returned
+ * \return True on success, false if queue is empty
+ */
+ bool pop(T& element);
+
+ /**
+ * \brief Conditional wait.
+ */
+ void wait();
+
+ /**
+ * \brief waitUntilEmpty message queue
+ * Wait until message queue is empty
+ */
+ void WaitUntilEmpty();
+
+ /**
+ * \brief Shutdown the queue.
+ * This leads to waking up everyone waiting on the queue
+ * Queue being shut down can be drained ( with pop() )
+ * But nothing must be added to the queue after it began
+ * shutting down
+ */
+ void Shutdown();
+
+ /**
+ * \brief Clears queue.
+ */
+ void Reset();
+
+ private:
+ /**
+ *\brief Queue
+ */
+ Queue queue_;
+ volatile bool shutting_down_;
+
+ /**
+ *\brief Platform specific syncronisation variable
+ */
+ mutable sync_primitives::Lock queue_lock_;
+ sync_primitives::ConditionalVariable queue_new_items_;
};
-template<typename T, class Q> MessageQueue<T, Q>::MessageQueue()
- : shutting_down_(false) {
-}
+template <typename T, class Q>
+MessageQueue<T, Q>::MessageQueue()
+ : shutting_down_(false) {}
-template<typename T, class Q> MessageQueue<T, Q>::~MessageQueue() {
- if (!queue_.empty()) {
- CREATE_LOGGERPTR_LOCAL(logger_, "Utils")
- LOG4CXX_ERROR(logger_, "Destruction of non-drained queue");
+template <typename T, class Q>
+MessageQueue<T, Q>::~MessageQueue() {}
+
+template <typename T, class Q>
+void MessageQueue<T, Q>::wait() {
+ sync_primitives::AutoLock auto_lock(queue_lock_);
+ while ((!shutting_down_) && queue_.empty()) {
+ queue_new_items_.Wait(auto_lock);
}
}
-template<typename T, class Q> void MessageQueue<T, Q>::wait() {
+template <typename T, class Q>
+void MessageQueue<T, Q>::WaitUntilEmpty() {
sync_primitives::AutoLock auto_lock(queue_lock_);
- while ((!shutting_down_) && queue_.empty()) {
+ while ((!shutting_down_) && !queue_.empty()) {
queue_new_items_.Wait(auto_lock);
}
}
-template<typename T, class Q> size_t MessageQueue<T, Q>::size() const {
+template <typename T, class Q>
+size_t MessageQueue<T, Q>::size() const {
sync_primitives::AutoLock auto_lock(queue_lock_);
return queue_.size();
}
-template<typename T, class Q> bool MessageQueue<T, Q>::empty() const {
+template <typename T, class Q>
+bool MessageQueue<T, Q>::empty() const {
sync_primitives::AutoLock auto_lock(queue_lock_);
return queue_.empty();
}
-template<typename T, class Q> bool MessageQueue<T, Q>::IsShuttingDown() const {
+template <typename T, class Q>
+bool MessageQueue<T, Q>::IsShuttingDown() const {
return shutting_down_;
}
-template<typename T, class Q> void MessageQueue<T, Q>::push(const T& element) {
+template <typename T, class Q>
+void MessageQueue<T, Q>::push(const T& element) {
{
sync_primitives::AutoLock auto_lock(queue_lock_);
if (shutting_down_) {
- CREATE_LOGGERPTR_LOCAL(logger_, "Utils")
- LOG4CXX_ERROR(logger_, "Runtime error, pushing into queue"
- " that is being shut down");
- return;
+ return;
}
- queue_.push(element);
+ queue_.push(element);
}
queue_new_items_.Broadcast();
}
-template<typename T, class Q> T MessageQueue<T, Q>::pop() {
+template <typename T, class Q>
+bool MessageQueue<T, Q>::pop(T& element) {
sync_primitives::AutoLock auto_lock(queue_lock_);
if (queue_.empty()) {
- CREATE_LOGGERPTR_LOCAL(logger_, "Utils")
- LOG4CXX_ERROR(logger_, "Runtime error, popping out of empty queue");
- NOTREACHED();
+ return false;
}
- T result = queue_.front();
+ element = queue_.front();
queue_.pop();
- return result;
+ queue_new_items_.NotifyOne();
+ return true;
}
-template<typename T, class Q> void MessageQueue<T, Q>::Shutdown() {
+template <typename T, class Q>
+void MessageQueue<T, Q>::Shutdown() {
sync_primitives::AutoLock auto_lock(queue_lock_);
shutting_down_ = true;
+ if (!queue_.empty()) {
+ Queue empty_queue;
+ std::swap(queue_, empty_queue);
+ }
queue_new_items_.Broadcast();
}
-template<typename T, class Q> void MessageQueue<T, Q>::Reset() {
+template <typename T, class Q>
+void MessageQueue<T, Q>::Reset() {
sync_primitives::AutoLock auto_lock(queue_lock_);
shutting_down_ = false;
if (!queue_.empty()) {
Queue empty_queue;
- queue_.swap(empty_queue);
+ std::swap(queue_, empty_queue);
}
}
diff --git a/src/components/include/utils/messagemeter.h b/src/components/include/utils/messagemeter.h
index a5d9968d81..42b658ad6b 100644
--- a/src/components/include/utils/messagemeter.h
+++ b/src/components/include/utils/messagemeter.h
@@ -94,7 +94,7 @@ class MessageMeter {
template <class Id>
MessageMeter<Id>::MessageMeter()
- : time_range_(TimevalStruct {0, 0}) {
+ : time_range_(TimevalStruct{0, 0}) {
time_range_.tv_sec = 1;
}
@@ -104,8 +104,7 @@ size_t MessageMeter<Id>::TrackMessage(const Id& id) {
}
template <class Id>
-size_t MessageMeter<Id>::TrackMessages(const Id& id,
- const size_t count) {
+size_t MessageMeter<Id>::TrackMessages(const Id& id, const size_t count) {
Timings& timings = timing_map_[id];
const TimevalStruct current_time = date_time::DateTime::getCurrentTime();
for (size_t i = 0; i < count; ++i) {
@@ -118,18 +117,16 @@ size_t MessageMeter<Id>::TrackMessages(const Id& id,
template <class Id>
size_t MessageMeter<Id>::Frequency(const Id& id) {
typename TimingMap::iterator it = timing_map_.find(id);
- if(it == timing_map_.end()) {
+ if (it == timing_map_.end()) {
return 0u;
}
Timings& timings = it->second;
if (timings.empty()) {
return 0u;
}
- const TimevalStruct actual_begin_time =
- date_time::DateTime::Sub(date_time::DateTime::getCurrentTime(),
- time_range_);
- timings.erase(timings.begin(),
- timings.upper_bound(actual_begin_time));
+ const TimevalStruct actual_begin_time = date_time::DateTime::Sub(
+ date_time::DateTime::getCurrentTime(), time_range_);
+ timings.erase(timings.begin(), timings.upper_bound(actual_begin_time));
return timings.size();
}
@@ -152,7 +149,7 @@ void MessageMeter<Id>::set_time_range(const size_t time_range_msecs) {
const size_t mSecs =
time_range_msecs % date_time::DateTime::MILLISECONDS_IN_SECOND;
time_range_.tv_usec =
- mSecs * date_time::DateTime::MICROSECONDS_IN_MILLISECONDS;
+ mSecs * date_time::DateTime::MICROSECONDS_IN_MILLISECOND;
}
template <class Id>
void MessageMeter<Id>::set_time_range(const TimevalStruct& time_range) {
diff --git a/src/components/include/utils/prioritized_queue.h b/src/components/include/utils/prioritized_queue.h
index 2a8ebf0a7b..eb4ba6a6c3 100644
--- a/src/components/include/utils/prioritized_queue.h
+++ b/src/components/include/utils/prioritized_queue.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Ford Motor Company
+ * Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,12 +30,12 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#ifndef SRC_COMPONENTS_UTILS_INCLUDE_UTILS_PRIORITIZED_QUEUE_H_
-#define SRC_COMPONENTS_UTILS_INCLUDE_UTILS_PRIORITIZED_QUEUE_H_
+#ifndef SRC_COMPONENTS_INCLUDE_UTILS_PRIORITIZED_QUEUE_H_
+#define SRC_COMPONENTS_INCLUDE_UTILS_PRIORITIZED_QUEUE_H_
#include <queue>
#include <map>
-#include <iostream>
+#include <algorithm>
#include "utils/macro.h"
@@ -45,15 +45,13 @@ namespace utils {
* Template queue class that gives out messages respecting their priority
* Message class must have size_t PriorityOrder() method implemented
*/
-template < typename M >
+template <typename M>
class PrioritizedQueue {
public:
typedef M value_type;
// std::map guarantees it's contents is sorted by key
typedef std::map<size_t, std::queue<value_type> > QueuesMap;
- PrioritizedQueue()
- : total_size_(0) {
- }
+ PrioritizedQueue() : total_size_(0) {}
// All api mimics usual std queue interface
void push(const value_type& message) {
size_t message_priority = message.PriorityOrder();
@@ -66,6 +64,10 @@ class PrioritizedQueue {
bool empty() const {
return queues_.empty();
}
+ void swap(PrioritizedQueue<M>& x) {
+ std::swap(queues_, x.queues_);
+ std::swap(total_size_, x.total_size_);
+ }
value_type front() {
DCHECK(!queues_.empty() && !queues_.rbegin()->second.empty());
return queues_.rbegin()->second.front();
@@ -79,11 +81,12 @@ class PrioritizedQueue {
queues_.erase(last);
}
}
+
private:
QueuesMap queues_;
size_t total_size_;
};
-}
+} // namespace utils
-#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_
+#endif // SRC_COMPONENTS_INCLUDE_UTILS_PRIORITIZED_QUEUE_H_
diff --git a/src/components/include/utils/push_log.h b/src/components/include/utils/push_log.h
index 01389fb736..aaeaa83bae 100644
--- a/src/components/include/utils/push_log.h
+++ b/src/components/include/utils/push_log.h
@@ -38,15 +38,20 @@
namespace logger {
-bool push_log(
- log4cxx::LoggerPtr logger,
- log4cxx::LevelPtr level,
- const std::string& entry,
- log4cxx_time_t timeStamp,
- const log4cxx::spi::LocationInfo& location,
- const log4cxx::LogString& threadName
- );
+bool push_log(log4cxx::LoggerPtr logger,
+ log4cxx::LevelPtr level,
+ const std::string& entry,
+ log4cxx_time_t timeStamp,
+ const log4cxx::spi::LocationInfo& location,
+ const log4cxx::LogString& threadName);
+void flush_logger();
+
+bool logs_enabled();
+void set_logs_enabled(bool state);
+
+void create_log_message_loop_thread();
+void delete_log_message_loop_thread();
} // namespace logger
#endif // SRC_COMPONENTS_INCLUDE_UTILS_PUSH_LOG_H_
diff --git a/src/components/include/utils/rwlock.h b/src/components/include/utils/rwlock.h
index 1083dbd63f..b7e7484b48 100644
--- a/src/components/include/utils/rwlock.h
+++ b/src/components/include/utils/rwlock.h
@@ -51,10 +51,13 @@ typedef pthread_rwlock_t PlatformRWLock;
/**
* RW locks wrapper
- * Read-write locks permit concurrent reads and exclusive writes to a protected shared resource.
- * The read-write lock is a single entity that can be locked in read or write mode.
+ * Read-write locks permit concurrent reads and exclusive writes to a protected
+ * shared resource.
+ * The read-write lock is a single entity that can be locked in read or write
+ * mode.
* To modify a resource, a thread must first acquire the exclusive write lock.
- * An exclusive write lock is not permitted until all read locks have been released.
+ * An exclusive write lock is not permitted until all read locks have been
+ * released.
*/
class RWLock {
@@ -67,14 +70,19 @@ class RWLock {
* The calling thread acquires the read lock if a writer does not
* hold the lock and there are no writers blocked on the lock.
* It is unspecified whether the calling thread acquires the lock
- * when a writer does not hold the lock and there are writers waiting for the lock.
- * If a writer holds the lock, the calling thread will not acquire the read lock.
+ * when a writer does not hold the lock and there are writers waiting for the
+ * lock.
+ * If a writer holds the lock, the calling thread will not acquire the read
+ * lock.
* If the read lock is not acquired, the calling thread blocks
- * (that is, it does not return from the AcquireForReading()) until it can acquire the lock.
- * Results are undefined if the calling thread holds a write lock on rwlock at the time the call is made.
+ * (that is, it does not return from the AcquireForReading()) until it can
+ * acquire the lock.
+ * Results are undefined if the calling thread holds a write lock on rwlock at
+ * the time the call is made.
* A thread can hold multiple concurrent read locks on rwlock
* (that is, successfully call AcquireForReading() n times)
- * If so, the thread must perform matching unlocks (that is, it must call Release() n times).
+ * If so, the thread must perform matching unlocks (that is, it must call
+ * Release() n times).
* @returns true if lock was acquired and false if was not
*/
bool AcquireForReading();
@@ -91,9 +99,12 @@ class RWLock {
/**
* @brief Try to Acqure read-write lock for writing.
- * Applies a write lock like AcquireForWriting(), with the exception that the
- * function fails if any thread currently holds rwlock (for reading or writing)
- * Invoke of TryAcquireForWriting will not block calling thread and returns "false"
+ * Applies a write lock like AcquireForWriting(), with the exception that
+ * the
+ * function fails if any thread currently holds rwlock (for reading or
+ * writing)
+ * Invoke of TryAcquireForWriting will not block calling thread and returns
+ * "false"
* @returns true if lock was acquired and false if was not
*/
bool TryAcquireForWriting();
@@ -101,11 +112,13 @@ class RWLock {
/**
* @brief Acqure read-write lock for writing.
* Applies a write lock to the read-write lock.
- * The calling thread acquires the write lock if no other thread (reader or writer)
+ * The calling thread acquires the write lock if no other thread (reader or
+ * writer)
* holds the read-write lock rwlock. Otherwise, the thread blocks
* (that is, does not return from the AcquireForWriting() call)
* until it can acquire the lock.
- * Results are undefined if the calling thread holds the read-write lock (whether a read or write lock)
+ * Results are undefined if the calling thread holds the read-write lock
+ * (whether a read or write lock)
* at the time the call is made.
* The thread must perform matching unlock (that is, it must call Release()).
* @returns true if lock was acquired and false if was not
@@ -132,8 +145,7 @@ class RWLock {
class AutoReadLock {
public:
- explicit AutoReadLock(RWLock& rwlock)
- : rwlock_(rwlock) {
+ explicit AutoReadLock(RWLock& rwlock) : rwlock_(rwlock) {
rwlock_.AcquireForReading();
}
~AutoReadLock() {
@@ -147,12 +159,12 @@ class AutoReadLock {
/**
* @brief Makes auto lock read-write locks for writing
- * Please use AutoWriteLock to acquire for writing and (automatically) release it
+ * Please use AutoWriteLock to acquire for writing and (automatically) release
+ * it
*/
class AutoWriteLock {
public:
- explicit AutoWriteLock(RWLock& rwlock)
- : rwlock_(rwlock) {
+ explicit AutoWriteLock(RWLock& rwlock) : rwlock_(rwlock) {
rwlock_.AcquireForWriting();
}
~AutoWriteLock() {
diff --git a/src/components/include/utils/scope_guard.h b/src/components/include/utils/scope_guard.h
new file mode 100644
index 0000000000..bc60a7d288
--- /dev/null
+++ b/src/components/include/utils/scope_guard.h
@@ -0,0 +1,326 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_UTILS_SCOPE_GUARD_H
+#define SRC_COMPONENTS_INCLUDE_UTILS_SCOPE_GUARD_H
+
+namespace utils {
+
+/**
+ * @brief The ScopeGuardImplBase class the class which allows to keep safety
+ * raw pointer within local scope. The same ScopeGuard has been provided by
+ * Andrej Alexandresku in the Loki library.
+ *
+ * The usage area example:
+ *
+ * Suppose user have to create some pointer in function call Init(). And in case
+ * of some fail condition this pointer has to be freed. So in order to avoid
+ * code duplicate as follows:
+ *
+ * bool SomeClass::Init() {
+ * memberObject_ = custom_allocate() // initialize member object with some
+ *value
+ * if(!some_condition) {
+ * custom_release(memberObject();
+ * return false;
+ * }
+ *
+ * if(!other_condition) {
+ * custom_release(memberObject)
+ * return false;
+ * }
+ * return true;
+ * }
+ *
+ * The user is able to use ScopeGuard, where possible to automatically call
+ * custom release function. See example bellow:
+ *
+ * bool SomeClass::Init() {
+ * memberObject_ = custom_allocate() // initialize member object with some
+ *value
+ * // The guard will call custom release function when it goes out of scope.
+ * ScopeGaurd guard = MakeGuard(custom_release, memberObject);
+ * if(!some_condition) {
+ * return false;
+ * }
+ *
+ * if(!other_condition) {
+ * return false;
+ * }
+ * // Here to avoid object releasing the user has to call Dismiss method.
+ * // So no custom release function will be called after return statement.
+ * guard.Dismiss();
+ * return true;
+ * }
+ */
+class ScopeGuardImplBase {
+ public:
+ /**
+ * @brief ScopeGuardImplBase the ScopeGuards constructor.
+ */
+ ScopeGuardImplBase() : dismissed_(false) {}
+
+ /**
+ * @brief Dismiss function which allows to dismiss releasing of stored object.
+ */
+ void Dismiss() const {
+ dismissed_ = true;
+ }
+
+ protected:
+ /**
+ * @brief ScopeGuardImplBase the copy constructor
+ *
+ * @param other the object that should be copied.
+ */
+ ScopeGuardImplBase(const ScopeGuardImplBase& other)
+ : dismissed_(other.dismissed_) {
+ other.Dismiss();
+ }
+
+ /**
+ * Allows to safely execute release function(i.e. it will be called only
+ * in case of releasing wasn't dismiss.)
+ */
+ template <typename T>
+ void SafeExecute(T& t) {
+ if (!t.dismissed_) {
+ t.Execute();
+ }
+ }
+
+ ~ScopeGuardImplBase() {}
+
+ mutable bool dismissed_;
+
+ private:
+ // Disallow copying via assign operator.
+ ScopeGuardImplBase& operator=(const ScopeGuardImplBase&);
+};
+
+/**
+ * The class which allows to bind some parameter with free function.
+ * I.E.
+ * void release(char* p){delete p;}
+ *
+ * ScopeGuard guard = MakeGuard(release, p);
+ *
+ * So the parameter p will be passed to the specified function.
+ */
+template <typename Function, typename Parameter1>
+class ScopeGuardImpl1 : public ScopeGuardImplBase {
+ public:
+ /**
+ * @brief MakeGuard allows to create ScopeGuard object.
+ *
+ * @param fun function to call, when out of scope.
+ *
+ * @param p1 parameter which will be passed to the certain function.
+ *
+ * @return ScopeGuard object.
+ */
+ static ScopeGuardImpl1<Function, Parameter1> MakeGuard(Function fun,
+ const Parameter1& p1) {
+ return ScopeGuardImpl1<Function, Parameter1>(fun, p1);
+ }
+
+ /**
+ Execute the SafeExecute function in destructor.
+ */
+ ~ScopeGuardImpl1() {
+ SafeExecute(*this);
+ }
+
+ protected:
+ /**
+ * @brief Execute allows to execute certain function with certain parameter.
+ */
+ void Execute() {
+ fun_(p1_);
+ }
+
+ /**
+ * @brief ScopeGuardImpl1 create ScopeGuard object.
+ *
+ * @param f function object.
+ *
+ * @param p1 parameter to to pass to the function object.
+ */
+ ScopeGuardImpl1(const Function& f, const Parameter1& p1) : fun_(f), p1_(p1) {}
+
+ private:
+ Function fun_;
+ const Parameter1 p1_;
+
+ friend class ScopeGuardImplBase;
+};
+
+/**
+ * The class which allows to call some member function in case of
+ * ScopeGuard object out of scope.
+ * I.E.
+ * vector<int> vec;
+ *
+ * // When function returns, the pop_back method for vector will be called.
+ * void foo() {
+ * ScopeGuard guard = MakeObjGuard(vec, &vector::pop_back);
+ * vec.push_back(5);
+ * }
+ */
+template <typename Obj, typename MemFun>
+class ObjScopeGuardImpl0 : public ScopeGuardImplBase {
+ public:
+ /**
+ * @brief MakeObjGuard creates ScopeGuard object.
+ *
+ * @param obj object whose method will be called.
+ *
+ * @param memFun the method to call.
+ *
+ * @return ScopeGuard object.
+ */
+ static ObjScopeGuardImpl0<Obj, MemFun> MakeObjGuard(Obj& obj, MemFun memFun) {
+ return ObjScopeGuardImpl0<Obj, MemFun>(obj, memFun);
+ }
+
+ /**
+ Execute the SafeExecute function in destructor.
+ */
+ ~ObjScopeGuardImpl0() {
+ SafeExecute(*this);
+ }
+
+ protected:
+ /**
+ * @brief Execute allows to execute certain function with certain parameter.
+ */
+ void Execute() {
+ (obj_.*memFun_)();
+ }
+
+ /**
+ * @brief ObjScopeGuardImpl0 Create ScopeGuard object.
+ *
+ * @param obj object whose method will be called.
+ *
+ * @param memFun the method to call.
+ *
+ * @return ScopeGuard object.
+ */
+ ObjScopeGuardImpl0(Obj& obj, MemFun memFun) : obj_(obj), memFun_(memFun) {}
+
+ private:
+ Obj& obj_;
+ MemFun memFun_;
+ friend class ScopeGuardImplBase;
+};
+
+/**
+ * The class which allows to call some member function with certain parameter
+ * in case of ScopeGuard object out of scope.
+
+ */
+template <typename Obj, typename MemFun, typename Parameter1>
+class ObjScopeGuardImpl1 : public ScopeGuardImplBase {
+ public:
+ /**
+ * @brief MakeObjGuard creates ScopeGuard object.
+ *
+ * @param obj object whose method will be called.
+ *
+ * @param memFun the method to call.
+ *
+ * @param p1 the parameter to pass to the member function.
+ *
+ * @return ScopeGuard object.
+ */
+ static ObjScopeGuardImpl1<Obj, MemFun, Parameter1> MakeObjGuard(
+ Obj& obj, MemFun memFun, const Parameter1& p1) {
+ return ObjScopeGuardImpl1<Obj, MemFun, Parameter1>(obj, memFun, p1);
+ }
+
+ /**
+ Execute the SafeExecute function in destructor.
+ */
+ ~ObjScopeGuardImpl1() {
+ SafeExecute(*this);
+ }
+
+ protected:
+ /**
+ * @brief Execute allows to execute certain function with certain parameter.
+ */
+ void Execute() {
+ (obj_.*memFun_)(p1_);
+ }
+
+ /**
+ * @brief MakeObjGuard creates ScopeGuard object.
+ *
+ * @param obj object whose method will be called.
+ *
+ * @param memFun the method to call.
+ *
+ * @param p1 the parameter to pass to the member function.
+ *
+ * @return ScopeGuard object.
+ */
+ ObjScopeGuardImpl1(Obj& obj, MemFun memFun, const Parameter1& p1)
+ : obj_(obj), memFun_(memFun), p1_(p1) {}
+
+ private:
+ Obj& obj_;
+ MemFun memFun_;
+ const Parameter1 p1_;
+ friend class ScopeGuardImplBase;
+};
+
+typedef const ScopeGuardImplBase& ScopeGuard;
+
+template <typename F, typename P1>
+ScopeGuardImpl1<F, P1> MakeGuard(F fun, P1 p1) {
+ return ScopeGuardImpl1<F, P1>::MakeGuard(fun, p1);
+}
+
+template <typename Obj, typename MemFun>
+ObjScopeGuardImpl0<Obj, MemFun> MakeObjGuard(Obj& obj, MemFun memFun) {
+ return ObjScopeGuardImpl0<Obj, MemFun>::MakeObjGuard(obj, memFun);
+}
+
+template <typename Obj, typename MemFun, typename P1>
+ObjScopeGuardImpl1<Obj, MemFun, P1> MakeObjGuard(Obj& obj,
+ MemFun memFun,
+ const P1& p1) {
+ return ObjScopeGuardImpl1<Obj, MemFun, P1>::MakeObjGuard(obj, memFun, p1);
+}
+}
+#endif // SRC_COMPONENTS_INCLUDE_UTILS_SCOPE_GUARD_H
diff --git a/src/components/include/utils/shared_ptr.h b/src/components/include/utils/shared_ptr.h
index f506c6018e..064bb36b4a 100644
--- a/src/components/include/utils/shared_ptr.h
+++ b/src/components/include/utils/shared_ptr.h
@@ -41,6 +41,7 @@
#include "utils/atomic.h"
namespace utils {
+
/**
* @brief Shared pointer.
*
@@ -50,215 +51,228 @@ namespace utils {
*
* @tparam ObjectType Type of wrapped object.
**/
-template<typename ObjectType>
+template <typename ObjectType>
class SharedPtr {
- public:
- //std smart pointer compability
- typedef ObjectType element_type;
- /**
- * @brief Constructor.
- *
- * Initialize shared pointer with wrapped object.
- * Reference counter will be initialized to 1.
- *
- * @param Object Wrapped object.
- **/
- SharedPtr(ObjectType* Object);
-
- SharedPtr();
-
- /**
- * @brief Copy constructor.
- *
- * Initialize shared pointer with another shared pointer.
- * Reference counter will be incremented.
- *
- * @param Other Other shared pointer.
- **/
- SharedPtr(const SharedPtr<ObjectType>& Other);
-
- /**
- * @brief Copy constructor.
- *
- * Initialize shared pointer with another shared pointer.
- * Reference counter will be incremented.
- *
- * @tparam OtherObjectType Type of other object pointer. This
- * allows creating a shared pointer to an
- * intstance of a base class from a shared
- * pointer to an instance of a class
- * inherited from this base class.
- * If OtherObjectType is not implicitly
- * convertible to ObjectType it will
- * cause a compile error.
- *
- * @param Other Other shared pointer.
- **/
- template<typename OtherObjectType>
- SharedPtr(const SharedPtr<OtherObjectType>& Other);
-
- /**
- * @brief Destructor.
- *
- * Decrement reference counter and destroy wrapped object
- * if reference counter reaches zero.
- **/
- ~SharedPtr();
-
- /**
- * @brief Assignment operator.
- *
- * Drop reference to currently referenced object and add
- * reference to assigned object.
- *
- * @param Other Shared pointer to an object
- * that must be referenced.
- *
- * @return Reference to this shared pointer.
- **/
- SharedPtr<ObjectType>& operator =(const SharedPtr<ObjectType>& Other);
-
- bool operator ==(const SharedPtr<ObjectType>& Other) const;
-
- bool operator< (const SharedPtr<ObjectType>& other) const;
-
- /**
- * @brief Assignment operator.
- *
- * Drop reference to currently referenced object and add
- * reference to assigned object.
- *
- * @tparam OtherObjectType Type of other object pointer. This
- * allows creating a shared pointer to an
- * intstance of a base class from a shared
- * pointer to an instance of a class
- * inherited from this base class.
- * If OtherObjectType is not implicitly
- * convertible to ObjectType it will
- * cause a compile error.
- *
- * @param Other Shared pointer to an object
- * that must be referenced.
- *
- * @return Reference to this shared pointer.
- **/
- template<typename OtherObjectType>
- SharedPtr<ObjectType>& operator =(const SharedPtr<OtherObjectType>& Other);
-
- template<typename OtherObjectType>
- static SharedPtr<OtherObjectType> static_pointer_cast(
+ static void DummyDeleter(ObjectType* object_to_delete) {
+ delete object_to_delete;
+ }
+
+ public:
+ // std smart pointer compatibility
+ typedef ObjectType element_type;
+ typedef void (*Deleter)(ObjectType*);
+ /**
+ * @brief Constructor.
+ *
+ * Initialize shared pointer with wrapped object.
+ * Reference counter will be initialized to 1.
+ *
+ * @param Object Wrapped object.
+ **/
+ SharedPtr(ObjectType* Object);
+
+ SharedPtr(ObjectType* Object, Deleter deleter)
+ : mObject(Object)
+ , mReferenceCounter(new uint32_t(1))
+ , deleter_(deleter) {}
+
+ SharedPtr();
+
+ /**
+ * @brief Copy constructor.
+ *
+ * Initialize shared pointer with another shared pointer.
+ * Reference counter will be incremented.
+ *
+ * @param Other Other shared pointer.
+ **/
+ SharedPtr(const SharedPtr<ObjectType>& Other);
+
+ /**
+ * @brief Copy constructor.
+ *
+ * Initialize shared pointer with another shared pointer.
+ * Reference counter will be incremented.
+ *
+ * @tparam OtherObjectType Type of other object pointer. This
+ * allows creating a shared pointer to an
+ * intstance of a base class from a shared
+ * pointer to an instance of a class
+ * inherited from this base class.
+ * If OtherObjectType is not implicitly
+ * convertible to ObjectType it will
+ * cause a compile error.
+ *
+ * @param Other Other shared pointer.
+ **/
+ template <typename OtherObjectType>
+ SharedPtr(const SharedPtr<OtherObjectType>& Other);
+
+ /**
+ * @brief Destructor.
+ *
+ * Decrement reference counter and destroy wrapped object
+ * if reference counter reaches zero.
+ **/
+ ~SharedPtr();
+
+ /**
+ * @brief Assignment operator.
+ *
+ * Drop reference to currently referenced object and add
+ * reference to assigned object.
+ *
+ * @param Other Shared pointer to an object
+ * that must be referenced.
+ *
+ * @return Reference to this shared pointer.
+ **/
+ SharedPtr<ObjectType>& operator=(const SharedPtr<ObjectType>& Other);
+
+ bool operator==(const SharedPtr<ObjectType>& Other) const;
+
+ bool operator<(const SharedPtr<ObjectType>& other) const;
+
+ /**
+ * @brief Assignment operator.
+ *
+ * Drop reference to currently referenced object and add
+ * reference to assigned object.
+ *
+ * @tparam OtherObjectType Type of other object pointer. This
+ * allows creating a shared pointer to an
+ * intstance of a base class from a shared
+ * pointer to an instance of a class
+ * inherited from this base class.
+ * If OtherObjectType is not implicitly
+ * convertible to ObjectType it will
+ * cause a compile error.
+ *
+ * @param Other Shared pointer to an object
+ * that must be referenced.
+ *
+ * @return Reference to this shared pointer.
+ **/
+ template <typename OtherObjectType>
+ SharedPtr<ObjectType>& operator=(const SharedPtr<OtherObjectType>& Other);
+
+ template <typename OtherObjectType>
+ static SharedPtr<OtherObjectType> static_pointer_cast(
const SharedPtr<ObjectType>& pointer);
- template<typename OtherObjectType>
- static SharedPtr<OtherObjectType> dynamic_pointer_cast(
+ template <typename OtherObjectType>
+ static SharedPtr<OtherObjectType> dynamic_pointer_cast(
const SharedPtr<ObjectType>& pointer);
- /**
- * @brief Member access operator.
- *
- * @return Wrapped object.
- **/
- ObjectType* operator->() const;
-
- ObjectType& operator*() const;
- operator bool() const;
- void reset();
- void reset(ObjectType* other);
- ObjectType* get() const;
-
- /**
- * @return true if mObject not NULL
- */
- bool valid() const;
-
- private:
- void reset_impl(ObjectType* other);
-
- // TSharedPtr needs access to other TSharedPtr private members
- // for shared pointers type casts.
- template<typename OtherObjectType>
- friend class SharedPtr;
-
- /**
- * @brief Drop reference to wrapped object.
- *
- * If reference counter reaches zero object and its reference
- * counter will be deallocated.
- **/
- void dropReference();
-
- /**
- * @brief Wrapped object.
- **/
- ObjectType* mObject;
-
- /**
- * @brief Pointer to reference counter.
- **/
- uint32_t* mReferenceCounter;
-
- void release();
+ /**
+ * @brief Member access operator.
+ *
+ * @return Wrapped object.
+ **/
+ ObjectType* operator->() const;
+
+ ObjectType& operator*() const;
+ operator bool() const;
+ void reset();
+ void reset(ObjectType* other);
+ ObjectType* get() const;
+
+#ifdef BUILD_TESTS
+ inline const uint32_t* get_ReferenceCounter() const {
+ return mReferenceCounter;
+ }
+#endif // BUILD_TESTS
+
+ /**
+ * @return true if mObject not NULL
+ */
+ bool valid() const;
+
+ private:
+ void reset_impl(ObjectType* other);
+
+ // TSharedPtr needs access to other TSharedPtr private members
+ // for shared pointers type casts.
+ template <typename OtherObjectType>
+ friend class SharedPtr;
+
+ /**
+ * @brief Drop reference to wrapped object.
+ *
+ * If reference counter reaches zero object and its reference
+ * counter will be deallocated.
+ **/
+ void dropReference();
+
+ /**
+ * @brief Wrapped object.
+ **/
+ ObjectType* mObject;
+
+ /**
+ * @brief Pointer to reference counter.
+ **/
+ uint32_t* mReferenceCounter;
+
+ Deleter deleter_;
+ void release();
};
-template<typename ObjectType>
+template <typename ObjectType>
inline utils::SharedPtr<ObjectType>::SharedPtr(ObjectType* Object)
- : mObject(NULL),
- mReferenceCounter(new uint32_t(1)) {
+ : mObject(NULL)
+ , mReferenceCounter(new uint32_t(1))
+ , deleter_(DummyDeleter) {
DCHECK(Object != NULL);
mObject = Object;
}
-template<typename ObjectType>
+template <typename ObjectType>
inline utils::SharedPtr<ObjectType>::SharedPtr()
- : mObject(0),
- mReferenceCounter(0) {
-}
+ : mObject(0), mReferenceCounter(0), deleter_(DummyDeleter) {}
-template<typename ObjectType>
+template <typename ObjectType>
inline utils::SharedPtr<ObjectType>::SharedPtr(
- const SharedPtr<ObjectType>& Other)
- : mObject(0),
- mReferenceCounter(0) {
+ const SharedPtr<ObjectType>& Other)
+ : mObject(0), mReferenceCounter(0), deleter_(DummyDeleter) {
*this = Other;
}
-template<typename ObjectType>
-template<typename OtherObjectType>
+template <typename ObjectType>
+template <typename OtherObjectType>
inline utils::SharedPtr<ObjectType>::SharedPtr(
- const SharedPtr<OtherObjectType>& Other)
- : mObject(0),
- mReferenceCounter(0) {
+ const SharedPtr<OtherObjectType>& Other)
+ : mObject(0), mReferenceCounter(0), deleter_(DummyDeleter) {
*this = Other;
}
-template<typename ObjectType>
+template <typename ObjectType>
inline utils::SharedPtr<ObjectType>::~SharedPtr() {
dropReference();
}
-template<typename ObjectType>
-inline utils::SharedPtr<ObjectType>&
-utils::SharedPtr<ObjectType>::operator=(const SharedPtr<ObjectType>& Other) {
+template <typename ObjectType>
+inline utils::SharedPtr<ObjectType>& utils::SharedPtr<ObjectType>::operator=(
+ const SharedPtr<ObjectType>& Other) {
return operator=<ObjectType>(Other);
}
-template<typename ObjectType>
-inline bool utils::SharedPtr<ObjectType>::operator ==(
- const SharedPtr<ObjectType>& Other) const {
+template <typename ObjectType>
+inline bool utils::SharedPtr<ObjectType>::operator==(
+ const SharedPtr<ObjectType>& Other) const {
return (mObject == Other.mObject);
}
-template<typename ObjectType>
-inline bool utils::SharedPtr<ObjectType>::operator< (
- const SharedPtr<ObjectType>& other) const {
+template <typename ObjectType>
+inline bool utils::SharedPtr<ObjectType>::operator<(
+ const SharedPtr<ObjectType>& other) const {
return (mObject < other.mObject);
}
-template<typename ObjectType>
-template<typename OtherObjectType>
-inline utils::SharedPtr<ObjectType>&
-utils::SharedPtr<ObjectType>::operator=(
- const SharedPtr<OtherObjectType>& Other) {
+template <typename ObjectType>
+template <typename OtherObjectType>
+inline utils::SharedPtr<ObjectType>& utils::SharedPtr<ObjectType>::operator=(
+ const SharedPtr<OtherObjectType>& Other) {
dropReference();
mObject = Other.mObject;
@@ -271,9 +285,10 @@ utils::SharedPtr<ObjectType>::operator=(
return *this;
}
-template<typename ObjectType>
-template<typename OtherObjectType>
-utils::SharedPtr<OtherObjectType> utils::SharedPtr<ObjectType>::static_pointer_cast(const SharedPtr<ObjectType>& pointer) {
+template <typename ObjectType>
+template <typename OtherObjectType>
+utils::SharedPtr<OtherObjectType> utils::SharedPtr<
+ ObjectType>::static_pointer_cast(const SharedPtr<ObjectType>& pointer) {
SharedPtr<OtherObjectType> casted_pointer;
casted_pointer.mObject = static_cast<OtherObjectType*>(pointer.mObject);
casted_pointer.mReferenceCounter = pointer.mReferenceCounter;
@@ -285,9 +300,10 @@ utils::SharedPtr<OtherObjectType> utils::SharedPtr<ObjectType>::static_pointer_c
return casted_pointer;
}
-template<typename ObjectType>
-template<typename OtherObjectType>
-utils::SharedPtr<OtherObjectType> utils::SharedPtr<ObjectType>::dynamic_pointer_cast(const SharedPtr<ObjectType>& pointer) {
+template <typename ObjectType>
+template <typename OtherObjectType>
+utils::SharedPtr<OtherObjectType> utils::SharedPtr<
+ ObjectType>::dynamic_pointer_cast(const SharedPtr<ObjectType>& pointer) {
SharedPtr<OtherObjectType> casted_pointer;
casted_pointer.mObject = dynamic_cast<OtherObjectType*>(pointer.mObject);
if (NULL != casted_pointer.mObject) {
@@ -301,52 +317,51 @@ utils::SharedPtr<OtherObjectType> utils::SharedPtr<ObjectType>::dynamic_pointer_
return casted_pointer;
}
-template<typename ObjectType> ObjectType*
-utils::SharedPtr<ObjectType>::operator->() const {
+template <typename ObjectType>
+ObjectType* utils::SharedPtr<ObjectType>::operator->() const {
DCHECK(mObject);
return mObject;
}
-template<typename ObjectType> ObjectType&
-utils::SharedPtr<ObjectType>::operator*() const {
+template <typename ObjectType>
+ObjectType& utils::SharedPtr<ObjectType>::operator*() const {
DCHECK(mObject);
return *mObject;
}
-template<typename ObjectType>
+template <typename ObjectType>
utils::SharedPtr<ObjectType>::operator bool() const {
return valid();
}
-template<typename ObjectType> void
-utils::SharedPtr<ObjectType>::reset() {
+template <typename ObjectType>
+void utils::SharedPtr<ObjectType>::reset() {
reset_impl(0);
}
-template<typename ObjectType> void
-utils::SharedPtr<ObjectType>::reset(ObjectType* other) {
+template <typename ObjectType>
+void utils::SharedPtr<ObjectType>::reset(ObjectType* other) {
DCHECK(other != NULL);
reset_impl(other);
}
-template<typename ObjectType>
+template <typename ObjectType>
void SharedPtr<ObjectType>::release() {
-
- delete mObject;
+ deleter_(mObject);
mObject = 0;
delete mReferenceCounter;
mReferenceCounter = 0;
}
-template<typename ObjectType> void
-utils::SharedPtr<ObjectType>::reset_impl(ObjectType* other) {
+template <typename ObjectType>
+void utils::SharedPtr<ObjectType>::reset_impl(ObjectType* other) {
dropReference();
mObject = other;
mReferenceCounter = new uint32_t(1);
}
-template<typename ObjectType>
+template <typename ObjectType>
inline void SharedPtr<ObjectType>::dropReference() {
if (0 != mReferenceCounter) {
if (1 == atomic_post_dec(mReferenceCounter)) {
@@ -355,12 +370,12 @@ inline void SharedPtr<ObjectType>::dropReference() {
}
}
-template<typename ObjectType>
+template <typename ObjectType>
ObjectType* SharedPtr<ObjectType>::get() const {
return mObject;
}
-template<typename ObjectType>
+template <typename ObjectType>
inline bool SharedPtr<ObjectType>::valid() const {
if (mReferenceCounter && (0 < *mReferenceCounter)) {
return (mObject != NULL);
diff --git a/src/components/include/utils/threads/async_runner.h b/src/components/include/utils/threads/async_runner.h
index c3afe4eea0..c6da0638f4 100644
--- a/src/components/include/utils/threads/async_runner.h
+++ b/src/components/include/utils/threads/async_runner.h
@@ -52,76 +52,75 @@ namespace threads {
* is kind of manager for async functions.
*/
class AsyncRunner {
- public:
+ public:
+ /**
+ * @brief AsyncRunner constructor, allows to create and run new thread.
+ * The thread will be removed in destructor and appropriate delegate will
+ * be removed some time latter after pthred_join.
+ *
+ * @param thread_name thread's name.
+ *
+ * @param delegate delegate to run within thread.
+ */
+ explicit AsyncRunner(const std::string& thread_name);
+
+ /**
+ * @brief AsyncRun pass obtained delegate into internal queue
+ *
+ * @param delegate the objet which has to be concuremtly run
+ */
+ void AsyncRun(threads::ThreadDelegate* delegate);
+ /**
+ * @brief Stop delegates activity
+ */
+ void Stop();
+
+ ~AsyncRunner();
+
+ private:
+ class AsyncRunnerDelegate : public threads::ThreadDelegate {
+ public:
+ AsyncRunnerDelegate();
+
/**
- * @brief AsyncRunner constructor, allows to create and run new thread.
- * The thread will be removed in destructor and appropriate delegate will
- * be removed some time latter after pthred_join.
- *
- * @param thread_name thread's name.
- *
- * @param delegate delegate to run within thread.
+ * @brief threadMain runs delegates queue handling.
+ */
+ virtual void threadMain();
+
+ /**
+ * @brief exitThreadMain doing stuff before exit from thread.
*/
- explicit AsyncRunner(const std::string& thread_name);
+ virtual void exitThreadMain();
/**
- * @brief AsyncRun pass obtained delegate into internal queue
+ * @brief runDelegate push obtained delegate into specific queue
*
- * @param delegate the objet which has to be concuremtly run
+ * @param delegate object that has to be executed.
*/
- void AsyncRun(threads::ThreadDelegate* delegate);
+ void runDelegate(threads::ThreadDelegate* delegate);
+
+ private:
+ /**
+ * @brief processDelegate allows to pop delegate
+ * from queue and process it.
+ */
+ void processDelegate();
+
/**
- * @brief Stop delegates activity
+ * @brief waitForDelegate wait while delegates queue is empty.
*/
- void Stop();
-
- ~AsyncRunner();
-
- private:
-
- class AsyncRunnerDelegate: public threads::ThreadDelegate {
- public:
- AsyncRunnerDelegate();
-
- /**
- * @brief threadMain runs delegates queue handling.
- */
- virtual void threadMain();
-
- /**
- * @brief exitThreadMain doing stuff before exit from thread.
- */
- virtual void exitThreadMain();
-
- /**
- * @brief runDelegate push obtained delegate into specific queue
- *
- * @param delegate object that has to be executed.
- */
- void runDelegate(threads::ThreadDelegate* delegate);
-
- private:
- /**
- * @brief processDelegate allows to pop delegate
- * from queue and process it.
- */
- void processDelegate();
-
- /**
- * @brief waitForDelegate wait while delegates queue is empty.
- */
- void waitForDelegate();
-
- std::queue<threads::ThreadDelegate*> delegates_queue_;
- sync_primitives::ConditionalVariable delegate_notifier_;
- sync_primitives::Lock delegates_queue_lock_;
- volatile bool stop_flag_;
- };
-
- threads::Thread* thread_;
- AsyncRunnerDelegate* executor_;
+ void waitForDelegate();
+
+ std::queue<threads::ThreadDelegate*> delegates_queue_;
+ sync_primitives::ConditionalVariable delegate_notifier_;
+ sync_primitives::Lock delegates_queue_lock_;
+ volatile bool stop_flag_;
+ };
+
+ threads::Thread* thread_;
+ AsyncRunnerDelegate* executor_;
};
-} // namespace threads
+} // namespace threads
-#endif // SRC_COMPONENTS_INCLUDE_UTILS_ASYNC_RUNNER_H_
+#endif // SRC_COMPONENTS_INCLUDE_UTILS_ASYNC_RUNNER_H_
diff --git a/src/components/include/utils/threads/message_loop_thread.h b/src/components/include/utils/threads/message_loop_thread.h
index 6f90df209c..15023f02dd 100644
--- a/src/components/include/utils/threads/message_loop_thread.h
+++ b/src/components/include/utils/threads/message_loop_thread.h
@@ -41,6 +41,7 @@
#include "utils/message_queue.h"
#include "utils/threads/thread.h"
#include "utils/shared_ptr.h"
+#include "utils/lock.h"
namespace threads {
@@ -52,7 +53,7 @@ using ::utils::MessageQueue;
* to it's queue. To handle messages someone, Handler must be implemented and
* passed to MessageLoopThread constructor.
*/
-template < class Q >
+template <class Q>
class MessageLoopThread {
public:
typedef Q Queue;
@@ -67,7 +68,8 @@ class MessageLoopThread {
* Method called by MessageLoopThread to process single message
* from it's queue. After calling this method message is discarded.
*/
- virtual void Handle(const Message message) = 0; // TODO(dchmerev): Use reference?
+ // TODO (AKozoriz) : change to const reference (APPLINK-20235)
+ virtual void Handle(const Message message) = 0;
virtual ~Handler() {}
};
@@ -86,12 +88,21 @@ class MessageLoopThread {
// Process already posted messages and stop thread processing. Thread-safe.
void Shutdown();
+ // Added for utils/test/auto_trace_test.cc
+ size_t GetMessageQueueSize() const;
+
+ /*
+ * Wait until message queue will be empty
+ */
+ void WaitDumpQueue();
+
private:
/*
* Implementation of ThreadDelegate that actually pumps the queue and is
* able to correctly shut it down
*/
- struct LoopThreadDelegate : public threads::ThreadDelegate {
+ class LoopThreadDelegate : public threads::ThreadDelegate {
+ public:
LoopThreadDelegate(MessageQueue<Message, Queue>* message_queue,
Handler* handler);
@@ -116,13 +127,17 @@ class MessageLoopThread {
///////// Implementation
-template<class Q>
-MessageLoopThread<Q>::MessageLoopThread(const std::string& name,
- Handler* handler,
+template <class Q>
+size_t MessageLoopThread<Q>::GetMessageQueueSize() const {
+ return message_queue_.size();
+}
+
+template <class Q>
+MessageLoopThread<Q>::MessageLoopThread(const std::string& name,
+ Handler* handler,
const ThreadOptions& thread_opts)
- : thread_delegate_(new LoopThreadDelegate(&message_queue_, handler)),
- thread_(threads::CreateThread(name.c_str(),
- thread_delegate_)) {
+ : thread_delegate_(new LoopThreadDelegate(&message_queue_, handler))
+ , thread_(threads::CreateThread(name.c_str(), thread_delegate_)) {
const bool started = thread_->start(thread_opts);
if (!started) {
CREATE_LOGGERPTR_LOCAL(logger_, "Utils")
@@ -130,10 +145,9 @@ MessageLoopThread<Q>::MessageLoopThread(const std::string& name,
}
}
-template<class Q>
+template <class Q>
MessageLoopThread<Q>::~MessageLoopThread() {
Shutdown();
- thread_->join();
delete thread_delegate_;
threads::DeleteThread(thread_);
}
@@ -145,20 +159,24 @@ void MessageLoopThread<Q>::PostMessage(const Message& message) {
template <class Q>
void MessageLoopThread<Q>::Shutdown() {
- thread_->stop();
+ thread_->join();
+}
+
+template <class Q>
+void MessageLoopThread<Q>::WaitDumpQueue() {
+ message_queue_.WaitUntilEmpty();
}
//////////
-template<class Q>
+template <class Q>
MessageLoopThread<Q>::LoopThreadDelegate::LoopThreadDelegate(
MessageQueue<Message, Queue>* message_queue, Handler* handler)
- : handler_(*handler),
- message_queue_(*message_queue) {
+ : handler_(*handler), message_queue_(*message_queue) {
DCHECK(handler != NULL);
DCHECK(message_queue != NULL);
}
-template<class Q>
+template <class Q>
void MessageLoopThread<Q>::LoopThreadDelegate::threadMain() {
CREATE_LOGGERPTR_LOCAL(logger_, "Utils")
LOG4CXX_AUTO_TRACE(logger_);
@@ -170,18 +188,20 @@ void MessageLoopThread<Q>::LoopThreadDelegate::threadMain() {
DrainQue();
}
-template<class Q>
+template <class Q>
void MessageLoopThread<Q>::LoopThreadDelegate::exitThreadMain() {
- CREATE_LOGGERPTR_LOCAL(logger_, "Utils")
- LOG4CXX_AUTO_TRACE(logger_);
message_queue_.Shutdown();
}
-template<class Q>
+template <class Q>
void MessageLoopThread<Q>::LoopThreadDelegate::DrainQue() {
while (!message_queue_.empty()) {
- handler_.Handle(message_queue_.pop());
+ Message msg;
+ if (message_queue_.pop(msg)) {
+ handler_.Handle(msg);
+ }
}
}
+
} // namespace threads
#endif // SRC_COMPONENTS_INCLUDE_UTILS_THREADS_MESSAGE_LOOP_THREAD_H_
diff --git a/src/components/include/utils/threads/thread.h b/src/components/include/utils/threads/thread.h
index fd2b5e9fd9..c81b912e9a 100644
--- a/src/components/include/utils/threads/thread.h
+++ b/src/components/include/utils/threads/thread.h
@@ -119,12 +119,11 @@ class Thread {
return delegate_lock_;
}
- ThreadDelegate *delegate() const {
+ ThreadDelegate* delegate() const {
return delegate_;
}
- void set_delegate(ThreadDelegate *delegate) {
- DCHECK(!isThreadRunning_);
+ void set_delegate(ThreadDelegate* delegate) {
delegate_ = delegate;
}
@@ -132,6 +131,9 @@ class Thread {
friend void DeleteThread(Thread* thread);
public:
+ // Yield current thread
+ static void yield();
+
// Get unique ID of currently executing thread
static PlatformThreadHandle CurrentId();
@@ -195,6 +197,12 @@ class Thread {
}
/**
+ * @brief Checks if invoked in this Thread context
+ * @return True if called from this Thread class, false otherwise
+ */
+ bool IsCurrentThread() const;
+
+ /**
* @brief Thread options.
* @return thread options.
*/
diff --git a/src/components/include/utils/threads/thread_delegate.h b/src/components/include/utils/threads/thread_delegate.h
index 66ad30241c..2f2c8b3744 100644
--- a/src/components/include/utils/threads/thread_delegate.h
+++ b/src/components/include/utils/threads/thread_delegate.h
@@ -39,11 +39,7 @@
namespace threads {
-enum ThreadState {
- kInit = 0,
- kStarted = 1,
- kStopReq = 2
-};
+enum ThreadState { kInit = 0, kStarted = 1, kStopReq = 2 };
class Thread;
@@ -53,10 +49,7 @@ class Thread;
*/
class ThreadDelegate {
public:
- ThreadDelegate()
- : state_(kInit),
- thread_(NULL) {
- }
+ ThreadDelegate() : state_(kInit), thread_(NULL) {}
/**
* \brief Thread procedure.
*/
@@ -76,7 +69,7 @@ class ThreadDelegate {
return thread_;
}
- void set_thread(Thread *thread);
+ void set_thread(Thread* thread);
bool ImproveState(unsigned int to) {
state_lock_.Lock();
diff --git a/src/components/include/utils/threads/thread_options.h b/src/components/include/utils/threads/thread_options.h
index 797ee0693b..2f5c90ae44 100644
--- a/src/components/include/utils/threads/thread_options.h
+++ b/src/components/include/utils/threads/thread_options.h
@@ -51,15 +51,12 @@ class ThreadOptions {
* @param is_joinable - is thread joinable?
*/
explicit ThreadOptions(size_t stack_size = 0, bool is_joinable = true)
- : stack_size_(stack_size),
- is_joinable_(is_joinable) {
- }
+ : stack_size_(stack_size), is_joinable_(is_joinable) {}
/**
* Dtor.
*/
- virtual ~ThreadOptions() {
- }
+ virtual ~ThreadOptions() {}
/**
* Copy ctor.
diff --git a/src/components/include/utils/timer_thread.h b/src/components/include/utils/timer_thread.h
deleted file mode 100644
index 4236c4e46f..0000000000
--- a/src/components/include/utils/timer_thread.h
+++ /dev/null
@@ -1,449 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_INCLUDE_UTILS_TIMER_THREAD_H_
-#define SRC_COMPONENTS_INCLUDE_UTILS_TIMER_THREAD_H_
-
-#include <time.h>
-#include <inttypes.h>
-#include <cstdint>
-#include <limits>
-#include <string>
-
-#include "utils/conditional_variable.h"
-#include "utils/lock.h"
-#include "utils/logger.h"
-#include "utils/macro.h"
-#include "utils/timer_thread.h"
-#include "utils/threads/thread.h"
-#include "utils/threads/thread_delegate.h"
-
-namespace timer {
-// TODO(AKutsan): Remove this logger after bugfix
-CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")
-
-class TimerDelegate;
-
-/**
- * \class TimerThread
- * \brief TimerThread class provide possibility to run timer in a separate thread.
- * The client should specify callee and const callback function.
- * Example usage:
- *
- * Create timer in mobile request
- *
- * timer::TimerThread<MobileRequest> timer(this, &MobileRequest::onTimeOut);
- * timer.start(10);
- *
- * some actions
- *
- * To stop timer call timer.stop();
- *
- */
-template<class T>
-class TimerThread {
- public:
- friend class TimerDelegate;
- friend class TimerLooperDelegate;
-
- /**
- * @brief Default constructor
- *
- * @param name - display string to identify the thread.
- * @param callee A class that use timer
- * @param f CallBackFunction which will be called on timeout
- * Attention! "f()" will be called not in main thread but in timer thread
- * Never use stop() and start() methods inside f
- * @param is_looper Define this timer as looper,
- * if true, TimerThread will call "f()" function every time out
- * until stop()
- */
- TimerThread(const char* name, T* callee, void (T::*f)(), bool is_looper =
- false);
-
- /**
- * @brief Destructor
- */
- virtual ~TimerThread();
-
- /**
- * @brief Starts timer for specified timeout.
- * Previously started timeout will be set to new value.
- * On timeout TimerThread::onTimeOut interface will be called.
- * Must not be used in callback function!
- *
- * @param timeout_seconds Timeout in seconds to be set
- */
- virtual void start(uint32_t timeout_seconds);
-
- /**
- * @brief Starts timer for specified timeout.
- * Previously started timeout will be set to new value.
- * On timeout TimerThread::onTimeOut interface will be called.
- * Must not be used in callback function!
- *
- * @param timeout_seconds Timeout in seconds to be set
- *
- * @param callee A class that use timer
- *
- * @param allBackFunction which will be called on timeout
- * Attention! "f()" will be called not in main thread but in timer thread
- * Never use stop() and start() methods inside f
- */
- virtual void start(uint32_t timeout_seconds, T* callee, void (T::*f)());
-
- /**
- * @brief Stops timer execution
- * Must not be used in callback function!
- */
- virtual void stop();
-
- /**
- * @brief Tell timer status
- * @return true if timer is currently running, otherwise return false
- */
- virtual bool isRunning();
-
- /**
- * @brief Suspends timer execution after next loop.
- */
- virtual void suspend();
-
- /**
- * @brief Stop timer update timeout and start timer again
- * Note that it cancel thread of timer, If you use it from callback,
- * it probably will stop execution of callback function
- * @param timeout_seconds new timeout value
- *
- */
- virtual void updateTimeOut(const uint32_t timeout_seconds);
-
- protected:
- /**
- * @brief Interface called by delegator on timeout
- */
- void onTimeOut() const;
-
- private:
- /**
- * @brief Delegate release timer, will call callback function one time
- */
- class TimerDelegate : public threads::ThreadDelegate {
- public:
- /**
- * @brief Default constructor
- *
- * @param timer_thread The Timer_thread pointer
- */
- explicit TimerDelegate(TimerThread* timer_thread);
-
- /**
- * @brief Destructor
- */
- virtual ~TimerDelegate();
-
- /**
- * @brief Thread main function.
- */
- virtual void threadMain();
-
- /**
- * @brief Called by thread::thread to free all allocated resources.
- */
- virtual void exitThreadMain();
-
- /**
- * @brief Set new Timeout
- * @param timeout_seconds New timeout to be set
- */
- virtual void setTimeOut(const uint32_t timeout_seconds);
-
- /**
- * @brief Quits threadMain function after next loop.
- */
- virtual void shouldBeStoped();
-
- /**
- * @brief Restarts non-loop timer after current iteration.
- */
- virtual void shouldBeRestarted();
-
- protected:
- TimerThread* timer_thread_;
- uint32_t timeout_seconds_;
- sync_primitives::Lock state_lock_;
- sync_primitives::ConditionalVariable termination_condition_;
- volatile bool stop_flag_;
- sync_primitives::Lock restart_flag_lock_;
- volatile bool restart_flag_;
- int32_t calculateMillisecondsLeft();
-
- private:
- DISALLOW_COPY_AND_ASSIGN(TimerDelegate);
- };
-
- /**
- * @brief Delegate release looper timer.
- * Will call delegate every timeout function while stop()
- * won't be called
- */
- class TimerLooperDelegate : public TimerDelegate {
- public:
- /**
- * @brief Default constructor
- *
- * @param timer_thread The Timer_thread pointer
- * @param timeout Timeout to be set
- */
- explicit TimerLooperDelegate(TimerThread* timer_thread);
-
- /**
- * @brief Thread main function.
- */
- virtual void threadMain();
-
- private:
- DISALLOW_COPY_AND_ASSIGN(TimerLooperDelegate);
- };
- threads::Thread* thread_;
- void (T::*callback_)();
- T* callee_;
- TimerDelegate* delegate_;
- std::string name_;
- volatile bool is_looper_;
-
- DISALLOW_COPY_AND_ASSIGN(TimerThread);
-};
-
-template<class T>
-TimerThread<T>::TimerThread(const char* name, T* callee, void (T::*f)(),
- bool is_looper)
- : thread_(NULL),
- callback_(f),
- callee_(callee),
- delegate_(NULL),
- name_(name),
- is_looper_(is_looper) {
- delegate_ =
- is_looper_ ? new TimerLooperDelegate(this) : new TimerDelegate(this);
-
- thread_ = threads::CreateThread(name_.c_str(), delegate_);
-}
-
-template<class T>
-TimerThread<T>::~TimerThread() {
- LOG4CXX_DEBUG(logger_, "TimerThread is to be destroyed " << name_);
- thread_->join();
- delete delegate_;
- threads::DeleteThread(thread_);
- callback_ = NULL;
- callee_ = NULL;
-}
-
-template<class T>
-void TimerThread<T>::start(uint32_t timeout_seconds) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (isRunning()) {
- LOG4CXX_INFO(logger_, "Restart timer in thread " << name_);
- delegate_->shouldBeRestarted();
- updateTimeOut(timeout_seconds);
- } else {
- updateTimeOut(timeout_seconds);
- thread_->start();
- }
-}
-
-template<class T>
-void TimerThread<T>::start(uint32_t timeout_seconds, T* callee,
- void (T::*f)()) {
- callee_ = callee;
- callback_ = f;
- start(timeout_seconds);
-}
-
-template<class T>
-void TimerThread<T>::stop() {
- LOG4CXX_AUTO_TRACE(logger_);
- DCHECK(thread_);
- LOG4CXX_DEBUG(logger_, "Stopping timer " << name_);
- thread_->join();
-}
-
-template<class T>
-bool TimerThread<T>::isRunning() {
- DCHECK(thread_);
- return thread_->is_running();
-}
-
-template<class T>
-void TimerThread<T>::suspend() {
- LOG4CXX_DEBUG(logger_, "Suspend timer " << name_ << " after next loop");
- delegate_->shouldBeStoped();
-}
-
-template<class T>
-void TimerThread<T>::updateTimeOut(const uint32_t timeout_seconds) {
- delegate_->setTimeOut(timeout_seconds);
-}
-
-template<class T> void TimerThread<T>::onTimeOut() const {
- if (callee_ && callback_) {
- (callee_->*callback_)();
- }
-}
-
-template<class T>
-TimerThread<T>::TimerDelegate::TimerDelegate(TimerThread* timer_thread)
- : timer_thread_(timer_thread),
- timeout_seconds_(0),
- state_lock_(true),
- stop_flag_(false),
- restart_flag_(false) {
- DCHECK(timer_thread_);
-}
-
-template<class T>
-TimerThread<T>::TimerLooperDelegate::TimerLooperDelegate(
- TimerThread* timer_thread)
- : TimerDelegate(timer_thread) {
-}
-
-template<class T>
-TimerThread<T>::TimerDelegate::~TimerDelegate() {
- timer_thread_ = NULL;
-}
-
-template<class T>
-void TimerThread<T>::TimerDelegate::threadMain() {
- using sync_primitives::ConditionalVariable;
- sync_primitives::AutoLock auto_lock(state_lock_);
- stop_flag_ = false;
- while (!stop_flag_) {
- // Sleep
- int32_t wait_milliseconds_left = TimerDelegate::calculateMillisecondsLeft();
- ConditionalVariable::WaitStatus wait_status =
- termination_condition_.WaitFor(auto_lock, wait_milliseconds_left);
- // Quit sleeping or continue sleeping in case of spurious wake up
- if (ConditionalVariable::kTimeout == wait_status
- || wait_milliseconds_left <= 0) {
- LOG4CXX_TRACE(logger_,
- "Timer timeout " << wait_milliseconds_left << " ms");
- timer_thread_->onTimeOut();
- } else {
- LOG4CXX_DEBUG(logger_,
- "Timeout reset force: " << TimerDelegate::timeout_seconds_);
- }
- {
- sync_primitives::AutoLock auto_lock(restart_flag_lock_);
- if (!restart_flag_) {
- return;
- }
- restart_flag_ = false;
- }
- }
-}
-
-template<class T>
-void TimerThread<T>::TimerLooperDelegate::threadMain() {
- using sync_primitives::ConditionalVariable;
- sync_primitives::AutoLock auto_lock(TimerDelegate::state_lock_);
- TimerDelegate::stop_flag_ = false;
- while (!TimerDelegate::stop_flag_) {
- int32_t wait_milliseconds_left = TimerDelegate::calculateMillisecondsLeft();
- ConditionalVariable::WaitStatus wait_status =
- TimerDelegate::termination_condition_.WaitFor(auto_lock,
- wait_milliseconds_left);
- // Quit sleeping or continue sleeping in case of spurious wake up
- if (ConditionalVariable::kTimeout == wait_status
- || wait_milliseconds_left <= 0) {
- LOG4CXX_TRACE(logger_,
- "Timer timeout " << wait_milliseconds_left << " ms");
- TimerDelegate::timer_thread_->onTimeOut();
- } else {
- LOG4CXX_DEBUG(logger_,
- "Timeout reset force: " << TimerDelegate::timeout_seconds_);
- }
- }
-}
-
-template<class T>
-void TimerThread<T>::TimerDelegate::exitThreadMain() {
- shouldBeStoped();
- termination_condition_.NotifyOne();
-}
-
-template<class T>
-void TimerThread<T>::TimerDelegate::setTimeOut(const uint32_t timeout_seconds) {
- timeout_seconds_ = timeout_seconds;
- termination_condition_.NotifyOne();
-}
-
-template<class T>
-void TimerThread<T>::TimerDelegate::shouldBeStoped() {
- {
- sync_primitives::AutoLock auto_lock(state_lock_);
- stop_flag_ = true;
- }
- {
- sync_primitives::AutoLock auto_lock(restart_flag_lock_);
- restart_flag_ = false;
- }
-}
-
-template<class T>
-void TimerThread<T>::TimerDelegate::shouldBeRestarted() {
- sync_primitives::AutoLock auto_lock(restart_flag_lock_);
- restart_flag_ = true;
-}
-
-template<class T>
-int32_t TimerThread<T>::TimerThread::TimerDelegate::calculateMillisecondsLeft() {
- time_t cur_time = time(NULL);
- time_t end_time = std::numeric_limits<time_t>::max();
- if (TimerDelegate::timeout_seconds_ + cur_time
- > TimerDelegate::timeout_seconds_) { // no overflow occurred
- end_time = cur_time + TimerDelegate::timeout_seconds_;
- }
-
- int64_t wait_seconds_left = static_cast<int64_t>(difftime(end_time, cur_time));
- int32_t wait_milliseconds_left = std::numeric_limits<int32_t>::max();
- const int32_t milliseconds_in_second = 1000;
- if (wait_seconds_left
- < std::numeric_limits<int32_t>::max() / milliseconds_in_second) {
- wait_milliseconds_left = milliseconds_in_second * wait_seconds_left;
- }
- return wait_milliseconds_left;
-}
-
-} // namespace timer
-
-#endif // SRC_COMPONENTS_INCLUDE_UTILS_TIMER_THREAD_H_
diff --git a/src/components/interfaces/HMI_API.xml b/src/components/interfaces/HMI_API.xml
index 7bc099ac7f..f778649b86 100644
--- a/src/components/interfaces/HMI_API.xml
+++ b/src/components/interfaces/HMI_API.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" standalone="yes"?>
<!--
-* Copyright (c) 2013, Ford Motor Company
+* Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -34,7 +34,7 @@
<interfaces name="SmartDeviceLink HMI API">
-<interface name="Common" version="1.1" date="2013-10-02">
+<interface name="Common" version="1.4" date="2016-05-11">
<enum name="Result">
<element name="SUCCESS" value="0"/>
@@ -62,15 +62,15 @@
<element name="GENERIC_ERROR" value="22"/>
<element name="USER_DISALLOWED" value="23"/>
<element name="TRUNCATED_DATA" value="24"/>
+ <element name="SAVED" value="25"/>
</enum>
<enum name="TransportType">
- <description>
- Lists of the transport types used for device connection to HU.
- </description>
- <element name="BLUETOOTH"/>
- <element name="USB"/>
- <element name="WIFI"/>
+ <description>Lists of the transport types used for device connection to HU.</description>
+ <element name="BLUETOOTH"/>
+ <element name="USB_IOS"/>
+ <element name="USB_AOA"/>
+ <element name="WIFI"/>
</enum>
<enum name="ButtonName">
@@ -185,6 +185,21 @@
<element name="NO-NO" internal_name="NO_NO">
<description>Norwegian - Norway</description>
</element>
+ <element name="NL-BE" internal_name="NL_BE">
+ <description>Dutch (Flemish) - Belgium</description>
+ </element>
+ <element name="EL-GR" internal_name="EL_GR">
+ <description>Greek - Greece</description>
+ </element>
+ <element name="HU-HU" internal_name="HU_HU">
+ <description>Hungarian - Hungary</description>
+ </element>
+ <element name="FI-FI" internal_name="FI_FI">
+ <description>Finnish - Finland</description>
+ </element>
+ <element name="SK-SK" internal_name="SK_SK">
+ <description>Slovak - Slovakia</description>
+ </element>
</enum>
<enum name="SoftButtonType">
@@ -221,6 +236,21 @@
<element name="SYSTEM" />
</enum>
+ <enum name="WayPointType">
+ <description>Describes what kind of waypoint is requested/provided.</description>
+ <element name="ALL" />
+ <element name="DESTINATION" />
+ </enum>
+
+ <struct name="Coordinate">
+ <param name="latitudeDegrees" minvalue="-90" maxvalue="90" type="Double" mandatory="true">
+ <description>Latitude of the location.</description>
+ </param>
+ <param name="longitudeDegrees" minvalue="-180" maxvalue="180" type="Double" mandatory="true">
+ <description>Longitude of the location.</description>
+ </param>
+ </struct>
+
<enum name="LayoutMode">
<description>For touchscreen interactions, the mode of how the choices are presented.</description>
<element name="ICON_ONLY" />
@@ -235,28 +265,6 @@
<description>This mode causes the interaction to immediately display a keyboard entry through the HMI.</description>
</enum>
-<enum name="DeactivateReason">
- <description>Specifies the functionality the User has switched to.</description>
- <element name="AUDIO">
- <description>Navigated to audio(radio, etc)</description>
- </element>
- <element name="PHONECALL">
- <description>Navigated to make a call.</description>
- </element>
- <element name="NAVIGATIONMAP">
- <description>Navigated to navigation screen.</description>
- </element>
- <element name="PHONEMENU">
- <description>Navigated to phone menu.</description>
- </element>
- <element name="SYNCSETTINGS">
- <description>Navigated to settings menu.</description>
- </element>
- <element name="GENERAL">
- <description>Other screens navigation apart from other mobile app.</description>
- </element>
-</enum>
-
<enum name="ClockUpdateMode">
<description>Describes how the media clock timer should behave on the platform</description>
<element name="COUNTUP" />
@@ -382,10 +390,19 @@
<element name="DYNAMIC" />
</enum>
-<enum name="ApplicationToNONEReason">
- <description>Describes the reasons of moving the app to NONE.</description>
- <element name="DRIVER_DISTRACTION_VIOLATION" />
- <element name="USER_EXIT" />
+<enum name="ApplicationExitReason">
+ <element name="DRIVER_DISTRACTION_VIOLATION" >
+ <description>By getting this value, SDL puts the named app to NONE HMILevel</description>
+ </element>
+ <element name="USER_EXIT" >
+ <description>By getting this value, SDL puts the named app to NONE HMILevel</description>
+ </element>
+ <element name="UNAUTHORIZED_TRANSPORT_REGISTRATION">
+ <description>By getting this value, SDL unregisters the named application</description>
+ </element>
+ <element name="UNSUPPORTED_HMI_RESOURCE">
+ <description>By getting this value, SDL unregisters the named application</description>
+ </element>
</enum>
<enum name="TextFieldName">
@@ -1162,6 +1179,32 @@
<element name="NONE"/>
</enum>
+<enum name="EventTypes">
+ <description>Reflects the current active event</description>
+ <element name="AUDIO_SOURCE">
+ <description>Navigated to audio(radio, etc)</description>
+ </element>
+ <element name="EMBEDDED_NAVI">
+ <description>Navigated to navigation screen</description>
+ </element>
+ <element name="PHONE_CALL">
+ <description>Phone call is active</description>
+ </element>
+ <element name="EMERGENCY_EVENT">
+ <description>Active emergency event, active parking event</description>
+ </element>
+ <element name="DEACTIVATE_HMI">
+ <description> GAL/DIO is active </description>
+ </element>
+</enum>
+
+<enum name="DeliveryMode">
+ <description>The mode in which the SendLocation request is sent</description>
+ <element name="PROMPT" />
+ <element name="DESTINATION" />
+ <element name="QUEUE" />
+</enum>
+
<!-- Policies -->
<enum name="UpdateResult">
<element name="UP_TO_DATE"/>
@@ -1303,7 +1346,7 @@
<description>The name of the device connected.</description>
</param>
<param name="id" type="String" mandatory="true">
- <description>The ID of the device connected</description>
+ <description>The ID of the device connectedi: either hash of device's USB serial number(in case of USB connection) or has of device's MAC address(in case of BlueTooth or WIFI connection</description>
</param>
<param name="transportType" type="Common.TransportType" mandatory="false">
<description>The transport type the named-app's-device is connected over HU(BlueTooth, USB or WiFi). It must be provided in OnAppRegistered and in UpdateDeviceList</description>
@@ -1393,7 +1436,7 @@
</param>
<param name="greyOut" type="Boolean" mandatory="false">
<description>Indicates whether application should be dimmed on the screen.</description>
- <description>In case app is not in foreground SDL must notify HMI to grey out the corresponding apps-available-for-launching and currently not registered</description>
+ <description>Applicable only for apps received through QueryApps and still not registered.</description>
</param>
<param name="requestType" type="Common.RequestType" minsize="0" maxsize="100" array="true" mandatory="false">
<description>The list of SystemRequest's RequestTypes allowed by policies for the named application</description>
@@ -1438,7 +1481,7 @@
<param name="tertiaryText" maxlength="500" type="String" mandatory="false">
<description>Optional tertiary text to display; e.g. distance to POI for a search result entry</description>
</param>
- <param name="secondaryImage" type="Image" mandatory="false">
+ <param name="secondaryImage" type="Common.Image" mandatory="false">
<description>Optional secondary image struct for choice</description>
</param>
</struct>
@@ -1636,9 +1679,9 @@
<!--IVI part-->
<struct name="GPSData">
<description>Struct with the GPS data.</description>
- <param name="longitudeDegrees" type="Float" minvalue="-180" maxvalue="180" mandatory="false">
+ <param name="longitudeDegrees" type="Double" minvalue="-180" maxvalue="180" mandatory="false">
</param>
- <param name="latitudeDegrees" type="Float" minvalue="-90" maxvalue="90" mandatory="false">
+ <param name="latitudeDegrees" type="Double" minvalue="-90" maxvalue="90" mandatory="false">
</param>
<param name="utcYear" type="Integer" minvalue="2010" maxvalue="2100" mandatory="false">
<description>The current UTC year.</description>
@@ -1936,6 +1979,87 @@
</struct>
<!--end of IVI part-->
+<struct name="DateTime">
+ <param name="second" type="Integer" minvalue="0" maxvalue="60" mandatory="true">
+ <description>Seconds part of time</description>
+ </param>
+ <param name="minute" type="Integer" minvalue="0" maxvalue="59" mandatory="true">
+ <description>Minutes part of time</description>
+ </param>
+ <param name="hour" type="Integer" minvalue="0" maxvalue="23" mandatory="true">
+ <description>Hours part of time. Note that this structure accepts time only in 24 Hr format</description>
+ </param>
+ <param name="day" type="Integer" minvalue="1" maxvalue="31" mandatory="true">
+ <description>Day of the month</description>
+ </param>
+ <param name="month" type="Integer" minvalue="1" maxvalue="12" mandatory="true">
+ <description>Month of the year</description>
+ </param>
+ <param name="year" type="Integer" maxvalue="4095" mandatory="true">
+ <description>The year in YYYY format</description>
+ </param>
+ <param name="tz_hour" type="Integer" minvalue="-12" maxvalue="14" defvalue="0" mandatory="true">
+ <description>Time zone offset in Hours wrt UTC.</description>
+ </param>
+ <param name="tz_minute" type="Integer" minvalue="0" maxvalue="59" defvalue="0" mandatory="true">
+ <description>Time zone offset in Min wrt UTC.</description>
+ </param>
+ </struct>
+
+<struct name="OASISAddress">
+ <param name="countryName" minlength="0" maxlength="200" type="String" mandatory="false">
+ <description>Name of the country (localized)</description>
+ </param>
+ <param name="countryCode" minlength="0" maxlength="50" type="String" mandatory="false">
+ <description>Name of country (ISO 3166-2)</description>
+ </param>
+ <param name="postalCode" minlength="0" maxlength="16" type="String" mandatory="false">
+ <description>(PLZ, ZIP, PIN, CAP etc.)</description>
+ </param>
+ <param name="administrativeArea" minlength="0" maxlength="200" type="String" mandatory="false">
+ <description>Portion of country (e.g. state)</description>
+ </param>
+ <param name="subAdministrativeArea" minlength="0" maxlength="200" type="String" mandatory="false">
+ <description>Portion of e.g. state (e.g. county)</description>
+ </param>
+ <param name="locality" minlength="0" maxlength="200" type="String" mandatory="false">
+ <description>Hypernym for e.g. city/village</description>
+ </param>
+ <param name="subLocality" minlength="0" maxlength="200" type="String" mandatory="false">
+ <description>Hypernym for e.g. district</description>
+ </param>
+ <param name="thoroughfare" minlength="0" maxlength="200" type="String" mandatory="false">
+ <description>Hypernym for street, road etc.</description>
+ </param>
+ <param name="subThoroughfare" minlength="0" maxlength="200" type="String" mandatory="false">
+ <description>Portion of thoroughfare e.g. house number</description>
+ </param>
+</struct>
+
+ <struct name="LocationDetails">
+ <param name="coordinate" type="Coordinate" mandatory="false">
+ <description>Latitude/Longitude of the location.</description>
+ </param>
+ <param name="locationName" type="String" maxlength="500" mandatory="false">
+ <description>Name of location.</description>
+ </param>
+ <param name="addressLines" type="String" maxlength="500" minsize="0" maxsize="4" array="true" mandatory="false">
+ <description>Location address for display purposes only</description>
+ </param>
+ <param name="locationDescription" type="String" maxlength="500" mandatory="false">
+ <description>Description intended location / establishment (if applicable)</description>
+ </param>
+ <param name="phoneNumber" type="String" maxlength="500" mandatory="false">
+ <description>Phone number of location / establishment.</description>
+ </param>
+ <param name="locationImage" type="Image" mandatory="false">
+ <description>Image / icon of intended location.</description>
+ </param>
+ <param name="searchAddress" type="OASISAddress" mandatory="false">
+ <description>Address to be used by navigation engines for search</description>
+ </param>
+ </struct>
+
</interface>
<interface name="Buttons" version="1.1" date="2016-08-18">
@@ -2108,9 +2232,6 @@
<param name="appID" type="Integer" mandatory="true">
<description>ID of deactivated application.</description>
</param>
- <param name="reason" type="Common.DeactivateReason" mandatory="true">
- <description>Specifies the functionality the user has switched to.</description>
- </param>
</function>
<function name="OnAppRegistered" messagetype="notification">
<description>Issued by SDL to notify HMI about new application registered.</description>
@@ -2156,7 +2277,7 @@
</function>
<function name="OnExitApplication" messagetype="notification">
<description>Must be sent by HMI when the User chooses to exit the application..</description>
- <param name="reason" type="Common.ApplicationToNONEReason" mandatory="true">
+ <param name="reason" type="Common.ApplicationExitReason" mandatory="true">
<description>Specifies reason of moving the app to NONE</description>
</param>
<param name="appID" type="Integer" mandatory="true">
@@ -2183,27 +2304,15 @@
<description>Must be true if supported</description>
</param>
</function>
- <function name="PlayTone" messagetype="notification">
- <description>Sent by SDL to HMI to notify that the tone should be played.</description>
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of the application that invoked this notification</description>
- </param>
- <param name="methodName" type="Common.MethodName" mandatory="true">
- <description>Defines the name of app's request that initiates playing a tone</description>
- </param>
- </function>
<function name="DialNumber" messagetype="request">
<description>Request from SDL to call a specific number.</description>
<param name="number" type="String" maxlength="40">
- <description>Phone number is a string, which can be up to 40 chars.
- All characters shall be stripped from string except digits 0-9 and * # , ; +
- </description>
+ <description>The number to dial. Only the character + and numbers are allowed.</description>
</param>
<param name="appID" type="Integer" mandatory="true">
<description>ID of application that concerns this RPC.</description>
</param>
</function>
-
<function name="DialNumber" messagetype="response">
</function>
<!-- Policies -->
@@ -2346,6 +2455,25 @@
<description>Notification from system to SDL to let it know that ignition cycle is over.</description>
</function>
<!-- End of Policies -->
+ <function name="OnDeactivateHMI" messagetype="notification">
+ <description>
+ Sender: HMI->SDL. When: in case GAL/DIO is active or disabling
+ </description>
+ <param name="isDeactivated" type="Boolean" mandatory="true">
+ <description>
+ Must be 'true' - GAL/DIO is active. Must be 'false' when GAL/DIO is disabling
+ </description>
+ </param>
+ </function>
+ <function name="OnEventChanged" messagetype="notification">
+ <description>Sender: HMI->SDL. When event is become active</description>
+ <param name="eventName" type="Common.EventTypes" mandatory="true">
+ <description>Specifies the types of active events.</description>
+ </param>
+ <param name="isActive" type="Boolean" mandatory="true">
+ <description>Must be 'true' - when the event is started on HMI. Must be 'false' when the event is ended on HMI</description>
+ </param>
+ </function>
</interface>
<interface name="VR" version="1.0" date="2013-04-17">
@@ -2429,6 +2557,9 @@
IDs of the specific compiled grammars for this voice interaction.
</description>
</param>
+ <param name="appID" type="Integer" mandatory="true">
+ <description>ID of application related to this RPC.</description>
+ </param>
</function>
<function name="PerformInteraction" messagetype="response">
<param name="choiceID" type="Integer" minvalue="0" maxvalue="2000000000" mandatory="false">
@@ -2532,6 +2663,9 @@
<param name="speakType" type="Common.MethodName" mandatory="false">
<description>Defines the type of the request which causes text-to-speech</description>
</param>
+ <param name="playTone" type="Boolean" mandatory="false">
+ <description>Defines that the tone should be played</description>
+ </param>
</function>
<function name="Speak" messagetype="response">
<description>Provides information about success of operation.</description>
@@ -2776,14 +2910,14 @@
<function name="SetMediaClockTimer" messagetype="request">
<description>Sets the initial media clock value and automatic update method.</description>
<param name="startTime" type="Common.TimeFormat" mandatory="false">
- <description>startTime should be ignored for "PAUSE", "RESUME", and "CLEAR"</description>
+ <description>SDL transfers startTime together with modes: "COUNTUP", "COUNTDOWN", "PAUSE" to HMI.
+ SDL ignores startTime for modes: "RESUME", and "CLEAR"</description>
</param>
<param name="endTime" type="Common.TimeFormat" mandatory="false">
<description>
See TimeFormat.
- endTime can be provided for "COUNTUP" and "COUNTDOWN"; to be used to calculate any visual progress bar (if not provided, this feature is ignored)
- If endTime is greater then startTime for COUNTDOWN or less than startTime for COUNTUP, then the request will return an INVALID_DATA.
- endTime will be ignored for "PAUSE", "RESUME", and "CLEAR"
+ SDL transfers endTime together with modes: "COUNTUP", "COUNTDOWN", "PAUSE" to HMI. To be used to calculate any visual progress bar (if not provided, this feature is ignored).
+ SDL ignores endTime for modes: "RESUME", and "CLEAR"
</description>
</param>
<param name="updateMode" type="Common.ClockUpdateMode" mandatory="true">
@@ -2850,7 +2984,7 @@
</param>
<param name="audioPassThruCapabilities" type="Common.AudioPassThruCapabilities" mandatory="true"/>
<param name="hmiZoneCapabilities" type="Common.HmiZoneCapabilities" mandatory="true"/>
- <param name="softButtonCapabilities" type="Common.SoftButtonCapabilities" mandatory="false">
+ <param name="softButtonCapabilities" type="Common.SoftButtonCapabilities" minsize="1" maxsize="100" array="true" mandatory="false">
<description>Must be returned if the platform supports on-screen SoftButtons.</description>
</param>
<param name="hmiCapabilities" type="Common.HMICapabilities" mandatory="false">
@@ -3110,7 +3244,8 @@
</function>
</interface>
-<interface name="Navigation" version="1.0" date="2013-05-22">
+<interface name="Navigation" version="1.2" date="2016-06-09">
+
<function name="IsReady" messagetype="request">
<description>Method is invoked at system startup. Response must provide the information about presence of UI Navigation module and its readiness to cooperate with SDL.</description>
</function>
@@ -3124,9 +3259,9 @@
<param name="appID" type="Integer" mandatory="true">
<description>ID of application related to this RPC.</description>
</param>
- <param name="longitudeDegrees" type="Float" minvalue="-180" maxvalue="180" mandatory="true">
+ <param name="longitudeDegrees" type="Float" minvalue="-180" maxvalue="180" mandatory="false">
</param>
- <param name="latitudeDegrees" type="Float" minvalue="-90" maxvalue="90" mandatory="true">
+ <param name="latitudeDegrees" type="Float" minvalue="-90" maxvalue="90" mandatory="false">
</param>
<param name="locationName" type="String" maxlength="500" mandatory="false">
<description> Name / title of intended location </description>
@@ -3143,6 +3278,17 @@
<param name="locationImage" type="Common.Image" mandatory="false">
<description> Image / icon of intended location (if applicable and supported) </description>
</param>
+ <param name="timeStamp" type="Common.DateTime" mandatory="false">
+ <description>
+ timestamp in ISO 8601 format
+ </description>
+ </param>
+ <param name="address" type="Common.OASISAddress" mandatory="false">
+ <description>Address to be used for setting destination</description>
+ </param>
+ <param name="deliveryMode" type="Common.DeliveryMode" mandatory="false">
+ <description>Defines the mode of prompt for user</description>
+ </param>
</function>
<function name="SendLocation" messagetype="response" >
</function>
@@ -3214,7 +3360,7 @@
</param>
</function>
<function name="StartStream" messagetype="request">
- <description>Notification from SmartDeviceLinkCore to HMI to start playing video streaming.</description>
+ <description>Request from SmartDeviceLinkCore to HMI to start playing video streaming.</description>
<param name="url" type="String" minlength="21" maxlength="500" mandatory="true">
<description>URL that HMI start playing.</description>
</param>
@@ -3225,7 +3371,7 @@
<function name="StartStream" messagetype="response">
</function>
<function name="StopStream" messagetype="request">
- <description>Notification from SmartDeviceLinkCore to HMI to start playing video streaming.</description>
+ <description>Request from SmartDeviceLinkCore to HMI to stop playing video streaming.</description>
<param name="appID" type="Integer" mandatory="true">
<description>ID of application related to this RPC.</description>
</param>
@@ -3233,7 +3379,7 @@
<function name="StopStream" messagetype="response">
</function>
<function name="StartAudioStream" messagetype="request">
- <description>Notification from SmartDeviceLinkCore to HMI to start playing audio streaming.</description>
+ <description>Request from SmartDeviceLinkCore to HMI to start playing audio streaming.</description>
<param name="url" type="String" minlength="21" maxlength="500" mandatory="true">
<description>URL that HMI start playing.</description>
</param>
@@ -3244,7 +3390,7 @@
<function name="StartAudioStream" messagetype="response">
</function>
<function name="StopAudioStream" messagetype="request">
- <description>Notification from SmartDeviceLinkCore to HMI to start playing audio streaming.</description>
+ <description>Request from SmartDeviceLinkCore to HMI to stop playing audio streaming.</description>
<param name="appID" type="Integer" mandatory="true">
<description>ID of application related to this RPC.</description>
</param>
@@ -3263,6 +3409,43 @@
<description>If "true" - video data started. If "false" - video data stopped.</description>
</param>
</function>
+ <function name="GetWayPoints" functionID="GetWayPointsID" messagetype="request">
+ <description>Request for getting waypoint/destination data.</description>
+ <param name="wayPointType" type="Common.WayPointType" defvalue="ALL" mandatory="false">
+ <description>To request for either the destination only or for all waypoints including destination</description>
+ </param>
+ <param name="appID" type="Integer" mandatory="true">
+ <description>ID of the application.</description>
+ </param>
+ </function>
+ <function name="GetWayPoints" functionID="GetWayPointsID" messagetype="response">
+ <param name="appID" type="Integer" mandatory="true">
+ <description>ID of the application.</description>
+ </param>
+ <param name="wayPoints" type="Common.LocationDetails" mandatory="false" array="true" minsize="1" maxsize="10">
+ <description>See LocationDetails</description>
+ </param>
+ </function>
+ <function name="OnWayPointChange" functionID="OnWayPointChangeID" messagetype="notification">
+ <description>Notification which provides the entire LocationDetails when there is a change to any waypoints or destination.</description>
+ <param name="wayPoints" type="Common.LocationDetails" mandatory="true" array="true" minsize="1" maxsize="10">
+ <description>See LocationDetails</description>
+ </param>
+ </function>
+
+ <function name="SubscribeWayPoints" functionID="SubscribeWayPointsID" messagetype="request">
+ <description>To subscribe in getting changes for Waypoints/destinations</description>
+ </function>
+
+ <function name="SubscribeWayPoints" functionID="SubscribeWayPointsID" messagetype="response">
+ </function>
+
+ <function name="UnsubscribeWayPoints" functionID="UnsubscribeWayPointsID" messagetype="request">
+ <description>Request to unsubscribe from WayPoints and Destination</description>
+ </function>
+
+ <function name="UnsubscribeWayPoints" functionID="UnsubscribeWayPointsID" messagetype="response">
+ </function>
</interface>
@@ -3353,9 +3536,6 @@
The application will be notified by the onVehicleData notification whenever new data is available.
To unsubscribe the notifications, use unsubscribe with the same subscriptionType.
</description>
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application that requested this RPC.</description>
- </param>
<param name="gps" type="Boolean" mandatory="false">
<description>See GPSData</description>
</param>
@@ -3742,9 +3922,6 @@
<param name="myKey" type="Boolean" mandatory="false">
<description>Information related to the MyKey feature</description>
</param>
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="GetVehicleData" messagetype="response">
<param name="gps" type="Common.GPSData" mandatory="false">
diff --git a/src/components/interfaces/MOBILE_API.xml b/src/components/interfaces/MOBILE_API.xml
index 5430aedbf1..1bff09ef38 100644
--- a/src/components/interfaces/MOBILE_API.xml
+++ b/src/components/interfaces/MOBILE_API.xml
@@ -1,7 +1,7 @@
<?xml version="1.0" standalone="no"?>
<?xml-stylesheet type="text/xml" href="protocol2html.xsl"?>
-<interface name="Ford Sync RAPI" version="4.0" date="2015-03-30">
+<interface name="Ford Sync RAPI" version="4.1" date="2016-04-08">
<enum name="Result" internal_scope="base">
<element name="SUCCESS">
@@ -231,6 +231,21 @@
<element name="NO-NO" internal_name="NO_NO">
<description>Norwegian - Norway</description>
</element>
+ <element name="NL-BE" internal_name="NL_BE">
+ <description>Dutch (Flemish) - Belgium</description>
+ </element>
+ <element name="EL-GR" internal_name="EL_GR">
+ <description>Greek - Greece</description>
+ </element>
+ <element name="HU-HU" internal_name="HU_HU">
+ <description>Hungarian - Hungary</description>
+ </element>
+ <element name="FI-FI" internal_name="FI_FI">
+ <description>Finnish - Finland</description>
+ </element>
+ <element name="SK-SK" internal_name="SK_SK">
+ <description>Slovak - Slovakia</description>
+ </element>
</enum>
<enum name="UpdateMode">
@@ -370,6 +385,7 @@
<element name="FACTORY_DEFAULTS" />
<element name="APP_UNAUTHORIZED" />
<element name="PROTOCOL_VIOLATION" />
+ <element name="UNSUPPORTED_HMI_RESOURCE" />
</enum>
<enum name="TriggerSource">
@@ -781,6 +797,13 @@
<element name="DYNAMIC" />
</enum>
+ <enum name="DeliveryMode">
+ <description>The mode in which the SendLocation request is sent</description>
+ <element name="PROMPT" />
+ <element name="DESTINATION" />
+ <element name="QUEUE" />
+ </enum>
+
<struct name="Image">
<param name="value" minlength="0" maxlength="65535" type="String">
<description>Either the static hex icon value or the binary image file name identifier (sent by PutFile).</description>
@@ -2178,7 +2201,10 @@
<element name="DiagnosticMessageID" value="37" hexvalue="25" />
<element name="SystemRequestID" value="38" hexvalue="26" />
<element name="SendLocationID" value="39" hexvalue="27" />
- <element name="DialNumberID" value="40" hexvalue="28" />
+ <element name="DialNumberID" value="40" hexvalue="28" />
+ <element name="GetWayPointsID" value="41" hexvalue="29" />
+ <element name="SubscribeWayPointsID" value="42" hexvalue="2A"/>
+ <element name="UnsubscribeWayPointsID" value="43" hexvalue="2B"/>
<!--
Base Notifications
@@ -2200,6 +2226,7 @@
<element name="OnTouchEventID" value="32780" hexvalue="800C" />
<element name="OnSystemRequestID" value="32781" hexvalue="800D" />
<element name="OnHashChangeID" value="32782" hexvalue="800E" />
+ <element name="OnWayPointChangeID" value="32783" hexvalue="800F" />
<!--
Ford Specific Request / Response RPCs
@@ -2229,6 +2256,101 @@
<element name="notification" value="2" />
</enum>
+ <struct name="DateTime">
+ <param name="second" type="Integer" minvalue="0" maxvalue="60" mandatory="true">
+ <description>Seconds part of time</description>
+ </param>
+ <param name="minute" type="Integer" minvalue="0" maxvalue="59" mandatory="true">
+ <description>Minutes part of time</description>
+ </param>
+ <param name="hour" type="Integer" minvalue="0" maxvalue="23" mandatory="true">
+ <description>Hours part of time. Note that this structure accepts time only in 24 Hr format</description>
+ </param>
+ <param name="day" type="Integer" minvalue="1" maxvalue="31" mandatory="true">
+ <description>Day of the month</description>
+ </param>
+ <param name="month" type="Integer" minvalue="1" maxvalue="12" mandatory="true">
+ <description>Month of the year</description>
+ </param>
+ <param name="year" type="Integer" maxvalue="4095" mandatory="true">
+ <description>The year in YYYY format</description>
+ </param>
+ <param name="tz_hour" type="Integer" minvalue="-12" maxvalue="14" defvalue="0" mandatory="true">
+ <description>Time zone offset in Hours wrt UTC.</description>
+ </param>
+ <param name="tz_minute" type="Integer" minvalue="0" maxvalue="59" defvalue="0" mandatory="true">
+ <description>Time zone offset in Min wrt UTC.</description>
+ </param>
+ </struct>
+
+ <enum name="WayPointType">
+ <description>Describes what kind of waypoint is requested/provided.</description>
+ <element name="ALL" />
+ <element name="DESTINATION" />
+ </enum>
+
+ <struct name="Coordinate">
+ <param name="latitudeDegrees" minvalue="-90" maxvalue="90" type="Double" mandatory="true">
+ <description>Latitude of the location.</description>
+ </param>
+ <param name="longitudeDegrees" minvalue="-180" maxvalue="180" type="Double" mandatory="true">
+ <description>Longitude of the location.</description>
+ </param>
+ </struct>
+
+<struct name="OASISAddress">
+ <param name="countryName" minlength="0" maxlength="200" type="String" mandatory="false">
+ <description>Name of the country (localized)</description>
+ </param>
+ <param name="countryCode" minlength="0" maxlength="50" type="String" mandatory="false">
+ <description>Name of country (ISO 3166-2)</description>
+ </param>
+ <param name="postalCode" minlength="0" maxlength="16" type="String" mandatory="false">
+ <description>(PLZ, ZIP, PIN, CAP etc.)</description>
+ </param>
+ <param name="administrativeArea" minlength="0" maxlength="200" type="String" mandatory="false">
+ <description>Portion of country (e.g. state)</description>
+ </param>
+ <param name="subAdministrativeArea" minlength="0" maxlength="200" type="String" mandatory="false">
+ <description>Portion of e.g. state (e.g. county)</description>
+ </param>
+ <param name="locality" minlength="0" maxlength="200" type="String" mandatory="false">
+ <description>Hypernym for e.g. city/village</description>
+ </param>
+ <param name="subLocality" minlength="0" maxlength="200" type="String" mandatory="false">
+ <description>Hypernym for e.g. district</description>
+ </param>
+ <param name="thoroughfare" minlength="0" maxlength="200" type="String" mandatory="false">
+ <description>Hypernym for street, road etc.</description>
+ </param>
+ <param name="subThoroughfare" minlength="0" maxlength="200" type="String" mandatory="false">
+ <description>Portion of thoroughfare e.g. house number</description>
+ </param>
+</struct>
+
+ <struct name="LocationDetails">
+ <param name="coordinate" type="Coordinate" mandatory="false">
+ <description>Latitude/Longitude of the location.</description>
+ </param>
+ <param name="locationName" type="String" maxlength="500" mandatory="false">
+ <description>Name of location.</description>
+ </param>
+ <param name="addressLines" type="String" maxlength="500" minsize="0" maxsize="4" array="true" mandatory="false">
+ <description>Location address for display purposes only</description>
+ </param>
+ <param name="locationDescription" type="String" maxlength="500" mandatory="false">
+ <description>Description intended location / establishment (if applicable)</description>
+ </param>
+ <param name="phoneNumber" type="String" maxlength="500" mandatory="false">
+ <description>Phone number of location / establishment.</description>
+ </param>
+ <param name="locationImage" type="Image" mandatory="false">
+ <description>Image / icon of intended location.</description>
+ </param>
+ <param name="searchAddress" type="OASISAddress" mandatory="false">
+ <description>Address to be used by navigation engines for search</description>
+ </param>
+ </struct>
<!-- Requests/Responses -->
<function name="RegisterAppInterface" functionID="RegisterAppInterfaceID" messagetype="request">
@@ -2403,6 +2525,10 @@
<description>See AudioPassThruCapability</description>
</param>
+ <param name="pcmStreamCapabilities" type="AudioPassThruCapabilities" array="false" mandatory="false">
+ <description>See AudioPassThruCapability</description>
+ </param>
+
<param name="vehicleType" type="VehicleType" mandatory="false">
<description>Specifies the vehicle's type. See VehicleType.</description>
</param>
@@ -4663,9 +4789,9 @@
</function>
<function name="SendLocation" functionID="SendLocationID" messagetype="request">
- <param name="longitudeDegrees" type="Float" minvalue="-180" maxvalue="180" mandatory="true">
+ <param name="longitudeDegrees" type="Double" minvalue="-180" maxvalue="180" mandatory="false">
</param>
- <param name="latitudeDegrees" type="Float" minvalue="-90" maxvalue="90" mandatory="true">
+ <param name="latitudeDegrees" type="Double" minvalue="-90" maxvalue="90" mandatory="false">
</param>
<param name="locationName" type="String" maxlength="500" mandatory="false">
<description>
@@ -4691,6 +4817,19 @@
<description>
Image / icon of intended location (if applicable and supported)
</description>
+ </param>
+
+ <param name="timeStamp" type="DateTime" mandatory="false">
+ <description>
+ timestamp in ISO 8601 format
+ </description>
+ </param>
+
+ <param name="address" type="OASISAddress" mandatory="false">
+ <description>Address to be used for setting destination</description>
+ </param>
+ <param name="deliveryMode" type="DeliveryMode" mandatory="false">
+ <description>Defines the mode of prompt for user</description>
</param>
</function>
@@ -4960,7 +5099,7 @@
<param name="url" type="String" maxlength="1000" minsize="1" maxsize="100" array="true" mandatory="false">
<description>
Optional URL for HTTP requests.
- If blank, the binary data shall be forwarded to the app.
+ If blank, the binary data shall be forwarded to the app.
If not blank, the binary data shall be forwarded to the url with a provided timeout in seconds.
</description>
</param>
@@ -4973,13 +5112,13 @@
<param name="fileType" type="FileType" mandatory="false">
<description>Optional file type (meant for HTTP file requests).</description>
</param>
- <param name="offset" type="Integer" minvalue="0" maxvalue="2000000000" mandatory="false">
+ <param name="offset" type="Integer" minvalue="0" maxvalue="100000000000" mandatory="false">
<description>Optional offset in bytes for resuming partial data chunks</description>
</param>
- <param name="length" type="Integer" minvalue="0" maxvalue="2000000000" mandatory="false">
+ <param name="length" type="Integer" minvalue="0" maxvalue="100000000000" mandatory="false">
<description>Optional length in bytes for resuming partial data chunks</description>
- </param>
- </function>
+ </param>
+ </function>
<function name="OnHashChange" functionID="OnHashChangeID" messagetype="notification">
<description>
@@ -5082,6 +5221,91 @@
</param>
</function>
+ <function name="SubscribeWayPoints" functionID="SubscribeWayPointsID" messagetype="request">
+ <description>To subscribe in getting changes for Waypoints/destinations</description>
+ </function>
+
+ <function name="SubscribeWayPoints" functionID="SubscribeWayPointsID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ <element name="IGNORED"/>
+ <element name="DISALLOWED"/>
+ </param>
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="GetWayPoints" functionID="GetWayPointsID" messagetype="request">
+ <description>Request for getting waypoint/destination data.</description>
+ <param name="wayPointType" type="WayPointType" defvalue="ALL" mandatory="false">
+ <description>To request for either the destination only or for all waypoints including destination</description>
+ </param>
+ </function>
+
+ <function name="GetWayPoints" functionID="GetWayPointsID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="TIMED_OUT"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ <element name="IGNORED"/>
+ <element name="IN_USE"/>
+ <element name="DISALLOWED"/>
+ </param>
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="UnsubscribeWayPoints" functionID="UnsubscribeWayPointsID" messagetype="request">
+ <description>Request to unsubscribe from WayPoints and Destination</description>
+ </function>
+
+ <function name="UnsubscribeWayPoints" functionID="UnsubscribeWayPointsID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ <element name="IGNORED"/>
+ <element name="DISALLOWED"/>
+ </param>
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ <param name="wayPoints" type="LocationDetails" mandatory="false" array="true" minsize="1" maxsize="10">
+ <description>See LocationDetails</description>
+ </param>
+ </function>
+
+ <function name="OnWayPointChange" functionID="OnWayPointChangeID" messagetype="notification">
+ <description>Notification which provides the entire LocationDetails when there is a change to any waypoints or destination.</description>
+ <param name="wayPoints" type="LocationDetails" mandatory="true" array="true" minsize="1" maxsize="10">
+ <description>See LocationDetails</description>
+ </param>
+ </function>
+
+
<!-- Deprecating - covered by OnSystemRequest
<function name="OnSyncPData" functionID="OnSyncPDataID" messagetype="notification" >
<description>
diff --git a/src/components/interfaces/QT_HMI_API.xml b/src/components/interfaces/QT_HMI_API.xml
index eab9edb864..85a4d4143f 100644
--- a/src/components/interfaces/QT_HMI_API.xml
+++ b/src/components/interfaces/QT_HMI_API.xml
@@ -63,7 +63,8 @@
Lists of the transport types used for device connection to HU.
</description>
<element name="BLUETOOTH"/>
- <element name="USB"/>
+ <element name="USB_IOS"/>
+ <element name="USB_AOA"/>
<element name="WIFI"/>
</enum>
<enum name="ButtonName">
@@ -175,6 +176,21 @@
<element name="NO-NO" internal_name="NO_NO">
<description>Norwegian - Norway</description>
</element>
+ <element name="NL-BE" internal_name="NL_BE">
+ <description>Dutch (Flemish) - Belgium</description>
+ </element>
+ <element name="EL-GR" internal_name="EL_GR">
+ <description>Greek - Greece</description>
+ </element>
+ <element name="HU-HU" internal_name="HU_HU">
+ <description>Hungarian - Hungary</description>
+ </element>
+ <element name="FI-FI" internal_name="FI_FI">
+ <description>Finnish - Finland</description>
+ </element>
+ <element name="SK-SK" internal_name="SK_SK">
+ <description>Slovak - Slovakia</description>
+ </element>
</enum>
<enum name="SoftButtonType">
<description>Contains information about the SoftButton capabilities.</description>
@@ -356,10 +372,16 @@
<element name="STATIC"/>
<element name="DYNAMIC"/>
</enum>
- <enum name="ApplicationToNONEReason">
- <description>Describes the reasons of moving the app to NONE.</description>
- <element name="DRIVER_DISTRACTION_VIOLATION" />
- <element name="USER_EXIT" />
+ <enum name="ApplicationExitReason">
+ <element name="DRIVER_DISTRACTION_VIOLATION" >
+ <description>By getting this value, SDL puts the named app to NONE HMILevel</description>
+ </element>
+ <element name="USER_EXIT" >
+ <description>By getting this value, SDL puts the named app to NONE HMILevel</description>
+ </element>
+ <element name="UNAUTHORIZED_TRANSPORT_REGISTRATION">
+ <description>By getting this value, SDL unregisters the named application</description>
+ </element>
</enum>
<enum name="TextFieldName">
<element name="mainField1">
@@ -1190,6 +1212,20 @@
<description>Published data result code.</description>
</param>
</struct>
+ <struct name="DeviceInfo">
+ <param name="name" type="String" mandatory="true">
+ <description>The name of the device connected.</description>
+ </param>
+ <param name="id" type="String" mandatory="true">
+ <description>The ID of the device connected: either hash of device's USB serial number(in case of USB connection) or hash of device's MAC address(in case of BlueTooth or WIFI connection).</description>
+ </param>
+ <param name="transportType" type="Common.TransportType" mandatory="false">
+ <description>The transport type the named-app's-device is connected over HU(BlueTooth, USB or WiFi). It must be provided in OnAppRegistered and in UpdateDeviceList</description>
+ </param>
+ <param name="isSDLAllowed" type="Boolean" mandatory="false">
+ <description>Sent by SDL in UpdateDeviceList. ’true’ – if device is allowed for PolicyTable Exchange; ‘false’ – if device is NOT allowed for PolicyTable Exchange </description>
+ </param>
+ </struct>
<struct name="TouchCoord">
<param name="x" type="Integer" mandatory="true" minvalue="0" maxvalue="10000">
<description>The x coordinate of the touch.</description>
@@ -2036,7 +2072,7 @@
</function>
<function name="OnExitApplication" messagetype="notification" provider="hmi">
<description>Must be sent by HMI when the User chooses to exit the application..</description>
- <param name="reason" type="Common.ApplicationToNONEReason" mandatory="true">
+ <param name="reason" type="Common.ApplicationExitReason" mandatory="true">
<description>Specifies reason of moving the app to NONE</description>
</param>
<param name="appID" type="Integer" mandatory="true">
@@ -2704,7 +2740,7 @@
</param>
<param name="audioPassThruCapabilities" type="Common.AudioPassThruCapabilities" mandatory="true"/>
<param name="hmiZoneCapabilities" type="Common.HmiZoneCapabilities" mandatory="true"/>
- <param name="softButtonCapabilities" type="Common.SoftButtonCapabilities" mandatory="false">
+ <param name="softButtonCapabilities" type="Common.SoftButtonCapabilities" minsize="1" maxsize="100" array="true" mandatory="false">
<description>Must be returned if the platform supports on-screen SoftButtons.</description>
</param>
<param name="hmiCapabilities" type="Common.HMICapabilities" mandatory="false">
@@ -2999,6 +3035,34 @@
</function>
<function name="SendLocation" messagetype="response" >
</function>
+
+ <function name="DialNumber" functionID="DialNumberID" messagetype="request">
+ <description>Dials a phone number and switches to phone application.</description>
+ <param name="number" type="String" maxlength="40">
+ <description>Phone number is a string, which can be up to 40 chars.</description>
+ </param>
+ </function>
+
+ <function name="DialNumber" functionID="DialNumberID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description>true, if successful</description>
+ <description>false, if failed</description>
+ </param>
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ </param>
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
<function name="ShowConstantTBT" messagetype="request" provider="hmi">
<description>Request from SmartDeviceLinkCore to HMI to show info about navigation.</description>
<param name="navigationTexts" type="Common.TextFieldStruct" mandatory="true" array="true" minsize="0" maxsize="5">
@@ -3067,7 +3131,7 @@
</param>
</function>
<function name="StartStream" messagetype="request" provider="hmi">
- <description>Notification from SmartDeviceLinkCore to HMI to start playing video streaming.</description>
+ <description>Request from SmartDeviceLinkCore to HMI to start playing video streaming.</description>
<param name="url" type="String" minlength="21" maxlength="500" mandatory="true">
<description>URL that HMI start playing.</description>
</param>
@@ -3078,7 +3142,7 @@
<function name="StartStream" messagetype="response">
</function>
<function name="StopStream" messagetype="request" provider="hmi">
- <description>Notification from SmartDeviceLinkCore to HMI to start playing video streaming.</description>
+ <description>Request from SmartDeviceLinkCore to HMI to stop playing video streaming.</description>
<param name="appID" type="Integer" mandatory="true">
<description>ID of application related to this RPC.</description>
</param>
@@ -3086,7 +3150,7 @@
<function name="StopStream" messagetype="response">
</function>
<function name="StartAudioStream" messagetype="request" provider="hmi">
- <description>Notification from SmartDeviceLinkCore to HMI to start playing audio streaming.</description>
+ <description>Request from SmartDeviceLinkCore to HMI to start playing audio streaming.</description>
<param name="url" type="String" minlength="21" maxlength="500" mandatory="true">
<description>URL that HMI start playing.</description>
</param>
@@ -3097,7 +3161,7 @@
<function name="StartAudioStream" messagetype="response">
</function>
<function name="StopAudioStream" messagetype="request" provider="hmi">
- <description>Notification from SmartDeviceLinkCore to HMI to start playing audio streaming.</description>
+ <description>Request from SmartDeviceLinkCore to HMI to stop playing audio streaming.</description>
<param name="appID" type="Integer" mandatory="true">
<description>ID of application related to this RPC.</description>
</param>
@@ -3580,9 +3644,6 @@
<!--end Qt HMI version of OnVehicleData-->
<!--Qt HMI version of SubscribeVehicleData/UnsubscribeVehicleData-->
<function name="SubscribeGps" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeGps" messagetype="response">
<param name="gps" type="Common.VehicleDataResult" mandatory="true">
@@ -3590,9 +3651,6 @@
</param>
</function>
<function name="UnsubscribeGps" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeGps" messagetype="response">
<param name="gps" type="Common.VehicleDataResult" mandatory="true">
@@ -3600,9 +3658,6 @@
</param>
</function>
<function name="SubscribeSpeed" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeSpeed" messagetype="response">
<param name="speed" type="Common.VehicleDataResult" mandatory="true">
@@ -3610,9 +3665,6 @@
</param>
</function>
<function name="UnsubscribeSpeed" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeSpeed" messagetype="response">
<param name="speed" type="Common.VehicleDataResult" mandatory="true">
@@ -3620,9 +3672,6 @@
</param>
</function>
<function name="SubscribeRpm" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeRpm" messagetype="response">
<param name="rpm" type="Common.VehicleDataResult" mandatory="true">
@@ -3630,9 +3679,6 @@
</param>
</function>
<function name="UnsubscribeRpm" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeRpm" messagetype="response">
<param name="rpm" type="Common.VehicleDataResult" mandatory="true">
@@ -3640,9 +3686,6 @@
</param>
</function>
<function name="SubscribeFuelLevel" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeFuelLevel" messagetype="response">
<param name="fuelLevel" type="Common.VehicleDataResult" mandatory="true">
@@ -3650,9 +3693,6 @@
</param>
</function>
<function name="UnsubscribeFuelLevel" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeFuelLevel" messagetype="response">
<param name="fuelLevel" type="Common.VehicleDataResult" mandatory="true">
@@ -3660,9 +3700,6 @@
</param>
</function>
<function name="SubscribeFuelLevel_State" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeFuelLevel_State" messagetype="response">
<param name="fuelLevel_State" type="Common.VehicleDataResult" mandatory="true">
@@ -3670,9 +3707,6 @@
</param>
</function>
<function name="UnsubscribeFuelLevel_State" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeFuelLevel_State" messagetype="response">
<param name="fuelLevel_State" type="Common.VehicleDataResult" mandatory="true">
@@ -3680,9 +3714,6 @@
</param>
</function>
<function name="SubscribeInstantFuelConsumption" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeInstantFuelConsumption" messagetype="response">
<param name="instantFuelConsumption" type="Common.VehicleDataResult" mandatory="true">
@@ -3690,9 +3721,6 @@
</param>
</function>
<function name="UnsubscribeInstantFuelConsumption" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeInstantFuelConsumption" messagetype="response">
<param name="instantFuelConsumption" type="Common.VehicleDataResult" mandatory="true">
@@ -3700,9 +3728,6 @@
</param>
</function>
<function name="SubscribeExternalTemperature" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeExternalTemperature" messagetype="response">
<param name="externalTemperature" type="Common.VehicleDataResult" mandatory="true">
@@ -3710,9 +3735,6 @@
</param>
</function>
<function name="UnsubscribeExternalTemperature" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeExternalTemperature" messagetype="response">
<param name="externalTemperature" type="Common.VehicleDataResult" mandatory="true">
@@ -3720,9 +3742,6 @@
</param>
</function>
<function name="SubscribePrndl" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribePrndl" messagetype="response">
<param name="prndl" type="Common.VehicleDataResult" mandatory="true">
@@ -3730,9 +3749,6 @@
</param>
</function>
<function name="UnsubscribePrndl" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribePrndl" messagetype="response">
<param name="prndl" type="Common.VehicleDataResult" mandatory="true">
@@ -3740,9 +3756,6 @@
</param>
</function>
<function name="SubscribeVin" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeVin" messagetype="response">
<param name="vin" type="String" maxlength="17" mandatory="true">
@@ -3750,9 +3763,6 @@
</param>
</function>
<function name="UnsubscribeVin" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeVin" messagetype="response">
<param name="vin" type="String" maxlength="17" mandatory="true">
@@ -3760,9 +3770,6 @@
</param>
</function>
<function name="SubscribeTirePressure" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeTirePressure" messagetype="response">
<param name="tirePressure" type="Common.VehicleDataResult" mandatory="true">
@@ -3770,9 +3777,6 @@
</param>
</function>
<function name="UnsubscribeTirePressure" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeTirePressure" messagetype="response">
<param name="tirePressure" type="Common.VehicleDataResult" mandatory="true">
@@ -3780,9 +3784,6 @@
</param>
</function>
<function name="SubscribeOdometer" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeOdometer" messagetype="response">
<param name="odometer" type="Common.VehicleDataResult" mandatory="true">
@@ -3790,9 +3791,6 @@
</param>
</function>
<function name="UnsubscribeOdometer" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeOdometer" messagetype="response">
<param name="odometer" type="Common.VehicleDataResult" mandatory="true">
@@ -3800,9 +3798,6 @@
</param>
</function>
<function name="SubscribeBeltStatus" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeBeltStatus" messagetype="response">
<param name="beltStatus" type="Common.VehicleDataResult" mandatory="true">
@@ -3810,9 +3805,6 @@
</param>
</function>
<function name="UnsubscribeBeltStatus" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeBeltStatus" messagetype="response">
<param name="beltStatus" type="Common.VehicleDataResult" mandatory="true">
@@ -3820,9 +3812,6 @@
</param>
</function>
<function name="SubscribeBodyInformation" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeBodyInformation" messagetype="response">
<param name="bodyInformation" type="Common.VehicleDataResult" mandatory="true">
@@ -3830,9 +3819,6 @@
</param>
</function>
<function name="UnsubscribeBodyInformation" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeBodyInformation" messagetype="response">
<param name="bodyInformation" type="Common.VehicleDataResult" mandatory="true">
@@ -3840,9 +3826,6 @@
</param>
</function>
<function name="SubscribeDeviceStatus" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeDeviceStatus" messagetype="response">
<param name="deviceStatus" type="Common.VehicleDataResult" mandatory="true">
@@ -3850,9 +3833,6 @@
</param>
</function>
<function name="UnsubscribeDeviceStatus" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeDeviceStatus" messagetype="response">
<param name="deviceStatus" type="Common.VehicleDataResult" mandatory="true">
@@ -3860,9 +3840,6 @@
</param>
</function>
<function name="SubscribeDriverBraking" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeDriverBraking" messagetype="response">
<param name="driverBraking" type="Common.VehicleDataResult" mandatory="true">
@@ -3870,9 +3847,6 @@
</param>
</function>
<function name="UnsubscribeDriverBraking" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeDriverBraking" messagetype="response">
<param name="driverBraking" type="Common.VehicleDataResult" mandatory="true">
@@ -3880,9 +3854,6 @@
</param>
</function>
<function name="SubscribeWiperStatus" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeWiperStatus" messagetype="response">
<param name="wiperStatus" type="Common.VehicleDataResult" mandatory="true">
@@ -3890,9 +3861,6 @@
</param>
</function>
<function name="UnsubscribeWiperStatus" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeWiperStatus" messagetype="response">
<param name="wiperStatus" type="Common.VehicleDataResult" mandatory="true">
@@ -3900,9 +3868,6 @@
</param>
</function>
<function name="SubscribeHeadLampStatus" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeHeadLampStatus" messagetype="response">
<param name="headLampStatus" type="Common.VehicleDataResult" mandatory="true">
@@ -3910,9 +3875,6 @@
</param>
</function>
<function name="UnsubscribeHeadLampStatus" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeHeadLampStatus" messagetype="response">
<param name="headLampStatus" type="Common.VehicleDataResult" mandatory="true">
@@ -3920,9 +3882,6 @@
</param>
</function>
<function name="SubscribeEngineTorque" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeEngineTorque" messagetype="response">
<param name="engineTorque" type="Common.VehicleDataResult" mandatory="true">
@@ -3930,9 +3889,6 @@
</param>
</function>
<function name="UnsubscribeEngineTorque" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeEngineTorque" messagetype="response">
<param name="engineTorque" type="Common.VehicleDataResult" mandatory="true">
@@ -3940,9 +3896,6 @@
</param>
</function>
<function name="SubscribeAccPedalPosition" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeAccPedalPosition" messagetype="response">
<param name="accPedalPosition" type="Common.VehicleDataResult" mandatory="true">
@@ -3950,9 +3903,6 @@
</param>
</function>
<function name="UnsubscribeAccPedalPosition" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeAccPedalPosition" messagetype="response">
<param name="accPedalPosition" type="Common.VehicleDataResult" mandatory="true">
@@ -3960,9 +3910,6 @@
</param>
</function>
<function name="SubscribeSteeringWheelAngle" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeSteeringWheelAngle" messagetype="response">
<param name="steeringWheelAngle" type="Common.VehicleDataResult" mandatory="true">
@@ -3970,9 +3917,6 @@
</param>
</function>
<function name="UnsubscribeSteeringWheelAngle" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeSteeringWheelAngle" messagetype="response">
<param name="steeringWheelAngle" type="Common.VehicleDataResult" mandatory="true">
@@ -3980,9 +3924,6 @@
</param>
</function>
<function name="SubscribeECallInfo" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeECallInfo" messagetype="response">
<param name="eCallInfo" type="Common.VehicleDataResult" mandatory="true">
@@ -3990,9 +3931,6 @@
</param>
</function>
<function name="UnsubscribeECallInfo" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeECallInfo" messagetype="response">
<param name="eCallInfo" type="Common.VehicleDataResult" mandatory="true">
@@ -4000,9 +3938,6 @@
</param>
</function>
<function name="SubscribeAirbagStatus" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeAirbagStatus" messagetype="response">
<param name="airbagStatus" type="Common.VehicleDataResult" mandatory="true">
@@ -4010,9 +3945,6 @@
</param>
</function>
<function name="UnsubscribeAirbagStatus" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeAirbagStatus" messagetype="response">
<param name="airbagStatus" type="Common.VehicleDataResult" mandatory="true">
@@ -4020,9 +3952,6 @@
</param>
</function>
<function name="SubscribeEmergencyEvent" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeEmergencyEvent" messagetype="response">
<param name="emergencyEvent" type="Common.VehicleDataResult" mandatory="true">
@@ -4030,9 +3959,6 @@
</param>
</function>
<function name="UnsubscribeEmergencyEvent" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeEmergencyEvent" messagetype="response">
<param name="emergencyEvent" type="Common.VehicleDataResult" mandatory="true">
@@ -4040,9 +3966,6 @@
</param>
</function>
<function name="SubscribeClusterModeStatus" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeClusterModeStatus" messagetype="response">
<param name="clusterModeStatus" type="Common.VehicleDataResult" mandatory="true">
@@ -4050,9 +3973,6 @@
</param>
</function>
<function name="UnsubscribeClusterModeStatus" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeClusterModeStatus" messagetype="response">
<param name="clusterModeStatus" type="Common.VehicleDataResult" mandatory="true">
@@ -4060,9 +3980,6 @@
</param>
</function>
<function name="SubscribeMyKey" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="SubscribeMyKey" messagetype="response">
<param name="myKey" type="Common.VehicleDataResult" mandatory="true">
@@ -4070,9 +3987,6 @@
</param>
</function>
<function name="UnsubscribeMyKey" messagetype="request" provider="hmi">
- <param name="appID" type="Integer" mandatory="true">
- <description>ID of application requested this RPC.</description>
- </param>
</function>
<function name="UnsubscribeMyKey" messagetype="response">
<param name="myKey" type="Common.VehicleDataResult" mandatory="true">
diff --git a/src/components/media_manager/CMakeLists.txt b/src/components/media_manager/CMakeLists.txt
index 9a8618fa60..69af6e7841 100644
--- a/src/components/media_manager/CMakeLists.txt
+++ b/src/components/media_manager/CMakeLists.txt
@@ -45,11 +45,14 @@ set(default_sources
${COMPONENTS_DIR}/media_manager/src/audio/from_mic_to_file_recorder_thread.cc
${COMPONENTS_DIR}/media_manager/src/audio/socket_audio_streamer_adapter.cc
${COMPONENTS_DIR}/media_manager/src/audio/pipe_audio_streamer_adapter.cc
+ ${COMPONENTS_DIR}/media_manager/src/audio/file_audio_streamer_adapter.cc
${COMPONENTS_DIR}/media_manager/src/video/socket_video_streamer_adapter.cc
${COMPONENTS_DIR}/media_manager/src/video/pipe_video_streamer_adapter.cc
- ${COMPONENTS_DIR}/media_manager/src/video/video_stream_to_file_adapter.cc
+ ${COMPONENTS_DIR}/media_manager/src/video/file_video_streamer_adapter.cc
+ ${COMPONENTS_DIR}/media_manager/src/streamer_adapter.cc
${COMPONENTS_DIR}/media_manager/src/pipe_streamer_adapter.cc
${COMPONENTS_DIR}/media_manager/src/socket_streamer_adapter.cc
+ ${COMPONENTS_DIR}/media_manager/src/file_streamer_adapter.cc
)
set(LIBRARIES
${GSTREAMER_gstreamer_LIBRARY}
@@ -60,17 +63,18 @@ set(LIBRARIES
glib-2.0
)
else(EXTENDED_MEDIA_MODE)
-set(default_includes
-)
+
set(default_sources
- ${COMPONENTS_DIR}/media_manager/src/video/video_stream_to_file_adapter.cc
${COMPONENTS_DIR}/media_manager/src/audio/socket_audio_streamer_adapter.cc
${COMPONENTS_DIR}/media_manager/src/audio/pipe_audio_streamer_adapter.cc
+ ${COMPONENTS_DIR}/media_manager/src/audio/file_audio_streamer_adapter.cc
${COMPONENTS_DIR}/media_manager/src/video/socket_video_streamer_adapter.cc
${COMPONENTS_DIR}/media_manager/src/video/pipe_video_streamer_adapter.cc
- ${COMPONENTS_DIR}/media_manager/src/video/video_stream_to_file_adapter.cc
+ ${COMPONENTS_DIR}/media_manager/src/video/file_video_streamer_adapter.cc
+ ${COMPONENTS_DIR}/media_manager/src/streamer_adapter.cc
${COMPONENTS_DIR}/media_manager/src/pipe_streamer_adapter.cc
${COMPONENTS_DIR}/media_manager/src/socket_streamer_adapter.cc
+ ${COMPONENTS_DIR}/media_manager/src/file_streamer_adapter.cc
)
set(LIBRARIES
ProtocolLibrary
@@ -91,9 +95,7 @@ include_directories (
${COMPONENTS_DIR}/config_profile/include/
${JSONCPP_INCLUDE_DIRECTORY}
${CMAKE_BINARY_DIR}/src/components/
- ${CMAKE_SOURCE_DIR}/src/components/policy/src/policy/include/
- ${CMAKE_SOURCE_DIR}/src/components/policy/src/policy/usage_statistics/include/
- ${default_includes}
+ ${COMPONENTS_DIR}/policy/include/
${LOG4CXX_INCLUDE_DIRECTORY}
)
@@ -109,5 +111,6 @@ add_library("MediaManager" ${SOURCES} ${default_sources})
target_link_libraries("MediaManager" ${LIBRARIES})
if(BUILD_TESTS)
- add_subdirectory(test)
+ add_subdirectory(test)
endif()
+
diff --git a/src/components/media_manager/include/media_manager/audio/a2dp_source_player_adapter.h b/src/components/media_manager/include/media_manager/audio/a2dp_source_player_adapter.h
index 257564e81a..3f262b27bb 100644
--- a/src/components/media_manager/include/media_manager/audio/a2dp_source_player_adapter.h
+++ b/src/components/media_manager/include/media_manager/audio/a2dp_source_player_adapter.h
@@ -38,6 +38,10 @@
#include "media_manager/media_adapter_impl.h"
#include "utils/threads/thread_delegate.h"
+namespace protocol_handler {
+class SessionObserver;
+}
+
namespace threads {
class Thread;
}
@@ -45,22 +49,28 @@ class Thread;
namespace media_manager {
class A2DPSourcePlayerAdapter : public MediaAdapterImpl {
- public:
- A2DPSourcePlayerAdapter();
- ~A2DPSourcePlayerAdapter();
- void SendData(int32_t application_key,
- const ::protocol_handler::RawMessagePtr message) {}
- void StartActivity(int32_t application_key);
- void StopActivity(int32_t application_key);
- bool is_app_performing_activity(int32_t application_key);
+ public:
+ A2DPSourcePlayerAdapter(protocol_handler::SessionObserver& session_observer);
+ ~A2DPSourcePlayerAdapter();
+ void SendData(int32_t application_key,
+ const ::protocol_handler::RawMessagePtr message) {}
+ void StartActivity(int32_t application_key);
+ void StopActivity(int32_t application_key);
+ bool is_app_performing_activity(int32_t application_key) const;
+
+ void set_connection_handler(
+ connection_handler::ConnectionHandlerImpl* connection_handler) {
+ connection_handler_ = connection_handler;
+ }
- private:
- class A2DPSourcePlayerThread;
+ private:
+ class A2DPSourcePlayerThread;
- typedef std::pair<threads::Thread*, A2DPSourcePlayerThread*> Pair;
- typedef std::map<int32_t, Pair> SourcesMap;
- SourcesMap sources_;
- DISALLOW_COPY_AND_ASSIGN(A2DPSourcePlayerAdapter);
+ typedef std::pair<threads::Thread*, A2DPSourcePlayerThread*> Pair;
+ typedef std::map<int32_t, Pair> SourcesMap;
+ SourcesMap sources_;
+ protocol_handler::SessionObserver& session_observer_;
+ DISALLOW_COPY_AND_ASSIGN(A2DPSourcePlayerAdapter);
};
} // namespace media_manager
diff --git a/src/components/media_manager/include/media_manager/audio/audio_stream_sender_thread.h b/src/components/media_manager/include/media_manager/audio/audio_stream_sender_thread.h
index cb1c144706..b956f2c9e2 100644
--- a/src/components/media_manager/include/media_manager/audio/audio_stream_sender_thread.h
+++ b/src/components/media_manager/include/media_manager/audio/audio_stream_sender_thread.h
@@ -39,13 +39,16 @@
#include "utils/conditional_variable.h"
#include "utils/lock.h"
-
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
class SmartObject;
}
}
+namespace application_manager {
+class ApplicationManager;
+}
+
namespace media_manager {
typedef enum {
@@ -62,68 +65,67 @@ typedef enum {
ACQ_16_BIT = 1
} AudioCaptureQuality;
-typedef enum {
- AT_INVALID = -1,
- AT_PCM = 0
-} AudioType;
+typedef enum { AT_INVALID = -1, AT_PCM = 0 } AudioType;
/*
- * @brief AudioStreamSenderThread class used to read binary data written from microphone
+ * @brief AudioStreamSenderThread class used to read binary data written from
+ * microphone
* and send it every 1 second to mobile device.
*/
class AudioStreamSenderThread : public threads::ThreadDelegate {
- public:
- /*
- * @brief AudioStreamSenderThread class constructor
- *
- * @param session_key Session key of connection for Mobile side
- * @param correlation_id Correlation id for response for Mobile side
- */
- AudioStreamSenderThread(const std::string fileName,
- uint32_t session_key);
-
- /*
- * @brief AudioStreamSenderThread class destructor
- */
- ~AudioStreamSenderThread();
-
- /**
- * @brief Thread procedure.
- */
- void threadMain();
-
- /*
- * @brief Retrieve session key
- *
- * @return Stored session key
- */
- uint32_t session_key() const;
-
- void exitThreadMain();
-
- private:
- /*
- * @brief Sends AudioPassThru request
- */
- bool SendEndAudioPassThru();
-
- void sendAudioChunkToMobile();
-
-
- bool getShouldBeStopped();
- void setShouldBeStopped(bool should_stop);
-
- uint32_t session_key_;
- const std::string fileName_;
- int32_t offset_;
- volatile bool shouldBeStoped_;
- sync_primitives::Lock shouldBeStoped_lock_;
- sync_primitives::ConditionalVariable shouldBeStoped_cv_;
-
- static const int32_t kAudioPassThruTimeout;
-
-
- DISALLOW_COPY_AND_ASSIGN(AudioStreamSenderThread);
+ public:
+ /*
+ * @brief AudioStreamSenderThread class constructor
+ *
+ * @param session_key Session key of connection for Mobile side
+ * @param correlation_id Correlation id for response for Mobile side
+ */
+ AudioStreamSenderThread(const std::string& fileName,
+ uint32_t session_key,
+ application_manager::ApplicationManager& app_mngr);
+
+ /*
+ * @brief AudioStreamSenderThread class destructor
+ */
+ ~AudioStreamSenderThread();
+
+ /**
+ * @brief Thread procedure.
+ */
+ void threadMain();
+
+ /*
+ * @brief Retrieve session key
+ *
+ * @return Stored session key
+ */
+ uint32_t session_key() const;
+
+ void exitThreadMain();
+
+ private:
+ /*
+ * @brief Sends AudioPassThru request
+ */
+ bool SendEndAudioPassThru();
+
+ void sendAudioChunkToMobile();
+
+ bool getShouldBeStopped();
+ void setShouldBeStopped(bool should_stop);
+
+ uint32_t session_key_;
+ const std::string fileName_;
+ int32_t offset_;
+ volatile bool shouldBeStoped_;
+ sync_primitives::Lock shouldBeStoped_lock_;
+ sync_primitives::ConditionalVariable shouldBeStoped_cv_;
+
+ static const int32_t kAudioPassThruTimeout;
+
+ application_manager::ApplicationManager& application_manager_;
+
+ DISALLOW_COPY_AND_ASSIGN(AudioStreamSenderThread);
};
} // namespace media_manager
diff --git a/src/components/media_manager/include/media_manager/audio/file_audio_streamer_adapter.h b/src/components/media_manager/include/media_manager/audio/file_audio_streamer_adapter.h
new file mode 100644
index 0000000000..dc0c001acf
--- /dev/null
+++ b/src/components/media_manager/include/media_manager/audio/file_audio_streamer_adapter.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2014-2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_AUDIO_FILE_AUDIO_STREAMER_ADAPTER_H_
+#define SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_AUDIO_FILE_AUDIO_STREAMER_ADAPTER_H_
+
+#include "media_manager/file_streamer_adapter.h"
+
+namespace media_manager {
+
+class FileAudioStreamerAdapter : public FileStreamerAdapter {
+ public:
+ FileAudioStreamerAdapter(const std::string& audio_stream_file,
+ const std::string& app_storage_folder);
+ ~FileAudioStreamerAdapter();
+};
+
+} // namespace media_manager
+
+#endif // SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_AUDIO_FILE_AUDIO_STREAMER_ADAPTER_H_
diff --git a/src/components/media_manager/include/media_manager/audio/from_mic_recorder_adapter.h b/src/components/media_manager/include/media_manager/audio/from_mic_recorder_adapter.h
index 3ea4581435..7daf9c7add 100644
--- a/src/components/media_manager/include/media_manager/audio/from_mic_recorder_adapter.h
+++ b/src/components/media_manager/include/media_manager/audio/from_mic_recorder_adapter.h
@@ -43,22 +43,23 @@ class Thread;
namespace media_manager {
class FromMicRecorderAdapter : public MediaAdapterImpl {
- public:
- FromMicRecorderAdapter();
- ~FromMicRecorderAdapter();
- void SendData(int32_t application_key,
- const ::protocol_handler::RawMessagePtr message) {}
- void StartActivity(int32_t application_key);
- void StopActivity(int32_t application_key);
- bool is_app_performing_activity(int32_t application_key);
- void set_output_file(const std::string& output_file);
- void set_duration(int32_t duration);
- private:
- threads::Thread* recorder_thread_;
- std::string output_file_;
- const int32_t kDefaultDuration;
- int32_t duration_;
- DISALLOW_COPY_AND_ASSIGN(FromMicRecorderAdapter);
+ public:
+ FromMicRecorderAdapter();
+ ~FromMicRecorderAdapter();
+ void SendData(int32_t application_key,
+ const ::protocol_handler::RawMessagePtr message) {}
+ void StartActivity(int32_t application_key);
+ void StopActivity(int32_t application_key);
+ bool is_app_performing_activity(int32_t application_key) const;
+ void set_output_file(const std::string& output_file);
+ void set_duration(int32_t duration);
+
+ private:
+ threads::Thread* recorder_thread_;
+ std::string output_file_;
+ const int32_t kDefaultDuration;
+ int32_t duration_;
+ DISALLOW_COPY_AND_ASSIGN(FromMicRecorderAdapter);
};
} // namespace media_manager
diff --git a/src/components/media_manager/include/media_manager/audio/from_mic_recorder_listener.h b/src/components/media_manager/include/media_manager/audio/from_mic_recorder_listener.h
index 7df2af7f4a..c615195f94 100644
--- a/src/components/media_manager/include/media_manager/audio/from_mic_recorder_listener.h
+++ b/src/components/media_manager/include/media_manager/audio/from_mic_recorder_listener.h
@@ -36,30 +36,33 @@
#include <string>
#include "media_manager/media_adapter_listener.h"
+namespace application_manager {
+class ApplicationManager;
+}
+
namespace threads {
class Thread;
}
namespace media_manager {
class FromMicRecorderListener : public MediaAdapterListener {
- public:
- explicit FromMicRecorderListener(
- const std::string& file_name);
- ~FromMicRecorderListener();
- virtual void OnDataReceived(
- int32_t application_key,
- const DataForListener& data);
- virtual void OnErrorReceived(
- int32_t application_key,
- const DataForListener& data);
- virtual void OnActivityStarted(int32_t application_key);
- virtual void OnActivityEnded(int32_t application_key);
+ public:
+ FromMicRecorderListener(const std::string& file_name,
+ application_manager::ApplicationManager&);
+ ~FromMicRecorderListener();
+ virtual void OnDataReceived(int32_t application_key,
+ const DataForListener& data);
+ virtual void OnErrorReceived(int32_t application_key,
+ const DataForListener& data);
+ virtual void OnActivityStarted(int32_t application_key);
+ virtual void OnActivityEnded(int32_t application_key);
- private:
- threads::Thread* reader_;
- std::string file_name_;
- int32_t current_application_;
- DISALLOW_COPY_AND_ASSIGN(FromMicRecorderListener);
+ private:
+ threads::Thread* reader_;
+ std::string file_name_;
+ int32_t current_application_;
+ application_manager::ApplicationManager& application_manager_;
+ DISALLOW_COPY_AND_ASSIGN(FromMicRecorderListener);
};
} // namespace media_manager
diff --git a/src/components/media_manager/include/media_manager/audio/from_mic_to_file_recorder_thread.h b/src/components/media_manager/include/media_manager/audio/from_mic_to_file_recorder_thread.h
index 7bb036fa42..f0c6d3c48f 100644
--- a/src/components/media_manager/include/media_manager/audio/from_mic_to_file_recorder_thread.h
+++ b/src/components/media_manager/include/media_manager/audio/from_mic_to_file_recorder_thread.h
@@ -44,53 +44,52 @@
namespace media_manager {
class FromMicToFileRecorderThread : public threads::ThreadDelegate {
- public:
- FromMicToFileRecorderThread(const std::string& output_file,
- int32_t duration);
- ~FromMicToFileRecorderThread();
- void threadMain();
+ public:
+ FromMicToFileRecorderThread(const std::string& output_file, int32_t duration);
+ ~FromMicToFileRecorderThread();
+ void threadMain();
- void exitThreadMain();
+ void exitThreadMain();
- void set_output_file(const std::string& output_file);
- void set_record_duration(int32_t duration);
+ void set_output_file(const std::string& output_file);
+ void set_record_duration(int32_t duration);
- private:
- int32_t argc_;
- gchar** argv_;
+ private:
+ int32_t argc_;
+ gchar** argv_;
- const std::string oKey_;
- const std::string tKey_;
+ const std::string oKey_;
+ const std::string tKey_;
- static GMainLoop* loop;
- threads::Thread* sleepThread_;
- bool shouldBeStoped_;
- sync_primitives::Lock stopFlagLock_;
+ static GMainLoop* loop;
+ threads::Thread* sleepThread_;
+ bool shouldBeStoped_;
+ sync_primitives::Lock stopFlagLock_;
- std::string outputFileName_, durationString_;
+ std::string outputFileName_, durationString_;
- typedef struct {
- GstElement* pipeline;
- gint duration;
- } GstTimeout;
+ typedef struct {
+ GstElement* pipeline;
+ gint duration;
+ } GstTimeout;
- void initArgs();
+ void initArgs();
- void psleep(void* timeout);
+ void psleep(void* timeout);
- class SleepThreadDelegate : public threads::ThreadDelegate {
- public:
- explicit SleepThreadDelegate(GstTimeout timeout);
+ class SleepThreadDelegate : public threads::ThreadDelegate {
+ public:
+ explicit SleepThreadDelegate(GstTimeout timeout);
- void threadMain();
+ void threadMain();
- private:
- GstTimeout timeout_;
+ private:
+ GstTimeout timeout_;
- DISALLOW_COPY_AND_ASSIGN(SleepThreadDelegate);
- };
+ DISALLOW_COPY_AND_ASSIGN(SleepThreadDelegate);
+ };
- DISALLOW_COPY_AND_ASSIGN(FromMicToFileRecorderThread);
+ DISALLOW_COPY_AND_ASSIGN(FromMicToFileRecorderThread);
};
} // namespace media_manager
diff --git a/src/components/media_manager/include/media_manager/audio/pipe_audio_streamer_adapter.h b/src/components/media_manager/include/media_manager/audio/pipe_audio_streamer_adapter.h
index 437f34fa03..d0dbbebd38 100644
--- a/src/components/media_manager/include/media_manager/audio/pipe_audio_streamer_adapter.h
+++ b/src/components/media_manager/include/media_manager/audio/pipe_audio_streamer_adapter.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2014-2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -33,17 +33,15 @@
#ifndef SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_AUDIO_PIPE_AUDIO_STREAMER_ADAPTER_H_
#define SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_AUDIO_PIPE_AUDIO_STREAMER_ADAPTER_H_
-#include <string>
#include "media_manager/pipe_streamer_adapter.h"
namespace media_manager {
-class PipeAudioStreamerAdapter : public PipeStreamerAdapter {
- public:
- PipeAudioStreamerAdapter();
- ~PipeAudioStreamerAdapter();
- private:
- DISALLOW_COPY_AND_ASSIGN(PipeAudioStreamerAdapter);
+class PipeAudioStreamerAdapter : public PipeStreamerAdapter {
+ public:
+ PipeAudioStreamerAdapter(const std::string& named_audio_pipe_path,
+ const std::string& app_storage_folder);
+ ~PipeAudioStreamerAdapter();
};
} // namespace media_manager
diff --git a/src/components/media_manager/include/media_manager/audio/socket_audio_streamer_adapter.h b/src/components/media_manager/include/media_manager/audio/socket_audio_streamer_adapter.h
index be5951be3e..c0f3174496 100644
--- a/src/components/media_manager/include/media_manager/audio/socket_audio_streamer_adapter.h
+++ b/src/components/media_manager/include/media_manager/audio/socket_audio_streamer_adapter.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2014-2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -33,18 +33,17 @@
#ifndef SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_AUDIO_SOCKET_AUDIO_STREAMER_ADAPTER_H_
#define SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_AUDIO_SOCKET_AUDIO_STREAMER_ADAPTER_H_
-#include <string>
#include "media_manager/socket_streamer_adapter.h"
namespace media_manager {
+
class SocketAudioStreamerAdapter : public SocketStreamerAdapter {
- public:
- SocketAudioStreamerAdapter();
- virtual ~SocketAudioStreamerAdapter();
- private:
- DISALLOW_COPY_AND_ASSIGN(SocketAudioStreamerAdapter);
+ public:
+ SocketAudioStreamerAdapter(const std::string& server_address,
+ uint16_t audio_streaming_port);
+ virtual ~SocketAudioStreamerAdapter();
};
-} // namespace media_manager
+} // namespace media_manager
#endif // SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_AUDIO_SOCKET_AUDIO_STREAMER_ADAPTER_H_
diff --git a/src/components/media_manager/include/media_manager/file_streamer_adapter.h b/src/components/media_manager/include/media_manager/file_streamer_adapter.h
new file mode 100644
index 0000000000..293c6721ee
--- /dev/null
+++ b/src/components/media_manager/include/media_manager/file_streamer_adapter.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2014-2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_FILE_STREAMER_ADAPTER_H_
+#define SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_FILE_STREAMER_ADAPTER_H_
+
+#include <string>
+#include <fstream>
+#include "media_manager/streamer_adapter.h"
+#include "utils/threads/thread_delegate.h"
+
+namespace media_manager {
+
+class FileStreamerAdapter : public StreamerAdapter {
+ public:
+ FileStreamerAdapter(const std::string& file_name,
+ const std::string& app_storage_folder);
+ virtual ~FileStreamerAdapter();
+
+ protected:
+ class FileStreamer : public StreamerAdapter::Streamer {
+ public:
+ FileStreamer(FileStreamerAdapter* const adapter,
+ const std::string& file_name,
+ const std::string& app_storage_folder);
+ virtual ~FileStreamer();
+
+ protected:
+ virtual bool Connect();
+ virtual void Disconnect();
+ virtual bool Send(protocol_handler::RawMessagePtr msg);
+
+ private:
+ std::string file_name_;
+ std::string app_storage_folder_;
+ std::ofstream* file_stream_;
+ };
+};
+
+} // namespace media_manager
+
+#endif // SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_FILE_STREAMER_ADAPTER_H_
diff --git a/src/components/media_manager/include/media_manager/media_adapter.h b/src/components/media_manager/include/media_manager/media_adapter.h
index a96ce03c87..3fe05cae33 100644
--- a/src/components/media_manager/include/media_manager/media_adapter.h
+++ b/src/components/media_manager/include/media_manager/media_adapter.h
@@ -33,7 +33,7 @@
#ifndef SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_MEDIA_ADAPTER_H_
#define SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_MEDIA_ADAPTER_H_
-#include <cstdint>
+#include <stdint.h>
#include "protocol/common.h"
namespace media_manager {
@@ -44,9 +44,11 @@ class MediaAdapter {
const ::protocol_handler::RawMessagePtr message) = 0;
virtual void StartActivity(int32_t application_key) = 0;
virtual void StopActivity(int32_t application_key) = 0;
- virtual bool is_app_performing_activity(int32_t application_key) = 0;
+ virtual bool is_app_performing_activity(int32_t application_key) const = 0;
- virtual ~MediaAdapter() { ;}
+ virtual ~MediaAdapter() {
+ ;
+ }
};
} // namespace media_manager
#endif // SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_MEDIA_ADAPTER_H_
diff --git a/src/components/media_manager/include/media_manager/media_adapter_impl.h b/src/components/media_manager/include/media_manager/media_adapter_impl.h
index a3a296150b..75c48c98b7 100644
--- a/src/components/media_manager/include/media_manager/media_adapter_impl.h
+++ b/src/components/media_manager/include/media_manager/media_adapter_impl.h
@@ -43,18 +43,18 @@ namespace media_manager {
typedef utils::SharedPtr<MediaAdapterListener> MediaListenerPtr;
class MediaAdapterImpl : public MediaAdapter {
- public:
- virtual ~MediaAdapterImpl();
- virtual void AddListener(const MediaListenerPtr& listener);
- virtual void RemoveListener(const MediaListenerPtr& listener);
+ public:
+ virtual ~MediaAdapterImpl();
+ virtual void AddListener(const MediaListenerPtr& listener);
+ virtual void RemoveListener(const MediaListenerPtr& listener);
- protected:
- MediaAdapterImpl();
- std::set<MediaListenerPtr> media_listeners_;
- int32_t current_application_;
+ protected:
+ MediaAdapterImpl();
+ std::set<MediaListenerPtr> media_listeners_;
+ int32_t current_application_;
- private:
- DISALLOW_COPY_AND_ASSIGN(MediaAdapterImpl);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(MediaAdapterImpl);
};
typedef utils::SharedPtr<MediaAdapterImpl> MediaAdapterImplPtr;
diff --git a/src/components/media_manager/include/media_manager/media_adapter_listener.h b/src/components/media_manager/include/media_manager/media_adapter_listener.h
index 423d41c89b..37c3925199 100644
--- a/src/components/media_manager/include/media_manager/media_adapter_listener.h
+++ b/src/components/media_manager/include/media_manager/media_adapter_listener.h
@@ -40,17 +40,14 @@ namespace media_manager {
typedef int32_t DataForListener;
class MediaAdapterListener {
- public:
- virtual ~MediaAdapterListener() {
- }
- virtual void OnDataReceived(
- int32_t application_key,
- const DataForListener& data) = 0;
- virtual void OnErrorReceived(
- int32_t application_key,
- const DataForListener& data) = 0;
- virtual void OnActivityStarted(int32_t application_key) = 0;
- virtual void OnActivityEnded(int32_t application_key) = 0;
+ public:
+ virtual ~MediaAdapterListener() {}
+ virtual void OnDataReceived(int32_t application_key,
+ const DataForListener& data) = 0;
+ virtual void OnErrorReceived(int32_t application_key,
+ const DataForListener& data) = 0;
+ virtual void OnActivityStarted(int32_t application_key) = 0;
+ virtual void OnActivityEnded(int32_t application_key) = 0;
};
} // namespace media_manager
#endif // SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_MEDIA_ADAPTER_LISTENER_H_
diff --git a/src/components/media_manager/include/media_manager/media_manager.h b/src/components/media_manager/include/media_manager/media_manager.h
index b4f5c9c28b..53e3690c13 100644
--- a/src/components/media_manager/include/media_manager/media_manager.h
+++ b/src/components/media_manager/include/media_manager/media_manager.h
@@ -34,26 +34,33 @@
#define SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_MEDIA_MANAGER_H_
#include <string>
-#include "protocol_handler/protocol_handler.h"
-
+#include "protocol/service_type.h"
+#include "media_manager/media_manager_settings.h"
namespace media_manager {
class MediaManager {
- public:
- virtual void PlayA2DPSource(int32_t application_key) = 0;
- virtual void StopA2DPSource(int32_t application_key) = 0;
+ public:
+ virtual void PlayA2DPSource(int32_t application_key) = 0;
+ virtual void StopA2DPSource(int32_t application_key) = 0;
- virtual void StartMicrophoneRecording(int32_t application_key,
- const std::string& outputFileName,
- int32_t duration) = 0;
- virtual void StopMicrophoneRecording(int32_t application_key) = 0;
+ virtual void StartMicrophoneRecording(int32_t application_key,
+ const std::string& outputFileName,
+ int32_t duration) = 0;
+ virtual void StopMicrophoneRecording(int32_t application_key) = 0;
- virtual void StartStreaming(
- int32_t application_key, protocol_handler::ServiceType service_type) = 0;
- virtual void StopStreaming(
- int32_t application_key, protocol_handler::ServiceType service_type) = 0;
+ virtual void StartStreaming(int32_t application_key,
+ protocol_handler::ServiceType service_type) = 0;
+ virtual void StopStreaming(int32_t application_key,
+ protocol_handler::ServiceType service_type) = 0;
+ virtual void FramesProcessed(int32_t application_key,
+ int32_t frame_number) = 0;
+ /**
+ * \brief Media manager settings getter
+ * \return pointer to media manager settings class
+ */
+ virtual const MediaManagerSettings& settings() const = 0;
- virtual ~MediaManager(){}
+ virtual ~MediaManager() {}
};
} // namespace media_manager
diff --git a/src/components/media_manager/include/media_manager/media_manager_impl.h b/src/components/media_manager/include/media_manager/media_manager_impl.h
index ebdae7b958..c84a5a884f 100644
--- a/src/components/media_manager/include/media_manager/media_manager_impl.h
+++ b/src/components/media_manager/include/media_manager/media_manager_impl.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -35,58 +35,80 @@
#include <string>
#include <map>
-#include "utils/singleton.h"
#include "protocol_handler/protocol_observer.h"
#include "protocol_handler/protocol_handler.h"
#include "media_manager/media_manager.h"
#include "media_manager/media_adapter_impl.h"
#include "media_manager/media_adapter_listener.h"
+namespace application_manager {
+class ApplicationManager;
+}
+
+namespace connection_handler {
+class ConnectionHandlerImpl;
+}
+
namespace media_manager {
class MediaManagerImpl : public MediaManager,
- public protocol_handler::ProtocolObserver,
- public utils::Singleton<MediaManagerImpl> {
- public:
- virtual ~MediaManagerImpl();
+ public protocol_handler::ProtocolObserver {
+ public:
+ MediaManagerImpl(application_manager::ApplicationManager& application_manager,
+ const MediaManagerSettings& settings);
+ virtual ~MediaManagerImpl();
- virtual void PlayA2DPSource(int32_t application_key);
- virtual void StopA2DPSource(int32_t application_key);
+ virtual void PlayA2DPSource(int32_t application_key);
+ virtual void StopA2DPSource(int32_t application_key);
- virtual void StartMicrophoneRecording(int32_t application_key,
- const std::string& outputFileName,
- int32_t duration);
- virtual void StopMicrophoneRecording(int32_t application_key);
+ virtual void StartMicrophoneRecording(int32_t application_key,
+ const std::string& outputFileName,
+ int32_t duration);
+ virtual void StopMicrophoneRecording(int32_t application_key);
- virtual void StartStreaming(
- int32_t application_key, protocol_handler::ServiceType service_type);
- virtual void StopStreaming(
- int32_t application_key, protocol_handler::ServiceType service_type);
+ virtual void StartStreaming(int32_t application_key,
+ protocol_handler::ServiceType service_type);
+ virtual void StopStreaming(int32_t application_key,
+ protocol_handler::ServiceType service_type);
- virtual void SetProtocolHandler(
+ virtual void SetProtocolHandler(
protocol_handler::ProtocolHandler* protocol_handler);
- virtual void OnMessageReceived(
+ virtual void OnMessageReceived(
const ::protocol_handler::RawMessagePtr message);
- virtual void OnMobileMessageSent(
+ virtual void OnMobileMessageSent(
const ::protocol_handler::RawMessagePtr message);
- virtual void FramesProcessed(int32_t application_key, int32_t frame_number);
+ virtual void FramesProcessed(int32_t application_key, int32_t frame_number);
+
+ virtual const MediaManagerSettings& settings() const OVERRIDE;
+
+#ifdef BUILD_TESTS
+ void set_mock_a2dp_player(MediaAdapter* media_adapter);
+ void set_mock_mic_listener(MediaListenerPtr media_listener);
+ void set_mock_mic_recorder(MediaAdapterImpl* media_adapter);
+ void set_mock_streamer(protocol_handler::ServiceType stype,
+ MediaAdapterImpl* mock_stream);
+ void set_mock_streamer_listener(protocol_handler::ServiceType stype,
+ MediaAdapterListener* mock_stream);
+#endif // BUILD_TESTS
+
+ protected:
+ virtual void Init();
+
+ const MediaManagerSettings& settings_;
- protected:
- MediaManagerImpl();
- virtual void Init();
+ protocol_handler::ProtocolHandler* protocol_handler_;
+ MediaAdapter* a2dp_player_;
- protocol_handler::ProtocolHandler* protocol_handler_;
- MediaAdapter* a2dp_player_;
+ MediaAdapterImpl* from_mic_recorder_;
+ MediaListenerPtr from_mic_listener_;
- MediaAdapterImpl* from_mic_recorder_;
- MediaListenerPtr from_mic_listener_;
+ std::map<protocol_handler::ServiceType, MediaAdapterImplPtr> streamer_;
+ std::map<protocol_handler::ServiceType, MediaListenerPtr> streamer_listener_;
- std::map<protocol_handler::ServiceType, MediaAdapterImplPtr> streamer_;
- std::map<protocol_handler::ServiceType, MediaListenerPtr> streamer_listener_;
+ application_manager::ApplicationManager& application_manager_;
- private:
- DISALLOW_COPY_AND_ASSIGN(MediaManagerImpl);
- FRIEND_BASE_SINGLETON_CLASS(MediaManagerImpl);
+ private:
+ DISALLOW_COPY_AND_ASSIGN(MediaManagerImpl);
};
} // namespace media_manager
diff --git a/src/components/media_manager/include/media_manager/pipe_streamer_adapter.h b/src/components/media_manager/include/media_manager/pipe_streamer_adapter.h
index f6a0c687ea..1e998ef82f 100644
--- a/src/components/media_manager/include/media_manager/pipe_streamer_adapter.h
+++ b/src/components/media_manager/include/media_manager/pipe_streamer_adapter.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2014-2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -34,82 +34,35 @@
#define SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_PIPE_STREAMER_ADAPTER_H_
#include <string>
-#include "media_manager/media_adapter_impl.h"
-#include "utils/shared_ptr.h"
-#include "utils/message_queue.h"
-#include "utils/threads/thread.h"
+#include "media_manager/streamer_adapter.h"
#include "utils/threads/thread_delegate.h"
namespace media_manager {
-using ::utils::MessageQueue;
-
-class PipeStreamerAdapter : public MediaAdapterImpl {
- public:
- PipeStreamerAdapter();
- virtual ~PipeStreamerAdapter();
- virtual void SendData(int32_t application_key,
- const ::protocol_handler::RawMessagePtr message);
- virtual void StartActivity(int32_t application_key);
- virtual void StopActivity(int32_t application_key);
- virtual bool is_app_performing_activity(int32_t application_key);
-
- protected:
+class PipeStreamerAdapter : public StreamerAdapter {
+ public:
+ PipeStreamerAdapter(const std::string& named_pipe_path,
+ const std::string& app_storage_folder);
+ virtual ~PipeStreamerAdapter();
+
+ protected:
+ class PipeStreamer : public StreamerAdapter::Streamer {
+ public:
+ PipeStreamer(PipeStreamerAdapter* const adapter,
+ const std::string& named_pipe_path,
+ const std::string& app_storage_folder);
+ virtual ~PipeStreamer();
+
+ protected:
+ virtual bool Connect();
+ virtual void Disconnect();
+ virtual bool Send(protocol_handler::RawMessagePtr msg);
+
+ private:
std::string named_pipe_path_;
-
- /*
- * @brief Start streamer thread
- */
- virtual void Init();
-
- private:
- class Streamer : public threads::ThreadDelegate {
- public:
- /*
- * Default constructor
- *
- * @param server Server pointer
- */
- explicit Streamer(PipeStreamerAdapter* server);
-
- /*
- * Destructor
- */
- ~Streamer();
-
- /*
- * @brief Function called by thread on start
- */
- void threadMain();
-
- /*
- * @brief Function called by thread on exit
- */
- void exitThreadMain();
-
- /*
- * @brief Opens pipe
- */
- void open();
-
- /*
- * @brief Closes pipe
- */
- void close();
-
- private:
- PipeStreamerAdapter* server_;
- int32_t pipe_fd_;
- volatile bool stop_flag_;
-
- DISALLOW_COPY_AND_ASSIGN(Streamer);
- };
-
- bool is_ready_;
- threads::Thread* thread_;
- MessageQueue<protocol_handler::RawMessagePtr> messages_;
-
- DISALLOW_COPY_AND_ASSIGN(PipeStreamerAdapter);
+ std::string app_storage_folder_;
+ int32_t pipe_fd_;
+ };
};
} // namespace media_manager
diff --git a/src/components/media_manager/include/media_manager/socket_streamer_adapter.h b/src/components/media_manager/include/media_manager/socket_streamer_adapter.h
index a4ded9cb33..45311b6077 100644
--- a/src/components/media_manager/include/media_manager/socket_streamer_adapter.h
+++ b/src/components/media_manager/include/media_manager/socket_streamer_adapter.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2014-2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -34,106 +34,43 @@
#define SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_SOCKET_STREAMER_ADAPTER_H_
#include <string>
-#include "media_manager/media_adapter_impl.h"
-#include "utils/logger.h"
-#include "utils/shared_ptr.h"
-#include "utils/message_queue.h"
-#include "utils/threads/thread.h"
+#include "media_manager/streamer_adapter.h"
#include "utils/threads/thread_delegate.h"
namespace media_manager {
-using ::utils::MessageQueue;
-
-class SocketStreamerAdapter : public MediaAdapterImpl {
- public:
- SocketStreamerAdapter();
- virtual ~SocketStreamerAdapter();
- virtual void SendData(int32_t application_key,
- const ::protocol_handler::RawMessagePtr message);
- virtual void StartActivity(int32_t application_key);
- virtual void StopActivity(int32_t application_key);
- virtual bool is_app_performing_activity(int32_t application_key);
-
- protected:
-
- /*
- * @brief Start streamer thread
- */
- virtual void Init();
-
- int32_t port_;
+class SocketStreamerAdapter : public StreamerAdapter {
+ public:
+ SocketStreamerAdapter(const std::string& ip,
+ uint16_t port,
+ const std::string& header);
+ virtual ~SocketStreamerAdapter();
+
+ protected:
+ class SocketStreamer : public StreamerAdapter::Streamer {
+ public:
+ SocketStreamer(SocketStreamerAdapter* const adapter,
+ const std::string& ip,
+ uint16_t port,
+ const std::string& header);
+ virtual ~SocketStreamer();
+
+ protected:
+ virtual bool Connect();
+ virtual void Disconnect();
+ virtual bool Send(protocol_handler::RawMessagePtr msg);
+
+ private:
std::string ip_;
+ uint16_t port_;
+ std::string header_;
- private:
- class Streamer : public threads::ThreadDelegate {
- public:
- /*
- * Default constructor
- *
- * @param server Server pointer
- */
- explicit Streamer(SocketStreamerAdapter* const server);
-
- /*
- * Destructor
- */
- ~Streamer();
-
- /*
- * Function called by thread on start
- */
- void threadMain();
-
- /*
- * Function called by thread on exit
- */
- void exitThreadMain();
-
- /*
- * Checks if server is ready
- *
- * @return TRUE if socket is ready otherwise FALSE
- */
- bool is_ready() const;
-
- /*
- * Starts server
- *
- */
- void start();
-
- /*
- * Stops server
- *
- */
- void stop();
-
- /*
- * Sends data to connected client
- *
- * @param block Pointer to the data
- */
- bool send(const ::protocol_handler::RawMessagePtr msg);
-
- private:
- SocketStreamerAdapter* const server_;
- int32_t new_socket_fd_;
- bool is_first_loop_;
- volatile bool is_client_connected_;
- volatile bool stop_flag_;
- sync_primitives::Lock thread_lock;
- DISALLOW_COPY_AND_ASSIGN(Streamer);
- };
-
- int32_t socket_fd_;
- bool is_ready_;
- Streamer* streamer_;
- threads::Thread* thread_;
- MessageQueue<protocol_handler::RawMessagePtr> messages_;
- DISALLOW_COPY_AND_ASSIGN(SocketStreamerAdapter);
+ int32_t socket_fd_;
+ int32_t send_socket_fd_;
+ bool is_first_frame_;
+ };
};
-} // namespace media_manager
+} // namespace media_manager
#endif // SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_SOCKET_STREAMER_ADAPTER_H_
diff --git a/src/components/media_manager/include/media_manager/streamer_adapter.h b/src/components/media_manager/include/media_manager/streamer_adapter.h
new file mode 100644
index 0000000000..30353b8d09
--- /dev/null
+++ b/src/components/media_manager/include/media_manager/streamer_adapter.h
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_STREAMER_ADAPTER_H_
+#define SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_STREAMER_ADAPTER_H_
+
+#include "media_manager/media_adapter_impl.h"
+#include "utils/message_queue.h"
+#include "utils/threads/thread.h"
+#include "utils/threads/thread_delegate.h"
+#include "utils/atomic_object.h"
+#include "utils/shared_ptr.h"
+#include "protocol/raw_message.h"
+
+namespace media_manager {
+
+/**
+ * Class StreamerAdapter represents media adapter
+ * for streaming data to some destination point
+ * (pipe, socket, file)
+ */
+class StreamerAdapter : public MediaAdapterImpl {
+ protected:
+ class Streamer;
+
+ public:
+ explicit StreamerAdapter(Streamer* const streamer);
+ virtual ~StreamerAdapter();
+
+ virtual void StartActivity(int32_t application_key);
+ virtual void StopActivity(int32_t application_key);
+ virtual void SendData(int32_t application_key,
+ const ::protocol_handler::RawMessagePtr msg);
+ virtual bool is_app_performing_activity(int32_t application_key) const;
+
+ protected:
+ // TODO(AN): APPLINK-15203 Use MessageLoopThread
+ class Streamer : public threads::ThreadDelegate {
+ public:
+ explicit Streamer(StreamerAdapter* const adapter);
+ virtual ~Streamer();
+
+ virtual void threadMain();
+ virtual void exitThreadMain();
+
+ protected:
+ virtual bool Connect() = 0;
+ virtual void Disconnect() = 0;
+ virtual bool Send(protocol_handler::RawMessagePtr msg) = 0;
+
+ private:
+ sync_primitives::atomic_bool stop_flag_;
+ StreamerAdapter* adapter_;
+
+ DISALLOW_COPY_AND_ASSIGN(Streamer);
+ };
+
+ private:
+ int32_t current_application_;
+ utils::MessageQueue<protocol_handler::RawMessagePtr> messages_;
+
+ Streamer* streamer_;
+ threads::Thread* thread_;
+
+ DISALLOW_COPY_AND_ASSIGN(StreamerAdapter);
+};
+
+typedef utils::SharedPtr<StreamerAdapter> StreamerAdapterPtr;
+
+} // namespace media_manager
+
+#endif // SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_STREAMER_ADAPTER_H_
diff --git a/src/components/media_manager/include/media_manager/streamer_listener.h b/src/components/media_manager/include/media_manager/streamer_listener.h
index d232582514..32ba167985 100644
--- a/src/components/media_manager/include/media_manager/streamer_listener.h
+++ b/src/components/media_manager/include/media_manager/streamer_listener.h
@@ -38,21 +38,24 @@
#include "utils/macro.h"
namespace media_manager {
+
+class MediaManager;
+
class StreamerListener : public MediaAdapterListener {
- public:
- StreamerListener();
- ~StreamerListener();
- virtual void OnDataReceived(
- int32_t application_key,
- const DataForListener& data);
- virtual void OnErrorReceived(
- int32_t application_key,
- const DataForListener& data);
- virtual void OnActivityStarted(int32_t application_key);
- virtual void OnActivityEnded(int32_t application_key);
- private:
- int32_t current_application_;
- DISALLOW_COPY_AND_ASSIGN(StreamerListener);
+ public:
+ StreamerListener(MediaManager& media_manager);
+ ~StreamerListener();
+ virtual void OnDataReceived(int32_t application_key,
+ const DataForListener& data);
+ virtual void OnErrorReceived(int32_t application_key,
+ const DataForListener& data);
+ virtual void OnActivityStarted(int32_t application_key);
+ virtual void OnActivityEnded(int32_t application_key);
+
+ private:
+ int32_t current_application_;
+ media_manager::MediaManager& media_manager_;
+ DISALLOW_COPY_AND_ASSIGN(StreamerListener);
};
} // namespace media_manager
diff --git a/src/components/media_manager/include/media_manager/video/file_video_streamer_adapter.h b/src/components/media_manager/include/media_manager/video/file_video_streamer_adapter.h
new file mode 100644
index 0000000000..1677b5ad34
--- /dev/null
+++ b/src/components/media_manager/include/media_manager/video/file_video_streamer_adapter.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2014-2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_VIDEO_FILE_VIDEO_STREAMER_ADAPTER_H_
+#define SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_VIDEO_FILE_VIDEO_STREAMER_ADAPTER_H_
+
+#include "media_manager/file_streamer_adapter.h"
+
+namespace media_manager {
+
+class FileVideoStreamerAdapter : public FileStreamerAdapter {
+ public:
+ FileVideoStreamerAdapter(const std::string& video_stream_file,
+ const std::string& app_storage_folder);
+ ~FileVideoStreamerAdapter();
+};
+
+} // namespace media_manager
+
+#endif // SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_VIDEO_FILE_VIDEO_STREAMER_ADAPTER_H_
diff --git a/src/components/media_manager/include/media_manager/video/pipe_video_streamer_adapter.h b/src/components/media_manager/include/media_manager/video/pipe_video_streamer_adapter.h
index 62447661a6..3bf5723572 100644
--- a/src/components/media_manager/include/media_manager/video/pipe_video_streamer_adapter.h
+++ b/src/components/media_manager/include/media_manager/video/pipe_video_streamer_adapter.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2014-2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -33,17 +33,15 @@
#ifndef SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_VIDEO_PIPE_VIDEO_STREAMER_ADAPTER_H_
#define SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_VIDEO_PIPE_VIDEO_STREAMER_ADAPTER_H_
-#include <string>
#include "media_manager/pipe_streamer_adapter.h"
namespace media_manager {
-class PipeVideoStreamerAdapter : public PipeStreamerAdapter {
- public:
- PipeVideoStreamerAdapter();
- ~PipeVideoStreamerAdapter();
- private:
- DISALLOW_COPY_AND_ASSIGN(PipeVideoStreamerAdapter);
+class PipeVideoStreamerAdapter : public PipeStreamerAdapter {
+ public:
+ PipeVideoStreamerAdapter(const std::string& named_video_pipe_path,
+ const std::string& app_storage_folder);
+ ~PipeVideoStreamerAdapter();
};
} // namespace media_manager
diff --git a/src/components/media_manager/include/media_manager/video/socket_video_streamer_adapter.h b/src/components/media_manager/include/media_manager/video/socket_video_streamer_adapter.h
index e5eefed12c..ad5739bd5f 100644
--- a/src/components/media_manager/include/media_manager/video/socket_video_streamer_adapter.h
+++ b/src/components/media_manager/include/media_manager/video/socket_video_streamer_adapter.h
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2014-2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -34,18 +34,19 @@
#define SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_VIDEO_SOCKET_VIDEO_STREAMER_ADAPTER_H_
#include <string>
+#include <stdint.h>
+
#include "media_manager/socket_streamer_adapter.h"
namespace media_manager {
-class SocketVideoStreamerAdapter : public SocketStreamerAdapter {
- public:
- SocketVideoStreamerAdapter();
- virtual ~SocketVideoStreamerAdapter();
- private:
- DISALLOW_COPY_AND_ASSIGN(SocketVideoStreamerAdapter);
+class SocketVideoStreamerAdapter : public SocketStreamerAdapter {
+ public:
+ SocketVideoStreamerAdapter(const std::string& server_address,
+ uint16_t video_streaming_port);
+ virtual ~SocketVideoStreamerAdapter();
};
-} // namespace media_manager
+} // namespace media_manager
#endif // SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_VIDEO_SOCKET_VIDEO_STREAMER_ADAPTER_H_
diff --git a/src/components/media_manager/include/media_manager/video/video_stream_to_file_adapter.h b/src/components/media_manager/include/media_manager/video/video_stream_to_file_adapter.h
deleted file mode 100644
index 8ec7fff803..0000000000
--- a/src/components/media_manager/include/media_manager/video/video_stream_to_file_adapter.h
+++ /dev/null
@@ -1,113 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_VIDEO_VIDEO_STREAM_TO_FILE_ADAPTER_H_
-#define SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_VIDEO_VIDEO_STREAM_TO_FILE_ADAPTER_H_
-
-#include <string>
-#include <fstream>
-#include "media_manager/media_adapter_impl.h"
-#include "utils/message_queue.h"
-#include "utils/threads/thread.h"
-#include "utils/threads/thread_delegate.h"
-
-namespace media_manager {
-
-using ::utils::MessageQueue;
-
-class VideoStreamToFileAdapter : public MediaAdapterImpl {
- public:
- explicit VideoStreamToFileAdapter(const std::string& file_name);
- virtual ~VideoStreamToFileAdapter();
- virtual void SendData(int32_t application_key,
- const ::protocol_handler::RawMessagePtr message);
- virtual void StartActivity(int32_t application_key);
- virtual void StopActivity(int32_t application_key);
- virtual bool is_app_performing_activity(int32_t application_key);
-
- /*
- * @brief Start streamer thread
- */
- virtual void Init();
-
- private:
- class Streamer : public threads::ThreadDelegate {
- public:
- /*
- * Default constructor
- *
- * @param server Server pointer
- */
- explicit Streamer(VideoStreamToFileAdapter* server);
-
- /*
- * Destructor
- */
- ~Streamer();
-
- /*
- * @brief Function called by thread on start
- */
- void threadMain();
-
- /*
- * @brief Function called by thread on exit
- */
- void exitThreadMain();
-
- /*
- * @brief Opens file
- */
- void open();
-
- /*
- * @brief Closes file
- */
- void close();
-
- private:
- VideoStreamToFileAdapter* server_;
- volatile bool stop_flag_;
- std::ofstream* file_stream_;
-
- DISALLOW_COPY_AND_ASSIGN(Streamer);
- };
-
- private:
- std::string file_name_;
- bool is_ready_;
- threads::Thread* thread_;
- MessageQueue<protocol_handler::RawMessagePtr> messages_;
-};
-} // namespace media_manager
-
-#endif // SRC_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_VIDEO_VIDEO_STREAM_TO_FILE_ADAPTER_H_
diff --git a/src/components/media_manager/src/audio/a2dp_source_player_adapter.cc b/src/components/media_manager/src/audio/a2dp_source_player_adapter.cc
index a6a36ef547..e5cd41c8c3 100644
--- a/src/components/media_manager/src/audio/a2dp_source_player_adapter.cc
+++ b/src/components/media_manager/src/audio/a2dp_source_player_adapter.cc
@@ -39,42 +39,43 @@
#include "utils/lock.h"
#include "utils/logger.h"
#include "connection_handler/connection_handler_impl.h"
+#include "protocol_handler/session_observer.h"
namespace media_manager {
-CREATE_LOGGERPTR_GLOBAL(logger_, "A2DPSourcePlayerAdapter");
+CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManager")
const static size_t BUFSIZE = 32;
class A2DPSourcePlayerAdapter::A2DPSourcePlayerThread
: public threads::ThreadDelegate {
- public:
- explicit A2DPSourcePlayerThread(const std::string& device);
+ public:
+ explicit A2DPSourcePlayerThread(const std::string& device);
- void threadMain();
+ void threadMain();
- void exitThreadMain();
+ void exitThreadMain();
- private:
- // The Sample format to use
- static const pa_sample_spec sSampleFormat_;
+ private:
+ // The Sample format to use
+ static const pa_sample_spec sSampleFormat_;
- pa_simple* s_in, *s_out;
- std::string device_;
- bool should_be_stopped_;
- sync_primitives::Lock should_be_stopped_lock_;
+ pa_simple* s_in, *s_out;
+ std::string device_;
+ bool should_be_stopped_;
+ sync_primitives::Lock should_be_stopped_lock_;
- void freeStreams();
+ void freeStreams();
- DISALLOW_COPY_AND_ASSIGN(A2DPSourcePlayerThread);
+ DISALLOW_COPY_AND_ASSIGN(A2DPSourcePlayerThread);
};
-A2DPSourcePlayerAdapter::A2DPSourcePlayerAdapter() {
-}
+A2DPSourcePlayerAdapter::A2DPSourcePlayerAdapter(
+ protocol_handler::SessionObserver& session_observer)
+ : session_observer_(session_observer) {}
A2DPSourcePlayerAdapter::~A2DPSourcePlayerAdapter() {
- for (SourcesMap::iterator it = sources_.begin();
- sources_.end() != it; ++it) {
+ for (SourcesMap::iterator it = sources_.begin(); sources_.end() != it; ++it) {
Pair pair = it->second;
pair.first->join();
delete pair.second;
@@ -84,20 +85,19 @@ A2DPSourcePlayerAdapter::~A2DPSourcePlayerAdapter() {
}
void A2DPSourcePlayerAdapter::StartActivity(int32_t application_key) {
- LOG4CXX_INFO(logger_, "Starting a2dp playing music for "
- << application_key << " application.");
+ LOG4CXX_INFO(logger_,
+ "Starting a2dp playing music for " << application_key
+ << " application.");
if (application_key != current_application_) {
current_application_ = application_key;
+ const protocol_handler::SessionObserver&
+ session_observer =->connection_handler().get_session_observer();
+
uint32_t device_id = 0;
- connection_handler::ConnectionHandlerImpl::instance()->
- GetDataOnSessionKey(application_key, 0, NULL, &device_id);
+ session_observer_.GetDataOnSessionKey(application_key, 0, NULL, &device_id);
std::string mac_adddress;
- connection_handler::ConnectionHandlerImpl::instance()->GetDataOnDeviceID(
- device_id,
- NULL,
- NULL,
- &mac_adddress);
+ session_observer_.GetDataOnDeviceID(device_id, NULL, NULL, &mac_adddress);
// TODO(PK): Convert mac_adddress to the
// following format : "bluez_source.XX_XX_XX_XX_XX_XX" if needed
@@ -105,16 +105,17 @@ void A2DPSourcePlayerAdapter::StartActivity(int32_t application_key) {
A2DPSourcePlayerThread* delegate =
new A2DPSourcePlayerAdapter::A2DPSourcePlayerThread(mac_adddress);
- threads::Thread* new_activity = threads::CreateThread(
- mac_adddress.c_str(), delegate);
+ threads::Thread* new_activity =
+ threads::CreateThread(mac_adddress.c_str(), delegate);
sources_[application_key] = Pair(new_activity, delegate);
new_activity->start();
}
}
void A2DPSourcePlayerAdapter::StopActivity(int32_t application_key) {
- LOG4CXX_INFO(logger_, "Stopping 2dp playing for "
- << application_key << " application.");
+ LOG4CXX_INFO(logger_,
+ "Stopping 2dp playing for " << application_key
+ << " application.");
if (application_key != current_application_) {
return;
}
@@ -128,23 +129,20 @@ void A2DPSourcePlayerAdapter::StopActivity(int32_t application_key) {
}
}
-bool A2DPSourcePlayerAdapter::is_app_performing_activity(int32_t
- application_key) {
+bool A2DPSourcePlayerAdapter::is_app_performing_activity(
+ int32_t application_key) const {
return (application_key == current_application_);
}
-const pa_sample_spec A2DPSourcePlayerAdapter::A2DPSourcePlayerThread::
-sSampleFormat_ = {
- /*format*/ PA_SAMPLE_S16LE,
- /*rate*/ 44100,
- /*channels*/ 2
-};
+const pa_sample_spec
+ A2DPSourcePlayerAdapter::A2DPSourcePlayerThread::sSampleFormat_ = {
+ /*format*/ PA_SAMPLE_S16LE,
+ /*rate*/ 44100,
+ /*channels*/ 2};
A2DPSourcePlayerAdapter::A2DPSourcePlayerThread::A2DPSourcePlayerThread(
- const std::string& device)
- : threads::ThreadDelegate(),
- device_(device) {
-}
+ const std::string& device)
+ : threads::ThreadDelegate(), device_(device) {}
void A2DPSourcePlayerAdapter::A2DPSourcePlayerThread::freeStreams() {
LOG4CXX_INFO(logger_, "Free streams in A2DPSourcePlayerThread.");
@@ -179,15 +177,29 @@ void A2DPSourcePlayerAdapter::A2DPSourcePlayerThread::threadMain() {
LOG4CXX_DEBUG(logger_, "Creating streams");
/* Create a new playback stream */
- if (!(s_out = pa_simple_new(NULL, "AudioManager", PA_STREAM_PLAYBACK, NULL,
- "playback", &sSampleFormat_, NULL, NULL, &error))) {
+ if (!(s_out = pa_simple_new(NULL,
+ "AudioManager",
+ PA_STREAM_PLAYBACK,
+ NULL,
+ "playback",
+ &sSampleFormat_,
+ NULL,
+ NULL,
+ &error))) {
LOG4CXX_ERROR(logger_, "pa_simple_new() failed: " << pa_strerror(error));
freeStreams();
return;
}
- if (!(s_in = pa_simple_new(NULL, "AudioManager", PA_STREAM_RECORD, a2dpSource,
- "record", &sSampleFormat_, NULL, NULL, &error))) {
+ if (!(s_in = pa_simple_new(NULL,
+ "AudioManager",
+ PA_STREAM_RECORD,
+ a2dpSource,
+ "record",
+ &sSampleFormat_,
+ NULL,
+ NULL,
+ &error))) {
LOG4CXX_ERROR(logger_, "pa_simple_new() failed: " << pa_strerror(error));
freeStreams();
return;
@@ -200,17 +212,17 @@ void A2DPSourcePlayerAdapter::A2DPSourcePlayerThread::threadMain() {
pa_usec_t latency;
- if ((latency = pa_simple_get_latency(s_in, &error)) == (pa_usec_t) - 1) {
- LOG4CXX_ERROR(logger_, "pa_simple_get_latency() failed: "
- << pa_strerror(error));
+ if ((latency = pa_simple_get_latency(s_in, &error)) == (pa_usec_t)-1) {
+ LOG4CXX_ERROR(logger_,
+ "pa_simple_get_latency() failed: " << pa_strerror(error));
break;
}
// LOG4CXX_INFO(logger_, "In: " << static_cast<float>(latency));
- if ((latency = pa_simple_get_latency(s_out, &error)) == (pa_usec_t) - 1) {
- LOG4CXX_ERROR(logger_, "pa_simple_get_latency() failed: "
- << pa_strerror(error));
+ if ((latency = pa_simple_get_latency(s_out, &error)) == (pa_usec_t)-1) {
+ LOG4CXX_ERROR(logger_,
+ "pa_simple_get_latency() failed: " << pa_strerror(error));
break;
}
@@ -223,8 +235,8 @@ void A2DPSourcePlayerAdapter::A2DPSourcePlayerThread::threadMain() {
/* ... and play it */
if (pa_simple_write(s_out, buf, sizeof(buf), &error) < 0) {
- LOG4CXX_ERROR(logger_, "pa_simple_write() failed: "
- << pa_strerror(error));
+ LOG4CXX_ERROR(logger_,
+ "pa_simple_write() failed: " << pa_strerror(error));
break;
}
diff --git a/src/components/media_manager/src/audio/audio_stream_sender_thread.cc b/src/components/media_manager/src/audio/audio_stream_sender_thread.cc
index a78ca8b49c..24b12cabad 100644
--- a/src/components/media_manager/src/audio/audio_stream_sender_thread.cc
+++ b/src/components/media_manager/src/audio/audio_stream_sender_thread.cc
@@ -30,23 +30,21 @@
// POSSIBILITY OF SUCH DAMAGE.
//
-
#if defined(OS_POSIX) && defined(OS_LINUX)
#include <pthread.h> // TODO(DK): Need to remove
#include <unistd.h>
#endif
-
#include <string>
#include <string.h>
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
#include "application_manager/mobile_command_factory.h"
#include "application_manager/application_impl.h"
#include "smart_objects/smart_object.h"
#include "interfaces/MOBILE_API.h"
#include "utils/file_system.h"
#include "utils/logger.h"
-
+#include "media_manager/media_manager_settings.h"
#include "media_manager/audio/audio_stream_sender_thread.h"
#include "application_manager/smart_object_keys.h"
#include "application_manager/message.h"
@@ -57,20 +55,22 @@ using sync_primitives::AutoLock;
const int32_t AudioStreamSenderThread::kAudioPassThruTimeout = 1;
const uint32_t kMqueueMessageSize = 4095;
-CREATE_LOGGERPTR_GLOBAL(logger_, "AudioPassThruThread")
+CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManager")
AudioStreamSenderThread::AudioStreamSenderThread(
- const std::string fileName, uint32_t session_key)
- : session_key_(session_key),
- fileName_(fileName),
- shouldBeStoped_(false),
- shouldBeStoped_lock_(),
- shouldBeStoped_cv_() {
+ const std::string& fileName,
+ uint32_t session_key,
+ application_manager::ApplicationManager& app_mngr)
+ : session_key_(session_key)
+ , fileName_(fileName)
+ , shouldBeStoped_(false)
+ , shouldBeStoped_lock_()
+ , shouldBeStoped_cv_()
+ , application_manager_(app_mngr) {
LOG4CXX_AUTO_TRACE(logger_);
}
-AudioStreamSenderThread::~AudioStreamSenderThread() {
-}
+AudioStreamSenderThread::~AudioStreamSenderThread() {}
void AudioStreamSenderThread::threadMain() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -82,7 +82,6 @@ void AudioStreamSenderThread::threadMain() {
shouldBeStoped_cv_.WaitFor(auto_lock, kAudioPassThruTimeout * 1000);
sendAudioChunkToMobile();
}
-
}
void AudioStreamSenderThread::sendAudioChunkToMobile() {
@@ -93,29 +92,28 @@ void AudioStreamSenderThread::sendAudioChunkToMobile() {
std::vector<uint8_t>::iterator to;
if (!file_system::ReadBinaryFile(fileName_, binaryData)) {
- LOG4CXX_ERROR_EXT(logger_, "Unable to read file." << fileName_);
+ LOG4CXX_ERROR(logger_, "Unable to read file." << fileName_);
return;
}
if (binaryData.empty()) {
- LOG4CXX_ERROR_EXT(logger_, "Binary data is empty.");
+ LOG4CXX_ERROR(logger_, "Binary data is empty.");
return;
}
- LOG4CXX_INFO_EXT(logger_, "offset = " << offset_);
+ LOG4CXX_INFO(logger_, "offset = " << offset_);
from = binaryData.begin() + offset_;
to = binaryData.end();
if (from < binaryData.end() /*from != binaryData.end()*/) {
- LOG4CXX_INFO_EXT(logger_, "from != binaryData.end()");
+ LOG4CXX_INFO(logger_, "from != binaryData.end()");
offset_ = offset_ + to - from;
std::vector<uint8_t> data(from, to);
- application_manager::ApplicationManagerImpl::instance()->
- SendAudioPassThroughNotification(session_key_, data);
+ application_manager_.SendAudioPassThroughNotification(session_key_, data);
binaryData.clear();
}
#if !defined(EXTENDED_MEDIA_MODE)
diff --git a/src/components/media_manager/src/audio/file_audio_streamer_adapter.cc b/src/components/media_manager/src/audio/file_audio_streamer_adapter.cc
new file mode 100644
index 0000000000..f632fa81af
--- /dev/null
+++ b/src/components/media_manager/src/audio/file_audio_streamer_adapter.cc
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2014-2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "media_manager/audio/file_audio_streamer_adapter.h"
+
+namespace media_manager {
+
+FileAudioStreamerAdapter::FileAudioStreamerAdapter(
+ const std::string& audio_stream_file, const std::string& app_storage_folder)
+ : FileStreamerAdapter(audio_stream_file, app_storage_folder) {}
+
+FileAudioStreamerAdapter::~FileAudioStreamerAdapter() {}
+
+} // namespace media_manager
diff --git a/src/components/media_manager/src/audio/from_mic_recorder_adapter.cc b/src/components/media_manager/src/audio/from_mic_recorder_adapter.cc
index ef9d5b8de6..d9735fcbbc 100644
--- a/src/components/media_manager/src/audio/from_mic_recorder_adapter.cc
+++ b/src/components/media_manager/src/audio/from_mic_recorder_adapter.cc
@@ -38,15 +38,13 @@
namespace media_manager {
-CREATE_LOGGERPTR_GLOBAL(logger_, "FromMicRecorderAdapter")
+CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManager")
FromMicRecorderAdapter::FromMicRecorderAdapter()
- : recorder_thread_(NULL)
- , output_file_("default_recorded_audio.wav")
- , kDefaultDuration(1000)
- , duration_(kDefaultDuration) {
-
-}
+ : recorder_thread_(NULL)
+ , output_file_("default_recorded_audio.wav")
+ , kDefaultDuration(1000)
+ , duration_(kDefaultDuration) {}
FromMicRecorderAdapter::~FromMicRecorderAdapter() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -60,18 +58,16 @@ FromMicRecorderAdapter::~FromMicRecorderAdapter() {
void FromMicRecorderAdapter::StartActivity(int32_t application_key) {
LOG4CXX_DEBUG(logger_, "Start with app " << application_key);
if (application_key == current_application_) {
- LOG4CXX_WARN(logger_, "Running recording from mic for "
- << current_application_);
+ LOG4CXX_WARN(logger_,
+ "Running recording from mic for " << current_application_);
return;
}
-// Todd: No gstreamer recorder thread
+ // Todd: No gstreamer recorder thread
if (!recorder_thread_) {
FromMicToFileRecorderThread* thread_delegate =
- new FromMicToFileRecorderThread(
- output_file_, duration_);
- recorder_thread_ = threads::CreateThread("MicrophoneRec",
- thread_delegate);
+ new FromMicToFileRecorderThread(output_file_, duration_);
+ recorder_thread_ = threads::CreateThread("MicrophoneRec", thread_delegate);
}
if (NULL != recorder_thread_) {
@@ -81,11 +77,11 @@ void FromMicRecorderAdapter::StartActivity(int32_t application_key) {
}
void FromMicRecorderAdapter::StopActivity(int32_t application_key) {
- LOG4CXX_INFO(logger_, "FromMicRecorderAdapter::StopActivity "
- << application_key);
+ LOG4CXX_INFO(logger_,
+ "FromMicRecorderAdapter::StopActivity " << application_key);
if (application_key != current_application_) {
- LOG4CXX_WARN(logger_, "Running activity on other app key "
- << current_application_);
+ LOG4CXX_WARN(logger_,
+ "Running activity on other app key " << current_application_);
return;
}
@@ -98,8 +94,8 @@ void FromMicRecorderAdapter::StopActivity(int32_t application_key) {
current_application_ = 0;
}
-bool FromMicRecorderAdapter::is_app_performing_activity(int32_t
- application_key) {
+bool FromMicRecorderAdapter::is_app_performing_activity(
+ int32_t application_key) const {
return (application_key == current_application_);
}
diff --git a/src/components/media_manager/src/audio/from_mic_recorder_listener.cc b/src/components/media_manager/src/audio/from_mic_recorder_listener.cc
index 3718e82c60..a02ec17f90 100644
--- a/src/components/media_manager/src/audio/from_mic_recorder_listener.cc
+++ b/src/components/media_manager/src/audio/from_mic_recorder_listener.cc
@@ -37,13 +37,12 @@
namespace media_manager {
-CREATE_LOGGERPTR_GLOBAL(logger_, "FromMicRecorderListener")
+CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManager")
FromMicRecorderListener::FromMicRecorderListener(
- const std::string& file_name)
- : reader_(NULL)
- , file_name_(file_name) {
-}
+ const std::string& file_name,
+ application_manager::ApplicationManager& app_mngr)
+ : reader_(NULL), file_name_(file_name), application_manager_(app_mngr) {}
FromMicRecorderListener::~FromMicRecorderListener() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -54,25 +53,22 @@ FromMicRecorderListener::~FromMicRecorderListener() {
}
}
-void FromMicRecorderListener::OnDataReceived(
- int32_t application_key,
- const DataForListener& data) {
-}
+void FromMicRecorderListener::OnDataReceived(int32_t application_key,
+ const DataForListener& data) {}
-void FromMicRecorderListener::OnErrorReceived(
- int32_t application_key,
- const DataForListener& data) {
-}
+void FromMicRecorderListener::OnErrorReceived(int32_t application_key,
+ const DataForListener& data) {}
void FromMicRecorderListener::OnActivityStarted(int32_t application_key) {
- LOG4CXX_INFO(logger_, "FromMicRecorderListener::OnActivityStarted "
- << application_key);
+ LOG4CXX_INFO(logger_,
+ "FromMicRecorderListener::OnActivityStarted "
+ << application_key);
if (application_key == current_application_) {
return;
}
if (!reader_) {
- AudioStreamSenderThread* thread_delegate =
- new AudioStreamSenderThread(file_name_, application_key);
+ AudioStreamSenderThread* thread_delegate = new AudioStreamSenderThread(
+ file_name_, application_key, application_manager_);
reader_ = threads::CreateThread("RecorderSender", thread_delegate);
}
if (reader_) {
@@ -82,11 +78,12 @@ void FromMicRecorderListener::OnActivityStarted(int32_t application_key) {
}
void FromMicRecorderListener::OnActivityEnded(int32_t application_key) {
- LOG4CXX_INFO(logger_, "FromMicRecorderListener::OnActivityEnded "
- << application_key);
+ LOG4CXX_INFO(logger_,
+ "FromMicRecorderListener::OnActivityEnded " << application_key);
if (application_key != current_application_) {
- LOG4CXX_WARN(logger_, "Not performing activity on " << application_key
- << " but on " << current_application_);
+ LOG4CXX_WARN(logger_,
+ "Not performing activity on " << application_key << " but on "
+ << current_application_);
return;
}
if (reader_) {
diff --git a/src/components/media_manager/src/audio/from_mic_to_file_recorder_thread.cc b/src/components/media_manager/src/audio/from_mic_to_file_recorder_thread.cc
index 88c358a494..0239795d75 100644
--- a/src/components/media_manager/src/audio/from_mic_to_file_recorder_thread.cc
+++ b/src/components/media_manager/src/audio/from_mic_to_file_recorder_thread.cc
@@ -37,19 +37,19 @@
namespace media_manager {
-CREATE_LOGGERPTR_GLOBAL(logger_, "FromMicToFileRecorderThread")
+CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManager")
GMainLoop* FromMicToFileRecorderThread::loop = NULL;
FromMicToFileRecorderThread::FromMicToFileRecorderThread(
- const std::string& output_file, int32_t duration)
- : threads::ThreadDelegate(),
- argc_(5),
- argv_(NULL),
- oKey_("-o"),
- tKey_("-t"),
- sleepThread_(NULL),
- outputFileName_(output_file) {
+ const std::string& output_file, int32_t duration)
+ : threads::ThreadDelegate()
+ , argc_(5)
+ , argv_(NULL)
+ , oKey_("-o")
+ , tKey_("-t")
+ , sleepThread_(NULL)
+ , outputFileName_(output_file) {
LOG4CXX_AUTO_TRACE(logger_);
set_record_duration(duration);
}
@@ -64,7 +64,7 @@ FromMicToFileRecorderThread::~FromMicToFileRecorderThread() {
}
void FromMicToFileRecorderThread::set_output_file(
- const std::string& output_file) {
+ const std::string& output_file) {
LOG4CXX_AUTO_TRACE(logger_);
outputFileName_ = output_file;
}
@@ -80,7 +80,7 @@ void FromMicToFileRecorderThread::set_record_duration(int32_t duration) {
void FromMicToFileRecorderThread::initArgs() {
LOG4CXX_AUTO_TRACE(logger_);
- argv_ = new gchar*[argc_];
+ argv_ = new gchar* [argc_];
argv_[0] = new gchar[14];
argv_[1] = new gchar[3];
@@ -114,20 +114,29 @@ void FromMicToFileRecorderThread::threadMain() {
gint duration = -1;
GOptionContext* context = NULL;
GError* err = NULL;
- GOptionEntry entries[] = { {
- "device", 'd', 0, G_OPTION_ARG_FILENAME, &device,
- "device file (Default: hw:0,0)", "SRC"
- }, {
- "output", 'o', 0, G_OPTION_ARG_FILENAME, &outfile,
- "save output of the stream to DEST", "DEST"
- }, {
- "duration", 't', 0, G_OPTION_ARG_INT, &duration,
- "length of time in seconds to capture", "int32_t"
- }, {
- NULL
- }
- };
-#ifndef GLIB_VERSION_2_32 // g_thread_init() does nothing since 2.32
+ GOptionEntry entries[] = {{"device",
+ 'd',
+ 0,
+ G_OPTION_ARG_FILENAME,
+ &device,
+ "device file (Default: hw:0,0)",
+ "SRC"},
+ {"output",
+ 'o',
+ 0,
+ G_OPTION_ARG_FILENAME,
+ &outfile,
+ "save output of the stream to DEST",
+ "DEST"},
+ {"duration",
+ 't',
+ 0,
+ G_OPTION_ARG_INT,
+ &duration,
+ "length of time in seconds to capture",
+ "int32_t"},
+ {NULL}};
+#ifndef GLIB_VERSION_2_32 // g_thread_init() does nothing since 2.32
if (!g_thread_supported()) {
g_thread_init(NULL);
}
@@ -156,10 +165,10 @@ void FromMicToFileRecorderThread::threadMain() {
// Set up error handling
bus = gst_pipeline_get_bus(GST_PIPELINE(pipeline));
- gst_bus_add_watch(bus,
- reinterpret_cast<int32_t (*)(_GstBus*, _GstMessage*, void*)>
- (recvmsg),
- NULL);
+ gst_bus_add_watch(
+ bus,
+ reinterpret_cast<int32_t (*)(_GstBus*, _GstMessage*, void*)>(recvmsg),
+ NULL);
gst_object_unref(bus);
// Create all of the elements to be added to the pipeline
@@ -199,7 +208,7 @@ void FromMicToFileRecorderThread::threadMain() {
g_option_context_free(context);
if (argv_) {
- delete [] argv_;
+ delete[] argv_;
argv_ = NULL;
}
return;
@@ -213,7 +222,8 @@ void FromMicToFileRecorderThread::threadMain() {
timeout.pipeline = pipeline;
timeout.duration = duration;
- sleepThread_ = threads::CreateThread("SleepThread", new SleepThreadDelegate(timeout));
+ sleepThread_ =
+ threads::CreateThread("SleepThread", new SleepThreadDelegate(timeout));
sleepThread_->start();
}
@@ -229,18 +239,16 @@ void FromMicToFileRecorderThread::threadMain() {
g_option_context_free(context);
if (argv_) {
- delete [] argv_;
+ delete[] argv_;
argv_ = NULL;
}
loop = NULL;
}
-FromMicToFileRecorderThread::SleepThreadDelegate::SleepThreadDelegate(GstTimeout
- timeout)
- : threads::ThreadDelegate(),
- timeout_(timeout) {
-}
+FromMicToFileRecorderThread::SleepThreadDelegate::SleepThreadDelegate(
+ GstTimeout timeout)
+ : threads::ThreadDelegate(), timeout_(timeout) {}
void FromMicToFileRecorderThread::SleepThreadDelegate::threadMain() {
LOG4CXX_TRACE(logger_, "Sleep for " << timeout_.duration << " seconds");
diff --git a/src/components/media_manager/src/audio/pipe_audio_streamer_adapter.cc b/src/components/media_manager/src/audio/pipe_audio_streamer_adapter.cc
index 5c120397cf..2220c08b26 100644
--- a/src/components/media_manager/src/audio/pipe_audio_streamer_adapter.cc
+++ b/src/components/media_manager/src/audio/pipe_audio_streamer_adapter.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2014-2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -31,22 +31,14 @@
*/
#include "media_manager/audio/pipe_audio_streamer_adapter.h"
-#include "config_profile/profile.h"
-#include "utils/logger.h"
namespace media_manager {
-CREATE_LOGGERPTR_GLOBAL(logger, "PipeAudioStreamerAdapter")
+PipeAudioStreamerAdapter::PipeAudioStreamerAdapter(
+ const std::string& named_audio_pipe_path,
+ const std::string& app_storage_folder)
+ : PipeStreamerAdapter(named_audio_pipe_path, app_storage_folder) {}
-PipeAudioStreamerAdapter::PipeAudioStreamerAdapter() {
- LOG4CXX_AUTO_TRACE(logger);
- named_pipe_path_ = profile::Profile::instance()->named_audio_pipe_path();
-
- Init();
-}
-
-PipeAudioStreamerAdapter::~PipeAudioStreamerAdapter() {
- LOG4CXX_INFO(logger, "PipeAudioStreamerAdapter::~PipeAudioStreamerAdapter");
-}
+PipeAudioStreamerAdapter::~PipeAudioStreamerAdapter() {}
} // namespace media_manager
diff --git a/src/components/media_manager/src/audio/socket_audio_streamer_adapter.cc b/src/components/media_manager/src/audio/socket_audio_streamer_adapter.cc
index 06dc877d89..429fab01b3 100644
--- a/src/components/media_manager/src/audio/socket_audio_streamer_adapter.cc
+++ b/src/components/media_manager/src/audio/socket_audio_streamer_adapter.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014 Ford Motor Company
+ * Copyright (c) 2014-2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,22 +30,24 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include "config_profile/profile.h"
+#include <string>
#include "media_manager/audio/socket_audio_streamer_adapter.h"
-#include "utils/logger.h"
+
+namespace {
+const std::string kHeader =
+ "HTTP/1.1 200 OK\r\n"
+ "Connection: Keep-Alive\r\n"
+ "Keep-Alive: timeout=15, max=300\r\n"
+ "Server: SDL\r\n"
+ "Content-Type: video/mp4\r\n\r\n";
+}
namespace media_manager {
-CREATE_LOGGERPTR_GLOBAL(logger, "SocketAudioStreamerAdapter")
+SocketAudioStreamerAdapter::SocketAudioStreamerAdapter(
+ const std::string& server_address, uint16_t audio_streaming_port)
+ : SocketStreamerAdapter(server_address, audio_streaming_port, kHeader) {}
-SocketAudioStreamerAdapter::SocketAudioStreamerAdapter() {
- LOG4CXX_AUTO_TRACE(logger);
- port_ = profile::Profile::instance()->audio_streaming_port();
- ip_ = profile::Profile::instance()->server_address();
+SocketAudioStreamerAdapter::~SocketAudioStreamerAdapter() {}
- Init();
-}
-
-SocketAudioStreamerAdapter::~SocketAudioStreamerAdapter() {
-}
} // namespace media_manager
diff --git a/src/components/media_manager/src/file_streamer_adapter.cc b/src/components/media_manager/src/file_streamer_adapter.cc
new file mode 100644
index 0000000000..3418f7d963
--- /dev/null
+++ b/src/components/media_manager/src/file_streamer_adapter.cc
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "utils/logger.h"
+#include "utils/file_system.h"
+#include "media_manager/file_streamer_adapter.h"
+
+namespace media_manager {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "FileStreamerAdapter")
+
+FileStreamerAdapter::FileStreamerAdapter(const std::string& file_name,
+ const std::string& app_storage_folder)
+ : StreamerAdapter(new FileStreamer(this, file_name, app_storage_folder)) {}
+
+FileStreamerAdapter::~FileStreamerAdapter() {}
+
+FileStreamerAdapter::FileStreamer::FileStreamer(
+ FileStreamerAdapter* const adapter,
+ const std::string& file_name,
+ const std::string& app_storage_folder)
+ : Streamer(adapter)
+ , file_name_(file_name)
+ , app_storage_folder_(app_storage_folder)
+ , file_stream_(NULL) {}
+
+FileStreamerAdapter::FileStreamer::~FileStreamer() {}
+
+bool FileStreamerAdapter::FileStreamer::Connect() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!file_system::CreateDirectoryRecursively(app_storage_folder_)) {
+ LOG4CXX_ERROR(logger_, "Cannot create app folder");
+ return false;
+ }
+
+ file_stream_ = file_system::Open(file_name_);
+ if (!file_stream_) {
+ LOG4CXX_ERROR(logger_, "Cannot open file stream " << file_name_);
+ return false;
+ }
+
+ LOG4CXX_INFO(logger_, "File " << file_name_ << " was successfuly opened");
+ return true;
+}
+
+void FileStreamerAdapter::FileStreamer::Disconnect() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (file_stream_) {
+ file_system::Close(file_stream_);
+ delete file_stream_;
+ file_stream_ = NULL;
+ }
+ file_system::DeleteFile(file_name_);
+}
+
+bool FileStreamerAdapter::FileStreamer::Send(
+ protocol_handler::RawMessagePtr msg) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!file_stream_) {
+ LOG4CXX_ERROR(logger_, "File stream not found " << file_name_);
+ return false;
+ }
+
+ if (!file_system::Write(file_stream_, msg->data(), msg->data_size())) {
+ LOG4CXX_ERROR(logger_, "Failed writing data to file " << file_name_);
+ return false;
+ }
+
+ LOG4CXX_INFO(logger_, "Streamer::sent " << msg->data_size());
+ return true;
+}
+
+} // namespace media_manager
diff --git a/src/components/media_manager/src/media_adapter_impl.cc b/src/components/media_manager/src/media_adapter_impl.cc
index 257801ffd8..cf15a7af97 100644
--- a/src/components/media_manager/src/media_adapter_impl.cc
+++ b/src/components/media_manager/src/media_adapter_impl.cc
@@ -35,11 +35,9 @@
namespace media_manager {
-CREATE_LOGGERPTR_GLOBAL(logger_, "MediaAdapterImpl")
+CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManager")
-MediaAdapterImpl::MediaAdapterImpl()
- : current_application_(0) {
-}
+MediaAdapterImpl::MediaAdapterImpl() : current_application_(0) {}
MediaAdapterImpl::~MediaAdapterImpl() {
media_listeners_.clear();
diff --git a/src/components/media_manager/src/media_manager_impl.cc b/src/components/media_manager/src/media_manager_impl.cc
index 61b2c5bb92..e531894b27 100644
--- a/src/components/media_manager/src/media_manager_impl.cc
+++ b/src/components/media_manager/src/media_manager_impl.cc
@@ -30,13 +30,12 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include "config_profile/profile.h"
#include "media_manager/media_manager_impl.h"
#include "media_manager/audio/from_mic_recorder_listener.h"
#include "media_manager/streamer_listener.h"
#include "application_manager/message_helper.h"
#include "application_manager/application.h"
-#include "application_manager/application_manager_impl.h"
+#include "application_manager/application_manager.h"
#include "application_manager/application_impl.h"
#include "protocol_handler/protocol_handler.h"
#include "utils/file_system.h"
@@ -50,19 +49,22 @@
#include "media_manager/audio/socket_audio_streamer_adapter.h"
#include "media_manager/video/pipe_video_streamer_adapter.h"
#include "media_manager/audio/pipe_audio_streamer_adapter.h"
-#include "media_manager/video/video_stream_to_file_adapter.h"
+#include "media_manager/video/file_video_streamer_adapter.h"
+#include "media_manager/audio/file_audio_streamer_adapter.h"
+#include "media_manager/media_manager_settings.h"
namespace media_manager {
-using profile::Profile;
-using timer::TimerThread;
+CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManager")
-CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManagerImpl")
-
-MediaManagerImpl::MediaManagerImpl()
- : protocol_handler_(NULL)
- , a2dp_player_(NULL)
- , from_mic_recorder_(NULL) {
+MediaManagerImpl::MediaManagerImpl(
+ application_manager::ApplicationManager& application_manager,
+ const MediaManagerSettings& settings)
+ : settings_(settings)
+ , protocol_handler_(NULL)
+ , a2dp_player_(NULL)
+ , from_mic_recorder_(NULL)
+ , application_manager_(application_manager) {
Init();
}
@@ -78,36 +80,69 @@ MediaManagerImpl::~MediaManagerImpl() {
}
}
+#ifdef BUILD_TESTS
+void MediaManagerImpl::set_mock_a2dp_player(MediaAdapter* media_adapter) {
+ a2dp_player_ = media_adapter;
+}
+
+void MediaManagerImpl::set_mock_mic_listener(MediaListenerPtr media_listener) {
+ from_mic_listener_ = media_listener;
+}
+
+#ifdef EXTENDED_MEDIA_MODE
+void MediaManagerImpl::set_mock_mic_recorder(MediaAdapterImpl* media_adapter) {
+ from_mic_recorder_ = media_adapter;
+}
+
+#endif // EXTENDED_MEDIA_MODE
+
+void MediaManagerImpl::set_mock_streamer(protocol_handler::ServiceType stype,
+ MediaAdapterImpl* mock_stream) {
+ streamer_[stype] = mock_stream;
+}
+
+void MediaManagerImpl::set_mock_streamer_listener(
+ protocol_handler::ServiceType stype, MediaAdapterListener* mock_stream) {
+ streamer_listener_[stype] = mock_stream;
+}
+
+#endif // BUILD_TESTS
+
void MediaManagerImpl::Init() {
using namespace protocol_handler;
LOG4CXX_INFO(logger_, "MediaManagerImpl::Init()");
#if defined(EXTENDED_MEDIA_MODE)
LOG4CXX_INFO(logger_, "Called Init with default configuration.");
- a2dp_player_ = new A2DPSourcePlayerAdapter();
+ a2dp_player_ =
+ new A2DPSourcePlayerAdapter(protocol_handler_->get_session_observer());
from_mic_recorder_ = new FromMicRecorderAdapter();
#endif
- if ("socket" == profile::Profile::instance()->video_server_type()) {
- streamer_[ServiceType::kMobileNav] = new SocketVideoStreamerAdapter();
- } else if ("pipe" == profile::Profile::instance()->video_server_type()) {
- streamer_[ServiceType::kMobileNav] = new PipeVideoStreamerAdapter();
- } else if ("file" == profile::Profile::instance()->video_server_type()) {
- streamer_[ServiceType::kMobileNav] = new VideoStreamToFileAdapter(
- profile::Profile::instance()->video_stream_file());
+ if ("socket" == settings().video_server_type()) {
+ streamer_[ServiceType::kMobileNav] = new SocketVideoStreamerAdapter(
+ settings().server_address(), settings().video_streaming_port());
+ } else if ("pipe" == settings().video_server_type()) {
+ streamer_[ServiceType::kMobileNav] = new PipeVideoStreamerAdapter(
+ settings().named_video_pipe_path(), settings().app_storage_folder());
+ } else if ("file" == settings().video_server_type()) {
+ streamer_[ServiceType::kMobileNav] = new FileVideoStreamerAdapter(
+ settings().video_stream_file(), settings().app_storage_folder());
}
- if ("socket" == profile::Profile::instance()->audio_server_type()) {
- streamer_[ServiceType::kAudio] = new SocketAudioStreamerAdapter();
- } else if ("pipe" == profile::Profile::instance()->audio_server_type()) {
- streamer_[ServiceType::kAudio] = new PipeAudioStreamerAdapter();
- } else if ("file" == profile::Profile::instance()->audio_server_type()) {
- streamer_[ServiceType::kAudio] = new VideoStreamToFileAdapter(
- profile::Profile::instance()->audio_stream_file());
+ if ("socket" == settings().audio_server_type()) {
+ streamer_[ServiceType::kAudio] = new SocketAudioStreamerAdapter(
+ settings().server_address(), settings().audio_streaming_port());
+ } else if ("pipe" == settings().audio_server_type()) {
+ streamer_[ServiceType::kAudio] = new PipeAudioStreamerAdapter(
+ settings().named_audio_pipe_path(), settings().app_storage_folder());
+ } else if ("file" == settings().audio_server_type()) {
+ streamer_[ServiceType::kAudio] = new FileAudioStreamerAdapter(
+ settings().audio_stream_file(), settings().app_storage_folder());
}
- streamer_listener_[ServiceType::kMobileNav] = new StreamerListener();
- streamer_listener_[ServiceType::kAudio] = new StreamerListener();
+ streamer_listener_[ServiceType::kMobileNav] = new StreamerListener(*this);
+ streamer_listener_[ServiceType::kAudio] = new StreamerListener(*this);
if (streamer_[ServiceType::kMobileNav]) {
streamer_[ServiceType::kMobileNav]->AddListener(
@@ -134,27 +169,25 @@ void MediaManagerImpl::StopA2DPSource(int32_t application_key) {
}
}
-void MediaManagerImpl::StartMicrophoneRecording(
- int32_t application_key,
- const std::string& output_file,
- int32_t duration) {
- LOG4CXX_INFO(logger_, "MediaManagerImpl::StartMicrophoneRecording to "
- << output_file);
+void MediaManagerImpl::StartMicrophoneRecording(int32_t application_key,
+ const std::string& output_file,
+ int32_t duration) {
+ LOG4CXX_INFO(logger_,
+ "MediaManagerImpl::StartMicrophoneRecording to " << output_file);
application_manager::ApplicationSharedPtr app =
- application_manager::ApplicationManagerImpl::instance()->
- application(application_key);
- std::string file_path =
- profile::Profile::instance()->app_storage_folder();
+ application_manager_.application(application_key);
+ std::string file_path = settings().app_storage_folder();
file_path += "/";
file_path += output_file;
- from_mic_listener_ = new FromMicRecorderListener(file_path);
-#if defined(EXTENDED_MEDIA_MODE)
+ from_mic_listener_ =
+ new FromMicRecorderListener(file_path, application_manager_);
+#ifdef EXTENDED_MEDIA_MODE
if (from_mic_recorder_) {
from_mic_recorder_->AddListener(from_mic_listener_);
(static_cast<FromMicRecorderAdapter*>(from_mic_recorder_))
- ->set_output_file(file_path);
+ ->set_output_file(file_path);
(static_cast<FromMicRecorderAdapter*>(from_mic_recorder_))
- ->set_duration(duration);
+ ->set_duration(duration);
from_mic_recorder_->StartActivity(application_key);
}
#else
@@ -162,25 +195,23 @@ void MediaManagerImpl::StartMicrophoneRecording(
LOG4CXX_INFO(logger_, "File " << output_file << " exists, removing");
if (file_system::DeleteFile(file_path)) {
LOG4CXX_INFO(logger_, "File " << output_file << " removed");
- }
- else {
+ } else {
LOG4CXX_WARN(logger_, "Could not remove file " << output_file);
}
}
- const std::string record_file_source =
- profile::Profile::instance()->app_resourse_folder() + "/" +
- profile::Profile::instance()->recording_file_source();
+ const std::string record_file_source = settings().app_resource_folder() +
+ "/" +
+ settings().recording_file_source();
std::vector<uint8_t> buf;
if (file_system::ReadBinaryFile(record_file_source, buf)) {
if (file_system::Write(file_path, buf)) {
LOG4CXX_INFO(logger_,
- "File " << record_file_source << " copied to " << output_file);
- }
- else {
+ "File " << record_file_source << " copied to "
+ << output_file);
+ } else {
LOG4CXX_WARN(logger_, "Could not write to file " << output_file);
}
- }
- else {
+ } else {
LOG4CXX_WARN(logger_, "Could not read file " << record_file_source);
}
#endif
@@ -223,7 +254,7 @@ void MediaManagerImpl::StopStreaming(
}
void MediaManagerImpl::SetProtocolHandler(
- protocol_handler::ProtocolHandler* protocol_handler) {
+ protocol_handler::ProtocolHandler* protocol_handler) {
protocol_handler_ = protocol_handler;
}
@@ -238,21 +269,19 @@ void MediaManagerImpl::OnMessageReceived(
const ServiceType service_type = message->service_type();
if (Compare<ServiceType, NEQ, ALL>(
- service_type, ServiceType::kMobileNav, ServiceType::kAudio)) {
+ service_type, ServiceType::kMobileNav, ServiceType::kAudio)) {
LOG4CXX_DEBUG(logger_, "Unsupported service type in MediaManager");
return;
}
- ApplicationManagerImpl* app_mgr = ApplicationManagerImpl::instance();
- DCHECK_OR_RETURN_VOID(app_mgr);
-
- if (!app_mgr->CanAppStream(streaming_app_id, service_type)) {
- app_mgr->ForbidStreaming(streaming_app_id);
- LOG4CXX_ERROR(logger_, "The application trying to stream when it should not.");
+ if (!application_manager_.CanAppStream(streaming_app_id, service_type)) {
+ application_manager_.ForbidStreaming(streaming_app_id);
+ LOG4CXX_ERROR(logger_,
+ "The application trying to stream when it should not.");
return;
}
- ApplicationSharedPtr app = app_mgr->application(streaming_app_id);
+ ApplicationSharedPtr app = application_manager_.application(streaming_app_id);
if (app) {
app->WakeUpStreaming(service_type);
streamer_[service_type]->SendData(streaming_app_id, message);
@@ -260,15 +289,17 @@ void MediaManagerImpl::OnMessageReceived(
}
void MediaManagerImpl::OnMobileMessageSent(
- const ::protocol_handler::RawMessagePtr message) {
-}
+ const ::protocol_handler::RawMessagePtr message) {}
void MediaManagerImpl::FramesProcessed(int32_t application_key,
int32_t frame_number) {
if (protocol_handler_) {
- protocol_handler_->SendFramesNumber(application_key,
- frame_number);
+ protocol_handler_->SendFramesNumber(application_key, frame_number);
}
}
+const MediaManagerSettings& MediaManagerImpl::settings() const {
+ return settings_;
+}
+
} // namespace media_manager
diff --git a/src/components/media_manager/src/pipe_streamer_adapter.cc b/src/components/media_manager/src/pipe_streamer_adapter.cc
index 5990428c68..8bf14a546e 100644
--- a/src/components/media_manager/src/pipe_streamer_adapter.cc
+++ b/src/components/media_manager/src/pipe_streamer_adapter.cc
@@ -36,195 +36,89 @@
#include <unistd.h>
#include "utils/logger.h"
#include "utils/file_system.h"
-#include "config_profile/profile.h"
#include "media_manager/pipe_streamer_adapter.h"
namespace media_manager {
CREATE_LOGGERPTR_GLOBAL(logger_, "PipeStreamerAdapter")
-PipeStreamerAdapter::PipeStreamerAdapter()
- : is_ready_(false),
- thread_(threads::CreateThread("PipeStreamer", new Streamer(this))),
- messages_() {
- LOG4CXX_AUTO_TRACE(logger_);
-}
-
-PipeStreamerAdapter::~PipeStreamerAdapter() {
- LOG4CXX_AUTO_TRACE(logger_);
-
- if ((0 != current_application_ ) && (is_ready_)) {
- StopActivity(current_application_);
- }
-
- thread_->join();
- delete thread_->delegate();
- threads::DeleteThread(thread_);
-}
-
-void PipeStreamerAdapter::SendData(
- int32_t application_key,
- const ::protocol_handler::RawMessagePtr message) {
- LOG4CXX_AUTO_TRACE(logger_);
-
- if (application_key != current_application_) {
- LOG4CXX_WARN(logger_, "Wrong application " << application_key);
+PipeStreamerAdapter::PipeStreamerAdapter(const std::string& named_pipe_path,
+ const std::string& app_storage_folder)
+ : StreamerAdapter(
+ new PipeStreamer(this, named_pipe_path, app_storage_folder)) {}
+
+PipeStreamerAdapter::~PipeStreamerAdapter() {}
+
+PipeStreamerAdapter::PipeStreamer::PipeStreamer(
+ PipeStreamerAdapter* const adapter,
+ const std::string& named_pipe_path,
+ const std::string& app_storage_folder)
+ : Streamer(adapter)
+ , named_pipe_path_(named_pipe_path)
+ , app_storage_folder_(app_storage_folder)
+ , pipe_fd_(0) {
+ if (!file_system::CreateDirectoryRecursively(app_storage_folder_)) {
+ LOG4CXX_ERROR(logger_,
+ "Cannot create app storage folder " << app_storage_folder_);
return;
}
-
- if (is_ready_) {
- messages_.push(message);
+ if ((mkfifo(named_pipe_path_.c_str(), S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) <
+ 0) &&
+ (errno != EEXIST)) {
+ LOG4CXX_ERROR(logger_, "Cannot create pipe " << named_pipe_path_);
+ } else {
+ LOG4CXX_INFO(logger_,
+ "Pipe " << named_pipe_path_ << " was successfully created");
}
}
-
-void PipeStreamerAdapter::StartActivity(int32_t application_key) {
- LOG4CXX_AUTO_TRACE(logger_);
-
- if (application_key == current_application_) {
- LOG4CXX_WARN(logger_, "Already started activity for " << application_key);
- return;
+PipeStreamerAdapter::PipeStreamer::~PipeStreamer() {
+ if (0 == unlink(named_pipe_path_.c_str())) {
+ LOG4CXX_INFO(logger_, "Pipe " << named_pipe_path_ << " was removed");
+ } else {
+ LOG4CXX_ERROR(logger_, "Error removing pipe " << named_pipe_path_);
}
-
- current_application_ = application_key;
- is_ready_ = true;
-
- for (std::set<MediaListenerPtr>::iterator it = media_listeners_.begin();
- media_listeners_.end() != it;
- ++it) {
- (*it)->OnActivityStarted(application_key);
- }
-
- LOG4CXX_DEBUG(logger_, "Pipe was opened for writing " << named_pipe_path_);
}
-void PipeStreamerAdapter::StopActivity(int32_t application_key) {
+bool PipeStreamerAdapter::PipeStreamer::Connect() {
LOG4CXX_AUTO_TRACE(logger_);
- if (application_key != current_application_) {
- LOG4CXX_WARN(logger_, "Not performing activity for " << application_key);
- return;
- }
-
- is_ready_ = false;
- current_application_ = 0;
-
- messages_.Reset();
-
- for (std::set<MediaListenerPtr>::iterator it = media_listeners_.begin();
- media_listeners_.end() != it;
- ++it) {
- (*it)->OnActivityEnded(application_key);
- }
-}
-
-bool PipeStreamerAdapter::is_app_performing_activity( int32_t application_key) {
- return (application_key == current_application_);
-}
-
-void PipeStreamerAdapter::Init() {
- LOG4CXX_AUTO_TRACE(logger_);
- if (thread_->is_running()) {
- thread_->stop();
- thread_->join();
+ pipe_fd_ = open(named_pipe_path_.c_str(), O_RDWR, 0);
+ if (-1 == pipe_fd_) {
+ LOG4CXX_ERROR(logger_, "Cannot open pipe for writing " << named_pipe_path_);
+ return false;
}
- LOG4CXX_DEBUG(logger_, "Start sending thread");
- const size_t kStackSize = 16384;
- thread_->start(threads::ThreadOptions(kStackSize));
-}
-PipeStreamerAdapter::Streamer::Streamer(
- PipeStreamerAdapter* server)
- : server_(server),
- pipe_fd_(0),
- stop_flag_(false) {
+ LOG4CXX_INFO(logger_,
+ "Pipe " << named_pipe_path_
+ << " was successfuly opened for writing");
+ return true;
}
-PipeStreamerAdapter::Streamer::~Streamer() {
- server_ = NULL;
-}
-
-void PipeStreamerAdapter::Streamer::threadMain() {
+void PipeStreamerAdapter::PipeStreamer::Disconnect() {
LOG4CXX_AUTO_TRACE(logger_);
-
- open();
-
- while (!stop_flag_) {
- while (!server_->messages_.empty()) {
- ::protocol_handler::RawMessagePtr msg = server_->messages_.pop();
- if (!msg) {
- LOG4CXX_ERROR(logger_, "Null pointer message");
- continue;
- }
-
- ssize_t ret = write(pipe_fd_, msg.get()->data(),
- msg.get()->data_size());
-
- if (ret == -1) {
- LOG4CXX_ERROR(logger_, "Failed writing data to pipe "
- << server_->named_pipe_path_);
-
- std::set<MediaListenerPtr>::iterator it =
- server_->media_listeners_.begin();
- for (;server_->media_listeners_.end() != it; ++it) {
- (*it)->OnErrorReceived(server_->current_application_, -1);
- }
- } else if (static_cast<uint32_t>(ret) != msg.get()->data_size()) {
- LOG4CXX_WARN(logger_, "Couldn't write all the data to pipe "
- << server_->named_pipe_path_);
- }
-
- static int32_t messsages_for_session = 0;
- ++messsages_for_session;
-
- LOG4CXX_DEBUG(logger_, "Handling map streaming message. This is "
- << messsages_for_session << " the message for "
- << server_->current_application_);
- std::set<MediaListenerPtr>::iterator it =
- server_->media_listeners_.begin();
- for (; server_->media_listeners_.end() != it; ++it) {
- (*it)->OnDataReceived(server_->current_application_,
- messsages_for_session);
- }
- }
- server_->messages_.wait();
+ if (0 == close(pipe_fd_)) {
+ LOG4CXX_INFO(logger_, "Pipe " << named_pipe_path_ << " was closed");
+ } else {
+ LOG4CXX_ERROR(logger_, "Error closing pipe " << named_pipe_path_);
}
- close();
}
-void PipeStreamerAdapter::Streamer::exitThreadMain() {
+bool PipeStreamerAdapter::PipeStreamer::Send(
+ protocol_handler::RawMessagePtr msg) {
LOG4CXX_AUTO_TRACE(logger_);
- stop_flag_ = true;
- server_->messages_.Shutdown();
-}
-
-void PipeStreamerAdapter::Streamer::open() {
- LOG4CXX_AUTO_TRACE(logger_);
-
- DCHECK(file_system::CreateDirectoryRecursively(
- profile::Profile::instance()->app_storage_folder()));
-
- if ((mkfifo(server_->named_pipe_path_.c_str(),
- S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0)
- && (errno != EEXIST)) {
- LOG4CXX_ERROR(logger_, "Cannot create pipe " << server_->named_pipe_path_);
- return;
+ ssize_t ret = write(pipe_fd_, msg->data(), msg->data_size());
+ if (-1 == ret) {
+ LOG4CXX_ERROR(logger_, "Failed writing data to pipe " << named_pipe_path_);
+ return false;
}
- pipe_fd_ = ::open(server_->named_pipe_path_.c_str(), O_RDWR, 0);
- if (-1 == pipe_fd_) {
- LOG4CXX_ERROR(logger_, "Cannot open pipe for writing "
- << server_->named_pipe_path_);
- return;
+ if (static_cast<uint32_t>(ret) != msg->data_size()) {
+ LOG4CXX_WARN(logger_,
+ "Couldn't write all the data to pipe " << named_pipe_path_);
}
- LOG4CXX_DEBUG(logger_, "Pipe " << server_->named_pipe_path_
- << " was successfully created");
-}
-
-void PipeStreamerAdapter::Streamer::close() {
- LOG4CXX_AUTO_TRACE(logger_);
- ::close(pipe_fd_);
- unlink(server_->named_pipe_path_.c_str());
+ LOG4CXX_INFO(logger_, "Streamer::sent " << msg->data_size());
+ return true;
}
} // namespace media_manager
diff --git a/src/components/media_manager/src/socket_streamer_adapter.cc b/src/components/media_manager/src/socket_streamer_adapter.cc
index 45b1f63a17..2bb0fe10ec 100644
--- a/src/components/media_manager/src/socket_streamer_adapter.cc
+++ b/src/components/media_manager/src/socket_streamer_adapter.cc
@@ -33,282 +33,116 @@
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/select.h>
-#include <sys/time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
-#include <string.h>
-#include <errno.h>
-#include "config_profile/profile.h"
-#include "media_manager/video/socket_video_streamer_adapter.h"
#include "utils/logger.h"
+#include "media_manager/socket_streamer_adapter.h"
namespace media_manager {
CREATE_LOGGERPTR_GLOBAL(logger, "SocketStreamerAdapter")
-SocketStreamerAdapter::SocketStreamerAdapter()
- : socket_fd_(0),
- is_ready_(false),
- streamer_(new Streamer(this)),
- thread_(threads::CreateThread("SocketStreamer", streamer_)),
- messages_() {
-}
-
-SocketStreamerAdapter::~SocketStreamerAdapter() {
+SocketStreamerAdapter::SocketStreamerAdapter(const std::string& ip,
+ const uint16_t port,
+ const std::string& header)
+ : StreamerAdapter(new SocketStreamer(this, ip, port, header)) {}
+
+SocketStreamerAdapter::~SocketStreamerAdapter() {}
+
+SocketStreamerAdapter::SocketStreamer::SocketStreamer(
+ SocketStreamerAdapter* const adapter,
+ const std::string& ip,
+ const uint16_t port,
+ const std::string& header)
+ : Streamer(adapter)
+ , ip_(ip)
+ , port_(port)
+ , header_(header)
+ , socket_fd_(0)
+ , send_socket_fd_(0)
+ , is_first_frame_(true) {}
+
+SocketStreamerAdapter::SocketStreamer::~SocketStreamer() {}
+
+bool SocketStreamerAdapter::SocketStreamer::Connect() {
LOG4CXX_AUTO_TRACE(logger);
- thread_->join();
- delete streamer_;
- threads::DeleteThread(thread_);
-}
-
-void SocketStreamerAdapter::StartActivity(int32_t application_key) {
- LOG4CXX_TRACE(logger, "enter " << application_key);
-
- if (application_key == current_application_) {
- LOG4CXX_INFO(logger, "Already running for app " << application_key);
- } else {
- is_ready_ = true;
- current_application_ = application_key;
-
- messages_.Reset();
-
- for (std::set<MediaListenerPtr>::iterator it = media_listeners_.begin();
- media_listeners_.end() != it;
- ++it) {
- (*it)->OnActivityStarted(application_key);
- }
- }
- LOG4CXX_TRACE(logger, "exit");
-}
-
-void SocketStreamerAdapter::StopActivity(int32_t application_key) {
- LOG4CXX_TRACE(logger, "enter " << application_key);
-
- if (application_key != current_application_) {
- LOG4CXX_WARN(logger, "Streaming is not active for " << application_key);
- } else {
- is_ready_ = false;
- current_application_ = 0;
-
- if (streamer_) {
- streamer_->stop();
- messages_.Shutdown();
- }
-
- for (std::set<MediaListenerPtr>::iterator it = media_listeners_.begin();
- media_listeners_.end() != it;
- ++it) {
- (*it)->OnActivityEnded(application_key);
- }
- }
- LOG4CXX_TRACE(logger, "exit");
-}
-
-bool SocketStreamerAdapter::is_app_performing_activity(
- int32_t application_key) {
- return (application_key == current_application_);
-}
-
-void SocketStreamerAdapter::Init() {
- LOG4CXX_DEBUG(logger, "Start sending thread");
- const size_t kStackSize = 16384;
- thread_->start(threads::ThreadOptions(kStackSize));
-}
-
-void SocketStreamerAdapter::SendData(
- int32_t application_key,
- const ::protocol_handler::RawMessagePtr message) {
- LOG4CXX_INFO(logger, "SendData(application_key = " << application_key << ")");
-
-
- if (application_key != current_application_) {
- LOG4CXX_WARN(logger, "Currently working with other app "
- << current_application_);
- return;
- }
-
- if (is_ready_) {
- messages_.push(message);
- }
-}
-
-SocketStreamerAdapter::Streamer::Streamer(
- SocketStreamerAdapter* const server)
- : server_(server),
- new_socket_fd_(0),
- is_first_loop_(true),
- is_client_connected_(false),
- stop_flag_(false) {
-}
-
-SocketStreamerAdapter::Streamer::~Streamer() {
- stop();
-}
-
-void SocketStreamerAdapter::Streamer::threadMain() {
- LOG4CXX_TRACE(logger,"enter " << this);
- sync_primitives::AutoLock auto_lock(thread_lock);
- start();
-
- while (!stop_flag_) {
- new_socket_fd_ = accept(server_->socket_fd_, NULL, NULL);
- LOG4CXX_INFO(logger, "Client connectd " << new_socket_fd_);
- if (0 > new_socket_fd_) {
- LOG4CXX_ERROR(logger, "Socket is closed " << strerror(errno));
- sleep(1);
- continue;
- }
-
- is_client_connected_ = true;
- is_first_loop_ = true;
- while (is_client_connected_) {
- while (!server_->messages_.empty()) {
- ::protocol_handler::RawMessagePtr msg = server_->messages_.pop();
- if (!msg) {
- LOG4CXX_ERROR(logger, "Null pointer message");
- continue;
- }
-
- is_client_connected_ = send(msg);
- static int32_t messages_for_session = 0;
- ++messages_for_session;
-
- LOG4CXX_INFO(logger, "Handling map streaming message. This is "
- << messages_for_session << " the message for "
- << server_->current_application_);
- std::set<MediaListenerPtr>::iterator it = server_->media_listeners_
- .begin();
- for (; server_->media_listeners_.end() != it; ++it) {
- (*it)->OnDataReceived(server_->current_application_,
- messages_for_session);
- }
- }
-
- if (!is_ready()) {
- LOG4CXX_INFO(logger, "Client disconnected.");
- stop();
- break;
- }
- server_->messages_.wait();
- }
- }
- LOG4CXX_TRACE(logger,"exit " << this);
-}
-
-void SocketStreamerAdapter::Streamer::exitThreadMain() {
- LOG4CXX_TRACE(logger,"enter " << this);
- stop_flag_ = true;
- stop();
- server_->messages_.Shutdown();
- if (server_->socket_fd_ != -1) {
- shutdown(server_->socket_fd_, SHUT_RDWR);
- close(server_->socket_fd_);
- }
- LOG4CXX_TRACE(logger,"exit " << this);
-}
-
-void SocketStreamerAdapter::Streamer::start() {
- server_->socket_fd_ = socket(AF_INET, SOCK_STREAM, 0);
-
- if (0 >= server_->socket_fd_) {
- LOG4CXX_ERROR_EXT(logger, "Server open error");
- return;
+ socket_fd_ = socket(AF_INET, SOCK_STREAM, 0);
+ if (0 >= socket_fd_) {
+ LOG4CXX_ERROR(logger, "Unable to create socket");
+ return false;
}
int32_t optval = 1;
- if (-1 == setsockopt(server_->socket_fd_, SOL_SOCKET, SO_REUSEADDR,
- &optval, sizeof optval)) {
- LOG4CXX_ERROR_EXT(logger, "Unable to set sockopt");
- return;
+ if (-1 == setsockopt(
+ socket_fd_, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof optval)) {
+ LOG4CXX_ERROR(logger, "Unable to set sockopt");
+ return false;
}
- struct sockaddr_in serv_addr_ = { 0 };
- serv_addr_.sin_addr.s_addr = inet_addr(server_->ip_.c_str());
+ struct sockaddr_in serv_addr_ = {0};
+ serv_addr_.sin_addr.s_addr = inet_addr(ip_.c_str());
serv_addr_.sin_family = AF_INET;
- serv_addr_.sin_port = htons(server_->port_);
-
- if (-1 == bind(server_->socket_fd_,
+ serv_addr_.sin_port = htons(port_);
+ if (-1 == bind(socket_fd_,
reinterpret_cast<struct sockaddr*>(&serv_addr_),
sizeof(serv_addr_))) {
- LOG4CXX_ERROR_EXT(logger, "Unable to bind");
- return;
+ LOG4CXX_ERROR(logger, "Unable to bind");
+ return false;
}
- LOG4CXX_INFO(logger, "SocketStreamerAdapter::listen for connections");
- if (-1 == listen(server_->socket_fd_, 5)) {
- LOG4CXX_ERROR_EXT(logger, "Unable to listen");
- return;
+ if (-1 == listen(socket_fd_, 5)) {
+ LOG4CXX_ERROR(logger, "Unable to listen");
+ return false;
}
-}
-void SocketStreamerAdapter::Streamer::stop() {
- LOG4CXX_TRACE(logger,"enter " << this);
- if (0 == new_socket_fd_) {
- LOG4CXX_ERROR(logger, "Client Socket does not exist: ");
- } else if (-1 == shutdown(new_socket_fd_, SHUT_RDWR)) {
- LOG4CXX_ERROR(logger, "Unable to shutdown socket " << strerror(errno));
- } else if (-1 == ::close(new_socket_fd_)) {
- LOG4CXX_ERROR(logger, "Unable to close socket " << strerror(errno));
+ send_socket_fd_ = accept(socket_fd_, NULL, NULL);
+ if (0 >= send_socket_fd_) {
+ LOG4CXX_ERROR(logger, "Unable to accept");
+ return false;
}
- new_socket_fd_ = 0;
- is_client_connected_ = false;
- LOG4CXX_TRACE(logger,"exit" << this);
+ is_first_frame_ = true;
+ LOG4CXX_INFO(logger, "Client connected: " << send_socket_fd_);
+ return true;
}
-bool SocketStreamerAdapter::Streamer::is_ready() const {
- bool result = true;
- fd_set fds;
- FD_ZERO(&fds);
- FD_SET(new_socket_fd_, &fds);
- struct timeval tv;
- tv.tv_sec = 5; // set a 5 second timeout
- tv.tv_usec = 0;
-
- int32_t retval = 0;
- retval = select(new_socket_fd_ + 1, 0, &fds, 0, &tv);
-
- if (-1 == retval) {
- LOG4CXX_ERROR_EXT(logger, "An error occurred");
- result = false;
- } else if (0 == retval) {
- LOG4CXX_ERROR_EXT(logger, "The timeout expired");
- result = false;
+void SocketStreamerAdapter::SocketStreamer::Disconnect() {
+ LOG4CXX_AUTO_TRACE(logger);
+ if (0 < send_socket_fd_) {
+ close(send_socket_fd_);
}
- return result;
-}
-
-bool SocketStreamerAdapter::Streamer::send(
- const ::protocol_handler::RawMessagePtr msg) {
- if (!is_ready()) {
- LOG4CXX_ERROR_EXT(logger, " Socket is not ready");
- return false;
+ if (0 < socket_fd_) {
+ close(socket_fd_);
}
+}
- if (is_first_loop_) {
- is_first_loop_ = false;
- char hdr[] = {"HTTP/1.1 200 OK\r\n "
- "Connection: Keep-Alive\r\n"
- "Keep-Alive: timeout=15, max=300\r\n"
- "Server: SDL\r\n"
- "Content-Type: video/mp4\r\n\r\n"
- };
-
- if (-1 == ::send(new_socket_fd_, hdr, strlen(hdr), MSG_NOSIGNAL)) {
- LOG4CXX_ERROR_EXT(logger, " Unable to send");
+bool SocketStreamerAdapter::SocketStreamer::Send(
+ protocol_handler::RawMessagePtr msg) {
+ LOG4CXX_AUTO_TRACE(logger);
+ ssize_t ret;
+ if (is_first_frame_) {
+ ret = send(send_socket_fd_, header_.c_str(), header_.size(), MSG_NOSIGNAL);
+ if (static_cast<uint32_t>(ret) != header_.size()) {
+ LOG4CXX_ERROR(logger, "Unable to send data to socket");
return false;
}
+ is_first_frame_ = false;
}
- if (-1 == ::send(new_socket_fd_, (*msg).data(),
- (*msg).data_size(), MSG_NOSIGNAL)) {
- LOG4CXX_ERROR_EXT(logger, " Unable to send");
+ ret = send(send_socket_fd_, msg->data(), msg->data_size(), MSG_NOSIGNAL);
+ if (-1 == ret) {
+ LOG4CXX_ERROR(logger, "Unable to send data to socket");
return false;
}
- LOG4CXX_INFO(logger, "Streamer::sent " << (*msg).data_size());
+ if (static_cast<uint32_t>(ret) != msg->data_size()) {
+ LOG4CXX_WARN(logger,
+ "Couldn't send all the data to socket " << send_socket_fd_);
+ }
+
+ LOG4CXX_INFO(logger, "Streamer::sent " << msg->data_size());
return true;
}
diff --git a/src/components/media_manager/src/streamer_adapter.cc b/src/components/media_manager/src/streamer_adapter.cc
new file mode 100644
index 0000000000..20c067da1c
--- /dev/null
+++ b/src/components/media_manager/src/streamer_adapter.cc
@@ -0,0 +1,172 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "media_manager/streamer_adapter.h"
+#include "utils/logger.h"
+
+namespace media_manager {
+
+CREATE_LOGGERPTR_GLOBAL(logger, "StreamerAdapter")
+
+StreamerAdapter::StreamerAdapter(Streamer* const streamer)
+ : current_application_(0), messages_(), streamer_(streamer), thread_(NULL) {
+ DCHECK(streamer_);
+ thread_ = threads::CreateThread("StreamerAdapter", streamer_);
+}
+
+StreamerAdapter::~StreamerAdapter() {
+ delete streamer_;
+ thread_->join();
+ threads::DeleteThread(thread_);
+}
+
+void StreamerAdapter::StartActivity(int32_t application_key) {
+ LOG4CXX_AUTO_TRACE(logger);
+ if (is_app_performing_activity(application_key)) {
+ LOG4CXX_WARN(logger,
+ "Activity for application: " << application_key
+ << " has been already started");
+ return;
+ }
+ messages_.Reset();
+
+ DCHECK(thread_);
+ const size_t kStackSize = 16384;
+ thread_->start(threads::ThreadOptions(kStackSize));
+
+ for (std::set<MediaListenerPtr>::iterator it = media_listeners_.begin();
+ media_listeners_.end() != it;
+ ++it) {
+ (*it)->OnActivityStarted(application_key);
+ }
+ current_application_ = application_key;
+}
+
+void StreamerAdapter::StopActivity(int32_t application_key) {
+ LOG4CXX_AUTO_TRACE(logger);
+ if (!is_app_performing_activity(application_key)) {
+ LOG4CXX_WARN(logger,
+ "Activity for application: " << application_key
+ << " has not been started");
+ return;
+ }
+
+ DCHECK(thread_);
+ thread_->stop();
+
+ for (std::set<MediaListenerPtr>::iterator it = media_listeners_.begin();
+ media_listeners_.end() != it;
+ ++it) {
+ (*it)->OnActivityEnded(application_key);
+ }
+ current_application_ = 0;
+}
+
+void StreamerAdapter::SendData(int32_t application_key,
+ const ::protocol_handler::RawMessagePtr msg) {
+ LOG4CXX_AUTO_TRACE(logger);
+ if (!is_app_performing_activity(application_key)) {
+ LOG4CXX_ERROR(logger,
+ "Activity for application: " << application_key
+ << " has not been started");
+ return;
+ }
+ messages_.push(msg);
+}
+
+bool StreamerAdapter::is_app_performing_activity(
+ int32_t application_key) const {
+ return application_key == current_application_;
+}
+
+StreamerAdapter::Streamer::Streamer(StreamerAdapter* const adapter)
+ : stop_flag_(false), adapter_(adapter) {
+ DCHECK(adapter_);
+}
+
+StreamerAdapter::Streamer::~Streamer() {}
+
+void StreamerAdapter::Streamer::threadMain() {
+ LOG4CXX_AUTO_TRACE(logger);
+ if (!adapter_) {
+ LOG4CXX_ERROR(logger, "Null pointer to adapter");
+ return;
+ }
+ if (!Connect()) {
+ LOG4CXX_ERROR(logger, "Unable to connect");
+ return;
+ }
+ stop_flag_ = false;
+ while (!stop_flag_) {
+ adapter_->messages_.wait();
+ while (!adapter_->messages_.empty()) {
+ protocol_handler::RawMessagePtr msg;
+ if (!adapter_->messages_.pop(msg)) {
+ LOG4CXX_ERROR(logger, "Empty message queue");
+ continue;
+ }
+ if (!msg) {
+ LOG4CXX_ERROR(logger, "Null pointer message");
+ continue;
+ }
+ if (!Send(msg)) {
+ LOG4CXX_ERROR(logger, "Unable to send. Disconnecting");
+ Disconnect();
+ return;
+ }
+ static int32_t messages_for_session = 0;
+ ++messages_for_session;
+
+ LOG4CXX_DEBUG(logger,
+ "Handling map streaming message. This is "
+ << messages_for_session << " message for "
+ << adapter_->current_application_);
+ std::set<MediaListenerPtr>::iterator it =
+ adapter_->media_listeners_.begin();
+ for (; adapter_->media_listeners_.end() != it; ++it) {
+ (*it)->OnDataReceived(adapter_->current_application_,
+ messages_for_session);
+ }
+ }
+ }
+ Disconnect();
+}
+
+void StreamerAdapter::Streamer::exitThreadMain() {
+ LOG4CXX_AUTO_TRACE(logger);
+ stop_flag_ = true;
+ if (adapter_) {
+ adapter_->messages_.Shutdown();
+ }
+}
+
+} // namespace media_manager
diff --git a/src/components/media_manager/src/streamer_listener.cc b/src/components/media_manager/src/streamer_listener.cc
index 3181ba8e09..2d6c3bc984 100644
--- a/src/components/media_manager/src/streamer_listener.cc
+++ b/src/components/media_manager/src/streamer_listener.cc
@@ -36,33 +36,30 @@
namespace media_manager {
-CREATE_LOGGERPTR_GLOBAL(logger_, "StreamerListener")
+CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManager")
-StreamerListener::StreamerListener()
- : current_application_(0) {
-}
+StreamerListener::StreamerListener(MediaManager& media_manager)
+ : current_application_(0), media_manager_(media_manager) {}
StreamerListener::~StreamerListener() {
OnActivityEnded(current_application_);
}
-void StreamerListener::OnDataReceived(
- int32_t application_key,
- const DataForListener& data) {
- MediaManagerImpl::instance()->FramesProcessed(application_key, data);
+void StreamerListener::OnDataReceived(int32_t application_key,
+ const DataForListener& data) {
+ media_manager_.FramesProcessed(application_key, data);
}
-void StreamerListener::OnErrorReceived(
- int32_t application_key,
- const DataForListener& data) {
- LOG4CXX_ERROR(logger_, "StreamerListener::OnErrorReceived");
+void StreamerListener::OnErrorReceived(int32_t application_key,
+ const DataForListener& data) {
+ LOG4CXX_AUTO_TRACE(logger_);
}
void StreamerListener::OnActivityStarted(int32_t application_key) {
LOG4CXX_AUTO_TRACE(logger_);
if (current_application_ == application_key) {
- LOG4CXX_WARN(logger_, "Already performing activity for "
- << application_key);
+ LOG4CXX_WARN(logger_,
+ "Already performing activity for " << application_key);
return;
}
current_application_ = application_key;
@@ -71,8 +68,8 @@ void StreamerListener::OnActivityStarted(int32_t application_key) {
void StreamerListener::OnActivityEnded(int32_t application_key) {
LOG4CXX_AUTO_TRACE(logger_);
if (current_application_ != application_key) {
- LOG4CXX_WARN(logger_, "Already not performing activity for "
- << application_key);
+ LOG4CXX_WARN(logger_,
+ "Already not performing activity for " << application_key);
return;
}
current_application_ = 0;
diff --git a/src/components/media_manager/src/video/file_video_streamer_adapter.cc b/src/components/media_manager/src/video/file_video_streamer_adapter.cc
new file mode 100644
index 0000000000..f9e4d58a0e
--- /dev/null
+++ b/src/components/media_manager/src/video/file_video_streamer_adapter.cc
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2014-2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "media_manager/video/file_video_streamer_adapter.h"
+
+namespace media_manager {
+
+FileVideoStreamerAdapter::FileVideoStreamerAdapter(
+ const std::string& video_stream_file, const std::string& app_storage_folder)
+ : FileStreamerAdapter(video_stream_file, app_storage_folder) {}
+
+FileVideoStreamerAdapter::~FileVideoStreamerAdapter() {}
+
+} // namespace media_manager
diff --git a/src/components/media_manager/src/video/pipe_video_streamer_adapter.cc b/src/components/media_manager/src/video/pipe_video_streamer_adapter.cc
index 4812e19c9f..cf1a6fb347 100644
--- a/src/components/media_manager/src/video/pipe_video_streamer_adapter.cc
+++ b/src/components/media_manager/src/video/pipe_video_streamer_adapter.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2014-2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -31,21 +31,14 @@
*/
#include "media_manager/video/pipe_video_streamer_adapter.h"
-#include "config_profile/profile.h"
namespace media_manager {
-CREATE_LOGGERPTR_GLOBAL(logger, "PipeVideoStreamerAdapter")
+PipeVideoStreamerAdapter::PipeVideoStreamerAdapter(
+ const std::string& named_video_pipe_path,
+ const std::string& app_storage_folder)
+ : PipeStreamerAdapter(named_video_pipe_path, app_storage_folder) {}
-PipeVideoStreamerAdapter::PipeVideoStreamerAdapter() {
- LOG4CXX_AUTO_TRACE(logger);
- named_pipe_path_ = profile::Profile::instance()->named_video_pipe_path();
-
- Init();
-}
-
-PipeVideoStreamerAdapter::~PipeVideoStreamerAdapter() {
- LOG4CXX_INFO(logger, "PipeVideoStreamerAdapter::~PipeVideoStreamerAdapter");
-}
+PipeVideoStreamerAdapter::~PipeVideoStreamerAdapter() {}
} // namespace media_manager
diff --git a/src/components/media_manager/src/video/socket_video_streamer_adapter.cc b/src/components/media_manager/src/video/socket_video_streamer_adapter.cc
index 3a83aabd10..12ae93da69 100644
--- a/src/components/media_manager/src/video/socket_video_streamer_adapter.cc
+++ b/src/components/media_manager/src/video/socket_video_streamer_adapter.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2014-2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,23 +30,23 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include "config_profile/profile.h"
#include "media_manager/video/socket_video_streamer_adapter.h"
-#include "utils/logger.h"
-namespace media_manager {
-
-CREATE_LOGGERPTR_GLOBAL(logger, "SocketVideoStreamerAdapter")
+namespace {
+const std::string kHeader =
+ "HTTP/1.1 200 OK\r\n"
+ "Connection: Keep-Alive\r\n"
+ "Keep-Alive: timeout=15, max=300\r\n"
+ "Server: SDL\r\n"
+ "Content-Type: video/mp4\r\n\r\n";
+}
-SocketVideoStreamerAdapter::SocketVideoStreamerAdapter() {
- LOG4CXX_AUTO_TRACE(logger);
- port_ = profile::Profile::instance()->video_streaming_port();
- ip_ = profile::Profile::instance()->server_address();
+namespace media_manager {
- Init();
-}
+SocketVideoStreamerAdapter::SocketVideoStreamerAdapter(
+ const std::string& server_address, uint16_t video_streaming_port)
+ : SocketStreamerAdapter(server_address, video_streaming_port, kHeader) {}
-SocketVideoStreamerAdapter::~SocketVideoStreamerAdapter() {
-}
+SocketVideoStreamerAdapter::~SocketVideoStreamerAdapter() {}
} // namespace media_manager
diff --git a/src/components/media_manager/src/video/video_stream_to_file_adapter.cc b/src/components/media_manager/src/video/video_stream_to_file_adapter.cc
index 33b0c43ee5..f41954b117 100644
--- a/src/components/media_manager/src/video/video_stream_to_file_adapter.cc
+++ b/src/components/media_manager/src/video/video_stream_to_file_adapter.cc
@@ -40,16 +40,15 @@ namespace media_manager {
CREATE_LOGGERPTR_GLOBAL(logger, "VideoStreamToFileAdapter")
VideoStreamToFileAdapter::VideoStreamToFileAdapter(const std::string& file_name)
- : file_name_(file_name),
- is_ready_(false),
- thread_(threads::CreateThread("VideoStreamer",
- new Streamer(this))) {
+ : file_name_(file_name)
+ , is_ready_(false)
+ , thread_(threads::CreateThread("VideoStreamer", new Streamer(this))) {
Init();
}
VideoStreamToFileAdapter::~VideoStreamToFileAdapter() {
LOG4CXX_AUTO_TRACE(logger);
- if ((0 != current_application_ ) && (is_ready_)) {
+ if ((0 != current_application_) && (is_ready_)) {
StopActivity(current_application_);
}
thread_->join();
@@ -68,10 +67,9 @@ void VideoStreamToFileAdapter::Init() {
}
void VideoStreamToFileAdapter::SendData(
- int32_t application_key,
- const ::protocol_handler::RawMessagePtr message) {
- LOG4CXX_INFO(logger, "VideoStreamToFileAdapter::SendData "
- << application_key);
+ int32_t application_key, const ::protocol_handler::RawMessagePtr message) {
+ LOG4CXX_INFO(logger,
+ "VideoStreamToFileAdapter::SendData " << application_key);
if (application_key != current_application_) {
LOG4CXX_WARN(logger, "Wrong application " << application_key);
@@ -84,11 +82,11 @@ void VideoStreamToFileAdapter::SendData(
}
void VideoStreamToFileAdapter::StartActivity(int32_t application_key) {
- LOG4CXX_INFO(logger, "VideoStreamToFileAdapter::StartActivity "
- << application_key);
+ LOG4CXX_INFO(logger,
+ "VideoStreamToFileAdapter::StartActivity " << application_key);
if (application_key == current_application_) {
- LOG4CXX_WARN(logger, "Already running video stream to file for "
- << application_key);
+ LOG4CXX_WARN(
+ logger, "Already running video stream to file for " << application_key);
return;
}
@@ -103,11 +101,11 @@ void VideoStreamToFileAdapter::StartActivity(int32_t application_key) {
}
void VideoStreamToFileAdapter::StopActivity(int32_t application_key) {
- LOG4CXX_INFO(logger, "VideoStreamToFileAdapter::StopActivity "
- << application_key);
+ LOG4CXX_INFO(logger,
+ "VideoStreamToFileAdapter::StopActivity " << application_key);
if (application_key != current_application_) {
- LOG4CXX_WARN(logger, "Performing activity for another key "
- << current_application_);
+ LOG4CXX_WARN(
+ logger, "Performing activity for another key " << current_application_);
return;
}
@@ -121,17 +119,13 @@ void VideoStreamToFileAdapter::StopActivity(int32_t application_key) {
}
}
-bool VideoStreamToFileAdapter::is_app_performing_activity(int32_t
- application_key) {
+bool VideoStreamToFileAdapter::is_app_performing_activity(
+ int32_t application_key) {
return (application_key == current_application_ && is_ready_);
}
-VideoStreamToFileAdapter::Streamer::Streamer(
- VideoStreamToFileAdapter* server)
- : server_(server),
- stop_flag_(false),
- file_stream_(NULL) {
-}
+VideoStreamToFileAdapter::Streamer::Streamer(VideoStreamToFileAdapter* server)
+ : server_(server), stop_flag_(false), file_stream_(NULL) {}
VideoStreamToFileAdapter::Streamer::~Streamer() {
server_ = NULL;
@@ -139,7 +133,7 @@ VideoStreamToFileAdapter::Streamer::~Streamer() {
}
void VideoStreamToFileAdapter::Streamer::threadMain() {
- LOG4CXX_INFO(logger, "Streamer::threadMain");
+ LOG4CXX_AUTO_TRACE(logger);
open();
@@ -173,7 +167,7 @@ void VideoStreamToFileAdapter::Streamer::threadMain() {
}
void VideoStreamToFileAdapter::Streamer::exitThreadMain() {
- LOG4CXX_INFO(logger, "Streamer::exitThreadMain");
+ LOG4CXX_AUTO_TRACE(logger);
stop_flag_ = true;
server_->messages_.Shutdown();
}
@@ -186,7 +180,7 @@ void VideoStreamToFileAdapter::Streamer::open() {
file_stream_ = file_system::Open(server_->file_name_);
if (!file_stream_) {
- LOG4CXX_WARN(logger, "Can't open file stream! " << server_->file_name_);
+ LOG4CXX_WARN(logger, "Can't open file stream! " << server_->file_name_);
} else {
LOG4CXX_INFO(logger, "file_stream_ opened :" << file_stream_);
}
diff --git a/src/components/media_manager/test/CMakeLists.txt b/src/components/media_manager/test/CMakeLists.txt
index 1146aacff0..ede6f27f95 100644
--- a/src/components/media_manager/test/CMakeLists.txt
+++ b/src/components/media_manager/test/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2014, Ford Motor Company
+# Copyright (c) 2016, Ford Motor Company
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -33,6 +33,10 @@ if(BUILD_TESTS)
include_directories(
${GMOCK_INCLUDE_DIRECTORY}
${COMPONENTS_DIR}/media_manager/include
+ ${COMPONENTS_DIR}/media_manager/test/include
+ ${COMPONENTS_DIR}/application_manager/test/include
+ ${COMPONENTS_DIR}/resumption/include
+
)
if(EXTENDED_MEDIA_MODE)
@@ -43,12 +47,14 @@ if(EXTENDED_MEDIA_MODE)
endif()
set(SOURCES
- media_manager_impl_test.cc
+ ${COMPONENTS_DIR}/media_manager/test/media_manager_impl_test.cc
)
set(LIBRARIES
+ SmartObjects
MediaManager
ApplicationManager
+ MessageHelper
ProtocolHandler
gmock
connectionHandler
@@ -69,6 +75,6 @@ if(ENABLE_LOG)
target_link_libraries("media_manager_test" log4cxx -L${LOG4CXX_LIBS_DIRECTORY})
endif()
-endif() # BUILD_TESTS
+endif()
# vim: set ts=2 sw=2 et:
diff --git a/src/components/media_manager/test/include/media_manager/media_adapter_impl_mock.h b/src/components/media_manager/test/include/media_manager/media_adapter_impl_mock.h
new file mode 100644
index 0000000000..ff9c2fec9f
--- /dev/null
+++ b/src/components/media_manager/test/include/media_manager/media_adapter_impl_mock.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef TEST_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_MEDIA_ADAPTER_IMPL_MOCK_H_
+#define TEST_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_MEDIA_ADAPTER_IMPL_MOCK_H_
+
+#include <gmock/gmock.h>
+#include "media_manager/media_adapter_impl.h"
+#include "media_adapter_listener_mock.h"
+#include "media_manager/media_adapter_listener.h"
+#include "media_adapter_mock.h"
+#include "utils/macro.h"
+#include "protocol_handler/protocol_handler.h"
+
+namespace test {
+namespace components {
+namespace media_manager_test {
+
+/*
+ * MOCK implementation of ::media_manager::MediaAdapterImpl
+ */
+using namespace media_manager;
+typedef utils::SharedPtr<MediaAdapterListener> MediaListenerPtr;
+class MockMediaAdapterImpl : public ::media_manager::MediaAdapterImpl {
+ public:
+ MOCK_METHOD1(AddListener,
+ void(const utils::SharedPtr<MediaAdapterListener>&));
+ MOCK_METHOD1(RemoveListener,
+ void(const utils::SharedPtr<MediaAdapterListener>&));
+ MOCK_METHOD2(SendData,
+ void(int32_t application_key,
+ const ::protocol_handler::RawMessagePtr message));
+ MOCK_METHOD1(StartActivity, void(int32_t application_key));
+ MOCK_METHOD1(StopActivity, void(int32_t application_key));
+ MOCK_CONST_METHOD1(is_app_performing_activity, bool(int32_t application_key));
+};
+
+} // namespace media_manager_test
+} // namespace components
+} // namespace test
+
+#endif // TEST_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_MEDIA_ADAPTER_IMPL_MOCK_H_
diff --git a/src/components/media_manager/test/include/media_manager/media_adapter_listener_mock.h b/src/components/media_manager/test/include/media_manager/media_adapter_listener_mock.h
new file mode 100644
index 0000000000..2ba64479b6
--- /dev/null
+++ b/src/components/media_manager/test/include/media_manager/media_adapter_listener_mock.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef TEST_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_MEDIA_ADAPTER_LISTENER_MOCK_H_
+#define TEST_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_MEDIA_ADAPTER_LISTENER_MOCK_H_
+
+#include <gmock/gmock.h>
+#include "media_manager/media_adapter_listener.h"
+
+namespace test {
+namespace components {
+namespace media_manager_test {
+
+/*
+ * MOCK implementation of ::media_manager::MediaAdapterListener
+ */
+class MockMediaAdapterListener : public ::media_manager::MediaAdapterListener {
+ public:
+ MOCK_METHOD2(OnDataReceived,
+ void(int32_t application_key, const int32_t& data));
+ MOCK_METHOD1(OnActivityStarted, void(int32_t application_key));
+ MOCK_METHOD1(OnActivityEnded, void(int32_t application_key));
+ MOCK_METHOD2(OnErrorReceived,
+ void(int32_t application_key, const int32_t& data));
+};
+
+} // namespace media_manager_test
+} // namespace components
+} // namespace test
+
+#endif // TEST_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_MEDIA_ADAPTER_LISTENER_MOCK_H_
diff --git a/src/components/media_manager/test/include/media_manager/media_adapter_mock.h b/src/components/media_manager/test/include/media_manager/media_adapter_mock.h
new file mode 100644
index 0000000000..576a1a1a9f
--- /dev/null
+++ b/src/components/media_manager/test/include/media_manager/media_adapter_mock.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef TEST_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_MEDIA_ADAPTER_MOCK_H_
+#define TEST_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_MEDIA_ADAPTER_MOCK_H_
+
+#include <gmock/gmock.h>
+#include "media_manager/media_manager.h"
+#include "media_manager/media_adapter.h"
+
+namespace test {
+namespace components {
+namespace media_manager_test {
+
+/*
+ * MOCK implementation of ::media_manager::MediaAdapter
+ */
+class MockMediaAdapter : public ::media_manager::MediaAdapter {
+ public:
+ MOCK_METHOD2(SendData,
+ void(int32_t application_key,
+ const ::protocol_handler::RawMessagePtr message));
+ MOCK_METHOD1(StartActivity, void(int32_t application_key));
+ MOCK_METHOD1(StopActivity, void(int32_t application_key));
+ MOCK_CONST_METHOD1(is_app_performing_activity, bool(int32_t application_key));
+};
+
+} // namespace media_manager_test
+} // namespace components
+} // namespace test
+
+#endif // TEST_COMPONENTS_MEDIA_MANAGER_INCLUDE_MEDIA_MANAGER_MEDIA_ADAPTER_MOCK_H_
diff --git a/src/components/media_manager/test/media_adapter_impl_test.cc b/src/components/media_manager/test/media_adapter_impl_test.cc
deleted file mode 100644
index f6a6ffa518..0000000000
--- a/src/components/media_manager/test/media_adapter_impl_test.cc
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
-* Copyright (c) 2014, Ford Motor Company
-* All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions are met:
-*
-* Redistributions of source code must retain the above copyright notice, this
-* list of conditions and the following disclaimer.
-*
-* Redistributions in binary form must reproduce the above copyright notice,
-* this list of conditions and the following
-* disclaimer in the documentation and/or other materials provided with the
-* distribution.
-*
-* Neither the name of the Ford Motor Company nor the names of its contributors
-* may be used to endorse or promote products derived from this software
-* without specific prior written permission.
-*
-* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-* POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include "gmock/gmock.h"
-
-TEST(MediaAdapterImplTest, DummyTest) {
- ASSERT_TRUE(true);
-}
diff --git a/src/components/media_manager/test/media_manager_impl_test.cc b/src/components/media_manager/test/media_manager_impl_test.cc
index 615d74f9a1..8db510580c 100644
--- a/src/components/media_manager/test/media_manager_impl_test.cc
+++ b/src/components/media_manager/test/media_manager_impl_test.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -32,61 +32,150 @@
#include "gmock/gmock.h"
#include "media_manager/media_manager_impl.h"
+#include "media_manager/media_adapter_mock.h"
+#include "media_manager/media_adapter_listener_mock.h"
+#include "media_manager/media_adapter_impl_mock.h"
+#include "protocol_handler/mock_protocol_handler.h"
+#include "media_manager/mock_media_manager_settings.h"
+#include "application_manager/mock_application_manager.h"
+#include "utils/shared_ptr.h"
+#include "utils/make_shared.h"
+#include "application_manager/event_engine/event_dispatcher.h"
+#include "application_manager/state_controller.h"
+#include "application_manager/resumption/resume_ctrl.h"
+#include "resumption/last_state.h"
namespace test {
namespace components {
namespace media_manager_test {
-CREATE_LOGGERPTR_GLOBAL(logger_, "MediaManagerImplTest")
+using ::testing::_;
+using ::testing::ReturnRef;
+using protocol_handler::ServiceType;
-class MediaManagerTest : public ::testing::Test {
- protected:
- virtual void SetUp();
- virtual void TearDown();
+class MediaManagerImplTest : public ::testing::Test {
+ protected:
+ const ::testing::NiceMock<MockMediaManagerSettings>
+ mock_media_manager_settings_;
+ const std::string kDefaultValue_ = "";
};
-void MediaManagerTest::SetUp() {
-}
-
-void MediaManagerTest::TearDown() {
-}
-
-TEST_F(MediaManagerTest, AddAndPlayStream) {
- media_manager::MediaManager* mediaManager =
- media_manager::MediaManagerImpl::instance();
-
- const useconds_t sleeptime = 100;
-
- mediaManager->PlayA2DPSource(1);
- LOG4CXX_INFO(logger_, ".Playing stream");
-
- usleep(sleeptime);
-
- mediaManager->StopA2DPSource(1);
-
- usleep(sleeptime);
+TEST_F(MediaManagerImplTest, PlayA2DPSource) {
+ MockMediaAdapter* media_mock_ = new MockMediaAdapter();
- mediaManager->PlayA2DPSource(1);
+ application_manager_test::MockApplicationManager mock_application_manager;
- usleep(sleeptime);
+ ON_CALL(mock_media_manager_settings_, video_server_type())
+ .WillByDefault(ReturnRef(kDefaultValue_));
+ ON_CALL(mock_media_manager_settings_, audio_server_type())
+ .WillByDefault(ReturnRef(kDefaultValue_));
+ MediaManagerImpl mediaManagerImpl(mock_application_manager,
+ mock_media_manager_settings_);
+ int32_t application_key = 1;
- mediaManager->StopA2DPSource(1);
-
- usleep(sleeptime);
-
- mediaManager->PlayA2DPSource(1);
-
- usleep(sleeptime);
-
- mediaManager->StopA2DPSource(1);
+ mediaManagerImpl.set_mock_a2dp_player(media_mock_);
+ EXPECT_CALL(*media_mock_, StartActivity(application_key));
+ mediaManagerImpl.PlayA2DPSource(application_key);
+}
- usleep(sleeptime);
+TEST_F(MediaManagerImplTest, StopA2DPSource) {
+ MockMediaAdapter* media_mock_ = new MockMediaAdapter();
+ application_manager_test::MockApplicationManager mock_application_manager;
+
+ ON_CALL(mock_media_manager_settings_, video_server_type())
+ .WillByDefault(ReturnRef(kDefaultValue_));
+ ON_CALL(mock_media_manager_settings_, audio_server_type())
+ .WillByDefault(ReturnRef(kDefaultValue_));
+ MediaManagerImpl mediaManagerImpl(mock_application_manager,
+ mock_media_manager_settings_);
+ int32_t application_key = 1;
+
+ mediaManagerImpl.set_mock_a2dp_player(media_mock_);
+ EXPECT_CALL(*media_mock_, StopActivity(application_key));
+ mediaManagerImpl.StopA2DPSource(application_key);
+}
- mediaManager->StopA2DPSource(1);
+TEST_F(MediaManagerImplTest, StopMicrophoneRecording) {
+ MockMediaAdapterListener* media_adapter_listener_mock_ =
+ new MockMediaAdapterListener();
+ application_manager_test::MockApplicationManager mock_application_manager;
+
+ ON_CALL(mock_media_manager_settings_, video_server_type())
+ .WillByDefault(ReturnRef(kDefaultValue_));
+ ON_CALL(mock_media_manager_settings_, audio_server_type())
+ .WillByDefault(ReturnRef(kDefaultValue_));
+ MediaManagerImpl mediaManagerImpl(mock_application_manager,
+ mock_media_manager_settings_);
+ int32_t application_key = 1;
+
+ mediaManagerImpl.set_mock_mic_listener(media_adapter_listener_mock_);
+#ifdef EXTENDED_MEDIA_MODE
+ MockMediaAdapterImpl* media_adapter_recorder_mock =
+ new MockMediaAdapterImpl();
+ mediaManagerImpl.set_mock_mic_recorder(media_adapter_recorder_mock);
+ EXPECT_CALL(*media_adapter_recorder_mock, StopActivity(application_key));
+#endif // EXTENDED_MEDIA_MODE
+ EXPECT_CALL(*media_adapter_listener_mock_, OnActivityEnded(application_key));
+#ifdef EXTENDED_MEDIA_MODE
+ EXPECT_CALL(*media_adapter_recorder_mock, RemoveListener(_));
+#endif // EXTENDED_MEDIA_MODE
+ mediaManagerImpl.StopMicrophoneRecording(application_key);
}
-} // namespace media_manager_test
-} // namespace components
-} // namespace test
+TEST_F(MediaManagerImplTest, StartStopStreaming) {
+ application_manager_test::MockApplicationManager mock_application_manager;
+
+ ON_CALL(mock_media_manager_settings_, video_server_type())
+ .WillByDefault(ReturnRef(kDefaultValue_));
+ ON_CALL(mock_media_manager_settings_, audio_server_type())
+ .WillByDefault(ReturnRef(kDefaultValue_));
+ MediaManagerImpl mediaManagerImpl(mock_application_manager,
+ mock_media_manager_settings_);
+
+ int32_t application_key = 1;
+ MockMediaAdapterImpl* mock_audio_media_streamer = new MockMediaAdapterImpl();
+ mediaManagerImpl.set_mock_streamer(protocol_handler::ServiceType::kAudio,
+ mock_audio_media_streamer);
+ MockMediaAdapterImpl* mock_nav_media_streamer = new MockMediaAdapterImpl();
+ mediaManagerImpl.set_mock_streamer(protocol_handler::ServiceType::kMobileNav,
+ mock_nav_media_streamer);
+
+ EXPECT_CALL(*mock_audio_media_streamer, StartActivity(application_key));
+ mediaManagerImpl.StartStreaming(application_key,
+ protocol_handler::ServiceType::kAudio);
+
+ EXPECT_CALL(*mock_nav_media_streamer, StartActivity(application_key));
+ mediaManagerImpl.StartStreaming(application_key,
+ protocol_handler::ServiceType::kMobileNav);
+
+ EXPECT_CALL(*mock_audio_media_streamer, StopActivity(application_key));
+ mediaManagerImpl.StopStreaming(application_key,
+ protocol_handler::ServiceType::kAudio);
+
+ EXPECT_CALL(*mock_nav_media_streamer, StopActivity(application_key));
+ mediaManagerImpl.StopStreaming(application_key,
+ protocol_handler::ServiceType::kMobileNav);
+}
+TEST_F(MediaManagerImplTest, CheckFramesProcessed) {
+ application_manager_test::MockApplicationManager mock_application_manager;
+
+ ON_CALL(mock_media_manager_settings_, video_server_type())
+ .WillByDefault(ReturnRef(kDefaultValue_));
+ ON_CALL(mock_media_manager_settings_, audio_server_type())
+ .WillByDefault(ReturnRef(kDefaultValue_));
+ MediaManagerImpl mediaManagerImpl(mock_application_manager,
+ mock_media_manager_settings_);
+ protocol_handler_test::MockProtocolHandler mock_protocol_handler;
+ mediaManagerImpl.SetProtocolHandler(&mock_protocol_handler);
+ int32_t application_key = 1;
+ int32_t frame_number = 10;
+
+ EXPECT_CALL(mock_protocol_handler,
+ SendFramesNumber(application_key, frame_number));
+ mediaManagerImpl.FramesProcessed(application_key, frame_number);
+}
+} // namespace media_manager_test
+} // namespace components
+} // namespace test
diff --git a/src/components/policy/CMakeLists.txt b/src/components/policy/CMakeLists.txt
index f32ef344d2..3a2b0829dc 100644
--- a/src/components/policy/CMakeLists.txt
+++ b/src/components/policy/CMakeLists.txt
@@ -28,11 +28,83 @@
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
-# --- Policy
-add_subdirectory(./src/policy)
-#======================= Unit-Test section =======================
-if(BUILD_TESTS)
- add_subdirectory(test)
+set(target Policy)
+set(install_destination bin)
+set(copy_destination ${CMAKE_BINARY_DIR}/src/appMain)
+set(library_name ${CMAKE_SHARED_LIBRARY_PREFIX}${target}${CMAKE_SHARED_LIBRARY_SUFFIX})
+
+set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules/")
+
+include_directories (
+ ${COMPONENTS_DIR}/policy/include
+ ${COMPONENTS_DIR}/rpc_base/include
+ ${JSONCPP_INCLUDE_DIRECTORY}
+ ${COMPONENTS_DIR}/utils/include/
+ ${COMPONENTS_DIR}/config_profile/include
+ ${LOG4CXX_INCLUDE_DIRECTORY}
+)
+
+set(SOURCES
+ ${COMPONENTS_DIR}/policy/src/policy_manager_impl.cc
+ ${COMPONENTS_DIR}/policy/src/policy_helper.cc
+ ${COMPONENTS_DIR}/policy/src/policy_table.cc
+ ${COMPONENTS_DIR}/policy/src/sql_pt_queries.cc
+ ${COMPONENTS_DIR}/policy/src/sql_pt_representation.cc
+ ${COMPONENTS_DIR}/policy/src/update_status_manager.cc
+ ${COMPONENTS_DIR}/policy/src/cache_manager.cc
+ ${COMPONENTS_DIR}/rpc_base/src/rpc_base/rpc_base.cc
+)
+
+# --- Table struct section
+set(policy_struct_target policy_struct)
+set(POLICY_TABLE_SOURCES
+ ${COMPONENTS_DIR}/policy/src/policy_table/enums.cc
+ ${COMPONENTS_DIR}/policy/src/policy_table/types.cc
+ ${COMPONENTS_DIR}/policy/src/policy_table/validation.cc
+)
+
+add_library(${policy_struct_target} ${POLICY_TABLE_SOURCES})
+target_link_libraries(${policy_struct_target} Utils)
+# --- end of Table struct section
+
+# --- Usage statistics section
+set(USAGE_STATISTICS_SOURCES
+ ${COMPONENTS_DIR}/policy/src/usage_statistics/counter.cc
+)
+add_library(UsageStatistics ${USAGE_STATISTICS_SOURCES})
+# --- end of Usage statistics section
+
+set(LIBRARIES ConfigProfile policy_struct dbms jsoncpp Utils)
+if (CMAKE_SYSTEM_NAME STREQUAL "QNX")
+ # --- QDB Wrapper
+ include_directories (${COMPONENTS_DIR}/utils/include/utils)
+else ()
+ # --- SQLite Wrapper
+ include_directories (${COMPONENTS_DIR}/utils/include/utils)
+ list(APPEND LIBRARIES sqlite3)
+endif ()
+
+add_library(${target} SHARED ${SOURCES})
+target_link_libraries(${target} ${LIBRARIES} )
+
+if(ENABLE_LOG)
+ target_link_libraries(${target} log4cxx -L${LOG4CXX_LIBS_DIRECTORY})
endif()
-#=================================================================
+add_custom_target(copy_library_${target} ALL
+ COMMAND ${CMAKE_COMMAND} -E copy_if_different
+ ${CMAKE_CURRENT_BINARY_DIR}/${library_name}
+ ${copy_destination}
+ DEPENDS ${target}
+ COMMENT "Copying library ${library_name}")
+
+install(TARGETS ${target}
+ DESTINATION ${install_destination}
+ PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE
+ GROUP_READ GROUP_EXECUTE
+ WORLD_READ WORLD_EXECUTE
+)
+
+if(BUILD_TESTS)
+ add_subdirectory(test)
+endif() # BUILD_TESTS
diff --git a/src/components/policy/src/policy/Readme.txt b/src/components/policy/Readme.txt
index 370fab238a..370fab238a 100644
--- a/src/components/policy/src/policy/Readme.txt
+++ b/src/components/policy/Readme.txt
diff --git a/src/components/policy/include/policy/cache_manager.h b/src/components/policy/include/policy/cache_manager.h
new file mode 100644
index 0000000000..3a46d395f3
--- /dev/null
+++ b/src/components/policy/include/policy/cache_manager.h
@@ -0,0 +1,768 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_CACHE_MANAGER_H_
+#define SRC_COMPONENTS_POLICY_INCLUDE_CACHE_MANAGER_H_
+
+#include <map>
+
+#include "utils/shared_ptr.h"
+#include "policy/pt_representation.h"
+#include "policy/pt_ext_representation.h"
+#include "policy/usage_statistics/statistics_manager.h"
+#include "policy/cache_manager_interface.h"
+#include "utils/threads/thread.h"
+#include "utils/threads/thread_delegate.h"
+
+#include "utils/lock.h"
+#include "utils/conditional_variable.h"
+#include "policy/policy_types.h"
+
+namespace policy {
+class PolicySettings;
+
+class CacheManager : public CacheManagerInterface {
+ public:
+ CacheManager();
+ ~CacheManager();
+
+ /**
+ * @brief Check if specified RPC for specified application
+ * has permission to be executed in specified HMI Level
+ * and also its permitted params.
+ * @param app_id Id of application provided during registration
+ * @param hmi_level Current HMI Level of application
+ * @param rpc Name of RPC
+ * @return CheckPermissionResult containing flag if HMI Level is allowed
+ * and list of allowed params.
+ */
+ virtual void CheckPermissions(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ CheckPermissionResult& result);
+
+ /**
+ * @brief Returns true if Policy Table was not updated yet
+ * from preloaded pt file.
+ */
+ virtual bool IsPTPreloaded();
+
+ /**
+ * Gets number of ignition cycles before next update policy table
+ * @return number of ignition cycles
+ */
+ virtual int IgnitionCyclesBeforeExchange();
+
+ /**
+ * Gets value in kilometers before next update policy table
+ * @param current value in kilometers from the odometers
+ * @return value in kilometers
+ */
+ virtual int KilometersBeforeExchange(int current);
+
+ /**
+ * @brief Sets counter value that passed for recieved successful PT UPdate
+ */
+ virtual bool SetCountersPassedForSuccessfulUpdate(Counters counter,
+ int value);
+
+ /**
+ * Gets value in days before next update policy table
+ * @param current value in days after epoch
+ * @return value in days
+ */
+ virtual int DaysBeforeExchange(int current);
+
+ /**
+ * @brief Increment number of ignition cycles since last exchange by 1
+ */
+ virtual void IncrementIgnitionCycles();
+
+ /**
+ * @brief Reset number of ignition cycles since last exchange to 0
+ */
+ virtual void ResetIgnitionCycles();
+
+ /**
+ * @brief Returns timeout to wait for a response of PT update
+ * @return value in seconds
+ */
+ virtual int TimeoutResponse();
+
+ /**
+ * @brief Returns number of seconds between each try of sending PTS
+ * @param seconds Return value: array of 5 elements
+ * @return bool Success of operation
+ */
+ virtual bool SecondsBetweenRetries(std::vector<int>& seconds);
+
+ /**
+ * @brief Get information about vehicle
+ */
+ virtual const VehicleInfo GetVehicleInfo() const;
+
+ /**
+ * @brief Allows to update 'vin' field in module_meta table.
+ *
+ * @param new 'vin' value.
+ *
+ * @return true in case when data has been successfully updated,
+ * false otherwise.
+ */
+ bool SetVINValue(const std::string& value);
+
+ /**
+ * @brief Get message text for displaying/pronouncing for user
+ * dependent on language and context.
+ * @param msg_codes Context of message (Driver distraction, Grant permission
+ * etc)
+ * @param language Language of the message
+ * @return Array of appropriate messages parameters
+ */
+ std::vector<UserFriendlyMessage> GetUserFriendlyMsg(
+ const std::vector<std::string>& msg_codes, const std::string& language);
+
+ /**
+ * @brief Get list of URLs related to particular service
+ * @param service_type If URLs for specific service are preset,
+ * return them otherwise default URLs.
+ */
+ virtual void GetServiceUrls(const std::string& service_type,
+ EndpointUrls& end_points);
+
+ /**
+ * @brief GetLockScreenIcon allows to obtain lock screen icon url;
+ *
+ * @return url which point to the resourse where lock screen icon could be
+ *obtained.
+ */
+ virtual std::string GetLockScreenIconUrl() const;
+
+ /**
+ * @brief Get allowed number of notifications
+ * depending on application priority.
+ * @param priority Priority of application
+ */
+ virtual rpc::policy_table_interface_base::NumberOfNotificationsType
+ GetNotificationsNumber(const std::string& priority);
+
+ /**
+ * @brief Get priority for given application
+ * @param policy_app_id Unique application id
+ * @param priority Priority for application or empty, if value was not set
+ * @return true, if succedeed, otherwise - false
+ */
+ virtual bool GetPriority(const std::string& policy_app_id,
+ std::string& priority) const OVERRIDE;
+
+ /**
+ * @brief Initialized Policy Table (load)
+ * @return bool Success of operation
+ */
+ bool Init(const std::string& file_name, const PolicySettings* settings);
+
+ /**
+ * @brief Get snapshot of Policy Table
+ * including app_policies, functional_groups,
+ * device_info, statistics, excluding user messages
+ * @return Generated structure for obtaining Json string.
+ */
+ virtual utils::SharedPtr<policy_table::Table> GenerateSnapshot();
+
+ /**
+ * Applies policy table to the current table
+ * @param update_pt policy table
+ * @return true if successfully
+ */
+ bool ApplyUpdate(const policy_table::Table& update_pt);
+
+ /**
+ * @brief Gets list of appHMIType associated with mobile appID
+ * @param container of appHMIType
+ */
+ virtual void GetHMIAppTypeAfterUpdate(
+ std::map<std::string, StringArray>& app_hmi_types);
+
+ /**
+ * Gets flag updateRequired
+ * @return true if update is required
+ */
+ bool UpdateRequired() const;
+
+ /**
+ * @brief Saves flag updateRequired
+ * @param status update status if true then update required.
+ */
+ void SaveUpdateRequired(bool status);
+
+ /**
+ * @brief GetInitialAppData Retrieves data from app_policies
+ * about app on its registration
+ * @param app_id id of registered app.
+ * All outputs are filled in only if not null
+ * @param nicknames Synonyms for application
+ * @param app_hmi_types app_types Section on HMI where app can
+ * appear (Navigation, Phone etc)
+ * @return true in case initial application data was obtained successfuly.
+ */
+ bool GetInitialAppData(const std::string& app_id,
+ StringArray& nicknames,
+ StringArray& app_hmi_types);
+
+ /**
+ * Checks if the application is revoked
+ * @param app_id application id
+ * @return true if application is revoked
+ */
+ bool IsApplicationRevoked(const std::string& app_id) const;
+
+ /**
+ * @brief Get functional groupings from DB
+ * @param groups Known functional groupings
+ * @return true, if succeeded, otherwise - false
+ */
+ bool GetFunctionalGroupings(policy_table::FunctionalGroupings& groups);
+
+ /**
+ * Checks if the application is represented in policy table
+ * @param app_id application id
+ * @return true if application is represented in policy table
+ */
+ bool IsApplicationRepresented(const std::string& app_id) const;
+
+ /**
+ * Checks if the application has default policy
+ * @param app_id application id
+ * @return true if application has default policy
+ */
+ bool IsDefaultPolicy(const std::string& app_id);
+
+ /**
+ * @brief SetIsDefault Sets is_default flag for application
+ * @param app_id app specific application
+ * @return true in case opperation was done successfully.
+ */
+ bool SetIsDefault(const std::string& app_id);
+
+ /**
+ * Checks if the application has pre_data policy
+ * @param app_id application id
+ * @return true if application has pre_data policy
+ */
+ bool IsPredataPolicy(const std::string& app_id);
+
+ /**
+ * Sets default policy for application
+ * @param app_id application id
+ * @return true if success
+ */
+ bool SetDefaultPolicy(const std::string& app_id);
+
+ /**
+ * @brief Is application allowed to send notifications while in
+ * Backgound or limited mode.
+ * @param app_id Application id
+ * @return bool Allowed/disallowed.
+ */
+ bool CanAppKeepContext(const std::string& app_id) const OVERRIDE;
+
+ /**
+ * @brief Is application allowed to move foreground at will?
+ * @param app_id Application id
+ * @return bool Allowed/disallowed.
+ */
+ bool CanAppStealFocus(const std::string& app_id) const;
+
+ /**
+ * @brief Gets default_hmi for given application
+ * @param policy_app_id Unique application id
+ * @param default_hmi Default HMI level for application or empty, if value was
+ * not set
+ * @return true, if succedeed, otherwise - false
+ */
+ bool GetDefaultHMI(const std::string& app_id, std::string& default_hmi) const;
+
+ /**
+ * @brief Reset user consent for device data and applications permissions
+ * @return
+ */
+ bool ResetUserConsent();
+
+ /**
+ * @brief Get user permissions for device data usage
+ * @param device_id Generated or obtained id of device
+ * @param consented_groups Groups consented by user
+ * @param disallowed_groups Groups not consented by user
+ * @return true, if query was successfull, otherwise - false
+ */
+ bool GetUserPermissionsForDevice(const std::string& device_id,
+ StringArray& consented_groups,
+ StringArray& disallowed_groups) const;
+
+ /**
+ * @brief Gets list of groups permissions from policy table
+ * @param device_id Unique device id, which hosts specific application
+ * @param policy_app_id Unique application id
+ * @param group_types Group list sorted by permission status
+ * @return true, if query was successfull, otherwise - false
+ */
+ bool GetPermissionsForApp(const std::string& device_id,
+ const std::string& app_id,
+ FunctionalIdType& group_types);
+
+ /**
+ * @brief Get device groups and preconsented groups from policies section
+ * @param groups List of groups to be consented for device usage
+ * @param preconsented_groups List of preconsented groups for device usage
+ * @return true, if query was successful, otherwise - false
+ */
+ bool GetDeviceGroupsFromPolicies(
+ rpc::policy_table_interface_base::Strings& groups,
+ rpc::policy_table_interface_base::Strings& preconsented_groups) const;
+
+ /**
+ * @brief Add's information about mobile device in Policy Table.
+ * @param device_id Generated or obtained id of device
+ * @param connection_type device connection type
+ * @return bool Success of operation
+ */
+ bool AddDevice(const std::string& device_id,
+ const std::string& connection_type);
+
+ /**
+ * @brief Record information about mobile device in Policy Table.
+ * @param device_id Generated or obtained id of device
+ * @return bool Success of operation
+ */
+ bool SetDeviceData(const std::string& device_id,
+ const std::string& hardware = "",
+ const std::string& firmware = "",
+ const std::string& os = "",
+ const std::string& os_version = "",
+ const std::string& carrier = "",
+ const uint32_t number_of_ports = 0,
+ const std::string& connection_type = "");
+
+ /**
+ * @brief Sets user consent for particular mobile device,
+ * i.e. to use device for exchanging of Policy Table.
+ * @return bool Success of operation
+ */
+ bool SetUserPermissionsForDevice(
+ const std::string& device_id,
+ const StringArray& consented_groups = StringArray(),
+ const StringArray& disallowed_groups = StringArray());
+
+ /**
+ * @brief Update Application Policies as reaction
+ * on User allowing/disallowing device this app is running on.
+ */
+ bool ReactOnUserDevConsentForApp(const std::string& app_id,
+ bool is_device_allowed);
+
+ /**
+ * @brief Set user consent on functional groups
+ * @param permissions User consent on functional group
+ * @return true, if operation succedeed, otherwise - false
+ */
+ bool SetUserPermissionsForApp(const PermissionConsent& permissions);
+
+ /**
+ * @brief Records information about head unit system to PT
+ * @return bool Success of operation
+ */
+ bool SetMetaInfo(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language);
+
+ /**
+ * @brief Checks, if specific head unit is present in PT
+ * @return boot Suceess, if present, otherwise - false
+ */
+ bool IsMetaInfoPresent() const;
+
+ /**
+ * @brief Set current system language
+ * @param language System language
+ * @return true, if succedeed, otherwise - false
+ */
+ bool SetSystemLanguage(const std::string& language);
+
+ /**
+ * Increments global counter
+ * @param type type of counter
+ */
+ void Increment(usage_statistics::GlobalCounterId type);
+
+ /**
+ * Increments counter of application
+ * @param app_id id application
+ * @param type type of counter
+ */
+ void Increment(const std::string& app_id,
+ usage_statistics::AppCounterId type);
+
+ /**
+ * Sets value of application information
+ * @param app_id id application
+ * @param type type of information
+ * @param value value of information
+ */
+ void Set(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value);
+
+ /**
+ * Adds value to stopwatch of application
+ * @param app_id id application
+ * @param type type of stopwatch
+ * @param seconds value for adding in seconds
+ */
+ void Add(const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int seconds);
+
+ /**
+ * @brief CountUnconsentedGroups allows to obtain the count of unconsented
+ * groups for specific application.
+ * @param policy_app_id application id.
+ * @param device_id device id.
+ * @return the count of unconsented groups
+ */
+ int CountUnconsentedGroups(const std::string& policy_app_id,
+ const std::string& device_id);
+
+ /**
+ * @brief Gets functional group names and user_consent_prompts, if any
+ * @param Array to be filled with group ids, names and functional prompts
+ * @return true, if succeeded, otherwise - false
+ */
+ bool GetFunctionalGroupNames(FunctionalGroupNames& names);
+
+ /**
+ * @brief GetAllAppGroups allows to obtain all groups for certain application.
+ * @param app_id specific application id.
+ * @param all_group_ids parameter to fill.
+ */
+ void GetAllAppGroups(const std::string& app_id,
+ FunctionalGroupIDs& all_group_ids);
+ /**
+ * @brief GetPreConsentedGroups allows to obtain all pre-consented groups for
+ * specific application.
+ * @param app_id specific application id.
+ * @param preconsented_groups parameter to fill.
+ */
+ void GetPreConsentedGroups(const std::string& app_id,
+ FunctionalGroupIDs& preconsented_groups);
+ /**
+ * @brief GetConsentedGroups allows to obtain list of allowed and disallowed
+ * groups for specific application on certain device.
+ * @param device_id certain device
+ * @param app_id application id.
+ * @param allowed_groups list of allowed groups
+ * @param disallowed_groups list of disallowed groups
+ */
+ void GetConsentedGroups(const std::string& device_id,
+ const std::string& app_id,
+ FunctionalGroupIDs& allowed_groups,
+ FunctionalGroupIDs& disallowed_groups);
+
+ /**
+ * @brief GetUnconsentedGroups allows to obtain list of allowed and disallowed
+ * groups for specific application on certain device.
+ * @param device_id certain device
+ * @param policy_app_id application id.
+ * @param unconsented_groups list of unconsented groups.
+ */
+ void GetUnconsentedGroups(const std::string& device_id,
+ const std::string& policy_app_id,
+ FunctionalGroupIDs& unconsented_groups);
+
+ void RemoveAppConsentForGroup(const std::string& app_id,
+ const std::string& group_name);
+
+ /**
+ * @brief Set app policy to pre_DataConsented policy
+ * @param app_id Policy ID of application to be changed
+ * @return true, if succeeded, otherwise - false
+ */
+ bool SetPredataPolicy(const std::string& app_id);
+
+ /**
+ * @brief Removes unpaired devices
+ * @return true if success
+ */
+ bool CleanupUnpairedDevices();
+
+ /**
+ * Sets flag of unpaired device
+ * @param device_id Unique device id
+ * @param unpaired True, if should be marked as unpaired, otherwise - false
+ * @return true if success
+ */
+ bool SetUnpairedDevice(const std::string& device_id, bool unpaired = true);
+
+ /**
+ * Resets Policy Table
+ * @param file_name Path to preloaded PT file
+ * @return true if successfully
+ */
+ bool ResetPT(const std::string& file_name);
+
+ /**
+ * @brief LoadFromBackup allows to load policy into the cache from backup.
+ * @return true in case operation was successful.
+ */
+ bool LoadFromBackup();
+
+ /**
+ * @brief LoadFromFile allows to load policy cache from preloaded table.
+ * @param file_name preloaded
+ * @return
+ */
+ bool LoadFromFile(const std::string& file_name, policy_table::Table& table);
+
+ /**
+ * @brief Backup allows to save cache onto hard drive.
+ */
+ void Backup();
+
+ /**
+ * Returns heart beat timeout
+ * @param app_id application id
+ * @return if timeout was set then value in milliseconds greater zero
+ * otherwise heart beat for specific application isn't set
+ */
+ uint32_t HeartBeatTimeout(const std::string& app_id) const;
+
+ /**
+ * @brief Allows to generate hash from the specified string.
+ * The djb2 algorithm uses for hash generation.
+ * @param str_to_hash - the string from which hash should be generated.
+ * @return integer hash for the specified string.
+ */
+ static int32_t GenerateHash(const std::string& str_to_hash);
+
+ /**
+ * @brief Gets request types for application
+ * @param policy_app_id Unique application id
+ * @param request_types Request types of application
+ */
+ void GetAppRequestTypes(const std::string& policy_app_id,
+ std::vector<std::string>& request_types) const;
+
+ /**
+ * @brief GetCertificate allows to obtain certificate in order to
+ * make secure connection
+ *
+ * @return The certificate in PKCS#7.
+ */
+ virtual std::string GetCertificate() const OVERRIDE;
+
+ /**
+ * @brief MergePreloadPT allows to load policy table from certain JSON file,
+ * and then decide if merge is needed. The merge is needed in case when
+ *preload
+ * JSON date is different than current database.
+ *
+ * @param file_name the preloaded policy table JSON file.
+ */
+ void MergePreloadPT(const std::string& file_name);
+
+ /**
+ * @brief MergeMC allows to merge ModuleConfig section by definite rules.
+ *
+ * The rules are:
+ * 1. Add new fields (known to PoliciesManager) & sub-sections if such are
+ * present in the updated Preloaded PT
+ * 2. "vehicle_make", “model”, “year” – leave the fields & values as they were
+ * in the database
+ * 3. For all other fields – overwrite the values with the new ones from
+ *preloaded PT.
+ *
+ * @param new_pt the policy table loaded from updated preload JSON file.
+ *
+ * @param pt the exists database.
+ */
+ void MergeMC(const policy_table::PolicyTable& new_pt,
+ policy_table::PolicyTable& pt);
+
+ /**
+ * @brief MergeFG allows to merge FunctionalGroupings sections by definite
+ *rules.
+ *
+ * The rules are:
+ * 1. If functional_group_name exists in both database (LocalPT) and updated
+ * PreloadedPT -> PoliciesManager must overwrite it (that is, replace such
+ * functional_group_name in the database by the one from Pre-PT).
+ * 2. If functional_group_name exists in updated PreloadedPT and does not
+ * exist in database (LocalPT), PoliciesManager must add such group to the
+ *database.
+ * 3. If functional_group_name does not exist in updated PreloadedPT and
+ * exists in the database (LocalPT), PoliciesManager must leave such group in
+ * the database without changes.
+ *
+ * @param new_pt the policy table loaded from updated preload JSON file.
+ *
+ * @param pt the exists database.
+ */
+ void MergeFG(const policy_table::PolicyTable& new_pt,
+ policy_table::PolicyTable& pt);
+
+ /**
+ * @brief MergeAP Allows to merge ApplicationPolicies section by definite
+ *relues.
+ * The rules are:
+ * 1. Leave “<appID>” sub-sections as they were in the database (fields &
+ *their values).
+ * 2. Over-write "default", "device", "pre_DataConsent" subsections.
+ *
+ * @param new_pt the policy table loaded from updated preload JSON file.
+ *
+ * @param pt the exists database.
+ */
+ void MergeAP(const policy_table::PolicyTable& new_pt,
+ policy_table::PolicyTable& pt);
+
+ /**
+ * @brief MergeCFM allows to merge ConsumerFriendlyMessages section by
+ *definite rules.
+ *
+ * The rules are:
+ * 1. If friendly_message_name exists in both database (LocalPT) and updated
+ * Preloaded PT -> PoliciesManager must overwrite it.
+ * 2. If friendly_message_name exists in updated Preloaded PT and does not
+ * exist in database (LocalPT), PoliciesManager must add such
+ * friendly_message_name to the database (LocalPT).
+ * 3. If friendly_message_name does not exist in updated Preloaded PT and
+ * exists in the database (LocalPT), PoliciesManager must leave such
+ * friendly_message_name in the database without changes.
+ *
+ * @param new_pt the policy table loaded from updated preload JSON file.
+ *
+ * @param pt the exists database
+ */
+ void MergeCFM(const policy_table::PolicyTable& new_pt,
+ policy_table::PolicyTable& pt);
+
+ const PolicySettings& get_settings() const;
+
+#ifdef BUILD_TESTS
+ utils::SharedPtr<policy_table::Table> GetPT() const {
+ return pt_;
+ }
+#endif
+
+ private:
+ std::string currentDateTime();
+ struct AppHMITypeToString {
+ std::string operator()(rpc::Enum<policy_table::AppHMIType> value) {
+ return std::string(policy_table::EnumToJsonString(value));
+ }
+ };
+
+ void GetGroupNameByHashID(const int32_t group_id, std::string& group_name);
+ void FillDeviceSpecificData();
+ bool AppExists(const std::string& app_id) const;
+ long ConvertSecondsToMinute(int seconds);
+
+ /**
+ * @brief Checks snapshot initialization and initializes to default values, if
+ * necessary
+ */
+ void CheckSnapshotInitialization();
+
+ void PersistData();
+
+ void ResetCalculatedPermissions();
+
+ void AddCalculatedPermissions(const std::string& device_id,
+ const std::string& policy_app_id,
+ const policy::Permissions& permissions);
+
+ bool IsPermissionsCalculated(const std::string& device_id,
+ const std::string& policy_app_id,
+ policy::Permissions& permission);
+
+ private:
+ /**
+ * @brief Checks, if input string is known service represented by number, than
+ * converts input string to service number
+ * @param input Input string
+ * @param output Output service
+ * @return true, if successfully converted, otherwise - false
+ */
+ bool IsNumberService(const std::string& input, std::string& output) const;
+
+ private:
+ utils::SharedPtr<policy_table::Table> pt_;
+ utils::SharedPtr<policy_table::Table> snapshot_;
+ utils::SharedPtr<PTRepresentation> backup_;
+ bool update_required;
+ typedef std::set<std::string> UnpairedDevices;
+ UnpairedDevices is_unpaired_;
+
+ sync_primitives::Lock cache_lock_;
+ sync_primitives::Lock unpaired_lock_;
+
+ typedef std::map<std::string, Permissions> AppCalculatedPermissions;
+ typedef std::map<std::string, AppCalculatedPermissions> CalculatedPermissions;
+ CalculatedPermissions calculated_permissions_;
+ sync_primitives::Lock calculated_permissions_lock_;
+
+ class BackgroundBackuper : public threads::ThreadDelegate {
+ friend class CacheManager;
+
+ public:
+ BackgroundBackuper(CacheManager* cache_manager);
+ ~BackgroundBackuper();
+ virtual void threadMain();
+ virtual void exitThreadMain();
+ void DoBackup();
+
+ private:
+ void InternalBackup();
+ CacheManager* cache_manager_;
+ sync_primitives::ConditionalVariable backup_notifier_;
+ volatile bool stop_flag_;
+ volatile bool new_data_available_;
+
+ sync_primitives::Lock need_backup_lock_;
+ DISALLOW_COPY_AND_ASSIGN(BackgroundBackuper);
+ };
+ threads::Thread* backup_thread_;
+ sync_primitives::Lock backuper_locker_;
+ BackgroundBackuper* backuper_;
+ const PolicySettings* settings_;
+};
+} // namespace policy
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_CACHE_MANAGER_H_
diff --git a/src/components/policy/include/policy/cache_manager_interface.h b/src/components/policy/include/policy/cache_manager_interface.h
new file mode 100644
index 0000000000..2b8a9fa101
--- /dev/null
+++ b/src/components/policy/include/policy/cache_manager_interface.h
@@ -0,0 +1,631 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_SRC_POLICY_INCLUDE_POLICY_CACHE_MANAGER_INTERFACE_H_
+#define SRC_COMPONENTS_POLICY_SRC_POLICY_INCLUDE_POLICY_CACHE_MANAGER_INTERFACE_H_
+
+#include <string>
+#include <vector>
+
+#include "utils/shared_ptr.h"
+#include "policy/usage_statistics/counter.h"
+#include "policy/policy_types.h"
+#include "policy/policy_settings.h"
+
+namespace policy_table = rpc::policy_table_interface_base;
+
+namespace policy {
+
+class CacheManagerInterface {
+ public:
+ virtual ~CacheManagerInterface() {}
+
+ /**
+ * @brief Check if specified RPC for specified application
+ * has permission to be executed in specified HMI Level
+ * and also its permitted params.
+ * @param app_id Id of application provided during registration
+ * @param hmi_level Current HMI Level of application
+ * @param rpc Name of RPC
+ * @return CheckPermissionResult containing flag if HMI Level is allowed
+ * and list of allowed params.
+ */
+ virtual void CheckPermissions(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ CheckPermissionResult& result) = 0;
+
+ /**
+ * @brief Returns true if Policy Table was not updated yet
+ * from preloaded pt file.
+ */
+ virtual bool IsPTPreloaded() = 0;
+
+ /**
+ * Gets number of ignition cycles before next update policy table
+ * @return number of ignition cycles
+ */
+ virtual int IgnitionCyclesBeforeExchange() = 0;
+
+ /**
+ * Gets value in kilometers before next update policy table
+ * @param current value in kilometers from the odometers
+ * @return value in kilometers
+ */
+ virtual int KilometersBeforeExchange(int current) = 0;
+
+ /**
+ * @brief Sets counter value that passed for recieved successful PT UPdate
+ */
+ virtual bool SetCountersPassedForSuccessfulUpdate(Counters counter,
+ int value) = 0;
+
+ /**
+ * Gets value in days before next update policy table
+ * @param current value in days after epoch
+ * @return value in days
+ */
+ virtual int DaysBeforeExchange(int current) = 0;
+
+ /**
+ * @brief Increment number of ignition cycles since last exchange by 1
+ */
+ virtual void IncrementIgnitionCycles() = 0;
+
+ /**
+ * @brief Reset number of ignition cycles since last exchange to 0
+ */
+ virtual void ResetIgnitionCycles() = 0;
+
+ /**
+ * @brief Returns timeout to wait for a response of PT update
+ * @return value in seconds
+ */
+ virtual int TimeoutResponse() = 0;
+
+ /**
+ * @brief Returns number of seconds between each try of sending PTS
+ * @param seconds Return value: array of 5 elements
+ * @return bool Success of operation
+ */
+ virtual bool SecondsBetweenRetries(std::vector<int>& seconds) = 0;
+
+ /**
+ * @brief Get information about vehicle
+ */
+ virtual const VehicleInfo GetVehicleInfo() const = 0;
+
+ /**
+ * @brief Allows to update 'vin' field in module_meta table.
+ *
+ * @param new 'vin' value.
+ *
+ * @return true in case when data has been successfully updated,
+ * false otherwise.
+ */
+ virtual bool SetVINValue(const std::string& value) = 0;
+
+ /**
+ * @brief Get message text for displaying/pronouncing for user
+ * dependent on language and context.
+ * @param msg_codes Context of message (Driver distraction, Grant permission
+ * etc)
+ * @param language Language of the message
+ * @return Array of appropriate messages parameters
+ */
+ virtual std::vector<UserFriendlyMessage> GetUserFriendlyMsg(
+ const std::vector<std::string>& msg_codes,
+ const std::string& language) = 0;
+
+ /**
+ * @brief Get list of URLs related to particular service
+ * @param service_type If URLs for specific service are preset,
+ * return them otherwise default URLs.
+ */
+ virtual void GetServiceUrls(const std::string& service_type,
+ EndpointUrls& end_points) = 0;
+
+ /**
+ * @brief GetLockScreenIcon allows to obtain lock screen icon url;
+ *
+ * @return url which point to the resourse where lock screen icon could be
+ *obtained.
+ */
+ virtual std::string GetLockScreenIconUrl() const = 0;
+
+ /**
+ * @brief Get allowed number of notifications
+ * depending on application priority.
+ * @param priority Priority of application
+ */
+ virtual policy_table::NumberOfNotificationsType GetNotificationsNumber(
+ const std::string& priority) = 0;
+
+ /**
+ * @brief Get priority for given application
+ * @param policy_app_id Unique application id
+ * @param priority Priority for application or empty, if value was not set
+ * @return true, if succedeed, otherwise - false
+ */
+ virtual bool GetPriority(const std::string& policy_app_id,
+ std::string& priority) const = 0;
+
+ /**
+ * @brief Initialized Policy Table (load)
+ * @return bool Success of operation
+ */
+ virtual bool Init(const std::string& file_name,
+ const PolicySettings* settings) = 0;
+
+ /**
+ * @brief Get snapshot of Policy Table
+ * including app_policies, functional_groups,
+ * device_info, statistics, excluding user messages
+ * @return Generated structure for obtaining Json string.
+ */
+ virtual utils::SharedPtr<policy_table::Table> GenerateSnapshot() = 0;
+
+ /**
+ * Applies policy table to the current table
+ * @param update_pt policy table
+ * @return true if successfully
+ */
+ virtual bool ApplyUpdate(const policy_table::Table& update_pt) = 0;
+
+ /**
+ * @brief Gets list of appHMIType associated with mobile appID
+ * @param container of appHMIType
+ */
+ virtual void GetHMIAppTypeAfterUpdate(
+ std::map<std::string, StringArray>& app_hmi_types) = 0;
+
+ /**
+ * Gets flag updateRequired
+ * @return true if update is required
+ */
+ virtual bool UpdateRequired() const = 0;
+
+ /**
+ * @brief Saves flag updateRequired
+ * @param status update status if true then update required.
+ */
+ virtual void SaveUpdateRequired(bool status) = 0;
+
+ /**
+ * @brief GetInitialAppData Retrieves data from app_policies
+ * about app on its registration
+ * @param app_id id of registered app.
+ * All outputs are filled in only if not null
+ * @param nicknames Synonyms for application
+ * @param app_hmi_types app_types Section on HMI where app can
+ * appear (Navigation, Phone etc)
+ * @return true in case initial application data was obtained successfuly.
+ */
+ virtual bool GetInitialAppData(const std::string& app_id,
+ StringArray& nicknames,
+ StringArray& app_hmi_types) = 0;
+
+ /**
+ * Checks if the application is revoked
+ * @param app_id application id
+ * @return true if application is revoked
+ */
+ virtual bool IsApplicationRevoked(const std::string& app_id) const = 0;
+
+ /**
+ * @brief Get functional groupings from DB
+ * @param groups Known functional groupings
+ * @return true, if succeeded, otherwise - false
+ */
+ virtual bool GetFunctionalGroupings(
+ policy_table::FunctionalGroupings& groups) = 0;
+
+ /**
+ * Checks if the application is represented in policy table
+ * @param app_id application id
+ * @return true if application is represented in policy table
+ */
+ virtual bool IsApplicationRepresented(const std::string& app_id) const = 0;
+
+ /**
+ * Checks if the application has default policy
+ * @param app_id application id
+ * @return true if application has default policy
+ */
+ virtual bool IsDefaultPolicy(const std::string& app_id) = 0;
+
+ /**
+ * @brief SetIsDefault Sets is_default flag for application
+ * @param app_id app specific application
+ * @return true in case opperation was done successfully.
+ */
+ virtual bool SetIsDefault(const std::string& app_id) = 0;
+
+ /**
+ * Checks if the application has pre_data policy
+ * @param app_id application id
+ * @return true if application has pre_data policy
+ */
+ virtual bool IsPredataPolicy(const std::string& app_id) = 0;
+
+ /**
+ * Sets default policy for application
+ * @param app_id application id
+ * @return true if success
+ */
+ virtual bool SetDefaultPolicy(const std::string& app_id) = 0;
+
+ /**
+ * @brief Is application allowed to send notifications while in
+ * Backgound or limited mode.
+ * @param app_id Application id
+ * @return bool Allowed/disallowed.
+ */
+ virtual bool CanAppKeepContext(const std::string& app_id) const = 0;
+
+ /**
+ * @brief Is application allowed to move foreground at will?
+ * @param app_id Application id
+ * @return bool Allowed/disallowed.
+ */
+ virtual bool CanAppStealFocus(const std::string& app_id) const = 0;
+
+ /**
+ * @brief Get default_hmi for given application
+ * @param policy_app_id Unique application id
+ * @param default_hmi Default HMI level for application or empty, if value was
+ * not set
+ * @return true, if succedeed, otherwise - false
+ */
+ virtual bool GetDefaultHMI(const std::string& app_id,
+ std::string& default_hmi) const = 0;
+
+ /**
+ * @brief Reset user consent for device data and applications permissions
+ * @return
+ */
+ virtual bool ResetUserConsent() = 0;
+
+ /**
+ * @brief Get user permissions for device data usage
+ * @param device_id Generated or obtained id of device
+ * @param consented_groups Groups consented by user
+ * @param disallowed_groups Groups not consented by user
+ * @return true, if query was successfull, otherwise - false
+ */
+ virtual bool GetUserPermissionsForDevice(
+ const std::string& device_id,
+ StringArray& consented_groups,
+ StringArray& disallowed_groups) const = 0;
+
+ /**
+ * @brief Gets list of groups permissions from policy table
+ * @param device_id Unique device id, which hosts specific application
+ * @param policy_app_id Unique application id
+ * @param group_types Group list sorted by permission status
+ * @return true, if query was successfull, otherwise - false
+ */
+ virtual bool GetPermissionsForApp(const std::string& device_id,
+ const std::string& app_id,
+ FunctionalIdType& group_types) = 0;
+
+ /**
+ * @brief Get device groups and preconsented groups from policies section
+ * @param groups List of groups to be consented for device usage
+ * @param preconsented_groups List of preconsented groups for device usage
+ * @return true, if query was successful, otherwise - false
+ */
+ virtual bool GetDeviceGroupsFromPolicies(
+ rpc::policy_table_interface_base::Strings& groups,
+ rpc::policy_table_interface_base::Strings& preconsented_groups) const = 0;
+
+ /**
+ * @brief Add's information about mobile device in Policy Table.
+ * @param device_id Generated or obtained id of device
+ * @param connection_type device connection type
+ * @return bool Success of operation
+ */
+ virtual bool AddDevice(const std::string& device_id,
+ const std::string& connection_type) = 0;
+
+ /**
+ * @brief Record information about mobile device in Policy Table.
+ * @param device_id Generated or obtained id of device
+ * @return bool Success of operation
+ */
+ virtual bool SetDeviceData(const std::string& device_id,
+ const std::string& hardware,
+ const std::string& firmware,
+ const std::string& os,
+ const std::string& os_version,
+ const std::string& carrier,
+ const uint32_t number_of_ports,
+ const std::string& connection_type) = 0;
+
+ /**
+ * @brief Sets user consent for particular mobile device,
+ * i.e. to use device for exchanging of Policy Table.
+ * @return bool Success of operation
+ */
+ virtual bool SetUserPermissionsForDevice(
+ const std::string& device_id,
+ const StringArray& consented_groups,
+ const StringArray& disallowed_groups) = 0;
+
+ /**
+ * @brief Update Application Policies as reaction
+ * on User allowing/disallowing device this app is running on.
+ */
+ virtual bool ReactOnUserDevConsentForApp(const std::string& app_id,
+ bool is_device_allowed) = 0;
+
+ /**
+ * @brief Set user consent on functional groups
+ * @param permissions User consent on functional group
+ * @return true, if operation succedeed, otherwise - false
+ */
+ virtual bool SetUserPermissionsForApp(
+ const PermissionConsent& permissions) = 0;
+
+ /**
+ * @brief Records information about head unit system to PT
+ * @return bool Success of operation
+ */
+ virtual bool SetMetaInfo(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language) = 0;
+
+ /**
+ * @brief Checks, if specific head unit is present in PT
+ * @return boot Suceess, if present, otherwise - false
+ */
+ virtual bool IsMetaInfoPresent() const = 0;
+
+ /**
+ * @brief Set current system language
+ * @param language System language
+ * @return true, if succedeed, otherwise - false
+ */
+ virtual bool SetSystemLanguage(const std::string& language) = 0;
+
+ /**
+ * Increments global counter
+ * @param type type of counter
+ */
+ virtual void Increment(usage_statistics::GlobalCounterId type) = 0;
+
+ /**
+ * Increments counter of application
+ * @param app_id id application
+ * @param type type of counter
+ */
+ virtual void Increment(const std::string& app_id,
+ usage_statistics::AppCounterId type) = 0;
+
+ /**
+ * Sets value of application information
+ * @param app_id id application
+ * @param type type of information
+ * @param value value of information
+ */
+ virtual void Set(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value) = 0;
+
+ /**
+ * Adds value to stopwatch of application
+ * @param app_id id application
+ * @param type type of stopwatch
+ * @param seconds value for adding in seconds
+ */
+ virtual void Add(const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int seconds) = 0;
+
+ /**
+ * @brief CountUnconsentedGroups allows to obtain the count of unconsented
+ * groups for specific application.
+ * @param policy_app_id application id.
+ * @param device_id device id.
+ * @param the count of unconsented groups
+ */
+ virtual int CountUnconsentedGroups(const std::string& policy_app_id,
+ const std::string& device_id) = 0;
+
+ /**
+ * @brief Gets functional group names and user_consent_prompts, if any
+ * @param Array to be filled with group ids, names and functional prompts
+ * @return true, if succeeded, otherwise - false
+ */
+ virtual bool GetFunctionalGroupNames(FunctionalGroupNames& names) = 0;
+
+ /**
+ * @brief GetAllAppGroups allows to obtain all groups for certain application.
+ * @param app_id specific application id.
+ * @param all_group_ids parameter to fill.
+ */
+ virtual void GetAllAppGroups(const std::string& app_id,
+ FunctionalGroupIDs& all_group_ids) = 0;
+ /**
+ * @brief GetPreConsentedGroups allows to obtain all pre-consented groups for
+ * specific application.
+ * @param app_id specific application id.
+ * @param preconsented_groups parameter to fill.
+ */
+ virtual void GetPreConsentedGroups(
+ const std::string& app_id, FunctionalGroupIDs& preconsented_groups) = 0;
+ /**
+ * @brief GetConsentedGroups allows to obtain list of allowed and disallowed
+ * groups for specific application on certain device.
+ * @param device_id certain device
+ * @param app_id application id.
+ * @param allowed_groups list of allowed groups
+ * @param disallowed_groups list of disallowed groups
+ */
+ virtual void GetConsentedGroups(const std::string& device_id,
+ const std::string& app_id,
+ FunctionalGroupIDs& allowed_groups,
+ FunctionalGroupIDs& disallowed_groups) = 0;
+
+ /**
+ * @brief GetUnconsentedGroups allows to obtain list of allowed and disallowed
+ * groups for specific application on certain device.
+ * @param device_id certain device
+ * @param policy_app_id application id.
+ * @param unconsented_groups list of unconsented groups.
+ */
+ virtual void GetUnconsentedGroups(const std::string& device_id,
+ const std::string& policy_app_id,
+ FunctionalGroupIDs& unconsented_groups) = 0;
+
+ virtual void RemoveAppConsentForGroup(const std::string& app_id,
+ const std::string& group_name) = 0;
+
+ /**
+ * @brief Set app policy to pre_DataConsented policy
+ * @param app_id Policy ID of application to be changed
+ * @return true, if succeeded, otherwise - false
+ */
+ virtual bool SetPredataPolicy(const std::string& app_id) = 0;
+
+ /**
+ * @brief Removes unpaired devices
+ * @return true if success
+ */
+ virtual bool CleanupUnpairedDevices() = 0;
+
+ /**
+ * Sets flag of unpaired device
+ * @param device_id Unique device id
+ * @param unpaired True, if should be marked as unpaired, otherwise - false
+ * @return true if success
+ */
+ virtual bool SetUnpairedDevice(const std::string& device_id,
+ bool unpaired = true) = 0;
+
+ /**
+ * Resets Policy Table
+ * @param file_name Path to preloaded PT file
+ * @return true if successfully
+ */
+ virtual bool ResetPT(const std::string& file_name) = 0;
+
+ /**
+ * @brief LoadFromBackup allows to load policy into the cache from backup.
+ * @return true in case operation was successful.
+ */
+ virtual bool LoadFromBackup() = 0;
+
+ /**
+ * @brief LoadFromFile allows to load policy cache from preloaded table.
+ * @param file_name preloaded
+ * @param table object which will be filled during file parsing.
+ * @return true in case file was successfuly loaded, false otherwise.
+ */
+ virtual bool LoadFromFile(const std::string& file_name,
+ policy_table::Table& table) = 0;
+
+ /**
+ * @brief Backup allows to save cache onto hard drive.
+ */
+ virtual void Backup() = 0;
+
+ /**
+ * Returns heart beat timeout
+ * @param app_id application id
+ * @return if timeout was set then value in milliseconds greater zero
+ * otherwise heart beat for specific application isn't set
+ */
+ virtual uint32_t HeartBeatTimeout(const std::string& app_id) const = 0;
+
+ /**
+ * @brief Resets all calculated permissions in cache
+ */
+ virtual void ResetCalculatedPermissions() = 0;
+
+ /**
+ * @brief Adds calculated permissions for specific app on particular device
+ * into cache
+ * @param device_id Device id
+ * @param policy_app_id Application id
+ * @param permissions Calculated permissions
+ */
+ virtual void AddCalculatedPermissions(
+ const std::string& device_id,
+ const std::string& policy_app_id,
+ const policy::Permissions& permissions) = 0;
+
+ /**
+ * @brief Checks if permissions calculated for specific app on particular
+ * device
+ * @param device_id Device id
+ * @param policy_app_id Application id
+ * @param permission Permissions to be filled, in case of presence in cache
+ * @return true if present, otherwise false
+ */
+ virtual bool IsPermissionsCalculated(const std::string& device_id,
+ const std::string& policy_app_id,
+ policy::Permissions& permission) = 0;
+
+ /**
+ * @brief Gets request types for application
+ * @param policy_app_id Unique application id
+ * @param request_types Request types of application
+ */
+ virtual void GetAppRequestTypes(
+ const std::string& policy_app_id,
+ std::vector<std::string>& request_types) const = 0;
+
+ /**
+ * @brief GetCertificate allows to obtain certificate in order to
+ * make secure connection
+ *
+ * @return The certificate in PKCS#7.
+ */
+ virtual std::string GetCertificate() const = 0;
+
+#ifdef BUILD_TESTS
+ /**
+ * @brief GetPT allows to obtain SharedPtr to PT.
+ * Used ONLY in Unit tests
+ * @return SharedPTR to PT
+ *
+ */
+ virtual utils::SharedPtr<policy_table::Table> GetPT() const = 0;
+#endif
+};
+
+typedef utils::SharedPtr<CacheManagerInterface> CacheManagerInterfaceSPtr;
+
+} // namespace policy
+
+#endif // SRC_COMPONENTS_POLICY_SRC_POLICY_INCLUDE_POLICY_CACHE_MANAGER_INTERFACE_H_
diff --git a/src/components/policy/include/policy/policy_helper.h b/src/components/policy/include/policy/policy_helper.h
new file mode 100644
index 0000000000..746c5efeba
--- /dev/null
+++ b/src/components/policy/include/policy/policy_helper.h
@@ -0,0 +1,248 @@
+/*
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_HELPER_H_
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_HELPER_H_
+
+#include "policy/policy_table/functions.h"
+#include "utils/shared_ptr.h"
+#include "policy/policy_types.h"
+
+namespace policy {
+class PolicyManagerImpl;
+
+const std::string kAllowedKey = "allowed";
+const std::string kUserDisallowedKey = "userDisallowed";
+const std::string kUndefinedKey = "undefined";
+
+namespace policy_table = rpc::policy_table_interface_base;
+
+typedef policy_table::Strings::const_iterator StringsConstItr;
+typedef policy_table::ApplicationPolicies::const_iterator AppPoliciesConstItr;
+typedef policy_table::HmiLevels::const_iterator HMILevelsConstItr;
+typedef policy_table::Parameters::const_iterator ParametersConstItr;
+typedef policy_table::FunctionalGroupings::const_iterator FuncGroupConstItr;
+
+typedef policy_table::ApplicationPolicies::value_type AppPoliciesValueType;
+typedef policy_table::Rpc::value_type RpcValueType;
+typedef policy_table::Strings::value_type StringsValueType;
+
+/*
+ * @brief Helper struct to compare functional group names
+ */
+struct CompareGroupName {
+ explicit CompareGroupName(const StringsValueType& group_name);
+ bool operator()(const StringsValueType& group_name_to_compare) const;
+
+ private:
+ const StringsValueType& group_name_;
+};
+
+/*
+ * @brief Used for compare of policies parameters mapped with specific
+ * application ids
+ */
+bool operator!=(const policy_table::ApplicationParams& first,
+ const policy_table::ApplicationParams& second);
+
+/*
+ * @brief Helper struct for checking changes of application policies, which
+ * come with update along with current data snapshot
+ * In case of policies changed for some application, current data will be
+ * updated and notification will be sent to application
+ */
+struct CheckAppPolicy {
+ CheckAppPolicy(PolicyManagerImpl* pm,
+ const utils::SharedPtr<policy_table::Table> update,
+ const utils::SharedPtr<policy_table::Table> snapshot);
+ bool operator()(const AppPoliciesValueType& app_policy);
+
+ private:
+ enum PermissionsCheckResult {
+ RESULT_NO_CHANGES,
+ RESULT_APP_REVOKED,
+ RESULT_NICKNAME_MISMATCH,
+ RESULT_PERMISSIONS_REVOKED,
+ RESULT_CONSENT_NEEDED,
+ RESULT_CONSENT_NOT_REQIURED,
+ RESULT_PERMISSIONS_REVOKED_AND_CONSENT_NEEDED,
+ RESULT_REQUEST_TYPE_CHANGED
+ };
+
+ void SetPendingPermissions(const AppPoliciesValueType& app_policy,
+ PermissionsCheckResult result) const;
+ PermissionsCheckResult CheckPermissionsChanges(
+ const AppPoliciesValueType& app_policy) const;
+ bool HasRevokedGroups(const AppPoliciesValueType& app_policy,
+ policy_table::Strings* revoked_groups = NULL) const;
+ bool HasNewGroups(const AppPoliciesValueType& app_policy,
+ policy_table::Strings* new_groups = NULL) const;
+ bool HasConsentNeededGroups(const AppPoliciesValueType& app_policy) const;
+ std::vector<FunctionalGroupPermission> GetRevokedGroups(
+ const AppPoliciesValueType& app_policy) const;
+ void RemoveRevokedConsents(
+ const AppPoliciesValueType& app_policy,
+ const std::vector<FunctionalGroupPermission>& revoked_groups) const;
+ bool IsKnownAppication(const std::string& application_id) const;
+ void NotifySystem(const AppPoliciesValueType& app_policy) const;
+ void SendPermissionsToApp(const AppPoliciesValueType& app_policy) const;
+ bool IsAppRevoked(const AppPoliciesValueType& app_policy) const;
+ bool NicknamesMatch(const AppPoliciesValueType& app_policy) const;
+ /**
+ * @brief Allows to check if appropriate group requires any consent.
+ * @param group_name the group for which consent will be checked.
+ * @return true if consent is required, false otherwise.
+ */
+ bool IsConsentRequired(const std::string& app_id,
+ const std::string& group_name) const;
+ bool IsRequestTypeChanged(const AppPoliciesValueType& app_policy) const;
+
+ private:
+ PolicyManagerImpl* pm_;
+ const utils::SharedPtr<policy_table::Table> update_;
+ const utils::SharedPtr<policy_table::Table> snapshot_;
+};
+
+/*
+ * @brief Fill permissions data with merged rpc permissions for hmi levels and
+ * parameters
+ */
+struct FillNotificationData {
+ FillNotificationData(Permissions& data,
+ GroupConsent group_state,
+ GroupConsent undefined_group_consent);
+ bool operator()(const RpcValueType& rpc);
+ void UpdateHMILevels(const policy_table::HmiLevels& in_hmi,
+ std::set<HMILevel>& out_hmi);
+ void UpdateParameters(const policy_table::Parameters& in_parameters,
+ std::set<Parameter>& out_parameter);
+
+ private:
+ void ExcludeSame();
+ void ExcludeSameHMILevels(std::set<HMILevel>& source,
+ const std::set<HMILevel>& target);
+ void ExcludeSameParameters(std::set<Parameter>& source,
+ const std::set<Parameter>& target);
+ void InitRpcKeys(const std::string& rpc_name);
+ std::string current_key_;
+ Permissions& data_;
+};
+
+/*
+ * @brief Checks for functional group presence and pass it to helper struct,
+ * which fills permissions data according to group consent
+ */
+struct ProcessFunctionalGroup {
+ ProcessFunctionalGroup(
+ const policy_table::FunctionalGroupings& fg,
+ const std::vector<FunctionalGroupPermission>& group_permissions,
+ Permissions& data,
+ GroupConsent undefined_group_consent = GroupConsent::kGroupDisallowed);
+ bool operator()(const StringsValueType& group_name);
+
+ private:
+ GroupConsent GetGroupState(const std::string& group_name);
+ const policy_table::FunctionalGroupings& fg_;
+ const std::vector<FunctionalGroupPermission>& group_permissions_;
+ Permissions& data_;
+ GroupConsent undefined_group_consent_;
+};
+
+struct FunctionalGroupInserter {
+ FunctionalGroupInserter(const policy_table::Strings& preconsented_groups,
+ PermissionsList& list);
+ void operator()(const StringsValueType& group_name);
+
+ private:
+ PermissionsList& list_;
+ const policy_table::Strings& preconsented_;
+};
+
+/**
+ * @brief Fills FunctionalGroupPermissions with provided params
+ * @param ids Functional group ids from DB
+ * @param names Group names and user_consent_prompt
+ * @param state User consent for group
+ * @param permissions Struct to be filled with provided params
+ */
+void FillFunctionalGroupPermissions(
+ FunctionalGroupIDs& ids,
+ FunctionalGroupNames& names,
+ GroupConsent state,
+ std::vector<FunctionalGroupPermission>& permissions);
+
+/**
+ * @brief Checks, if application is predefined, e.g. "default", i.e. which is
+ * must be present in policy table
+ * @param app Application struct
+ * @return true, if app is predefined, otherwise - false
+ */
+bool IsPredefinedApp(const AppPoliciesValueType& app);
+
+/**
+ * @brief Excludes same values
+ * @param from Source, which should be checked
+ * @param what Target, which should be excluded from source
+ * @return Values without excluded
+ */
+FunctionalGroupIDs ExcludeSame(const FunctionalGroupIDs& from,
+ const FunctionalGroupIDs& what);
+
+/**
+ * @brief Merges all values without same values
+ * @param first First source of values
+ * @param second Second source of values
+ * @return Merged values w/o same values
+ */
+FunctionalGroupIDs Merge(const FunctionalGroupIDs& first,
+ const FunctionalGroupIDs& second);
+
+/**
+ * @brief Finds same values
+ * @param first First source of values
+ * @param second Second source of values
+ * @return Same values set, if any found
+ */
+FunctionalGroupIDs FindSame(const FunctionalGroupIDs& first,
+ const FunctionalGroupIDs& second);
+
+/**
+ * @brief Unwrap application policies from predefined values to specific policy
+ * values, i.e. if application has "default", it will be assigned default
+ * policies
+ * @param app_policies Application policies to unwrap
+ * @return true, if succeded, otherwise - false
+ */
+bool UnwrapAppPolicies(policy_table::ApplicationPolicies& app_policies);
+}
+
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_HELPER_H_
diff --git a/src/components/policy/include/policy/policy_listener.h b/src/components/policy/include/policy/policy_listener.h
new file mode 100644
index 0000000000..197dfd5c8a
--- /dev/null
+++ b/src/components/policy/include/policy/policy_listener.h
@@ -0,0 +1,104 @@
+/*
+ Copyright (c) 2016, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_LISTENER_H_
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_LISTENER_H_
+
+#include <queue>
+
+#include "policy/policy_types.h"
+#include "utils/custom_string.h"
+
+namespace policy {
+
+namespace custom_str = utils::custom_string;
+
+class PolicyListener {
+ public:
+ virtual ~PolicyListener() {}
+ virtual void OnPermissionsUpdated(const std::string& policy_app_id,
+ const Permissions& permissions,
+ const policy::HMILevel& default_hmi) = 0;
+ virtual void OnPermissionsUpdated(const std::string& policy_app_id,
+ const Permissions& permissions) = 0;
+ virtual void OnPendingPermissionChange(const std::string& policy_app_id) = 0;
+ virtual void OnUpdateStatusChanged(const std::string&) = 0;
+ virtual std::string OnCurrentDeviceIdUpdateRequired(
+ const std::string& policy_app_id) = 0;
+ virtual void OnSystemInfoUpdateRequired() = 0;
+ virtual custom_str::CustomString GetAppName(
+ const std::string& policy_app_id) = 0;
+ virtual void OnUpdateHMIAppType(
+ std::map<std::string, StringArray> app_hmi_types) = 0;
+
+ /**
+ * @brief CanUpdate allows to find active application
+ * and check whether related device consented.
+ *
+ * @return true if there are at least one application has been registered
+ * with consented device.
+ */
+ virtual bool CanUpdate() = 0;
+
+ /**
+ * @brief OnSnapshotCreated the notification which will be sent
+ * when snapshot for PTU has been created.
+ *
+ * @param pt_string the snapshot
+ *
+ */
+ virtual void OnSnapshotCreated(const BinaryMessage& pt_string) = 0;
+
+ /**
+ * @brief Make appropriate changes for related applications permissions and
+ * notify them, if it possible
+ * @param device_id Unique device id, which consent had been changed
+ * @param device_consent Device consent, which is done by user
+ */
+ virtual void OnDeviceConsentChanged(const std::string& device_id,
+ bool is_allowed) = 0;
+
+ /**
+ * @brief GetAvailableApps allows to obtain list of registered applications.
+ */
+ virtual void GetAvailableApps(std::queue<std::string>&) = 0;
+
+ /**
+ * @brief OnCertificateUpdated the callback which signals if certificate field
+ * has been updated during PTU
+ *
+ * @param certificate_data the value of the updated field.
+ */
+ virtual void OnCertificateUpdated(const std::string& certificate_data) = 0;
+};
+} // namespace policy
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_LISTENER_H_
diff --git a/src/components/policy/include/policy/policy_manager.h b/src/components/policy/include/policy/policy_manager.h
new file mode 100644
index 0000000000..70ec5d23a2
--- /dev/null
+++ b/src/components/policy/include/policy/policy_manager.h
@@ -0,0 +1,481 @@
+/*
+ Copyright (c) 2016, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_H_
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_H_
+
+#include <vector>
+#include <cstdint>
+
+#include "policy/policy_types.h"
+#include "policy/policy_listener.h"
+#include "policy/usage_statistics/statistics_manager.h"
+
+namespace policy {
+class PolicySettings;
+
+class PolicyManager : public usage_statistics::StatisticsManager {
+ public:
+ virtual ~PolicyManager() {}
+
+ virtual void set_listener(PolicyListener* listener) = 0;
+
+ /**
+ * Inits Policy Table
+ * @param file_name Path to preloaded PT file
+ * @return true if successfully
+ */
+ virtual bool InitPT(const std::string& file_name,
+ const PolicySettings* settings) = 0;
+
+ /**
+ * @brief Updates Policy Table from binary message received from
+ * mobile device. Saves to Policy Table diff between Policy Table
+ * sent in snapshot and received Policy Table.
+ * @param file name of file with update policy table
+ * @param pt_content PTU as binary string
+ * @return bool Success of operation
+ */
+ virtual bool LoadPT(const std::string& file,
+ const BinaryMessage& pt_content) = 0;
+
+ /**
+ * Resets Policy Table
+ * @param file_name Path to preloaded PT file
+ * @return true if successfully
+ */
+ virtual bool ResetPT(const std::string& file_name) = 0;
+
+ /**
+ * @brief GetLockScreenIcon allows to obtain lock screen icon url;
+ *
+ * @return url which point to the resourse where lock screen icon could be
+ *obtained.
+ */
+ virtual std::string GetLockScreenIconUrl() const = 0;
+
+ /**
+ * @brief Gets all URLs for sending PTS to from PT itself.
+ * @param service_type Service specifies user of URL
+ * @return vector of urls
+ */
+ virtual void GetServiceUrls(const std::string& service_type,
+ EndpointUrls& end_points) = 0;
+
+ /**
+ * @brief PTU is needed, for this PTS has to be formed and sent.
+ */
+ virtual bool RequestPTUpdate() = 0;
+
+ /**
+ * @brief Check if specified RPC for specified application
+ * has permission to be executed in specified HMI Level
+ * and also its permitted params.
+ * @param app_id Id of application provided during registration
+ * @param hmi_level Current HMI Level of application
+ * @param rpc Name of RPC
+ * @param CheckPermissionResult containing flag if HMI Level is allowed
+ * and list of allowed params.
+ */
+ virtual void CheckPermissions(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ const RPCParams& rpc_params,
+ CheckPermissionResult& result) = 0;
+
+ /**
+ * @brief Clear all record of user consents. Used during Factory Reset.
+ * @return bool Success of operation
+ */
+ virtual bool ResetUserConsent() = 0;
+
+ /**
+ * @brief Returns current status of policy table for HMI
+ * @return Current status of policy table
+ */
+ virtual std::string GetPolicyTableStatus() const = 0;
+
+ /**
+ * Checks is PT exceeded kilometers
+ * @param kilometers current kilometers at odometer
+ * @return true if exceeded
+ */
+ virtual void KmsChanged(int kilometers) = 0;
+
+ /**
+ * Increments counter of ignition cycles
+ */
+ virtual void IncrementIgnitionCycles() = 0;
+
+ /**
+ * @brief ExchangeByUserRequest
+ */
+ virtual std::string ForcePTExchange() = 0;
+
+ /**
+ * Resets retry sequence
+ */
+ virtual void ResetRetrySequence() = 0;
+
+ /**
+ * Gets timeout to wait before next retry updating PT
+ * If timeout is equal to zero then the retry sequence is not need.
+ * @return timeout in seconds
+ */
+ virtual uint32_t NextRetryTimeout() = 0;
+
+ /**
+ * Gets timeout to wait until receive response
+ * @return timeout in seconds
+ */
+ virtual int TimeoutExchange() = 0;
+
+ /**
+ * @brief List of timeouts in seconds between retries
+ * when attempt to update PT fails
+ * @return List of delays between attempts.
+ */
+ virtual const std::vector<int> RetrySequenceDelaysSeconds() = 0;
+
+ /**
+ * Handler of exceeding timeout of exchanging policy table
+ */
+ virtual void OnExceededTimeout() = 0;
+
+ /**
+ * @brief Handler of PTS sending out
+ */
+ virtual void OnUpdateStarted() = 0;
+
+ /**
+ * @brief Check user consent for mobile device data connection
+ * @param device_id Unique device identifier
+ * @return status of device consent
+ */
+ virtual DeviceConsent GetUserConsentForDevice(
+ const std::string& device_id) const = 0;
+
+ /**
+ * @brief Get user consent for application
+ * @param device_id Device id
+ * @param policy_app_id Unique application id
+ * @param permissions Array of functional groups permissions
+ */
+ virtual void GetUserConsentForApp(
+ const std::string& device_id,
+ const std::string& policy_app_id,
+ std::vector<FunctionalGroupPermission>& permissions) = 0;
+
+ /**
+ * @brief Set user consent for mobile device data connection
+ * @param device_id Unique device identifier
+ * @param is_allowed User consent for usage device data connection
+ */
+ virtual void SetUserConsentForDevice(const std::string& device_id,
+ bool is_allowed) = 0;
+
+ /**
+ * @brief Update Application Policies as reaction
+ * on User allowing/disallowing device this app is running on.
+ */
+ virtual bool ReactOnUserDevConsentForApp(const std::string app_id,
+ bool is_device_allowed) = 0;
+ /**
+ * Sets counter value that passed for receiving PT UPdate.
+ */
+ virtual void PTUpdatedAt(Counters counter, int value) = 0;
+
+ /**
+ * @brief Retrieves data from app_policies about app on its registration:
+ * @param app_id - id of registered app
+ * @param app_types Section on HMI where app can appear (Navigation, Phone
+ * etc)
+ * @param nicknames Synonyms for application
+ */
+ virtual bool GetInitialAppData(const std::string& application_id,
+ StringArray* nicknames = NULL,
+ StringArray* app_hmi_types = NULL) = 0;
+
+ /**
+ * @brief Add's device to policy table
+ * @param device_id Device mac address
+ * @param connection_type Device connection type
+ */
+ virtual void AddDevice(const std::string& device_id,
+ const std::string& connection_type) = 0;
+
+ /**
+ * @brief Stores device parameters received during application registration
+ * to policy table
+ * @param device_id Device mac address
+ * @param device_info Received device parameters
+ */
+ virtual void SetDeviceInfo(const std::string& device_id,
+ const DeviceInfo& device_info) = 0;
+
+ /**
+ * @brief Set user consent for application functional groups
+ * @param permissions User-defined application group pemissions.
+ * The permissions is not const reference because it may contains
+ * valid data as well as invalid. So we will remove all invalid data
+ * from this structure.
+ */
+ virtual void SetUserConsentForApp(const PermissionConsent& permissions) = 0;
+
+ /**
+ * @brief Get default HMI level for application
+ * @param policy_app_id Unique application id
+ * @param default_hmi Default HMI level for application or empty, if value
+ * was not set
+ * @return true, if succedeed, otherwise - false
+ */
+ virtual bool GetDefaultHmi(const std::string& policy_app_id,
+ std::string* default_hmi) const = 0;
+
+ /**
+ * @brief Get priority for application
+ * @param policy_app_id Unique application id
+ * @param priority Priority for application or empty, if value was not set
+ * @return true, if succedeed, otherwise - false
+ */
+ virtual bool GetPriority(const std::string& policy_app_id,
+ std::string* priority) const = 0;
+
+ /**
+ * @brief Get user friendly messages for given RPC messages and language
+ * @param message_codes RPC message codes
+ * @param language Language
+ * @return Array of structs with appropriate message parameters
+ */
+ virtual std::vector<UserFriendlyMessage> GetUserFriendlyMessages(
+ const std::vector<std::string>& message_code,
+ const std::string& language) = 0;
+
+ /**
+ * Checks if the application is revoked
+ * @param app_id application id
+ * @return true if application is revoked
+ */
+ virtual bool IsApplicationRevoked(const std::string& app_id) const = 0;
+
+ /**
+ * @brief Get resulting RPCs permissions for application which started on
+ * specific device
+ * @param device_id Device id
+ * @param policy_app_id Unique application id
+ * @param permissions Array of functional groups permissions
+ */
+ virtual void GetPermissionsForApp(
+ const std::string& device_id,
+ const std::string& policy_app_id,
+ std::vector<FunctionalGroupPermission>& permissions) = 0;
+
+ /**
+ * @brief Gets specific application permissions changes since last policy
+ * table update
+ * @param policy_app_id Unique application id
+ * @return Permissions changes
+ */
+ virtual AppPermissions GetAppPermissionsChanges(
+ const std::string& policy_app_id) = 0;
+
+ virtual void RemovePendingPermissionChanges(const std::string& app_id) = 0;
+
+ /**
+ * @brief Return device id, which hosts specific application
+ * @param Application id, which is required to update device id
+ */
+ virtual std::string& GetCurrentDeviceId(
+ const std::string& policy_app_id) const = 0;
+
+ /**
+ * @brief Set current system language
+ * @param language Language
+ */
+ virtual void SetSystemLanguage(const std::string& language) = 0;
+
+ /**
+ * @brief Set data from GetSystemInfo response to policy table
+ * @param ccpu_version CCPU version
+ * @param wers_country_code WERS country code
+ * @param language System language
+ */
+ virtual void SetSystemInfo(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language) = 0;
+
+ /**
+ * @brief Send OnPermissionsUpdated for choosen application
+ * @param application_id
+ */
+ virtual void SendNotificationOnPermissionsUpdated(
+ const std::string& application_id) = 0;
+
+ /**
+ * Marks device as upaired
+ * @param device_id id device
+ */
+ virtual void MarkUnpairedDevice(const std::string& device_id) = 0;
+
+ /**
+ * @brief Adds, application to the db or update existed one
+ * run PTU if policy update is necessary for application.
+ * @param Application id assigned by Ford to the application
+ */
+ virtual void AddApplication(const std::string& application_id) = 0;
+
+ /**
+ * @brief Removes unpaired device records and related records from DB
+ * @param device_ids List of device_id, which should be removed
+ * @return true, if succedeed, otherwise - false
+ */
+ virtual bool CleanupUnpairedDevices() = 0;
+
+ /**
+ * @brief Check if app can keep context.
+ */
+ virtual bool CanAppKeepContext(const std::string& app_id) const = 0;
+
+ /**
+ * @brief Check if app can steal focus.
+ */
+ virtual bool CanAppStealFocus(const std::string& app_id) const = 0;
+
+ /**
+ * @brief Runs necessary operations, which is depends on external system
+ * state, e.g. getting system-specific parameters which are need to be
+ * filled into policy table
+ */
+ virtual void OnSystemReady() = 0;
+
+ /**
+ * @brief GetNotificationNumber
+ * @param priority
+ * @return
+ */
+ virtual uint32_t GetNotificationsNumber(
+ const std::string& priority) const = 0;
+
+ /**
+ * @brief Allows to update Vehicle Identification Number in policy table.
+ * @param new value for the parameter.
+ */
+ virtual void SetVINValue(const std::string& value) = 0;
+
+ /**
+ * @brief Checks, if application has policy assigned w/o data consent
+ * @param policy_app_id Unique application id
+ * @return true, if policy assigned w/o data consent, otherwise -false
+ */
+ virtual bool IsPredataPolicy(const std::string& policy_app_id) = 0;
+
+ /**
+ * Returns heart beat timeout
+ * @param app_id application id
+ * @return if timeout was set then value in milliseconds greater zero
+ * otherwise heart beat for specific application isn't set
+ */
+ virtual uint32_t HeartBeatTimeout(const std::string& app_id) const = 0;
+
+ /**
+ * @brief SaveUpdateStatusRequired alows to save update status.
+ */
+ virtual void SaveUpdateStatusRequired(bool is_update_needed) = 0;
+
+ /**
+ * @brief Handler on applications search started
+ */
+ virtual void OnAppsSearchStarted() = 0;
+
+ /**
+ * @brief Handler on applications search completed
+ */
+ virtual void OnAppsSearchCompleted() = 0;
+ /**
+ * @brief Gets request types for application
+ * @param policy_app_id Unique application id
+ * @return request_types Request types of application
+ */
+ virtual const std::vector<std::string> GetAppRequestTypes(
+ const std::string policy_app_id) const = 0;
+
+ /**
+ * @brief Get information about vehicle
+ */
+ virtual const VehicleInfo GetVehicleInfo() const = 0;
+
+ /**
+ * @brief OnAppRegisteredOnMobile alows to handle event when application were
+ * succesfully registered on mobile device.
+ * It will send OnAppPermissionSend notification and will try to start PTU.
+ *
+ * @param application_id registered application.
+ */
+ virtual void OnAppRegisteredOnMobile(const std::string& application_id) = 0;
+
+ /**
+ * @brief RetrieveCertificate Allows to obtain certificate in order
+ * to start secure connection.
+ *
+ * @return The certificate in PKCS#7 format.
+ */
+ virtual std::string RetrieveCertificate() const = 0;
+
+ virtual const PolicySettings& get_settings() const = 0;
+
+ protected:
+ /**
+ * Checks is PT exceeded IgnitionCycles
+ * @return true if exceeded
+ */
+ virtual bool ExceededIgnitionCycles() = 0;
+
+ /**
+ * Checks is PT exceeded days
+ * @return true if exceeded
+ */
+ virtual bool ExceededDays() = 0;
+
+ /**
+ * @brief StartPTExchange allows to start PTU. The function will check
+ * if one is required and starts the update flow in only case when previous
+ * condition is true.
+ */
+ virtual void StartPTExchange() = 0;
+};
+
+} // namespace policy
+
+extern "C" policy::PolicyManager* CreateManager();
+extern "C" void DeleteManager(policy::PolicyManager*);
+
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_H_
diff --git a/src/components/policy/include/policy/policy_manager_impl.h b/src/components/policy/include/policy/policy_manager_impl.h
new file mode 100644
index 0000000000..66a96bf7a7
--- /dev/null
+++ b/src/components/policy/include/policy/policy_manager_impl.h
@@ -0,0 +1,352 @@
+/*
+ Copyright (c) 2016, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_IMPL_H_
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_IMPL_H_
+
+#include <string>
+#include <list>
+#include <cstdint>
+
+#include "utils/shared_ptr.h"
+#include "utils/lock.h"
+#include "policy/policy_manager.h"
+#include "policy/policy_table.h"
+#include "policy/cache_manager_interface.h"
+#include "policy/update_status_manager.h"
+#include "policy/policy_table/functions.h"
+#include "policy/usage_statistics/statistics_manager.h"
+#include "policy/policy_helper.h"
+#include "utils/timer.h"
+
+namespace policy_table = rpc::policy_table_interface_base;
+
+namespace policy {
+struct CheckAppPolicy;
+
+class PolicyManagerImpl : public PolicyManager {
+ public:
+ PolicyManagerImpl();
+ virtual void set_listener(PolicyListener* listener);
+ PolicyListener* listener() const {
+ return listener_;
+ }
+ virtual bool InitPT(const std::string& file_name,
+ const PolicySettings* settings);
+ virtual bool LoadPT(const std::string& file, const BinaryMessage& pt_content);
+ virtual bool ResetPT(const std::string& file_name);
+
+ virtual void GetServiceUrls(const std::string& service_type,
+ EndpointUrls& end_points);
+
+ virtual std::string GetLockScreenIconUrl() const;
+ virtual bool RequestPTUpdate();
+ virtual void CheckPermissions(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ const RPCParams& rpc_params,
+ CheckPermissionResult& result);
+ virtual bool ResetUserConsent();
+ virtual void KmsChanged(int kilometers);
+ virtual void IncrementIgnitionCycles();
+ virtual std::string ForcePTExchange();
+ virtual std::string GetPolicyTableStatus() const;
+ virtual void ResetRetrySequence();
+ virtual uint32_t NextRetryTimeout();
+ virtual int TimeoutExchange();
+ virtual const std::vector<int> RetrySequenceDelaysSeconds();
+ virtual void OnExceededTimeout();
+ virtual void OnUpdateStarted();
+ virtual void PTUpdatedAt(Counters counter, int value);
+
+ /**
+ * Refresh data about retry sequence from policy table
+ */
+ virtual void RefreshRetrySequence();
+ virtual DeviceConsent GetUserConsentForDevice(
+ const std::string& device_id) const OVERRIDE;
+ virtual void GetUserConsentForApp(
+ const std::string& device_id,
+ const std::string& policy_app_id,
+ std::vector<FunctionalGroupPermission>& permissions);
+ virtual void SetUserConsentForDevice(const std::string& device_id,
+ bool is_allowed);
+ virtual bool ReactOnUserDevConsentForApp(const std::string app_id,
+ bool is_device_allowed);
+ virtual bool GetInitialAppData(const std::string& application_id,
+ StringArray* nicknames = NULL,
+ StringArray* app_hmi_types = NULL);
+
+ virtual void AddDevice(const std::string& device_id,
+ const std::string& connection_type);
+
+ virtual void SetDeviceInfo(const std::string& device_id,
+ const DeviceInfo& device_info);
+
+ virtual void SetUserConsentForApp(const PermissionConsent& permissions);
+
+ virtual bool GetDefaultHmi(const std::string& policy_app_id,
+ std::string* default_hmi) const;
+
+ virtual bool GetPriority(const std::string& policy_app_id,
+ std::string* priority) const;
+
+ virtual std::vector<UserFriendlyMessage> GetUserFriendlyMessages(
+ const std::vector<std::string>& message_code,
+ const std::string& language);
+
+ virtual bool IsApplicationRevoked(const std::string& app_id) const;
+
+ virtual void GetPermissionsForApp(
+ const std::string& device_id,
+ const std::string& policy_app_id,
+ std::vector<FunctionalGroupPermission>& permissions);
+
+ virtual std::string& GetCurrentDeviceId(
+ const std::string& policy_app_id) const;
+
+ virtual void SetSystemLanguage(const std::string& language);
+
+ virtual void SetSystemInfo(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language);
+ virtual void OnSystemReady();
+
+ virtual uint32_t GetNotificationsNumber(
+ const std::string& priority) const OVERRIDE;
+
+ virtual void SetVINValue(const std::string& value);
+
+ // Interface StatisticsManager (begin)
+ virtual void Increment(usage_statistics::GlobalCounterId type);
+ virtual void Increment(const std::string& app_id,
+ usage_statistics::AppCounterId type);
+ virtual void Set(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value);
+ virtual void Add(const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int32_t timespan_seconds);
+ // Interface StatisticsManager (end)
+
+ AppPermissions GetAppPermissionsChanges(const std::string& policy_app_id);
+ void RemovePendingPermissionChanges(const std::string& app_id);
+
+ void SendNotificationOnPermissionsUpdated(const std::string& application_id);
+
+ bool CleanupUnpairedDevices();
+
+ bool CanAppKeepContext(const std::string& app_id) const;
+ bool CanAppStealFocus(const std::string& app_id) const;
+ void MarkUnpairedDevice(const std::string& device_id);
+
+ void AddApplication(const std::string& application_id);
+
+ virtual void RemoveAppConsentForGroup(const std::string& app_id,
+ const std::string& group_name);
+
+ virtual uint32_t HeartBeatTimeout(const std::string& app_id) const;
+
+ virtual void SaveUpdateStatusRequired(bool is_update_needed);
+
+ virtual bool IsPredataPolicy(const std::string& policy_app_id);
+ void set_cache_manager(CacheManagerInterface* cache_manager);
+
+ virtual void OnAppsSearchStarted();
+
+ virtual void OnAppsSearchCompleted();
+
+#ifdef BUILD_TESTS
+ inline CacheManagerInterfaceSPtr GetCache() {
+ return cache_;
+ }
+#endif // BUILD_TESTS
+ virtual const std::vector<std::string> GetAppRequestTypes(
+ const std::string policy_app_id) const;
+
+ virtual const VehicleInfo GetVehicleInfo() const;
+
+ virtual void OnAppRegisteredOnMobile(
+ const std::string& application_id) OVERRIDE;
+
+ virtual std::string RetrieveCertificate() const OVERRIDE;
+
+ protected:
+#ifdef USE_HMI_PTU_DECRYPTION
+ virtual utils::SharedPtr<policy_table::Table> Parse(
+ const BinaryMessage& pt_content);
+#else
+ virtual utils::SharedPtr<policy_table::Table> ParseArray(
+ const BinaryMessage& pt_content);
+#endif
+
+ const PolicySettings& get_settings() const OVERRIDE;
+
+ private:
+ void CheckTriggers();
+ /*
+ * @brief Checks policy table update along with current data for any changes
+ * in assigned functional group list of application
+ *
+ * @param Policy table update struct
+ */
+ void CheckPermissionsChanges(
+ const utils::SharedPtr<policy_table::Table> update,
+ const utils::SharedPtr<policy_table::Table> snapshot);
+
+ /**
+ * @brief Fill structure to be sent with OnPermissionsChanged notification
+ *
+ * @param Policy table struct, which contains rpc functional groups data
+ * @param List of rpc functional group names, which should be checked
+ * @param group_permission User permissions for functional groups
+ * @param Notification struct to be filled and sent
+ */
+ void PrepareNotificationData(
+ const policy_table::FunctionalGroupings& groups,
+ const policy_table::Strings& group_names,
+ const std::vector<FunctionalGroupPermission>& group_permission,
+ Permissions& notification_data);
+
+ /**
+ * @brief Validate PermissionConsent structure according to currently
+ * assigned groups
+ * @param permissions PermissionConsent structure that should be validated.
+ * @return PermissonConsent struct, which contains no foreign groups
+ */
+ PermissionConsent EnsureCorrectPermissionConsent(
+ const PermissionConsent& permissions_to_check);
+
+ /**
+ * @brief Allows to process case when added application is not present in
+ * policy db.
+ * @param policy application id.
+ * @param cuuren consent for application's device.
+ */
+ void AddNewApplication(const std::string& application_id,
+ DeviceConsent device_consent);
+
+ /**
+ * @brief Allows to process case when added application is already
+ * in policy db.
+ * @param policy application id.
+ * @param cuuren consent for application's device.
+ */
+ void PromoteExistedApplication(const std::string& application_id,
+ DeviceConsent device_consent);
+
+ /**
+ * @brief Check if certain application already in policy db.
+ * @param policy application id.
+ * @return true if application presents false otherwise.
+ */
+ bool IsNewApplication(const std::string& application_id) const;
+
+ /**
+ * Checks existing and permissions of AppStorageFolder
+ * @return true if AppStorageFolder exists and has permissions read/write
+ */
+ bool CheckAppStorageFolder() const;
+
+ /**
+ * @brief Checks whether need ask the permission of users
+ * @return true if user consent is needed
+ */
+ virtual bool IsConsentNeeded(const std::string& app_id);
+
+ /**
+ * @brief Changes isConsentNeeded for app pending permissions, in case
+ * user set permissions before app activation.
+ * @param Unique app id
+ * @param Current permissions for app
+ */
+ void CheckPendingPermissionsChanges(
+ const std::string& policy_app_id,
+ const std::vector<FunctionalGroupPermission>& current_permissions);
+
+ virtual void StartPTExchange();
+ virtual bool ExceededDays();
+ virtual bool ExceededIgnitionCycles();
+ bool IsPTValid(utils::SharedPtr<policy_table::Table> policy_table,
+ policy_table::PolicyTableType type) const;
+
+ void RetrySequence();
+
+ private:
+ PolicyListener* listener_;
+
+ UpdateStatusManager update_status_manager_;
+ CacheManagerInterfaceSPtr cache_;
+ sync_primitives::Lock apps_registration_lock_;
+ sync_primitives::Lock app_permissions_diff_lock_;
+ std::map<std::string, AppPermissions> app_permissions_diff_;
+
+ /**
+ * Timeout to wait response with UpdatePT
+ */
+ uint32_t retry_sequence_timeout_;
+
+ /**
+ * Seconds between retries to update PT
+ */
+ std::vector<int> retry_sequence_seconds_;
+
+ /**
+ * Current index trying of retry sequence
+ */
+ uint32_t retry_sequence_index_;
+
+ /**
+ * Lock for guarding retry sequence
+ */
+ sync_primitives::Lock retry_sequence_lock_;
+
+ /**
+ * Timer to retry UpdatePT
+ */
+ timer::Timer timer_retry_sequence_;
+
+ /**
+ * @brief Device id, which is used during PTU handling for specific
+ * application
+ */
+ mutable std::string last_device_id_;
+
+ bool ignition_check;
+
+ const PolicySettings* settings_;
+ friend struct CheckAppPolicy;
+};
+
+} // namespace policy
+
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_IMPL_H_
diff --git a/src/components/policy/src/policy/include/policy/policy_table.h b/src/components/policy/include/policy/policy_table.h
index fdd4c9c2fc..fdd4c9c2fc 100644
--- a/src/components/policy/src/policy/include/policy/policy_table.h
+++ b/src/components/policy/include/policy/policy_table.h
diff --git a/src/components/policy/include/policy/policy_table/enums.h b/src/components/policy/include/policy/policy_table/enums.h
new file mode 100644
index 0000000000..523c2e9d04
--- /dev/null
+++ b/src/components/policy/include/policy/policy_table/enums.h
@@ -0,0 +1,113 @@
+// This file is generated, do not edit
+#ifndef POLICY_TABLE_INTERFACE_BASE_POLICY_TABLE_INTERFACE_BASE_ENUMS_H_
+#define POLICY_TABLE_INTERFACE_BASE_POLICY_TABLE_INTERFACE_BASE_ENUMS_H_
+#include <string>
+
+namespace rpc {
+namespace policy_table_interface_base {
+
+enum Priority {
+ P_EMERGENCY,
+ P_NAVIGATION,
+ P_VOICECOM,
+ P_COMMUNICATION,
+ P_NORMAL,
+ P_NONE,
+};
+
+bool IsValidEnum(Priority val);
+const char* EnumToJsonString(Priority val);
+bool EnumFromJsonString(const std::string& literal, Priority* result);
+
+enum HmiLevel {
+ HL_BACKGROUND,
+ HL_FULL,
+ HL_LIMITED,
+ HL_NONE,
+};
+bool IsValidEnum(HmiLevel val);
+const char* EnumToJsonString(HmiLevel val);
+bool EnumFromJsonString(const std::string& literal, HmiLevel* result);
+
+enum Parameter {
+ P_GPS,
+ P_SPEED,
+ P_ENGINETORQUE,
+ P_EXTERNALTEMPERATURE,
+ P_FUELLEVEL,
+ P_FUELLEVEL_STATE,
+ P_HEADLAMPSTATUS,
+ P_INSTANTFUELCONSUMPTION,
+ P_ODOMETER,
+ P_TIREPRESSURE,
+ P_WIPERSTATUS,
+ P_VIN,
+ P_ACCPEDALPOSITION,
+ P_BELTSTATUS,
+ P_DRIVERBRAKING,
+ P_PRNDL,
+ P_RPM,
+ P_STEERINGWHEELANGLE,
+ P_MYKEY,
+ P_AIRBAGSTATUS,
+ P_BODYINFORMATION,
+ P_CLUSTERMODESTATUS,
+ P_DEVICESTATUS,
+ P_EMERGENCYEVENT,
+ P_ECALLINFO,
+};
+bool IsValidEnum(Parameter val);
+const char* EnumToJsonString(Parameter val);
+bool EnumFromJsonString(const std::string& literal, Parameter* result);
+
+enum AppHMIType {
+ AHT_DEFAULT,
+ AHT_COMMUNICATION,
+ AHT_MEDIA,
+ AHT_MESSAGING,
+ AHT_NAVIGATION,
+ AHT_INFORMATION,
+ AHT_SOCIAL,
+ AHT_BACKGROUND_PROCESS,
+ AHT_TESTING,
+ AHT_SYSTEM,
+};
+bool IsValidEnum(AppHMIType val);
+const char* EnumToJsonString(AppHMIType val);
+bool EnumFromJsonString(const std::string& literal, AppHMIType* result);
+
+enum RequestType {
+ RT_HTTP,
+ RT_FILE_RESUME,
+ RT_AUTH_REQUEST,
+ RT_AUTH_CHALLENGE,
+ RT_AUTH_ACK,
+ RT_PROPRIETARY,
+ RT_QUERY_APPS,
+ RT_LAUNCH_APP,
+ RT_LOCK_SCREEN_ICON_URL,
+ RT_TRAFFIC_MESSAGE_CHANNEL,
+ RT_DRIVER_PROFILE,
+ RT_VOICE_SEARCH,
+ RT_NAVIGATION,
+ RT_PHONE,
+ RT_CLIMATE,
+ RT_SETTINGS,
+ RT_VEHICLE_DIAGNOSTICS,
+ RT_EMERGENCY,
+ RT_MEDIA,
+ RT_FOTA
+};
+
+bool IsValidEnum(RequestType val);
+const char* EnumToJsonString(RequestType val);
+bool EnumFromJsonString(const std::string& literal, RequestType* result);
+
+extern const std::string kDefaultApp;
+extern const std::string kPreDataConsentApp;
+extern const std::string kDeviceApp;
+
+} // namespace policy_table_interface_base
+} // namespace rpc
+
+#endif // POLICY_TABLE_INTERFACE_BASE_POLICY_TABLE_INTERFACE_BASE_ENUMS_H_
diff --git a/src/components/policy/src/policy/policy_table/table_struct/functions.h b/src/components/policy/include/policy/policy_table/functions.h
index ee4b16b649..ee4b16b649 100644
--- a/src/components/policy/src/policy/policy_table/table_struct/functions.h
+++ b/src/components/policy/include/policy/policy_table/functions.h
diff --git a/src/components/policy/include/policy/policy_table/types.h b/src/components/policy/include/policy/policy_table/types.h
new file mode 100644
index 0000000000..77ef575139
--- /dev/null
+++ b/src/components/policy/include/policy/policy_table/types.h
@@ -0,0 +1,441 @@
+// This file is generated, do not edit
+#ifndef POLICY_TABLE_INTERFACE_BASE_POLICY_TABLE_INTERFACE_BASE_TYPES_H_
+#define POLICY_TABLE_INTERFACE_BASE_POLICY_TABLE_INTERFACE_BASE_TYPES_H_
+#include <climits>
+
+#include "./enums.h"
+#include "rpc_base/rpc_message.h"
+namespace Json {
+class Value;
+} // namespace Json
+namespace rpc {
+namespace policy_table_interface_base {
+struct AppLevel;
+struct ApplicationParams;
+struct DeviceParams;
+struct MessageLanguages;
+struct MessageString;
+struct RpcParameters;
+struct Rpcs;
+} // namespace policy_table_interface_base
+} // namespace rpc
+
+namespace rpc {
+namespace policy_table_interface_base {
+
+// According to HMI API
+#define ODO_MAX 17000000
+
+typedef Array<String<1, 255>, 0, 255> Strings;
+
+typedef Array<Enum<AppHMIType>, 0, 255> AppHMITypes;
+
+typedef Array<Enum<HmiLevel>, 0, 4> HmiLevels;
+
+typedef Array<Enum<Parameter>, 0, 24> Parameters;
+
+typedef Map<RpcParameters, 0, 50> Rpc;
+
+typedef Array<String<10, 255>, 1, 255> URL;
+
+typedef Map<URL, 1, 255> URLList;
+
+typedef Map<URLList, 1, 255> ServiceEndpoints;
+
+typedef uint8_t NumberOfNotificationsType;
+typedef Map<Integer<NumberOfNotificationsType, 0, 255>, 0, 6>
+ NumberOfNotificationsPerMinute;
+
+typedef Array<Integer<uint16_t, 1, 1000>, 0, 10> SecondsBetweenRetries;
+
+typedef Map<MessageString, 0, 500> Languages;
+
+typedef Map<MessageLanguages, 0, 255> Messages;
+
+typedef Map<AppLevel, 0, 255> AppLevels;
+
+typedef Map<Stringifyable<Nullable<ApplicationParams>>, 1, 1000>
+ ApplicationPolicies;
+
+typedef Map<Rpcs, 1, 255> FunctionalGroupings;
+
+typedef Map<DeviceParams, 0, 255> DeviceData;
+
+typedef Array<Enum<RequestType>, 0, 255> RequestTypes;
+
+struct PolicyBase : CompositeType {
+ public:
+ Enum<Priority> priority;
+
+ public:
+ PolicyBase();
+ PolicyBase(Priority priority);
+ virtual ~PolicyBase();
+ explicit PolicyBase(const Json::Value* value__);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+ virtual void SetPolicyTableType(PolicyTableType pt_type);
+
+ private:
+ bool Validate() const;
+};
+
+struct DevicePolicy : PolicyBase {
+ public:
+ DevicePolicy();
+ DevicePolicy(Priority priority);
+ ~DevicePolicy();
+ explicit DevicePolicy(const Json::Value* value__);
+};
+
+struct ApplicationParams : PolicyBase {
+ public:
+ Strings groups;
+ Optional<Strings> nicknames;
+ Optional<AppHMITypes> AppHMIType;
+ Optional<RequestTypes> RequestType;
+ Optional<Integer<uint16_t, 0, 65225>> memory_kb;
+ Optional<Integer<uint32_t, 0, UINT_MAX>> heart_beat_timeout_ms;
+ Optional<String<0, 255>> certificate;
+
+ public:
+ ApplicationParams();
+ ApplicationParams(const Strings& groups, Priority priority);
+ ~ApplicationParams();
+ explicit ApplicationParams(const Json::Value* value__);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+ virtual void SetPolicyTableType(PolicyTableType pt_type);
+
+ private:
+ bool Validate() const;
+};
+
+struct ApplicationPoliciesSection : CompositeType {
+ public:
+ mutable ApplicationPolicies apps;
+ DevicePolicy device;
+
+ public:
+ ApplicationPoliciesSection();
+ ApplicationPoliciesSection(const ApplicationPolicies& apps,
+ const DevicePolicy& device);
+ ~ApplicationPoliciesSection();
+ explicit ApplicationPoliciesSection(const Json::Value* value__);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+ virtual void SetPolicyTableType(PolicyTableType pt_type);
+
+ private:
+ bool Validate() const;
+};
+
+struct RpcParameters : CompositeType {
+ public:
+ HmiLevels hmi_levels;
+ Optional<Parameters> parameters;
+
+ public:
+ RpcParameters();
+ explicit RpcParameters(const HmiLevels& hmi_levels);
+ ~RpcParameters();
+ explicit RpcParameters(const Json::Value* value__);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+ virtual void SetPolicyTableType(PolicyTableType pt_type);
+
+ private:
+ bool Validate() const;
+};
+
+struct Rpcs : CompositeType {
+ public:
+ Optional<String<1, 255>> user_consent_prompt;
+ Nullable<Rpc> rpcs;
+
+ public:
+ Rpcs();
+ explicit Rpcs(const Rpc& rpcs);
+ ~Rpcs();
+ explicit Rpcs(const Json::Value* value__);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+ virtual void SetPolicyTableType(PolicyTableType pt_type);
+
+ private:
+ bool Validate() const;
+};
+
+struct ModuleConfig : CompositeType {
+ public:
+ Optional<Map<String<0, 100>, 0, 255>> device_certificates;
+ Optional<Boolean> preloaded_pt;
+ Integer<uint8_t, 0, 255> exchange_after_x_ignition_cycles;
+ Integer<int64_t, 0, 4294967296ll> exchange_after_x_kilometers;
+ Integer<uint8_t, 0, 255> exchange_after_x_days;
+ Integer<uint16_t, 0, 65535> timeout_after_x_seconds;
+ SecondsBetweenRetries seconds_between_retries;
+ ServiceEndpoints endpoints;
+ NumberOfNotificationsPerMinute notifications_per_minute_by_priority;
+ Optional<String<1, 100>> vehicle_make;
+ Optional<String<1, 100>> vehicle_model;
+ Optional<String<4, 4>> vehicle_year;
+ Optional<String<0, 10>> preloaded_date;
+ Optional<String<0, 65535>> certificate;
+
+ public:
+ ModuleConfig();
+ ModuleConfig(uint8_t exchange_after_x_ignition_cycles,
+ int64_t exchange_after_x_kilometers,
+ uint8_t exchange_after_x_days,
+ uint16_t timeout_after_x_seconds,
+ const SecondsBetweenRetries& seconds_between_retries,
+ const ServiceEndpoints& endpoints,
+ const NumberOfNotificationsPerMinute&
+ notifications_per_minute_by_priority);
+ ~ModuleConfig();
+ explicit ModuleConfig(const Json::Value* value__);
+ void SafeCopyFrom(const ModuleConfig& from);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+ virtual void SetPolicyTableType(PolicyTableType pt_type);
+
+ private:
+ bool Validate() const;
+};
+
+struct MessageString : CompositeType {
+ public:
+ Optional<String<1, 65535>> line1;
+ Optional<String<1, 65535>> line2;
+ Optional<String<1, 65535>> tts;
+ Optional<String<1, 65535>> label;
+ Optional<String<1, 65535>> textBody;
+
+ public:
+ MessageString();
+ ~MessageString();
+ explicit MessageString(const Json::Value* value__);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+ virtual void SetPolicyTableType(PolicyTableType pt_type);
+
+ private:
+ bool Validate() const;
+};
+
+struct MessageLanguages : CompositeType {
+ public:
+ Languages languages;
+
+ public:
+ MessageLanguages();
+ explicit MessageLanguages(const Languages& languages);
+ ~MessageLanguages();
+ explicit MessageLanguages(const Json::Value* value__);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+ virtual void SetPolicyTableType(PolicyTableType pt_type);
+
+ private:
+ bool Validate() const;
+};
+
+struct ConsumerFriendlyMessages : CompositeType {
+ public:
+ String<1, 100> version;
+ Optional<Messages> messages;
+
+ public:
+ ConsumerFriendlyMessages();
+ explicit ConsumerFriendlyMessages(const std::string& version);
+ ~ConsumerFriendlyMessages();
+ explicit ConsumerFriendlyMessages(const Json::Value* value__);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+ virtual void SetPolicyTableType(PolicyTableType pt_type);
+
+ private:
+ bool Validate() const;
+};
+
+struct ModuleMeta : CompositeType {
+ public:
+ Optional<Integer<uint32_t, 0, ODO_MAX>> pt_exchanged_at_odometer_x;
+ Optional<Integer<uint16_t, 0, 65535>> pt_exchanged_x_days_after_epoch;
+ Optional<Integer<uint16_t, 0, 65535>> ignition_cycles_since_last_exchange;
+
+ public:
+ ModuleMeta();
+ ~ModuleMeta();
+ explicit ModuleMeta(const Json::Value* value__);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+
+ private:
+ bool Validate() const;
+};
+
+struct AppLevel : CompositeType {
+ public:
+ Integer<uint16_t, 0, 65535> minutes_in_hmi_full;
+ String<1, 10> app_registration_language_gui;
+ String<0, 10> app_registration_language_vui;
+ Integer<uint16_t, 0, 65535> minutes_in_hmi_limited;
+ Integer<uint16_t, 0, 65535> minutes_in_hmi_background;
+ Integer<uint16_t, 0, 65535> minutes_in_hmi_none;
+ Integer<uint16_t, 0, 65535> count_of_user_selections;
+ Integer<uint16_t, 0, 65535> count_of_rejections_sync_out_of_memory;
+ Integer<uint16_t, 0, 65535> count_of_rejections_nickname_mismatch;
+ Integer<uint16_t, 0, 65535> count_of_rejections_duplicate_name;
+ Integer<uint16_t, 0, 65535> count_of_rejected_rpc_calls;
+ Integer<uint16_t, 0, 65535> count_of_rpcs_sent_in_hmi_none;
+ Integer<uint16_t, 0, 65535> count_of_removals_for_bad_behavior;
+ Integer<uint16_t, 0, 65535> count_of_tls_errors;
+ Integer<uint16_t, 0, 65535> count_of_run_attempts_while_revoked;
+
+ public:
+ AppLevel();
+ AppLevel(uint16_t minutes_in_hmi_full,
+ const std::string& app_registration_language_gui,
+ const std::string& app_registration_language_vui,
+ uint16_t minutes_in_hmi_limited,
+ uint16_t minutes_in_hmi_background,
+ uint16_t minutes_in_hmi_none,
+ uint16_t count_of_user_selections,
+ uint16_t count_of_rejections_sync_out_of_memory,
+ uint16_t count_of_rejections_nickname_mismatch,
+ uint16_t count_of_rejections_duplicate_name,
+ uint16_t count_of_rejected_rpc_calls,
+ uint16_t count_of_rpcs_sent_in_hmi_none,
+ uint16_t count_of_removals_for_bad_behavior,
+ uint16_t count_of_tls_errors,
+ uint16_t count_of_run_attempts_while_revoked);
+ ~AppLevel();
+ explicit AppLevel(const Json::Value* value__);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+
+ private:
+ bool Validate() const;
+};
+
+struct UsageAndErrorCounts : CompositeType {
+ public:
+ Optional<AppLevels> app_level;
+
+ public:
+ UsageAndErrorCounts();
+ ~UsageAndErrorCounts();
+ explicit UsageAndErrorCounts(const Json::Value* value__);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+ virtual void SetPolicyTableType(PolicyTableType pt_type);
+
+ private:
+ bool Validate() const;
+};
+
+struct DeviceParams : CompositeType {
+ public:
+ DeviceParams();
+ ~DeviceParams();
+ explicit DeviceParams(const Json::Value* value__);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+
+ private:
+ bool Validate() const;
+};
+
+struct PolicyTable : CompositeType {
+ public:
+ ApplicationPoliciesSection app_policies_section;
+ FunctionalGroupings functional_groupings;
+ Optional<ConsumerFriendlyMessages> consumer_friendly_messages;
+ ModuleConfig module_config;
+ Optional<ModuleMeta> module_meta;
+ Optional<UsageAndErrorCounts> usage_and_error_counts;
+ Optional<DeviceData> device_data;
+
+ public:
+ PolicyTable();
+ PolicyTable(const ApplicationPoliciesSection& app_policies_section,
+ const FunctionalGroupings& functional_groupings,
+ const ConsumerFriendlyMessages& consumer_friendly_messages,
+ const ModuleConfig& module_config);
+ ~PolicyTable();
+ explicit PolicyTable(const Json::Value* value__);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+ virtual void SetPolicyTableType(PolicyTableType pt_type);
+
+ private:
+ bool Validate() const;
+};
+
+struct Table : CompositeType {
+ public:
+ PolicyTable policy_table;
+
+ public:
+ Table();
+ explicit Table(const PolicyTable& policy_table);
+ ~Table();
+ explicit Table(const Json::Value* value__);
+ Json::Value ToJsonValue() const;
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool struct_empty() const;
+ void ReportErrors(rpc::ValidationReport* report__) const;
+ virtual void SetPolicyTableType(PolicyTableType pt_type);
+
+ private:
+ bool Validate() const;
+};
+} // namespace policy_table_interface_base
+} // namespace rpc
+
+#endif // POLICY_TABLE_INTERFACE_BASE_POLICY_TABLE_INTERFACE_BASE_TYPES_H_
diff --git a/src/components/policy/include/policy/pt_ext_representation.h b/src/components/policy/include/policy/pt_ext_representation.h
new file mode 100644
index 0000000000..2c5db4f002
--- /dev/null
+++ b/src/components/policy/include/policy/pt_ext_representation.h
@@ -0,0 +1,333 @@
+/*
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_PT_EXT_REPRESENTATION_H_
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_PT_EXT_REPRESENTATION_H_
+
+#include "policy/pt_representation.h"
+
+namespace policy {
+
+enum StatisticsType {
+ S_NONE = 0,
+ S_IAP_BUFFER_FULL,
+ S_SYNC_OUT_OF_MEMORY,
+ S_SYNC_REBOOTS,
+ S_MINS_HMI_FULL,
+ S_MINS_HMI_LIMITED,
+ S_MINS_HMI_BACKGROUND,
+ S_MINS_HMI_NONE,
+ S_RFCOM_LIMIT_REACHED,
+ S_USER_SELECTIONS,
+ S_REJECTIONS_SYNC_OUT_OF_MEMORY,
+ S_REJECTIONS_NICKNAME_MISMATCH,
+ S_REJECTIONS_DUPLICATE_NAME,
+ S_REJECTED_RPC_CALLS,
+ S_RPCS_IN_HMI_NONE,
+ S_REMOVALS_MISBEHAVED,
+ S_RUN_ATTEMPTS_WHILE_REVOKED
+};
+
+enum LanguageType { L_NONE = 0, L_GUI, L_VUI };
+
+class PTExtRepresentation : public virtual PTRepresentation {
+ public:
+ virtual ~PTExtRepresentation() {}
+
+ /**
+ * @brief Is application allowed to send notifications while in
+ * Backgound or limited mode.
+ * @param app_id Application id
+ * @return bool Allowed/disallowed.
+ */
+ virtual bool CanAppKeepContext(const std::string& app_id) = 0;
+
+ /**
+ * @brief Is application allowed to move foreground at will?
+ * @param app_id Application id
+ * @return bool Allowed/disallowed.
+ */
+ virtual bool CanAppStealFocus(const std::string& app_id) = 0;
+
+ /**
+ * @brief Get default_hmi for given application
+ * @param policy_app_id Unique application id
+ * @param default_hmi Default HMI level for application or empty, if value was
+ * not set
+ * @return true, if succedeed, otherwise - false
+ */
+ virtual bool GetDefaultHMI(const std::string& policy_app_id,
+ std::string* default_hmi) = 0;
+
+ /**
+ * @brief Reset user consent for device data and applications permissions
+ * @return
+ */
+ virtual bool ResetUserConsent() = 0;
+
+ /**
+ * @brief Reset user consent for device data
+ * @return
+ */
+ virtual bool ResetDeviceConsents() = 0;
+
+ /**
+ * @brief Reset user consent for applications permissions
+ * @return
+ */
+ virtual bool ResetAppConsents() = 0;
+
+ /**
+ * @brief Get user permissions for device data usage
+ * @param device_id Generated or obtained id of device
+ * @param consented_groups Groups consented by user
+ * @param disallowed_groups Groups not consented by user
+ * @return true, if query was successfull, otherwise - false
+ */
+ virtual bool GetUserPermissionsForDevice(
+ const std::string& device_id,
+ StringArray* consented_groups = NULL,
+ StringArray* disallowed_groups = NULL) = 0;
+
+ /**
+ * @brief Gets list of groups permissions from policy table
+ * @param device_id Unique device id, which hosts specific application
+ * @param policy_app_id Unique application id
+ * @param group_types Group list sorted by permission status
+ * @return true, if query was successfull, otherwise - false
+ */
+ virtual bool GetPermissionsForApp(const std::string& device_id,
+ const std::string& policy_app_id,
+ FunctionalIdType* group_types) = 0;
+
+ /**
+ * @brief Get device groups and preconsented groups from policies section
+ * @param groups List of groups to be consented for device usage
+ * @param preconsented_groups List of preconsented groups for device usage
+ * @return true, if query was successful, otherwise - false
+ */
+ virtual bool GetDeviceGroupsFromPolicies(
+ policy_table::Strings* groups = NULL,
+ policy_table::Strings* preconsented_groups = NULL) = 0;
+
+ /**
+ * @brief Record information about mobile device in Policy Table.
+ * @param device_id Generated or obtained id of device
+ * @return bool Success of operation
+ */
+ virtual bool SetDeviceData(const std::string& device_id,
+ const std::string& hardware = "",
+ const std::string& firmware = "",
+ const std::string& os = "",
+ const std::string& os_version = "",
+ const std::string& carrier = "",
+ const uint32_t number_of_ports = 0,
+ const std::string& connection_type = "") = 0;
+
+ /**
+ * @brief Sets user consent for particular mobile device,
+ * i.e. to use device for exchanging of Policy Table.
+ * @return bool Success of operation
+ */
+ virtual bool SetUserPermissionsForDevice(
+ const std::string& device_id,
+ const StringArray& consented_groups = StringArray(),
+ const StringArray& disallowed_gropus = StringArray()) = 0;
+
+ /**
+ * @brief Update Application Policies as reaction
+ * on User allowing/disallowing device this app is running on.
+ */
+ virtual bool ReactOnUserDevConsentForApp(const std::string& app_id,
+ bool is_device_allowed) = 0;
+
+ /**
+ * @brief Set user consent on functional groups
+ * @param permissions User consent on functional group
+ * @return true, if operation succedeed, otherwise - false
+ */
+ virtual bool SetUserPermissionsForApp(
+ const PermissionConsent& permissions) = 0;
+
+ /**
+ * @brief Counter for statistics information: adds 1 to existing number.
+ * @param type Type of statistics (errors, mins in mode etc)
+ * @return bool Success of operation
+ */
+ virtual bool IncreaseStatisticsData(StatisticsType type) = 0;
+
+ /**
+ * @brief Records information about what language
+ * application tried to register with.
+ * @param app_id Id of application
+ * @param type - language for UI/VR
+ * @param language Language
+ * @return bool Success of operation
+ */
+ virtual bool SetAppRegistrationLanguage(const std::string& app_id,
+ LanguageType type,
+ const std::string& language) = 0;
+
+ /**
+ * @brief Records information about head unit system to PT
+ * @return bool Success of operation
+ */
+ virtual bool SetMetaInfo(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language) = 0;
+
+ /**
+ * @brief Checks, if specific head unit is present in PT
+ * @return boot Suceess, if present, otherwise - false
+ */
+ virtual bool IsMetaInfoPresent() = 0;
+
+ /**
+ * @brief Kms pass since last successfull PT update
+ */
+ virtual int GetKmFromSuccessfulExchange() = 0;
+
+ /**
+ * @brief Days pass since last successfull PT update
+ */
+ virtual int GetDayFromScsExchange() = 0;
+
+ /**
+ * @brief Ignition cycles pass since last successfull PT update
+ */
+ virtual int GetIgnitionsFromScsExchange() = 0;
+
+ /**
+ * @brief Set current system language
+ * @param language System language
+ * @return true, if succedeed, otherwise - false
+ */
+ virtual bool SetSystemLanguage(const std::string& language) = 0;
+
+ /**
+ * Increments global counter
+ * @param type type of counter
+ */
+ virtual void Increment(const std::string& type) const = 0;
+
+ /**
+ * Increments counter of application
+ * @param app_id id application
+ * @param type type of counter
+ */
+ virtual void Increment(const std::string& app_id,
+ const std::string& type) const = 0;
+
+ /**
+ * Sets value of application information
+ * @param app_id id application
+ * @param type type of information
+ * @param value value of information
+ */
+ virtual void Set(const std::string& app_id,
+ const std::string& type,
+ const std::string& value) const = 0;
+
+ /**
+ * Adds value to stopwatch of application
+ * @param app_id id application
+ * @param type type of stopwatch
+ * @param seconds value for adding in seconds
+ */
+ virtual void Add(const std::string& app_id,
+ const std::string& type,
+ int seconds) const = 0;
+
+ virtual bool CountUnconsentedGroups(const std::string& policy_app_id,
+ const std::string& device_id,
+ int* result) const = 0;
+
+ /**
+ * @brief Gets functional group names and user_consent_prompts, if any
+ * @param Array to be filled with group ids, names and functional prompts
+ * @return true, if succeeded, otherwise - false
+ */
+ // TODO(AOleynik): Possibly, we can get rid of this method. Check this.
+ virtual bool GetFunctionalGroupNames(policy::FunctionalGroupNames& names) = 0;
+
+ /**
+ * @brief Set app policy to pre_DataConsented policy
+ * @param app_id Policy ID of application to be changed
+ * @return true, if succeeded, otherwise - false
+ */
+ virtual bool SetPredataPolicy(const std::string& app_id) = 0;
+
+ /**
+ * @brief Updates application policy to either pre_DataConsented or not
+ * @param app_id Policy Id of application to be checked
+ * @param is_pre_data True of False to setting app policy to be
+ * pre_DataConsented
+ * @return true, if succeeded, otherwise - false
+ */
+ virtual bool SetIsPredata(const std::string& app_id, bool is_pre_data) = 0;
+
+ /**
+ * @brief Removes unpaired devices
+ * @return true if success
+ */
+ virtual bool CleanupUnpairedDevices(const DeviceIds& device_ids) const = 0;
+
+ /**
+ * Sets flag of unpaired device
+ * @param device_id Unique device id
+ * @param unpaired True, if unpaired, otherwise - false
+ * @return true if success
+ */
+ virtual bool SetUnpairedDevice(const std::string& device_id,
+ bool unpaired) const = 0;
+
+ /**
+ * Gets list of unpaired devices
+ * @param device_ids output list
+ * @return true if success
+ */
+ virtual bool UnpairedDevicesList(DeviceIds* device_ids) const = 0;
+
+ /**
+ * @brief Remove application consent for particular group
+ * @param policy_app_id Unique application id
+ * @param functional_group_name Functional group name, which consents should
+ * be removed
+ * @return true, in case of success, otherwise - false
+ */
+ virtual bool RemoveAppConsentForGroup(
+ const std::string& policy_app_id,
+ const std::string& functional_group_name) const = 0;
+};
+} // namespace policy
+
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_PT_EXT_REPRESENTATION_H_
diff --git a/src/components/policy/include/policy/pt_representation.h b/src/components/policy/include/policy/pt_representation.h
new file mode 100644
index 0000000000..122f5326d8
--- /dev/null
+++ b/src/components/policy/include/policy/pt_representation.h
@@ -0,0 +1,324 @@
+/*
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_PT_REPRESENTATION_H_
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_PT_REPRESENTATION_H_
+
+#include <vector>
+#include <string>
+#include "policy/policy_types.h"
+#include "policy/policy_table/types.h"
+#include "policy/policy_settings.h"
+
+namespace policy_table = rpc::policy_table_interface_base;
+
+namespace policy {
+
+enum InitResult { NONE = 0, EXISTS, SUCCESS, FAIL };
+
+class PTRepresentation {
+ public:
+ virtual ~PTRepresentation() {}
+
+ /**
+ * @brief Check if specified RPC for specified application
+ * has permission to be executed in specified HMI Level
+ * and also its permitted params.
+ * @param app_id Id of application provided during registration
+ * @param hmi_level Current HMI Level of application
+ * @param rpc Name of RPC
+ * @params CheckPermissionResult containing flag if HMI Level is allowed
+ * and list of allowed params.
+ */
+ virtual void CheckPermissions(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ CheckPermissionResult& result) = 0;
+
+ /**
+ * @brief Returns true if Policy Table was not updated yet
+ * from preloaded pt file.
+ */
+ virtual bool IsPTPreloaded() = 0;
+
+ virtual bool RefreshDB() = 0;
+ /**
+ * Gets number of ignition cycles before next update policy table
+ * @return number of ignition cycles
+ */
+ virtual int IgnitionCyclesBeforeExchange() = 0;
+
+ /**
+ * Gets value in kilometers before next update policy table
+ * @param current value in kilometers from the odometers
+ * @return value in kilometers
+ */
+ virtual int KilometersBeforeExchange(int current) = 0;
+
+ /**
+ * @brief Sets kilometers and days after epoch, that passed for recieved
+ * successful PT UPdate
+ */
+ virtual bool SetCountersPassedForSuccessfulUpdate(int kilometers,
+ int days_after_epoch) = 0;
+
+ /**
+ * Gets value in days before next update policy table
+ * @param current value in days after epoch
+ * @return value in days
+ */
+ virtual int DaysBeforeExchange(int current) = 0;
+
+ /**
+ * @brief Increment number of ignition cycles since last exchange by 1
+ */
+ virtual void IncrementIgnitionCycles() = 0;
+
+ /**
+ * @brief Reset number of ignition cycles since last exchange to 0
+ */
+ virtual void ResetIgnitionCycles() = 0;
+
+ /**
+ * @brief Returns timeout to wait for a response of PT update
+ * @return value in seconds
+ */
+ virtual int TimeoutResponse() = 0;
+
+ /**
+ * @brief Returns number of seconds between each try of sending PTS
+ * @param seconds Return value: array of 5 elements
+ * @return bool Success of operation
+ */
+ virtual bool SecondsBetweenRetries(std::vector<int>* seconds) = 0;
+
+ /**
+ * @brief Get information about vehicle
+ */
+ virtual const VehicleInfo GetVehicleInfo() const = 0;
+
+ /**
+ * @brief Allows to update 'vin' field in module_meta table.
+ *
+ * @param new 'vin' value.
+ *
+ * @return true in case when data has been successfully updated,
+ * false otherwise.
+ */
+ virtual bool SetVINValue(const std::string& value) = 0;
+
+ /**
+ * @brief Get message text for displaying/pronouncing for user
+ * dependent on language and context.
+ * @param msg_codes Context of message (Driver distraction, Grant permission
+ * etc)
+ * @param language Language of the message
+ * @return Array of appropriate messages parameters
+ */
+ virtual std::vector<UserFriendlyMessage> GetUserFriendlyMsg(
+ const std::vector<std::string>& msg_codes,
+ const std::string& language) = 0;
+
+ /**
+ * @brief Get list of URL to send PTS to
+ * @param service_type If URLs for specific service are preset,
+ * return them otherwise default URLs.
+ */
+ virtual EndpointUrls GetUpdateUrls(int service_type) = 0;
+
+ /**
+ * @brief GetLockScreenIcon allows to obtain lock screen icon url;
+ *
+ * @return url which point to the resourse where lock screen icon could be
+ *obtained.
+ */
+ virtual std::string GetLockScreenIconUrl() const = 0;
+
+ /**
+ * @brief Get allowed number of notifications
+ * depending on application priority.
+ * @param priority Priority of application
+ */
+ virtual int GetNotificationsNumber(const std::string& priority) = 0;
+
+ /**
+ * @brief Get priority for given application
+ * @param policy_app_id Unique application id
+ * @param priority Priority for application or empty, if value was not set
+ * @return true, if succedeed, otherwise - false
+ */
+ virtual bool GetPriority(const std::string& policy_app_id,
+ std::string* priority) = 0;
+
+ /**
+ * @brief Initialized Policy Table (load)
+ * @return bool Success of operation
+ */
+ virtual InitResult Init(const PolicySettings* settings) = 0;
+
+ /**
+ * @brief Close policy table
+ * @return bool Success of operation
+ */
+ virtual bool Close() = 0;
+
+ /**
+ * @brief Removes policy table content.
+ * @return bool Success of operation
+ */
+ virtual bool Clear() = 0;
+
+ /**
+ * Drops policy table (schema and content)
+ * @return true if successfully
+ */
+ virtual bool Drop() = 0;
+
+ /**
+ * @brief Get snapshot of Policy Table
+ * including app_policies, functional_groups,
+ * device_info, statistics, excluding user messages
+ * @return Generated structure for obtaining Json string.
+ */
+ virtual utils::SharedPtr<policy_table::Table> GenerateSnapshot() const = 0;
+
+ virtual bool Save(const policy_table::Table& table) = 0;
+
+ /**
+ * Gets flag updateRequired
+ * @return true if update is required
+ */
+ virtual bool UpdateRequired() const = 0;
+
+ /**
+ * Saves flag updateRequired
+ */
+ virtual void SaveUpdateRequired(bool value) = 0;
+
+ /*
+ Retrieves data from app_policies about app on its registration:
+ app_id - id of registered app; all outputs are filled in only if not null
+ output: nicknames Synonyms for application
+ output: app_types Section on HMI where app can appear (Navigation, Phone etc)
+ */
+ virtual bool GetInitialAppData(const std::string& app_id,
+ StringArray* nicknames = NULL,
+ StringArray* app_types = NULL) = 0;
+
+ /**
+ * Checks if the application is revoked
+ * @param app_id application id
+ * @return true if application is revoked
+ */
+ virtual bool IsApplicationRevoked(const std::string& app_id) const = 0;
+
+ /**
+ * @brief Get functional groupings from DB
+ * @param groups Known functional groupings
+ * @return true, if succeeded, otherwise - false
+ */
+ virtual bool GetFunctionalGroupings(
+ policy_table::FunctionalGroupings& groups) = 0;
+
+ /**
+ * Checks if the application is represented in policy table
+ * @param app_id application id
+ * @return true if application is represented in policy table
+ */
+ virtual bool IsApplicationRepresented(const std::string& app_id) const = 0;
+
+ /**
+ * Checks if the application has default policy
+ * @param app_id application id
+ * @return true if application has default policy
+ */
+ virtual bool IsDefaultPolicy(const std::string& app_id) const = 0;
+
+ /**
+ * Checks if the application has pre_data policy
+ * @param app_id application id
+ * @return true if application has pre_data policy
+ */
+ virtual bool IsPredataPolicy(const std::string& app_id) const = 0;
+
+ /**
+ * Sets default policy for application
+ * @param app_id application id
+ * @return true if success
+ */
+ virtual bool SetDefaultPolicy(const std::string& app_id) = 0;
+
+ /**
+ * @brief SaveApplicationCustomData allows to save specific data to database.
+ * This data is only for internal use.
+ * @param app_id the application id for which the data will be saved.
+ * @param is_revoked parameter to save.
+ * @param is_default parameter to save.
+ * @param is_predata parameter to save.
+ */
+ virtual bool SaveApplicationCustomData(const std::string& app_id,
+ bool is_revoked,
+ bool is_default,
+ bool is_predata) = 0;
+
+ virtual void WriteDb() = 0;
+
+ /**
+ * @brief RemoveDB allows to remove the database.
+ * It will either remove or do nothing in case file not exists or any other
+ * troubles are happens during this operation.
+ */
+ virtual void RemoveDB() const = 0;
+
+ /**
+ * @brief Checks if DB version is actual to current schema
+ * @return true if actual, otherwise - false
+ */
+ virtual bool IsDBVersionActual() const = 0;
+
+ /**
+ * @brief Updates DB version according to current schema
+ * @return true if success, otherwise - false
+ */
+ virtual bool UpdateDBVersion() const = 0;
+
+ protected:
+ const PolicySettings& get_settings() const {
+ DCHECK(settings_);
+ return *settings_;
+ }
+ const PolicySettings* settings_;
+};
+
+} // namespace policy
+
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_PT_REPRESENTATION_H_
diff --git a/src/components/policy/src/policy/include/policy/sql_pt_ext_queries.h b/src/components/policy/include/policy/sql_pt_ext_queries.h
index 2b65df45f3..2b65df45f3 100644
--- a/src/components/policy/src/policy/include/policy/sql_pt_ext_queries.h
+++ b/src/components/policy/include/policy/sql_pt_ext_queries.h
diff --git a/src/components/policy/include/policy/sql_pt_ext_representation.h b/src/components/policy/include/policy/sql_pt_ext_representation.h
new file mode 100644
index 0000000000..1d33750b12
--- /dev/null
+++ b/src/components/policy/include/policy/sql_pt_ext_representation.h
@@ -0,0 +1,205 @@
+/*
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_EXT_REPRESENTATION_H_
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_EXT_REPRESENTATION_H_
+
+#include <string>
+#include "policy/sql_pt_representation.h"
+#include "policy/pt_ext_representation.h"
+
+namespace policy {
+
+class SQLPTExtRepresentation : public SQLPTRepresentation,
+ public PTExtRepresentation {
+ public:
+ bool CanAppKeepContext(const std::string& app_id);
+ bool CanAppStealFocus(const std::string& app_id);
+ bool GetDefaultHMI(const std::string& policy_app_id,
+ std::string* default_hmi);
+ bool ResetUserConsent();
+ bool ResetDeviceConsents();
+ bool ResetAppConsents();
+ bool GetUserPermissionsForDevice(const std::string& device_id,
+ StringArray* consented_groups = NULL,
+ StringArray* disallowed_groups = NULL);
+
+ bool GetPermissionsForApp(const std::string& device_id,
+ const std::string& policy_app_id,
+ FunctionalIdType* group_types);
+
+ bool GetDeviceGroupsFromPolicies(
+ policy_table::Strings* groups = NULL,
+ policy_table::Strings* preconsented_groups = NULL);
+ bool SetDeviceData(const std::string& device_id,
+ const std::string& hardware = "",
+ const std::string& firmware = "",
+ const std::string& os = "",
+ const std::string& os_version = "",
+ const std::string& carrier = "",
+ const uint32_t number_of_ports = 0,
+ const std::string& connection_type = "");
+ bool SetUserPermissionsForDevice(
+ const std::string& device_id,
+ const StringArray& consented_groups = StringArray(),
+ const StringArray& disallowed_groups = StringArray());
+
+ bool ReactOnUserDevConsentForApp(const std::string& app_id,
+ bool is_device_allowed);
+
+ bool SetUserPermissionsForApp(const PermissionConsent& permissions);
+
+ std::vector<UserFriendlyMessage> GetUserFriendlyMsg(
+ const std::vector<std::string>& msg_codes, const std::string& language);
+
+ bool IncreaseStatisticsData(StatisticsType type) {
+ return true;
+ }
+ bool SetAppRegistrationLanguage(const std::string& app_id,
+ LanguageType type,
+ const std::string& language) {
+ return true;
+ }
+
+ bool SetMetaInfo(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language);
+
+ bool IsMetaInfoPresent();
+
+ bool SetSystemLanguage(const std::string& language);
+
+ int GetKmFromSuccessfulExchange() {
+ return true;
+ }
+ int GetDayFromScsExchange() {
+ return true;
+ }
+ int GetIgnitionsFromScsExchange() {
+ return true;
+ }
+
+ bool GetFunctionalGroupNames(FunctionalGroupNames& names);
+ bool CleanupUnpairedDevices(const DeviceIds& device_ids) const;
+
+ void Increment(const std::string& type) const;
+ void Increment(const std::string& app_id, const std::string& type) const;
+ void Set(const std::string& app_id,
+ const std::string& type,
+ const std::string& value) const;
+ void Add(const std::string& app_id,
+ const std::string& type,
+ int seconds) const;
+ bool SetDefaultPolicy(const std::string& app_id);
+ bool SetPredataPolicy(const std::string& app_id);
+ bool SetIsPredata(const std::string& app_id, bool is_pre_data);
+ bool IsPredataPolicy(const std::string& app_id) const;
+ bool SetUnpairedDevice(const std::string& device_id, bool unpaired) const;
+ bool UnpairedDevicesList(DeviceIds* device_ids) const;
+ bool RemoveAppConsentForGroup(const std::string& policy_app_id,
+ const std::string& functional_group_name) const;
+
+ virtual bool SetVINValue(const std::string& value);
+
+ private:
+ void GatherModuleMeta(policy_table::ModuleMeta* meta) const;
+ void GatherPreconsentedGroup(const std::string& app_id,
+ policy_table::Strings* groups) const;
+ bool GatherUsageAndErrorCounts(
+ policy_table::UsageAndErrorCounts* counts) const;
+ bool GatherAppLevels(policy_table::AppLevels* apps) const;
+ void GatherDeviceData(policy_table::DeviceData* data) const;
+ void GatherConsentGroup(const std::string& device_id,
+ policy_table::UserConsentRecords* records) const;
+ bool GatherApplicationPoliciesSection(
+ policy_table::ApplicationPoliciesSection* policies) const;
+ bool SaveDeviceData(const policy_table::DeviceData& devices);
+ bool GatherConsumerFriendlyMessages(
+ policy_table::ConsumerFriendlyMessages* messages) const;
+ bool SaveConsentGroup(const std::string& device_id,
+ const policy_table::UserConsentRecords& records);
+ bool SaveApplicationPoliciesSection(
+ const policy_table::ApplicationPoliciesSection& policies);
+ bool SaveSpecificAppPolicy(
+ const policy_table::ApplicationPolicies::value_type& app);
+ bool SaveDevicePolicy(const policy_table::DevicePolicy& device);
+ bool SavePreconsentedGroup(const std::string& app_id,
+ const policy_table::Strings& groups);
+ bool SaveMessageString(const std::string& type,
+ const std::string& lang,
+ const policy_table::MessageString& strings);
+
+ virtual bool SaveUsageAndErrorCounts(
+ const policy_table::UsageAndErrorCounts& counts);
+
+ virtual bool SaveModuleMeta(const policy_table::ModuleMeta& meta);
+
+ bool SaveAppCounters(const policy_table::AppLevels& app_levels);
+
+ bool SaveGlobalCounters(const policy_table::UsageAndErrorCounts& counts);
+
+ bool IsExistAppLevel(const std::string& app_id) const;
+
+ bool GetAllAppGroups(const std::string& policy_app_id,
+ FunctionalGroupIDs& all_groups);
+
+ bool GetConsentedGroups(const std::string& policy_app_id,
+ const std::string& device_id,
+ FunctionalGroupIDs& allowed_groups,
+ FunctionalGroupIDs& disallowed_groups);
+
+ bool GetPreconsentedGroups(const std::string& policy_app_id,
+ FunctionalGroupIDs& preconsented_groups);
+
+ void FillFunctionalGroupPermissions(
+ FunctionalGroupIDs& ids,
+ FunctionalGroupNames& names,
+ GroupConsent state,
+ std::vector<FunctionalGroupPermission>& permissions);
+ bool CountUnconsentedGroups(const std::string& policy_app_id,
+ const std::string& device_id,
+ int* result) const;
+
+ /**
+ * @brief Checks, if there is message present with requested language in PT
+ * @param message Message name
+ * @param language Required message language
+ * @return True, if message with requested language is present, otherwise -
+ * false
+ */
+ bool IsMsgLanguagePresent(const std::string& message,
+ const std::string& language);
+};
+
+} // namespace policy
+
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_EXT_REPRESENTATION_H_
diff --git a/src/components/policy/include/policy/sql_pt_queries.h b/src/components/policy/include/policy/sql_pt_queries.h
new file mode 100644
index 0000000000..cf3028b0a0
--- /dev/null
+++ b/src/components/policy/include/policy/sql_pt_queries.h
@@ -0,0 +1,125 @@
+/*
+ Copyright (c) 2013, " Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, " with or without
+ modification, " are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, " this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice, "
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, " INCLUDING, " BUT NOT LIMITED TO, " THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, " INDIRECT, " INCIDENTAL, " SPECIAL, " EXEMPLARY, " OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, " BUT NOT LIMITED TO, " PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, " DATA, " OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, " WHETHER IN
+ CONTRACT, " STRICT LIABILITY, " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, " EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_QUERIES_H_
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_QUERIES_H_
+
+#include <string>
+
+namespace policy {
+namespace sql_pt {
+
+extern const std::string kSelectPriority;
+extern const std::string kCreateSchema;
+extern const std::string kDropSchema;
+extern const std::string kDeleteData;
+extern const std::string kCheckPgNumber;
+extern const std::string kCheckDBIntegrity;
+extern const std::string kSelectRpc;
+extern const std::string kSelectPreloaded;
+extern const std::string kIsFirstRun;
+extern const std::string kSetNotFirstRun;
+extern const std::string kSelectEndpoint;
+extern const std::string kSelectLockScreenIcon;
+extern const std::string kSelectModuleConfig;
+extern const std::string kSelectEndpoints;
+extern const std::string kSelectNotificationsPerMin;
+extern const std::string kSelectNotificationsPerPriority;
+extern const std::string kSelectAppLevels;
+extern const std::string kSelectDeviceData;
+extern const std::string kSelectFunctionalGroups;
+extern const std::string kSelectAllRpcs;
+extern const std::string kSelectUserMsgsVersion;
+extern const std::string kSelectAppPolicies;
+extern const std::string kCollectFriendlyMsg;
+extern const std::string kSelectAppGroups;
+extern const std::string kSelectNicknames;
+extern const std::string kSelectAppTypes;
+extern const std::string kSelectRequestTypes;
+extern const std::string kSelectSecondsBetweenRetries;
+extern const std::string kSelectIgnitionCycles;
+extern const std::string kSelectKilometers;
+extern const std::string kSelectDays;
+extern const std::string kSelectTimeoutResponse;
+extern const std::string kInsertFunctionalGroup;
+extern const std::string kInsertRpc;
+extern const std::string kInsertRpcWithParameter;
+extern const std::string kInsertApplication;
+extern const std::string kInsertAppGroup;
+extern const std::string kInsertNickname;
+extern const std::string kInsertAppType;
+extern const std::string kInsertRequestType;
+extern const std::string kInsertMessageType;
+extern const std::string kInsertLanguage;
+extern const std::string kInsertMessageString;
+extern const std::string kUpdateVersion;
+extern const std::string kUpdateModuleConfig;
+extern const std::string kInsertEndpoint;
+extern const std::string kInsertSecondsBetweenRetry;
+extern const std::string kInsertNotificationsByPriority;
+extern const std::string kInsertDeviceData;
+extern const std::string kInsertAppLevel;
+extern const std::string kDeleteSecondsBetweenRetries;
+extern const std::string kDeleteEndpoint;
+extern const std::string kDeleteAppLevel;
+extern const std::string kDeleteMessageString;
+extern const std::string kDeleteFunctionalGroup;
+extern const std::string kDeleteRpc;
+extern const std::string kDeleteAppGroup;
+extern const std::string kDeleteApplication;
+extern const std::string kDeleteRequestType;
+extern const std::string kDeleteDevice;
+extern const std::string kIncrementIgnitionCycles;
+extern const std::string kResetIgnitionCycles;
+extern const std::string kUpdateFlagUpdateRequired;
+extern const std::string kSelectFlagUpdateRequired;
+extern const std::string kUpdateCountersSuccessfulUpdate;
+extern const std::string kSelectApplicationRevoked;
+extern const std::string kUpdateApplicationCustomData;
+extern const std::string kSelectApplicationRepresented;
+extern const std::string kSelectApplicationIsDefault;
+extern const std::string kUpdateIsDefault;
+extern const std::string kInsertInitData;
+extern const std::string kDeleteAppGroupByApplicationId;
+extern const std::string kInsertApplicationFull;
+extern const std::string kDeletePreconsentedGroupsByApplicationId;
+extern const std::string kSelectApplicationFull;
+extern const std::string kUpdatePreloaded;
+extern const std::string kSelectDBVersion;
+extern const std::string kUpdateDBVersion;
+extern const std::string kSaveModuleMeta;
+extern const std::string kSelectModuleMeta;
+
+} // namespace sql_pt
+} // namespace policy
+
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_QUERIES_H_
diff --git a/src/components/policy/include/policy/sql_pt_representation.h b/src/components/policy/include/policy/sql_pt_representation.h
new file mode 100644
index 0000000000..89ee3788f0
--- /dev/null
+++ b/src/components/policy/include/policy/sql_pt_representation.h
@@ -0,0 +1,203 @@
+/*
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_REPRESENTATION_H_
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_REPRESENTATION_H_
+
+#include <string>
+#include <vector>
+#include "policy/pt_representation.h"
+#include "rpc_base/rpc_base.h"
+#include "policy/policy_table/types.h"
+
+namespace policy_table = rpc::policy_table_interface_base;
+
+namespace utils {
+namespace dbms {
+class SQLDatabase;
+} // namespace dbms
+} // namespace utils
+
+namespace policy {
+
+class SQLPTRepresentation : public virtual PTRepresentation {
+ public:
+ SQLPTRepresentation();
+ ~SQLPTRepresentation();
+ virtual void CheckPermissions(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ CheckPermissionResult& result);
+
+ virtual bool IsPTPreloaded();
+ virtual int IgnitionCyclesBeforeExchange();
+ virtual int KilometersBeforeExchange(int current);
+ virtual bool SetCountersPassedForSuccessfulUpdate(int kilometers,
+ int days_after_epoch);
+ virtual int DaysBeforeExchange(int current);
+ virtual void IncrementIgnitionCycles();
+ virtual void ResetIgnitionCycles();
+ virtual int TimeoutResponse();
+ virtual bool SecondsBetweenRetries(std::vector<int>* seconds);
+ virtual bool RefreshDB();
+ virtual const VehicleInfo GetVehicleInfo() const;
+
+ virtual std::vector<UserFriendlyMessage> GetUserFriendlyMsg(
+ const std::vector<std::string>& msg_codes, const std::string& language);
+
+ virtual EndpointUrls GetUpdateUrls(int service_type);
+ virtual std::string GetLockScreenIconUrl() const;
+ virtual int GetNotificationsNumber(const std::string& priority);
+ virtual bool GetPriority(const std::string& policy_app_id,
+ std::string* priority);
+ InitResult Init(const PolicySettings* settings);
+ bool Close();
+ bool Clear();
+ bool Drop();
+ virtual void WriteDb();
+ virtual utils::SharedPtr<policy_table::Table> GenerateSnapshot() const;
+ virtual bool Save(const policy_table::Table& table);
+ bool GetInitialAppData(const std::string& app_id,
+ StringArray* nicknames = NULL,
+ StringArray* app_hmi_types = NULL);
+ bool GetFunctionalGroupings(policy_table::FunctionalGroupings& groups);
+
+#ifdef BUILD_TESTS
+ uint32_t open_counter() {
+ return open_counter_;
+ }
+#endif // BUILD_TESTS
+ protected:
+ virtual void GatherModuleMeta(policy_table::ModuleMeta* meta) const;
+ virtual void GatherModuleConfig(policy_table::ModuleConfig* config) const;
+ virtual bool GatherUsageAndErrorCounts(
+ policy_table::UsageAndErrorCounts* counts) const;
+ virtual void GatherDeviceData(policy_table::DeviceData* data) const;
+ virtual bool GatherFunctionalGroupings(
+ policy_table::FunctionalGroupings* groups) const;
+ virtual bool GatherConsumerFriendlyMessages(
+ policy_table::ConsumerFriendlyMessages* messages) const;
+ virtual bool GatherApplicationPoliciesSection(
+ policy_table::ApplicationPoliciesSection* policies) const;
+
+ bool GatherAppGroup(const std::string& app_id,
+ policy_table::Strings* app_groups) const;
+ bool GatherAppType(const std::string& app_id,
+ policy_table::AppHMITypes* app_types) const;
+ bool GatherRequestType(const std::string& app_id,
+ policy_table::RequestTypes* request_types) const;
+ bool GatherNickName(const std::string& app_id,
+ policy_table::Strings* nicknames) const;
+
+ virtual bool SaveApplicationCustomData(const std::string& app_id,
+ bool is_revoked,
+ bool is_default,
+ bool is_predata);
+
+ virtual bool SaveModuleMeta(const policy_table::ModuleMeta& meta);
+ virtual bool SaveModuleConfig(const policy_table::ModuleConfig& config);
+ virtual bool SaveUsageAndErrorCounts(
+ const policy_table::UsageAndErrorCounts& counts);
+ virtual bool SaveDeviceData(const policy_table::DeviceData& devices);
+ virtual bool SaveFunctionalGroupings(
+ const policy_table::FunctionalGroupings& groups);
+ virtual bool SaveConsumerFriendlyMessages(
+ const policy_table::ConsumerFriendlyMessages& messages);
+ virtual bool SaveApplicationPoliciesSection(
+ const policy_table::ApplicationPoliciesSection& policies);
+ virtual bool SaveSpecificAppPolicy(
+ const policy_table::ApplicationPolicies::value_type& app);
+ virtual bool SaveDevicePolicy(const policy_table::DevicePolicy& device);
+
+ virtual bool SaveMessageString(const std::string& type,
+ const std::string& lang,
+ const policy_table::MessageString& strings);
+
+ bool SaveAppGroup(const std::string& app_id,
+ const policy_table::Strings& app_groups);
+ bool SaveNickname(const std::string& app_id,
+ const policy_table::Strings& nicknames);
+ bool SaveAppType(const std::string& app_id,
+ const policy_table::AppHMITypes& types);
+ bool SaveRequestType(const std::string& app_id,
+ const policy_table::RequestTypes& types);
+
+ public:
+ bool UpdateRequired() const;
+ void SaveUpdateRequired(bool value);
+
+ bool IsApplicationRepresented(const std::string& app_id) const;
+ bool CopyApplication(const std::string& source,
+ const std::string& destination);
+
+ bool IsApplicationRevoked(const std::string& app_id) const;
+ virtual bool IsDefaultPolicy(const std::string& app_id) const;
+ virtual bool IsPredataPolicy(const std::string& app_id) const;
+ virtual bool SetDefaultPolicy(const std::string& app_id);
+ virtual void SetPreloaded(bool value);
+
+ virtual bool SetVINValue(const std::string& value);
+
+ virtual utils::dbms::SQLDatabase* db() const;
+ virtual bool SetIsDefault(const std::string& app_id, bool is_default) const;
+
+ void RemoveDB() const OVERRIDE;
+ virtual bool IsDBVersionActual() const OVERRIDE;
+ virtual bool UpdateDBVersion() const OVERRIDE;
+
+ private:
+ static const std::string kDatabaseName;
+ utils::dbms::SQLDatabase* db_;
+
+#ifdef BUILD_TESTS
+ uint32_t open_counter_;
+#endif // BUILD_TESTS
+
+ /**
+ * @brief Calculates DB version from current schema
+ * @return version
+ */
+ const int32_t GetDBVersion() const;
+ bool SaveRpcs(int64_t group_id, const policy_table::Rpc& rpcs);
+ bool SaveServiceEndpoints(const policy_table::ServiceEndpoints& endpoints);
+ bool SaveSecondsBetweenRetries(
+ const policy_table::SecondsBetweenRetries& seconds);
+ bool SaveNumberOfNotificationsPerMinute(
+ const policy_table::NumberOfNotificationsPerMinute& notifications);
+ bool SaveMessageType(const std::string& type);
+ bool SaveLanguage(const std::string& code);
+
+ bool is_in_memory;
+};
+} // namespace policy
+
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_REPRESENTATION_H_
diff --git a/src/components/policy/include/policy/sql_wrapper.h b/src/components/policy/include/policy/sql_wrapper.h
new file mode 100644
index 0000000000..d6639f6635
--- /dev/null
+++ b/src/components/policy/include/policy/sql_wrapper.h
@@ -0,0 +1,44 @@
+/*
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_WRAPPER_H_
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_WRAPPER_H_
+
+#if __QNX__
+#include "qdb_wrapper/sql_database.h"
+#include "qdb_wrapper/sql_query.h"
+#else // __QNX__
+#include "sqlite_wrapper/sql_database.h"
+#include "sqlite_wrapper/sql_query.h"
+#endif // __QNX__
+
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_WRAPPER_H_
diff --git a/src/components/policy/include/policy/update_status_manager.h b/src/components/policy/include/policy/update_status_manager.h
new file mode 100644
index 0000000000..b4f52a8b03
--- /dev/null
+++ b/src/components/policy/include/policy/update_status_manager.h
@@ -0,0 +1,198 @@
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_H
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_H
+
+#include "policy/policy_types.h"
+#include "utils/lock.h"
+#include "utils/threads/thread.h"
+#include "utils/threads/thread_delegate.h"
+#include "utils/conditional_variable.h"
+#include "utils/lock.h"
+#include "utils/logger.h"
+#include "utils/macro.h"
+
+namespace policy {
+
+class PolicyListener;
+
+class UpdateStatusManager {
+ public:
+ /**
+ * @brief Constructor
+ */
+ UpdateStatusManager();
+
+ ~UpdateStatusManager();
+
+ /**
+ * @brief Sets listener pointer
+ * @param listener Pointer to policy listener implementation
+ */
+ void set_listener(PolicyListener* listener);
+
+ /**
+ * @brief Update status hanlder for PTS sending out
+ * @param update_timeout Timeout for waiting of incoming PTU
+ */
+ void OnUpdateSentOut(uint32_t update_timeout);
+
+ /**
+ * @brief Update status handler for PTU waiting timeout
+ */
+ void OnUpdateTimeoutOccurs();
+
+ /**
+ * @brief Update status handler for valid PTU receiving
+ */
+ void OnValidUpdateReceived();
+
+ /**
+ * @brief Update status handler for wrong PTU receiving
+ */
+ void OnWrongUpdateReceived();
+
+ /**
+ * @brief Update status handler for reset PT to default state
+ * @param is_update_required Update necessity flag
+ */
+ void OnResetDefaultPT(bool is_update_required);
+
+ /**
+ * @brief Update status handler for restarting retry sequence
+ */
+ void OnResetRetrySequence();
+
+ /**
+ * @brief Update status handler on new application registering
+ */
+ void OnNewApplicationAdded();
+
+ /**
+ * @brief Update status handler for policy initialization
+ * @param is_update_required Update necessity flag
+ */
+ void OnPolicyInit(bool is_update_required);
+
+ /**
+ * @brief IsUpdateRequired allows to distiguish if update is required
+ *
+ * @return true if update required.
+ */
+ bool IsUpdateRequired() const;
+
+ /**
+ * @brief IsUpdatePending allows to distinguish if update is in pending mode.
+ *
+ * @return true if update is in pending mode.
+ */
+ bool IsUpdatePending() const;
+
+ /**
+ * @brief ScheduleUpdate allows to schedule next update.
+ * It will change state to Update_Needed, that's is.
+ */
+ void ScheduleUpdate();
+
+ /**
+ * @brief ResetUpdateSchedule allows to reset all scheduled updates.
+ */
+ void ResetUpdateSchedule();
+
+ /**
+ * @brief StringifiedUpdateStatus allows to obtain update status as a string.
+ *
+ * @return stringified update status.
+ */
+ std::string StringifiedUpdateStatus() const;
+
+ /**
+ * @brief Status handler on applications search started
+ */
+ void OnAppsSearchStarted();
+
+ /**
+ * @brief Status handler on applications search completed
+ */
+ void OnAppsSearchCompleted();
+
+ /**
+ * @brief Returns status is application search in progress
+ * @return true, if in progress, otherwise - false
+ */
+ bool IsAppsSearchInProgress();
+
+#ifdef BUILD_TESTS
+ PolicyTableStatus GetLastUpdateStatus() const {
+ return GetUpdateStatus();
+ }
+#endif // BUILD_TESTS
+
+ private:
+ /*
+ * @brief Sets flag for update progress
+ *
+ * @param value
+ */
+ void set_exchange_in_progress(bool value);
+
+ /*
+ * @brief Sets flag for pending update
+ *
+ * @param value
+ */
+ void set_exchange_pending(bool value);
+
+ /*
+ * @brief Sets flag for update necessity
+ *
+ * @param value
+ */
+ void set_update_required(bool value);
+
+ /**
+ * @brief Check update status and notify HMI on changes
+ */
+ void CheckUpdateStatus();
+
+ private:
+ /**
+ * @brief Returns current policy update status
+ * @return
+ */
+ PolicyTableStatus GetUpdateStatus() const;
+
+ PolicyListener* listener_;
+ bool exchange_in_progress_;
+ bool update_required_;
+ bool update_scheduled_;
+ bool exchange_pending_;
+ bool apps_search_in_progress_;
+ sync_primitives::Lock exchange_in_progress_lock_;
+ sync_primitives::Lock update_required_lock_;
+ sync_primitives::Lock exchange_pending_lock_;
+ sync_primitives::Lock apps_search_in_progress_lock_;
+ /**
+ * @brief Last status of policy table update
+ */
+ PolicyTableStatus last_update_status_;
+
+ class UpdateThreadDelegate : public threads::ThreadDelegate {
+ public:
+ UpdateThreadDelegate(UpdateStatusManager* update_status_manager);
+ ~UpdateThreadDelegate();
+ virtual void threadMain();
+ virtual void exitThreadMain();
+ void updateTimeOut(const uint32_t timeout_ms);
+
+ volatile uint32_t timeout_;
+ volatile bool stop_flag_;
+ sync_primitives::Lock state_lock_;
+ sync_primitives::ConditionalVariable termination_condition_;
+ UpdateStatusManager* update_status_manager_;
+ };
+
+ UpdateThreadDelegate* update_status_thread_delegate_;
+ threads::Thread* thread_;
+};
+}
+
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_H
diff --git a/src/components/policy/include/policy/update_status_manager_interface.h b/src/components/policy/include/policy/update_status_manager_interface.h
new file mode 100644
index 0000000000..4c74910791
--- /dev/null
+++ b/src/components/policy/include/policy/update_status_manager_interface.h
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_SRC_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_INTERFACE_H_
+#define SRC_COMPONENTS_POLICY_SRC_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_INTERFACE_H_
+
+#include "utils/shared_ptr.h"
+#include "policy/policy_types.h"
+
+namespace policy {
+
+class PolicyListener;
+
+class UpdateStatusManagerInterface {
+ public:
+ virtual ~UpdateStatusManagerInterface() {}
+ /**
+ * @brief Sets listener pointer
+ * @param listener Pointer to policy listener implementation
+ */
+ virtual void set_listener(PolicyListener* listener) = 0;
+
+ /**
+ * @brief Update status hanlder for PTS sending out
+ * @param update_timeout Timeout for waiting of incoming PTU
+ */
+ virtual void OnUpdateSentOut(uint32_t update_timeout) = 0;
+
+ /**
+ * @brief Update status handler for PTU waiting timeout
+ */
+ virtual void OnUpdateTimeoutOccurs() = 0;
+
+ /**
+ * @brief Update status handler for valid PTU receiving
+ */
+ virtual void OnValidUpdateReceived() = 0;
+
+ /**
+ * @brief Update status handler for wrong PTU receiving
+ */
+ virtual void OnWrongUpdateReceived() = 0;
+
+ /**
+ * @brief Update status handler for reset PT to default state
+ * @param is_update_required Update necessity flag
+ */
+ virtual void OnResetDefaultPT(bool is_update_required) = 0;
+
+ /**
+ * @brief Update status handler for restarting retry sequence
+ */
+ virtual void OnResetRetrySequence() = 0;
+
+ /**
+ * @brief Update status handler on new application registering
+ */
+ virtual void OnNewApplicationAdded() = 0;
+
+ /**
+ * @brief Update status handler for policy initialization
+ * @param is_update_required Update necessity flag
+ */
+ virtual void OnPolicyInit(bool is_update_required) = 0;
+
+ /**
+ * @brief Returns current policy update status
+ * @return
+ */
+ virtual PolicyTableStatus GetUpdateStatus() = 0;
+};
+
+typedef utils::SharedPtr<UpdateStatusManagerInterface>
+ UpdateStatusManagerInterfaceSPtr;
+
+} // namespace policy
+
+#endif // SRC_COMPONENTS_POLICY_SRC_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_INTERFACE_H_
diff --git a/src/components/policy/include/policy/usage_statistics/app_stopwatch.h b/src/components/policy/include/policy/usage_statistics/app_stopwatch.h
new file mode 100644
index 0000000000..0f9ce35459
--- /dev/null
+++ b/src/components/policy/include/policy/usage_statistics/app_stopwatch.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_POLICY_USAGE_STATISTICS_APP_STOPWATCH_H_
+#define SRC_COMPONENTS_INCLUDE_POLICY_USAGE_STATISTICS_APP_STOPWATCH_H_
+
+#include "policy/usage_statistics/statistics_manager.h"
+
+namespace usage_statistics {
+
+class AppStopwatch {
+ public:
+ virtual ~AppStopwatch() {}
+ virtual void Start(AppStopwatchId stopwatch_type) = 0;
+ virtual void Switch(AppStopwatchId stopwatch_type) = 0;
+ virtual void WriteTime() = 0;
+};
+
+} // namespace usage_statistics
+
+#endif // SRC_COMPONENTS_INCLUDE_POLICY_USAGE_STATISTICS_APP_STOPWATCH_H_
diff --git a/src/components/policy/include/policy/usage_statistics/counter.h b/src/components/policy/include/policy/usage_statistics/counter.h
new file mode 100644
index 0000000000..6f50013bcd
--- /dev/null
+++ b/src/components/policy/include/policy/usage_statistics/counter.h
@@ -0,0 +1,107 @@
+/*
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USAGE_STATISTICS_COUNTER_H
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USAGE_STATISTICS_COUNTER_H
+
+#include <ctime>
+#include "policy/usage_statistics/statistics_manager.h"
+#include "policy/usage_statistics/app_stopwatch.h"
+#include "utils/shared_ptr.h"
+#include "utils/timer.h"
+#include "utils/macro.h"
+
+namespace usage_statistics {
+
+using timer::Timer;
+
+class GlobalCounter {
+ public:
+ GlobalCounter(utils::SharedPtr<StatisticsManager> statistics_manager,
+ GlobalCounterId counter_type);
+ void operator++() const;
+
+ private:
+ GlobalCounterId counter_type_;
+ utils::SharedPtr<StatisticsManager> statistics_manager_;
+};
+
+class AppCounter {
+ public:
+ AppCounter(utils::SharedPtr<StatisticsManager> statistics_manager,
+ const std::string& app_id,
+ AppCounterId counter_type);
+ void operator++() const;
+
+ private:
+ std::string app_id_;
+ AppCounterId counter_type_;
+ utils::SharedPtr<StatisticsManager> statistics_manager_;
+};
+
+class AppInfo {
+ public:
+ AppInfo(utils::SharedPtr<StatisticsManager> statistics_manager,
+ const std::string& app_id,
+ AppInfoId info_type);
+ void Update(const std::string& new_info) const;
+
+ private:
+ std::string app_id_;
+ AppInfoId info_type_;
+ utils::SharedPtr<StatisticsManager> statistics_manager_;
+};
+
+class AppStopwatchImpl : public AppStopwatch {
+ public:
+ AppStopwatchImpl(utils::SharedPtr<StatisticsManager> statistics_manager,
+ const std::string& app_id);
+ AppStopwatchImpl(utils::SharedPtr<StatisticsManager> statistics_manager,
+ const std::string& app_id,
+ std::uint32_t timeout);
+ void Start(AppStopwatchId stopwatch_type) OVERRIDE;
+ void Switch(AppStopwatchId stopwatch_type) OVERRIDE;
+ void WriteTime() OVERRIDE;
+
+ private:
+ // Fields
+ std::string app_id_;
+ AppStopwatchId stopwatch_type_;
+ utils::SharedPtr<StatisticsManager> statistics_manager_;
+ timer::Timer timer_;
+ const std::uint32_t time_out_;
+ DISALLOW_COPY_AND_ASSIGN(AppStopwatchImpl);
+};
+
+} // namespace usage_statistics
+
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USAGE_STATISTICS_COUNTER_H
diff --git a/src/components/policy/include/policy/user_consent_manager.h b/src/components/policy/include/policy/user_consent_manager.h
new file mode 100644
index 0000000000..55c6239a6c
--- /dev/null
+++ b/src/components/policy/include/policy/user_consent_manager.h
@@ -0,0 +1,44 @@
+/*
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USER_CONSENT_MANAGER_H_
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USER_CONSENT_MANAGER_H_
+
+namespace policy {
+class UserConsentManager {
+ public:
+ UserConsentManager() {}
+ ~UserConsentManager() {}
+};
+} // namespace policy
+
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USER_CONSENT_MANAGER_H_
diff --git a/src/components/policy/src/policy/policy_table_interface.xml b/src/components/policy/policy_table_interface.xml
index 6b671226ae..6b671226ae 100644
--- a/src/components/policy/src/policy/policy_table_interface.xml
+++ b/src/components/policy/policy_table_interface.xml
diff --git a/src/components/policy/src/policy/policy_table_interface_ext.xml b/src/components/policy/policy_table_interface_ext.xml
index 468eec2b0b..468eec2b0b 100644
--- a/src/components/policy/src/policy/policy_table_interface_ext.xml
+++ b/src/components/policy/policy_table_interface_ext.xml
diff --git a/src/components/policy/src/policy/specification.txt b/src/components/policy/specification.txt
index b00a2932e0..b00a2932e0 100644
--- a/src/components/policy/src/policy/specification.txt
+++ b/src/components/policy/specification.txt
diff --git a/src/components/policy/src/cache_manager.cc b/src/components/policy/src/cache_manager.cc
new file mode 100644
index 0000000000..c0e402c580
--- /dev/null
+++ b/src/components/policy/src/cache_manager.cc
@@ -0,0 +1,1601 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "policy/cache_manager.h"
+
+#include <algorithm>
+#include <functional>
+#include <ctime>
+#include <cmath>
+
+#include "utils/file_system.h"
+#include "json/reader.h"
+#include "json/features.h"
+#include "json/writer.h"
+#include "utils/logger.h"
+#include "utils/gen_hash.h"
+#include "utils/macro.h"
+#include "utils/threads/thread.h"
+#include "utils/threads/thread_delegate.h"
+
+#include "policy/sql_pt_representation.h"
+
+namespace policy_table = rpc::policy_table_interface_base;
+
+namespace policy {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")
+
+#define CACHE_MANAGER_CHECK(return_value) \
+ { \
+ if (!pt_) { \
+ LOG4CXX_WARN(logger_, "The cache manager is not initialized"); \
+ return return_value; \
+ } \
+ }
+
+#define CACHE_MANAGER_CHECK_VOID() \
+ { \
+ if (!pt_) { \
+ LOG4CXX_WARN(logger_, "The cache manager is not initialized"); \
+ return; \
+ } \
+ }
+
+struct LanguageFinder {
+ LanguageFinder(const std::string& language) : language_(language) {}
+ bool operator()(const policy_table::Languages::value_type& lang) const {
+ return !strcasecmp(language_.c_str(), lang.first.c_str());
+ }
+
+ private:
+ const std::string& language_;
+};
+
+CacheManager::CacheManager()
+ : CacheManagerInterface()
+ , pt_(new policy_table::Table)
+ , backup_(new SQLPTRepresentation())
+ , update_required(false) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ backuper_ = new BackgroundBackuper(this);
+ backup_thread_ = threads::CreateThread("Backup thread", backuper_);
+ backup_thread_->start();
+}
+
+CacheManager::~CacheManager() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(backuper_locker_);
+ backup_thread_->join();
+ delete backup_thread_->delegate();
+ threads::DeleteThread(backup_thread_);
+}
+
+bool CacheManager::CanAppKeepContext(const std::string& app_id) const {
+ CACHE_MANAGER_CHECK(false);
+ bool result = true;
+ return result;
+}
+
+uint32_t CacheManager::HeartBeatTimeout(const std::string& app_id) const {
+ CACHE_MANAGER_CHECK(0);
+ uint32_t result = 0;
+ if (AppExists(app_id)) {
+ if (pt_->policy_table.app_policies_section.apps[app_id]
+ .heart_beat_timeout_ms.is_initialized()) {
+ result = *(pt_->policy_table.app_policies_section.apps[app_id]
+ .heart_beat_timeout_ms);
+ }
+ }
+ return result;
+}
+
+bool CacheManager::CanAppStealFocus(const std::string& app_id) const {
+ CACHE_MANAGER_CHECK(false);
+ bool result = true;
+ return result;
+}
+
+bool CacheManager::GetDefaultHMI(const std::string& app_id,
+ std::string& default_hmi) const {
+ CACHE_MANAGER_CHECK(false);
+ bool result = true;
+ return result;
+}
+
+bool CacheManager::ResetUserConsent() {
+ CACHE_MANAGER_CHECK(false);
+ sync_primitives::AutoLock lock(cache_lock_);
+ return true;
+}
+
+bool CacheManager::GetUserPermissionsForDevice(
+ const std::string& device_id,
+ StringArray& consented_groups,
+ StringArray& disallowed_groups) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK(false);
+ return true;
+}
+
+void CacheManager::GetAllAppGroups(const std::string& app_id,
+ FunctionalGroupIDs& all_group_ids) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK_VOID();
+
+ if (kDeviceId == app_id) {
+ LOG4CXX_INFO(logger_, "Devices doesn't have groups");
+ return;
+ }
+
+ policy_table::ApplicationPolicies::const_iterator app_params_iter =
+ pt_->policy_table.app_policies_section.apps.find(app_id);
+
+ if (pt_->policy_table.app_policies_section.apps.end() != app_params_iter) {
+ policy_table::Strings::const_iterator iter =
+ (*app_params_iter).second.groups.begin();
+ policy_table::Strings::const_iterator iter_end =
+ (*app_params_iter).second.groups.end();
+
+ for (; iter != iter_end; ++iter) {
+ const uint32_t group_id = static_cast<uint32_t>((GenerateHash(*iter)));
+ all_group_ids.push_back(group_id);
+ }
+ }
+}
+
+void CacheManager::GetPreConsentedGroups(
+ const std::string& app_id, FunctionalGroupIDs& preconsented_groups) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK_VOID();
+}
+
+void CacheManager::GetConsentedGroups(const std::string& device_id,
+ const std::string& app_id,
+ FunctionalGroupIDs& allowed_groups,
+ FunctionalGroupIDs& disallowed_groups) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK_VOID();
+}
+
+void CacheManager::GetUnconsentedGroups(
+ const std::string& device_id,
+ const std::string& policy_app_id,
+ FunctionalGroupIDs& unconsented_groups) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK_VOID();
+}
+
+void CacheManager::RemoveAppConsentForGroup(const std::string& app_id,
+ const std::string& group_name) {
+ CACHE_MANAGER_CHECK_VOID();
+}
+
+bool CacheManager::ApplyUpdate(const policy_table::Table& update_pt) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK(false);
+ sync_primitives::AutoLock auto_lock(cache_lock_);
+ pt_->policy_table.functional_groupings =
+ update_pt.policy_table.functional_groupings;
+
+ policy_table::ApplicationPolicies::const_iterator iter =
+ update_pt.policy_table.app_policies_section.apps.begin();
+ policy_table::ApplicationPolicies::const_iterator iter_end =
+ update_pt.policy_table.app_policies_section.apps.end();
+
+ for (; iter != iter_end; ++iter) {
+ if (iter->second.is_null()) {
+ pt_->policy_table.app_policies_section.apps[iter->first].set_to_null();
+ pt_->policy_table.app_policies_section.apps[iter->first].set_to_string(
+ "");
+ } else if (policy::kDefaultId == (iter->second).get_string()) {
+ policy_table::ApplicationPolicies::const_iterator iter_default =
+ update_pt.policy_table.app_policies_section.apps.find(kDefaultId);
+ if (update_pt.policy_table.app_policies_section.apps.end() ==
+ iter_default) {
+ LOG4CXX_ERROR(logger_, "The default section was not found in PTU");
+ continue;
+ }
+ pt_->policy_table.app_policies_section.apps[iter->first] =
+ iter_default->second;
+ } else {
+ pt_->policy_table.app_policies_section.apps[iter->first] = iter->second;
+ }
+ }
+
+ pt_->policy_table.app_policies_section.device =
+ update_pt.policy_table.app_policies_section.device;
+
+ pt_->policy_table.module_config.SafeCopyFrom(
+ update_pt.policy_table.module_config);
+
+ pt_->policy_table.consumer_friendly_messages.assign_if_valid(
+ update_pt.policy_table.consumer_friendly_messages);
+
+ ResetCalculatedPermissions();
+ Backup();
+ return true;
+}
+
+void CacheManager::GetHMIAppTypeAfterUpdate(
+ std::map<std::string, StringArray>& app_hmi_types) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK_VOID();
+ policy_table::ApplicationPolicies::const_iterator policy_iter_begin =
+ pt_->policy_table.app_policies_section.apps.begin();
+ policy_table::ApplicationPolicies::const_iterator policy_iter_end =
+ pt_->policy_table.app_policies_section.apps.end();
+ std::vector<std::string> transform_app_hmi_types;
+ for (; policy_iter_begin != policy_iter_end; ++policy_iter_begin) {
+ const policy_table::ApplicationParams& app_params =
+ (*policy_iter_begin).second;
+ if (app_params.AppHMIType.is_initialized()) {
+ if (!(transform_app_hmi_types.empty())) {
+ transform_app_hmi_types.clear();
+ }
+ std::transform(app_params.AppHMIType->begin(),
+ app_params.AppHMIType->end(),
+ std::back_inserter(transform_app_hmi_types),
+ AppHMITypeToString());
+ app_hmi_types[(*policy_iter_begin).first] = transform_app_hmi_types;
+ }
+ }
+}
+
+void CacheManager::Backup() {
+ sync_primitives::AutoLock lock(backuper_locker_);
+ DCHECK(backuper_);
+ backuper_->DoBackup();
+}
+
+std::string CacheManager::currentDateTime() {
+ time_t now = time(0);
+ struct tm tstruct;
+ char buf[80];
+ tstruct = *localtime(&now);
+ // ISO_8601 format is expected, e.g. “2000-01-01T12:18:53Z”
+ strftime(buf, sizeof(buf), "%Y-%m-%dT%XZ", &tstruct);
+ return buf;
+}
+
+bool CacheManager::GetPermissionsForApp(const std::string& device_id,
+ const std::string& app_id,
+ FunctionalIdType& group_types) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ GetAllAppGroups(app_id, group_types[kTypeGeneral]);
+ GetAllAppGroups(kDefaultId, group_types[kTypeDefault]);
+ GetAllAppGroups(kPreDataConsentId, group_types[kTypePreDataConsented]);
+ return true;
+}
+
+bool CacheManager::GetDeviceGroupsFromPolicies(
+ policy_table::Strings& groups,
+ policy_table::Strings& preconsented_groups) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK(false);
+ return true;
+}
+
+bool CacheManager::AddDevice(const std::string& device_id,
+ const std::string& connection_type) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ sync_primitives::AutoLock auto_lock(cache_lock_);
+ CACHE_MANAGER_CHECK(false);
+ policy_table::DeviceParams& params =
+ (*(pt_->policy_table.device_data))[device_id];
+
+ // Open SDL stored just device id in policy
+ UNUSED(params);
+
+ // We have to set preloaded flag as false in policy table on adding new
+ // information (SDLAQ-CRS-2365). It can happens only after device addition.
+ *pt_->policy_table.module_config.preloaded_pt = false;
+
+ Backup();
+ return true;
+}
+
+bool CacheManager::SetDeviceData(const std::string& device_id,
+ const std::string& hardware,
+ const std::string& firmware,
+ const std::string& os,
+ const std::string& os_version,
+ const std::string& carrier,
+ const uint32_t number_of_ports,
+ const std::string& connection_type) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ sync_primitives::AutoLock auto_lock(cache_lock_);
+ CACHE_MANAGER_CHECK(false);
+ Backup();
+ return true;
+}
+
+bool CacheManager::SetUserPermissionsForDevice(
+ const std::string& device_id,
+ const StringArray& consented_groups,
+ const StringArray& disallowed_groups) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock auto_lock(cache_lock_);
+ CACHE_MANAGER_CHECK(false);
+ Backup();
+ return true;
+}
+
+bool CacheManager::ReactOnUserDevConsentForApp(const std::string& app_id,
+ bool is_device_allowed) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK(false);
+ bool result = true;
+ Backup();
+ return result;
+}
+
+void CacheManager::GetGroupNameByHashID(const int32_t group_id,
+ std::string& group_name) {
+ CACHE_MANAGER_CHECK_VOID();
+ policy_table::FunctionalGroupings::const_iterator fg_iter =
+ pt_->policy_table.functional_groupings.begin();
+ policy_table::FunctionalGroupings::const_iterator fg_iter_end =
+ pt_->policy_table.functional_groupings.end();
+
+ for (; fg_iter != fg_iter_end; ++fg_iter) {
+ const int32_t id = GenerateHash((*fg_iter).first);
+ if (group_id == id) {
+ group_name = (*fg_iter).first;
+ }
+ }
+}
+
+bool CacheManager::SetUserPermissionsForApp(
+ const PermissionConsent& permissions) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock auto_lock(cache_lock_);
+ CACHE_MANAGER_CHECK(false);
+ Backup();
+ return true;
+}
+
+bool CacheManager::UpdateRequired() const {
+ return update_required;
+}
+
+void CacheManager::SaveUpdateRequired(bool status) {
+ update_required = status;
+ Backup();
+}
+
+bool CacheManager::IsApplicationRevoked(const std::string& app_id) const {
+ CACHE_MANAGER_CHECK(false);
+ bool is_revoked = false;
+ if (pt_->policy_table.app_policies_section.apps.end() !=
+ pt_->policy_table.app_policies_section.apps.find(app_id)) {
+ is_revoked = pt_->policy_table.app_policies_section.apps[app_id].is_null();
+ }
+
+ return is_revoked;
+}
+
+void CacheManager::CheckPermissions(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ CheckPermissionResult& result) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK_VOID();
+
+ if (pt_->policy_table.app_policies_section.apps.end() ==
+ pt_->policy_table.app_policies_section.apps.find(app_id)) {
+ LOG4CXX_ERROR(
+ logger_, "Application id " << app_id << " was not found in policy DB.");
+ return;
+ }
+
+ policy_table::Strings::const_iterator app_groups_iter =
+ pt_->policy_table.app_policies_section.apps[app_id].groups.begin();
+
+ policy_table::Strings::const_iterator app_groups_iter_end =
+ pt_->policy_table.app_policies_section.apps[app_id].groups.end();
+
+ policy_table::FunctionalGroupings::const_iterator concrete_group;
+
+ for (; app_groups_iter != app_groups_iter_end; ++app_groups_iter) {
+ concrete_group =
+ pt_->policy_table.functional_groupings.find(*app_groups_iter);
+ if (pt_->policy_table.functional_groupings.end() != concrete_group) {
+ const policy_table::Rpcs& rpcs = concrete_group->second;
+
+ policy_table::Rpc::const_iterator rpc_iter = rpcs.rpcs.find(rpc);
+ if (rpcs.rpcs.end() != rpc_iter) {
+ policy_table::RpcParameters rpc_param = rpc_iter->second;
+
+ policy_table::HmiLevel hmi_level_e;
+ policy_table::EnumFromJsonString(hmi_level, &hmi_level_e);
+
+ policy_table::HmiLevels::const_iterator hmi_iter =
+ std::find(rpc_param.hmi_levels.begin(),
+ rpc_param.hmi_levels.end(),
+ hmi_level_e);
+
+ if (rpc_param.hmi_levels.end() != hmi_iter) {
+ result.hmi_level_permitted = PermitResult::kRpcAllowed;
+
+ policy_table::Parameters::const_iterator params_iter =
+ rpc_param.parameters->begin();
+ policy_table::Parameters::const_iterator params_iter_end =
+ rpc_param.parameters->end();
+
+ for (; params_iter != params_iter_end; ++params_iter) {
+ result.list_of_allowed_params.push_back(
+ policy_table::EnumToJsonString(*params_iter));
+ }
+ }
+ }
+ }
+ }
+}
+
+bool CacheManager::IsPTPreloaded() {
+ CACHE_MANAGER_CHECK(false);
+ return *pt_->policy_table.module_config.preloaded_pt;
+}
+
+int CacheManager::IgnitionCyclesBeforeExchange() {
+ CACHE_MANAGER_CHECK(0);
+ const uint8_t limit = std::max(
+ static_cast<int>(
+ pt_->policy_table.module_config.exchange_after_x_ignition_cycles),
+ 0);
+ LOG4CXX_DEBUG(logger_, "IgnitionCyclesBeforeExchange limit:" << limit);
+ uint8_t current = 0;
+
+ const int last_exch = static_cast<int>(
+ *pt_->policy_table.module_meta->ignition_cycles_since_last_exchange);
+ current = std::max(last_exch, 0);
+ LOG4CXX_DEBUG(
+ logger_,
+ "IgnitionCyclesBeforeExchange current:" << static_cast<int>(current));
+
+ return std::max(limit - current, 0);
+}
+
+int CacheManager::KilometersBeforeExchange(int current) {
+ CACHE_MANAGER_CHECK(0);
+ const int limit =
+ std::max(static_cast<int>(
+ pt_->policy_table.module_config.exchange_after_x_kilometers),
+ 0);
+ LOG4CXX_DEBUG(logger_, "KilometersBeforeExchange limit:" << limit);
+ int last = 0;
+
+ const int odo_val = static_cast<int>(
+ *pt_->policy_table.module_meta->pt_exchanged_at_odometer_x);
+ last = std::max(odo_val, 0);
+ LOG4CXX_DEBUG(logger_, "KilometersBeforeExchange last:" << last);
+
+ const int actual = std::max((current - last), 0);
+ LOG4CXX_DEBUG(logger_, "KilometersBeforeExchange actual:" << actual);
+ return std::max(limit - actual, 0);
+}
+
+bool CacheManager::SetCountersPassedForSuccessfulUpdate(
+ policy::Counters counter, int value) {
+ CACHE_MANAGER_CHECK(false);
+ switch (counter) {
+ case KILOMETERS:
+ *pt_->policy_table.module_meta->pt_exchanged_at_odometer_x = value;
+ LOG4CXX_DEBUG(logger_,
+ "SetCountersPassedForSuccessfulUpdate km:" << value);
+ break;
+ case DAYS_AFTER_EPOCH:
+ *pt_->policy_table.module_meta->pt_exchanged_x_days_after_epoch = value;
+ LOG4CXX_DEBUG(
+ logger_,
+ "SetCountersPassedForSuccessfulUpdate days after epoch:" << value);
+ break;
+ default:
+ LOG4CXX_ERROR(logger_,
+ "Unknown counter was requested to set: " << counter);
+ return false;
+ }
+
+ Backup();
+ return true;
+}
+
+int CacheManager::DaysBeforeExchange(int current) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK(0);
+ const uint8_t limit = pt_->policy_table.module_config.exchange_after_x_days;
+ LOG4CXX_DEBUG(logger_,
+ "Exchange after: " << static_cast<int>(limit) << " days");
+
+ const uint16_t days_after_epoch =
+ (*pt_->policy_table.module_meta->pt_exchanged_x_days_after_epoch);
+ LOG4CXX_DEBUG(logger_, "Epoch since last update: " << days_after_epoch);
+
+ const uint16_t actual =
+ std::max(static_cast<uint16_t>(current - days_after_epoch), uint16_t(0));
+ LOG4CXX_DEBUG(logger_, "The days since last update: " << actual);
+
+ return std::max(limit - actual, 0);
+}
+
+void CacheManager::IncrementIgnitionCycles() {
+ CACHE_MANAGER_CHECK_VOID();
+ const int ign_val = static_cast<int>(
+ *pt_->policy_table.module_meta->ignition_cycles_since_last_exchange);
+ (*pt_->policy_table.module_meta->ignition_cycles_since_last_exchange) =
+ ign_val + 1;
+ LOG4CXX_DEBUG(logger_, "IncrementIgnitionCycles ignitions:" << ign_val);
+ Backup();
+}
+
+void CacheManager::ResetIgnitionCycles() {
+ CACHE_MANAGER_CHECK_VOID();
+ (*pt_->policy_table.module_meta->ignition_cycles_since_last_exchange) = 0;
+ Backup();
+}
+
+int CacheManager::TimeoutResponse() {
+ CACHE_MANAGER_CHECK(0);
+ return pt_->policy_table.module_config.timeout_after_x_seconds;
+}
+
+bool CacheManager::SecondsBetweenRetries(std::vector<int>& seconds) {
+ CACHE_MANAGER_CHECK(false);
+ rpc::policy_table_interface_base::SecondsBetweenRetries::iterator iter =
+ pt_->policy_table.module_config.seconds_between_retries.begin();
+ rpc::policy_table_interface_base::SecondsBetweenRetries::iterator iter_end =
+ pt_->policy_table.module_config.seconds_between_retries.end();
+
+ const std::size_t size =
+ pt_->policy_table.module_config.seconds_between_retries.size();
+ seconds.reserve(size);
+ for (; iter != iter_end; ++iter) {
+ seconds.push_back(*iter);
+ }
+ return true;
+}
+
+const policy::VehicleInfo CacheManager::GetVehicleInfo() const {
+ CACHE_MANAGER_CHECK(VehicleInfo());
+ policy_table::ModuleConfig& module_config = pt_->policy_table.module_config;
+ VehicleInfo vehicle_info;
+ vehicle_info.vehicle_make = *module_config.vehicle_make;
+ vehicle_info.vehicle_model = *module_config.vehicle_model;
+ vehicle_info.vehicle_year = *module_config.vehicle_year;
+ LOG4CXX_DEBUG(
+ logger_,
+ "Vehicle info (make, model, year):" << vehicle_info.vehicle_make << ","
+ << vehicle_info.vehicle_model << ","
+ << vehicle_info.vehicle_year);
+ return vehicle_info;
+}
+
+std::vector<UserFriendlyMessage> CacheManager::GetUserFriendlyMsg(
+ const std::vector<std::string>& msg_codes, const std::string& language) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ std::vector<UserFriendlyMessage> result;
+ CACHE_MANAGER_CHECK(result);
+
+ std::vector<std::string>::const_iterator it = msg_codes.begin();
+ std::vector<std::string>::const_iterator it_end = msg_codes.end();
+ for (; it != it_end; ++it) {
+ policy_table::MessageLanguages msg_languages =
+ (*pt_->policy_table.consumer_friendly_messages->messages)[*it];
+
+ policy_table::MessageString message_string;
+
+ // If message has no records with required language, fallback language
+ // should be used instead.
+ LanguageFinder finder(language);
+ policy_table::Languages::const_iterator it_language = std::find_if(
+ msg_languages.languages.begin(), msg_languages.languages.end(), finder);
+
+ if (msg_languages.languages.end() == it_language) {
+ LOG4CXX_WARN(logger_,
+ "Language "
+ << language
+ << " haven't been found for message code: " << *it);
+
+ LanguageFinder fallback_language_finder("en-us");
+
+ policy_table::Languages::const_iterator it_fallback_language =
+ std::find_if(msg_languages.languages.begin(),
+ msg_languages.languages.end(),
+ fallback_language_finder);
+
+ if (msg_languages.languages.end() == it_fallback_language) {
+ LOG4CXX_ERROR(logger_,
+ "No fallback language found for message code: " << *it);
+ continue;
+ }
+
+ message_string = it_fallback_language->second;
+ } else {
+ message_string = it_language->second;
+ }
+
+ UserFriendlyMessage msg;
+ msg.message_code = *it;
+ result.push_back(msg);
+ }
+ return result;
+}
+
+void CacheManager::GetServiceUrls(const std::string& service_type,
+ EndpointUrls& end_points) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK_VOID();
+ std::string search_value;
+ if (!IsNumberService(service_type, search_value)) {
+ search_value = service_type;
+ }
+
+ LOG4CXX_DEBUG(logger_, "Search service value is: " << search_value);
+
+ policy_table::ServiceEndpoints::const_iterator iter =
+ pt_->policy_table.module_config.endpoints.find(search_value);
+
+ if (pt_->policy_table.module_config.endpoints.end() != iter) {
+ policy_table::URLList::const_iterator url_list_iter =
+ (*iter).second.begin();
+ policy_table::URLList::const_iterator url_list_iter_end =
+ (*iter).second.end();
+ for (; url_list_iter != url_list_iter_end; ++url_list_iter) {
+ EndpointData data;
+ data.app_id = (*url_list_iter).first;
+ std::copy((*url_list_iter).second.begin(),
+ (*url_list_iter).second.end(),
+ std::back_inserter(data.url));
+
+ end_points.push_back(data);
+ }
+ }
+}
+
+std::string CacheManager::GetLockScreenIconUrl() const {
+ if (backup_) {
+ return backup_->GetLockScreenIconUrl();
+ }
+ return std::string("");
+}
+
+rpc::policy_table_interface_base::NumberOfNotificationsType
+CacheManager::GetNotificationsNumber(const std::string& priority) {
+ CACHE_MANAGER_CHECK(0);
+ typedef rpc::policy_table_interface_base::NumberOfNotificationsPerMinute NNPM;
+
+ const NNPM& nnpm =
+ pt_->policy_table.module_config.notifications_per_minute_by_priority;
+
+ NNPM::const_iterator priority_iter = nnpm.find(priority);
+
+ const rpc::policy_table_interface_base::NumberOfNotificationsType result =
+ (nnpm.end() != priority_iter ? (*priority_iter).second : 0u);
+ return result;
+}
+
+bool CacheManager::GetPriority(const std::string& policy_app_id,
+ std::string& priority) const {
+ CACHE_MANAGER_CHECK(false);
+ if (kDeviceId == policy_app_id) {
+ priority = EnumToJsonString(
+ pt_->policy_table.app_policies_section.device.priority);
+ return true;
+ }
+
+ const policy_table::ApplicationPolicies& policies =
+ pt_->policy_table.app_policies_section.apps;
+
+ policy_table::ApplicationPolicies::const_iterator policy_iter =
+ policies.find(policy_app_id);
+ const bool app_id_exists = policies.end() != policy_iter;
+ if (app_id_exists) {
+ priority = EnumToJsonString((*policy_iter).second.priority);
+ }
+
+ return app_id_exists;
+}
+
+void CacheManager::CheckSnapshotInitialization() {
+ CACHE_MANAGER_CHECK_VOID();
+ if (!snapshot_) {
+ LOG4CXX_ERROR(logger_, "Snapshot pointer is not initialized");
+ return;
+ }
+
+ *(snapshot_->policy_table.module_config.preloaded_pt) = false;
+
+ // SDL must not send certificate in snapshot
+ snapshot_->policy_table.module_config.certificate =
+ rpc::Optional<rpc::String<0, 65535> >();
+
+ /* consumer_friendly_messages are required for the snapshot;
+ * consumer_friendly_messages->version is required always, but
+ * consumer_friendly_messages->messages must be omitted in PTS */
+ if (snapshot_->policy_table.consumer_friendly_messages->is_initialized()) {
+ snapshot_->policy_table.consumer_friendly_messages->messages =
+ rpc::Optional<policy_table::Messages>();
+ } else {
+ LOG4CXX_WARN(logger_,
+ "policy_table.consumer_friendly_messages is not initialized");
+ }
+
+ /* policy_table.usage_and_error_counts are required for PTS and
+ * policy_table.usage_and_error_counts->app_level is optional */
+ rpc::Optional<policy_table::UsageAndErrorCounts>& usage_and_error_counts =
+ snapshot_->policy_table.usage_and_error_counts;
+
+ if (usage_and_error_counts->app_level->is_initialized()) {
+ policy_table::AppLevels::iterator it =
+ usage_and_error_counts->app_level->begin();
+ policy_table::AppLevels::const_iterator it_end =
+ usage_and_error_counts->app_level->end();
+ for (; it != it_end; ++it) {
+ if (!(*it).second.minutes_in_hmi_full.is_initialized()) {
+ (*it).second.minutes_in_hmi_full = 0;
+ }
+
+ if (!(*it).second.app_registration_language_gui.is_initialized()) {
+ (*it).second.app_registration_language_gui = "unknown";
+ }
+
+ if (!(*it).second.app_registration_language_vui.is_initialized()) {
+ (*it).second.app_registration_language_vui = "unknown";
+ }
+
+ if (!(*it).second.minutes_in_hmi_limited.is_initialized()) {
+ (*it).second.minutes_in_hmi_limited = 0;
+ }
+
+ if (!(*it).second.minutes_in_hmi_background.is_initialized()) {
+ (*it).second.minutes_in_hmi_background = 0;
+ }
+
+ if (!(*it).second.minutes_in_hmi_none.is_initialized()) {
+ (*it).second.minutes_in_hmi_none = 0;
+ }
+
+ if (!(*it).second.count_of_user_selections.is_initialized()) {
+ (*it).second.count_of_user_selections = 0;
+ }
+
+ if (!(*it)
+ .second.count_of_rejections_sync_out_of_memory
+ .is_initialized()) {
+ (*it).second.count_of_rejections_sync_out_of_memory = 0;
+ }
+
+ if (!(*it)
+ .second.count_of_rejections_nickname_mismatch.is_initialized()) {
+ (*it).second.count_of_rejections_nickname_mismatch = 0;
+ }
+
+ if (!(*it).second.count_of_rejections_duplicate_name.is_initialized()) {
+ (*it).second.count_of_rejections_duplicate_name = 0;
+ }
+
+ if (!(*it).second.count_of_rejected_rpc_calls.is_initialized()) {
+ (*it).second.count_of_rejected_rpc_calls = 0;
+ }
+
+ if (!(*it).second.count_of_rpcs_sent_in_hmi_none.is_initialized()) {
+ (*it).second.count_of_rpcs_sent_in_hmi_none = 0;
+ }
+
+ if (!(*it).second.count_of_removals_for_bad_behavior.is_initialized()) {
+ (*it).second.count_of_removals_for_bad_behavior = 0;
+ }
+
+ if (!(*it).second.count_of_run_attempts_while_revoked.is_initialized()) {
+ (*it).second.count_of_run_attempts_while_revoked = 0;
+ }
+ }
+ } else {
+ LOG4CXX_WARN(logger_, "app_level is not initialized");
+ }
+}
+
+void CacheManager::PersistData() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (backup_.valid()) {
+ if (pt_.valid()) {
+ cache_lock_.Acquire();
+ policy_table::Table copy_pt(*pt_);
+ cache_lock_.Release();
+
+ backup_->Save(copy_pt);
+ backup_->SaveUpdateRequired(update_required);
+
+ policy_table::ApplicationPolicies::const_iterator app_policy_iter =
+ copy_pt.policy_table.app_policies_section.apps.begin();
+ policy_table::ApplicationPolicies::const_iterator app_policy_iter_end =
+ copy_pt.policy_table.app_policies_section.apps.end();
+
+ bool is_revoked = false;
+ bool is_default_policy;
+ bool is_predata_policy;
+
+ for (; app_policy_iter != app_policy_iter_end; ++app_policy_iter) {
+ const std::string app_id = (*app_policy_iter).first;
+
+ if (copy_pt.policy_table.app_policies_section.apps.end() !=
+ copy_pt.policy_table.app_policies_section.apps.find(app_id)) {
+ is_revoked =
+ copy_pt.policy_table.app_policies_section.apps[app_id].is_null();
+ }
+
+ is_default_policy =
+ copy_pt.policy_table.app_policies_section.apps.end() !=
+ copy_pt.policy_table.app_policies_section.apps.find(app_id) &&
+ policy::kDefaultId ==
+ copy_pt.policy_table.app_policies_section.apps[app_id]
+ .get_string();
+
+ // TODO(AOleynik): Remove this field from DB
+ is_predata_policy =
+ copy_pt.policy_table.app_policies_section.apps.end() !=
+ copy_pt.policy_table.app_policies_section.apps.find(app_id) &&
+ policy::kPreDataConsentId ==
+ copy_pt.policy_table.app_policies_section.apps[app_id]
+ .get_string();
+
+ backup_->SaveApplicationCustomData(
+ app_id, is_revoked, is_default_policy, is_predata_policy);
+ is_revoked = false;
+ }
+
+ // In case of extended policy the meta info should be backuped as well.
+ backup_->WriteDb();
+ }
+ }
+}
+
+void CacheManager::ResetCalculatedPermissions() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(calculated_permissions_lock_);
+ calculated_permissions_.clear();
+}
+
+void CacheManager::AddCalculatedPermissions(const std::string& device_id,
+ const std::string& policy_app_id,
+ const Permissions& permissions) {
+ LOG4CXX_DEBUG(logger_,
+ "AddCalculatedPermissions for device: "
+ << device_id << " and app: " << policy_app_id);
+ sync_primitives::AutoLock lock(calculated_permissions_lock_);
+ calculated_permissions_[device_id][policy_app_id] = permissions;
+}
+
+bool CacheManager::IsPermissionsCalculated(const std::string& device_id,
+ const std::string& policy_app_id,
+ Permissions& permission) {
+ LOG4CXX_DEBUG(logger_,
+ "IsPermissionsCalculated for device: "
+ << device_id << " and app: " << policy_app_id);
+ sync_primitives::AutoLock lock(calculated_permissions_lock_);
+ CalculatedPermissions::const_iterator it =
+ calculated_permissions_.find(device_id);
+
+ if (calculated_permissions_.end() == it) {
+ return false;
+ }
+
+ AppCalculatedPermissions::const_iterator app_it =
+ (*it).second.find(policy_app_id);
+ if ((*it).second.end() == app_it) {
+ return false;
+ } else {
+ permission = (*app_it).second;
+ return true;
+ }
+ return false;
+}
+
+bool policy::CacheManager::IsNumberService(const std::string& input,
+ std::string& output) const {
+ const char* input_value = input.c_str();
+ char* endptr;
+ const int base = 10;
+ errno = 0;
+ uint32_t service_value = strtoul(input_value, &endptr, base);
+ bool is_real_zero_value =
+ (!service_value && endptr != input_value && *endptr == '\0');
+ if (!is_real_zero_value && (!service_value || errno == ERANGE)) {
+ return false;
+ }
+
+ output = input;
+ if (service_value <= 9) {
+ output.insert(0, "0x0", 3);
+ } else {
+ output.insert(0, "0x", 2);
+ }
+
+ return true;
+}
+
+utils::SharedPtr<policy_table::Table> CacheManager::GenerateSnapshot() {
+ CACHE_MANAGER_CHECK(snapshot_);
+ sync_primitives::AutoLock lock(cache_lock_);
+
+ snapshot_ = new policy_table::Table();
+
+ // Copy all members of policy table except messages in consumer friendly
+ // messages
+ snapshot_->policy_table.app_policies_section =
+ pt_->policy_table.app_policies_section;
+ snapshot_->policy_table.functional_groupings =
+ pt_->policy_table.functional_groupings;
+ snapshot_->policy_table.consumer_friendly_messages->version =
+ pt_->policy_table.consumer_friendly_messages->version;
+ snapshot_->policy_table.consumer_friendly_messages->mark_initialized();
+ snapshot_->policy_table.module_config = pt_->policy_table.module_config;
+ snapshot_->policy_table.module_meta = pt_->policy_table.module_meta;
+ snapshot_->policy_table.usage_and_error_counts =
+ pt_->policy_table.usage_and_error_counts;
+ snapshot_->policy_table.device_data = pt_->policy_table.device_data;
+
+ // Set policy table type to Snapshot
+ snapshot_->SetPolicyTableType(
+ rpc::policy_table_interface_base::PolicyTableType::PT_SNAPSHOT);
+
+ CheckSnapshotInitialization();
+ return snapshot_;
+}
+
+bool CacheManager::GetInitialAppData(const std::string& app_id,
+ StringArray& nicknames,
+ StringArray& app_hmi_types) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK(false);
+ policy_table::ApplicationPolicies::const_iterator policy_iter =
+ pt_->policy_table.app_policies_section.apps.find(app_id);
+
+ if (pt_->policy_table.app_policies_section.apps.end() != policy_iter) {
+ const policy_table::ApplicationParams& app_params = (*policy_iter).second;
+
+ std::copy(app_params.nicknames->begin(),
+ app_params.nicknames->end(),
+ std::back_inserter(nicknames));
+
+ std::transform(app_params.AppHMIType->begin(),
+ app_params.AppHMIType->end(),
+ std::back_inserter(app_hmi_types),
+ AppHMITypeToString());
+ }
+ return true;
+}
+
+bool CacheManager::GetFunctionalGroupings(
+ policy_table::FunctionalGroupings& groups) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK(false);
+ const policy_table::FunctionalGroupings& f_groupings =
+ pt_->policy_table.functional_groupings;
+
+ groups.insert(f_groupings.begin(), f_groupings.end());
+ return true;
+}
+
+int CacheManager::CountUnconsentedGroups(const std::string& policy_app_id,
+ const std::string& device_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK(false);
+ LOG4CXX_DEBUG(logger_, "Application id: " << policy_app_id);
+ int result = 0;
+ return result;
+}
+
+bool CacheManager::SetMetaInfo(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language) {
+ CACHE_MANAGER_CHECK(false);
+
+ // We have to set preloaded flag as false in policy table on any response
+ // of GetSystemInfo (SDLAQ-CRS-2365)
+ *pt_->policy_table.module_config.preloaded_pt = false;
+
+ Backup();
+ return true;
+}
+
+bool CacheManager::IsMetaInfoPresent() const {
+ CACHE_MANAGER_CHECK(false);
+ bool result = true;
+ return result;
+}
+
+bool CacheManager::SetSystemLanguage(const std::string& language) {
+ CACHE_MANAGER_CHECK(false);
+ Backup();
+ return true;
+}
+
+bool CacheManager::GetFunctionalGroupNames(FunctionalGroupNames& names) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK(false);
+ rpc::policy_table_interface_base::FunctionalGroupings::iterator iter =
+ pt_->policy_table.functional_groupings.begin();
+ rpc::policy_table_interface_base::FunctionalGroupings::iterator iter_end =
+ pt_->policy_table.functional_groupings.end();
+
+ for (; iter != iter_end; ++iter) {
+ const int32_t id = GenerateHash((*iter).first);
+ std::pair<std::string, std::string> value =
+ std::make_pair(*(*iter).second.user_consent_prompt, (*iter).first);
+
+ names.insert(
+ std::pair<uint32_t, std::pair<std::string, std::string> >(id, value));
+ }
+ return true;
+}
+
+bool CacheManager::CleanupUnpairedDevices() {
+ CACHE_MANAGER_CHECK(false);
+ Backup();
+ return true;
+}
+
+void CacheManager::Increment(usage_statistics::GlobalCounterId type) {
+ CACHE_MANAGER_CHECK_VOID();
+ Backup();
+}
+
+void CacheManager::Increment(const std::string& app_id,
+ usage_statistics::AppCounterId type) {
+ CACHE_MANAGER_CHECK_VOID();
+ sync_primitives::AutoLock lock(cache_lock_);
+ switch (type) {
+ case usage_statistics::USER_SELECTIONS:
+ ++(*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .count_of_user_selections;
+ break;
+ case usage_statistics::REJECTIONS_SYNC_OUT_OF_MEMORY:
+ ++(*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .count_of_rejections_sync_out_of_memory;
+ break;
+ case usage_statistics::REJECTIONS_NICKNAME_MISMATCH:
+ ++(*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .count_of_rejections_nickname_mismatch;
+ break;
+ case usage_statistics::REJECTIONS_DUPLICATE_NAME:
+ ++(*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .count_of_rejections_duplicate_name;
+ break;
+ case usage_statistics::REJECTED_RPC_CALLS:
+ ++(*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .count_of_rejected_rpc_calls;
+ break;
+ case usage_statistics::RPCS_IN_HMI_NONE:
+ ++(*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .count_of_rpcs_sent_in_hmi_none;
+ break;
+ case usage_statistics::REMOVALS_MISBEHAVED:
+ ++(*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .count_of_removals_for_bad_behavior;
+ break;
+ case usage_statistics::RUN_ATTEMPTS_WHILE_REVOKED:
+ ++(*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .count_of_run_attempts_while_revoked;
+ break;
+ case usage_statistics::COUNT_OF_TLS_ERRORS:
+ ++(*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .count_of_tls_errors;
+ break;
+ default:
+ LOG4CXX_WARN(logger_, "Type app counter is unknown");
+ return;
+ }
+ Backup();
+}
+
+void CacheManager::Set(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value) {
+ CACHE_MANAGER_CHECK_VOID();
+ sync_primitives::AutoLock lock(cache_lock_);
+ switch (type) {
+ case usage_statistics::LANGUAGE_GUI:
+ (*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .app_registration_language_gui = value;
+ break;
+ case usage_statistics::LANGUAGE_VUI:
+ (*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .app_registration_language_vui = value;
+ break;
+ default:
+ LOG4CXX_WARN(logger_, "Type app info is unknown");
+ return;
+ }
+ Backup();
+}
+
+void CacheManager::Add(const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int seconds) {
+ CACHE_MANAGER_CHECK_VOID();
+ sync_primitives::AutoLock lock(cache_lock_);
+ const int minutes = ConvertSecondsToMinute(seconds);
+ switch (type) {
+ case usage_statistics::SECONDS_HMI_FULL:
+ (*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .minutes_in_hmi_full += minutes;
+ break;
+ case usage_statistics::SECONDS_HMI_LIMITED:
+ (*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .minutes_in_hmi_limited += minutes;
+ break;
+ case usage_statistics::SECONDS_HMI_BACKGROUND:
+ (*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .minutes_in_hmi_background += minutes;
+ break;
+ case usage_statistics::SECONDS_HMI_NONE:
+ (*pt_->policy_table.usage_and_error_counts->app_level)[app_id]
+ .minutes_in_hmi_none += minutes;
+ break;
+ default:
+ LOG4CXX_WARN(logger_, "Type app stopwatch is unknown");
+ return;
+ }
+ Backup();
+}
+
+long CacheManager::ConvertSecondsToMinute(int seconds) {
+ const float seconds_in_minute = 60.0;
+ return std::round(seconds / seconds_in_minute);
+}
+
+bool CacheManager::SetDefaultPolicy(const std::string& app_id) {
+ CACHE_MANAGER_CHECK(false);
+ policy_table::ApplicationPolicies::const_iterator iter =
+ pt_->policy_table.app_policies_section.apps.find(kDefaultId);
+ if (pt_->policy_table.app_policies_section.apps.end() != iter) {
+ pt_->policy_table.app_policies_section.apps[app_id] =
+ pt_->policy_table.app_policies_section.apps[kDefaultId];
+
+ SetIsDefault(app_id);
+ }
+ Backup();
+ return true;
+}
+
+bool CacheManager::IsDefaultPolicy(const std::string& app_id) {
+ CACHE_MANAGER_CHECK(false);
+ const bool result =
+ pt_->policy_table.app_policies_section.apps.end() !=
+ pt_->policy_table.app_policies_section.apps.find(app_id) &&
+ policy::kDefaultId ==
+ pt_->policy_table.app_policies_section.apps[app_id].get_string();
+
+ return result;
+}
+
+bool CacheManager::SetIsDefault(const std::string& app_id) {
+ CACHE_MANAGER_CHECK(false);
+ policy_table::ApplicationPolicies::const_iterator iter =
+ pt_->policy_table.app_policies_section.apps.find(app_id);
+ if (pt_->policy_table.app_policies_section.apps.end() != iter) {
+ pt_->policy_table.app_policies_section.apps[app_id].set_to_string(
+ kDefaultId);
+ }
+ return true;
+}
+
+bool CacheManager::SetPredataPolicy(const std::string& app_id) {
+ CACHE_MANAGER_CHECK(false);
+ policy_table::ApplicationPolicies::const_iterator iter =
+ pt_->policy_table.app_policies_section.apps.find(kPreDataConsentId);
+
+ if (pt_->policy_table.app_policies_section.apps.end() == iter) {
+ LOG4CXX_ERROR(logger_,
+ "Could not set " << kPreDataConsentId
+ << " permissions for app " << app_id);
+ return false;
+ }
+
+ pt_->policy_table.app_policies_section.apps[app_id] =
+ pt_->policy_table.app_policies_section.apps[kPreDataConsentId];
+
+ pt_->policy_table.app_policies_section.apps[app_id].set_to_string(
+ kPreDataConsentId);
+
+ Backup();
+ return true;
+}
+
+bool CacheManager::IsPredataPolicy(const std::string& app_id) {
+ // TODO(AOleynik): Maybe change for comparison with pre_DataConsent
+ // permissions or check string value from get_string()
+ policy_table::ApplicationParams& pre_data_app =
+ pt_->policy_table.app_policies_section.apps[kPreDataConsentId];
+ policy_table::ApplicationParams& specific_app =
+ pt_->policy_table.app_policies_section.apps[app_id];
+
+ policy_table::Strings res;
+ std::set_intersection(pre_data_app.groups.begin(),
+ pre_data_app.groups.end(),
+ specific_app.groups.begin(),
+ specific_app.groups.end(),
+ std::back_inserter(res));
+
+ bool is_marked_as_predata =
+ kPreDataConsentId ==
+ pt_->policy_table.app_policies_section.apps[app_id].get_string();
+
+ return !res.empty() && is_marked_as_predata;
+}
+
+bool CacheManager::SetUnpairedDevice(const std::string& device_id,
+ bool unpaired) {
+ const bool result = pt_->policy_table.device_data->end() !=
+ pt_->policy_table.device_data->find(device_id);
+ if (!result) {
+ LOG4CXX_DEBUG(logger_,
+ "Couldn't set unpaired flag for device id "
+ << device_id << " , since it wasn't found.");
+ return false;
+ }
+
+ sync_primitives::AutoLock lock(unpaired_lock_);
+ if (unpaired) {
+ is_unpaired_.insert(device_id);
+ LOG4CXX_DEBUG(logger_, "Unpaired flag was set for device id " << device_id);
+ } else {
+ is_unpaired_.erase(device_id);
+ LOG4CXX_DEBUG(logger_,
+ "Unpaired flag was removed for device id " << device_id);
+ }
+ return result;
+}
+
+bool CacheManager::SetVINValue(const std::string& value) {
+ CACHE_MANAGER_CHECK(false);
+ Backup();
+ return true;
+}
+
+bool CacheManager::IsApplicationRepresented(const std::string& app_id) const {
+ CACHE_MANAGER_CHECK(false);
+ if (kDeviceId == app_id) {
+ return true;
+ }
+ policy_table::ApplicationPolicies::const_iterator iter =
+ pt_->policy_table.app_policies_section.apps.find(app_id);
+ return pt_->policy_table.app_policies_section.apps.end() != iter;
+}
+
+bool CacheManager::Init(const std::string& file_name,
+ const PolicySettings* settings) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ settings_ = settings;
+ InitResult init_result = backup_->Init(settings);
+
+ bool result = true;
+ switch (init_result) {
+ case InitResult::EXISTS: {
+ LOG4CXX_INFO(logger_, "Policy Table exists, was loaded correctly.");
+ result = LoadFromBackup();
+ if (result) {
+ if (!backup_->IsDBVersionActual()) {
+ LOG4CXX_INFO(logger_, "DB version is NOT actual");
+ if (!backup_->RefreshDB()) {
+ LOG4CXX_ERROR(logger_, "RefreshDB() failed");
+ return false;
+ }
+ backup_->UpdateDBVersion();
+ Backup();
+ }
+ MergePreloadPT(file_name);
+ }
+ } break;
+ case InitResult::SUCCESS: {
+ LOG4CXX_INFO(logger_, "Policy Table was inited successfully");
+
+ result = LoadFromFile(file_name, *pt_);
+
+ utils::SharedPtr<policy_table::Table> snapshot = GenerateSnapshot();
+ result &= snapshot->is_valid();
+ LOG4CXX_DEBUG(logger_,
+ "Check if snapshot is valid: " << std::boolalpha << result);
+ if (!result) {
+ rpc::ValidationReport report("policy_table");
+ snapshot->ReportErrors(&report);
+ return result;
+ }
+
+ backup_->UpdateDBVersion();
+ Backup();
+ } break;
+ default: {
+ result = false;
+ LOG4CXX_ERROR(logger_, "Failed to init policy table.");
+ } break;
+ }
+
+ return result;
+}
+
+void CacheManager::FillDeviceSpecificData() {}
+
+bool CacheManager::LoadFromBackup() {
+ sync_primitives::AutoLock lock(cache_lock_);
+ pt_ = backup_->GenerateSnapshot();
+ update_required = backup_->UpdateRequired();
+
+ FillDeviceSpecificData();
+
+ return true;
+}
+
+bool CacheManager::LoadFromFile(const std::string& file_name,
+ policy_table::Table& table) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ BinaryMessage json_string;
+ if (!file_system::ReadBinaryFile(file_name, json_string)) {
+ LOG4CXX_FATAL(logger_, "Failed to read pt file.");
+ return false;
+ }
+
+ Json::Value value;
+ Json::Reader reader(Json::Features::strictMode());
+ std::string json(json_string.begin(), json_string.end());
+ if (!reader.parse(json.c_str(), value)) {
+ LOG4CXX_FATAL(
+ logger_,
+ "Preloaded PT is corrupted: " << reader.getFormattedErrorMessages());
+ return false;
+ }
+
+ LOG4CXX_TRACE(logger_, "Start create PT");
+ sync_primitives::AutoLock locker(cache_lock_);
+
+ table = policy_table::Table(&value);
+
+ Json::StyledWriter s_writer;
+ LOG4CXX_DEBUG(logger_, "PT out:");
+ LOG4CXX_DEBUG(logger_, s_writer.write(table.ToJsonValue()));
+
+ if (!table.is_valid()) {
+ rpc::ValidationReport report("policy_table");
+ table.ReportErrors(&report);
+ LOG4CXX_FATAL(logger_,
+ "Parsed table is not valid " << rpc::PrettyFormat(report));
+ return false;
+ }
+ return true;
+}
+
+bool CacheManager::ResetPT(const std::string& file_name) {
+ bool result = true;
+ Backup();
+ return result;
+}
+
+bool CacheManager::AppExists(const std::string& app_id) const {
+ CACHE_MANAGER_CHECK(false);
+ if (kDeviceId == app_id) {
+ return true;
+ }
+ policy_table::ApplicationPolicies::iterator policy_iter =
+ pt_->policy_table.app_policies_section.apps.find(app_id);
+ return pt_->policy_table.app_policies_section.apps.end() != policy_iter;
+}
+
+int32_t CacheManager::GenerateHash(const std::string& str_to_hash) {
+ uint32_t hash = 5381U;
+ std::string::const_iterator it = str_to_hash.begin();
+ std::string::const_iterator it_end = str_to_hash.end();
+
+ for (; it != it_end; ++it) {
+ hash = ((hash << 5) + hash) + (*it);
+ }
+
+ // Reset sign bit in case it has been set.
+ // This is needed to avoid overflow for signed int.
+ const int32_t result = hash & 0x7FFFFFFF;
+ return result;
+}
+
+void CacheManager::GetAppRequestTypes(
+ const std::string& policy_app_id,
+ std::vector<std::string>& request_types) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ CACHE_MANAGER_CHECK_VOID();
+ policy_table::ApplicationPolicies::iterator policy_iter =
+ pt_->policy_table.app_policies_section.apps.find(policy_app_id);
+ if (pt_->policy_table.app_policies_section.apps.end() == policy_iter) {
+ LOG4CXX_DEBUG(logger_,
+ "Can't find request types for app_id " << policy_app_id);
+ return;
+ }
+ policy_table::RequestTypes::iterator it_request_type =
+ policy_iter->second.RequestType->begin();
+ for (; it_request_type != policy_iter->second.RequestType->end();
+ ++it_request_type) {
+ request_types.push_back(EnumToJsonString(*it_request_type));
+ }
+ return;
+}
+
+std::string CacheManager::GetCertificate() const {
+ CACHE_MANAGER_CHECK(std::string(""));
+ if (pt_->policy_table.module_config.certificate.is_initialized()) {
+ return *pt_->policy_table.module_config.certificate;
+ }
+ return std::string("");
+}
+
+void CacheManager::MergePreloadPT(const std::string& file_name) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ policy_table::Table table;
+ if (!LoadFromFile(file_name, table)) {
+ LOG4CXX_DEBUG(logger_, "Unable to load preloaded PT.");
+ return;
+ }
+
+ sync_primitives::AutoLock lock(cache_lock_);
+ policy_table::PolicyTable& current = pt_->policy_table;
+ policy_table::PolicyTable& new_table = table.policy_table;
+ const std::string date_current = *current.module_config.preloaded_date;
+ const std::string date_new = *new_table.module_config.preloaded_date;
+ if (date_current != date_new) {
+ MergeMC(new_table, current);
+ MergeFG(new_table, current);
+ MergeAP(new_table, current);
+ MergeCFM(new_table, current);
+ Backup();
+ }
+}
+
+void CacheManager::MergeMC(const policy_table::PolicyTable& new_pt,
+ policy_table::PolicyTable& pt) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ policy_table::ModuleConfig copy(pt.module_config);
+
+ pt.module_config = new_pt.module_config;
+ pt.module_config.vehicle_make = copy.vehicle_make;
+ pt.module_config.vehicle_year = copy.vehicle_year;
+ pt.module_config.vehicle_model = copy.vehicle_model;
+}
+
+void CacheManager::MergeFG(const policy_table::PolicyTable& new_pt,
+ policy_table::PolicyTable& pt) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ policy_table::FunctionalGroupings::const_iterator it =
+ new_pt.functional_groupings.begin();
+
+ for (; it != new_pt.functional_groupings.end(); ++it) {
+ LOG4CXX_DEBUG(logger_, "Merge functional group: " << it->first);
+ pt.functional_groupings[it->first] = it->second;
+ }
+}
+
+void CacheManager::MergeAP(const policy_table::PolicyTable& new_pt,
+ policy_table::PolicyTable& pt) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ pt.app_policies_section.device = const_cast<policy_table::PolicyTable&>(
+ new_pt).app_policies_section.device;
+
+ pt.app_policies_section.apps[kDefaultId] =
+ const_cast<policy_table::PolicyTable&>(new_pt)
+ .app_policies_section.apps[kDefaultId];
+
+ pt.app_policies_section.apps[kPreDataConsentId] =
+ const_cast<policy_table::PolicyTable&>(new_pt)
+ .app_policies_section.apps[kPreDataConsentId];
+}
+
+void CacheManager::MergeCFM(const policy_table::PolicyTable& new_pt,
+ policy_table::PolicyTable& pt) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (new_pt.consumer_friendly_messages.is_initialized()) {
+ if (!pt.consumer_friendly_messages.is_initialized()) {
+ pt.consumer_friendly_messages = new_pt.consumer_friendly_messages;
+ } else {
+ policy_table::Messages::const_iterator it =
+ new_pt.consumer_friendly_messages->messages->begin();
+
+ pt.consumer_friendly_messages->version =
+ new_pt.consumer_friendly_messages->version;
+ for (; it != new_pt.consumer_friendly_messages->messages->end(); ++it) {
+ LOG4CXX_DEBUG(logger_, "Merge CFM: " << it->first);
+ if (!(pt.consumer_friendly_messages->messages.is_initialized())) {
+ LOG4CXX_DEBUG(logger_, "CFM not initialized.");
+ }
+ (*pt.consumer_friendly_messages->messages)[it->first] = it->second;
+ }
+ }
+ }
+}
+
+const PolicySettings& CacheManager::get_settings() const {
+ DCHECK(settings_);
+
+ return *settings_;
+}
+
+CacheManager::BackgroundBackuper::BackgroundBackuper(
+ CacheManager* cache_manager)
+ : cache_manager_(cache_manager)
+ , stop_flag_(false)
+ , new_data_available_(false) {
+ LOG4CXX_AUTO_TRACE(logger_);
+}
+
+CacheManager::BackgroundBackuper::~BackgroundBackuper() {
+ LOG4CXX_AUTO_TRACE(logger_);
+}
+
+void CacheManager::BackgroundBackuper::InternalBackup() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK(cache_manager_);
+
+ while (new_data_available_) {
+ new_data_available_ = false;
+ LOG4CXX_DEBUG(logger_, "DoBackup");
+ cache_manager_->PersistData();
+ }
+}
+
+void CacheManager::BackgroundBackuper::threadMain() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(need_backup_lock_);
+ while (!stop_flag_) {
+ need_backup_lock_.Release();
+ InternalBackup();
+ need_backup_lock_.Acquire();
+ if (new_data_available_ || stop_flag_) {
+ continue;
+ }
+ LOG4CXX_DEBUG(logger_, "Wait for a next backup");
+ backup_notifier_.Wait(need_backup_lock_);
+ }
+}
+
+void CacheManager::BackgroundBackuper::exitThreadMain() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock auto_lock(need_backup_lock_);
+ stop_flag_ = true;
+ backup_notifier_.NotifyOne();
+}
+
+void CacheManager::BackgroundBackuper::DoBackup() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock auto_lock(need_backup_lock_);
+ new_data_available_ = true;
+ backup_notifier_.NotifyOne();
+}
+
+} // namespace policy
diff --git a/src/components/policy/src/policy/CMakeLists.txt b/src/components/policy/src/policy/CMakeLists.txt
deleted file mode 100644
index 2b794e9db8..0000000000
--- a/src/components/policy/src/policy/CMakeLists.txt
+++ /dev/null
@@ -1,102 +0,0 @@
-# Copyright (c) 2013, Ford Motor Company
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# Redistributions of source code must retain the above copyright notice, this
-# list of conditions and the following disclaimer.
-#
-# Redistributions in binary form must reproduce the above copyright notice,
-# this list of conditions and the following
-# disclaimer in the documentation and/or other materials provided with the
-# distribution.
-#
-# Neither the name of the Ford Motor Company nor the names of its contributors
-# may be used to endorse or promote products derived from this software
-# without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-# POSSIBILITY OF SUCH DAMAGE.
-
-set(target Policy)
-set(install_destination bin)
-set(copy_destination ${CMAKE_BINARY_DIR}/src/appMain)
-set(library_name ${CMAKE_SHARED_LIBRARY_PREFIX}${target}${CMAKE_SHARED_LIBRARY_SUFFIX})
-
-set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/Modules/")
-
-
-#Generation of policy table interface...
-#include(${CMAKE_SOURCE_DIR}/tools/intergen/GenerateInterfaceLibrary.cmake)
-
-include_directories (
- ./include
- ./usage_statistics/include
- ${CMAKE_SOURCE_DIR}/src/components/rpc_base/include
- ${JSONCPP_INCLUDE_DIRECTORY}
- #${CMAKE_CURRENT_BINARY_DIR}
- ${CMAKE_SOURCE_DIR}/src/components/utils/include/
- ${CMAKE_SOURCE_DIR}/src/components
- ${CMAKE_SOURCE_DIR}/src/components/config_profile/include
- ${LOG4CXX_INCLUDE_DIRECTORY}
-)
-
-set(SOURCES
- ./src/policy_manager_impl.cc
- ./src/policy_helper.cc
- ./src/policy_table.cc
- ./src/sql_pt_queries.cc
- ./src/sql_pt_representation.cc
- ./src/update_status_manager.cc
- ./src/cache_manager.cc
- ${CMAKE_SOURCE_DIR}/src/components/rpc_base/src/rpc_base/rpc_base.cc
-)
-
-
-add_subdirectory(usage_statistics)
-
-include_directories(./policy_table/table_struct)
-add_subdirectory(policy_table/table_struct)
-
-set(LIBRARIES ConfigProfile policy_struct dbms jsoncpp Utils)
-if (CMAKE_SYSTEM_NAME STREQUAL "QNX")
- # --- QDB Wrapper
- include_directories (qdb_wrapper/include)
- add_subdirectory(qdb_wrapper)
-else ()
- # --- SQLite Wrapper
- include_directories (sqlite_wrapper/include)
- add_subdirectory(sqlite_wrapper)
- list(APPEND LIBRARIES sqlite3)
-endif ()
-
-add_library(${target} SHARED ${SOURCES})
-target_link_libraries(${target} ${LIBRARIES} )
-
-if(ENABLE_LOG)
- target_link_libraries(${target} log4cxx -L${LOG4CXX_LIBS_DIRECTORY})
-endif()
-
-add_custom_target(copy_library_${target} ALL
- COMMAND ${CMAKE_COMMAND} -E copy_if_different
- ${CMAKE_CURRENT_BINARY_DIR}/${library_name}
- ${copy_destination}
- DEPENDS ${target}
- COMMENT "Copying library ${library_name}")
-
-install(TARGETS ${target}
- DESTINATION ${install_destination}
- PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE
- GROUP_READ GROUP_EXECUTE
- WORLD_READ WORLD_EXECUTE
-)
diff --git a/src/components/policy/src/policy/include/policy/cache_manager.h b/src/components/policy/src/policy/include/policy/cache_manager.h
deleted file mode 100644
index ff30d95363..0000000000
--- a/src/components/policy/src/policy/include/policy/cache_manager.h
+++ /dev/null
@@ -1,652 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_CACHE_MANAGER_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_CACHE_MANAGER_H_
-
-#include <map>
-
-#include "utils/shared_ptr.h"
-#include "policy/pt_representation.h"
-#include "policy/pt_ext_representation.h"
-#include "usage_statistics/statistics_manager.h"
-#include "policy/cache_manager_interface.h"
-
-#include "utils/lock.h"
-#include "utils/timer_thread.h"
-#include "utils/conditional_variable.h"
-
-namespace policy {
-
-class CacheManager : public CacheManagerInterface {
- public:
- CacheManager();
- ~CacheManager();
-
- /**
- * @brief Check if specified RPC for specified application
- * has permission to be executed in specified HMI Level
- * and also its permitted params.
- * @param app_id Id of application provided during registration
- * @param hmi_level Current HMI Level of application
- * @param rpc Name of RPC
- * @return CheckPermissionResult containing flag if HMI Level is allowed
- * and list of allowed params.
- */
- virtual void CheckPermissions(const PTString& app_id,
- const PTString& hmi_level,
- const PTString& rpc,
- CheckPermissionResult& result);
-
- /**
- * @brief Returns true if Policy Table was not updated yet
- * from preloaded pt file.
- */
- virtual bool IsPTPreloaded();
-
- /**
- * Gets number of ignition cycles before next update policy table
- * @return number of ignition cycles
- */
- virtual int IgnitionCyclesBeforeExchange();
-
- /**
- * Gets value in kilometers before next update policy table
- * @param current value in kilometers from the odometers
- * @return value in kilometers
- */
- virtual int KilometersBeforeExchange(int current);
-
- /**
- * @brief Sets kilometers and days after epoch, that passed for recieved
- * successful PT UPdate
- */
- virtual bool SetCountersPassedForSuccessfulUpdate(int kilometers,
- int days_after_epoch);
-
- /**
- * Gets value in days before next update policy table
- * @param current value in days after epoch
- * @return value in days
- */
- virtual int DaysBeforeExchange(int current);
-
- /**
- * @brief Increment number of ignition cycles since last exchange by 1
- */
- virtual void IncrementIgnitionCycles();
-
- /**
- * @brief Reset number of ignition cycles since last exchange to 0
- */
- virtual void ResetIgnitionCycles();
-
- /**
- * @brief Returns timeout to wait for a response of PT update
- * @return value in seconds
- */
- virtual int TimeoutResponse();
-
- /**
- * @brief Returns number of seconds between each try of sending PTS
- * @param seconds Return value: array of 5 elements
- * @return bool Success of operation
- */
- virtual bool SecondsBetweenRetries(std::vector<int> &seconds);
-
- /**
- * @brief Get information about vehicle
- */
- virtual VehicleData GetVehicleData();
-
- /**
- * @brief Allows to update 'vin' field in module_meta table.
- *
- * @param new 'vin' value.
- *
- * @return true in case when data has been successfully updated,
- * false otherwise.
- */
- bool SetVINValue(const std::string& value);
-
- /**
- * @brief Get message text for displaying/pronouncing for user
- * dependent on language and context.
- * @param msg_codes Context of message (Driver distraction, Grant permission etc)
- * @param language Language of the message
- * @return Array of appropriate messages parameters
- */
- std::vector<UserFriendlyMessage> GetUserFriendlyMsg(
- const std::vector<std::string>& msg_codes, const std::string& language);
-
- /**
- * @brief Get list of URLs related to particular service
- * @param service_type If URLs for specific service are preset,
- * return them otherwise default URLs.
- */
- virtual void GetServiceUrls(const std::string& service_type,
- EndpointUrls& end_points);
-
- /**
- * @brief GetLockScreenIcon allows to obtain lock screen icon url;
- *
- * @return url which point to the resourse where lock screen icon could be obtained.
- */
- virtual std::string GetLockScreenIconUrl() const;
-
- /**
- * @brief Get allowed number of notifications
- * depending on application priority.
- * @param priority Priority of application
- */
- virtual int GetNotificationsNumber(const std::string& priority);
-
- /**
- * @brief Get priority for given application
- * @param policy_app_id Unique application id
- * @param priority Priority for application or empty, if value was not set
- * @return true, if succedeed, otherwise - false
- */
- virtual bool GetPriority(const std::string& policy_app_id,
- std::string& priority);
-
- /**
- * @brief Initialized Policy Table (load)
- * @return bool Success of operation
- */
- bool Init(const std::string& file_name);
-
- /**
- * @brief Get snapshot of Policy Table
- * including app_policies, functional_groups,
- * device_info, statistics, excluding user messages
- * @return Generated structure for obtaining Json string.
- */
- virtual utils::SharedPtr<policy_table::Table> GenerateSnapshot();
-
- /**
- * Applies policy table to the current table
- * @param update_pt policy table
- * @return true if successfully
- */
- bool ApplyUpdate(const policy_table::Table& update_pt);
-
- /**
- * @brief Gets list of appHMIType associated with mobile appID
- * @param container of appHMIType
- */
- virtual void GetHMIAppTypeAfterUpdate(std::map<std::string, StringArray>& app_hmi_types);
-
- /**
- * Gets flag updateRequired
- * @return true if update is required
- */
- bool UpdateRequired() const;
-
- /**
- * @brief Saves flag updateRequired
- * @param status update status if true then update required.
- */
- void SaveUpdateRequired(bool status);
-
- /**
- * @brief GetInitialAppData Retrieves data from app_policies
- * about app on its registration
- * @param app_id id of registered app.
- * All outputs are filled in only if not null
- * @param nicknames Synonyms for application
- * @param app_hmi_types app_types Section on HMI where app can
- * appear (Navigation, Phone etc)
- * @return true in case initial application data was obtained successfuly.
- */
- bool GetInitialAppData(const std::string& app_id,
- StringArray& nicknames,
- StringArray& app_hmi_types);
-
- /**
- * Checks if the application is revoked
- * @param app_id application id
- * @return true if application is revoked
- */
- bool IsApplicationRevoked(const std::string& app_id) const;
-
- /**
- * @brief Get functional groupings from DB
- * @param groups Known functional groupings
- * @return true, if succeeded, otherwise - false
- */
- bool GetFunctionalGroupings(policy_table::FunctionalGroupings& groups);
-
- /**
- * Checks if the application is represented in policy table
- * @param app_id application id
- * @return true if application is represented in policy table
- */
- bool IsApplicationRepresented(const std::string& app_id) const;
-
- /**
- * Checks if the application has default policy
- * @param app_id application id
- * @return true if application has default policy
- */
- bool IsDefaultPolicy(const std::string& app_id);
-
- /**
- * @brief SetIsDefault Sets is_default flag for application
- * @param app_id app specific application
- * @return true in case opperation was done successfully.
- */
- bool SetIsDefault(const std::string& app_id);
-
- /**
- * Checks if the application has pre_data policy
- * @param app_id application id
- * @return true if application has pre_data policy
- */
- bool IsPredataPolicy(const std::string& app_id);
-
- /**
- * Sets default policy for application
- * @param app_id application id
- * @return true if success
- */
- bool SetDefaultPolicy(const std::string& app_id);
-
- /**
- * @brief Is application allowed to send notifications while in
- * Backgound or limited mode.
- * @param app_id Application id
- * @return bool Allowed/disallowed.
- */
- bool CanAppKeepContext(const std::string& app_id);
-
- /**
- * @brief Is application allowed to move foreground at will?
- * @param app_id Application id
- * @return bool Allowed/disallowed.
- */
- bool CanAppStealFocus(const std::string& app_id);
-
- /**
- * @brief Get default_hmi for given application
- * @param policy_app_id Unique application id
- * @param default_hmi Default HMI level for application or empty, if value was
- * not set
- * @return true, if succedeed, otherwise - false
- */
- bool GetDefaultHMI(const std::string& app_id,
- std::string &default_hmi);
-
- /**
- * @brief Reset user consent for device data and applications permissions
- * @return
- */
- bool ResetUserConsent();
-
- /**
- * @brief Get user permissions for device data usage
- * @param device_id Generated or obtained id of device
- * @param consented_groups Groups consented by user
- * @param disallowed_groups Groups not consented by user
- * @return true, if query was successfull, otherwise - false
- */
- bool GetUserPermissionsForDevice(const std::string& device_id,
- StringArray &consented_groups,
- StringArray &disallowed_groups);
-
- /**
- * @brief Gets list of groups permissions from policy table
- * @param device_id Unique device id, which hosts specific application
- * @param policy_app_id Unique application id
- * @param group_types Group list sorted by permission status
- * @return true, if query was successfull, otherwise - false
- */
- bool GetPermissionsForApp(const std::string& device_id,
- const std::string& app_id,
- FunctionalIdType &group_types);
-
- /**
- * @brief Get device groups and preconsented groups from policies section
- * @param groups List of groups to be consented for device usage
- * @param preconsented_groups List of preconsented groups for device usage
- * @return true, if query was successful, otherwise - false
- */
- bool GetDeviceGroupsFromPolicies(
- rpc::policy_table_interface_base::Strings &groups,
- rpc::policy_table_interface_base::Strings &preconsented_groups);
-
- /**
- * @brief Record information about mobile device in Policy Table.
- * @param device_id Generated or obtained id of device
- * @return bool Success of operation
- */
- bool SetDeviceData(const std::string& device_id,
- const std::string& hardware = "",
- const std::string& firmware = "",
- const std::string& os = "",
- const std::string& os_version = "",
- const std::string& carrier = "",
- const uint32_t number_of_ports = 0,
- const std::string& connection_type = "");
-
- /**
- * @brief Sets user consent for particular mobile device,
- * i.e. to use device for exchanging of Policy Table.
- * @return bool Success of operation
- */
- bool SetUserPermissionsForDevice(
- const std::string& device_id,
- const StringArray& consented_groups = StringArray(),
- const StringArray& disallowed_groups = StringArray());
-
- /**
- * @brief Update Application Policies as reaction
- * on User allowing/disallowing device this app is running on.
- */
- bool ReactOnUserDevConsentForApp(const std::string& app_id,
- bool is_device_allowed);
-
- /**
- * @brief Set user consent on functional groups
- * @param permissions User consent on functional group
- * @return true, if operation succedeed, otherwise - false
- */
- bool SetUserPermissionsForApp(const PermissionConsent& permissions);
-
- /**
- * @brief Records information about head unit system to PT
- * @return bool Success of operation
- */
- bool SetMetaInfo(const std::string& ccpu_version,
- const std::string& wers_country_code,
- const std::string& language);
-
- /**
- * @brief Checks, if specific head unit is present in PT
- * @return boot Suceess, if present, otherwise - false
- */
- bool IsMetaInfoPresent() const;
-
- /**
- * @brief Set current system language
- * @param language System language
- * @return true, if succedeed, otherwise - false
- */
- bool SetSystemLanguage(const std::string& language);
-
- /**
- * Increments global counter
- * @param type type of counter
- */
- void Increment(usage_statistics::GlobalCounterId type);
-
- /**
- * Increments counter of application
- * @param app_id id application
- * @param type type of counter
- */
- void Increment(const std::string& app_id,
- usage_statistics::AppCounterId type);
-
- /**
- * Sets value of application information
- * @param app_id id application
- * @param type type of information
- * @param value value of information
- */
- void Set(const std::string& app_id,
- usage_statistics::AppInfoId type,
- const std::string& value);
-
- /**
- * Adds value to stopwatch of application
- * @param app_id id application
- * @param type type of stopwatch
- * @param seconds value for adding in seconds
- */
- void Add(const std::string& app_id,
- usage_statistics::AppStopwatchId type,
- int seconds);
-
- /**
- * @brief CountUnconsentedGroups allows to obtain the count of unconsented
- * groups for specific application.
- * @param policy_app_id application id.
- * @param device_id device id.
- * @return the count of unconsented groups
- */
- int CountUnconsentedGroups(const std::string& policy_app_id,
- const std::string& device_id);
-
- /**
- * @brief Gets functional group names and user_consent_prompts, if any
- * @param Array to be filled with group ids, names and functional prompts
- * @return true, if succeeded, otherwise - false
- */
- bool GetFunctionalGroupNames(FunctionalGroupNames& names);
-
- /**
- * @brief GetAllAppGroups allows to obtain all groups for certain application.
- * @param app_id specific application id.
- * @param all_group_ids parameter to fill.
- */
- void GetAllAppGroups(const std::string& app_id,
- FunctionalGroupIDs& all_group_ids);
- /**
- * @brief GetPreConsentedGroups allows to obtain all pre-consented groups for
- * specific application.
- * @param app_id specific application id.
- * @param preconsented_groups parameter to fill.
- */
- void GetPreConsentedGroups(const std::string &app_id,
- FunctionalGroupIDs& preconsented_groups);
- /**
- * @brief GetConsentedGroups allows to obtain list of allowed and disallowed
- * groups for specific application on certain device.
- * @param device_id certain device
- * @param app_id application id.
- * @param allowed_groups list of allowed groups
- * @param disallowed_groups list of disallowed groups
- */
- void GetConsentedGroups(const std::string &device_id,
- const std::string &app_id,
- FunctionalGroupIDs& allowed_groups,
- FunctionalGroupIDs& disallowed_groups);
-
- /**
- * @brief GetUnconsentedGroups allows to obtain list of allowed and disallowed
- * groups for specific application on certain device.
- * @param device_id certain device
- * @param policy_app_id application id.
- * @param unconsented_groups list of unconsented groups.
- */
- void GetUnconsentedGroups(const std::string& device_id,
- const std::string& policy_app_id,
- FunctionalGroupIDs& unconsented_groups);
-
- void RemoveAppConsentForGroup(const std::string& app_id,
- const std::string& group_name);
-
- /**
- * @brief Set app policy to pre_DataConsented policy
- * @param app_id Policy ID of application to be changed
- * @return true, if succeeded, otherwise - false
- */
- bool SetPredataPolicy(const std::string& app_id);
-
- /**
- * @brief Removes unpaired devices
- * @return true if success
- */
- bool CleanupUnpairedDevices();
-
- /**
- * Sets flag of unpaired device
- * @param device_id Unique device id
- * @param unpaired True, if should be marked as unpaired, otherwise - false
- * @return true if success
- */
- bool SetUnpairedDevice(const std::string& device_id, bool unpaired = true);
-
- /**
- * Resets Policy Table
- * @param file_name Path to preloaded PT file
- * @return true if successfully
- */
- bool ResetPT(const std::string& file_name);
-
- /**
- * @brief LoadFromBackup allows to load policy into the cache from backup.
- * @return true in case operation was successful.
- */
- bool LoadFromBackup();
-
- /**
- * @brief LoadFromFile allows to load policy cache from preloaded table.
- * @param file_name preloaded
- * @return
- */
- bool LoadFromFile(const std::string& file_name);
-
- /**
- * @brief Backup allows to save cache onto hard drive.
- */
- void Backup();
-
-
- /**
- * Returns heart beat timeout
- * @param app_id application id
- * @return if timeout was set then value in seconds greater zero
- * otherwise heart beat for specific application isn't set
- */
- uint16_t HeartBeatTimeout(const std::string& app_id) const;
-
- /**
- * @brief Allows to generate hash from the specified string.
- * The djb2 algorithm uses for hash generation.
- * @param str_to_hash - the string from which hash should be generated.
- * @return integer hash for the specified string.
- */
- static int32_t GenerateHash(const std::string& str_to_hash);
-
- /**
- * @brief Gets request types for application
- * @param policy_app_id Unique application id
- * @param request_types Request types of application
- */
- void GetAppRequestTypes(const std::string& policy_app_id,
- std::vector<std::string>& request_types) const;
-private:
- std::string currentDateTime();
- struct AppHMITypeToString {
- std::string operator()(rpc::Enum<policy_table::AppHMIType> value) {
- return std::string(
- policy_table::EnumToJsonString(value));
- }
- };
-
- void GetGroupNameByHashID(const int32_t group_id, std::string& group_name);
- void FillDeviceSpecificData();
- bool AppExists(const std::string& app_id) const;
- long ConvertSecondsToMinute(int seconds);
-
- /**
- * @brief Checks snapshot initialization and initializes to default values, if
- * necessary
- */
- void CheckSnapshotInitialization();
-
- void PersistData();
-
- void ResetCalculatedPermissions();
-
- void AddCalculatedPermissions(
- const std::string& device_id,
- const std::string& policy_app_id,
- const policy::Permissions& permissions);
-
- bool IsPermissionsCalculated(const std::string& device_id,
- const std::string& policy_app_id,
- policy::Permissions& permission);
-
-private:
- /**
- * @brief Checks, if input string is known service represented by number, than
- * converts input string to service number
- * @param input Input string
- * @param output Output service
- * @return true, if successfully converted, otherwise - false
- */
- bool IsNumberService(const std::string& input, std::string& output) const;
-
-private:
- utils::SharedPtr<policy_table::Table> pt_;
- utils::SharedPtr<policy_table::Table> snapshot_;
- utils::SharedPtr<PTRepresentation> backup_;
- utils::SharedPtr<PTExtRepresentation> ex_backup_;
- bool update_required;
- typedef std::set<std::string> UnpairedDevices;
- UnpairedDevices is_unpaired_;
-
- sync_primitives::Lock cache_lock_;
- sync_primitives::Lock unpaired_lock_;
-
- typedef std::map<std::string, Permissions> AppCalculatedPermissions;
- typedef std::map<std::string, AppCalculatedPermissions> CalculatedPermissions;
- CalculatedPermissions calculated_permissions_;
- sync_primitives::Lock calculated_permissions_lock_;
-
- class BackgroundBackuper: public threads::ThreadDelegate {
- friend class CacheManager;
- public:
- BackgroundBackuper(CacheManager* cache_manager);
- ~BackgroundBackuper();
- virtual void threadMain();
- virtual void exitThreadMain();
- void DoBackup();
- private:
- void InternalBackup();
- CacheManager* cache_manager_;
- sync_primitives::ConditionalVariable backup_notifier_;
- volatile bool stop_flag_;
- volatile bool new_data_available_;
-
- sync_primitives::Lock need_backup_lock_;
- DISALLOW_COPY_AND_ASSIGN(BackgroundBackuper);
- };
- threads::Thread* backup_thread_;
- sync_primitives::Lock backuper_locker_;
- BackgroundBackuper* backuper_;
-};
-} // namespace policy
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_CACHE_MANAGER_H_
diff --git a/src/components/policy/src/policy/include/policy/cache_manager_interface.h b/src/components/policy/src/policy/include/policy/cache_manager_interface.h
deleted file mode 100644
index 56d0933e45..0000000000
--- a/src/components/policy/src/policy/include/policy/cache_manager_interface.h
+++ /dev/null
@@ -1,591 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_SRC_POLICY_INCLUDE_POLICY_CACHE_MANAGER_INTERFACE_H_
-#define SRC_COMPONENTS_POLICY_SRC_POLICY_INCLUDE_POLICY_CACHE_MANAGER_INTERFACE_H_
-
-#include <string>
-#include <vector>
-
-#include "utils/shared_ptr.h"
-#include "usage_statistics/counter.h"
-
-namespace policy_table = rpc::policy_table_interface_base;
-
-namespace policy {
-
-class CacheManagerInterface {
- public:
- virtual ~CacheManagerInterface() {
- }
-
- /**
- * @brief Check if specified RPC for specified application
- * has permission to be executed in specified HMI Level
- * and also its permitted params.
- * @param app_id Id of application provided during registration
- * @param hmi_level Current HMI Level of application
- * @param rpc Name of RPC
- * @return CheckPermissionResult containing flag if HMI Level is allowed
- * and list of allowed params.
- */
- virtual void CheckPermissions(const PTString& app_id,
- const PTString& hmi_level, const PTString& rpc,
- CheckPermissionResult& result) = 0;
-
- /**
- * @brief Returns true if Policy Table was not updated yet
- * from preloaded pt file.
- */
- virtual bool IsPTPreloaded() = 0;
-
- /**
- * Gets number of ignition cycles before next update policy table
- * @return number of ignition cycles
- */
- virtual int IgnitionCyclesBeforeExchange() = 0;
-
- /**
- * Gets value in kilometers before next update policy table
- * @param current value in kilometers from the odometers
- * @return value in kilometers
- */
- virtual int KilometersBeforeExchange(int current) = 0;
-
- /**
- * @brief Sets kilometers and days after epoch, that passed for recieved
- * successful PT UPdate
- */
- virtual bool SetCountersPassedForSuccessfulUpdate(int kilometers,
- int days_after_epoch) = 0;
-
- /**
- * Gets value in days before next update policy table
- * @param current value in days after epoch
- * @return value in days
- */
- virtual int DaysBeforeExchange(int current) = 0;
-
- /**
- * @brief Increment number of ignition cycles since last exchange by 1
- */
- virtual void IncrementIgnitionCycles() = 0;
-
- /**
- * @brief Reset number of ignition cycles since last exchange to 0
- */
- virtual void ResetIgnitionCycles() = 0;
-
- /**
- * @brief Returns timeout to wait for a response of PT update
- * @return value in seconds
- */
- virtual int TimeoutResponse() = 0;
-
- /**
- * @brief Returns number of seconds between each try of sending PTS
- * @param seconds Return value: array of 5 elements
- * @return bool Success of operation
- */
- virtual bool SecondsBetweenRetries(std::vector<int> &seconds) = 0;
-
- /**
- * @brief Get information about vehicle
- */
- virtual VehicleData GetVehicleData() = 0;
-
- /**
- * @brief Allows to update 'vin' field in module_meta table.
- *
- * @param new 'vin' value.
- *
- * @return true in case when data has been successfully updated,
- * false otherwise.
- */
- virtual bool SetVINValue(const std::string& value) = 0;
-
- /**
- * @brief Get message text for displaying/pronouncing for user
- * dependent on language and context.
- * @param msg_codes Context of message (Driver distraction, Grant permission etc)
- * @param language Language of the message
- * @return Array of appropriate messages parameters
- */
- virtual std::vector<UserFriendlyMessage> GetUserFriendlyMsg(
- const std::vector<std::string>& msg_codes,
- const std::string& language) = 0;
-
- /**
- * @brief Get list of URLs related to particular service
- * @param service_type If URLs for specific service are preset,
- * return them otherwise default URLs.
- */
- virtual void GetServiceUrls(const std::string& service_type,
- EndpointUrls& end_points) = 0;
-
- /**
- * @brief GetLockScreenIcon allows to obtain lock screen icon url;
- *
- * @return url which point to the resourse where lock screen icon could be obtained.
- */
- virtual std::string GetLockScreenIconUrl() const = 0;
-
- /**
- * @brief Get allowed number of notifications
- * depending on application priority.
- * @param priority Priority of application
- */
- virtual int GetNotificationsNumber(const std::string& priority) = 0;
-
- /**
- * @brief Get priority for given application
- * @param policy_app_id Unique application id
- * @param priority Priority for application or empty, if value was not set
- * @return true, if succedeed, otherwise - false
- */
- virtual bool GetPriority(const std::string& policy_app_id,
- std::string& priority) = 0;
-
- /**
- * @brief Initialized Policy Table (load)
- * @return bool Success of operation
- */
- virtual bool Init(const std::string& file_name) = 0;
-
- /**
- * @brief Get snapshot of Policy Table
- * including app_policies, functional_groups,
- * device_info, statistics, excluding user messages
- * @return Generated structure for obtaining Json string.
- */
- virtual utils::SharedPtr<policy_table::Table> GenerateSnapshot() = 0;
-
- /**
- * Applies policy table to the current table
- * @param update_pt policy table
- * @return true if successfully
- */
- virtual bool ApplyUpdate(const policy_table::Table& update_pt) = 0;
-
- /**
- * @brief Gets list of appHMIType associated with mobile appID
- * @param container of appHMIType
- */
- virtual void GetHMIAppTypeAfterUpdate(std::map<std::string, StringArray>& app_hmi_types) = 0;
-
- /**
- * Gets flag updateRequired
- * @return true if update is required
- */
- virtual bool UpdateRequired() const = 0;
-
- /**
- * @brief Saves flag updateRequired
- * @param status update status if true then update required.
- */
- virtual void SaveUpdateRequired(bool status) = 0;
-
- /**
- * @brief GetInitialAppData Retrieves data from app_policies
- * about app on its registration
- * @param app_id id of registered app.
- * All outputs are filled in only if not null
- * @param nicknames Synonyms for application
- * @param app_hmi_types app_types Section on HMI where app can
- * appear (Navigation, Phone etc)
- * @return true in case initial application data was obtained successfuly.
- */
- virtual bool GetInitialAppData(const std::string& app_id,
- StringArray& nicknames,
- StringArray& app_hmi_types) = 0;
-
- /**
- * Checks if the application is revoked
- * @param app_id application id
- * @return true if application is revoked
- */
- virtual bool IsApplicationRevoked(const std::string& app_id) const = 0;
-
- /**
- * @brief Get functional groupings from DB
- * @param groups Known functional groupings
- * @return true, if succeeded, otherwise - false
- */
- virtual bool GetFunctionalGroupings(
- policy_table::FunctionalGroupings& groups) = 0;
-
- /**
- * Checks if the application is represented in policy table
- * @param app_id application id
- * @return true if application is represented in policy table
- */
- virtual bool IsApplicationRepresented(const std::string& app_id) const = 0;
-
- /**
- * Checks if the application has default policy
- * @param app_id application id
- * @return true if application has default policy
- */
- virtual bool IsDefaultPolicy(const std::string& app_id) = 0;
-
- /**
- * @brief SetIsDefault Sets is_default flag for application
- * @param app_id app specific application
- * @return true in case opperation was done successfully.
- */
- virtual bool SetIsDefault(const std::string& app_id) = 0;
-
- /**
- * Checks if the application has pre_data policy
- * @param app_id application id
- * @return true if application has pre_data policy
- */
- virtual bool IsPredataPolicy(const std::string& app_id) = 0;
-
- /**
- * Sets default policy for application
- * @param app_id application id
- * @return true if success
- */
- virtual bool SetDefaultPolicy(const std::string& app_id) = 0;
-
- /**
- * @brief Is application allowed to send notifications while in
- * Backgound or limited mode.
- * @param app_id Application id
- * @return bool Allowed/disallowed.
- */
- virtual bool CanAppKeepContext(const std::string& app_id) = 0;
-
- /**
- * @brief Is application allowed to move foreground at will?
- * @param app_id Application id
- * @return bool Allowed/disallowed.
- */
- virtual bool CanAppStealFocus(const std::string& app_id) = 0;
-
- /**
- * @brief Get default_hmi for given application
- * @param policy_app_id Unique application id
- * @param default_hmi Default HMI level for application or empty, if value was
- * not set
- * @return true, if succedeed, otherwise - false
- */
- virtual bool GetDefaultHMI(const std::string& app_id,
- std::string &default_hmi) = 0;
-
- /**
- * @brief Reset user consent for device data and applications permissions
- * @return
- */
- virtual bool ResetUserConsent() = 0;
-
- /**
- * @brief Get user permissions for device data usage
- * @param device_id Generated or obtained id of device
- * @param consented_groups Groups consented by user
- * @param disallowed_groups Groups not consented by user
- * @return true, if query was successfull, otherwise - false
- */
- virtual bool GetUserPermissionsForDevice(const std::string& device_id,
- StringArray &consented_groups,
- StringArray &disallowed_groups) = 0;
-
- /**
- * @brief Gets list of groups permissions from policy table
- * @param device_id Unique device id, which hosts specific application
- * @param policy_app_id Unique application id
- * @param group_types Group list sorted by permission status
- * @return true, if query was successfull, otherwise - false
- */
- virtual bool GetPermissionsForApp(const std::string& device_id,
- const std::string& app_id,
- FunctionalIdType &group_types) = 0;
-
- /**
- * @brief Get device groups and preconsented groups from policies section
- * @param groups List of groups to be consented for device usage
- * @param preconsented_groups List of preconsented groups for device usage
- * @return true, if query was successful, otherwise - false
- */
- virtual bool GetDeviceGroupsFromPolicies(
- rpc::policy_table_interface_base::Strings &groups,
- rpc::policy_table_interface_base::Strings &preconsented_groups) = 0;
-
- /**
- * @brief Record information about mobile device in Policy Table.
- * @param device_id Generated or obtained id of device
- * @return bool Success of operation
- */
- virtual bool SetDeviceData(const std::string& device_id,
- const std::string& hardware,
- const std::string& firmware, const std::string& os,
- const std::string& os_version,
- const std::string& carrier,
- const uint32_t number_of_ports,
- const std::string& connection_type) = 0;
-
- /**
- * @brief Sets user consent for particular mobile device,
- * i.e. to use device for exchanging of Policy Table.
- * @return bool Success of operation
- */
- virtual bool SetUserPermissionsForDevice(
- const std::string& device_id, const StringArray& consented_groups,
- const StringArray& disallowed_groups) = 0;
-
- /**
- * @brief Update Application Policies as reaction
- * on User allowing/disallowing device this app is running on.
- */
- virtual bool ReactOnUserDevConsentForApp(const std::string& app_id,
- bool is_device_allowed) = 0;
-
- /**
- * @brief Set user consent on functional groups
- * @param permissions User consent on functional group
- * @return true, if operation succedeed, otherwise - false
- */
- virtual bool SetUserPermissionsForApp(
- const PermissionConsent& permissions) = 0;
-
- /**
- * @brief Records information about head unit system to PT
- * @return bool Success of operation
- */
- virtual bool SetMetaInfo(const std::string& ccpu_version,
- const std::string& wers_country_code,
- const std::string& language) = 0;
-
- /**
- * @brief Checks, if specific head unit is present in PT
- * @return boot Suceess, if present, otherwise - false
- */
- virtual bool IsMetaInfoPresent() const = 0;
-
- /**
- * @brief Set current system language
- * @param language System language
- * @return true, if succedeed, otherwise - false
- */
- virtual bool SetSystemLanguage(const std::string& language) = 0;
-
- /**
- * Increments global counter
- * @param type type of counter
- */
- virtual void Increment(usage_statistics::GlobalCounterId type) = 0;
-
- /**
- * Increments counter of application
- * @param app_id id application
- * @param type type of counter
- */
- virtual void Increment(const std::string& app_id,
- usage_statistics::AppCounterId type) = 0;
-
- /**
- * Sets value of application information
- * @param app_id id application
- * @param type type of information
- * @param value value of information
- */
- virtual void Set(const std::string& app_id, usage_statistics::AppInfoId type,
- const std::string& value) = 0;
-
- /**
- * Adds value to stopwatch of application
- * @param app_id id application
- * @param type type of stopwatch
- * @param seconds value for adding in seconds
- */
- virtual void Add(const std::string& app_id,
- usage_statistics::AppStopwatchId type, int seconds) = 0;
-
- /**
- * @brief CountUnconsentedGroups allows to obtain the count of unconsented
- * groups for specific application.
- * @param policy_app_id application id.
- * @param device_id device id.
- * @param the count of unconsented groups
- */
- virtual int CountUnconsentedGroups(const std::string& policy_app_id,
- const std::string& device_id) = 0;
-
- /**
- * @brief Gets functional group names and user_consent_prompts, if any
- * @param Array to be filled with group ids, names and functional prompts
- * @return true, if succeeded, otherwise - false
- */
- virtual bool GetFunctionalGroupNames(FunctionalGroupNames& names) = 0;
-
- /**
- * @brief GetAllAppGroups allows to obtain all groups for certain application.
- * @param app_id specific application id.
- * @param all_group_ids parameter to fill.
- */
- virtual void GetAllAppGroups(const std::string& app_id,
- FunctionalGroupIDs& all_group_ids) = 0;
- /**
- * @brief GetPreConsentedGroups allows to obtain all pre-consented groups for
- * specific application.
- * @param app_id specific application id.
- * @param preconsented_groups parameter to fill.
- */
- virtual void GetPreConsentedGroups(
- const std::string &app_id, FunctionalGroupIDs& preconsented_groups) = 0;
- /**
- * @brief GetConsentedGroups allows to obtain list of allowed and disallowed
- * groups for specific application on certain device.
- * @param device_id certain device
- * @param app_id application id.
- * @param allowed_groups list of allowed groups
- * @param disallowed_groups list of disallowed groups
- */
- virtual void GetConsentedGroups(const std::string &device_id,
- const std::string &app_id,
- FunctionalGroupIDs& allowed_groups,
- FunctionalGroupIDs& disallowed_groups) = 0;
-
- /**
- * @brief GetUnconsentedGroups allows to obtain list of allowed and disallowed
- * groups for specific application on certain device.
- * @param device_id certain device
- * @param policy_app_id application id.
- * @param unconsented_groups list of unconsented groups.
- */
- virtual void GetUnconsentedGroups(const std::string& device_id,
- const std::string& policy_app_id,
- FunctionalGroupIDs& unconsented_groups) = 0;
-
- virtual void RemoveAppConsentForGroup(const std::string& app_id,
- const std::string& group_name) = 0;
-
- /**
- * @brief Set app policy to pre_DataConsented policy
- * @param app_id Policy ID of application to be changed
- * @return true, if succeeded, otherwise - false
- */
- virtual bool SetPredataPolicy(const std::string& app_id) = 0;
-
- /**
- * @brief Removes unpaired devices
- * @return true if success
- */
- virtual bool CleanupUnpairedDevices() = 0;
-
- /**
- * Sets flag of unpaired device
- * @param device_id Unique device id
- * @param unpaired True, if should be marked as unpaired, otherwise - false
- * @return true if success
- */
- virtual bool SetUnpairedDevice(const std::string& device_id, bool unpaired = true) = 0;
-
- /**
- * Resets Policy Table
- * @param file_name Path to preloaded PT file
- * @return true if successfully
- */
- virtual bool ResetPT(const std::string& file_name) = 0;
-
- /**
- * @brief LoadFromBackup allows to load policy into the cache from backup.
- * @return true in case operation was successful.
- */
- virtual bool LoadFromBackup() = 0;
-
- /**
- * @brief LoadFromFile allows to load policy cache from preloaded table.
- * @param file_name preloaded
- * @return
- */
- virtual bool LoadFromFile(const std::string& file_name) = 0;
-
- /**
- * @brief Backup allows to save cache onto hard drive.
- */
- virtual void Backup() = 0;
-
- /**
- * Returns heart beat timeout
- * @param app_id application id
- * @return if timeout was set then value in seconds greater zero
- * otherwise heart beat for specific application isn't set
- */
- virtual uint16_t HeartBeatTimeout(const std::string& app_id) const = 0;
-
- /**
- * @brief Resets all calculated permissions in cache
- */
- virtual void ResetCalculatedPermissions() = 0;
-
- /**
- * @brief Adds calculated permissions for specific app on particular device
- * into cache
- * @param device_id Device id
- * @param policy_app_id Application id
- * @param permissions Calculated permissions
- */
- virtual void AddCalculatedPermissions(
- const std::string& device_id,
- const std::string& policy_app_id,
- const policy::Permissions& permissions) = 0;
-
- /**
- * @brief Checks if permissions calculated for specific app on particular
- * device
- * @param device_id Device id
- * @param policy_app_id Application id
- * @param permission Permissions to be filled, in case of presence in cache
- * @return true if present, otherwise false
- */
- virtual bool IsPermissionsCalculated(
- const std::string& device_id,
- const std::string& policy_app_id,
- policy::Permissions& permission) = 0;
-
- /**
- * @brief Gets request types for application
- * @param policy_app_id Unique application id
- * @param request_types Request types of application
- */
- virtual void GetAppRequestTypes(
- const std::string& policy_app_id,
- std::vector<std::string>& request_types) const = 0;
-};
-
-typedef utils::SharedPtr<CacheManagerInterface> CacheManagerInterfaceSPtr;
-
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_SRC_POLICY_INCLUDE_POLICY_CACHE_MANAGER_INTERFACE_H_
diff --git a/src/components/policy/src/policy/include/policy/policy_helper.h b/src/components/policy/src/policy/include/policy/policy_helper.h
deleted file mode 100644
index c3fcce6b2b..0000000000
--- a/src/components/policy/src/policy/include/policy/policy_helper.h
+++ /dev/null
@@ -1,243 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_HELPER_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_HELPER_H_
-
-#include "./functions.h"
-#include "utils/shared_ptr.h"
-#include "policy/policy_types.h"
-
-namespace policy {
-class PolicyManagerImpl;
-
-const std::string kAllowedKey = "allowed";
-const std::string kUserDisallowedKey = "userDisallowed";
-const std::string kUndefinedKey = "undefined";
-
-namespace policy_table = rpc::policy_table_interface_base;
-
-typedef policy_table::Strings::const_iterator StringsConstItr;
-typedef policy_table::ApplicationPolicies::const_iterator AppPoliciesConstItr;
-typedef policy_table::HmiLevels::const_iterator HMILevelsConstItr;
-typedef policy_table::Parameters::const_iterator ParametersConstItr;
-typedef policy_table::FunctionalGroupings::const_iterator FuncGroupConstItr;
-
-typedef policy_table::ApplicationPolicies::value_type AppPoliciesValueType;
-typedef policy_table::Rpc::value_type RpcValueType;
-typedef policy_table::Strings::value_type StringsValueType;
-
-/*
- * @brief Helper struct to compare functional group names
- */
-struct CompareGroupName {
- explicit CompareGroupName(const StringsValueType& group_name);
- bool operator()(const StringsValueType& group_name_to_compare) const;
- private:
- const StringsValueType& group_name_;
-};
-
-/*
- * @brief Used for compare of policies parameters mapped with specific
- * application ids
- */
-bool operator!=(const policy_table::ApplicationParams& first,
- const policy_table::ApplicationParams& second);
-
-/*
- * @brief Helper struct for checking changes of application policies, which
- * come with update along with current data snapshot
- * In case of policies changed for some application, current data will be
- * updated and notification will be sent to application
- */
-struct CheckAppPolicy {
- CheckAppPolicy(PolicyManagerImpl* pm,
- const utils::SharedPtr<policy_table::Table> update,
- const utils::SharedPtr<policy_table::Table> snapshot);
- bool operator()(const AppPoliciesValueType& app_policy);
- private:
- enum PermissionsCheckResult {
- RESULT_NO_CHANGES,
- RESULT_APP_REVOKED,
- RESULT_NICKNAME_MISMATCH,
- RESULT_PERMISSIONS_REVOKED,
- RESULT_CONSENT_NEEDED,
- RESULT_CONSENT_NOT_REQIURED,
- RESULT_PERMISSIONS_REVOKED_AND_CONSENT_NEEDED,
- RESULT_REQUEST_TYPE_CHANGED
- };
-
- void SetPendingPermissions(const AppPoliciesValueType& app_policy,
- PermissionsCheckResult result) const;
- PermissionsCheckResult CheckPermissionsChanges(
- const AppPoliciesValueType &app_policy) const;
- bool HasRevokedGroups(const AppPoliciesValueType& app_policy,
- policy_table::Strings* revoked_groups = NULL) const;
- bool HasNewGroups(const AppPoliciesValueType& app_policy,
- policy_table::Strings* new_groups = NULL) const;
- bool HasConsentNeededGroups(const AppPoliciesValueType& app_policy) const;
- std::vector<FunctionalGroupPermission> GetRevokedGroups(
- const AppPoliciesValueType& app_policy) const;
- void RemoveRevokedConsents(
- const AppPoliciesValueType& app_policy,
- const std::vector<FunctionalGroupPermission>& revoked_groups) const;
- bool IsKnownAppication(const std::string& application_id) const;
- void NotifySystem(const AppPoliciesValueType& app_policy) const;
- void SendPermissionsToApp(const AppPoliciesValueType& app_policy) const;
- bool IsAppRevoked(const AppPoliciesValueType& app_policy) const;
- bool NicknamesMatch(const AppPoliciesValueType& app_policy) const;
- /**
- * @brief Allows to check if appropriate group requires any consent.
- * @param group_name the group for which consent will be checked.
- * @return true if consent is required, false otherwise.
- */
- bool IsConsentRequired(const std::string& app_id,
- const std::string& group_name) const;
- bool IsRequestTypeChanged(const AppPoliciesValueType& app_policy) const;
-
- private:
- PolicyManagerImpl* pm_;
- const utils::SharedPtr<policy_table::Table> update_;
- const utils::SharedPtr<policy_table::Table> snapshot_;
-};
-
-/*
- * @brief Fill permissions data with merged rpc permissions for hmi levels and
- * parameters
- */
-struct FillNotificationData {
- FillNotificationData(Permissions& data, GroupConsent group_state,
- GroupConsent undefined_group_consent);
- bool operator()(const RpcValueType& rpc);
- void UpdateHMILevels(const policy_table::HmiLevels& in_hmi,
- std::set<HMILevel>& out_hmi);
- void UpdateParameters(const policy_table::Parameters& in_parameters,
- std::set<Parameter>& out_parameter);
- private:
- void ExcludeSame();
- void ExcludeSameHMILevels(std::set<HMILevel>& source,
- const std::set<HMILevel>& target);
- void ExcludeSameParameters(std::set<Parameter>& source,
- const std::set<Parameter>& target);
- void InitRpcKeys(const std::string& rpc_name);
- std::string current_key_;
- Permissions& data_;
-};
-
-/*
- * @brief Checks for functional group presence and pass it to helper struct,
- * which fills permissions data according to group consent
- */
-struct ProcessFunctionalGroup {
- ProcessFunctionalGroup(
- const policy_table::FunctionalGroupings& fg,
- const std::vector<FunctionalGroupPermission>& group_permissions,
- Permissions& data,
- GroupConsent undefined_group_consent = GroupConsent::kGroupDisallowed);
- bool operator()(const StringsValueType& group_name);
- private:
- GroupConsent GetGroupState(const std::string& group_name);
- const policy_table::FunctionalGroupings& fg_;
- const std::vector<FunctionalGroupPermission>& group_permissions_;
- Permissions& data_;
- GroupConsent undefined_group_consent_;
-};
-
-struct FunctionalGroupInserter {
- FunctionalGroupInserter(const policy_table::Strings& preconsented_groups,
- PermissionsList& list);
- void operator()(const StringsValueType& group_name);
- private:
- PermissionsList& list_;
- const policy_table::Strings& preconsented_;
-};
-
-/**
- * @brief Fills FunctionalGroupPermissions with provided params
- * @param ids Functional group ids from DB
- * @param names Group names and user_consent_prompt
- * @param state User consent for group
- * @param permissions Struct to be filled with provided params
- */
-void FillFunctionalGroupPermissions(
- FunctionalGroupIDs& ids,
- FunctionalGroupNames& names,
- GroupConsent state,
- std::vector<FunctionalGroupPermission>& permissions);
-
-/**
- * @brief Checks, if application is predefined, e.g. "default", i.e. which is
- * must be present in policy table
- * @param app Application struct
- * @return true, if app is predefined, otherwise - false
- */
-bool IsPredefinedApp(const AppPoliciesValueType& app);
-
-/**
- * @brief Excludes same values
- * @param from Source, which should be checked
- * @param what Target, which should be excluded from source
- * @return Values without excluded
- */
-FunctionalGroupIDs ExcludeSame(const FunctionalGroupIDs& from,
- const FunctionalGroupIDs& what);
-
-/**
- * @brief Merges all values without same values
- * @param first First source of values
- * @param second Second source of values
- * @return Merged values w/o same values
- */
-FunctionalGroupIDs Merge(const FunctionalGroupIDs& first,
- const FunctionalGroupIDs& second);
-
-/**
- * @brief Finds same values
- * @param first First source of values
- * @param second Second source of values
- * @return Same values set, if any found
- */
-FunctionalGroupIDs FindSame(const FunctionalGroupIDs& first,
- const FunctionalGroupIDs& second);
-
-/**
- * @brief Unwrap application policies from predefined values to specific policy
- * values, i.e. if application has "default", it will be assigned default
- * policies
- * @param app_policies Application policies to unwrap
- * @return true, if succeded, otherwise - false
- */
-bool UnwrapAppPolicies(policy_table::ApplicationPolicies& app_policies);
-
-}
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_HELPER_H_
diff --git a/src/components/policy/src/policy/include/policy/policy_listener.h b/src/components/policy/src/policy/include/policy/policy_listener.h
deleted file mode 100644
index 9046af4201..0000000000
--- a/src/components/policy/src/policy/include/policy/policy_listener.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*
- Copyright (c) 2016, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_LISTENER_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_LISTENER_H_
-
-#include <queue>
-
-#include "policy/policy_types.h"
-
-namespace policy {
-class PolicyListener {
-public:
- virtual ~PolicyListener() {}
- virtual void OnPermissionsUpdated(const std::string &policy_app_id,
- const Permissions &permissions,
- const policy::HMILevel &default_hmi) = 0;
- virtual void OnPermissionsUpdated(const std::string &policy_app_id,
- const Permissions &permissions) = 0;
- virtual void OnPendingPermissionChange(const std::string &policy_app_id) = 0;
- virtual void OnUpdateStatusChanged(const std::string &) = 0;
- virtual std::string
- OnCurrentDeviceIdUpdateRequired(const std::string &policy_app_id) = 0;
- virtual void OnSystemInfoUpdateRequired() = 0;
- virtual std::string GetAppName(const std::string &policy_app_id) = 0;
- virtual void
- OnUpdateHMIAppType(std::map<std::string, StringArray> app_hmi_types) = 0;
-
- /**
- * @brief CanUpdate allows to find active application
- * and check whether related device consented.
- *
- * @return true if there are at least one application has been registered
- * with consented device.
- */
- virtual bool CanUpdate() = 0;
-
- /**
- * @brief OnSnapshotCreated the notification which will be sent
- * when snapshot for PTU has been created.
- *
- * @param pt_string the snapshot
- *
- */
- virtual void OnSnapshotCreated(const BinaryMessage &pt_string) = 0;
-
- /**
- * @brief Make appropriate changes for related applications permissions and
- * notify them, if it possible
- * @param device_id Unique device id, which consent had been changed
- * @param device_consent Device consent, which is done by user
- */
- virtual void OnDeviceConsentChanged(const std::string &device_id,
- bool is_allowed) = 0;
-
- /**
- * @brief GetAvailableApps allows to obtain list of registered applications.
- */
- virtual void GetAvailableApps(std::queue<std::string> &) = 0;
-
- /**
- * @brief OnCertificateUpdated the callback which signals if certificate field
- * has been updated during PTU
- *
- * @param certificate_data the value of the updated field.
- */
- virtual void OnCertificateUpdated(const std::string &certificate_data) = 0;
-};
-} // namespace policy
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_LISTENER_H_
diff --git a/src/components/policy/src/policy/include/policy/policy_manager.h b/src/components/policy/src/policy/include/policy/policy_manager.h
deleted file mode 100644
index 0a62c94e7d..0000000000
--- a/src/components/policy/src/policy/include/policy/policy_manager.h
+++ /dev/null
@@ -1,453 +0,0 @@
-/*
- Copyright (c) 2016, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_H_
-
-#include <vector>
-#include <cstdint>
-
-#include "policy/policy_types.h"
-#include "policy/policy_listener.h"
-#include "usage_statistics/statistics_manager.h"
-
-namespace policy {
-class PolicyManager : public usage_statistics::StatisticsManager {
-
-public:
- virtual ~PolicyManager() {}
-
- virtual void set_listener(PolicyListener *listener) = 0;
-
- /**
- * Inits Policy Table
- * @param file_name Path to preloaded PT file
- * @return true if successfully
- */
- virtual bool InitPT(const std::string &file_name) = 0;
-
- /**
- * @brief Updates Policy Table from binary message received from
- * mobile device. Saves to Policy Table diff between Policy Table
- * sent in snapshot and received Policy Table.
- * @param file name of file with update policy table
- * @param pt_content PTU as binary string
- * @return bool Success of operation
- */
- virtual bool LoadPT(const std::string &file,
- const BinaryMessage &pt_content) = 0;
-
- /**
- * Resets Policy Table
- * @param file_name Path to preloaded PT file
- * @return true if successfully
- */
- virtual bool ResetPT(const std::string &file_name) = 0;
-
- /**
- * @brief GetLockScreenIcon allows to obtain lock screen icon url;
- *
- * @return url which point to the resourse where lock screen icon could be
- *obtained.
- */
- virtual std::string GetLockScreenIconUrl() const = 0;
-
- /**
- * @brief Gets all URLs for sending PTS to from PT itself.
- * @param service_type Service specifies user of URL
- * @return vector of urls
- */
- virtual void GetServiceUrls(const std::string &service_type,
- EndpointUrls &end_points) = 0;
-
- /**
- * @brief PTU is needed, for this PTS has to be formed and sent.
- */
- virtual bool RequestPTUpdate() = 0;
-
- /**
- * @brief Check if specified RPC for specified application
- * has permission to be executed in specified HMI Level
- * and also its permitted params.
- * @param app_id Id of application provided during registration
- * @param hmi_level Current HMI Level of application
- * @param rpc Name of RPC
- * @param CheckPermissionResult containing flag if HMI Level is allowed
- * and list of allowed params.
- */
- virtual void CheckPermissions(const PTString &app_id,
- const PTString &hmi_level, const PTString &rpc,
- const RPCParams &rpc_params,
- CheckPermissionResult &result) = 0;
-
- /**
- * @brief Clear all record of user consents. Used during Factory Reset.
- * @return bool Success of operation
- */
- virtual bool ResetUserConsent() = 0;
-
- /**
- * @brief Returns current status of policy table for HMI
- * @return Current status of policy table
- */
- virtual std::string GetPolicyTableStatus() const = 0;
-
- /**
- * Checks is PT exceeded kilometers
- * @param kilometers current kilometers at odometer
- * @return true if exceeded
- */
- virtual void KmsChanged(int kilometers) = 0;
-
- /**
- * Increments counter of ignition cycles
- */
- virtual void IncrementIgnitionCycles() = 0;
-
- /**
- * @brief ExchangeByUserRequest
- */
- virtual std::string ForcePTExchange() = 0;
-
- /**
- * Resets retry sequence
- */
- virtual void ResetRetrySequence() = 0;
-
- /**
- * Gets timeout to wait before next retry updating PT
- * If timeout is equal to zero then the retry sequence is not need.
- * @return timeout in seconds
- */
- virtual uint32_t NextRetryTimeout() = 0;
-
- /**
- * Gets timeout to wait until receive response
- * @return timeout in seconds
- */
- virtual int TimeoutExchange() = 0;
-
- /**
- * @brief List of timeouts in seconds between retries
- * when attempt to update PT fails
- * @return List of delays between attempts.
- */
- virtual const std::vector<int> RetrySequenceDelaysSeconds() = 0;
-
- /**
- * Handler of exceeding timeout of exchanging policy table
- */
- virtual void OnExceededTimeout() = 0;
-
- /**
- * @brief Handler of PTS sending out
- */
- virtual void OnUpdateStarted() = 0;
-
- /**
- * @brief Check user consent for mobile device data connection
- * @param device_id Unique device identifier
- * @return status of device consent
- */
- virtual DeviceConsent
- GetUserConsentForDevice(const std::string &device_id) = 0;
-
- /**
- * @brief Get user consent for application
- * @param device_id Device id
- * @param policy_app_id Unique application id
- * @param permissions Array of functional groups permissions
- */
- virtual void
- GetUserConsentForApp(const std::string &device_id,
- const std::string &policy_app_id,
- std::vector<FunctionalGroupPermission> &permissions) = 0;
-
- /**
- * @brief Set user consent for mobile device data connection
- * @param device_id Unique device identifier
- * @param is_allowed User consent for usage device data connection
- */
- virtual void SetUserConsentForDevice(const std::string &device_id,
- bool is_allowed) = 0;
-
- /**
- * @brief Update Application Policies as reaction
- * on User allowing/disallowing device this app is running on.
- */
- virtual bool ReactOnUserDevConsentForApp(const std::string app_id,
- bool is_device_allowed) = 0;
- /**
- * Sets number of kilometers and days after epoch, that passed for
- * receiving PT UPdate.
- */
- virtual void PTUpdatedAt(int kilometers, int days_after_epoch) = 0;
-
- /**
- * @brief Retrieves data from app_policies about app on its registration:
- * @param app_id - id of registered app
- * @param app_types Section on HMI where app can appear (Navigation, Phone
- * etc)
- * @param nicknames Synonyms for application
- */
- virtual bool GetInitialAppData(const std::string &application_id,
- StringArray *nicknames = NULL,
- StringArray *app_hmi_types = NULL) = 0;
- /**
- * @brief Stores device parameters received during application registration
- * to policy table
- * @param device_id Device mac address
- * @param device_info Received device parameters
- */
- virtual void SetDeviceInfo(const std::string &device_id,
- const DeviceInfo &device_info) = 0;
-
- /**
- * @brief Set user consent for application functional groups
- * @param permissions User-defined application group pemissions.
- * The permissions is not const reference because it may contains
- * valid data as well as invalid. So we will remove all invalid data
- * from this structure.
- */
- virtual void SetUserConsentForApp(const PermissionConsent &permissions) = 0;
-
- /**
- * @brief Get default HMI level for application
- * @param policy_app_id Unique application id
- * @param default_hmi Default HMI level for application or empty, if value
- * was not set
- * @return true, if succedeed, otherwise - false
- */
- virtual bool GetDefaultHmi(const std::string &policy_app_id,
- std::string *default_hmi) = 0;
-
- /**
- * @brief Get priority for application
- * @param policy_app_id Unique application id
- * @param priority Priority for application or empty, if value was not set
- * @return true, if succedeed, otherwise - false
- */
- virtual bool GetPriority(const std::string &policy_app_id,
- std::string *priority) = 0;
-
- /**
- * @brief Get user friendly messages for given RPC messages and language
- * @param message_codes RPC message codes
- * @param language Language
- * @return Array of structs with appropriate message parameters
- */
- virtual std::vector<UserFriendlyMessage>
- GetUserFriendlyMessages(const std::vector<std::string> &message_code,
- const std::string &language) = 0;
-
- /**
- * Checks if the application is revoked
- * @param app_id application id
- * @return true if application is revoked
- */
- virtual bool IsApplicationRevoked(const std::string &app_id) const = 0;
-
- /**
- * @brief Get resulting RPCs permissions for application which started on
- * specific device
- * @param device_id Device id
- * @param policy_app_id Unique application id
- * @param permissions Array of functional groups permissions
- */
- virtual void
- GetPermissionsForApp(const std::string &device_id,
- const std::string &policy_app_id,
- std::vector<FunctionalGroupPermission> &permissions) = 0;
-
- /**
- * @brief Gets specific application permissions changes since last policy
- * table update
- * @param policy_app_id Unique application id
- * @return Permissions changes
- */
- virtual AppPermissions
- GetAppPermissionsChanges(const std::string &policy_app_id) = 0;
-
- virtual void RemovePendingPermissionChanges(const std::string &app_id) = 0;
-
- /**
- * @brief Return device id, which hosts specific application
- * @param Application id, which is required to update device id
- */
- virtual std::string &GetCurrentDeviceId(const std::string &policy_app_id) = 0;
-
- /**
- * @brief Set current system language
- * @param language Language
- */
- virtual void SetSystemLanguage(const std::string &language) = 0;
-
- /**
- * @brief Set data from GetSystemInfo response to policy table
- * @param ccpu_version CCPU version
- * @param wers_country_code WERS country code
- * @param language System language
- */
- virtual void SetSystemInfo(const std::string &ccpu_version,
- const std::string &wers_country_code,
- const std::string &language) = 0;
-
- /**
- * @brief Send OnPermissionsUpdated for choosen application
- * @param application_id
- */
- virtual void
- SendNotificationOnPermissionsUpdated(const std::string &application_id) = 0;
-
- /**
- * Marks device as upaired
- * @param device_id id device
- */
- virtual void MarkUnpairedDevice(const std::string &device_id) = 0;
-
- /**
- * @brief Adds, application to the db or update existed one
- * run PTU if policy update is necessary for application.
- * @param Application id assigned by Ford to the application
- */
- virtual void AddApplication(const std::string &application_id) = 0;
-
- /**
- * @brief Removes unpaired device records and related records from DB
- * @param device_ids List of device_id, which should be removed
- * @return true, if succedeed, otherwise - false
- */
- virtual bool CleanupUnpairedDevices() = 0;
-
- /**
- * @brief Check if app can keep context.
- */
- virtual bool CanAppKeepContext(const std::string &app_id) = 0;
-
- /**
- * @brief Check if app can steal focus.
- */
- virtual bool CanAppStealFocus(const std::string &app_id) = 0;
-
- /**
- * @brief Runs necessary operations, which is depends on external system
- * state, e.g. getting system-specific parameters which are need to be
- * filled into policy table
- */
- virtual void OnSystemReady() = 0;
-
- /**
- * @brief GetNotificationNumber
- * @param priority
- * @return
- */
- virtual uint32_t GetNotificationsNumber(const std::string &priority) = 0;
-
- /**
- * @brief Allows to update Vehicle Identification Number in policy table.
- * @param new value for the parameter.
- */
- virtual void SetVINValue(const std::string &value) = 0;
-
- /**
- * @brief Checks, if application has policy assigned w/o data consent
- * @param policy_app_id Unique application id
- * @return true, if policy assigned w/o data consent, otherwise -false
- */
- virtual bool IsPredataPolicy(const std::string &policy_app_id) = 0;
-
- /**
- * Returns heart beat timeout
- * @param app_id application id
- * @return if timeout was set then value in seconds greater zero
- * otherwise heart beat for specific application isn't set
- */
- virtual uint16_t HeartBeatTimeout(const std::string &app_id) const = 0;
-
- /**
- * @brief SaveUpdateStatusRequired alows to save update status.
- */
- virtual void SaveUpdateStatusRequired(bool is_update_needed) = 0;
-
- /**
- * @brief Handler on applications search started
- */
- virtual void OnAppsSearchStarted() = 0;
-
- /**
- * @brief Handler on applications search completed
- */
- virtual void OnAppsSearchCompleted() = 0;
-
- /**
- * @brief OnAppRegisteredOnMobile alows to handle event when application were
- * succesfully registered on mobile device.
- * It will send OnAppPermissionSend notification and will try to start PTU.
- *
- * @param application_id registered application.
- */
- virtual void OnAppRegisteredOnMobile(const std::string &application_id) = 0;
-
- /**
- * @brief Gets request types for application
- * @param policy_app_id Unique application id
- * @return request_types Request types of application
- */
- virtual const std::vector<std::string>
- GetAppRequestTypes(const std::string policy_app_id) const = 0;
-
-protected:
- /**
- * Checks is PT exceeded IgnitionCycles
- * @return true if exceeded
- */
- virtual bool ExceededIgnitionCycles() = 0;
-
- /**
- * Checks is PT exceeded days
- * @return true if exceeded
- */
- virtual bool ExceededDays() = 0;
-
- /**
- * @brief StartPTExchange allows to start PTU. The function will check
- * if one is required and starts the update flow in only case when previous
- * condition is true.
- */
- virtual void StartPTExchange() = 0;
-};
-
-} // namespace policy
-
-extern "C" policy::PolicyManager *CreateManager();
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_H_
diff --git a/src/components/policy/src/policy/include/policy/policy_manager_impl.h b/src/components/policy/src/policy/include/policy/policy_manager_impl.h
deleted file mode 100644
index 78688c8fd5..0000000000
--- a/src/components/policy/src/policy/include/policy/policy_manager_impl.h
+++ /dev/null
@@ -1,332 +0,0 @@
-/*
- Copyright (c) 2016, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_IMPL_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_IMPL_H_
-
-#include <list>
-#include <cstdint>
-
-#include "utils/shared_ptr.h"
-#include "utils/lock.h"
-#include "policy/policy_manager.h"
-#include "policy/policy_table.h"
-#include "policy/cache_manager_interface.h"
-#include "policy/update_status_manager.h"
-#include "./functions.h"
-#include "usage_statistics/statistics_manager.h"
-#include "policy/policy_helper.h"
-#include "utils/timer_thread.h"
-
-namespace policy_table = rpc::policy_table_interface_base;
-
-namespace policy {
-struct CheckAppPolicy;
-
-class PolicyManagerImpl : public PolicyManager {
-public:
- PolicyManagerImpl();
- virtual void set_listener(PolicyListener *listener);
- PolicyListener *listener() const { return listener_; }
- virtual bool InitPT(const std::string &file_name);
- virtual bool LoadPT(const std::string &file, const BinaryMessage &pt_content);
- virtual bool ResetPT(const std::string &file_name);
-
- virtual void GetServiceUrls(const std::string &service_type,
- EndpointUrls &end_points);
-
- virtual std::string GetLockScreenIconUrl() const;
- virtual bool RequestPTUpdate();
- virtual void CheckPermissions(const PTString &app_id,
- const PTString &hmi_level, const PTString &rpc,
- const RPCParams &rpc_params,
- CheckPermissionResult &result);
- virtual bool ResetUserConsent();
- virtual void KmsChanged(int kilometers);
- virtual void IncrementIgnitionCycles();
- virtual std::string ForcePTExchange();
- virtual std::string GetPolicyTableStatus() const;
- virtual void ResetRetrySequence();
- virtual uint32_t NextRetryTimeout();
- virtual int TimeoutExchange();
- virtual const std::vector<int> RetrySequenceDelaysSeconds();
- virtual void OnExceededTimeout();
- virtual void OnUpdateStarted();
- virtual void PTUpdatedAt(int kilometers, int days_after_epoch);
-
- /**
- * Refresh data about retry sequence from policy table
- */
- virtual void RefreshRetrySequence();
- virtual DeviceConsent GetUserConsentForDevice(const std::string &device_id);
- virtual void
- GetUserConsentForApp(const std::string &device_id,
- const std::string &policy_app_id,
- std::vector<FunctionalGroupPermission> &permissions);
- virtual void SetUserConsentForDevice(const std::string &device_id,
- bool is_allowed);
- virtual bool ReactOnUserDevConsentForApp(const std::string app_id,
- bool is_device_allowed);
- virtual bool GetInitialAppData(const std::string &application_id,
- StringArray *nicknames = NULL,
- StringArray *app_hmi_types = NULL);
-
- virtual void SetDeviceInfo(const std::string &device_id,
- const DeviceInfo &device_info);
-
- virtual void SetUserConsentForApp(const PermissionConsent &permissions);
-
- virtual bool GetDefaultHmi(const std::string &policy_app_id,
- std::string *default_hmi);
-
- virtual bool GetPriority(const std::string &policy_app_id,
- std::string *priority);
-
- virtual std::vector<UserFriendlyMessage>
- GetUserFriendlyMessages(const std::vector<std::string> &message_code,
- const std::string &language);
-
- virtual bool IsApplicationRevoked(const std::string &app_id) const;
-
- virtual void
- GetPermissionsForApp(const std::string &device_id,
- const std::string &policy_app_id,
- std::vector<FunctionalGroupPermission> &permissions);
-
- virtual std::string &GetCurrentDeviceId(const std::string &policy_app_id);
-
- virtual void SetSystemLanguage(const std::string &language);
-
- virtual void SetSystemInfo(const std::string &ccpu_version,
- const std::string &wers_country_code,
- const std::string &language);
- virtual void OnSystemReady();
-
- virtual uint32_t GetNotificationsNumber(const std::string &priority);
-
- virtual void SetVINValue(const std::string &value);
-
- // Interface StatisticsManager (begin)
- virtual void Increment(usage_statistics::GlobalCounterId type);
- virtual void Increment(const std::string &app_id,
- usage_statistics::AppCounterId type);
- virtual void Set(const std::string &app_id, usage_statistics::AppInfoId type,
- const std::string &value);
- virtual void Add(const std::string &app_id,
- usage_statistics::AppStopwatchId type,
- int32_t timespan_seconds);
- // Interface StatisticsManager (end)
-
- AppPermissions GetAppPermissionsChanges(const std::string &policy_app_id);
- void RemovePendingPermissionChanges(const std::string &app_id);
-
- void SendNotificationOnPermissionsUpdated(const std::string &application_id);
-
- bool CleanupUnpairedDevices();
-
- bool CanAppKeepContext(const std::string &app_id);
- bool CanAppStealFocus(const std::string &app_id);
- void MarkUnpairedDevice(const std::string &device_id);
-
- void AddApplication(const std::string &application_id);
-
- virtual void RemoveAppConsentForGroup(const std::string &app_id,
- const std::string &group_name);
-
- virtual uint16_t HeartBeatTimeout(const std::string &app_id) const;
-
- virtual void SaveUpdateStatusRequired(bool is_update_needed);
-
- virtual bool IsPredataPolicy(const std::string &policy_app_id);
- void set_cache_manager(CacheManagerInterface *cache_manager);
-
- virtual void OnAppsSearchStarted();
-
- virtual void OnAppsSearchCompleted();
-
- virtual void OnAppRegisteredOnMobile(const std::string &application_id);
-
- virtual const std::vector<std::string>
- GetAppRequestTypes(const std::string policy_app_id) const;
-
-protected:
-#ifdef USE_HMI_PTU_DECRYPTION
- virtual utils::SharedPtr<policy_table::Table>
- Parse(const BinaryMessage &pt_content);
-#else
- virtual utils::SharedPtr<policy_table::Table>
- ParseArray(const BinaryMessage &pt_content);
-#endif
-
-private:
- void CheckTriggers();
- /*
- * @brief Checks policy table update along with current data for any changes
- * in assigned functional group list of application
- *
- * @param Policy table update struct
- */
- void
- CheckPermissionsChanges(const utils::SharedPtr<policy_table::Table> update,
- const utils::SharedPtr<policy_table::Table> snapshot);
-
- /**
- * @brief Fill structure to be sent with OnPermissionsChanged notification
- *
- * @param Policy table struct, which contains rpc functional groups data
- * @param List of rpc functional group names, which should be checked
- * @param group_permission User permissions for functional groups
- * @param Notification struct to be filled and sent
- */
- void PrepareNotificationData(
- const policy_table::FunctionalGroupings &groups,
- const policy_table::Strings &group_names,
- const std::vector<FunctionalGroupPermission> &group_permission,
- Permissions &notification_data);
-
- /**
- * @brief Validate PermissionConsent structure according to currently
- * assigned groups
- * @param permissions PermissionConsent structure that should be validated.
- * @return PermissonConsent struct, which contains no foreign groups
- */
- PermissionConsent
- EnsureCorrectPermissionConsent(const PermissionConsent &permissions_to_check);
-
- /**
- * @brief Allows to process case when added application is not present in
- * policy db.
- * @param policy application id.
- * @param cuuren consent for application's device.
- */
- void AddNewApplication(const std::string &application_id,
- DeviceConsent device_consent);
-
- /**
- * @brief Allows to process case when added application is already
- * in policy db.
- * @param policy application id.
- * @param cuuren consent for application's device.
- */
- void PromoteExistedApplication(const std::string &application_id,
- DeviceConsent device_consent);
-
- /**
- * @brief Check if certain application already in policy db.
- * @param policy application id.
- * @return true if application presents false otherwise.
- */
- bool IsNewApplication(const std::string &application_id) const;
-
- /**
- * Checks existing and permissions of AppStorageFolder
- * @return true if AppStorageFolder exists and has permissions read/write
- */
- bool CheckAppStorageFolder() const;
-
- /**
- * @brief Checks whether need ask the permission of users
- * @return true if user consent is needed
- */
- virtual bool IsConsentNeeded(const std::string &app_id);
-
- /**
- * @brief Changes isConsentNeeded for app pending permissions, in case
- * user set permissions before app activation.
- * @param Unique app id
- * @param Current permissions for app
- */
- void CheckPendingPermissionsChanges(
- const std::string &policy_app_id,
- const std::vector<FunctionalGroupPermission> &current_permissions);
-
- virtual void StartPTExchange();
- virtual bool ExceededDays();
- virtual bool ExceededIgnitionCycles();
- bool IsPTValid(utils::SharedPtr<policy_table::Table> policy_table,
- policy_table::PolicyTableType type) const;
-
- void RetrySequence();
-
-private:
- PolicyListener *listener_;
-
- UpdateStatusManager update_status_manager_;
- CacheManagerInterfaceSPtr cache_;
- sync_primitives::Lock apps_registration_lock_;
- sync_primitives::Lock app_permissions_diff_lock_;
- std::map<std::string, AppPermissions> app_permissions_diff_;
-
- /**
- * Timeout to wait response with UpdatePT
- */
- uint32_t retry_sequence_timeout_;
-
- /**
- * Seconds between retries to update PT
- */
- std::vector<int> retry_sequence_seconds_;
-
- /**
- * Current index trying of retry sequence
- */
- uint32_t retry_sequence_index_;
-
- /**
- * Lock for guarding retry sequence
- */
- sync_primitives::Lock retry_sequence_lock_;
-
- /**
- * Timer to retry UpdatePT
- */
- timer::TimerThread<PolicyManagerImpl> timer_retry_sequence_;
-
- /**
- * Lock for guarding recording statistics
- */
- sync_primitives::Lock statistics_lock_;
-
- /**
- * @brief Device id, which is used during PTU handling for specific
- * application
- */
- std::string last_device_id_;
-
- bool ignition_check;
-
- friend struct CheckAppPolicy;
-};
-
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_MANAGER_IMPL_H_
diff --git a/src/components/policy/src/policy/include/policy/policy_types.h b/src/components/policy/src/policy/include/policy/policy_types.h
deleted file mode 100644
index ded7a530fc..0000000000
--- a/src/components/policy/src/policy/include/policy/policy_types.h
+++ /dev/null
@@ -1,311 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_TYPES_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_TYPES_H_
-
-#include <string>
-#include <vector>
-#include <map>
-#include <set>
-#include "utils/shared_ptr.h"
-#include "utils/helpers.h"
-namespace policy {
-
-// TODO(PV): specify errors
-enum PolicyErrorEnum {
-};
-
-const std::string kDefaultDeviceMacAddress = "00:00:00:00:00:00";
-const std::string kDefaultDeviceName = "MyDevice";
-const std::string kDefaultDeviceConnectionType = "UNKNOWN";
-
-/**
- * @brief Constants for special ids in application policies section of
- * policy table
- */
-const std::string kPreDataConsentId = "pre_DataConsent";
-const std::string kDefaultId = "default";
-const std::string kDeviceId = "device";
-
-/*
- * @brief Status of policy table update
- */
-enum PolicyTableStatus {
- StatusUpToDate = 0,
- StatusUpdatePending,
- StatusUpdateRequired,
- StatusUnknown
-};
-
-// Code generator uses String class name, so this typedef was renamed to PTSring
-typedef std::string PTString;
-typedef std::vector<uint8_t> BinaryMessage;
-typedef utils::SharedPtr<BinaryMessage> BinaryMessageSptr;
-
-typedef std::string HMILevel;
-typedef std::string Parameter;
-typedef std::string RpcName;
-typedef std::vector<std::string> RPCParams;
-
-typedef std::map<std::string, std::set<policy::HMILevel> > HMIPermissions;
-typedef std::map<std::string, std::set<policy::Parameter> > ParameterPermissions;
-
-struct RpcPermissions {
- HMIPermissions hmi_permissions;
- ParameterPermissions parameter_permissions;
-};
-
-typedef std::map<RpcName, RpcPermissions> Permissions;
-
-/**
- * @brief Typedef for use with AllowApp request/notification
- */
-typedef std::vector<std::string> PermissionsList;
-
-/**
- * @brief Typedef for getting initial application data, e.g. nickname list
- */
-typedef std::vector<std::string> StringArray;
-
-enum PermitResult {
- kRpcAllowed = 0,
- kRpcDisallowed,
- kRpcUserDisallowed
-};
-
-/**
- * @struct Stores result of check:
- * if HMI Level was allowed for RPC to work in
- * and list of parameters allowed for RPC if specified in PT.
- */
-struct CheckPermissionResult {
- CheckPermissionResult()
- : hmi_level_permitted(kRpcDisallowed) {
- }
-
- PermitResult hmi_level_permitted;
- std::vector<PTString> list_of_allowed_params;
- std::vector<PTString> list_of_disallowed_params;
- std::vector<PTString> list_of_undefined_params;
-};
-
-/**
- @struct Holds Url string and optional policy app id.
- */
-struct EndpointData {
- explicit EndpointData(const std::string& url_string = "")
- : app_id("default") {
- if (false == url_string.empty()) {
- url.push_back(url_string);
- }
- }
- std::vector<std::string> url;
- std::string app_id;
-};
-
-typedef std::vector<EndpointData> EndpointUrls;
-
-/**
- * @brief Struct contains device data to be used for dialogs, generation of IDs
- */
-struct DeviceParams {
- DeviceParams()
- : device_name(kDefaultDeviceName),
- device_mac_address(kDefaultDeviceMacAddress),
- device_connection_type(kDefaultDeviceConnectionType),
- device_handle(0) {
- }
-
- std::string device_name;
- std::string device_mac_address;
- std::string device_connection_type;
- uint32_t device_handle;
-};
-
-/**
- * @brief User consent for device data usage
- */
-enum DeviceConsent {
- kDeviceAllowed = 0,
- kDeviceDisallowed,
- kDeviceHasNoConsent
-};
-
-/**
- * @brief Struct contains parameters, which can be received during application
- * registration and should be stored in policy table
- */
-struct DeviceInfo {
- DeviceInfo()
- : max_number_rfcom_ports(0) {
- }
-
- std::string hardware;
- std::string firmware_rev;
- std::string os;
- std::string os_ver;
- std::string carrier;
- uint32_t max_number_rfcom_ports;
- std::string connection_type;
-
- void AdoptDeviceType(const std::string& deviceType) {
- connection_type = "USB_serial_number";
- using namespace helpers;
- if (Compare<std::string, EQ, ONE> (deviceType,
- "BLUETOOTH",
- "WIFI")) {
- connection_type.assign("BTMAC");
- }
- }
-};
-
-/**
- * @brief User consent for functional group
- */
-enum GroupConsent {
- kGroupAllowed = 0,
- kGroupDisallowed,
- kGroupUndefined
-};
-
-/**
- * @brief Contains user permission for RPC functional group with specific name
- * and id from DB
- */
-struct FunctionalGroupPermission {
- FunctionalGroupPermission()
- : group_id(0),
- state(kGroupUndefined) {
- }
-
- bool operator ==(const FunctionalGroupPermission& rhs) {
- if (this->group_id == rhs.group_id &&
- this->group_alias == rhs.group_alias &&
- this->group_name == rhs.group_name) {
- return true;
- }
- return false;
- }
-
- std::string group_alias;
- std::string group_name;
- int32_t group_id;
- GroupConsent state;
-};
-
-/**
- * @brief Stores data to be sent to HMI on application permissions change
- */
-struct AppPermissions {
-
- AppPermissions(const std::string& app_id)
- : application_id(app_id),
- isAppPermissionsRevoked(false),
- appRevoked(false),
- appPermissionsConsentNeeded(false),
- appUnauthorized(false),
- isSDLAllowed(false),
- requestTypeChanged(false) {
- }
-
- std::string application_id;
- bool isAppPermissionsRevoked;
- std::vector<policy::FunctionalGroupPermission> appRevokedPermissions;
- bool appRevoked;
- bool appPermissionsConsentNeeded;
- bool appUnauthorized;
- bool isSDLAllowed;
- std::string priority;
- DeviceParams deviceInfo;
- bool requestTypeChanged;
- std::vector<std::string> requestType;
-};
-
-/**
- * @brief Contains parameters for user-defined consent for appication
- * functional groups on given device
- */
-struct PermissionConsent {
- std::string device_id;
- std::string policy_app_id;
- std::vector<FunctionalGroupPermission> group_permissions;
- std::string consent_source;
-};
-
-/**
- * @brief Contain data for GetUserFriendyMessage response
- */
-struct UserFriendlyMessage {
- std::string message_code;
-};
-
-/**
- * @brief Types of functional groups in policy table
- */
-enum GroupType {
- kTypeDefault = 0, // groups assigned to 'default' permissions section
- kTypeAllowed, // groups allowed by user for specific application
- kTypeDisallowed, // groups disallowed by user for specific application
- kTypeUnconsented, // groups disallowed by default but consent may be changed by user
- kTypePreconsented, // groups allowed for specific application without
- // user consent by default (could be changed by user)
- kTypeGeneral, // groups assigned to specific application
- kTypePreDataConsented, // groups assigned to 'pre_DataConsent' permissions
- // section
- kTypeDevice // groups assigned to 'device' permissions section
-};
-
-/**
- * @brief Array of functional group id from DB
- */
-typedef std::vector<int32_t> FunctionalGroupIDs;
-
-/**
- * @brief Array of functional group ids sorted by types
- */
-typedef std::map<GroupType, FunctionalGroupIDs> FunctionalIdType;
-
-/**
- * @brief Array of functional group ids binded to user_consent_prompt (e.g.
- * VehicleData) and group name (e.g. VehicleData-4)
- */
-typedef std::map<uint32_t, std::pair<std::string, std::string> > FunctionalGroupNames;
-
-/**
- * @brief Array of device ids, which are an identifiers in policy table
- */
-typedef std::vector<std::string> DeviceIds;
-
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_POLICY_TYPES_H_
diff --git a/src/components/policy/src/policy/include/policy/pt_ext_representation.h b/src/components/policy/src/policy/include/policy/pt_ext_representation.h
deleted file mode 100644
index 55ed86e445..0000000000
--- a/src/components/policy/src/policy/include/policy/pt_ext_representation.h
+++ /dev/null
@@ -1,336 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_PT_EXT_REPRESENTATION_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_PT_EXT_REPRESENTATION_H_
-
-#include "policy/pt_representation.h"
-
-namespace policy {
-
-enum StatisticsType {
- S_NONE = 0,
- S_IAP_BUFFER_FULL,
- S_SYNC_OUT_OF_MEMORY,
- S_SYNC_REBOOTS,
- S_MINS_HMI_FULL,
- S_MINS_HMI_LIMITED,
- S_MINS_HMI_BACKGROUND,
- S_MINS_HMI_NONE,
- S_RFCOM_LIMIT_REACHED,
- S_USER_SELECTIONS,
- S_REJECTIONS_SYNC_OUT_OF_MEMORY,
- S_REJECTIONS_NICKNAME_MISMATCH,
- S_REJECTIONS_DUPLICATE_NAME,
- S_REJECTED_RPC_CALLS,
- S_RPCS_IN_HMI_NONE,
- S_REMOVALS_MISBEHAVED,
- S_RUN_ATTEMPTS_WHILE_REVOKED
-};
-
-enum LanguageType {
- L_NONE = 0,
- L_GUI,
- L_VUI
-};
-
-class PTExtRepresentation : public virtual PTRepresentation {
- public:
- virtual ~PTExtRepresentation() {
- }
-
- /**
- * @brief Is application allowed to send notifications while in
- * Backgound or limited mode.
- * @param app_id Application id
- * @return bool Allowed/disallowed.
- */
- virtual bool CanAppKeepContext(const std::string& app_id) = 0;
-
- /**
- * @brief Is application allowed to move foreground at will?
- * @param app_id Application id
- * @return bool Allowed/disallowed.
- */
- virtual bool CanAppStealFocus(const std::string& app_id) = 0;
-
- /**
- * @brief Get default_hmi for given application
- * @param policy_app_id Unique application id
- * @param default_hmi Default HMI level for application or empty, if value was
- * not set
- * @return true, if succedeed, otherwise - false
- */
- virtual bool GetDefaultHMI(const std::string& policy_app_id,
- std::string* default_hmi) = 0;
-
- /**
- * @brief Reset user consent for device data and applications permissions
- * @return
- */
- virtual bool ResetUserConsent() = 0;
-
- /**
- * @brief Reset user consent for device data
- * @return
- */
- virtual bool ResetDeviceConsents() = 0;
-
- /**
- * @brief Reset user consent for applications permissions
- * @return
- */
- virtual bool ResetAppConsents() = 0;
-
- /**
- * @brief Get user permissions for device data usage
- * @param device_id Generated or obtained id of device
- * @param consented_groups Groups consented by user
- * @param disallowed_groups Groups not consented by user
- * @return true, if query was successfull, otherwise - false
- */
- virtual bool GetUserPermissionsForDevice(
- const std::string& device_id, StringArray* consented_groups = NULL,
- StringArray* disallowed_groups = NULL) = 0;
-
- /**
- * @brief Gets list of groups permissions from policy table
- * @param device_id Unique device id, which hosts specific application
- * @param policy_app_id Unique application id
- * @param group_types Group list sorted by permission status
- * @return true, if query was successfull, otherwise - false
- */
- virtual bool GetPermissionsForApp(
- const std::string& device_id,
- const std::string& policy_app_id,
- FunctionalIdType* group_types) = 0;
-
- /**
- * @brief Get device groups and preconsented groups from policies section
- * @param groups List of groups to be consented for device usage
- * @param preconsented_groups List of preconsented groups for device usage
- * @return true, if query was successful, otherwise - false
- */
- virtual bool GetDeviceGroupsFromPolicies(
- policy_table::Strings* groups = NULL,
- policy_table::Strings* preconsented_groups = NULL) = 0;
-
- /**
- * @brief Record information about mobile device in Policy Table.
- * @param device_id Generated or obtained id of device
- * @return bool Success of operation
- */
- virtual bool SetDeviceData(const std::string& device_id,
- const std::string& hardware = "",
- const std::string& firmware = "",
- const std::string& os = "",
- const std::string& os_version = "",
- const std::string& carrier = "",
- const uint32_t number_of_ports = 0,
- const std::string& connection_type = "") = 0;
-
- /**
- * @brief Sets user consent for particular mobile device,
- * i.e. to use device for exchanging of Policy Table.
- * @return bool Success of operation
- */
- virtual bool SetUserPermissionsForDevice(
- const std::string& device_id, const StringArray& consented_groups =
- StringArray(),
- const StringArray& disallowed_gropus = StringArray()) = 0;
-
- /**
- * @brief Update Application Policies as reaction
- * on User allowing/disallowing device this app is running on.
- */
- virtual bool ReactOnUserDevConsentForApp(
- const std::string& app_id,
- bool is_device_allowed) = 0;
-
- /**
- * @brief Set user consent on functional groups
- * @param permissions User consent on functional group
- * @return true, if operation succedeed, otherwise - false
- */
- virtual bool SetUserPermissionsForApp(
- const PermissionConsent& permissions) = 0;
-
- /**
- * @brief Counter for statistics information: adds 1 to existing number.
- * @param type Type of statistics (errors, mins in mode etc)
- * @return bool Success of operation
- */
- virtual bool IncreaseStatisticsData(StatisticsType type) = 0;
-
- /**
- * @brief Records information about what language
- * application tried to register with.
- * @param app_id Id of application
- * @param type - language for UI/VR
- * @param language Language
- * @return bool Success of operation
- */
- virtual bool SetAppRegistrationLanguage(const std::string& app_id,
- LanguageType type,
- const std::string& language) = 0;
-
- /**
- * @brief Records information about head unit system to PT
- * @return bool Success of operation
- */
- virtual bool SetMetaInfo(const std::string& ccpu_version,
- const std::string& wers_country_code,
- const std::string& language) = 0;
-
- /**
- * @brief Checks, if specific head unit is present in PT
- * @return boot Suceess, if present, otherwise - false
- */
- virtual bool IsMetaInfoPresent() = 0;
-
- /**
- * @brief Kms pass since last successfull PT update
- */
- virtual int GetKmFromSuccessfulExchange() = 0;
-
- /**
- * @brief Days pass since last successfull PT update
- */
- virtual int GetDayFromScsExchange() = 0;
-
- /**
- * @brief Ignition cycles pass since last successfull PT update
- */
- virtual int GetIgnitionsFromScsExchange() = 0;
-
- /**
- * @brief Set current system language
- * @param language System language
- * @return true, if succedeed, otherwise - false
- */
- virtual bool SetSystemLanguage(const std::string& language) = 0;
-
- /**
- * Increments global counter
- * @param type type of counter
- */
- virtual void Increment(const std::string& type) const = 0;
-
- /**
- * Increments counter of application
- * @param app_id id application
- * @param type type of counter
- */
- virtual void Increment(const std::string& app_id,
- const std::string& type) const = 0;
-
- /**
- * Sets value of application information
- * @param app_id id application
- * @param type type of information
- * @param value value of information
- */
- virtual void Set(const std::string& app_id, const std::string& type,
- const std::string& value) const = 0;
-
- /**
- * Adds value to stopwatch of application
- * @param app_id id application
- * @param type type of stopwatch
- * @param seconds value for adding in seconds
- */
- virtual void Add(const std::string& app_id, const std::string& type,
- int seconds) const = 0;
-
- virtual bool CountUnconsentedGroups(const std::string& policy_app_id,
- const std::string& device_id,
- int* result) const = 0;
-
- /**
- * @brief Gets functional group names and user_consent_prompts, if any
- * @param Array to be filled with group ids, names and functional prompts
- * @return true, if succeeded, otherwise - false
- */
- // TODO(AOleynik): Possibly, we can get rid of this method. Check this.
- virtual bool GetFunctionalGroupNames(policy::FunctionalGroupNames& names) = 0;
-
- /**
- * @brief Set app policy to pre_DataConsented policy
- * @param app_id Policy ID of application to be changed
- * @return true, if succeeded, otherwise - false
- */
- virtual bool SetPredataPolicy(const std::string& app_id) = 0;
-
- /**
- * @brief Updates application policy to either pre_DataConsented or not
- * @param app_id Policy Id of application to be checked
- * @param is_pre_data True of False to setting app policy to be pre_DataConsented
- * @return true, if succeeded, otherwise - false
- */
- virtual bool SetIsPredata(const std::string& app_id, bool is_pre_data) = 0;
-
- /**
- * @brief Removes unpaired devices
- * @return true if success
- */
- virtual bool CleanupUnpairedDevices(const DeviceIds& device_ids) const = 0;
-
- /**
- * Sets flag of unpaired device
- * @param device_id Unique device id
- * @param unpaired True, if unpaired, otherwise - false
- * @return true if success
- */
- virtual bool SetUnpairedDevice(const std::string& device_id,
- bool unpaired) const = 0;
-
- /**
- * Gets list of unpaired devices
- * @param device_ids output list
- * @return true if success
- */
- virtual bool UnpairedDevicesList(DeviceIds* device_ids) const = 0;
-
- /**
- * @brief Remove application consent for particular group
- * @param policy_app_id Unique application id
- * @param functional_group_name Functional group name, which consents should
- * be removed
- * @return true, in case of success, otherwise - false
- */
- virtual bool RemoveAppConsentForGroup(
- const std::string& policy_app_id,
- const std::string& functional_group_name) const = 0;
-};
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_PT_EXT_REPRESENTATION_H_
diff --git a/src/components/policy/src/policy/include/policy/pt_representation.h b/src/components/policy/src/policy/include/policy/pt_representation.h
deleted file mode 100644
index 3c02985446..0000000000
--- a/src/components/policy/src/policy/include/policy/pt_representation.h
+++ /dev/null
@@ -1,310 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_PT_REPRESENTATION_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_PT_REPRESENTATION_H_
-
-#include <vector>
-#include <string>
-#include "policy/policy_types.h"
-#include "./types.h"
-
-namespace policy_table = rpc::policy_table_interface_base;
-
-namespace policy {
-
-/**
- * @struct Data about vehicle
- */
-struct VehicleData {
- const std::string vehicle_make;
- const std::string vehicle_model;
- int vehicle_year;
-};
-
-enum InitResult {
- NONE = 0,
- EXISTS,
- SUCCESS,
- FAIL
-};
-
-class PTRepresentation {
- public:
- virtual ~PTRepresentation() {
- }
-
- /**
- * @brief Check if specified RPC for specified application
- * has permission to be executed in specified HMI Level
- * and also its permitted params.
- * @param app_id Id of application provided during registration
- * @param hmi_level Current HMI Level of application
- * @param rpc Name of RPC
- * @params CheckPermissionResult containing flag if HMI Level is allowed
- * and list of allowed params.
- */
- virtual void CheckPermissions(const PTString& app_id,
- const PTString& hmi_level,
- const PTString& rpc,
- CheckPermissionResult& result) = 0;
-
- /**
- * @brief Returns true if Policy Table was not updated yet
- * from preloaded pt file.
- */
- virtual bool IsPTPreloaded() = 0;
-
- virtual bool RefreshDB() = 0;
- /**
- * Gets number of ignition cycles before next update policy table
- * @return number of ignition cycles
- */
- virtual int IgnitionCyclesBeforeExchange() = 0;
-
- /**
- * Gets value in kilometers before next update policy table
- * @param current value in kilometers from the odometers
- * @return value in kilometers
- */
- virtual int KilometersBeforeExchange(int current) = 0;
-
- /**
- * @brief Sets kilometers and days after epoch, that passed for recieved
- * successful PT UPdate
- */
- virtual bool SetCountersPassedForSuccessfulUpdate(int kilometers,
- int days_after_epoch) = 0;
-
- /**
- * Gets value in days before next update policy table
- * @param current value in days after epoch
- * @return value in days
- */
- virtual int DaysBeforeExchange(int current) = 0;
-
- /**
- * @brief Increment number of ignition cycles since last exchange by 1
- */
- virtual void IncrementIgnitionCycles() = 0;
-
- /**
- * @brief Reset number of ignition cycles since last exchange to 0
- */
- virtual void ResetIgnitionCycles() = 0;
-
- /**
- * @brief Returns timeout to wait for a response of PT update
- * @return value in seconds
- */
- virtual int TimeoutResponse() = 0;
-
- /**
- * @brief Returns number of seconds between each try of sending PTS
- * @param seconds Return value: array of 5 elements
- * @return bool Success of operation
- */
- virtual bool SecondsBetweenRetries(std::vector<int>* seconds) = 0;
-
- /**
- * @brief Get information about vehicle
- */
- virtual VehicleData GetVehicleData() = 0;
-
- /**
- * @brief Allows to update 'vin' field in module_meta table.
- *
- * @param new 'vin' value.
- *
- * @return true in case when data has been successfully updated,
- * false otherwise.
- */
- virtual bool SetVINValue(const std::string& value) = 0;
-
- /**
- * @brief Get message text for displaying/pronouncing for user
- * dependent on language and context.
- * @param msg_codes Context of message (Driver distraction, Grant permission etc)
- * @param language Language of the message
- * @return Array of appropriate messages parameters
- */
- virtual std::vector<UserFriendlyMessage> GetUserFriendlyMsg(
- const std::vector<std::string>& msg_codes, const std::string& language) = 0;
-
- /**
- * @brief Get list of URL to send PTS to
- * @param service_type If URLs for specific service are preset,
- * return them otherwise default URLs.
- */
- virtual EndpointUrls GetUpdateUrls(int service_type) = 0;
-
- /**
- * @brief GetLockScreenIcon allows to obtain lock screen icon url;
- *
- * @return url which point to the resourse where lock screen icon could be obtained.
- */
- virtual std::string GetLockScreenIconUrl() const = 0;
-
- /**
- * @brief Get allowed number of notifications
- * depending on application priority.
- * @param priority Priority of application
- */
- virtual int GetNotificationsNumber(const std::string& priority) = 0;
-
- /**
- * @brief Get priority for given application
- * @param policy_app_id Unique application id
- * @param priority Priority for application or empty, if value was not set
- * @return true, if succedeed, otherwise - false
- */
- virtual bool GetPriority(const std::string& policy_app_id,
- std::string* priority) = 0;
-
-
- /**
- * @brief Initialized Policy Table (load)
- * @return bool Success of operation
- */
- virtual InitResult Init() = 0;
-
- /**
- * @brief Close policy table
- * @return bool Success of operation
- */
- virtual bool Close() = 0;
-
- /**
- * @brief Removes policy table content.
- * @return bool Success of operation
- */
- virtual bool Clear() = 0;
-
- /**
- * Drops policy table (schema and content)
- * @return true if successfully
- */
- virtual bool Drop() = 0;
-
- /**
- * @brief Get snapshot of Policy Table
- * including app_policies, functional_groups,
- * device_info, statistics, excluding user messages
- * @return Generated structure for obtaining Json string.
- */
- virtual utils::SharedPtr<policy_table::Table> GenerateSnapshot() const = 0;
-
-
- virtual bool Save(const policy_table::Table& table) = 0;
-
- /**
- * Gets flag updateRequired
- * @return true if update is required
- */
- virtual bool UpdateRequired() const = 0;
-
- /**
- * Saves flag updateRequired
- */
- virtual void SaveUpdateRequired(bool value) = 0;
-
- /*
- Retrieves data from app_policies about app on its registration:
- app_id - id of registered app; all outputs are filled in only if not null
- output: nicknames Synonyms for application
- output: app_types Section on HMI where app can appear (Navigation, Phone etc)
- */
- virtual bool GetInitialAppData(const std::string& app_id,
- StringArray* nicknames = NULL,
- StringArray* app_types = NULL) = 0;
-
- /**
- * Checks if the application is revoked
- * @param app_id application id
- * @return true if application is revoked
- */
- virtual bool IsApplicationRevoked(const std::string& app_id) const = 0;
-
- /**
- * @brief Get functional groupings from DB
- * @param groups Known functional groupings
- * @return true, if succeeded, otherwise - false
- */
- virtual bool GetFunctionalGroupings(policy_table::FunctionalGroupings& groups) = 0;
-
- /**
- * Checks if the application is represented in policy table
- * @param app_id application id
- * @return true if application is represented in policy table
- */
- virtual bool IsApplicationRepresented(const std::string& app_id) const = 0;
-
- /**
- * Checks if the application has default policy
- * @param app_id application id
- * @return true if application has default policy
- */
- virtual bool IsDefaultPolicy(const std::string& app_id) const = 0;
-
- /**
- * Checks if the application has pre_data policy
- * @param app_id application id
- * @return true if application has pre_data policy
- */
- virtual bool IsPredataPolicy(const std::string& app_id) const = 0;
-
- /**
- * Sets default policy for application
- * @param app_id application id
- * @return true if success
- */
- virtual bool SetDefaultPolicy(const std::string& app_id) = 0;
-
- /**
- * @brief SaveApplicationCustomData allows to save specific data to database.
- * This data is only for internal use.
- * @param app_id the application id for which the data will be saved.
- * @param is_revoked parameter to save.
- * @param is_default parameter to save.
- * @param is_predata parameter to save.
- */
- virtual bool SaveApplicationCustomData(const std::string& app_id,
- bool is_revoked,
- bool is_default,
- bool is_predata) = 0;
-
- virtual void WriteDb() = 0;
-};
-
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_PT_REPRESENTATION_H_
diff --git a/src/components/policy/src/policy/include/policy/sql_pt_ext_representation.h b/src/components/policy/src/policy/include/policy/sql_pt_ext_representation.h
deleted file mode 100644
index 1a8663fdee..0000000000
--- a/src/components/policy/src/policy/include/policy/sql_pt_ext_representation.h
+++ /dev/null
@@ -1,201 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_EXT_REPRESENTATION_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_EXT_REPRESENTATION_H_
-
-#include <string>
-#include "policy/sql_pt_representation.h"
-#include "policy/pt_ext_representation.h"
-
-namespace policy {
-
-class SQLPTExtRepresentation : public SQLPTRepresentation,
- public PTExtRepresentation {
- public:
- bool CanAppKeepContext(const std::string& app_id);
- bool CanAppStealFocus(const std::string& app_id);
- bool GetDefaultHMI(const std::string& policy_app_id,
- std::string* default_hmi);
- bool ResetUserConsent();
- bool ResetDeviceConsents();
- bool ResetAppConsents();
- bool GetUserPermissionsForDevice(const std::string& device_id,
- StringArray* consented_groups = NULL,
- StringArray* disallowed_groups = NULL);
-
- bool GetPermissionsForApp(
- const std::string& device_id, const std::string& policy_app_id,
- FunctionalIdType* group_types);
-
- bool GetDeviceGroupsFromPolicies(policy_table::Strings* groups = NULL,
- policy_table::Strings* preconsented_groups =
- NULL);
- bool SetDeviceData(const std::string& device_id,
- const std::string& hardware = "",
- const std::string& firmware = "",
- const std::string& os = "",
- const std::string& os_version = "",
- const std::string& carrier = "",
- const uint32_t number_of_ports = 0,
- const std::string& connection_type = "");
- bool SetUserPermissionsForDevice(const std::string& device_id,
- const StringArray& consented_groups =
- StringArray(),
- const StringArray& disallowed_groups =
- StringArray());
-
- bool ReactOnUserDevConsentForApp(const std::string& app_id,
- bool is_device_allowed);
-
- bool SetUserPermissionsForApp(const PermissionConsent& permissions);
-
- std::vector<UserFriendlyMessage> GetUserFriendlyMsg(
- const std::vector<std::string>& msg_codes, const std::string& language);
-
- bool IncreaseStatisticsData(StatisticsType type) {
- return true;
- }
- bool SetAppRegistrationLanguage(const std::string& app_id, LanguageType type,
- const std::string& language) {
- return true;
- }
-
- bool SetMetaInfo(const std::string& ccpu_version,
- const std::string& wers_country_code,
- const std::string& language);
-
- bool IsMetaInfoPresent();
-
- bool SetSystemLanguage(const std::string& language);
-
- int GetKmFromSuccessfulExchange() {
- return true;
- }
- int GetDayFromScsExchange() {
- return true;
- }
- int GetIgnitionsFromScsExchange() {
- return true;
- }
-
- bool GetFunctionalGroupNames(FunctionalGroupNames& names);
- bool CleanupUnpairedDevices(const DeviceIds& device_ids) const;
-
- void Increment(const std::string& type) const;
- void Increment(const std::string& app_id, const std::string& type) const;
- void Set(const std::string& app_id, const std::string& type,
- const std::string& value) const;
- void Add(const std::string& app_id, const std::string& type,
- int seconds) const;
- bool SetDefaultPolicy(const std::string& app_id);
- bool SetPredataPolicy(const std::string& app_id);
- bool SetIsPredata(const std::string& app_id, bool is_pre_data);
- bool IsPredataPolicy(const std::string& app_id) const;
- bool SetUnpairedDevice(const std::string& device_id, bool unpaired) const;
- bool UnpairedDevicesList(DeviceIds* device_ids) const;
- bool RemoveAppConsentForGroup(
- const std::string& policy_app_id,
- const std::string& functional_group_name) const;
-
- virtual bool SetVINValue(const std::string& value);
-
- private:
- void GatherModuleMeta(policy_table::ModuleMeta* meta) const;
- void GatherPreconsentedGroup(const std::string& app_id,
- policy_table::Strings* groups) const;
- bool GatherUsageAndErrorCounts(
- policy_table::UsageAndErrorCounts* counts) const;
- bool GatherAppLevels(policy_table::AppLevels* apps) const;
- void GatherDeviceData(policy_table::DeviceData* data) const;
- void GatherConsentGroup(const std::string& device_id,
- policy_table::UserConsentRecords* records) const;
- bool GatherApplicationPoliciesSection(
- policy_table::ApplicationPoliciesSection* policies) const;
- bool SaveDeviceData(const policy_table::DeviceData& devices);
- bool GatherConsumerFriendlyMessages(
- policy_table::ConsumerFriendlyMessages* messages) const;
- bool SaveConsentGroup(const std::string& device_id,
- const policy_table::UserConsentRecords& records);
- bool SaveApplicationPoliciesSection(const policy_table::ApplicationPoliciesSection& policies);
- bool SaveSpecificAppPolicy(
- const policy_table::ApplicationPolicies::value_type& app);
- bool SaveDevicePolicy(const policy_table::DevicePolicy& device);
- bool SavePreconsentedGroup(const std::string& app_id,
- const policy_table::Strings& groups);
- bool SaveMessageString(const std::string& type, const std::string& lang,
- const policy_table::MessageString& strings);
-
- virtual bool SaveUsageAndErrorCounts(
- const policy_table::UsageAndErrorCounts& counts);
-
- virtual bool SaveModuleMeta(const policy_table::ModuleMeta& meta);
-
- bool SaveAppCounters(const policy_table::AppLevels& app_levels);
-
- bool SaveGlobalCounters(const policy_table::UsageAndErrorCounts& counts);
-
- bool IsExistAppLevel(const std::string& app_id) const;
-
- bool GetAllAppGroups(const std::string& policy_app_id,
- FunctionalGroupIDs& all_groups);
-
- bool GetConsentedGroups(const std::string& policy_app_id,
- const std::string& device_id,
- FunctionalGroupIDs& allowed_groups,
- FunctionalGroupIDs& disallowed_groups);
-
- bool GetPreconsentedGroups(const std::string& policy_app_id,
- FunctionalGroupIDs& preconsented_groups);
-
- void FillFunctionalGroupPermissions(
- FunctionalGroupIDs& ids, FunctionalGroupNames& names,
- GroupConsent state,
- std::vector<FunctionalGroupPermission>& permissions);
- bool CountUnconsentedGroups(const std::string& policy_app_id,
- const std::string& device_id,
- int* result) const;
-
- /**
- * @brief Checks, if there is message present with requested language in PT
- * @param message Message name
- * @param language Required message language
- * @return True, if message with requested language is present, otherwise -
- * false
- */
- bool IsMsgLanguagePresent(const std::string& message,
- const std::string& language);
-};
-
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_EXT_REPRESENTATION_H_
diff --git a/src/components/policy/src/policy/include/policy/sql_pt_queries.h b/src/components/policy/src/policy/include/policy/sql_pt_queries.h
deleted file mode 100644
index 14c10d6319..0000000000
--- a/src/components/policy/src/policy/include/policy/sql_pt_queries.h
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- Copyright (c) 2013, " Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, " with or without
- modification, " are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, " this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice, "
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, " INCLUDING, " BUT NOT LIMITED TO, " THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, " INDIRECT, " INCIDENTAL, " SPECIAL, " EXEMPLARY, " OR
- CONSEQUENTIAL DAMAGES (INCLUDING, " BUT NOT LIMITED TO, " PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, " DATA, " OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, " WHETHER IN
- CONTRACT, " STRICT LIABILITY, " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, " EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_QUERIES_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_QUERIES_H_
-
-#include <string>
-
-namespace policy {
-namespace sql_pt {
-
-extern const std::string kSelectPriority;
-extern const std::string kCreateSchema;
-extern const std::string kDropSchema;
-extern const std::string kDeleteData;
-extern const std::string kCheckPgNumber;
-extern const std::string kCheckDBIntegrity;
-extern const std::string kSelectRpc;
-extern const std::string kSelectPreloaded;
-extern const std::string kIsFirstRun;
-extern const std::string kSetNotFirstRun;
-extern const std::string kSelectEndpoint;
-extern const std::string kSelectLockScreenIcon;
-extern const std::string kSelectModuleConfig;
-extern const std::string kSelectEndpoints;
-extern const std::string kSelectNotificationsPerMin;
-extern const std::string kSelectNotificationsPerPriority;
-extern const std::string kSelectAppLevels;
-extern const std::string kSelectDeviceData;
-extern const std::string kSelectFunctionalGroups;
-extern const std::string kSelectAllRpcs;
-extern const std::string kSelectUserMsgsVersion;
-extern const std::string kSelectAppPolicies;
-extern const std::string kSelectAppGroups;
-extern const std::string kSelectNicknames;
-extern const std::string kSelectAppTypes;
-extern const std::string kSelectRequestTypes;
-extern const std::string kSelectSecondsBetweenRetries;
-extern const std::string kSelectIgnitionCycles;
-extern const std::string kSelectKilometers;
-extern const std::string kSelectDays;
-extern const std::string kSelectTimeoutResponse;
-extern const std::string kInsertFunctionalGroup;
-extern const std::string kInsertRpc;
-extern const std::string kInsertRpcWithParameter;
-extern const std::string kInsertApplication;
-extern const std::string kInsertAppGroup;
-extern const std::string kInsertNickname;
-extern const std::string kInsertAppType;
-extern const std::string kInsertRequestType;
-extern const std::string kInsertMessageType;
-extern const std::string kInsertLanguage;
-extern const std::string kInsertMessageString;
-extern const std::string kUpdateVersion;
-extern const std::string kUpdateModuleConfig;
-extern const std::string kInsertEndpoint;
-extern const std::string kInsertSecondsBetweenRetry;
-extern const std::string kInsertNotificationsByPriority;
-extern const std::string kInsertDeviceData;
-extern const std::string kInsertAppLevel;
-extern const std::string kDeleteSecondsBetweenRetries;
-extern const std::string kDeleteEndpoint;
-extern const std::string kDeleteAppLevel;
-extern const std::string kDeleteMessageString;
-extern const std::string kDeleteFunctionalGroup;
-extern const std::string kDeleteRpc;
-extern const std::string kDeleteAppGroup;
-extern const std::string kDeleteApplication;
-extern const std::string kDeleteRequestType;
-extern const std::string kDeleteDevice;
-extern const std::string kIncrementIgnitionCycles;
-extern const std::string kResetIgnitionCycles;
-extern const std::string kUpdateFlagUpdateRequired;
-extern const std::string kSelectFlagUpdateRequired;
-extern const std::string kUpdateCountersSuccessfulUpdate;
-extern const std::string kSelectApplicationRevoked;
-extern const std::string kUpdateApplicationCustomData;
-extern const std::string kSelectApplicationRepresented;
-extern const std::string kSelectApplicationIsDefault;
-extern const std::string kUpdateIsDefault;
-extern const std::string kInsertInitData;
-extern const std::string kDeleteAppGroupByApplicationId;
-extern const std::string kInsertApplicationFull;
-extern const std::string kDeletePreconsentedGroupsByApplicationId;
-extern const std::string kSelectApplicationFull;
-extern const std::string kUpdatePreloaded;
-
-} // namespace sql_pt
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_QUERIES_H_
diff --git a/src/components/policy/src/policy/include/policy/sql_pt_representation.h b/src/components/policy/src/policy/include/policy/sql_pt_representation.h
deleted file mode 100644
index 2a498a6fb0..0000000000
--- a/src/components/policy/src/policy/include/policy/sql_pt_representation.h
+++ /dev/null
@@ -1,181 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_REPRESENTATION_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_REPRESENTATION_H_
-
-#include <string>
-#include <vector>
-#include "policy/pt_representation.h"
-#include "rpc_base/rpc_base.h"
-#include "./types.h"
-
-namespace policy_table = rpc::policy_table_interface_base;
-
-namespace policy {
-
-namespace dbms {
-class SQLDatabase;
-} // namespace dbms
-
-class SQLPTRepresentation : public virtual PTRepresentation {
- public:
- SQLPTRepresentation();
- ~SQLPTRepresentation();
- virtual void CheckPermissions(const PTString& app_id,
- const PTString& hmi_level,
- const PTString& rpc,
- CheckPermissionResult& result);
-
- virtual bool IsPTPreloaded();
- virtual int IgnitionCyclesBeforeExchange();
- virtual int KilometersBeforeExchange(int current);
- virtual bool SetCountersPassedForSuccessfulUpdate(int kilometers,
- int days_after_epoch);
- virtual int DaysBeforeExchange(int current);
- virtual void IncrementIgnitionCycles();
- virtual void ResetIgnitionCycles();
- virtual int TimeoutResponse();
- virtual bool SecondsBetweenRetries(std::vector<int>* seconds);
- virtual bool RefreshDB();
- virtual VehicleData GetVehicleData();
-
- virtual std::vector<UserFriendlyMessage> GetUserFriendlyMsg(
- const std::vector<std::string>& msg_codes, const std::string& language);
-
- virtual EndpointUrls GetUpdateUrls(int service_type);
- virtual std::string GetLockScreenIconUrl() const;
- virtual int GetNotificationsNumber(const std::string& priority);
- virtual bool GetPriority(const std::string& policy_app_id,
- std::string* priority);
- InitResult Init();
- bool Close();
- bool Clear();
- bool Drop();
- virtual void WriteDb();
- virtual utils::SharedPtr<policy_table::Table> GenerateSnapshot() const;
- virtual bool Save(const policy_table::Table& table);
- bool GetInitialAppData(const std::string& app_id, StringArray* nicknames =
- NULL,
- StringArray* app_hmi_types = NULL);
- bool GetFunctionalGroupings(policy_table::FunctionalGroupings& groups);
-
- protected:
- virtual void GatherModuleMeta(policy_table::ModuleMeta* meta) const;
- virtual void GatherModuleConfig(policy_table::ModuleConfig* config) const;
- virtual bool GatherUsageAndErrorCounts(
- policy_table::UsageAndErrorCounts* counts) const;
- virtual void GatherDeviceData(policy_table::DeviceData* data) const;
- virtual bool GatherFunctionalGroupings(
- policy_table::FunctionalGroupings* groups) const;
- virtual bool GatherConsumerFriendlyMessages(
- policy_table::ConsumerFriendlyMessages* messages) const;
- virtual bool GatherApplicationPoliciesSection(
- policy_table::ApplicationPoliciesSection* policies) const;
-
- bool GatherAppGroup(const std::string& app_id,
- policy_table::Strings* app_groups) const;
- bool GatherAppType(const std::string& app_id,
- policy_table::AppHMITypes* app_types) const;
- bool GatherRequestType(const std::string& app_id,
- policy_table::RequestTypes* request_types) const;
- bool GatherNickName(const std::string& app_id,
- policy_table::Strings* nicknames) const;
-
- virtual bool SaveApplicationCustomData(const std::string& app_id,
- bool is_revoked,
- bool is_default,
- bool is_predata);
-
- virtual bool SaveModuleMeta(const policy_table::ModuleMeta& meta);
- virtual bool SaveModuleConfig(const policy_table::ModuleConfig& config);
- virtual bool SaveUsageAndErrorCounts(
- const policy_table::UsageAndErrorCounts& counts);
- virtual bool SaveDeviceData(const policy_table::DeviceData& devices);
- virtual bool SaveFunctionalGroupings(
- const policy_table::FunctionalGroupings& groups);
- virtual bool SaveConsumerFriendlyMessages(
- const policy_table::ConsumerFriendlyMessages& messages);
- virtual bool SaveApplicationPoliciesSection(
- const policy_table::ApplicationPoliciesSection& policies);
- virtual bool SaveSpecificAppPolicy(
- const policy_table::ApplicationPolicies::value_type& app);
- virtual bool SaveDevicePolicy(const policy_table::DevicePolicy& device);
-
- virtual bool SaveMessageString(const std::string& type,
- const std::string& lang,
- const policy_table::MessageString& strings);
-
- bool SaveAppGroup(const std::string& app_id,
- const policy_table::Strings& app_groups);
- bool SaveNickname(const std::string& app_id,
- const policy_table::Strings& nicknames);
- bool SaveAppType(const std::string& app_id,
- const policy_table::AppHMITypes& types);
- bool SaveRequestType(const std::string& app_id,
- const policy_table::RequestTypes& types);
-
- public:
- bool UpdateRequired() const;
- void SaveUpdateRequired(bool value);
-
- bool IsApplicationRepresented(const std::string& app_id) const;
- bool CopyApplication(const std::string& source,
- const std::string& destination);
-
- bool IsApplicationRevoked(const std::string& app_id) const;
- virtual bool IsDefaultPolicy(const std::string& app_id) const;
- virtual bool IsPredataPolicy(const std::string& app_id) const;
- virtual bool SetDefaultPolicy(const std::string& app_id);
- virtual void SetPreloaded(bool value);
-
- virtual bool SetVINValue(const std::string& value);
-
- dbms::SQLDatabase* db() const;
- virtual bool SetIsDefault(const std::string& app_id, bool is_default) const;
-
- private:
- static const std::string kDatabaseName;
- dbms::SQLDatabase* db_;
-
- bool SaveRpcs(int64_t group_id, const policy_table::Rpc& rpcs);
- bool SaveServiceEndpoints(const policy_table::ServiceEndpoints& endpoints);
- bool SaveSecondsBetweenRetries(
- const policy_table::SecondsBetweenRetries& seconds);
- bool SaveNumberOfNotificationsPerMinute(
- const policy_table::NumberOfNotificationsPerMinute& notifications);
- bool SaveMessageType(const std::string& type);
- bool SaveLanguage(const std::string& code);
-};
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_PT_REPRESENTATION_H_
diff --git a/src/components/policy/src/policy/include/policy/sql_wrapper.h b/src/components/policy/src/policy/include/policy/sql_wrapper.h
deleted file mode 100644
index 29dbdd481d..0000000000
--- a/src/components/policy/src/policy/include/policy/sql_wrapper.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_WRAPPER_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_WRAPPER_H_
-
-#if __QNX__
-# include "qdb_wrapper/sql_database.h"
-# include "qdb_wrapper/sql_query.h"
-#else // __QNX__
-# include "sqlite_wrapper/sql_database.h"
-# include "sqlite_wrapper/sql_query.h"
-#endif // __QNX__
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_SQL_WRAPPER_H_
diff --git a/src/components/policy/src/policy/include/policy/update_status_manager.h b/src/components/policy/src/policy/include/policy/update_status_manager.h
deleted file mode 100644
index 2fb0a2b18b..0000000000
--- a/src/components/policy/src/policy/include/policy/update_status_manager.h
+++ /dev/null
@@ -1,196 +0,0 @@
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_H
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_H
-
-#include "policy/policy_types.h"
-#include "utils/lock.h"
-#include "utils/timer_thread.h"
-#include "utils/threads/thread.h"
-#include "utils/threads/thread_delegate.h"
-#include "utils/conditional_variable.h"
-#include "utils/lock.h"
-#include "utils/logger.h"
-#include "utils/macro.h"
-
-namespace policy {
-
-class PolicyListener;
-
-class UpdateStatusManager {
- public:
- /**
- * @brief Constructor
- */
- UpdateStatusManager();
-
- ~UpdateStatusManager();
-
- /**
- * @brief Sets listener pointer
- * @param listener Pointer to policy listener implementation
- */
- void set_listener(PolicyListener* listener);
-
- /**
- * @brief Update status hanlder for PTS sending out
- * @param update_timeout Timeout for waiting of incoming PTU
- */
- void OnUpdateSentOut(uint32_t update_timeout);
-
- /**
- * @brief Update status handler for PTU waiting timeout
- */
- void OnUpdateTimeoutOccurs();
-
- /**
- * @brief Update status handler for valid PTU receiving
- */
- void OnValidUpdateReceived();
-
- /**
- * @brief Update status handler for wrong PTU receiving
- */
- void OnWrongUpdateReceived();
-
- /**
- * @brief Update status handler for reset PT to default state
- * @param is_update_required Update necessity flag
- */
- void OnResetDefaultPT(bool is_update_required);
-
- /**
- * @brief Update status handler for restarting retry sequence
- */
- void OnResetRetrySequence();
-
- /**
- * @brief Update status handler on new application registering
- */
- void OnNewApplicationAdded();
-
- /**
- * @brief Update status handler for policy initialization
- * @param is_update_required Update necessity flag
- */
- void OnPolicyInit(bool is_update_required);
-
- /**
- * @brief IsUpdateRequired allows to distiguish if update is required
- *
- * @return true if update required.
- */
- bool IsUpdateRequired() const;
-
- /**
- * @brief IsUpdatePending allows to distinguish if update is in pending mode.
- *
- * @return true if update is in pending mode.
- */
- bool IsUpdatePending() const;
-
- /**
- * @brief ScheduleUpdate allows to schedule next update.
- * It will change state to Update_Needed, that's is.
- */
- void ScheduleUpdate();
-
- /**
- * @brief ResetUpdateSchedule allows to reset all scheduled updates.
- */
- void ResetUpdateSchedule();
-
- /**
- * @brief StringifiedUpdateStatus allows to obtain update status as a string.
- *
- * @return stringified update status.
- */
- std::string StringifiedUpdateStatus() const;
-
- /**
- * @brief Status handler on applications search started
- */
- void OnAppsSearchStarted();
-
- /**
- * @brief Status handler on applications search completed
- */
- void OnAppsSearchCompleted();
-
- /**
- * @brief Returns status is application search in progress
- * @return true, if in progress, otherwise - false
- */
- bool IsAppsSearchInProgress();
-
-private:
- /*
- * @brief Sets flag for update progress
- *
- * @param value
- */
- void set_exchange_in_progress(bool value);
-
- /*
- * @brief Sets flag for pending update
- *
- * @param value
- */
- void set_exchange_pending(bool value);
-
- /*
- * @brief Sets flag for update necessity
- *
- * @param value
- */
- void set_update_required(bool value);
-
- /**
- * @brief Check update status and notify HMI on changes
- */
- void CheckUpdateStatus();
-
-private:
-
- /**
- * @brief Returns current policy update status
- * @return
- */
- PolicyTableStatus GetUpdateStatus() const;
-
- PolicyListener* listener_;
- bool exchange_in_progress_;
- bool update_required_;
- bool update_scheduled_;
- bool exchange_pending_;
- bool apps_search_in_progress_;
- sync_primitives::Lock exchange_in_progress_lock_;
- sync_primitives::Lock update_required_lock_;
- sync_primitives::Lock exchange_pending_lock_;
- sync_primitives::Lock apps_search_in_progress_lock_;
- /**
- * @brief Last status of policy table update
- */
- PolicyTableStatus last_update_status_;
-
- class UpdateThreadDelegate: public threads::ThreadDelegate {
-
- public:
- UpdateThreadDelegate(UpdateStatusManager* update_status_manager);
- ~UpdateThreadDelegate();
- virtual void threadMain();
- virtual void exitThreadMain();
- void updateTimeOut(const uint32_t timeout_ms);
-
- volatile uint32_t timeout_;
- volatile bool stop_flag_;
- sync_primitives::Lock state_lock_;
- sync_primitives::ConditionalVariable termination_condition_;
- UpdateStatusManager* update_status_manager_;
- };
-
- UpdateThreadDelegate* update_status_thread_delegate_;
- threads::Thread* thread_;
-};
-
-}
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_H
diff --git a/src/components/policy/src/policy/include/policy/update_status_manager_interface.h b/src/components/policy/src/policy/include/policy/update_status_manager_interface.h
deleted file mode 100644
index f059958477..0000000000
--- a/src/components/policy/src/policy/include/policy/update_status_manager_interface.h
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_SRC_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_INTERFACE_H_
-#define SRC_COMPONENTS_POLICY_SRC_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_INTERFACE_H_
-
-#include "utils/shared_ptr.h"
-#include "policy/policy_types.h"
-
-namespace policy {
-
-class PolicyListener;
-
-class UpdateStatusManagerInterface {
- public:
- virtual ~UpdateStatusManagerInterface() {
- }
- /**
- * @brief Sets listener pointer
- * @param listener Pointer to policy listener implementation
- */
- virtual void set_listener(PolicyListener* listener) = 0;
-
- /**
- * @brief Update status hanlder for PTS sending out
- * @param update_timeout Timeout for waiting of incoming PTU
- */
- virtual void OnUpdateSentOut(uint32_t update_timeout) = 0;
-
- /**
- * @brief Update status handler for PTU waiting timeout
- */
- virtual void OnUpdateTimeoutOccurs() = 0;
-
- /**
- * @brief Update status handler for valid PTU receiving
- */
- virtual void OnValidUpdateReceived() = 0;
-
- /**
- * @brief Update status handler for wrong PTU receiving
- */
- virtual void OnWrongUpdateReceived() = 0;
-
- /**
- * @brief Update status handler for reset PT to default state
- * @param is_update_required Update necessity flag
- */
- virtual void OnResetDefaultPT(bool is_update_required) = 0;
-
- /**
- * @brief Update status handler for restarting retry sequence
- */
- virtual void OnResetRetrySequence() = 0;
-
- /**
- * @brief Update status handler on new application registering
- */
- virtual void OnNewApplicationAdded() = 0;
-
- /**
- * @brief Update status handler for policy initialization
- * @param is_update_required Update necessity flag
- */
- virtual void OnPolicyInit(bool is_update_required) = 0;
-
- /**
- * @brief Returns current policy update status
- * @return
- */
- virtual PolicyTableStatus GetUpdateStatus() = 0;
-};
-
-typedef utils::SharedPtr<UpdateStatusManagerInterface> UpdateStatusManagerInterfaceSPtr;
-
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_SRC_POLICY_INCLUDE_POLICY_UPDATE_STATUS_MANAGER_INTERFACE_H_
diff --git a/src/components/policy/src/policy/include/policy/user_consent_manager.h b/src/components/policy/src/policy/include/policy/user_consent_manager.h
deleted file mode 100644
index 4bf80afb13..0000000000
--- a/src/components/policy/src/policy/include/policy/user_consent_manager.h
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USER_CONSENT_MANAGER_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USER_CONSENT_MANAGER_H_
-
-namespace policy {
-class UserConsentManager {
- public:
- UserConsentManager() {}
- ~UserConsentManager() {}
-};
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USER_CONSENT_MANAGER_H_
diff --git a/src/components/policy/src/policy/policy_table/table_struct/CMakeLists.txt b/src/components/policy/src/policy/policy_table/table_struct/CMakeLists.txt
deleted file mode 100644
index 6d67c71d8b..0000000000
--- a/src/components/policy/src/policy/policy_table/table_struct/CMakeLists.txt
+++ /dev/null
@@ -1,42 +0,0 @@
-# Copyright (c) 2013, Ford Motor Company
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# Redistributions of source code must retain the above copyright notice, this
-# list of conditions and the following disclaimer.
-#
-# Redistributions in binary form must reproduce the above copyright notice,
-# this list of conditions and the following
-# disclaimer in the documentation and/or other materials provided with the
-# distribution.
-#
-# Neither the name of the Ford Motor Company nor the names of its contributors
-# may be used to endorse or promote products derived from this software
-# without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-# POSSIBILITY OF SUCH DAMAGE.
-
-set(target policy_struct)
-
-include_directories(.)
-
-set(SOURCES
- ./enums.cc
- ./types.cc
- ./validation.cc
-)
-
-add_library(${target} ${SOURCES})
-target_link_libraries(${target} Utils)
diff --git a/src/components/policy/src/policy/policy_table/table_struct/enums.cc b/src/components/policy/src/policy/policy_table/table_struct/enums.cc
deleted file mode 100644
index 5ba1efe52c..0000000000
--- a/src/components/policy/src/policy/policy_table/table_struct/enums.cc
+++ /dev/null
@@ -1,438 +0,0 @@
-// This file is generated, do not edit
-#include "./enums.h"
-
-namespace rpc {
-namespace policy_table_interface_base {
-bool IsValidEnum(Priority val) {
- switch (val) {
- case P_EMERGENCY: return true;
- case P_NAVIGATION: return true;
- case P_VOICECOM: return true;
- case P_COMMUNICATION: return true;
- case P_NORMAL: return true;
- case P_NONE: return true;
- default: return false;
- }
-}
-const char* EnumToJsonString(Priority val) {
- switch (val) {
- case P_EMERGENCY: return "EMERGENCY";
- case P_NAVIGATION: return "NAVIGATION";
- case P_VOICECOM: return "VOICECOM";
- case P_COMMUNICATION: return "COMMUNICATION";
- case P_NORMAL: return "NORMAL";
- case P_NONE: return "NONE";
- default: return "";
- }
-}
-bool EnumFromJsonString(const std::string& literal, Priority* result) {
- if ("EMERGENCY" == literal) {
- *result = P_EMERGENCY;
- return true;
- } else if ("NAVIGATION" == literal) {
- *result = P_NAVIGATION;
- return true;
- } else if ("VOICECOM" == literal) {
- *result = P_VOICECOM;
- return true;
- } else if ("COMMUNICATION" == literal) {
- *result = P_COMMUNICATION;
- return true;
- } else if ("NORMAL" == literal) {
- *result = P_NORMAL;
- return true;
- } else if ("NONE" == literal) {
- *result = P_NONE;
- return true;
- } else {
- return false;
- }
-}
-
-bool IsValidEnum(HmiLevel val) {
- switch (val) {
- case HL_BACKGROUND: return true;
- case HL_FULL: return true;
- case HL_LIMITED: return true;
- case HL_NONE: return true;
- default: return false;
- }
-}
-const char* EnumToJsonString(HmiLevel val) {
- switch (val) {
- case HL_BACKGROUND: return "BACKGROUND";
- case HL_FULL: return "FULL";
- case HL_LIMITED: return "LIMITED";
- case HL_NONE: return "NONE";
- default: return "";
- }
-}
-bool EnumFromJsonString(const std::string& literal, HmiLevel* result) {
- if ("BACKGROUND" == literal) {
- *result = HL_BACKGROUND;
- return true;
- } else if ("FULL" == literal) {
- *result = HL_FULL;
- return true;
- } else if ("LIMITED" == literal) {
- *result = HL_LIMITED;
- return true;
- } else if ("NONE" == literal) {
- *result = HL_NONE;
- return true;
- } else {
- return false;
- }
-}
-
-bool IsValidEnum(Parameter val) {
- switch (val) {
- case P_GPS: return true;
- case P_SPEED: return true;
- case P_ENGINETORQUE: return true;
- case P_EXTERNALTEMPERATURE: return true;
- case P_FUELLEVEL: return true;
- case P_FUELLEVEL_STATE: return true;
- case P_HEADLAMPSTATUS: return true;
- case P_INSTANTFUELCONSUMPTION: return true;
- case P_ODOMETER: return true;
- case P_TIREPRESSURE: return true;
- case P_WIPERSTATUS: return true;
- case P_VIN: return true;
- case P_ACCPEDALPOSITION: return true;
- case P_BELTSTATUS: return true;
- case P_DRIVERBRAKING: return true;
- case P_PRNDL: return true;
- case P_RPM: return true;
- case P_STEERINGWHEELANGLE: return true;
- case P_MYKEY: return true;
- case P_AIRBAGSTATUS: return true;
- case P_BODYINFORMATION: return true;
- case P_CLUSTERMODESTATUS: return true;
- case P_DEVICESTATUS: return true;
- case P_EMERGENCYEVENT: return true;
- case P_ECALLINFO: return true;
- default: return false;
- }
-}
-const char* EnumToJsonString(Parameter val) {
- switch (val) {
- case P_GPS: return "gps";
- case P_SPEED: return "speed";
- case P_ENGINETORQUE: return "engineTorque";
- case P_EXTERNALTEMPERATURE: return "externalTemperature";
- case P_FUELLEVEL: return "fuelLevel";
- case P_FUELLEVEL_STATE: return "fuelLevel_State";
- case P_HEADLAMPSTATUS: return "headLampStatus";
- case P_INSTANTFUELCONSUMPTION: return "instantFuelConsumption";
- case P_ODOMETER: return "odometer";
- case P_TIREPRESSURE: return "tirePressure";
- case P_WIPERSTATUS: return "wiperStatus";
- case P_VIN: return "vin";
- case P_ACCPEDALPOSITION: return "accPedalPosition";
- case P_BELTSTATUS: return "beltStatus";
- case P_DRIVERBRAKING: return "driverBraking";
- case P_PRNDL: return "prndl";
- case P_RPM: return "rpm";
- case P_STEERINGWHEELANGLE: return "steeringWheelAngle";
- case P_MYKEY: return "myKey";
- case P_AIRBAGSTATUS: return "airbagStatus";
- case P_BODYINFORMATION: return "bodyInformation";
- case P_CLUSTERMODESTATUS: return "clusterModeStatus";
- case P_DEVICESTATUS: return "deviceStatus";
- case P_EMERGENCYEVENT: return "emergencyEvent";
- case P_ECALLINFO: return "eCallInfo";
- default: return "";
- }
-}
-bool EnumFromJsonString(const std::string& literal, Parameter* result) {
- if ("gps" == literal) {
- *result = P_GPS;
- return true;
- } else if ("speed" == literal) {
- *result = P_SPEED;
- return true;
- } else if ("engineTorque" == literal) {
- *result = P_ENGINETORQUE;
- return true;
- } else if ("externalTemperature" == literal) {
- *result = P_EXTERNALTEMPERATURE;
- return true;
- } else if ("fuelLevel" == literal) {
- *result = P_FUELLEVEL;
- return true;
- } else if ("fuelLevel_State" == literal) {
- *result = P_FUELLEVEL_STATE;
- return true;
- } else if ("headLampStatus" == literal) {
- *result = P_HEADLAMPSTATUS;
- return true;
- } else if ("instantFuelConsumption" == literal) {
- *result = P_INSTANTFUELCONSUMPTION;
- return true;
- } else if ("odometer" == literal) {
- *result = P_ODOMETER;
- return true;
- } else if ("tirePressure" == literal) {
- *result = P_TIREPRESSURE;
- return true;
- } else if ("wiperStatus" == literal) {
- *result = P_WIPERSTATUS;
- return true;
- } else if ("vin" == literal) {
- *result = P_VIN;
- return true;
- } else if ("accPedalPosition" == literal) {
- *result = P_ACCPEDALPOSITION;
- return true;
- } else if ("beltStatus" == literal) {
- *result = P_BELTSTATUS;
- return true;
- } else if ("driverBraking" == literal) {
- *result = P_DRIVERBRAKING;
- return true;
- } else if ("prndl" == literal) {
- *result = P_PRNDL;
- return true;
- } else if ("rpm" == literal) {
- *result = P_RPM;
- return true;
- } else if ("steeringWheelAngle" == literal) {
- *result = P_STEERINGWHEELANGLE;
- return true;
- } else if ("myKey" == literal) {
- *result = P_MYKEY;
- return true;
- } else if ("airbagStatus" == literal) {
- *result = P_AIRBAGSTATUS;
- return true;
- } else if ("bodyInformation" == literal) {
- *result = P_BODYINFORMATION;
- return true;
- } else if ("clusterModeStatus" == literal) {
- *result = P_CLUSTERMODESTATUS;
- return true;
- } else if ("deviceStatus" == literal) {
- *result = P_DEVICESTATUS;
- return true;
- } else if ("emergencyEvent" == literal) {
- *result = P_EMERGENCYEVENT;
- return true;
- } else if ("eCallInfo" == literal) {
- *result = P_ECALLINFO;
- return true;
- } else {
- return false;
- }
-}
-
-bool IsValidEnum(AppHMIType val) {
- switch (val) {
- case AHT_DEFAULT: return true;
- case AHT_COMMUNICATION: return true;
- case AHT_MEDIA: return true;
- case AHT_MESSAGING: return true;
- case AHT_NAVIGATION: return true;
- case AHT_INFORMATION: return true;
- case AHT_SOCIAL: return true;
- case AHT_BACKGROUND_PROCESS: return true;
- case AHT_TESTING: return true;
- case AHT_SYSTEM: return true;
- default: return false;
- }
-}
-const char* EnumToJsonString(AppHMIType val) {
- switch (val) {
- case AHT_DEFAULT: return "DEFAULT";
- case AHT_COMMUNICATION: return "COMMUNICATION";
- case AHT_MEDIA: return "MEDIA";
- case AHT_MESSAGING: return "MESSAGING";
- case AHT_NAVIGATION: return "NAVIGATION";
- case AHT_INFORMATION: return "INFORMATION";
- case AHT_SOCIAL: return "SOCIAL";
- case AHT_BACKGROUND_PROCESS: return "BACKGROUND_PROCESS";
- case AHT_TESTING: return "TESTING";
- case AHT_SYSTEM: return "SYSTEM";
- default: return "";
- }
-}
-bool EnumFromJsonString(const std::string& literal, AppHMIType* result) {
- if ("DEFAULT" == literal) {
- *result = AHT_DEFAULT;
- return true;
- } else if ("COMMUNICATION" == literal) {
- *result = AHT_COMMUNICATION;
- return true;
- } else if ("MEDIA" == literal) {
- *result = AHT_MEDIA;
- return true;
- } else if ("MESSAGING" == literal) {
- *result = AHT_MESSAGING;
- return true;
- } else if ("NAVIGATION" == literal) {
- *result = AHT_NAVIGATION;
- return true;
- } else if ("INFORMATION" == literal) {
- *result = AHT_INFORMATION;
- return true;
- } else if ("SOCIAL" == literal) {
- *result = AHT_SOCIAL;
- return true;
- } else if ("BACKGROUND_PROCESS" == literal) {
- *result = AHT_BACKGROUND_PROCESS;
- return true;
- } else if ("TESTING" == literal) {
- *result = AHT_TESTING;
- return true;
- } else if ("SYSTEM" == literal) {
- *result = AHT_SYSTEM;
- return true;
- } else {
- return false;
- }
-}
-
-bool IsValidEnum(RequestType val) {
- switch(val) {
- case RT_HTTP : return true;
- case RT_FILE_RESUME : return true;
- case RT_AUTH_REQUEST: return true;
- case RT_AUTH_CHALLENGE: return true;
- case RT_AUTH_ACK: return true;
- case RT_PROPRIETARY: return true;
- case RT_QUERY_APPS: return true;
- case RT_LAUNCH_APP: return true;
- case RT_LOCK_SCREEN_ICON_URL: return true;
- case RT_TRAFFIC_MESSAGE_CHANNEL: return true;
- case RT_DRIVER_PROFILE: return true;
- case RT_VOICE_SEARCH: return true;
- case RT_NAVIGATION: return true;
- case RT_PHONE: return true;
- case RT_CLIMATE: return true;
- case RT_SETTINGS: return true;
- case RT_VEHICLE_DIAGNOSTICS: return true;
- case RT_EMERGENCY: return true;
- case RT_MEDIA: return true;
- case RT_FOTA: return true;
- default: return false;
- }
-}
-
-const char*EnumToJsonString(RequestType val) {
- switch(val) {
- case RT_HTTP : return "HTTP";
- case RT_FILE_RESUME : return "FILE_RESUME";
- case RT_AUTH_REQUEST: return "AUTH_REQUEST";
- case RT_AUTH_CHALLENGE: return "AUTH_CHALLENGE";
- case RT_AUTH_ACK: return "AUTH_ACK";
- case RT_PROPRIETARY: return "PROPRIETARY";
- case RT_QUERY_APPS: return "QUERY_APPS";
- case RT_LAUNCH_APP: return "LAUNCH_APP";
- case RT_LOCK_SCREEN_ICON_URL: return "LOCK_SCREEN_ICON_URL";
- case RT_TRAFFIC_MESSAGE_CHANNEL: return "TRAFFIC_MESSAGE_CHANNEL";
- case RT_DRIVER_PROFILE: return "DRIVER_PROFILE";
- case RT_VOICE_SEARCH: return "VOICE_SEARCH";
- case RT_NAVIGATION: return "NAVIGATION";
- case RT_PHONE: return "PHONE";
- case RT_CLIMATE: return "CLIMATE";
- case RT_SETTINGS: return "SETTINGS";
- case RT_VEHICLE_DIAGNOSTICS: return "VEHICLE_DIAGNOSTICS";
- case RT_EMERGENCY: return "EMERGENCY";
- case RT_MEDIA: return "MEDIA";
- case RT_FOTA: return "FOTA";
- default: return "";
- }
-}
-
-bool EnumFromJsonString(const std::string& literal, RequestType* result) {
- if ("HTTP" == literal) {
- *result = RT_HTTP;
- return true;
- }
- if ("FILE_RESUME" == literal) {
- *result = RT_FILE_RESUME;
- return true;
- }
- if ("AUTH_REQUEST" == literal) {
- *result = RT_AUTH_REQUEST;
- return true;
- }
- if ("AUTH_CHALLENGE" == literal) {
- *result = RT_AUTH_CHALLENGE;
- return true;
- }
- if ("AUTH_ACK" == literal) {
- *result = RT_AUTH_ACK;
- return true;
- }
- if ("PROPRIETARY" == literal) {
- *result = RT_PROPRIETARY;
- return true;
- }
- if ("QUERY_APPS" == literal) {
- *result = RT_QUERY_APPS;
- return true;
- }
- if ("LAUNCH_APP" == literal) {
- *result = RT_LAUNCH_APP;
- return true;
- }
- if ("LOCK_SCREEN_ICON_URL" == literal) {
- *result = RT_LOCK_SCREEN_ICON_URL;
- return true;
- }
- if ("TRAFFIC_MESSAGE_CHANNEL" == literal) {
- *result = RT_TRAFFIC_MESSAGE_CHANNEL;
- return true;
- }
- if ("DRIVER_PROFILE" == literal) {
- *result = RT_DRIVER_PROFILE;
- return true;
- }
- if ("VOICE_SEARCH" == literal) {
- *result = RT_VOICE_SEARCH;
- return true;
- }
- if ("NAVIGATION" == literal) {
- *result = RT_NAVIGATION;
- return true;
- }
- if ("PHONE" == literal) {
- *result = RT_PHONE;
- return true;
- }
- if ("CLIMATE" == literal) {
- *result = RT_CLIMATE;
- return true;
- }
- if ("SETTINGS" == literal) {
- *result = RT_SETTINGS;
- return true;
- }
- if ("VEHICLE_DIAGNOSTICS" == literal) {
- *result = RT_VEHICLE_DIAGNOSTICS;
- return true;
- }
- if ("EMERGENCY" == literal) {
- *result = RT_EMERGENCY;
- return true;
- }
- if ("MEDIA" == literal) {
- *result = RT_MEDIA;
- return true;
- }
- if ("FOTA" == literal) {
- *result = RT_FOTA;
- return true;
- } else {
- return false;
- }
-}
-
-const std::string kDefaultApp = "default";
-const std::string kPreDataConsentApp = "pre_DataConsent";
-const std::string kDeviceApp = "device";
-
-} // namespace policy_table_interface_base
-} // namespace rpc
-
diff --git a/src/components/policy/src/policy/policy_table/table_struct/enums.h b/src/components/policy/src/policy/policy_table/table_struct/enums.h
deleted file mode 100644
index f003679e13..0000000000
--- a/src/components/policy/src/policy/policy_table/table_struct/enums.h
+++ /dev/null
@@ -1,117 +0,0 @@
-// This file is generated, do not edit
-#ifndef POLICY_TABLE_INTERFACE_BASE_POLICY_TABLE_INTERFACE_BASE_ENUMS_H_
-#define POLICY_TABLE_INTERFACE_BASE_POLICY_TABLE_INTERFACE_BASE_ENUMS_H_
-#include <string>
-
-namespace rpc {
-namespace policy_table_interface_base {
-
-enum Priority {
- P_EMERGENCY,
- P_NAVIGATION,
- P_VOICECOM,
- P_COMMUNICATION,
- P_NORMAL,
- P_NONE,
-};
-
-bool IsValidEnum(Priority val);
-const char* EnumToJsonString(Priority val);
-bool EnumFromJsonString(const std::string& literal, Priority* result);
-
-
-enum HmiLevel {
- HL_BACKGROUND,
- HL_FULL,
- HL_LIMITED,
- HL_NONE,
-};
-bool IsValidEnum(HmiLevel val);
-const char* EnumToJsonString(HmiLevel val);
-bool EnumFromJsonString(const std::string& literal, HmiLevel* result);
-
-
-enum Parameter {
- P_GPS,
- P_SPEED,
- P_ENGINETORQUE,
- P_EXTERNALTEMPERATURE,
- P_FUELLEVEL,
- P_FUELLEVEL_STATE,
- P_HEADLAMPSTATUS,
- P_INSTANTFUELCONSUMPTION,
- P_ODOMETER,
- P_TIREPRESSURE,
- P_WIPERSTATUS,
- P_VIN,
- P_ACCPEDALPOSITION,
- P_BELTSTATUS,
- P_DRIVERBRAKING,
- P_PRNDL,
- P_RPM,
- P_STEERINGWHEELANGLE,
- P_MYKEY,
- P_AIRBAGSTATUS,
- P_BODYINFORMATION,
- P_CLUSTERMODESTATUS,
- P_DEVICESTATUS,
- P_EMERGENCYEVENT,
- P_ECALLINFO,
-};
-bool IsValidEnum(Parameter val);
-const char* EnumToJsonString(Parameter val);
-bool EnumFromJsonString(const std::string& literal, Parameter* result);
-
-
-enum AppHMIType {
- AHT_DEFAULT,
- AHT_COMMUNICATION,
- AHT_MEDIA,
- AHT_MESSAGING,
- AHT_NAVIGATION,
- AHT_INFORMATION,
- AHT_SOCIAL,
- AHT_BACKGROUND_PROCESS,
- AHT_TESTING,
- AHT_SYSTEM,
-};
-bool IsValidEnum(AppHMIType val);
-const char* EnumToJsonString(AppHMIType val);
-bool EnumFromJsonString(const std::string& literal, AppHMIType* result);
-
-
-enum RequestType {
- RT_HTTP,
- RT_FILE_RESUME,
- RT_AUTH_REQUEST,
- RT_AUTH_CHALLENGE,
- RT_AUTH_ACK,
- RT_PROPRIETARY,
- RT_QUERY_APPS,
- RT_LAUNCH_APP,
- RT_LOCK_SCREEN_ICON_URL,
- RT_TRAFFIC_MESSAGE_CHANNEL,
- RT_DRIVER_PROFILE,
- RT_VOICE_SEARCH,
- RT_NAVIGATION,
- RT_PHONE,
- RT_CLIMATE,
- RT_SETTINGS,
- RT_VEHICLE_DIAGNOSTICS,
- RT_EMERGENCY,
- RT_MEDIA,
- RT_FOTA
-};
-
-bool IsValidEnum(RequestType val);
-const char* EnumToJsonString(RequestType val);
-bool EnumFromJsonString(const std::string& literal, RequestType* result);
-
-extern const std::string kDefaultApp;
-extern const std::string kPreDataConsentApp;
-extern const std::string kDeviceApp;
-
-} // namespace policy_table_interface_base
-} // namespace rpc
-
-#endif // POLICY_TABLE_INTERFACE_BASE_POLICY_TABLE_INTERFACE_BASE_ENUMS_H_
diff --git a/src/components/policy/src/policy/policy_table/table_struct/types.cc b/src/components/policy/src/policy/policy_table/table_struct/types.cc
deleted file mode 100644
index 08ed6ca7df..0000000000
--- a/src/components/policy/src/policy/policy_table/table_struct/types.cc
+++ /dev/null
@@ -1,1126 +0,0 @@
-// This file is generated, do not edit
-#include "./types.h"
-#include "rpc_base/rpc_base_json_inl.h"
-
-namespace rpc {
-namespace policy_table_interface_base {
-
-std::string PolicyTableTypeToString(const PolicyTableType pt_type) {
- switch (pt_type) {
- case PT_PRELOADED: {
- return "PT_PRELOADED";
- }
- case PT_UPDATE: {
- return "PT_UPDATE";
- }
- case PT_SNAPSHOT: {
- return "PT_SNAPSHOT";
- }
- default: { return "INVALID_PT_TYPE"; }
- }
-}
-
-// PolicyBase methods
-PolicyBase::PolicyBase() : CompositeType(kUninitialized) {}
-PolicyBase::PolicyBase(Priority priority)
- : CompositeType(kUninitialized), priority(priority) {}
-PolicyBase::~PolicyBase() {}
-PolicyBase::PolicyBase(const Json::Value *value__)
- : CompositeType(InitHelper(value__, &Json::Value::isObject)),
- priority(impl::ValueMember(value__, "priority")) {}
-Json::Value PolicyBase::ToJsonValue() const {
- Json::Value result__(Json::objectValue);
- impl::WriteJsonField("priority", priority, &result__);
- return result__;
-}
-bool PolicyBase::is_valid() const {
- if (!priority.is_valid()) {
- return false;
- }
- return Validate();
-}
-bool PolicyBase::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool PolicyBase::struct_empty() const {
- if (priority.is_initialized()) {
- return false;
- }
- return true;
-}
-void PolicyBase::ReportErrors(rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
- if (!priority.is_valid()) {
- priority.ReportErrors(&report__->ReportSubobject("priority"));
- }
-}
-
-void PolicyBase::SetPolicyTableType(PolicyTableType pt_type) {
- CompositeType::SetPolicyTableType(pt_type);
- priority.SetPolicyTableType(pt_type);
-}
-
-// DevicePolicy methods
-DevicePolicy::DevicePolicy() : PolicyBase() {}
-DevicePolicy::DevicePolicy(Priority priority) : PolicyBase(priority) {}
-DevicePolicy::~DevicePolicy() {}
-DevicePolicy::DevicePolicy(const Json::Value *value__) : PolicyBase(value__) {}
-
-// AppPoliciesSection methods
-ApplicationPoliciesSection::ApplicationPoliciesSection()
- : CompositeType(kUninitialized) {}
-ApplicationPoliciesSection::ApplicationPoliciesSection(
- const ApplicationPolicies &apps, const DevicePolicy &device)
- : CompositeType(kUninitialized), apps(apps), device(device) {}
-ApplicationPoliciesSection::~ApplicationPoliciesSection() {}
-ApplicationPoliciesSection::ApplicationPoliciesSection(
- const Json::Value *value__)
- : CompositeType(InitHelper(value__, &Json::Value::isObject)), apps(value__),
- device(impl::ValueMember(value__, "device")) {
- // Since "device" is moved to separate struct, we have to delete it from
- // parsed apps to avoid validation issues due to possible wrong params in
- // device section
- apps.erase("device");
-}
-Json::Value ApplicationPoliciesSection::ToJsonValue() const {
- Json::Value result__(Json::objectValue);
- result__ = apps.ToJsonValue();
- impl::WriteJsonField("device", device, &result__);
- return result__;
-}
-bool ApplicationPoliciesSection::is_valid() const {
- if (!device.is_valid()) {
- return false;
- }
- if (!apps.is_valid()) {
- return false;
- }
- return Validate();
-}
-bool ApplicationPoliciesSection::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool ApplicationPoliciesSection::struct_empty() const {
- if (device.is_initialized()) {
- return false;
- }
- if (apps.is_initialized()) {
- return false;
- }
- return true;
-}
-void ApplicationPoliciesSection::ReportErrors(
- rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
- if (!device.is_valid()) {
- device.ReportErrors(&report__->ReportSubobject("device"));
- }
- if (!apps.is_valid()) {
- apps.ReportErrors(&report__->ReportSubobject("apps"));
- }
-}
-
-void ApplicationPoliciesSection::SetPolicyTableType(PolicyTableType pt_type) {
- CompositeType::SetPolicyTableType(pt_type);
- device.SetPolicyTableType(pt_type);
- apps.SetPolicyTableType(pt_type);
-}
-
-// ApplicationParams methods
-ApplicationParams::ApplicationParams() : PolicyBase() {}
-ApplicationParams::ApplicationParams(const Strings &groups, Priority priority)
- : PolicyBase(priority), groups(groups) {}
-ApplicationParams::~ApplicationParams() {}
-ApplicationParams::ApplicationParams(const Json::Value *value__)
- : PolicyBase(value__), groups(impl::ValueMember(value__, "groups")),
- nicknames(impl::ValueMember(value__, "nicknames")),
- AppHMIType(impl::ValueMember(value__, "AppHMIType")),
- RequestType(impl::ValueMember(value__, "RequestType")),
- memory_kb(impl::ValueMember(value__, "memory_kb"), 0),
- heart_beat_timeout_ms(
- impl::ValueMember(value__, "heart_beat_timeout_ms")),
- certificate(impl::ValueMember(value__, "certificate"), "not_specified") {}
-Json::Value ApplicationParams::ToJsonValue() const {
- Json::Value result__(PolicyBase::ToJsonValue());
- impl::WriteJsonField("groups", groups, &result__);
- impl::WriteJsonField("nicknames", nicknames, &result__);
- impl::WriteJsonField("AppHMIType", AppHMIType, &result__);
- impl::WriteJsonField("RequestType", RequestType, &result__);
- impl::WriteJsonField("memory_kb", memory_kb, &result__);
- impl::WriteJsonField("heart_beat_timeout_ms", heart_beat_timeout_ms,
- &result__);
- impl::WriteJsonField("certificate", certificate, &result__);
- return result__;
-}
-bool ApplicationParams::is_valid() const {
- // RequestType is not validated since there is high-level validation logic,
- // which takes into account information not available here.
- if (!PolicyBase::is_valid()) {
- return false;
- }
- if (!groups.is_valid()) {
- return false;
- }
- if (!nicknames.is_valid()) {
- return false;
- }
- if (!AppHMIType.is_valid()) {
- return false;
- }
- if (!memory_kb.is_valid()) {
- return false;
- }
- if (!heart_beat_timeout_ms.is_valid()) {
- return false;
- }
- if (!certificate.is_valid()) {
- return false;
- }
- return Validate();
-}
-bool ApplicationParams::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool ApplicationParams::struct_empty() const {
- if (!PolicyBase::is_initialized()) {
- return false;
- }
- if (groups.is_initialized()) {
- return false;
- }
- if (nicknames.is_initialized()) {
- return false;
- }
- if (AppHMIType.is_initialized()) {
- return false;
- }
- if (RequestType.is_initialized()) {
- return false;
- }
- if (memory_kb.is_initialized()) {
- return false;
- }
- if (heart_beat_timeout_ms.is_initialized()) {
- return false;
- }
- if (certificate.is_initialized()) {
- return false;
- }
- return true;
-}
-void ApplicationParams::ReportErrors(rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
- if (!groups.is_valid()) {
- groups.ReportErrors(&report__->ReportSubobject("groups"));
- }
- if (!nicknames.is_valid()) {
- nicknames.ReportErrors(&report__->ReportSubobject("nicknames"));
- }
- if (!AppHMIType.is_valid()) {
- AppHMIType.ReportErrors(&report__->ReportSubobject("AppHMIType"));
- }
- if (!RequestType.is_valid()) {
- RequestType.ReportErrors(&report__->ReportSubobject("RequestType"));
- }
- if (!priority.is_valid()) {
- priority.ReportErrors(&report__->ReportSubobject("priority"));
- }
- if (!memory_kb.is_valid()) {
- memory_kb.ReportErrors(&report__->ReportSubobject("memory_kb"));
- }
- if (!heart_beat_timeout_ms.is_valid()) {
- heart_beat_timeout_ms.ReportErrors(
- &report__->ReportSubobject("heart_beat_timeout_ms"));
- }
- if (!certificate.is_valid()) {
- certificate.ReportErrors(&report__->ReportSubobject("certificate"));
- }
-}
-
-void ApplicationParams::SetPolicyTableType(PolicyTableType pt_type) {
- PolicyBase::SetPolicyTableType(pt_type);
- groups.SetPolicyTableType(pt_type);
- AppHMIType.SetPolicyTableType(pt_type);
- RequestType.SetPolicyTableType(pt_type);
- memory_kb.SetPolicyTableType(pt_type);
- heart_beat_timeout_ms.SetPolicyTableType(pt_type);
- certificate.SetPolicyTableType(pt_type);
-}
-// RpcParameters methods
-RpcParameters::RpcParameters() : CompositeType(kUninitialized) {}
-RpcParameters::RpcParameters(const HmiLevels &hmi_levels)
- : CompositeType(kUninitialized), hmi_levels(hmi_levels) {}
-RpcParameters::~RpcParameters() {}
-RpcParameters::RpcParameters(const Json::Value *value__)
- : CompositeType(InitHelper(value__, &Json::Value::isObject)),
- hmi_levels(impl::ValueMember(value__, "hmi_levels")),
- parameters(impl::ValueMember(value__, "parameters")) {}
-Json::Value RpcParameters::ToJsonValue() const {
- Json::Value result__(Json::objectValue);
- impl::WriteJsonField("hmi_levels", hmi_levels, &result__);
- impl::WriteJsonField("parameters", parameters, &result__);
- return result__;
-}
-bool RpcParameters::is_valid() const {
- if (!hmi_levels.is_valid()) {
- return false;
- }
- if (!parameters.is_valid()) {
- return false;
- }
- return Validate();
-}
-bool RpcParameters::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool RpcParameters::struct_empty() const {
- if (hmi_levels.is_initialized()) {
- return false;
- }
- if (parameters.is_initialized()) {
- return false;
- }
-
- return true;
-}
-void RpcParameters::ReportErrors(rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
- if (!hmi_levels.is_valid()) {
- hmi_levels.ReportErrors(&report__->ReportSubobject("hmi_levels"));
- }
- if (!parameters.is_valid()) {
- parameters.ReportErrors(&report__->ReportSubobject("parameters"));
- }
-}
-
-void RpcParameters::SetPolicyTableType(PolicyTableType pt_type) {
- CompositeType::SetPolicyTableType(pt_type);
- hmi_levels.SetPolicyTableType(pt_type);
- parameters.SetPolicyTableType(pt_type);
-}
-
-// Rpcs methods
-Rpcs::Rpcs() : CompositeType(kUninitialized) {}
-Rpcs::Rpcs(const Rpc &rpcs) : CompositeType(kUninitialized), rpcs(rpcs) {}
-Rpcs::~Rpcs() {}
-Rpcs::Rpcs(const Json::Value *value__)
- : CompositeType(InitHelper(value__, &Json::Value::isObject)),
- user_consent_prompt(impl::ValueMember(value__, "user_consent_prompt")),
- rpcs(impl::ValueMember(value__, "rpcs")) {}
-Json::Value Rpcs::ToJsonValue() const {
- Json::Value result__(Json::objectValue);
- impl::WriteJsonField("user_consent_prompt", user_consent_prompt, &result__);
- impl::WriteJsonField("rpcs", rpcs, &result__);
- return result__;
-}
-bool Rpcs::is_valid() const {
- if (!user_consent_prompt.is_valid()) {
- return false;
- }
- if (!rpcs.is_valid()) {
- return false;
- }
- return Validate();
-}
-bool Rpcs::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool Rpcs::struct_empty() const {
- if (user_consent_prompt.is_initialized()) {
- return false;
- }
- if (rpcs.is_initialized()) {
- return false;
- }
-
- return true;
-}
-void Rpcs::ReportErrors(rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
- if (!user_consent_prompt.is_valid()) {
- user_consent_prompt.ReportErrors(
- &report__->ReportSubobject("user_consent_prompt"));
- }
- if (!rpcs.is_valid()) {
- rpcs.ReportErrors(&report__->ReportSubobject("rpcs"));
- }
-}
-
-void Rpcs::SetPolicyTableType(PolicyTableType pt_type) {
- CompositeType::SetPolicyTableType(pt_type);
- user_consent_prompt.SetPolicyTableType(pt_type);
- rpcs.SetPolicyTableType(pt_type);
-}
-
-// ModuleConfig methods
-ModuleConfig::ModuleConfig() : CompositeType(kUninitialized) {}
-ModuleConfig::ModuleConfig(
- uint8_t exchange_after_x_ignition_cycles,
- int64_t exchange_after_x_kilometers, uint8_t exchange_after_x_days,
- uint16_t timeout_after_x_seconds,
- const SecondsBetweenRetries &seconds_between_retries,
- const ServiceEndpoints &endpoints,
- const NumberOfNotificationsPerMinute &notifications_per_minute_by_priority)
- : CompositeType(kUninitialized),
- exchange_after_x_ignition_cycles(exchange_after_x_ignition_cycles),
- exchange_after_x_kilometers(exchange_after_x_kilometers),
- exchange_after_x_days(exchange_after_x_days),
- timeout_after_x_seconds(timeout_after_x_seconds),
- seconds_between_retries(seconds_between_retries), endpoints(endpoints),
- notifications_per_minute_by_priority(
- notifications_per_minute_by_priority) {}
-ModuleConfig::~ModuleConfig() {}
-ModuleConfig::ModuleConfig(const Json::Value *value__)
- : CompositeType(InitHelper(value__, &Json::Value::isObject)),
- preloaded_pt(impl::ValueMember(value__, "preloaded_pt")),
- exchange_after_x_ignition_cycles(
- impl::ValueMember(value__, "exchange_after_x_ignition_cycles")),
- exchange_after_x_kilometers(
- impl::ValueMember(value__, "exchange_after_x_kilometers")),
- exchange_after_x_days(
- impl::ValueMember(value__, "exchange_after_x_days")),
- timeout_after_x_seconds(
- impl::ValueMember(value__, "timeout_after_x_seconds")),
- seconds_between_retries(
- impl::ValueMember(value__, "seconds_between_retries")),
- endpoints(impl::ValueMember(value__, "endpoints")),
- notifications_per_minute_by_priority(
- impl::ValueMember(value__, "notifications_per_minute_by_priority")),
- vehicle_make(impl::ValueMember(value__, "vehicle_make")),
- vehicle_model(impl::ValueMember(value__, "vehicle_model")),
- vehicle_year(impl::ValueMember(value__, "vehicle_year")) {}
-
-void ModuleConfig::SafeCopyFrom(const ModuleConfig &from) {
- // device_certificates = from.device_certificates; // According to the
- // requirements this is optional.
- exchange_after_x_ignition_cycles = from.exchange_after_x_ignition_cycles;
- exchange_after_x_kilometers = from.exchange_after_x_kilometers;
- exchange_after_x_days = from.exchange_after_x_days;
- timeout_after_x_seconds = from.timeout_after_x_seconds;
- seconds_between_retries = from.seconds_between_retries;
- endpoints = from.endpoints;
- notifications_per_minute_by_priority =
- from.notifications_per_minute_by_priority;
-
- vehicle_make.assign_if_valid(from.vehicle_make);
- vehicle_model.assign_if_valid(from.vehicle_model);
- vehicle_year.assign_if_valid(from.vehicle_year);
-}
-
-Json::Value ModuleConfig::ToJsonValue() const {
- Json::Value result__(Json::objectValue);
- impl::WriteJsonField("preloaded_pt", preloaded_pt, &result__);
- impl::WriteJsonField("exchange_after_x_ignition_cycles",
- exchange_after_x_ignition_cycles, &result__);
- impl::WriteJsonField("exchange_after_x_kilometers",
- exchange_after_x_kilometers, &result__);
- impl::WriteJsonField("exchange_after_x_days", exchange_after_x_days,
- &result__);
- impl::WriteJsonField("timeout_after_x_seconds", timeout_after_x_seconds,
- &result__);
- impl::WriteJsonField("seconds_between_retries", seconds_between_retries,
- &result__);
- impl::WriteJsonField("endpoints", endpoints, &result__);
- impl::WriteJsonField("notifications_per_minute_by_priority",
- notifications_per_minute_by_priority, &result__);
- impl::WriteJsonField("vehicle_make", vehicle_make, &result__);
- impl::WriteJsonField("vehicle_model", vehicle_model, &result__);
- impl::WriteJsonField("vehicle_year", vehicle_year, &result__);
- return result__;
-}
-bool ModuleConfig::is_valid() const {
- if (!preloaded_pt.is_valid()) {
- return false;
- }
- if (!exchange_after_x_ignition_cycles.is_valid()) {
- return false;
- }
- if (!exchange_after_x_kilometers.is_valid()) {
- return false;
- }
- if (!exchange_after_x_days.is_valid()) {
- return false;
- }
- if (!timeout_after_x_seconds.is_valid()) {
- return false;
- }
- if (!seconds_between_retries.is_valid()) {
- return false;
- }
- if (!endpoints.is_valid()) {
- return false;
- }
- if (!notifications_per_minute_by_priority.is_valid()) {
- return false;
- }
- if (!vehicle_make.is_valid()) {
- return false;
- }
- if (!vehicle_model.is_valid()) {
- return false;
- }
- if (!vehicle_year.is_valid()) {
- return false;
- }
- return Validate();
-}
-bool ModuleConfig::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool ModuleConfig::struct_empty() const {
- if (preloaded_pt.is_initialized()) {
- return false;
- }
-
- if (exchange_after_x_ignition_cycles.is_initialized()) {
- return false;
- }
- if (exchange_after_x_kilometers.is_initialized()) {
- return false;
- }
-
- if (exchange_after_x_days.is_initialized()) {
- return false;
- }
- if (timeout_after_x_seconds.is_initialized()) {
- return false;
- }
-
- if (seconds_between_retries.is_initialized()) {
- return false;
- }
- if (endpoints.is_initialized()) {
- return false;
- }
-
- if (notifications_per_minute_by_priority.is_initialized()) {
- return false;
- }
- if (vehicle_make.is_initialized()) {
- return false;
- }
-
- if (vehicle_model.is_initialized()) {
- return false;
- }
- if (vehicle_year.is_initialized()) {
- return false;
- }
-
- return true;
-}
-void ModuleConfig::ReportErrors(rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
- if (!preloaded_pt.is_valid()) {
- preloaded_pt.ReportErrors(&report__->ReportSubobject("preloaded_pt"));
- }
- if (!exchange_after_x_ignition_cycles.is_valid()) {
- exchange_after_x_ignition_cycles.ReportErrors(
- &report__->ReportSubobject("exchange_after_x_ignition_cycles"));
- }
- if (!exchange_after_x_kilometers.is_valid()) {
- exchange_after_x_kilometers.ReportErrors(
- &report__->ReportSubobject("exchange_after_x_kilometers"));
- }
- if (!exchange_after_x_days.is_valid()) {
- exchange_after_x_days.ReportErrors(
- &report__->ReportSubobject("exchange_after_x_days"));
- }
- if (!timeout_after_x_seconds.is_valid()) {
- timeout_after_x_seconds.ReportErrors(
- &report__->ReportSubobject("timeout_after_x_seconds"));
- }
- if (!seconds_between_retries.is_valid()) {
- seconds_between_retries.ReportErrors(
- &report__->ReportSubobject("seconds_between_retries"));
- }
- if (!endpoints.is_valid()) {
- endpoints.ReportErrors(&report__->ReportSubobject("endpoints"));
- }
- if (!notifications_per_minute_by_priority.is_valid()) {
- notifications_per_minute_by_priority.ReportErrors(
- &report__->ReportSubobject("notifications_per_minute_by_priority"));
- }
- if (!vehicle_make.is_valid()) {
- vehicle_make.ReportErrors(&report__->ReportSubobject("vehicle_make"));
- }
- if (!vehicle_model.is_valid()) {
- vehicle_model.ReportErrors(&report__->ReportSubobject("vehicle_model"));
- }
- if (!vehicle_year.is_valid()) {
- vehicle_year.ReportErrors(&report__->ReportSubobject("vehicle_year"));
- }
- if (PT_PRELOADED == GetPolicyTableType()) {
- std::string validation_info =
- ommited_validation_info + PolicyTableTypeToString(GetPolicyTableType());
- rpc::ValidationReport *ommited_field_report;
- if (vehicle_make.is_initialized()) {
- ommited_field_report = &report__->ReportSubobject("vehicle_make");
- ommited_field_report->set_validation_info(validation_info);
- }
- if (vehicle_year.is_initialized()) {
- ommited_field_report = &report__->ReportSubobject("vehicle_year");
- ommited_field_report->set_validation_info(validation_info);
- }
- if (vehicle_model.is_initialized()) {
- ommited_field_report = &report__->ReportSubobject("vehicle_model");
- ommited_field_report->set_validation_info(validation_info);
- }
- }
-}
-
-void ModuleConfig::SetPolicyTableType(PolicyTableType pt_type) {
- CompositeType::SetPolicyTableType(pt_type);
- preloaded_pt.SetPolicyTableType(pt_type);
- exchange_after_x_ignition_cycles.SetPolicyTableType(pt_type);
- exchange_after_x_kilometers.SetPolicyTableType(pt_type);
- exchange_after_x_days.SetPolicyTableType(pt_type);
- timeout_after_x_seconds.SetPolicyTableType(pt_type);
- seconds_between_retries.SetPolicyTableType(pt_type);
- endpoints.SetPolicyTableType(pt_type);
- notifications_per_minute_by_priority.SetPolicyTableType(pt_type);
- vehicle_make.SetPolicyTableType(pt_type);
- vehicle_model.SetPolicyTableType(pt_type);
- vehicle_year.SetPolicyTableType(pt_type);
-}
-
-// MessageString methods
-MessageString::MessageString() : CompositeType(kUninitialized) {}
-MessageString::~MessageString() {}
-MessageString::MessageString(const Json::Value *value__)
- : CompositeType(InitHelper(value__, &Json::Value::isObject)),
- line1(impl::ValueMember(value__, "line1")),
- line2(impl::ValueMember(value__, "line2")),
- tts(impl::ValueMember(value__, "tts")),
- label(impl::ValueMember(value__, "label")),
- textBody(impl::ValueMember(value__, "textBody")) {}
-Json::Value MessageString::ToJsonValue() const {
- Json::Value result__(Json::objectValue);
- impl::WriteJsonField("line1", line1, &result__);
- impl::WriteJsonField("line2", line2, &result__);
- impl::WriteJsonField("tts", tts, &result__);
- impl::WriteJsonField("label", label, &result__);
- impl::WriteJsonField("textBody", textBody, &result__);
- return result__;
-}
-bool MessageString::is_valid() const {
- if (struct_empty()) {
- return initialization_state__ == kInitialized && Validate();
- }
- if (!line1.is_valid()) {
- return false;
- }
- if (!line2.is_valid()) {
- return false;
- }
- if (!tts.is_valid()) {
- return false;
- }
- if (!label.is_valid()) {
- return false;
- }
- if (!textBody.is_valid()) {
- return false;
- }
- return Validate();
-}
-bool MessageString::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool MessageString::struct_empty() const {
- if (line1.is_initialized()) {
- return false;
- }
- if (line2.is_initialized()) {
- return false;
- }
-
- if (tts.is_initialized()) {
- return false;
- }
- if (label.is_initialized()) {
- return false;
- }
-
- if (textBody.is_initialized()) {
- return false;
- }
- return true;
-}
-void MessageString::ReportErrors(rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
- if (!line1.is_valid()) {
- line1.ReportErrors(&report__->ReportSubobject("line1"));
- }
- if (!line2.is_valid()) {
- line2.ReportErrors(&report__->ReportSubobject("line2"));
- }
- if (!tts.is_valid()) {
- tts.ReportErrors(&report__->ReportSubobject("tts"));
- }
- if (!label.is_valid()) {
- label.ReportErrors(&report__->ReportSubobject("label"));
- }
- if (!textBody.is_valid()) {
- textBody.ReportErrors(&report__->ReportSubobject("textBody"));
- }
-}
-
-void MessageString::SetPolicyTableType(PolicyTableType pt_type) {
- CompositeType::SetPolicyTableType(pt_type);
- line1.SetPolicyTableType(pt_type);
- line2.SetPolicyTableType(pt_type);
- tts.SetPolicyTableType(pt_type);
- label.SetPolicyTableType(pt_type);
- textBody.SetPolicyTableType(pt_type);
-}
-
-// MessageLanguages methods
-MessageLanguages::MessageLanguages() : CompositeType(kUninitialized) {}
-MessageLanguages::MessageLanguages(const Languages &languages)
- : CompositeType(kUninitialized), languages(languages) {}
-MessageLanguages::~MessageLanguages() {}
-MessageLanguages::MessageLanguages(const Json::Value *value__)
- : CompositeType(InitHelper(value__, &Json::Value::isObject)),
- languages(impl::ValueMember(value__, "languages")) {}
-Json::Value MessageLanguages::ToJsonValue() const {
- Json::Value result__(Json::objectValue);
- impl::WriteJsonField("languages", languages, &result__);
- return result__;
-}
-bool MessageLanguages::is_valid() const {
- if (!languages.is_valid()) {
- return false;
- }
- return Validate();
-}
-bool MessageLanguages::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool MessageLanguages::struct_empty() const {
- if (languages.is_initialized()) {
- return false;
- }
- return true;
-}
-
-void MessageLanguages::ReportErrors(rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
- if (PT_SNAPSHOT == GetPolicyTableType()) {
- if (languages.is_initialized()) {
- std::string validation_info =
- ommited_validation_info +
- PolicyTableTypeToString(GetPolicyTableType());
- report__->ReportSubobject("languages")
- .set_validation_info(validation_info);
- }
- }
- if (!languages.is_valid()) {
- languages.ReportErrors(&report__->ReportSubobject("languages"));
- }
-}
-
-void MessageLanguages::SetPolicyTableType(PolicyTableType pt_type) {
- CompositeType::SetPolicyTableType(pt_type);
- languages.SetPolicyTableType(pt_type);
-}
-
-// ConsumerFriendlyMessages methods
-ConsumerFriendlyMessages::ConsumerFriendlyMessages()
- : CompositeType(kUninitialized) {}
-ConsumerFriendlyMessages::ConsumerFriendlyMessages(const std::string &version)
- : CompositeType(kUninitialized), version(version) {}
-ConsumerFriendlyMessages::~ConsumerFriendlyMessages() {}
-ConsumerFriendlyMessages::ConsumerFriendlyMessages(const Json::Value *value__)
- : CompositeType(InitHelper(value__, &Json::Value::isObject)),
- version(impl::ValueMember(value__, "version")),
- messages(impl::ValueMember(value__, "messages")) {}
-Json::Value ConsumerFriendlyMessages::ToJsonValue() const {
- Json::Value result__(Json::objectValue);
- impl::WriteJsonField("version", version, &result__);
- impl::WriteJsonField("messages", messages, &result__);
- return result__;
-}
-bool ConsumerFriendlyMessages::is_valid() const {
- if (!version.is_valid()) {
- return false;
- }
- if (!messages.is_valid()) {
- return false;
- }
- return Validate();
-}
-bool ConsumerFriendlyMessages::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool ConsumerFriendlyMessages::struct_empty() const {
- if (version.is_initialized()) {
- return false;
- }
- if (messages.is_initialized()) {
- return false;
- }
-
- return true;
-}
-void ConsumerFriendlyMessages::ReportErrors(
- rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
- if (!version.is_valid()) {
- version.ReportErrors(&report__->ReportSubobject("version"));
- }
- if (PT_SNAPSHOT == GetPolicyTableType()) {
- if (messages.is_initialized()) {
- std::string validation_info =
- ommited_validation_info +
- PolicyTableTypeToString(GetPolicyTableType());
- report__->ReportSubobject("messages")
- .set_validation_info(validation_info);
- }
- }
- if (!messages.is_valid()) {
- messages.ReportErrors(&report__->ReportSubobject("messages"));
- }
-}
-
-void ConsumerFriendlyMessages::SetPolicyTableType(PolicyTableType pt_type) {
- CompositeType::SetPolicyTableType(pt_type);
- version.SetPolicyTableType(pt_type);
- messages.SetPolicyTableType(pt_type);
-}
-
-// ModuleMeta methods
-ModuleMeta::ModuleMeta() : CompositeType(kUninitialized) {}
-ModuleMeta::~ModuleMeta() {}
-ModuleMeta::ModuleMeta(const Json::Value *value__)
- : CompositeType(InitHelper(value__, &Json::Value::isObject)) {}
-Json::Value ModuleMeta::ToJsonValue() const {
- Json::Value result__(Json::objectValue);
- return result__;
-}
-bool ModuleMeta::is_valid() const {
- if (struct_empty()) {
- return initialization_state__ == kInitialized && Validate();
- }
- return Validate();
-}
-bool ModuleMeta::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool ModuleMeta::struct_empty() const { return true; }
-void ModuleMeta::ReportErrors(rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
-}
-
-// AppLevel methods
-AppLevel::AppLevel() : CompositeType(kUninitialized) {}
-AppLevel::~AppLevel() {}
-AppLevel::AppLevel(const Json::Value *value__)
- : CompositeType(InitHelper(value__, &Json::Value::isObject)) {}
-Json::Value AppLevel::ToJsonValue() const {
- Json::Value result__(Json::objectValue);
- return result__;
-}
-bool AppLevel::is_valid() const {
- if (struct_empty()) {
- return initialization_state__ == kInitialized && Validate();
- }
- return Validate();
-}
-bool AppLevel::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool AppLevel::struct_empty() const { return true; }
-void AppLevel::ReportErrors(rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
- if (PT_PRELOADED == GetPolicyTableType() ||
- PT_UPDATE == GetPolicyTableType()) {
- std::string validation_info =
- ommited_validation_info + PolicyTableTypeToString(GetPolicyTableType());
- report__->set_validation_info(validation_info);
- }
-}
-
-// UsageAndErrorCounts methods
-UsageAndErrorCounts::UsageAndErrorCounts() : CompositeType(kUninitialized) {}
-
-UsageAndErrorCounts::~UsageAndErrorCounts() {}
-UsageAndErrorCounts::UsageAndErrorCounts(const Json::Value *value__)
- : CompositeType(InitHelper(value__, &Json::Value::isObject)),
- app_level(impl::ValueMember(value__, "app_level")) {}
-Json::Value UsageAndErrorCounts::ToJsonValue() const {
- Json::Value result__(Json::objectValue);
- impl::WriteJsonField("app_level", app_level, &result__);
- return result__;
-}
-bool UsageAndErrorCounts::is_valid() const {
- if (struct_empty()) {
- return initialization_state__ == kInitialized && Validate();
- }
- if (!app_level.is_valid()) {
- return false;
- }
- return Validate();
-}
-bool UsageAndErrorCounts::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool UsageAndErrorCounts::struct_empty() const {
- if (app_level.is_initialized()) {
- return false;
- }
- return true;
-}
-void UsageAndErrorCounts::ReportErrors(rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
- if (PT_PRELOADED == GetPolicyTableType() ||
- PT_UPDATE == GetPolicyTableType()) {
- std::string validation_info =
- ommited_validation_info + PolicyTableTypeToString(GetPolicyTableType());
- report__->set_validation_info(validation_info);
- }
- if (!app_level.is_valid()) {
- app_level.ReportErrors(&report__->ReportSubobject("app_level"));
- }
-}
-
-void UsageAndErrorCounts::SetPolicyTableType(PolicyTableType pt_type) {
- CompositeType::SetPolicyTableType(pt_type);
- app_level.SetPolicyTableType(pt_type);
-}
-
-// DeviceParams methods
-DeviceParams::DeviceParams() : CompositeType(kUninitialized) {}
-DeviceParams::~DeviceParams() {}
-DeviceParams::DeviceParams(const Json::Value *value__)
- : CompositeType(InitHelper(value__, &Json::Value::isObject)) {}
-Json::Value DeviceParams::ToJsonValue() const {
- Json::Value result__(Json::objectValue);
- return result__;
-}
-bool DeviceParams::is_valid() const {
- if (struct_empty()) {
- return initialization_state__ == kInitialized && Validate();
- }
- return Validate();
-}
-bool DeviceParams::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool DeviceParams::struct_empty() const { return true; }
-void DeviceParams::ReportErrors(rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
-}
-
-// PolicyTable methods
-PolicyTable::PolicyTable() : CompositeType(kUninitialized) {}
-PolicyTable::PolicyTable(
- const ApplicationPoliciesSection &app_policies_section,
- const FunctionalGroupings &functional_groupings,
- const ConsumerFriendlyMessages &consumer_friendly_messages,
- const ModuleConfig &module_config)
- : CompositeType(kUninitialized), app_policies_section(app_policies_section),
- functional_groupings(functional_groupings),
- consumer_friendly_messages(consumer_friendly_messages),
- module_config(module_config) {}
-PolicyTable::~PolicyTable() {}
-PolicyTable::PolicyTable(const Json::Value *value__)
- : CompositeType(InitHelper(value__, &Json::Value::isObject)),
- app_policies_section(impl::ValueMember(value__, "app_policies")),
- functional_groupings(impl::ValueMember(value__, "functional_groupings")),
- consumer_friendly_messages(
- impl::ValueMember(value__, "consumer_friendly_messages")),
- module_config(impl::ValueMember(value__, "module_config")),
- module_meta(impl::ValueMember(value__, "module_meta")),
- usage_and_error_counts(
- impl::ValueMember(value__, "usage_and_error_counts")),
- device_data(impl::ValueMember(value__, "device_data")) {}
-Json::Value PolicyTable::ToJsonValue() const {
- Json::Value result__(Json::objectValue);
- impl::WriteJsonField("app_policies", app_policies_section, &result__);
- impl::WriteJsonField("functional_groupings", functional_groupings, &result__);
- impl::WriteJsonField("consumer_friendly_messages", consumer_friendly_messages,
- &result__);
- impl::WriteJsonField("module_config", module_config, &result__);
- impl::WriteJsonField("module_meta", module_meta, &result__);
- impl::WriteJsonField("usage_and_error_counts", usage_and_error_counts,
- &result__);
- impl::WriteJsonField("device_data", device_data, &result__);
- return result__;
-}
-bool PolicyTable::is_valid() const {
- if (!app_policies_section.is_valid()) {
- return false;
- }
- if (!functional_groupings.is_valid()) {
- return false;
- }
- if (!consumer_friendly_messages.is_valid()) {
- return false;
- }
- if (!module_config.is_valid()) {
- return false;
- }
- if (!module_meta.is_valid()) {
- return false;
- }
- if (!usage_and_error_counts.is_valid()) {
- return false;
- }
- if (!device_data.is_valid()) {
- return false;
- }
- return Validate();
-}
-bool PolicyTable::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool PolicyTable::struct_empty() const {
- if (app_policies_section.is_initialized()) {
- return false;
- }
- if (functional_groupings.is_initialized()) {
- return false;
- }
-
- if (consumer_friendly_messages.is_initialized()) {
- return false;
- }
- if (module_config.is_initialized()) {
- return false;
- }
-
- if (module_meta.is_initialized()) {
- return false;
- }
- if (usage_and_error_counts.is_initialized()) {
- return false;
- }
-
- if (device_data.is_initialized()) {
- return false;
- }
- return true;
-}
-void PolicyTable::ReportErrors(rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
- if (PT_PRELOADED == GetPolicyTableType() ||
- PT_UPDATE == GetPolicyTableType()) {
- std::string validation_info =
- ommited_validation_info + PolicyTableTypeToString(GetPolicyTableType());
-
- if (device_data.is_initialized()) {
- report__->ReportSubobject("device_data")
- .set_validation_info(validation_info);
- }
- }
- if (!app_policies_section.is_valid()) {
- app_policies_section.ReportErrors(
- &report__->ReportSubobject("app_policies"));
- }
- if (!functional_groupings.is_valid()) {
- functional_groupings.ReportErrors(
- &report__->ReportSubobject("functional_groupings"));
- }
- if (!consumer_friendly_messages.is_valid()) {
- consumer_friendly_messages.ReportErrors(
- &report__->ReportSubobject("consumer_friendly_messages"));
- }
- if (!module_config.is_valid()) {
- module_config.ReportErrors(&report__->ReportSubobject("module_config"));
- }
- if (!module_meta.is_valid()) {
- module_meta.ReportErrors(&report__->ReportSubobject("module_meta"));
- }
- if (!usage_and_error_counts.is_valid()) {
- usage_and_error_counts.ReportErrors(
- &report__->ReportSubobject("usage_and_error_counts"));
- }
- if (!device_data.is_valid()) {
- device_data.ReportErrors(&report__->ReportSubobject("device_data"));
- }
-}
-
-void PolicyTable::SetPolicyTableType(PolicyTableType pt_type) {
- CompositeType::SetPolicyTableType(pt_type);
- app_policies_section.SetPolicyTableType(pt_type);
- functional_groupings.SetPolicyTableType(pt_type);
- consumer_friendly_messages.SetPolicyTableType(pt_type);
- module_config.SetPolicyTableType(pt_type);
- module_meta.SetPolicyTableType(pt_type);
- usage_and_error_counts.SetPolicyTableType(pt_type);
- device_data.SetPolicyTableType(pt_type);
-}
-
-// Table methods
-Table::Table() : CompositeType(kUninitialized) {}
-Table::Table(const PolicyTable &policy_table)
- : CompositeType(kUninitialized), policy_table(policy_table) {}
-Table::~Table() {}
-Table::Table(const Json::Value *value__)
- : CompositeType(InitHelper(value__, &Json::Value::isObject)),
- policy_table(impl::ValueMember(value__, "policy_table")) {}
-Json::Value Table::ToJsonValue() const {
- Json::Value result__(Json::objectValue);
- impl::WriteJsonField("policy_table", policy_table, &result__);
- return result__;
-}
-bool Table::is_valid() const {
- if (!policy_table.is_valid()) {
- return false;
- }
- return Validate();
-}
-bool Table::is_initialized() const {
- return (initialization_state__ != kUninitialized) || (!struct_empty());
-}
-bool Table::struct_empty() const {
- if (policy_table.is_initialized()) {
- return false;
- }
- return true;
-}
-void Table::ReportErrors(rpc::ValidationReport *report__) const {
- if (struct_empty()) {
- rpc::CompositeType::ReportErrors(report__);
- }
- if (!policy_table.is_valid()) {
- policy_table.ReportErrors(&report__->ReportSubobject("policy_table"));
- }
-}
-
-void Table::SetPolicyTableType(PolicyTableType pt_type) {
- CompositeType::SetPolicyTableType(pt_type);
- policy_table.SetPolicyTableType(pt_type);
-}
-
-} // namespace policy_table_interface_base
-} // namespace rpc
diff --git a/src/components/policy/src/policy/policy_table/table_struct/types.h b/src/components/policy/src/policy/policy_table/table_struct/types.h
deleted file mode 100644
index 1ac850ae9a..0000000000
--- a/src/components/policy/src/policy/policy_table/table_struct/types.h
+++ /dev/null
@@ -1,396 +0,0 @@
-// This file is generated, do not edit
-#ifndef POLICY_TABLE_INTERFACE_BASE_POLICY_TABLE_INTERFACE_BASE_TYPES_H_
-#define POLICY_TABLE_INTERFACE_BASE_POLICY_TABLE_INTERFACE_BASE_TYPES_H_
-#include "./enums.h"
-#include "rpc_base/rpc_message.h"
-namespace Json {
-class Value;
-} // namespace Json
-namespace rpc {
-namespace policy_table_interface_base {
-struct AppLevel;
-struct ApplicationParams;
-struct DeviceParams;
-struct MessageLanguages;
-struct MessageString;
-struct RpcParameters;
-struct Rpcs;
-} // namespace policy_table_interface_base
-} // namespace rpc
-
-namespace rpc {
-namespace policy_table_interface_base {
-
-typedef Array<String<1, 255>, 0, 255> Strings;
-
-typedef Array<Enum<AppHMIType>, 0, 255> AppHMITypes;
-
-typedef Array<Enum<HmiLevel>, 0, 4> HmiLevels;
-
-typedef Array<Enum<Parameter>, 0, 24> Parameters;
-
-typedef Map<RpcParameters, 0, 50> Rpc;
-
-typedef Array<String<10, 255>, 1, 255> URL;
-
-typedef Map<URL, 1, 255> URLList;
-
-typedef Map<URLList, 1, 255> ServiceEndpoints;
-
-typedef Map<Integer<uint8_t, 0, 255>, 0, 6> NumberOfNotificationsPerMinute;
-
-typedef Array<Integer<uint16_t, 1, 1000>, 0, 10> SecondsBetweenRetries;
-
-typedef Map<MessageString, 0, 500> Languages;
-
-typedef Map<MessageLanguages, 0, 255> Messages;
-
-typedef Map<AppLevel, 0, 255> AppLevels;
-
-typedef Map<Stringifyable<Nullable<ApplicationParams>>, 1, 1000>
- ApplicationPolicies;
-
-typedef Map<Rpcs, 1, 255> FunctionalGroupings;
-
-typedef Map<DeviceParams, 0, 255> DeviceData;
-
-typedef Array<Enum<RequestType>, 0, 255> RequestTypes;
-
-struct PolicyBase : CompositeType {
-public:
- Enum<Priority> priority;
-
-public:
- PolicyBase();
- PolicyBase(Priority priority);
- virtual ~PolicyBase();
- explicit PolicyBase(const Json::Value *value__);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
- virtual void SetPolicyTableType(PolicyTableType pt_type);
-
-private:
- bool Validate() const;
-};
-
-struct DevicePolicy : PolicyBase {
-public:
- DevicePolicy();
- DevicePolicy(Priority priority);
- ~DevicePolicy();
- explicit DevicePolicy(const Json::Value *value__);
-};
-
-struct ApplicationParams : PolicyBase {
-public:
- Strings groups;
- Optional<Strings> nicknames;
- Optional<AppHMITypes> AppHMIType;
- Optional<RequestTypes> RequestType;
- Optional<Integer<uint16_t, 0, 65225>> memory_kb;
- Optional<Integer<uint16_t, 0, 65225>> heart_beat_timeout_ms;
- Optional<String<0, 255>> certificate;
-
-public:
- ApplicationParams();
- ApplicationParams(const Strings &groups, Priority priority);
- ~ApplicationParams();
- explicit ApplicationParams(const Json::Value *value__);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
- virtual void SetPolicyTableType(PolicyTableType pt_type);
-
-private:
- bool Validate() const;
-};
-
-struct ApplicationPoliciesSection : CompositeType {
-public:
- mutable ApplicationPolicies apps;
- DevicePolicy device;
-
-public:
- ApplicationPoliciesSection();
- ApplicationPoliciesSection(const ApplicationPolicies &apps,
- const DevicePolicy &device);
- ~ApplicationPoliciesSection();
- explicit ApplicationPoliciesSection(const Json::Value *value__);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
- virtual void SetPolicyTableType(PolicyTableType pt_type);
-
-private:
- bool Validate() const;
-};
-
-struct RpcParameters : CompositeType {
-public:
- HmiLevels hmi_levels;
- Optional<Parameters> parameters;
-
-public:
- RpcParameters();
- explicit RpcParameters(const HmiLevels &hmi_levels);
- ~RpcParameters();
- explicit RpcParameters(const Json::Value *value__);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
- virtual void SetPolicyTableType(PolicyTableType pt_type);
-
-private:
- bool Validate() const;
-};
-
-struct Rpcs : CompositeType {
-public:
- Optional<String<1, 255>> user_consent_prompt;
- Nullable<Rpc> rpcs;
-
-public:
- Rpcs();
- explicit Rpcs(const Rpc &rpcs);
- ~Rpcs();
- explicit Rpcs(const Json::Value *value__);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
- virtual void SetPolicyTableType(PolicyTableType pt_type);
-
-private:
- bool Validate() const;
-};
-
-struct ModuleConfig : CompositeType {
-public:
- Optional<Boolean> preloaded_pt;
- Integer<uint8_t, 0, 255> exchange_after_x_ignition_cycles;
- Integer<int64_t, 0, 4294967296ll> exchange_after_x_kilometers;
- Integer<uint8_t, 0, 255> exchange_after_x_days;
- Integer<uint16_t, 0, 65535> timeout_after_x_seconds;
- SecondsBetweenRetries seconds_between_retries;
- ServiceEndpoints endpoints;
- NumberOfNotificationsPerMinute notifications_per_minute_by_priority;
- Optional<String<1, 100>> vehicle_make;
- Optional<String<1, 100>> vehicle_model;
- Optional<String<4, 4>> vehicle_year;
-
-public:
- ModuleConfig();
- ModuleConfig(uint8_t exchange_after_x_ignition_cycles,
- int64_t exchange_after_x_kilometers,
- uint8_t exchange_after_x_days, uint16_t timeout_after_x_seconds,
- const SecondsBetweenRetries &seconds_between_retries,
- const ServiceEndpoints &endpoints,
- const NumberOfNotificationsPerMinute &
- notifications_per_minute_by_priority);
- ~ModuleConfig();
- explicit ModuleConfig(const Json::Value *value__);
- void SafeCopyFrom(const ModuleConfig &from);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
- virtual void SetPolicyTableType(PolicyTableType pt_type);
-
-private:
- bool Validate() const;
-};
-
-struct MessageString : CompositeType {
-public:
- Optional<String<1, 65535>> line1;
- Optional<String<1, 65535>> line2;
- Optional<String<1, 65535>> tts;
- Optional<String<1, 65535>> label;
- Optional<String<1, 65535>> textBody;
-
-public:
- MessageString();
- ~MessageString();
- explicit MessageString(const Json::Value *value__);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
- virtual void SetPolicyTableType(PolicyTableType pt_type);
-
-private:
- bool Validate() const;
-};
-
-struct MessageLanguages : CompositeType {
-public:
- Languages languages;
-
-public:
- MessageLanguages();
- explicit MessageLanguages(const Languages &languages);
- ~MessageLanguages();
- explicit MessageLanguages(const Json::Value *value__);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
- virtual void SetPolicyTableType(PolicyTableType pt_type);
-
-private:
- bool Validate() const;
-};
-
-struct ConsumerFriendlyMessages : CompositeType {
-public:
- String<1, 100> version;
- Optional<Messages> messages;
-
-public:
- ConsumerFriendlyMessages();
- explicit ConsumerFriendlyMessages(const std::string &version);
- ~ConsumerFriendlyMessages();
- explicit ConsumerFriendlyMessages(const Json::Value *value__);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
- virtual void SetPolicyTableType(PolicyTableType pt_type);
-
-private:
- bool Validate() const;
-};
-
-struct ModuleMeta : CompositeType {
-public:
-public:
- ModuleMeta();
- ~ModuleMeta();
- explicit ModuleMeta(const Json::Value *value__);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
-
-private:
- bool Validate() const;
-};
-
-struct AppLevel : CompositeType {
-public:
-public:
- AppLevel();
- ~AppLevel();
- explicit AppLevel(const Json::Value *value__);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
-
-private:
- bool Validate() const;
-};
-
-struct UsageAndErrorCounts : CompositeType {
-public:
- Optional<AppLevels> app_level;
-
-public:
- UsageAndErrorCounts();
- ~UsageAndErrorCounts();
- explicit UsageAndErrorCounts(const Json::Value *value__);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
- virtual void SetPolicyTableType(PolicyTableType pt_type);
-
-private:
- bool Validate() const;
-};
-
-struct DeviceParams : CompositeType {
-public:
-public:
- DeviceParams();
- ~DeviceParams();
- explicit DeviceParams(const Json::Value *value__);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
-
-private:
- bool Validate() const;
-};
-
-struct PolicyTable : CompositeType {
-public:
- ApplicationPoliciesSection app_policies_section;
- FunctionalGroupings functional_groupings;
- Optional<ConsumerFriendlyMessages> consumer_friendly_messages;
- ModuleConfig module_config;
- Optional<ModuleMeta> module_meta;
- Optional<UsageAndErrorCounts> usage_and_error_counts;
- Optional<DeviceData> device_data;
-
-public:
- PolicyTable();
- PolicyTable(const ApplicationPoliciesSection &app_policies_section,
- const FunctionalGroupings &functional_groupings,
- const ConsumerFriendlyMessages &consumer_friendly_messages,
- const ModuleConfig &module_config);
- ~PolicyTable();
- explicit PolicyTable(const Json::Value *value__);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
- virtual void SetPolicyTableType(PolicyTableType pt_type);
-
-private:
- bool Validate() const;
-};
-
-struct Table : CompositeType {
-public:
- PolicyTable policy_table;
-
-public:
- Table();
- explicit Table(const PolicyTable &policy_table);
- ~Table();
- explicit Table(const Json::Value *value__);
- Json::Value ToJsonValue() const;
- bool is_valid() const;
- bool is_initialized() const;
- bool struct_empty() const;
- void ReportErrors(rpc::ValidationReport *report__) const;
- virtual void SetPolicyTableType(PolicyTableType pt_type);
-
-private:
- bool Validate() const;
-};
-} // namespace policy_table_interface_base
-} // namespace rpc
-
-#endif // POLICY_TABLE_INTERFACE_BASE_POLICY_TABLE_INTERFACE_BASE_TYPES_H_
diff --git a/src/components/policy/src/policy/policy_table/table_struct/validation.cc b/src/components/policy/src/policy/policy_table/table_struct/validation.cc
deleted file mode 100644
index a7656960fa..0000000000
--- a/src/components/policy/src/policy/policy_table/table_struct/validation.cc
+++ /dev/null
@@ -1,199 +0,0 @@
-#include <algorithm>
-#include "./types.h"
-#include "utils/logger.h"
-
-namespace {
-bool IsTypeInvalid(rpc::Enum<rpc::policy_table_interface_base::RequestType> request) { return !request.is_valid(); }
-}
-
-namespace rpc {
-namespace policy_table_interface_base {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "PolicyTableValidation")
-
-void RemoveInvalidTypes(RequestTypes& types) {
- types.erase(
- std::remove_if(types.begin(), types.end(), &IsTypeInvalid),
- types.end());
-}
-
-bool PolicyBase::Validate() const {
- return true;
-}
-
-bool ApplicationPoliciesSection::Validate() const {
- ApplicationPolicies::iterator it_default_policy =
- apps.find(kDefaultApp);
- ApplicationPolicies::iterator it_pre_data_policy =
- apps.find(kPreDataConsentApp);
-
- // Default and PreData policies are mandatory
- if (apps.end() == it_default_policy || apps.end() == it_pre_data_policy) {
- LOG4CXX_ERROR(logger_, "Default or preData policy is not present.");
- return false;
- }
-
- // Device policy is mandatory
- if (!device.is_initialized()) {
- LOG4CXX_ERROR(logger_, "Device policy is not present.");
- return false;
- }
-
- PolicyTableType pt_type = GetPolicyTableType();
- if (PT_PRELOADED != pt_type && PT_UPDATE != pt_type) {
- return true;
- }
-
- if (!it_default_policy->second.RequestType.is_valid()) {
- LOG4CXX_WARN(logger_,
- "Default policy RequestTypes are not valid. Will be cleaned.");
- RemoveInvalidTypes(*it_default_policy->second.RequestType);
- // If preloaded does not have valid default types - validation fails
- // Otherwise default will be empty, i.e. all types allowed
- if (PT_PRELOADED == pt_type) {
- if (it_default_policy->second.RequestType->empty()) {
- LOG4CXX_ERROR(
- logger_,
- "Default policy RequestTypes empty after clean-up. Exiting.");
- return false;
- }
- }
- }
-
- ApplicationPolicies::iterator iter = apps.begin();
- ApplicationPolicies::iterator end_iter = apps.end();
-
-
- while(iter != end_iter) {
- ApplicationParams& app_params = (*iter).second;
- bool is_request_type_ommited = !app_params.RequestType.is_initialized();
- bool is_request_type_valid = app_params.RequestType.is_valid();
- bool is_request_type_empty = app_params.RequestType->empty();
-
- if (PT_PRELOADED == pt_type) {
- if (!is_request_type_valid) {
- LOG4CXX_WARN(
- logger_,
- "App policy RequestTypes are not valid. Will be cleaned.");
- RemoveInvalidTypes(*app_params.RequestType);
- if (app_params.RequestType->empty()) {
- LOG4CXX_ERROR(
- logger_,
- "App policy RequestTypes empty after clean-up. Exiting.");
- return false;
- }
- }
- } else {
- if (is_request_type_ommited) {
- LOG4CXX_WARN(logger_, "App policy RequestTypes ommited."
- " Will be replaced with default.");
- app_params.RequestType = apps[kDefaultApp].RequestType;
- ++iter;
- continue;
- }
- if (!is_request_type_valid) {
- LOG4CXX_WARN(
- logger_,
- "App policy RequestTypes are invalid. Will be cleaned.");
- RemoveInvalidTypes(*app_params.RequestType);
- if (app_params.RequestType->empty()) {
- LOG4CXX_WARN(logger_, "App policy RequestTypes empty after clean-up."
- " Will be replaced with default.");
- app_params.RequestType = apps[kDefaultApp].RequestType;
- ++iter;
- continue;
- }
- }
- if (is_request_type_empty) {
- LOG4CXX_WARN(logger_, "App policy RequestTypes empty.");
- }
- }
- ++iter;
- }
-
- return true;
-}
-
-bool ApplicationParams::Validate() const {
- return true;
-}
-bool RpcParameters::Validate() const {
- return true;
-}
-bool Rpcs::Validate() const {
- return true;
-}
-
-bool ModuleConfig::Validate() const {
-
- if (PT_PRELOADED == GetPolicyTableType()) {
-
- if (vehicle_make.is_initialized()) {
- return false;
- }
- if (vehicle_year.is_initialized()) {
- return false;
- }
- if (vehicle_model.is_initialized()) {
- return false;
- }
- }
- return true;
-}
-
-bool MessageString::Validate() const {
- return true;
-}
-
-bool MessageLanguages::Validate() const {
- if (PT_SNAPSHOT == GetPolicyTableType()) {
- return false;
- }
- return true;
-}
-
-bool ConsumerFriendlyMessages::Validate() const {
- if (PT_SNAPSHOT == GetPolicyTableType() &&
- messages.is_initialized()) {
- return false;
- }
- return true;
-}
-
-bool ModuleMeta::Validate() const {
- return true;
-}
-
-bool AppLevel::Validate() const {
- if (PT_PRELOADED == GetPolicyTableType() ||
- PT_UPDATE == GetPolicyTableType()) {
- return false;
- }
- return true;
-}
-
-bool UsageAndErrorCounts::Validate() const {
- if (PT_PRELOADED == GetPolicyTableType() ||
- PT_UPDATE == GetPolicyTableType()) {
- return false;
- }
- return true;
-}
-bool DeviceParams::Validate() const {
- return true;
-}
-bool PolicyTable::Validate() const {
- if (PT_PRELOADED == GetPolicyTableType() ||
- PT_UPDATE == GetPolicyTableType()) {
- if (device_data.is_initialized()) {
- return false;
- }
- }
- return true;
-}
-bool Table::Validate() const {
- return true;
-}
-} // namespace policy_table_interface_base
-} // namespace rpc
-
diff --git a/src/components/policy/src/policy/qdb_wrapper/CMakeLists.txt b/src/components/policy/src/policy/qdb_wrapper/CMakeLists.txt
deleted file mode 100644
index 8b06351e21..0000000000
--- a/src/components/policy/src/policy/qdb_wrapper/CMakeLists.txt
+++ /dev/null
@@ -1,54 +0,0 @@
-# Copyright (c) 2013, Ford Motor Company
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# Redistributions of source code must retain the above copyright notice, this
-# list of conditions and the following disclaimer.
-#
-# Redistributions in binary form must reproduce the above copyright notice,
-# this list of conditions and the following
-# disclaimer in the documentation and/or other materials provided with the
-# distribution.
-#
-# Neither the name of the Ford Motor Company nor the names of its contributors
-# may be used to endorse or promote products derived from this software
-# without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-# POSSIBILITY OF SUCH DAMAGE.
-
-set(target dbms)
-
-include_directories(include)
-
-set(SOURCES
- src/sql_database.cc
- src/sql_query.cc
- src/sql_error.cc
-)
-
-add_library(${target} ${SOURCES})
-target_link_libraries(${target} qdb Utils)
-
-if (CMAKE_SYSTEM_NAME STREQUAL "QNX")
- file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/policy.ini DESTINATION ${CMAKE_BINARY_DIR}/src/appMain)
- file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/qdbserver.sh DESTINATION ${CMAKE_BINARY_DIR}/src/appMain)
-endif ()
-
-if (CMAKE_SYSTEM_NAME STREQUAL "QNX")
- install(FILES policy.ini DESTINATION bin)
- install(FILES qdbserver.sh DESTINATION bin
- PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ
- GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
-endif () \ No newline at end of file
diff --git a/src/components/policy/src/policy/qdb_wrapper/include/qdb_wrapper/sql_database.h b/src/components/policy/src/policy/qdb_wrapper/include/qdb_wrapper/sql_database.h
deleted file mode 100644
index caf954e1d2..0000000000
--- a/src/components/policy/src/policy/qdb_wrapper/include/qdb_wrapper/sql_database.h
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_DATABASE_H_
-#define SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_DATABASE_H_
-
-#include <qdb/qdb.h>
-#include <string>
-#include "qdb_wrapper/sql_error.h"
-#include "utils/lock.h"
-
-namespace policy {
-namespace dbms {
-
-class SQLQuery;
-
-/**
- * Represents a connection to a database.
- */
-class SQLDatabase {
- public:
- explicit SQLDatabase(const std::string& db_name);
- ~SQLDatabase();
-
- /**
- * Opens connection to the temporary in-memory database
- * @return true if successfully
- */
- bool Open();
-
- /**
- * Closes connection to the database
- */
- void Close();
-
- /**
- * Begins a transaction on the database
- * @return true if successfully
- */
- bool BeginTransaction();
-
- /**
- * Commits a transaction to the database
- * @return true if successfully
- */
- bool CommitTransaction();
-
- /**
- * Rolls back a transaction on the database
- * @return true if successfully
- */
- bool RollbackTransaction();
-
- /**
- * Gets information about the last error that occurred on the database
- * @return last error
- */
- SQLError LastError() const;
-
- /**
- * Call backup for opened DB
- */
- bool Backup();
- protected:
- /**
- * Gets connection to the SQLite database
- * @return pointer to connection
- */
- qdb_hdl_t* conn() const;
-
- private:
- /**
- * The connection to the SQLite database
- */
- qdb_hdl_t* conn_;
-
- /**
- * Lock for guarding connection to database
- */
- sync_primitives::Lock conn_lock_;
-
- /**
- * The database name
- */
- std::string db_name_;
-
- /**
- * The last error that occurred on the database
- */
- Error error_;
-
- /**
- * Execs query for internal using in this class
- * @param query sql query without return results
- * @return true if query was executed successfully
- */
- inline bool Exec(const std::string& query);
-
- friend class SQLQuery;
-};
-
-} // namespace dbms
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_DATABASE_H_
diff --git a/src/components/policy/src/policy/qdb_wrapper/include/qdb_wrapper/sql_error.h b/src/components/policy/src/policy/qdb_wrapper/include/qdb_wrapper/sql_error.h
deleted file mode 100644
index cf21a66ff4..0000000000
--- a/src/components/policy/src/policy/qdb_wrapper/include/qdb_wrapper/sql_error.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_ERROR_H_
-#define SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_ERROR_H_
-
-#include <string>
-
-namespace policy {
-namespace dbms {
-
-typedef enum Error {
- OK = 0, /* Successful result */
- ERROR /* Error */
-} Error;
-
-/**
- * Provides SQL database error information
- */
-class SQLError {
- public:
- SQLError(Error number, const std::string& text = "");
-
- /**
- * Gets number of error
- * @return error number
- */
- Error number() const;
-
- /**
- * Gets text description of the error
- * @return text
- */
- std::string text() const;
-
- private:
- /**
- * Number of the error
- */
- Error number_;
-
- /**
- * Description of the error
- */
- mutable std::string text_;
-};
-
-} // namespace dbms
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_ERROR_H_
diff --git a/src/components/policy/src/policy/qdb_wrapper/include/qdb_wrapper/sql_query.h b/src/components/policy/src/policy/qdb_wrapper/include/qdb_wrapper/sql_query.h
deleted file mode 100644
index af46402c8e..0000000000
--- a/src/components/policy/src/policy/qdb_wrapper/include/qdb_wrapper/sql_query.h
+++ /dev/null
@@ -1,251 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_QUERY_H_
-#define SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_QUERY_H_
-
-#include <stdint.h>
-#include <qdb/qdb.h>
-#include <string>
-#include <vector>
-#include <utility>
-#include "qdb_wrapper/sql_error.h"
-#include "utils/lock.h"
-
-namespace policy {
-namespace dbms {
-
-class SQLDatabase;
-
-/**
- * Provides a means of executing and manipulating SQL statements
- */
-class SQLQuery {
- public:
- explicit SQLQuery(SQLDatabase* db);
- ~SQLQuery();
-
- /**
- * Prepares the SQL query for executing
- * @param query the utf-8 string of SQL query
- * @return true if successfully
- */
- bool Prepare(const std::string& query);
-
- /**
- * Resets the binds of query for re-executing
- * @return true if successfully
- */
- bool Reset();
-
- /**
- * Deletes prepared SQL query
- */
- void Finalize();
-
- /**
- * Executes SQL query without make binds
- * @param query the utf-8 string of SQL query
- * @return true if successfull
- */
- bool Exec(const std::string& query);
-
- /**
- * Executes prepared SQL query and positions the query on the first record
- * @return true if successfull
- */
- bool Exec();
-
- /**
- * Retrieves the next record in the result, if available,
- * and positions the query on the retrieved record
- * @return true if record was retrieved successfully, false if a error was
- * or the result is empty or was retrieves last record
- */
- bool Next();
-
- /**
- * Binds null in the prepared query
- * @param pos position of param in the query
- */
- void Bind(int pos);
-
- /**
- * Binds int value in the prepared query.
- * @param pos position of param in the query
- * @param value value of param
- */
- void Bind(int pos, int value);
-
- /**
- * Binds int64_t value in the prepared query.
- * @param pos position of param in the query
- * @param value value of param
- */
- void Bind(int pos, int64_t value);
-
- /**
- * Binds double value in the prepared query.
- * @param pos position of param in the query
- * @param value value of param
- */
- void Bind(int pos, double value);
-
- /**
- * Binds bool value in the prepared query.
- * @param pos position of param in the query
- * @param value value of param
- */
- void Bind(int pos, bool value);
-
- /**
- * Binds string in the prepared query.
- * @param pos position of param in the query
- * @param value utf-8 string
- */
- void Bind(int pos, const std::string& value);
-
- /**
- * Gets value in the result record
- * @param pos position of value
- * @return boolean value
- */
- bool GetBoolean(int pos) const;
-
- /**
- * Gets value in the result record
- * @param pos position of value
- * @return integer value
- */
- int GetInteger(int pos) const;
-
- /**
- * Gets value in the result record
- * @param pos position of value
- * @return double value
- */
- double GetDouble(int pos) const;
-
- /**
- * Gets value in the result record
- * @param pos position of value
- * @return string value
- */
- std::string GetString(int pos) const;
-
- /**
- * Checks if value is null
- * @param pos position of value
- * @return true if value is null
- */
- bool IsNull(int pos) const;
-
- /**
- * Gets last id of insert row
- * @return id of insert row
- */
- int64_t LastInsertId() const;
-
- /**
- * Gets string of the query
- * @return string of the query
- */
- const std::string& query() const;
-
- /**
- * Gets information about the last error that occurred on the database
- * @return last error
- */
- SQLError LastError() const;
-
- private:
- /**
- * The instantiation of database
- */
- SQLDatabase* db_;
-
- /**
- * The string of query
- */
- std::string query_;
-
- /**
- * The id of SQL statement in QDB
- */
- int statement_;
-
- /**
- * Containers for keeping bind data
- */
- std::vector<std::pair<int, int64_t> > int_binds_;
- std::vector<std::pair<int, double> > double_binds_;
- std::vector<std::pair<int, std::string> > string_binds_;
- std::vector<int> null_binds_;
-
- /**
- * The array for binging data to the prepare query
- */
- qdb_binding_t* bindings_;
-
- /**
- * Lock for guarding bindings
- */
- sync_primitives::Lock bindings_lock_;
-
- /**
- * The result of query
- */
- qdb_result_t *result_;
-
- /**
- * The current row in result for select
- */
- int current_row_;
-
- /**
- * The number of rows in a result
- */
- int rows_;
-
- /**
- * The last error that occurred with this query
- */
- Error error_;
-
- uint8_t SetBinds();
- bool Result();
-};
-
-} // namespace dbms
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_QUERY_H_
diff --git a/src/components/policy/src/policy/qdb_wrapper/src/sql_database.cc b/src/components/policy/src/policy/qdb_wrapper/src/sql_database.cc
deleted file mode 100644
index ef26e64353..0000000000
--- a/src/components/policy/src/policy/qdb_wrapper/src/sql_database.cc
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <cstring>
-#include "qdb_wrapper/sql_database.h"
-#include "utils/logger.h"
-
-namespace policy {
-namespace dbms {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "SQLDatabase")
-
-SQLDatabase::SQLDatabase(const std::string& db_name)
- : conn_(NULL),
- db_name_(db_name),
- error_(Error::OK) {
-}
-
-SQLDatabase::~SQLDatabase() {
- Close();
-}
-
-bool SQLDatabase::Open() {
- sync_primitives::AutoLock auto_lock(conn_lock_);
- if (conn_) return true;
- conn_ = qdb_connect(db_name_.c_str(), 0);
- if (conn_ == NULL) {
- error_ = Error::ERROR;
- return false;
- }
- return true;
-}
-
-void SQLDatabase::Close() {
- sync_primitives::AutoLock auto_lock(conn_lock_);
- if (conn_) {
- if (qdb_disconnect(conn_) != -1) {
- conn_ = NULL;
- } else {
- error_ = Error::ERROR;
- }
- }
-}
-
-bool SQLDatabase::BeginTransaction() {
- return Exec("BEGIN TRANSACTION");
-}
-
-bool SQLDatabase::CommitTransaction() {
- return Exec("COMMIT TRANSACTION");
-}
-
-bool SQLDatabase::RollbackTransaction() {
- return Exec("ROLLBACK TRANSACTION");
-}
-
-bool SQLDatabase::Exec(const std::string& query) {
- sync_primitives::AutoLock auto_lock(conn_lock_);
- if (qdb_statement(conn_, query.c_str()) == -1) {
- error_ = Error::ERROR;
- return false;
- }
- return true;
-}
-
-SQLError SQLDatabase::LastError() const {
- return SQLError(error_, qdb_geterrmsg(conn_));
-}
-
-qdb_hdl_t* SQLDatabase::conn() const {
- return conn_;
-}
-
-bool SQLDatabase::Backup() {
- if (qdb_backup(conn_, QDB_ATTACH_DEFAULT) == -1) {
- error_ = Error::ERROR;
- LOG4CXX_ERROR(logger_, "Backup returned error: " << std::strerror(errno));
- return false;
- }
- LOG4CXX_INFO(logger_, "Backup was successful.");
- return true;
-}
-
-} // namespace dbms
-} // namespace policy
diff --git a/src/components/policy/src/policy/qdb_wrapper/src/sql_error.cc b/src/components/policy/src/policy/qdb_wrapper/src/sql_error.cc
deleted file mode 100644
index b8f836cc26..0000000000
--- a/src/components/policy/src/policy/qdb_wrapper/src/sql_error.cc
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "qdb_wrapper/sql_error.h"
-
-namespace policy {
-namespace dbms {
-
-SQLError::SQLError(Error number, const std::string& text)
- : number_(number),
- text_(text) {
-}
-
-Error SQLError::number() const {
- return number_;
-}
-
-std::string SQLError::text() const {
- if (!text_.empty()) {
- return text_;
- }
- switch (number_) {
- case OK:
- text_ = "Successful result";
- break;
- case ERROR:
- text_ = "Error";
- break;
- default:
- text_ = "Unknown error";
- }
- return text_;
-}
-
-} // namespace dbms
-} // namespace policy
-
diff --git a/src/components/policy/src/policy/qdb_wrapper/src/sql_query.cc b/src/components/policy/src/policy/qdb_wrapper/src/sql_query.cc
deleted file mode 100644
index d3191193be..0000000000
--- a/src/components/policy/src/policy/qdb_wrapper/src/sql_query.cc
+++ /dev/null
@@ -1,278 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "qdb_wrapper/sql_query.h"
-#include <string.h>
-#include <cassert>
-#include <algorithm>
-#include "qdb_wrapper/sql_database.h"
-
-namespace policy {
-namespace dbms {
-
-class SetBindInteger {
- public:
- explicit SetBindInteger(qdb_binding_t* array)
- : array_(array) {
- }
- void operator()(const std::pair<int, int64_t>& x) {
- // In QDB the number of position for binding starts since 1.
- QDB_SETARRAYBIND_INT(array_, x.first + 1, x.second);
- }
- private:
- qdb_binding_t* array_;
-};
-
-class SetBindReal {
- public:
- explicit SetBindReal(qdb_binding_t* array)
- : array_(array) {
- }
- void operator()(const std::pair<int, double>& x) {
- // In QDB the number of position for binding starts since 1.
- QDB_SETARRAYBIND_REAL(array_, x.first + 1, x.second);
- }
- private:
- qdb_binding_t* array_;
-};
-
-class SetBindText {
- public:
- explicit SetBindText(qdb_binding_t* array)
- : array_(array) {
- }
- void operator()(const std::pair<int, std::string>& x) {
- // In QDB the number of position for binding starts since 1.
- QDB_SETARRAYBIND_TEXT(array_, x.first + 1, x.second.c_str());
- }
- private:
- qdb_binding_t* array_;
-};
-
-class SetBindNull {
- public:
- explicit SetBindNull(qdb_binding_t* array)
- : array_(array) {
- }
- void operator()(int x) {
- // In QDB the number of position for binding starts since 1.
- QDB_SETARRAYBIND_NULL(array_, x + 1);
- }
- private:
- qdb_binding_t* array_;
-};
-
-SQLQuery::SQLQuery(SQLDatabase* db)
- : db_(db),
- query_(""),
- statement_(-1),
- bindings_(NULL),
- result_(NULL),
- current_row_(0),
- rows_(0),
- error_(Error::OK) {
-}
-
-SQLQuery::~SQLQuery() {
- Finalize();
- db_->Close();
- delete db_;
-}
-
-bool SQLQuery::Prepare(const std::string& query) {
- query_ = query;
- statement_ = qdb_stmt_init(db_->conn(), query.c_str(), query.length() + 1);
- if (statement_ == -1) {
- error_ = Error::ERROR;
- return false;
- }
- return true;
-}
-
-uint8_t SQLQuery::SetBinds() {
- uint8_t binding_count = int_binds_.size() + double_binds_.size()
- + string_binds_.size() + null_binds_.size();
-
- bindings_ = new qdb_binding_t[binding_count];
-
- std::for_each(int_binds_.begin(), int_binds_.end(),
- SetBindInteger(bindings_));
- std::for_each(double_binds_.begin(), double_binds_.end(),
- SetBindReal(bindings_));
- std::for_each(string_binds_.begin(), string_binds_.end(),
- SetBindText(bindings_));
- std::for_each(null_binds_.begin(), null_binds_.end(), SetBindNull(bindings_));
-
- return binding_count;
-}
-
-bool SQLQuery::Result() {
- result_ = qdb_getresult(db_->conn());
- if (!result_) {
- error_ = Error::ERROR;
- return false;
- }
- rows_ = qdb_rows(result_);
- if (rows_ == -1) {
- rows_ = 0;
- error_ = Error::ERROR;
- return false;
- }
- return true;
-}
-
-bool SQLQuery::Exec() {
- sync_primitives::AutoLock auto_lock(bindings_lock_);
- if (result_)
- return true;
-
- current_row_ = 0;
- uint8_t binding_count = SetBinds();
- if (qdb_stmt_exec(db_->conn(), statement_, bindings_, binding_count) == -1) {
- error_ = Error::ERROR;
- return false;
- }
- return Result();
-}
-
-bool SQLQuery::Next() {
- ++current_row_;
- return Exec() && current_row_ < rows_;
-}
-
-bool SQLQuery::Reset() {
- sync_primitives::AutoLock auto_lock(bindings_lock_);
- int_binds_.clear();
- double_binds_.clear();
- string_binds_.clear();
- null_binds_.clear();
- delete[] bindings_;
- bindings_ = NULL;
- rows_ = 0;
- current_row_ = 0;
- if (result_ && qdb_freeresult(result_) == -1) {
- error_ = Error::ERROR;
- return false;
- }
- result_ = NULL;
- return true;
-}
-
-void SQLQuery::Finalize() {
- if (Reset() && qdb_stmt_free(db_->conn(), statement_) != -1) {
- statement_ = 0;
- } else {
- error_ = Error::ERROR;
- }
-}
-
-bool SQLQuery::Exec(const std::string& query) {
- query_ = query;
- if (qdb_statement(db_->conn(), query.c_str()) == -1) {
- error_ = Error::ERROR;
- return false;
- }
- return true;
-}
-
-void SQLQuery::Bind(int pos, int value) {
- int_binds_.push_back(std::make_pair(pos, value));
-}
-
-void SQLQuery::Bind(int pos, int64_t value) {
- int_binds_.push_back(std::make_pair(pos, value));
-}
-
-void SQLQuery::Bind(int pos, double value) {
- double_binds_.push_back(std::make_pair(pos, value));
-}
-
-void SQLQuery::Bind(int pos, bool value) {
- Bind(pos, static_cast<int>(value));
-}
-
-void SQLQuery::Bind(int pos, const std::string& value) {
- string_binds_.push_back(std::make_pair(pos, value));
-}
-
-void SQLQuery::Bind(int pos) {
- null_binds_.push_back(pos);
-}
-
-bool SQLQuery::GetBoolean(int pos) const {
- return static_cast<bool>(GetInteger(pos));
-}
-
-int SQLQuery::GetInteger(int pos) const {
- void* ret = qdb_cell(result_, current_row_, pos);
- if (rows_ !=0 && ret) {
- return *static_cast<int*>(ret);
- }
- return 0;
-}
-
-double SQLQuery::GetDouble(int pos) const {
- void* ret = qdb_cell(result_, current_row_, pos);
- if (rows_ !=0 && ret) {
- return *static_cast<double*>(ret);
- }
- return 0;
-}
-
-std::string SQLQuery::GetString(int pos) const {
- void* ret = qdb_cell(result_, current_row_, pos);
- if (rows_ != 0 && ret) {
- return static_cast<const char*>(ret);
- }
- return "";
-}
-
-bool SQLQuery::IsNull(int pos) const {
- return rows_ == 0 || qdb_cell_type(result_, current_row_, pos) == QDB_NULL;
-}
-
-const std::string& SQLQuery::query() const {
- // TODO(KKolodiy): may return string query with value of arguments
- return query_;
-}
-
-SQLError SQLQuery::LastError() const {
- return SQLError(error_, qdb_geterrmsg(db_->conn()));
-}
-
-int64_t SQLQuery::LastInsertId() const {
- return qdb_last_insert_rowid(db_->conn(), result_);
-}
-
-} // namespace dbms
-} // namespace policy
-
diff --git a/src/components/policy/src/policy/sqlite_wrapper/CMakeLists.txt b/src/components/policy/src/policy/sqlite_wrapper/CMakeLists.txt
deleted file mode 100644
index 9007f84745..0000000000
--- a/src/components/policy/src/policy/sqlite_wrapper/CMakeLists.txt
+++ /dev/null
@@ -1,44 +0,0 @@
-# Copyright (c) 2013, Ford Motor Company
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# Redistributions of source code must retain the above copyright notice, this
-# list of conditions and the following disclaimer.
-#
-# Redistributions in binary form must reproduce the above copyright notice,
-# this list of conditions and the following
-# disclaimer in the documentation and/or other materials provided with the
-# distribution.
-#
-# Neither the name of the Ford Motor Company nor the names of its contributors
-# may be used to endorse or promote products derived from this software
-# without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-# POSSIBILITY OF SUCH DAMAGE.
-
-set(target dbms)
-
-find_package(Sqlite3 REQUIRED)
-
-include_directories(include)
-
-set(SOURCES
- src/sql_database.cc
- src/sql_query.cc
- src/sql_error.cc
-)
-
-add_library(${target} ${SOURCES})
-target_link_libraries(${target} Utils)
diff --git a/src/components/policy/src/policy/sqlite_wrapper/include/sqlite_wrapper/sql_database.h b/src/components/policy/src/policy/sqlite_wrapper/include/sqlite_wrapper/sql_database.h
deleted file mode 100644
index 274c64bef4..0000000000
--- a/src/components/policy/src/policy/sqlite_wrapper/include/sqlite_wrapper/sql_database.h
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_DATABASE_H_
-#define SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_DATABASE_H_
-
-#include <string>
-#include "sqlite_wrapper/sql_error.h"
-#include "utils/lock.h"
-
-struct sqlite3;
-
-namespace policy {
-namespace dbms {
-
-class SQLQuery;
-
-/**
- * Represents a connection to a database.
- */
-class SQLDatabase {
- public:
- SQLDatabase();
- explicit SQLDatabase(const std::string& filename);
- ~SQLDatabase();
-
- /**
- * Opens connection to the temporary in-memory database
- * @return true if successfully
- */
- bool Open();
-
- /**
- * Closes connection to the database
- */
- void Close();
-
- /**
- * Begins a transaction on the database
- * @return true if successfully
- */
- bool BeginTransaction();
-
- /**
- * Commits a transaction to the database
- * @return true if successfully
- */
- bool CommitTransaction();
-
- /**
- * Rolls back a transaction on the database
- * @return true if successfully
- */
- bool RollbackTransaction();
-
- /**
- * Gets information about the last error that occurred on the database
- * @return last error
- */
- SQLError LastError() const;
-
- /**
- * Sets path to database
- * If the database is already opened then need reopen it
- */
- void set_path(const std::string& path);
-
- /**
- * Checks if database is read/write
- * @return true if database is read/write
- */
- bool IsReadWrite();
-
- /**
- * Call backup for opened DB
- */
- bool Backup();
-
- protected:
- /**
- * Gets connection to the SQLite database
- * @return pointer to connection
- */
- sqlite3* conn() const;
-
- private:
- /**
- * The connection to the SQLite database
- */
- sqlite3* conn_;
-
- /**
- * Lock for guarding connection to database
- */
- sync_primitives::Lock conn_lock_;
-
- /**
- * The filename of database
- */
- std::string databasename_;
-
- /**
- * The last error that occurred on the database
- */
- int error_;
-
- /**
- * The temporary in-memory database
- * @see SQLite manual
- */
- static const std::string kInMemory;
-
- /**
- * The extension of filename of database
- */
- static const std::string kExtension;
-
- /**
- * Execs query for internal using in this class
- * @param query sql query without return results
- * @return true if query was executed successfully
- */
- inline bool Exec(const std::string& query);
-
- friend class SQLQuery;
-};
-
-} // namespace dbms
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_DATABASE_H_
diff --git a/src/components/policy/src/policy/sqlite_wrapper/include/sqlite_wrapper/sql_error.h b/src/components/policy/src/policy/sqlite_wrapper/include/sqlite_wrapper/sql_error.h
deleted file mode 100644
index 578b3990c9..0000000000
--- a/src/components/policy/src/policy/sqlite_wrapper/include/sqlite_wrapper/sql_error.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_ERROR_H_
-#define SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_ERROR_H_
-
-#include <string>
-
-namespace policy {
-namespace dbms {
-
-typedef enum Error {
- OK = 0, /* Successful result */
- ERROR, /* SQL error or missing database */
- INTERNAL, /* Internal logic error in SQLite */
- PERM, /* Access permission denied */
- ABORT, /* Callback routine requested an abort */
- BUSY, /* The database file is locked */
- LOCKED, /* A table in the database is locked */
- NOMEM, /* A malloc() failed */
- READONLY, /* Attempt to write a readonly database */
- INTERRUPT, /* Operation terminated by sqlite3_interrupt()*/
- IOERR, /* Some kind of disk I/O error occurred */
- CORRUPT, /* The database disk image is malformed */
- NOTFOUND, /* Unknown opcode in sqlite3_file_control() */
- FULL, /* Insertion failed because database is full */
- CANTOPEN, /* Unable to open the database file */
- PROTOCOL, /* Database lock protocol error */
- EMPTY, /* Database is empty */
- SCHEMA, /* The database schema changed */
- TOOBIG, /* String or BLOB exceeds size limit */
- CONSTRAINT, /* Abort due to constraint violation */
- MISMATCH, /* Data type mismatch */
- MISUSE, /* Library used incorrectly */
- NOLFS, /* Uses OS features not supported on host */
- AUTH, /* Authorization denied */
- FORMAT, /* Auxiliary database format error */
- RANGE, /* 2nd parameter to sqlite3_bind out of range */
- NOTADB, /* File opened that is not a database file */
- NOTICE, /* Notifications from sqlite3_log() */
- WARNING, /* Warnings from sqlite3_log() */
- ROW = 100, /* sqlite3_step() has another row ready */
- DONE = 101 /* sqlite3_step() has finished executing */
-} Error;
-
-/**
- * Provides SQL database error information
- */
-class SQLError {
- public:
- SQLError(Error number, const std::string& text = "");
-
- /**
- * Gets number of error
- * @return error number
- */
- Error number() const;
-
- /**
- * Gets text description of the error
- * @return text
- */
- std::string text() const;
-
- private:
- /**
- * Number of the error
- */
- Error number_;
-
- /**
- * Description of the error
- */
- mutable std::string text_;
-};
-
-} // namespace dbms
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_ERROR_H_
diff --git a/src/components/policy/src/policy/sqlite_wrapper/include/sqlite_wrapper/sql_query.h b/src/components/policy/src/policy/sqlite_wrapper/include/sqlite_wrapper/sql_query.h
deleted file mode 100644
index b477a812da..0000000000
--- a/src/components/policy/src/policy/sqlite_wrapper/include/sqlite_wrapper/sql_query.h
+++ /dev/null
@@ -1,219 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_QUERY_H_
-#define SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_QUERY_H_
-
-#include <stdint.h>
-#include <string>
-#include "sqlite_wrapper/sql_error.h"
-#include "utils/lock.h"
-
-struct sqlite3_stmt;
-
-namespace policy {
-namespace dbms {
-
-class SQLDatabase;
-
-/**
- * Provides a means of executing and manipulating SQL statements
- */
-class SQLQuery {
- public:
- explicit SQLQuery(SQLDatabase* db);
- ~SQLQuery();
-
- /**
- * Prepares the SQL query for executing
- * @param query the utf-8 string of SQL query
- * @return true if successfully
- */
- bool Prepare(const std::string& query);
-
- /**
- * Resets the binds of query for re-executing
- * @return true if successfully
- */
- bool Reset();
-
- /**
- * Deletes prepared SQL query
- */
- void Finalize();
-
- /**
- * Executes SQL query without make binds
- * @param query the utf-8 string of SQL query
- * @return true if successfull
- */
- bool Exec(const std::string& query);
-
- /**
- * Executes prepared SQL query and positions the query on the first record
- * @return true if successfull
- */
- bool Exec();
-
- /**
- * Retrieves the next record in the result, if available,
- * and positions the query on the retrieved record
- * @return true if record was retrieved successfully, false if a error was
- * or the result is empty or was retrieves last record
- */
- bool Next();
-
- /**
- * Binds null in the prepared query
- * @param pos position of param in the query
- */
- void Bind(int pos);
-
- /**
- * Binds int value in the prepared query.
- * @param pos position of param in the query
- * @param value value of param
- */
- void Bind(int pos, int value);
-
- /**
- * Binds int64_t value in the prepared query.
- * @param pos position of param in the query
- * @param value value of param
- */
- void Bind(int pos, int64_t value);
-
- /**
- * Binds double value in the prepared query.
- * @param pos position of param in the query
- * @param value value of param
- */
- void Bind(int pos, double value);
-
- /**
- * Binds bool value in the prepared query.
- * @param pos position of param in the query
- * @param value value of param
- */
- void Bind(int pos, bool value);
-
- /**
- * Binds string in the prepared query.
- * @param pos position of param in the query
- * @param value utf-8 string
- */
- void Bind(int pos, const std::string& value);
-
- /**
- * Gets value in the result record
- * @param pos position of value
- * @return boolean value
- */
- bool GetBoolean(int pos) const;
-
- /**
- * Gets value in the result record
- * @param pos position of value
- * @return integer value
- */
- int GetInteger(int pos) const;
-
- /**
- * Gets value in the result record
- * @param pos position of value
- * @return double value
- */
- double GetDouble(int pos) const;
-
- /**
- * Gets value in the result record
- * @param pos position of value
- * @return string value
- */
- std::string GetString(int pos) const;
-
- /**
- * Checks if value is null
- * @param pos position of value
- * @return true if value is null
- */
- bool IsNull(int pos) const;
-
- /**
- * Gets last id of insert row
- * @return id of insert row
- */
- int64_t LastInsertId() const;
-
- /**
- * Gets string of the query
- * @return string of the query
- */
- const std::string& query() const;
-
- /**
- * Gets information about the last error that occurred on the database
- * @return last error
- */
- SQLError LastError() const;
-
- private:
- /**
- * The instantiation of database
- */
- SQLDatabase& db_;
-
- /**
- * The string of query
- */
- std::string query_;
-
- /**
- * The SQL statement in SQLite
- */
- sqlite3_stmt* statement_;
-
- /**
- * Lock for guarding statement
- */
- sync_primitives::Lock statement_lock_;
-
- /**
- * The last error that occurred with this query
- */
- int error_;
-};
-
-} // namespace dbms
-} // namespace policy
-
-#endif // SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_QUERY_H_
diff --git a/src/components/policy/src/policy/sqlite_wrapper/src/sql_database.cc b/src/components/policy/src/policy/sqlite_wrapper/src/sql_database.cc
deleted file mode 100644
index 6a1d70f005..0000000000
--- a/src/components/policy/src/policy/sqlite_wrapper/src/sql_database.cc
+++ /dev/null
@@ -1,114 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "sqlite_wrapper/sql_database.h"
-#include <sqlite3.h>
-
-namespace policy {
-namespace dbms {
-
-const std::string SQLDatabase::kInMemory = ":memory:";
-const std::string SQLDatabase::kExtension = ".sqlite";
-
-SQLDatabase::SQLDatabase()
- : conn_(NULL),
- databasename_(kInMemory),
- error_(SQLITE_OK) {}
-
-SQLDatabase::SQLDatabase(const std::string& db_name)
- : conn_(NULL),
- databasename_(db_name + kExtension),
- error_(SQLITE_OK) {}
-
-SQLDatabase::~SQLDatabase() {
- Close();
-}
-
-bool SQLDatabase::Open() {
- sync_primitives::AutoLock auto_lock(conn_lock_);
- if (conn_) return true;
- error_ = sqlite3_open(databasename_.c_str(), &conn_);
- return error_ == SQLITE_OK;
-}
-
-bool SQLDatabase::IsReadWrite() {
- const char* schema = "main";
- return sqlite3_db_readonly(conn_, schema) == 0;
-}
-
-void SQLDatabase::Close() {
- if (!conn_) {
- return;
- }
-
- sync_primitives::AutoLock auto_lock(conn_lock_);
- error_ = sqlite3_close(conn_);
- if (error_ == SQLITE_OK) {
- conn_ = NULL;
- }
-}
-
-bool SQLDatabase::BeginTransaction() {
- return Exec("BEGIN TRANSACTION");
-}
-
-bool SQLDatabase::CommitTransaction() {
- return Exec("COMMIT TRANSACTION");
-}
-
-bool SQLDatabase::RollbackTransaction() {
- return Exec("ROLLBACK TRANSACTION");
-}
-
-bool SQLDatabase::Exec(const std::string& query) {
- sync_primitives::AutoLock auto_lock(conn_lock_);
- error_ = sqlite3_exec(conn_, query.c_str(), NULL, NULL, NULL);
- return error_ == SQLITE_OK;
-}
-
-SQLError SQLDatabase::LastError() const {
- return SQLError(Error(error_));
-}
-
-sqlite3* SQLDatabase::conn() const {
- return conn_;
-}
-
-void SQLDatabase::set_path(const std::string& path) {
- databasename_ = path + databasename_;
-}
-
-bool SQLDatabase::Backup() {
- return true;
-}
-} // namespace dbms
-} // namespace policy
diff --git a/src/components/policy/src/policy/sqlite_wrapper/src/sql_error.cc b/src/components/policy/src/policy/sqlite_wrapper/src/sql_error.cc
deleted file mode 100644
index 6ee82cc23b..0000000000
--- a/src/components/policy/src/policy/sqlite_wrapper/src/sql_error.cc
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "sqlite_wrapper/sql_error.h"
-
-namespace policy {
-namespace dbms {
-
-SQLError::SQLError(Error number, const std::string& text)
- : number_(number),
- text_(text) {
-}
-
-Error SQLError::number() const {
- return number_;
-}
-
-std::string SQLError::text() const {
- if (!text_.empty()) {
- return text_;
- }
- switch (number_) {
- case OK:
- text_ = "Successful result";
- break;
- case ERROR:
- text_ = "SQL error or missing database";
- break;
- case INTERNAL:
- text_ = "Internal logic error in SQLite";
- break;
- case PERM:
- text_ = "Access permission denied";
- break;
- case ABORT:
- text_ = "Callback routine requested an abort";
- break;
- case BUSY:
- text_ = "The database file is locked";
- break;
- case LOCKED:
- text_ = "A table in the database is locked";
- break;
- case NOMEM:
- text_ = "A malloc() failed";
- break;
- case READONLY:
- text_ = "Attempt to write a readonly database";
- break;
- case INTERRUPT:
- text_ = "Operation terminated by sqlite3_interrupt()";
- break;
- case IOERR:
- text_ = "Some kind of disk I/O error occurred";
- break;
- case CORRUPT:
- text_ = "The database disk image is malformed";
- break;
- case NOTFOUND:
- text_ = "Unknown opcode in sqlite3_file_control()";
- break;
- case FULL:
- text_ = "Insertion failed because database is full";
- break;
- case CANTOPEN:
- text_ = "Unable to open the database file";
- break;
- case PROTOCOL:
- text_ = "Database lock protocol error";
- break;
- case EMPTY:
- text_ = "Database is empty";
- break;
- case SCHEMA:
- text_ = "The database schema changed";
- break;
- case TOOBIG:
- text_ = "String or BLOB exceeds size limit";
- break;
- case CONSTRAINT:
- text_ = "Abort due to constraint violation";
- break;
- case MISMATCH:
- text_ = "Data type mismatch";
- break;
- case MISUSE:
- text_ = "Library used incorrectly";
- break;
- case NOLFS:
- text_ = "Uses OS features not supported on host";
- break;
- case AUTH:
- text_ = "Authorization denied";
- break;
- case FORMAT:
- text_ = "Auxiliary database format error";
- break;
- case RANGE:
- text_ = "2nd parameter to sqlite3_bind out of range";
- break;
- case NOTADB:
- text_ = "File opened that is not a database file";
- break;
- case NOTICE:
- text_ = "Notifications from sqlite3_log()";
- break;
- case WARNING:
- text_ = "Warnings from sqlite3_log()";
- break;
- case ROW:
- text_ = "sqlite3_step() has another row ready";
- break;
- case DONE:
- text_ = "sqlite3_step() has finished executing";
- break;
- default:
- text_ = "Unknown error";
- }
- return text_;
-}
-
-} // namespace dbms
-} // namespace policy
-
diff --git a/src/components/policy/src/policy/sqlite_wrapper/src/sql_query.cc b/src/components/policy/src/policy/sqlite_wrapper/src/sql_query.cc
deleted file mode 100644
index d6a643a5d2..0000000000
--- a/src/components/policy/src/policy/sqlite_wrapper/src/sql_query.cc
+++ /dev/null
@@ -1,157 +0,0 @@
-/*
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "sqlite_wrapper/sql_query.h"
-#include <sqlite3.h>
-#include <cassert>
-#include "sqlite_wrapper/sql_database.h"
-
-namespace policy {
-namespace dbms {
-
-SQLQuery::SQLQuery(SQLDatabase* db)
- : db_(*db),
- query_(""),
- statement_(NULL),
- error_(SQLITE_OK) {
-}
-
-SQLQuery::~SQLQuery() {
- Finalize();
-}
-
-bool SQLQuery::Prepare(const std::string& query) {
- Finalize();
- sync_primitives::AutoLock auto_lock(statement_lock_);
- if (statement_) return false;
- error_ = sqlite3_prepare(db_.conn(), query.c_str(), query.length(),
- &statement_, NULL);
- query_ = query;
- return error_ == SQLITE_OK;
-}
-
-bool SQLQuery::Exec() {
- error_ = sqlite3_step(statement_);
- return error_ == SQLITE_ROW || error_ == SQLITE_DONE;
-}
-
-bool SQLQuery::Next() {
- error_ = sqlite3_step(statement_);
- return error_ == SQLITE_ROW;
-}
-
-bool SQLQuery::Reset() {
- error_ = sqlite3_reset(statement_);
- return error_ == SQLITE_OK;
-}
-
-void SQLQuery::Finalize() {
- sync_primitives::AutoLock auto_lock(statement_lock_);
- error_ = sqlite3_finalize(statement_);
- if (error_ == SQLITE_OK) {
- statement_ = NULL;
- }
-}
-
-bool SQLQuery::Exec(const std::string& query) {
- query_ = query;
- error_ = sqlite3_exec(db_.conn(), query.c_str(), NULL, NULL, NULL);
- return error_ == SQLITE_OK;
-}
-
-void SQLQuery::Bind(int pos, int value) {
- // In SQLite the number of position for binding starts since 1.
- error_ = sqlite3_bind_int(statement_, pos + 1, value);
-}
-
-void SQLQuery::Bind(int pos, int64_t value) {
- // In SQLite the number of position for binding starts since 1.
- error_ = sqlite3_bind_int64(statement_, pos + 1, value);
-}
-
-void SQLQuery::Bind(int pos, double value) {
- // In SQLite the number of position for binding starts since 1.
- error_ = sqlite3_bind_double(statement_, pos + 1, value);
-}
-
-void SQLQuery::Bind(int pos, bool value) {
- Bind(pos, static_cast<int>(value));
-}
-
-void SQLQuery::Bind(int pos, const std::string& value) {
- // In SQLite the number of position for binding starts since 1.
- error_ = sqlite3_bind_text(statement_, pos + 1, value.c_str(), value.length(),
- SQLITE_TRANSIENT);
-}
-
-bool SQLQuery::GetBoolean(int pos) const {
- return static_cast<bool>(GetInteger(pos));
-}
-
-int SQLQuery::GetInteger(int pos) const {
- return sqlite3_column_int(statement_, pos);
-}
-
-double SQLQuery::GetDouble(int pos) const {
- return sqlite3_column_double(statement_, pos);
-}
-
-std::string SQLQuery::GetString(int pos) const {
- const unsigned char* str = sqlite3_column_text(statement_, pos);
- return str ? reinterpret_cast<const char*>(str) : "";
-}
-
-const std::string& SQLQuery::query() const {
- // TODO(KKolodiy): may return string query with value of arguments
- return query_;
-}
-
-bool SQLQuery::IsNull(int pos) const {
- return sqlite3_column_type(statement_, pos) == SQLITE_NULL;
-}
-
-void SQLQuery::Bind(int pos) {
- // In SQLite the number of position for binding starts since 1.
- error_ = sqlite3_bind_null(statement_, pos + 1);
-}
-
-SQLError SQLQuery::LastError() const {
- return SQLError(Error(error_));
-}
-
-int64_t SQLQuery::LastInsertId() const {
- return sqlite3_last_insert_rowid(db_.conn());
-}
-
-} // namespace dbms
-} // namespace policy
-
diff --git a/src/components/policy/src/policy/src/cache_manager.cc b/src/components/policy/src/policy/src/cache_manager.cc
deleted file mode 100644
index 0481997b50..0000000000
--- a/src/components/policy/src/policy/src/cache_manager.cc
+++ /dev/null
@@ -1,1227 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "policy/cache_manager.h"
-
-#include <algorithm>
-#include <functional>
-#include <ctime>
-#include <cmath>
-
-#include "utils/file_system.h"
-#include "json/reader.h"
-#include "json/features.h"
-#include "json/writer.h"
-#include "utils/logger.h"
-
-#include "policy/sql_pt_representation.h"
-
-namespace policy_table = rpc::policy_table_interface_base;
-
-namespace policy {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "CacheManager")
-
-#define CACHE_MANAGER_CHECK(return_value) \
- { \
- if (!pt_) { \
- LOG4CXX_WARN(logger_, "The cache manager is not initialized"); \
- return return_value; \
- } \
- }
-
-#define CACHE_MANAGER_CHECK_VOID() \
- { \
- if (!pt_) { \
- LOG4CXX_WARN(logger_, "The cache manager is not initialized"); \
- return; \
- } \
- }
-
-struct LanguageFinder {
- LanguageFinder(const std::string &language) : language_(language) {}
- bool operator()(const policy_table::Languages::value_type &lang) const {
- return !strcasecmp(language_.c_str(), lang.first.c_str());
- }
-
-private:
- const std::string &language_;
-};
-
-CacheManager::CacheManager()
- : CacheManagerInterface(), backup_(new SQLPTRepresentation()),
- update_required(false) {
-
- LOG4CXX_AUTO_TRACE(logger_);
- backuper_ = new BackgroundBackuper(this);
- backup_thread_ = threads::CreateThread("Backup thread", backuper_);
- backup_thread_->start();
-}
-
-CacheManager::~CacheManager() {
- LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock lock(backuper_locker_);
- backup_thread_->join();
- delete backup_thread_->delegate();
- threads::DeleteThread(backup_thread_);
-}
-
-bool CacheManager::CanAppKeepContext(const std::string &app_id) {
- CACHE_MANAGER_CHECK(false);
- bool result = true;
- return result;
-}
-
-uint16_t CacheManager::HeartBeatTimeout(const std::string &app_id) const {
- CACHE_MANAGER_CHECK(0);
- uint16_t result = 0;
- if (AppExists(app_id)) {
- if (pt_->policy_table.app_policies_section.apps[app_id]
- .heart_beat_timeout_ms.is_initialized()) {
- result = *(pt_->policy_table.app_policies_section.apps[app_id]
- .heart_beat_timeout_ms);
- }
- }
- return result;
-}
-
-bool CacheManager::CanAppStealFocus(const std::string &app_id) {
- CACHE_MANAGER_CHECK(false);
- bool result = true;
- return result;
-}
-
-bool CacheManager::GetDefaultHMI(const std::string &app_id,
- std::string &default_hmi) {
- CACHE_MANAGER_CHECK(false);
- bool result = true;
- return result;
-}
-
-bool CacheManager::ResetUserConsent() {
- CACHE_MANAGER_CHECK(false);
- sync_primitives::AutoLock lock(cache_lock_);
- return true;
-}
-
-bool CacheManager::GetUserPermissionsForDevice(const std::string &device_id,
- StringArray &consented_groups,
- StringArray &disallowed_groups) {
-
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK(false);
- return true;
-}
-
-void CacheManager::GetAllAppGroups(const std::string &app_id,
- FunctionalGroupIDs &all_group_ids) {
-
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK_VOID();
- if (kDeviceId == app_id) {
- LOG4CXX_INFO(logger_, "Devices doesn't have groups");
- return;
- }
-
- policy_table::ApplicationPolicies::const_iterator app_params_iter =
- pt_->policy_table.app_policies_section.apps.find(app_id);
-
- if (pt_->policy_table.app_policies_section.apps.end() != app_params_iter) {
- policy_table::Strings::const_iterator iter =
- (*app_params_iter).second.groups.begin();
- policy_table::Strings::const_iterator iter_end =
- (*app_params_iter).second.groups.end();
-
- for (; iter != iter_end; ++iter) {
- const uint32_t group_id = static_cast<uint32_t>((GenerateHash(*iter)));
- all_group_ids.push_back(group_id);
- }
- }
-}
-
-void CacheManager::GetPreConsentedGroups(
- const std::string &app_id, FunctionalGroupIDs &preconsented_groups) {
-
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK_VOID();
-}
-
-void CacheManager::GetConsentedGroups(const std::string &device_id,
- const std::string &app_id,
- FunctionalGroupIDs &allowed_groups,
- FunctionalGroupIDs &disallowed_groups) {
-
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK_VOID();
-}
-
-void CacheManager::GetUnconsentedGroups(
- const std::string &device_id, const std::string &policy_app_id,
- FunctionalGroupIDs &unconsented_groups) {
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK_VOID();
-}
-
-void CacheManager::RemoveAppConsentForGroup(const std::string &app_id,
- const std::string &group_name) {
- CACHE_MANAGER_CHECK_VOID();
-}
-
-bool CacheManager::ApplyUpdate(const policy_table::Table &update_pt) {
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK(false);
- sync_primitives::AutoLock auto_lock(cache_lock_);
- pt_->policy_table.functional_groupings =
- update_pt.policy_table.functional_groupings;
-
- policy_table::ApplicationPolicies::const_iterator iter =
- update_pt.policy_table.app_policies_section.apps.begin();
- policy_table::ApplicationPolicies::const_iterator iter_end =
- update_pt.policy_table.app_policies_section.apps.end();
-
- for (; iter != iter_end; ++iter) {
- if (iter->second.is_null()) {
- pt_->policy_table.app_policies_section.apps[iter->first].set_to_null();
- pt_->policy_table.app_policies_section.apps[iter->first].set_to_string(
- "");
- } else if (policy::kDefaultId == (iter->second).get_string()) {
- policy_table::ApplicationPolicies::const_iterator iter_default =
- update_pt.policy_table.app_policies_section.apps.find(kDefaultId);
- if (update_pt.policy_table.app_policies_section.apps.end() ==
- iter_default) {
- LOG4CXX_ERROR(logger_, "The default section was not found in PTU");
- continue;
- }
- pt_->policy_table.app_policies_section.apps[iter->first] =
- iter_default->second;
- } else {
- pt_->policy_table.app_policies_section.apps[iter->first] = iter->second;
- }
- }
-
- pt_->policy_table.app_policies_section.device =
- update_pt.policy_table.app_policies_section.device;
-
- pt_->policy_table.module_config.SafeCopyFrom(
- update_pt.policy_table.module_config);
-
- pt_->policy_table.consumer_friendly_messages.assign_if_valid(
- update_pt.policy_table.consumer_friendly_messages);
-
- ResetCalculatedPermissions();
- Backup();
- return true;
-}
-
-void CacheManager::GetHMIAppTypeAfterUpdate(
- std::map<std::string, StringArray> &app_hmi_types) {
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK_VOID();
- policy_table::ApplicationPolicies::const_iterator policy_iter_begin =
- pt_->policy_table.app_policies_section.apps.begin();
- policy_table::ApplicationPolicies::const_iterator policy_iter_end =
- pt_->policy_table.app_policies_section.apps.end();
- std::vector<std::string> transform_app_hmi_types;
- for (; policy_iter_begin != policy_iter_end; ++policy_iter_begin) {
- const policy_table::ApplicationParams &app_params =
- (*policy_iter_begin).second;
- if (app_params.AppHMIType.is_initialized()) {
- if (!(transform_app_hmi_types.empty())) {
- transform_app_hmi_types.clear();
- }
- std::transform(
- app_params.AppHMIType->begin(), app_params.AppHMIType->end(),
- std::back_inserter(transform_app_hmi_types), AppHMITypeToString());
- app_hmi_types[(*policy_iter_begin).first] = transform_app_hmi_types;
- }
- }
-}
-
-void CacheManager::Backup() {
- sync_primitives::AutoLock lock(backuper_locker_);
- DCHECK(backuper_);
- backuper_->DoBackup();
-}
-
-std::string CacheManager::currentDateTime() {
- time_t now = time(0);
- struct tm tstruct;
- char buf[80];
- tstruct = *localtime(&now);
- // ISO_8601 format is expected, e.g. “2000-01-01T12:18:53Z”
- strftime(buf, sizeof(buf), "%Y-%m-%dT%XZ", &tstruct);
- return buf;
-}
-
-bool CacheManager::GetPermissionsForApp(const std::string &device_id,
- const std::string &app_id,
- FunctionalIdType &group_types) {
-
- LOG4CXX_AUTO_TRACE(logger_);
- GetAllAppGroups(app_id, group_types[kTypeGeneral]);
- GetAllAppGroups(kDefaultId, group_types[kTypeDefault]);
- GetAllAppGroups(kPreDataConsentId, group_types[kTypePreDataConsented]);
- return true;
-}
-
-bool CacheManager::GetDeviceGroupsFromPolicies(
- policy_table::Strings &groups, policy_table::Strings &preconsented_groups) {
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK(false);
- return true;
-}
-
-bool CacheManager::SetDeviceData(
- const std::string &device_id, const std::string &hardware,
- const std::string &firmware, const std::string &os,
- const std::string &os_version, const std::string &carrier,
- const uint32_t number_of_ports, const std::string &connection_type) {
- LOG4CXX_AUTO_TRACE(logger_);
-
- sync_primitives::AutoLock auto_lock(cache_lock_);
- CACHE_MANAGER_CHECK(false);
- Backup();
- return true;
-}
-
-bool CacheManager::SetUserPermissionsForDevice(
- const std::string &device_id, const StringArray &consented_groups,
- const StringArray &disallowed_groups) {
- LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock auto_lock(cache_lock_);
- CACHE_MANAGER_CHECK(false);
- Backup();
- return true;
-}
-
-bool CacheManager::ReactOnUserDevConsentForApp(const std::string &app_id,
- bool is_device_allowed) {
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK(false);
- bool result = true;
- Backup();
- return result;
-}
-
-void CacheManager::GetGroupNameByHashID(const int32_t group_id,
- std::string &group_name) {
-
- CACHE_MANAGER_CHECK_VOID();
- policy_table::FunctionalGroupings::const_iterator fg_iter =
- pt_->policy_table.functional_groupings.begin();
- policy_table::FunctionalGroupings::const_iterator fg_iter_end =
- pt_->policy_table.functional_groupings.end();
-
- for (; fg_iter != fg_iter_end; ++fg_iter) {
- const int32_t id = GenerateHash((*fg_iter).first);
- if (group_id == id) {
- group_name = (*fg_iter).first;
- }
- }
-}
-
-bool CacheManager::SetUserPermissionsForApp(
- const PermissionConsent &permissions) {
- LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock auto_lock(cache_lock_);
- CACHE_MANAGER_CHECK(false);
- Backup();
- return true;
-}
-
-bool CacheManager::UpdateRequired() const { return update_required; }
-
-void CacheManager::SaveUpdateRequired(bool status) {
- update_required = status;
- Backup();
-}
-
-bool CacheManager::IsApplicationRevoked(const std::string &app_id) const {
- CACHE_MANAGER_CHECK(false);
- bool is_revoked = false;
- if (pt_->policy_table.app_policies_section.apps.end() !=
- pt_->policy_table.app_policies_section.apps.find(app_id)) {
- is_revoked = pt_->policy_table.app_policies_section.apps[app_id].is_null();
- }
-
- return is_revoked;
-}
-
-void CacheManager::CheckPermissions(const PTString &app_id,
- const PTString &hmi_level,
- const PTString &rpc,
- CheckPermissionResult &result) {
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK_VOID();
-
- if (pt_->policy_table.app_policies_section.apps.end() ==
- pt_->policy_table.app_policies_section.apps.find(app_id)) {
- LOG4CXX_ERROR(logger_, "Application id " << app_id
- << " was not found in policy DB.");
- return;
- }
-
- policy_table::Strings::const_iterator app_groups_iter =
- pt_->policy_table.app_policies_section.apps[app_id].groups.begin();
-
- policy_table::Strings::const_iterator app_groups_iter_end =
- pt_->policy_table.app_policies_section.apps[app_id].groups.end();
-
- policy_table::FunctionalGroupings::const_iterator concrete_group;
-
- for (; app_groups_iter != app_groups_iter_end; ++app_groups_iter) {
- concrete_group =
- pt_->policy_table.functional_groupings.find(*app_groups_iter);
- if (pt_->policy_table.functional_groupings.end() != concrete_group) {
- const policy_table::Rpcs &rpcs = concrete_group->second;
-
- policy_table::Rpc::const_iterator rpc_iter = rpcs.rpcs.find(rpc);
- if (rpcs.rpcs.end() != rpc_iter) {
- policy_table::RpcParameters rpc_param = rpc_iter->second;
-
- policy_table::HmiLevel hmi_level_e;
- policy_table::EnumFromJsonString(hmi_level, &hmi_level_e);
-
- policy_table::HmiLevels::const_iterator hmi_iter =
- std::find(rpc_param.hmi_levels.begin(), rpc_param.hmi_levels.end(),
- hmi_level_e);
-
- if (rpc_param.hmi_levels.end() != hmi_iter) {
- result.hmi_level_permitted = PermitResult::kRpcAllowed;
-
- policy_table::Parameters::const_iterator params_iter =
- rpc_param.parameters->begin();
- policy_table::Parameters::const_iterator params_iter_end =
- rpc_param.parameters->end();
-
- for (; params_iter != params_iter_end; ++params_iter) {
- result.list_of_allowed_params.push_back(
- policy_table::EnumToJsonString(*params_iter));
- }
- }
- }
- }
- }
-}
-
-bool CacheManager::IsPTPreloaded() {
- CACHE_MANAGER_CHECK(false);
- return *pt_->policy_table.module_config.preloaded_pt;
-}
-
-int CacheManager::IgnitionCyclesBeforeExchange() {
- CACHE_MANAGER_CHECK(0);
- const uint8_t limit = std::max(
- static_cast<int>(
- pt_->policy_table.module_config.exchange_after_x_ignition_cycles),
- 0);
- LOG4CXX_DEBUG(logger_, "IgnitionCyclesBeforeExchange limit:" << limit);
- uint8_t current = 0;
-
- return std::max(limit - current, 0);
-}
-
-int CacheManager::KilometersBeforeExchange(int current) {
- CACHE_MANAGER_CHECK(0);
- const int limit =
- std::max(static_cast<int>(
- pt_->policy_table.module_config.exchange_after_x_kilometers),
- 0);
- LOG4CXX_DEBUG(logger_, "KilometersBeforeExchange limit:" << limit);
- int last = 0;
-
- const int actual = std::max((current - last), 0);
- LOG4CXX_DEBUG(logger_, "KilometersBeforeExchange actual:" << actual);
- return std::max(limit - actual, 0);
-}
-
-bool CacheManager::SetCountersPassedForSuccessfulUpdate(int kilometers,
- int days_after_epoch) {
- CACHE_MANAGER_CHECK(false);
- Backup();
- return true;
-}
-
-int CacheManager::DaysBeforeExchange(int current) {
- CACHE_MANAGER_CHECK(0);
- const uint8_t limit = std::max(
- static_cast<int>(pt_->policy_table.module_config.exchange_after_x_days),
- 0);
- LOG4CXX_DEBUG(logger_, "DaysBeforeExchange limit:" << limit);
- uint8_t last = 0;
-
- const uint8_t actaul = std::max((current - last), 0);
- LOG4CXX_DEBUG(logger_, "DaysBeforeExchange actual:" << actaul);
- return std::max(limit - actaul, 0);
-}
-
-void CacheManager::IncrementIgnitionCycles() {
- CACHE_MANAGER_CHECK_VOID();
- Backup();
-}
-
-void CacheManager::ResetIgnitionCycles() {
- CACHE_MANAGER_CHECK_VOID();
- Backup();
-}
-
-int CacheManager::TimeoutResponse() {
- CACHE_MANAGER_CHECK(0);
- return pt_->policy_table.module_config.timeout_after_x_seconds;
-}
-
-bool CacheManager::SecondsBetweenRetries(std::vector<int> &seconds) {
- CACHE_MANAGER_CHECK(false);
- rpc::policy_table_interface_base::SecondsBetweenRetries::iterator iter =
- pt_->policy_table.module_config.seconds_between_retries.begin();
- rpc::policy_table_interface_base::SecondsBetweenRetries::iterator iter_end =
- pt_->policy_table.module_config.seconds_between_retries.end();
-
- const std::size_t size =
- pt_->policy_table.module_config.seconds_between_retries.size();
- seconds.reserve(size);
- for (; iter != iter_end; ++iter) {
- seconds.push_back(*iter);
- }
- return true;
-}
-
-VehicleData CacheManager::GetVehicleData() {
- // TODO(AGaliuzov): maybe should be removed.
- return VehicleData();
-}
-
-std::vector<UserFriendlyMessage>
-CacheManager::GetUserFriendlyMsg(const std::vector<std::string> &msg_codes,
- const std::string &language) {
-
- LOG4CXX_AUTO_TRACE(logger_);
- std::vector<UserFriendlyMessage> result;
- CACHE_MANAGER_CHECK(result);
-
- std::vector<std::string>::const_iterator it = msg_codes.begin();
- std::vector<std::string>::const_iterator it_end = msg_codes.end();
- for (; it != it_end; ++it) {
-
- policy_table::MessageLanguages msg_languages =
- (*pt_->policy_table.consumer_friendly_messages->messages)[*it];
-
- policy_table::MessageString message_string;
-
- // If message has no records with required language, fallback language
- // should be used instead.
- LanguageFinder finder(language);
- policy_table::Languages::const_iterator it_language = std::find_if(
- msg_languages.languages.begin(), msg_languages.languages.end(), finder);
-
- if (msg_languages.languages.end() == it_language) {
- LOG4CXX_WARN(logger_,
- "Language "
- << language
- << " haven't been found for message code: " << *it);
-
- LanguageFinder fallback_language_finder("en-us");
-
- policy_table::Languages::const_iterator it_fallback_language =
- std::find_if(msg_languages.languages.begin(),
- msg_languages.languages.end(), fallback_language_finder);
-
- if (msg_languages.languages.end() == it_fallback_language) {
- LOG4CXX_ERROR(logger_,
- "No fallback language found for message code: " << *it);
- continue;
- }
-
- message_string = it_fallback_language->second;
- } else {
- message_string = it_language->second;
- }
-
- UserFriendlyMessage msg;
- msg.message_code = *it;
- result.push_back(msg);
- }
- return result;
-}
-
-void CacheManager::GetServiceUrls(const std::string &service_type,
- EndpointUrls &end_points) {
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK_VOID();
- std::string search_value;
- if (!IsNumberService(service_type, search_value)) {
- search_value = service_type;
- }
-
- LOG4CXX_DEBUG(logger_, "Search service value is: " << search_value);
-
- policy_table::ServiceEndpoints::const_iterator iter =
- pt_->policy_table.module_config.endpoints.find(search_value);
-
- if (pt_->policy_table.module_config.endpoints.end() != iter) {
- policy_table::URLList::const_iterator url_list_iter =
- (*iter).second.begin();
- policy_table::URLList::const_iterator url_list_iter_end =
- (*iter).second.end();
- for (; url_list_iter != url_list_iter_end; ++url_list_iter) {
- EndpointData data;
- data.app_id = (*url_list_iter).first;
- std::copy((*url_list_iter).second.begin(), (*url_list_iter).second.end(),
- std::back_inserter(data.url));
-
- end_points.push_back(data);
- }
- }
-}
-
-std::string CacheManager::GetLockScreenIconUrl() const {
- if (backup_) {
- return backup_->GetLockScreenIconUrl();
- }
- return std::string("");
-}
-
-int CacheManager::GetNotificationsNumber(const std::string &priority) {
- CACHE_MANAGER_CHECK(0);
- typedef rpc::policy_table_interface_base::NumberOfNotificationsPerMinute NNPM;
-
- const NNPM &nnpm =
- pt_->policy_table.module_config.notifications_per_minute_by_priority;
-
- NNPM::const_iterator priority_iter = nnpm.find(priority);
-
- const int result =
- (nnpm.end() != priority_iter ? (*priority_iter).second : 0);
- return result;
-}
-
-bool CacheManager::GetPriority(const std::string &policy_app_id,
- std::string &priority) {
- CACHE_MANAGER_CHECK(false);
- if (kDeviceId == policy_app_id) {
- priority = EnumToJsonString(
- pt_->policy_table.app_policies_section.device.priority);
- return true;
- }
-
- const policy_table::ApplicationPolicies &policies =
- pt_->policy_table.app_policies_section.apps;
-
- policy_table::ApplicationPolicies::const_iterator policy_iter =
- policies.find(policy_app_id);
- const bool app_id_exists = policies.end() != policy_iter;
- if (app_id_exists) {
- priority = EnumToJsonString((*policy_iter).second.priority);
- }
-
- return app_id_exists;
-}
-
-void CacheManager::CheckSnapshotInitialization() {
- CACHE_MANAGER_CHECK_VOID();
- if (!snapshot_) {
- LOG4CXX_ERROR(logger_, "Snapshot pointer is not initialized");
- return;
- }
-
- *(snapshot_->policy_table.module_config.preloaded_pt) = false;
-}
-
-void CacheManager::PersistData() {
- LOG4CXX_AUTO_TRACE(logger_);
- if (backup_.valid()) {
- if (pt_.valid()) {
-
- cache_lock_.Acquire();
- policy_table::Table copy_pt(*pt_);
- cache_lock_.Release();
-
- backup_->Save(copy_pt);
- backup_->SaveUpdateRequired(update_required);
-
- policy_table::ApplicationPolicies::const_iterator app_policy_iter =
- copy_pt.policy_table.app_policies_section.apps.begin();
- policy_table::ApplicationPolicies::const_iterator app_policy_iter_end =
- copy_pt.policy_table.app_policies_section.apps.end();
-
- bool is_revoked = false;
- bool is_default_policy;
- bool is_predata_policy;
-
- for (; app_policy_iter != app_policy_iter_end; ++app_policy_iter) {
-
- const std::string app_id = (*app_policy_iter).first;
-
- if (copy_pt.policy_table.app_policies_section.apps.end() !=
- copy_pt.policy_table.app_policies_section.apps.find(app_id)) {
- is_revoked =
- copy_pt.policy_table.app_policies_section.apps[app_id].is_null();
- }
-
- is_default_policy =
- copy_pt.policy_table.app_policies_section.apps.end() !=
- copy_pt.policy_table.app_policies_section.apps.find(app_id) &&
- policy::kDefaultId ==
- copy_pt.policy_table.app_policies_section.apps[app_id]
- .get_string();
-
- // TODO(AOleynik): Remove this field from DB
- is_predata_policy =
- copy_pt.policy_table.app_policies_section.apps.end() !=
- copy_pt.policy_table.app_policies_section.apps.find(app_id) &&
- policy::kPreDataConsentId ==
- copy_pt.policy_table.app_policies_section.apps[app_id]
- .get_string();
-
- backup_->SaveApplicationCustomData(
- app_id, is_revoked, is_default_policy, is_predata_policy);
- is_revoked = false;
- }
-
- // In case of extended policy the meta info should be backuped as well.
- backup_->WriteDb();
- }
- }
-}
-
-void CacheManager::ResetCalculatedPermissions() {
- LOG4CXX_TRACE(logger_, "ResetCalculatedPermissions");
- sync_primitives::AutoLock lock(calculated_permissions_lock_);
- calculated_permissions_.clear();
-}
-
-void CacheManager::AddCalculatedPermissions(const std::string &device_id,
- const std::string &policy_app_id,
- const Permissions &permissions) {
- LOG4CXX_DEBUG(logger_, "AddCalculatedPermissions for device: "
- << device_id << " and app: " << policy_app_id);
- sync_primitives::AutoLock lock(calculated_permissions_lock_);
- calculated_permissions_[device_id][policy_app_id] = permissions;
-}
-
-bool CacheManager::IsPermissionsCalculated(const std::string &device_id,
- const std::string &policy_app_id,
- Permissions &permission) {
- LOG4CXX_DEBUG(logger_, "IsPermissionsCalculated for device: "
- << device_id << " and app: " << policy_app_id);
- sync_primitives::AutoLock lock(calculated_permissions_lock_);
- CalculatedPermissions::const_iterator it =
- calculated_permissions_.find(device_id);
-
- if (calculated_permissions_.end() == it) {
- return false;
- }
-
- AppCalculatedPermissions::const_iterator app_it =
- (*it).second.find(policy_app_id);
- if ((*it).second.end() == app_it) {
- return false;
- } else {
- permission = (*app_it).second;
- return true;
- }
- return false;
-}
-
-bool policy::CacheManager::IsNumberService(const std::string &input,
- std::string &output) const {
- const char *input_value = input.c_str();
- char *endptr;
- const int base = 10;
- errno = 0;
- uint32_t service_value = strtoul(input_value, &endptr, base);
- bool is_real_zero_value =
- (!service_value && endptr != input_value && *endptr == '\0');
- if (!is_real_zero_value && (!service_value || errno == ERANGE)) {
- return false;
- }
-
- output = input;
- if (service_value <= 9) {
- output.insert(0, "0x0", 3);
- } else {
- output.insert(0, "0x", 2);
- }
-
- return true;
-}
-
-utils::SharedPtr<policy_table::Table> CacheManager::GenerateSnapshot() {
- CACHE_MANAGER_CHECK(snapshot_);
- sync_primitives::AutoLock lock(cache_lock_);
-
- snapshot_ = new policy_table::Table();
-
- //Copy all members of policy table except messages in consumer friendly messages
- snapshot_->policy_table.app_policies_section = pt_->policy_table.app_policies_section;
- snapshot_->policy_table.functional_groupings = pt_->policy_table.functional_groupings;
- snapshot_->policy_table.consumer_friendly_messages->version = pt_->policy_table.consumer_friendly_messages->version;
- snapshot_->policy_table.consumer_friendly_messages->mark_initialized();
- snapshot_->policy_table.module_config = pt_->policy_table.module_config;
- snapshot_->policy_table.module_meta = pt_->policy_table.module_meta;
- snapshot_->policy_table.usage_and_error_counts = pt_->policy_table.usage_and_error_counts;
- snapshot_->policy_table.device_data = pt_->policy_table.device_data;
-
- //Set policy table type to Snapshot
- snapshot_->SetPolicyTableType(rpc::policy_table_interface_base::PolicyTableType::PT_SNAPSHOT);
-
- CheckSnapshotInitialization();
- return snapshot_;
-}
-
-bool CacheManager::GetInitialAppData(const std::string &app_id,
- StringArray &nicknames,
- StringArray &app_hmi_types) {
-
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK(false);
- policy_table::ApplicationPolicies::const_iterator policy_iter =
- pt_->policy_table.app_policies_section.apps.find(app_id);
-
- if (pt_->policy_table.app_policies_section.apps.end() != policy_iter) {
- const policy_table::ApplicationParams &app_params = (*policy_iter).second;
-
- std::copy(app_params.nicknames->begin(), app_params.nicknames->end(),
- std::back_inserter(nicknames));
-
- std::transform(app_params.AppHMIType->begin(), app_params.AppHMIType->end(),
- std::back_inserter(app_hmi_types), AppHMITypeToString());
- }
- return true;
-}
-
-bool CacheManager::GetFunctionalGroupings(
- policy_table::FunctionalGroupings &groups) {
-
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK(false);
- const policy_table::FunctionalGroupings &f_groupings =
- pt_->policy_table.functional_groupings;
-
- groups.insert(f_groupings.begin(), f_groupings.end());
- return true;
-}
-
-int CacheManager::CountUnconsentedGroups(const std::string &policy_app_id,
- const std::string &device_id) {
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK(false);
- LOG4CXX_DEBUG(logger_, "Application id: " << policy_app_id);
- int result = 0;
- return result;
-}
-
-bool CacheManager::SetMetaInfo(const std::string &ccpu_version,
- const std::string &wers_country_code,
- const std::string &language) {
- CACHE_MANAGER_CHECK(false);
-
- // We have to set preloaded flag as false in policy table on any response
- // of GetSystemInfo (SDLAQ-CRS-2365)
- *pt_->policy_table.module_config.preloaded_pt = false;
-
- Backup();
- return true;
-}
-
-bool CacheManager::IsMetaInfoPresent() const {
- CACHE_MANAGER_CHECK(false);
- bool result = true;
- return result;
-}
-
-bool CacheManager::SetSystemLanguage(const std::string &language) {
- CACHE_MANAGER_CHECK(false);
- Backup();
- return true;
-}
-
-bool CacheManager::GetFunctionalGroupNames(FunctionalGroupNames &names) {
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK(false);
- rpc::policy_table_interface_base::FunctionalGroupings::iterator iter =
- pt_->policy_table.functional_groupings.begin();
- rpc::policy_table_interface_base::FunctionalGroupings::iterator iter_end =
- pt_->policy_table.functional_groupings.end();
-
- for (; iter != iter_end; ++iter) {
- const int32_t id = GenerateHash((*iter).first);
- std::pair<std::string, std::string> value =
- std::make_pair(*(*iter).second.user_consent_prompt, (*iter).first);
-
- names.insert(
- std::pair<uint32_t, std::pair<std::string, std::string>>(id, value));
- }
- return true;
-}
-
-bool CacheManager::CleanupUnpairedDevices() {
- CACHE_MANAGER_CHECK(false);
- Backup();
- return true;
-}
-
-void CacheManager::Increment(usage_statistics::GlobalCounterId type) {
- CACHE_MANAGER_CHECK_VOID();
- Backup();
-}
-
-void CacheManager::Increment(const std::string &app_id,
- usage_statistics::AppCounterId type) {
- CACHE_MANAGER_CHECK_VOID();
- Backup();
-}
-
-void CacheManager::Set(const std::string &app_id,
- usage_statistics::AppInfoId type,
- const std::string &value) {
- CACHE_MANAGER_CHECK_VOID();
- Backup();
-}
-
-void CacheManager::Add(const std::string &app_id,
- usage_statistics::AppStopwatchId type, int seconds) {
- CACHE_MANAGER_CHECK_VOID();
- Backup();
-}
-
-long CacheManager::ConvertSecondsToMinute(int seconds) {
- const float seconds_in_minute = 60.0;
- return std::round(seconds / seconds_in_minute);
-}
-
-bool CacheManager::SetDefaultPolicy(const std::string &app_id) {
- CACHE_MANAGER_CHECK(false);
- policy_table::ApplicationPolicies::const_iterator iter =
- pt_->policy_table.app_policies_section.apps.find(kDefaultId);
- if (pt_->policy_table.app_policies_section.apps.end() != iter) {
- pt_->policy_table.app_policies_section.apps[app_id] =
- pt_->policy_table.app_policies_section.apps[kDefaultId];
-
- SetIsDefault(app_id);
- }
- Backup();
- return true;
-}
-
-bool CacheManager::IsDefaultPolicy(const std::string &app_id) {
- CACHE_MANAGER_CHECK(false);
- const bool result =
- pt_->policy_table.app_policies_section.apps.end() !=
- pt_->policy_table.app_policies_section.apps.find(app_id) &&
- policy::kDefaultId ==
- pt_->policy_table.app_policies_section.apps[app_id].get_string();
-
- return result;
-}
-
-bool CacheManager::SetIsDefault(const std::string &app_id) {
- CACHE_MANAGER_CHECK(false);
- policy_table::ApplicationPolicies::const_iterator iter =
- pt_->policy_table.app_policies_section.apps.find(app_id);
- if (pt_->policy_table.app_policies_section.apps.end() != iter) {
- pt_->policy_table.app_policies_section.apps[app_id].set_to_string(
- kDefaultId);
- }
- return true;
-}
-
-bool CacheManager::SetPredataPolicy(const std::string &app_id) {
- CACHE_MANAGER_CHECK(false);
- policy_table::ApplicationPolicies::const_iterator iter =
- pt_->policy_table.app_policies_section.apps.find(kPreDataConsentId);
-
- if (pt_->policy_table.app_policies_section.apps.end() == iter) {
- LOG4CXX_ERROR(logger_, "Could not set " << kPreDataConsentId
- << " permissions for app "
- << app_id);
- return false;
- }
-
- pt_->policy_table.app_policies_section.apps[app_id] =
- pt_->policy_table.app_policies_section.apps[kPreDataConsentId];
-
- pt_->policy_table.app_policies_section.apps[app_id].set_to_string(
- kPreDataConsentId);
-
- Backup();
- return true;
-}
-
-bool CacheManager::IsPredataPolicy(const std::string &app_id) {
- // TODO(AOleynik): Maybe change for comparison with pre_DataConsent
- // permissions or check string value from get_string()
- policy_table::ApplicationParams &pre_data_app =
- pt_->policy_table.app_policies_section.apps[kPreDataConsentId];
- policy_table::ApplicationParams &specific_app =
- pt_->policy_table.app_policies_section.apps[app_id];
-
- policy_table::Strings res;
- std::set_intersection(pre_data_app.groups.begin(), pre_data_app.groups.end(),
- specific_app.groups.begin(), specific_app.groups.end(),
- std::back_inserter(res));
-
- bool is_marked_as_predata =
- kPreDataConsentId ==
- pt_->policy_table.app_policies_section.apps[app_id].get_string();
-
- return !res.empty() && is_marked_as_predata;
-}
-
-bool CacheManager::SetUnpairedDevice(const std::string &device_id,
- bool unpaired) {
- const bool result = pt_->policy_table.device_data->end() !=
- pt_->policy_table.device_data->find(device_id);
- if (!result) {
- LOG4CXX_DEBUG(logger_, "Couldn't set unpaired flag for device id "
- << device_id << " , since it wasn't found.");
- return false;
- }
-
- sync_primitives::AutoLock lock(unpaired_lock_);
- if (unpaired) {
- is_unpaired_.insert(device_id);
- LOG4CXX_DEBUG(logger_, "Unpaired flag was set for device id " << device_id);
- } else {
- is_unpaired_.erase(device_id);
- LOG4CXX_DEBUG(logger_, "Unpaired flag was removed for device id "
- << device_id);
- }
- return result;
-}
-
-bool CacheManager::SetVINValue(const std::string &value) {
- CACHE_MANAGER_CHECK(false);
- Backup();
- return true;
-}
-
-bool CacheManager::IsApplicationRepresented(const std::string &app_id) const {
- CACHE_MANAGER_CHECK(false);
- if (kDeviceId == app_id) {
- return true;
- }
- policy_table::ApplicationPolicies::const_iterator iter =
- pt_->policy_table.app_policies_section.apps.find(app_id);
- return pt_->policy_table.app_policies_section.apps.end() != iter;
-}
-
-bool CacheManager::Init(const std::string &file_name) {
- LOG4CXX_AUTO_TRACE(logger_);
-
- InitResult init_result = backup_->Init();
-
- bool result = true;
- switch (init_result) {
- case InitResult::EXISTS: {
- LOG4CXX_INFO(logger_, "Policy Table exists, was loaded correctly.");
- result = LoadFromBackup();
- } break;
- case InitResult::SUCCESS: {
- LOG4CXX_INFO(logger_, "Policy Table was inited successfully");
- result = LoadFromFile(file_name);
-
- utils::SharedPtr<policy_table::Table> snapshot = GenerateSnapshot();
- result &= snapshot->is_valid();
- LOG4CXX_DEBUG(logger_, "Check if snapshot is valid: " << std::boolalpha
- << result);
- if (!result) {
- rpc::ValidationReport report("policy_table");
- snapshot->ReportErrors(&report);
- }
-
- } break;
- default: {
- result = false;
- LOG4CXX_ERROR(logger_, "Failed to init policy table.");
- } break;
- }
-
- return result;
-}
-
-void CacheManager::FillDeviceSpecificData() {}
-
-bool CacheManager::LoadFromBackup() {
- sync_primitives::AutoLock lock(cache_lock_);
- pt_ = backup_->GenerateSnapshot();
- update_required = backup_->UpdateRequired();
-
- FillDeviceSpecificData();
-
- return true;
-}
-
-bool CacheManager::LoadFromFile(const std::string &file_name) {
- LOG4CXX_AUTO_TRACE(logger_);
- BinaryMessage json_string;
- if (!file_system::ReadBinaryFile(file_name, json_string)) {
- LOG4CXX_FATAL(logger_, "Failed to read pt file.");
- return false;
- }
-
- Json::Value value;
- Json::Reader reader(Json::Features::strictMode());
- std::string json(json_string.begin(), json_string.end());
- if (!reader.parse(json.c_str(), value)) {
- LOG4CXX_FATAL(logger_, "Preloaded PT is corrupted: "
- << reader.getFormattedErrorMessages());
- return false;
- }
-
- LOG4CXX_TRACE(logger_, "Start create PT");
- sync_primitives::AutoLock locker(cache_lock_);
- backup_->Clear();
-
- pt_ = new policy_table::Table(&value);
- if (pt_->is_valid()) {
- if (backup_->Save(*pt_)) {
- backup_->WriteDb();
- return true;
- } else {
- LOG4CXX_FATAL(logger_, "Failed to save PT");
- return false;
- }
- } else {
- rpc::ValidationReport report("policy_table");
- pt_->ReportErrors(&report);
- LOG4CXX_FATAL(logger_, "Parsed table is not valid "
- << rpc::PrettyFormat(report));
- return false;
- }
-}
-
-bool CacheManager::ResetPT(const std::string &file_name) {
- bool result = true;
- Backup();
- return result;
-}
-
-bool CacheManager::AppExists(const std::string &app_id) const {
- CACHE_MANAGER_CHECK(false);
- if (kDeviceId == app_id) {
- return true;
- }
- policy_table::ApplicationPolicies::iterator policy_iter =
- pt_->policy_table.app_policies_section.apps.find(app_id);
- return pt_->policy_table.app_policies_section.apps.end() != policy_iter;
-}
-
-int32_t CacheManager::GenerateHash(const std::string &str_to_hash) {
-
- uint32_t hash = 5381U;
- std::string::const_iterator it = str_to_hash.begin();
- std::string::const_iterator it_end = str_to_hash.end();
-
- for (; it != it_end; ++it) {
- hash = ((hash << 5) + hash) + (*it);
- }
-
- // Reset sign bit in case it has been set.
- // This is needed to avoid overflow for signed int.
- const int32_t result = hash & 0x7FFFFFFF;
- return result;
-}
-
-void CacheManager::GetAppRequestTypes(
- const std::string &policy_app_id,
- std::vector<std::string> &request_types) const {
- LOG4CXX_AUTO_TRACE(logger_);
- CACHE_MANAGER_CHECK_VOID();
- policy_table::ApplicationPolicies::iterator policy_iter =
- pt_->policy_table.app_policies_section.apps.find(policy_app_id);
- if (pt_->policy_table.app_policies_section.apps.end() == policy_iter) {
- LOG4CXX_DEBUG(logger_, "Can't find request types for app_id "
- << policy_app_id);
- return;
- }
- policy_table::RequestTypes::iterator it_request_type =
- policy_iter->second.RequestType->begin();
- for (; it_request_type != policy_iter->second.RequestType->end();
- ++it_request_type) {
- request_types.push_back(EnumToJsonString(*it_request_type));
- }
- return;
-}
-
-CacheManager::BackgroundBackuper::BackgroundBackuper(
- CacheManager *cache_manager)
- : cache_manager_(cache_manager), stop_flag_(false),
- new_data_available_(false) {
- LOG4CXX_AUTO_TRACE(logger_);
-}
-
-CacheManager::BackgroundBackuper::~BackgroundBackuper() {
- LOG4CXX_AUTO_TRACE(logger_);
-}
-
-void CacheManager::BackgroundBackuper::InternalBackup() {
- LOG4CXX_AUTO_TRACE(logger_);
- DCHECK(cache_manager_);
-
- while (new_data_available_) {
- new_data_available_ = false;
- LOG4CXX_DEBUG(logger_, "DoBackup");
- cache_manager_->PersistData();
- }
-}
-
-void CacheManager::BackgroundBackuper::threadMain() {
- LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock lock(need_backup_lock_);
- while (!stop_flag_) {
- need_backup_lock_.Release();
- InternalBackup();
- need_backup_lock_.Acquire();
- if (new_data_available_ || stop_flag_) {
- continue;
- }
- LOG4CXX_DEBUG(logger_, "Wait for a next backup");
- backup_notifier_.Wait(need_backup_lock_);
- }
-}
-
-void CacheManager::BackgroundBackuper::exitThreadMain() {
- LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock auto_lock(need_backup_lock_);
- stop_flag_ = true;
- backup_notifier_.NotifyOne();
-}
-
-void CacheManager::BackgroundBackuper::DoBackup() {
- LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock auto_lock(need_backup_lock_);
- new_data_available_ = true;
- backup_notifier_.NotifyOne();
-}
-
-} // namespace policy
diff --git a/src/components/policy/src/policy/src/policy_helper.cc b/src/components/policy/src/policy/src/policy_helper.cc
deleted file mode 100644
index 5a32f6f5ff..0000000000
--- a/src/components/policy/src/policy/src/policy_helper.cc
+++ /dev/null
@@ -1,796 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <algorithm>
-#include <sstream>
-#include <string.h>
-#include "utils/logger.h"
-#include "policy/policy_helper.h"
-#include "policy/policy_manager_impl.h"
-
-namespace policy {
-
-namespace {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "PolicyManagerImpl")
-
-bool Compare(const StringsValueType& first, const StringsValueType& second) {
- const std::string& first_str = first;
- const std::string& second_str = second;
- return (strcasecmp(first_str.c_str(), second_str.c_str()) < 0);
-}
-
-struct CheckGroupName {
- CheckGroupName(const policy::StringsValueType& value)
- : value_(value) {
- }
-
- bool operator()(const FunctionalGroupNames::value_type& value) {
- return value.second.second == std::string(value_);
- }
-
-private:
- const policy::StringsValueType& value_;
-};
-
-struct CopyAttributes{
- CopyAttributes(const FunctionalGroupNames& groups_attributes,
- std::vector<FunctionalGroupPermission>& groups_permissions)
- : groups_attributes_(groups_attributes),
- groups_permissions_(groups_permissions) {
- }
-
-bool operator()(const policy::StringsValueType& value) {
- CheckGroupName checker(value);
- FunctionalGroupNames::const_iterator it =
- std::find_if(groups_attributes_.begin(), groups_attributes_.end(),
- checker);
- if (groups_attributes_.end() == it) {
- return false;
- }
- FunctionalGroupPermission group;
- group.group_name = it->second.second;
- group.group_alias = it->second.first;
- group.group_id = it->first;
- groups_permissions_.push_back(group);
- return true;
-}
-
-private:
- const FunctionalGroupNames& groups_attributes_;
- std::vector<FunctionalGroupPermission>& groups_permissions_;
-};
-} // namespace
-
-CompareGroupName::CompareGroupName(const StringsValueType& group_name)
- : group_name_(group_name) {
-}
-
-bool CompareGroupName::operator()(
- const StringsValueType& group_name_to_compare) const {
- const std::string gn_ = group_name_;
- const std::string gn_compare = group_name_to_compare;
- return !(strcasecmp(gn_.c_str(), gn_compare.c_str()));
-}
-
-bool operator!=(const policy_table::ApplicationParams& first,
- const policy_table::ApplicationParams& second) {
- if (first.groups.size() != second.groups.size()) {
- return true;
- }
- StringsConstItr it_first = first.groups.begin();
- StringsConstItr it_first_end = first.groups.end();
- StringsConstItr it_second = second.groups.begin();
- StringsConstItr it_second_end = second.groups.end();
- for (; it_first != it_first_end; ++it_first) {
- CompareGroupName gp(*it_first);
- StringsConstItr it = std::find_if(it_second, it_second_end, gp);
- if (it_first_end == it) {
- return true;
- }
- }
- return false;
-}
-
-CheckAppPolicy::CheckAppPolicy(
- PolicyManagerImpl* pm,
- const utils::SharedPtr<policy_table::Table> update,
- const utils::SharedPtr<policy_table::Table> snapshot)
- : pm_(pm),
- update_(update),
- snapshot_(snapshot) {
-}
-
-bool policy::CheckAppPolicy::HasRevokedGroups(
- const policy::AppPoliciesValueType& app_policy,
- policy_table::Strings* revoked_groups) const {
- AppPoliciesConstItr it =
- snapshot_->policy_table.app_policies_section.apps.find(app_policy.first);
-
- policy_table::Strings groups_new = app_policy.second.groups;
- std::sort(groups_new.begin(), groups_new.end(), Compare);
-
- policy_table::Strings groups_curr = (*it).second.groups;
- std::sort(groups_curr.begin(), groups_curr.end(), Compare);
-
- StringsConstItr it_groups_new = groups_new.begin();
- StringsConstItr it_groups_new_end = groups_new.end();
-
- StringsConstItr it_groups_curr = groups_curr.begin();
- StringsConstItr it_groups_curr_end = groups_curr.end();
-
- policy_table::Strings revoked_group_list;
- std::set_difference(it_groups_curr, it_groups_curr_end,
- it_groups_new, it_groups_new_end,
- std::back_inserter(revoked_group_list), Compare);
-
- // Remove groups which are not required user consent
- policy_table::Strings::iterator it_revoked = revoked_group_list.begin();
- for (;revoked_group_list.end() != it_revoked; ) {
- if (!IsConsentRequired(app_policy.first, std::string(*it_revoked))) {
- revoked_group_list.erase(it_revoked);
- it_revoked = revoked_group_list.begin();
- } else {
- ++it_revoked;
- }
- }
-
- if (revoked_groups) {
- *revoked_groups = revoked_group_list;
- }
-
- return !revoked_group_list.empty();
-}
-
-bool policy::CheckAppPolicy::HasNewGroups(
- const policy::AppPoliciesValueType& app_policy,
- policy_table::Strings* new_groups) const {
- AppPoliciesConstItr it =
- snapshot_->policy_table.app_policies_section.apps.find(app_policy.first);
-
- policy_table::Strings groups_new = app_policy.second.groups;
- std::sort(groups_new.begin(), groups_new.end(), Compare);
-
- policy_table::Strings groups_curr = (*it).second.groups;
- std::sort(groups_curr.begin(), groups_curr.end(), Compare);
-
- StringsConstItr it_groups_new = groups_new.begin();
- StringsConstItr it_groups_new_end = groups_new.end();
-
- StringsConstItr it_groups_curr = groups_curr.begin();
- StringsConstItr it_groups_curr_end = groups_curr.end();
-
- policy_table::Strings new_group_list;
- std::set_difference(it_groups_new, it_groups_new_end,
- it_groups_curr, it_groups_curr_end,
- std::back_inserter(new_group_list), Compare);
-
- if (new_groups) {
- *new_groups = new_group_list;
- }
-
- return !new_group_list.empty();
-}
-
-bool policy::CheckAppPolicy::HasConsentNeededGroups(
- const policy::AppPoliciesValueType& app_policy) const {
- policy_table::Strings new_groups;
- if (!HasNewGroups(app_policy, &new_groups)) {
- return false;
- }
-
- StringsConstItr it_new = new_groups.begin();
- StringsConstItr it_new_end = new_groups.end();
- for (; it_new != it_new_end; ++it_new) {
- if (IsConsentRequired(app_policy.first, *it_new)) {
- return true;
- }
- }
-
- return false;
-}
-
-std::vector<FunctionalGroupPermission>
-policy::CheckAppPolicy::GetRevokedGroups(
- const policy::AppPoliciesValueType& app_policy) const {
- policy_table::Strings revoked_groups_names;
- if (!HasRevokedGroups(app_policy, &revoked_groups_names)) {
- return std::vector<FunctionalGroupPermission>();
- }
-
- FunctionalGroupNames groups_attributes;
- if (!pm_->cache_->GetFunctionalGroupNames(groups_attributes)) {
- LOG4CXX_WARN(logger_, "Can't get functional group names");
- return std::vector<FunctionalGroupPermission>();
- }
-
- std::vector<FunctionalGroupPermission> revoked_groups_permissions;
- CopyAttributes copier(groups_attributes, revoked_groups_permissions);
- std::for_each(revoked_groups_names.begin(), revoked_groups_names.end(),
- copier);
-
- return revoked_groups_permissions;
-}
-
-void policy::CheckAppPolicy::RemoveRevokedConsents(
- const AppPoliciesValueType& app_policy,
- const std::vector<FunctionalGroupPermission>& revoked_groups) const {
- std::vector<policy::FunctionalGroupPermission>::const_iterator it =
- revoked_groups.begin();
- std::vector<policy::FunctionalGroupPermission>::const_iterator it_end =
- revoked_groups.end();
- for (;it != it_end; ++it) {
- pm_->RemoveAppConsentForGroup(app_policy.first, it->group_name);
- }
-}
-
-bool CheckAppPolicy::IsKnownAppication(
- const std::string& application_id) const {
- const policy_table::ApplicationPolicies& current_policies =
- snapshot_->policy_table.app_policies_section.apps;
-
- return !(current_policies.end() == current_policies.find(application_id));
-}
-
-void policy::CheckAppPolicy::NotifySystem(
- const policy::AppPoliciesValueType& app_policy) const {
- pm_->listener()->OnPendingPermissionChange(app_policy.first);
-}
-
-void CheckAppPolicy::SendPermissionsToApp(
- const AppPoliciesValueType& app_policy) const {
- const std::string app_id = app_policy.first;
-
- const std::string device_id = pm_->GetCurrentDeviceId(app_id);
- if (device_id.empty()) {
- LOG4CXX_WARN(logger_, "Couldn't find device info for application id: "
- << app_id);
- return;
- }
- std::vector<FunctionalGroupPermission> group_permissons;
- pm_->GetPermissionsForApp(device_id, app_id, group_permissons);
-
- Permissions notification_data;
- pm_->PrepareNotificationData(update_->policy_table.functional_groupings,
- app_policy.second.groups,
- group_permissons, notification_data);
-
- LOG4CXX_INFO(logger_, "Send notification for application_id: " << app_id);
- // Default_hmi is Ford-specific and should not be used with basic policy
- const std::string default_hmi;
- pm_->listener()->OnPermissionsUpdated(app_id, notification_data, default_hmi);
-}
-
-bool CheckAppPolicy::IsAppRevoked(
- const AppPoliciesValueType& app_policy) const {
- LOG4CXX_AUTO_TRACE(logger_);
- // Application params are not initialized = application revoked
- // i.e. "123":null
- return app_policy.second.is_null();
-}
-
-bool CheckAppPolicy::NicknamesMatch(
- const AppPoliciesValueType& app_policy) const {
- const std::string& app_id = app_policy.first;
- std::string app_name = pm_->listener()->GetAppName(app_id);
- if (!app_name.empty() &&
- app_policy.second.nicknames &&
- !app_policy.second.nicknames->empty()) {
- for (policy_table::Strings::const_iterator it =
- app_policy.second.nicknames->begin();
- app_policy.second.nicknames->end() != it; ++it) {
- std::string temp = *it;
- if (!strcasecmp(temp.c_str(), app_name.c_str())) {
- return true;
- }
- }
- return false;
- }
- return true;
-}
-
-bool CheckAppPolicy::operator()(const AppPoliciesValueType& app_policy) {
- const std::string app_id = app_policy.first;
-
- if (!IsKnownAppication(app_id)) {
- LOG4CXX_WARN(logger_, "Application:" << app_id <<
- " is not present in snapshot.");
- return true;
- }
-
- if (!IsPredefinedApp(app_policy) && IsAppRevoked(app_policy)) {
- SetPendingPermissions(app_policy, RESULT_APP_REVOKED);
- NotifySystem(app_policy);
- return true;
- }
-
- if (!IsPredefinedApp(app_policy) && !NicknamesMatch(app_policy)) {
- SetPendingPermissions(app_policy, RESULT_NICKNAME_MISMATCH);
- NotifySystem(app_policy);
- return true;
- }
-
- PermissionsCheckResult result = CheckPermissionsChanges(app_policy);
- if (!IsPredefinedApp(app_policy) && IsRequestTypeChanged(app_policy)) {
- SetPendingPermissions(app_policy, RESULT_REQUEST_TYPE_CHANGED);
- NotifySystem(app_policy);
- }
- if (RESULT_NO_CHANGES == result) {
- LOG4CXX_INFO(logger_, "Permissions for application:" << app_id <<
- " wasn't changed.");
- return true;
- }
-
- LOG4CXX_INFO(logger_, "Permissions for application:" << app_id <<
- " have been changed.");
-
- if (!IsPredefinedApp(app_policy) && RESULT_CONSENT_NOT_REQIURED != result) {
- SetPendingPermissions(app_policy, result);
- NotifySystem(app_policy);
- }
-
- // Don't sent notification for predefined apps (e.g. default, device etc.)
- if (!IsPredefinedApp(app_policy)) {
- SendPermissionsToApp(app_policy);
- }
- return true;
-}
-
-void policy::CheckAppPolicy::SetPendingPermissions(
- const AppPoliciesValueType& app_policy,
- PermissionsCheckResult result) const {
- const std::string app_id = app_policy.first;
- AppPermissions permissions_diff(app_id);
- permissions_diff.priority = policy_table::EnumToJsonString(
- app_policy.second.priority);
-
- switch (result) {
- case RESULT_APP_REVOKED:
- permissions_diff.appRevoked = true;
- break;
- case RESULT_NICKNAME_MISMATCH:
- permissions_diff.appUnauthorized = true;
- break;
- case RESULT_PERMISSIONS_REVOKED:
- permissions_diff.isAppPermissionsRevoked = true;
- permissions_diff.appRevokedPermissions = GetRevokedGroups(app_policy);
- RemoveRevokedConsents(app_policy, permissions_diff.appRevokedPermissions);
- break;
- case RESULT_CONSENT_NEEDED:
- permissions_diff.appPermissionsConsentNeeded = true;
- break;
- case RESULT_PERMISSIONS_REVOKED_AND_CONSENT_NEEDED:
- permissions_diff.isAppPermissionsRevoked = true;
- permissions_diff.appPermissionsConsentNeeded = true;
- permissions_diff.appRevokedPermissions = GetRevokedGroups(app_policy);
- RemoveRevokedConsents(app_policy, permissions_diff.appRevokedPermissions);
- break;
- case RESULT_REQUEST_TYPE_CHANGED:
- permissions_diff.priority.clear();
- permissions_diff.requestTypeChanged = true;
- {
- // Getting RequestTypes from PTU (not from cache)
- policy_table::RequestTypes::const_iterator it_request_type =
- app_policy.second.RequestType->begin();
- for (; app_policy.second.RequestType->end() != it_request_type;
- ++it_request_type) {
- permissions_diff.requestType.push_back(EnumToJsonString(*it_request_type));
- }
- }
-
- break;
- default:
- return;
- }
- pm_->app_permissions_diff_lock_.Acquire();
- pm_->app_permissions_diff_.insert(std::make_pair(app_id, permissions_diff));
- pm_->app_permissions_diff_lock_.Release();
-}
-
-policy::CheckAppPolicy::PermissionsCheckResult
-policy::CheckAppPolicy::CheckPermissionsChanges(
- const policy::AppPoliciesValueType& app_policy) const {
-
- bool has_revoked_groups = HasRevokedGroups(app_policy);
-
- bool has_consent_needed_groups = HasConsentNeededGroups(app_policy);
-
- bool has_new_groups = HasNewGroups(app_policy);
-
- if (has_revoked_groups && has_consent_needed_groups) {
- return RESULT_PERMISSIONS_REVOKED_AND_CONSENT_NEEDED;
- } else if (has_revoked_groups) {
- return RESULT_PERMISSIONS_REVOKED;
- } else if (has_consent_needed_groups) {
- return RESULT_CONSENT_NEEDED;
- } else if (has_new_groups) {
- return RESULT_CONSENT_NOT_REQIURED;
- }
-
- return RESULT_NO_CHANGES;
-}
-
-bool CheckAppPolicy::IsConsentRequired(const std::string& app_id,
- const std::string& group_name) const {
- const policy_table::FunctionalGroupings& functional_groupings =
- snapshot_->policy_table.functional_groupings;
-
- FuncGroupConstItr it = functional_groupings.find(group_name);
-
- if (functional_groupings.end() == it) {
- return false;
- }
-
- bool is_preconsented = false;
- return it->second.user_consent_prompt.is_initialized() && !is_preconsented;
-}
-
-bool CheckAppPolicy::IsRequestTypeChanged(
- const AppPoliciesValueType& app_policy) const {
- policy::AppPoliciesConstItr it =
- snapshot_->policy_table.app_policies_section.apps.find(app_policy.first);
- if (it == snapshot_->policy_table.app_policies_section.apps.end()) {
- if (!app_policy.second.RequestType->empty()) {
- return true;
- }
- return false;
- }
- if (it->second.RequestType->size() != app_policy.second.RequestType->size()) {
- return true;
- }
- policy_table::RequestTypes diff;
- std::set_difference(it->second.RequestType->begin(),
- it->second.RequestType->end(),
- app_policy.second.RequestType->begin(),
- app_policy.second.RequestType->end(),
- std::back_inserter(diff));
- return diff.size();
-}
-
-FillNotificationData::FillNotificationData(Permissions& data,
- GroupConsent group_state, GroupConsent undefined_group_consent)
- : data_(data) {
- switch (group_state) {
- case kGroupAllowed:
- current_key_ = kAllowedKey;
- break;
- case kGroupUndefined:
- if (kGroupUndefined == undefined_group_consent) {
- current_key_ = kUndefinedKey;
- break;
- }
- current_key_ = kGroupAllowed == undefined_group_consent?
- kAllowedKey:
- kUserDisallowedKey;
- break;
- default:
- current_key_ = kUserDisallowedKey;
- break;
- }
-}
-
-bool FillNotificationData::operator()(const RpcValueType& rpc) {
- Permissions::iterator it = data_.find(rpc.first);
- // If rpc is present already - update its permissions
- if (data_.end() != it) {
- UpdateHMILevels(rpc.second.hmi_levels,
- (*it).second.hmi_permissions[current_key_]);
- // TODO(IKozyrenko): Check logic if optional container is missing
- UpdateParameters(*rpc.second.parameters,
- (*it).second.parameter_permissions[current_key_]);
- ExcludeSame();
- } else {
- // Init mandatory keys, since they should be present irrespectively of
- // values presence
- InitRpcKeys(rpc.first);
- // If rpc is not present - add its permissions
- UpdateHMILevels(rpc.second.hmi_levels,
- data_[rpc.first].hmi_permissions[current_key_]);
- // TODO(IKozyrenko): Check logic if optional container is missing
- UpdateParameters(*rpc.second.parameters,
- data_[rpc.first].parameter_permissions[current_key_]);
- ExcludeSame();
- }
- return true;
-}
-
-void FillNotificationData::UpdateHMILevels(
- const policy_table::HmiLevels& in_hmi, std::set<HMILevel>& out_hmi) {
- HMILevelsConstItr it_hmi_levels = in_hmi.begin();
- HMILevelsConstItr it_hmi_levels_end = in_hmi.end();
-
- for (; it_hmi_levels != it_hmi_levels_end; ++it_hmi_levels) {
- out_hmi.insert(policy_table::EnumToJsonString(*it_hmi_levels));
- }
-}
-
-void FillNotificationData::UpdateParameters(
- const policy_table::Parameters& in_parameters,
- std::set<Parameter>& out_parameter) {
- ParametersConstItr it_parameters = in_parameters.begin();
- ParametersConstItr it_parameters_end = in_parameters.end();
-
- for (; it_parameters != it_parameters_end; ++it_parameters) {
- out_parameter.insert(policy_table::EnumToJsonString(*it_parameters));
- }
-}
-
-void FillNotificationData::ExcludeSame() {
- Permissions::iterator it = data_.begin();
- Permissions::const_iterator it_end = data_.end();
- // Groups
- for (; it != it_end; ++it) {
- HMIPermissions& rpc_hmi_permissions = (*it).second.hmi_permissions;
- HMIPermissions::const_iterator it_hmi_allowed =
- (*it).second.hmi_permissions.find(kAllowedKey);
- HMIPermissions::const_iterator it_hmi_undefined =
- (*it).second.hmi_permissions.find(kUndefinedKey);
- HMIPermissions::const_iterator it_hmi_user_disallowed =
- (*it).second.hmi_permissions.find(kUserDisallowedKey);
-
- ParameterPermissions& rpc_parameter_permissions =
- (*it).second.parameter_permissions;
- ParameterPermissions::const_iterator it_parameter_allowed =
- (*it).second.parameter_permissions.find(kAllowedKey);
- ParameterPermissions::const_iterator it_parameter_undefined =
- (*it).second.parameter_permissions.find(kUndefinedKey);
- ParameterPermissions::const_iterator it_parameter_user_disallowed =
- (*it).second.parameter_permissions.find(kUserDisallowedKey);
-
- // First, remove disallowed from other types
- if (rpc_hmi_permissions.end() != it_hmi_user_disallowed) {
- if (rpc_hmi_permissions.end() != it_hmi_allowed) {
- ExcludeSameHMILevels(rpc_hmi_permissions[kAllowedKey],
- rpc_hmi_permissions[kUserDisallowedKey]);
- }
- if (rpc_hmi_permissions.end() != it_hmi_undefined) {
- ExcludeSameHMILevels(rpc_hmi_permissions[kUndefinedKey],
- rpc_hmi_permissions[kUserDisallowedKey]);
- }
- }
-
- if (rpc_parameter_permissions.end() != it_parameter_user_disallowed) {
- if (rpc_parameter_permissions.end() != it_parameter_allowed) {
- ExcludeSameParameters(rpc_parameter_permissions[kAllowedKey],
- rpc_parameter_permissions[kUserDisallowedKey]);
- }
- if (rpc_parameter_permissions.end() != it_parameter_undefined) {
- ExcludeSameParameters(rpc_parameter_permissions[kUndefinedKey],
- rpc_parameter_permissions[kUserDisallowedKey]);
- }
- }
-
- // Then, remove undefined from allowed
- if (rpc_hmi_permissions.end() != it_hmi_undefined) {
- if (rpc_hmi_permissions.end() != it_hmi_allowed) {
- ExcludeSameHMILevels(rpc_hmi_permissions[kAllowedKey],
- rpc_hmi_permissions[kUndefinedKey]);
- }
- }
-
- if (rpc_parameter_permissions.end() != it_parameter_undefined) {
- if (rpc_parameter_permissions.end() != it_parameter_allowed) {
- ExcludeSameParameters(rpc_parameter_permissions[kAllowedKey],
- rpc_parameter_permissions[kUndefinedKey]);
- }
- }
- }
-}
-
-void FillNotificationData::ExcludeSameHMILevels(
- std::set<HMILevel>& source,
- const std::set<HMILevel>& target) {
- std::set<HMILevel> diff_hmi;
-
- std::set_difference(source.begin(), source.end(),
- target.begin(), target.end(),
- std::inserter(diff_hmi, diff_hmi.begin()));
-
- source = diff_hmi;
-}
-
-void FillNotificationData::ExcludeSameParameters(
- std::set<Parameter>& source,
- const std::set<Parameter>& target) {
- std::set<Parameter> diff_parameter;
-
- std::set_difference(source.begin(), source.end(),
- target.begin(), target.end(),
- std::inserter(diff_parameter, diff_parameter.begin()));
-
- source = diff_parameter;
-}
-
-void FillNotificationData::InitRpcKeys(const std::string& rpc_name) {
- data_[rpc_name].hmi_permissions[kAllowedKey];
- data_[rpc_name].hmi_permissions[kUserDisallowedKey];
- data_[rpc_name].parameter_permissions[kAllowedKey];
- data_[rpc_name].parameter_permissions[kUserDisallowedKey];
-}
-
-ProcessFunctionalGroup::ProcessFunctionalGroup(
- const policy_table::FunctionalGroupings& fg,
- const std::vector<FunctionalGroupPermission>& group_permissions,
- Permissions& data,
- GroupConsent undefined_group_consent)
- : fg_(fg),
- group_permissions_(group_permissions),
- data_(data),
- undefined_group_consent_(undefined_group_consent) {
-}
-
-bool ProcessFunctionalGroup::operator()(const StringsValueType& group_name) {
- const std::string group_name_str = group_name;
- FuncGroupConstItr it = fg_.find(group_name_str);
-
- if (fg_.end() != it) {
- const policy_table::Rpc& rpcs = (*it).second.rpcs;
- FillNotificationData filler(data_, GetGroupState(group_name_str),
- undefined_group_consent_);
- std::for_each(rpcs.begin(), rpcs.end(), filler);
- }
- return true;
-}
-
-GroupConsent ProcessFunctionalGroup::GetGroupState(
- const std::string& group_name) {
- std::vector<FunctionalGroupPermission>::const_iterator it =
- group_permissions_.begin();
- std::vector<FunctionalGroupPermission>::const_iterator it_end =
- group_permissions_.end();
- for (; it != it_end; ++it) {
- if (group_name == (*it).group_name) {
- return (*it).state;
- }
- }
- return kGroupUndefined;
-}
-
-FunctionalGroupInserter::FunctionalGroupInserter(
- const policy_table::Strings& preconsented_groups, PermissionsList& list)
- : list_(list),
- preconsented_(preconsented_groups) {
-}
-
-void FunctionalGroupInserter::operator()(const StringsValueType& group_name) {
- CompareGroupName name(group_name);
- if (std::find_if(preconsented_.begin(), preconsented_.end(), name)
- == preconsented_.end()) {
- list_.push_back(group_name);
- }
-}
-
-void FillFunctionalGroupPermissions(
- FunctionalGroupIDs& ids,
- FunctionalGroupNames& names,
- GroupConsent state,
- std::vector<FunctionalGroupPermission>& permissions) {
- LOG4CXX_INFO(logger_, "FillFunctionalGroupPermissions" );
- FunctionalGroupIDs::const_iterator it = ids.begin();
- FunctionalGroupIDs::const_iterator it_end = ids.end();
- for (; it != it_end; ++it) {
- FunctionalGroupPermission current_group;
- current_group.group_id = *it;
- current_group.group_alias = names[*it].first;
- current_group.group_name = names[*it].second;
- current_group.state = state;
- permissions.push_back(current_group);
- }
-}
-
-bool IsPredefinedApp(const AppPoliciesValueType& app) {
- return app.first == kDefaultId || app.first == kPreDataConsentId ||
- app.first == kDeviceId;
-}
-
-FunctionalGroupIDs ExcludeSame(const FunctionalGroupIDs& from,
- const FunctionalGroupIDs& what) {
- LOG4CXX_INFO(logger_, "Exclude same groups" );
- FunctionalGroupIDs from_copy(from);
- FunctionalGroupIDs what_copy(what);
-
- std::sort(from_copy.begin(), from_copy.end());
- std::sort(what_copy.begin(), what_copy.end());
-
- FunctionalGroupIDs no_same;
- std::set_difference(from_copy.begin(), from_copy.end(),
- what_copy.begin(),what_copy.end(),
- std::back_inserter(no_same));
-
- no_same.resize(std::distance(no_same.begin(),
- std::unique(no_same.begin(), no_same.end())));
-
- return no_same;
-}
-
-FunctionalGroupIDs Merge(const FunctionalGroupIDs& first,
- const FunctionalGroupIDs& second) {
- LOG4CXX_INFO(logger_, "Merge groups" );
- FunctionalGroupIDs first_copy(first);
- FunctionalGroupIDs second_copy(second);
-
- std::sort(first_copy.begin(), first_copy.end());
- std::sort(second_copy.begin(), second_copy.end());
-
- FunctionalGroupIDs merged;
- std::set_union(first_copy.begin(), first_copy.end(),
- second_copy.begin(), second_copy.end(),
- std::back_inserter(merged));
-
- merged.resize(std::distance(merged.begin(),
- std::unique(merged.begin(), merged.end())));
-
- return merged;
-}
-
-FunctionalGroupIDs FindSame(const FunctionalGroupIDs& first,
- const FunctionalGroupIDs& second) {
- LOG4CXX_INFO(logger_, "Find same groups");
- FunctionalGroupIDs first_copy(first);
- FunctionalGroupIDs second_copy(second);
-
- std::sort(first_copy.begin(), first_copy.end());
- std::sort(second_copy.begin(), second_copy.end());
-
- FunctionalGroupIDs same;
- std::set_intersection(first_copy.begin(), first_copy.end(),
- second_copy.begin(), second_copy.end(),
- std::back_inserter(same));
-
- same.resize(std::distance(same.begin(),
- std::unique(same.begin(), same.end())));
-
- return same;
-}
-
-bool UnwrapAppPolicies(policy_table::ApplicationPolicies& app_policies) {
- policy_table::ApplicationPolicies::iterator it = app_policies.begin();
- policy_table::ApplicationPolicies::iterator it_default = app_policies.
- find(kDefaultId);
- for (; app_policies.end() != it; ++it) {
- // Set default policies for app, if there is record like "123":"default"
- if (kDefaultId.compare((*it).second.get_string()) == 0) {
- if (it != app_policies.end()) {
- (*it).second = (*it_default).second;
- it->second.set_to_string(kDefaultId);
- } else {
- LOG4CXX_ERROR(logger_, "There is no default application policy was "
- "found in PTU.");
- return false;
- }
- }
- }
-
- return true;
-}
-
-}
diff --git a/src/components/policy/src/policy/src/policy_manager_impl.cc b/src/components/policy/src/policy/src/policy_manager_impl.cc
deleted file mode 100644
index 0e73a465d8..0000000000
--- a/src/components/policy/src/policy/src/policy_manager_impl.cc
+++ /dev/null
@@ -1,959 +0,0 @@
-/*
- Copyright (c) 2016, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-#include "policy/policy_manager_impl.h"
-
-#include <algorithm>
-#include <set>
-#include <queue>
-#include <iterator>
-#include "json/reader.h"
-#include "json/writer.h"
-#include "policy/policy_table.h"
-#include "policy/pt_representation.h"
-#include "policy/policy_helper.h"
-#include "utils/file_system.h"
-#include "utils/logger.h"
-#include "utils/date_time.h"
-#include "utils/make_shared.h"
-#include "policy/cache_manager.h"
-#include "policy/update_status_manager.h"
-#include "config_profile/profile.h"
-
-policy::PolicyManager *CreateManager() {
- return new policy::PolicyManagerImpl();
-}
-
-namespace {
-const uint32_t kDefaultRetryTimeoutInSec = 60u;
-} // namespace
-
-namespace policy {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "PolicyManagerImpl")
-
-PolicyManagerImpl::PolicyManagerImpl()
- : PolicyManager(), listener_(NULL), cache_(new CacheManager),
- retry_sequence_timeout_(kDefaultRetryTimeoutInSec),
- retry_sequence_index_(0),
- timer_retry_sequence_("Retry sequence timer", this,
- &PolicyManagerImpl::RetrySequence),
- ignition_check(true) {}
-
-void PolicyManagerImpl::set_listener(PolicyListener *listener) {
- listener_ = listener;
- update_status_manager_.set_listener(listener);
-}
-
-#ifdef USE_HMI_PTU_DECRYPTION
-
-utils::SharedPtr<policy_table::Table>
-PolicyManagerImpl::Parse(const BinaryMessage &pt_content) {
- std::string json(pt_content.begin(), pt_content.end());
- Json::Value value;
- Json::Reader reader;
- if (reader.parse(json.c_str(), value)) {
- return new policy_table::Table(&value);
- } else {
- return utils::SharedPtr<policy_table::Table>();
- }
-}
-
-#else
-
-utils::SharedPtr<policy_table::Table>
-PolicyManagerImpl::ParseArray(const BinaryMessage &pt_content) {
- std::string json(pt_content.begin(), pt_content.end());
- Json::Value value;
- Json::Reader reader;
- if (reader.parse(json.c_str(), value)) {
- // For PT Update received from SDL Server.
- if (value["data"].size() != 0) {
- Json::Value data = value["data"];
- // First Element in
- return new policy_table::Table(&data[0]);
- } else {
- return new policy_table::Table(&value);
- }
- } else {
- return utils::SharedPtr<policy_table::Table>();
- }
-}
-
-#endif
-
-void PolicyManagerImpl::CheckTriggers() {
- LOG4CXX_AUTO_TRACE(logger_);
- const bool exceed_ignition_cycles = ExceededIgnitionCycles();
- const bool exceed_days = ExceededDays();
-
- LOG4CXX_DEBUG(logger_, "\nDays exceeded: "
- << std::boolalpha << exceed_ignition_cycles
- << "\nStatusUpdateRequired: " << std::boolalpha
- << exceed_days);
-
- if (exceed_ignition_cycles || exceed_days) {
- update_status_manager_.ScheduleUpdate();
- }
-}
-
-bool PolicyManagerImpl::LoadPT(const std::string &file,
- const BinaryMessage &pt_content) {
- LOG4CXX_INFO(logger_, "LoadPT of size " << pt_content.size());
-
-#ifdef USE_HMI_PTU_DECRYPTION
- // Assuemes Policy Table was parsed, formatted, and/or decrypted by
- // the HMI after system request before calling OnReceivedPolicyUpdate
- // Parse message into table struct
- utils::SharedPtr<policy_table::Table> pt_update = Parse(pt_content);
-#else
- // Message Received from server unecnrypted with PTU in first element
- // of 'data' array. No Parsing was done by HMI.
- utils::SharedPtr<policy_table::Table> pt_update = ParseArray(pt_content);
-#endif
- if (!pt_update) {
- LOG4CXX_WARN(logger_, "Parsed table pointer is 0.");
- update_status_manager_.OnWrongUpdateReceived();
- return false;
- }
-
- if (!IsPTValid(pt_update, policy_table::PT_UPDATE)) {
- update_status_manager_.OnWrongUpdateReceived();
- return false;
- }
-
- update_status_manager_.OnValidUpdateReceived();
- cache_->SaveUpdateRequired(false);
-
- // Update finished, no need retry
- if (timer_retry_sequence_.isRunning()) {
- LOG4CXX_INFO(logger_, "Stop retry sequence");
- timer_retry_sequence_.stop();
- }
-
- apps_registration_lock_.Acquire();
-
- // Get current DB data, since it could be updated during awaiting of PTU
- utils::SharedPtr<policy_table::Table> policy_table_snapshot =
- cache_->GenerateSnapshot();
- if (!policy_table_snapshot) {
- LOG4CXX_ERROR(logger_, "Failed to create snapshot of policy table");
- return false;
- }
-
- // Checking of difference between PTU and current policy state
- // Must to be done before PTU applying since it is possible, that functional
- // groups, which had been present before are absent in PTU and will be
- // removed after update. So in case of revoked groups system has to know
- // names and ids of revoked groups before they will be removed.
- CheckPermissionsChanges(pt_update, policy_table_snapshot);
-
- // Replace current data with updated
- if (!cache_->ApplyUpdate(*pt_update)) {
- LOG4CXX_WARN(logger_, "Unsuccessful save of updated policy table.");
- return false;
- }
-
- std::map<std::string, StringArray> app_hmi_types;
- cache_->GetHMIAppTypeAfterUpdate(app_hmi_types);
- if (!app_hmi_types.empty()) {
- LOG4CXX_INFO(logger_, "app_hmi_types is full calling OnUpdateHMIAppType");
- listener_->OnUpdateHMIAppType(app_hmi_types);
- } else {
- LOG4CXX_INFO(logger_, "app_hmi_types empty" << pt_content.size());
- }
-
- apps_registration_lock_.Release();
-
- // If there was a user request for policy table update, it should be started
- // right after current update is finished
- if (update_status_manager_.IsUpdateRequired()) {
- StartPTExchange();
- return true;
- }
-
- RefreshRetrySequence();
- return true;
-}
-
-void PolicyManagerImpl::CheckPermissionsChanges(
- const utils::SharedPtr<policy_table::Table> pt_update,
- const utils::SharedPtr<policy_table::Table> snapshot) {
- LOG4CXX_INFO(logger_, "Checking incoming permissions.");
-
- // Replace predefined policies with its actual setting, e.g. "123":"default"
- // to actual values of default section
- UnwrapAppPolicies(pt_update->policy_table.app_policies_section.apps);
-
- std::for_each(pt_update->policy_table.app_policies_section.apps.begin(),
- pt_update->policy_table.app_policies_section.apps.end(),
- CheckAppPolicy(this, pt_update, snapshot));
-}
-
-void PolicyManagerImpl::PrepareNotificationData(
- const policy_table::FunctionalGroupings &groups,
- const policy_table::Strings &group_names,
- const std::vector<FunctionalGroupPermission> &group_permission,
- Permissions &notification_data) {
-
- LOG4CXX_INFO(logger_, "Preparing data for notification.");
- ProcessFunctionalGroup processor(groups, group_permission, notification_data);
- std::for_each(group_names.begin(), group_names.end(), processor);
-}
-
-void PolicyManagerImpl::GetServiceUrls(const std::string &service_type,
- EndpointUrls &end_points) {
- LOG4CXX_AUTO_TRACE(logger_);
- cache_->GetServiceUrls(service_type, end_points);
-}
-
-bool PolicyManagerImpl::RequestPTUpdate() {
- LOG4CXX_AUTO_TRACE(logger_);
- utils::SharedPtr<policy_table::Table> policy_table_snapshot =
- cache_->GenerateSnapshot();
- if (!policy_table_snapshot) {
- LOG4CXX_ERROR(logger_, "Failed to create snapshot of policy table");
- return false;
- }
-
- IsPTValid(policy_table_snapshot, policy_table::PT_SNAPSHOT);
-
- Json::Value value = policy_table_snapshot->ToJsonValue();
- Json::FastWriter writer;
- std::string message_string = writer.write(value);
-
- LOG4CXX_DEBUG(logger_, "Snapshot contents is : " << message_string);
-
- BinaryMessage update(message_string.begin(), message_string.end());
-
- listener_->OnSnapshotCreated(update);
-
- // Need to reset update schedule since all currenly registered applications
- // were already added to the snapshot so no update for them required.
- update_status_manager_.ResetUpdateSchedule();
-
- return true;
-}
-
-std::string PolicyManagerImpl::GetLockScreenIconUrl() const {
- return cache_->GetLockScreenIconUrl();
-}
-
-void PolicyManagerImpl::StartPTExchange() {
- LOG4CXX_AUTO_TRACE(logger_);
-
- const bool update_required = update_status_manager_.IsUpdateRequired();
-
- if (update_status_manager_.IsAppsSearchInProgress() && update_required) {
- update_status_manager_.ScheduleUpdate();
- LOG4CXX_INFO(logger_, "Starting exchange skipped, since applications "
- "search is in progress.");
- return;
- }
-
- if (update_status_manager_.IsUpdatePending() && update_required) {
- update_status_manager_.ScheduleUpdate();
- LOG4CXX_INFO(logger_, "Starting exchange skipped, since another exchange "
- "is in progress.");
- return;
- }
-
- if (listener_ && listener_->CanUpdate()) {
- if (ignition_check) {
- CheckTriggers();
- ignition_check = false;
- }
-
- if (update_required) {
- if (RequestPTUpdate() && !timer_retry_sequence_.isRunning()) {
- LOG4CXX_DEBUG(logger_, "Starting retry sequence.");
- timer_retry_sequence_.start(NextRetryTimeout());
- }
- }
- }
-}
-
-void PolicyManagerImpl::OnAppsSearchStarted() {
- LOG4CXX_AUTO_TRACE(logger_);
- update_status_manager_.OnAppsSearchStarted();
-}
-
-void PolicyManagerImpl::OnAppsSearchCompleted() {
- LOG4CXX_AUTO_TRACE(logger_);
- update_status_manager_.OnAppsSearchCompleted();
- if (update_status_manager_.IsUpdateRequired()) {
- StartPTExchange();
- }
-}
-
-void PolicyManagerImpl::OnAppRegisteredOnMobile(
- const std::string &application_id) {
- StartPTExchange();
- SendNotificationOnPermissionsUpdated(application_id);
-}
-
-const std::vector<std::string>
-PolicyManagerImpl::GetAppRequestTypes(const std::string policy_app_id) const {
- std::vector<std::string> request_types;
- cache_->GetAppRequestTypes(policy_app_id, request_types);
- return request_types;
-}
-void PolicyManagerImpl::CheckPermissions(const PTString &app_id,
- const PTString &hmi_level,
- const PTString &rpc,
- const RPCParams &rpc_params,
- CheckPermissionResult &result) {
- LOG4CXX_INFO(logger_, "CheckPermissions for " << app_id << " and rpc " << rpc
- << " for " << hmi_level
- << " level.");
-
- cache_->CheckPermissions(app_id, hmi_level, rpc, result);
-}
-
-bool PolicyManagerImpl::ResetUserConsent() {
- bool result = true;
-
- return result;
-}
-
-void PolicyManagerImpl::SendNotificationOnPermissionsUpdated(
- const std::string &application_id) {
- LOG4CXX_AUTO_TRACE(logger_);
- const std::string device_id = GetCurrentDeviceId(application_id);
- if (device_id.empty()) {
- LOG4CXX_WARN(logger_, "Couldn't find device info for application id "
- "'" << application_id << "'");
- return;
- }
-
- std::vector<FunctionalGroupPermission> app_group_permissions;
- GetPermissionsForApp(device_id, application_id, app_group_permissions);
-
- policy_table::FunctionalGroupings functional_groupings;
- cache_->GetFunctionalGroupings(functional_groupings);
-
- policy_table::Strings app_groups;
- std::vector<FunctionalGroupPermission>::const_iterator it =
- app_group_permissions.begin();
- std::vector<FunctionalGroupPermission>::const_iterator it_end =
- app_group_permissions.end();
- for (; it != it_end; ++it) {
- app_groups.push_back((*it).group_name);
- }
-
- Permissions notification_data;
- PrepareNotificationData(functional_groupings, app_groups,
- app_group_permissions, notification_data);
-
- LOG4CXX_INFO(logger_,
- "Send notification for application_id:" << application_id);
-
- std::string default_hmi;
- default_hmi = "NONE";
-
- listener()->OnPermissionsUpdated(application_id, notification_data,
- default_hmi);
-}
-
-bool PolicyManagerImpl::CleanupUnpairedDevices() {
- LOG4CXX_INFO(logger_, "CleanupUnpairedDevices");
- // For SDL-specific it doesn't matter
- return true;
-}
-
-DeviceConsent
-PolicyManagerImpl::GetUserConsentForDevice(const std::string &device_id) {
- LOG4CXX_AUTO_TRACE(logger_);
- return kDeviceAllowed;
-}
-
-void PolicyManagerImpl::SetUserConsentForDevice(const std::string &device_id,
- bool is_allowed) {
- LOG4CXX_INFO(logger_, "SetUserConsentForDevice");
- LOG4CXX_DEBUG(logger_, "Device :" << device_id);
- DeviceConsent current_consent = GetUserConsentForDevice(device_id);
- bool is_current_device_allowed =
- DeviceConsent::kDeviceAllowed == current_consent ? true : false;
- if (DeviceConsent::kDeviceHasNoConsent != current_consent &&
- is_current_device_allowed == is_allowed) {
- const std::string consent = is_allowed ? "allowed" : "disallowed";
- LOG4CXX_INFO(logger_, "Device is already " << consent << ".");
- return;
- }
-}
-
-bool PolicyManagerImpl::ReactOnUserDevConsentForApp(const std::string app_id,
- bool is_device_allowed) {
- return true;
-}
-
-bool PolicyManagerImpl::GetInitialAppData(const std::string &application_id,
- StringArray *nicknames,
- StringArray *app_hmi_types) {
- LOG4CXX_INFO(logger_, "GetInitialAppData");
- const bool result = nicknames && app_hmi_types;
- if (result) {
- cache_->GetInitialAppData(application_id, *nicknames, *app_hmi_types);
- }
- return result;
-}
-
-void PolicyManagerImpl::SetDeviceInfo(const std::string &device_id,
- const DeviceInfo &device_info) {
- LOG4CXX_INFO(logger_, "SetDeviceInfo");
- LOG4CXX_DEBUG(logger_, "Device :" << device_id);
-}
-
-PermissionConsent PolicyManagerImpl::EnsureCorrectPermissionConsent(
- const PermissionConsent &permissions_to_check) {
- std::vector<FunctionalGroupPermission> current_user_consents;
- GetUserConsentForApp(permissions_to_check.device_id,
- permissions_to_check.policy_app_id,
- current_user_consents);
-
- PermissionConsent permissions_to_set;
- permissions_to_set.device_id = permissions_to_check.device_id;
- permissions_to_set.policy_app_id = permissions_to_check.policy_app_id;
- permissions_to_set.consent_source = permissions_to_check.consent_source;
-
- std::vector<FunctionalGroupPermission>::const_iterator it =
- permissions_to_check.group_permissions.begin();
- std::vector<FunctionalGroupPermission>::const_iterator it_end =
- permissions_to_check.group_permissions.end();
-
- for (; it != it_end; ++it) {
- std::vector<FunctionalGroupPermission>::const_iterator it_curr =
- current_user_consents.begin();
- std::vector<FunctionalGroupPermission>::const_iterator it_curr_end =
- current_user_consents.end();
-
- for (; it_curr != it_curr_end; ++it_curr) {
- if (it->group_alias == it_curr->group_alias &&
- it->group_id == it_curr->group_id) {
- permissions_to_set.group_permissions.push_back(*it);
- }
- }
- }
-
- return permissions_to_set;
-}
-
-void PolicyManagerImpl::CheckPendingPermissionsChanges(
- const std::string &policy_app_id,
- const std::vector<FunctionalGroupPermission> &current_permissions) {
- LOG4CXX_INFO(logger_, "CheckPendingPermissionsChanges");
- sync_primitives::AutoLock lock(app_permissions_diff_lock_);
- std::map<std::string, AppPermissions>::iterator it_pending =
- app_permissions_diff_.find(policy_app_id);
- if (app_permissions_diff_.end() == it_pending) {
- LOG4CXX_WARN(logger_, "No pending permissions had been found for appID: "
- << policy_app_id);
- return;
- }
-
- LOG4CXX_DEBUG(logger_, "Pending permissions had been found for appID: "
- << policy_app_id);
-
- // Change appPermissionsConsentNeeded depending on unconsented groups
- // presence
- std::vector<policy::FunctionalGroupPermission>::const_iterator it_groups =
- current_permissions.begin();
- std::vector<policy::FunctionalGroupPermission>::const_iterator it_end_groups =
- current_permissions.end();
-
- for (; it_groups != it_end_groups; ++it_groups) {
- if (policy::kGroupUndefined == it_groups->state) {
- LOG4CXX_DEBUG(logger_, "Unconsented groups still present for appID: "
- << policy_app_id);
- it_pending->second.appPermissionsConsentNeeded = true;
- return;
- }
- }
-
- LOG4CXX_DEBUG(logger_, "Unconsented groups not present anymore for appID: "
- << policy_app_id);
- it_pending->second.appPermissionsConsentNeeded = false;
- return;
-}
-
-void PolicyManagerImpl::SetUserConsentForApp(
- const PermissionConsent &permissions) {
- LOG4CXX_INFO(logger_, "SetUserConsentForApp");
-}
-
-bool PolicyManagerImpl::GetDefaultHmi(const std::string &policy_app_id,
- std::string *default_hmi) {
- LOG4CXX_INFO(logger_, "GetDefaultHmi");
- return false;
-}
-
-bool PolicyManagerImpl::GetPriority(const std::string &policy_app_id,
- std::string *priority) {
- LOG4CXX_INFO(logger_, "GetPriority");
- if (!priority) {
- LOG4CXX_WARN(logger_, "Input priority parameter is null.");
- return false;
- }
-
- return cache_->GetPriority(policy_app_id, *priority);
-}
-
-std::vector<UserFriendlyMessage> PolicyManagerImpl::GetUserFriendlyMessages(
- const std::vector<std::string> &message_code, const std::string &language) {
- return cache_->GetUserFriendlyMsg(message_code, language);
-}
-
-void PolicyManagerImpl::GetUserConsentForApp(
- const std::string &device_id, const std::string &policy_app_id,
- std::vector<FunctionalGroupPermission> &permissions) {
- LOG4CXX_INFO(logger_, "GetUserConsentForApp");
-
- FunctionalIdType group_types;
- if (!cache_->GetPermissionsForApp(device_id, policy_app_id, group_types)) {
- LOG4CXX_WARN(logger_, "Can't get user permissions for app "
- << policy_app_id);
- return;
- }
-
- // Functional groups w/o alias ("user_consent_prompt") considered as
- // automatically allowed and it could not be changed by user
- FunctionalGroupNames group_names;
- if (!cache_->GetFunctionalGroupNames(group_names)) {
- LOG4CXX_WARN(logger_, "Can't get functional group names");
- return;
- }
-
- FunctionalGroupNames::const_iterator it = group_names.begin();
- FunctionalGroupNames::const_iterator it_end = group_names.end();
- FunctionalGroupIDs auto_allowed_groups;
- for (; it != it_end; ++it) {
- if (it->second.first.empty()) {
- auto_allowed_groups.push_back(it->first);
- }
- }
-
- // For basic policy
- FunctionalGroupIDs all_groups = group_types[kTypeGeneral];
- FunctionalGroupIDs default_groups = group_types[kTypeDefault];
- FunctionalGroupIDs predataconsented_groups =
- group_types[kTypePreDataConsented];
-
- FunctionalGroupIDs allowed_groups;
- FunctionalGroupIDs no_auto = ExcludeSame(all_groups, auto_allowed_groups);
-
- if (cache_->IsDefaultPolicy(policy_app_id)) {
- allowed_groups = ExcludeSame(no_auto, default_groups);
- } else if (cache_->IsPredataPolicy(policy_app_id)) {
- allowed_groups = ExcludeSame(no_auto, predataconsented_groups);
- }
- FillFunctionalGroupPermissions(allowed_groups, group_names, kGroupAllowed,
- permissions);
-}
-
-void PolicyManagerImpl::GetPermissionsForApp(
- const std::string &device_id, const std::string &policy_app_id,
- std::vector<FunctionalGroupPermission> &permissions) {
- LOG4CXX_INFO(logger_, "GetPermissionsForApp");
- std::string app_id_to_check = policy_app_id;
-
- bool allowed_by_default = false;
- if (cache_->IsDefaultPolicy(policy_app_id)) {
- app_id_to_check = kDefaultId;
- allowed_by_default = true;
- } else if (cache_->IsPredataPolicy(policy_app_id) ||
- policy::kDeviceDisallowed == GetUserConsentForDevice(device_id)) {
- app_id_to_check = kPreDataConsentId;
- allowed_by_default = true;
- }
-
- FunctionalIdType group_types;
- if (!cache_->GetPermissionsForApp(device_id, app_id_to_check, group_types)) {
- LOG4CXX_WARN(logger_, "Can't get user permissions for app "
- << policy_app_id);
- return;
- }
-
- // Functional groups w/o alias ("user_consent_prompt") considered as
- // automatically allowed and it could not be changed by user
- FunctionalGroupNames group_names;
- if (!cache_->GetFunctionalGroupNames(group_names)) {
- LOG4CXX_WARN(logger_, "Can't get functional group names");
- return;
- }
-
- // The "default" and "pre_DataConsent" are auto-allowed groups
- // So, check if application in the one of these mode.
- if (allowed_by_default) {
- LOG4CXX_INFO(logger_, "Get auto allowed groups");
- GroupType type =
- (kDefaultId == app_id_to_check ? kTypeDefault : kTypePreDataConsented);
-
- FillFunctionalGroupPermissions(group_types[type], group_names,
- kGroupAllowed, permissions);
- } else {
-
- // The code bellow allows to process application which
- // has specific permissions(not default and pre_DataConsent).
-
- // All groups for specific application
- FunctionalGroupIDs all_groups = group_types[kTypeGeneral];
-
- // In case of GENIVI all groups are allowed
- FunctionalGroupIDs common_allowed = all_groups;
- FillFunctionalGroupPermissions(common_allowed, group_names, kGroupAllowed,
- permissions);
- }
- return;
-}
-
-std::string &
-PolicyManagerImpl::GetCurrentDeviceId(const std::string &policy_app_id) {
- LOG4CXX_INFO(logger_, "GetDeviceInfo");
- last_device_id_ = listener()->OnCurrentDeviceIdUpdateRequired(policy_app_id);
- return last_device_id_;
-}
-
-void PolicyManagerImpl::SetSystemLanguage(const std::string &language) {}
-
-void PolicyManagerImpl::SetSystemInfo(const std::string &ccpu_version,
- const std::string &wers_country_code,
- const std::string &language) {
- LOG4CXX_INFO(logger_, "SetSystemInfo");
-}
-
-void PolicyManagerImpl::OnSystemReady() {
- // Update policy table for the first time with system information
- if (cache_->IsPTPreloaded()) {
- listener()->OnSystemInfoUpdateRequired();
- return;
- }
-}
-
-uint32_t
-PolicyManagerImpl::GetNotificationsNumber(const std::string &priority) {
- LOG4CXX_INFO(logger_, "GetNotificationsNumber");
- return cache_->GetNotificationsNumber(priority);
-}
-
-bool PolicyManagerImpl::ExceededIgnitionCycles() {
- return 0 == cache_->IgnitionCyclesBeforeExchange();
-}
-
-bool PolicyManagerImpl::IsPTValid(
- utils::SharedPtr<policy_table::Table> policy_table,
- policy_table::PolicyTableType type) const {
- policy_table->SetPolicyTableType(type);
- if (!policy_table->is_valid()) {
- LOG4CXX_ERROR(logger_, "Policy table is not valid.");
- rpc::ValidationReport report("policy_table");
- policy_table->ReportErrors(&report);
- LOG4CXX_DEBUG(logger_, "Errors: " << rpc::PrettyFormat(report));
- return false;
- }
- return true;
-}
-
-bool PolicyManagerImpl::ExceededDays() {
-
- TimevalStruct current_time = date_time::DateTime::getCurrentTime();
- const int kSecondsInDay = 60 * 60 * 24;
- int days = current_time.tv_sec / kSecondsInDay;
-
- return 0 == cache_->DaysBeforeExchange(days);
-}
-
-void PolicyManagerImpl::KmsChanged(int kilometers) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (0 == cache_->KilometersBeforeExchange(kilometers)) {
- LOG4CXX_INFO(logger_, "Enough kilometers passed to send for PT update.");
- update_status_manager_.ScheduleUpdate();
- StartPTExchange();
- }
-}
-
-void PolicyManagerImpl::IncrementIgnitionCycles() {
- cache_->IncrementIgnitionCycles();
-}
-
-std::string PolicyManagerImpl::ForcePTExchange() {
- update_status_manager_.ScheduleUpdate();
- StartPTExchange();
- return update_status_manager_.StringifiedUpdateStatus();
-}
-
-std::string PolicyManagerImpl::GetPolicyTableStatus() const {
- return update_status_manager_.StringifiedUpdateStatus();
-}
-
-uint32_t PolicyManagerImpl::NextRetryTimeout() {
- sync_primitives::AutoLock auto_lock(retry_sequence_lock_);
- LOG4CXX_DEBUG(logger_, "Index: " << retry_sequence_index_);
- uint32_t next = 0u;
- if (retry_sequence_seconds_.empty() ||
- retry_sequence_index_ >= retry_sequence_seconds_.size()) {
- LOG4CXX_WARN(logger_, "Next retry timeout is " << next);
- return next;
- }
-
- ++retry_sequence_index_;
-
- for (uint32_t i = 0u; i < retry_sequence_index_; ++i) {
- next += retry_sequence_seconds_[i];
- LOG4CXX_DEBUG(logger_, "Next retry timeout to add is " << next);
- // According to requirement APPLINK-18244
- }
- next += retry_sequence_timeout_;
- LOG4CXX_DEBUG(logger_, "Total retry timeout is " << next);
- return next;
-}
-
-void PolicyManagerImpl::RefreshRetrySequence() {
- sync_primitives::AutoLock auto_lock(retry_sequence_lock_);
- retry_sequence_timeout_ = cache_->TimeoutResponse();
- retry_sequence_seconds_.clear();
- cache_->SecondsBetweenRetries(retry_sequence_seconds_);
-}
-
-void PolicyManagerImpl::ResetRetrySequence() {
- sync_primitives::AutoLock auto_lock(retry_sequence_lock_);
- retry_sequence_index_ = 0;
- update_status_manager_.OnResetRetrySequence();
-}
-
-int PolicyManagerImpl::TimeoutExchange() { return retry_sequence_timeout_; }
-
-const std::vector<int> PolicyManagerImpl::RetrySequenceDelaysSeconds() {
- sync_primitives::AutoLock auto_lock(retry_sequence_lock_);
- return retry_sequence_seconds_;
-}
-
-void PolicyManagerImpl::OnExceededTimeout() {
- update_status_manager_.OnUpdateTimeoutOccurs();
-}
-
-void PolicyManagerImpl::OnUpdateStarted() {
- int update_timeout = TimeoutExchange();
- LOG4CXX_INFO(logger_, "Update timeout will be set to: " << update_timeout);
- update_status_manager_.OnUpdateSentOut(update_timeout);
- cache_->SaveUpdateRequired(true);
-}
-
-void PolicyManagerImpl::PTUpdatedAt(int kilometers, int days_after_epoch) {
- LOG4CXX_INFO(logger_, "PTUpdatedAt");
- LOG4CXX_INFO(logger_, "Kilometers: " << kilometers
- << " Days: " << days_after_epoch);
- cache_->SetCountersPassedForSuccessfulUpdate(kilometers, days_after_epoch);
- cache_->ResetIgnitionCycles();
-}
-
-void PolicyManagerImpl::Increment(usage_statistics::GlobalCounterId type) {
- LOG4CXX_INFO(logger_, "Increment without app id");
- sync_primitives::AutoLock locker(statistics_lock_);
-}
-
-void PolicyManagerImpl::Increment(const std::string &app_id,
- usage_statistics::AppCounterId type) {
- LOG4CXX_INFO(logger_, "Increment " << app_id);
- sync_primitives::AutoLock locker(statistics_lock_);
-}
-
-void PolicyManagerImpl::Set(const std::string &app_id,
- usage_statistics::AppInfoId type,
- const std::string &value) {
- LOG4CXX_INFO(logger_, "Set " << app_id);
- sync_primitives::AutoLock locker(statistics_lock_);
-}
-
-void PolicyManagerImpl::Add(const std::string &app_id,
- usage_statistics::AppStopwatchId type,
- int32_t timespan_seconds) {
- LOG4CXX_INFO(logger_, "Add " << app_id);
- sync_primitives::AutoLock locker(statistics_lock_);
-}
-
-bool PolicyManagerImpl::IsApplicationRevoked(const std::string &app_id) const {
- return cache_->IsApplicationRevoked(app_id);
-}
-
-bool PolicyManagerImpl::IsConsentNeeded(const std::string &app_id) {
- LOG4CXX_AUTO_TRACE(logger_);
- return false;
-}
-
-void PolicyManagerImpl::SetVINValue(const std::string &value) {}
-
-AppPermissions
-PolicyManagerImpl::GetAppPermissionsChanges(const std::string &policy_app_id) {
- typedef std::map<std::string, AppPermissions>::iterator PermissionsIt;
- PermissionsIt app_id_diff = app_permissions_diff_.find(policy_app_id);
- AppPermissions permissions(policy_app_id);
- if (app_permissions_diff_.end() != app_id_diff) {
- permissions = app_id_diff->second;
- } else {
- permissions.appPermissionsConsentNeeded = IsConsentNeeded(policy_app_id);
- permissions.appRevoked = IsApplicationRevoked(policy_app_id);
- GetPriority(permissions.application_id, &permissions.priority);
- }
- return permissions;
-}
-
-void PolicyManagerImpl::RemovePendingPermissionChanges(
- const std::string &app_id) {
- app_permissions_diff_.erase(app_id);
-}
-
-bool PolicyManagerImpl::CanAppKeepContext(const std::string &app_id) {
- return cache_->CanAppKeepContext(app_id);
-}
-
-bool PolicyManagerImpl::CanAppStealFocus(const std::string &app_id) {
- return cache_->CanAppStealFocus(app_id);
-}
-
-void PolicyManagerImpl::MarkUnpairedDevice(const std::string &device_id) {}
-
-void PolicyManagerImpl::AddApplication(const std::string &application_id) {
- LOG4CXX_INFO(logger_, "AddApplication");
- const std::string device_id = GetCurrentDeviceId(application_id);
- DeviceConsent device_consent = GetUserConsentForDevice(device_id);
- sync_primitives::AutoLock lock(apps_registration_lock_);
-
- if (IsNewApplication(application_id)) {
- AddNewApplication(application_id, device_consent);
- update_status_manager_.OnNewApplicationAdded();
- } else {
- PromoteExistedApplication(application_id, device_consent);
- }
-}
-
-void PolicyManagerImpl::RemoveAppConsentForGroup(
- const std::string &app_id, const std::string &group_name) {
- cache_->RemoveAppConsentForGroup(app_id, group_name);
-}
-
-bool PolicyManagerImpl::IsPredataPolicy(const std::string &policy_app_id) {
- LOG4CXX_INFO(logger_, "IsPredataApp");
- return cache_->IsPredataPolicy(policy_app_id);
-}
-
-void PolicyManagerImpl::AddNewApplication(const std::string &application_id,
- DeviceConsent device_consent) {
- LOG4CXX_AUTO_TRACE(logger_);
-
- cache_->SetDefaultPolicy(application_id);
-}
-
-void PolicyManagerImpl::PromoteExistedApplication(
- const std::string &application_id, DeviceConsent device_consent) {
- // If device consent changed to allowed during application being
- // disconnected, app permissions should be changed also
- if (kDeviceAllowed == device_consent &&
- cache_->IsPredataPolicy(application_id)) {
- cache_->SetDefaultPolicy(application_id);
- }
-}
-
-bool PolicyManagerImpl::IsNewApplication(
- const std::string &application_id) const {
- return false == cache_->IsApplicationRepresented(application_id);
-}
-
-bool PolicyManagerImpl::ResetPT(const std::string &file_name) {
- cache_->ResetCalculatedPermissions();
- const bool result = cache_->ResetPT(file_name);
- if (result) {
- RefreshRetrySequence();
- }
- return result;
-}
-
-bool PolicyManagerImpl::CheckAppStorageFolder() const {
- LOG4CXX_AUTO_TRACE(logger_);
- const std::string app_storage_folder =
- profile::Profile::instance()->app_storage_folder();
- LOG4CXX_DEBUG(logger_, "AppStorageFolder " << app_storage_folder);
- if (!file_system::DirectoryExists(app_storage_folder)) {
- LOG4CXX_WARN(logger_, "Storage directory doesn't exist "
- << app_storage_folder);
- return false;
- }
- if (!(file_system::IsWritingAllowed(app_storage_folder) &&
- file_system::IsReadingAllowed(app_storage_folder))) {
- LOG4CXX_WARN(logger_,
- "Storage directory doesn't have read/write permissions "
- << app_storage_folder);
- return false;
- }
- return true;
-}
-
-bool PolicyManagerImpl::InitPT(const std::string &file_name) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (!CheckAppStorageFolder()) {
- LOG4CXX_ERROR(logger_, "Can not read/write into AppStorageFolder");
- return false;
- }
- const bool ret = cache_->Init(file_name);
- if (ret) {
- RefreshRetrySequence();
- update_status_manager_.OnPolicyInit(cache_->UpdateRequired());
- }
- return ret;
-}
-
-uint16_t PolicyManagerImpl::HeartBeatTimeout(const std::string &app_id) const {
- return cache_->HeartBeatTimeout(app_id);
-}
-
-void PolicyManagerImpl::SaveUpdateStatusRequired(bool is_update_needed) {
- cache_->SaveUpdateRequired(is_update_needed);
-}
-
-void PolicyManagerImpl::set_cache_manager(
- CacheManagerInterface *cache_manager) {
- cache_ = cache_manager;
-}
-
-void PolicyManagerImpl::RetrySequence() {
- LOG4CXX_INFO(logger_, "Start new retry sequence");
- RequestPTUpdate();
-
- uint32_t timeout = NextRetryTimeout();
-
- if (!timeout && timer_retry_sequence_.isRunning()) {
- timer_retry_sequence_.stop();
- return;
- }
-
- timer_retry_sequence_.start(timeout);
-}
-
-} // namespace policy
diff --git a/src/components/policy/src/policy/src/policy_table.cc b/src/components/policy/src/policy/src/policy_table.cc
deleted file mode 100644
index 991f2ee08d..0000000000
--- a/src/components/policy/src/policy/src/policy_table.cc
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "policy/policy_table.h"
-
-# include "policy/sql_pt_representation.h"
-
-#include "utils/logger.h"
-
-namespace policy {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "PolicyTable")
-
-PolicyTable::PolicyTable()
- : pt_data_(
- new SQLPTRepresentation()
- ) {
-}
-
-PolicyTable::PolicyTable(utils::SharedPtr<PTRepresentation> pt_data)
- : pt_data_(pt_data) {
-}
-
-PolicyTable::~PolicyTable() {
- LOG4CXX_INFO(logger_, "Destroying policy table.");
-}
-
-} // namespace policy
diff --git a/src/components/policy/src/policy/src/sql_pt_ext_queries.cc b/src/components/policy/src/policy/src/sql_pt_ext_queries.cc
deleted file mode 100644
index 776b318991..0000000000
--- a/src/components/policy/src/policy/src/sql_pt_ext_queries.cc
+++ /dev/null
@@ -1,247 +0,0 @@
-/*
- Copyright (c) 2013, " Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, " with or without
- modification, " are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, " this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice, "
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, " INCLUDING, " BUT NOT LIMITED TO, " THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, " INDIRECT, " INCIDENTAL, " SPECIAL, " EXEMPLARY, " OR
- CONSEQUENTIAL DAMAGES (INCLUDING, " BUT NOT LIMITED TO, " PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, " DATA, " OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, " WHETHER IN
- CONTRACT, " STRICT LIABILITY, " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, " EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "policy/sql_pt_ext_queries.h"
-
-namespace policy {
-namespace sql_pt_ext {
-
-const std::string kSelectKeepContext =
- "SELECT `keep_context` FROM `application` WHERE `id` = ? LIMIT 1";
-
-const std::string kSelectStealFocus =
- "SELECT `steal_focus` FROM `application` WHERE `id` = ? LIMIT 1";
-
-const std::string kSelectDefaultHmi =
- "SELECT `default_hmi` FROM `application` WHERE `id` = ? LIMIT 1";
-
-const std::string kResetDeviceConsents = "DELETE FROM `device_consent_group`";
-
-const std::string kResetAppConsents = "DELETE FROM `consent_group`";
-
-const std::string kCountDeviceConsentGroup = "SELECT COUNT (`device_id`) "
- "FROM `device_consent_group` WHERE `device_id` = ?";
-
-const std::string kCountDevice = "SELECT COUNT (`id`) "
- "FROM `device` WHERE `id` = ?";
-
-const std::string kSelectDeviceConsentedGroup =
- "SELECT * FROM `device_consent_group` WHERE `device_id` = ?";
-
-const std::string kUpdateDeviceConsentedGroup =
- "UPDATE `device_consent_group` SET `is_consented` = ?, `input` = ? WHERE "
- "(`device_id` = ? AND `functional_group_id` = ?)";
-
-const std::string kUpdateDevice =
- "UPDATE `device` SET `hardware` = ?, `firmware_rev` = ?, `os` = ?, "
- "`os_version` = ?, `carrier` = ?, `max_number_rfcom_ports` = ?, "
- " `connection_type` = ? WHERE `id` = ? ";
-
-const std::string kInsertDeviceConsentedGroup =
- "INSERT OR REPLACE INTO `device_consent_group` "
- "(`device_id`, `functional_group_id`, `is_consented`, `input`, `time_stamp`) "
- "VALUES (?,?,?,?,?)";
-
-const std::string kInsertDevice =
- "INSERT OR IGNORE INTO `device` "
- "(`id`, `hardware`, `firmware_rev`, `os`, `os_version`, `carrier`,"
- "`max_number_rfcom_ports`, `connection_type`) "
- "VALUES (?,?,?,?,?,?,?,?)";
-
-const std::string kSelectDeviceData = "SELECT * FROM `device`";
-
-const std::string kSelectConsentGroup =
- "SELECT * FROM `consent_group` WHERE `device_id` = ? ";
-
-const std::string kInsertPreconsentedGroups =
- "INSERT INTO `preconsented_group` (`application_id`, `functional_group_id`)"
- " SELECT ?, `id` FROM `functional_group` WHERE `name` = ? LIMIT 1";
-
-const std::string kSelectPreconsentedGroups =
- "SELECT `f`.`name` FROM `preconsented_group` AS `p`"
- " LEFT JOIN `functional_group` AS `f` "
- " ON (`f`.`id` = `p`.`functional_group_id`)"
- " WHERE `p`.`application_id` = ?";
-
-const std::string kDeletePreconsentedGroups = "DELETE FROM `preconsented_group`";
-
-const std::string kSelectUsageAndErrorCount =
- "SELECT `count_of_iap_buffer_full`, `count_sync_out_of_memory`, "
- " `count_of_sync_reboots` "
- "FROM `usage_and_error_count` LIMIT 1";
-
-const std::string kSelectAppLevels =
- "SELECT `application_id`, `minutes_in_hmi_full`, `minutes_in_hmi_limited`, "
- " `minutes_in_hmi_background`, `minutes_in_hmi_none`, "
- " `count_of_user_selections`, "
- " `count_of_rejections_sync_out_of_memory`, "
- " `count_of_rejections_nickname_mismatch`, "
- " `count_of_rejections_duplicate_name`, "
- " `count_of_rejected_rpcs_calls`, "
- " `count_of_rpcs_sent_in_hmi_none`, "
- " `count_of_removals_for_bad_behavior`, "
- " `count_of_run_attempts_while_revoked`, "
- " `app_registration_language_gui`, "
- " `app_registration_language_vui` "
- "FROM `app_level`";
-
-const std::string kUpdateGlobalCounters = "UPDATE `usage_and_error_count` SET "
- "`count_of_iap_buffer_full` = ?, "
- "`count_sync_out_of_memory` = ?, "
- "`count_of_sync_reboots` = ? ";
-
-const std::string kInsertDeviceData =
- "INSERT OR IGNORE INTO `device` "
- "(`id`, `hardware`, `firmware_rev`, `os`, `os_version`, `carrier`, "
- "`max_number_rfcom_ports`,`connection_type`) VALUES (?,?,?,?,?,?,?,?) ";
-
-const std::string kInsertConsentGroups =
- "INSERT OR REPLACE INTO `consent_group` "
- "(`device_id`, `application_id`, `functional_group_id`, `is_consented`, `input`, `time_stamp`) "
- "VALUES (?,?,?,?,?,?)";
-
-const std::string kDeleteAppGroupConsent = "DELETE FROM `consent_group` WHERE "
- "`application_id` = ? AND `functional_group_id` = ? ";
-
- const std::string kSelectGroupId =
- "SELECT `id` FROM `functional_group` WHERE `name` = ? ";
-
-const std::string kCountUnconsentedGroups =
- "SELECT COUNT(`a`.`functional_group_id`) FROM `app_group` AS `a` "
- " WHERE `a`.`application_id` = ? AND NOT EXISTS "
- " (SELECT NULL FROM `preconsented_group` AS `p` WHERE "
- " (`p`.`functional_group_id` = `a`.`functional_group_id` AND "
- " `p`.`application_id` = `a`.`application_id`)) "
- " AND NOT EXISTS (SELECT NULL FROM `consent_group` AS `c` "
- " WHERE (`c`.`application_id` = `a`.`application_id` "
- " AND `c`.`functional_group_id` = `a`.`functional_group_id` "
- " AND `c`.`device_id` = ?)) AND NOT EXISTS "
- " (SELECT NULL FROM `app_group` AS `def` WHERE "
- " (`def`.`application_id` = ? OR "
- " `def`.`application_id` = ?) "
- " AND `def`.`functional_group_id` = `a`.`functional_group_id`)"
- " AND NOT EXISTS (SELECT NULL FROM `functional_group` AS `f` "
- " WHERE (`a`.`functional_group_id` = `f`.`id`"
- " AND`f`.`user_consent_prompt` IS NULL))";
-
-const std::string kSelectModuleMeta = "SELECT* FROM `module_meta`";
-
-const std::string kUpdateMetaParams = "UPDATE `module_meta` SET "
- "`ccpu_version` = ?, `wers_country_code` = ?, `language` = ? ";
-
-const std::string kUpdateModuleMetaVinParam =
- "UPDATE `module_meta` SET `vin` = ? ";
-
-const std::string kSaveModuleMeta =
- "UPDATE `module_meta` SET `ccpu_version` = ?, `language` = ?,"
- "`wers_country_code` = ?, `pt_exchanged_at_odometer_x` = ?,"
- "`pt_exchanged_x_days_after_epoch` = ?,"
- "`ignition_cycles_since_last_exchange` = ?, `vin` = ?";
-
-const std::string kSelectMetaParams = "SELECT `ccpu_version`, "
- "`wers_country_code`, `language` from `module_meta`";
-
-const std::string kUpdateMetaLanguage = "UPDATE `module_meta` SET `language` = ? ";
-
-const std::string kCountAppLevel =
- "SELECT COUNT(`application_id`) FROM `app_level`"
- " WHERE `application_id` = ? ";
-
-const std::string kUpdateGroupPermissions =
- "UPDATE `consent_group` "
- "SET `is_consented` = ?, `input` = ? "
- "WHERE(`application_id` = ? AND `functional_group_id` = ? AND `device_id` = ?) ";
-
-const std::string kInsertApplication =
- "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, `steal_focus`, "
- " `default_hmi`, `priority_value`, `is_revoked`, `memory_kb`, "
- " `heart_beat_timeout_ms`, `certificate`) VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?) ";
-
-const std::string kCollectFriendlyMsg = "SELECT * FROM `message`";
-
-const std::string kSelectFriendlyMsg =
- "SELECT `tts`, `label`, `line1`, `line2`, `textBody` FROM `message` "
- "WHERE `message_type_name` = ? AND `language_code` = ? LIMIT 1";
-
-const std::string kSelectAppGroupsId = "SELECT `functional_group_id` "
- "FROM `app_group` WHERE `application_id` = ? ";
-
-const std::string kSelectConsentedGroupsId =
- "SELECT `functional_group_id`, `is_consented` "
- "FROM `consent_group` WHERE(`application_id` = ? AND `device_id` = ?) ";
-
-const std::string kCountAppConsents = "SELECT COUNT(*) from `consent_group`"
- "WHERE(`device_id` = ? AND `application_id` = ? AND "
- "`functional_group_id` = ?) ";
-
-const std::string kSelectPreconsentedGroupsId = "SELECT `functional_group_id` "
- "FROM `preconsented_group` WHERE `application_id` = ? ";
-
-const std::string kSelectAppPolicies =
- "SELECT `id`, `priority_value`, `default_hmi`, `keep_context`, `steal_focus`, "
- " `memory_kb`, `heart_beat_timeout_ms`, `certificate` FROM `application`";
-
-const std::string kSelectFunctionalGroupNames = "SELECT `id`, `user_consent_prompt`, `name`"
- " FROM `functional_group`";
-
-const std::string kDeleteDeviceConsent = "DELETE FROM `device_consent_group` "
- "WHERE `device_id` = ? ";
-
-const std::string kDeleteAppConsent = "DELETE FROM `consent_group` "
- "WHERE `device_id` = ? ";
-
-const std::string kSelectApplicationIsPreData =
- "SELECT `is_predata` FROM `application` WHERE `id` = ? ";
-
-const std::string kUpdateIsPredata =
- "UPDATE `application` SET `is_predata` = ? WHERE `id` = ? ";
-
-const std::string kHasAppPreloadedGroups =
- "SELECT COUNT(`a1`.`functional_group_id`) FROM `app_group` "
- " AS `a1` JOIN `app_group` AS `a2` "
- " ON `a1`.`functional_group_id` = `a2`.`functional_group_id` "
- " WHERE `a1`.`application_id` = ? AND `a2`.`application_id` = ? ";
-
-const std::string kUpdateUnpairedDevice =
- "UPDATE `device` SET `unpaired` = ? WHERE `id` = ? ";
-
-const std::string kSelectUnpairedDevices =
- "SELECT `id` FROM `device` WHERE `unpaired` = 1";
-
-const std::string kHasMsgLanguageCode = "SELECT COUNT (`id`) FROM message "
- "WHERE `message_type_name` = ? AND `language_code` = ? ";
-
-const std::string kDeletePreconsentedGroupsByApplicationId =
- "DELETE FROM `preconsented_group` WHERE `application_id` = ?";
-
-} // namespace sql_pt_ext
-} // namespace policy
diff --git a/src/components/policy/src/policy/src/sql_pt_ext_representation.cc b/src/components/policy/src/policy/src/sql_pt_ext_representation.cc
deleted file mode 100644
index a24141999b..0000000000
--- a/src/components/policy/src/policy/src/sql_pt_ext_representation.cc
+++ /dev/null
@@ -1,1771 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-#include <algorithm>
-#include <utility>
-#include "utils/logger.h"
-#include "policy/sql_pt_ext_representation.h"
-#include "policy/sql_wrapper.h"
-#include "policy/sql_pt_queries.h"
-#include "policy/sql_pt_ext_queries.h"
-#include "policy/policy_helper.h"
-#include "policy/cache_manager.h"
-
-namespace policy {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "SQLPTRepresentation")
-
-bool SQLPTExtRepresentation::CanAppKeepContext(const std::string& app_id) {
- dbms::SQLQuery query(db());
- if (query.Prepare(sql_pt_ext::kSelectKeepContext)) {
- query.Bind(0, app_id);
- if (query.Exec()) {
- return query.GetBoolean(0);
- }
- }
- return false;
-}
-
-bool SQLPTExtRepresentation::CanAppStealFocus(const std::string& app_id) {
- dbms::SQLQuery query(db());
- if (query.Prepare(sql_pt_ext::kSelectStealFocus)) {
- query.Bind(0, app_id);
- if (query.Exec()) {
- return query.GetBoolean(0);
- }
- }
- return false;
-}
-
-bool SQLPTExtRepresentation::ResetUserConsent() {
- return ResetDeviceConsents() && ResetAppConsents();
-}
-
-bool SQLPTExtRepresentation::ResetDeviceConsents() {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kResetDeviceConsents)) {
- LOG4CXX_WARN(logger_, "Incorrect delete statement from device_consents.");
- return false;
- }
- return query.Exec();
-}
-
-bool SQLPTExtRepresentation::ResetAppConsents() {
- return dbms::SQLQuery(db()).Exec(sql_pt_ext::kResetAppConsents);
-}
-
-bool SQLPTExtRepresentation::GetUserPermissionsForDevice(
- const std::string& device_id, StringArray* consented_groups,
- StringArray* disallowed_groups) {
- LOG4CXX_INFO(logger_, "GetUserPermissionsForDevice");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kSelectDeviceConsentedGroup)) {
- LOG4CXX_WARN(logger_, "Incorrect select from device consented groups");
- return false;
- }
- query.Bind(0, device_id);
- while (query.Next()) {
- if (query.GetBoolean(2)) {
- if (!consented_groups) {
- continue;
- }
- consented_groups->push_back(query.GetString(1));
- } else {
- if (!disallowed_groups) {
- continue;
- }
- disallowed_groups->push_back(query.GetString(1));
- }
- }
-
- return true;
-}
-
-bool SQLPTExtRepresentation::GetPermissionsForApp(
- const std::string& device_id, const std::string& policy_app_id,
- FunctionalIdType* group_types) {
- LOG4CXX_INFO(logger_, "GetPermissionsForApp");
- if (!group_types) {
- LOG4CXX_WARN(logger_, "Input parameter for group types is null.");
- return false;
- }
- // Get all app groups for specified device and application
- FunctionalGroupIDs all_groups;
- if (!GetAllAppGroups(policy_app_id, all_groups)) {
- return false;
- }
- // Get preconsented group
- FunctionalGroupIDs preconsented_groups;
- if (!GetPreconsentedGroups(policy_app_id, preconsented_groups)) {
- return false;
- }
- // Get consented (allowed/disallowed) groups
- FunctionalGroupIDs allowed_groups;
- FunctionalGroupIDs disallowed_groups;
- if (!GetConsentedGroups(policy_app_id, device_id,
- allowed_groups, disallowed_groups)) {
- return false;
- }
- // Get all default groups
- FunctionalGroupIDs default_groups;
- if (!GetAllAppGroups(kDefaultId, default_groups)) {
- return false;
- }
-
- // Get all pre_DataConsent groups
- FunctionalGroupIDs predataconsented_groups;
- if (!GetAllAppGroups(kPreDataConsentId, predataconsented_groups)) {
- return false;
- }
-
- // Get all device groups
- FunctionalGroupIDs device_groups;
- if (!GetAllAppGroups(kDeviceId, device_groups)) {
- return false;
- }
-
- (*group_types)[kTypeDefault] = default_groups;
- (*group_types)[kTypeAllowed] = allowed_groups;
- (*group_types)[kTypeDisallowed] = disallowed_groups;
- (*group_types)[kTypePreconsented] = preconsented_groups;
- (*group_types)[kTypeGeneral] = all_groups;
- (*group_types)[kTypePreDataConsented] = predataconsented_groups;
- (*group_types)[kTypeDevice] = device_groups;
-
- return true;
-}
-
-bool SQLPTExtRepresentation::GetDeviceGroupsFromPolicies(
- policy_table::Strings* groups, policy_table::Strings* preconsented_groups) {
- LOG4CXX_INFO(logger_, "GetDeviceGroupsFromPolicies");
- if (groups) {
- GatherAppGroup(kDeviceId, groups);
- }
- if (preconsented_groups) {
- GatherPreconsentedGroup(kDeviceId, preconsented_groups);
- }
- return true;
-}
-
-bool SQLPTExtRepresentation::SetDeviceData(const std::string& device_id,
- const std::string& hardware,
- const std::string& firmware,
- const std::string& os,
- const std::string& os_version,
- const std::string& carrier,
- const uint32_t number_of_ports,
- const std::string& connection_type) {
- LOG4CXX_INFO(logger_, "SetDeviceData");
- dbms::SQLQuery count_query(db());
- if (!count_query.Prepare(sql_pt_ext::kCountDevice)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for count of device.");
- return false;
- }
-
- count_query.Bind(0, device_id);
-
- if (!count_query.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrect count of device.");
- return false;
- }
-
- bool update = count_query.GetInteger(0);
-
- // Update old value
- if (update) {
- dbms::SQLQuery update_query(db());
- if (!update_query.Prepare(sql_pt_ext::kUpdateDevice)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for udpate device.");
- return false;
- }
-
- update_query.Bind(0, hardware);
- update_query.Bind(1, firmware);
- update_query.Bind(2, os);
- update_query.Bind(3, os_version);
- update_query.Bind(4, carrier);
- update_query.Bind(5, static_cast<int>(number_of_ports));
- update_query.Bind(6, device_id);
- update_query.Bind(7, connection_type);
-
- if (!update_query.Exec() || !update_query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect update for device.");
- return false;
- }
-
- return true;
- }
-
- // Insert new data
- dbms::SQLQuery insert_query(db());
- if (!insert_query.Prepare(sql_pt_ext::kInsertDevice)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for device.");
- return false;
- }
-
- insert_query.Bind(0, device_id);
- insert_query.Bind(1, hardware);
- insert_query.Bind(2, firmware);
- insert_query.Bind(3, os);
- insert_query.Bind(4, os_version);
- insert_query.Bind(5, carrier);
- insert_query.Bind(6, static_cast<int>(number_of_ports));
- insert_query.Bind(7, connection_type);
-
- if (!insert_query.Exec() || !insert_query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert to device.");
- return false;
- }
-
- SetPreloaded(false);
-
- return true;
-}
-
-bool SQLPTExtRepresentation::SetUserPermissionsForDevice(
- const std::string& device_id, const StringArray& consented_groups,
- const StringArray& disallowed_groups) {
- LOG4CXX_TRACE(logger_, "SetUserPermissionsForDevice");
- dbms::SQLQuery count_query(db());
- if (!count_query.Prepare(sql_pt_ext::kCountDeviceConsentGroup)) {
- LOG4CXX_WARN(logger_, "Incorrect count of device consented groups");
- return false;
- }
-
- count_query.Bind(0, device_id);
-
- if (!count_query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed count of device consented groups");
- return false;
- }
-
- bool update = count_query.GetInteger(0);
-
- // TODO(AOleynik): Split to several methods?
- dbms::SQLQuery query(db());
- // Update old values
- if (update) {
- if (!query.Prepare(sql_pt_ext::kUpdateDeviceConsentedGroup)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for updating consented groups on device");
- return false;
- }
-
- StringArray::const_iterator it_consented_groups = consented_groups.begin();
- StringArray::const_iterator it_consented_groups_end =
- consented_groups.end();
- for (; it_consented_groups != it_consented_groups_end;
- ++it_consented_groups) {
- query.Bind(0, true);
- query.Bind(1, std::string("GUI"));
- query.Bind(2, device_id);
- query.Bind(3, *it_consented_groups);
- // TODO(AOleynik): Get this info from external data
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Failed update of device allowed consented groups.");
- return false;
- }
- }
-
- StringArray::const_iterator it_disallowed_groups =
- disallowed_groups.begin();
- StringArray::const_iterator it_disallowed_groups_end =
- disallowed_groups.end();
- for (; it_disallowed_groups != it_disallowed_groups_end;
- ++it_disallowed_groups) {
- query.Bind(0, false);
- query.Bind(1);
- query.Bind(2, device_id);
- query.Bind(3, *it_disallowed_groups);
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Failed update of device disallowed consented groups.");
- return false;
- }
- }
-
- return true;
- }
-
- // Insert new values
- if (!query.Prepare(sql_pt_ext::kInsertDeviceConsentedGroup)) {
- LOG4CXX_WARN(logger_, "Incorrect statement of inserting to device consented groups");
- return false;
- }
-
- StringArray::const_iterator it_consented_groups = consented_groups.begin();
- StringArray::const_iterator it_consented_groups_end = consented_groups.end();
- for (; it_consented_groups != it_consented_groups_end;
- ++it_consented_groups) {
- query.Bind(0, device_id);
- query.Bind(1, *it_consented_groups);
- query.Bind(2, true);
- // TODO(AOleynik): Get this info from external data
- query.Bind(3, std::string("GUI"));
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Failed insert to device allowed consented groups.");
- return false;
- }
- }
-
- StringArray::const_iterator it_disallowed_groups = disallowed_groups.begin();
- StringArray::const_iterator it_disallowed_groups_end =
- disallowed_groups.end();
- for (; it_disallowed_groups != it_disallowed_groups_end;
- ++it_disallowed_groups) {
- query.Bind(0, device_id);
- query.Bind(1, *it_disallowed_groups);
- query.Bind(2, false);
- query.Bind(3);
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Failed insert to device disallowed consented groups.");
- return false;
- }
- }
-
- return true;
-}
-
-bool SQLPTExtRepresentation::ReactOnUserDevConsentForApp(
- const std::string& app_id,
- bool is_device_allowed) {
- bool result = true;
- if (is_device_allowed) {
- // If app has pre_DataConsented groups it should be 'promoted' to default
- // If app has only pre_DataConsented flag it should be only set to false and
- // all groups get restored automatically
- if (IsPredataPolicy(app_id)) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kHasAppPreloadedGroups)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for has app preloaded groups");
- return false;
- }
- query.Bind(0, app_id);
- query.Bind(1, kPreDataConsentId);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrect select for app has predataconsted groups");
- return false;
- }
- if (query.GetInteger(0) > 0) {
- result = result && SetDefaultPolicy(app_id);
- } else {
- result = result && SetIsPredata(app_id, false);
- }
- }
- } else {
- // If app has default groups change them to pre_DataConsented
- // If app has 'normal' groups leave them as is and set
- // pre_DataConsented flag to true.
- if (IsDefaultPolicy(app_id)) {
- result = result && SetPredataPolicy(app_id);
- } else {
- result = result && SetIsPredata(app_id, true);
- }
- }
- return result;
-}
-
-bool SQLPTExtRepresentation::SetUserPermissionsForApp(
- const PermissionConsent& permissions) {
- LOG4CXX_INFO(logger_, "SetUserPermissionsForApp");
- // TODO(AOleynik): Handle situation, when no application was specified, i.e.
- // general permissions were set
- std::vector<FunctionalGroupPermission>::const_iterator it = permissions
- .group_permissions.begin();
- std::vector<FunctionalGroupPermission>::const_iterator it_end = permissions
- .group_permissions.end();
-
- dbms::SQLQuery query(db());
- for (; it != it_end; ++it) {
- dbms::SQLQuery counter(db());
- if (!counter.Prepare(sql_pt_ext::kCountAppConsents)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for consent group count.");
- return false;
- }
-
- counter.Bind(0, permissions.device_id);
- counter.Bind(1, permissions.policy_app_id);
- counter.Bind(2, static_cast<int>((*it).group_id));
- if (!counter.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrent count on consent groups.");
- return false;
- }
-
- bool update_required = counter.GetInteger(0);
-
- // Update already present consent record
- if (update_required) {
- if (!query.Prepare(sql_pt_ext::kUpdateGroupPermissions)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for update consent groups.");
- return false;
- }
-
- // Skip consent saving, if user didn't choose any state
- if (policy::kGroupUndefined == (*it).state) {
- continue;
- }
- query.Bind(0, (*it).state == kGroupAllowed ? 1 : 0);
- query.Bind(1, permissions.consent_source);
- query.Bind(2, permissions.policy_app_id);
- query.Bind(3, static_cast<int>((*it).group_id));
- query.Bind(4, permissions.device_id);
-
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect update on user defined permissions "
- "for app groups.");
- return false;
- }
- continue;
- }
-
- // Insert new consent record
- if (!query.Prepare(sql_pt_ext::kInsertConsentGroups)) {
- LOG4CXX_WARN(logger_,
- "Incorrect statement for update app group permissions.");
- return false;
- }
-
- // Skip consent saving, if user didn't choose any state
- if (policy::kGroupUndefined == (*it).state) {
- continue;
- }
- query.Bind(0, permissions.device_id);
- query.Bind(1, permissions.policy_app_id);
- query.Bind(2, static_cast<int>((*it).group_id));
- query.Bind(3, (*it).state == kGroupAllowed ? 1 : 0);
- query.Bind(4, permissions.consent_source);
-
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert to user defined permissions "
- "for app groups.");
- return false;
- }
- continue;
- }
- return true;
-}
-
-std::vector<UserFriendlyMessage> SQLPTExtRepresentation::GetUserFriendlyMsg(
- const std::vector<std::string>& msg_codes, const std::string& language) {
- dbms::SQLQuery query(db());
- std::vector<UserFriendlyMessage> result;
- if (!query.Prepare(sql_pt_ext::kSelectFriendlyMsg)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for select friendly messages.");
- return result;
- }
-
- const std::string fallback_language = "en-us";
- std::vector<std::string>::const_iterator it = msg_codes.begin();
- std::vector<std::string>::const_iterator it_end = msg_codes.end();
- for (; it != it_end; ++it) {
- std::string msg_language = language;
- // If message has no records with required language, fallback language
- // should be used instead.
- if (!IsMsgLanguagePresent((*it), language)) {
- msg_language = fallback_language;
- }
- query.Bind(0, *it);
- query.Bind(1, msg_language);
-
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect select from friendly messages.");
- return result;
- }
-
- UserFriendlyMessage msg;
-
- msg.message_code = *it;
- msg.tts = query.GetString(0);
- msg.label = query.GetString(1);
- msg.line1 = query.GetString(2);
- msg.line2 = query.GetString(3);
- msg.text_body = query.GetString(4);
-
- result.push_back(msg);
-
- if (!query.Reset()) {
- LOG4CXX_WARN(logger_, "Failed reset statement for selecting friendly "
- "messages.");
- return result;
- }
- }
-
- return result;
-}
-
-bool SQLPTExtRepresentation::GatherConsumerFriendlyMessages(
- policy_table::ConsumerFriendlyMessages* messages) const {
- if (NULL == messages) {
- LOG4CXX_ERROR(logger_, "NULL pointer has been passed to fill");
- return false;
- }
-
- if (!SQLPTRepresentation::GatherConsumerFriendlyMessages(messages)) {
- return false;
- }
-
- dbms::SQLQuery query(db());
- bool result = query.Prepare(sql_pt_ext::kCollectFriendlyMsg);
-
- if (result) {
- while (query.Next()) {
-
- UserFriendlyMessage msg;
-
- msg.tts = query.GetString(1);
- msg.label = query.GetString(2);
- msg.line1 = query.GetString(3);
- msg.line2 = query.GetString(4);
- msg.text_body = query.GetString(5);
- msg.message_code = query.GetString(7);
-
- std::string language = query.GetString(6);
-
- *(*messages->messages)[msg.message_code].languages[language].tts = msg.tts;
- *(*messages->messages)[msg.message_code].languages[language].label = msg.label;
- *(*messages->messages)[msg.message_code].languages[language].line1 = msg.line1;
- *(*messages->messages)[msg.message_code].languages[language].line2 = msg.line2;
- *(*messages->messages)[msg.message_code].languages[language].textBody = msg.text_body;
- }
- } else {
- LOG4CXX_WARN(logger_, "Incorrect statement for select friendly messages.");
- }
- return result;
-}
-
-bool SQLPTExtRepresentation::SetMetaInfo(const std::string& ccpu_version,
- const std::string& wers_country_code,
- const std::string& language) {
- LOG4CXX_AUTO_TRACE(logger_);
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kUpdateMetaParams)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for insert to module meta.");
- return false;
- }
-
- query.Bind(0, ccpu_version);
- query.Bind(1, wers_country_code);
- query.Bind(2, language);
-
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert to module meta.");
- return false;
- }
- return true;
-}
-
-bool SQLPTExtRepresentation::IsMetaInfoPresent() {
- LOG4CXX_INFO(logger_, "IsMetaInfoPresent");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kSelectMetaParams)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for selecting meta info.");
- return false;
- }
-
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrect select from module meta.");
- return false;
- }
-
- return !query.IsNull(0) && !query.IsNull(1) && !query.IsNull(2);
-}
-
-bool SQLPTExtRepresentation::SetSystemLanguage(const std::string& language) {
- LOG4CXX_INFO(logger_, "SetSystemLanguage");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kUpdateMetaLanguage)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for update meta language.");
- return false;
- }
-
- query.Bind(0, language);
-
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrect update for meta language.");
- return false;
- }
-
- return true;
-}
-
-bool SQLPTExtRepresentation::SaveApplicationPoliciesSection(
- const policy_table::ApplicationPoliciesSection& policies) {
- LOG4CXX_INFO(logger_, "SaveApplicationPolicies ext");
- dbms::SQLQuery query_delete(db());
- if (!query_delete.Exec(sql_pt::kDeleteAppGroup)) {
- LOG4CXX_WARN(logger_, "Incorrect delete from app_group.");
- return false;
- }
-
- dbms::SQLQuery query_delete_preconsented(db());
- if (!query_delete_preconsented.Exec(sql_pt_ext::kDeletePreconsentedGroups)) {
- LOG4CXX_WARN(logger_, "Incorrect delete from preconsented_group.");
- return false;
- }
-
- if (!query_delete.Exec(sql_pt::kDeleteApplication)) {
- LOG4CXX_WARN(logger_, "Incorrect delete from application.");
- return false;
- }
-
- if (!query_delete.Exec(sql_pt::kDeleteRequestType)) {
- LOG4CXX_WARN(logger_, "Incorrect delete from request type.");
- return false;
- }
-
- // First, all predefined apps (e.g. default, pre_DataConsent) should be saved,
- // otherwise another app with the predefined permissions can get incorrect
- // permissions
- policy_table::ApplicationPolicies::const_iterator it_default =
- policies.apps.find(kDefaultId);
- if (policies.apps.end() != it_default) {
- if (!SaveSpecificAppPolicy(*it_default)) {
- return false;
- }
- }
- policy_table::ApplicationPolicies::const_iterator it_pre_data_consent =
- policies.apps.find(kPreDataConsentId);
- if (policies.apps.end() != it_pre_data_consent) {
- if (!SaveSpecificAppPolicy(*it_pre_data_consent)) {
- return false;
- }
- }
-
- if (!SaveDevicePolicy(policies.device)) {
- return false;
- }
-
- policy_table::ApplicationPolicies::const_iterator it;
- for (it = policies.apps.begin(); it != policies.apps.end(); ++it) {
- // Skip saving of predefined app, since they should be saved before
- if (IsPredefinedApp(*it)) {
- continue;
- }
- if (!SaveSpecificAppPolicy(*it)) {
- return false;
- }
- }
-
- return true;
-}
-
-bool SQLPTExtRepresentation::SaveSpecificAppPolicy(
- const policy_table::ApplicationPolicies::value_type& app) {
- if (app.second.is_string()) {
- if (kDefaultId.compare(app.second.get_string()) == 0) {
- if (!SetDefaultPolicy(app.first)) {
- return false;
- }
- if (!SaveRequestType(app.first, *app.second.RequestType)) {
- return false;
- }
- } else if (kPreDataConsentId.compare(app.second.get_string()) == 0) {
- if (!SetPredataPolicy(app.first)) {
- return false;
- }
- if (!SaveRequestType(app.first, *app.second.RequestType)) {
- return false;
- }
- }
-
- // Stop saving other params, since predefined permissions already set
- return true;
- }
-
- SetIsDefault(app.first, false);
- SetIsPredata(app.first, false);
-
- dbms::SQLQuery app_query(db());
- if (!app_query.Prepare(sql_pt_ext::kInsertApplication)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement into application.");
- return false;
- }
-
- app_query.Bind(0, app.first);
- app_query.Bind(1, app.second.keep_context);
- app_query.Bind(2, app.second.steal_focus);
- app_query.Bind(
- 3, std::string(policy_table::EnumToJsonString(app.second.default_hmi)));
- app_query.Bind(
- 4, std::string(policy_table::EnumToJsonString(app.second.priority)));
- app_query.Bind(
- 5, app.second.is_null());
- app_query.Bind(6, *app.second.memory_kb);
- app_query.Bind(7, *app.second.heart_beat_timeout_ms);
- app.second.certificate.is_initialized() ?
- app_query.Bind(8, *app.second.certificate) : app_query.Bind(8, std::string());
-
- if (!app_query.Exec() || !app_query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into application.");
- return false;
- }
-
- if (!SaveAppGroup(app.first, app.second.groups)) {
- return false;
- }
- // TODO(IKozyrenko): Check logic if optional container is missing
- if (!SaveNickname(app.first, *app.second.nicknames)) {
- return false;
- }
- // TODO(IKozyrenko): Check logic if optional container is missing
- if (!SaveAppType(app.first, *app.second.AppHMIType)) {
- return false;
- }
- // TODO(IKozyrenko): Check logic if optional container is missing
- if (!SavePreconsentedGroup(app.first, *app.second.preconsented_groups)) {
- return false;
- }
-
- return true;
-}
-
-bool policy::SQLPTExtRepresentation::SaveDevicePolicy(
- const policy_table::DevicePolicy& device) {
- dbms::SQLQuery app_query(db());
- if (!app_query.Prepare(sql_pt_ext::kInsertApplication)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement into application (device).");
- return false;
- }
- app_query.Bind(0, kDeviceId);
- app_query.Bind(1, device.keep_context);
- app_query.Bind(2, device.steal_focus);
- app_query.Bind(
- 3, std::string(policy_table::EnumToJsonString(device.default_hmi)));
- app_query.Bind(
- 4, std::string(policy_table::EnumToJsonString(device.priority)));
- app_query.Bind(5, false);
- app_query.Bind(6, 0);
- app_query.Bind(7, 0);
- app_query.Bind(8, std::string());
-
- if (!app_query.Exec() || !app_query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into application.");
- return false;
- }
-
- if (!SaveAppGroup(kDeviceId, device.groups)) {
- return false;
- }
- if (!SavePreconsentedGroup(kDeviceId, *device.preconsented_groups)) {
- return false;
- }
-
- return true;
-}
-
-bool SQLPTExtRepresentation::GatherApplicationPoliciesSection(
- policy_table::ApplicationPoliciesSection* policies) const {
- LOG4CXX_INFO(logger_, "Gather applications policies");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kSelectAppPolicies)) {
- LOG4CXX_WARN(logger_, "Incorrect select from app_policies");
- return false;
- }
-
- while (query.Next()) {
- rpc::Nullable<policy_table::ApplicationParams> params;
- const std::string& app_id = query.GetString(0);
- if (IsApplicationRevoked(app_id)) {
- params.set_to_null();
- (*policies).apps[app_id] = params;
- continue;
- }
- if (IsDefaultPolicy(app_id)) {
- (*policies).apps[app_id].set_to_string(kDefaultId);
- }
- if (IsPredataPolicy(app_id)) {
- (*policies).apps[app_id].set_to_string(kPreDataConsentId);
- }
- if (kDeviceId == app_id) {
- policy_table::DevicePolicy device_policy;
- policy_table::Priority priority;
- policy_table::EnumFromJsonString(query.GetString(1), &priority);
- device_policy.priority = priority;
- policy_table::HmiLevel hmi;
- policy_table::EnumFromJsonString(query.GetString(2), &hmi);
- device_policy.default_hmi = hmi;
- device_policy.keep_context = query.GetBoolean(3);
- device_policy.steal_focus = query.GetBoolean(4);
- if (!GatherAppGroup(app_id, &device_policy.groups)) {
- return false;
- }
- GatherPreconsentedGroup(app_id, &*device_policy.preconsented_groups);
- (*policies).device = device_policy;
- continue;
- }
- policy_table::Priority priority;
- policy_table::EnumFromJsonString(query.GetString(1), &priority);
- params.priority = priority;
- policy_table::HmiLevel hmi;
- policy_table::EnumFromJsonString(query.GetString(2), &hmi);
- params.default_hmi = hmi;
- params.keep_context = query.GetBoolean(3);
- params.steal_focus = query.GetBoolean(4);
- *params.memory_kb = query.GetInteger(5);
- *params.heart_beat_timeout_ms = query.GetInteger(6);
- if (!query.IsNull(7)) {
- *params.certificate = query.GetString(7);
- }
- if (!GatherAppGroup(app_id, &params.groups)) {
- return false;
- }
- if (!GatherNickName(app_id, &*params.nicknames)) {
- return false;
- }
- if (!GatherAppType(app_id, &*params.AppHMIType)) {
- return false;
- }
- if (!GatherRequestType(app_id, &*params.RequestType)) {
- return false;
- }
- GatherPreconsentedGroup(app_id, &*params.preconsented_groups);
- (*policies).apps[app_id] = params;
- }
- return true;
-}
-
-void SQLPTExtRepresentation::GatherPreconsentedGroup(
- const std::string& app_id, policy_table::Strings* groups) const {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kSelectPreconsentedGroups)) {
- LOG4CXX_WARN(logger_, "Incorrect select from preconsented group");
- return;
- }
-
- query.Bind(0, app_id);
- while (query.Next()) {
- groups->push_back(query.GetString(0));
- }
-}
-
-bool SQLPTExtRepresentation::GatherUsageAndErrorCounts(
- policy_table::UsageAndErrorCounts* counts) const {
- LOG4CXX_INFO(logger_, "Gather Usage and Error Counts.");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kSelectUsageAndErrorCount) || !query.Exec()) {
- LOG4CXX_INFO(logger_, "Failed select from user_and_error_count");
- return false;
- }
-
- *counts->count_of_iap_buffer_full = query.GetInteger(0);
- *counts->count_sync_out_of_memory = query.GetInteger(1);
- *counts->count_of_sync_reboots = query.GetInteger(2);
-
- return GatherAppLevels(&*counts->app_level);
-}
-
-bool SQLPTExtRepresentation::GatherAppLevels(
- policy_table::AppLevels* apps) const {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kSelectAppLevels)) {
- LOG4CXX_INFO(logger_, "Failed select from app_level. SQLError = "
- << query.LastError().text());
- return false;
- }
- while (query.Next()) {
- policy_table::AppLevel level;
- // value of time fields database is seconds
- level.minutes_in_hmi_full = query.GetInteger(1);
- level.minutes_in_hmi_limited = query.GetInteger(2);
- level.minutes_in_hmi_background = query.GetInteger(3);
- level.minutes_in_hmi_none = query.GetInteger(4);
- level.count_of_user_selections = query.GetInteger(5);
- level.count_of_rejections_sync_out_of_memory = query.GetInteger(6);
- level.count_of_rejections_nickname_mismatch = query.GetInteger(7);
- level.count_of_rejections_duplicate_name = query.GetInteger(8);
- level.count_of_rejected_rpc_calls = query.GetInteger(9);
- level.count_of_rpcs_sent_in_hmi_none = query.GetInteger(10);
- level.count_of_removals_for_bad_behavior = query.GetInteger(11);
- level.count_of_run_attempts_while_revoked = query.GetInteger(12);
- level.app_registration_language_gui = query.GetString(13);
- level.app_registration_language_vui = query.GetString(14);
- (*apps)[query.GetString(0)] = level;
- }
-
- return true;
-}
-
-void SQLPTExtRepresentation::GatherDeviceData(
- policy_table::DeviceData* data) const {
- LOG4CXX_INFO(logger_, "Gather device data.");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kSelectDeviceData)) {
- LOG4CXX_WARN(logger_, "Incorrect select statement for device data.");
- return;
- }
- data->mark_initialized();
- while (query.Next()) {
- policy_table::DeviceParams* specific_device = &(*data)[query.GetString(0)];
- *specific_device->hardware = query.GetString(1);
- *specific_device->firmware_rev = query.GetString(2);
- *specific_device->os = query.GetString(3);
- *specific_device->os_version = query.GetString(4);
- *specific_device->carrier = query.GetString(5);
- *specific_device->max_number_rfcom_ports = query.GetInteger(6);
-
- // TODO(IKozyrenko): Check logic if optional container is missing
- GatherConsentGroup(query.GetString(0),
- &(*specific_device->user_consent_records));
- }
-}
-
-void SQLPTExtRepresentation::GatherConsentGroup(
- const std::string& device_id,
- policy_table::UserConsentRecords* records) const {
- LOG4CXX_INFO(logger_, "Gather consent records.");
- dbms::SQLQuery query(db());
- // Fill data for device
- if (!query.Prepare(sql_pt_ext::kSelectDeviceConsentedGroup)) {
- LOG4CXX_WARN(logger_,
- "Incorrect select statement for device consented groups.");
- return;
- }
-
- query.Bind(0, device_id);
-
- // Fill device_data -> user_consent_records -> "device"
- while (query.Next()) {
- policy_table::ConsentRecords* device_consent_records = &(*records)[kDeviceId];
- // TODO(IKozyrenko): Check logic if optional container is missing
- policy_table::ConsentGroups& consent_groups = *device_consent_records->consent_groups;
- consent_groups[query.GetString(1)] = query.GetBoolean(2);
- policy_table::Input input;
- policy_table::EnumFromJsonString(query.GetString(3), &input);
- *device_consent_records->input = input;
- *device_consent_records->time_stamp = query.GetString(4);
- }
-
- if (!query.Reset()) {
- return;
- }
-
- // Fill data for applications
- if (!query.Prepare(sql_pt_ext::kSelectConsentGroup)) {
- LOG4CXX_WARN(logger_,
- "Incorrect select statement for app consented groups.");
- return;
- }
-
- query.Bind(0, device_id);
-
- // Fill device_data -> user_consent_records -> <app_id>
- while (query.Next()) {
- policy_table::ConsentRecords* app_consent_records = &(*records)[query
- .GetString(1)];
- // TODO(IKozyrenko): Check logic if optional container is missing
- policy_table::ConsentGroups& consent_groups = *app_consent_records->consent_groups;
-
- consent_groups[query.GetString(2)] = query.GetBoolean(3);
- policy_table::Input input;
- policy_table::EnumFromJsonString(query.GetString(4), &input);
- *app_consent_records->input = input;
- *app_consent_records->time_stamp = query.GetString(5);
- }
-}
-
-bool SQLPTExtRepresentation::SaveDeviceData(
-const policy_table::DeviceData& devices) {
- LOG4CXX_INFO(logger_, "SaveDeviceData");
- dbms::SQLQuery drop_device_query(db());
- const std::string drop_device = "DELETE FROM `device`";
- if (!drop_device_query.Exec(drop_device)) {
- LOG4CXX_WARN(logger_, "Could not clear device table.");
- return false;
- }
-
- dbms::SQLQuery drop_device_consents_query(db());
- const std::string drop_device_consents = "DELETE FROM `device_consent_group`";
- if (!drop_device_consents_query.Exec(drop_device_consents)) {
- LOG4CXX_WARN(logger_, "Could not clear device consents.");
- return false;
- }
-
- dbms::SQLQuery drop_user_consents_query(db());
- const std::string drop_user_consents = "DELETE FROM `consent_group`";
- if (!drop_user_consents_query.Exec(drop_user_consents)) {
- LOG4CXX_WARN(logger_, "Could not clear user consents.");
- return false;
- }
-
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kInsertDeviceData)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for device data.");
- return false;
- }
-
- policy_table::DeviceData::const_iterator it = devices.begin();
- policy_table::DeviceData::const_iterator it_end = devices.end();
- for (; it != it_end; ++it) {
- query.Bind(0, it->first);
- query.Bind(1, *(it->second.hardware));
- query.Bind(2, *(it->second.firmware_rev));
- query.Bind(3, *(it->second.os));
- query.Bind(4, *(it->second.os_version));
- query.Bind(5, *(it->second.carrier));
- query.Bind(6, *(it->second.max_number_rfcom_ports));
- query.Bind(7, *(it->second.connection_type));
-
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into device data.");
- return false;
- }
-
- // TODO(IKozyrenko): Check logic if optional container is missing
- if (!SaveConsentGroup(it->first, *it->second.user_consent_records)) {
- return false;
- }
- }
-
- return true;
-}
-
-bool SQLPTExtRepresentation::SaveConsentGroup(
- const std::string& device_id,
- const policy_table::UserConsentRecords& records) {
- LOG4CXX_INFO(logger_, "SaveConsentGroup");
- dbms::SQLQuery query(db());
-
- policy_table::UserConsentRecords::const_iterator it = records.begin();
- policy_table::UserConsentRecords::const_iterator it_end = records.end();
- for (; it != it_end; ++it) {
- // TODO(IKozyrenko): Check logic if optional container is missing
- policy_table::ConsentGroups::const_iterator it_groups = it->second
- .consent_groups->begin();
- policy_table::ConsentGroups::const_iterator it_groups_end = it->second
- .consent_groups->end();
- for (; it_groups != it_groups_end; ++it_groups) {
- if (kDeviceId == it->first) {
- if (!query.Prepare(sql_pt_ext::kInsertDeviceConsentedGroup)) {
- LOG4CXX_WARN(logger_,
- "Incorrect insert statement for device consent group.");
- return false;
- }
- query.Bind(0, device_id);
- query.Bind(1, it_groups->first);
- query.Bind(2, it_groups->second);
- query.Bind(
- 3,
- std::string(policy_table::EnumToJsonString(*(it->second.input))));
- query.Bind(4, std::string(*(it->second.time_stamp)));
- LOG4CXX_INFO(logger_, "Device:" <<
- "time stamp " << std::string(*(it->second.time_stamp))
- << " group " << it_groups->first
- << " consent " << it_groups->second);
- } else {
- if (!query.Prepare(sql_pt_ext::kInsertConsentGroups)) {
- LOG4CXX_WARN(logger_,
- "Incorrect insert statement for consent group.");
- return false;
- }
- query.Bind(0, device_id);
- query.Bind(1, it->first);
- query.Bind(2, it_groups->first);
- query.Bind(3, it_groups->second);
- query.Bind(
- 4,
- std::string(policy_table::EnumToJsonString(*(it->second.input))));
- query.Bind(5, std::string(*(it->second.time_stamp)));
- LOG4CXX_INFO(logger_, "Device:" <<
- "time stamp " << std::string(*(it->second.time_stamp))
- << " group " << it_groups->first
- << " consent " << it_groups->second);
- }
-
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into consent group.");
- return false;
- }
- }
- }
-
- return true;
-}
-
-bool SQLPTExtRepresentation::SavePreconsentedGroup(
- const std::string& app_id, const policy_table::Strings& groups) {
- LOG4CXX_INFO(logger_, "SavePreconsentedGroup");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kInsertPreconsentedGroups)) {
- LOG4CXX_WARN(logger_,
- "Incorrect insert statement for preconsented groups");
- return false;
- }
-
- policy_table::Strings::const_iterator it;
- for (it = groups.begin(); it != groups.end(); ++it) {
- query.Bind(0, app_id);
- query.Bind(1, *it);
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into preconsented groups.");
- return false;
- }
- }
-
- return true;
-}
-
-void SQLPTExtRepresentation::GatherModuleMeta(
- policy_table::ModuleMeta* meta) const {
- LOG4CXX_INFO(logger_, "Gather Module Meta Info");
- dbms::SQLQuery query(db());
- if (query.Prepare(sql_pt_ext::kSelectModuleMeta) && query.Next()) {
- *meta->ccpu_version = query.GetString(0);
- *meta->language = query.GetString(1);
- *meta->wers_country_code = query.GetString(2);
- *meta->pt_exchanged_at_odometer_x = query.GetInteger(3);
- *meta->pt_exchanged_x_days_after_epoch = query.GetInteger(4);
- *meta->ignition_cycles_since_last_exchange = query.GetInteger(5);
- *meta->vin = query.GetString(6);
- }
-}
-
-void SQLPTExtRepresentation::Increment(const std::string& type) const {
- dbms::SQLQuery query(db());
- std::string update_counter = "UPDATE `usage_and_error_count` SET `" + type
- + "` = `" + type + "` + 1";
- if (!query.Exec(update_counter)) {
- LOG4CXX_INFO(logger_, "Failed updating global counter");
- }
-}
-
-bool SQLPTExtRepresentation::IsExistAppLevel(const std::string& app_id) const {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kCountAppLevel)) {
- LOG4CXX_INFO(logger_, "Incorrect statement of count app_level");
- return false;
- }
- query.Bind(0, app_id);
- if (!query.Exec()) {
- LOG4CXX_INFO(logger_, "Failed count app_level");
- return false;
- }
- return query.GetInteger(0) > 0;
-}
-
-bool SQLPTExtRepresentation::GetAllAppGroups(const std::string& policy_app_id,
- FunctionalGroupIDs& all_groups) {
- LOG4CXX_INFO(logger_, "GetAllAppGroups for '" << policy_app_id << "'");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kSelectAppGroupsId)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for select app groups id.");
- return false;
- }
-
- query.Bind(0, policy_app_id);
-
- while (query.Next()) {
- all_groups.push_back(query.GetInteger(0));
- }
-
- return true;
-}
-
-bool SQLPTExtRepresentation::GetConsentedGroups(
- const std::string& policy_app_id, const std::string& device_id,
- FunctionalGroupIDs& allowed_groups, FunctionalGroupIDs& disallowed_groups) {
-
- LOG4CXX_INFO(logger_, "GetConsentedGroups");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kSelectConsentedGroupsId)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for select consent groups id.");
- return false;
- }
-
- query.Bind(0, policy_app_id);
- query.Bind(1, device_id);
-
- while (query.Next()) {
- if (query.GetBoolean(1)) {
- allowed_groups.push_back(query.GetInteger(0));
- } else {
- disallowed_groups.push_back(query.GetInteger(0));
- }
- }
-
- return true;
-}
-
-bool SQLPTExtRepresentation::GetPreconsentedGroups(
- const std::string& policy_app_id, FunctionalGroupIDs& preconsented_groups) {
- LOG4CXX_INFO(logger_, "GetPreconsentedGroups");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kSelectPreconsentedGroupsId)) {
- LOG4CXX_WARN(logger_,
- "Incorrect statement for select preconsented groups id.");
- return false;
- }
-
- query.Bind(0, policy_app_id);
-
- while (query.Next()) {
- preconsented_groups.push_back(query.GetInteger(0));
- }
-
- return true;
-}
-
-bool SQLPTExtRepresentation::GetFunctionalGroupNames(
- FunctionalGroupNames& names) {
- LOG4CXX_INFO(logger_, "GetFunctionalGroupNames");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kSelectFunctionalGroupNames)) {
- LOG4CXX_WARN(logger_,
- "Incorrect statement for select functional groups names.");
- return false;
- }
-
- while (query.Next()) {
- // Some of functional grous doesn't have filled user_consent_prompt
- if (query.IsNull(1)) {
- names[query.GetInteger(0)] =
- std::make_pair<std::string, std::string>("", query.GetString(2));
- } else {
- names[query.GetInteger(0)] =
- std::make_pair<std::string, std::string>(query.GetString(1), query.GetString(2));
- }
-
- }
-
- return true;
-}
-
-void SQLPTExtRepresentation::FillFunctionalGroupPermissions(
- FunctionalGroupIDs& ids, FunctionalGroupNames& names, GroupConsent state,
- std::vector<FunctionalGroupPermission>& permissions) {
- FunctionalGroupIDs::const_iterator it = ids.begin();
- FunctionalGroupIDs::const_iterator it_end = ids.end();
- for (; it != it_end; ++it) {
- FunctionalGroupPermission current_group;
- current_group.group_id = *it;
- current_group.group_alias = names[*it].first;
- current_group.group_name = names[*it].second;
- current_group.state = state;
- permissions.push_back(current_group);
- }
-}
-
-void SQLPTExtRepresentation::Increment(const std::string& app_id,
- const std::string& type) const {
- dbms::SQLQuery query(db());
- std::string sql_counter;
- if (IsExistAppLevel(app_id)) {
- // update
- sql_counter = "UPDATE `app_level` SET `" + type + "` = `" + type
- + "` + 1 WHERE `application_id` = ?";
- } else {
- // insert
- sql_counter = "INSERT INTO `app_level` (`application_id`, `" + type + "`) "
- "VALUES (?, 1)";
- }
- if (!query.Prepare(sql_counter)) {
- LOG4CXX_INFO(logger_, "Incorrect statement of update app counter");
- return;
- }
- query.Bind(0, app_id);
- if (!query.Exec()) {
- LOG4CXX_INFO(logger_, "Failed updating app counter");
- }
-}
-
-void SQLPTExtRepresentation::Set(const std::string& app_id,
- const std::string& type,
- const std::string& value) const {
- dbms::SQLQuery query(db());
- std::string sql_info;
- if (IsExistAppLevel(app_id)) {
- // update
- sql_info = "UPDATE `app_level` SET `" + type + "` = ? "
- "WHERE `application_id` = ?";
- } else {
- // insert
- sql_info = "INSERT INTO `app_level` (`" + type + "`, `application_id`) "
- "VALUES (?, ?)";
- }
- if (!query.Prepare(sql_info)) {
- LOG4CXX_INFO(logger_, "Incorrect statement of update app info");
- return;
- }
- query.Bind(0, value);
- query.Bind(1, app_id);
- if (!query.Exec()) {
- LOG4CXX_INFO(logger_, "Failed updating app info");
- }
-}
-
-void SQLPTExtRepresentation::Add(const std::string& app_id,
- const std::string& type, int seconds) const {
- dbms::SQLQuery query(db());
- std::string sql_stopwatch;
- if (IsExistAppLevel(app_id)) {
- // update
- sql_stopwatch = "UPDATE `app_level` SET `" + type + "` = `" + type
- + "` + ? WHERE `application_id` = ?";
- } else {
- // insert
- sql_stopwatch = "INSERT INTO `app_level` (`" + type
- + "`, `application_id`) "
- "VALUES (?, ?)";
- }
- if (!query.Prepare(sql_stopwatch)) {
- LOG4CXX_INFO(logger_, "Incorrect statement of update app stopwatch");
- return;
- }
- query.Bind(0, seconds);
- query.Bind(1, app_id);
- if (!query.Exec()) {
- LOG4CXX_INFO(logger_, "Failed updating app stopwatch");
- }
-}
-
-bool SQLPTExtRepresentation::GetDefaultHMI(const std::string& policy_app_id,
- std::string* default_hmi) {
- LOG4CXX_INFO(logger_, "GetDefaultHMI");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kSelectDefaultHmi)) {
- LOG4CXX_INFO(logger_, "Incorrect statement for default hmi.");
- return false;
- }
-
- query.Bind(0, policy_app_id);
-
- if (!query.Exec()) {
- LOG4CXX_INFO(logger_, "Error during default hmi getting.");
- return false;
- }
-
- if (query.IsNull(0)) {
- default_hmi->clear();
- return true;
- }
-
- default_hmi->assign(query.GetString(0));
-
- return true;
-}
-
-bool SQLPTExtRepresentation::CountUnconsentedGroups(
- const std::string& policy_app_id,
- const std::string& device_id,
- int* result) const {
- LOG4CXX_INFO(logger_, "CountUnconsentedGroups");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kCountUnconsentedGroups)) {
- LOG4CXX_WARN(logger_, "Incorrect select for unconsented groups.");
- return false;
- }
-
- query.Bind(0, policy_app_id);
- query.Bind(1, device_id);
- query.Bind(2, kDefaultId);
- query.Bind(3, kPreDataConsentId);
-
- if (!query.Exec()) {
- LOG4CXX_INFO(logger_, "Error during executing unconsented groups.");
- return false;
- }
- *result = query.GetInteger(0);
- return true;
-}
-
-bool SQLPTExtRepresentation::IsMsgLanguagePresent(const std::string &message,
- const std::string &language) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kHasMsgLanguageCode)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for message language check.");
- return false;
- }
-
- query.Bind(0, message);
- query.Bind(1, language);
-
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed to check message language code.");
- return false;
- }
-
- return query.GetInteger(0) != 0;
-}
-
-bool SQLPTExtRepresentation::SaveMessageString(
- const std::string& type, const std::string& lang,
- const policy_table::MessageString& strings) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kInsertMessageString)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for message.");
- return false;
- }
-
- query.Bind(0, *strings.tts);
- query.Bind(1, *strings.label);
- query.Bind(2, *strings.line1);
- query.Bind(3, *strings.line2);
- query.Bind(4, lang);
- query.Bind(5, type);
- query.Bind(6, *strings.textBody);
-
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into message.");
- return false;
- }
-
- return true;
-}
-
-bool SQLPTExtRepresentation::SaveUsageAndErrorCounts(
- const policy_table::UsageAndErrorCounts& counts) {
- return SaveAppCounters(*counts.app_level) && SaveGlobalCounters(counts);
-}
-
-bool SQLPTExtRepresentation::SaveModuleMeta(
- const policy_table::ModuleMeta& meta) {
- dbms::SQLQuery query(db());
-
- if (!query.Prepare(sql_pt_ext::kSaveModuleMeta)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for module_meta.");
- return false;
- }
- const int64_t odometer = *(meta.pt_exchanged_at_odometer_x);
-
- query.Bind(0, *(meta.ccpu_version));
- query.Bind(1, *(meta.language));
- query.Bind(2, *(meta.wers_country_code));
- query.Bind(3, odometer);
- query.Bind(4, *(meta.pt_exchanged_x_days_after_epoch));
- query.Bind(5, *(meta.ignition_cycles_since_last_exchange));
- query.Bind(6, *(meta.vin));
-
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrect update for module_meta.");
- return false;
- }
-
- return true;
-}
-
-bool SQLPTExtRepresentation::SaveAppCounters(
- const rpc::policy_table_interface_base::AppLevels& app_levels) {
- dbms::SQLQuery query(db());
- if (!query.Exec(sql_pt::kDeleteAppLevel)) {
- LOG4CXX_WARN(logger_, "Incorrect delete from app level.");
- return false;
- }
- if (!query.Prepare(sql_pt::kInsertAppLevel)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for app level.");
- return false;
- }
-
- policy_table::AppLevels::const_iterator it;
- for (it = app_levels.begin(); it != app_levels.end(); ++it) {
- query.Bind(0, it->first);
- query.Bind(1, it->second.minutes_in_hmi_full);
- query.Bind(2, it->second.minutes_in_hmi_limited);
- query.Bind(3, it->second.minutes_in_hmi_background);
- query.Bind(4, it->second.minutes_in_hmi_none);
- query.Bind(5, it->second.count_of_user_selections);
- query.Bind(6, it->second.count_of_rejections_sync_out_of_memory);
- query.Bind(7, it->second.count_of_rejections_nickname_mismatch);
- query.Bind(8, it->second.count_of_rejections_duplicate_name);
- query.Bind(9, it->second.count_of_rejected_rpc_calls);
- query.Bind(10, it->second.count_of_rpcs_sent_in_hmi_none);
- query.Bind(11, it->second.count_of_removals_for_bad_behavior);
- query.Bind(12, it->second.count_of_run_attempts_while_revoked);
- query.Bind(13, it->second.app_registration_language_gui);
- query.Bind(14, it->second.app_registration_language_vui);
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into app level.");
- return false;
- }
- }
- return true;
-}
-
-bool SQLPTExtRepresentation::SaveGlobalCounters(
- const rpc::policy_table_interface_base::UsageAndErrorCounts& counts) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kUpdateGlobalCounters)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for global counters.");
- return false;
- }
-
- query.Bind(0, *counts.count_of_iap_buffer_full);
- query.Bind(1, *counts.count_sync_out_of_memory);
- query.Bind(2, *counts.count_of_sync_reboots);
-
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into global counters.");
- return false;
- }
-
- return true;
-}
-
-bool SQLPTExtRepresentation::CleanupUnpairedDevices(
- const DeviceIds& device_ids) const {
- LOG4CXX_INFO(logger_, "CleanupUnpairedDevices");
- dbms::SQLQuery delete_device_query(db());
- if (!delete_device_query.Prepare(sql_pt::kDeleteDevice)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for device delete.");
- return true;
- }
-
- dbms::SQLQuery delete_device_consent_query(db());
- if (!delete_device_consent_query.Prepare(sql_pt_ext::kDeleteDeviceConsent)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for delete device consent.");
- return false;
- }
-
- dbms::SQLQuery delete_app_consent_query(db());
- if (!delete_app_consent_query.Prepare(sql_pt_ext::kDeleteAppConsent)) {
- LOG4CXX_WARN(logger_, "Incorrect statement for delete app consent.");
- return false;
- }
-
- DeviceIds::const_iterator it = device_ids.begin();
- DeviceIds::const_iterator it_end = device_ids.end();
- for (; it != it_end; ++it) {
- delete_device_query.Bind(0, (*it));
- if (!delete_device_query.Exec() || !delete_device_query.Reset()) {
- LOG4CXX_WARN(logger_, "Failed to delete from device");
- return false;
- }
-
- delete_device_consent_query.Bind(0, (*it));
- if (!delete_device_consent_query.Exec() ||
- !delete_device_consent_query.Reset()) {
- LOG4CXX_WARN(logger_, "Failed to delete from device consent.");
- return false;
- }
-
- delete_app_consent_query.Bind(0, (*it));
- if (!delete_app_consent_query.Exec() || !delete_app_consent_query.Reset()) {
- LOG4CXX_WARN(logger_, "Failed to delete from app consent.");
- return false;
- }
- }
- return true;
-}
-
-bool SQLPTExtRepresentation::SetDefaultPolicy(const std::string& app_id) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kDeleteAppGroupByApplicationId)) {
- LOG4CXX_ERROR(logger_, "Incorrect statement to delete from app_group.");
- return false;
- }
- query.Bind(0, app_id);
- if (!query.Exec()) {
- LOG4CXX_ERROR(logger_, "Failed deleting from app_group.");
- return false;
- }
-
- if (!query.Prepare(sql_pt_ext::kDeletePreconsentedGroupsByApplicationId)) {
- LOG4CXX_ERROR(logger_, "Incorrect statement to delete from app_group.");
- return false;
- }
- query.Bind(0, app_id);
- if (!query.Exec()) {
- LOG4CXX_ERROR(logger_, "Failed deleting from app_group.");
- return false;
- }
-
- if (!CopyApplication(kDefaultId, app_id)) {
- return false;
- }
-
- SetPreloaded(false);
-
- policy_table::Strings default_groups;
- policy_table::Strings default_preconsented_groups;
- GatherAppGroup(kDefaultId, &default_groups);
- GatherPreconsentedGroup(kDefaultId, &default_preconsented_groups);
- if (SaveAppGroup(app_id, default_groups) &&
- SavePreconsentedGroup(app_id, default_preconsented_groups)) {
- return SetIsDefault(app_id, true) && SetIsPredata(app_id, false);
- }
-
- return false;
-}
-
-bool SQLPTExtRepresentation::SetPredataPolicy(const std::string& app_id) {
- LOG4CXX_INFO(logger_, "SQLPTExtRepresentation::SetPredataPolicy for " << app_id);
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kDeleteAppGroupByApplicationId)) {
- LOG4CXX_ERROR(logger_, "Incorrect statement to delete from app_group.");
- return false;
- }
- query.Bind(0, app_id);
- if (!query.Exec()) {
- LOG4CXX_ERROR(logger_, "Failed deleting from app_group.");
- return false;
- }
-
- if (!query.Prepare(sql_pt_ext::kDeletePreconsentedGroupsByApplicationId)) {
- LOG4CXX_ERROR(logger_, "Incorrect statement to delete from app_group.");
- return false;
- }
- query.Bind(0, app_id);
- if (!query.Exec()) {
- LOG4CXX_ERROR(logger_, "Failed deleting from app_group.");
- return false;
- }
-
- if (!CopyApplication(kPreDataConsentId, app_id)) {
- return false;
- }
-
- SetPreloaded(false);
-
- policy_table::Strings predataconsent_groups;
- policy_table::Strings predataconsent_preconsented_groups;
- GatherAppGroup(kPreDataConsentId, &predataconsent_groups);
- GatherPreconsentedGroup(kPreDataConsentId, &predataconsent_groups);
- if (SaveAppGroup(app_id, predataconsent_groups) &&
- SavePreconsentedGroup(app_id, predataconsent_groups)) {
- return SetIsDefault(app_id, false) && SetIsPredata(app_id, true);
- }
- return false;
-}
-
-bool SQLPTExtRepresentation::IsPredataPolicy(const std::string& app_id) const {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kSelectApplicationIsPreData)) {
- LOG4CXX_WARN(logger_, "Incorrect select application is pre_dataConsented");
- return false;
- }
-
- query.Bind(0, app_id);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed select application is pre_dataConsented");
- return false;
- }
- return query.IsNull(0) ? false : query.GetBoolean(0);
-}
-
-bool SQLPTExtRepresentation::SetIsPredata(const std::string& app_id,
- bool is_pre_data) {
- LOG4CXX_TRACE(logger_, "Set flag is_predata of application");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kUpdateIsPredata)) {
- LOG4CXX_WARN(logger_, "Incorect statement for updating is_predata");
- return false;
- }
-
- query.Bind(0, is_pre_data);
- query.Bind(1, app_id);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed update is_predata");
- return false;
- }
- return true;
-}
-
-bool SQLPTExtRepresentation::SetUnpairedDevice(const std::string& device_id,
- bool unpaired) const {
- LOG4CXX_TRACE(logger_, "Set unpaired device: " << device_id);
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kUpdateUnpairedDevice)) {
- LOG4CXX_WARN(logger_, "Incorect statement for updating unpaired device");
- return false;
- }
-
- query.Bind(0, unpaired);
- query.Bind(1, device_id);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed update unpaired device");
- return false;
- }
- return true;
-}
-
-bool SQLPTExtRepresentation::UnpairedDevicesList(DeviceIds* device_ids) const {
- LOG4CXX_TRACE(logger_, "Get list of unpaired devices");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kSelectUnpairedDevices)) {
- LOG4CXX_WARN(logger_, "Incorect statement for selecting unpaired devices");
- return false;
- }
-
- while (query.Next()) {
- device_ids->push_back(query.GetString(0));
- }
- return true;
-}
-
-bool SQLPTExtRepresentation::SetVINValue(const std::string& value){
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kUpdateModuleMetaVinParam)) {
- LOG4CXX_WARN(logger_, "Incorect statement for updating module_meta params");
- return false;
- }
-
- query.Bind(0, value);
- const bool result = query.Exec();
-
- if (!result) {
- LOG4CXX_WARN(logger_, "Failed update module_meta");
- }
- return result;
-}
-
-bool SQLPTExtRepresentation::RemoveAppConsentForGroup(
- const std::string& policy_app_id,
- const std::string& functional_group_name) const {
- dbms::SQLQuery query_group_id(db());
- if (!query_group_id.Prepare(sql_pt_ext::kSelectGroupId)) {
- LOG4CXX_WARN(logger_, "Incorect statement for select group name.");
- return false;
- }
-
- query_group_id.Bind(0, functional_group_name);
-
- if (!query_group_id.Exec()) {
- LOG4CXX_WARN(logger_, "Failed to select group id.");
- return false;
- }
-
- const int id = query_group_id.GetInteger(0);
-
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt_ext::kDeleteAppGroupConsent)) {
- LOG4CXX_WARN(logger_, "Incorect statement for remove app consent.");
- return false;
- }
-
- query.Bind(0, policy_app_id);
- query.Bind(1, id);
-
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed to remove app consent.");
- return false;
- }
-
- return true;
-}
-
-} // namespace policy
-
diff --git a/src/components/policy/src/policy/src/sql_pt_queries.cc b/src/components/policy/src/policy/src/sql_pt_queries.cc
deleted file mode 100644
index 150934615f..0000000000
--- a/src/components/policy/src/policy/src/sql_pt_queries.cc
+++ /dev/null
@@ -1,695 +0,0 @@
-/*
- Copyright (c) 2013, " Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, " with or without
- modification, " are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, " this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice, "
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, " INCLUDING, " BUT NOT LIMITED TO, " THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, " INDIRECT, " INCIDENTAL, " SPECIAL, " EXEMPLARY, " OR
- CONSEQUENTIAL DAMAGES (INCLUDING, " BUT NOT LIMITED TO, " PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, " DATA, " OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, " WHETHER IN
- CONTRACT, " STRICT LIABILITY, " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, " EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "policy/sql_pt_queries.h"
-
-namespace policy {
-namespace sql_pt {
-
-const std::string kSelectPriority =
- "SELECT `priority_value` FROM `application` WHERE `id` = ? LIMIT 1";
-const std::string kCreateSchema =
- "BEGIN; "
- "CREATE TABLE IF NOT EXISTS `device`( "
- " `id` VARCHAR(100) PRIMARY KEY NOT NULL, "
- " `hardware` VARCHAR(45), "
- " `firmware_rev` VARCHAR(45), "
- " `os` VARCHAR(45), "
- " `os_version` VARCHAR(45), "
- " `carrier` VARCHAR(45), "
- " `max_number_rfcom_ports` INTEGER,"
- " `connection_type` VARCHAR(45), "
- " `unpaired` BOOL "
- "); "
- "CREATE TABLE IF NOT EXISTS `usage_and_error_count`( "
- " `count_of_iap_buffer_full` INTEGER, "
- " `count_sync_out_of_memory` INTEGER, "
- " `count_of_sync_reboots` INTEGER "
- "); "
- "CREATE TABLE IF NOT EXISTS `module_meta`( "
- " `ccpu_version` VARCHAR(45), "
- " `language` VARCHAR(45), "
- " `wers_country_code` VARCHAR(45), "
- " `pt_exchanged_at_odometer_x` INTEGER NOT NULL DEFAULT 0, "
- " `pt_exchanged_x_days_after_epoch` INTEGER NOT NULL DEFAULT 0, "
- " `ignition_cycles_since_last_exchange` INTEGER NOT NULL DEFAULT 0, "
- " `vin` VARCHAR(45),"
- " `flag_update_required` BOOL NOT NULL "
- "); "
- "CREATE TABLE IF NOT EXISTS `module_config`( "
- " `preloaded_pt` BOOL NOT NULL, "
- " `is_first_run` BOOL NOT NULL, "
- " `exchange_after_x_ignition_cycles` INTEGER NOT NULL, "
- " `exchange_after_x_kilometers` INTEGER NOT NULL, "
- " `exchange_after_x_days` INTEGER NOT NULL, "
- " `timeout_after_x_seconds` INTEGER NOT NULL, "
- " `vehicle_make` VARCHAR(45), "
- " `vehicle_model` VARCHAR(45), "
- " `vehicle_year` VARCHAR(4)"
- "); "
- "CREATE TABLE IF NOT EXISTS `functional_group`( "
- " `id` INTEGER PRIMARY KEY NOT NULL, "
- " `user_consent_prompt` TEXT UNIQUE ON CONFLICT REPLACE, "
- " `name` VARCHAR(100) NOT NULL "
- "); "
- "CREATE TABLE IF NOT EXISTS `priority`( "
- " `value` VARCHAR(45) PRIMARY KEY NOT NULL "
- "); "
- "CREATE TABLE IF NOT EXISTS `hmi_level`( "
- " `value` VARCHAR(45) PRIMARY KEY NOT NULL "
- "); "
- "CREATE TABLE IF NOT EXISTS `notifications_by_priority`( "
- " `priority_value` VARCHAR(45) PRIMARY KEY NOT NULL, "
- " `value` INTEGER NOT NULL, "
- " CONSTRAINT `fk_notifications_by_priority_priority1` "
- " FOREIGN KEY(`priority_value`) "
- " REFERENCES `priority`(`value`) "
- "); "
- "CREATE INDEX IF NOT EXISTS "
- "`notifications_by_priority.fk_notifications_by_priority_priority1_idx` "
- " ON `notifications_by_priority`(`priority_value`); "
- "CREATE TABLE IF NOT EXISTS `language`( "
- " `code` VARCHAR(25) PRIMARY KEY NOT NULL "
- "); "
- "CREATE TABLE IF NOT EXISTS `message_type`( "
- " `name` VARCHAR(45) PRIMARY KEY NOT NULL "
- "); "
- "CREATE TABLE IF NOT EXISTS `version`( "
- " `number` VARCHAR(45) NOT NULL "
- "); "
- "CREATE TABLE IF NOT EXISTS `rpc`( "
- " `id` INTEGER PRIMARY KEY NOT NULL, "
- " `name` VARCHAR(45) NOT NULL, "
- " `parameter` VARCHAR(45), "
- " `hmi_level_value` VARCHAR(45) NOT NULL, "
- " `functional_group_id` INTEGER NOT NULL, "
- " CONSTRAINT `fk_rpc_hmi_level1` "
- " FOREIGN KEY(`hmi_level_value`) "
- " REFERENCES `hmi_level`(`value`), "
- " CONSTRAINT `fk_rpc_functional_group1` "
- " FOREIGN KEY(`functional_group_id`) "
- " REFERENCES `functional_group`(`id`) "
- "); "
- "CREATE INDEX IF NOT EXISTS `rpc.fk_rpc_hmi_level1_idx` "
- " ON `rpc`(`hmi_level_value`); "
- "CREATE INDEX IF NOT EXISTS `rpc.fk_rpc_functional_group1_idx` "
- " ON `rpc`(`functional_group_id`); "
- "CREATE INDEX `rpc.select_rpc_name_hmi_level` "
- " ON `rpc`(`name`,`hmi_level_value`);"
- "CREATE TABLE IF NOT EXISTS `application`( "
- " `id` VARCHAR(45) PRIMARY KEY NOT NULL, "
- " `keep_context` BOOLEAN, "
- " `steal_focus` BOOLEAN, "
- " `default_hmi` VARCHAR(45), "
- " `priority_value` VARCHAR(45), "
- " `is_revoked` BOOLEAN, "
- " `is_default` BOOLEAN, "
- " `is_predata` BOOLEAN, "
- " `memory_kb` INTEGER NOT NULL, "
- " `heart_beat_timeout_ms` INTEGER NOT NULL, "
- " `certificate` VARCHAR(45), "
- " CONSTRAINT `fk_application_hmi_level1` "
- " FOREIGN KEY(`default_hmi`) "
- " REFERENCES `hmi_level`(`value`), "
- " CONSTRAINT `fk_application_priorities1` "
- " FOREIGN KEY(`priority_value`) "
- " REFERENCES `priority`(`value`) "
- "); "
- "CREATE INDEX IF NOT EXISTS `application.fk_application_hmi_level1_idx` "
- " ON `application`(`default_hmi`); "
- "CREATE INDEX IF NOT EXISTS `application.fk_application_priorities1_idx` "
- " ON `application`(`priority_value`); "
- "CREATE TABLE IF NOT EXISTS `app_group`( "
- " `application_id` VARCHAR(45) NOT NULL, "
- " `functional_group_id` INTEGER NOT NULL, "
- " PRIMARY KEY(`application_id`,`functional_group_id`), "
- " CONSTRAINT `fk_application_has_functional_group_application1` "
- " FOREIGN KEY(`application_id`) "
- " REFERENCES `application`(`id`), "
- " CONSTRAINT `fk_application_has_functional_group_functional_group1` "
- " FOREIGN KEY(`functional_group_id`) "
- " REFERENCES `functional_group`(`id`) "
- "); "
- "CREATE INDEX IF NOT EXISTS "
- "`app_group.fk_application_has_functional_group_functional_group1_idx` "
- " ON `app_group`(`functional_group_id`); "
- "CREATE INDEX IF NOT EXISTS "
- "`app_group.fk_application_has_functional_group_application1_idx` "
- " ON `app_group`(`application_id`); "
- "CREATE TABLE IF NOT EXISTS `preconsented_group`( "
- " `application_id` VARCHAR(45) NOT NULL, "
- " `functional_group_id` INTEGER NOT NULL, "
- " PRIMARY KEY(`application_id`,`functional_group_id`), "
- " CONSTRAINT `fk_application_has_functional_group_application2` "
- " FOREIGN KEY(`application_id`) "
- " REFERENCES `application`(`id`), "
- " CONSTRAINT `fk_application_has_functional_group_functional_group2` "
- " FOREIGN KEY(`functional_group_id`) "
- " REFERENCES `functional_group`(`id`) "
- "); "
- "CREATE INDEX IF NOT EXISTS "
- "`preconsented_group.fk_application_has_functional_group_functional_group2_"
- "idx` "
- " ON `preconsented_group`(`functional_group_id`); "
- "CREATE INDEX IF NOT EXISTS "
- "`preconsented_group.fk_application_has_functional_group_application2_idx` "
- " ON `preconsented_group`(`application_id`); "
- "CREATE TABLE IF NOT EXISTS `seconds_between_retry`( "
- " `index` INTEGER PRIMARY KEY NOT NULL, "
- " `value` INTEGER NOT NULL "
- "); "
- "CREATE TABLE IF NOT EXISTS `device_consent_group`( "
- " `device_id` VARCHAR(100) NOT NULL, "
- " `functional_group_id` INTEGER NOT NULL, "
- " `is_consented` BOOL NOT NULL, "
- " `input` VARCHAR(45), "
- " `time_stamp` VARCHAR(45), "
- " PRIMARY KEY(`device_id`,`functional_group_id`), "
- " CONSTRAINT `fk_device_has_functional_group_device1` "
- " FOREIGN KEY(`device_id`) "
- " REFERENCES `device`(`id`), "
- " CONSTRAINT `fk_device_has_functional_group_functional_group1` "
- " FOREIGN KEY(`functional_group_id`) "
- " REFERENCES `functional_group`(`id`) "
- "); "
- "CREATE INDEX IF NOT EXISTS "
- "`device_consent_group.fk_device_has_functional_group_functional_group1_"
- "idx` "
- " ON `device_consent_group`(`functional_group_id`); "
- "CREATE INDEX IF NOT EXISTS "
- "`device_consent_group.fk_device_has_functional_group_device1_idx` "
- " ON `device_consent_group`(`device_id`); "
- "CREATE TABLE IF NOT EXISTS `app_level`( "
- " `application_id` VARCHAR(45) PRIMARY KEY NOT NULL, "
- " `minutes_in_hmi_full` INTEGER DEFAULT 0, "
- " `minutes_in_hmi_limited` INTEGER DEFAULT 0, "
- " `minutes_in_hmi_background` INTEGER DEFAULT 0, "
- " `minutes_in_hmi_none` INTEGER DEFAULT 0, "
- " `count_of_user_selections` INTEGER DEFAULT 0, "
- " `count_of_rejections_sync_out_of_memory` INTEGER DEFAULT 0, "
- " `count_of_rejections_nickname_mismatch` INTEGER DEFAULT 0, "
- " `count_of_rejections_duplicate_name` INTEGER DEFAULT 0, "
- " `count_of_rejected_rpcs_calls` INTEGER DEFAULT 0, "
- " `count_of_rpcs_sent_in_hmi_none` INTEGER DEFAULT 0, "
- " `count_of_removals_for_bad_behavior` INTEGER DEFAULT 0, "
- " `count_of_run_attempts_while_revoked` INTEGER DEFAULT 0, "
- " `app_registration_language_gui` VARCHAR(25), "
- " `app_registration_language_vui` VARCHAR(25), "
- " CONSTRAINT `fk_app_levels_application1` "
- " FOREIGN KEY(`application_id`) "
- " REFERENCES `application`(`id`), "
- " CONSTRAINT `fk_app_level_language1` "
- " FOREIGN KEY(`app_registration_language_gui`) "
- " REFERENCES `language`(`code`), "
- " CONSTRAINT `fk_app_level_language2` "
- " FOREIGN KEY(`app_registration_language_vui`) "
- " REFERENCES `language`(`code`) "
- "); "
- "CREATE INDEX IF NOT EXISTS `app_level.fk_app_levels_application1_idx` "
- " ON `app_level`(`application_id`); "
- "CREATE INDEX IF NOT EXISTS `app_level.fk_app_level_language1_idx` "
- " ON `app_level`(`app_registration_language_gui`); "
- "CREATE INDEX IF NOT EXISTS `app_level.fk_app_level_language2_idx` "
- " ON `app_level`(`app_registration_language_vui`); "
- "CREATE TABLE IF NOT EXISTS `nickname`( "
- " `name` VARCHAR(100) NOT NULL, "
- " `application_id` VARCHAR(45) NOT NULL, "
- " PRIMARY KEY(`name`,`application_id`), "
- " CONSTRAINT `fk_nickname_application1` "
- " FOREIGN KEY(`application_id`) "
- " REFERENCES `application`(`id`) "
- "); "
- "CREATE INDEX IF NOT EXISTS `nickname.fk_nickname_application1_idx` "
- " ON `nickname`(`application_id`); "
- "CREATE TABLE IF NOT EXISTS `app_type`( "
- " `name` VARCHAR(50) NOT NULL, "
- " `application_id` VARCHAR(45) NOT NULL, "
- " PRIMARY KEY(`name`,`application_id`), "
- " CONSTRAINT `fk_app_type_application1` "
- " FOREIGN KEY(`application_id`) "
- " REFERENCES `application`(`id`) "
- "); "
- "CREATE TABLE IF NOT EXISTS `request_type`( "
- " `request_type` VARCHAR(50) NOT NULL, "
- " `application_id` VARCHAR(45) NOT NULL, "
- " PRIMARY KEY(`request_type`,`application_id`), "
- " CONSTRAINT `fk_app_type_application1` "
- " FOREIGN KEY(`application_id`) "
- " REFERENCES `application`(`id`) "
- "); "
- "CREATE INDEX IF NOT EXISTS `app_type.fk_app_type_application1_idx` "
- " ON `app_type`(`application_id`); "
- "CREATE TABLE IF NOT EXISTS `consent_group`( "
- " `device_id` VARCHAR(100) NOT NULL, "
- " `application_id` VARCHAR(45) NOT NULL, "
- " `functional_group_id` INTEGER NOT NULL, "
- " `is_consented` BOOL NOT NULL, "
- " `input` VARCHAR(45), "
- " `time_stamp` VARCHAR(45), "
- " PRIMARY KEY(`application_id`,`functional_group_id`,`device_id`), "
- " CONSTRAINT `fk_consent_group_device1` "
- " FOREIGN KEY(`device_id`) "
- " REFERENCES `device`(`id`), "
- " CONSTRAINT `fk_consent_group_application1` "
- " FOREIGN KEY(`application_id`) "
- " REFERENCES `application`(`id`), "
- " CONSTRAINT `fk_consent_group_functional_group1` "
- " FOREIGN KEY(`functional_group_id`) "
- " REFERENCES `functional_group`(`id`) "
- "); "
- "CREATE INDEX IF NOT EXISTS "
- "`consent_group.fk_consent_group_device1_idx` "
- " ON `device_consent_group`(`device_id`); "
- "CREATE INDEX IF NOT EXISTS "
- "`consent_group.fk_consent_group_functional_group1_idx` "
- " ON `consent_group`(`functional_group_id`); "
- "CREATE TABLE IF NOT EXISTS `endpoint`( "
- " `service` VARCHAR(100) NOT NULL, "
- " `url` VARCHAR(100) NOT NULL, "
- " `application_id` VARCHAR(45) NOT NULL, "
- " CONSTRAINT `fk_endpoint_application1` "
- " FOREIGN KEY(`application_id`) "
- " REFERENCES `application`(`id`) "
- "); "
- "CREATE INDEX IF NOT EXISTS `endpoint.fk_endpoint_application1_idx` "
- " ON `endpoint`(`application_id`); "
- "CREATE TABLE IF NOT EXISTS `message`( "
- " `id` INTEGER PRIMARY KEY NOT NULL, "
- " `tts` TEXT, "
- " `label` TEXT, "
- " `line1` TEXT, "
- " `line2` TEXT, "
- " `textBody` TEXT, "
- " `language_code` VARCHAR(25) NOT NULL, "
- " `message_type_name` VARCHAR(45) NOT NULL, "
- " CONSTRAINT `fk_messages_languages1` "
- " FOREIGN KEY(`language_code`) "
- " REFERENCES `language`(`code`), "
- " CONSTRAINT `fk_message_consumer_friendly_messages1` "
- " FOREIGN KEY(`message_type_name`) "
- " REFERENCES `message_type`(`name`) "
- "); "
- "CREATE INDEX IF NOT EXISTS `message.fk_messages_languages1_idx` "
- " ON `message`(`language_code`);"
- "CREATE INDEX IF NOT EXISTS "
- "`message.fk_message_consumer_friendly_messages1_idx` "
- " ON `message`(`message_type_name`);"
- "COMMIT;";
-
-const std::string kInsertInitData =
- "INSERT OR IGNORE INTO `usage_and_error_count` ( "
- " `count_of_iap_buffer_full`, `count_sync_out_of_memory`, "
- " `count_of_sync_reboots`) VALUES (0, 0, 0); "
- "INSERT OR IGNORE INTO `module_meta` (`pt_exchanged_at_odometer_x`, "
- " `pt_exchanged_x_days_after_epoch`, "
- "`ignition_cycles_since_last_exchange`,"
- " `flag_update_required`) "
- " VALUES (0, 0, 0, 0); "
- "INSERT OR IGNORE INTO `module_config` (`preloaded_pt`, `is_first_run`,"
- " `exchange_after_x_ignition_cycles`, `exchange_after_x_kilometers`, "
- " `exchange_after_x_days`, `timeout_after_x_seconds`) "
- " VALUES(1, 0, 0, 0, 0, 0); "
- "INSERT OR IGNORE INTO `priority`(`value`) VALUES ('EMERGENCY'); "
- "INSERT OR IGNORE INTO `priority`(`value`) VALUES ('NAVIGATION'); "
- "INSERT OR IGNORE INTO `priority`(`value`) VALUES ('VOICECOMMUNICATION'); "
- "INSERT OR IGNORE INTO `priority`(`value`) VALUES ('COMMUNICATION'); "
- "INSERT OR IGNORE INTO `priority`(`value`) VALUES ('NORMAL'); "
- "INSERT OR IGNORE INTO `priority`(`value`) VALUES ('NONE'); "
- "INSERT OR IGNORE INTO `hmi_level`(`value`) VALUES ('FULL'); "
- "INSERT OR IGNORE INTO `hmi_level`(`value`) VALUES ('LIMITED'); "
- "INSERT OR IGNORE INTO `hmi_level`(`value`) VALUES ('BACKGROUND'); "
- "INSERT OR IGNORE INTO `hmi_level`(`value`) VALUES ('NONE'); "
- "INSERT OR IGNORE INTO `version` (`number`) VALUES('0'); "
- "";
-
-const std::string kDropSchema =
- "BEGIN; "
- "DROP INDEX IF EXISTS `message.fk_messages_languages1_idx`; "
- "DROP INDEX IF EXISTS "
- "`message.fk_message_consumer_friendly_messages1_idx`; "
- "DROP TABLE IF EXISTS `message`; "
- "DROP INDEX IF EXISTS `endpoint.fk_endpoint_application1_idx`; "
- "DROP TABLE IF EXISTS `endpoint`; "
- "DROP INDEX IF EXISTS `consent_group.fk_consent_group_device1_idx`; "
- "DROP INDEX IF EXISTS "
- "`consent_group.fk_consent_group_functional_group1_idx`; "
- "DROP TABLE IF EXISTS `consent_group`; "
- "DROP INDEX IF EXISTS `app_type.fk_app_type_application1_idx`; "
- "DROP TABLE IF EXISTS `app_type`; "
- "DROP INDEX IF EXISTS `nickname.fk_nickname_application1_idx`; "
- "DROP TABLE IF EXISTS `nickname`; "
- "DROP INDEX IF EXISTS `app_level.fk_app_level_language2_idx`; "
- "DROP INDEX IF EXISTS `app_level.fk_app_level_language1_idx`; "
- "DROP INDEX IF EXISTS `app_level.fk_app_levels_application1_idx`; "
- "DROP TABLE IF EXISTS `app_level`; "
- "DROP INDEX IF EXISTS "
- "`device_consent_group.fk_device_has_functional_group_device1_idx`; "
- "DROP INDEX IF EXISTS "
- "`device_consent_group.fk_device_has_functional_group_functional_group1_"
- "idx`; "
- "DROP TABLE IF EXISTS `device_consent_group`; "
- "DROP TABLE IF EXISTS `seconds_between_retry`; "
- "DROP INDEX IF EXISTS "
- "`preconsented_group.fk_application_has_functional_group_application2_idx`;"
- " "
- "DROP INDEX IF EXISTS "
- "`preconsented_group.fk_application_has_functional_group_functional_group2_"
- "idx`; "
- "DROP TABLE IF EXISTS `preconsented_group`; "
- "DROP INDEX IF EXISTS "
- "`app_group.fk_application_has_functional_group_application1_idx`; "
- "DROP INDEX IF EXISTS "
- "`app_group.fk_application_has_functional_group_functional_group1_idx`; "
- "DROP TABLE IF EXISTS `app_group`; "
- "DROP INDEX IF EXISTS `application.fk_application_priorities1_idx`; "
- "DROP INDEX IF EXISTS `application.fk_application_hmi_level1_idx`; "
- "DROP TABLE IF EXISTS `application`; "
- "DROP INDEX IF EXISTS `rpc.select_rpc_name_hmi_level`; "
- "DROP INDEX IF EXISTS `rpc.fk_rpc_functional_group1_idx`; "
- "DROP INDEX IF EXISTS `rpc.fk_rpc_hmi_level1_idx`; "
- "DROP TABLE IF EXISTS `rpc`; "
- "DROP TABLE IF EXISTS `version`; "
- "DROP TABLE IF EXISTS `message_type`; "
- "DROP TABLE IF EXISTS `language`; "
- "DROP INDEX IF EXISTS "
- "`notifications_by_priority.fk_notifications_by_priority_priority1_idx`; "
- "DROP TABLE IF EXISTS `notifications_by_priority`; "
- "DROP TABLE IF EXISTS `hmi_level`; "
- "DROP TABLE IF EXISTS `priority`; "
- "DROP TABLE IF EXISTS `functional_group`; "
- "DROP TABLE IF EXISTS `module_config`; "
- "DROP TABLE IF EXISTS `module_meta`; "
- "DROP TABLE IF EXISTS `usage_and_error_count`; "
- "DROP TABLE IF EXISTS `device`; "
- "COMMIT; "
- "VACUUM;";
-
-const std::string kDeleteData = "BEGIN; "
- "DELETE FROM `message`; "
- "DELETE FROM `endpoint`; "
- "DELETE FROM `consent_group`; "
- "DELETE FROM `app_type`; "
- "DELETE FROM `nickname`; "
- "DELETE FROM `app_level`; "
- "DELETE FROM `device_consent_group`; "
- "DELETE FROM `seconds_between_retry`; "
- "DELETE FROM `preconsented_group`; "
- "DELETE FROM `app_group`; "
- "DELETE FROM `application`; "
- "DELETE FROM `rpc`; "
- "DELETE FROM `version`; "
- "DELETE FROM `message_type`; "
- "DELETE FROM `language`; "
- "DELETE FROM `notifications_by_priority`; "
- "DELETE FROM `hmi_level`; "
- "DELETE FROM `priority`; "
- "DELETE FROM `functional_group`; "
- "DELETE FROM `module_config`; "
- "DELETE FROM `module_meta`; "
- "DELETE FROM `usage_and_error_count`; "
- "DELETE FROM `device`; "
- "COMMIT; "
- "VACUUM;";
-
-const std::string kCheckDBIntegrity = "PRAGMA integrity_check";
-
-const std::string kCheckPgNumber = "PRAGMA page_count";
-
-const std::string kSelectRpc =
- "SELECT DISTINCT `rpc`.`parameter` FROM `rpc` "
- " JOIN `app_group` AS `g` ON (`g`.`functional_group_id` = "
- "`rpc`.`functional_group_id` "
- " AND (`g`.`application_id` = ?)) "
- "WHERE `rpc`.`hmi_level_value` = ? AND `rpc`.`name` = ?";
-
-const std::string kSelectPreloaded =
- "SELECT `preloaded_pt` FROM `module_config` "
- "WHERE `preloaded_pt` = 1 LIMIT 1";
-
-const std::string kUpdatePreloaded =
- "UPDATE `module_config` SET `preloaded_pt` = ?";
-
-const std::string kIsFirstRun = "SELECT `is_first_run` FROM `module_config` ";
-
-const std::string kSetNotFirstRun =
- "UPDATE `module_config` SET `is_first_run`= 0 ";
-
-const std::string kSelectEndpoint =
- "SELECT `url`, `application_id` FROM `endpoint` WHERE `service` = ? ";
-
-const std::string kSelectLockScreenIcon =
- "SELECT `url` FROM `endpoint` WHERE `service` = ? AND `application_id` = ?";
-
-const std::string kInsertFunctionalGroup =
- "INSERT INTO `functional_group` (`id`, `name`, `user_consent_prompt`) "
- " VALUES (?, ?, ?)";
-
-const std::string kInsertRpc =
- "INSERT INTO `rpc` (`name`, `hmi_level_value`, `functional_group_id`) "
- " VALUES (?, ?, ?)";
-
-const std::string kInsertRpcWithParameter = "INSERT INTO `rpc` (`name`, "
- "`hmi_level_value`, `parameter`, "
- "`functional_group_id`) "
- " VALUES (?, ?, ?, ?)";
-
-const std::string kInsertApplication =
- "INSERT OR IGNORE INTO `application` (`id`, `priority_value`, "
- "`is_revoked`, `memory_kb`,"
- " `heart_beat_timeout_ms`, `certificate`) VALUES (?,?,?,?,?,?)";
-
-const std::string kInsertAppGroup =
- "INSERT INTO `app_group` (`application_id`, `functional_group_id`)"
- " SELECT ?, `id` FROM `functional_group` WHERE `name` = ? LIMIT 1";
-
-const std::string kInsertNickname =
- "INSERT OR IGNORE INTO `nickname` (`application_id`, `name`) VALUES (?, ?)";
-
-const std::string kInsertAppType =
- "INSERT OR IGNORE INTO `app_type` (`application_id`, `name`) VALUES (?, ?)";
-
-const std::string kInsertRequestType = "INSERT OR IGNORE INTO `request_type` "
- "(`application_id`, `request_type`) "
- "VALUES (?, ?)";
-
-const std::string kUpdateVersion = "UPDATE `version` SET `number`= ?";
-
-const std::string kInsertMessageType =
- "INSERT OR IGNORE INTO `message_type` (`name`) VALUES (?)";
-
-const std::string kInsertLanguage =
- "INSERT OR IGNORE INTO `language` (`code`) VALUES (?)";
-
-const std::string kInsertMessageString =
- "INSERT INTO `message` (`tts`, `label`, `line1`, `line2`, `language_code`, "
- " `message_type_name`, `textBody`) VALUES (?, ?, ?, ?, ?, ?, ?)";
-
-const std::string kUpdateModuleConfig =
- "UPDATE `module_config` SET `preloaded_pt` = ?, "
- " `exchange_after_x_ignition_cycles` = ?,"
- " `exchange_after_x_kilometers` = ?, `exchange_after_x_days` = ?, "
- " `timeout_after_x_seconds` = ?, `vehicle_make` = ?, "
- " `vehicle_model` = ?, `vehicle_year` = ?";
-
-const std::string kInsertEndpoint =
- "INSERT INTO `endpoint` (`service`, `url`, `application_id`) "
- " VALUES (?, ?, ?)";
-
-const std::string kInsertSecondsBetweenRetry =
- "INSERT INTO `seconds_between_retry` (`index`, `value`) VALUES (?, ?)";
-
-const std::string kInsertNotificationsByPriority =
- "INSERT OR REPLACE INTO `notifications_by_priority` (`priority_value`, "
- "`value`) "
- " VALUES (?, ?)";
-
-const std::string kInsertDeviceData =
- "INSERT OR IGNORE INTO `device` (`id`) VALUES (?)";
-
-const std::string kInsertAppLevel =
- "INSERT INTO `app_level` (`application_id`, `minutes_in_hmi_full`,"
- "`minutes_in_hmi_limited` ,`minutes_in_hmi_background`,"
- "`minutes_in_hmi_none`,`count_of_user_selections`,"
- "`count_of_rejections_sync_out_of_memory`,"
- "`count_of_rejections_nickname_mismatch`,"
- "`count_of_rejections_duplicate_name`,`count_of_rejected_rpcs_calls`,"
- "`count_of_rpcs_sent_in_hmi_none`,`count_of_removals_for_bad_behavior`,"
- "`count_of_run_attempts_while_revoked`,`app_registration_language_gui`,"
- "`app_registration_language_vui`) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
-
-const std::string kDeleteSecondsBetweenRetries =
- "DELETE FROM `seconds_between_retry`";
-
-const std::string kDeleteEndpoint = "DELETE FROM `endpoint`";
-
-const std::string kDeleteAppLevel = "DELETE FROM `app_level`";
-
-const std::string kDeleteMessageString = "DELETE FROM `message`";
-
-const std::string kDeleteFunctionalGroup = "DELETE FROM `functional_group`";
-
-const std::string kDeleteRpc = "DELETE FROM `rpc`";
-
-const std::string kDeleteAppGroup = "DELETE FROM `app_group`";
-
-const std::string kSelectModuleConfig =
- "SELECT `preloaded_pt`, `exchange_after_x_ignition_cycles`, "
- " `exchange_after_x_kilometers`, `exchange_after_x_days`, "
- " `timeout_after_x_seconds`, `vehicle_make`,"
- " `vehicle_model`, `vehicle_year` "
- " FROM `module_config`";
-
-const std::string kSelectEndpoints =
- "SELECT `url`, `service`, `application_id` FROM `endpoint` ";
-
-const std::string kSelectNotificationsPerMin =
- "SELECT `priority_value`, `value` FROM notifications_by_priority";
-
-const std::string kSelectNotificationsPerPriority =
- "SELECT `value` FROM notifications_by_priority WHERE `priority_value` = ? ";
-
-const std::string kSelectAppLevels = "SELECT `application_id` FROM `app_level`";
-
-const std::string kSelectDeviceData = "SELECT * FROM `device`";
-
-const std::string kSelectFunctionalGroups =
- "SELECT `id`,`name`, `user_consent_prompt` "
- "FROM `functional_group`";
-
-const std::string kSelectAllRpcs =
- "SELECT `name`, `hmi_level_value`, `parameter` "
- "FROM `rpc` WHERE `functional_group_id` = ? ";
-
-const std::string kSelectUserMsgsVersion =
- "SELECT DISTINCT `number` FROM `version`";
-
-const std::string kSelectAppPolicies =
- "SELECT `id`, `priority_value`, `memory_kb`, "
- " `heart_beat_timeout_ms`, `certificate` FROM `application`";
-
-const std::string kSelectAppGroups =
- "SELECT `f`.`name` FROM `app_group` AS `a`"
- " LEFT JOIN `functional_group` AS `f` "
- " ON (`f`.`id` = `a`.`functional_group_id`)"
- " WHERE `a`.`application_id` = ?";
-
-const std::string kSelectNicknames = "SELECT DISTINCT `name` FROM `nickname` "
- "WHERE `application_id` = ?";
-
-const std::string kSelectAppTypes = "SELECT DISTINCT `name` FROM `app_type` "
- "WHERE `application_id` = ?";
-
-const std::string kSelectRequestTypes = "SELECT DISTINCT `request_type` FROM "
- "`request_type` WHERE `application_id` "
- "= ?";
-
-const std::string kSelectSecondsBetweenRetries =
- "SELECT `value` FROM `seconds_between_retry` ORDER BY `index`";
-
-const std::string kSelectIgnitionCycles =
- "SELECT `c`.`exchange_after_x_ignition_cycles`, "
- " `m`.`ignition_cycles_since_last_exchange` "
- " FROM `module_config` AS `c`, `module_meta` AS `m` "
- "LIMIT 1";
-
-const std::string kSelectKilometers =
- "SELECT `c`.`exchange_after_x_kilometers`, "
- " `m`.`pt_exchanged_at_odometer_x` "
- " FROM `module_config` AS `c`, `module_meta` AS `m` "
- "LIMIT 1";
-
-const std::string kSelectDays =
- "SELECT `c`.`exchange_after_x_days`, "
- " `m`.`pt_exchanged_x_days_after_epoch` "
- " FROM `module_config` AS `c`, `module_meta` AS `m` "
- "LIMIT 1";
-
-const std::string kIncrementIgnitionCycles =
- "UPDATE `module_meta` SET `ignition_cycles_since_last_exchange` = 1 + "
- " `ignition_cycles_since_last_exchange`";
-
-const std::string kResetIgnitionCycles =
- "UPDATE `module_meta` SET `ignition_cycles_since_last_exchange` = 0";
-
-const std::string kSelectTimeoutResponse =
- "SELECT `timeout_after_x_seconds` FROM `module_config` LIMIT 1";
-
-const std::string kUpdateFlagUpdateRequired =
- "UPDATE `module_meta` SET `flag_update_required` = ?";
-
-const std::string kSelectFlagUpdateRequired =
- "SELECT `flag_update_required` FROM `module_meta` LIMIT 1";
-
-const std::string kUpdateCountersSuccessfulUpdate =
- "UPDATE `module_meta` SET `pt_exchanged_at_odometer_x` = ?,"
- "`pt_exchanged_x_days_after_epoch` = ?";
-
-const std::string kDeleteApplication = "DELETE FROM `application`";
-
-const std::string kDeleteRequestType = "DELETE FROM `request_type`";
-
-const std::string kSelectApplicationRevoked =
- "SELECT `is_revoked` FROM `application` WHERE `id` = ?";
-
-const std::string kUpdateApplicationCustomData =
- "UPDATE `application` SET `is_revoked` = ?, `is_default` = ?,"
- "`is_predata` = ? WHERE `id` = ?";
-
-const std::string kSelectApplicationRepresented =
- "SELECT COUNT(`id`) FROM `application` WHERE `id` = ?";
-
-const std::string kSelectApplicationIsDefault =
- "SELECT `is_default` FROM `application` WHERE `id` = ?";
-
-const std::string kUpdateIsDefault =
- "UPDATE `application` SET `is_default` = ? WHERE `id` = ?";
-
-const std::string kDeleteDevice = "DELETE FROM `device` WHERE `id` = ?";
-
-const std::string kDeleteAppGroupByApplicationId =
- "DELETE FROM `app_group` WHERE `application_id` = ?";
-
-const std::string kInsertApplicationFull =
- "INSERT OR IGNORE INTO `application` (`id`, `keep_context`, `steal_focus`, "
- " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
- "`is_predata`, "
- " `memory_kb`, `heart_beat_timeout_ms`, `certificate`) "
- " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
-
-const std::string kSelectApplicationFull =
- "SELECT `keep_context`, `steal_focus`, `default_hmi`, `priority_value`, "
- " `is_revoked`, `is_default`, `is_predata`, `memory_kb`,"
- " `heart_beat_timeout_ms`, `certificate` FROM `application` WHERE `id` = "
- "?";
-
-} // namespace sql_pt
-} // namespace policy
diff --git a/src/components/policy/src/policy/src/sql_pt_representation.cc b/src/components/policy/src/policy/src/sql_pt_representation.cc
deleted file mode 100644
index b0afde343e..0000000000
--- a/src/components/policy/src/policy/src/sql_pt_representation.cc
+++ /dev/null
@@ -1,1612 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <sstream>
-#include <stdlib.h>
-#include <stdint.h>
-#include <errno.h>
-#include <unistd.h>
-
-#include "utils/logger.h"
-#include "policy/sql_pt_representation.h"
-#include "policy/sql_wrapper.h"
-#include "policy/sql_pt_queries.h"
-#include "policy/policy_helper.h"
-#include "policy/cache_manager.h"
-#include "config_profile/profile.h"
-
-namespace policy {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "SQLPTRepresentation")
-
-namespace {
-template <typename T, typename K> void InsertUnique(K value, T *array) {
- uint32_t i = 0;
- for (; i < array->size() && array->at(i) != value; ++i) {
- continue;
- }
- if (array->size() == i) {
- array->push_back(value);
- }
-}
-} // namespace
-
-const std::string SQLPTRepresentation::kDatabaseName = "policy";
-
-SQLPTRepresentation::SQLPTRepresentation()
- : db_(new dbms::SQLDatabase(kDatabaseName)) {
-#ifndef __QNX__
- std::string path = profile::Profile::instance()->app_storage_folder();
- if (!path.empty()) {
- db_->set_path(path + "/");
- }
-#endif // __QNX__
-}
-
-SQLPTRepresentation::~SQLPTRepresentation() {
- db_->Close();
- delete db_;
-}
-
-void SQLPTRepresentation::CheckPermissions(const PTString &app_id,
- const PTString &hmi_level,
- const PTString &rpc,
- CheckPermissionResult &result) {
- dbms::SQLQuery query(db());
-
- if (!query.Prepare(sql_pt::kSelectRpc)) {
- LOG4CXX_WARN(logger_, "Incorrect select statement from rpcs"
- << query.LastError().text());
- return;
- }
- query.Bind(0, app_id);
- query.Bind(1, hmi_level);
- query.Bind(2, rpc);
-
- bool ret = query.Next();
- result.hmi_level_permitted = ret ? kRpcAllowed : kRpcDisallowed;
- LOG4CXX_INFO(logger_, "Level is "
- << (result.hmi_level_permitted == kRpcAllowed
- ? "permitted"
- : "not permitted"));
- std::string parameter;
- while (ret) {
- if (!query.IsNull(0)) {
- parameter = query.GetString(0);
- result.list_of_allowed_params.push_back(parameter);
- }
- ret = query.Next();
- }
-}
-
-bool SQLPTRepresentation::IsPTPreloaded() {
- dbms::SQLQuery query(db());
- return query.Prepare(sql_pt::kSelectPreloaded) && query.Next();
-}
-
-int SQLPTRepresentation::IgnitionCyclesBeforeExchange() {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectIgnitionCycles) || !query.Exec()) {
- LOG4CXX_WARN(logger_, "Can not select ignition cycles");
- return 0;
- }
- int limit = query.GetInteger(0);
- int current = query.GetInteger(1);
-
- if (limit < 0 || current < 0 || current > limit) {
- return 0;
- }
-
- return limit - current;
-}
-
-int SQLPTRepresentation::KilometersBeforeExchange(int current) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectKilometers) || !query.Exec()) {
- LOG4CXX_WARN(logger_, "Can not select kilometers");
- return 0;
- }
- int limit = query.GetInteger(0);
- int last = query.GetInteger(1);
-
- if (limit < 0 || last < 0 || current < 0 || current < last ||
- limit < (current - last)) {
- return 0;
- }
-
- return limit - (current - last);
-}
-
-bool SQLPTRepresentation::SetCountersPassedForSuccessfulUpdate(
- int kilometers, int days_after_epoch) {
- LOG4CXX_AUTO_TRACE(logger_);
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kUpdateCountersSuccessfulUpdate)) {
- LOG4CXX_WARN(logger_,
- "Wrong update query for counters on successful update.");
- return false;
- }
- query.Bind(0, kilometers);
- query.Bind(1, days_after_epoch);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed to update counters on successful update.");
- return false;
- }
- return true;
-}
-
-int SQLPTRepresentation::DaysBeforeExchange(int current) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectDays) || !query.Exec()) {
- LOG4CXX_WARN(logger_, "Can not select days");
- return 0;
- }
- int limit = query.GetInteger(0);
- int last = query.GetInteger(1);
-
- if (0 == last) {
- return limit;
- }
-
- if (limit < 0 || last < 0 || current < 0 || current < last ||
- limit < (current - last)) {
- return 0;
- }
-
- return limit - (current - last);
-}
-
-int SQLPTRepresentation::TimeoutResponse() {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectTimeoutResponse) || !query.Exec()) {
- LOG4CXX_INFO(logger_, "Can not select timeout response for retry sequence");
- const int kDefault = 30;
- return kDefault;
- }
- return query.GetInteger(0);
-}
-
-bool SQLPTRepresentation::SecondsBetweenRetries(std::vector<int> *seconds) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectSecondsBetweenRetries)) {
- LOG4CXX_INFO(logger_,
- "Incorrect select statement from seconds between retries");
- return false;
- }
- while (query.Next()) {
- seconds->push_back(query.GetInteger(0));
- }
- return true;
-}
-
-std::vector<UserFriendlyMessage> SQLPTRepresentation::GetUserFriendlyMsg(
- const std::vector<std::string> &msg_codes, const std::string &language) {
- std::vector<UserFriendlyMessage> result;
- std::vector<std::string>::const_iterator it = msg_codes.begin();
- std::vector<std::string>::const_iterator it_end = msg_codes.end();
- for (; it != it_end; ++it) {
- UserFriendlyMessage msg;
- msg.message_code = *it;
- result.push_back(msg);
- }
- return result;
-}
-
-EndpointUrls SQLPTRepresentation::GetUpdateUrls(int service_type) {
- LOG4CXX_INFO(logger_, "SQLPTRepresentation::GetUpdateUrls for "
- << service_type);
- dbms::SQLQuery query(db());
- EndpointUrls ret;
- if (query.Prepare(sql_pt::kSelectEndpoint)) {
- query.Bind(0, service_type);
- while (query.Next()) {
- EndpointData data;
-
- data.url.push_back(query.GetString(0));
- if (!query.IsNull(1)) {
- data.app_id = query.GetString(1);
- }
- ret.push_back(data);
- }
- } else {
- LOG4CXX_WARN(logger_, "Invalid select endpoints statement.");
- }
- return ret;
-}
-
-std::string SQLPTRepresentation::GetLockScreenIconUrl() const {
- dbms::SQLQuery query(db());
- std::string ret;
- if (query.Prepare(sql_pt::kSelectLockScreenIcon)) {
- query.Bind(0, std::string("lock_screen_icon_url"));
- query.Bind(1, std::string("default"));
-
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrect select from notifications by priority.");
- return ret;
- }
-
- if (!query.IsNull(0)) {
- ret = query.GetString(0);
- }
-
- } else {
- LOG4CXX_WARN(logger_, "Invalid select endpoints statement.");
- }
- return ret;
-}
-
-int SQLPTRepresentation::GetNotificationsNumber(const std::string &priority) {
- LOG4CXX_INFO(logger_, "GetNotificationsNumber");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectNotificationsPerPriority)) {
- LOG4CXX_WARN(logger_, "Incorrect select statement for priority "
- "notification number.");
- return 0;
- }
- query.Bind(0, priority);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrect select from notifications by priority.");
- return 0;
- }
-
- if (!query.IsNull(0)) {
- return query.GetInteger(0);
- }
-
- return 0;
-}
-
-bool SQLPTRepresentation::GetPriority(const std::string &policy_app_id,
- std::string *priority) {
- LOG4CXX_INFO(logger_, "GetPriority");
- if (NULL == priority) {
- LOG4CXX_WARN(logger_, "Input priority parameter is null.");
- return false;
- }
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectPriority)) {
- LOG4CXX_INFO(logger_, "Incorrect statement for priority.");
- return false;
- }
-
- query.Bind(0, policy_app_id);
-
- if (!query.Exec()) {
- LOG4CXX_INFO(logger_, "Error during select priority.");
- return false;
- }
-
- if (query.IsNull(0)) {
- priority->clear();
- return true;
- }
-
- priority->assign(query.GetString(0));
-
- return true;
-}
-
-InitResult SQLPTRepresentation::Init() {
- LOG4CXX_AUTO_TRACE(logger_);
-
- if (!db_->Open()) {
- LOG4CXX_ERROR(logger_, "Failed opening database.");
- LOG4CXX_INFO(logger_, "Starting opening retries.");
- const uint16_t attempts =
- profile::Profile::instance()->attempts_to_open_policy_db();
- LOG4CXX_DEBUG(logger_, "Total attempts number is: " << attempts);
- bool is_opened = false;
- const uint16_t open_attempt_timeout_ms =
- profile::Profile::instance()->open_attempt_timeout_ms();
- const useconds_t sleep_interval_mcsec = open_attempt_timeout_ms * 1000;
- LOG4CXX_DEBUG(logger_,
- "Open attempt timeout(ms) is: " << open_attempt_timeout_ms);
- for (int i = 0; i < attempts; ++i) {
- usleep(sleep_interval_mcsec);
- LOG4CXX_INFO(logger_, "Attempt: " << i + 1);
- if (db_->Open()) {
- LOG4CXX_INFO(logger_, "Database opened.");
- is_opened = true;
- break;
- }
- }
- if (!is_opened) {
- LOG4CXX_ERROR(logger_, "Open retry sequence failed. Tried "
- << attempts << " attempts with "
- << open_attempt_timeout_ms
- << " open timeout(ms) for each.");
- return InitResult::FAIL;
- }
- }
-#ifndef __QNX__
- if (!db_->IsReadWrite()) {
- LOG4CXX_ERROR(logger_, "There are no read/write permissions for database");
- return InitResult::FAIL;
- }
-#endif // __QNX__
- dbms::SQLQuery check_pages(db());
- if (!check_pages.Prepare(sql_pt::kCheckPgNumber) || !check_pages.Next()) {
- LOG4CXX_WARN(logger_, "Incorrect pragma for page counting.");
- } else {
- if (0 < check_pages.GetInteger(0)) {
- dbms::SQLQuery db_check(db());
- if (!db_check.Prepare(sql_pt::kCheckDBIntegrity)) {
- LOG4CXX_WARN(logger_, "Incorrect pragma for integrity check.");
- } else {
- while (db_check.Next()) {
- if (db_check.GetString(0).compare("ok") == 0) {
- dbms::SQLQuery check_first_run(db());
- if (check_first_run.Prepare(sql_pt::kIsFirstRun) &&
- check_first_run.Next()) {
- LOG4CXX_INFO(logger_, "Selecting is first run "
- << check_first_run.GetBoolean(0));
- if (check_first_run.GetBoolean(0)) {
- dbms::SQLQuery set_not_first_run(db());
- set_not_first_run.Exec(sql_pt::kSetNotFirstRun);
- return InitResult::SUCCESS;
- }
- } else {
- LOG4CXX_WARN(logger_, "Incorrect select is first run");
- }
- return InitResult::EXISTS;
- } else {
- LOG4CXX_ERROR(logger_,
- "Existing policy table representation is invlaid.");
- // TODO(PV): add handle
- return InitResult::FAIL;
- }
- }
- }
- }
- }
- dbms::SQLQuery query(db());
- if (!query.Exec(sql_pt::kCreateSchema)) {
- LOG4CXX_ERROR(logger_, "Failed creating schema of database: "
- << query.LastError().text());
- return InitResult::FAIL;
- }
- if (!query.Exec(sql_pt::kInsertInitData)) {
- LOG4CXX_ERROR(logger_, "Failed insert init data to database: "
- << query.LastError().text());
- return InitResult::FAIL;
- }
- return InitResult::SUCCESS;
-}
-
-bool SQLPTRepresentation::Close() {
- db_->Close();
- return db_->LastError().number() == dbms::OK;
-}
-
-VehicleData SQLPTRepresentation::GetVehicleData() { return VehicleData(); }
-
-bool SQLPTRepresentation::Drop() {
- dbms::SQLQuery query(db());
- if (!query.Exec(sql_pt::kDropSchema)) {
- LOG4CXX_WARN(logger_,
- "Failed dropping database: " << query.LastError().text());
- return false;
- }
- return true;
-}
-
-void SQLPTRepresentation::WriteDb() { db_->Backup(); }
-
-bool SQLPTRepresentation::Clear() {
- dbms::SQLQuery query(db());
- if (!query.Exec(sql_pt::kDeleteData)) {
- LOG4CXX_ERROR(logger_,
- "Failed clearing database: " << query.LastError().text());
- return false;
- }
- if (!query.Exec(sql_pt::kInsertInitData)) {
- LOG4CXX_ERROR(logger_, "Failed insert init data to database: "
- << query.LastError().text());
- return false;
- }
- return true;
-}
-
-bool SQLPTRepresentation::RefreshDB() {
- dbms::SQLQuery query(db());
- if (!query.Exec(sql_pt::kDropSchema)) {
- LOG4CXX_WARN(logger_,
- "Failed dropping database: " << query.LastError().text());
- return false;
- }
- if (!query.Exec(sql_pt::kCreateSchema)) {
- LOG4CXX_ERROR(logger_, "Failed creating schema of database: "
- << query.LastError().text());
- return false;
- }
- if (!query.Exec(sql_pt::kInsertInitData)) {
- LOG4CXX_ERROR(logger_, "Failed insert init data to database: "
- << query.LastError().text());
- return false;
- }
- return true;
-}
-
-utils::SharedPtr<policy_table::Table>
-SQLPTRepresentation::GenerateSnapshot() const {
- LOG4CXX_INFO(logger_, "GenerateSnapshot");
- utils::SharedPtr<policy_table::Table> table = new policy_table::Table();
- GatherModuleMeta(&*table->policy_table.module_meta);
- GatherModuleConfig(&table->policy_table.module_config);
- GatherUsageAndErrorCounts(&*table->policy_table.usage_and_error_counts);
- GatherDeviceData(&*table->policy_table.device_data);
- GatherFunctionalGroupings(&table->policy_table.functional_groupings);
- GatherConsumerFriendlyMessages(
- &*table->policy_table.consumer_friendly_messages);
- GatherApplicationPoliciesSection(&table->policy_table.app_policies_section);
- return table;
-}
-
-void SQLPTRepresentation::GatherModuleMeta(
- policy_table::ModuleMeta *meta) const {
- LOG4CXX_INFO(logger_, "Gather Module Meta Info");
- meta->mark_initialized();
- // Section Module Meta is empty for SDL specific
-}
-
-void SQLPTRepresentation::GatherModuleConfig(
- policy_table::ModuleConfig *config) const {
- LOG4CXX_INFO(logger_, "Gather Configuration Info");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectModuleConfig) || !query.Next()) {
- LOG4CXX_WARN(logger_, "Incorrect select statement for module config");
- } else {
- *config->preloaded_pt = query.GetBoolean(0);
- config->exchange_after_x_ignition_cycles = query.GetInteger(1);
- config->exchange_after_x_kilometers = query.GetInteger(2);
- config->exchange_after_x_days = query.GetInteger(3);
- config->timeout_after_x_seconds = query.GetInteger(4);
- *config->vehicle_make = query.GetString(5);
- *config->vehicle_model = query.GetString(6);
- *config->vehicle_year = query.GetString(7);
- }
-
- dbms::SQLQuery endpoints(db());
- if (!endpoints.Prepare(sql_pt::kSelectEndpoints)) {
- LOG4CXX_WARN(logger_, "Incorrect select statement for endpoints");
- } else {
- while (endpoints.Next()) {
- config->endpoints[endpoints.GetString(1)][endpoints.GetString(2)]
- .push_back(endpoints.GetString(0));
- }
- }
-
- dbms::SQLQuery notifications(db());
- if (!notifications.Prepare(sql_pt::kSelectNotificationsPerMin)) {
- LOG4CXX_WARN(logger_, "Incorrect select statement for notifications");
- } else {
- while (notifications.Next()) {
- config->notifications_per_minute_by_priority[notifications.GetString(0)] =
- notifications.GetInteger(1);
- }
- }
- dbms::SQLQuery seconds(db());
- if (!seconds.Prepare(sql_pt::kSelectSecondsBetweenRetries)) {
- LOG4CXX_INFO(logger_,
- "Incorrect select statement from seconds between retries");
- } else {
- while (seconds.Next()) {
- config->seconds_between_retries.push_back(seconds.GetInteger(0));
- }
- }
-}
-
-bool SQLPTRepresentation::GatherUsageAndErrorCounts(
- policy_table::UsageAndErrorCounts *counts) const {
- LOG4CXX_INFO(logger_, "Gather Usage and Error Counts.");
- dbms::SQLQuery query(db());
- if (query.Prepare(sql_pt::kSelectAppLevels)) {
- policy_table::AppLevel app_level_empty;
- app_level_empty.mark_initialized();
- while (query.Next()) {
- (*counts->app_level)[query.GetString(0)] = app_level_empty;
- }
- }
- return true;
-}
-
-void SQLPTRepresentation::GatherDeviceData(
- policy_table::DeviceData *data) const {
- LOG4CXX_INFO(logger_, "Gather device data.");
- data->mark_initialized();
-
- dbms::SQLQuery query(db());
- if (query.Prepare(sql_pt::kSelectDeviceData)) {
- policy_table::DeviceParams device_data_empty;
- device_data_empty.mark_initialized();
- while (query.Next()) {
- (*data)[query.GetString(0)] = device_data_empty;
- }
- }
-}
-
-bool SQLPTRepresentation::GatherFunctionalGroupings(
- policy_table::FunctionalGroupings *groups) const {
- LOG4CXX_INFO(logger_, "Gather Functional Groupings info");
- dbms::SQLQuery func_group(db());
- if (!func_group.Prepare(sql_pt::kSelectFunctionalGroups)) {
- LOG4CXX_WARN(logger_, "Incorrect select from functional_groupings");
- return false;
- }
- dbms::SQLQuery rpcs(db());
- if (!rpcs.Prepare(sql_pt::kSelectAllRpcs)) {
- LOG4CXX_WARN(logger_, "Incorrect select all from rpc");
- return false;
- }
- while (func_group.Next()) {
- policy_table::Rpcs rpcs_tbl;
- if (!func_group.IsNull(2)) {
- *rpcs_tbl.user_consent_prompt = func_group.GetString(2);
- }
- int func_id = func_group.GetInteger(0);
- rpcs.Bind(0, func_id);
- while (rpcs.Next()) {
- if (!rpcs.IsNull(1)) {
- policy_table::HmiLevel level;
- if (policy_table::EnumFromJsonString(rpcs.GetString(1), &level)) {
- InsertUnique(level, &rpcs_tbl.rpcs[rpcs.GetString(0)].hmi_levels);
- }
- }
- if (!rpcs.IsNull(2)) {
- policy_table::Parameter param;
- if (policy_table::EnumFromJsonString(rpcs.GetString(2), &param)) {
- InsertUnique(param, &(*rpcs_tbl.rpcs[rpcs.GetString(0)].parameters));
- }
- }
- }
- if (!rpcs_tbl.rpcs.is_initialized()) {
- rpcs_tbl.rpcs.set_to_null();
- }
- rpcs.Reset();
- (*groups)[func_group.GetString(1)] = rpcs_tbl;
- }
- return true;
-}
-
-bool SQLPTRepresentation::GatherConsumerFriendlyMessages(
- policy_table::ConsumerFriendlyMessages *messages) const {
- LOG4CXX_INFO(logger_, "Gather Consumer Friendly Messages");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectUserMsgsVersion) || !query.Next()) {
- LOG4CXX_WARN(logger_, "Incorrect select from consumer_friendly_messages");
- return false;
- }
- messages->version = query.GetString(0);
- return true;
-}
-
-bool SQLPTRepresentation::GatherApplicationPoliciesSection(
- policy_table::ApplicationPoliciesSection *policies) const {
- LOG4CXX_INFO(logger_, "Gather applications policies");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectAppPolicies)) {
- LOG4CXX_WARN(logger_, "Incorrect select from app_policies");
- return false;
- }
-
- while (query.Next()) {
- rpc::Nullable<policy_table::ApplicationParams> params;
- const std::string &app_id = query.GetString(0);
- if (IsApplicationRevoked(app_id)) {
- params.set_to_null();
- (*policies).apps[app_id] = params;
- continue;
- }
- if (IsDefaultPolicy(app_id)) {
- (*policies).apps[app_id].set_to_string(kDefaultId);
- }
- if (IsPredataPolicy(app_id)) {
- (*policies).apps[app_id].set_to_string(kPreDataConsentId);
- }
- if (kDeviceId == app_id) {
- // Priority is only SDL-specific item for device
- policy_table::Priority priority;
- policy_table::EnumFromJsonString(query.GetString(1), &priority);
- (*policies).device.priority = priority;
- continue;
- }
- policy_table::Priority priority;
- policy_table::EnumFromJsonString(query.GetString(1), &priority);
- params.priority = priority;
-
- *params.memory_kb = query.GetInteger(2);
- *params.heart_beat_timeout_ms = query.GetInteger(3);
- if (!query.IsNull(3)) {
- *params.certificate = query.GetString(4);
- }
- if (!GatherAppGroup(app_id, &params.groups)) {
- return false;
- }
- if (!GatherNickName(app_id, &*params.nicknames)) {
- return false;
- }
- if (!GatherAppType(app_id, &*params.AppHMIType)) {
- return false;
- }
- if (!GatherRequestType(app_id, &*params.RequestType)) {
- return false;
- }
-
- (*policies).apps[app_id] = params;
- }
- return true;
-}
-
-bool SQLPTRepresentation::Save(const policy_table::Table &table) {
- LOG4CXX_AUTO_TRACE(logger_);
- db_->BeginTransaction();
- if (!SaveFunctionalGroupings(table.policy_table.functional_groupings)) {
- db_->RollbackTransaction();
- return false;
- }
- if (!SaveApplicationPoliciesSection(
- table.policy_table.app_policies_section)) {
- db_->RollbackTransaction();
- return false;
- }
- if (!SaveModuleConfig(table.policy_table.module_config)) {
- db_->RollbackTransaction();
- return false;
- }
- if (!SaveConsumerFriendlyMessages(
- *table.policy_table.consumer_friendly_messages)) {
- db_->RollbackTransaction();
- return false;
- }
-
- if (!SaveDeviceData(*table.policy_table.device_data)) {
- db_->RollbackTransaction();
- return false;
- }
- if (!SaveUsageAndErrorCounts(*table.policy_table.usage_and_error_counts)) {
- db_->RollbackTransaction();
- return false;
- }
- if (!SaveModuleMeta(*table.policy_table.module_meta)) {
- db_->RollbackTransaction();
- return false;
- }
- db_->CommitTransaction();
- return true;
-}
-
-bool SQLPTRepresentation::SaveFunctionalGroupings(
- const policy_table::FunctionalGroupings &groups) {
- dbms::SQLQuery query_delete(db());
- if (!query_delete.Exec(sql_pt::kDeleteRpc)) {
- LOG4CXX_WARN(logger_, "Incorrect delete from rpc.");
- return false;
- }
-
- dbms::SQLQuery query(db());
- if (!query.Exec(sql_pt::kDeleteFunctionalGroup)) {
- LOG4CXX_WARN(logger_, "Incorrect delete from seconds between retries.");
- return false;
- }
- if (!query.Prepare(sql_pt::kInsertFunctionalGroup)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for functional groups");
- return false;
- }
-
- policy_table::FunctionalGroupings::const_iterator it;
-
- for (it = groups.begin(); it != groups.end(); ++it) {
- // Since we uses this id in other tables, we have to be sure
- // that id for certain group will be same in case when
- // we drop records from the table and add them again.
- // That's why we use hash as a primary key insted of
- // simple auto incremental index.
- const long int id = abs(CacheManager::GenerateHash(it->first));
- // SQLite's Bind doesn support 'long' type
- // So we need to explicitly cast it to int64_t
- // to avoid ambiguity.
- query.Bind(0, static_cast<int64_t>(id));
- query.Bind(1, it->first);
- it->second.user_consent_prompt.is_initialized()
- ? query.Bind(2, *(it->second.user_consent_prompt))
- : query.Bind(2);
-
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into functional groups");
- return false;
- }
-
- if (!SaveRpcs(query.LastInsertId(), it->second.rpcs)) {
- return false;
- }
- }
- return true;
-}
-
-bool SQLPTRepresentation::SaveRpcs(int64_t group_id,
- const policy_table::Rpc &rpcs) {
- dbms::SQLQuery query(db());
- dbms::SQLQuery query_parameter(db());
- if (!query.Prepare(sql_pt::kInsertRpc) ||
- !query_parameter.Prepare(sql_pt::kInsertRpcWithParameter)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for rpc");
- return false;
- }
-
- policy_table::Rpc::const_iterator it;
- for (it = rpcs.begin(); it != rpcs.end(); ++it) {
- const policy_table::HmiLevels &hmi_levels = it->second.hmi_levels;
- // TODO(IKozyrenko): Check logic if optional container is missing
- const policy_table::Parameters &parameters = *it->second.parameters;
- policy_table::HmiLevels::const_iterator hmi_it;
- policy_table::Parameters::const_iterator ps_it;
- for (hmi_it = hmi_levels.begin(); hmi_it != hmi_levels.end(); ++hmi_it) {
- if (!parameters.empty()) {
- for (ps_it = parameters.begin(); ps_it != parameters.end(); ++ps_it) {
- query_parameter.Bind(0, it->first);
- query_parameter.Bind(
- 1, std::string(policy_table::EnumToJsonString(*hmi_it)));
- query_parameter.Bind(
- 2, std::string(policy_table::EnumToJsonString(*ps_it)));
- query_parameter.Bind(3, group_id);
- if (!query_parameter.Exec() || !query_parameter.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into rpc with parameter");
- return false;
- }
- }
- } else {
- query.Bind(0, it->first);
- query.Bind(1, std::string(policy_table::EnumToJsonString(*hmi_it)));
- query.Bind(2, group_id);
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into rpc");
- return false;
- }
- }
- }
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveApplicationPoliciesSection(
- const policy_table::ApplicationPoliciesSection &policies) {
- dbms::SQLQuery query_delete(db());
- if (!query_delete.Exec(sql_pt::kDeleteAppGroup)) {
- LOG4CXX_WARN(logger_, "Incorrect delete from app_group.");
- return false;
- }
- if (!query_delete.Exec(sql_pt::kDeleteApplication)) {
- LOG4CXX_WARN(logger_, "Incorrect delete from application.");
- return false;
- }
-
- if (!query_delete.Exec(sql_pt::kDeleteRequestType)) {
- LOG4CXX_WARN(logger_, "Incorrect delete from request type.");
- return false;
- }
-
- // All predefined apps (e.g. default, pre_DataConsent) should be saved first,
- // otherwise another app with the predefined permissions can get incorrect
- // permissions
- policy_table::ApplicationPolicies::const_iterator it_default =
- policies.apps.find(kDefaultId);
- if (policies.apps.end() != it_default) {
- if (!SaveSpecificAppPolicy(*it_default)) {
- return false;
- }
- }
- policy_table::ApplicationPolicies::const_iterator it_pre_data_consented =
- policies.apps.find(kPreDataConsentId);
- if (policies.apps.end() != it_pre_data_consented) {
- if (!SaveSpecificAppPolicy(*it_pre_data_consented)) {
- return false;
- }
- }
-
- if (!SaveDevicePolicy(policies.device)) {
- return false;
- }
-
- policy_table::ApplicationPolicies::const_iterator it;
- for (it = policies.apps.begin(); it != policies.apps.end(); ++it) {
- // Skip saving of predefined app, since they should be saved before
- if (IsPredefinedApp(*it)) {
- continue;
- }
- if (!SaveSpecificAppPolicy(*it)) {
- return false;
- }
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveSpecificAppPolicy(
- const policy_table::ApplicationPolicies::value_type &app) {
- dbms::SQLQuery app_query(db());
- if (!app_query.Prepare(sql_pt::kInsertApplication)) {
- LOG4CXX_WARN(logger_,
- "Incorrect insert statement into application (device).");
- return false;
- }
-
- app_query.Bind(0, app.first);
- app_query.Bind(
- 1, std::string(policy_table::EnumToJsonString(app.second.priority)));
- app_query.Bind(2, app.second.is_null());
- app_query.Bind(3, *app.second.memory_kb);
- app_query.Bind(4, *app.second.heart_beat_timeout_ms);
- app.second.certificate.is_initialized()
- ? app_query.Bind(5, *app.second.certificate)
- : app_query.Bind(5);
-
- if (!app_query.Exec() || !app_query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into application.");
- return false;
- }
-
- if (app.second.is_string()) {
- if (kDefaultId.compare(app.second.get_string()) == 0) {
- if (!SetDefaultPolicy(app.first)) {
- return false;
- }
- // Stop saving other params, since predefined permissions already set
- return true;
- }
- }
-
- if (!SaveAppGroup(app.first, app.second.groups)) {
- return false;
- }
- if (!SaveNickname(app.first, *app.second.nicknames)) {
- return false;
- }
- if (!SaveAppType(app.first, *app.second.AppHMIType)) {
- return false;
- }
-
- if (!SaveRequestType(app.first, *app.second.RequestType)) {
- return false;
- }
-
- return true;
-}
-
-bool policy::SQLPTRepresentation::SaveDevicePolicy(
- const policy_table::DevicePolicy &device) {
- dbms::SQLQuery app_query(db());
- if (!app_query.Prepare(sql_pt::kInsertApplication)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement into application.");
- return false;
- }
-
- app_query.Bind(0, kDeviceId);
- app_query.Bind(1,
- std::string(policy_table::EnumToJsonString(device.priority)));
- app_query.Bind(2, false);
- app_query.Bind(3, 0);
- app_query.Bind(4, 0);
- app_query.Bind(5);
-
- if (!app_query.Exec() || !app_query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into application.");
- return false;
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveAppGroup(
- const std::string &app_id, const policy_table::Strings &app_groups) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kInsertAppGroup)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for app group");
- return false;
- }
- LOG4CXX_INFO(logger_, "SaveAppGroup");
- policy_table::Strings::const_iterator it;
- for (it = app_groups.begin(); it != app_groups.end(); ++it) {
- std::string ssss = *it;
- LOG4CXX_INFO(logger_, "Group: " << ssss);
- query.Bind(0, app_id);
- query.Bind(1, *it);
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into app group."
- << query.LastError().text());
- return false;
- }
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveNickname(const std::string &app_id,
- const policy_table::Strings &nicknames) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kInsertNickname)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for nickname");
- return false;
- }
-
- policy_table::Strings::const_iterator it;
- for (it = nicknames.begin(); it != nicknames.end(); ++it) {
- query.Bind(0, app_id);
- query.Bind(1, *it);
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into nickname.");
- return false;
- }
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveAppType(const std::string &app_id,
- const policy_table::AppHMITypes &types) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kInsertAppType)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for app type");
- return false;
- }
-
- policy_table::AppHMITypes::const_iterator it;
- for (it = types.begin(); it != types.end(); ++it) {
- query.Bind(0, app_id);
- query.Bind(1, std::string(policy_table::EnumToJsonString(*it)));
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into app type.");
- return false;
- }
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveRequestType(
- const std::string &app_id, const policy_table::RequestTypes &types) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kInsertRequestType)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for request types.");
- return false;
- }
-
- policy_table::RequestTypes::const_iterator it;
- for (it = types.begin(); it != types.end(); ++it) {
- query.Bind(0, app_id);
- query.Bind(1, std::string(policy_table::EnumToJsonString(*it)));
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into request types.");
- return false;
- }
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveModuleMeta(const policy_table::ModuleMeta &meta) {
- // Section Module Meta is empty for SDL specific
- return true;
-}
-
-bool SQLPTRepresentation::SaveModuleConfig(
- const policy_table::ModuleConfig &config) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kUpdateModuleConfig)) {
- LOG4CXX_WARN(logger_, "Incorrect update statement for module config");
- return false;
- }
-
- bool is_preloaded =
- config.preloaded_pt.is_initialized() && *config.preloaded_pt;
-
- query.Bind(0, is_preloaded);
- query.Bind(1, config.exchange_after_x_ignition_cycles);
- query.Bind(2, config.exchange_after_x_kilometers);
- query.Bind(3, config.exchange_after_x_days);
- query.Bind(4, config.timeout_after_x_seconds);
- config.vehicle_make.is_initialized() ? query.Bind(5, *(config.vehicle_make))
- : query.Bind(5);
- config.vehicle_model.is_initialized() ? query.Bind(6, *(config.vehicle_model))
- : query.Bind(6);
- config.vehicle_year.is_initialized() ? query.Bind(7, *(config.vehicle_year))
- : query.Bind(7);
-
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrect update module config");
- return false;
- }
-
- if (!SaveSecondsBetweenRetries(config.seconds_between_retries)) {
- return false;
- }
-
- if (!SaveNumberOfNotificationsPerMinute(
- config.notifications_per_minute_by_priority)) {
- return false;
- }
-
- if (!SaveServiceEndpoints(config.endpoints)) {
- return false;
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveServiceEndpoints(
- const policy_table::ServiceEndpoints &endpoints) {
- dbms::SQLQuery query(db());
- if (!query.Exec(sql_pt::kDeleteEndpoint)) {
- LOG4CXX_WARN(logger_, "Incorrect delete from endpoint.");
- return false;
- }
-
- if (!query.Prepare(sql_pt::kInsertEndpoint)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for endpoint");
- return false;
- }
-
- policy_table::ServiceEndpoints::const_iterator it;
- for (it = endpoints.begin(); it != endpoints.end(); ++it) {
- const policy_table::URLList &apps = it->second;
- policy_table::URLList::const_iterator app_it;
- for (app_it = apps.begin(); app_it != apps.end(); ++app_it) {
- const policy_table::URL &urls = app_it->second;
- policy_table::URL::const_iterator url_it;
- for (url_it = urls.begin(); url_it != urls.end(); ++url_it) {
- query.Bind(0, it->first);
- query.Bind(1, *url_it);
- query.Bind(2, app_it->first);
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into endpoint");
- return false;
- }
- }
- }
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveConsumerFriendlyMessages(
- const policy_table::ConsumerFriendlyMessages &messages) {
- LOG4CXX_AUTO_TRACE(logger_);
-
- // According CRS-2419 If there is no “consumer_friendly_messages” key,
- // the current local consumer_friendly_messages section shall be maintained in
- // the policy table. So it won't be changed/updated
- if (messages.messages.is_initialized()) {
- dbms::SQLQuery query(db());
- if (!query.Exec(sql_pt::kDeleteMessageString)) {
- LOG4CXX_WARN(logger_, "Incorrect delete from message.");
- return false;
- }
-
- if (query.Prepare(sql_pt::kUpdateVersion)) {
- query.Bind(0, messages.version);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrect update into version.");
- return false;
- }
- } else {
- LOG4CXX_WARN(logger_, "Incorrect update statement for version.");
- return false;
- }
-
- policy_table::Messages::const_iterator it;
- // TODO(IKozyrenko): Check logic if optional container is missing
- for (it = messages.messages->begin(); it != messages.messages->end();
- ++it) {
- if (!SaveMessageType(it->first)) {
- return false;
- }
- const policy_table::Languages &langs = it->second.languages;
- policy_table::Languages::const_iterator lang_it;
- for (lang_it = langs.begin(); lang_it != langs.end(); ++lang_it) {
- if (!SaveLanguage(lang_it->first)) {
- return false;
- }
- if (!SaveMessageString(it->first, lang_it->first, lang_it->second)) {
- return false;
- }
- }
- }
- } else {
- LOG4CXX_INFO(logger_, "Messages list is empty");
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveMessageType(const std::string &type) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kInsertMessageType)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for message type.");
- return false;
- }
-
- query.Bind(0, type);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into message type.");
- return false;
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveLanguage(const std::string &code) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kInsertLanguage)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for language.");
- return false;
- }
-
- query.Bind(0, code);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into language.");
- return false;
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveMessageString(
- const std::string &type, const std::string &lang,
- const policy_table::MessageString &strings) {
- // Section is empty for SDL specific
- return true;
-}
-
-bool SQLPTRepresentation::SaveSecondsBetweenRetries(
- const policy_table::SecondsBetweenRetries &seconds) {
- dbms::SQLQuery query(db());
- if (!query.Exec(sql_pt::kDeleteSecondsBetweenRetries)) {
- LOG4CXX_WARN(logger_, "Incorrect delete from seconds between retries.");
- return false;
- }
- if (!query.Prepare(sql_pt::kInsertSecondsBetweenRetry)) {
- LOG4CXX_WARN(logger_,
- "Incorrect insert statement for seconds between retries.");
- return false;
- }
-
- for (uint32_t i = 0; i < seconds.size(); ++i) {
- query.Bind(0, static_cast<int>(i));
- query.Bind(1, seconds[i]);
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into seconds between retries.");
- return false;
- }
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveNumberOfNotificationsPerMinute(
- const policy_table::NumberOfNotificationsPerMinute &notifications) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kInsertNotificationsByPriority)) {
- LOG4CXX_WARN(logger_,
- "Incorrect insert statement for notifications by priority.");
- return false;
- }
-
- policy_table::NumberOfNotificationsPerMinute::const_iterator it;
- for (it = notifications.begin(); it != notifications.end(); ++it) {
- query.Bind(0, it->first);
- query.Bind(1, it->second);
- if (!query.Exec() || !query.Reset()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into notifications by priority.");
- return false;
- }
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveDeviceData(
- const policy_table::DeviceData &devices) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kInsertDeviceData)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for device data.");
- return false;
- }
-
- policy_table::DeviceData::const_iterator it;
- for (it = devices.begin(); it != devices.end(); ++it) {
- query.Bind(0, it->first);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into device data.");
- return false;
- }
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::SaveUsageAndErrorCounts(
- const policy_table::UsageAndErrorCounts &counts) {
- const_cast<policy_table::UsageAndErrorCounts &>(counts).mark_initialized();
- dbms::SQLQuery query(db());
- if (!query.Exec(sql_pt::kDeleteAppLevel)) {
- LOG4CXX_WARN(logger_, "Incorrect delete from app level.");
- return false;
- }
- if (!query.Prepare(sql_pt::kInsertAppLevel)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement for app level.");
- return false;
- }
-
- policy_table::AppLevels::const_iterator it;
- const policy_table::AppLevels &app_levels = *counts.app_level;
- const_cast<policy_table::AppLevels &>(*counts.app_level).mark_initialized();
- for (it = app_levels.begin(); it != app_levels.end(); ++it) {
- query.Bind(0, it->first);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Incorrect insert into app level.");
- return false;
- }
- }
- return true;
-}
-
-void SQLPTRepresentation::IncrementIgnitionCycles() {
- dbms::SQLQuery query(db());
- if (!query.Exec(sql_pt::kIncrementIgnitionCycles)) {
- LOG4CXX_WARN(logger_, "Failed incrementing ignition cycles");
- }
-}
-
-void SQLPTRepresentation::ResetIgnitionCycles() {
- LOG4CXX_INFO(logger_, "ResetIgnitionCycles");
- dbms::SQLQuery query(db());
- if (!query.Exec(sql_pt::kResetIgnitionCycles)) {
- LOG4CXX_WARN(logger_, "Failed to reset ignition cycles number.");
- }
-}
-
-bool SQLPTRepresentation::UpdateRequired() const {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectFlagUpdateRequired) || !query.Exec()) {
- LOG4CXX_WARN(logger_,
- "Failed select update required flag from module meta");
- return false;
- }
- return query.GetBoolean(0);
-}
-
-void SQLPTRepresentation::SaveUpdateRequired(bool value) {
- dbms::SQLQuery query(db());
- // TODO(AOleynik): Quick fix, will be reworked
- if (!query.Prepare(/*sql_pt::kUpdateFlagUpdateRequired*/
- "UPDATE `module_meta` SET `flag_update_required` = ?")) {
- LOG4CXX_WARN(logger_,
- "Incorrect update into module meta (update_required): "
- << strerror(errno));
- return;
- }
- query.Bind(0, value);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed update module meta (update_required)");
- }
-}
-
-bool SQLPTRepresentation::GetInitialAppData(const std::string &app_id,
- StringArray *nicknames,
- StringArray *app_types) {
- LOG4CXX_INFO(logger_, "Getting initial application data.");
- dbms::SQLQuery app_names(db());
- if (!app_names.Prepare(sql_pt::kSelectNicknames)) {
- LOG4CXX_WARN(logger_, "Incorrect select from app nicknames");
- return false;
- }
- dbms::SQLQuery app_hmi_types(db());
- if (!app_hmi_types.Prepare(sql_pt::kSelectAppTypes)) {
- LOG4CXX_WARN(logger_, "Incorrect select from app types");
- return false;
- }
- app_names.Bind(0, app_id);
- while (app_names.Next()) {
- nicknames->push_back(app_names.GetString(0));
- }
- app_names.Reset();
- app_hmi_types.Bind(0, app_id);
- while (app_hmi_types.Next()) {
- app_types->push_back(app_hmi_types.GetString(0));
- }
- app_hmi_types.Reset();
- return true;
-}
-
-bool SQLPTRepresentation::GetFunctionalGroupings(
- policy_table::FunctionalGroupings &groups) {
- LOG4CXX_INFO(logger_, "GetFunctionalGroupings");
- return GatherFunctionalGroupings(&groups);
-}
-
-bool SQLPTRepresentation::GatherAppType(
- const std::string &app_id, policy_table::AppHMITypes *app_types) const {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectAppTypes)) {
- LOG4CXX_WARN(logger_, "Incorrect select from app types");
- return false;
- }
-
- query.Bind(0, app_id);
- while (query.Next()) {
- policy_table::AppHMIType type;
- if (!policy_table::EnumFromJsonString(query.GetString(0), &type)) {
- return false;
- }
- app_types->push_back(type);
- }
- return true;
-}
-
-bool SQLPTRepresentation::GatherRequestType(
- const std::string &app_id,
- policy_table::RequestTypes *request_types) const {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectRequestTypes)) {
- LOG4CXX_WARN(logger_, "Incorrect select from request types.");
- return false;
- }
-
- query.Bind(0, app_id);
- while (query.Next()) {
- policy_table::RequestType type;
- if (!policy_table::EnumFromJsonString(query.GetString(0), &type)) {
- return false;
- }
- request_types->push_back(type);
- }
- return true;
-}
-
-bool SQLPTRepresentation::GatherNickName(
- const std::string &app_id, policy_table::Strings *nicknames) const {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectNicknames)) {
- LOG4CXX_WARN(logger_, "Incorrect select from app nicknames");
- return false;
- }
-
- query.Bind(0, app_id);
- while (query.Next()) {
- nicknames->push_back(query.GetString(0));
- }
- return true;
-}
-
-bool SQLPTRepresentation::GatherAppGroup(
- const std::string &app_id, policy_table::Strings *app_groups) const {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectAppGroups)) {
- LOG4CXX_WARN(logger_, "Incorrect select from app groups");
- return false;
- }
-
- query.Bind(0, app_id);
- while (query.Next()) {
- app_groups->push_back(query.GetString(0));
- }
- return true;
-}
-
-bool SQLPTRepresentation::SaveApplicationCustomData(const std::string &app_id,
- bool is_revoked,
- bool is_default,
- bool is_predata) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kUpdateApplicationCustomData)) {
- LOG4CXX_WARN(logger_, "Incorrect update in application");
- return false;
- }
-
- query.Bind(0, is_revoked);
- query.Bind(1, is_default);
- query.Bind(2, is_predata);
- query.Bind(3, app_id);
-
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed update in application");
- return false;
- }
-
- return true;
-}
-
-bool SQLPTRepresentation::IsApplicationRevoked(
- const std::string &app_id) const {
-
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectApplicationRevoked)) {
- LOG4CXX_WARN(logger_, "Incorrect select from is_revoked of application");
- }
-
- query.Bind(0, app_id);
-
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed select is_revoked of application");
- return false;
- }
- return query.IsNull(0) ? false : query.GetBoolean(0);
-}
-bool SQLPTRepresentation::IsApplicationRepresented(
- const std::string &app_id) const {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectApplicationRepresented)) {
- LOG4CXX_WARN(logger_, "Incorrect select application by id");
- return false;
- }
-
- query.Bind(0, app_id);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed select application by id");
- return false;
- }
- return query.GetInteger(0) != 0;
-}
-
-bool SQLPTRepresentation::IsDefaultPolicy(const std::string &app_id) const {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kSelectApplicationIsDefault)) {
- LOG4CXX_WARN(logger_, "Incorrect select application by id");
- return false;
- }
-
- query.Bind(0, app_id);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed select application by id");
- return false;
- }
- return query.IsNull(0) ? false : query.GetBoolean(0);
-}
-
-bool SQLPTRepresentation::IsPredataPolicy(const std::string &app_id) const {
- return false;
-}
-
-bool SQLPTRepresentation::SetDefaultPolicy(const std::string &app_id) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kDeleteAppGroupByApplicationId)) {
- LOG4CXX_ERROR(logger_, "Incorrect statement to delete from app_group.");
- return false;
- }
- query.Bind(0, app_id);
- if (!query.Exec()) {
- LOG4CXX_ERROR(logger_, "Failed deleting from app_group.");
- return false;
- }
-
- if (!CopyApplication(kDefaultId, app_id)) {
- return false;
- }
-
- SetPreloaded(false);
-
- policy_table::Strings default_groups;
- if (GatherAppGroup(kDefaultId, &default_groups) &&
- SaveAppGroup(app_id, default_groups)) {
- return SetIsDefault(app_id, true);
- }
- return false;
-}
-
-bool SQLPTRepresentation::SetIsDefault(const std::string &app_id,
- bool is_default) const {
- LOG4CXX_TRACE(logger_, "Set flag is_default of application");
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kUpdateIsDefault)) {
- LOG4CXX_WARN(logger_, "Incorect statement for updating is_default");
- return false;
- }
-
- query.Bind(0, is_default);
- query.Bind(1, app_id);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed update is_default");
- return false;
- }
- return true;
-}
-
-dbms::SQLDatabase *SQLPTRepresentation::db() const {
-#ifdef __QNX__
- dbms::SQLDatabase *db = new dbms::SQLDatabase(kDatabaseName);
- db->Open();
- return db;
-#else
- return db_;
-#endif
-}
-
-bool SQLPTRepresentation::CopyApplication(const std::string &source,
- const std::string &destination) {
- dbms::SQLQuery source_app(db());
- if (!source_app.Prepare(sql_pt::kSelectApplicationFull)) {
- LOG4CXX_WARN(logger_, "Incorrect select statement from application.");
- return false;
- }
- source_app.Bind(0, source);
- if (!source_app.Exec()) {
- LOG4CXX_WARN(logger_, "Failed selecting from application.");
- return false;
- }
-
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kInsertApplicationFull)) {
- LOG4CXX_WARN(logger_, "Incorrect insert statement into application.");
- return false;
- }
- query.Bind(0, destination);
- source_app.IsNull(0) ? query.Bind(1)
- : query.Bind(1, source_app.GetBoolean(0));
- source_app.IsNull(1) ? query.Bind(2)
- : query.Bind(2, source_app.GetBoolean(1));
- source_app.IsNull(2) ? query.Bind(3) : query.Bind(3, source_app.GetString(2));
- source_app.IsNull(3) ? query.Bind(4) : query.Bind(4, source_app.GetString(3));
- source_app.IsNull(4) ? query.Bind(5)
- : query.Bind(5, source_app.GetBoolean(4));
- source_app.IsNull(5) ? query.Bind(6)
- : query.Bind(6, source_app.GetBoolean(5));
- source_app.IsNull(6) ? query.Bind(7)
- : query.Bind(7, source_app.GetBoolean(6));
- query.Bind(8, source_app.GetInteger(7));
- query.Bind(9, source_app.GetInteger(8));
- source_app.IsNull(9) ? query.Bind(10)
- : query.Bind(10, source_app.GetString(9));
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed inserting into application.");
- return false;
- }
- return true;
-}
-
-void SQLPTRepresentation::SetPreloaded(bool value) {
- dbms::SQLQuery query(db());
- if (!query.Prepare(sql_pt::kUpdatePreloaded)) {
- LOG4CXX_WARN(logger_, "Incorrect statement of updating preloaded.");
- return;
- }
-
- query.Bind(0, value);
- if (!query.Exec()) {
- LOG4CXX_WARN(logger_, "Failed updating preloaded.");
- return;
- }
-}
-
-bool SQLPTRepresentation::SetVINValue(const std::string &value) { return true; }
-
-} // namespace policy
diff --git a/src/components/policy/src/policy/src/update_status_manager.cc b/src/components/policy/src/policy/src/update_status_manager.cc
deleted file mode 100644
index e5cc74a315..0000000000
--- a/src/components/policy/src/policy/src/update_status_manager.cc
+++ /dev/null
@@ -1,268 +0,0 @@
-/*
- Copyright (c) 2014, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "policy/update_status_manager.h"
-#include "policy/policy_listener.h"
-#include "utils/logger.h"
-
-namespace policy {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "UpdateStatusManager")
-
-UpdateStatusManager::UpdateStatusManager() :
- listener_(NULL),
- exchange_in_progress_(false),
- update_required_(false),
- update_scheduled_(false),
- exchange_pending_(false),
- apps_search_in_progress_(false),
- last_update_status_(policy::StatusUnknown) {
- update_status_thread_delegate_ = new UpdateThreadDelegate(this);
- thread_ = threads::CreateThread("UpdateStatusThread", update_status_thread_delegate_);
- thread_->start();
-}
-
-UpdateStatusManager::~UpdateStatusManager() {
- LOG4CXX_AUTO_TRACE(logger_);
- DCHECK(update_status_thread_delegate_);
- DCHECK(thread_);
- thread_->join();
- delete update_status_thread_delegate_;
- threads::DeleteThread(thread_);
-}
-
-void UpdateStatusManager::set_listener(PolicyListener* listener) {
- listener_ = listener;
-}
-
-void UpdateStatusManager::OnUpdateSentOut(uint32_t update_timeout) {
- LOG4CXX_INFO(logger_, "OnUpdateSentOut");
- DCHECK(update_status_thread_delegate_);
- const unsigned milliseconds_in_second = 1000;
- update_status_thread_delegate_->updateTimeOut(update_timeout *
- milliseconds_in_second);
- set_exchange_in_progress(true);
- set_exchange_pending(true);
- set_update_required(false);
-}
-
-void UpdateStatusManager::OnUpdateTimeoutOccurs() {
- LOG4CXX_INFO(logger_, "OnUpdateTimeoutOccurs");
- set_update_required(true);
- set_exchange_in_progress(false);
- set_exchange_pending(false);
- DCHECK(update_status_thread_delegate_);
- update_status_thread_delegate_->updateTimeOut(0); // Stop Timer
-}
-
-void UpdateStatusManager::OnValidUpdateReceived() {
- LOG4CXX_INFO(logger_, "OnValidUpdateReceived");
- update_status_thread_delegate_->updateTimeOut(0); // Stop Timer
- set_exchange_pending(false);
- set_exchange_in_progress(false);
-}
-
-void UpdateStatusManager::OnWrongUpdateReceived() {
- LOG4CXX_INFO(logger_, "OnWrongUpdateReceived");
- update_status_thread_delegate_->updateTimeOut(0); // Stop Timer
- set_update_required(true);
- set_exchange_in_progress(false);
-}
-
-void UpdateStatusManager::OnResetDefaultPT(bool is_update_required) {
- LOG4CXX_INFO(logger_, "OnResetDefaultPT");
- exchange_in_progress_ = false;
- update_required_ = is_update_required;
- exchange_pending_ = false;
- last_update_status_ = policy::StatusUnknown;
-}
-
-void UpdateStatusManager::OnResetRetrySequence() {
- LOG4CXX_INFO(logger_, "OnResetRetrySequence");
- if (exchange_in_progress_) {
- set_exchange_pending(true);
- }
- set_update_required(true);
-}
-
-void UpdateStatusManager::OnNewApplicationAdded() {
- LOG4CXX_INFO(logger_, "OnNewApplicationAdded");
- set_update_required(true);
-}
-
-void UpdateStatusManager::OnPolicyInit(bool is_update_required) {
- LOG4CXX_INFO(logger_, "OnPolicyInit");
- update_required_ = is_update_required;
-}
-
-PolicyTableStatus UpdateStatusManager::GetUpdateStatus() const {
- LOG4CXX_AUTO_TRACE(logger_);
- if (!exchange_in_progress_ && !exchange_pending_ && !update_required_) {
- return PolicyTableStatus::StatusUpToDate;
- }
-
- if (update_required_ && !exchange_in_progress_ && !exchange_pending_) {
- return PolicyTableStatus::StatusUpdateRequired;
- }
-
- return PolicyTableStatus::StatusUpdatePending;
-}
-
-bool UpdateStatusManager::IsUpdateRequired() const {
- return update_required_ || update_scheduled_;
-}
-
-bool UpdateStatusManager::IsUpdatePending() const {
- return exchange_pending_;
-}
-
-void UpdateStatusManager::ScheduleUpdate() {
- update_scheduled_ = true;
- update_required_ = true;
-}
-
-void UpdateStatusManager::ResetUpdateSchedule() {
- update_scheduled_ = false;
-}
-
-std::string UpdateStatusManager::StringifiedUpdateStatus() const {
- switch (GetUpdateStatus()) {
- case policy::StatusUpdatePending:
- return "UPDATING";
- case policy::StatusUpdateRequired:
- return "UPDATE_NEEDED";
- case policy::StatusUpToDate:
- return "UP_TO_DATE";
- default: {
- return "UNKNOWN";
- }
- }
-}
-
-void policy::UpdateStatusManager::OnAppsSearchStarted() {
- LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
- apps_search_in_progress_ = true;
-}
-
-void policy::UpdateStatusManager::OnAppsSearchCompleted() {
- LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
- apps_search_in_progress_ = false;
-}
-
-bool policy::UpdateStatusManager::IsAppsSearchInProgress() {
- LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
- return apps_search_in_progress_;
-}
-
-void UpdateStatusManager::CheckUpdateStatus() {
- LOG4CXX_AUTO_TRACE(logger_);
- policy::PolicyTableStatus status = GetUpdateStatus();
- if (listener_ && last_update_status_ != status) {
- LOG4CXX_INFO(logger_, "Send OnUpdateStatusChanged");
- listener_->OnUpdateStatusChanged(StringifiedUpdateStatus());
- }
- last_update_status_ = status;
-}
-
-void UpdateStatusManager::set_exchange_in_progress(bool value) {
- sync_primitives::AutoLock lock(exchange_in_progress_lock_);
- LOG4CXX_INFO(logger_,
- "Exchange in progress value is:" << std::boolalpha << value);
- exchange_in_progress_ = value;
- CheckUpdateStatus();
-}
-
-void UpdateStatusManager::set_exchange_pending(bool value) {
- sync_primitives::AutoLock lock(exchange_pending_lock_);
- LOG4CXX_INFO(logger_,
- "Exchange pending value is:" << std::boolalpha << value);
- exchange_pending_ = value;
- CheckUpdateStatus();
-}
-
-void UpdateStatusManager::set_update_required(bool value) {
- sync_primitives::AutoLock lock(update_required_lock_);
- LOG4CXX_INFO(logger_, "Update required value is:" << std::boolalpha << value);
- update_required_ = value;
- CheckUpdateStatus();
-}
-
-UpdateStatusManager::UpdateThreadDelegate::UpdateThreadDelegate(UpdateStatusManager* update_status_manager):
- timeout_(0),
- stop_flag_(false),
- state_lock_(true),
- update_status_manager_(update_status_manager) {
- LOG4CXX_INFO(logger_, "Create UpdateThreadDelegate");
-}
-
-UpdateStatusManager::UpdateThreadDelegate::~UpdateThreadDelegate() {
- LOG4CXX_INFO(logger_, "Delete UpdateThreadDelegate");
-}
-
-void UpdateStatusManager::UpdateThreadDelegate::threadMain() {
- LOG4CXX_DEBUG(logger_, "UpdateStatusManager thread started (started normal)");
- sync_primitives::AutoLock auto_lock(state_lock_);
- while (false == stop_flag_) {
- if (timeout_ > 0) {
- LOG4CXX_DEBUG(logger_, "Timeout is greater then 0");
- sync_primitives::ConditionalVariable::WaitStatus wait_status =
- termination_condition_.WaitFor(auto_lock, timeout_);
- if (sync_primitives::ConditionalVariable::kTimeout == wait_status ) {
- if (update_status_manager_) {
- update_status_manager_->OnUpdateTimeoutOccurs();
- }
- }
- } else {
- // Time is not active, wait, while timeout will be seted,
- // or UpdateStatusManager will be deleted
- termination_condition_.Wait(auto_lock);
- }
- }
-}
-
-void UpdateStatusManager::UpdateThreadDelegate::exitThreadMain() {
- sync_primitives::AutoLock auto_lock(state_lock_);
- stop_flag_ = true;
- LOG4CXX_INFO(logger_, "before notify");
- termination_condition_.NotifyOne();
-}
-
-void UpdateStatusManager::UpdateThreadDelegate::updateTimeOut(const uint32_t timeout_ms) {
- sync_primitives::AutoLock auto_lock(state_lock_);
- timeout_ = timeout_ms;
- termination_condition_.NotifyOne();
-}
-
-} // namespace policy
diff --git a/src/components/policy/src/policy/usage_statistics/CMakeLists.txt b/src/components/policy/src/policy/usage_statistics/CMakeLists.txt
deleted file mode 100644
index b57431b8f8..0000000000
--- a/src/components/policy/src/policy/usage_statistics/CMakeLists.txt
+++ /dev/null
@@ -1,37 +0,0 @@
-# Copyright (c) 2014, Ford Motor Company
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# Redistributions of source code must retain the above copyright notice, this
-# list of conditions and the following disclaimer.
-#
-# Redistributions in binary form must reproduce the above copyright notice,
-# this list of conditions and the following
-# disclaimer in the documentation and/or other materials provided with the
-# distribution.
-#
-# Neither the name of the Ford Motor Company nor the names of its contributors
-# may be used to endorse or promote products derived from this software
-# without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-# POSSIBILITY OF SUCH DAMAGE.
-
-include_directories(include)
-
-set(SOURCES
- src/counter.cc
-)
-
-add_library(UsageStatistics ${SOURCES})
diff --git a/src/components/policy/src/policy/usage_statistics/include/usage_statistics/counter.h b/src/components/policy/src/policy/usage_statistics/include/usage_statistics/counter.h
deleted file mode 100644
index 6ccfb0a426..0000000000
--- a/src/components/policy/src/policy/usage_statistics/include/usage_statistics/counter.h
+++ /dev/null
@@ -1,100 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USAGE_STATISTICS_COUNTER_H
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USAGE_STATISTICS_COUNTER_H
-
-#include <ctime>
-#include "usage_statistics/statistics_manager.h"
-#include "utils/shared_ptr.h"
-#include "utils/timer_thread.h"
-
-namespace usage_statistics {
-
-class GlobalCounter {
- public:
- GlobalCounter(utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager,
- GlobalCounterId counter_type);
- void operator++() const;
- private:
- GlobalCounterId counter_type_;
- utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager_;
-};
-
-class AppCounter {
- public:
- AppCounter(utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager,
- const std::string& app_id,
- AppCounterId counter_type);
- void operator++() const;
- private:
- std::string app_id_;
- AppCounterId counter_type_;
- utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager_;
-};
-
-class AppInfo {
- public:
- AppInfo(utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager,
- const std::string& app_id,
- AppInfoId info_type);
- void Update(const std::string& new_info) const;
- private:
- std::string app_id_;
- AppInfoId info_type_;
- utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager_;
-};
-
-class AppStopwatch {
- public:
- AppStopwatch(utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager,
- const std::string& app_id);
- AppStopwatch(utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager,
- const std::string& app_id,
- std::uint32_t time_out);
- ~AppStopwatch();
- void Start(AppStopwatchId stopwatch_type);
- void Switch(AppStopwatchId stopwatch_type);
- void WriteTime();
- private:
- // Fields
- std::string app_id_;
- AppStopwatchId stopwatch_type_;
- utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager_;
- typedef timer::TimerThread<AppStopwatch> Timer;
- Timer* timer_;
- const std::uint32_t time_out_;
-};
-
-} // namespace usage_statistics
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USAGE_STATISTICS_COUNTER_H
diff --git a/src/components/policy/src/policy/usage_statistics/include/usage_statistics/statistics_manager.h b/src/components/policy/src/policy/usage_statistics/include/usage_statistics/statistics_manager.h
deleted file mode 100644
index 3af8f4c195..0000000000
--- a/src/components/policy/src/policy/usage_statistics/include/usage_statistics/statistics_manager.h
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USAGE_STATISTICS_STATISTICS_MANAGER_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USAGE_STATISTICS_STATISTICS_MANAGER_H_
-
-#include <stdint.h>
-#include <string>
-
-namespace usage_statistics {
-
-enum GlobalCounterId {
- IAP_BUFFER_FULL,
- SYNC_OUT_OF_MEMORY,
- SYNC_REBOOTS
-};
-
-enum AppInfoId {
- LANGUAGE_GUI,
- LANGUAGE_VUI
-};
-
-enum AppStopwatchId {
- SECONDS_HMI_FULL,
- SECONDS_HMI_LIMITED,
- SECONDS_HMI_BACKGROUND,
- SECONDS_HMI_NONE
-};
-
-enum AppCounterId {
- USER_SELECTIONS,
- REJECTIONS_SYNC_OUT_OF_MEMORY,
- REJECTIONS_NICKNAME_MISMATCH,
- REJECTIONS_DUPLICATE_NAME,
- REJECTED_RPC_CALLS,
- RPCS_IN_HMI_NONE,
- REMOVALS_MISBEHAVED,
- RUN_ATTEMPTS_WHILE_REVOKED
-};
-
-class StatisticsManager {
- public:
- virtual ~StatisticsManager() {}
- virtual void Increment(GlobalCounterId type) = 0;
- virtual void Increment(const std::string& app_id, AppCounterId type) = 0;
- virtual void Set(const std::string& app_id, AppInfoId type,
- const std::string& value) = 0;
- virtual void Add(const std::string& app_id,
- AppStopwatchId type,
- int32_t timespan_seconds) = 0;
-};
-
-} // namespace usage_statistics
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_USAGE_STATISTICS_STATISTICS_MANAGER_H_
diff --git a/src/components/policy/src/policy/usage_statistics/src/counter.cc b/src/components/policy/src/policy/usage_statistics/src/counter.cc
deleted file mode 100644
index 070de140b3..0000000000
--- a/src/components/policy/src/policy/usage_statistics/src/counter.cc
+++ /dev/null
@@ -1,125 +0,0 @@
-/*
- Copyright (c) 2013, Ford Motor Company
- All rights reserved.
-
- Redistribution and use in source and binary forms, with or without
- modification, are permitted provided that the following conditions are met:
-
- Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
- Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following
- disclaimer in the documentation and/or other materials provided with the
- distribution.
-
- Neither the name of the Ford Motor Company nor the names of its contributors
- may be used to endorse or promote products derived from this software
- without specific prior written permission.
-
- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_STATISTICS_MANAGER_H_
-#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_STATISTICS_MANAGER_H_
-
-#include "usage_statistics/counter.h"
-#include <cassert>
-
-namespace usage_statistics {
-
-GlobalCounter::GlobalCounter(utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager,
- GlobalCounterId counter_type)
- : counter_type_(counter_type),
- statistics_manager_(statistics_manager) {
-}
-
-void GlobalCounter::operator++() const {
- if (statistics_manager_) {
- statistics_manager_->Increment(counter_type_);
- }
-}
-
-AppCounter::AppCounter(utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager,
- const std::string& app_id,
- AppCounterId counter_type)
- : app_id_(app_id),
- counter_type_(counter_type),
- statistics_manager_(statistics_manager) {
-}
-
-void AppCounter::operator++() const {
- if (statistics_manager_) {
- statistics_manager_->Increment(app_id_, counter_type_);
- }
-}
-
-AppInfo::AppInfo(utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager,
- const std::string& app_id,
- AppInfoId info_type)
- : app_id_(app_id),
- info_type_(info_type),
- statistics_manager_(statistics_manager) {
-}
-
-void AppInfo::Update(const std::string& new_info) const {
- if (statistics_manager_) {
- statistics_manager_->Set(app_id_, info_type_, new_info);
- }
-}
-
-AppStopwatch::AppStopwatch(utils::SharedPtr<usage_statistics::StatisticsManager> statistics_manager,
- const std::string& app_id)
- : app_id_(app_id),
- stopwatch_type_(SECONDS_HMI_NONE),
- statistics_manager_(statistics_manager),
- timer_(new Timer("HMI levels timer",this, &AppStopwatch::WriteTime, true)),
- time_out_(60) {
-}
-
-AppStopwatch::AppStopwatch(utils::SharedPtr<StatisticsManager> statistics_manager,
- const std::string& app_id,
- std::uint32_t time_out)
- : app_id_(app_id),
- stopwatch_type_(SECONDS_HMI_NONE),
- statistics_manager_(statistics_manager),
- timer_(new Timer("HMI levels timer",this, &AppStopwatch::WriteTime, true)),
- time_out_(time_out) {
-
-}
-
-AppStopwatch::~AppStopwatch() {
- if (NULL != timer_) {
- timer_->stop();
- delete timer_;
- }
-}
-
-void AppStopwatch::Start(AppStopwatchId stopwatch_type) {
- stopwatch_type_ = stopwatch_type;
- timer_->start(time_out_);
-}
-
-void AppStopwatch::Switch(AppStopwatchId stopwatch_type) {
- Start(stopwatch_type);
-}
-
-void AppStopwatch::WriteTime() {
- if (statistics_manager_) {
- statistics_manager_->Add(app_id_, stopwatch_type_, time_out_);
- }
-}
-
-} // namespace usage_statistics
-
-#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_STATISTICS_MANAGER_H_
diff --git a/src/components/policy/src/policy_helper.cc b/src/components/policy/src/policy_helper.cc
new file mode 100644
index 0000000000..b72a041a83
--- /dev/null
+++ b/src/components/policy/src/policy_helper.cc
@@ -0,0 +1,805 @@
+/*
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <algorithm>
+#include <sstream>
+#include <string.h>
+#include "utils/logger.h"
+#include "utils/custom_string.h"
+#include "policy/policy_helper.h"
+#include "policy/policy_manager_impl.h"
+
+namespace policy {
+
+namespace custom_str = utils::custom_string;
+
+namespace {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")
+
+bool Compare(const StringsValueType& first, const StringsValueType& second) {
+ const std::string& first_str = first;
+ const std::string& second_str = second;
+ return (strcasecmp(first_str.c_str(), second_str.c_str()) < 0);
+}
+
+struct CheckGroupName {
+ CheckGroupName(const policy::StringsValueType& value) : value_(value) {}
+
+ bool operator()(const FunctionalGroupNames::value_type& value) {
+ return value.second.second == std::string(value_);
+ }
+
+ private:
+ const policy::StringsValueType& value_;
+};
+
+struct CopyAttributes {
+ CopyAttributes(const FunctionalGroupNames& groups_attributes,
+ std::vector<FunctionalGroupPermission>& groups_permissions)
+ : groups_attributes_(groups_attributes)
+ , groups_permissions_(groups_permissions) {}
+
+ bool operator()(const policy::StringsValueType& value) {
+ CheckGroupName checker(value);
+ FunctionalGroupNames::const_iterator it = std::find_if(
+ groups_attributes_.begin(), groups_attributes_.end(), checker);
+ if (groups_attributes_.end() == it) {
+ return false;
+ }
+ FunctionalGroupPermission group;
+ group.group_name = it->second.second;
+ group.group_alias = it->second.first;
+ group.group_id = it->first;
+ groups_permissions_.push_back(group);
+ return true;
+ }
+
+ private:
+ const FunctionalGroupNames& groups_attributes_;
+ std::vector<FunctionalGroupPermission>& groups_permissions_;
+};
+} // namespace
+
+CompareGroupName::CompareGroupName(const StringsValueType& group_name)
+ : group_name_(group_name) {}
+
+bool CompareGroupName::operator()(
+ const StringsValueType& group_name_to_compare) const {
+ const std::string gn_ = group_name_;
+ const std::string gn_compare = group_name_to_compare;
+ return !(strcasecmp(gn_.c_str(), gn_compare.c_str()));
+}
+
+bool operator!=(const policy_table::ApplicationParams& first,
+ const policy_table::ApplicationParams& second) {
+ if (first.groups.size() != second.groups.size()) {
+ return true;
+ }
+ StringsConstItr it_first = first.groups.begin();
+ StringsConstItr it_first_end = first.groups.end();
+ StringsConstItr it_second = second.groups.begin();
+ StringsConstItr it_second_end = second.groups.end();
+ for (; it_first != it_first_end; ++it_first) {
+ CompareGroupName gp(*it_first);
+ StringsConstItr it = std::find_if(it_second, it_second_end, gp);
+ if (it_first_end == it) {
+ return true;
+ }
+ }
+ return false;
+}
+
+CheckAppPolicy::CheckAppPolicy(
+ PolicyManagerImpl* pm,
+ const utils::SharedPtr<policy_table::Table> update,
+ const utils::SharedPtr<policy_table::Table> snapshot)
+ : pm_(pm), update_(update), snapshot_(snapshot) {}
+
+bool policy::CheckAppPolicy::HasRevokedGroups(
+ const policy::AppPoliciesValueType& app_policy,
+ policy_table::Strings* revoked_groups) const {
+ AppPoliciesConstItr it =
+ snapshot_->policy_table.app_policies_section.apps.find(app_policy.first);
+
+ policy_table::Strings groups_new = app_policy.second.groups;
+ std::sort(groups_new.begin(), groups_new.end(), Compare);
+
+ policy_table::Strings groups_curr = (*it).second.groups;
+ std::sort(groups_curr.begin(), groups_curr.end(), Compare);
+
+ StringsConstItr it_groups_new = groups_new.begin();
+ StringsConstItr it_groups_new_end = groups_new.end();
+
+ StringsConstItr it_groups_curr = groups_curr.begin();
+ StringsConstItr it_groups_curr_end = groups_curr.end();
+
+ policy_table::Strings revoked_group_list;
+ std::set_difference(it_groups_curr,
+ it_groups_curr_end,
+ it_groups_new,
+ it_groups_new_end,
+ std::back_inserter(revoked_group_list),
+ Compare);
+
+ // Remove groups which are not required user consent
+ policy_table::Strings::iterator it_revoked = revoked_group_list.begin();
+ for (; revoked_group_list.end() != it_revoked;) {
+ if (!IsConsentRequired(app_policy.first, std::string(*it_revoked))) {
+ revoked_group_list.erase(it_revoked);
+ it_revoked = revoked_group_list.begin();
+ } else {
+ ++it_revoked;
+ }
+ }
+
+ if (revoked_groups) {
+ *revoked_groups = revoked_group_list;
+ }
+
+ return !revoked_group_list.empty();
+}
+
+bool policy::CheckAppPolicy::HasNewGroups(
+ const policy::AppPoliciesValueType& app_policy,
+ policy_table::Strings* new_groups) const {
+ AppPoliciesConstItr it =
+ snapshot_->policy_table.app_policies_section.apps.find(app_policy.first);
+
+ policy_table::Strings groups_new = app_policy.second.groups;
+ std::sort(groups_new.begin(), groups_new.end(), Compare);
+
+ policy_table::Strings groups_curr = (*it).second.groups;
+ std::sort(groups_curr.begin(), groups_curr.end(), Compare);
+
+ StringsConstItr it_groups_new = groups_new.begin();
+ StringsConstItr it_groups_new_end = groups_new.end();
+
+ StringsConstItr it_groups_curr = groups_curr.begin();
+ StringsConstItr it_groups_curr_end = groups_curr.end();
+
+ policy_table::Strings new_group_list;
+ std::set_difference(it_groups_new,
+ it_groups_new_end,
+ it_groups_curr,
+ it_groups_curr_end,
+ std::back_inserter(new_group_list),
+ Compare);
+
+ if (new_groups) {
+ *new_groups = new_group_list;
+ }
+
+ return !new_group_list.empty();
+}
+
+bool policy::CheckAppPolicy::HasConsentNeededGroups(
+ const policy::AppPoliciesValueType& app_policy) const {
+ policy_table::Strings new_groups;
+ if (!HasNewGroups(app_policy, &new_groups)) {
+ return false;
+ }
+
+ StringsConstItr it_new = new_groups.begin();
+ StringsConstItr it_new_end = new_groups.end();
+ for (; it_new != it_new_end; ++it_new) {
+ if (IsConsentRequired(app_policy.first, *it_new)) {
+ return true;
+ }
+ }
+
+ return false;
+}
+
+std::vector<FunctionalGroupPermission> policy::CheckAppPolicy::GetRevokedGroups(
+ const policy::AppPoliciesValueType& app_policy) const {
+ policy_table::Strings revoked_groups_names;
+ if (!HasRevokedGroups(app_policy, &revoked_groups_names)) {
+ return std::vector<FunctionalGroupPermission>();
+ }
+
+ FunctionalGroupNames groups_attributes;
+ if (!pm_->cache_->GetFunctionalGroupNames(groups_attributes)) {
+ LOG4CXX_WARN(logger_, "Can't get functional group names");
+ return std::vector<FunctionalGroupPermission>();
+ }
+
+ std::vector<FunctionalGroupPermission> revoked_groups_permissions;
+ CopyAttributes copier(groups_attributes, revoked_groups_permissions);
+ std::for_each(
+ revoked_groups_names.begin(), revoked_groups_names.end(), copier);
+
+ return revoked_groups_permissions;
+}
+
+void policy::CheckAppPolicy::RemoveRevokedConsents(
+ const AppPoliciesValueType& app_policy,
+ const std::vector<FunctionalGroupPermission>& revoked_groups) const {
+ std::vector<policy::FunctionalGroupPermission>::const_iterator it =
+ revoked_groups.begin();
+ std::vector<policy::FunctionalGroupPermission>::const_iterator it_end =
+ revoked_groups.end();
+ for (; it != it_end; ++it) {
+ pm_->RemoveAppConsentForGroup(app_policy.first, it->group_name);
+ }
+}
+
+bool CheckAppPolicy::IsKnownAppication(
+ const std::string& application_id) const {
+ const policy_table::ApplicationPolicies& current_policies =
+ snapshot_->policy_table.app_policies_section.apps;
+
+ return !(current_policies.end() == current_policies.find(application_id));
+}
+
+void policy::CheckAppPolicy::NotifySystem(
+ const policy::AppPoliciesValueType& app_policy) const {
+ pm_->listener()->OnPendingPermissionChange(app_policy.first);
+}
+
+void CheckAppPolicy::SendPermissionsToApp(
+ const AppPoliciesValueType& app_policy) const {
+ const std::string app_id = app_policy.first;
+
+ const std::string device_id = pm_->GetCurrentDeviceId(app_id);
+ if (device_id.empty()) {
+ LOG4CXX_WARN(logger_,
+ "Couldn't find device info for application id: " << app_id);
+ return;
+ }
+ std::vector<FunctionalGroupPermission> group_permissons;
+ pm_->GetPermissionsForApp(device_id, app_id, group_permissons);
+
+ Permissions notification_data;
+ pm_->PrepareNotificationData(update_->policy_table.functional_groupings,
+ app_policy.second.groups,
+ group_permissons,
+ notification_data);
+
+ LOG4CXX_INFO(logger_, "Send notification for application_id: " << app_id);
+ // Default_hmi is Ford-specific and should not be used with basic policy
+ const std::string default_hmi;
+ pm_->listener()->OnPermissionsUpdated(app_id, notification_data, default_hmi);
+}
+
+bool CheckAppPolicy::IsAppRevoked(
+ const AppPoliciesValueType& app_policy) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ // Application params are not initialized = application revoked
+ // i.e. "123":null
+ return app_policy.second.is_null();
+}
+
+bool CheckAppPolicy::NicknamesMatch(
+ const AppPoliciesValueType& app_policy) const {
+ const std::string& app_id = app_policy.first;
+ const custom_str::CustomString app_name = pm_->listener()->GetAppName(app_id);
+ if (!app_name.empty() && app_policy.second.nicknames &&
+ !app_policy.second.nicknames->empty()) {
+ for (policy_table::Strings::const_iterator it =
+ app_policy.second.nicknames->begin();
+ app_policy.second.nicknames->end() != it;
+ ++it) {
+ std::string temp = *it;
+ if (app_name.CompareIgnoreCase(temp.c_str())) {
+ return true;
+ }
+ }
+ return false;
+ }
+ return true;
+}
+
+bool CheckAppPolicy::operator()(const AppPoliciesValueType& app_policy) {
+ const std::string app_id = app_policy.first;
+
+ if (!IsKnownAppication(app_id)) {
+ LOG4CXX_WARN(logger_,
+ "Application:" << app_id << " is not present in snapshot.");
+ return true;
+ }
+
+ if (!IsPredefinedApp(app_policy) && IsAppRevoked(app_policy)) {
+ SetPendingPermissions(app_policy, RESULT_APP_REVOKED);
+ NotifySystem(app_policy);
+ return true;
+ }
+
+ if (!IsPredefinedApp(app_policy) && !NicknamesMatch(app_policy)) {
+ SetPendingPermissions(app_policy, RESULT_NICKNAME_MISMATCH);
+ NotifySystem(app_policy);
+ return true;
+ }
+
+ PermissionsCheckResult result = CheckPermissionsChanges(app_policy);
+ if (!IsPredefinedApp(app_policy) && IsRequestTypeChanged(app_policy)) {
+ SetPendingPermissions(app_policy, RESULT_REQUEST_TYPE_CHANGED);
+ NotifySystem(app_policy);
+ }
+ if (RESULT_NO_CHANGES == result) {
+ LOG4CXX_INFO(logger_,
+ "Permissions for application:" << app_id
+ << " wasn't changed.");
+ return true;
+ }
+
+ LOG4CXX_INFO(logger_,
+ "Permissions for application:" << app_id
+ << " have been changed.");
+
+ if (!IsPredefinedApp(app_policy) && RESULT_CONSENT_NOT_REQIURED != result) {
+ SetPendingPermissions(app_policy, result);
+ NotifySystem(app_policy);
+ }
+
+ // Don't sent notification for predefined apps (e.g. default, device etc.)
+ if (!IsPredefinedApp(app_policy)) {
+ SendPermissionsToApp(app_policy);
+ }
+ return true;
+}
+
+void policy::CheckAppPolicy::SetPendingPermissions(
+ const AppPoliciesValueType& app_policy,
+ PermissionsCheckResult result) const {
+ const std::string app_id = app_policy.first;
+ AppPermissions permissions_diff(app_id);
+ permissions_diff.priority =
+ policy_table::EnumToJsonString(app_policy.second.priority);
+
+ switch (result) {
+ case RESULT_APP_REVOKED:
+ permissions_diff.appRevoked = true;
+ break;
+ case RESULT_NICKNAME_MISMATCH:
+ permissions_diff.appUnauthorized = true;
+ break;
+ case RESULT_PERMISSIONS_REVOKED:
+ permissions_diff.isAppPermissionsRevoked = true;
+ permissions_diff.appRevokedPermissions = GetRevokedGroups(app_policy);
+ RemoveRevokedConsents(app_policy, permissions_diff.appRevokedPermissions);
+ break;
+ case RESULT_CONSENT_NEEDED:
+ permissions_diff.appPermissionsConsentNeeded = true;
+ break;
+ case RESULT_PERMISSIONS_REVOKED_AND_CONSENT_NEEDED:
+ permissions_diff.isAppPermissionsRevoked = true;
+ permissions_diff.appPermissionsConsentNeeded = true;
+ permissions_diff.appRevokedPermissions = GetRevokedGroups(app_policy);
+ RemoveRevokedConsents(app_policy, permissions_diff.appRevokedPermissions);
+ break;
+ case RESULT_REQUEST_TYPE_CHANGED:
+ permissions_diff.priority.clear();
+ permissions_diff.requestTypeChanged = true;
+ {
+ // Getting RequestTypes from PTU (not from cache)
+ policy_table::RequestTypes::const_iterator it_request_type =
+ app_policy.second.RequestType->begin();
+ for (; app_policy.second.RequestType->end() != it_request_type;
+ ++it_request_type) {
+ permissions_diff.requestType.push_back(
+ EnumToJsonString(*it_request_type));
+ }
+ }
+
+ break;
+ default:
+ return;
+ }
+ pm_->app_permissions_diff_lock_.Acquire();
+ pm_->app_permissions_diff_.insert(std::make_pair(app_id, permissions_diff));
+ pm_->app_permissions_diff_lock_.Release();
+}
+
+policy::CheckAppPolicy::PermissionsCheckResult
+policy::CheckAppPolicy::CheckPermissionsChanges(
+ const policy::AppPoliciesValueType& app_policy) const {
+ bool has_revoked_groups = HasRevokedGroups(app_policy);
+
+ bool has_consent_needed_groups = HasConsentNeededGroups(app_policy);
+
+ bool has_new_groups = HasNewGroups(app_policy);
+
+ if (has_revoked_groups && has_consent_needed_groups) {
+ return RESULT_PERMISSIONS_REVOKED_AND_CONSENT_NEEDED;
+ } else if (has_revoked_groups) {
+ return RESULT_PERMISSIONS_REVOKED;
+ } else if (has_consent_needed_groups) {
+ return RESULT_CONSENT_NEEDED;
+ } else if (has_new_groups) {
+ return RESULT_CONSENT_NOT_REQIURED;
+ }
+
+ return RESULT_NO_CHANGES;
+}
+
+bool CheckAppPolicy::IsConsentRequired(const std::string& app_id,
+ const std::string& group_name) const {
+ const policy_table::FunctionalGroupings& functional_groupings =
+ snapshot_->policy_table.functional_groupings;
+
+ FuncGroupConstItr it = functional_groupings.find(group_name);
+
+ if (functional_groupings.end() == it) {
+ return false;
+ }
+
+ bool is_preconsented = false;
+ return it->second.user_consent_prompt.is_initialized() && !is_preconsented;
+}
+
+bool CheckAppPolicy::IsRequestTypeChanged(
+ const AppPoliciesValueType& app_policy) const {
+ policy::AppPoliciesConstItr it =
+ snapshot_->policy_table.app_policies_section.apps.find(app_policy.first);
+ if (it == snapshot_->policy_table.app_policies_section.apps.end()) {
+ if (!app_policy.second.RequestType->empty()) {
+ return true;
+ }
+ return false;
+ }
+ if (it->second.RequestType->size() != app_policy.second.RequestType->size()) {
+ return true;
+ }
+ policy_table::RequestTypes diff;
+ std::set_difference(it->second.RequestType->begin(),
+ it->second.RequestType->end(),
+ app_policy.second.RequestType->begin(),
+ app_policy.second.RequestType->end(),
+ std::back_inserter(diff));
+ return diff.size();
+}
+
+FillNotificationData::FillNotificationData(Permissions& data,
+ GroupConsent group_state,
+ GroupConsent undefined_group_consent)
+ : data_(data) {
+ switch (group_state) {
+ case kGroupAllowed:
+ current_key_ = kAllowedKey;
+ break;
+ case kGroupUndefined:
+ if (kGroupUndefined == undefined_group_consent) {
+ current_key_ = kUndefinedKey;
+ break;
+ }
+ current_key_ = kGroupAllowed == undefined_group_consent
+ ? kAllowedKey
+ : kUserDisallowedKey;
+ break;
+ default:
+ current_key_ = kUserDisallowedKey;
+ break;
+ }
+}
+
+bool FillNotificationData::operator()(const RpcValueType& rpc) {
+ Permissions::iterator it = data_.find(rpc.first);
+ // If rpc is present already - update its permissions
+ if (data_.end() != it) {
+ UpdateHMILevels(rpc.second.hmi_levels,
+ (*it).second.hmi_permissions[current_key_]);
+ // TODO(IKozyrenko): Check logic if optional container is missing
+ UpdateParameters(*rpc.second.parameters,
+ (*it).second.parameter_permissions[current_key_]);
+ ExcludeSame();
+ } else {
+ // Init mandatory keys, since they should be present irrespectively of
+ // values presence
+ InitRpcKeys(rpc.first);
+ // If rpc is not present - add its permissions
+ UpdateHMILevels(rpc.second.hmi_levels,
+ data_[rpc.first].hmi_permissions[current_key_]);
+ // TODO(IKozyrenko): Check logic if optional container is missing
+ UpdateParameters(*rpc.second.parameters,
+ data_[rpc.first].parameter_permissions[current_key_]);
+ ExcludeSame();
+ }
+ return true;
+}
+
+void FillNotificationData::UpdateHMILevels(
+ const policy_table::HmiLevels& in_hmi, std::set<HMILevel>& out_hmi) {
+ HMILevelsConstItr it_hmi_levels = in_hmi.begin();
+ HMILevelsConstItr it_hmi_levels_end = in_hmi.end();
+
+ for (; it_hmi_levels != it_hmi_levels_end; ++it_hmi_levels) {
+ out_hmi.insert(policy_table::EnumToJsonString(*it_hmi_levels));
+ }
+}
+
+void FillNotificationData::UpdateParameters(
+ const policy_table::Parameters& in_parameters,
+ std::set<Parameter>& out_parameter) {
+ ParametersConstItr it_parameters = in_parameters.begin();
+ ParametersConstItr it_parameters_end = in_parameters.end();
+
+ for (; it_parameters != it_parameters_end; ++it_parameters) {
+ out_parameter.insert(policy_table::EnumToJsonString(*it_parameters));
+ }
+}
+
+void FillNotificationData::ExcludeSame() {
+ Permissions::iterator it = data_.begin();
+ Permissions::const_iterator it_end = data_.end();
+ // Groups
+ for (; it != it_end; ++it) {
+ HMIPermissions& rpc_hmi_permissions = (*it).second.hmi_permissions;
+ HMIPermissions::const_iterator it_hmi_allowed =
+ (*it).second.hmi_permissions.find(kAllowedKey);
+ HMIPermissions::const_iterator it_hmi_undefined =
+ (*it).second.hmi_permissions.find(kUndefinedKey);
+ HMIPermissions::const_iterator it_hmi_user_disallowed =
+ (*it).second.hmi_permissions.find(kUserDisallowedKey);
+
+ ParameterPermissions& rpc_parameter_permissions =
+ (*it).second.parameter_permissions;
+ ParameterPermissions::const_iterator it_parameter_allowed =
+ (*it).second.parameter_permissions.find(kAllowedKey);
+ ParameterPermissions::const_iterator it_parameter_undefined =
+ (*it).second.parameter_permissions.find(kUndefinedKey);
+ ParameterPermissions::const_iterator it_parameter_user_disallowed =
+ (*it).second.parameter_permissions.find(kUserDisallowedKey);
+
+ // First, remove disallowed from other types
+ if (rpc_hmi_permissions.end() != it_hmi_user_disallowed) {
+ if (rpc_hmi_permissions.end() != it_hmi_allowed) {
+ ExcludeSameHMILevels(rpc_hmi_permissions[kAllowedKey],
+ rpc_hmi_permissions[kUserDisallowedKey]);
+ }
+ if (rpc_hmi_permissions.end() != it_hmi_undefined) {
+ ExcludeSameHMILevels(rpc_hmi_permissions[kUndefinedKey],
+ rpc_hmi_permissions[kUserDisallowedKey]);
+ }
+ }
+
+ if (rpc_parameter_permissions.end() != it_parameter_user_disallowed) {
+ if (rpc_parameter_permissions.end() != it_parameter_allowed) {
+ ExcludeSameParameters(rpc_parameter_permissions[kAllowedKey],
+ rpc_parameter_permissions[kUserDisallowedKey]);
+ }
+ if (rpc_parameter_permissions.end() != it_parameter_undefined) {
+ ExcludeSameParameters(rpc_parameter_permissions[kUndefinedKey],
+ rpc_parameter_permissions[kUserDisallowedKey]);
+ }
+ }
+
+ // Then, remove undefined from allowed
+ if (rpc_hmi_permissions.end() != it_hmi_undefined) {
+ if (rpc_hmi_permissions.end() != it_hmi_allowed) {
+ ExcludeSameHMILevels(rpc_hmi_permissions[kAllowedKey],
+ rpc_hmi_permissions[kUndefinedKey]);
+ }
+ }
+
+ if (rpc_parameter_permissions.end() != it_parameter_undefined) {
+ if (rpc_parameter_permissions.end() != it_parameter_allowed) {
+ ExcludeSameParameters(rpc_parameter_permissions[kAllowedKey],
+ rpc_parameter_permissions[kUndefinedKey]);
+ }
+ }
+ }
+}
+
+void FillNotificationData::ExcludeSameHMILevels(
+ std::set<HMILevel>& source, const std::set<HMILevel>& target) {
+ std::set<HMILevel> diff_hmi;
+
+ std::set_difference(source.begin(),
+ source.end(),
+ target.begin(),
+ target.end(),
+ std::inserter(diff_hmi, diff_hmi.begin()));
+
+ source = diff_hmi;
+}
+
+void FillNotificationData::ExcludeSameParameters(
+ std::set<Parameter>& source, const std::set<Parameter>& target) {
+ std::set<Parameter> diff_parameter;
+
+ std::set_difference(source.begin(),
+ source.end(),
+ target.begin(),
+ target.end(),
+ std::inserter(diff_parameter, diff_parameter.begin()));
+
+ source = diff_parameter;
+}
+
+void FillNotificationData::InitRpcKeys(const std::string& rpc_name) {
+ data_[rpc_name].hmi_permissions[kAllowedKey];
+ data_[rpc_name].hmi_permissions[kUserDisallowedKey];
+ data_[rpc_name].parameter_permissions[kAllowedKey];
+ data_[rpc_name].parameter_permissions[kUserDisallowedKey];
+}
+
+ProcessFunctionalGroup::ProcessFunctionalGroup(
+ const policy_table::FunctionalGroupings& fg,
+ const std::vector<FunctionalGroupPermission>& group_permissions,
+ Permissions& data,
+ GroupConsent undefined_group_consent)
+ : fg_(fg)
+ , group_permissions_(group_permissions)
+ , data_(data)
+ , undefined_group_consent_(undefined_group_consent) {}
+
+bool ProcessFunctionalGroup::operator()(const StringsValueType& group_name) {
+ const std::string group_name_str = group_name;
+ FuncGroupConstItr it = fg_.find(group_name_str);
+
+ if (fg_.end() != it) {
+ const policy_table::Rpc& rpcs = (*it).second.rpcs;
+ FillNotificationData filler(
+ data_, GetGroupState(group_name_str), undefined_group_consent_);
+ std::for_each(rpcs.begin(), rpcs.end(), filler);
+ }
+ return true;
+}
+
+GroupConsent ProcessFunctionalGroup::GetGroupState(
+ const std::string& group_name) {
+ std::vector<FunctionalGroupPermission>::const_iterator it =
+ group_permissions_.begin();
+ std::vector<FunctionalGroupPermission>::const_iterator it_end =
+ group_permissions_.end();
+ for (; it != it_end; ++it) {
+ if (group_name == (*it).group_name) {
+ return (*it).state;
+ }
+ }
+ return kGroupUndefined;
+}
+
+FunctionalGroupInserter::FunctionalGroupInserter(
+ const policy_table::Strings& preconsented_groups, PermissionsList& list)
+ : list_(list), preconsented_(preconsented_groups) {}
+
+void FunctionalGroupInserter::operator()(const StringsValueType& group_name) {
+ CompareGroupName name(group_name);
+ if (std::find_if(preconsented_.begin(), preconsented_.end(), name) ==
+ preconsented_.end()) {
+ list_.push_back(group_name);
+ }
+}
+
+void FillFunctionalGroupPermissions(
+ FunctionalGroupIDs& ids,
+ FunctionalGroupNames& names,
+ GroupConsent state,
+ std::vector<FunctionalGroupPermission>& permissions) {
+ LOG4CXX_INFO(logger_, "FillFunctionalGroupPermissions");
+ FunctionalGroupIDs::const_iterator it = ids.begin();
+ FunctionalGroupIDs::const_iterator it_end = ids.end();
+ for (; it != it_end; ++it) {
+ FunctionalGroupPermission current_group;
+ current_group.group_id = *it;
+ current_group.group_alias = names[*it].first;
+ current_group.group_name = names[*it].second;
+ current_group.state = state;
+ permissions.push_back(current_group);
+ }
+}
+
+bool IsPredefinedApp(const AppPoliciesValueType& app) {
+ return app.first == kDefaultId || app.first == kPreDataConsentId ||
+ app.first == kDeviceId;
+}
+
+FunctionalGroupIDs ExcludeSame(const FunctionalGroupIDs& from,
+ const FunctionalGroupIDs& what) {
+ LOG4CXX_INFO(logger_, "Exclude same groups");
+ FunctionalGroupIDs from_copy(from);
+ FunctionalGroupIDs what_copy(what);
+
+ std::sort(from_copy.begin(), from_copy.end());
+ std::sort(what_copy.begin(), what_copy.end());
+
+ FunctionalGroupIDs no_same;
+ std::set_difference(from_copy.begin(),
+ from_copy.end(),
+ what_copy.begin(),
+ what_copy.end(),
+ std::back_inserter(no_same));
+
+ no_same.resize(std::distance(no_same.begin(),
+ std::unique(no_same.begin(), no_same.end())));
+
+ return no_same;
+}
+
+FunctionalGroupIDs Merge(const FunctionalGroupIDs& first,
+ const FunctionalGroupIDs& second) {
+ LOG4CXX_INFO(logger_, "Merge groups");
+ FunctionalGroupIDs first_copy(first);
+ FunctionalGroupIDs second_copy(second);
+
+ std::sort(first_copy.begin(), first_copy.end());
+ std::sort(second_copy.begin(), second_copy.end());
+
+ FunctionalGroupIDs merged;
+ std::set_union(first_copy.begin(),
+ first_copy.end(),
+ second_copy.begin(),
+ second_copy.end(),
+ std::back_inserter(merged));
+
+ merged.resize(
+ std::distance(merged.begin(), std::unique(merged.begin(), merged.end())));
+
+ return merged;
+}
+
+FunctionalGroupIDs FindSame(const FunctionalGroupIDs& first,
+ const FunctionalGroupIDs& second) {
+ LOG4CXX_INFO(logger_, "Find same groups");
+ FunctionalGroupIDs first_copy(first);
+ FunctionalGroupIDs second_copy(second);
+
+ std::sort(first_copy.begin(), first_copy.end());
+ std::sort(second_copy.begin(), second_copy.end());
+
+ FunctionalGroupIDs same;
+ std::set_intersection(first_copy.begin(),
+ first_copy.end(),
+ second_copy.begin(),
+ second_copy.end(),
+ std::back_inserter(same));
+
+ same.resize(
+ std::distance(same.begin(), std::unique(same.begin(), same.end())));
+
+ return same;
+}
+
+bool UnwrapAppPolicies(policy_table::ApplicationPolicies& app_policies) {
+ policy_table::ApplicationPolicies::iterator it = app_policies.begin();
+ policy_table::ApplicationPolicies::iterator it_default =
+ app_policies.find(kDefaultId);
+ for (; app_policies.end() != it; ++it) {
+ // Set default policies for app, if there is record like "123":"default"
+ if (kDefaultId.compare((*it).second.get_string()) == 0) {
+ if (it != app_policies.end()) {
+ (*it).second = (*it_default).second;
+ it->second.set_to_string(kDefaultId);
+ } else {
+ LOG4CXX_ERROR(logger_,
+ "There is no default application policy was "
+ "found in PTU.");
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+}
diff --git a/src/components/policy/src/policy_manager_impl.cc b/src/components/policy/src/policy_manager_impl.cc
new file mode 100644
index 0000000000..4e3f892b45
--- /dev/null
+++ b/src/components/policy/src/policy_manager_impl.cc
@@ -0,0 +1,1014 @@
+/*
+ Copyright (c) 2016, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "policy/policy_manager_impl.h"
+
+#include <algorithm>
+#include <set>
+#include <queue>
+#include <iterator>
+#include <limits>
+#include "json/reader.h"
+#include "json/writer.h"
+#include "policy/policy_table.h"
+#include "policy/pt_representation.h"
+#include "policy/policy_helper.h"
+#include "utils/file_system.h"
+#include "utils/logger.h"
+#include "utils/date_time.h"
+#include "utils/make_shared.h"
+#include "policy/cache_manager.h"
+#include "policy/update_status_manager.h"
+#include "config_profile/profile.h"
+#include "utils/timer_task_impl.h"
+
+policy::PolicyManager* CreateManager() {
+ return new policy::PolicyManagerImpl();
+}
+void DeleteManager(policy::PolicyManager* pm) {
+ delete pm;
+}
+
+namespace {
+const uint32_t kDefaultRetryTimeoutInSec = 60u;
+} // namespace
+
+namespace policy {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")
+
+PolicyManagerImpl::PolicyManagerImpl()
+ : PolicyManager()
+ , listener_(NULL)
+ , cache_(new CacheManager)
+ , retry_sequence_timeout_(kDefaultRetryTimeoutInSec)
+ , retry_sequence_index_(0)
+ , timer_retry_sequence_("Retry sequence timer",
+ new timer::TimerTaskImpl<PolicyManagerImpl>(
+ this, &PolicyManagerImpl::RetrySequence))
+ , ignition_check(true) {}
+
+void PolicyManagerImpl::set_listener(PolicyListener* listener) {
+ listener_ = listener;
+ update_status_manager_.set_listener(listener);
+}
+
+#ifdef USE_HMI_PTU_DECRYPTION
+
+utils::SharedPtr<policy_table::Table> PolicyManagerImpl::Parse(
+ const BinaryMessage& pt_content) {
+ std::string json(pt_content.begin(), pt_content.end());
+ Json::Value value;
+ Json::Reader reader;
+ if (reader.parse(json.c_str(), value)) {
+ return new policy_table::Table(&value);
+ } else {
+ return utils::SharedPtr<policy_table::Table>();
+ }
+}
+
+#else
+
+utils::SharedPtr<policy_table::Table> PolicyManagerImpl::ParseArray(
+ const BinaryMessage& pt_content) {
+ std::string json(pt_content.begin(), pt_content.end());
+ Json::Value value;
+ Json::Reader reader;
+ if (reader.parse(json.c_str(), value)) {
+ // For PT Update received from SDL Server.
+ if (value["data"].size() != 0) {
+ Json::Value data = value["data"];
+ return new policy_table::Table(&data[0]);
+ } else {
+ return new policy_table::Table(&value);
+ }
+ } else {
+ return utils::SharedPtr<policy_table::Table>();
+ }
+}
+
+#endif
+
+void PolicyManagerImpl::CheckTriggers() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ const bool exceed_ignition_cycles = ExceededIgnitionCycles();
+ const bool exceed_days = ExceededDays();
+
+ LOG4CXX_DEBUG(
+ logger_,
+ "\nDays exceeded: " << std::boolalpha << exceed_days
+ << "\nIgnition cycles exceeded: " << std::boolalpha
+ << exceed_ignition_cycles);
+
+ if (exceed_ignition_cycles || exceed_days) {
+ update_status_manager_.ScheduleUpdate();
+ }
+}
+
+bool PolicyManagerImpl::LoadPT(const std::string& file,
+ const BinaryMessage& pt_content) {
+ LOG4CXX_INFO(logger_, "LoadPT of size " << pt_content.size());
+
+#ifdef USE_HMI_PTU_DECRYPTION
+ // Assuemes Policy Table was parsed, formatted, and/or decrypted by
+ // the HMI after system request before calling OnReceivedPolicyUpdate
+ // Parse message into table struct
+ utils::SharedPtr<policy_table::Table> pt_update = Parse(pt_content);
+#else
+ // Message Received from server unecnrypted with PTU in first element
+ // of 'data' array. No Parsing was done by HMI.
+ utils::SharedPtr<policy_table::Table> pt_update = ParseArray(pt_content);
+#endif
+ if (!pt_update) {
+ LOG4CXX_WARN(logger_, "Parsed table pointer is 0.");
+ update_status_manager_.OnWrongUpdateReceived();
+ return false;
+ }
+
+ file_system::DeleteFile(file);
+
+ if (!IsPTValid(pt_update, policy_table::PT_UPDATE)) {
+ update_status_manager_.OnWrongUpdateReceived();
+ return false;
+ }
+
+ update_status_manager_.OnValidUpdateReceived();
+ cache_->SaveUpdateRequired(false);
+
+ // Update finished, no need retry
+ if (timer_retry_sequence_.is_running()) {
+ LOG4CXX_INFO(logger_, "Stop retry sequence");
+ timer_retry_sequence_.Stop();
+ }
+
+ {
+ sync_primitives::AutoLock lock(apps_registration_lock_);
+
+ // Get current DB data, since it could be updated during awaiting of PTU
+ utils::SharedPtr<policy_table::Table> policy_table_snapshot =
+ cache_->GenerateSnapshot();
+ if (!policy_table_snapshot) {
+ LOG4CXX_ERROR(logger_, "Failed to create snapshot of policy table");
+ return false;
+ }
+
+ // Checking of difference between PTU and current policy state
+ // Must to be done before PTU applying since it is possible, that functional
+ // groups, which had been present before are absent in PTU and will be
+ // removed after update. So in case of revoked groups system has to know
+ // names and ids of revoked groups before they will be removed.
+ CheckPermissionsChanges(pt_update, policy_table_snapshot);
+
+ // Replace current data with updated
+ if (!cache_->ApplyUpdate(*pt_update)) {
+ LOG4CXX_WARN(logger_, "Unsuccessful save of updated policy table.");
+ return false;
+ }
+
+ if (pt_update->policy_table.module_config.certificate.is_initialized()) {
+ listener_->OnCertificateUpdated(
+ *(pt_update->policy_table.module_config.certificate));
+ }
+
+ std::map<std::string, StringArray> app_hmi_types;
+ cache_->GetHMIAppTypeAfterUpdate(app_hmi_types);
+ if (!app_hmi_types.empty()) {
+ LOG4CXX_INFO(logger_, "app_hmi_types is full calling OnUpdateHMIAppType");
+ listener_->OnUpdateHMIAppType(app_hmi_types);
+ } else {
+ LOG4CXX_INFO(logger_, "app_hmi_types empty" << pt_content.size());
+ }
+ }
+
+ // If there was a user request for policy table update, it should be started
+ // right after current update is finished
+ if (update_status_manager_.IsUpdateRequired()) {
+ StartPTExchange();
+ return true;
+ }
+
+ RefreshRetrySequence();
+ return true;
+}
+
+void PolicyManagerImpl::CheckPermissionsChanges(
+ const utils::SharedPtr<policy_table::Table> pt_update,
+ const utils::SharedPtr<policy_table::Table> snapshot) {
+ LOG4CXX_INFO(logger_, "Checking incoming permissions.");
+
+ // Replace predefined policies with its actual setting, e.g. "123":"default"
+ // to actual values of default section
+ UnwrapAppPolicies(pt_update->policy_table.app_policies_section.apps);
+
+ std::for_each(pt_update->policy_table.app_policies_section.apps.begin(),
+ pt_update->policy_table.app_policies_section.apps.end(),
+ CheckAppPolicy(this, pt_update, snapshot));
+}
+
+void PolicyManagerImpl::PrepareNotificationData(
+ const policy_table::FunctionalGroupings& groups,
+ const policy_table::Strings& group_names,
+ const std::vector<FunctionalGroupPermission>& group_permission,
+ Permissions& notification_data) {
+ LOG4CXX_INFO(logger_, "Preparing data for notification.");
+ ProcessFunctionalGroup processor(groups, group_permission, notification_data);
+ std::for_each(group_names.begin(), group_names.end(), processor);
+}
+
+void PolicyManagerImpl::GetServiceUrls(const std::string& service_type,
+ EndpointUrls& end_points) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ cache_->GetServiceUrls(service_type, end_points);
+}
+
+bool PolicyManagerImpl::RequestPTUpdate() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::SharedPtr<policy_table::Table> policy_table_snapshot =
+ cache_->GenerateSnapshot();
+ if (!policy_table_snapshot) {
+ LOG4CXX_ERROR(logger_, "Failed to create snapshot of policy table");
+ return false;
+ }
+
+ IsPTValid(policy_table_snapshot, policy_table::PT_SNAPSHOT);
+
+ Json::Value value = policy_table_snapshot->ToJsonValue();
+ Json::FastWriter writer;
+ std::string message_string = writer.write(value);
+
+ LOG4CXX_DEBUG(logger_, "Snapshot contents is : " << message_string);
+
+ BinaryMessage update(message_string.begin(), message_string.end());
+
+ listener_->OnSnapshotCreated(update);
+
+ // Need to reset update schedule since all currenly registered applications
+ // were already added to the snapshot so no update for them required.
+ update_status_manager_.ResetUpdateSchedule();
+
+ return true;
+}
+
+std::string PolicyManagerImpl::GetLockScreenIconUrl() const {
+ return cache_->GetLockScreenIconUrl();
+}
+
+void PolicyManagerImpl::StartPTExchange() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ const bool update_required = update_status_manager_.IsUpdateRequired();
+
+ if (update_status_manager_.IsAppsSearchInProgress() && update_required) {
+ update_status_manager_.ScheduleUpdate();
+ LOG4CXX_INFO(logger_,
+ "Starting exchange skipped, since applications "
+ "search is in progress.");
+ return;
+ }
+
+ if (update_status_manager_.IsUpdatePending() && update_required) {
+ update_status_manager_.ScheduleUpdate();
+ LOG4CXX_INFO(logger_,
+ "Starting exchange skipped, since another exchange "
+ "is in progress.");
+ return;
+ }
+
+ if (listener_ && listener_->CanUpdate()) {
+ if (ignition_check) {
+ CheckTriggers();
+ ignition_check = false;
+ }
+
+ if (update_status_manager_.IsUpdateRequired()) {
+ if (RequestPTUpdate() && !timer_retry_sequence_.is_running()) {
+ // Start retry sequency
+ timer_retry_sequence_.Start(NextRetryTimeout(), false);
+ }
+ }
+ }
+}
+
+void PolicyManagerImpl::OnAppsSearchStarted() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ update_status_manager_.OnAppsSearchStarted();
+}
+
+void PolicyManagerImpl::OnAppsSearchCompleted() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ update_status_manager_.OnAppsSearchCompleted();
+ if (update_status_manager_.IsUpdateRequired()) {
+ StartPTExchange();
+ }
+}
+
+void PolicyManagerImpl::OnAppRegisteredOnMobile(
+ const std::string& application_id) {
+ StartPTExchange();
+ SendNotificationOnPermissionsUpdated(application_id);
+}
+
+const std::vector<std::string> PolicyManagerImpl::GetAppRequestTypes(
+ const std::string policy_app_id) const {
+ std::vector<std::string> request_types;
+ cache_->GetAppRequestTypes(policy_app_id, request_types);
+ return request_types;
+}
+
+const VehicleInfo PolicyManagerImpl::GetVehicleInfo() const {
+ return cache_->GetVehicleInfo();
+}
+
+void PolicyManagerImpl::CheckPermissions(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ const RPCParams& rpc_params,
+ CheckPermissionResult& result) {
+ LOG4CXX_INFO(logger_,
+ "CheckPermissions for " << app_id << " and rpc " << rpc
+ << " for " << hmi_level << " level.");
+
+ cache_->CheckPermissions(app_id, hmi_level, rpc, result);
+}
+
+bool PolicyManagerImpl::ResetUserConsent() {
+ bool result = true;
+
+ return result;
+}
+
+void PolicyManagerImpl::SendNotificationOnPermissionsUpdated(
+ const std::string& application_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ const std::string device_id = GetCurrentDeviceId(application_id);
+ if (device_id.empty()) {
+ LOG4CXX_WARN(logger_,
+ "Couldn't find device info for application id "
+ "'" << application_id << "'");
+ return;
+ }
+
+ std::vector<FunctionalGroupPermission> app_group_permissions;
+ GetPermissionsForApp(device_id, application_id, app_group_permissions);
+
+ policy_table::FunctionalGroupings functional_groupings;
+ cache_->GetFunctionalGroupings(functional_groupings);
+
+ policy_table::Strings app_groups;
+ std::vector<FunctionalGroupPermission>::const_iterator it =
+ app_group_permissions.begin();
+ std::vector<FunctionalGroupPermission>::const_iterator it_end =
+ app_group_permissions.end();
+ for (; it != it_end; ++it) {
+ app_groups.push_back((*it).group_name);
+ }
+
+ Permissions notification_data;
+ PrepareNotificationData(functional_groupings,
+ app_groups,
+ app_group_permissions,
+ notification_data);
+
+ LOG4CXX_INFO(logger_,
+ "Send notification for application_id:" << application_id);
+
+ std::string default_hmi;
+ default_hmi = "NONE";
+
+ listener()->OnPermissionsUpdated(
+ application_id, notification_data, default_hmi);
+}
+
+bool PolicyManagerImpl::CleanupUnpairedDevices() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ // For SDL-specific it doesn't matter
+ return true;
+}
+
+DeviceConsent PolicyManagerImpl::GetUserConsentForDevice(
+ const std::string& device_id) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ return kDeviceAllowed;
+}
+
+void PolicyManagerImpl::SetUserConsentForDevice(const std::string& device_id,
+ bool is_allowed) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_, "Device :" << device_id);
+ DeviceConsent current_consent = GetUserConsentForDevice(device_id);
+ bool is_current_device_allowed =
+ DeviceConsent::kDeviceAllowed == current_consent ? true : false;
+ if (DeviceConsent::kDeviceHasNoConsent != current_consent &&
+ is_current_device_allowed == is_allowed) {
+ const std::string consent = is_allowed ? "allowed" : "disallowed";
+ LOG4CXX_INFO(logger_, "Device is already " << consent << ".");
+ return;
+ }
+}
+
+bool PolicyManagerImpl::ReactOnUserDevConsentForApp(const std::string app_id,
+ bool is_device_allowed) {
+ return true;
+}
+
+bool PolicyManagerImpl::GetInitialAppData(const std::string& application_id,
+ StringArray* nicknames,
+ StringArray* app_hmi_types) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ const bool result = nicknames && app_hmi_types;
+ if (result) {
+ cache_->GetInitialAppData(application_id, *nicknames, *app_hmi_types);
+ }
+ return result;
+}
+
+void PolicyManagerImpl::AddDevice(const std::string& device_id,
+ const std::string& connection_type) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_, "Device: " << device_id);
+ if (!cache_->AddDevice(device_id, connection_type)) {
+ LOG4CXX_WARN(logger_, "Can't add device.");
+ }
+}
+
+void PolicyManagerImpl::SetDeviceInfo(const std::string& device_id,
+ const DeviceInfo& device_info) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_, "Device :" << device_id);
+}
+
+PermissionConsent PolicyManagerImpl::EnsureCorrectPermissionConsent(
+ const PermissionConsent& permissions_to_check) {
+ std::vector<FunctionalGroupPermission> current_user_consents;
+ GetUserConsentForApp(permissions_to_check.device_id,
+ permissions_to_check.policy_app_id,
+ current_user_consents);
+
+ PermissionConsent permissions_to_set;
+ permissions_to_set.device_id = permissions_to_check.device_id;
+ permissions_to_set.policy_app_id = permissions_to_check.policy_app_id;
+ permissions_to_set.consent_source = permissions_to_check.consent_source;
+
+ std::vector<FunctionalGroupPermission>::const_iterator it =
+ permissions_to_check.group_permissions.begin();
+ std::vector<FunctionalGroupPermission>::const_iterator it_end =
+ permissions_to_check.group_permissions.end();
+
+ for (; it != it_end; ++it) {
+ std::vector<FunctionalGroupPermission>::const_iterator it_curr =
+ current_user_consents.begin();
+ std::vector<FunctionalGroupPermission>::const_iterator it_curr_end =
+ current_user_consents.end();
+
+ for (; it_curr != it_curr_end; ++it_curr) {
+ if (it->group_alias == it_curr->group_alias &&
+ it->group_id == it_curr->group_id) {
+ permissions_to_set.group_permissions.push_back(*it);
+ }
+ }
+ }
+
+ return permissions_to_set;
+}
+
+void PolicyManagerImpl::CheckPendingPermissionsChanges(
+ const std::string& policy_app_id,
+ const std::vector<FunctionalGroupPermission>& current_permissions) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(app_permissions_diff_lock_);
+ std::map<std::string, AppPermissions>::iterator it_pending =
+ app_permissions_diff_.find(policy_app_id);
+ if (app_permissions_diff_.end() == it_pending) {
+ LOG4CXX_WARN(
+ logger_,
+ "No pending permissions had been found for appID: " << policy_app_id);
+ return;
+ }
+
+ LOG4CXX_DEBUG(
+ logger_,
+ "Pending permissions had been found for appID: " << policy_app_id);
+
+ // Change appPermissionsConsentNeeded depending on unconsented groups
+ // presence
+ std::vector<policy::FunctionalGroupPermission>::const_iterator it_groups =
+ current_permissions.begin();
+ std::vector<policy::FunctionalGroupPermission>::const_iterator it_end_groups =
+ current_permissions.end();
+
+ for (; it_groups != it_end_groups; ++it_groups) {
+ if (policy::kGroupUndefined == it_groups->state) {
+ LOG4CXX_DEBUG(
+ logger_,
+ "Unconsented groups still present for appID: " << policy_app_id);
+ it_pending->second.appPermissionsConsentNeeded = true;
+ return;
+ }
+ }
+
+ LOG4CXX_DEBUG(
+ logger_,
+ "Unconsented groups not present anymore for appID: " << policy_app_id);
+ it_pending->second.appPermissionsConsentNeeded = false;
+ return;
+}
+
+void PolicyManagerImpl::SetUserConsentForApp(
+ const PermissionConsent& permissions) {
+ LOG4CXX_AUTO_TRACE(logger_);
+}
+
+bool PolicyManagerImpl::GetDefaultHmi(const std::string& policy_app_id,
+ std::string* default_hmi) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ const std::string device_id = GetCurrentDeviceId(policy_app_id);
+ DeviceConsent device_consent = GetUserConsentForDevice(device_id);
+ const std::string app_id = policy::kDeviceAllowed != device_consent
+ ? kPreDataConsentId
+ : policy_app_id;
+ return cache_->GetDefaultHMI(app_id, *default_hmi);
+}
+
+bool PolicyManagerImpl::GetPriority(const std::string& policy_app_id,
+ std::string* priority) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!priority) {
+ LOG4CXX_WARN(logger_, "Input priority parameter is null.");
+ return false;
+ }
+
+ return cache_->GetPriority(policy_app_id, *priority);
+}
+
+std::vector<UserFriendlyMessage> PolicyManagerImpl::GetUserFriendlyMessages(
+ const std::vector<std::string>& message_code, const std::string& language) {
+ return cache_->GetUserFriendlyMsg(message_code, language);
+}
+
+void PolicyManagerImpl::GetUserConsentForApp(
+ const std::string& device_id,
+ const std::string& policy_app_id,
+ std::vector<FunctionalGroupPermission>& permissions) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ FunctionalIdType group_types;
+ if (!cache_->GetPermissionsForApp(device_id, policy_app_id, group_types)) {
+ LOG4CXX_WARN(logger_,
+ "Can't get user permissions for app " << policy_app_id);
+ return;
+ }
+
+ // Functional groups w/o alias ("user_consent_prompt") considered as
+ // automatically allowed and it could not be changed by user
+ FunctionalGroupNames group_names;
+ if (!cache_->GetFunctionalGroupNames(group_names)) {
+ LOG4CXX_WARN(logger_, "Can't get functional group names");
+ return;
+ }
+
+ FunctionalGroupNames::const_iterator it = group_names.begin();
+ FunctionalGroupNames::const_iterator it_end = group_names.end();
+ FunctionalGroupIDs auto_allowed_groups;
+ for (; it != it_end; ++it) {
+ if (it->second.first.empty()) {
+ auto_allowed_groups.push_back(it->first);
+ }
+ }
+
+ // For basic policy
+ FunctionalGroupIDs all_groups = group_types[kTypeGeneral];
+ FunctionalGroupIDs default_groups = group_types[kTypeDefault];
+ FunctionalGroupIDs predataconsented_groups =
+ group_types[kTypePreDataConsented];
+
+ FunctionalGroupIDs allowed_groups;
+ FunctionalGroupIDs no_auto = ExcludeSame(all_groups, auto_allowed_groups);
+
+ if (cache_->IsDefaultPolicy(policy_app_id)) {
+ allowed_groups = ExcludeSame(no_auto, default_groups);
+ } else if (cache_->IsPredataPolicy(policy_app_id)) {
+ allowed_groups = ExcludeSame(no_auto, predataconsented_groups);
+ }
+ FillFunctionalGroupPermissions(
+ allowed_groups, group_names, kGroupAllowed, permissions);
+}
+
+void PolicyManagerImpl::GetPermissionsForApp(
+ const std::string& device_id,
+ const std::string& policy_app_id,
+ std::vector<FunctionalGroupPermission>& permissions) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ std::string app_id_to_check = policy_app_id;
+
+ bool allowed_by_default = false;
+ if (cache_->IsDefaultPolicy(policy_app_id)) {
+ app_id_to_check = kDefaultId;
+ allowed_by_default = true;
+ } else if (cache_->IsPredataPolicy(policy_app_id) ||
+ policy::kDeviceDisallowed == GetUserConsentForDevice(device_id)) {
+ app_id_to_check = kPreDataConsentId;
+ allowed_by_default = true;
+ }
+
+ FunctionalIdType group_types;
+ if (!cache_->GetPermissionsForApp(device_id, app_id_to_check, group_types)) {
+ LOG4CXX_WARN(logger_,
+ "Can't get user permissions for app " << policy_app_id);
+ return;
+ }
+
+ // Functional groups w/o alias ("user_consent_prompt") considered as
+ // automatically allowed and it could not be changed by user
+ FunctionalGroupNames group_names;
+ if (!cache_->GetFunctionalGroupNames(group_names)) {
+ LOG4CXX_WARN(logger_, "Can't get functional group names");
+ return;
+ }
+
+ // The "default" and "pre_DataConsent" are auto-allowed groups
+ // So, check if application in the one of these mode.
+ if (allowed_by_default) {
+ LOG4CXX_INFO(logger_, "Get auto allowed groups");
+ GroupType type =
+ (kDefaultId == app_id_to_check ? kTypeDefault : kTypePreDataConsented);
+
+ FillFunctionalGroupPermissions(
+ group_types[type], group_names, kGroupAllowed, permissions);
+ } else {
+ // The code bellow allows to process application which
+ // has specific permissions(not default and pre_DataConsent).
+
+ // All groups for specific application
+ FunctionalGroupIDs all_groups = group_types[kTypeGeneral];
+
+ // In case of GENIVI all groups are allowed
+ FunctionalGroupIDs common_allowed = all_groups;
+ FillFunctionalGroupPermissions(
+ common_allowed, group_names, kGroupAllowed, permissions);
+ }
+ return;
+}
+
+std::string& PolicyManagerImpl::GetCurrentDeviceId(
+ const std::string& policy_app_id) const {
+ LOG4CXX_INFO(logger_, "GetDeviceInfo");
+ last_device_id_ = listener()->OnCurrentDeviceIdUpdateRequired(policy_app_id);
+ return last_device_id_;
+}
+
+void PolicyManagerImpl::SetSystemLanguage(const std::string& language) {}
+
+void PolicyManagerImpl::SetSystemInfo(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language) {
+ LOG4CXX_AUTO_TRACE(logger_);
+}
+
+void PolicyManagerImpl::OnSystemReady() {
+ // Update policy table for the first time with system information
+ if (cache_->IsPTPreloaded()) {
+ listener()->OnSystemInfoUpdateRequired();
+ return;
+ }
+}
+
+uint32_t PolicyManagerImpl::GetNotificationsNumber(
+ const std::string& priority) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ return cache_->GetNotificationsNumber(priority);
+}
+
+bool PolicyManagerImpl::ExceededIgnitionCycles() {
+ return 0 == cache_->IgnitionCyclesBeforeExchange();
+}
+
+bool PolicyManagerImpl::IsPTValid(
+ utils::SharedPtr<policy_table::Table> policy_table,
+ policy_table::PolicyTableType type) const {
+ policy_table->SetPolicyTableType(type);
+ if (!policy_table->is_valid()) {
+ LOG4CXX_ERROR(logger_, "Policy table is not valid.");
+ rpc::ValidationReport report("policy_table");
+ policy_table->ReportErrors(&report);
+ LOG4CXX_DEBUG(logger_, "Errors: " << rpc::PrettyFormat(report));
+ return false;
+ }
+ return true;
+}
+
+const PolicySettings& PolicyManagerImpl::get_settings() const {
+ DCHECK(settings_);
+ return *settings_;
+}
+
+bool PolicyManagerImpl::ExceededDays() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ TimevalStruct current_time = date_time::DateTime::getCurrentTime();
+ const int kSecondsInDay = 60 * 60 * 24;
+ const int days = current_time.tv_sec / kSecondsInDay;
+
+ return 0 == cache_->DaysBeforeExchange(days);
+}
+
+void PolicyManagerImpl::KmsChanged(int kilometers) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (0 == cache_->KilometersBeforeExchange(kilometers)) {
+ LOG4CXX_INFO(logger_, "Enough kilometers passed to send for PT update.");
+ update_status_manager_.ScheduleUpdate();
+ StartPTExchange();
+ }
+}
+
+void PolicyManagerImpl::IncrementIgnitionCycles() {
+ cache_->IncrementIgnitionCycles();
+}
+
+std::string PolicyManagerImpl::ForcePTExchange() {
+ update_status_manager_.ScheduleUpdate();
+ StartPTExchange();
+ return update_status_manager_.StringifiedUpdateStatus();
+}
+
+std::string PolicyManagerImpl::GetPolicyTableStatus() const {
+ return update_status_manager_.StringifiedUpdateStatus();
+}
+
+uint32_t PolicyManagerImpl::NextRetryTimeout() {
+ sync_primitives::AutoLock auto_lock(retry_sequence_lock_);
+ LOG4CXX_DEBUG(logger_, "Index: " << retry_sequence_index_);
+ uint32_t next = 0u;
+ if (retry_sequence_seconds_.empty() ||
+ retry_sequence_index_ >= retry_sequence_seconds_.size()) {
+ return next;
+ }
+
+ ++retry_sequence_index_;
+
+ for (uint32_t i = 0u; i < retry_sequence_index_; ++i) {
+ next += retry_sequence_seconds_[i];
+ // According to requirement APPLINK-18244
+ next += retry_sequence_timeout_;
+ }
+
+ // Return miliseconds
+ return next * date_time::DateTime::MILLISECONDS_IN_SECOND;
+}
+
+void PolicyManagerImpl::RefreshRetrySequence() {
+ sync_primitives::AutoLock auto_lock(retry_sequence_lock_);
+ retry_sequence_timeout_ = cache_->TimeoutResponse();
+ retry_sequence_seconds_.clear();
+ cache_->SecondsBetweenRetries(retry_sequence_seconds_);
+}
+
+void PolicyManagerImpl::ResetRetrySequence() {
+ sync_primitives::AutoLock auto_lock(retry_sequence_lock_);
+ retry_sequence_index_ = 0;
+ update_status_manager_.OnResetRetrySequence();
+}
+
+int PolicyManagerImpl::TimeoutExchange() {
+ return retry_sequence_timeout_;
+}
+
+const std::vector<int> PolicyManagerImpl::RetrySequenceDelaysSeconds() {
+ sync_primitives::AutoLock auto_lock(retry_sequence_lock_);
+ return retry_sequence_seconds_;
+}
+
+void PolicyManagerImpl::OnExceededTimeout() {
+ update_status_manager_.OnUpdateTimeoutOccurs();
+}
+
+void PolicyManagerImpl::OnUpdateStarted() {
+ int update_timeout = TimeoutExchange();
+ LOG4CXX_DEBUG(logger_,
+ "Update timeout will be set to (sec): " << update_timeout);
+ update_status_manager_.OnUpdateSentOut(update_timeout);
+ cache_->SaveUpdateRequired(true);
+}
+
+void PolicyManagerImpl::PTUpdatedAt(Counters counter, int value) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ cache_->SetCountersPassedForSuccessfulUpdate(counter, value);
+ cache_->ResetIgnitionCycles();
+}
+
+void PolicyManagerImpl::Increment(usage_statistics::GlobalCounterId type) {
+ LOG4CXX_INFO(logger_, "Increment without app id");
+ cache_->Increment(type);
+}
+
+void PolicyManagerImpl::Increment(const std::string& app_id,
+ usage_statistics::AppCounterId type) {
+ LOG4CXX_DEBUG(logger_, "Increment " << app_id << " AppCounter: " << type);
+ cache_->Increment(app_id, type);
+}
+
+void PolicyManagerImpl::Set(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value) {
+ LOG4CXX_INFO(logger_, "Set " << app_id);
+ cache_->Set(app_id, type, value);
+}
+
+void PolicyManagerImpl::Add(const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int32_t timespan_seconds) {
+ LOG4CXX_INFO(logger_, "Add " << app_id);
+ cache_->Add(app_id, type, timespan_seconds);
+}
+
+bool PolicyManagerImpl::IsApplicationRevoked(const std::string& app_id) const {
+ return cache_->IsApplicationRevoked(app_id);
+}
+
+bool PolicyManagerImpl::IsConsentNeeded(const std::string& app_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ return false;
+}
+
+void PolicyManagerImpl::SetVINValue(const std::string& value) {}
+
+AppPermissions PolicyManagerImpl::GetAppPermissionsChanges(
+ const std::string& policy_app_id) {
+ typedef std::map<std::string, AppPermissions>::iterator PermissionsIt;
+ PermissionsIt app_id_diff = app_permissions_diff_.find(policy_app_id);
+ AppPermissions permissions(policy_app_id);
+ if (app_permissions_diff_.end() != app_id_diff) {
+ permissions = app_id_diff->second;
+ } else {
+ permissions.appPermissionsConsentNeeded = IsConsentNeeded(policy_app_id);
+ permissions.appRevoked = IsApplicationRevoked(policy_app_id);
+ GetPriority(permissions.application_id, &permissions.priority);
+ }
+ return permissions;
+}
+
+void PolicyManagerImpl::RemovePendingPermissionChanges(
+ const std::string& app_id) {
+ app_permissions_diff_.erase(app_id);
+}
+
+bool PolicyManagerImpl::CanAppKeepContext(const std::string& app_id) const {
+ return cache_->CanAppKeepContext(app_id);
+}
+
+bool PolicyManagerImpl::CanAppStealFocus(const std::string& app_id) const {
+ return cache_->CanAppStealFocus(app_id);
+}
+
+void PolicyManagerImpl::MarkUnpairedDevice(const std::string& device_id) {}
+
+std::string PolicyManagerImpl::RetrieveCertificate() const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ return cache_->GetCertificate();
+}
+
+void PolicyManagerImpl::AddApplication(const std::string& application_id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ const std::string device_id = GetCurrentDeviceId(application_id);
+ DeviceConsent device_consent = GetUserConsentForDevice(device_id);
+ sync_primitives::AutoLock lock(apps_registration_lock_);
+
+ if (IsNewApplication(application_id)) {
+ AddNewApplication(application_id, device_consent);
+ update_status_manager_.OnNewApplicationAdded();
+ } else {
+ PromoteExistedApplication(application_id, device_consent);
+ }
+}
+
+void PolicyManagerImpl::RemoveAppConsentForGroup(
+ const std::string& app_id, const std::string& group_name) {
+ cache_->RemoveAppConsentForGroup(app_id, group_name);
+}
+
+bool PolicyManagerImpl::IsPredataPolicy(const std::string& policy_app_id) {
+ LOG4CXX_INFO(logger_, "IsPredataApp");
+ return cache_->IsPredataPolicy(policy_app_id);
+}
+
+void PolicyManagerImpl::AddNewApplication(const std::string& application_id,
+ DeviceConsent device_consent) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ cache_->SetDefaultPolicy(application_id);
+}
+
+void PolicyManagerImpl::PromoteExistedApplication(
+ const std::string& application_id, DeviceConsent device_consent) {
+ // If device consent changed to allowed during application being
+ // disconnected, app permissions should be changed also
+ if (kDeviceAllowed == device_consent &&
+ cache_->IsPredataPolicy(application_id)) {
+ cache_->SetDefaultPolicy(application_id);
+ }
+}
+
+bool PolicyManagerImpl::IsNewApplication(
+ const std::string& application_id) const {
+ return false == cache_->IsApplicationRepresented(application_id);
+}
+
+bool PolicyManagerImpl::ResetPT(const std::string& file_name) {
+ cache_->ResetCalculatedPermissions();
+ const bool result = cache_->ResetPT(file_name);
+ if (result) {
+ RefreshRetrySequence();
+ }
+ return result;
+}
+
+bool PolicyManagerImpl::CheckAppStorageFolder() const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ const std::string app_storage_folder = get_settings().app_storage_folder();
+ LOG4CXX_DEBUG(logger_, "AppStorageFolder " << app_storage_folder);
+ if (!file_system::DirectoryExists(app_storage_folder)) {
+ LOG4CXX_WARN(logger_,
+ "Storage directory doesn't exist " << app_storage_folder);
+ return false;
+ }
+ if (!(file_system::IsWritingAllowed(app_storage_folder) &&
+ file_system::IsReadingAllowed(app_storage_folder))) {
+ LOG4CXX_WARN(logger_,
+ "Storage directory doesn't have read/write permissions "
+ << app_storage_folder);
+ return false;
+ }
+ return true;
+}
+
+bool PolicyManagerImpl::InitPT(const std::string& file_name,
+ const PolicySettings* settings) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ settings_ = settings;
+ if (!CheckAppStorageFolder()) {
+ LOG4CXX_ERROR(logger_, "Can not read/write into AppStorageFolder");
+ return false;
+ }
+ const bool ret = cache_->Init(file_name, settings);
+ if (ret) {
+ RefreshRetrySequence();
+ update_status_manager_.OnPolicyInit(cache_->UpdateRequired());
+ }
+ return ret;
+}
+
+uint32_t PolicyManagerImpl::HeartBeatTimeout(const std::string& app_id) const {
+ return cache_->HeartBeatTimeout(app_id);
+}
+
+void PolicyManagerImpl::SaveUpdateStatusRequired(bool is_update_needed) {
+ cache_->SaveUpdateRequired(is_update_needed);
+}
+
+void PolicyManagerImpl::set_cache_manager(
+ CacheManagerInterface* cache_manager) {
+ cache_ = cache_manager;
+}
+
+void PolicyManagerImpl::RetrySequence() {
+ LOG4CXX_INFO(logger_, "Start new retry sequence");
+ RequestPTUpdate();
+
+ uint32_t timeout = NextRetryTimeout();
+
+ if (!timeout && timer_retry_sequence_.is_running()) {
+ timer_retry_sequence_.Stop();
+ return;
+ }
+
+ timer_retry_sequence_.Start(timeout, false);
+}
+
+} // namespace policy
diff --git a/src/components/policy/src/policy_table.cc b/src/components/policy/src/policy_table.cc
new file mode 100644
index 0000000000..c5c6e3e132
--- /dev/null
+++ b/src/components/policy/src/policy_table.cc
@@ -0,0 +1,52 @@
+/*
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "policy/policy_table.h"
+
+#include "policy/sql_pt_representation.h"
+
+#include "utils/logger.h"
+
+namespace policy {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")
+
+PolicyTable::PolicyTable() : pt_data_(new SQLPTRepresentation()) {}
+
+PolicyTable::PolicyTable(utils::SharedPtr<PTRepresentation> pt_data)
+ : pt_data_(pt_data) {}
+
+PolicyTable::~PolicyTable() {
+ LOG4CXX_INFO(logger_, "Destroying policy table.");
+}
+
+} // namespace policy
diff --git a/src/components/policy/src/policy_table/enums.cc b/src/components/policy/src/policy_table/enums.cc
new file mode 100644
index 0000000000..26c7b96b32
--- /dev/null
+++ b/src/components/policy/src/policy_table/enums.cc
@@ -0,0 +1,577 @@
+// This file is generated, do not edit
+#include "policy/policy_table/enums.h"
+
+namespace rpc {
+namespace policy_table_interface_base {
+bool IsValidEnum(Priority val) {
+ switch (val) {
+ case P_EMERGENCY:
+ return true;
+ case P_NAVIGATION:
+ return true;
+ case P_VOICECOM:
+ return true;
+ case P_COMMUNICATION:
+ return true;
+ case P_NORMAL:
+ return true;
+ case P_NONE:
+ return true;
+ default:
+ return false;
+ }
+}
+const char* EnumToJsonString(Priority val) {
+ switch (val) {
+ case P_EMERGENCY:
+ return "EMERGENCY";
+ case P_NAVIGATION:
+ return "NAVIGATION";
+ case P_VOICECOM:
+ return "VOICECOM";
+ case P_COMMUNICATION:
+ return "COMMUNICATION";
+ case P_NORMAL:
+ return "NORMAL";
+ case P_NONE:
+ return "NONE";
+ default:
+ return "";
+ }
+}
+bool EnumFromJsonString(const std::string& literal, Priority* result) {
+ if ("EMERGENCY" == literal) {
+ *result = P_EMERGENCY;
+ return true;
+ } else if ("NAVIGATION" == literal) {
+ *result = P_NAVIGATION;
+ return true;
+ } else if ("VOICECOM" == literal) {
+ *result = P_VOICECOM;
+ return true;
+ } else if ("COMMUNICATION" == literal) {
+ *result = P_COMMUNICATION;
+ return true;
+ } else if ("NORMAL" == literal) {
+ *result = P_NORMAL;
+ return true;
+ } else if ("NONE" == literal) {
+ *result = P_NONE;
+ return true;
+ } else {
+ return false;
+ }
+}
+
+bool IsValidEnum(HmiLevel val) {
+ switch (val) {
+ case HL_BACKGROUND:
+ return true;
+ case HL_FULL:
+ return true;
+ case HL_LIMITED:
+ return true;
+ case HL_NONE:
+ return true;
+ default:
+ return false;
+ }
+}
+const char* EnumToJsonString(HmiLevel val) {
+ switch (val) {
+ case HL_BACKGROUND:
+ return "BACKGROUND";
+ case HL_FULL:
+ return "FULL";
+ case HL_LIMITED:
+ return "LIMITED";
+ case HL_NONE:
+ return "NONE";
+ default:
+ return "";
+ }
+}
+bool EnumFromJsonString(const std::string& literal, HmiLevel* result) {
+ if ("BACKGROUND" == literal) {
+ *result = HL_BACKGROUND;
+ return true;
+ } else if ("FULL" == literal) {
+ *result = HL_FULL;
+ return true;
+ } else if ("LIMITED" == literal) {
+ *result = HL_LIMITED;
+ return true;
+ } else if ("NONE" == literal) {
+ *result = HL_NONE;
+ return true;
+ } else {
+ return false;
+ }
+}
+
+bool IsValidEnum(Parameter val) {
+ switch (val) {
+ case P_GPS:
+ return true;
+ case P_SPEED:
+ return true;
+ case P_ENGINETORQUE:
+ return true;
+ case P_EXTERNALTEMPERATURE:
+ return true;
+ case P_FUELLEVEL:
+ return true;
+ case P_FUELLEVEL_STATE:
+ return true;
+ case P_HEADLAMPSTATUS:
+ return true;
+ case P_INSTANTFUELCONSUMPTION:
+ return true;
+ case P_ODOMETER:
+ return true;
+ case P_TIREPRESSURE:
+ return true;
+ case P_WIPERSTATUS:
+ return true;
+ case P_VIN:
+ return true;
+ case P_ACCPEDALPOSITION:
+ return true;
+ case P_BELTSTATUS:
+ return true;
+ case P_DRIVERBRAKING:
+ return true;
+ case P_PRNDL:
+ return true;
+ case P_RPM:
+ return true;
+ case P_STEERINGWHEELANGLE:
+ return true;
+ case P_MYKEY:
+ return true;
+ case P_AIRBAGSTATUS:
+ return true;
+ case P_BODYINFORMATION:
+ return true;
+ case P_CLUSTERMODESTATUS:
+ return true;
+ case P_DEVICESTATUS:
+ return true;
+ case P_EMERGENCYEVENT:
+ return true;
+ case P_ECALLINFO:
+ return true;
+ default:
+ return false;
+ }
+}
+const char* EnumToJsonString(Parameter val) {
+ switch (val) {
+ case P_GPS:
+ return "gps";
+ case P_SPEED:
+ return "speed";
+ case P_ENGINETORQUE:
+ return "engineTorque";
+ case P_EXTERNALTEMPERATURE:
+ return "externalTemperature";
+ case P_FUELLEVEL:
+ return "fuelLevel";
+ case P_FUELLEVEL_STATE:
+ return "fuelLevel_State";
+ case P_HEADLAMPSTATUS:
+ return "headLampStatus";
+ case P_INSTANTFUELCONSUMPTION:
+ return "instantFuelConsumption";
+ case P_ODOMETER:
+ return "odometer";
+ case P_TIREPRESSURE:
+ return "tirePressure";
+ case P_WIPERSTATUS:
+ return "wiperStatus";
+ case P_VIN:
+ return "vin";
+ case P_ACCPEDALPOSITION:
+ return "accPedalPosition";
+ case P_BELTSTATUS:
+ return "beltStatus";
+ case P_DRIVERBRAKING:
+ return "driverBraking";
+ case P_PRNDL:
+ return "prndl";
+ case P_RPM:
+ return "rpm";
+ case P_STEERINGWHEELANGLE:
+ return "steeringWheelAngle";
+ case P_MYKEY:
+ return "myKey";
+ case P_AIRBAGSTATUS:
+ return "airbagStatus";
+ case P_BODYINFORMATION:
+ return "bodyInformation";
+ case P_CLUSTERMODESTATUS:
+ return "clusterModeStatus";
+ case P_DEVICESTATUS:
+ return "deviceStatus";
+ case P_EMERGENCYEVENT:
+ return "emergencyEvent";
+ case P_ECALLINFO:
+ return "eCallInfo";
+ default:
+ return "";
+ }
+}
+bool EnumFromJsonString(const std::string& literal, Parameter* result) {
+ if ("gps" == literal) {
+ *result = P_GPS;
+ return true;
+ } else if ("speed" == literal) {
+ *result = P_SPEED;
+ return true;
+ } else if ("engineTorque" == literal) {
+ *result = P_ENGINETORQUE;
+ return true;
+ } else if ("externalTemperature" == literal) {
+ *result = P_EXTERNALTEMPERATURE;
+ return true;
+ } else if ("fuelLevel" == literal) {
+ *result = P_FUELLEVEL;
+ return true;
+ } else if ("fuelLevel_State" == literal) {
+ *result = P_FUELLEVEL_STATE;
+ return true;
+ } else if ("headLampStatus" == literal) {
+ *result = P_HEADLAMPSTATUS;
+ return true;
+ } else if ("instantFuelConsumption" == literal) {
+ *result = P_INSTANTFUELCONSUMPTION;
+ return true;
+ } else if ("odometer" == literal) {
+ *result = P_ODOMETER;
+ return true;
+ } else if ("tirePressure" == literal) {
+ *result = P_TIREPRESSURE;
+ return true;
+ } else if ("wiperStatus" == literal) {
+ *result = P_WIPERSTATUS;
+ return true;
+ } else if ("vin" == literal) {
+ *result = P_VIN;
+ return true;
+ } else if ("accPedalPosition" == literal) {
+ *result = P_ACCPEDALPOSITION;
+ return true;
+ } else if ("beltStatus" == literal) {
+ *result = P_BELTSTATUS;
+ return true;
+ } else if ("driverBraking" == literal) {
+ *result = P_DRIVERBRAKING;
+ return true;
+ } else if ("prndl" == literal) {
+ *result = P_PRNDL;
+ return true;
+ } else if ("rpm" == literal) {
+ *result = P_RPM;
+ return true;
+ } else if ("steeringWheelAngle" == literal) {
+ *result = P_STEERINGWHEELANGLE;
+ return true;
+ } else if ("myKey" == literal) {
+ *result = P_MYKEY;
+ return true;
+ } else if ("airbagStatus" == literal) {
+ *result = P_AIRBAGSTATUS;
+ return true;
+ } else if ("bodyInformation" == literal) {
+ *result = P_BODYINFORMATION;
+ return true;
+ } else if ("clusterModeStatus" == literal) {
+ *result = P_CLUSTERMODESTATUS;
+ return true;
+ } else if ("deviceStatus" == literal) {
+ *result = P_DEVICESTATUS;
+ return true;
+ } else if ("emergencyEvent" == literal) {
+ *result = P_EMERGENCYEVENT;
+ return true;
+ } else if ("eCallInfo" == literal) {
+ *result = P_ECALLINFO;
+ return true;
+ } else {
+ return false;
+ }
+}
+
+bool IsValidEnum(AppHMIType val) {
+ switch (val) {
+ case AHT_DEFAULT:
+ return true;
+ case AHT_COMMUNICATION:
+ return true;
+ case AHT_MEDIA:
+ return true;
+ case AHT_MESSAGING:
+ return true;
+ case AHT_NAVIGATION:
+ return true;
+ case AHT_INFORMATION:
+ return true;
+ case AHT_SOCIAL:
+ return true;
+ case AHT_BACKGROUND_PROCESS:
+ return true;
+ case AHT_TESTING:
+ return true;
+ case AHT_SYSTEM:
+ return true;
+ default:
+ return false;
+ }
+}
+const char* EnumToJsonString(AppHMIType val) {
+ switch (val) {
+ case AHT_DEFAULT:
+ return "DEFAULT";
+ case AHT_COMMUNICATION:
+ return "COMMUNICATION";
+ case AHT_MEDIA:
+ return "MEDIA";
+ case AHT_MESSAGING:
+ return "MESSAGING";
+ case AHT_NAVIGATION:
+ return "NAVIGATION";
+ case AHT_INFORMATION:
+ return "INFORMATION";
+ case AHT_SOCIAL:
+ return "SOCIAL";
+ case AHT_BACKGROUND_PROCESS:
+ return "BACKGROUND_PROCESS";
+ case AHT_TESTING:
+ return "TESTING";
+ case AHT_SYSTEM:
+ return "SYSTEM";
+ default:
+ return "";
+ }
+}
+bool EnumFromJsonString(const std::string& literal, AppHMIType* result) {
+ if ("DEFAULT" == literal) {
+ *result = AHT_DEFAULT;
+ return true;
+ } else if ("COMMUNICATION" == literal) {
+ *result = AHT_COMMUNICATION;
+ return true;
+ } else if ("MEDIA" == literal) {
+ *result = AHT_MEDIA;
+ return true;
+ } else if ("MESSAGING" == literal) {
+ *result = AHT_MESSAGING;
+ return true;
+ } else if ("NAVIGATION" == literal) {
+ *result = AHT_NAVIGATION;
+ return true;
+ } else if ("INFORMATION" == literal) {
+ *result = AHT_INFORMATION;
+ return true;
+ } else if ("SOCIAL" == literal) {
+ *result = AHT_SOCIAL;
+ return true;
+ } else if ("BACKGROUND_PROCESS" == literal) {
+ *result = AHT_BACKGROUND_PROCESS;
+ return true;
+ } else if ("TESTING" == literal) {
+ *result = AHT_TESTING;
+ return true;
+ } else if ("SYSTEM" == literal) {
+ *result = AHT_SYSTEM;
+ return true;
+ } else {
+ return false;
+ }
+}
+
+bool IsValidEnum(RequestType val) {
+ switch (val) {
+ case RT_HTTP:
+ return true;
+ case RT_FILE_RESUME:
+ return true;
+ case RT_AUTH_REQUEST:
+ return true;
+ case RT_AUTH_CHALLENGE:
+ return true;
+ case RT_AUTH_ACK:
+ return true;
+ case RT_PROPRIETARY:
+ return true;
+ case RT_QUERY_APPS:
+ return true;
+ case RT_LAUNCH_APP:
+ return true;
+ case RT_LOCK_SCREEN_ICON_URL:
+ return true;
+ case RT_TRAFFIC_MESSAGE_CHANNEL:
+ return true;
+ case RT_DRIVER_PROFILE:
+ return true;
+ case RT_VOICE_SEARCH:
+ return true;
+ case RT_NAVIGATION:
+ return true;
+ case RT_PHONE:
+ return true;
+ case RT_CLIMATE:
+ return true;
+ case RT_SETTINGS:
+ return true;
+ case RT_VEHICLE_DIAGNOSTICS:
+ return true;
+ case RT_EMERGENCY:
+ return true;
+ case RT_MEDIA:
+ return true;
+ case RT_FOTA:
+ return true;
+ default:
+ return false;
+ }
+}
+
+const char* EnumToJsonString(RequestType val) {
+ switch (val) {
+ case RT_HTTP:
+ return "HTTP";
+ case RT_FILE_RESUME:
+ return "FILE_RESUME";
+ case RT_AUTH_REQUEST:
+ return "AUTH_REQUEST";
+ case RT_AUTH_CHALLENGE:
+ return "AUTH_CHALLENGE";
+ case RT_AUTH_ACK:
+ return "AUTH_ACK";
+ case RT_PROPRIETARY:
+ return "PROPRIETARY";
+ case RT_QUERY_APPS:
+ return "QUERY_APPS";
+ case RT_LAUNCH_APP:
+ return "LAUNCH_APP";
+ case RT_LOCK_SCREEN_ICON_URL:
+ return "LOCK_SCREEN_ICON_URL";
+ case RT_TRAFFIC_MESSAGE_CHANNEL:
+ return "TRAFFIC_MESSAGE_CHANNEL";
+ case RT_DRIVER_PROFILE:
+ return "DRIVER_PROFILE";
+ case RT_VOICE_SEARCH:
+ return "VOICE_SEARCH";
+ case RT_NAVIGATION:
+ return "NAVIGATION";
+ case RT_PHONE:
+ return "PHONE";
+ case RT_CLIMATE:
+ return "CLIMATE";
+ case RT_SETTINGS:
+ return "SETTINGS";
+ case RT_VEHICLE_DIAGNOSTICS:
+ return "VEHICLE_DIAGNOSTICS";
+ case RT_EMERGENCY:
+ return "EMERGENCY";
+ case RT_MEDIA:
+ return "MEDIA";
+ case RT_FOTA:
+ return "FOTA";
+ default:
+ return "";
+ }
+}
+
+bool EnumFromJsonString(const std::string& literal, RequestType* result) {
+ if ("HTTP" == literal) {
+ *result = RT_HTTP;
+ return true;
+ }
+ if ("FILE_RESUME" == literal) {
+ *result = RT_FILE_RESUME;
+ return true;
+ }
+ if ("AUTH_REQUEST" == literal) {
+ *result = RT_AUTH_REQUEST;
+ return true;
+ }
+ if ("AUTH_CHALLENGE" == literal) {
+ *result = RT_AUTH_CHALLENGE;
+ return true;
+ }
+ if ("AUTH_ACK" == literal) {
+ *result = RT_AUTH_ACK;
+ return true;
+ }
+ if ("PROPRIETARY" == literal) {
+ *result = RT_PROPRIETARY;
+ return true;
+ }
+ if ("QUERY_APPS" == literal) {
+ *result = RT_QUERY_APPS;
+ return true;
+ }
+ if ("LAUNCH_APP" == literal) {
+ *result = RT_LAUNCH_APP;
+ return true;
+ }
+ if ("LOCK_SCREEN_ICON_URL" == literal) {
+ *result = RT_LOCK_SCREEN_ICON_URL;
+ return true;
+ }
+ if ("TRAFFIC_MESSAGE_CHANNEL" == literal) {
+ *result = RT_TRAFFIC_MESSAGE_CHANNEL;
+ return true;
+ }
+ if ("DRIVER_PROFILE" == literal) {
+ *result = RT_DRIVER_PROFILE;
+ return true;
+ }
+ if ("VOICE_SEARCH" == literal) {
+ *result = RT_VOICE_SEARCH;
+ return true;
+ }
+ if ("NAVIGATION" == literal) {
+ *result = RT_NAVIGATION;
+ return true;
+ }
+ if ("PHONE" == literal) {
+ *result = RT_PHONE;
+ return true;
+ }
+ if ("CLIMATE" == literal) {
+ *result = RT_CLIMATE;
+ return true;
+ }
+ if ("SETTINGS" == literal) {
+ *result = RT_SETTINGS;
+ return true;
+ }
+ if ("VEHICLE_DIAGNOSTICS" == literal) {
+ *result = RT_VEHICLE_DIAGNOSTICS;
+ return true;
+ }
+ if ("EMERGENCY" == literal) {
+ *result = RT_EMERGENCY;
+ return true;
+ }
+ if ("MEDIA" == literal) {
+ *result = RT_MEDIA;
+ return true;
+ }
+ if ("FOTA" == literal) {
+ *result = RT_FOTA;
+ return true;
+ } else {
+ return false;
+ }
+}
+
+const std::string kDefaultApp = "default";
+const std::string kPreDataConsentApp = "pre_DataConsent";
+const std::string kDeviceApp = "device";
+
+} // namespace policy_table_interface_base
+} // namespace rpc
diff --git a/src/components/policy/src/policy_table/types.cc b/src/components/policy/src/policy_table/types.cc
new file mode 100644
index 0000000000..33779928ad
--- /dev/null
+++ b/src/components/policy/src/policy_table/types.cc
@@ -0,0 +1,1371 @@
+// This file is generated, do not edit
+#include "policy/policy_table/types.h"
+#include "rpc_base/rpc_base_json_inl.h"
+
+namespace rpc {
+namespace policy_table_interface_base {
+
+std::string PolicyTableTypeToString(const PolicyTableType pt_type) {
+ switch (pt_type) {
+ case PT_PRELOADED: {
+ return "PT_PRELOADED";
+ }
+ case PT_UPDATE: {
+ return "PT_UPDATE";
+ }
+ case PT_SNAPSHOT: {
+ return "PT_SNAPSHOT";
+ }
+ default: { return "INVALID_PT_TYPE"; }
+ }
+}
+
+// PolicyBase methods
+PolicyBase::PolicyBase() : CompositeType(kUninitialized) {}
+
+PolicyBase::PolicyBase(Priority priority)
+ : CompositeType(kUninitialized), priority(priority) {}
+
+PolicyBase::~PolicyBase() {}
+
+PolicyBase::PolicyBase(const Json::Value* value__)
+ : CompositeType(InitHelper(value__, &Json::Value::isObject))
+ , priority(impl::ValueMember(value__, "priority")) {}
+
+Json::Value PolicyBase::ToJsonValue() const {
+ Json::Value result__(Json::objectValue);
+ impl::WriteJsonField("priority", priority, &result__);
+ return result__;
+}
+
+bool PolicyBase::is_valid() const {
+ if (!priority.is_valid()) {
+ return false;
+ }
+ return Validate();
+}
+
+bool PolicyBase::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+
+bool PolicyBase::struct_empty() const {
+ if (priority.is_initialized()) {
+ return false;
+ }
+ return true;
+}
+
+void PolicyBase::ReportErrors(rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+ if (!priority.is_valid()) {
+ priority.ReportErrors(&report__->ReportSubobject("priority"));
+ }
+}
+
+void PolicyBase::SetPolicyTableType(PolicyTableType pt_type) {
+ CompositeType::SetPolicyTableType(pt_type);
+ priority.SetPolicyTableType(pt_type);
+}
+
+// DevicePolicy methods
+DevicePolicy::DevicePolicy() : PolicyBase() {}
+
+DevicePolicy::DevicePolicy(Priority priority) : PolicyBase(priority) {}
+
+DevicePolicy::~DevicePolicy() {}
+
+DevicePolicy::DevicePolicy(const Json::Value* value__) : PolicyBase(value__) {}
+
+// AppPoliciesSection methods
+ApplicationPoliciesSection::ApplicationPoliciesSection()
+ : CompositeType(kUninitialized) {}
+
+ApplicationPoliciesSection::ApplicationPoliciesSection(
+ const ApplicationPolicies& apps, const DevicePolicy& device)
+ : CompositeType(kUninitialized), apps(apps), device(device) {}
+
+ApplicationPoliciesSection::~ApplicationPoliciesSection() {}
+
+ApplicationPoliciesSection::ApplicationPoliciesSection(
+ const Json::Value* value__)
+ : CompositeType(InitHelper(value__, &Json::Value::isObject))
+ , apps(value__)
+ , device(impl::ValueMember(value__, "device")) {
+ // Since "device" is moved to separate struct, we have to delete it from
+ // parsed apps to avoid validation issues due to possible wrong params in
+ // device section
+ apps.erase("device");
+}
+
+Json::Value ApplicationPoliciesSection::ToJsonValue() const {
+ Json::Value result__(Json::objectValue);
+ result__ = apps.ToJsonValue();
+ impl::WriteJsonField("device", device, &result__);
+ return result__;
+}
+
+bool ApplicationPoliciesSection::is_valid() const {
+ if (!device.is_valid()) {
+ return false;
+ }
+ if (!apps.is_valid()) {
+ return false;
+ }
+ return Validate();
+}
+
+bool ApplicationPoliciesSection::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+
+bool ApplicationPoliciesSection::struct_empty() const {
+ if (device.is_initialized()) {
+ return false;
+ }
+ if (apps.is_initialized()) {
+ return false;
+ }
+ return true;
+}
+
+void ApplicationPoliciesSection::ReportErrors(
+ rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+ if (!device.is_valid()) {
+ device.ReportErrors(&report__->ReportSubobject("device"));
+ }
+ if (!apps.is_valid()) {
+ apps.ReportErrors(&report__->ReportSubobject("apps"));
+ }
+}
+
+void ApplicationPoliciesSection::SetPolicyTableType(PolicyTableType pt_type) {
+ CompositeType::SetPolicyTableType(pt_type);
+ device.SetPolicyTableType(pt_type);
+ apps.SetPolicyTableType(pt_type);
+}
+
+// ApplicationParams methods
+ApplicationParams::ApplicationParams() : PolicyBase(), groups() {}
+
+ApplicationParams::ApplicationParams(const Strings& groups, Priority priority)
+ : PolicyBase(priority), groups(groups) {}
+
+ApplicationParams::~ApplicationParams() {}
+
+ApplicationParams::ApplicationParams(const Json::Value* value__)
+ : PolicyBase(value__)
+ , groups(impl::ValueMember(value__, "groups"))
+ , nicknames(impl::ValueMember(value__, "nicknames"))
+ , AppHMIType(impl::ValueMember(value__, "AppHMIType"))
+ , RequestType(impl::ValueMember(value__, "RequestType"))
+ , memory_kb(impl::ValueMember(value__, "memory_kb"), 0)
+ , heart_beat_timeout_ms(impl::ValueMember(value__, "heart_beat_timeout_ms"))
+ , certificate(impl::ValueMember(value__, "certificate"), "not_specified") {}
+
+Json::Value ApplicationParams::ToJsonValue() const {
+ Json::Value result__(PolicyBase::ToJsonValue());
+ impl::WriteJsonField("groups", groups, &result__);
+ impl::WriteJsonField("nicknames", nicknames, &result__);
+ impl::WriteJsonField("AppHMIType", AppHMIType, &result__);
+ impl::WriteJsonField("RequestType", RequestType, &result__);
+ impl::WriteJsonField("memory_kb", memory_kb, &result__);
+ impl::WriteJsonField(
+ "heart_beat_timeout_ms", heart_beat_timeout_ms, &result__);
+ impl::WriteJsonField("certificate", certificate, &result__);
+ return result__;
+}
+
+bool ApplicationParams::is_valid() const {
+ // RequestType is not validated since there is high-level validation logic,
+ // which takes into account information not available here.
+ if (!PolicyBase::is_valid()) {
+ return false;
+ }
+ if (!groups.is_valid()) {
+ return false;
+ }
+ if (!nicknames.is_valid()) {
+ return false;
+ }
+ if (!AppHMIType.is_valid()) {
+ return false;
+ }
+ if (!memory_kb.is_valid()) {
+ return false;
+ }
+ if (!heart_beat_timeout_ms.is_valid()) {
+ return false;
+ }
+ if (!certificate.is_valid()) {
+ return false;
+ }
+ return Validate();
+}
+
+bool ApplicationParams::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+
+bool ApplicationParams::struct_empty() const {
+ if (!PolicyBase::is_initialized()) {
+ return false;
+ }
+ if (groups.is_initialized()) {
+ return false;
+ }
+ if (nicknames.is_initialized()) {
+ return false;
+ }
+ if (AppHMIType.is_initialized()) {
+ return false;
+ }
+ if (RequestType.is_initialized()) {
+ return false;
+ }
+ if (memory_kb.is_initialized()) {
+ return false;
+ }
+ if (heart_beat_timeout_ms.is_initialized()) {
+ return false;
+ }
+ if (certificate.is_initialized()) {
+ return false;
+ }
+ return true;
+}
+
+void ApplicationParams::ReportErrors(rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+ if (!groups.is_valid()) {
+ groups.ReportErrors(&report__->ReportSubobject("groups"));
+ }
+ if (!nicknames.is_valid()) {
+ nicknames.ReportErrors(&report__->ReportSubobject("nicknames"));
+ }
+ if (!AppHMIType.is_valid()) {
+ AppHMIType.ReportErrors(&report__->ReportSubobject("AppHMIType"));
+ }
+ if (!RequestType.is_valid()) {
+ RequestType.ReportErrors(&report__->ReportSubobject("RequestType"));
+ }
+ if (!priority.is_valid()) {
+ priority.ReportErrors(&report__->ReportSubobject("priority"));
+ }
+ if (!memory_kb.is_valid()) {
+ memory_kb.ReportErrors(&report__->ReportSubobject("memory_kb"));
+ }
+ if (!heart_beat_timeout_ms.is_valid()) {
+ heart_beat_timeout_ms.ReportErrors(
+ &report__->ReportSubobject("heart_beat_timeout_ms"));
+ }
+ if (!certificate.is_valid()) {
+ certificate.ReportErrors(&report__->ReportSubobject("certificate"));
+ }
+}
+
+void ApplicationParams::SetPolicyTableType(PolicyTableType pt_type) {
+ PolicyBase::SetPolicyTableType(pt_type);
+ groups.SetPolicyTableType(pt_type);
+ AppHMIType.SetPolicyTableType(pt_type);
+ RequestType.SetPolicyTableType(pt_type);
+ memory_kb.SetPolicyTableType(pt_type);
+ heart_beat_timeout_ms.SetPolicyTableType(pt_type);
+ certificate.SetPolicyTableType(pt_type);
+}
+
+// RpcParameters methods
+RpcParameters::RpcParameters() : CompositeType(kUninitialized) {}
+RpcParameters::RpcParameters(const HmiLevels& hmi_levels)
+ : CompositeType(kUninitialized), hmi_levels(hmi_levels) {}
+RpcParameters::~RpcParameters() {}
+RpcParameters::RpcParameters(const Json::Value* value__)
+ : CompositeType(InitHelper(value__, &Json::Value::isObject))
+ , hmi_levels(impl::ValueMember(value__, "hmi_levels"))
+ , parameters(impl::ValueMember(value__, "parameters")) {}
+Json::Value RpcParameters::ToJsonValue() const {
+ Json::Value result__(Json::objectValue);
+ impl::WriteJsonField("hmi_levels", hmi_levels, &result__);
+ impl::WriteJsonField("parameters", parameters, &result__);
+ return result__;
+}
+bool RpcParameters::is_valid() const {
+ if (!hmi_levels.is_valid()) {
+ return false;
+ }
+ if (!parameters.is_valid()) {
+ return false;
+ }
+ return Validate();
+}
+bool RpcParameters::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+bool RpcParameters::struct_empty() const {
+ if (hmi_levels.is_initialized()) {
+ return false;
+ }
+ if (parameters.is_initialized()) {
+ return false;
+ }
+
+ return true;
+}
+void RpcParameters::ReportErrors(rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+ if (!hmi_levels.is_valid()) {
+ hmi_levels.ReportErrors(&report__->ReportSubobject("hmi_levels"));
+ }
+ if (!parameters.is_valid()) {
+ parameters.ReportErrors(&report__->ReportSubobject("parameters"));
+ }
+}
+
+void RpcParameters::SetPolicyTableType(PolicyTableType pt_type) {
+ CompositeType::SetPolicyTableType(pt_type);
+ hmi_levels.SetPolicyTableType(pt_type);
+ parameters.SetPolicyTableType(pt_type);
+}
+
+// Rpcs methods
+Rpcs::Rpcs() : CompositeType(kUninitialized) {}
+Rpcs::Rpcs(const Rpc& rpcs) : CompositeType(kUninitialized), rpcs(rpcs) {}
+Rpcs::~Rpcs() {}
+Rpcs::Rpcs(const Json::Value* value__)
+ : CompositeType(InitHelper(value__, &Json::Value::isObject))
+ , user_consent_prompt(impl::ValueMember(value__, "user_consent_prompt"))
+ , rpcs(impl::ValueMember(value__, "rpcs")) {}
+Json::Value Rpcs::ToJsonValue() const {
+ Json::Value result__(Json::objectValue);
+ impl::WriteJsonField("user_consent_prompt", user_consent_prompt, &result__);
+ impl::WriteJsonField("rpcs", rpcs, &result__);
+ return result__;
+}
+bool Rpcs::is_valid() const {
+ if (!user_consent_prompt.is_valid()) {
+ return false;
+ }
+ if (!rpcs.is_valid()) {
+ return false;
+ }
+ return Validate();
+}
+bool Rpcs::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+bool Rpcs::struct_empty() const {
+ if (user_consent_prompt.is_initialized()) {
+ return false;
+ }
+ if (rpcs.is_initialized()) {
+ return false;
+ }
+
+ return true;
+}
+void Rpcs::ReportErrors(rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+ if (!user_consent_prompt.is_valid()) {
+ user_consent_prompt.ReportErrors(
+ &report__->ReportSubobject("user_consent_prompt"));
+ }
+ if (!rpcs.is_valid()) {
+ rpcs.ReportErrors(&report__->ReportSubobject("rpcs"));
+ }
+}
+
+void Rpcs::SetPolicyTableType(PolicyTableType pt_type) {
+ CompositeType::SetPolicyTableType(pt_type);
+ user_consent_prompt.SetPolicyTableType(pt_type);
+ rpcs.SetPolicyTableType(pt_type);
+}
+
+// ModuleConfig methods
+ModuleConfig::ModuleConfig() : CompositeType(kUninitialized) {}
+ModuleConfig::ModuleConfig(
+ uint8_t exchange_after_x_ignition_cycles,
+ int64_t exchange_after_x_kilometers,
+ uint8_t exchange_after_x_days,
+ uint16_t timeout_after_x_seconds,
+ const SecondsBetweenRetries& seconds_between_retries,
+ const ServiceEndpoints& endpoints,
+ const NumberOfNotificationsPerMinute& notifications_per_minute_by_priority)
+ : CompositeType(kUninitialized)
+ , exchange_after_x_ignition_cycles(exchange_after_x_ignition_cycles)
+ , exchange_after_x_kilometers(exchange_after_x_kilometers)
+ , exchange_after_x_days(exchange_after_x_days)
+ , timeout_after_x_seconds(timeout_after_x_seconds)
+ , seconds_between_retries(seconds_between_retries)
+ , endpoints(endpoints)
+ , notifications_per_minute_by_priority(
+ notifications_per_minute_by_priority) {}
+ModuleConfig::~ModuleConfig() {}
+ModuleConfig::ModuleConfig(const Json::Value* value__)
+ : CompositeType(InitHelper(value__, &Json::Value::isObject))
+ , device_certificates(impl::ValueMember(value__, "device_certificates"))
+ , preloaded_pt(impl::ValueMember(value__, "preloaded_pt"))
+ , exchange_after_x_ignition_cycles(
+ impl::ValueMember(value__, "exchange_after_x_ignition_cycles"))
+ , exchange_after_x_kilometers(
+ impl::ValueMember(value__, "exchange_after_x_kilometers"))
+ , exchange_after_x_days(impl::ValueMember(value__, "exchange_after_x_days"))
+ , timeout_after_x_seconds(
+ impl::ValueMember(value__, "timeout_after_x_seconds"))
+ , seconds_between_retries(
+ impl::ValueMember(value__, "seconds_between_retries"))
+ , endpoints(impl::ValueMember(value__, "endpoints"))
+ , notifications_per_minute_by_priority(
+ impl::ValueMember(value__, "notifications_per_minute_by_priority"))
+ , vehicle_make(impl::ValueMember(value__, "vehicle_make"))
+ , vehicle_model(impl::ValueMember(value__, "vehicle_model"))
+ , vehicle_year(impl::ValueMember(value__, "vehicle_year"))
+ , preloaded_date(impl::ValueMember(value__, "preloaded_date"))
+ , certificate(impl::ValueMember(value__, "certificate")) {}
+
+void ModuleConfig::SafeCopyFrom(const ModuleConfig& from) {
+ // device_certificates = from.device_certificates; // According to the
+ // requirements this is optional.
+ exchange_after_x_ignition_cycles = from.exchange_after_x_ignition_cycles;
+ exchange_after_x_kilometers = from.exchange_after_x_kilometers;
+ exchange_after_x_days = from.exchange_after_x_days;
+ timeout_after_x_seconds = from.timeout_after_x_seconds;
+ seconds_between_retries = from.seconds_between_retries;
+ endpoints = from.endpoints;
+ notifications_per_minute_by_priority =
+ from.notifications_per_minute_by_priority;
+
+ vehicle_make.assign_if_valid(from.vehicle_make);
+ vehicle_model.assign_if_valid(from.vehicle_model);
+ vehicle_year.assign_if_valid(from.vehicle_year);
+ certificate.assign_if_valid(from.certificate);
+}
+
+Json::Value ModuleConfig::ToJsonValue() const {
+ Json::Value result__(Json::objectValue);
+ impl::WriteJsonField("preloaded_pt", preloaded_pt, &result__);
+ impl::WriteJsonField("exchange_after_x_ignition_cycles",
+ exchange_after_x_ignition_cycles,
+ &result__);
+ impl::WriteJsonField(
+ "exchange_after_x_kilometers", exchange_after_x_kilometers, &result__);
+ impl::WriteJsonField(
+ "exchange_after_x_days", exchange_after_x_days, &result__);
+ impl::WriteJsonField(
+ "timeout_after_x_seconds", timeout_after_x_seconds, &result__);
+ impl::WriteJsonField(
+ "seconds_between_retries", seconds_between_retries, &result__);
+ impl::WriteJsonField("endpoints", endpoints, &result__);
+ impl::WriteJsonField("notifications_per_minute_by_priority",
+ notifications_per_minute_by_priority,
+ &result__);
+ impl::WriteJsonField("vehicle_make", vehicle_make, &result__);
+ impl::WriteJsonField("vehicle_model", vehicle_model, &result__);
+ impl::WriteJsonField("vehicle_year", vehicle_year, &result__);
+ impl::WriteJsonField("certificate", certificate, &result__);
+ impl::WriteJsonField("preloaded_date", preloaded_date, &result__);
+ return result__;
+}
+bool ModuleConfig::is_valid() const {
+ if (!preloaded_pt.is_valid()) {
+ return false;
+ }
+ if (!exchange_after_x_ignition_cycles.is_valid()) {
+ return false;
+ }
+ if (!exchange_after_x_kilometers.is_valid()) {
+ return false;
+ }
+ if (!exchange_after_x_days.is_valid()) {
+ return false;
+ }
+ if (!timeout_after_x_seconds.is_valid()) {
+ return false;
+ }
+ if (!seconds_between_retries.is_valid()) {
+ return false;
+ }
+ if (!endpoints.is_valid()) {
+ return false;
+ }
+ if (!notifications_per_minute_by_priority.is_valid()) {
+ return false;
+ }
+ if (!vehicle_make.is_valid()) {
+ return false;
+ }
+ if (!vehicle_model.is_valid()) {
+ return false;
+ }
+ if (!vehicle_year.is_valid()) {
+ return false;
+ }
+ if (!certificate.is_valid()) {
+ return false;
+ }
+ if (!preloaded_date.is_valid()) {
+ return false;
+ }
+ return Validate();
+}
+bool ModuleConfig::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+bool ModuleConfig::struct_empty() const {
+ if (preloaded_pt.is_initialized()) {
+ return false;
+ }
+
+ if (exchange_after_x_ignition_cycles.is_initialized()) {
+ return false;
+ }
+ if (exchange_after_x_kilometers.is_initialized()) {
+ return false;
+ }
+
+ if (exchange_after_x_days.is_initialized()) {
+ return false;
+ }
+ if (timeout_after_x_seconds.is_initialized()) {
+ return false;
+ }
+
+ if (seconds_between_retries.is_initialized()) {
+ return false;
+ }
+ if (endpoints.is_initialized()) {
+ return false;
+ }
+
+ if (notifications_per_minute_by_priority.is_initialized()) {
+ return false;
+ }
+ if (vehicle_make.is_initialized()) {
+ return false;
+ }
+
+ if (vehicle_model.is_initialized()) {
+ return false;
+ }
+ if (vehicle_year.is_initialized()) {
+ return false;
+ }
+
+ return true;
+}
+void ModuleConfig::ReportErrors(rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+ if (!device_certificates.is_valid()) {
+ device_certificates.ReportErrors(
+ &report__->ReportSubobject("device_certificates"));
+ }
+ if (!preloaded_pt.is_valid()) {
+ preloaded_pt.ReportErrors(&report__->ReportSubobject("preloaded_pt"));
+ }
+ if (!exchange_after_x_ignition_cycles.is_valid()) {
+ exchange_after_x_ignition_cycles.ReportErrors(
+ &report__->ReportSubobject("exchange_after_x_ignition_cycles"));
+ }
+ if (!exchange_after_x_kilometers.is_valid()) {
+ exchange_after_x_kilometers.ReportErrors(
+ &report__->ReportSubobject("exchange_after_x_kilometers"));
+ }
+ if (!exchange_after_x_days.is_valid()) {
+ exchange_after_x_days.ReportErrors(
+ &report__->ReportSubobject("exchange_after_x_days"));
+ }
+ if (!timeout_after_x_seconds.is_valid()) {
+ timeout_after_x_seconds.ReportErrors(
+ &report__->ReportSubobject("timeout_after_x_seconds"));
+ }
+ if (!seconds_between_retries.is_valid()) {
+ seconds_between_retries.ReportErrors(
+ &report__->ReportSubobject("seconds_between_retries"));
+ }
+ if (!endpoints.is_valid()) {
+ endpoints.ReportErrors(&report__->ReportSubobject("endpoints"));
+ }
+ if (!notifications_per_minute_by_priority.is_valid()) {
+ notifications_per_minute_by_priority.ReportErrors(
+ &report__->ReportSubobject("notifications_per_minute_by_priority"));
+ }
+ if (!vehicle_make.is_valid()) {
+ vehicle_make.ReportErrors(&report__->ReportSubobject("vehicle_make"));
+ }
+ if (!vehicle_model.is_valid()) {
+ vehicle_model.ReportErrors(&report__->ReportSubobject("vehicle_model"));
+ }
+ if (!vehicle_year.is_valid()) {
+ vehicle_year.ReportErrors(&report__->ReportSubobject("vehicle_year"));
+ }
+ if (PT_PRELOADED == GetPolicyTableType()) {
+ std::string validation_info =
+ ommited_validation_info + PolicyTableTypeToString(GetPolicyTableType());
+ rpc::ValidationReport* ommited_field_report;
+ if (vehicle_make.is_initialized()) {
+ ommited_field_report = &report__->ReportSubobject("vehicle_make");
+ ommited_field_report->set_validation_info(validation_info);
+ }
+ if (vehicle_year.is_initialized()) {
+ ommited_field_report = &report__->ReportSubobject("vehicle_year");
+ ommited_field_report->set_validation_info(validation_info);
+ }
+ if (vehicle_model.is_initialized()) {
+ ommited_field_report = &report__->ReportSubobject("vehicle_model");
+ ommited_field_report->set_validation_info(validation_info);
+ }
+ }
+}
+
+void ModuleConfig::SetPolicyTableType(PolicyTableType pt_type) {
+ CompositeType::SetPolicyTableType(pt_type);
+ preloaded_pt.SetPolicyTableType(pt_type);
+ exchange_after_x_ignition_cycles.SetPolicyTableType(pt_type);
+ exchange_after_x_kilometers.SetPolicyTableType(pt_type);
+ exchange_after_x_days.SetPolicyTableType(pt_type);
+ timeout_after_x_seconds.SetPolicyTableType(pt_type);
+ seconds_between_retries.SetPolicyTableType(pt_type);
+ endpoints.SetPolicyTableType(pt_type);
+ notifications_per_minute_by_priority.SetPolicyTableType(pt_type);
+ vehicle_make.SetPolicyTableType(pt_type);
+ vehicle_model.SetPolicyTableType(pt_type);
+ vehicle_year.SetPolicyTableType(pt_type);
+}
+
+// MessageString methods
+MessageString::MessageString() : CompositeType(kUninitialized) {}
+MessageString::~MessageString() {}
+MessageString::MessageString(const Json::Value* value__)
+ : CompositeType(InitHelper(value__, &Json::Value::isObject))
+ , line1(impl::ValueMember(value__, "line1"))
+ , line2(impl::ValueMember(value__, "line2"))
+ , tts(impl::ValueMember(value__, "tts"))
+ , label(impl::ValueMember(value__, "label"))
+ , textBody(impl::ValueMember(value__, "textBody")) {}
+Json::Value MessageString::ToJsonValue() const {
+ Json::Value result__(Json::objectValue);
+ impl::WriteJsonField("line1", line1, &result__);
+ impl::WriteJsonField("line2", line2, &result__);
+ impl::WriteJsonField("tts", tts, &result__);
+ impl::WriteJsonField("label", label, &result__);
+ impl::WriteJsonField("textBody", textBody, &result__);
+ return result__;
+}
+bool MessageString::is_valid() const {
+ if (struct_empty()) {
+ return initialization_state__ == kInitialized && Validate();
+ }
+ if (!line1.is_valid()) {
+ return false;
+ }
+ if (!line2.is_valid()) {
+ return false;
+ }
+ if (!tts.is_valid()) {
+ return false;
+ }
+ if (!label.is_valid()) {
+ return false;
+ }
+ if (!textBody.is_valid()) {
+ return false;
+ }
+ return Validate();
+}
+bool MessageString::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+bool MessageString::struct_empty() const {
+ if (line1.is_initialized()) {
+ return false;
+ }
+ if (line2.is_initialized()) {
+ return false;
+ }
+
+ if (tts.is_initialized()) {
+ return false;
+ }
+ if (label.is_initialized()) {
+ return false;
+ }
+
+ if (textBody.is_initialized()) {
+ return false;
+ }
+ return true;
+}
+void MessageString::ReportErrors(rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+ if (!line1.is_valid()) {
+ line1.ReportErrors(&report__->ReportSubobject("line1"));
+ }
+ if (!line2.is_valid()) {
+ line2.ReportErrors(&report__->ReportSubobject("line2"));
+ }
+ if (!tts.is_valid()) {
+ tts.ReportErrors(&report__->ReportSubobject("tts"));
+ }
+ if (!label.is_valid()) {
+ label.ReportErrors(&report__->ReportSubobject("label"));
+ }
+ if (!textBody.is_valid()) {
+ textBody.ReportErrors(&report__->ReportSubobject("textBody"));
+ }
+}
+
+void MessageString::SetPolicyTableType(PolicyTableType pt_type) {
+ CompositeType::SetPolicyTableType(pt_type);
+ line1.SetPolicyTableType(pt_type);
+ line2.SetPolicyTableType(pt_type);
+ tts.SetPolicyTableType(pt_type);
+ label.SetPolicyTableType(pt_type);
+ textBody.SetPolicyTableType(pt_type);
+}
+
+// MessageLanguages methods
+MessageLanguages::MessageLanguages() : CompositeType(kUninitialized) {}
+MessageLanguages::MessageLanguages(const Languages& languages)
+ : CompositeType(kUninitialized), languages(languages) {}
+MessageLanguages::~MessageLanguages() {}
+MessageLanguages::MessageLanguages(const Json::Value* value__)
+ : CompositeType(InitHelper(value__, &Json::Value::isObject))
+ , languages(impl::ValueMember(value__, "languages")) {}
+Json::Value MessageLanguages::ToJsonValue() const {
+ Json::Value result__(Json::objectValue);
+ impl::WriteJsonField("languages", languages, &result__);
+ return result__;
+}
+bool MessageLanguages::is_valid() const {
+ if (!languages.is_valid()) {
+ return false;
+ }
+ return Validate();
+}
+bool MessageLanguages::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+bool MessageLanguages::struct_empty() const {
+ if (languages.is_initialized()) {
+ return false;
+ }
+ return true;
+}
+
+void MessageLanguages::ReportErrors(rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+ if (PT_SNAPSHOT == GetPolicyTableType()) {
+ if (languages.is_initialized()) {
+ std::string validation_info =
+ ommited_validation_info +
+ PolicyTableTypeToString(GetPolicyTableType());
+ report__->ReportSubobject("languages")
+ .set_validation_info(validation_info);
+ }
+ }
+ if (!languages.is_valid()) {
+ languages.ReportErrors(&report__->ReportSubobject("languages"));
+ }
+}
+
+void MessageLanguages::SetPolicyTableType(PolicyTableType pt_type) {
+ CompositeType::SetPolicyTableType(pt_type);
+ languages.SetPolicyTableType(pt_type);
+}
+
+// ConsumerFriendlyMessages methods
+ConsumerFriendlyMessages::ConsumerFriendlyMessages()
+ : CompositeType(kUninitialized) {}
+ConsumerFriendlyMessages::ConsumerFriendlyMessages(const std::string& version)
+ : CompositeType(kUninitialized), version(version) {}
+ConsumerFriendlyMessages::~ConsumerFriendlyMessages() {}
+ConsumerFriendlyMessages::ConsumerFriendlyMessages(const Json::Value* value__)
+ : CompositeType(InitHelper(value__, &Json::Value::isObject))
+ , version(impl::ValueMember(value__, "version"))
+ , messages(impl::ValueMember(value__, "messages")) {}
+Json::Value ConsumerFriendlyMessages::ToJsonValue() const {
+ Json::Value result__(Json::objectValue);
+ impl::WriteJsonField("version", version, &result__);
+ impl::WriteJsonField("messages", messages, &result__);
+ return result__;
+}
+bool ConsumerFriendlyMessages::is_valid() const {
+ if (!version.is_valid()) {
+ return false;
+ }
+ if (!messages.is_valid()) {
+ return false;
+ }
+ return Validate();
+}
+bool ConsumerFriendlyMessages::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+bool ConsumerFriendlyMessages::struct_empty() const {
+ if (version.is_initialized()) {
+ return false;
+ }
+ if (messages.is_initialized()) {
+ return false;
+ }
+
+ return true;
+}
+void ConsumerFriendlyMessages::ReportErrors(
+ rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+ if (!version.is_valid()) {
+ version.ReportErrors(&report__->ReportSubobject("version"));
+ }
+ if (PT_SNAPSHOT == GetPolicyTableType()) {
+ if (messages.is_initialized()) {
+ std::string validation_info =
+ ommited_validation_info +
+ PolicyTableTypeToString(GetPolicyTableType());
+ report__->ReportSubobject("messages")
+ .set_validation_info(validation_info);
+ }
+ }
+ if (!messages.is_valid()) {
+ messages.ReportErrors(&report__->ReportSubobject("messages"));
+ }
+}
+
+void ConsumerFriendlyMessages::SetPolicyTableType(PolicyTableType pt_type) {
+ CompositeType::SetPolicyTableType(pt_type);
+ version.SetPolicyTableType(pt_type);
+ messages.SetPolicyTableType(pt_type);
+}
+
+// ModuleMeta methods
+ModuleMeta::ModuleMeta() : CompositeType(kUninitialized) {}
+ModuleMeta::~ModuleMeta() {}
+ModuleMeta::ModuleMeta(const Json::Value* value__)
+ : CompositeType(InitHelper(value__, &Json::Value::isObject)) {}
+Json::Value ModuleMeta::ToJsonValue() const {
+ Json::Value result__(Json::objectValue);
+ return result__;
+}
+bool ModuleMeta::is_valid() const {
+ if (struct_empty()) {
+ return initialization_state__ == kInitialized && Validate();
+ }
+ return Validate();
+}
+bool ModuleMeta::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+bool ModuleMeta::struct_empty() const {
+ return true;
+}
+void ModuleMeta::ReportErrors(rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+}
+
+// AppLevel methods
+AppLevel::AppLevel() : CompositeType(kUninitialized) {}
+
+AppLevel::AppLevel(uint16_t minutes_in_hmi_full,
+ const std::string& app_registration_language_gui,
+ const std::string& app_registration_language_vui,
+ uint16_t minutes_in_hmi_limited,
+ uint16_t minutes_in_hmi_background,
+ uint16_t minutes_in_hmi_none,
+ uint16_t count_of_user_selections,
+ uint16_t count_of_rejections_sync_out_of_memory,
+ uint16_t count_of_rejections_nickname_mismatch,
+ uint16_t count_of_rejections_duplicate_name,
+ uint16_t count_of_rejected_rpc_calls,
+ uint16_t count_of_rpcs_sent_in_hmi_none,
+ uint16_t count_of_removals_for_bad_behavior,
+ uint16_t count_of_tls_errors,
+ uint16_t count_of_run_attempts_while_revoked)
+ : CompositeType(kUninitialized)
+ , minutes_in_hmi_full(minutes_in_hmi_full)
+ , app_registration_language_gui(app_registration_language_gui)
+ , app_registration_language_vui(app_registration_language_vui)
+ , minutes_in_hmi_limited(minutes_in_hmi_limited)
+ , minutes_in_hmi_background(minutes_in_hmi_background)
+ , minutes_in_hmi_none(minutes_in_hmi_none)
+ , count_of_user_selections(count_of_user_selections)
+ , count_of_rejections_sync_out_of_memory(
+ count_of_rejections_sync_out_of_memory)
+ , count_of_rejections_nickname_mismatch(
+ count_of_rejections_nickname_mismatch)
+ , count_of_rejections_duplicate_name(count_of_rejections_duplicate_name)
+ , count_of_rejected_rpc_calls(count_of_rejected_rpc_calls)
+ , count_of_rpcs_sent_in_hmi_none(count_of_rpcs_sent_in_hmi_none)
+ , count_of_removals_for_bad_behavior(count_of_removals_for_bad_behavior)
+ , count_of_tls_errors(count_of_tls_errors)
+ , count_of_run_attempts_while_revoked(count_of_run_attempts_while_revoked) {
+}
+AppLevel::~AppLevel() {}
+AppLevel::AppLevel(const Json::Value* value__)
+ : CompositeType(InitHelper(value__, &Json::Value::isObject))
+ , minutes_in_hmi_full(impl::ValueMember(value__, "minutes_in_hmi_full"))
+ , app_registration_language_gui(
+ impl::ValueMember(value__, "app_registration_language_gui"))
+ , app_registration_language_vui(
+ impl::ValueMember(value__, "app_registration_language_vui"))
+ , minutes_in_hmi_limited(
+ impl::ValueMember(value__, "minutes_in_hmi_limited"))
+ , minutes_in_hmi_background(
+ impl::ValueMember(value__, "minutes_in_hmi_background"))
+ , minutes_in_hmi_none(impl::ValueMember(value__, "minutes_in_hmi_none"))
+ , count_of_user_selections(
+ impl::ValueMember(value__, "count_of_user_selections"))
+ , count_of_rejections_sync_out_of_memory(
+ impl::ValueMember(value__, "count_of_rejections_sync_out_of_memory"))
+ , count_of_rejections_nickname_mismatch(
+ impl::ValueMember(value__, "count_of_rejections_nickname_mismatch"))
+ , count_of_rejections_duplicate_name(
+ impl::ValueMember(value__, "count_of_rejections_duplicate_name"))
+ , count_of_rejected_rpc_calls(
+ impl::ValueMember(value__, "count_of_rejected_rpc_calls"))
+ , count_of_rpcs_sent_in_hmi_none(
+ impl::ValueMember(value__, "count_of_rpcs_sent_in_hmi_none"))
+ , count_of_removals_for_bad_behavior(
+ impl::ValueMember(value__, "count_of_removals_for_bad_behavior"))
+ , count_of_tls_errors(impl::ValueMember(value__, "count_of_tls_errors"))
+ , count_of_run_attempts_while_revoked(
+ impl::ValueMember(value__, "count_of_run_attempts_while_revoked")) {}
+Json::Value AppLevel::ToJsonValue() const {
+ Json::Value result__(Json::objectValue);
+ impl::WriteJsonField("minutes_in_hmi_full", minutes_in_hmi_full, &result__);
+ impl::WriteJsonField("app_registration_language_gui",
+ app_registration_language_gui,
+ &result__);
+ impl::WriteJsonField("app_registration_language_vui",
+ app_registration_language_vui,
+ &result__);
+ impl::WriteJsonField(
+ "minutes_in_hmi_limited", minutes_in_hmi_limited, &result__);
+ impl::WriteJsonField(
+ "minutes_in_hmi_background", minutes_in_hmi_background, &result__);
+ impl::WriteJsonField("minutes_in_hmi_none", minutes_in_hmi_none, &result__);
+ impl::WriteJsonField(
+ "count_of_user_selections", count_of_user_selections, &result__);
+ impl::WriteJsonField("count_of_rejections_sync_out_of_memory",
+ count_of_rejections_sync_out_of_memory,
+ &result__);
+ impl::WriteJsonField("count_of_rejections_nickname_mismatch",
+ count_of_rejections_nickname_mismatch,
+ &result__);
+ impl::WriteJsonField("count_of_rejections_duplicate_name",
+ count_of_rejections_duplicate_name,
+ &result__);
+ impl::WriteJsonField(
+ "count_of_rejected_rpc_calls", count_of_rejected_rpc_calls, &result__);
+ impl::WriteJsonField("count_of_rpcs_sent_in_hmi_none",
+ count_of_rpcs_sent_in_hmi_none,
+ &result__);
+ impl::WriteJsonField("count_of_removals_for_bad_behavior",
+ count_of_removals_for_bad_behavior,
+ &result__);
+ impl::WriteJsonField("count_of_tls_errors", count_of_tls_errors, &result__);
+ impl::WriteJsonField("count_of_run_attempts_while_revoked",
+ count_of_run_attempts_while_revoked,
+ &result__);
+ return result__;
+}
+bool AppLevel::is_valid() const {
+ if (!minutes_in_hmi_full.is_valid()) {
+ return false;
+ }
+ if (!app_registration_language_gui.is_valid()) {
+ return false;
+ }
+ if (!app_registration_language_vui.is_valid()) {
+ return false;
+ }
+ if (!minutes_in_hmi_limited.is_valid()) {
+ return false;
+ }
+ if (!minutes_in_hmi_background.is_valid()) {
+ return false;
+ }
+ if (!minutes_in_hmi_none.is_valid()) {
+ return false;
+ }
+ if (!count_of_user_selections.is_valid()) {
+ return false;
+ }
+ if (!count_of_rejections_sync_out_of_memory.is_valid()) {
+ return false;
+ }
+ if (!count_of_rejections_nickname_mismatch.is_valid()) {
+ return false;
+ }
+ if (!count_of_rejections_duplicate_name.is_valid()) {
+ return false;
+ }
+ if (!count_of_rejected_rpc_calls.is_valid()) {
+ return false;
+ }
+ if (!count_of_rpcs_sent_in_hmi_none.is_valid()) {
+ return false;
+ }
+ if (!count_of_removals_for_bad_behavior.is_valid()) {
+ return false;
+ }
+ if (!count_of_tls_errors.is_valid()) {
+ return false;
+ }
+ if (!count_of_run_attempts_while_revoked.is_valid()) {
+ return false;
+ }
+ return Validate();
+}
+bool AppLevel::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+bool AppLevel::struct_empty() const {
+ if (minutes_in_hmi_full.is_initialized()) {
+ return false;
+ }
+ if (app_registration_language_gui.is_initialized()) {
+ return false;
+ }
+
+ if (app_registration_language_vui.is_initialized()) {
+ return false;
+ }
+
+ if (minutes_in_hmi_limited.is_initialized()) {
+ return false;
+ }
+ if (minutes_in_hmi_background.is_initialized()) {
+ return false;
+ }
+
+ if (minutes_in_hmi_none.is_initialized()) {
+ return false;
+ }
+ if (count_of_user_selections.is_initialized()) {
+ return false;
+ }
+
+ if (count_of_rejections_sync_out_of_memory.is_initialized()) {
+ return false;
+ }
+ if (count_of_rejections_nickname_mismatch.is_initialized()) {
+ return false;
+ }
+
+ if (count_of_rejections_duplicate_name.is_initialized()) {
+ return false;
+ }
+ if (count_of_rejected_rpc_calls.is_initialized()) {
+ return false;
+ }
+
+ if (count_of_rpcs_sent_in_hmi_none.is_initialized()) {
+ return false;
+ }
+ if (count_of_removals_for_bad_behavior.is_initialized()) {
+ return false;
+ }
+ if (count_of_tls_errors.is_initialized()) {
+ return false;
+ }
+ if (count_of_run_attempts_while_revoked.is_initialized()) {
+ return false;
+ }
+ return true;
+}
+void AppLevel::ReportErrors(rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+ if (PT_PRELOADED == GetPolicyTableType() ||
+ PT_UPDATE == GetPolicyTableType()) {
+ std::string validation_info =
+ ommited_validation_info + PolicyTableTypeToString(GetPolicyTableType());
+ report__->set_validation_info(validation_info);
+ }
+}
+
+// UsageAndErrorCounts methods
+UsageAndErrorCounts::UsageAndErrorCounts() : CompositeType(kUninitialized) {}
+
+UsageAndErrorCounts::~UsageAndErrorCounts() {}
+UsageAndErrorCounts::UsageAndErrorCounts(const Json::Value* value__)
+ : CompositeType(InitHelper(value__, &Json::Value::isObject))
+ , app_level(impl::ValueMember(value__, "app_level")) {}
+Json::Value UsageAndErrorCounts::ToJsonValue() const {
+ Json::Value result__(Json::objectValue);
+ impl::WriteJsonField("app_level", app_level, &result__);
+ return result__;
+}
+bool UsageAndErrorCounts::is_valid() const {
+ if (struct_empty()) {
+ return initialization_state__ == kInitialized && Validate();
+ }
+ if (!app_level.is_valid()) {
+ return false;
+ }
+ return Validate();
+}
+bool UsageAndErrorCounts::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+bool UsageAndErrorCounts::struct_empty() const {
+ if (app_level.is_initialized()) {
+ return false;
+ }
+ return true;
+}
+void UsageAndErrorCounts::ReportErrors(rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+ if (PT_PRELOADED == GetPolicyTableType() ||
+ PT_UPDATE == GetPolicyTableType()) {
+ std::string validation_info =
+ ommited_validation_info + PolicyTableTypeToString(GetPolicyTableType());
+ report__->set_validation_info(validation_info);
+ }
+ if (!app_level.is_valid()) {
+ app_level.ReportErrors(&report__->ReportSubobject("app_level"));
+ }
+}
+
+void UsageAndErrorCounts::SetPolicyTableType(PolicyTableType pt_type) {
+ CompositeType::SetPolicyTableType(pt_type);
+ app_level.SetPolicyTableType(pt_type);
+}
+
+// DeviceParams methods
+DeviceParams::DeviceParams() : CompositeType(kUninitialized) {}
+DeviceParams::~DeviceParams() {}
+DeviceParams::DeviceParams(const Json::Value* value__)
+ : CompositeType(InitHelper(value__, &Json::Value::isObject)) {}
+Json::Value DeviceParams::ToJsonValue() const {
+ Json::Value result__(Json::objectValue);
+ return result__;
+}
+bool DeviceParams::is_valid() const {
+ if (struct_empty()) {
+ return initialization_state__ == kInitialized && Validate();
+ }
+ return Validate();
+}
+bool DeviceParams::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+bool DeviceParams::struct_empty() const {
+ return true;
+}
+void DeviceParams::ReportErrors(rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+}
+
+// PolicyTable methods
+PolicyTable::PolicyTable() : CompositeType(kUninitialized) {}
+PolicyTable::PolicyTable(
+ const ApplicationPoliciesSection& app_policies_section,
+ const FunctionalGroupings& functional_groupings,
+ const ConsumerFriendlyMessages& consumer_friendly_messages,
+ const ModuleConfig& module_config)
+ : CompositeType(kUninitialized)
+ , app_policies_section(app_policies_section)
+ , functional_groupings(functional_groupings)
+ , consumer_friendly_messages(consumer_friendly_messages)
+ , module_config(module_config) {}
+PolicyTable::~PolicyTable() {}
+PolicyTable::PolicyTable(const Json::Value* value__)
+ : CompositeType(InitHelper(value__, &Json::Value::isObject))
+ , app_policies_section(impl::ValueMember(value__, "app_policies"))
+ , functional_groupings(impl::ValueMember(value__, "functional_groupings"))
+ , consumer_friendly_messages(
+ impl::ValueMember(value__, "consumer_friendly_messages"))
+ , module_config(impl::ValueMember(value__, "module_config"))
+ , module_meta(impl::ValueMember(value__, "module_meta"))
+ , usage_and_error_counts(
+ impl::ValueMember(value__, "usage_and_error_counts"))
+ , device_data(impl::ValueMember(value__, "device_data")) {}
+Json::Value PolicyTable::ToJsonValue() const {
+ Json::Value result__(Json::objectValue);
+ impl::WriteJsonField("app_policies", app_policies_section, &result__);
+ impl::WriteJsonField("functional_groupings", functional_groupings, &result__);
+ impl::WriteJsonField(
+ "consumer_friendly_messages", consumer_friendly_messages, &result__);
+ impl::WriteJsonField("module_config", module_config, &result__);
+ impl::WriteJsonField("module_meta", module_meta, &result__);
+ impl::WriteJsonField(
+ "usage_and_error_counts", usage_and_error_counts, &result__);
+ impl::WriteJsonField("device_data", device_data, &result__);
+ return result__;
+}
+bool PolicyTable::is_valid() const {
+ if (!app_policies_section.is_valid()) {
+ return false;
+ }
+ if (!functional_groupings.is_valid()) {
+ return false;
+ }
+ if (!consumer_friendly_messages.is_valid()) {
+ return false;
+ }
+ if (!module_config.is_valid()) {
+ return false;
+ }
+ if (!module_meta.is_valid()) {
+ return false;
+ }
+ if (!usage_and_error_counts.is_valid()) {
+ return false;
+ }
+ if (!device_data.is_valid()) {
+ return false;
+ }
+ return Validate();
+}
+bool PolicyTable::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+bool PolicyTable::struct_empty() const {
+ if (app_policies_section.is_initialized()) {
+ return false;
+ }
+ if (functional_groupings.is_initialized()) {
+ return false;
+ }
+
+ if (consumer_friendly_messages.is_initialized()) {
+ return false;
+ }
+ if (module_config.is_initialized()) {
+ return false;
+ }
+
+ if (module_meta.is_initialized()) {
+ return false;
+ }
+ if (usage_and_error_counts.is_initialized()) {
+ return false;
+ }
+
+ if (device_data.is_initialized()) {
+ return false;
+ }
+ return true;
+}
+void PolicyTable::ReportErrors(rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+ if (PT_PRELOADED == GetPolicyTableType() ||
+ PT_UPDATE == GetPolicyTableType()) {
+ std::string validation_info =
+ ommited_validation_info + PolicyTableTypeToString(GetPolicyTableType());
+
+ if (device_data.is_initialized()) {
+ report__->ReportSubobject("device_data")
+ .set_validation_info(validation_info);
+ }
+ }
+ if (!app_policies_section.is_valid()) {
+ app_policies_section.ReportErrors(
+ &report__->ReportSubobject("app_policies"));
+ }
+ if (!functional_groupings.is_valid()) {
+ functional_groupings.ReportErrors(
+ &report__->ReportSubobject("functional_groupings"));
+ }
+ if (!consumer_friendly_messages.is_valid()) {
+ consumer_friendly_messages.ReportErrors(
+ &report__->ReportSubobject("consumer_friendly_messages"));
+ }
+ if (!module_config.is_valid()) {
+ module_config.ReportErrors(&report__->ReportSubobject("module_config"));
+ }
+ if (!module_meta.is_valid()) {
+ module_meta.ReportErrors(&report__->ReportSubobject("module_meta"));
+ }
+ if (!usage_and_error_counts.is_valid()) {
+ usage_and_error_counts.ReportErrors(
+ &report__->ReportSubobject("usage_and_error_counts"));
+ }
+ if (!device_data.is_valid()) {
+ device_data.ReportErrors(&report__->ReportSubobject("device_data"));
+ }
+}
+
+void PolicyTable::SetPolicyTableType(PolicyTableType pt_type) {
+ CompositeType::SetPolicyTableType(pt_type);
+ app_policies_section.SetPolicyTableType(pt_type);
+ functional_groupings.SetPolicyTableType(pt_type);
+ consumer_friendly_messages.SetPolicyTableType(pt_type);
+ module_config.SetPolicyTableType(pt_type);
+ module_meta.SetPolicyTableType(pt_type);
+ usage_and_error_counts.SetPolicyTableType(pt_type);
+ device_data.SetPolicyTableType(pt_type);
+}
+
+// Table methods
+Table::Table() : CompositeType(kUninitialized) {}
+Table::Table(const PolicyTable& policy_table)
+ : CompositeType(kUninitialized), policy_table(policy_table) {}
+Table::~Table() {}
+Table::Table(const Json::Value* value__)
+ : CompositeType(InitHelper(value__, &Json::Value::isObject))
+ , policy_table(impl::ValueMember(value__, "policy_table")) {}
+Json::Value Table::ToJsonValue() const {
+ Json::Value result__(Json::objectValue);
+ impl::WriteJsonField("policy_table", policy_table, &result__);
+ return result__;
+}
+bool Table::is_valid() const {
+ if (!policy_table.is_valid()) {
+ return false;
+ }
+ return Validate();
+}
+bool Table::is_initialized() const {
+ return (initialization_state__ != kUninitialized) || (!struct_empty());
+}
+bool Table::struct_empty() const {
+ if (policy_table.is_initialized()) {
+ return false;
+ }
+ return true;
+}
+void Table::ReportErrors(rpc::ValidationReport* report__) const {
+ if (struct_empty()) {
+ rpc::CompositeType::ReportErrors(report__);
+ }
+ if (!policy_table.is_valid()) {
+ policy_table.ReportErrors(&report__->ReportSubobject("policy_table"));
+ }
+}
+
+void Table::SetPolicyTableType(PolicyTableType pt_type) {
+ CompositeType::SetPolicyTableType(pt_type);
+ policy_table.SetPolicyTableType(pt_type);
+}
+
+} // namespace policy_table_interface_base
+} // namespace rpc
diff --git a/src/components/policy/src/policy_table/validation.cc b/src/components/policy/src/policy_table/validation.cc
new file mode 100644
index 0000000000..b9bcbfa7ab
--- /dev/null
+++ b/src/components/policy/src/policy_table/validation.cc
@@ -0,0 +1,197 @@
+#include <algorithm>
+#include "policy/policy_table/types.h"
+#include "utils/logger.h"
+
+namespace {
+bool IsTypeInvalid(
+ rpc::Enum<rpc::policy_table_interface_base::RequestType> request) {
+ return !request.is_valid();
+}
+}
+
+namespace rpc {
+namespace policy_table_interface_base {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")
+
+void RemoveInvalidTypes(RequestTypes& types) {
+ types.erase(std::remove_if(types.begin(), types.end(), &IsTypeInvalid),
+ types.end());
+}
+
+bool PolicyBase::Validate() const {
+ return true;
+}
+
+bool ApplicationPoliciesSection::Validate() const {
+ ApplicationPolicies::iterator it_default_policy = apps.find(kDefaultApp);
+ ApplicationPolicies::iterator it_pre_data_policy =
+ apps.find(kPreDataConsentApp);
+
+ // Default and PreData policies are mandatory
+ if (apps.end() == it_default_policy || apps.end() == it_pre_data_policy) {
+ LOG4CXX_ERROR(logger_, "Default or preData policy is not present.");
+ return false;
+ }
+
+ // Device policy is mandatory
+ if (!device.is_initialized()) {
+ LOG4CXX_ERROR(logger_, "Device policy is not present.");
+ return false;
+ }
+
+ PolicyTableType pt_type = GetPolicyTableType();
+ if (PT_PRELOADED != pt_type && PT_UPDATE != pt_type) {
+ return true;
+ }
+
+ if (!it_default_policy->second.RequestType.is_valid()) {
+ LOG4CXX_WARN(logger_,
+ "Default policy RequestTypes are not valid. Will be cleaned.");
+ RemoveInvalidTypes(*it_default_policy->second.RequestType);
+ // If preloaded does not have valid default types - validation fails
+ // Otherwise default will be empty, i.e. all types allowed
+ if (PT_PRELOADED == pt_type) {
+ if (it_default_policy->second.RequestType->empty()) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Default policy RequestTypes empty after clean-up. Exiting.");
+ return false;
+ }
+ }
+ }
+
+ ApplicationPolicies::iterator iter = apps.begin();
+ ApplicationPolicies::iterator end_iter = apps.end();
+
+ while (iter != end_iter) {
+ ApplicationParams& app_params = (*iter).second;
+ bool is_request_type_ommited = !app_params.RequestType.is_initialized();
+ bool is_request_type_valid = app_params.RequestType.is_valid();
+ bool is_request_type_empty = app_params.RequestType->empty();
+
+ if (PT_PRELOADED == pt_type) {
+ if (!is_request_type_valid) {
+ LOG4CXX_WARN(logger_,
+ "App policy RequestTypes are not valid. Will be cleaned.");
+ RemoveInvalidTypes(*app_params.RequestType);
+ if (app_params.RequestType->empty()) {
+ LOG4CXX_ERROR(
+ logger_,
+ "App policy RequestTypes empty after clean-up. Exiting.");
+ return false;
+ }
+ }
+ } else {
+ if (is_request_type_ommited) {
+ LOG4CXX_WARN(logger_,
+ "App policy RequestTypes ommited."
+ " Will be replaced with default.");
+ app_params.RequestType = apps[kDefaultApp].RequestType;
+ ++iter;
+ continue;
+ }
+ if (!is_request_type_valid) {
+ LOG4CXX_WARN(logger_,
+ "App policy RequestTypes are invalid. Will be cleaned.");
+ RemoveInvalidTypes(*app_params.RequestType);
+ if (app_params.RequestType->empty()) {
+ LOG4CXX_WARN(logger_,
+ "App policy RequestTypes empty after clean-up."
+ " Will be replaced with default.");
+ app_params.RequestType = apps[kDefaultApp].RequestType;
+ ++iter;
+ continue;
+ }
+ }
+ if (is_request_type_empty) {
+ LOG4CXX_WARN(logger_, "App policy RequestTypes empty.");
+ }
+ }
+ ++iter;
+ }
+
+ return true;
+}
+
+bool ApplicationParams::Validate() const {
+ return true;
+}
+bool RpcParameters::Validate() const {
+ return true;
+}
+bool Rpcs::Validate() const {
+ return true;
+}
+
+bool ModuleConfig::Validate() const {
+ if (PT_PRELOADED == GetPolicyTableType()) {
+ if (vehicle_make.is_initialized()) {
+ return false;
+ }
+ if (vehicle_year.is_initialized()) {
+ return false;
+ }
+ if (vehicle_model.is_initialized()) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool MessageString::Validate() const {
+ return true;
+}
+
+bool MessageLanguages::Validate() const {
+ if (PT_SNAPSHOT == GetPolicyTableType()) {
+ return false;
+ }
+ return true;
+}
+
+bool ConsumerFriendlyMessages::Validate() const {
+ /* According to requirements consumer_friendly_messages are optional for PTU
+ and required for PTP and PTS. So, they are allowed always */
+ if (PT_SNAPSHOT == GetPolicyTableType() && messages.is_initialized()) {
+ return false;
+ }
+ return true;
+}
+
+bool ModuleMeta::Validate() const {
+ return true;
+}
+
+bool AppLevel::Validate() const {
+ if (PT_PRELOADED == GetPolicyTableType() ||
+ PT_UPDATE == GetPolicyTableType()) {
+ return false;
+ }
+ return true;
+}
+
+bool UsageAndErrorCounts::Validate() const {
+ if (PT_PRELOADED == GetPolicyTableType() ||
+ PT_UPDATE == GetPolicyTableType()) {
+ return false;
+ }
+ return true;
+}
+bool DeviceParams::Validate() const {
+ return true;
+}
+bool PolicyTable::Validate() const {
+ if (PT_PRELOADED == GetPolicyTableType() ||
+ PT_UPDATE == GetPolicyTableType()) {
+ if (device_data.is_initialized()) {
+ return false;
+ }
+ }
+ return true;
+}
+bool Table::Validate() const {
+ return true;
+}
+} // namespace policy_table_interface_base
+} // namespace rpc
diff --git a/src/components/policy/src/sql_pt_ext_queries.cc b/src/components/policy/src/sql_pt_ext_queries.cc
new file mode 100644
index 0000000000..3fde462a32
--- /dev/null
+++ b/src/components/policy/src/sql_pt_ext_queries.cc
@@ -0,0 +1,268 @@
+/*
+ Copyright (c) 2013, " Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, " with or without
+ modification, " are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, " this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice, "
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, " INCLUDING, " BUT NOT LIMITED TO, " THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, " INDIRECT, " INCIDENTAL, " SPECIAL, " EXEMPLARY, " OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, " BUT NOT LIMITED TO, " PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, " DATA, " OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, " WHETHER IN
+ CONTRACT, " STRICT LIABILITY, " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, " EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "policy/sql_pt_ext_queries.h"
+
+namespace policy {
+namespace sql_pt_ext {
+
+const std::string kSelectKeepContext =
+ "SELECT `keep_context` FROM `application` WHERE `id` = ? LIMIT 1";
+
+const std::string kSelectStealFocus =
+ "SELECT `steal_focus` FROM `application` WHERE `id` = ? LIMIT 1";
+
+const std::string kSelectDefaultHmi =
+ "SELECT `default_hmi` FROM `application` WHERE `id` = ? LIMIT 1";
+
+const std::string kResetDeviceConsents = "DELETE FROM `device_consent_group`";
+
+const std::string kResetAppConsents = "DELETE FROM `consent_group`";
+
+const std::string kCountDeviceConsentGroup =
+ "SELECT COUNT (`device_id`) "
+ "FROM `device_consent_group` WHERE `device_id` = ?";
+
+const std::string kCountDevice =
+ "SELECT COUNT (`id`) "
+ "FROM `device` WHERE `id` = ?";
+
+const std::string kSelectDeviceConsentedGroup =
+ "SELECT * FROM `device_consent_group` WHERE `device_id` = ?";
+
+const std::string kUpdateDeviceConsentedGroup =
+ "UPDATE `device_consent_group` SET `is_consented` = ?, `input` = ? WHERE "
+ "(`device_id` = ? AND `functional_group_id` = ?)";
+
+const std::string kUpdateDevice =
+ "UPDATE `device` SET `hardware` = ?, `firmware_rev` = ?, `os` = ?, "
+ "`os_version` = ?, `carrier` = ?, `max_number_rfcom_ports` = ?, "
+ " `connection_type` = ? WHERE `id` = ? ";
+
+const std::string kInsertDeviceConsentedGroup =
+ "INSERT OR REPLACE INTO `device_consent_group` "
+ "(`device_id`, `functional_group_id`, `is_consented`, `input`, "
+ "`time_stamp`) "
+ "VALUES (?,?,?,?,?)";
+
+const std::string kInsertDevice =
+ "INSERT OR IGNORE INTO `device` "
+ "(`id`, `hardware`, `firmware_rev`, `os`, `os_version`, `carrier`,"
+ "`max_number_rfcom_ports`, `connection_type`) "
+ "VALUES (?,?,?,?,?,?,?,?)";
+
+const std::string kSelectDeviceData = "SELECT * FROM `device`";
+
+const std::string kSelectConsentGroup =
+ "SELECT * FROM `consent_group` WHERE `device_id` = ? ";
+
+const std::string kInsertPreconsentedGroups =
+ "INSERT INTO `preconsented_group` (`application_id`, `functional_group_id`)"
+ " SELECT ?, `id` FROM `functional_group` WHERE `name` = ? LIMIT 1";
+
+const std::string kSelectPreconsentedGroups =
+ "SELECT `f`.`name` FROM `preconsented_group` AS `p`"
+ " LEFT JOIN `functional_group` AS `f` "
+ " ON (`f`.`id` = `p`.`functional_group_id`)"
+ " WHERE `p`.`application_id` = ?";
+
+const std::string kDeletePreconsentedGroups =
+ "DELETE FROM `preconsented_group`";
+
+const std::string kSelectUsageAndErrorCount =
+ "SELECT `count_of_iap_buffer_full`, `count_sync_out_of_memory`, "
+ " `count_of_sync_reboots` "
+ "FROM `usage_and_error_count` LIMIT 1";
+
+const std::string kSelectAppLevels =
+ "SELECT `application_id`, `minutes_in_hmi_full`, `minutes_in_hmi_limited`, "
+ " `minutes_in_hmi_background`, `minutes_in_hmi_none`, "
+ " `count_of_user_selections`, "
+ " `count_of_rejections_sync_out_of_memory`, "
+ " `count_of_rejections_nickname_mismatch`, "
+ " `count_of_rejections_duplicate_name`, "
+ " `count_of_rejected_rpcs_calls`, "
+ " `count_of_rpcs_sent_in_hmi_none`, "
+ " `count_of_removals_for_bad_behavior`, "
+ " `count_of_run_attempts_while_revoked`, "
+ " `app_registration_language_gui`, "
+ " `app_registration_language_vui`, "
+ " `count_of_tls_errors` "
+ "FROM `app_level`";
+
+const std::string kUpdateGlobalCounters =
+ "UPDATE `usage_and_error_count` SET "
+ "`count_of_iap_buffer_full` = ?, "
+ "`count_sync_out_of_memory` = ?, "
+ "`count_of_sync_reboots` = ? ";
+
+const std::string kInsertDeviceData =
+ "INSERT OR IGNORE INTO `device` "
+ "(`id`, `hardware`, `firmware_rev`, `os`, `os_version`, `carrier`, "
+ "`max_number_rfcom_ports`,`connection_type`) VALUES (?,?,?,?,?,?,?,?) ";
+
+const std::string kInsertConsentGroups =
+ "INSERT OR REPLACE INTO `consent_group` "
+ "(`device_id`, `application_id`, `functional_group_id`, `is_consented`, "
+ "`input`, `time_stamp`) "
+ "VALUES (?,?,?,?,?,?)";
+
+const std::string kDeleteAppGroupConsent =
+ "DELETE FROM `consent_group` WHERE "
+ "`application_id` = ? AND `functional_group_id` = ? ";
+
+const std::string kSelectGroupId =
+ "SELECT `id` FROM `functional_group` WHERE `name` = ? ";
+
+const std::string kCountUnconsentedGroups =
+ "SELECT COUNT(`a`.`functional_group_id`) FROM `app_group` AS `a` "
+ " WHERE `a`.`application_id` = ? AND NOT EXISTS "
+ " (SELECT NULL FROM `preconsented_group` AS `p` WHERE "
+ " (`p`.`functional_group_id` = `a`.`functional_group_id` AND "
+ " `p`.`application_id` = `a`.`application_id`)) "
+ " AND NOT EXISTS (SELECT NULL FROM `consent_group` AS `c` "
+ " WHERE (`c`.`application_id` = `a`.`application_id` "
+ " AND `c`.`functional_group_id` = `a`.`functional_group_id` "
+ " AND `c`.`device_id` = ?)) AND NOT EXISTS "
+ " (SELECT NULL FROM `app_group` AS `def` WHERE "
+ " (`def`.`application_id` = ? OR "
+ " `def`.`application_id` = ?) "
+ " AND `def`.`functional_group_id` = `a`.`functional_group_id`)"
+ " AND NOT EXISTS (SELECT NULL FROM `functional_group` AS `f` "
+ " WHERE (`a`.`functional_group_id` = `f`.`id`"
+ " AND`f`.`user_consent_prompt` IS NULL))";
+
+const std::string kSelectModuleMeta = "SELECT* FROM `module_meta`";
+
+const std::string kUpdateMetaParams =
+ "UPDATE `module_meta` SET "
+ "`ccpu_version` = ?, `wers_country_code` = ?, `language` = ? ";
+
+const std::string kUpdateModuleMetaVinParam =
+ "UPDATE `module_meta` SET `vin` = ? ";
+
+const std::string kSaveModuleMeta =
+ "UPDATE `module_meta` SET `ccpu_version` = ?, `language` = ?,"
+ "`wers_country_code` = ?, `pt_exchanged_at_odometer_x` = ?,"
+ "`pt_exchanged_x_days_after_epoch` = ?,"
+ "`ignition_cycles_since_last_exchange` = ?, `vin` = ?";
+
+const std::string kSelectMetaParams =
+ "SELECT `ccpu_version`, "
+ "`wers_country_code`, `language` from `module_meta`";
+
+const std::string kUpdateMetaLanguage =
+ "UPDATE `module_meta` SET `language` = ? ";
+
+const std::string kCountAppLevel =
+ "SELECT COUNT(`application_id`) FROM `app_level`"
+ " WHERE `application_id` = ? ";
+
+const std::string kUpdateGroupPermissions =
+ "UPDATE `consent_group` "
+ "SET `is_consented` = ?, `input` = ? "
+ "WHERE(`application_id` = ? AND `functional_group_id` = ? AND `device_id` "
+ "= ?) ";
+
+const std::string kInsertApplication =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, `steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `memory_kb`, "
+ " `heart_beat_timeout_ms`, `certificate`) VALUES( ?, ?, ?, ?, ?, ?, ?, ?, "
+ "?) ";
+
+const std::string kCollectFriendlyMsg = "SELECT * FROM `message`";
+
+const std::string kSelectFriendlyMsg =
+ "SELECT `tts`, `label`, `line1`, `line2`, `textBody` FROM `message` "
+ "WHERE `message_type_name` = ? AND `language_code` = ? LIMIT 1";
+
+const std::string kSelectAppGroupsId =
+ "SELECT `functional_group_id` "
+ "FROM `app_group` WHERE `application_id` = ? ";
+
+const std::string kSelectConsentedGroupsId =
+ "SELECT `functional_group_id`, `is_consented` "
+ "FROM `consent_group` WHERE(`application_id` = ? AND `device_id` = ?) ";
+
+const std::string kCountAppConsents =
+ "SELECT COUNT(*) from `consent_group`"
+ "WHERE(`device_id` = ? AND `application_id` = ? AND "
+ "`functional_group_id` = ?) ";
+
+const std::string kSelectPreconsentedGroupsId =
+ "SELECT `functional_group_id` "
+ "FROM `preconsented_group` WHERE `application_id` = ? ";
+
+const std::string kSelectAppPolicies =
+ "SELECT `id`, `priority_value`, `default_hmi`, `keep_context`, "
+ "`steal_focus`, "
+ " `memory_kb`, `heart_beat_timeout_ms`, `certificate` FROM `application`";
+
+const std::string kSelectFunctionalGroupNames =
+ "SELECT `id`, `user_consent_prompt`, `name`"
+ " FROM `functional_group`";
+
+const std::string kDeleteDeviceConsent =
+ "DELETE FROM `device_consent_group` "
+ "WHERE `device_id` = ? ";
+
+const std::string kDeleteAppConsent =
+ "DELETE FROM `consent_group` "
+ "WHERE `device_id` = ? ";
+
+const std::string kSelectApplicationIsPreData =
+ "SELECT `is_predata` FROM `application` WHERE `id` = ? ";
+
+const std::string kUpdateIsPredata =
+ "UPDATE `application` SET `is_predata` = ? WHERE `id` = ? ";
+
+const std::string kHasAppPreloadedGroups =
+ "SELECT COUNT(`a1`.`functional_group_id`) FROM `app_group` "
+ " AS `a1` JOIN `app_group` AS `a2` "
+ " ON `a1`.`functional_group_id` = `a2`.`functional_group_id` "
+ " WHERE `a1`.`application_id` = ? AND `a2`.`application_id` = ? ";
+
+const std::string kUpdateUnpairedDevice =
+ "UPDATE `device` SET `unpaired` = ? WHERE `id` = ? ";
+
+const std::string kSelectUnpairedDevices =
+ "SELECT `id` FROM `device` WHERE `unpaired` = 1";
+
+const std::string kHasMsgLanguageCode =
+ "SELECT COUNT (`id`) FROM message "
+ "WHERE `message_type_name` = ? AND `language_code` = ? ";
+
+const std::string kDeletePreconsentedGroupsByApplicationId =
+ "DELETE FROM `preconsented_group` WHERE `application_id` = ?";
+
+} // namespace sql_pt_ext
+} // namespace policy
diff --git a/src/components/policy/src/sql_pt_ext_representation.cc b/src/components/policy/src/sql_pt_ext_representation.cc
new file mode 100644
index 0000000000..c64efaaede
--- /dev/null
+++ b/src/components/policy/src/sql_pt_ext_representation.cc
@@ -0,0 +1,1807 @@
+/*
+ Copyright (c) 2015, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+#include <algorithm>
+#include <utility>
+#include "utils/logger.h"
+#include "policy/sql_pt_ext_representation.h"
+#include "policy/sql_wrapper.h"
+#include "policy/sql_pt_queries.h"
+#include "policy/sql_pt_ext_queries.h"
+#include "policy/policy_helper.h"
+#include "policy/cache_manager.h"
+
+namespace policy {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")
+
+bool SQLPTExtRepresentation::CanAppKeepContext(const std::string& app_id) {
+ utils::dbms::SQLQuery query(db());
+ if (query.Prepare(sql_pt_ext::kSelectKeepContext)) {
+ query.Bind(0, app_id);
+ if (query.Exec()) {
+ return query.GetBoolean(0);
+ }
+ }
+ return false;
+}
+
+bool SQLPTExtRepresentation::CanAppStealFocus(const std::string& app_id) {
+ utils::dbms::SQLQuery query(db());
+ if (query.Prepare(sql_pt_ext::kSelectStealFocus)) {
+ query.Bind(0, app_id);
+ if (query.Exec()) {
+ return query.GetBoolean(0);
+ }
+ }
+ return false;
+}
+
+bool SQLPTExtRepresentation::ResetUserConsent() {
+ return ResetDeviceConsents() && ResetAppConsents();
+}
+
+bool SQLPTExtRepresentation::ResetDeviceConsents() {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kResetDeviceConsents)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete statement from device_consents.");
+ return false;
+ }
+ return query.Exec();
+}
+
+bool SQLPTExtRepresentation::ResetAppConsents() {
+ return utils::dbms::SQLQuery(db()).Exec(sql_pt_ext::kResetAppConsents);
+}
+
+bool SQLPTExtRepresentation::GetUserPermissionsForDevice(
+ const std::string& device_id,
+ StringArray* consented_groups,
+ StringArray* disallowed_groups) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kSelectDeviceConsentedGroup)) {
+ LOG4CXX_WARN(logger_, "Incorrect select from device consented groups");
+ return false;
+ }
+ query.Bind(0, device_id);
+ while (query.Next()) {
+ if (query.GetBoolean(2)) {
+ if (!consented_groups) {
+ continue;
+ }
+ consented_groups->push_back(query.GetString(1));
+ } else {
+ if (!disallowed_groups) {
+ continue;
+ }
+ disallowed_groups->push_back(query.GetString(1));
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::GetPermissionsForApp(
+ const std::string& device_id,
+ const std::string& policy_app_id,
+ FunctionalIdType* group_types) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!group_types) {
+ LOG4CXX_WARN(logger_, "Input parameter for group types is null.");
+ return false;
+ }
+ // Get all app groups for specified device and application
+ FunctionalGroupIDs all_groups;
+ if (!GetAllAppGroups(policy_app_id, all_groups)) {
+ return false;
+ }
+ // Get preconsented group
+ FunctionalGroupIDs preconsented_groups;
+ if (!GetPreconsentedGroups(policy_app_id, preconsented_groups)) {
+ return false;
+ }
+ // Get consented (allowed/disallowed) groups
+ FunctionalGroupIDs allowed_groups;
+ FunctionalGroupIDs disallowed_groups;
+ if (!GetConsentedGroups(
+ policy_app_id, device_id, allowed_groups, disallowed_groups)) {
+ return false;
+ }
+ // Get all default groups
+ FunctionalGroupIDs default_groups;
+ if (!GetAllAppGroups(kDefaultId, default_groups)) {
+ return false;
+ }
+
+ // Get all pre_DataConsent groups
+ FunctionalGroupIDs predataconsented_groups;
+ if (!GetAllAppGroups(kPreDataConsentId, predataconsented_groups)) {
+ return false;
+ }
+
+ // Get all device groups
+ FunctionalGroupIDs device_groups;
+ if (!GetAllAppGroups(kDeviceId, device_groups)) {
+ return false;
+ }
+
+ (*group_types)[kTypeDefault] = default_groups;
+ (*group_types)[kTypeAllowed] = allowed_groups;
+ (*group_types)[kTypeDisallowed] = disallowed_groups;
+ (*group_types)[kTypePreconsented] = preconsented_groups;
+ (*group_types)[kTypeGeneral] = all_groups;
+ (*group_types)[kTypePreDataConsented] = predataconsented_groups;
+ (*group_types)[kTypeDevice] = device_groups;
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::GetDeviceGroupsFromPolicies(
+ policy_table::Strings* groups, policy_table::Strings* preconsented_groups) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (groups) {
+ GatherAppGroup(kDeviceId, groups);
+ }
+ if (preconsented_groups) {
+ GatherPreconsentedGroup(kDeviceId, preconsented_groups);
+ }
+ return true;
+}
+
+bool SQLPTExtRepresentation::SetDeviceData(const std::string& device_id,
+ const std::string& hardware,
+ const std::string& firmware,
+ const std::string& os,
+ const std::string& os_version,
+ const std::string& carrier,
+ const uint32_t number_of_ports,
+ const std::string& connection_type) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery count_query(db());
+ if (!count_query.Prepare(sql_pt_ext::kCountDevice)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement for count of device.");
+ return false;
+ }
+
+ count_query.Bind(0, device_id);
+
+ if (!count_query.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect count of device.");
+ return false;
+ }
+
+ bool update = count_query.GetInteger(0);
+
+ // Update old value
+ if (update) {
+ utils::dbms::SQLQuery update_query(db());
+ if (!update_query.Prepare(sql_pt_ext::kUpdateDevice)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement for udpate device.");
+ return false;
+ }
+
+ update_query.Bind(0, hardware);
+ update_query.Bind(1, firmware);
+ update_query.Bind(2, os);
+ update_query.Bind(3, os_version);
+ update_query.Bind(4, carrier);
+ update_query.Bind(5, static_cast<int>(number_of_ports));
+ update_query.Bind(6, device_id);
+ update_query.Bind(7, connection_type);
+
+ if (!update_query.Exec() || !update_query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect update for device.");
+ return false;
+ }
+
+ return true;
+ }
+
+ // Insert new data
+ utils::dbms::SQLQuery insert_query(db());
+ if (!insert_query.Prepare(sql_pt_ext::kInsertDevice)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for device.");
+ return false;
+ }
+
+ insert_query.Bind(0, device_id);
+ insert_query.Bind(1, hardware);
+ insert_query.Bind(2, firmware);
+ insert_query.Bind(3, os);
+ insert_query.Bind(4, os_version);
+ insert_query.Bind(5, carrier);
+ insert_query.Bind(6, static_cast<int>(number_of_ports));
+ insert_query.Bind(7, connection_type);
+
+ if (!insert_query.Exec() || !insert_query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert to device.");
+ return false;
+ }
+
+ SetPreloaded(false);
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::SetUserPermissionsForDevice(
+ const std::string& device_id,
+ const StringArray& consented_groups,
+ const StringArray& disallowed_groups) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery count_query(db());
+ if (!count_query.Prepare(sql_pt_ext::kCountDeviceConsentGroup)) {
+ LOG4CXX_WARN(logger_, "Incorrect count of device consented groups");
+ return false;
+ }
+
+ count_query.Bind(0, device_id);
+
+ if (!count_query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed count of device consented groups");
+ return false;
+ }
+
+ bool update = count_query.GetInteger(0);
+
+ // TODO(AOleynik): Split to several methods?
+ utils::dbms::SQLQuery query(db());
+ // Update old values
+ if (update) {
+ if (!query.Prepare(sql_pt_ext::kUpdateDeviceConsentedGroup)) {
+ LOG4CXX_WARN(
+ logger_,
+ "Incorrect statement for updating consented groups on device");
+ return false;
+ }
+
+ StringArray::const_iterator it_consented_groups = consented_groups.begin();
+ StringArray::const_iterator it_consented_groups_end =
+ consented_groups.end();
+ for (; it_consented_groups != it_consented_groups_end;
+ ++it_consented_groups) {
+ query.Bind(0, true);
+ query.Bind(1, std::string("GUI"));
+ query.Bind(2, device_id);
+ query.Bind(3, *it_consented_groups);
+ // TODO(AOleynik): Get this info from external data
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_,
+ "Failed update of device allowed consented groups.");
+ return false;
+ }
+ }
+
+ StringArray::const_iterator it_disallowed_groups =
+ disallowed_groups.begin();
+ StringArray::const_iterator it_disallowed_groups_end =
+ disallowed_groups.end();
+ for (; it_disallowed_groups != it_disallowed_groups_end;
+ ++it_disallowed_groups) {
+ query.Bind(0, false);
+ query.Bind(1);
+ query.Bind(2, device_id);
+ query.Bind(3, *it_disallowed_groups);
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_,
+ "Failed update of device disallowed consented groups.");
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ // Insert new values
+ if (!query.Prepare(sql_pt_ext::kInsertDeviceConsentedGroup)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect statement of inserting to device consented groups");
+ return false;
+ }
+
+ StringArray::const_iterator it_consented_groups = consented_groups.begin();
+ StringArray::const_iterator it_consented_groups_end = consented_groups.end();
+ for (; it_consented_groups != it_consented_groups_end;
+ ++it_consented_groups) {
+ query.Bind(0, device_id);
+ query.Bind(1, *it_consented_groups);
+ query.Bind(2, true);
+ // TODO(AOleynik): Get this info from external data
+ query.Bind(3, std::string("GUI"));
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_,
+ "Failed insert to device allowed consented groups.");
+ return false;
+ }
+ }
+
+ StringArray::const_iterator it_disallowed_groups = disallowed_groups.begin();
+ StringArray::const_iterator it_disallowed_groups_end =
+ disallowed_groups.end();
+ for (; it_disallowed_groups != it_disallowed_groups_end;
+ ++it_disallowed_groups) {
+ query.Bind(0, device_id);
+ query.Bind(1, *it_disallowed_groups);
+ query.Bind(2, false);
+ query.Bind(3);
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_,
+ "Failed insert to device disallowed consented groups.");
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::ReactOnUserDevConsentForApp(
+ const std::string& app_id, bool is_device_allowed) {
+ bool result = true;
+ if (is_device_allowed) {
+ // If app has pre_DataConsented groups it should be 'promoted' to default
+ // If app has only pre_DataConsented flag it should be only set to false and
+ // all groups get restored automatically
+ if (IsPredataPolicy(app_id)) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kHasAppPreloadedGroups)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect statement for has app preloaded groups");
+ return false;
+ }
+ query.Bind(0, app_id);
+ query.Bind(1, kPreDataConsentId);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect select for app has predataconsted groups");
+ return false;
+ }
+ if (query.GetInteger(0) > 0) {
+ result = result && SetDefaultPolicy(app_id);
+ } else {
+ result = result && SetIsPredata(app_id, false);
+ }
+ }
+ } else {
+ // If app has default groups change them to pre_DataConsented
+ // If app has 'normal' groups leave them as is and set
+ // pre_DataConsented flag to true.
+ if (IsDefaultPolicy(app_id)) {
+ result = result && SetPredataPolicy(app_id);
+ } else {
+ result = result && SetIsPredata(app_id, true);
+ }
+ }
+ return result;
+}
+
+bool SQLPTExtRepresentation::SetUserPermissionsForApp(
+ const PermissionConsent& permissions) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ // TODO(AOleynik): Handle situation, when no application was specified, i.e.
+ // general permissions were set
+ std::vector<FunctionalGroupPermission>::const_iterator it =
+ permissions.group_permissions.begin();
+ std::vector<FunctionalGroupPermission>::const_iterator it_end =
+ permissions.group_permissions.end();
+
+ utils::dbms::SQLQuery query(db());
+ for (; it != it_end; ++it) {
+ utils::dbms::SQLQuery counter(db());
+ if (!counter.Prepare(sql_pt_ext::kCountAppConsents)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement for consent group count.");
+ return false;
+ }
+
+ counter.Bind(0, permissions.device_id);
+ counter.Bind(1, permissions.policy_app_id);
+ counter.Bind(2, static_cast<int>((*it).group_id));
+ if (!counter.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrent count on consent groups.");
+ return false;
+ }
+
+ bool update_required = counter.GetInteger(0);
+
+ // Update already present consent record
+ if (update_required) {
+ if (!query.Prepare(sql_pt_ext::kUpdateGroupPermissions)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement for update consent groups.");
+ return false;
+ }
+
+ // Skip consent saving, if user didn't choose any state
+ if (policy::kGroupUndefined == (*it).state) {
+ continue;
+ }
+ query.Bind(0, (*it).state == kGroupAllowed ? 1 : 0);
+ query.Bind(1, permissions.consent_source);
+ query.Bind(2, permissions.policy_app_id);
+ query.Bind(3, static_cast<int>((*it).group_id));
+ query.Bind(4, permissions.device_id);
+
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect update on user defined permissions "
+ "for app groups.");
+ return false;
+ }
+ continue;
+ }
+
+ // Insert new consent record
+ if (!query.Prepare(sql_pt_ext::kInsertConsentGroups)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect statement for update app group permissions.");
+ return false;
+ }
+
+ // Skip consent saving, if user didn't choose any state
+ if (policy::kGroupUndefined == (*it).state) {
+ continue;
+ }
+ query.Bind(0, permissions.device_id);
+ query.Bind(1, permissions.policy_app_id);
+ query.Bind(2, static_cast<int>((*it).group_id));
+ query.Bind(3, (*it).state == kGroupAllowed ? 1 : 0);
+ query.Bind(4, permissions.consent_source);
+
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect insert to user defined permissions "
+ "for app groups.");
+ return false;
+ }
+ continue;
+ }
+ return true;
+}
+
+std::vector<UserFriendlyMessage> SQLPTExtRepresentation::GetUserFriendlyMsg(
+ const std::vector<std::string>& msg_codes, const std::string& language) {
+ utils::dbms::SQLQuery query(db());
+ std::vector<UserFriendlyMessage> result;
+ if (!query.Prepare(sql_pt_ext::kSelectFriendlyMsg)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement for select friendly messages.");
+ return result;
+ }
+
+ const std::string fallback_language = "en-us";
+ std::vector<std::string>::const_iterator it = msg_codes.begin();
+ std::vector<std::string>::const_iterator it_end = msg_codes.end();
+ for (; it != it_end; ++it) {
+ std::string msg_language = language;
+ // If message has no records with required language, fallback language
+ // should be used instead.
+ if (!IsMsgLanguagePresent((*it), language)) {
+ msg_language = fallback_language;
+ }
+ query.Bind(0, *it);
+ query.Bind(1, msg_language);
+
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect select from friendly messages.");
+ return result;
+ }
+
+ UserFriendlyMessage msg;
+
+ msg.message_code = *it;
+ msg.tts = query.GetString(0);
+ msg.label = query.GetString(1);
+ msg.line1 = query.GetString(2);
+ msg.line2 = query.GetString(3);
+ msg.text_body = query.GetString(4);
+
+ result.push_back(msg);
+
+ if (!query.Reset()) {
+ LOG4CXX_WARN(logger_,
+ "Failed reset statement for selecting friendly "
+ "messages.");
+ return result;
+ }
+ }
+
+ return result;
+}
+
+bool SQLPTExtRepresentation::GatherConsumerFriendlyMessages(
+ policy_table::ConsumerFriendlyMessages* messages) const {
+ if (NULL == messages) {
+ LOG4CXX_ERROR(logger_, "NULL pointer has been passed to fill");
+ return false;
+ }
+
+ if (!SQLPTRepresentation::GatherConsumerFriendlyMessages(messages)) {
+ return false;
+ }
+
+ utils::dbms::SQLQuery query(db());
+ bool result = query.Prepare(sql_pt_ext::kCollectFriendlyMsg);
+
+ if (result) {
+ while (query.Next()) {
+ UserFriendlyMessage msg;
+
+ msg.tts = query.GetString(1);
+ msg.label = query.GetString(2);
+ msg.line1 = query.GetString(3);
+ msg.line2 = query.GetString(4);
+ msg.text_body = query.GetString(5);
+ msg.message_code = query.GetString(7);
+
+ std::string language = query.GetString(6);
+
+ *(*messages->messages)[msg.message_code].languages[language].tts =
+ msg.tts;
+ *(*messages->messages)[msg.message_code].languages[language].label =
+ msg.label;
+ *(*messages->messages)[msg.message_code].languages[language].line1 =
+ msg.line1;
+ *(*messages->messages)[msg.message_code].languages[language].line2 =
+ msg.line2;
+ *(*messages->messages)[msg.message_code].languages[language].textBody =
+ msg.text_body;
+ }
+ } else {
+ LOG4CXX_WARN(logger_, "Incorrect statement for select friendly messages.");
+ }
+ return result;
+}
+
+bool SQLPTExtRepresentation::SetMetaInfo(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kUpdateMetaParams)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement for insert to module meta.");
+ return false;
+ }
+
+ query.Bind(0, ccpu_version);
+ query.Bind(1, wers_country_code);
+ query.Bind(2, language);
+
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert to module meta.");
+ return false;
+ }
+ return true;
+}
+
+bool SQLPTExtRepresentation::IsMetaInfoPresent() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kSelectMetaParams)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement for selecting meta info.");
+ return false;
+ }
+
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect select from module meta.");
+ return false;
+ }
+
+ return !query.IsNull(0) && !query.IsNull(1) && !query.IsNull(2);
+}
+
+bool SQLPTExtRepresentation::SetSystemLanguage(const std::string& language) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kUpdateMetaLanguage)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement for update meta language.");
+ return false;
+ }
+
+ query.Bind(0, language);
+
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect update for meta language.");
+ return false;
+ }
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::SaveApplicationPoliciesSection(
+ const policy_table::ApplicationPoliciesSection& policies) {
+ LOG4CXX_INFO(logger_, "SaveApplicationPolicies ext");
+ utils::dbms::SQLQuery query_delete(db());
+ if (!query_delete.Exec(sql_pt::kDeleteAppGroup)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from app_group.");
+ return false;
+ }
+
+ utils::dbms::SQLQuery query_delete_preconsented(db());
+ if (!query_delete_preconsented.Exec(sql_pt_ext::kDeletePreconsentedGroups)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from preconsented_group.");
+ return false;
+ }
+
+ if (!query_delete.Exec(sql_pt::kDeleteApplication)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from application.");
+ return false;
+ }
+
+ if (!query_delete.Exec(sql_pt::kDeleteRequestType)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from request type.");
+ return false;
+ }
+
+ // First, all predefined apps (e.g. default, pre_DataConsent) should be saved,
+ // otherwise another app with the predefined permissions can get incorrect
+ // permissions
+ policy_table::ApplicationPolicies::const_iterator it_default =
+ policies.apps.find(kDefaultId);
+ if (policies.apps.end() != it_default) {
+ if (!SaveSpecificAppPolicy(*it_default)) {
+ return false;
+ }
+ }
+ policy_table::ApplicationPolicies::const_iterator it_pre_data_consent =
+ policies.apps.find(kPreDataConsentId);
+ if (policies.apps.end() != it_pre_data_consent) {
+ if (!SaveSpecificAppPolicy(*it_pre_data_consent)) {
+ return false;
+ }
+ }
+
+ if (!SaveDevicePolicy(policies.device)) {
+ return false;
+ }
+
+ policy_table::ApplicationPolicies::const_iterator it;
+ for (it = policies.apps.begin(); it != policies.apps.end(); ++it) {
+ // Skip saving of predefined app, since they should be saved before
+ if (IsPredefinedApp(*it)) {
+ continue;
+ }
+ if (!SaveSpecificAppPolicy(*it)) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::SaveSpecificAppPolicy(
+ const policy_table::ApplicationPolicies::value_type& app) {
+ if (app.second.is_string()) {
+ if (kDefaultId.compare(app.second.get_string()) == 0) {
+ if (!SetDefaultPolicy(app.first)) {
+ return false;
+ }
+ if (!SaveRequestType(app.first, *app.second.RequestType)) {
+ return false;
+ }
+ } else if (kPreDataConsentId.compare(app.second.get_string()) == 0) {
+ if (!SetPredataPolicy(app.first)) {
+ return false;
+ }
+ if (!SaveRequestType(app.first, *app.second.RequestType)) {
+ return false;
+ }
+ }
+
+ // Stop saving other params, since predefined permissions already set
+ return true;
+ }
+
+ SetIsDefault(app.first, false);
+ SetIsPredata(app.first, false);
+
+ utils::dbms::SQLQuery app_query(db());
+ if (!app_query.Prepare(sql_pt_ext::kInsertApplication)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement into application.");
+ return false;
+ }
+
+ app_query.Bind(0, app.first);
+ app_query.Bind(1, app.second.keep_context);
+ app_query.Bind(2, app.second.steal_focus);
+ app_query.Bind(
+ 3, std::string(policy_table::EnumToJsonString(app.second.default_hmi)));
+ app_query.Bind(
+ 4, std::string(policy_table::EnumToJsonString(app.second.priority)));
+ app_query.Bind(5, app.second.is_null());
+ app_query.Bind(6, *app.second.memory_kb);
+ app_query.Bind(7, static_cast<int64_t>(*app.second.heart_beat_timeout_ms));
+ app.second.certificate.is_initialized()
+ ? app_query.Bind(8, *app.second.certificate)
+ : app_query.Bind(8, std::string());
+
+ if (!app_query.Exec() || !app_query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into application.");
+ return false;
+ }
+
+ if (!SaveAppGroup(app.first, app.second.groups)) {
+ return false;
+ }
+ // TODO(IKozyrenko): Check logic if optional container is missing
+ if (!SaveNickname(app.first, *app.second.nicknames)) {
+ return false;
+ }
+ // TODO(IKozyrenko): Check logic if optional container is missing
+ if (!SaveAppType(app.first, *app.second.AppHMIType)) {
+ return false;
+ }
+ // TODO(IKozyrenko): Check logic if optional container is missing
+ if (!SavePreconsentedGroup(app.first, *app.second.preconsented_groups)) {
+ return false;
+ }
+
+ return true;
+}
+
+bool policy::SQLPTExtRepresentation::SaveDevicePolicy(
+ const policy_table::DevicePolicy& device) {
+ dbms::SQLQuery app_query(db());
+ if (!app_query.Prepare(sql_pt_ext::kInsertApplication)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect insert statement into application (device).");
+ return false;
+ }
+ app_query.Bind(0, kDeviceId);
+ app_query.Bind(1, device.keep_context);
+ app_query.Bind(2, device.steal_focus);
+ app_query.Bind(
+ 3, std::string(policy_table::EnumToJsonString(device.default_hmi)));
+ app_query.Bind(4,
+ std::string(policy_table::EnumToJsonString(device.priority)));
+ app_query.Bind(5, false);
+ app_query.Bind(6, 0);
+ app_query.Bind(7, 0);
+ app_query.Bind(8, std::string());
+
+ if (!app_query.Exec() || !app_query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into application.");
+ return false;
+ }
+
+ if (!SaveAppGroup(kDeviceId, device.groups)) {
+ return false;
+ }
+ if (!SavePreconsentedGroup(kDeviceId, *device.preconsented_groups)) {
+ return false;
+ }
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::GatherApplicationPoliciesSection(
+ policy_table::ApplicationPoliciesSection* policies) const {
+ LOG4CXX_INFO(logger_, "Gather applications policies");
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kSelectAppPolicies)) {
+ LOG4CXX_WARN(logger_, "Incorrect select from app_policies");
+ return false;
+ }
+
+ while (query.Next()) {
+ rpc::Nullable<policy_table::ApplicationParams> params;
+ const std::string& app_id = query.GetString(0);
+ if (IsApplicationRevoked(app_id)) {
+ params.set_to_null();
+ (*policies).apps[app_id] = params;
+ continue;
+ }
+ if (IsDefaultPolicy(app_id)) {
+ (*policies).apps[app_id].set_to_string(kDefaultId);
+ }
+ if (IsPredataPolicy(app_id)) {
+ (*policies).apps[app_id].set_to_string(kPreDataConsentId);
+ }
+ if (kDeviceId == app_id) {
+ policy_table::DevicePolicy device_policy;
+ policy_table::Priority priority;
+ policy_table::EnumFromJsonString(query.GetString(1), &priority);
+ device_policy.priority = priority;
+ policy_table::HmiLevel hmi;
+ policy_table::EnumFromJsonString(query.GetString(2), &hmi);
+ device_policy.default_hmi = hmi;
+ device_policy.keep_context = query.GetBoolean(3);
+ device_policy.steal_focus = query.GetBoolean(4);
+ if (!GatherAppGroup(app_id, &device_policy.groups)) {
+ return false;
+ }
+ GatherPreconsentedGroup(app_id, &*device_policy.preconsented_groups);
+ (*policies).device = device_policy;
+ continue;
+ }
+ policy_table::Priority priority;
+ policy_table::EnumFromJsonString(query.GetString(1), &priority);
+ params.priority = priority;
+ policy_table::HmiLevel hmi;
+ policy_table::EnumFromJsonString(query.GetString(2), &hmi);
+ params.default_hmi = hmi;
+ params.keep_context = query.GetBoolean(3);
+ params.steal_focus = query.GetBoolean(4);
+ *params.memory_kb = query.GetInteger(5);
+ *params.heart_beat_timeout_ms = query.GetUInteger(6);
+ if (!query.IsNull(7)) {
+ *params.certificate = query.GetString(7);
+ }
+ if (!GatherAppGroup(app_id, &params.groups)) {
+ return false;
+ }
+ if (!GatherNickName(app_id, &*params.nicknames)) {
+ return false;
+ }
+ if (!GatherAppType(app_id, &*params.AppHMIType)) {
+ return false;
+ }
+ if (!GatherRequestType(app_id, &*params.RequestType)) {
+ return false;
+ }
+ GatherPreconsentedGroup(app_id, &*params.preconsented_groups);
+ (*policies).apps[app_id] = params;
+ }
+ return true;
+}
+
+void SQLPTExtRepresentation::GatherPreconsentedGroup(
+ const std::string& app_id, policy_table::Strings* groups) const {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kSelectPreconsentedGroups)) {
+ LOG4CXX_WARN(logger_, "Incorrect select from preconsented group");
+ return;
+ }
+
+ query.Bind(0, app_id);
+ while (query.Next()) {
+ groups->push_back(query.GetString(0));
+ }
+}
+
+bool SQLPTExtRepresentation::GatherUsageAndErrorCounts(
+ policy_table::UsageAndErrorCounts* counts) const {
+ LOG4CXX_INFO(logger_, "Gather Usage and Error Counts.");
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kSelectUsageAndErrorCount) || !query.Exec()) {
+ LOG4CXX_INFO(logger_, "Failed select from user_and_error_count");
+ return false;
+ }
+
+ *counts->count_of_iap_buffer_full = query.GetInteger(0);
+ *counts->count_sync_out_of_memory = query.GetInteger(1);
+ *counts->count_of_sync_reboots = query.GetInteger(2);
+
+ return GatherAppLevels(&*counts->app_level);
+}
+
+bool SQLPTExtRepresentation::GatherAppLevels(
+ policy_table::AppLevels* apps) const {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kSelectAppLevels)) {
+ LOG4CXX_INFO(logger_,
+ "Failed select from app_level. SQLError = "
+ << query.LastError().text());
+ return false;
+ }
+ while (query.Next()) {
+ policy_table::AppLevel level;
+ // value of time fields database is seconds
+ level.minutes_in_hmi_full = query.GetInteger(1);
+ level.minutes_in_hmi_limited = query.GetInteger(2);
+ level.minutes_in_hmi_background = query.GetInteger(3);
+ level.minutes_in_hmi_none = query.GetInteger(4);
+ level.count_of_user_selections = query.GetInteger(5);
+ level.count_of_rejections_sync_out_of_memory = query.GetInteger(6);
+ level.count_of_rejections_nickname_mismatch = query.GetInteger(7);
+ level.count_of_rejections_duplicate_name = query.GetInteger(8);
+ level.count_of_rejected_rpc_calls = query.GetInteger(9);
+ level.count_of_rpcs_sent_in_hmi_none = query.GetInteger(10);
+ level.count_of_removals_for_bad_behavior = query.GetInteger(11);
+ level.count_of_run_attempts_while_revoked = query.GetInteger(12);
+ level.app_registration_language_gui = query.GetString(13);
+ level.app_registration_language_vui = query.GetString(14);
+ level.count_of_tls_errors = query.GetInteger(15);
+ (*apps)[query.GetString(0)] = level;
+ }
+
+ return true;
+}
+
+void SQLPTExtRepresentation::GatherDeviceData(
+ policy_table::DeviceData* data) const {
+ LOG4CXX_INFO(logger_, "Gather device data.");
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kSelectDeviceData)) {
+ LOG4CXX_WARN(logger_, "Incorrect select statement for device data.");
+ return;
+ }
+ data->mark_initialized();
+ while (query.Next()) {
+ policy_table::DeviceParams* specific_device = &(*data)[query.GetString(0)];
+ *specific_device->hardware = query.GetString(1);
+ *specific_device->firmware_rev = query.GetString(2);
+ *specific_device->os = query.GetString(3);
+ *specific_device->os_version = query.GetString(4);
+ *specific_device->carrier = query.GetString(5);
+ *specific_device->max_number_rfcom_ports = query.GetInteger(6);
+
+ // TODO(IKozyrenko): Check logic if optional container is missing
+ GatherConsentGroup(query.GetString(0),
+ &(*specific_device->user_consent_records));
+ }
+}
+
+void SQLPTExtRepresentation::GatherConsentGroup(
+ const std::string& device_id,
+ policy_table::UserConsentRecords* records) const {
+ LOG4CXX_INFO(logger_, "Gather consent records.");
+ utils::dbms::SQLQuery query(db());
+ // Fill data for device
+ if (!query.Prepare(sql_pt_ext::kSelectDeviceConsentedGroup)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect select statement for device consented groups.");
+ return;
+ }
+
+ query.Bind(0, device_id);
+
+ // Fill device_data -> user_consent_records -> "device"
+ while (query.Next()) {
+ policy_table::ConsentRecords* device_consent_records =
+ &(*records)[kDeviceId];
+ // TODO(IKozyrenko): Check logic if optional container is missing
+ policy_table::ConsentGroups& consent_groups =
+ *device_consent_records->consent_groups;
+ consent_groups[query.GetString(1)] = query.GetBoolean(2);
+ policy_table::Input input;
+ policy_table::EnumFromJsonString(query.GetString(3), &input);
+ *device_consent_records->input = input;
+ *device_consent_records->time_stamp = query.GetString(4);
+ }
+
+ if (!query.Reset()) {
+ return;
+ }
+
+ // Fill data for applications
+ if (!query.Prepare(sql_pt_ext::kSelectConsentGroup)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect select statement for app consented groups.");
+ return;
+ }
+
+ query.Bind(0, device_id);
+
+ // Fill device_data -> user_consent_records -> <app_id>
+ while (query.Next()) {
+ policy_table::ConsentRecords* app_consent_records =
+ &(*records)[query.GetString(1)];
+ // TODO(IKozyrenko): Check logic if optional container is missing
+ policy_table::ConsentGroups& consent_groups =
+ *app_consent_records->consent_groups;
+
+ consent_groups[query.GetString(2)] = query.GetBoolean(3);
+ policy_table::Input input;
+ policy_table::EnumFromJsonString(query.GetString(4), &input);
+ *app_consent_records->input = input;
+ *app_consent_records->time_stamp = query.GetString(5);
+ }
+}
+
+bool SQLPTExtRepresentation::SaveDeviceData(
+ const policy_table::DeviceData& devices) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery drop_device_query(db());
+ const std::string drop_device = "DELETE FROM `device`";
+ if (!drop_device_query.Exec(drop_device)) {
+ LOG4CXX_WARN(logger_, "Could not clear device table.");
+ return false;
+ }
+
+ utils::dbms::SQLQuery drop_device_consents_query(db());
+ const std::string drop_device_consents = "DELETE FROM `device_consent_group`";
+ if (!drop_device_consents_query.Exec(drop_device_consents)) {
+ LOG4CXX_WARN(logger_, "Could not clear device consents.");
+ return false;
+ }
+
+ utils::dbms::SQLQuery drop_user_consents_query(db());
+ const std::string drop_user_consents = "DELETE FROM `consent_group`";
+ if (!drop_user_consents_query.Exec(drop_user_consents)) {
+ LOG4CXX_WARN(logger_, "Could not clear user consents.");
+ return false;
+ }
+
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kInsertDeviceData)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for device data.");
+ return false;
+ }
+
+ policy_table::DeviceData::const_iterator it = devices.begin();
+ policy_table::DeviceData::const_iterator it_end = devices.end();
+ for (; it != it_end; ++it) {
+ query.Bind(0, it->first);
+ query.Bind(1, *(it->second.hardware));
+ query.Bind(2, *(it->second.firmware_rev));
+ query.Bind(3, *(it->second.os));
+ query.Bind(4, *(it->second.os_version));
+ query.Bind(5, *(it->second.carrier));
+ query.Bind(6, *(it->second.max_number_rfcom_ports));
+ query.Bind(7, *(it->second.connection_type));
+
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into device data.");
+ return false;
+ }
+
+ // TODO(IKozyrenko): Check logic if optional container is missing
+ if (!SaveConsentGroup(it->first, *it->second.user_consent_records)) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::SaveConsentGroup(
+ const std::string& device_id,
+ const policy_table::UserConsentRecords& records) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+
+ policy_table::UserConsentRecords::const_iterator it = records.begin();
+ policy_table::UserConsentRecords::const_iterator it_end = records.end();
+ for (; it != it_end; ++it) {
+ // TODO(IKozyrenko): Check logic if optional container is missing
+ policy_table::ConsentGroups::const_iterator it_groups =
+ it->second.consent_groups->begin();
+ policy_table::ConsentGroups::const_iterator it_groups_end =
+ it->second.consent_groups->end();
+ for (; it_groups != it_groups_end; ++it_groups) {
+ if (kDeviceId == it->first) {
+ if (!query.Prepare(sql_pt_ext::kInsertDeviceConsentedGroup)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect insert statement for device consent group.");
+ return false;
+ }
+ query.Bind(0, device_id);
+ query.Bind(1, it_groups->first);
+ query.Bind(2, it_groups->second);
+ query.Bind(
+ 3,
+ std::string(policy_table::EnumToJsonString(*(it->second.input))));
+ query.Bind(4, std::string(*(it->second.time_stamp)));
+ LOG4CXX_INFO(logger_,
+ "Device:"
+ << "time stamp "
+ << std::string(*(it->second.time_stamp)) << " group "
+ << it_groups->first << " consent "
+ << it_groups->second);
+ } else {
+ if (!query.Prepare(sql_pt_ext::kInsertConsentGroups)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect insert statement for consent group.");
+ return false;
+ }
+ query.Bind(0, device_id);
+ query.Bind(1, it->first);
+ query.Bind(2, it_groups->first);
+ query.Bind(3, it_groups->second);
+ query.Bind(
+ 4,
+ std::string(policy_table::EnumToJsonString(*(it->second.input))));
+ query.Bind(5, std::string(*(it->second.time_stamp)));
+ LOG4CXX_INFO(logger_,
+ "Device:"
+ << "time stamp "
+ << std::string(*(it->second.time_stamp)) << " group "
+ << it_groups->first << " consent "
+ << it_groups->second);
+ }
+
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into consent group.");
+ return false;
+ }
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::SavePreconsentedGroup(
+ const std::string& app_id, const policy_table::Strings& groups) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kInsertPreconsentedGroups)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for preconsented groups");
+ return false;
+ }
+
+ policy_table::Strings::const_iterator it;
+ for (it = groups.begin(); it != groups.end(); ++it) {
+ query.Bind(0, app_id);
+ query.Bind(1, *it);
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into preconsented groups.");
+ return false;
+ }
+ }
+
+ return true;
+}
+
+void SQLPTExtRepresentation::GatherModuleMeta(
+ policy_table::ModuleMeta* meta) const {
+ LOG4CXX_INFO(logger_, "Gather Module Meta Info");
+ utils::dbms::SQLQuery query(db());
+ if (query.Prepare(sql_pt_ext::kSelectModuleMeta) && query.Next()) {
+ *meta->ccpu_version = query.GetString(0);
+ *meta->language = query.GetString(1);
+ *meta->wers_country_code = query.GetString(2);
+ *meta->pt_exchanged_at_odometer_x = query.GetInteger(3);
+ *meta->pt_exchanged_x_days_after_epoch = query.GetInteger(4);
+ *meta->ignition_cycles_since_last_exchange = query.GetInteger(5);
+ *meta->vin = query.GetString(6);
+ }
+}
+
+void SQLPTExtRepresentation::Increment(const std::string& type) const {
+ utils::dbms::SQLQuery query(db());
+ std::string update_counter =
+ "UPDATE `usage_and_error_count` SET `" + type + "` = `" + type + "` + 1";
+ if (!query.Exec(update_counter)) {
+ LOG4CXX_INFO(logger_, "Failed updating global counter");
+ }
+}
+
+bool SQLPTExtRepresentation::IsExistAppLevel(const std::string& app_id) const {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kCountAppLevel)) {
+ LOG4CXX_INFO(logger_, "Incorrect statement of count app_level");
+ return false;
+ }
+ query.Bind(0, app_id);
+ if (!query.Exec()) {
+ LOG4CXX_INFO(logger_, "Failed count app_level");
+ return false;
+ }
+ return query.GetInteger(0) > 0;
+}
+
+bool SQLPTExtRepresentation::GetAllAppGroups(const std::string& policy_app_id,
+ FunctionalGroupIDs& all_groups) {
+ LOG4CXX_INFO(logger_, "GetAllAppGroups for '" << policy_app_id << "'");
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kSelectAppGroupsId)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement for select app groups id.");
+ return false;
+ }
+
+ query.Bind(0, policy_app_id);
+
+ while (query.Next()) {
+ all_groups.push_back(query.GetInteger(0));
+ }
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::GetConsentedGroups(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ FunctionalGroupIDs& allowed_groups,
+ FunctionalGroupIDs& disallowed_groups) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kSelectConsentedGroupsId)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement for select consent groups id.");
+ return false;
+ }
+
+ query.Bind(0, policy_app_id);
+ query.Bind(1, device_id);
+
+ while (query.Next()) {
+ if (query.GetBoolean(1)) {
+ allowed_groups.push_back(query.GetInteger(0));
+ } else {
+ disallowed_groups.push_back(query.GetInteger(0));
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::GetPreconsentedGroups(
+ const std::string& policy_app_id, FunctionalGroupIDs& preconsented_groups) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kSelectPreconsentedGroupsId)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect statement for select preconsented groups id.");
+ return false;
+ }
+
+ query.Bind(0, policy_app_id);
+
+ while (query.Next()) {
+ preconsented_groups.push_back(query.GetInteger(0));
+ }
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::GetFunctionalGroupNames(
+ FunctionalGroupNames& names) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kSelectFunctionalGroupNames)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect statement for select functional groups names.");
+ return false;
+ }
+
+ while (query.Next()) {
+ // Some of functional grous doesn't have filled user_consent_prompt
+ if (query.IsNull(1)) {
+ names[query.GetInteger(0)] =
+ std::make_pair<std::string, std::string>("", query.GetString(2));
+ } else {
+ names[query.GetInteger(0)] = std::make_pair<std::string, std::string>(
+ query.GetString(1), query.GetString(2));
+ }
+ }
+
+ return true;
+}
+
+void SQLPTExtRepresentation::FillFunctionalGroupPermissions(
+ FunctionalGroupIDs& ids,
+ FunctionalGroupNames& names,
+ GroupConsent state,
+ std::vector<FunctionalGroupPermission>& permissions) {
+ FunctionalGroupIDs::const_iterator it = ids.begin();
+ FunctionalGroupIDs::const_iterator it_end = ids.end();
+ for (; it != it_end; ++it) {
+ FunctionalGroupPermission current_group;
+ current_group.group_id = *it;
+ current_group.group_alias = names[*it].first;
+ current_group.group_name = names[*it].second;
+ current_group.state = state;
+ permissions.push_back(current_group);
+ }
+}
+
+void SQLPTExtRepresentation::Increment(const std::string& app_id,
+ const std::string& type) const {
+ utils::dbms::SQLQuery query(db());
+ std::string sql_counter;
+ if (IsExistAppLevel(app_id)) {
+ // update
+ sql_counter = "UPDATE `app_level` SET `" + type + "` = `" + type +
+ "` + 1 WHERE `application_id` = ?";
+ } else {
+ // insert
+ sql_counter = "INSERT INTO `app_level` (`application_id`, `" + type +
+ "`) "
+ "VALUES (?, 1)";
+ }
+ if (!query.Prepare(sql_counter)) {
+ LOG4CXX_INFO(logger_, "Incorrect statement of update app counter");
+ return;
+ }
+ query.Bind(0, app_id);
+ if (!query.Exec()) {
+ LOG4CXX_INFO(logger_, "Failed updating app counter");
+ }
+}
+
+void SQLPTExtRepresentation::Set(const std::string& app_id,
+ const std::string& type,
+ const std::string& value) const {
+ utils::dbms::SQLQuery query(db());
+ std::string sql_info;
+ if (IsExistAppLevel(app_id)) {
+ // update
+ sql_info = "UPDATE `app_level` SET `" + type +
+ "` = ? "
+ "WHERE `application_id` = ?";
+ } else {
+ // insert
+ sql_info = "INSERT INTO `app_level` (`" + type +
+ "`, `application_id`) "
+ "VALUES (?, ?)";
+ }
+ if (!query.Prepare(sql_info)) {
+ LOG4CXX_INFO(logger_, "Incorrect statement of update app info");
+ return;
+ }
+ query.Bind(0, value);
+ query.Bind(1, app_id);
+ if (!query.Exec()) {
+ LOG4CXX_INFO(logger_, "Failed updating app info");
+ }
+}
+
+void SQLPTExtRepresentation::Add(const std::string& app_id,
+ const std::string& type,
+ int seconds) const {
+ utils::dbms::SQLQuery query(db());
+ std::string sql_stopwatch;
+ if (IsExistAppLevel(app_id)) {
+ // update
+ sql_stopwatch = "UPDATE `app_level` SET `" + type + "` = `" + type +
+ "` + ? WHERE `application_id` = ?";
+ } else {
+ // insert
+ sql_stopwatch = "INSERT INTO `app_level` (`" + type +
+ "`, `application_id`) "
+ "VALUES (?, ?)";
+ }
+ if (!query.Prepare(sql_stopwatch)) {
+ LOG4CXX_INFO(logger_, "Incorrect statement of update app stopwatch");
+ return;
+ }
+ query.Bind(0, seconds);
+ query.Bind(1, app_id);
+ if (!query.Exec()) {
+ LOG4CXX_INFO(logger_, "Failed updating app stopwatch");
+ }
+}
+
+bool SQLPTExtRepresentation::GetDefaultHMI(const std::string& policy_app_id,
+ std::string* default_hmi) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kSelectDefaultHmi)) {
+ LOG4CXX_INFO(logger_, "Incorrect statement for default hmi.");
+ return false;
+ }
+
+ query.Bind(0, policy_app_id);
+
+ if (!query.Exec()) {
+ LOG4CXX_INFO(logger_, "Error during default hmi getting.");
+ return false;
+ }
+
+ if (query.IsNull(0)) {
+ default_hmi->clear();
+ return true;
+ }
+
+ default_hmi->assign(query.GetString(0));
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::CountUnconsentedGroups(
+ const std::string& policy_app_id,
+ const std::string& device_id,
+ int* result) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kCountUnconsentedGroups)) {
+ LOG4CXX_WARN(logger_, "Incorrect select for unconsented groups.");
+ return false;
+ }
+
+ query.Bind(0, policy_app_id);
+ query.Bind(1, device_id);
+ query.Bind(2, kDefaultId);
+ query.Bind(3, kPreDataConsentId);
+
+ if (!query.Exec()) {
+ LOG4CXX_INFO(logger_, "Error during executing unconsented groups.");
+ return false;
+ }
+ *result = query.GetInteger(0);
+ return true;
+}
+
+bool SQLPTExtRepresentation::IsMsgLanguagePresent(const std::string& message,
+ const std::string& language) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kHasMsgLanguageCode)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement for message language check.");
+ return false;
+ }
+
+ query.Bind(0, message);
+ query.Bind(1, language);
+
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed to check message language code.");
+ return false;
+ }
+
+ return query.GetInteger(0) != 0;
+}
+
+bool SQLPTExtRepresentation::SaveMessageString(
+ const std::string& type,
+ const std::string& lang,
+ const policy_table::MessageString& strings) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kInsertMessageString)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for message.");
+ return false;
+ }
+
+ query.Bind(0, *strings.tts);
+ query.Bind(1, *strings.label);
+ query.Bind(2, *strings.line1);
+ query.Bind(3, *strings.line2);
+ query.Bind(4, lang);
+ query.Bind(5, type);
+ query.Bind(6, *strings.textBody);
+
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into message.");
+ return false;
+ }
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::SaveUsageAndErrorCounts(
+ const policy_table::UsageAndErrorCounts& counts) {
+ return SaveAppCounters(*counts.app_level) && SaveGlobalCounters(counts);
+}
+
+bool SQLPTExtRepresentation::SaveModuleMeta(
+ const policy_table::ModuleMeta& meta) {
+ utils::dbms::SQLQuery query(db());
+
+ if (!query.Prepare(sql_pt_ext::kSaveModuleMeta)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for module_meta.");
+ return false;
+ }
+ const int64_t odometer = *(meta.pt_exchanged_at_odometer_x);
+
+ query.Bind(0, *(meta.ccpu_version));
+ query.Bind(1, *(meta.language));
+ query.Bind(2, *(meta.wers_country_code));
+ query.Bind(3, odometer);
+ query.Bind(4, *(meta.pt_exchanged_x_days_after_epoch));
+ query.Bind(5, *(meta.ignition_cycles_since_last_exchange));
+ query.Bind(6, *(meta.vin));
+
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect update for module_meta.");
+ return false;
+ }
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::SaveAppCounters(
+ const rpc::policy_table_interface_base::AppLevels& app_levels) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Exec(sql_pt::kDeleteAppLevel)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from app level.");
+ return false;
+ }
+ if (!query.Prepare(sql_pt::kInsertAppLevel)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for app level.");
+ return false;
+ }
+
+ policy_table::AppLevels::const_iterator it;
+ for (it = app_levels.begin(); it != app_levels.end(); ++it) {
+ query.Bind(0, it->first);
+ query.Bind(1, it->second.minutes_in_hmi_full);
+ query.Bind(2, it->second.minutes_in_hmi_limited);
+ query.Bind(3, it->second.minutes_in_hmi_background);
+ query.Bind(4, it->second.minutes_in_hmi_none);
+ query.Bind(5, it->second.count_of_user_selections);
+ query.Bind(6, it->second.count_of_rejections_sync_out_of_memory);
+ query.Bind(7, it->second.count_of_rejections_nickname_mismatch);
+ query.Bind(8, it->second.count_of_rejections_duplicate_name);
+ query.Bind(9, it->second.count_of_rejected_rpc_calls);
+ query.Bind(10, it->second.count_of_rpcs_sent_in_hmi_none);
+ query.Bind(11, it->second.count_of_removals_for_bad_behavior);
+ query.Bind(12, it->second.count_of_run_attempts_while_revoked);
+ query.Bind(13, it->second.app_registration_language_gui);
+ query.Bind(14, it->second.app_registration_language_vui);
+ query.Bind(15, it->second.count_of_tls_errors);
+
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into app level.");
+ return false;
+ }
+ }
+ return true;
+}
+
+bool SQLPTExtRepresentation::SaveGlobalCounters(
+ const rpc::policy_table_interface_base::UsageAndErrorCounts& counts) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kUpdateGlobalCounters)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for global counters.");
+ return false;
+ }
+
+ query.Bind(0, *counts.count_of_iap_buffer_full);
+ query.Bind(1, *counts.count_sync_out_of_memory);
+ query.Bind(2, *counts.count_of_sync_reboots);
+
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into global counters.");
+ return false;
+ }
+
+ return true;
+}
+
+bool SQLPTExtRepresentation::CleanupUnpairedDevices(
+ const DeviceIds& device_ids) const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery delete_device_query(db());
+ if (!delete_device_query.Prepare(sql_pt::kDeleteDevice)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement for device delete.");
+ return true;
+ }
+
+ utils::dbms::SQLQuery delete_device_consent_query(db());
+ if (!delete_device_consent_query.Prepare(sql_pt_ext::kDeleteDeviceConsent)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement for delete device consent.");
+ return false;
+ }
+
+ utils::dbms::SQLQuery delete_app_consent_query(db());
+ if (!delete_app_consent_query.Prepare(sql_pt_ext::kDeleteAppConsent)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement for delete app consent.");
+ return false;
+ }
+
+ DeviceIds::const_iterator it = device_ids.begin();
+ DeviceIds::const_iterator it_end = device_ids.end();
+ for (; it != it_end; ++it) {
+ delete_device_query.Bind(0, (*it));
+ if (!delete_device_query.Exec() || !delete_device_query.Reset()) {
+ LOG4CXX_WARN(logger_, "Failed to delete from device");
+ return false;
+ }
+
+ delete_device_consent_query.Bind(0, (*it));
+ if (!delete_device_consent_query.Exec() ||
+ !delete_device_consent_query.Reset()) {
+ LOG4CXX_WARN(logger_, "Failed to delete from device consent.");
+ return false;
+ }
+
+ delete_app_consent_query.Bind(0, (*it));
+ if (!delete_app_consent_query.Exec() || !delete_app_consent_query.Reset()) {
+ LOG4CXX_WARN(logger_, "Failed to delete from app consent.");
+ return false;
+ }
+ }
+ return true;
+}
+
+bool SQLPTExtRepresentation::SetDefaultPolicy(const std::string& app_id) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kDeleteAppGroupByApplicationId)) {
+ LOG4CXX_ERROR(logger_, "Incorrect statement to delete from app_group.");
+ return false;
+ }
+ query.Bind(0, app_id);
+ if (!query.Exec()) {
+ LOG4CXX_ERROR(logger_, "Failed deleting from app_group.");
+ return false;
+ }
+
+ if (!query.Prepare(sql_pt_ext::kDeletePreconsentedGroupsByApplicationId)) {
+ LOG4CXX_ERROR(logger_, "Incorrect statement to delete from app_group.");
+ return false;
+ }
+ query.Bind(0, app_id);
+ if (!query.Exec()) {
+ LOG4CXX_ERROR(logger_, "Failed deleting from app_group.");
+ return false;
+ }
+
+ if (!CopyApplication(kDefaultId, app_id)) {
+ return false;
+ }
+
+ SetPreloaded(false);
+
+ policy_table::Strings default_groups;
+ policy_table::Strings default_preconsented_groups;
+ GatherAppGroup(kDefaultId, &default_groups);
+ GatherPreconsentedGroup(kDefaultId, &default_preconsented_groups);
+ if (SaveAppGroup(app_id, default_groups) &&
+ SavePreconsentedGroup(app_id, default_preconsented_groups)) {
+ return SetIsDefault(app_id, true) && SetIsPredata(app_id, false);
+ }
+
+ return false;
+}
+
+bool SQLPTExtRepresentation::SetPredataPolicy(const std::string& app_id) {
+ LOG4CXX_INFO(logger_,
+ "SQLPTExtRepresentation::SetPredataPolicy for " << app_id);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kDeleteAppGroupByApplicationId)) {
+ LOG4CXX_ERROR(logger_, "Incorrect statement to delete from app_group.");
+ return false;
+ }
+ query.Bind(0, app_id);
+ if (!query.Exec()) {
+ LOG4CXX_ERROR(logger_, "Failed deleting from app_group.");
+ return false;
+ }
+
+ if (!query.Prepare(sql_pt_ext::kDeletePreconsentedGroupsByApplicationId)) {
+ LOG4CXX_ERROR(logger_, "Incorrect statement to delete from app_group.");
+ return false;
+ }
+ query.Bind(0, app_id);
+ if (!query.Exec()) {
+ LOG4CXX_ERROR(logger_, "Failed deleting from app_group.");
+ return false;
+ }
+
+ if (!CopyApplication(kPreDataConsentId, app_id)) {
+ return false;
+ }
+
+ SetPreloaded(false);
+
+ policy_table::Strings predataconsent_groups;
+ policy_table::Strings predataconsent_preconsented_groups;
+ GatherAppGroup(kPreDataConsentId, &predataconsent_groups);
+ GatherPreconsentedGroup(kPreDataConsentId, &predataconsent_groups);
+ if (SaveAppGroup(app_id, predataconsent_groups) &&
+ SavePreconsentedGroup(app_id, predataconsent_groups)) {
+ return SetIsDefault(app_id, false) && SetIsPredata(app_id, true);
+ }
+ return false;
+}
+
+bool SQLPTExtRepresentation::IsPredataPolicy(const std::string& app_id) const {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kSelectApplicationIsPreData)) {
+ LOG4CXX_WARN(logger_, "Incorrect select application is pre_dataConsented");
+ return false;
+ }
+
+ query.Bind(0, app_id);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed select application is pre_dataConsented");
+ return false;
+ }
+ return query.IsNull(0) ? false : query.GetBoolean(0);
+}
+
+bool SQLPTExtRepresentation::SetIsPredata(const std::string& app_id,
+ bool is_pre_data) {
+ LOG4CXX_TRACE(logger_, "Set flag is_predata of application");
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kUpdateIsPredata)) {
+ LOG4CXX_WARN(logger_, "Incorect statement for updating is_predata");
+ return false;
+ }
+
+ query.Bind(0, is_pre_data);
+ query.Bind(1, app_id);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed update is_predata");
+ return false;
+ }
+ return true;
+}
+
+bool SQLPTExtRepresentation::SetUnpairedDevice(const std::string& device_id,
+ bool unpaired) const {
+ LOG4CXX_TRACE(logger_, "Set unpaired device: " << device_id);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kUpdateUnpairedDevice)) {
+ LOG4CXX_WARN(logger_, "Incorect statement for updating unpaired device");
+ return false;
+ }
+
+ query.Bind(0, unpaired);
+ query.Bind(1, device_id);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed update unpaired device");
+ return false;
+ }
+ return true;
+}
+
+bool SQLPTExtRepresentation::UnpairedDevicesList(DeviceIds* device_ids) const {
+ LOG4CXX_TRACE(logger_, "Get list of unpaired devices");
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kSelectUnpairedDevices)) {
+ LOG4CXX_WARN(logger_, "Incorect statement for selecting unpaired devices");
+ return false;
+ }
+
+ while (query.Next()) {
+ device_ids->push_back(query.GetString(0));
+ }
+ return true;
+}
+
+bool SQLPTExtRepresentation::SetVINValue(const std::string& value) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kUpdateModuleMetaVinParam)) {
+ LOG4CXX_WARN(logger_, "Incorect statement for updating module_meta params");
+ return false;
+ }
+
+ query.Bind(0, value);
+ const bool result = query.Exec();
+
+ if (!result) {
+ LOG4CXX_WARN(logger_, "Failed update module_meta");
+ }
+ return result;
+}
+
+bool SQLPTExtRepresentation::RemoveAppConsentForGroup(
+ const std::string& policy_app_id,
+ const std::string& functional_group_name) const {
+ utils::dbms::SQLQuery query_group_id(db());
+ if (!query_group_id.Prepare(sql_pt_ext::kSelectGroupId)) {
+ LOG4CXX_WARN(logger_, "Incorect statement for select group name.");
+ return false;
+ }
+
+ query_group_id.Bind(0, functional_group_name);
+
+ if (!query_group_id.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed to select group id.");
+ return false;
+ }
+
+ const int id = query_group_id.GetInteger(0);
+
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt_ext::kDeleteAppGroupConsent)) {
+ LOG4CXX_WARN(logger_, "Incorect statement for remove app consent.");
+ return false;
+ }
+
+ query.Bind(0, policy_app_id);
+ query.Bind(1, id);
+
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed to remove app consent.");
+ return false;
+ }
+
+ return true;
+}
+
+} // namespace policy
diff --git a/src/components/policy/src/sql_pt_queries.cc b/src/components/policy/src/sql_pt_queries.cc
new file mode 100644
index 0000000000..df4bc74cc2
--- /dev/null
+++ b/src/components/policy/src/sql_pt_queries.cc
@@ -0,0 +1,712 @@
+/*
+ Copyright (c) 2015, " Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, " with or without
+ modification, " are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, " this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice, "
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, " INCLUDING, " BUT NOT LIMITED TO, " THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, " INDIRECT, " INCIDENTAL, " SPECIAL, " EXEMPLARY, " OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, " BUT NOT LIMITED TO, " PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, " DATA, " OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, " WHETHER IN
+ CONTRACT, " STRICT LIABILITY, " OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, " EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "policy/sql_pt_queries.h"
+
+namespace policy {
+namespace sql_pt {
+
+const std::string kSelectPriority =
+ "SELECT `priority_value` FROM `application` WHERE `id` = ? LIMIT 1";
+const std::string kCreateSchema =
+ "BEGIN; "
+ "CREATE TABLE IF NOT EXISTS `device`( "
+ " `id` VARCHAR(100) PRIMARY KEY NOT NULL, "
+ " `hardware` VARCHAR(45), "
+ " `firmware_rev` VARCHAR(45), "
+ " `os` VARCHAR(45), "
+ " `os_version` VARCHAR(45), "
+ " `carrier` VARCHAR(45), "
+ " `max_number_rfcom_ports` INTEGER,"
+ " `connection_type` VARCHAR(45), "
+ " `unpaired` BOOL "
+ "); "
+ "CREATE TABLE IF NOT EXISTS `usage_and_error_count`( "
+ " `count_of_iap_buffer_full` INTEGER, "
+ " `count_sync_out_of_memory` INTEGER, "
+ " `count_of_sync_reboots` INTEGER "
+ "); "
+ "CREATE TABLE IF NOT EXISTS `module_meta`( "
+ " `pt_exchanged_at_odometer_x` INTEGER NOT NULL DEFAULT 0, "
+ " `pt_exchanged_x_days_after_epoch` INTEGER NOT NULL DEFAULT 0, "
+ " `ignition_cycles_since_last_exchange` INTEGER NOT NULL DEFAULT 0, "
+ " `flag_update_required` BOOL NOT NULL "
+ "); "
+ "CREATE TABLE IF NOT EXISTS `module_config`( "
+ " `preloaded_pt` BOOL NOT NULL, "
+ " `is_first_run` BOOL NOT NULL, "
+ " `exchange_after_x_ignition_cycles` INTEGER NOT NULL, "
+ " `exchange_after_x_kilometers` INTEGER NOT NULL, "
+ " `exchange_after_x_days` INTEGER NOT NULL, "
+ " `timeout_after_x_seconds` INTEGER NOT NULL, "
+ " `certificate` TEXT, "
+ " `vehicle_make` VARCHAR(45), "
+ " `vehicle_model` VARCHAR(45), "
+ " `vehicle_year` VARCHAR(4) "
+ "); "
+ "CREATE TABLE IF NOT EXISTS `functional_group`( "
+ " `id` INTEGER PRIMARY KEY NOT NULL, "
+ " `user_consent_prompt` TEXT, "
+ " `name` VARCHAR(100) NOT NULL "
+ "); "
+ "CREATE TABLE IF NOT EXISTS `priority`( "
+ " `value` VARCHAR(45) PRIMARY KEY NOT NULL "
+ "); "
+ "CREATE TABLE IF NOT EXISTS `hmi_level`( "
+ " `value` VARCHAR(45) PRIMARY KEY NOT NULL "
+ "); "
+ "CREATE TABLE IF NOT EXISTS `notifications_by_priority`( "
+ " `priority_value` VARCHAR(45) PRIMARY KEY NOT NULL, "
+ " `value` INTEGER NOT NULL, "
+ " CONSTRAINT `fk_notifications_by_priority_priority1` "
+ " FOREIGN KEY(`priority_value`) "
+ " REFERENCES `priority`(`value`) "
+ "); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`notifications_by_priority.fk_notifications_by_priority_priority1_idx` "
+ " ON `notifications_by_priority`(`priority_value`); "
+ "CREATE TABLE IF NOT EXISTS `language`( "
+ " `code` VARCHAR(25) PRIMARY KEY NOT NULL "
+ "); "
+ "CREATE TABLE IF NOT EXISTS `message_type`( "
+ " `name` VARCHAR(45) PRIMARY KEY NOT NULL "
+ "); "
+ "CREATE TABLE IF NOT EXISTS `version`( "
+ " `number` VARCHAR(45) NOT NULL "
+ "); "
+ "CREATE TABLE IF NOT EXISTS `rpc`( "
+ " `id` INTEGER PRIMARY KEY NOT NULL, "
+ " `name` VARCHAR(45) NOT NULL, "
+ " `parameter` VARCHAR(45), "
+ " `hmi_level_value` VARCHAR(45) NOT NULL, "
+ " `functional_group_id` INTEGER NOT NULL, "
+ " CONSTRAINT `fk_rpc_hmi_level1` "
+ " FOREIGN KEY(`hmi_level_value`) "
+ " REFERENCES `hmi_level`(`value`), "
+ " CONSTRAINT `fk_rpc_functional_group1` "
+ " FOREIGN KEY(`functional_group_id`) "
+ " REFERENCES `functional_group`(`id`) "
+ "); "
+ "CREATE INDEX IF NOT EXISTS `rpc.fk_rpc_hmi_level1_idx` "
+ " ON `rpc`(`hmi_level_value`); "
+ "CREATE INDEX IF NOT EXISTS `rpc.fk_rpc_functional_group1_idx` "
+ " ON `rpc`(`functional_group_id`); "
+ "CREATE INDEX `rpc.select_rpc_name_hmi_level` "
+ " ON `rpc`(`name`,`hmi_level_value`);"
+ "CREATE TABLE IF NOT EXISTS `application`( "
+ " `id` VARCHAR(45) PRIMARY KEY NOT NULL, "
+ " `keep_context` BOOLEAN, "
+ " `steal_focus` BOOLEAN, "
+ " `default_hmi` VARCHAR(45), "
+ " `priority_value` VARCHAR(45), "
+ " `is_revoked` BOOLEAN, "
+ " `is_default` BOOLEAN, "
+ " `is_predata` BOOLEAN, "
+ " `memory_kb` INTEGER NOT NULL, "
+ " `heart_beat_timeout_ms` INTEGER NOT NULL, "
+ " `certificate` VARCHAR(45), "
+ " CONSTRAINT `fk_application_hmi_level1` "
+ " FOREIGN KEY(`default_hmi`) "
+ " REFERENCES `hmi_level`(`value`), "
+ " CONSTRAINT `fk_application_priorities1` "
+ " FOREIGN KEY(`priority_value`) "
+ " REFERENCES `priority`(`value`) "
+ "); "
+ "CREATE INDEX IF NOT EXISTS `application.fk_application_hmi_level1_idx` "
+ " ON `application`(`default_hmi`); "
+ "CREATE INDEX IF NOT EXISTS `application.fk_application_priorities1_idx` "
+ " ON `application`(`priority_value`); "
+ "CREATE TABLE IF NOT EXISTS `app_group`( "
+ " `application_id` VARCHAR(45) NOT NULL, "
+ " `functional_group_id` INTEGER NOT NULL, "
+ " PRIMARY KEY(`application_id`,`functional_group_id`), "
+ " CONSTRAINT `fk_application_has_functional_group_application1` "
+ " FOREIGN KEY(`application_id`) "
+ " REFERENCES `application`(`id`), "
+ " CONSTRAINT `fk_application_has_functional_group_functional_group1` "
+ " FOREIGN KEY(`functional_group_id`) "
+ " REFERENCES `functional_group`(`id`) "
+ "); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`app_group.fk_application_has_functional_group_functional_group1_idx` "
+ " ON `app_group`(`functional_group_id`); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`app_group.fk_application_has_functional_group_application1_idx` "
+ " ON `app_group`(`application_id`); "
+ "CREATE TABLE IF NOT EXISTS `preconsented_group`( "
+ " `application_id` VARCHAR(45) NOT NULL, "
+ " `functional_group_id` INTEGER NOT NULL, "
+ " PRIMARY KEY(`application_id`,`functional_group_id`), "
+ " CONSTRAINT `fk_application_has_functional_group_application2` "
+ " FOREIGN KEY(`application_id`) "
+ " REFERENCES `application`(`id`), "
+ " CONSTRAINT `fk_application_has_functional_group_functional_group2` "
+ " FOREIGN KEY(`functional_group_id`) "
+ " REFERENCES `functional_group`(`id`) "
+ "); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`preconsented_group.fk_application_has_functional_group_functional_group2_"
+ "idx` "
+ " ON `preconsented_group`(`functional_group_id`); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`preconsented_group.fk_application_has_functional_group_application2_idx` "
+ " ON `preconsented_group`(`application_id`); "
+ "CREATE TABLE IF NOT EXISTS `seconds_between_retry`( "
+ " `index` INTEGER PRIMARY KEY NOT NULL, "
+ " `value` INTEGER NOT NULL "
+ "); "
+ "CREATE TABLE IF NOT EXISTS `device_consent_group`( "
+ " `device_id` VARCHAR(100) NOT NULL, "
+ " `functional_group_id` INTEGER NOT NULL, "
+ " `is_consented` BOOL NOT NULL, "
+ " `input` VARCHAR(45), "
+ " `time_stamp` VARCHAR(45), "
+ " PRIMARY KEY(`device_id`,`functional_group_id`), "
+ " CONSTRAINT `fk_device_has_functional_group_device1` "
+ " FOREIGN KEY(`device_id`) "
+ " REFERENCES `device`(`id`), "
+ " CONSTRAINT `fk_device_has_functional_group_functional_group1` "
+ " FOREIGN KEY(`functional_group_id`) "
+ " REFERENCES `functional_group`(`id`) "
+ "); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`device_consent_group.fk_device_has_functional_group_functional_group1_"
+ "idx` "
+ " ON `device_consent_group`(`functional_group_id`); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`device_consent_group.fk_device_has_functional_group_device1_idx` "
+ " ON `device_consent_group`(`device_id`); "
+ "CREATE TABLE IF NOT EXISTS `app_level`( "
+ " `application_id` VARCHAR(45) PRIMARY KEY NOT NULL, "
+ " `minutes_in_hmi_full` INTEGER DEFAULT 0, "
+ " `minutes_in_hmi_limited` INTEGER DEFAULT 0, "
+ " `minutes_in_hmi_background` INTEGER DEFAULT 0, "
+ " `minutes_in_hmi_none` INTEGER DEFAULT 0, "
+ " `count_of_user_selections` INTEGER DEFAULT 0, "
+ " `count_of_rejections_sync_out_of_memory` INTEGER DEFAULT 0, "
+ " `count_of_rejections_nickname_mismatch` INTEGER DEFAULT 0, "
+ " `count_of_rejections_duplicate_name` INTEGER DEFAULT 0, "
+ " `count_of_rejected_rpcs_calls` INTEGER DEFAULT 0, "
+ " `count_of_rpcs_sent_in_hmi_none` INTEGER DEFAULT 0, "
+ " `count_of_removals_for_bad_behavior` INTEGER DEFAULT 0, "
+ " `count_of_run_attempts_while_revoked` INTEGER DEFAULT 0, "
+ " `count_of_tls_errors` INTEGER DEFAULT 0, "
+ " `app_registration_language_gui` VARCHAR(25), "
+ " `app_registration_language_vui` VARCHAR(25), "
+ " CONSTRAINT `fk_app_levels_application1` "
+ " FOREIGN KEY(`application_id`) "
+ " REFERENCES `application`(`id`), "
+ " CONSTRAINT `fk_app_level_language1` "
+ " FOREIGN KEY(`app_registration_language_gui`) "
+ " REFERENCES `language`(`code`), "
+ " CONSTRAINT `fk_app_level_language2` "
+ " FOREIGN KEY(`app_registration_language_vui`) "
+ " REFERENCES `language`(`code`) "
+ "); "
+ "CREATE INDEX IF NOT EXISTS `app_level.fk_app_levels_application1_idx` "
+ " ON `app_level`(`application_id`); "
+ "CREATE INDEX IF NOT EXISTS `app_level.fk_app_level_language1_idx` "
+ " ON `app_level`(`app_registration_language_gui`); "
+ "CREATE INDEX IF NOT EXISTS `app_level.fk_app_level_language2_idx` "
+ " ON `app_level`(`app_registration_language_vui`); "
+ "CREATE TABLE IF NOT EXISTS `nickname`( "
+ " `name` VARCHAR(100) NOT NULL, "
+ " `application_id` VARCHAR(45) NOT NULL, "
+ " PRIMARY KEY(`name`,`application_id`), "
+ " CONSTRAINT `fk_nickname_application1` "
+ " FOREIGN KEY(`application_id`) "
+ " REFERENCES `application`(`id`) "
+ "); "
+ "CREATE INDEX IF NOT EXISTS `nickname.fk_nickname_application1_idx` "
+ " ON `nickname`(`application_id`); "
+ "CREATE TABLE IF NOT EXISTS `app_type`( "
+ " `name` VARCHAR(50) NOT NULL, "
+ " `application_id` VARCHAR(45) NOT NULL, "
+ " PRIMARY KEY(`name`,`application_id`), "
+ " CONSTRAINT `fk_app_type_application1` "
+ " FOREIGN KEY(`application_id`) "
+ " REFERENCES `application`(`id`) "
+ "); "
+ "CREATE TABLE IF NOT EXISTS `request_type`( "
+ " `request_type` VARCHAR(50) NOT NULL, "
+ " `application_id` VARCHAR(45) NOT NULL, "
+ " PRIMARY KEY(`request_type`,`application_id`), "
+ " CONSTRAINT `fk_app_type_application1` "
+ " FOREIGN KEY(`application_id`) "
+ " REFERENCES `application`(`id`) "
+ "); "
+ "CREATE INDEX IF NOT EXISTS `app_type.fk_app_type_application1_idx` "
+ " ON `app_type`(`application_id`); "
+ "CREATE TABLE IF NOT EXISTS `consent_group`( "
+ " `device_id` VARCHAR(100) NOT NULL, "
+ " `application_id` VARCHAR(45) NOT NULL, "
+ " `functional_group_id` INTEGER NOT NULL, "
+ " `is_consented` BOOL NOT NULL, "
+ " `input` VARCHAR(45), "
+ " `time_stamp` VARCHAR(45), "
+ " PRIMARY KEY(`application_id`,`functional_group_id`,`device_id`), "
+ " CONSTRAINT `fk_consent_group_device1` "
+ " FOREIGN KEY(`device_id`) "
+ " REFERENCES `device`(`id`), "
+ " CONSTRAINT `fk_consent_group_application1` "
+ " FOREIGN KEY(`application_id`) "
+ " REFERENCES `application`(`id`), "
+ " CONSTRAINT `fk_consent_group_functional_group1` "
+ " FOREIGN KEY(`functional_group_id`) "
+ " REFERENCES `functional_group`(`id`) "
+ "); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`consent_group.fk_consent_group_device1_idx` "
+ " ON `device_consent_group`(`device_id`); "
+ "CREATE INDEX IF NOT EXISTS "
+ "`consent_group.fk_consent_group_functional_group1_idx` "
+ " ON `consent_group`(`functional_group_id`); "
+ "CREATE TABLE IF NOT EXISTS `endpoint`( "
+ " `service` VARCHAR(100) NOT NULL, "
+ " `url` VARCHAR(100) NOT NULL, "
+ " `application_id` VARCHAR(45) NOT NULL, "
+ " CONSTRAINT `fk_endpoint_application1` "
+ " FOREIGN KEY(`application_id`) "
+ " REFERENCES `application`(`id`) "
+ "); "
+ "CREATE INDEX IF NOT EXISTS `endpoint.fk_endpoint_application1_idx` "
+ " ON `endpoint`(`application_id`); "
+ "CREATE TABLE IF NOT EXISTS `message`( "
+ " `id` INTEGER PRIMARY KEY NOT NULL, "
+ " `tts` TEXT, "
+ " `label` TEXT, "
+ " `line1` TEXT, "
+ " `line2` TEXT, "
+ " `textBody` TEXT, "
+ " `language_code` VARCHAR(25) NOT NULL, "
+ " `message_type_name` VARCHAR(45) NOT NULL, "
+ " CONSTRAINT `fk_messages_languages1` "
+ " FOREIGN KEY(`language_code`) "
+ " REFERENCES `language`(`code`), "
+ " CONSTRAINT `fk_message_consumer_friendly_messages1` "
+ " FOREIGN KEY(`message_type_name`) "
+ " REFERENCES `message_type`(`name`) "
+ "); "
+ "CREATE INDEX IF NOT EXISTS `message.fk_messages_languages1_idx` "
+ " ON `message`(`language_code`);"
+ "CREATE INDEX IF NOT EXISTS "
+ "`message.fk_message_consumer_friendly_messages1_idx` "
+ " ON `message`(`message_type_name`);"
+ "CREATE TABLE IF NOT EXISTS `_internal_data`( "
+ " `db_version_hash` INTEGER "
+ " ); "
+ "COMMIT;";
+
+const std::string kInsertInitData =
+ "INSERT OR IGNORE INTO `usage_and_error_count` ( "
+ " `count_of_iap_buffer_full`, `count_sync_out_of_memory`, "
+ " `count_of_sync_reboots`) VALUES (0, 0, 0); "
+ "INSERT OR IGNORE INTO `module_meta` (`pt_exchanged_at_odometer_x`, "
+ " `pt_exchanged_x_days_after_epoch`, "
+ "`ignition_cycles_since_last_exchange`,"
+ " `flag_update_required`) "
+ " VALUES (0, 0, 0, 0); "
+ "INSERT OR IGNORE INTO `module_config` (`preloaded_pt`, `is_first_run`,"
+ " `exchange_after_x_ignition_cycles`, `exchange_after_x_kilometers`, "
+ " `exchange_after_x_days`, `timeout_after_x_seconds`) "
+ " VALUES(1, 0, 0, 0, 0, 0); "
+ "INSERT OR IGNORE INTO `priority`(`value`) VALUES ('EMERGENCY'); "
+ "INSERT OR IGNORE INTO `priority`(`value`) VALUES ('NAVIGATION'); "
+ "INSERT OR IGNORE INTO `priority`(`value`) VALUES ('VOICECOMMUNICATION'); "
+ "INSERT OR IGNORE INTO `priority`(`value`) VALUES ('COMMUNICATION'); "
+ "INSERT OR IGNORE INTO `priority`(`value`) VALUES ('NORMAL'); "
+ "INSERT OR IGNORE INTO `priority`(`value`) VALUES ('NONE'); "
+ "INSERT OR IGNORE INTO `hmi_level`(`value`) VALUES ('FULL'); "
+ "INSERT OR IGNORE INTO `hmi_level`(`value`) VALUES ('LIMITED'); "
+ "INSERT OR IGNORE INTO `hmi_level`(`value`) VALUES ('BACKGROUND'); "
+ "INSERT OR IGNORE INTO `hmi_level`(`value`) VALUES ('NONE'); "
+ "INSERT OR IGNORE INTO `version` (`number`) VALUES('0'); "
+ "INSERT OR IGNORE INTO `_internal_data` (`db_version_hash`) VALUES(0); "
+ "";
+
+const std::string kDropSchema =
+ "BEGIN; "
+ "DROP INDEX IF EXISTS `message.fk_messages_languages1_idx`; "
+ "DROP INDEX IF EXISTS "
+ "`message.fk_message_consumer_friendly_messages1_idx`; "
+ "DROP TABLE IF EXISTS `message`; "
+ "DROP INDEX IF EXISTS `endpoint.fk_endpoint_application1_idx`; "
+ "DROP TABLE IF EXISTS `endpoint`; "
+ "DROP INDEX IF EXISTS `consent_group.fk_consent_group_device1_idx`; "
+ "DROP INDEX IF EXISTS "
+ "`consent_group.fk_consent_group_functional_group1_idx`; "
+ "DROP TABLE IF EXISTS `consent_group`; "
+ "DROP INDEX IF EXISTS `app_type.fk_app_type_application1_idx`; "
+ "DROP TABLE IF EXISTS `app_type`; "
+ "DROP INDEX IF EXISTS `nickname.fk_nickname_application1_idx`; "
+ "DROP TABLE IF EXISTS `nickname`; "
+ "DROP INDEX IF EXISTS `app_level.fk_app_level_language2_idx`; "
+ "DROP INDEX IF EXISTS `app_level.fk_app_level_language1_idx`; "
+ "DROP INDEX IF EXISTS `app_level.fk_app_levels_application1_idx`; "
+ "DROP TABLE IF EXISTS `app_level`; "
+ "DROP INDEX IF EXISTS "
+ "`device_consent_group.fk_device_has_functional_group_device1_idx`; "
+ "DROP INDEX IF EXISTS "
+ "`device_consent_group.fk_device_has_functional_group_functional_group1_"
+ "idx`; "
+ "DROP TABLE IF EXISTS `device_consent_group`; "
+ "DROP TABLE IF EXISTS `seconds_between_retry`; "
+ "DROP INDEX IF EXISTS "
+ "`preconsented_group.fk_application_has_functional_group_application2_idx`;"
+ " "
+ "DROP INDEX IF EXISTS "
+ "`preconsented_group.fk_application_has_functional_group_functional_group2_"
+ "idx`; "
+ "DROP TABLE IF EXISTS `preconsented_group`; "
+ "DROP INDEX IF EXISTS "
+ "`app_group.fk_application_has_functional_group_application1_idx`; "
+ "DROP INDEX IF EXISTS "
+ "`app_group.fk_application_has_functional_group_functional_group1_idx`; "
+ "DROP TABLE IF EXISTS `app_group`; "
+ "DROP INDEX IF EXISTS `application.fk_application_priorities1_idx`; "
+ "DROP INDEX IF EXISTS `application.fk_application_hmi_level1_idx`; "
+ "DROP TABLE IF EXISTS `application`; "
+ "DROP INDEX IF EXISTS `rpc.select_rpc_name_hmi_level`; "
+ "DROP INDEX IF EXISTS `rpc.fk_rpc_functional_group1_idx`; "
+ "DROP INDEX IF EXISTS `rpc.fk_rpc_hmi_level1_idx`; "
+ "DROP TABLE IF EXISTS `rpc`; "
+ "DROP TABLE IF EXISTS `version`; "
+ "DROP TABLE IF EXISTS `message_type`; "
+ "DROP TABLE IF EXISTS `language`; "
+ "DROP INDEX IF EXISTS "
+ "`notifications_by_priority.fk_notifications_by_priority_priority1_idx`; "
+ "DROP TABLE IF EXISTS `notifications_by_priority`; "
+ "DROP TABLE IF EXISTS `hmi_level`; "
+ "DROP TABLE IF EXISTS `priority`; "
+ "DROP TABLE IF EXISTS `functional_group`; "
+ "DROP TABLE IF EXISTS `module_config`; "
+ "DROP TABLE IF EXISTS `module_meta`; "
+ "DROP TABLE IF EXISTS `usage_and_error_count`; "
+ "DROP TABLE IF EXISTS `device`; "
+ "DROP TABLE IF EXISTS `_internal_data`; "
+ "COMMIT; "
+ "VACUUM;";
+
+const std::string kDeleteData =
+ "BEGIN; "
+ "DELETE FROM `message`; "
+ "DELETE FROM `endpoint`; "
+ "DELETE FROM `consent_group`; "
+ "DELETE FROM `app_type`; "
+ "DELETE FROM `nickname`; "
+ "DELETE FROM `app_level`; "
+ "DELETE FROM `device_consent_group`; "
+ "DELETE FROM `seconds_between_retry`; "
+ "DELETE FROM `preconsented_group`; "
+ "DELETE FROM `app_group`; "
+ "DELETE FROM `application`; "
+ "DELETE FROM `rpc`; "
+ "DELETE FROM `version`; "
+ "DELETE FROM `message_type`; "
+ "DELETE FROM `language`; "
+ "DELETE FROM `notifications_by_priority`; "
+ "DELETE FROM `hmi_level`; "
+ "DELETE FROM `priority`; "
+ "DELETE FROM `functional_group`; "
+ "DELETE FROM `module_config`; "
+ "DELETE FROM `module_meta`; "
+ "DELETE FROM `usage_and_error_count`; "
+ "DELETE FROM `device`; "
+ "COMMIT; "
+ "VACUUM;";
+
+const std::string kCheckDBIntegrity = "PRAGMA integrity_check";
+
+const std::string kCheckPgNumber = "PRAGMA page_count";
+
+const std::string kSelectRpc =
+ "SELECT DISTINCT `rpc`.`parameter` FROM `rpc` "
+ " JOIN `app_group` AS `g` ON (`g`.`functional_group_id` = "
+ "`rpc`.`functional_group_id` "
+ " AND (`g`.`application_id` = ?)) "
+ "WHERE `rpc`.`hmi_level_value` = ? AND `rpc`.`name` = ?";
+
+const std::string kSelectPreloaded =
+ "SELECT `preloaded_pt` FROM `module_config` "
+ "WHERE `preloaded_pt` = 1 LIMIT 1";
+
+const std::string kUpdatePreloaded =
+ "UPDATE `module_config` SET `preloaded_pt` = ?";
+
+const std::string kIsFirstRun = "SELECT `is_first_run` FROM `module_config` ";
+
+const std::string kSetNotFirstRun =
+ "UPDATE `module_config` SET `is_first_run`= 0 ";
+
+const std::string kSelectEndpoint =
+ "SELECT `url`, `application_id` FROM `endpoint` WHERE `service` = ? ";
+
+const std::string kSelectLockScreenIcon =
+ "SELECT `url` FROM `endpoint` WHERE `service` = ? AND `application_id` = ?";
+
+const std::string kInsertFunctionalGroup =
+ "INSERT INTO `functional_group` (`id`, `name`, `user_consent_prompt`) "
+ " VALUES (?, ?, ?)";
+
+const std::string kInsertRpc =
+ "INSERT INTO `rpc` (`name`, `hmi_level_value`, `functional_group_id`) "
+ " VALUES (?, ?, ?)";
+
+const std::string kInsertRpcWithParameter =
+ "INSERT INTO `rpc` (`name`, `hmi_level_value`, `parameter`, "
+ "`functional_group_id`) "
+ " VALUES (?, ?, ?, ?)";
+
+const std::string kInsertApplication =
+ "INSERT OR IGNORE INTO `application` (`id`, `priority_value`, "
+ "`is_revoked`, `memory_kb`,"
+ " `heart_beat_timeout_ms`, `certificate`) VALUES (?,?,?,?,?,?)";
+
+const std::string kInsertAppGroup =
+ "INSERT INTO `app_group` (`application_id`, `functional_group_id`)"
+ " SELECT ?, `id` FROM `functional_group` WHERE `name` = ? LIMIT 1";
+
+const std::string kInsertNickname =
+ "INSERT OR IGNORE INTO `nickname` (`application_id`, `name`) VALUES (?, ?)";
+
+const std::string kInsertAppType =
+ "INSERT OR IGNORE INTO `app_type` (`application_id`, `name`) VALUES (?, ?)";
+
+const std::string kInsertRequestType =
+ "INSERT OR IGNORE INTO `request_type` (`application_id`, `request_type`) "
+ "VALUES (?, ?)";
+
+const std::string kUpdateVersion = "UPDATE `version` SET `number`= ?";
+
+const std::string kInsertMessageType =
+ "INSERT OR IGNORE INTO `message_type` (`name`) VALUES (?)";
+
+const std::string kInsertLanguage =
+ "INSERT OR IGNORE INTO `language` (`code`) VALUES (?)";
+
+const std::string kInsertMessageString =
+ "INSERT INTO `message` (`language_code`, `message_type_name`) "
+ "VALUES (?, ?)";
+
+const std::string kUpdateModuleConfig =
+ "UPDATE `module_config` SET `preloaded_pt` = ?, "
+ " `exchange_after_x_ignition_cycles` = ?,"
+ " `exchange_after_x_kilometers` = ?, `exchange_after_x_days` = ?, "
+ " `timeout_after_x_seconds` = ?, `certificate` = ?, `vehicle_make` = ?, "
+ " `vehicle_model` = ?, `vehicle_year` = ?";
+
+const std::string kInsertEndpoint =
+ "INSERT INTO `endpoint` (`service`, `url`, `application_id`) "
+ " VALUES (?, ?, ?)";
+
+const std::string kInsertSecondsBetweenRetry =
+ "INSERT INTO `seconds_between_retry` (`index`, `value`) VALUES (?, ?)";
+
+const std::string kInsertNotificationsByPriority =
+ "INSERT OR REPLACE INTO `notifications_by_priority` (`priority_value`, "
+ "`value`) "
+ " VALUES (?, ?)";
+
+const std::string kInsertDeviceData =
+ "INSERT OR IGNORE INTO `device` (`id`) VALUES (?)";
+
+const std::string kInsertAppLevel =
+ "INSERT INTO `app_level` (`application_id`, `count_of_tls_errors`) "
+ "VALUES(?,?)";
+
+const std::string kDeleteSecondsBetweenRetries =
+ "DELETE FROM `seconds_between_retry`";
+
+const std::string kDeleteEndpoint = "DELETE FROM `endpoint`";
+
+const std::string kDeleteAppLevel = "DELETE FROM `app_level`";
+
+const std::string kDeleteMessageString = "DELETE FROM `message`";
+
+const std::string kDeleteFunctionalGroup = "DELETE FROM `functional_group`";
+
+const std::string kDeleteRpc = "DELETE FROM `rpc`";
+
+const std::string kDeleteAppGroup = "DELETE FROM `app_group`";
+
+const std::string kSelectModuleConfig =
+ "SELECT `preloaded_pt`, `exchange_after_x_ignition_cycles`, "
+ " `exchange_after_x_kilometers`, `exchange_after_x_days`, "
+ " `timeout_after_x_seconds`, `certificate`, `vehicle_make`,"
+ " `vehicle_model`, `vehicle_year` "
+ " FROM `module_config`";
+
+const std::string kSelectEndpoints =
+ "SELECT `url`, `service`, `application_id` FROM `endpoint` ";
+
+const std::string kSelectNotificationsPerMin =
+ "SELECT `priority_value`, `value` FROM notifications_by_priority";
+
+const std::string kSelectNotificationsPerPriority =
+ "SELECT `value` FROM notifications_by_priority WHERE `priority_value` = ? ";
+
+const std::string kSelectAppLevels =
+ "SELECT `application_id`, `count_of_tls_errors` "
+ "FROM `app_level`";
+
+const std::string kSelectDeviceData = "SELECT * FROM `device`";
+
+const std::string kSelectFunctionalGroups =
+ "SELECT `id`,`name`, `user_consent_prompt` "
+ "FROM `functional_group`";
+
+const std::string kSelectAllRpcs =
+ "SELECT `name`, `hmi_level_value`, `parameter` "
+ "FROM `rpc` WHERE `functional_group_id` = ? ";
+
+const std::string kSelectUserMsgsVersion =
+ "SELECT DISTINCT `number` FROM `version`";
+
+const std::string kSelectAppPolicies =
+ "SELECT `id`, `priority_value`, `memory_kb`, "
+ " `heart_beat_timeout_ms`, `certificate` FROM `application`";
+
+const std::string kCollectFriendlyMsg = "SELECT * FROM `message`";
+
+const std::string kSelectAppGroups =
+ "SELECT `f`.`name` FROM `app_group` AS `a`"
+ " LEFT JOIN `functional_group` AS `f` "
+ " ON (`f`.`id` = `a`.`functional_group_id`)"
+ " WHERE `a`.`application_id` = ?";
+
+const std::string kSelectNicknames =
+ "SELECT DISTINCT `name` FROM `nickname` "
+ "WHERE `application_id` = ?";
+
+const std::string kSelectAppTypes =
+ "SELECT DISTINCT `name` FROM `app_type` "
+ "WHERE `application_id` = ?";
+
+const std::string kSelectRequestTypes =
+ "SELECT DISTINCT `request_type` FROM `request_type` WHERE `application_id` "
+ "= ?";
+
+const std::string kSelectSecondsBetweenRetries =
+ "SELECT `value` FROM `seconds_between_retry` ORDER BY `index`";
+
+const std::string kSelectIgnitionCycles =
+ "SELECT `c`.`exchange_after_x_ignition_cycles`, "
+ " `m`.`ignition_cycles_since_last_exchange` "
+ " FROM `module_config` AS `c`, `module_meta` AS `m` "
+ "LIMIT 1";
+
+const std::string kSelectKilometers =
+ "SELECT `c`.`exchange_after_x_kilometers`, "
+ " `m`.`pt_exchanged_at_odometer_x` "
+ " FROM `module_config` AS `c`, `module_meta` AS `m` "
+ "LIMIT 1";
+
+const std::string kSelectDays =
+ "SELECT `c`.`exchange_after_x_days`, "
+ " `m`.`pt_exchanged_x_days_after_epoch` "
+ " FROM `module_config` AS `c`, `module_meta` AS `m` "
+ "LIMIT 1";
+
+const std::string kIncrementIgnitionCycles =
+ "UPDATE `module_meta` SET `ignition_cycles_since_last_exchange` = 1 + "
+ " `ignition_cycles_since_last_exchange`";
+
+const std::string kResetIgnitionCycles =
+ "UPDATE `module_meta` SET `ignition_cycles_since_last_exchange` = 0";
+
+const std::string kSelectTimeoutResponse =
+ "SELECT `timeout_after_x_seconds` FROM `module_config` LIMIT 1";
+
+const std::string kUpdateFlagUpdateRequired =
+ "UPDATE `module_meta` SET `flag_update_required` = ?";
+
+const std::string kSelectFlagUpdateRequired =
+ "SELECT `flag_update_required` FROM `module_meta` LIMIT 1";
+
+const std::string kUpdateCountersSuccessfulUpdate =
+ "UPDATE `module_meta` SET `pt_exchanged_at_odometer_x` = ?,"
+ "`pt_exchanged_x_days_after_epoch` = ?";
+
+const std::string kDeleteApplication = "DELETE FROM `application`";
+
+const std::string kDeleteRequestType = "DELETE FROM `request_type`";
+
+const std::string kSelectApplicationRevoked =
+ "SELECT `is_revoked` FROM `application` WHERE `id` = ?";
+
+const std::string kUpdateApplicationCustomData =
+ "UPDATE `application` SET `is_revoked` = ?, `is_default` = ?,"
+ "`is_predata` = ? WHERE `id` = ?";
+
+const std::string kSelectApplicationRepresented =
+ "SELECT COUNT(`id`) FROM `application` WHERE `id` = ?";
+
+const std::string kSelectApplicationIsDefault =
+ "SELECT `is_default` FROM `application` WHERE `id` = ?";
+
+const std::string kUpdateIsDefault =
+ "UPDATE `application` SET `is_default` = ? WHERE `id` = ?";
+
+const std::string kDeleteDevice = "DELETE FROM `device` WHERE `id` = ?";
+
+const std::string kDeleteAppGroupByApplicationId =
+ "DELETE FROM `app_group` WHERE `application_id` = ?";
+
+const std::string kInsertApplicationFull =
+ "INSERT OR IGNORE INTO `application` (`id`, `keep_context`, `steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, "
+ " `memory_kb`, `heart_beat_timeout_ms`, `certificate`) "
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
+
+const std::string kSelectApplicationFull =
+ "SELECT `keep_context`, `steal_focus`, `default_hmi`, `priority_value`, "
+ " `is_revoked`, `is_default`, `is_predata`, `memory_kb`,"
+ " `heart_beat_timeout_ms`, `certificate` FROM `application` WHERE `id` = "
+ "?";
+
+const std::string kSelectDBVersion =
+ "SELECT `db_version_hash` from `_internal_data`";
+
+const std::string kUpdateDBVersion =
+ "UPDATE `_internal_data` SET `db_version_hash` = ? ";
+
+const std::string kSaveModuleMeta =
+ "UPDATE `module_meta` SET "
+ "`pt_exchanged_at_odometer_x` = ?, "
+ "`pt_exchanged_x_days_after_epoch` = ?, "
+ "`ignition_cycles_since_last_exchange` = ? ";
+
+const std::string kSelectModuleMeta = "SELECT* FROM `module_meta`";
+
+} // namespace sql_pt
+} // namespace policy
diff --git a/src/components/policy/src/sql_pt_representation.cc b/src/components/policy/src/sql_pt_representation.cc
new file mode 100644
index 0000000000..03fd88b717
--- /dev/null
+++ b/src/components/policy/src/sql_pt_representation.cc
@@ -0,0 +1,1750 @@
+/*
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <sstream>
+#include <stdlib.h>
+#include <stdint.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "utils/logger.h"
+#include "utils/file_system.h"
+#include "utils/gen_hash.h"
+#include "policy/sql_pt_representation.h"
+#include "policy/sql_wrapper.h"
+#include "policy/sql_pt_queries.h"
+#include "policy/policy_helper.h"
+#include "policy/cache_manager.h"
+#include "config_profile/profile.h"
+
+namespace policy {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")
+
+namespace {
+template <typename T, typename K>
+void InsertUnique(K value, T* array) {
+ uint32_t i = 0;
+ for (; i < array->size() && array->at(i) != value; ++i) {
+ continue;
+ }
+ if (array->size() == i) {
+ array->push_back(value);
+ }
+}
+} // namespace
+
+const std::string SQLPTRepresentation::kDatabaseName = "policy";
+
+SQLPTRepresentation::SQLPTRepresentation()
+ : db_(new utils::dbms::SQLDatabase(kDatabaseName)) {}
+
+SQLPTRepresentation::~SQLPTRepresentation() {
+ db_->Close();
+ delete db_;
+}
+
+void SQLPTRepresentation::CheckPermissions(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ CheckPermissionResult& result) {
+ utils::dbms::SQLQuery query(db());
+
+ if (!query.Prepare(sql_pt::kSelectRpc)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect select statement from rpcs"
+ << query.LastError().text());
+ return;
+ }
+ query.Bind(0, app_id);
+ query.Bind(1, hmi_level);
+ query.Bind(2, rpc);
+
+ bool ret = query.Next();
+ result.hmi_level_permitted = ret ? kRpcAllowed : kRpcDisallowed;
+ LOG4CXX_INFO(logger_,
+ "Level is " << (result.hmi_level_permitted == kRpcAllowed
+ ? "permitted"
+ : "not permitted"));
+ std::string parameter;
+ while (ret) {
+ if (!query.IsNull(0)) {
+ parameter = query.GetString(0);
+ result.list_of_allowed_params.push_back(parameter);
+ }
+ ret = query.Next();
+ }
+}
+
+bool SQLPTRepresentation::IsPTPreloaded() {
+ utils::dbms::SQLQuery query(db());
+ return query.Prepare(sql_pt::kSelectPreloaded) && query.Next();
+}
+
+int SQLPTRepresentation::IgnitionCyclesBeforeExchange() {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectIgnitionCycles) || !query.Exec()) {
+ LOG4CXX_WARN(logger_, "Can not select ignition cycles");
+ return 0;
+ }
+ int limit = query.GetInteger(0);
+ int current = query.GetInteger(1);
+
+ if (limit < 0 || current < 0 || current > limit) {
+ return 0;
+ }
+
+ return limit - current;
+}
+
+int SQLPTRepresentation::KilometersBeforeExchange(int current) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectKilometers) || !query.Exec()) {
+ LOG4CXX_WARN(logger_, "Can not select kilometers");
+ return 0;
+ }
+ int limit = query.GetInteger(0);
+ int last = query.GetInteger(1);
+
+ if (limit < 0 || last < 0 || current < 0 || current < last ||
+ limit < (current - last)) {
+ return 0;
+ }
+
+ return limit - (current - last);
+}
+
+bool SQLPTRepresentation::SetCountersPassedForSuccessfulUpdate(
+ int kilometers, int days_after_epoch) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kUpdateCountersSuccessfulUpdate)) {
+ LOG4CXX_WARN(logger_,
+ "Wrong update query for counters on successful update.");
+ return false;
+ }
+ query.Bind(0, kilometers);
+ query.Bind(1, days_after_epoch);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed to update counters on successful update.");
+ return false;
+ }
+ return true;
+}
+
+int SQLPTRepresentation::DaysBeforeExchange(int current) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectDays) || !query.Exec()) {
+ LOG4CXX_WARN(logger_, "Can not select days");
+ return 0;
+ }
+ int limit = query.GetInteger(0);
+ int last = query.GetInteger(1);
+
+ if (0 == last) {
+ return limit;
+ }
+
+ if (limit < 0 || last < 0 || current < 0 || current < last ||
+ limit < (current - last)) {
+ return 0;
+ }
+
+ return limit - (current - last);
+}
+
+int SQLPTRepresentation::TimeoutResponse() {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectTimeoutResponse) || !query.Exec()) {
+ LOG4CXX_INFO(logger_, "Can not select timeout response for retry sequence");
+ const int kDefault = 30;
+ return kDefault;
+ }
+ return query.GetInteger(0);
+}
+
+bool SQLPTRepresentation::SecondsBetweenRetries(std::vector<int>* seconds) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectSecondsBetweenRetries)) {
+ LOG4CXX_INFO(logger_,
+ "Incorrect select statement from seconds between retries");
+ return false;
+ }
+ while (query.Next()) {
+ seconds->push_back(query.GetInteger(0));
+ }
+ return true;
+}
+
+std::vector<UserFriendlyMessage> SQLPTRepresentation::GetUserFriendlyMsg(
+ const std::vector<std::string>& msg_codes, const std::string& language) {
+ std::vector<UserFriendlyMessage> result;
+ std::vector<std::string>::const_iterator it = msg_codes.begin();
+ std::vector<std::string>::const_iterator it_end = msg_codes.end();
+ for (; it != it_end; ++it) {
+ UserFriendlyMessage msg;
+ msg.message_code = *it;
+ result.push_back(msg);
+ }
+ return result;
+}
+
+EndpointUrls SQLPTRepresentation::GetUpdateUrls(int service_type) {
+ LOG4CXX_INFO(logger_,
+ "SQLPTRepresentation::GetUpdateUrls for " << service_type);
+ utils::dbms::SQLQuery query(db());
+ EndpointUrls ret;
+ if (query.Prepare(sql_pt::kSelectEndpoint)) {
+ query.Bind(0, service_type);
+ while (query.Next()) {
+ EndpointData data;
+
+ data.url.push_back(query.GetString(0));
+ if (!query.IsNull(1)) {
+ data.app_id = query.GetString(1);
+ }
+ ret.push_back(data);
+ }
+ } else {
+ LOG4CXX_WARN(logger_, "Invalid select endpoints statement.");
+ }
+ return ret;
+}
+
+std::string SQLPTRepresentation::GetLockScreenIconUrl() const {
+ utils::dbms::SQLQuery query(db());
+ std::string ret;
+ if (query.Prepare(sql_pt::kSelectLockScreenIcon)) {
+ query.Bind(0, std::string("lock_screen_icon_url"));
+ query.Bind(1, std::string("default"));
+
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect select from notifications by priority.");
+ return ret;
+ }
+
+ if (!query.IsNull(0)) {
+ ret = query.GetString(0);
+ }
+
+ } else {
+ LOG4CXX_WARN(logger_, "Invalid select endpoints statement.");
+ }
+ return ret;
+}
+
+int SQLPTRepresentation::GetNotificationsNumber(const std::string& priority) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectNotificationsPerPriority)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect select statement for priority "
+ "notification number.");
+ return 0;
+ }
+ query.Bind(0, priority);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect select from notifications by priority.");
+ return 0;
+ }
+
+ if (!query.IsNull(0)) {
+ return query.GetInteger(0);
+ }
+
+ return 0;
+}
+
+bool SQLPTRepresentation::GetPriority(const std::string& policy_app_id,
+ std::string* priority) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (NULL == priority) {
+ LOG4CXX_WARN(logger_, "Input priority parameter is null.");
+ return false;
+ }
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectPriority)) {
+ LOG4CXX_INFO(logger_, "Incorrect statement for priority.");
+ return false;
+ }
+
+ query.Bind(0, policy_app_id);
+
+ if (!query.Exec()) {
+ LOG4CXX_INFO(logger_, "Error during select priority.");
+ return false;
+ }
+
+ if (query.IsNull(0)) {
+ priority->clear();
+ return true;
+ }
+
+ priority->assign(query.GetString(0));
+
+ return true;
+}
+
+InitResult SQLPTRepresentation::Init(const PolicySettings* settings) {
+ settings_ = settings;
+ LOG4CXX_AUTO_TRACE(logger_);
+#ifdef BUILD_TESTS
+ open_counter_ = 0;
+#endif // BUILD_TESTS
+ if (!db_->Open()) {
+ LOG4CXX_ERROR(logger_, "Failed opening database.");
+ LOG4CXX_INFO(logger_, "Starting opening retries.");
+ const uint16_t attempts = get_settings().attempts_to_open_policy_db();
+ LOG4CXX_DEBUG(logger_, "Total attempts number is: " << attempts);
+ bool is_opened = false;
+ const uint16_t open_attempt_timeout_ms =
+ get_settings().open_attempt_timeout_ms();
+ const useconds_t sleep_interval_mcsec = open_attempt_timeout_ms * 1000;
+ LOG4CXX_DEBUG(logger_,
+ "Open attempt timeout(ms) is: " << open_attempt_timeout_ms);
+ for (int i = 0; i < attempts; ++i) {
+ usleep(sleep_interval_mcsec);
+ LOG4CXX_INFO(logger_, "Attempt: " << i + 1);
+#ifdef BUILD_TESTS
+ ++open_counter_;
+#endif // BUILD_TESTS
+ if (db_->Open()) {
+ LOG4CXX_INFO(logger_, "Database opened.");
+ is_opened = true;
+ break;
+ }
+ }
+ if (!is_opened) {
+ LOG4CXX_ERROR(logger_,
+ "Open retry sequence failed. Tried "
+ << attempts << " attempts with "
+ << open_attempt_timeout_ms
+ << " open timeout(ms) for each.");
+ return InitResult::FAIL;
+ }
+ }
+#ifndef __QNX__
+ if (!db_->IsReadWrite()) {
+ LOG4CXX_ERROR(logger_, "There are no read/write permissions for database");
+ return InitResult::FAIL;
+ }
+
+#endif // __QNX__
+ utils::dbms::SQLQuery check_pages(db());
+ if (!check_pages.Prepare(sql_pt::kCheckPgNumber) || !check_pages.Next()) {
+ LOG4CXX_WARN(logger_, "Incorrect pragma for page counting.");
+ } else {
+ if (0 < check_pages.GetInteger(0)) {
+ utils::dbms::SQLQuery db_check(db());
+ if (!db_check.Prepare(sql_pt::kCheckDBIntegrity)) {
+ LOG4CXX_WARN(logger_, "Incorrect pragma for integrity check.");
+ } else {
+ while (db_check.Next()) {
+ if (db_check.GetString(0).compare("ok") == 0) {
+ utils::dbms::SQLQuery check_first_run(db());
+ if (check_first_run.Prepare(sql_pt::kIsFirstRun) &&
+ check_first_run.Next()) {
+ LOG4CXX_INFO(logger_,
+ "Selecting is first run "
+ << check_first_run.GetBoolean(0));
+ if (check_first_run.GetBoolean(0)) {
+ utils::dbms::SQLQuery set_not_first_run(db());
+ set_not_first_run.Exec(sql_pt::kSetNotFirstRun);
+ return InitResult::SUCCESS;
+ }
+ } else {
+ LOG4CXX_WARN(logger_, "Incorrect select is first run");
+ }
+ return InitResult::EXISTS;
+ } else {
+ LOG4CXX_ERROR(logger_,
+ "Existing policy table representation is invlaid.");
+ // TODO(PV): add handle
+ return InitResult::FAIL;
+ }
+ }
+ }
+ }
+ }
+ utils::dbms::SQLQuery query(db());
+ if (!query.Exec(sql_pt::kCreateSchema)) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Failed creating schema of database: " << query.LastError().text());
+ return InitResult::FAIL;
+ }
+ if (!query.Exec(sql_pt::kInsertInitData)) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Failed insert init data to database: " << query.LastError().text());
+ return InitResult::FAIL;
+ }
+ return InitResult::SUCCESS;
+}
+
+bool SQLPTRepresentation::Close() {
+ db_->Close();
+ return db_->LastError().number() == utils::dbms::OK;
+}
+
+const VehicleInfo SQLPTRepresentation::GetVehicleInfo() const {
+ policy_table::ModuleConfig module_config;
+ GatherModuleConfig(&module_config);
+ VehicleInfo vehicle_info;
+ vehicle_info.vehicle_make = *module_config.vehicle_make;
+ vehicle_info.vehicle_model = *module_config.vehicle_model;
+ vehicle_info.vehicle_year = *module_config.vehicle_year;
+ return vehicle_info;
+}
+
+bool SQLPTRepresentation::Drop() {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Exec(sql_pt::kDropSchema)) {
+ LOG4CXX_WARN(logger_,
+ "Failed dropping database: " << query.LastError().text());
+ return false;
+ }
+ return true;
+}
+
+void SQLPTRepresentation::WriteDb() {
+ db_->Backup();
+}
+
+bool SQLPTRepresentation::Clear() {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Exec(sql_pt::kDeleteData)) {
+ LOG4CXX_ERROR(logger_,
+ "Failed clearing database: " << query.LastError().text());
+ return false;
+ }
+ if (!query.Exec(sql_pt::kInsertInitData)) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Failed insert init data to database: " << query.LastError().text());
+ return false;
+ }
+ return true;
+}
+
+bool SQLPTRepresentation::RefreshDB() {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Exec(sql_pt::kDropSchema)) {
+ LOG4CXX_WARN(logger_,
+ "Failed dropping database: " << query.LastError().text());
+ return false;
+ }
+ if (!query.Exec(sql_pt::kCreateSchema)) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Failed creating schema of database: " << query.LastError().text());
+ return false;
+ }
+ if (!query.Exec(sql_pt::kInsertInitData)) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Failed insert init data to database: " << query.LastError().text());
+ return false;
+ }
+ return true;
+}
+
+utils::SharedPtr<policy_table::Table> SQLPTRepresentation::GenerateSnapshot()
+ const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::SharedPtr<policy_table::Table> table = new policy_table::Table();
+ GatherModuleMeta(&*table->policy_table.module_meta);
+ GatherModuleConfig(&table->policy_table.module_config);
+ GatherUsageAndErrorCounts(&*table->policy_table.usage_and_error_counts);
+ GatherDeviceData(&*table->policy_table.device_data);
+ GatherFunctionalGroupings(&table->policy_table.functional_groupings);
+ GatherConsumerFriendlyMessages(
+ &*table->policy_table.consumer_friendly_messages);
+ GatherApplicationPoliciesSection(&table->policy_table.app_policies_section);
+ return table;
+}
+
+void SQLPTRepresentation::GatherModuleMeta(
+ policy_table::ModuleMeta* meta) const {
+ LOG4CXX_INFO(logger_, "Gather Module Meta Info");
+ utils::dbms::SQLQuery query(db());
+ if (query.Prepare(sql_pt::kSelectModuleMeta) && query.Next()) {
+ *meta->pt_exchanged_at_odometer_x = query.GetInteger(0);
+ *meta->pt_exchanged_x_days_after_epoch = query.GetInteger(1);
+ *meta->ignition_cycles_since_last_exchange = query.GetInteger(2);
+ }
+}
+
+void SQLPTRepresentation::GatherModuleConfig(
+ policy_table::ModuleConfig* config) const {
+ LOG4CXX_INFO(logger_, "Gather Configuration Info");
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectModuleConfig) || !query.Next()) {
+ LOG4CXX_WARN(logger_, "Incorrect select statement for module config");
+ } else {
+ *config->preloaded_pt = query.GetBoolean(0);
+ config->exchange_after_x_ignition_cycles = query.GetInteger(1);
+ config->exchange_after_x_kilometers = query.GetInteger(2);
+ config->exchange_after_x_days = query.GetInteger(3);
+ config->timeout_after_x_seconds = query.GetInteger(4);
+ *config->certificate = query.GetString(5);
+ *config->vehicle_make = query.GetString(6);
+ *config->vehicle_model = query.GetString(7);
+ *config->vehicle_year = query.GetString(8);
+ *config->preloaded_date = query.GetString(9);
+ }
+
+ utils::dbms::SQLQuery endpoints(db());
+ if (!endpoints.Prepare(sql_pt::kSelectEndpoints)) {
+ LOG4CXX_WARN(logger_, "Incorrect select statement for endpoints");
+ } else {
+ while (endpoints.Next()) {
+ const std::string& url = endpoints.GetString(0);
+ const std::string& service = endpoints.GetString(1);
+ const std::string& app_id = endpoints.GetString(2);
+ config->endpoints[service][app_id].push_back(url);
+ }
+ }
+
+ utils::dbms::SQLQuery notifications(db());
+ if (!notifications.Prepare(sql_pt::kSelectNotificationsPerMin)) {
+ LOG4CXX_WARN(logger_, "Incorrect select statement for notifications");
+ } else {
+ while (notifications.Next()) {
+ config->notifications_per_minute_by_priority[notifications.GetString(0)] =
+ notifications.GetInteger(1);
+ }
+ }
+ utils::dbms::SQLQuery seconds(db());
+ if (!seconds.Prepare(sql_pt::kSelectSecondsBetweenRetries)) {
+ LOG4CXX_INFO(logger_,
+ "Incorrect select statement from seconds between retries");
+ } else {
+ while (seconds.Next()) {
+ config->seconds_between_retries.push_back(seconds.GetInteger(0));
+ }
+ }
+}
+
+bool SQLPTRepresentation::GatherUsageAndErrorCounts(
+ policy_table::UsageAndErrorCounts* counts) const {
+ LOG4CXX_INFO(logger_, "Gather Usage and Error Counts.");
+ utils::dbms::SQLQuery query(db());
+ if (query.Prepare(sql_pt::kSelectAppLevels)) {
+ policy_table::AppLevel app_level;
+ app_level.mark_initialized();
+ while (query.Next()) {
+ app_level.count_of_tls_errors = query.GetInteger(1);
+ const std::string app_id = query.GetString(0);
+ (*counts->app_level)[app_id] = app_level;
+ }
+ return true;
+ }
+ return false;
+}
+
+void SQLPTRepresentation::GatherDeviceData(
+ policy_table::DeviceData* data) const {
+ LOG4CXX_INFO(logger_, "Gather device data.");
+ data->mark_initialized();
+
+ utils::dbms::SQLQuery query(db());
+ if (query.Prepare(sql_pt::kSelectDeviceData)) {
+ policy_table::DeviceParams device_data;
+ device_data.mark_initialized();
+ while (query.Next()) {
+ const std::string device_id = query.GetString(0);
+ (*data)[device_id] = device_data;
+ }
+ }
+}
+
+bool SQLPTRepresentation::GatherFunctionalGroupings(
+ policy_table::FunctionalGroupings* groups) const {
+ LOG4CXX_INFO(logger_, "Gather Functional Groupings info");
+ utils::dbms::SQLQuery func_group(db());
+ if (!func_group.Prepare(sql_pt::kSelectFunctionalGroups)) {
+ LOG4CXX_WARN(logger_, "Incorrect select from functional_groupings");
+ return false;
+ }
+ utils::dbms::SQLQuery rpcs(db());
+ if (!rpcs.Prepare(sql_pt::kSelectAllRpcs)) {
+ LOG4CXX_WARN(logger_, "Incorrect select all from rpc");
+ return false;
+ }
+ while (func_group.Next()) {
+ policy_table::Rpcs rpcs_tbl;
+ if (!func_group.IsNull(2)) {
+ *rpcs_tbl.user_consent_prompt = func_group.GetString(2);
+ }
+ int func_id = func_group.GetInteger(0);
+ rpcs.Bind(0, func_id);
+ while (rpcs.Next()) {
+ if (!rpcs.IsNull(1)) {
+ policy_table::HmiLevel level;
+ if (policy_table::EnumFromJsonString(rpcs.GetString(1), &level)) {
+ InsertUnique(level, &rpcs_tbl.rpcs[rpcs.GetString(0)].hmi_levels);
+ }
+ }
+ if (!rpcs.IsNull(2)) {
+ policy_table::Parameter param;
+ if (policy_table::EnumFromJsonString(rpcs.GetString(2), &param)) {
+ InsertUnique(param, &(*rpcs_tbl.rpcs[rpcs.GetString(0)].parameters));
+ }
+ }
+ }
+ if (!rpcs_tbl.rpcs.is_initialized()) {
+ rpcs_tbl.rpcs.set_to_null();
+ }
+ rpcs.Reset();
+ (*groups)[func_group.GetString(1)] = rpcs_tbl;
+ }
+ return true;
+}
+
+bool SQLPTRepresentation::GatherConsumerFriendlyMessages(
+ policy_table::ConsumerFriendlyMessages* messages) const {
+ LOG4CXX_INFO(logger_, "Gather Consumer Friendly Messages");
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectUserMsgsVersion) || !query.Next()) {
+ LOG4CXX_WARN(logger_, "Incorrect select from consumer_friendly_messages");
+ return false;
+ }
+
+ messages->version = query.GetString(0);
+
+ if (query.Prepare(sql_pt::kCollectFriendlyMsg)) {
+ while (query.Next()) {
+ UserFriendlyMessage msg;
+ msg.message_code = query.GetString(7);
+ std::string language = query.GetString(6);
+
+ (*messages->messages)[msg.message_code].languages[language];
+ }
+ } else {
+ LOG4CXX_WARN(logger_, "Incorrect statement for select friendly messages.");
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::GatherApplicationPoliciesSection(
+ policy_table::ApplicationPoliciesSection* policies) const {
+ LOG4CXX_INFO(logger_, "Gather applications policies");
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectAppPolicies)) {
+ LOG4CXX_WARN(logger_, "Incorrect select from app_policies");
+ return false;
+ }
+
+ while (query.Next()) {
+ rpc::Nullable<policy_table::ApplicationParams> params;
+ const std::string& app_id = query.GetString(0);
+ if (IsApplicationRevoked(app_id)) {
+ params.set_to_null();
+ (*policies).apps[app_id] = params;
+ continue;
+ }
+ if (IsDefaultPolicy(app_id)) {
+ (*policies).apps[app_id].set_to_string(kDefaultId);
+ }
+ if (IsPredataPolicy(app_id)) {
+ (*policies).apps[app_id].set_to_string(kPreDataConsentId);
+ }
+ if (kDeviceId == app_id) {
+ // Priority is only SDL-specific item for device
+ policy_table::Priority priority;
+ policy_table::EnumFromJsonString(query.GetString(1), &priority);
+ (*policies).device.priority = priority;
+ continue;
+ }
+ policy_table::Priority priority;
+ policy_table::EnumFromJsonString(query.GetString(1), &priority);
+ params.priority = priority;
+
+ *params.memory_kb = query.GetInteger(2);
+
+ *params.heart_beat_timeout_ms = query.GetUInteger(3);
+ if (!query.IsNull(3)) {
+ *params.certificate = query.GetString(4);
+ }
+ if (!GatherAppGroup(app_id, &params.groups)) {
+ return false;
+ }
+ if (!GatherNickName(app_id, &*params.nicknames)) {
+ return false;
+ }
+ if (!GatherAppType(app_id, &*params.AppHMIType)) {
+ return false;
+ }
+ if (!GatherRequestType(app_id, &*params.RequestType)) {
+ return false;
+ }
+
+ (*policies).apps[app_id] = params;
+ }
+ return true;
+}
+
+bool SQLPTRepresentation::Save(const policy_table::Table& table) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ db_->BeginTransaction();
+ if (!SaveFunctionalGroupings(table.policy_table.functional_groupings)) {
+ db_->RollbackTransaction();
+ return false;
+ }
+ if (!SaveApplicationPoliciesSection(
+ table.policy_table.app_policies_section)) {
+ db_->RollbackTransaction();
+ return false;
+ }
+ if (!SaveModuleConfig(table.policy_table.module_config)) {
+ db_->RollbackTransaction();
+ return false;
+ }
+ if (!SaveConsumerFriendlyMessages(
+ *table.policy_table.consumer_friendly_messages)) {
+ db_->RollbackTransaction();
+ return false;
+ }
+
+ if (!SaveDeviceData(*table.policy_table.device_data)) {
+ db_->RollbackTransaction();
+ return false;
+ }
+ if (!SaveUsageAndErrorCounts(*table.policy_table.usage_and_error_counts)) {
+ db_->RollbackTransaction();
+ return false;
+ }
+ if (!SaveModuleMeta(*table.policy_table.module_meta)) {
+ db_->RollbackTransaction();
+ return false;
+ }
+ db_->CommitTransaction();
+ return true;
+}
+
+bool SQLPTRepresentation::SaveFunctionalGroupings(
+ const policy_table::FunctionalGroupings& groups) {
+ utils::dbms::SQLQuery query_delete(db());
+ if (!query_delete.Exec(sql_pt::kDeleteRpc)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from rpc.");
+ return false;
+ }
+
+ utils::dbms::SQLQuery query(db());
+ if (!query.Exec(sql_pt::kDeleteFunctionalGroup)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from seconds between retries.");
+ return false;
+ }
+ if (!query.Prepare(sql_pt::kInsertFunctionalGroup)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for functional groups");
+ return false;
+ }
+
+ policy_table::FunctionalGroupings::const_iterator it;
+
+ for (it = groups.begin(); it != groups.end(); ++it) {
+ // Since we uses this id in other tables, we have to be sure
+ // that id for certain group will be same in case when
+ // we drop records from the table and add them again.
+ // That's why we use hash as a primary key insted of
+ // simple auto incremental index.
+ const long int id = abs(CacheManager::GenerateHash(it->first));
+ // SQLite's Bind doesn support 'long' type
+ // So we need to explicitly cast it to int64_t
+ // to avoid ambiguity.
+ query.Bind(0, static_cast<int64_t>(id));
+ query.Bind(1, it->first);
+ it->second.user_consent_prompt.is_initialized()
+ ? query.Bind(2, *(it->second.user_consent_prompt))
+ : query.Bind(2);
+
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into functional groups");
+ return false;
+ }
+
+ if (!SaveRpcs(query.LastInsertId(), it->second.rpcs)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+bool SQLPTRepresentation::SaveRpcs(int64_t group_id,
+ const policy_table::Rpc& rpcs) {
+ utils::dbms::SQLQuery query(db());
+ utils::dbms::SQLQuery query_parameter(db());
+ if (!query.Prepare(sql_pt::kInsertRpc) ||
+ !query_parameter.Prepare(sql_pt::kInsertRpcWithParameter)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for rpc");
+ return false;
+ }
+
+ policy_table::Rpc::const_iterator it;
+ for (it = rpcs.begin(); it != rpcs.end(); ++it) {
+ const policy_table::HmiLevels& hmi_levels = it->second.hmi_levels;
+ // TODO(IKozyrenko): Check logic if optional container is missing
+ const policy_table::Parameters& parameters = *it->second.parameters;
+ policy_table::HmiLevels::const_iterator hmi_it;
+ policy_table::Parameters::const_iterator ps_it;
+ for (hmi_it = hmi_levels.begin(); hmi_it != hmi_levels.end(); ++hmi_it) {
+ if (!parameters.empty()) {
+ for (ps_it = parameters.begin(); ps_it != parameters.end(); ++ps_it) {
+ query_parameter.Bind(0, it->first);
+ query_parameter.Bind(
+ 1, std::string(policy_table::EnumToJsonString(*hmi_it)));
+ query_parameter.Bind(
+ 2, std::string(policy_table::EnumToJsonString(*ps_it)));
+ query_parameter.Bind(3, group_id);
+ if (!query_parameter.Exec() || !query_parameter.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into rpc with parameter");
+ return false;
+ }
+ }
+ } else {
+ query.Bind(0, it->first);
+ query.Bind(1, std::string(policy_table::EnumToJsonString(*hmi_it)));
+ query.Bind(2, group_id);
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into rpc");
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveApplicationPoliciesSection(
+ const policy_table::ApplicationPoliciesSection& policies) {
+ utils::dbms::SQLQuery query_delete(db());
+ if (!query_delete.Exec(sql_pt::kDeleteAppGroup)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from app_group.");
+ return false;
+ }
+ if (!query_delete.Exec(sql_pt::kDeleteApplication)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from application.");
+ return false;
+ }
+
+ if (!query_delete.Exec(sql_pt::kDeleteRequestType)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from request type.");
+ return false;
+ }
+
+ // All predefined apps (e.g. default, pre_DataConsent) should be saved first,
+ // otherwise another app with the predefined permissions can get incorrect
+ // permissions
+ policy_table::ApplicationPolicies::const_iterator it_default =
+ policies.apps.find(kDefaultId);
+ if (policies.apps.end() != it_default) {
+ if (!SaveSpecificAppPolicy(*it_default)) {
+ return false;
+ }
+ }
+ policy_table::ApplicationPolicies::const_iterator it_pre_data_consented =
+ policies.apps.find(kPreDataConsentId);
+ if (policies.apps.end() != it_pre_data_consented) {
+ if (!SaveSpecificAppPolicy(*it_pre_data_consented)) {
+ return false;
+ }
+ }
+
+ if (!SaveDevicePolicy(policies.device)) {
+ return false;
+ }
+
+ policy_table::ApplicationPolicies::const_iterator it;
+ for (it = policies.apps.begin(); it != policies.apps.end(); ++it) {
+ // Skip saving of predefined app, since they should be saved before
+ if (IsPredefinedApp(*it)) {
+ continue;
+ }
+ if (!SaveSpecificAppPolicy(*it)) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveSpecificAppPolicy(
+ const policy_table::ApplicationPolicies::value_type& app) {
+ utils::dbms::SQLQuery app_query(db());
+ if (!app_query.Prepare(sql_pt::kInsertApplication)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect insert statement into application (device).");
+ return false;
+ }
+
+ app_query.Bind(0, app.first);
+ app_query.Bind(
+ 1, std::string(policy_table::EnumToJsonString(app.second.priority)));
+ app_query.Bind(2, app.second.is_null());
+ app_query.Bind(3, *app.second.memory_kb);
+ app_query.Bind(4, static_cast<int64_t>(*app.second.heart_beat_timeout_ms));
+ app.second.certificate.is_initialized()
+ ? app_query.Bind(5, *app.second.certificate)
+ : app_query.Bind(5);
+ if (!app_query.Exec() || !app_query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into application.");
+ return false;
+ }
+
+ if (app.second.is_string()) {
+ if (kDefaultId.compare(app.second.get_string()) == 0) {
+ if (!SetDefaultPolicy(app.first)) {
+ return false;
+ }
+ // Stop saving other params, since predefined permissions already set
+ return true;
+ }
+ }
+
+ if (!SaveAppGroup(app.first, app.second.groups)) {
+ return false;
+ }
+ if (!SaveNickname(app.first, *app.second.nicknames)) {
+ return false;
+ }
+ if (!SaveAppType(app.first, *app.second.AppHMIType)) {
+ return false;
+ }
+
+ if (!SaveRequestType(app.first, *app.second.RequestType)) {
+ return false;
+ }
+
+ return true;
+}
+
+bool policy::SQLPTRepresentation::SaveDevicePolicy(
+ const policy_table::DevicePolicy& device) {
+ utils::dbms::SQLQuery app_query(db());
+ if (!app_query.Prepare(sql_pt::kInsertApplication)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement into application.");
+ return false;
+ }
+
+ app_query.Bind(0, kDeviceId);
+ app_query.Bind(1,
+ std::string(policy_table::EnumToJsonString(device.priority)));
+ app_query.Bind(2, false);
+ app_query.Bind(3, 0);
+ app_query.Bind(4, 0);
+ app_query.Bind(5);
+
+ if (!app_query.Exec() || !app_query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into application.");
+ return false;
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveAppGroup(
+ const std::string& app_id, const policy_table::Strings& app_groups) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kInsertAppGroup)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for app group");
+ return false;
+ }
+ LOG4CXX_INFO(logger_, "SaveAppGroup");
+ policy_table::Strings::const_iterator it;
+ for (it = app_groups.begin(); it != app_groups.end(); ++it) {
+ std::string ssss = *it;
+ LOG4CXX_INFO(logger_, "Group: " << ssss);
+ query.Bind(0, app_id);
+ query.Bind(1, *it);
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect insert into app group."
+ << query.LastError().text());
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveNickname(const std::string& app_id,
+ const policy_table::Strings& nicknames) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kInsertNickname)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for nickname");
+ return false;
+ }
+
+ policy_table::Strings::const_iterator it;
+ for (it = nicknames.begin(); it != nicknames.end(); ++it) {
+ query.Bind(0, app_id);
+ query.Bind(1, *it);
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into nickname.");
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveAppType(const std::string& app_id,
+ const policy_table::AppHMITypes& types) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kInsertAppType)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for app type");
+ return false;
+ }
+
+ policy_table::AppHMITypes::const_iterator it;
+ for (it = types.begin(); it != types.end(); ++it) {
+ query.Bind(0, app_id);
+ query.Bind(1, std::string(policy_table::EnumToJsonString(*it)));
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into app type.");
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveRequestType(
+ const std::string& app_id, const policy_table::RequestTypes& types) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kInsertRequestType)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for request types.");
+ return false;
+ }
+
+ policy_table::RequestTypes::const_iterator it;
+ for (it = types.begin(); it != types.end(); ++it) {
+ query.Bind(0, app_id);
+ query.Bind(1, std::string(policy_table::EnumToJsonString(*it)));
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into request types.");
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveModuleMeta(const policy_table::ModuleMeta& meta) {
+ utils::dbms::SQLQuery query(db());
+
+ if (!query.Prepare(sql_pt::kSaveModuleMeta)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for module_meta.");
+ return false;
+ }
+ const int64_t odometer = *(meta.pt_exchanged_at_odometer_x);
+
+ query.Bind(0, odometer);
+ query.Bind(1, *(meta.pt_exchanged_x_days_after_epoch));
+ query.Bind(2, *(meta.ignition_cycles_since_last_exchange));
+
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect update for module_meta.");
+ return false;
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveModuleConfig(
+ const policy_table::ModuleConfig& config) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kUpdateModuleConfig)) {
+ LOG4CXX_WARN(logger_, "Incorrect update statement for module config");
+ return false;
+ }
+
+ bool is_preloaded =
+ config.preloaded_pt.is_initialized() && *config.preloaded_pt;
+
+ query.Bind(0, is_preloaded);
+ query.Bind(1, config.exchange_after_x_ignition_cycles);
+ query.Bind(2, config.exchange_after_x_kilometers);
+ query.Bind(3, config.exchange_after_x_days);
+ query.Bind(4, config.timeout_after_x_seconds);
+ query.Bind(5, (*config.certificate));
+ config.vehicle_make.is_initialized() ? query.Bind(6, *(config.vehicle_make))
+ : query.Bind(6);
+ config.vehicle_model.is_initialized() ? query.Bind(7, *(config.vehicle_model))
+ : query.Bind(7);
+ config.vehicle_year.is_initialized() ? query.Bind(8, *(config.vehicle_year))
+ : query.Bind(8);
+
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect update module config");
+ return false;
+ }
+
+ if (!SaveSecondsBetweenRetries(config.seconds_between_retries)) {
+ return false;
+ }
+
+ if (!SaveNumberOfNotificationsPerMinute(
+ config.notifications_per_minute_by_priority)) {
+ return false;
+ }
+
+ if (!SaveServiceEndpoints(config.endpoints)) {
+ return false;
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveServiceEndpoints(
+ const policy_table::ServiceEndpoints& endpoints) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Exec(sql_pt::kDeleteEndpoint)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from endpoint.");
+ return false;
+ }
+
+ if (!query.Prepare(sql_pt::kInsertEndpoint)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for endpoint");
+ return false;
+ }
+
+ policy_table::ServiceEndpoints::const_iterator it;
+ for (it = endpoints.begin(); it != endpoints.end(); ++it) {
+ const policy_table::URLList& apps = it->second;
+ policy_table::URLList::const_iterator app_it;
+ for (app_it = apps.begin(); app_it != apps.end(); ++app_it) {
+ const policy_table::URL& urls = app_it->second;
+ policy_table::URL::const_iterator url_it;
+ for (url_it = urls.begin(); url_it != urls.end(); ++url_it) {
+ query.Bind(0, it->first);
+ query.Bind(1, *url_it);
+ query.Bind(2, app_it->first);
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into endpoint");
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveConsumerFriendlyMessages(
+ const policy_table::ConsumerFriendlyMessages& messages) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ // According CRS-2419 If there is no “consumer_friendly_messages” key,
+ // the current local consumer_friendly_messages section shall be maintained in
+ // the policy table. So it won't be changed/updated
+ if (messages.messages.is_initialized()) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Exec(sql_pt::kDeleteMessageString)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from message.");
+ return false;
+ }
+
+ if (query.Prepare(sql_pt::kUpdateVersion)) {
+ query.Bind(0, messages.version);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect update into version.");
+ return false;
+ }
+ } else {
+ LOG4CXX_WARN(logger_, "Incorrect update statement for version.");
+ return false;
+ }
+
+ policy_table::Messages::const_iterator it;
+ for (it = messages.messages->begin(); it != messages.messages->end();
+ ++it) {
+ if (!SaveMessageType(it->first)) {
+ return false;
+ }
+ const policy_table::Languages& langs = it->second.languages;
+ policy_table::Languages::const_iterator lang_it;
+ for (lang_it = langs.begin(); lang_it != langs.end(); ++lang_it) {
+ if (!SaveLanguage(lang_it->first)) {
+ return false;
+ }
+ if (!SaveMessageString(it->first, lang_it->first, lang_it->second)) {
+ return false;
+ }
+ }
+ }
+ } else {
+ LOG4CXX_INFO(logger_, "Messages list is empty");
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveMessageType(const std::string& type) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kInsertMessageType)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for message type.");
+ return false;
+ }
+
+ query.Bind(0, type);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into message type.");
+ return false;
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveLanguage(const std::string& code) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kInsertLanguage)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for language.");
+ return false;
+ }
+
+ query.Bind(0, code);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into language.");
+ return false;
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveMessageString(
+ const std::string& type,
+ const std::string& lang,
+ const policy_table::MessageString& strings) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kInsertMessageString)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for message.");
+ return false;
+ }
+
+ query.Bind(0, lang);
+ query.Bind(1, type);
+
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into message.");
+ return false;
+ }
+ return true;
+}
+
+bool SQLPTRepresentation::SaveSecondsBetweenRetries(
+ const policy_table::SecondsBetweenRetries& seconds) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Exec(sql_pt::kDeleteSecondsBetweenRetries)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from seconds between retries.");
+ return false;
+ }
+ if (!query.Prepare(sql_pt::kInsertSecondsBetweenRetry)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect insert statement for seconds between retries.");
+ return false;
+ }
+
+ for (uint32_t i = 0; i < seconds.size(); ++i) {
+ query.Bind(0, static_cast<int>(i));
+ query.Bind(1, seconds[i]);
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into seconds between retries.");
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveNumberOfNotificationsPerMinute(
+ const policy_table::NumberOfNotificationsPerMinute& notifications) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kInsertNotificationsByPriority)) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect insert statement for notifications by priority.");
+ return false;
+ }
+
+ policy_table::NumberOfNotificationsPerMinute::const_iterator it;
+ for (it = notifications.begin(); it != notifications.end(); ++it) {
+ query.Bind(0, it->first);
+ query.Bind(1, it->second);
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into notifications by priority.");
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveDeviceData(
+ const policy_table::DeviceData& devices) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kInsertDeviceData)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for device data.");
+ return false;
+ }
+
+ policy_table::DeviceData::const_iterator it;
+ for (it = devices.begin(); it != devices.end(); ++it) {
+ query.Bind(0, it->first);
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into device data.");
+ return false;
+ }
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::SaveUsageAndErrorCounts(
+ const policy_table::UsageAndErrorCounts& counts) {
+ const_cast<policy_table::UsageAndErrorCounts&>(counts).mark_initialized();
+ utils::dbms::SQLQuery query(db());
+ if (!query.Exec(sql_pt::kDeleteAppLevel)) {
+ LOG4CXX_WARN(logger_, "Incorrect delete from app level.");
+ return false;
+ }
+ if (!query.Prepare(sql_pt::kInsertAppLevel)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement for app level.");
+ return false;
+ }
+
+ policy_table::AppLevels::const_iterator it;
+ const policy_table::AppLevels& app_levels = *counts.app_level;
+ const_cast<policy_table::AppLevels&>(*counts.app_level).mark_initialized();
+ for (it = app_levels.begin(); it != app_levels.end(); ++it) {
+ query.Bind(0, it->first);
+ query.Bind(1, it->second.count_of_tls_errors);
+ if (!query.Exec() || !query.Reset()) {
+ LOG4CXX_WARN(logger_, "Incorrect insert into app level.");
+ return false;
+ }
+ }
+ return true;
+}
+
+void SQLPTRepresentation::IncrementIgnitionCycles() {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Exec(sql_pt::kIncrementIgnitionCycles)) {
+ LOG4CXX_WARN(logger_, "Failed incrementing ignition cycles");
+ }
+}
+
+void SQLPTRepresentation::ResetIgnitionCycles() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Exec(sql_pt::kResetIgnitionCycles)) {
+ LOG4CXX_WARN(logger_, "Failed to reset ignition cycles number.");
+ }
+}
+
+bool SQLPTRepresentation::UpdateRequired() const {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectFlagUpdateRequired) || !query.Exec()) {
+ LOG4CXX_WARN(logger_,
+ "Failed select update required flag from module meta");
+ return false;
+ }
+ return query.GetBoolean(0);
+}
+
+void SQLPTRepresentation::SaveUpdateRequired(bool value) {
+ utils::dbms::SQLQuery query(db());
+ // TODO(AOleynik): Quick fix, will be reworked
+ if (!query.Prepare(/*sql_pt::kUpdateFlagUpdateRequired*/
+ "UPDATE `module_meta` SET `flag_update_required` = ?")) {
+ LOG4CXX_WARN(logger_,
+ "Incorrect update into module meta (update_required): "
+ << strerror(errno));
+ return;
+ }
+ query.Bind(0, value);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed update module meta (update_required)");
+ }
+}
+
+bool SQLPTRepresentation::GetInitialAppData(const std::string& app_id,
+ StringArray* nicknames,
+ StringArray* app_types) {
+ LOG4CXX_INFO(logger_, "Getting initial application data.");
+ utils::dbms::SQLQuery app_names(db());
+ if (!app_names.Prepare(sql_pt::kSelectNicknames)) {
+ LOG4CXX_WARN(logger_, "Incorrect select from app nicknames");
+ return false;
+ }
+ utils::dbms::SQLQuery app_hmi_types(db());
+ if (!app_hmi_types.Prepare(sql_pt::kSelectAppTypes)) {
+ LOG4CXX_WARN(logger_, "Incorrect select from app types");
+ return false;
+ }
+ app_names.Bind(0, app_id);
+ while (app_names.Next()) {
+ nicknames->push_back(app_names.GetString(0));
+ }
+ app_names.Reset();
+ app_hmi_types.Bind(0, app_id);
+ while (app_hmi_types.Next()) {
+ app_types->push_back(app_hmi_types.GetString(0));
+ }
+ app_hmi_types.Reset();
+ return true;
+}
+
+bool SQLPTRepresentation::GetFunctionalGroupings(
+ policy_table::FunctionalGroupings& groups) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ return GatherFunctionalGroupings(&groups);
+}
+
+bool SQLPTRepresentation::GatherAppType(
+ const std::string& app_id, policy_table::AppHMITypes* app_types) const {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectAppTypes)) {
+ LOG4CXX_WARN(logger_, "Incorrect select from app types");
+ return false;
+ }
+
+ query.Bind(0, app_id);
+ while (query.Next()) {
+ policy_table::AppHMIType type;
+ if (!policy_table::EnumFromJsonString(query.GetString(0), &type)) {
+ return false;
+ }
+ app_types->push_back(type);
+ }
+ return true;
+}
+
+bool SQLPTRepresentation::GatherRequestType(
+ const std::string& app_id,
+ policy_table::RequestTypes* request_types) const {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectRequestTypes)) {
+ LOG4CXX_WARN(logger_, "Incorrect select from request types.");
+ return false;
+ }
+
+ query.Bind(0, app_id);
+ while (query.Next()) {
+ policy_table::RequestType type;
+ if (!policy_table::EnumFromJsonString(query.GetString(0), &type)) {
+ return false;
+ }
+ request_types->push_back(type);
+ }
+ return true;
+}
+
+bool SQLPTRepresentation::GatherNickName(
+ const std::string& app_id, policy_table::Strings* nicknames) const {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectNicknames)) {
+ LOG4CXX_WARN(logger_, "Incorrect select from app nicknames");
+ return false;
+ }
+
+ query.Bind(0, app_id);
+ while (query.Next()) {
+ nicknames->push_back(query.GetString(0));
+ }
+ return true;
+}
+
+bool SQLPTRepresentation::GatherAppGroup(
+ const std::string& app_id, policy_table::Strings* app_groups) const {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectAppGroups)) {
+ LOG4CXX_WARN(logger_, "Incorrect select from app groups");
+ return false;
+ }
+
+ query.Bind(0, app_id);
+ while (query.Next()) {
+ app_groups->push_back(query.GetString(0));
+ }
+ return true;
+}
+
+bool SQLPTRepresentation::SaveApplicationCustomData(const std::string& app_id,
+ bool is_revoked,
+ bool is_default,
+ bool is_predata) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kUpdateApplicationCustomData)) {
+ LOG4CXX_WARN(logger_, "Incorrect update in application");
+ return false;
+ }
+
+ query.Bind(0, is_revoked);
+ query.Bind(1, is_default);
+ query.Bind(2, is_predata);
+ query.Bind(3, app_id);
+
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed update in application");
+ return false;
+ }
+
+ return true;
+}
+
+bool SQLPTRepresentation::IsApplicationRevoked(
+ const std::string& app_id) const {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectApplicationRevoked)) {
+ LOG4CXX_WARN(logger_, "Incorrect select from is_revoked of application");
+ }
+
+ query.Bind(0, app_id);
+
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed select is_revoked of application");
+ return false;
+ }
+ return query.IsNull(0) ? false : query.GetBoolean(0);
+}
+bool SQLPTRepresentation::IsApplicationRepresented(
+ const std::string& app_id) const {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectApplicationRepresented)) {
+ LOG4CXX_WARN(logger_, "Incorrect select application by id");
+ return false;
+ }
+
+ query.Bind(0, app_id);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed select application by id");
+ return false;
+ }
+ return query.GetInteger(0) != 0;
+}
+
+bool SQLPTRepresentation::IsDefaultPolicy(const std::string& app_id) const {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectApplicationIsDefault)) {
+ LOG4CXX_WARN(logger_, "Incorrect select application by id");
+ return false;
+ }
+
+ query.Bind(0, app_id);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed select application by id");
+ return false;
+ }
+ return query.IsNull(0) ? false : query.GetBoolean(0);
+}
+
+bool SQLPTRepresentation::IsPredataPolicy(const std::string& app_id) const {
+ return false;
+}
+
+bool SQLPTRepresentation::SetDefaultPolicy(const std::string& app_id) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kDeleteAppGroupByApplicationId)) {
+ LOG4CXX_ERROR(logger_, "Incorrect statement to delete from app_group.");
+ return false;
+ }
+ query.Bind(0, app_id);
+ if (!query.Exec()) {
+ LOG4CXX_ERROR(logger_, "Failed deleting from app_group.");
+ return false;
+ }
+
+ if (!CopyApplication(kDefaultId, app_id)) {
+ return false;
+ }
+
+ SetPreloaded(false);
+
+ policy_table::Strings default_groups;
+ if (!GatherAppGroup(kDefaultId, &default_groups) ||
+ !SaveAppGroup(app_id, default_groups)) {
+ return false;
+ }
+ policy_table::RequestTypes request_types;
+ if (!GatherRequestType(kDefaultId, &request_types) ||
+ !SaveRequestType(app_id, request_types)) {
+ return false;
+ }
+ policy_table::AppHMITypes app_types;
+ if (!GatherAppType(kDefaultId, &app_types) ||
+ !SaveAppType(app_id, app_types)) {
+ return false;
+ }
+ return SetIsDefault(app_id, true);
+}
+
+bool SQLPTRepresentation::SetIsDefault(const std::string& app_id,
+ bool is_default) const {
+ LOG4CXX_TRACE(logger_, "Set flag is_default of application");
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kUpdateIsDefault)) {
+ LOG4CXX_WARN(logger_, "Incorect statement for updating is_default");
+ return false;
+ }
+
+ query.Bind(0, is_default);
+ query.Bind(1, app_id);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed update is_default");
+ return false;
+ }
+ return true;
+}
+
+void SQLPTRepresentation::RemoveDB() const {
+ file_system::DeleteFile(db_->get_path());
+}
+
+bool SQLPTRepresentation::IsDBVersionActual() const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kSelectDBVersion) || !query.Exec()) {
+ LOG4CXX_ERROR(logger_,
+ "Failed to get DB version: " << query.LastError().text());
+ return false;
+ }
+
+ const int32_t saved_db_version = query.GetInteger(0);
+ const int32_t current_db_version = GetDBVersion();
+ LOG4CXX_DEBUG(logger_,
+ "Saved DB version is: " << saved_db_version
+ << ". Current DB vesion is: "
+ << current_db_version);
+
+ return current_db_version == saved_db_version;
+}
+
+bool SQLPTRepresentation::UpdateDBVersion() const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kUpdateDBVersion)) {
+ LOG4CXX_ERROR(logger_,
+ "Incorrect DB version query: " << query.LastError().text());
+ return false;
+ }
+
+ const int32_t db_version = GetDBVersion();
+ LOG4CXX_DEBUG(logger_, "DB version will be updated to: " << db_version);
+ query.Bind(0, db_version);
+
+ if (!query.Exec()) {
+ LOG4CXX_ERROR(logger_,
+ "DB version getting failed: " << query.LastError().text());
+ return false;
+ }
+
+ return true;
+}
+
+const int32_t SQLPTRepresentation::GetDBVersion() const {
+ return utils::Djb2HashFromString(sql_pt::kCreateSchema);
+}
+
+utils::dbms::SQLDatabase* SQLPTRepresentation::db() const {
+#ifdef __QNX__
+ utils::dbms::SQLDatabase* db = new utils::dbms::SQLDatabase(kDatabaseName);
+ db->Open();
+ return db;
+#else
+ return db_;
+#endif
+}
+
+bool SQLPTRepresentation::CopyApplication(const std::string& source,
+ const std::string& destination) {
+ utils::dbms::SQLQuery source_app(db());
+ if (!source_app.Prepare(sql_pt::kSelectApplicationFull)) {
+ LOG4CXX_WARN(logger_, "Incorrect select statement from application.");
+ return false;
+ }
+ source_app.Bind(0, source);
+ if (!source_app.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed selecting from application.");
+ return false;
+ }
+
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kInsertApplicationFull)) {
+ LOG4CXX_WARN(logger_, "Incorrect insert statement into application.");
+ return false;
+ }
+ query.Bind(0, destination);
+ source_app.IsNull(0) ? query.Bind(1)
+ : query.Bind(1, source_app.GetBoolean(0));
+ source_app.IsNull(1) ? query.Bind(2)
+ : query.Bind(2, source_app.GetBoolean(1));
+ source_app.IsNull(2) ? query.Bind(3) : query.Bind(3, source_app.GetString(2));
+ source_app.IsNull(3) ? query.Bind(4) : query.Bind(4, source_app.GetString(3));
+ source_app.IsNull(4) ? query.Bind(5)
+ : query.Bind(5, source_app.GetBoolean(4));
+ source_app.IsNull(5) ? query.Bind(6)
+ : query.Bind(6, source_app.GetBoolean(5));
+ source_app.IsNull(6) ? query.Bind(7)
+ : query.Bind(7, source_app.GetBoolean(6));
+ query.Bind(8, source_app.GetInteger(7));
+ query.Bind(9, source_app.GetInteger(8));
+ source_app.IsNull(9) ? query.Bind(10)
+ : query.Bind(10, source_app.GetString(9));
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed inserting into application.");
+ return false;
+ }
+ return true;
+}
+
+void SQLPTRepresentation::SetPreloaded(bool value) {
+ utils::dbms::SQLQuery query(db());
+ if (!query.Prepare(sql_pt::kUpdatePreloaded)) {
+ LOG4CXX_WARN(logger_, "Incorrect statement of updating preloaded.");
+ return;
+ }
+
+ query.Bind(0, value);
+ if (!query.Exec()) {
+ LOG4CXX_WARN(logger_, "Failed updating preloaded.");
+ return;
+ }
+}
+
+bool SQLPTRepresentation::SetVINValue(const std::string& value) {
+ return true;
+}
+
+} // namespace policy
diff --git a/src/components/policy/src/update_status_manager.cc b/src/components/policy/src/update_status_manager.cc
new file mode 100644
index 0000000000..f821b9655b
--- /dev/null
+++ b/src/components/policy/src/update_status_manager.cc
@@ -0,0 +1,270 @@
+/*
+ Copyright (c) 2014, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "policy/update_status_manager.h"
+#include "policy/policy_listener.h"
+#include "utils/logger.h"
+
+namespace policy {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "Policy")
+
+UpdateStatusManager::UpdateStatusManager()
+ : listener_(NULL)
+ , exchange_in_progress_(false)
+ , update_required_(false)
+ , update_scheduled_(false)
+ , exchange_pending_(false)
+ , apps_search_in_progress_(false)
+ , last_update_status_(policy::StatusUnknown) {
+ update_status_thread_delegate_ = new UpdateThreadDelegate(this);
+ thread_ = threads::CreateThread("UpdateStatusThread",
+ update_status_thread_delegate_);
+ thread_->start();
+}
+
+UpdateStatusManager::~UpdateStatusManager() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK(update_status_thread_delegate_);
+ DCHECK(thread_);
+ thread_->join();
+ delete update_status_thread_delegate_;
+ threads::DeleteThread(thread_);
+}
+
+void UpdateStatusManager::set_listener(PolicyListener* listener) {
+ listener_ = listener;
+}
+
+void UpdateStatusManager::OnUpdateSentOut(uint32_t update_timeout) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK(update_status_thread_delegate_);
+ const unsigned milliseconds_in_second = 1000;
+ update_status_thread_delegate_->updateTimeOut(update_timeout *
+ milliseconds_in_second);
+ set_exchange_in_progress(true);
+ set_exchange_pending(true);
+ set_update_required(false);
+}
+
+void UpdateStatusManager::OnUpdateTimeoutOccurs() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ set_update_required(true);
+ set_exchange_in_progress(false);
+ set_exchange_pending(false);
+ DCHECK(update_status_thread_delegate_);
+ update_status_thread_delegate_->updateTimeOut(0); // Stop Timer
+}
+
+void UpdateStatusManager::OnValidUpdateReceived() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ update_status_thread_delegate_->updateTimeOut(0); // Stop Timer
+ set_exchange_pending(false);
+ set_exchange_in_progress(false);
+}
+
+void UpdateStatusManager::OnWrongUpdateReceived() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ update_status_thread_delegate_->updateTimeOut(0); // Stop Timer
+ set_update_required(true);
+ set_exchange_in_progress(false);
+ set_exchange_pending(false);
+}
+
+void UpdateStatusManager::OnResetDefaultPT(bool is_update_required) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ exchange_in_progress_ = false;
+ update_required_ = is_update_required;
+ exchange_pending_ = false;
+ last_update_status_ = policy::StatusUnknown;
+}
+
+void UpdateStatusManager::OnResetRetrySequence() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (exchange_in_progress_) {
+ set_exchange_pending(true);
+ }
+ set_update_required(true);
+}
+
+void UpdateStatusManager::OnNewApplicationAdded() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ set_update_required(true);
+}
+
+void UpdateStatusManager::OnPolicyInit(bool is_update_required) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ update_required_ = is_update_required;
+}
+
+PolicyTableStatus UpdateStatusManager::GetUpdateStatus() const {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!exchange_in_progress_ && !exchange_pending_ && !update_required_) {
+ return PolicyTableStatus::StatusUpToDate;
+ }
+
+ if (update_required_ && !exchange_in_progress_ && !exchange_pending_) {
+ return PolicyTableStatus::StatusUpdateRequired;
+ }
+
+ return PolicyTableStatus::StatusUpdatePending;
+}
+
+bool UpdateStatusManager::IsUpdateRequired() const {
+ return update_required_ || update_scheduled_;
+}
+
+bool UpdateStatusManager::IsUpdatePending() const {
+ return exchange_pending_;
+}
+
+void UpdateStatusManager::ScheduleUpdate() {
+ update_scheduled_ = true;
+ update_required_ = true;
+}
+
+void UpdateStatusManager::ResetUpdateSchedule() {
+ update_scheduled_ = false;
+}
+
+std::string UpdateStatusManager::StringifiedUpdateStatus() const {
+ switch (GetUpdateStatus()) {
+ case policy::StatusUpdatePending:
+ return "UPDATING";
+ case policy::StatusUpdateRequired:
+ return "UPDATE_NEEDED";
+ case policy::StatusUpToDate:
+ return "UP_TO_DATE";
+ default: { return "UNKNOWN"; }
+ }
+}
+
+void policy::UpdateStatusManager::OnAppsSearchStarted() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
+ apps_search_in_progress_ = true;
+}
+
+void policy::UpdateStatusManager::OnAppsSearchCompleted() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
+ apps_search_in_progress_ = false;
+}
+
+bool policy::UpdateStatusManager::IsAppsSearchInProgress() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(apps_search_in_progress_lock_);
+ return apps_search_in_progress_;
+}
+
+void UpdateStatusManager::CheckUpdateStatus() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ policy::PolicyTableStatus status = GetUpdateStatus();
+ if (listener_ && last_update_status_ != status) {
+ LOG4CXX_INFO(logger_, "Send OnUpdateStatusChanged");
+ listener_->OnUpdateStatusChanged(StringifiedUpdateStatus());
+ }
+ last_update_status_ = status;
+}
+
+void UpdateStatusManager::set_exchange_in_progress(bool value) {
+ sync_primitives::AutoLock lock(exchange_in_progress_lock_);
+ LOG4CXX_INFO(logger_,
+ "Exchange in progress value is:" << std::boolalpha << value);
+ exchange_in_progress_ = value;
+ CheckUpdateStatus();
+}
+
+void UpdateStatusManager::set_exchange_pending(bool value) {
+ sync_primitives::AutoLock lock(exchange_pending_lock_);
+ LOG4CXX_INFO(logger_,
+ "Exchange pending value is:" << std::boolalpha << value);
+ exchange_pending_ = value;
+ CheckUpdateStatus();
+}
+
+void UpdateStatusManager::set_update_required(bool value) {
+ sync_primitives::AutoLock lock(update_required_lock_);
+ LOG4CXX_INFO(logger_, "Update required value is:" << std::boolalpha << value);
+ update_required_ = value;
+ CheckUpdateStatus();
+}
+
+UpdateStatusManager::UpdateThreadDelegate::UpdateThreadDelegate(
+ UpdateStatusManager* update_status_manager)
+ : timeout_(0)
+ , stop_flag_(false)
+ , state_lock_(true)
+ , update_status_manager_(update_status_manager) {
+ LOG4CXX_INFO(logger_, "Create UpdateThreadDelegate");
+}
+
+UpdateStatusManager::UpdateThreadDelegate::~UpdateThreadDelegate() {
+ LOG4CXX_INFO(logger_, "Delete UpdateThreadDelegate");
+}
+
+void UpdateStatusManager::UpdateThreadDelegate::threadMain() {
+ LOG4CXX_DEBUG(logger_, "UpdateStatusManager thread started (started normal)");
+ sync_primitives::AutoLock auto_lock(state_lock_);
+ while (false == stop_flag_) {
+ if (timeout_ > 0) {
+ LOG4CXX_DEBUG(logger_, "Timeout is greater then 0");
+ sync_primitives::ConditionalVariable::WaitStatus wait_status =
+ termination_condition_.WaitFor(auto_lock, timeout_);
+ if (sync_primitives::ConditionalVariable::kTimeout == wait_status) {
+ if (update_status_manager_) {
+ update_status_manager_->OnUpdateTimeoutOccurs();
+ }
+ }
+ } else {
+ // Time is not active, wait, while timeout will be seted,
+ // or UpdateStatusManager will be deleted
+ termination_condition_.Wait(auto_lock);
+ }
+ }
+}
+
+void UpdateStatusManager::UpdateThreadDelegate::exitThreadMain() {
+ sync_primitives::AutoLock auto_lock(state_lock_);
+ stop_flag_ = true;
+ LOG4CXX_INFO(logger_, "before notify");
+ termination_condition_.NotifyOne();
+}
+
+void UpdateStatusManager::UpdateThreadDelegate::updateTimeOut(
+ const uint32_t timeout_ms) {
+ sync_primitives::AutoLock auto_lock(state_lock_);
+ timeout_ = timeout_ms;
+ termination_condition_.NotifyOne();
+}
+
+} // namespace policy
diff --git a/src/components/policy/src/usage_statistics/counter.cc b/src/components/policy/src/usage_statistics/counter.cc
new file mode 100644
index 0000000000..c5d7eaf9df
--- /dev/null
+++ b/src/components/policy/src/usage_statistics/counter.cc
@@ -0,0 +1,121 @@
+/*
+ Copyright (c) 2013, Ford Motor Company
+ All rights reserved.
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+
+ Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following
+ disclaimer in the documentation and/or other materials provided with the
+ distribution.
+
+ Neither the name of the Ford Motor Company nor the names of its contributors
+ may be used to endorse or promote products derived from this software
+ without specific prior written permission.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_INCLUDE_POLICY_STATISTICS_MANAGER_H_
+#define SRC_COMPONENTS_POLICY_INCLUDE_POLICY_STATISTICS_MANAGER_H_
+
+#include <cassert>
+#include "policy/usage_statistics/counter.h"
+#include "utils/date_time.h"
+#include "utils/make_shared.h"
+#include "utils/timer_task_impl.h"
+
+namespace usage_statistics {
+
+GlobalCounter::GlobalCounter(
+ utils::SharedPtr<StatisticsManager> statistics_manager,
+ GlobalCounterId counter_type)
+ : counter_type_(counter_type), statistics_manager_(statistics_manager) {}
+
+void GlobalCounter::operator++() const {
+ if (statistics_manager_) {
+ statistics_manager_->Increment(counter_type_);
+ }
+}
+
+AppCounter::AppCounter(utils::SharedPtr<StatisticsManager> statistics_manager,
+ const std::string& app_id,
+ AppCounterId counter_type)
+ : app_id_(app_id)
+ , counter_type_(counter_type)
+ , statistics_manager_(statistics_manager) {}
+
+void AppCounter::operator++() const {
+ if (statistics_manager_) {
+ statistics_manager_->Increment(app_id_, counter_type_);
+ }
+}
+
+AppInfo::AppInfo(utils::SharedPtr<StatisticsManager> statistics_manager,
+ const std::string& app_id,
+ AppInfoId info_type)
+ : app_id_(app_id)
+ , info_type_(info_type)
+ , statistics_manager_(statistics_manager) {}
+
+void AppInfo::Update(const std::string& new_info) const {
+ if (statistics_manager_) {
+ statistics_manager_->Set(app_id_, info_type_, new_info);
+ }
+}
+
+AppStopwatchImpl::AppStopwatchImpl(
+ utils::SharedPtr<StatisticsManager> statistics_manager,
+ const std::string& app_id)
+ : app_id_(app_id)
+ , stopwatch_type_(SECONDS_HMI_NONE)
+ , statistics_manager_(statistics_manager)
+ , timer_("HMI levels timer",
+ new timer::TimerTaskImpl<AppStopwatchImpl>(
+ this, &AppStopwatchImpl::WriteTime))
+ , time_out_(60) {}
+
+AppStopwatchImpl::AppStopwatchImpl(
+ utils::SharedPtr<StatisticsManager> statistics_manager,
+ const std::string& app_id,
+ uint32_t timeout)
+ : app_id_(app_id)
+ , stopwatch_type_(SECONDS_HMI_NONE)
+ , statistics_manager_(statistics_manager)
+ , timer_("HMI levels timer",
+ new timer::TimerTaskImpl<AppStopwatchImpl>(
+ this, &AppStopwatchImpl::WriteTime))
+ , time_out_(timeout) {}
+
+void AppStopwatchImpl::Start(AppStopwatchId stopwatch_type) {
+ stopwatch_type_ = stopwatch_type;
+ timer_.Start(time_out_ * date_time::DateTime::MILLISECONDS_IN_SECOND, false);
+}
+
+void AppStopwatchImpl::Switch(AppStopwatchId stopwatch_type) {
+ Start(stopwatch_type);
+}
+
+void AppStopwatchImpl::WriteTime() {
+ if (statistics_manager_) {
+ statistics_manager_->Add(app_id_, stopwatch_type_, time_out_);
+ }
+}
+
+} // namespace usage_statistics
+
+#endif // SRC_COMPONENTS_POLICY_INCLUDE_POLICY_STATISTICS_MANAGER_H_
diff --git a/src/components/policy/test/CMakeLists.txt b/src/components/policy/test/CMakeLists.txt
index d23a50e7fe..95a61f92ff 100644
--- a/src/components/policy/test/CMakeLists.txt
+++ b/src/components/policy/test/CMakeLists.txt
@@ -30,16 +30,14 @@
include_directories(
include
+ ${COMPONENTS_DIR}
${GMOCK_INCLUDE_DIRECTORY}
${JSONCPP_INCLUDE_DIRECTORY}
- ${COMPONENTS_DIR}/policy/src/policy/include/
- ${COMPONENTS_DIR}/policy/src/policy/sqlite_wrapper/include
- ${COMPONENTS_DIR}/policy/src/policy/qdb_wrapper/include
- ${COMPONENTS_DIR}/policy/src/policy/usage_statistics/include
+ ${COMPONENTS_DIR}/policy/include
${COMPONENTS_DIR}/rpc_base/include
${COMPONENTS_DIR}/config_profile/include
${COMPONENTS_DIR}/utils/include/
- ${COMPONENTS_DIR}/policy/src/policy/policy_table/
+ ${COMPONENTS_DIR}/policy/test/include/
)
set(testLibraries
@@ -50,46 +48,31 @@ set(testLibraries
)
set(testSources
- usage_statistics_test.cc
- shared_library_test.cc
- generated_code_test.cc
- #policy_manager_impl_test.cc
+ counter_test.cc
+ shared_library_test.cc
+ generated_code_test.cc
+ policy_manager_impl_test.cc
+ update_status_manager_test.cc
)
- include_directories(${COMPONENTS_DIR}/policy/src/policy/policy_table/table_struct)
- list (APPEND testSources
- sql_pt_representation_test.cc
- )
-
-if (CMAKE_SYSTEM_NAME STREQUAL "QNX")
- list(REMOVE_ITEM testLibraries dl)
- # --- Tests for QDB Wrapper
- include_directories(../src/policy/qdb_wrapper/include)
- list (APPEND testSources
- qdb_wrapper/sql_database_test.cc
- qdb_wrapper/sql_query_test.cc
- )
- file(COPY qdbserver.sh DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
- file(COPY test-qdb.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
- file(COPY policy.sql DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
-else ()
- # --- Tests for SQLite Wrapper
- find_package(Sqlite3 REQUIRED)
- include_directories(../src/policy/sqlite_wrapper/include)
- list (APPEND testSources
- sqlite_wrapper/sql_database_test.cc
- sqlite_wrapper/sql_query_test.cc
- generated_code_with_sqlite_test.cc
-
- # TODO{ALeshin} AssertTrue in SetUpTestCase() return false
- #policy_manager_impl_stress_test.cc
- )
- list (APPEND testLibraries sqlite3)
-endif()
+list (APPEND testSources
+ sql_pt_representation_test.cc
+)
create_test("policy_test" "${testSources}" "${testLibraries}")
file(COPY valid_sdl_pt_update.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
file(COPY sdl_preloaded_pt.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+file(COPY PTU.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+file(COPY PTU2.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+file(COPY PTU3.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+file(COPY PTU4.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+file(COPY ptu_requestType.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+file(COPY ptu2_requestType.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
file(COPY log4cxx.properties DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
file(COPY smartDeviceLink.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+file(COPY smartDeviceLink2.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+file(COPY smartDeviceLink3.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+file(COPY sdl_pt_first_update.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+file(COPY sdl_pt_second_update.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+file(COPY sdl_pt_update.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
diff --git a/src/components/policy/test/PTU.json b/src/components/policy/test/PTU.json
new file mode 100644
index 0000000000..a200667e54
--- /dev/null
+++ b/src/components/policy/test/PTU.json
@@ -0,0 +1,1949 @@
+ {
+ "policy_table": {
+ "module_config": {
+ "preloaded_pt": true,
+ "preloaded_date": "2015-12-08",
+ "exchange_after_x_ignition_cycles": 100,
+ "exchange_after_x_kilometers": 1800,
+ "exchange_after_x_days": 30,
+ "timeout_after_x_seconds": 60,
+ "seconds_between_retries": [1,
+ 5,
+ 25,
+ 125,
+ 625],
+ "endpoints": {
+ "0x07": {
+ "default": ["http://policies.telematics.ford.com/api/policies"]
+ }
+ },
+ "notifications_per_minute_by_priority": {
+ "EMERGENCY": 60,
+ "NAVIGATION": 15,
+ "COMMUNICATION": 6,
+ "NORMAL": 4,
+ "NONE": 0
+ }
+ },
+ "functional_groupings": {
+ "Base-4": {
+ "rpcs": {
+ "AddCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "AddSubMenu": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "Alert": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "ChangeRegistration": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "CreateInteractionChoiceSet": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "DeleteInteractionChoiceSet": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteSubMenu": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "EndAudioPassThru": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "GenericResponse": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ListFiles": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAudioPassThru": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnButtonEvent": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "OnButtonPress": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "OnCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnDriverDistraction": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHashChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "PerformAudioPassThru": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "PerformInteraction": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "PutFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ResetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ScrollableMessage": {
+ "hmi_levels": ["FULL"]
+ },
+ "SetAppIcon": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "SetMediaClockTimer": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "Show": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "Slider": {
+ "hmi_levels": ["FULL"]
+ },
+ "Speak": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "SubscribeButton": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "SystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnsubscribeButton": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "Location-1": {
+ "user_consent_prompt": "Location",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ }
+ }
+ },
+ "Notifications": {
+ "user_consent_prompt": "Notifications",
+ "rpcs": {
+ "Alert": {
+ "hmi_levels": ["BACKGROUND"]
+ }
+ }
+ },
+ "DrivingCharacteristics-3": {
+ "user_consent_prompt": "DrivingCharacteristics",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ }
+ }
+ },
+ "VehicleInfo-3": {
+ "user_consent_prompt": "VehicleInfo",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"]
+ }
+ }
+ },
+ "PropriataryData-1": {
+ "rpcs": {
+ "DiagnosticMessage": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "GetDTCs": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ReadDID": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "Emergency-1": {
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ }
+ }
+ },
+ "Navigation-1": {
+ "rpcs": {
+ "AlertManeuver": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ShowConstantTBT": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "UpdateTurnList": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "DataConsent-2": {
+ "user_consent_prompt": "DataConsent",
+ "rpcs": null
+ },
+ "BaseBeforeDataConsent": {
+ "rpcs": {
+ "ChangeRegistration": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "DeleteFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ListFiles": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHashChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "PutFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetAppIcon": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ }
+ }
+ }
+ },
+ "consumer_friendly_messages": {
+ "version": "001.001.019",
+ "messages": {
+ "AppPermissions": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% benötigt die folgenden Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Wenn Sie Ja drücken, erklären Sie sich damit einverstanden, dass %vehicleMake% nicht für Schäden oder Verletzungen der Privatsphäre haftet, die im Zusammenhang mit der Nutzung Ihrer Benutzerdaten durch %appName% entstehen. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab.",
+ "line1": "Zugriffsanfrage(n)",
+ "line2": "erlauben?"
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. Please press yes to allow or no to deny.",
+ "line1": "Grant Requested",
+ "line2": "Permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. \n\nIf you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "es-en": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?",
+ "textBody": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar. \n\n Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando el uso de los siguientes permisos e información del vehículo: %functionalGroupLabels%. Si pulsa sí, acepta que %vehicleMake% no será responsable de los daños o la pérdida de privacidad relacionados con el uso de sus datos por parte de %appName%. Pulse sí para permitir o no para denegar.",
+ "line1": "¿Conceder permisos",
+ "line2": "solicitados?"
+ },
+ "es-mx": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?"
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)",
+ "textBody": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)"
+ },
+ "it-it": {
+ "tts": "%appName% richiede l'uso delle seguenti informazioni e autorizzazioni sul veicolo: %functionalGroupLabels%. Se si preme Sì, si acconsente che %vehicleMake% non sarà responsabile per danni o perdita di privacy in relazione all'impiego dei dati da parte di %appName%. Premere Sì per consentire e No per negare.",
+ "line1": "Concedi autorizzaz.",
+ "line2": "richiesta(e)?"
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. Als u op Ja drukt, gaat u ermee akkoord dat %vehicleMake% in geen geval aansprakelijk gesteld kan worden voor schade of verlies van privacy als gevolg van het feit dat %appName% gebruik maakt van uw gegevens. Druk op Ja om dit toe te staan of Nee om te weigeren.",
+ "line1": "Aangevraagde",
+ "line2": "permissie(s) verlenen?"
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz pozwoleń: %functionalGroupLabels%. Naciśnięcie TAK oznacza zgodę na fakt, iż %vehicleMake% nie będzie ponosić odpowiedzialności za szkody ani utratę prywatności w związku z wykorzystaniem przez %appName% danych, należących do użytkownika. Naciśnij TAK w celu udzielenia zgody lub NIE w celu odrzucenia żądania.",
+ "line1": "Udzielić żądanych",
+ "line2": "pozwoleń?"
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando o uso das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se pressionar sim, você concorda que a %vehicleMake% não será responsável por danos ou perdas de privacidade relacionados ao uso dos seus dados por %appName%. Pressione sim para permitir ou não para negar.",
+ "line1": "Conceder permissão",
+ "line2": "solicitada?"
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar a utilização das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se premir “Sim”, concorda que %vehicleMake% não será responsável por quaisquer danos ou perda de privacidade relacionada com a utilização dos seus dados por parte de %appName%. Prima “Sim” para permitir ou “Não” para recusar.",
+ "line1": "Conceder permiss.",
+ "line2": "solicitada(s)?"
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Нажатием \"\"да\"\", Вы соглашаетесь, что %vehicleMake% не будет нести ответственность за какие-либо убытки или потерю прайвеси, связанные с использованием Ваших данных компанией %appName%. Нажмите \"\"Да\"\", если Вы согласны, или \"\"Нет\"\" - если не согласны.",
+ "line1": "Предост. заправш.",
+ "line2": "разрешения?"
+ },
+ "sv-se": {
+ "tts": "%appName% begär att få tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Om du trycker Ja godkänner du att %vehicleMake% ska hållas skadeslös för alla skador som kan uppstå eller eventuella integritetsintrång som uppstår när %appName% använder dina data. Tryck Ja för att godkänna eller Nej för att neka.",
+ "line1": "Vill du ge",
+ "line2": "tillstånd?"
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri kullanma isteğinde bulunuyor: %functionalGroupLabels%. Evet'e basarsanız, %appName%'in verilerinizi kullanması sonucunda oluşabilecek hasarlardan veya gizlilik kaybından %vehicleMake%'in sorumlu olmayacağını kabul etmiş olacaksınız. Lütfen kabul etmek için Evet'e veya reddetmek için Hayır'a basın.",
+ "line1": "İstenen izinler",
+ "line2": "verilsin mi?"
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求使用下列车辆信息和权限: %functionalGroupLabels%。如果您按“是”,则表示您同意。 %vehicleMake% 将不会对因 %appName% 使用您的数据而引起的任何损毁或隐私损失负责。 请按“是”允许或按“否”拒绝。",
+ "line1": "是否允许请求的",
+ "line2": "权限?"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。按「是」,表示您同意,如因 %appName% 使用您的資料導致任何損害或損失,%vehicleMake% 將不負賠償責任。同意請按「是」,拒絕請按「否」。",
+ "line1": "允許",
+ "line2": "授權請求?"
+ }
+ }
+ },
+ "AppPermissionsHelp": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% fordert folgende Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Im Einstellungsmenü der mobilen Apps können Sie diese Berechtigungen ändern und sich detaillierte Beschreibungen anhören. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press yes to grant permissions or no to deny."
+ },
+ "es-en": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando los siguientes permisos e información del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y escuchar descripciones detalladas en el menú de configuración de la aplicación móvil. Pulse sí para conceder el permiso o no para denegarlo."
+ },
+ "es-mx": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "it-it": {
+ "tts": "%appName% richiede le seguenti informazioni e autorizzazioni riguardo il veicolo: %functionalGroupLabels%. È possibile modificare tali autorizzazioni e ascoltare descrizioni dettagliate nel menu impostazioni delle app mobili. Premere Sì per concedere le autorizzazioni e No per negarle."
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. U kunt deze toestemmingen wijzigen en gedetailleerde beschrijvingen beluisteren in het instellingenmenu voor mobiele apps. Druk op Ja om permissies te verlenen of op Nee om te weigeren."
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz zezwoleń: %functionalGroupLabels%. W menu ustawień aplikacji mobilnych można zmienić owe zezwolenia i usłyszeć ich szczegółowy opis. Naciśnij TAK, aby wyrazić zgodę lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando as seguintes informações e permissões do veículo: %functionalGroupLabels%. Você pode alterar estas permissões e ouvir descrições detalhadas no menu de configurações de aplicativos móveis. Pressione sim para conceder as permissões ou não para negar."
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar as seguintes informações e permissões do veículo: %functionalGroupLabels%. Pode alterar estas permissões e ouvir descrições detalhadas no menu de definições das aplicações móveis. Prima \"\"Sim\"\" para permitir ou \"\"Não\"\" para recusar."
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Вы можете изменить эти разрешения и прослушать подробные их описания в меню настроек мобильного приложения. Нажмите \"\"да\"\", чтобы предоставить разрешения, или \"\"нет\"\", чтобы не предоставлять."
+ },
+ "sv-se": {
+ "tts": "%appName% begär tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Du kan ändra tillstånden och höra detaljerade beskrivningar i menyn för mobilappsinställningar. Tryck Ja för att ge tillstånd eller Nej för att neka."
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri istiyor: %functionalGroupLabels%. Bu izinleri değiştirebilir ve mobil uygulamalar ayarlar menüsünden ayrıntılı açıklamaları dinleyebilirsiniz. Lütfen izin vermek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求下列车辆信息和权限: %functionalGroupLabels%。您可在移动应用程序设置菜单中更改这些权限,并听取详细说明。请按“是”允许权限或按“否”拒绝。"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。您可在行動應用程式設定清單中更改這些許可,並聆聽詳細說明。給予許可請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsRevoked": {
+ "languages": {
+ "de-de": {
+ "tts": "Die Autorisierungsdaten der App wurden geändert. %appName% hat keinen Zugriff auf %functionalGroupLabels% mehr. Installieren Sie die neueste Version der App auf Ihrem Gerät.."
+ },
+ "en-au": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-gb": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-ie": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-us": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "es-en": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "es-es": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de que tiene la versión más reciente de la aplicación instalada en su dispositivo móvil."
+ },
+ "es-mx": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "fr-ca": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "fr-fr": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "it-it": {
+ "tts": "Le autorizzazioni dell'app sono cambiate. %appName% non è più in grado di accedere a %functionalGroupLabels%. Assicurarsi di avere la versione più recente dell'app installata sul dispositivo mobile."
+ },
+ "nl-nl": {
+ "tts": "De app-autorisaties zijn gewijzigd. %appName% heeft geen toegang meer tot %functionalGroupLabels%. Zorg ervoor dat u de meest recente app-versie op uw mobiele apparaat geïnstalleerd hebt."
+ },
+ "pl-pl": {
+ "tts": "Dane dostępu aplikacji zostały zmienione. %appName% nie ma już dostępu do %functionalGroupLabels%. Sprawdź, czy na telefonie komórkowym zainstalowano najnowszą wersję aplikacji."
+ },
+ "pt-br": {
+ "tts": "As autorizações dos aplicativos foram alteradas. %appName% não pode mais acessar %functionalGroupLabels%. Certifique-se de que a versão mais recente do aplicativo está instalada no seu dispositivo móvel."
+ },
+ "pt-pt": {
+ "tts": "As autorizações das aplicações mudaram. %appName% já não consegue aceder a %functionalGroupLabels%. Certifique-se de que tem a última versão da aplicação no seu dispositivo móvel."
+ },
+ "ru-ru": {
+ "tts": "Авторизации приложения изменены. %appName% больше не имеет доступа к %functionalGroupLabels%. Убедитесь, что на вашем мобильном устройстве установлена самая новая версия приложения."
+ },
+ "sv-se": {
+ "tts": "Appens behörigheter har ändrats. %appName% har inte längre åtkomst till %functionalGroupLabels%. Kontrollera att du har installerat den senaste versionen av appen på mobilenheten."
+ },
+ "tr-tr": {
+ "tts": "Uygulama yetkileri değişti. %appName% artık %functionalGroupLabels%'e erişemeyecek. Lütfen mobil aygıtınızda en son uygulama sürümünün yüklü olduğundan emin olun."
+ },
+ "zh-cn": {
+ "tts": "应用程序授权已变更。 %appName% 将不能再访问 %functionalGroupLabels%。 请确认您的移动设备上安装的应用程序是最新版本。"
+ },
+ "zh-tw": {
+ "tts": "應用程式授權已改變。%appName% 已無法進入 %functionalGroupLabels%。請確認您的行動裝置上安裝了最新版應用程式。"
+ }
+ }
+ },
+ "AppUnauthorized": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% ist nicht autorisiert und wird nicht mit SYNC funktionieren.",
+ "line1": "nicht autorisiert"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized",
+ "textBody": "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "Not Authorized",
+ "textBody": "This version of %appName% is no longer authorized to work with AppLink. Please update to the latest version of %appName%."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada",
+ "textBody": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no está autorizada y no funcionará con SYNC.",
+ "line1": "No autorizada"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada"
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée",
+ "textBody": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è autorizzata e non funziona con il SYNC.",
+ "line1": "non autorizzata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% is niet geautoriseerd en werkt niet met SYNC.",
+ "line1": "niet geautoriseerd"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie posiada autoryzacji i nie będzie działać z SYNC.",
+ "line1": "brak autoryzacji"
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não tem autorização e não funcionará com o SYNC.",
+ "line1": "não autorizado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não está autorizada e não funcionará com o SYNC.",
+ "line1": "não autorizada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не авторизирована и не будет работать с SYNC.",
+ "line1": "не авторизировано"
+ },
+ "sv-se": {
+ "tts": "Den här versionen av %appName% är inte godkänd och fungerar inte med SYNC.",
+ "line1": "är ej godkänd"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümüne izin verilmediğinden SYNC ile çalışamaz.",
+ "line1": "için izin yok"
+ },
+ "zh-cn": {
+ "tts": "此版本的%appName% 未得到授权,无法在SYNC上使用。",
+ "line1": "未得到授权"
+ },
+ "zh-tw": {
+ "tts": "%appName% 的版本未獲得授權,將無法透過 SYNC 使用。",
+ "line1": "無授權"
+ }
+ }
+ },
+ "AppUnsupported": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% wird von SYNC nicht unterstützt.",
+ "line1": "nicht unterstützt"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported",
+ "textBody": "This version of %appName% is not supported by SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "Not Supported",
+ "textBody": "Your version of %appName% is not supported by SYNC."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible",
+ "textBody": "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "No compatible"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible"
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible",
+ "textBody": "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è supportata dal SYNC.",
+ "line1": "non supportata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% wordt niet ondersteund door SYNC.",
+ "line1": "niet ondersteund"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie jest obsługiwana przez system SYNC.",
+ "line1": "aplikacja nie obsług."
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não é suportada pelo SYNC.",
+ "line1": "não suportado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não é suportado pelo SYNC.",
+ "line1": "não suportada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не поддерживается SYNC.",
+ "line1": "не поддерживается"
+ },
+ "sv-se": {
+ "tts": "SYNC har inte stöd för den här versionen av %appName%.",
+ "line1": "stöds ej"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümü SYNC tarafından desteklenmiyor.",
+ "line1": "desteklenmiyor"
+ },
+ "zh-cn": {
+ "tts": "SYNC不支持此版本的%appName%。",
+ "line1": "不受支持"
+ },
+ "zh-tw": {
+ "tts": "SYNC 不支援此版本的%appName% 。",
+ "line1": "不支援"
+ }
+ }
+ },
+ "DataConsent": {
+ "languages": {
+ "en-gb": {
+ "textBody": "Would you like to enable Mobile Apps on SYNC? To use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S. Updates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "en-us": {
+ "line1": "Enable Mobile Apps",
+ "line2": "on SYNC? (Uses Data)",
+ "textBody": "Would you like to enable Mobile Apps on SYNC?\n\nTo use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S.\n\nUpdates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "es-en": {
+ "textBody": "Para usar aplicaciones móviles con SYNC, este debe comunicarse con Ford al menos una vez al mes a través del plan de datos de su dispositivo móvil. Pueden aplicar tarifas normales. SYNC enviará su VIN y el número de módulo de SYNC a Ford de Estados Unidos de América. Las actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario. /r Presione Sí para permitir y No para denegar."
+ },
+ "fr-ca": {
+ "textBody": "Pour utiliser AppLink, SYNC devra communiquer avec Ford au moins une fois par mois en utilisant le forfait de données de votre appareil mobile. Les tarifs réguliers peuvent s’appliquer. SYNC enverra votre NIV et le numéro de votre module SYNC à Ford États-Unis. Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements. /r Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ }
+ }
+ },
+ "DataConsentHelp": {
+ "languages": {
+ "en-us": {
+ "textBody": "Updates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. See your Owner Guide for more information."
+ },
+ "es-en": {
+ "textBody": "Las actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario."
+ },
+ "fr-ca": {
+ "textBody": "Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements."
+ }
+ }
+ },
+ "DisableApps": {
+ "languages": {
+ "de-de": {
+ "tts": "Ausschalten der automatischen Updates führt zum Ausschalten von SYNC mobile Apps. Sie können Ihre mobilen Apps dann nicht mehr mit SYNC nutzen. Bitte drücken Sie Ja zur Bestätigung oder Nein, um abzubrechen.",
+ "line1": "Auto-Update",
+ "line2": "und Mobile Apps deaktivieren"
+ },
+ "en-au": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-gb": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-ie": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-us": {
+ "tts": "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel.",
+ "line1": "Disable Auto-Updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel."
+ },
+ "es-en": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?",
+ "textBody": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "es-es": {
+ "tts": "Si desactiva las actualizaciones automáticas, también se desactivará la sincronización de las aplicaciones móviles. No podrá utilizar ninguna aplicación móvil con SYNC. Pulse sí para confirmar o no para cancelar.",
+ "line1": "¿Desact. actual. auto",
+ "line2": "y apl. móviles?"
+ },
+ "es-mx": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?"
+ },
+ "fr-ca": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?",
+ "textBody": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "fr-fr": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?"
+ },
+ "it-it": {
+ "tts": "Disabilitando gli aggiornamenti automatici si disattiva anche la sincronizzazione delle app mobili. Non sarà possibile usare app mobili con il SYNC. Premere Sì per confermare e No per cancellare.",
+ "line1": "Disabilitare agg. aut.",
+ "line2": "e app mobili?"
+ },
+ "nl-nl": {
+ "tts": "Door automatische updates uit te schakelen, schakelt u ook SYNC-mobiele apps uit. U kunt dan geen mobiele apps meer gebruiken met SYNC. Druk op Ja om te bevestigen of op Nee om te annuleren.",
+ "line1": "Auto-updates en mob.",
+ "line2": "apps uitschakelen?"
+ },
+ "pl-pl": {
+ "tts": "Wyłączenie automatycznych aktualizacji spowoduje także wyłączenie aplikacji mobilnych SYNC. Korzystanie z mobilnych aplikacji za pomocą SYNC będzie niemożliwe. Naciśnij TAK, by potwierdzić lub NIE, by anulować.",
+ "line1": "Wył. automat. aktual.",
+ "line2": "i aplikacje mobilne?"
+ },
+ "pt-br": {
+ "tts": "Se as atualizações automáticas forem desativadas, os aplicativos também serão desativados. Você não poderá usar nenhum aplicativo com o SYNC. Pressione sim para confirmar ou não para cancelar.",
+ "line1": "Desativar atualizações",
+ "line2": "autom. e aplicativos?"
+ },
+ "pt-pt": {
+ "tts": "A desactivação das actualizações automáticas desactiva igualmente as aplicações móveis do SYNC. Não poderá utilizar quaisquer aplicações móveis com o SYNC. Prima \"\"Sim\"\" para confirmar ou \"\"Não\"\" para cancelar.",
+ "line1": "Desact. actual. autom.",
+ "line2": "e aplicações móveis?"
+ },
+ "ru-ru": {
+ "tts": "При отключении автоматических обновлений также будут отключены мобильные приложения sync. Вы не сможете использовать какие-либо мобильные приложения с SYNC. Нажмите \"\"Да\"\" для подтверждения или \"\"Нет\"\" для отмены.",
+ "line1": "Откл. автообновления",
+ "line2": "и мобил. прилож.?"
+ },
+ "sv-se": {
+ "tts": "Om du avaktiverar automatisk uppdatering avaktiverar du även synkning av mobilappar. Du kommer inte längre att kunna använda dina mobilappar med SYNC. Tryck Ja för att bekräfta eller Nej för att avbryta.",
+ "line1": "Avaktiverar autouppdat.",
+ "line2": "och mobilappar?"
+ },
+ "tr-tr": {
+ "tts": "Otomatik güncellemeleri devre dışı bırakırsanız sync mobil uygulamalar da devre dışı kalır. SYNC ile mobil uygulama kullanmanız mümkün olmaz. Lütfen onaylamak için Evet'e veya iptal etmek için Hayır'a basın.",
+ "line1": "Oto. güncelleme ve",
+ "line2": "mobil uygul. kapat?"
+ },
+ "zh-cn": {
+ "tts": "禁用自动更新同时也会禁用SYNC移动应用程序。您将无法在 SYNC 中使用任何移动应用程序。请按“是”确认或按“否”取消。",
+ "line1": "是否禁用自动更新和",
+ "line2": "移动应用程序?"
+ },
+ "zh-tw": {
+ "tts": "停用自動更新也將停用 sync 行動應用程式。您將無法透過 SYNC 使用任何行動應用程式。確認請按「是」,取消請按「否」。",
+ "line1": "停用自動更新",
+ "line2": "和行動應用程式?"
+ }
+ }
+ },
+ "DrivingCharacteristics": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahreigenschaften: Kraftstoffverbrauch, MyKey, Sicherheitsgurtstatus.",
+ "label": "Fahreigenschaften"
+ },
+ "en-au": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-gb": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-ie": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-us": {
+ "tts": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status.",
+ "label": "Driving Characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo",
+ "textBody": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a las siguientes características de conducción: Consumo de combustible, MyKey, Estado cinturones de seguridad.",
+ "label": "Características de conducción"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite",
+ "textBody": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti caratteristiche di guida: Consumo carburante, MyKey, Stato cinture di sicurezza.",
+ "label": "Caratteristiche di guida"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende rijkenmerken: Brandstofverbruik, MyKey, Veiligheidsgordelstatus.",
+ "label": "Rijkenmerken"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji dotyczących jazdy: Zużycie paliwa, MyKey, Stan pasów bezpieczeństwa.",
+ "label": "Informacje dotyczące stylu jazdy"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes características de condução: Consumo de combustível, MyKey, Estado do cinto de segurança.",
+ "label": "Características de condução"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações de condução: Consumo de combustível, MyKey, Estado dos cintos de segurança.",
+ "label": "Características de condução"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим характеристикам движения: Расход топлива, MyKey, Состояние ремней безопасности.",
+ "label": "Характеристики движения"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande köregenskaper: Bränsleförbrukning, MyKey, Bältesstatus.",
+ "label": "Köregenskaper"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu sürüş karakteristiklerine erişebilir: Yakıt tüketimi, MyKey, Emniyet kemeri durumu.",
+ "label": "Sürüş karakteristikleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列行驶特性: 油耗, MyKey, 安全带状态",
+ "label": "行驶特性"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取以下駕駛特性: 油耗, MyKey, 安全帶狀態",
+ "label": "駕駛特性"
+ }
+ }
+ },
+ "Location": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die GPS-Daten und die Geschwindigkeit des Fahrzeugs.",
+ "label": "GPS und Geschwindigkeit"
+ },
+ "en-au": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-gb": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "en-ie": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-us": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad",
+ "textBody": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder al GPS y la velocidad del vehículo.",
+ "label": "GPS y velocidad"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse",
+ "textBody": "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso a GPS e velocità del veicolo.",
+ "label": "GPS e velocità"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot gps en de snelheid van het voertuig.",
+ "label": "Gps en snelheid"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do modułu GPS i prędkości pojazdu.",
+ "label": "GPS i prędkość"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar o GPS e a velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder ao GPS e à velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к GPS и скорости автомобиля.",
+ "label": "GPS и скорость"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt fordonets GPS och hastighetsmätare.",
+ "label": "GPS och hastighet"
+ },
+ "tr-tr": {
+ "tts": "Bu uygulama aracın GPS ve hız bilgilerine erişebilir.",
+ "label": "GPS ve hız"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可以访问车辆 GPS 和车速信息。",
+ "label": "GPS 和车速"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取車輛的GPS和速度。",
+ "label": "GPS和車速"
+ }
+ }
+ },
+ "Notifications": {
+ "languages": {
+ "de-de": {
+ "tts": "Läuft die App im Hintergrund, kann Sie Benachrichtigungen senden.",
+ "label": "Push-Benachrichtigungen"
+ },
+ "en-au": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-gb": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "en-ie": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-us": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push",
+ "textBody": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede enviar notificaciones cuando se está ejecutando en segundo plano.",
+ "label": "Notificaciones push"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push"
+ },
+ "fr-ca": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications instantanées",
+ "textBody": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "fr-fr": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications push"
+ },
+ "it-it": {
+ "tts": "Un'app può inviare notifiche se eseguita in background.",
+ "label": "Notifiche push"
+ },
+ "nl-nl": {
+ "tts": "Een app kan meldingen versturen als deze op de achtergrond actief is.",
+ "label": "Push-meldingen"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może wysyłać powiadomienia, działając w tle.",
+ "label": "Powiadomienia Push"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode enviar notificações quando estiver sendo executado em segundo plano.",
+ "label": "Notificações Push"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue enviar notificações quando está activa em segundo plano.",
+ "label": "Notificações push"
+ },
+ "ru-ru": {
+ "tts": "Если приложение работает в фоновом режиме, оно может отправлять оповещения.",
+ "label": "Оповещения о пересылке"
+ },
+ "sv-se": {
+ "tts": "Appen kan skicka meddelanden när den körs i bakgrunden.",
+ "label": "Push-notiser"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama arka planda çalışırken bildirim gönderebilir.",
+ "label": "Anlık bildirimleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序在后台运行时可推送通知。",
+ "label": "推送通知"
+ },
+ "zh-tw": {
+ "tts": "車輛行進時,應用程式可在背景中傳送通知。",
+ "label": "傳送通知"
+ }
+ }
+ },
+ "SettingDisableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Updates deakt."
+ },
+ "en-au": {
+ "line1": "Disable updates"
+ },
+ "en-gb": {
+ "line1": "Disable updates"
+ },
+ "en-ie": {
+ "line1": "Disable updates"
+ },
+ "en-us": {
+ "line1": "Disable Updates",
+ "textBody": "Disable Updates"
+ },
+ "es-en": {
+ "line1": "Deshab. actual.",
+ "textBody": "Deshab. actual."
+ },
+ "es-es": {
+ "line1": "Desact. actual."
+ },
+ "es-mx": {
+ "line1": "Deshab. actual."
+ },
+ "fr-ca": {
+ "line1": "Désactiver MAJ",
+ "textBody": "Désactiver MAJ"
+ },
+ "fr-fr": {
+ "line1": "Désactiver màj"
+ },
+ "it-it": {
+ "line1": "Disabilita agg."
+ },
+ "nl-nl": {
+ "line1": "Upd. uitschak."
+ },
+ "pl-pl": {
+ "line1": "Wyłącz aktual."
+ },
+ "pt-br": {
+ "line1": "Desat. atualiz."
+ },
+ "pt-pt": {
+ "line1": "Desact. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Откл. обновл."
+ },
+ "sv-se": {
+ "line1": "Inaktivera uppd."
+ },
+ "tr-tr": {
+ "line1": "Güncell. Kapat"
+ },
+ "zh-cn": {
+ "line1": "禁用更新"
+ },
+ "zh-tw": {
+ "line1": "停用更新"
+ }
+ }
+ },
+ "SettingEnableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Apps aktivieren"
+ },
+ "en-au": {
+ "line1": "Enable Apps"
+ },
+ "en-gb": {
+ "line1": "Enable Apps"
+ },
+ "en-ie": {
+ "line1": "Enable Apps"
+ },
+ "en-us": {
+ "line1": "Enable Apps"
+ },
+ "es-en": {
+ "line1": "Hab. aplic."
+ },
+ "es-es": {
+ "line1": "Activar apl."
+ },
+ "es-mx": {
+ "line1": "Hab. aplic."
+ },
+ "fr-ca": {
+ "line1": "Activer app.",
+ "textBody": "Activer app."
+ },
+ "fr-fr": {
+ "line1": "Activer app."
+ },
+ "it-it": {
+ "line1": "Abilita app"
+ },
+ "nl-nl": {
+ "line1": "Apps inschak."
+ },
+ "pl-pl": {
+ "line1": "Włącz aplikacje"
+ },
+ "pt-br": {
+ "line1": "Ativar aplic."
+ },
+ "pt-pt": {
+ "line1": "Activar actualiz."
+ },
+ "ru-ru": {
+ "line1": "Вкл. прилож."
+ },
+ "sv-se": {
+ "line1": "Aktivera appar"
+ },
+ "tr-tr": {
+ "line1": "Uygulamaları aç"
+ },
+ "zh-cn": {
+ "line1": "启用应用程序"
+ },
+ "zh-tw": {
+ "line1": "啟用應用程式"
+ }
+ }
+ },
+ "SettingUpdateAuto": {
+ "languages": {
+ "de-de": {
+ "line1": "Update anford."
+ },
+ "en-au": {
+ "line1": "Request update"
+ },
+ "en-gb": {
+ "line1": "Request update"
+ },
+ "en-ie": {
+ "line1": "Request update"
+ },
+ "en-us": {
+ "line1": "Request Update",
+ "textBody": "Select `Update now` to receive app authorization information for your SYNC-enabled mobile apps. This may enable additional functionality depending on the app and your settings. If your phone has a working data connection, an update should complete in less than 1 minute."
+ },
+ "es-en": {
+ "line1": "Solicit. actualiz.",
+ "textBody": "Solicit. actualiz."
+ },
+ "es-es": {
+ "line1": "Solicitar actual."
+ },
+ "es-mx": {
+ "line1": "Solicit. actualiz."
+ },
+ "fr-ca": {
+ "line1": "Demander MAJ",
+ "textBody": "Demander MAJ"
+ },
+ "fr-fr": {
+ "line1": "Demander màj"
+ },
+ "it-it": {
+ "line1": "Rich. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Upd. aanvragen"
+ },
+ "pl-pl": {
+ "line1": "Zażądaj aktual."
+ },
+ "pt-br": {
+ "line1": "Solicitar atualiz."
+ },
+ "pt-pt": {
+ "line1": "Solicit. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Запрос на обн."
+ },
+ "sv-se": {
+ "line1": "Begär uppdat."
+ },
+ "tr-tr": {
+ "line1": "Güncelleme iste"
+ },
+ "zh-cn": {
+ "line1": "请求更新"
+ },
+ "zh-tw": {
+ "line1": "請求更新"
+ }
+ }
+ },
+ "StatusNeeded": {
+ "languages": {
+ "de-de": {
+ "line1": "Update benötigt"
+ },
+ "en-au": {
+ "line1": "Update needed"
+ },
+ "en-gb": {
+ "line1": "Update needed",
+ "textBody": "Update needed"
+ },
+ "en-ie": {
+ "line1": "Update needed"
+ },
+ "en-us": {
+ "line1": "Update Needed",
+ "textBody": "Update Needed"
+ },
+ "es-en": {
+ "line1": "Actualiz. neces.",
+ "textBody": "Actualiz. neces."
+ },
+ "es-es": {
+ "line1": "Actu. necesaria"
+ },
+ "es-mx": {
+ "line1": "Actualiz. neces."
+ },
+ "fr-ca": {
+ "line1": "Màj requise",
+ "textBody": "Màj requise"
+ },
+ "fr-fr": {
+ "line1": "Mise à jour requise"
+ },
+ "it-it": {
+ "line1": "Necess. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Update nodig"
+ },
+ "pl-pl": {
+ "line1": "Potrzeba aktual."
+ },
+ "pt-br": {
+ "line1": "Atualiz. necess."
+ },
+ "pt-pt": {
+ "line1": "Actual. necess."
+ },
+ "ru-ru": {
+ "line1": "Необх. обновл."
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs"
+ },
+ "tr-tr": {
+ "line1": "Güncellenmeli"
+ },
+ "zh-cn": {
+ "line1": "需要进行更新"
+ },
+ "zh-tw": {
+ "line1": "需更新"
+ }
+ }
+ },
+ "StatusPending": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktualisieren..."
+ },
+ "en-au": {
+ "line1": "Updating..."
+ },
+ "en-gb": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "en-ie": {
+ "line1": "Updating..."
+ },
+ "en-us": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "es-en": {
+ "line1": "Actualizando...",
+ "textBody": "Actualizando..."
+ },
+ "es-es": {
+ "line1": "Actualizando..."
+ },
+ "es-mx": {
+ "line1": "Actualizando..."
+ },
+ "fr-ca": {
+ "line1": "MAJ en cours...",
+ "textBody": "MAJ en cours..."
+ },
+ "fr-fr": {
+ "line1": "Màj en cours..."
+ },
+ "it-it": {
+ "line1": "Aggiornamento"
+ },
+ "nl-nl": {
+ "line1": "Updaten..."
+ },
+ "pl-pl": {
+ "line1": "Aktualizowanie"
+ },
+ "pt-br": {
+ "line1": "Atualizando..."
+ },
+ "pt-pt": {
+ "line1": "A actualizar..."
+ },
+ "ru-ru": {
+ "line1": "Обновление..."
+ },
+ "sv-se": {
+ "line1": "Uppdaterar..."
+ },
+ "tr-tr": {
+ "line1": "Güncelleniyor..."
+ },
+ "zh-cn": {
+ "line1": "正在更新......"
+ },
+ "zh-tw": {
+ "line1": "更新中..."
+ }
+ }
+ },
+ "StatusUpToDate": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktuelle Version"
+ },
+ "en-au": {
+ "line1": "Up-to-date"
+ },
+ "en-gb": {
+ "line1": "Up-to-date",
+ "textBody": "Up-to-date"
+ },
+ "en-ie": {
+ "line1": "Up-to-date"
+ },
+ "en-us": {
+ "line1": "Up-To-Date",
+ "textBody": "Up-To-Date"
+ },
+ "es-en": {
+ "line1": "Actualizado",
+ "textBody": "Actualizado"
+ },
+ "es-es": {
+ "line1": "Actualizada"
+ },
+ "es-mx": {
+ "line1": "Actualizado"
+ },
+ "fr-ca": {
+ "line1": "Déjà à jour",
+ "textBody": "Déjà à jour"
+ },
+ "fr-fr": {
+ "line1": "Déjà à jour"
+ },
+ "it-it": {
+ "line1": "più recente"
+ },
+ "nl-nl": {
+ "line1": "Up-to-date"
+ },
+ "pl-pl": {
+ "line1": "Aktualne"
+ },
+ "pt-br": {
+ "line1": "Atualizado"
+ },
+ "pt-pt": {
+ "line1": "Actualizado"
+ },
+ "ru-ru": {
+ "line1": "Обновлено"
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs ej"
+ },
+ "tr-tr": {
+ "line1": "Güncel"
+ },
+ "zh-cn": {
+ "line1": "最新更新"
+ },
+ "zh-tw": {
+ "line1": "更新最新"
+ }
+ }
+ },
+ "VehicleInfo": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahrzeuginformationen: Kraftstoff-Füllstand, Kraftstoffverbrauch, Motordrehzahl, Kilometerzähler, FIN, Außentemperatur, Gangstellung, Reifenluftdruck.",
+ "label": "Fahrzeuginformationen"
+ },
+ "en-au": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-gb": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure."
+ },
+ "en-ie": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-us": {
+ "tts": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo",
+ "textBody": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a la siguiente información del vehículo: Nivel de combustible, Ahorro de combustible, RPM del motor, Cuentakilómetros, VIN, Temperatura aire exterior, Marcha engranada, Presión de neumáticos.",
+ "label": "Información del vehículo"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus.",
+ "label": "Renseignements du véhicule",
+ "textBody": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Vitesse de moteur, Compteur kilométrique, NIV, Température extérieure, Position de vitesse, Pression des pneus.",
+ "label": "Renseignements du véhicule"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti informazioni del veicolo: Livello carburante, Consumi carburante, Numero giri motore, Contachilometri, VIN, Temperatura esterna, Posizione marcia, Pressione pneumatici.",
+ "label": "Informazioni sul veicolo"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende voertuiginformatie: Brandstofpeil, Brandstofverbruik, Motortoerental, Kilometerteller, VIN, Buitentemperatuur, Versnellingsstand, Bandenspanning.",
+ "label": "Voertuiginformatie"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji o pojeździe: Poziom paliwa, Zużycie paliwa, Obroty silnika, Licznik przebiegu, Numer VIN, Temperatura zewnętrzna, Aktualny bieg, Ciśnienie opon.",
+ "label": "Informacje o pojeździe"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes informações sobre o veículo: Nível de combustível, Economia de combustível, RPM do motor, Hodômetro, VIN, Temperatura externa, Posição das marchas, Pressão dos pneus.",
+ "label": "Informações sobre o veículo"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações do veículo: Nível de combustível, Poupança de combustível, RPM do motor, Conta-quilómetros, VIN, Temperatura exterior, Posição da mudança de velocidade, Pressão dos pneus.",
+ "label": "Informações do veículo"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим данным автомобиля: Уровень топлива, Економия топлива, Число оборотов двигателя, Одометр, Номер VIN, Температура за бортом, Положение передачи, Давление шин.",
+ "label": "Информация об автомобиле"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande fordonsinformation: Bränslenivå, Bränsleekonomi, Motorns varvtal, Vägmätare, VIN, Utetemperatur, Växelläge, Däcktryck.",
+ "label": "Fordonsinformation"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu araç bilgilerine erişebilir: Yakıt seviyesi, Yakıt ekonomisi, Motor devirleri, Kilometre sayacı, VIN, Dış sıcaklık, Vites konumu, Lastik basıncı.",
+ "label": "Araç bilgisi"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列车辆信息 : 燃油量, 燃油经济性, 发动机转速(RPM), 里程表, VIN, 车外温度, 档位, 胎压.",
+ "label": "车辆信息"
+ },
+ "zh-tw": {
+ "tts": "一個應用程式可存取以下車輛資訊 : 燃油存量, 燃油經濟性, 引擎轉速, 里程表, 車輛識別號碼, 車外溫度, 檔位, 胎壓.",
+ "label": "車輛資訊"
+ }
+ }
+ }
+ }
+ },
+ "app_policies": {
+ "default": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["Base-4"],
+ "RequestType": [
+ "HTTP",
+ "FILE_RESUME"
+ ]
+ },
+ "1234": "default",
+ "device": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["DataConsent-2"]
+ },
+ "pre_DataConsent": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["BaseBeforeDataConsent"],
+ "RequestType": [
+ "QUERY_APPS",
+ "LAUNCH_APP",
+ "PROPRIETARY"
+ ]
+ }
+ }
+ }
+ }
+
diff --git a/src/components/policy/test/PTU2.json b/src/components/policy/test/PTU2.json
new file mode 100644
index 0000000000..4062e94516
--- /dev/null
+++ b/src/components/policy/test/PTU2.json
@@ -0,0 +1,1953 @@
+ {
+ "policy_table": {
+ "module_config": {
+ "preloaded_pt": true,
+ "preloaded_date": "2015-12-08",
+ "exchange_after_x_ignition_cycles": 100,
+ "exchange_after_x_kilometers": 1800,
+ "exchange_after_x_days": 30,
+ "timeout_after_x_seconds": 60,
+ "seconds_between_retries": [1,
+ 5,
+ 25,
+ 125,
+ 625],
+ "endpoints": {
+ "0x07": {
+ "default": ["http://policies.telematics.ford.com/api/policies"]
+ }
+ },
+ "notifications_per_minute_by_priority": {
+ "EMERGENCY": 60,
+ "NAVIGATION": 15,
+ "COMMUNICATION": 6,
+ "NORMAL": 4,
+ "NONE": 0
+ }
+ },
+ "functional_groupings": {
+ "Base-4": {
+ "rpcs": {
+ "AddCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "AddSubMenu": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "Alert": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "ChangeRegistration": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "CreateInteractionChoiceSet": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "DeleteInteractionChoiceSet": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteSubMenu": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "EndAudioPassThru": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "GenericResponse": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ListFiles": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAudioPassThru": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnButtonEvent": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "OnButtonPress": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "OnCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnDriverDistraction": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHashChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "PerformAudioPassThru": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "PerformInteraction": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "PutFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ResetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ScrollableMessage": {
+ "hmi_levels": ["FULL"]
+ },
+ "SetAppIcon": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "SetMediaClockTimer": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "Show": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "Slider": {
+ "hmi_levels": ["FULL"]
+ },
+ "Speak": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "SubscribeButton": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "SystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnsubscribeButton": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "Location-1": {
+ "user_consent_prompt": "Location",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ }
+ }
+ },
+ "Notifications": {
+ "user_consent_prompt": "Notifications",
+ "rpcs": {
+ "Alert": {
+ "hmi_levels": ["BACKGROUND"]
+ }
+ }
+ },
+ "DrivingCharacteristics-3": {
+ "user_consent_prompt": "DrivingCharacteristics",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ }
+ }
+ },
+ "VehicleInfo-3": {
+ "user_consent_prompt": "VehicleInfo",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"]
+ }
+ }
+ },
+ "PropriataryData-1": {
+ "rpcs": {
+ "DiagnosticMessage": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "GetDTCs": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ReadDID": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "Emergency-1": {
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ }
+ }
+ },
+ "Navigation-1": {
+ "rpcs": {
+ "AlertManeuver": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ShowConstantTBT": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "UpdateTurnList": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "DataConsent-2": {
+ "user_consent_prompt": "DataConsent",
+ "rpcs": null
+ },
+ "BaseBeforeDataConsent": {
+ "rpcs": {
+ "ChangeRegistration": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "DeleteFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ListFiles": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHashChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "PutFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetAppIcon": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ }
+ }
+ }
+ },
+ "consumer_friendly_messages": {
+ "version": "001.001.019",
+ "messages": {
+ "AppPermissions": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% benötigt die folgenden Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Wenn Sie Ja drücken, erklären Sie sich damit einverstanden, dass %vehicleMake% nicht für Schäden oder Verletzungen der Privatsphäre haftet, die im Zusammenhang mit der Nutzung Ihrer Benutzerdaten durch %appName% entstehen. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab.",
+ "line1": "Zugriffsanfrage(n)",
+ "line2": "erlauben?"
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. Please press yes to allow or no to deny.",
+ "line1": "Grant Requested",
+ "line2": "Permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. \n\nIf you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "es-en": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?",
+ "textBody": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar. \n\n Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando el uso de los siguientes permisos e información del vehículo: %functionalGroupLabels%. Si pulsa sí, acepta que %vehicleMake% no será responsable de los daños o la pérdida de privacidad relacionados con el uso de sus datos por parte de %appName%. Pulse sí para permitir o no para denegar.",
+ "line1": "¿Conceder permisos",
+ "line2": "solicitados?"
+ },
+ "es-mx": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?"
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)",
+ "textBody": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)"
+ },
+ "it-it": {
+ "tts": "%appName% richiede l'uso delle seguenti informazioni e autorizzazioni sul veicolo: %functionalGroupLabels%. Se si preme Sì, si acconsente che %vehicleMake% non sarà responsabile per danni o perdita di privacy in relazione all'impiego dei dati da parte di %appName%. Premere Sì per consentire e No per negare.",
+ "line1": "Concedi autorizzaz.",
+ "line2": "richiesta(e)?"
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. Als u op Ja drukt, gaat u ermee akkoord dat %vehicleMake% in geen geval aansprakelijk gesteld kan worden voor schade of verlies van privacy als gevolg van het feit dat %appName% gebruik maakt van uw gegevens. Druk op Ja om dit toe te staan of Nee om te weigeren.",
+ "line1": "Aangevraagde",
+ "line2": "permissie(s) verlenen?"
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz pozwoleń: %functionalGroupLabels%. Naciśnięcie TAK oznacza zgodę na fakt, iż %vehicleMake% nie będzie ponosić odpowiedzialności za szkody ani utratę prywatności w związku z wykorzystaniem przez %appName% danych, należących do użytkownika. Naciśnij TAK w celu udzielenia zgody lub NIE w celu odrzucenia żądania.",
+ "line1": "Udzielić żądanych",
+ "line2": "pozwoleń?"
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando o uso das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se pressionar sim, você concorda que a %vehicleMake% não será responsável por danos ou perdas de privacidade relacionados ao uso dos seus dados por %appName%. Pressione sim para permitir ou não para negar.",
+ "line1": "Conceder permissão",
+ "line2": "solicitada?"
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar a utilização das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se premir “Sim”, concorda que %vehicleMake% não será responsável por quaisquer danos ou perda de privacidade relacionada com a utilização dos seus dados por parte de %appName%. Prima “Sim” para permitir ou “Não” para recusar.",
+ "line1": "Conceder permiss.",
+ "line2": "solicitada(s)?"
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Нажатием \"\"да\"\", Вы соглашаетесь, что %vehicleMake% не будет нести ответственность за какие-либо убытки или потерю прайвеси, связанные с использованием Ваших данных компанией %appName%. Нажмите \"\"Да\"\", если Вы согласны, или \"\"Нет\"\" - если не согласны.",
+ "line1": "Предост. заправш.",
+ "line2": "разрешения?"
+ },
+ "sv-se": {
+ "tts": "%appName% begär att få tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Om du trycker Ja godkänner du att %vehicleMake% ska hållas skadeslös för alla skador som kan uppstå eller eventuella integritetsintrång som uppstår när %appName% använder dina data. Tryck Ja för att godkänna eller Nej för att neka.",
+ "line1": "Vill du ge",
+ "line2": "tillstånd?"
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri kullanma isteğinde bulunuyor: %functionalGroupLabels%. Evet'e basarsanız, %appName%'in verilerinizi kullanması sonucunda oluşabilecek hasarlardan veya gizlilik kaybından %vehicleMake%'in sorumlu olmayacağını kabul etmiş olacaksınız. Lütfen kabul etmek için Evet'e veya reddetmek için Hayır'a basın.",
+ "line1": "İstenen izinler",
+ "line2": "verilsin mi?"
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求使用下列车辆信息和权限: %functionalGroupLabels%。如果您按“是”,则表示您同意。 %vehicleMake% 将不会对因 %appName% 使用您的数据而引起的任何损毁或隐私损失负责。 请按“是”允许或按“否”拒绝。",
+ "line1": "是否允许请求的",
+ "line2": "权限?"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。按「是」,表示您同意,如因 %appName% 使用您的資料導致任何損害或損失,%vehicleMake% 將不負賠償責任。同意請按「是」,拒絕請按「否」。",
+ "line1": "允許",
+ "line2": "授權請求?"
+ }
+ }
+ },
+ "AppPermissionsHelp": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% fordert folgende Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Im Einstellungsmenü der mobilen Apps können Sie diese Berechtigungen ändern und sich detaillierte Beschreibungen anhören. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press yes to grant permissions or no to deny."
+ },
+ "es-en": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando los siguientes permisos e información del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y escuchar descripciones detalladas en el menú de configuración de la aplicación móvil. Pulse sí para conceder el permiso o no para denegarlo."
+ },
+ "es-mx": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "it-it": {
+ "tts": "%appName% richiede le seguenti informazioni e autorizzazioni riguardo il veicolo: %functionalGroupLabels%. È possibile modificare tali autorizzazioni e ascoltare descrizioni dettagliate nel menu impostazioni delle app mobili. Premere Sì per concedere le autorizzazioni e No per negarle."
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. U kunt deze toestemmingen wijzigen en gedetailleerde beschrijvingen beluisteren in het instellingenmenu voor mobiele apps. Druk op Ja om permissies te verlenen of op Nee om te weigeren."
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz zezwoleń: %functionalGroupLabels%. W menu ustawień aplikacji mobilnych można zmienić owe zezwolenia i usłyszeć ich szczegółowy opis. Naciśnij TAK, aby wyrazić zgodę lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando as seguintes informações e permissões do veículo: %functionalGroupLabels%. Você pode alterar estas permissões e ouvir descrições detalhadas no menu de configurações de aplicativos móveis. Pressione sim para conceder as permissões ou não para negar."
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar as seguintes informações e permissões do veículo: %functionalGroupLabels%. Pode alterar estas permissões e ouvir descrições detalhadas no menu de definições das aplicações móveis. Prima \"\"Sim\"\" para permitir ou \"\"Não\"\" para recusar."
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Вы можете изменить эти разрешения и прослушать подробные их описания в меню настроек мобильного приложения. Нажмите \"\"да\"\", чтобы предоставить разрешения, или \"\"нет\"\", чтобы не предоставлять."
+ },
+ "sv-se": {
+ "tts": "%appName% begär tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Du kan ändra tillstånden och höra detaljerade beskrivningar i menyn för mobilappsinställningar. Tryck Ja för att ge tillstånd eller Nej för att neka."
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri istiyor: %functionalGroupLabels%. Bu izinleri değiştirebilir ve mobil uygulamalar ayarlar menüsünden ayrıntılı açıklamaları dinleyebilirsiniz. Lütfen izin vermek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求下列车辆信息和权限: %functionalGroupLabels%。您可在移动应用程序设置菜单中更改这些权限,并听取详细说明。请按“是”允许权限或按“否”拒绝。"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。您可在行動應用程式設定清單中更改這些許可,並聆聽詳細說明。給予許可請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsRevoked": {
+ "languages": {
+ "de-de": {
+ "tts": "Die Autorisierungsdaten der App wurden geändert. %appName% hat keinen Zugriff auf %functionalGroupLabels% mehr. Installieren Sie die neueste Version der App auf Ihrem Gerät.."
+ },
+ "en-au": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-gb": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-ie": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-us": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "es-en": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "es-es": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de que tiene la versión más reciente de la aplicación instalada en su dispositivo móvil."
+ },
+ "es-mx": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "fr-ca": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "fr-fr": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "it-it": {
+ "tts": "Le autorizzazioni dell'app sono cambiate. %appName% non è più in grado di accedere a %functionalGroupLabels%. Assicurarsi di avere la versione più recente dell'app installata sul dispositivo mobile."
+ },
+ "nl-nl": {
+ "tts": "De app-autorisaties zijn gewijzigd. %appName% heeft geen toegang meer tot %functionalGroupLabels%. Zorg ervoor dat u de meest recente app-versie op uw mobiele apparaat geïnstalleerd hebt."
+ },
+ "pl-pl": {
+ "tts": "Dane dostępu aplikacji zostały zmienione. %appName% nie ma już dostępu do %functionalGroupLabels%. Sprawdź, czy na telefonie komórkowym zainstalowano najnowszą wersję aplikacji."
+ },
+ "pt-br": {
+ "tts": "As autorizações dos aplicativos foram alteradas. %appName% não pode mais acessar %functionalGroupLabels%. Certifique-se de que a versão mais recente do aplicativo está instalada no seu dispositivo móvel."
+ },
+ "pt-pt": {
+ "tts": "As autorizações das aplicações mudaram. %appName% já não consegue aceder a %functionalGroupLabels%. Certifique-se de que tem a última versão da aplicação no seu dispositivo móvel."
+ },
+ "ru-ru": {
+ "tts": "Авторизации приложения изменены. %appName% больше не имеет доступа к %functionalGroupLabels%. Убедитесь, что на вашем мобильном устройстве установлена самая новая версия приложения."
+ },
+ "sv-se": {
+ "tts": "Appens behörigheter har ändrats. %appName% har inte längre åtkomst till %functionalGroupLabels%. Kontrollera att du har installerat den senaste versionen av appen på mobilenheten."
+ },
+ "tr-tr": {
+ "tts": "Uygulama yetkileri değişti. %appName% artık %functionalGroupLabels%'e erişemeyecek. Lütfen mobil aygıtınızda en son uygulama sürümünün yüklü olduğundan emin olun."
+ },
+ "zh-cn": {
+ "tts": "应用程序授权已变更。 %appName% 将不能再访问 %functionalGroupLabels%。 请确认您的移动设备上安装的应用程序是最新版本。"
+ },
+ "zh-tw": {
+ "tts": "應用程式授權已改變。%appName% 已無法進入 %functionalGroupLabels%。請確認您的行動裝置上安裝了最新版應用程式。"
+ }
+ }
+ },
+ "AppUnauthorized": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% ist nicht autorisiert und wird nicht mit SYNC funktionieren.",
+ "line1": "nicht autorisiert"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized",
+ "textBody": "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "Not Authorized",
+ "textBody": "This version of %appName% is no longer authorized to work with AppLink. Please update to the latest version of %appName%."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada",
+ "textBody": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no está autorizada y no funcionará con SYNC.",
+ "line1": "No autorizada"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada"
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée",
+ "textBody": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è autorizzata e non funziona con il SYNC.",
+ "line1": "non autorizzata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% is niet geautoriseerd en werkt niet met SYNC.",
+ "line1": "niet geautoriseerd"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie posiada autoryzacji i nie będzie działać z SYNC.",
+ "line1": "brak autoryzacji"
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não tem autorização e não funcionará com o SYNC.",
+ "line1": "não autorizado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não está autorizada e não funcionará com o SYNC.",
+ "line1": "não autorizada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не авторизирована и не будет работать с SYNC.",
+ "line1": "не авторизировано"
+ },
+ "sv-se": {
+ "tts": "Den här versionen av %appName% är inte godkänd och fungerar inte med SYNC.",
+ "line1": "är ej godkänd"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümüne izin verilmediğinden SYNC ile çalışamaz.",
+ "line1": "için izin yok"
+ },
+ "zh-cn": {
+ "tts": "此版本的%appName% 未得到授权,无法在SYNC上使用。",
+ "line1": "未得到授权"
+ },
+ "zh-tw": {
+ "tts": "%appName% 的版本未獲得授權,將無法透過 SYNC 使用。",
+ "line1": "無授權"
+ }
+ }
+ },
+ "AppUnsupported": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% wird von SYNC nicht unterstützt.",
+ "line1": "nicht unterstützt"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported",
+ "textBody": "This version of %appName% is not supported by SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "Not Supported",
+ "textBody": "Your version of %appName% is not supported by SYNC."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible",
+ "textBody": "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "No compatible"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible"
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible",
+ "textBody": "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è supportata dal SYNC.",
+ "line1": "non supportata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% wordt niet ondersteund door SYNC.",
+ "line1": "niet ondersteund"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie jest obsługiwana przez system SYNC.",
+ "line1": "aplikacja nie obsług."
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não é suportada pelo SYNC.",
+ "line1": "não suportado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não é suportado pelo SYNC.",
+ "line1": "não suportada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не поддерживается SYNC.",
+ "line1": "не поддерживается"
+ },
+ "sv-se": {
+ "tts": "SYNC har inte stöd för den här versionen av %appName%.",
+ "line1": "stöds ej"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümü SYNC tarafından desteklenmiyor.",
+ "line1": "desteklenmiyor"
+ },
+ "zh-cn": {
+ "tts": "SYNC不支持此版本的%appName%。",
+ "line1": "不受支持"
+ },
+ "zh-tw": {
+ "tts": "SYNC 不支援此版本的%appName% 。",
+ "line1": "不支援"
+ }
+ }
+ },
+ "DataConsent": {
+ "languages": {
+ "en-gb": {
+ "textBody": "Would you like to enable Mobile Apps on SYNC? To use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S. Updates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "en-us": {
+ "line1": "Enable Mobile Apps",
+ "line2": "on SYNC? (Uses Data)",
+ "textBody": "Would you like to enable Mobile Apps on SYNC?\n\nTo use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S.\n\nUpdates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "es-en": {
+ "textBody": "Para usar aplicaciones móviles con SYNC, este debe comunicarse con Ford al menos una vez al mes a través del plan de datos de su dispositivo móvil. Pueden aplicar tarifas normales. SYNC enviará su VIN y el número de módulo de SYNC a Ford de Estados Unidos de América. Las actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario. /r Presione Sí para permitir y No para denegar."
+ },
+ "fr-ca": {
+ "textBody": "Pour utiliser AppLink, SYNC devra communiquer avec Ford au moins une fois par mois en utilisant le forfait de données de votre appareil mobile. Les tarifs réguliers peuvent s’appliquer. SYNC enverra votre NIV et le numéro de votre module SYNC à Ford États-Unis. Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements. /r Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ }
+ }
+ },
+ "DataConsentHelp": {
+ "languages": {
+ "en-us": {
+ "textBody": "Updates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. See your Owner Guide for more information."
+ },
+ "es-en": {
+ "textBody": "Las actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario."
+ },
+ "fr-ca": {
+ "textBody": "Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements."
+ }
+ }
+ },
+ "DisableApps": {
+ "languages": {
+ "de-de": {
+ "tts": "Ausschalten der automatischen Updates führt zum Ausschalten von SYNC mobile Apps. Sie können Ihre mobilen Apps dann nicht mehr mit SYNC nutzen. Bitte drücken Sie Ja zur Bestätigung oder Nein, um abzubrechen.",
+ "line1": "Auto-Update",
+ "line2": "und Mobile Apps deaktivieren"
+ },
+ "en-au": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-gb": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-ie": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-us": {
+ "tts": "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel.",
+ "line1": "Disable Auto-Updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel."
+ },
+ "es-en": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?",
+ "textBody": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "es-es": {
+ "tts": "Si desactiva las actualizaciones automáticas, también se desactivará la sincronización de las aplicaciones móviles. No podrá utilizar ninguna aplicación móvil con SYNC. Pulse sí para confirmar o no para cancelar.",
+ "line1": "¿Desact. actual. auto",
+ "line2": "y apl. móviles?"
+ },
+ "es-mx": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?"
+ },
+ "fr-ca": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?",
+ "textBody": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "fr-fr": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?"
+ },
+ "it-it": {
+ "tts": "Disabilitando gli aggiornamenti automatici si disattiva anche la sincronizzazione delle app mobili. Non sarà possibile usare app mobili con il SYNC. Premere Sì per confermare e No per cancellare.",
+ "line1": "Disabilitare agg. aut.",
+ "line2": "e app mobili?"
+ },
+ "nl-nl": {
+ "tts": "Door automatische updates uit te schakelen, schakelt u ook SYNC-mobiele apps uit. U kunt dan geen mobiele apps meer gebruiken met SYNC. Druk op Ja om te bevestigen of op Nee om te annuleren.",
+ "line1": "Auto-updates en mob.",
+ "line2": "apps uitschakelen?"
+ },
+ "pl-pl": {
+ "tts": "Wyłączenie automatycznych aktualizacji spowoduje także wyłączenie aplikacji mobilnych SYNC. Korzystanie z mobilnych aplikacji za pomocą SYNC będzie niemożliwe. Naciśnij TAK, by potwierdzić lub NIE, by anulować.",
+ "line1": "Wył. automat. aktual.",
+ "line2": "i aplikacje mobilne?"
+ },
+ "pt-br": {
+ "tts": "Se as atualizações automáticas forem desativadas, os aplicativos também serão desativados. Você não poderá usar nenhum aplicativo com o SYNC. Pressione sim para confirmar ou não para cancelar.",
+ "line1": "Desativar atualizações",
+ "line2": "autom. e aplicativos?"
+ },
+ "pt-pt": {
+ "tts": "A desactivação das actualizações automáticas desactiva igualmente as aplicações móveis do SYNC. Não poderá utilizar quaisquer aplicações móveis com o SYNC. Prima \"\"Sim\"\" para confirmar ou \"\"Não\"\" para cancelar.",
+ "line1": "Desact. actual. autom.",
+ "line2": "e aplicações móveis?"
+ },
+ "ru-ru": {
+ "tts": "При отключении автоматических обновлений также будут отключены мобильные приложения sync. Вы не сможете использовать какие-либо мобильные приложения с SYNC. Нажмите \"\"Да\"\" для подтверждения или \"\"Нет\"\" для отмены.",
+ "line1": "Откл. автообновления",
+ "line2": "и мобил. прилож.?"
+ },
+ "sv-se": {
+ "tts": "Om du avaktiverar automatisk uppdatering avaktiverar du även synkning av mobilappar. Du kommer inte längre att kunna använda dina mobilappar med SYNC. Tryck Ja för att bekräfta eller Nej för att avbryta.",
+ "line1": "Avaktiverar autouppdat.",
+ "line2": "och mobilappar?"
+ },
+ "tr-tr": {
+ "tts": "Otomatik güncellemeleri devre dışı bırakırsanız sync mobil uygulamalar da devre dışı kalır. SYNC ile mobil uygulama kullanmanız mümkün olmaz. Lütfen onaylamak için Evet'e veya iptal etmek için Hayır'a basın.",
+ "line1": "Oto. güncelleme ve",
+ "line2": "mobil uygul. kapat?"
+ },
+ "zh-cn": {
+ "tts": "禁用自动更新同时也会禁用SYNC移动应用程序。您将无法在 SYNC 中使用任何移动应用程序。请按“是”确认或按“否”取消。",
+ "line1": "是否禁用自动更新和",
+ "line2": "移动应用程序?"
+ },
+ "zh-tw": {
+ "tts": "停用自動更新也將停用 sync 行動應用程式。您將無法透過 SYNC 使用任何行動應用程式。確認請按「是」,取消請按「否」。",
+ "line1": "停用自動更新",
+ "line2": "和行動應用程式?"
+ }
+ }
+ },
+ "DrivingCharacteristics": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahreigenschaften: Kraftstoffverbrauch, MyKey, Sicherheitsgurtstatus.",
+ "label": "Fahreigenschaften"
+ },
+ "en-au": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-gb": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-ie": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-us": {
+ "tts": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status.",
+ "label": "Driving Characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo",
+ "textBody": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a las siguientes características de conducción: Consumo de combustible, MyKey, Estado cinturones de seguridad.",
+ "label": "Características de conducción"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite",
+ "textBody": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti caratteristiche di guida: Consumo carburante, MyKey, Stato cinture di sicurezza.",
+ "label": "Caratteristiche di guida"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende rijkenmerken: Brandstofverbruik, MyKey, Veiligheidsgordelstatus.",
+ "label": "Rijkenmerken"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji dotyczących jazdy: Zużycie paliwa, MyKey, Stan pasów bezpieczeństwa.",
+ "label": "Informacje dotyczące stylu jazdy"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes características de condução: Consumo de combustível, MyKey, Estado do cinto de segurança.",
+ "label": "Características de condução"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações de condução: Consumo de combustível, MyKey, Estado dos cintos de segurança.",
+ "label": "Características de condução"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим характеристикам движения: Расход топлива, MyKey, Состояние ремней безопасности.",
+ "label": "Характеристики движения"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande köregenskaper: Bränsleförbrukning, MyKey, Bältesstatus.",
+ "label": "Köregenskaper"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu sürüş karakteristiklerine erişebilir: Yakıt tüketimi, MyKey, Emniyet kemeri durumu.",
+ "label": "Sürüş karakteristikleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列行驶特性: 油耗, MyKey, 安全带状态",
+ "label": "行驶特性"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取以下駕駛特性: 油耗, MyKey, 安全帶狀態",
+ "label": "駕駛特性"
+ }
+ }
+ },
+ "Location": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die GPS-Daten und die Geschwindigkeit des Fahrzeugs.",
+ "label": "GPS und Geschwindigkeit"
+ },
+ "en-au": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-gb": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "en-ie": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-us": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad",
+ "textBody": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder al GPS y la velocidad del vehículo.",
+ "label": "GPS y velocidad"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse",
+ "textBody": "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso a GPS e velocità del veicolo.",
+ "label": "GPS e velocità"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot gps en de snelheid van het voertuig.",
+ "label": "Gps en snelheid"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do modułu GPS i prędkości pojazdu.",
+ "label": "GPS i prędkość"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar o GPS e a velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder ao GPS e à velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к GPS и скорости автомобиля.",
+ "label": "GPS и скорость"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt fordonets GPS och hastighetsmätare.",
+ "label": "GPS och hastighet"
+ },
+ "tr-tr": {
+ "tts": "Bu uygulama aracın GPS ve hız bilgilerine erişebilir.",
+ "label": "GPS ve hız"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可以访问车辆 GPS 和车速信息。",
+ "label": "GPS 和车速"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取車輛的GPS和速度。",
+ "label": "GPS和車速"
+ }
+ }
+ },
+ "Notifications": {
+ "languages": {
+ "de-de": {
+ "tts": "Läuft die App im Hintergrund, kann Sie Benachrichtigungen senden.",
+ "label": "Push-Benachrichtigungen"
+ },
+ "en-au": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-gb": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "en-ie": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-us": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push",
+ "textBody": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede enviar notificaciones cuando se está ejecutando en segundo plano.",
+ "label": "Notificaciones push"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push"
+ },
+ "fr-ca": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications instantanées",
+ "textBody": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "fr-fr": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications push"
+ },
+ "it-it": {
+ "tts": "Un'app può inviare notifiche se eseguita in background.",
+ "label": "Notifiche push"
+ },
+ "nl-nl": {
+ "tts": "Een app kan meldingen versturen als deze op de achtergrond actief is.",
+ "label": "Push-meldingen"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może wysyłać powiadomienia, działając w tle.",
+ "label": "Powiadomienia Push"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode enviar notificações quando estiver sendo executado em segundo plano.",
+ "label": "Notificações Push"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue enviar notificações quando está activa em segundo plano.",
+ "label": "Notificações push"
+ },
+ "ru-ru": {
+ "tts": "Если приложение работает в фоновом режиме, оно может отправлять оповещения.",
+ "label": "Оповещения о пересылке"
+ },
+ "sv-se": {
+ "tts": "Appen kan skicka meddelanden när den körs i bakgrunden.",
+ "label": "Push-notiser"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama arka planda çalışırken bildirim gönderebilir.",
+ "label": "Anlık bildirimleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序在后台运行时可推送通知。",
+ "label": "推送通知"
+ },
+ "zh-tw": {
+ "tts": "車輛行進時,應用程式可在背景中傳送通知。",
+ "label": "傳送通知"
+ }
+ }
+ },
+ "SettingDisableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Updates deakt."
+ },
+ "en-au": {
+ "line1": "Disable updates"
+ },
+ "en-gb": {
+ "line1": "Disable updates"
+ },
+ "en-ie": {
+ "line1": "Disable updates"
+ },
+ "en-us": {
+ "line1": "Disable Updates",
+ "textBody": "Disable Updates"
+ },
+ "es-en": {
+ "line1": "Deshab. actual.",
+ "textBody": "Deshab. actual."
+ },
+ "es-es": {
+ "line1": "Desact. actual."
+ },
+ "es-mx": {
+ "line1": "Deshab. actual."
+ },
+ "fr-ca": {
+ "line1": "Désactiver MAJ",
+ "textBody": "Désactiver MAJ"
+ },
+ "fr-fr": {
+ "line1": "Désactiver màj"
+ },
+ "it-it": {
+ "line1": "Disabilita agg."
+ },
+ "nl-nl": {
+ "line1": "Upd. uitschak."
+ },
+ "pl-pl": {
+ "line1": "Wyłącz aktual."
+ },
+ "pt-br": {
+ "line1": "Desat. atualiz."
+ },
+ "pt-pt": {
+ "line1": "Desact. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Откл. обновл."
+ },
+ "sv-se": {
+ "line1": "Inaktivera uppd."
+ },
+ "tr-tr": {
+ "line1": "Güncell. Kapat"
+ },
+ "zh-cn": {
+ "line1": "禁用更新"
+ },
+ "zh-tw": {
+ "line1": "停用更新"
+ }
+ }
+ },
+ "SettingEnableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Apps aktivieren"
+ },
+ "en-au": {
+ "line1": "Enable Apps"
+ },
+ "en-gb": {
+ "line1": "Enable Apps"
+ },
+ "en-ie": {
+ "line1": "Enable Apps"
+ },
+ "en-us": {
+ "line1": "Enable Apps"
+ },
+ "es-en": {
+ "line1": "Hab. aplic."
+ },
+ "es-es": {
+ "line1": "Activar apl."
+ },
+ "es-mx": {
+ "line1": "Hab. aplic."
+ },
+ "fr-ca": {
+ "line1": "Activer app.",
+ "textBody": "Activer app."
+ },
+ "fr-fr": {
+ "line1": "Activer app."
+ },
+ "it-it": {
+ "line1": "Abilita app"
+ },
+ "nl-nl": {
+ "line1": "Apps inschak."
+ },
+ "pl-pl": {
+ "line1": "Włącz aplikacje"
+ },
+ "pt-br": {
+ "line1": "Ativar aplic."
+ },
+ "pt-pt": {
+ "line1": "Activar actualiz."
+ },
+ "ru-ru": {
+ "line1": "Вкл. прилож."
+ },
+ "sv-se": {
+ "line1": "Aktivera appar"
+ },
+ "tr-tr": {
+ "line1": "Uygulamaları aç"
+ },
+ "zh-cn": {
+ "line1": "启用应用程序"
+ },
+ "zh-tw": {
+ "line1": "啟用應用程式"
+ }
+ }
+ },
+ "SettingUpdateAuto": {
+ "languages": {
+ "de-de": {
+ "line1": "Update anford."
+ },
+ "en-au": {
+ "line1": "Request update"
+ },
+ "en-gb": {
+ "line1": "Request update"
+ },
+ "en-ie": {
+ "line1": "Request update"
+ },
+ "en-us": {
+ "line1": "Request Update",
+ "textBody": "Select `Update now` to receive app authorization information for your SYNC-enabled mobile apps. This may enable additional functionality depending on the app and your settings. If your phone has a working data connection, an update should complete in less than 1 minute."
+ },
+ "es-en": {
+ "line1": "Solicit. actualiz.",
+ "textBody": "Solicit. actualiz."
+ },
+ "es-es": {
+ "line1": "Solicitar actual."
+ },
+ "es-mx": {
+ "line1": "Solicit. actualiz."
+ },
+ "fr-ca": {
+ "line1": "Demander MAJ",
+ "textBody": "Demander MAJ"
+ },
+ "fr-fr": {
+ "line1": "Demander màj"
+ },
+ "it-it": {
+ "line1": "Rich. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Upd. aanvragen"
+ },
+ "pl-pl": {
+ "line1": "Zażądaj aktual."
+ },
+ "pt-br": {
+ "line1": "Solicitar atualiz."
+ },
+ "pt-pt": {
+ "line1": "Solicit. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Запрос на обн."
+ },
+ "sv-se": {
+ "line1": "Begär uppdat."
+ },
+ "tr-tr": {
+ "line1": "Güncelleme iste"
+ },
+ "zh-cn": {
+ "line1": "请求更新"
+ },
+ "zh-tw": {
+ "line1": "請求更新"
+ }
+ }
+ },
+ "StatusNeeded": {
+ "languages": {
+ "de-de": {
+ "line1": "Update benötigt"
+ },
+ "en-au": {
+ "line1": "Update needed"
+ },
+ "en-gb": {
+ "line1": "Update needed",
+ "textBody": "Update needed"
+ },
+ "en-ie": {
+ "line1": "Update needed"
+ },
+ "en-us": {
+ "line1": "Update Needed",
+ "textBody": "Update Needed"
+ },
+ "es-en": {
+ "line1": "Actualiz. neces.",
+ "textBody": "Actualiz. neces."
+ },
+ "es-es": {
+ "line1": "Actu. necesaria"
+ },
+ "es-mx": {
+ "line1": "Actualiz. neces."
+ },
+ "fr-ca": {
+ "line1": "Màj requise",
+ "textBody": "Màj requise"
+ },
+ "fr-fr": {
+ "line1": "Mise à jour requise"
+ },
+ "it-it": {
+ "line1": "Necess. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Update nodig"
+ },
+ "pl-pl": {
+ "line1": "Potrzeba aktual."
+ },
+ "pt-br": {
+ "line1": "Atualiz. necess."
+ },
+ "pt-pt": {
+ "line1": "Actual. necess."
+ },
+ "ru-ru": {
+ "line1": "Необх. обновл."
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs"
+ },
+ "tr-tr": {
+ "line1": "Güncellenmeli"
+ },
+ "zh-cn": {
+ "line1": "需要进行更新"
+ },
+ "zh-tw": {
+ "line1": "需更新"
+ }
+ }
+ },
+ "StatusPending": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktualisieren..."
+ },
+ "en-au": {
+ "line1": "Updating..."
+ },
+ "en-gb": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "en-ie": {
+ "line1": "Updating..."
+ },
+ "en-us": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "es-en": {
+ "line1": "Actualizando...",
+ "textBody": "Actualizando..."
+ },
+ "es-es": {
+ "line1": "Actualizando..."
+ },
+ "es-mx": {
+ "line1": "Actualizando..."
+ },
+ "fr-ca": {
+ "line1": "MAJ en cours...",
+ "textBody": "MAJ en cours..."
+ },
+ "fr-fr": {
+ "line1": "Màj en cours..."
+ },
+ "it-it": {
+ "line1": "Aggiornamento"
+ },
+ "nl-nl": {
+ "line1": "Updaten..."
+ },
+ "pl-pl": {
+ "line1": "Aktualizowanie"
+ },
+ "pt-br": {
+ "line1": "Atualizando..."
+ },
+ "pt-pt": {
+ "line1": "A actualizar..."
+ },
+ "ru-ru": {
+ "line1": "Обновление..."
+ },
+ "sv-se": {
+ "line1": "Uppdaterar..."
+ },
+ "tr-tr": {
+ "line1": "Güncelleniyor..."
+ },
+ "zh-cn": {
+ "line1": "正在更新......"
+ },
+ "zh-tw": {
+ "line1": "更新中..."
+ }
+ }
+ },
+ "StatusUpToDate": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktuelle Version"
+ },
+ "en-au": {
+ "line1": "Up-to-date"
+ },
+ "en-gb": {
+ "line1": "Up-to-date",
+ "textBody": "Up-to-date"
+ },
+ "en-ie": {
+ "line1": "Up-to-date"
+ },
+ "en-us": {
+ "line1": "Up-To-Date",
+ "textBody": "Up-To-Date"
+ },
+ "es-en": {
+ "line1": "Actualizado",
+ "textBody": "Actualizado"
+ },
+ "es-es": {
+ "line1": "Actualizada"
+ },
+ "es-mx": {
+ "line1": "Actualizado"
+ },
+ "fr-ca": {
+ "line1": "Déjà à jour",
+ "textBody": "Déjà à jour"
+ },
+ "fr-fr": {
+ "line1": "Déjà à jour"
+ },
+ "it-it": {
+ "line1": "più recente"
+ },
+ "nl-nl": {
+ "line1": "Up-to-date"
+ },
+ "pl-pl": {
+ "line1": "Aktualne"
+ },
+ "pt-br": {
+ "line1": "Atualizado"
+ },
+ "pt-pt": {
+ "line1": "Actualizado"
+ },
+ "ru-ru": {
+ "line1": "Обновлено"
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs ej"
+ },
+ "tr-tr": {
+ "line1": "Güncel"
+ },
+ "zh-cn": {
+ "line1": "最新更新"
+ },
+ "zh-tw": {
+ "line1": "更新最新"
+ }
+ }
+ },
+ "VehicleInfo": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahrzeuginformationen: Kraftstoff-Füllstand, Kraftstoffverbrauch, Motordrehzahl, Kilometerzähler, FIN, Außentemperatur, Gangstellung, Reifenluftdruck.",
+ "label": "Fahrzeuginformationen"
+ },
+ "en-au": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-gb": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure."
+ },
+ "en-ie": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-us": {
+ "tts": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo",
+ "textBody": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a la siguiente información del vehículo: Nivel de combustible, Ahorro de combustible, RPM del motor, Cuentakilómetros, VIN, Temperatura aire exterior, Marcha engranada, Presión de neumáticos.",
+ "label": "Información del vehículo"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus.",
+ "label": "Renseignements du véhicule",
+ "textBody": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Vitesse de moteur, Compteur kilométrique, NIV, Température extérieure, Position de vitesse, Pression des pneus.",
+ "label": "Renseignements du véhicule"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti informazioni del veicolo: Livello carburante, Consumi carburante, Numero giri motore, Contachilometri, VIN, Temperatura esterna, Posizione marcia, Pressione pneumatici.",
+ "label": "Informazioni sul veicolo"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende voertuiginformatie: Brandstofpeil, Brandstofverbruik, Motortoerental, Kilometerteller, VIN, Buitentemperatuur, Versnellingsstand, Bandenspanning.",
+ "label": "Voertuiginformatie"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji o pojeździe: Poziom paliwa, Zużycie paliwa, Obroty silnika, Licznik przebiegu, Numer VIN, Temperatura zewnętrzna, Aktualny bieg, Ciśnienie opon.",
+ "label": "Informacje o pojeździe"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes informações sobre o veículo: Nível de combustível, Economia de combustível, RPM do motor, Hodômetro, VIN, Temperatura externa, Posição das marchas, Pressão dos pneus.",
+ "label": "Informações sobre o veículo"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações do veículo: Nível de combustível, Poupança de combustível, RPM do motor, Conta-quilómetros, VIN, Temperatura exterior, Posição da mudança de velocidade, Pressão dos pneus.",
+ "label": "Informações do veículo"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим данным автомобиля: Уровень топлива, Економия топлива, Число оборотов двигателя, Одометр, Номер VIN, Температура за бортом, Положение передачи, Давление шин.",
+ "label": "Информация об автомобиле"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande fordonsinformation: Bränslenivå, Bränsleekonomi, Motorns varvtal, Vägmätare, VIN, Utetemperatur, Växelläge, Däcktryck.",
+ "label": "Fordonsinformation"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu araç bilgilerine erişebilir: Yakıt seviyesi, Yakıt ekonomisi, Motor devirleri, Kilometre sayacı, VIN, Dış sıcaklık, Vites konumu, Lastik basıncı.",
+ "label": "Araç bilgisi"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列车辆信息 : 燃油量, 燃油经济性, 发动机转速(RPM), 里程表, VIN, 车外温度, 档位, 胎压.",
+ "label": "车辆信息"
+ },
+ "zh-tw": {
+ "tts": "一個應用程式可存取以下車輛資訊 : 燃油存量, 燃油經濟性, 引擎轉速, 里程表, 車輛識別號碼, 車外溫度, 檔位, 胎壓.",
+ "label": "車輛資訊"
+ }
+ }
+ }
+ }
+ },
+ "app_policies": {
+ "default": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["Base-4"]
+ },
+ "device": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["DataConsent-2"]
+ },
+ "pre_DataConsent": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["BaseBeforeDataConsent"]
+ },
+ "1234": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["BaseBeforeDataConsent"],
+ "RequestType": [
+ "TRAFFIC_MESSAGE_CHANNEL",
+ "QUERY_APPS",
+ "LAUNCH_APP",
+ "PROPRIETARY",
+ "NAVIGATION",
+ "MEDIA"
+ ]
+ }
+ }
+ }
+ }
diff --git a/src/components/policy/test/PTU3.json b/src/components/policy/test/PTU3.json
new file mode 100644
index 0000000000..812fbfd36a
--- /dev/null
+++ b/src/components/policy/test/PTU3.json
@@ -0,0 +1,1951 @@
+ {
+ "policy_table": {
+ "module_config": {
+ "preloaded_pt": true,
+ "preloaded_date": "2015-12-08",
+ "exchange_after_x_ignition_cycles": 100,
+ "exchange_after_x_kilometers": 1800,
+ "exchange_after_x_days": 30,
+ "timeout_after_x_seconds": 60,
+ "seconds_between_retries": [1,
+ 5,
+ 25,
+ 125,
+ 625],
+ "endpoints": {
+ "0x07": {
+ "default": ["http://policies.telematics.ford.com/api/policies"]
+ }
+ },
+ "notifications_per_minute_by_priority": {
+ "EMERGENCY": 60,
+ "NAVIGATION": 15,
+ "COMMUNICATION": 6,
+ "NORMAL": 4,
+ "NONE": 0
+ }
+ },
+ "functional_groupings": {
+ "Base-4": {
+ "rpcs": {
+ "AddCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "AddSubMenu": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "Alert": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "ChangeRegistration": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "CreateInteractionChoiceSet": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "DeleteInteractionChoiceSet": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteSubMenu": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "EndAudioPassThru": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "GenericResponse": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ListFiles": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAudioPassThru": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnButtonEvent": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "OnButtonPress": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "OnCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnDriverDistraction": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHashChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "PerformAudioPassThru": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "PerformInteraction": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "PutFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ResetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ScrollableMessage": {
+ "hmi_levels": ["FULL"]
+ },
+ "SetAppIcon": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "SetMediaClockTimer": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "Show": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "Slider": {
+ "hmi_levels": ["FULL"]
+ },
+ "Speak": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "SubscribeButton": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "SystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnsubscribeButton": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "Location-1": {
+ "user_consent_prompt": "Location",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ }
+ }
+ },
+ "Notifications": {
+ "user_consent_prompt": "Notifications",
+ "rpcs": {
+ "Alert": {
+ "hmi_levels": ["BACKGROUND"]
+ }
+ }
+ },
+ "DrivingCharacteristics-3": {
+ "user_consent_prompt": "DrivingCharacteristics",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ }
+ }
+ },
+ "VehicleInfo-3": {
+ "user_consent_prompt": "VehicleInfo",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"]
+ }
+ }
+ },
+ "PropriataryData-1": {
+ "rpcs": {
+ "DiagnosticMessage": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "GetDTCs": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ReadDID": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "Emergency-1": {
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ }
+ }
+ },
+ "Navigation-1": {
+ "rpcs": {
+ "AlertManeuver": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ShowConstantTBT": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "UpdateTurnList": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "DataConsent-2": {
+ "user_consent_prompt": "DataConsent",
+ "rpcs": null
+ },
+ "BaseBeforeDataConsent": {
+ "rpcs": {
+ "ChangeRegistration": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "DeleteFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ListFiles": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHashChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "PutFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetAppIcon": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ }
+ }
+ }
+ },
+ "consumer_friendly_messages": {
+ "version": "001.001.019",
+ "messages": {
+ "AppPermissions": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% benötigt die folgenden Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Wenn Sie Ja drücken, erklären Sie sich damit einverstanden, dass %vehicleMake% nicht für Schäden oder Verletzungen der Privatsphäre haftet, die im Zusammenhang mit der Nutzung Ihrer Benutzerdaten durch %appName% entstehen. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab.",
+ "line1": "Zugriffsanfrage(n)",
+ "line2": "erlauben?"
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. Please press yes to allow or no to deny.",
+ "line1": "Grant Requested",
+ "line2": "Permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. \n\nIf you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "es-en": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?",
+ "textBody": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar. \n\n Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando el uso de los siguientes permisos e información del vehículo: %functionalGroupLabels%. Si pulsa sí, acepta que %vehicleMake% no será responsable de los daños o la pérdida de privacidad relacionados con el uso de sus datos por parte de %appName%. Pulse sí para permitir o no para denegar.",
+ "line1": "¿Conceder permisos",
+ "line2": "solicitados?"
+ },
+ "es-mx": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?"
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)",
+ "textBody": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)"
+ },
+ "it-it": {
+ "tts": "%appName% richiede l'uso delle seguenti informazioni e autorizzazioni sul veicolo: %functionalGroupLabels%. Se si preme Sì, si acconsente che %vehicleMake% non sarà responsabile per danni o perdita di privacy in relazione all'impiego dei dati da parte di %appName%. Premere Sì per consentire e No per negare.",
+ "line1": "Concedi autorizzaz.",
+ "line2": "richiesta(e)?"
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. Als u op Ja drukt, gaat u ermee akkoord dat %vehicleMake% in geen geval aansprakelijk gesteld kan worden voor schade of verlies van privacy als gevolg van het feit dat %appName% gebruik maakt van uw gegevens. Druk op Ja om dit toe te staan of Nee om te weigeren.",
+ "line1": "Aangevraagde",
+ "line2": "permissie(s) verlenen?"
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz pozwoleń: %functionalGroupLabels%. Naciśnięcie TAK oznacza zgodę na fakt, iż %vehicleMake% nie będzie ponosić odpowiedzialności za szkody ani utratę prywatności w związku z wykorzystaniem przez %appName% danych, należących do użytkownika. Naciśnij TAK w celu udzielenia zgody lub NIE w celu odrzucenia żądania.",
+ "line1": "Udzielić żądanych",
+ "line2": "pozwoleń?"
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando o uso das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se pressionar sim, você concorda que a %vehicleMake% não será responsável por danos ou perdas de privacidade relacionados ao uso dos seus dados por %appName%. Pressione sim para permitir ou não para negar.",
+ "line1": "Conceder permissão",
+ "line2": "solicitada?"
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar a utilização das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se premir “Sim”, concorda que %vehicleMake% não será responsável por quaisquer danos ou perda de privacidade relacionada com a utilização dos seus dados por parte de %appName%. Prima “Sim” para permitir ou “Não” para recusar.",
+ "line1": "Conceder permiss.",
+ "line2": "solicitada(s)?"
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Нажатием \"\"да\"\", Вы соглашаетесь, что %vehicleMake% не будет нести ответственность за какие-либо убытки или потерю прайвеси, связанные с использованием Ваших данных компанией %appName%. Нажмите \"\"Да\"\", если Вы согласны, или \"\"Нет\"\" - если не согласны.",
+ "line1": "Предост. заправш.",
+ "line2": "разрешения?"
+ },
+ "sv-se": {
+ "tts": "%appName% begär att få tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Om du trycker Ja godkänner du att %vehicleMake% ska hållas skadeslös för alla skador som kan uppstå eller eventuella integritetsintrång som uppstår när %appName% använder dina data. Tryck Ja för att godkänna eller Nej för att neka.",
+ "line1": "Vill du ge",
+ "line2": "tillstånd?"
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri kullanma isteğinde bulunuyor: %functionalGroupLabels%. Evet'e basarsanız, %appName%'in verilerinizi kullanması sonucunda oluşabilecek hasarlardan veya gizlilik kaybından %vehicleMake%'in sorumlu olmayacağını kabul etmiş olacaksınız. Lütfen kabul etmek için Evet'e veya reddetmek için Hayır'a basın.",
+ "line1": "İstenen izinler",
+ "line2": "verilsin mi?"
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求使用下列车辆信息和权限: %functionalGroupLabels%。如果您按“是”,则表示您同意。 %vehicleMake% 将不会对因 %appName% 使用您的数据而引起的任何损毁或隐私损失负责。 请按“是”允许或按“否”拒绝。",
+ "line1": "是否允许请求的",
+ "line2": "权限?"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。按「是」,表示您同意,如因 %appName% 使用您的資料導致任何損害或損失,%vehicleMake% 將不負賠償責任。同意請按「是」,拒絕請按「否」。",
+ "line1": "允許",
+ "line2": "授權請求?"
+ }
+ }
+ },
+ "AppPermissionsHelp": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% fordert folgende Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Im Einstellungsmenü der mobilen Apps können Sie diese Berechtigungen ändern und sich detaillierte Beschreibungen anhören. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press yes to grant permissions or no to deny."
+ },
+ "es-en": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando los siguientes permisos e información del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y escuchar descripciones detalladas en el menú de configuración de la aplicación móvil. Pulse sí para conceder el permiso o no para denegarlo."
+ },
+ "es-mx": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "it-it": {
+ "tts": "%appName% richiede le seguenti informazioni e autorizzazioni riguardo il veicolo: %functionalGroupLabels%. È possibile modificare tali autorizzazioni e ascoltare descrizioni dettagliate nel menu impostazioni delle app mobili. Premere Sì per concedere le autorizzazioni e No per negarle."
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. U kunt deze toestemmingen wijzigen en gedetailleerde beschrijvingen beluisteren in het instellingenmenu voor mobiele apps. Druk op Ja om permissies te verlenen of op Nee om te weigeren."
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz zezwoleń: %functionalGroupLabels%. W menu ustawień aplikacji mobilnych można zmienić owe zezwolenia i usłyszeć ich szczegółowy opis. Naciśnij TAK, aby wyrazić zgodę lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando as seguintes informações e permissões do veículo: %functionalGroupLabels%. Você pode alterar estas permissões e ouvir descrições detalhadas no menu de configurações de aplicativos móveis. Pressione sim para conceder as permissões ou não para negar."
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar as seguintes informações e permissões do veículo: %functionalGroupLabels%. Pode alterar estas permissões e ouvir descrições detalhadas no menu de definições das aplicações móveis. Prima \"\"Sim\"\" para permitir ou \"\"Não\"\" para recusar."
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Вы можете изменить эти разрешения и прослушать подробные их описания в меню настроек мобильного приложения. Нажмите \"\"да\"\", чтобы предоставить разрешения, или \"\"нет\"\", чтобы не предоставлять."
+ },
+ "sv-se": {
+ "tts": "%appName% begär tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Du kan ändra tillstånden och höra detaljerade beskrivningar i menyn för mobilappsinställningar. Tryck Ja för att ge tillstånd eller Nej för att neka."
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri istiyor: %functionalGroupLabels%. Bu izinleri değiştirebilir ve mobil uygulamalar ayarlar menüsünden ayrıntılı açıklamaları dinleyebilirsiniz. Lütfen izin vermek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求下列车辆信息和权限: %functionalGroupLabels%。您可在移动应用程序设置菜单中更改这些权限,并听取详细说明。请按“是”允许权限或按“否”拒绝。"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。您可在行動應用程式設定清單中更改這些許可,並聆聽詳細說明。給予許可請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsRevoked": {
+ "languages": {
+ "de-de": {
+ "tts": "Die Autorisierungsdaten der App wurden geändert. %appName% hat keinen Zugriff auf %functionalGroupLabels% mehr. Installieren Sie die neueste Version der App auf Ihrem Gerät.."
+ },
+ "en-au": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-gb": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-ie": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-us": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "es-en": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "es-es": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de que tiene la versión más reciente de la aplicación instalada en su dispositivo móvil."
+ },
+ "es-mx": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "fr-ca": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "fr-fr": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "it-it": {
+ "tts": "Le autorizzazioni dell'app sono cambiate. %appName% non è più in grado di accedere a %functionalGroupLabels%. Assicurarsi di avere la versione più recente dell'app installata sul dispositivo mobile."
+ },
+ "nl-nl": {
+ "tts": "De app-autorisaties zijn gewijzigd. %appName% heeft geen toegang meer tot %functionalGroupLabels%. Zorg ervoor dat u de meest recente app-versie op uw mobiele apparaat geïnstalleerd hebt."
+ },
+ "pl-pl": {
+ "tts": "Dane dostępu aplikacji zostały zmienione. %appName% nie ma już dostępu do %functionalGroupLabels%. Sprawdź, czy na telefonie komórkowym zainstalowano najnowszą wersję aplikacji."
+ },
+ "pt-br": {
+ "tts": "As autorizações dos aplicativos foram alteradas. %appName% não pode mais acessar %functionalGroupLabels%. Certifique-se de que a versão mais recente do aplicativo está instalada no seu dispositivo móvel."
+ },
+ "pt-pt": {
+ "tts": "As autorizações das aplicações mudaram. %appName% já não consegue aceder a %functionalGroupLabels%. Certifique-se de que tem a última versão da aplicação no seu dispositivo móvel."
+ },
+ "ru-ru": {
+ "tts": "Авторизации приложения изменены. %appName% больше не имеет доступа к %functionalGroupLabels%. Убедитесь, что на вашем мобильном устройстве установлена самая новая версия приложения."
+ },
+ "sv-se": {
+ "tts": "Appens behörigheter har ändrats. %appName% har inte längre åtkomst till %functionalGroupLabels%. Kontrollera att du har installerat den senaste versionen av appen på mobilenheten."
+ },
+ "tr-tr": {
+ "tts": "Uygulama yetkileri değişti. %appName% artık %functionalGroupLabels%'e erişemeyecek. Lütfen mobil aygıtınızda en son uygulama sürümünün yüklü olduğundan emin olun."
+ },
+ "zh-cn": {
+ "tts": "应用程序授权已变更。 %appName% 将不能再访问 %functionalGroupLabels%。 请确认您的移动设备上安装的应用程序是最新版本。"
+ },
+ "zh-tw": {
+ "tts": "應用程式授權已改變。%appName% 已無法進入 %functionalGroupLabels%。請確認您的行動裝置上安裝了最新版應用程式。"
+ }
+ }
+ },
+ "AppUnauthorized": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% ist nicht autorisiert und wird nicht mit SYNC funktionieren.",
+ "line1": "nicht autorisiert"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized",
+ "textBody": "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "Not Authorized",
+ "textBody": "This version of %appName% is no longer authorized to work with AppLink. Please update to the latest version of %appName%."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada",
+ "textBody": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no está autorizada y no funcionará con SYNC.",
+ "line1": "No autorizada"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada"
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée",
+ "textBody": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è autorizzata e non funziona con il SYNC.",
+ "line1": "non autorizzata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% is niet geautoriseerd en werkt niet met SYNC.",
+ "line1": "niet geautoriseerd"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie posiada autoryzacji i nie będzie działać z SYNC.",
+ "line1": "brak autoryzacji"
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não tem autorização e não funcionará com o SYNC.",
+ "line1": "não autorizado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não está autorizada e não funcionará com o SYNC.",
+ "line1": "não autorizada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не авторизирована и не будет работать с SYNC.",
+ "line1": "не авторизировано"
+ },
+ "sv-se": {
+ "tts": "Den här versionen av %appName% är inte godkänd och fungerar inte med SYNC.",
+ "line1": "är ej godkänd"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümüne izin verilmediğinden SYNC ile çalışamaz.",
+ "line1": "için izin yok"
+ },
+ "zh-cn": {
+ "tts": "此版本的%appName% 未得到授权,无法在SYNC上使用。",
+ "line1": "未得到授权"
+ },
+ "zh-tw": {
+ "tts": "%appName% 的版本未獲得授權,將無法透過 SYNC 使用。",
+ "line1": "無授權"
+ }
+ }
+ },
+ "AppUnsupported": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% wird von SYNC nicht unterstützt.",
+ "line1": "nicht unterstützt"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported",
+ "textBody": "This version of %appName% is not supported by SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "Not Supported",
+ "textBody": "Your version of %appName% is not supported by SYNC."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible",
+ "textBody": "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "No compatible"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible"
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible",
+ "textBody": "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è supportata dal SYNC.",
+ "line1": "non supportata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% wordt niet ondersteund door SYNC.",
+ "line1": "niet ondersteund"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie jest obsługiwana przez system SYNC.",
+ "line1": "aplikacja nie obsług."
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não é suportada pelo SYNC.",
+ "line1": "não suportado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não é suportado pelo SYNC.",
+ "line1": "não suportada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не поддерживается SYNC.",
+ "line1": "не поддерживается"
+ },
+ "sv-se": {
+ "tts": "SYNC har inte stöd för den här versionen av %appName%.",
+ "line1": "stöds ej"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümü SYNC tarafından desteklenmiyor.",
+ "line1": "desteklenmiyor"
+ },
+ "zh-cn": {
+ "tts": "SYNC不支持此版本的%appName%。",
+ "line1": "不受支持"
+ },
+ "zh-tw": {
+ "tts": "SYNC 不支援此版本的%appName% 。",
+ "line1": "不支援"
+ }
+ }
+ },
+ "DataConsent": {
+ "languages": {
+ "en-gb": {
+ "textBody": "Would you like to enable Mobile Apps on SYNC? To use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S. Updates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "en-us": {
+ "line1": "Enable Mobile Apps",
+ "line2": "on SYNC? (Uses Data)",
+ "textBody": "Would you like to enable Mobile Apps on SYNC?\n\nTo use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S.\n\nUpdates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "es-en": {
+ "textBody": "Para usar aplicaciones móviles con SYNC, este debe comunicarse con Ford al menos una vez al mes a través del plan de datos de su dispositivo móvil. Pueden aplicar tarifas normales. SYNC enviará su VIN y el número de módulo de SYNC a Ford de Estados Unidos de América. Las actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario. /r Presione Sí para permitir y No para denegar."
+ },
+ "fr-ca": {
+ "textBody": "Pour utiliser AppLink, SYNC devra communiquer avec Ford au moins une fois par mois en utilisant le forfait de données de votre appareil mobile. Les tarifs réguliers peuvent s’appliquer. SYNC enverra votre NIV et le numéro de votre module SYNC à Ford États-Unis. Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements. /r Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ }
+ }
+ },
+ "DataConsentHelp": {
+ "languages": {
+ "en-us": {
+ "textBody": "Updates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. See your Owner Guide for more information."
+ },
+ "es-en": {
+ "textBody": "Las actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario."
+ },
+ "fr-ca": {
+ "textBody": "Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements."
+ }
+ }
+ },
+ "DisableApps": {
+ "languages": {
+ "de-de": {
+ "tts": "Ausschalten der automatischen Updates führt zum Ausschalten von SYNC mobile Apps. Sie können Ihre mobilen Apps dann nicht mehr mit SYNC nutzen. Bitte drücken Sie Ja zur Bestätigung oder Nein, um abzubrechen.",
+ "line1": "Auto-Update",
+ "line2": "und Mobile Apps deaktivieren"
+ },
+ "en-au": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-gb": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-ie": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-us": {
+ "tts": "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel.",
+ "line1": "Disable Auto-Updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel."
+ },
+ "es-en": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?",
+ "textBody": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "es-es": {
+ "tts": "Si desactiva las actualizaciones automáticas, también se desactivará la sincronización de las aplicaciones móviles. No podrá utilizar ninguna aplicación móvil con SYNC. Pulse sí para confirmar o no para cancelar.",
+ "line1": "¿Desact. actual. auto",
+ "line2": "y apl. móviles?"
+ },
+ "es-mx": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?"
+ },
+ "fr-ca": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?",
+ "textBody": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "fr-fr": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?"
+ },
+ "it-it": {
+ "tts": "Disabilitando gli aggiornamenti automatici si disattiva anche la sincronizzazione delle app mobili. Non sarà possibile usare app mobili con il SYNC. Premere Sì per confermare e No per cancellare.",
+ "line1": "Disabilitare agg. aut.",
+ "line2": "e app mobili?"
+ },
+ "nl-nl": {
+ "tts": "Door automatische updates uit te schakelen, schakelt u ook SYNC-mobiele apps uit. U kunt dan geen mobiele apps meer gebruiken met SYNC. Druk op Ja om te bevestigen of op Nee om te annuleren.",
+ "line1": "Auto-updates en mob.",
+ "line2": "apps uitschakelen?"
+ },
+ "pl-pl": {
+ "tts": "Wyłączenie automatycznych aktualizacji spowoduje także wyłączenie aplikacji mobilnych SYNC. Korzystanie z mobilnych aplikacji za pomocą SYNC będzie niemożliwe. Naciśnij TAK, by potwierdzić lub NIE, by anulować.",
+ "line1": "Wył. automat. aktual.",
+ "line2": "i aplikacje mobilne?"
+ },
+ "pt-br": {
+ "tts": "Se as atualizações automáticas forem desativadas, os aplicativos também serão desativados. Você não poderá usar nenhum aplicativo com o SYNC. Pressione sim para confirmar ou não para cancelar.",
+ "line1": "Desativar atualizações",
+ "line2": "autom. e aplicativos?"
+ },
+ "pt-pt": {
+ "tts": "A desactivação das actualizações automáticas desactiva igualmente as aplicações móveis do SYNC. Não poderá utilizar quaisquer aplicações móveis com o SYNC. Prima \"\"Sim\"\" para confirmar ou \"\"Não\"\" para cancelar.",
+ "line1": "Desact. actual. autom.",
+ "line2": "e aplicações móveis?"
+ },
+ "ru-ru": {
+ "tts": "При отключении автоматических обновлений также будут отключены мобильные приложения sync. Вы не сможете использовать какие-либо мобильные приложения с SYNC. Нажмите \"\"Да\"\" для подтверждения или \"\"Нет\"\" для отмены.",
+ "line1": "Откл. автообновления",
+ "line2": "и мобил. прилож.?"
+ },
+ "sv-se": {
+ "tts": "Om du avaktiverar automatisk uppdatering avaktiverar du även synkning av mobilappar. Du kommer inte längre att kunna använda dina mobilappar med SYNC. Tryck Ja för att bekräfta eller Nej för att avbryta.",
+ "line1": "Avaktiverar autouppdat.",
+ "line2": "och mobilappar?"
+ },
+ "tr-tr": {
+ "tts": "Otomatik güncellemeleri devre dışı bırakırsanız sync mobil uygulamalar da devre dışı kalır. SYNC ile mobil uygulama kullanmanız mümkün olmaz. Lütfen onaylamak için Evet'e veya iptal etmek için Hayır'a basın.",
+ "line1": "Oto. güncelleme ve",
+ "line2": "mobil uygul. kapat?"
+ },
+ "zh-cn": {
+ "tts": "禁用自动更新同时也会禁用SYNC移动应用程序。您将无法在 SYNC 中使用任何移动应用程序。请按“是”确认或按“否”取消。",
+ "line1": "是否禁用自动更新和",
+ "line2": "移动应用程序?"
+ },
+ "zh-tw": {
+ "tts": "停用自動更新也將停用 sync 行動應用程式。您將無法透過 SYNC 使用任何行動應用程式。確認請按「是」,取消請按「否」。",
+ "line1": "停用自動更新",
+ "line2": "和行動應用程式?"
+ }
+ }
+ },
+ "DrivingCharacteristics": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahreigenschaften: Kraftstoffverbrauch, MyKey, Sicherheitsgurtstatus.",
+ "label": "Fahreigenschaften"
+ },
+ "en-au": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-gb": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-ie": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-us": {
+ "tts": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status.",
+ "label": "Driving Characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo",
+ "textBody": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a las siguientes características de conducción: Consumo de combustible, MyKey, Estado cinturones de seguridad.",
+ "label": "Características de conducción"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite",
+ "textBody": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti caratteristiche di guida: Consumo carburante, MyKey, Stato cinture di sicurezza.",
+ "label": "Caratteristiche di guida"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende rijkenmerken: Brandstofverbruik, MyKey, Veiligheidsgordelstatus.",
+ "label": "Rijkenmerken"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji dotyczących jazdy: Zużycie paliwa, MyKey, Stan pasów bezpieczeństwa.",
+ "label": "Informacje dotyczące stylu jazdy"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes características de condução: Consumo de combustível, MyKey, Estado do cinto de segurança.",
+ "label": "Características de condução"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações de condução: Consumo de combustível, MyKey, Estado dos cintos de segurança.",
+ "label": "Características de condução"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим характеристикам движения: Расход топлива, MyKey, Состояние ремней безопасности.",
+ "label": "Характеристики движения"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande köregenskaper: Bränsleförbrukning, MyKey, Bältesstatus.",
+ "label": "Köregenskaper"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu sürüş karakteristiklerine erişebilir: Yakıt tüketimi, MyKey, Emniyet kemeri durumu.",
+ "label": "Sürüş karakteristikleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列行驶特性: 油耗, MyKey, 安全带状态",
+ "label": "行驶特性"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取以下駕駛特性: 油耗, MyKey, 安全帶狀態",
+ "label": "駕駛特性"
+ }
+ }
+ },
+ "Location": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die GPS-Daten und die Geschwindigkeit des Fahrzeugs.",
+ "label": "GPS und Geschwindigkeit"
+ },
+ "en-au": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-gb": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "en-ie": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-us": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad",
+ "textBody": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder al GPS y la velocidad del vehículo.",
+ "label": "GPS y velocidad"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse",
+ "textBody": "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso a GPS e velocità del veicolo.",
+ "label": "GPS e velocità"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot gps en de snelheid van het voertuig.",
+ "label": "Gps en snelheid"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do modułu GPS i prędkości pojazdu.",
+ "label": "GPS i prędkość"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar o GPS e a velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder ao GPS e à velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к GPS и скорости автомобиля.",
+ "label": "GPS и скорость"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt fordonets GPS och hastighetsmätare.",
+ "label": "GPS och hastighet"
+ },
+ "tr-tr": {
+ "tts": "Bu uygulama aracın GPS ve hız bilgilerine erişebilir.",
+ "label": "GPS ve hız"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可以访问车辆 GPS 和车速信息。",
+ "label": "GPS 和车速"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取車輛的GPS和速度。",
+ "label": "GPS和車速"
+ }
+ }
+ },
+ "Notifications": {
+ "languages": {
+ "de-de": {
+ "tts": "Läuft die App im Hintergrund, kann Sie Benachrichtigungen senden.",
+ "label": "Push-Benachrichtigungen"
+ },
+ "en-au": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-gb": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "en-ie": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-us": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push",
+ "textBody": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede enviar notificaciones cuando se está ejecutando en segundo plano.",
+ "label": "Notificaciones push"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push"
+ },
+ "fr-ca": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications instantanées",
+ "textBody": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "fr-fr": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications push"
+ },
+ "it-it": {
+ "tts": "Un'app può inviare notifiche se eseguita in background.",
+ "label": "Notifiche push"
+ },
+ "nl-nl": {
+ "tts": "Een app kan meldingen versturen als deze op de achtergrond actief is.",
+ "label": "Push-meldingen"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może wysyłać powiadomienia, działając w tle.",
+ "label": "Powiadomienia Push"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode enviar notificações quando estiver sendo executado em segundo plano.",
+ "label": "Notificações Push"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue enviar notificações quando está activa em segundo plano.",
+ "label": "Notificações push"
+ },
+ "ru-ru": {
+ "tts": "Если приложение работает в фоновом режиме, оно может отправлять оповещения.",
+ "label": "Оповещения о пересылке"
+ },
+ "sv-se": {
+ "tts": "Appen kan skicka meddelanden när den körs i bakgrunden.",
+ "label": "Push-notiser"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama arka planda çalışırken bildirim gönderebilir.",
+ "label": "Anlık bildirimleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序在后台运行时可推送通知。",
+ "label": "推送通知"
+ },
+ "zh-tw": {
+ "tts": "車輛行進時,應用程式可在背景中傳送通知。",
+ "label": "傳送通知"
+ }
+ }
+ },
+ "SettingDisableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Updates deakt."
+ },
+ "en-au": {
+ "line1": "Disable updates"
+ },
+ "en-gb": {
+ "line1": "Disable updates"
+ },
+ "en-ie": {
+ "line1": "Disable updates"
+ },
+ "en-us": {
+ "line1": "Disable Updates",
+ "textBody": "Disable Updates"
+ },
+ "es-en": {
+ "line1": "Deshab. actual.",
+ "textBody": "Deshab. actual."
+ },
+ "es-es": {
+ "line1": "Desact. actual."
+ },
+ "es-mx": {
+ "line1": "Deshab. actual."
+ },
+ "fr-ca": {
+ "line1": "Désactiver MAJ",
+ "textBody": "Désactiver MAJ"
+ },
+ "fr-fr": {
+ "line1": "Désactiver màj"
+ },
+ "it-it": {
+ "line1": "Disabilita agg."
+ },
+ "nl-nl": {
+ "line1": "Upd. uitschak."
+ },
+ "pl-pl": {
+ "line1": "Wyłącz aktual."
+ },
+ "pt-br": {
+ "line1": "Desat. atualiz."
+ },
+ "pt-pt": {
+ "line1": "Desact. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Откл. обновл."
+ },
+ "sv-se": {
+ "line1": "Inaktivera uppd."
+ },
+ "tr-tr": {
+ "line1": "Güncell. Kapat"
+ },
+ "zh-cn": {
+ "line1": "禁用更新"
+ },
+ "zh-tw": {
+ "line1": "停用更新"
+ }
+ }
+ },
+ "SettingEnableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Apps aktivieren"
+ },
+ "en-au": {
+ "line1": "Enable Apps"
+ },
+ "en-gb": {
+ "line1": "Enable Apps"
+ },
+ "en-ie": {
+ "line1": "Enable Apps"
+ },
+ "en-us": {
+ "line1": "Enable Apps"
+ },
+ "es-en": {
+ "line1": "Hab. aplic."
+ },
+ "es-es": {
+ "line1": "Activar apl."
+ },
+ "es-mx": {
+ "line1": "Hab. aplic."
+ },
+ "fr-ca": {
+ "line1": "Activer app.",
+ "textBody": "Activer app."
+ },
+ "fr-fr": {
+ "line1": "Activer app."
+ },
+ "it-it": {
+ "line1": "Abilita app"
+ },
+ "nl-nl": {
+ "line1": "Apps inschak."
+ },
+ "pl-pl": {
+ "line1": "Włącz aplikacje"
+ },
+ "pt-br": {
+ "line1": "Ativar aplic."
+ },
+ "pt-pt": {
+ "line1": "Activar actualiz."
+ },
+ "ru-ru": {
+ "line1": "Вкл. прилож."
+ },
+ "sv-se": {
+ "line1": "Aktivera appar"
+ },
+ "tr-tr": {
+ "line1": "Uygulamaları aç"
+ },
+ "zh-cn": {
+ "line1": "启用应用程序"
+ },
+ "zh-tw": {
+ "line1": "啟用應用程式"
+ }
+ }
+ },
+ "SettingUpdateAuto": {
+ "languages": {
+ "de-de": {
+ "line1": "Update anford."
+ },
+ "en-au": {
+ "line1": "Request update"
+ },
+ "en-gb": {
+ "line1": "Request update"
+ },
+ "en-ie": {
+ "line1": "Request update"
+ },
+ "en-us": {
+ "line1": "Request Update",
+ "textBody": "Select `Update now` to receive app authorization information for your SYNC-enabled mobile apps. This may enable additional functionality depending on the app and your settings. If your phone has a working data connection, an update should complete in less than 1 minute."
+ },
+ "es-en": {
+ "line1": "Solicit. actualiz.",
+ "textBody": "Solicit. actualiz."
+ },
+ "es-es": {
+ "line1": "Solicitar actual."
+ },
+ "es-mx": {
+ "line1": "Solicit. actualiz."
+ },
+ "fr-ca": {
+ "line1": "Demander MAJ",
+ "textBody": "Demander MAJ"
+ },
+ "fr-fr": {
+ "line1": "Demander màj"
+ },
+ "it-it": {
+ "line1": "Rich. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Upd. aanvragen"
+ },
+ "pl-pl": {
+ "line1": "Zażądaj aktual."
+ },
+ "pt-br": {
+ "line1": "Solicitar atualiz."
+ },
+ "pt-pt": {
+ "line1": "Solicit. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Запрос на обн."
+ },
+ "sv-se": {
+ "line1": "Begär uppdat."
+ },
+ "tr-tr": {
+ "line1": "Güncelleme iste"
+ },
+ "zh-cn": {
+ "line1": "请求更新"
+ },
+ "zh-tw": {
+ "line1": "請求更新"
+ }
+ }
+ },
+ "StatusNeeded": {
+ "languages": {
+ "de-de": {
+ "line1": "Update benötigt"
+ },
+ "en-au": {
+ "line1": "Update needed"
+ },
+ "en-gb": {
+ "line1": "Update needed",
+ "textBody": "Update needed"
+ },
+ "en-ie": {
+ "line1": "Update needed"
+ },
+ "en-us": {
+ "line1": "Update Needed",
+ "textBody": "Update Needed"
+ },
+ "es-en": {
+ "line1": "Actualiz. neces.",
+ "textBody": "Actualiz. neces."
+ },
+ "es-es": {
+ "line1": "Actu. necesaria"
+ },
+ "es-mx": {
+ "line1": "Actualiz. neces."
+ },
+ "fr-ca": {
+ "line1": "Màj requise",
+ "textBody": "Màj requise"
+ },
+ "fr-fr": {
+ "line1": "Mise à jour requise"
+ },
+ "it-it": {
+ "line1": "Necess. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Update nodig"
+ },
+ "pl-pl": {
+ "line1": "Potrzeba aktual."
+ },
+ "pt-br": {
+ "line1": "Atualiz. necess."
+ },
+ "pt-pt": {
+ "line1": "Actual. necess."
+ },
+ "ru-ru": {
+ "line1": "Необх. обновл."
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs"
+ },
+ "tr-tr": {
+ "line1": "Güncellenmeli"
+ },
+ "zh-cn": {
+ "line1": "需要进行更新"
+ },
+ "zh-tw": {
+ "line1": "需更新"
+ }
+ }
+ },
+ "StatusPending": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktualisieren..."
+ },
+ "en-au": {
+ "line1": "Updating..."
+ },
+ "en-gb": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "en-ie": {
+ "line1": "Updating..."
+ },
+ "en-us": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "es-en": {
+ "line1": "Actualizando...",
+ "textBody": "Actualizando..."
+ },
+ "es-es": {
+ "line1": "Actualizando..."
+ },
+ "es-mx": {
+ "line1": "Actualizando..."
+ },
+ "fr-ca": {
+ "line1": "MAJ en cours...",
+ "textBody": "MAJ en cours..."
+ },
+ "fr-fr": {
+ "line1": "Màj en cours..."
+ },
+ "it-it": {
+ "line1": "Aggiornamento"
+ },
+ "nl-nl": {
+ "line1": "Updaten..."
+ },
+ "pl-pl": {
+ "line1": "Aktualizowanie"
+ },
+ "pt-br": {
+ "line1": "Atualizando..."
+ },
+ "pt-pt": {
+ "line1": "A actualizar..."
+ },
+ "ru-ru": {
+ "line1": "Обновление..."
+ },
+ "sv-se": {
+ "line1": "Uppdaterar..."
+ },
+ "tr-tr": {
+ "line1": "Güncelleniyor..."
+ },
+ "zh-cn": {
+ "line1": "正在更新......"
+ },
+ "zh-tw": {
+ "line1": "更新中..."
+ }
+ }
+ },
+ "StatusUpToDate": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktuelle Version"
+ },
+ "en-au": {
+ "line1": "Up-to-date"
+ },
+ "en-gb": {
+ "line1": "Up-to-date",
+ "textBody": "Up-to-date"
+ },
+ "en-ie": {
+ "line1": "Up-to-date"
+ },
+ "en-us": {
+ "line1": "Up-To-Date",
+ "textBody": "Up-To-Date"
+ },
+ "es-en": {
+ "line1": "Actualizado",
+ "textBody": "Actualizado"
+ },
+ "es-es": {
+ "line1": "Actualizada"
+ },
+ "es-mx": {
+ "line1": "Actualizado"
+ },
+ "fr-ca": {
+ "line1": "Déjà à jour",
+ "textBody": "Déjà à jour"
+ },
+ "fr-fr": {
+ "line1": "Déjà à jour"
+ },
+ "it-it": {
+ "line1": "più recente"
+ },
+ "nl-nl": {
+ "line1": "Up-to-date"
+ },
+ "pl-pl": {
+ "line1": "Aktualne"
+ },
+ "pt-br": {
+ "line1": "Atualizado"
+ },
+ "pt-pt": {
+ "line1": "Actualizado"
+ },
+ "ru-ru": {
+ "line1": "Обновлено"
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs ej"
+ },
+ "tr-tr": {
+ "line1": "Güncel"
+ },
+ "zh-cn": {
+ "line1": "最新更新"
+ },
+ "zh-tw": {
+ "line1": "更新最新"
+ }
+ }
+ },
+ "VehicleInfo": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahrzeuginformationen: Kraftstoff-Füllstand, Kraftstoffverbrauch, Motordrehzahl, Kilometerzähler, FIN, Außentemperatur, Gangstellung, Reifenluftdruck.",
+ "label": "Fahrzeuginformationen"
+ },
+ "en-au": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-gb": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure."
+ },
+ "en-ie": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-us": {
+ "tts": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo",
+ "textBody": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a la siguiente información del vehículo: Nivel de combustible, Ahorro de combustible, RPM del motor, Cuentakilómetros, VIN, Temperatura aire exterior, Marcha engranada, Presión de neumáticos.",
+ "label": "Información del vehículo"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus.",
+ "label": "Renseignements du véhicule",
+ "textBody": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Vitesse de moteur, Compteur kilométrique, NIV, Température extérieure, Position de vitesse, Pression des pneus.",
+ "label": "Renseignements du véhicule"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti informazioni del veicolo: Livello carburante, Consumi carburante, Numero giri motore, Contachilometri, VIN, Temperatura esterna, Posizione marcia, Pressione pneumatici.",
+ "label": "Informazioni sul veicolo"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende voertuiginformatie: Brandstofpeil, Brandstofverbruik, Motortoerental, Kilometerteller, VIN, Buitentemperatuur, Versnellingsstand, Bandenspanning.",
+ "label": "Voertuiginformatie"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji o pojeździe: Poziom paliwa, Zużycie paliwa, Obroty silnika, Licznik przebiegu, Numer VIN, Temperatura zewnętrzna, Aktualny bieg, Ciśnienie opon.",
+ "label": "Informacje o pojeździe"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes informações sobre o veículo: Nível de combustível, Economia de combustível, RPM do motor, Hodômetro, VIN, Temperatura externa, Posição das marchas, Pressão dos pneus.",
+ "label": "Informações sobre o veículo"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações do veículo: Nível de combustível, Poupança de combustível, RPM do motor, Conta-quilómetros, VIN, Temperatura exterior, Posição da mudança de velocidade, Pressão dos pneus.",
+ "label": "Informações do veículo"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим данным автомобиля: Уровень топлива, Економия топлива, Число оборотов двигателя, Одометр, Номер VIN, Температура за бортом, Положение передачи, Давление шин.",
+ "label": "Информация об автомобиле"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande fordonsinformation: Bränslenivå, Bränsleekonomi, Motorns varvtal, Vägmätare, VIN, Utetemperatur, Växelläge, Däcktryck.",
+ "label": "Fordonsinformation"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu araç bilgilerine erişebilir: Yakıt seviyesi, Yakıt ekonomisi, Motor devirleri, Kilometre sayacı, VIN, Dış sıcaklık, Vites konumu, Lastik basıncı.",
+ "label": "Araç bilgisi"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列车辆信息 : 燃油量, 燃油经济性, 发动机转速(RPM), 里程表, VIN, 车外温度, 档位, 胎压.",
+ "label": "车辆信息"
+ },
+ "zh-tw": {
+ "tts": "一個應用程式可存取以下車輛資訊 : 燃油存量, 燃油經濟性, 引擎轉速, 里程表, 車輛識別號碼, 車外溫度, 檔位, 胎壓.",
+ "label": "車輛資訊"
+ }
+ }
+ }
+ }
+ },
+ "app_policies": {
+ "default": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["Base-4"],
+ "RequestType": [
+ "HTTP",
+ "FILE_RESUMED",
+ "INVALID_REQUEST_TYPE"
+ ]
+ },
+ "1234": "default",
+ "device": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["DataConsent-2"]
+ },
+ "pre_DataConsent": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["BaseBeforeDataConsent"],
+ "RequestType": [
+ "QUERY_APPS",
+ "LAUNCH_APP",
+ "PROPRIETARY",
+ "INVALID_REQUEST_TYPE"
+ ]
+ }
+ }
+ }
+ }
+
diff --git a/src/components/policy/test/PTU4.json b/src/components/policy/test/PTU4.json
new file mode 100644
index 0000000000..ab4c2f8927
--- /dev/null
+++ b/src/components/policy/test/PTU4.json
@@ -0,0 +1,1954 @@
+ {
+ "policy_table": {
+ "module_config": {
+ "preloaded_pt": true,
+ "preloaded_date": "2015-12-08",
+ "exchange_after_x_ignition_cycles": 100,
+ "exchange_after_x_kilometers": 1800,
+ "exchange_after_x_days": 30,
+ "timeout_after_x_seconds": 60,
+ "seconds_between_retries": [1,
+ 5,
+ 25,
+ 125,
+ 625],
+ "endpoints": {
+ "0x07": {
+ "default": ["http://policies.telematics.ford.com/api/policies"]
+ }
+ },
+ "notifications_per_minute_by_priority": {
+ "EMERGENCY": 60,
+ "NAVIGATION": 15,
+ "COMMUNICATION": 6,
+ "NORMAL": 4,
+ "NONE": 0
+ }
+ },
+ "functional_groupings": {
+ "Base-4": {
+ "rpcs": {
+ "AddCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "AddSubMenu": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "Alert": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "ChangeRegistration": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "CreateInteractionChoiceSet": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "DeleteInteractionChoiceSet": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "DeleteSubMenu": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "EndAudioPassThru": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "GenericResponse": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ListFiles": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAudioPassThru": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnButtonEvent": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "OnButtonPress": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "OnCommand": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnDriverDistraction": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHashChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "PerformAudioPassThru": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "PerformInteraction": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "PutFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ResetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ScrollableMessage": {
+ "hmi_levels": ["FULL"]
+ },
+ "SetAppIcon": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetGlobalProperties": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "SetMediaClockTimer": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "Show": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "Slider": {
+ "hmi_levels": ["FULL"]
+ },
+ "Speak": {
+ "hmi_levels": ["FULL",
+ "LIMITED"]
+ },
+ "SubscribeButton": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "SystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnsubscribeButton": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "Location-1": {
+ "user_consent_prompt": "Location",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["gps",
+ "speed"]
+ }
+ }
+ },
+ "Notifications": {
+ "user_consent_prompt": "Notifications",
+ "rpcs": {
+ "Alert": {
+ "hmi_levels": ["BACKGROUND"]
+ }
+ }
+ },
+ "DrivingCharacteristics-3": {
+ "user_consent_prompt": "DrivingCharacteristics",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"]
+ }
+ }
+ },
+ "VehicleInfo-3": {
+ "user_consent_prompt": "VehicleInfo",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"]
+ }
+ }
+ },
+ "PropriataryData-1": {
+ "rpcs": {
+ "DiagnosticMessage": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "GetDTCs": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ReadDID": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "Emergency-1": {
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "OnVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"],
+ "parameters": ["airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"]
+ }
+ }
+ },
+ "Navigation-1": {
+ "rpcs": {
+ "AlertManeuver": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "ShowConstantTBT": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ },
+ "UpdateTurnList": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED"]
+ }
+ }
+ },
+ "DataConsent-2": {
+ "user_consent_prompt": "DataConsent",
+ "rpcs": null
+ },
+ "BaseBeforeDataConsent": {
+ "rpcs": {
+ "ChangeRegistration": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "DeleteFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "ListFiles": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHashChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "PutFile": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetAppIcon": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "SystemRequest": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": ["BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"]
+ }
+ }
+ }
+ },
+ "consumer_friendly_messages": {
+ "version": "001.001.019",
+ "messages": {
+ "AppPermissions": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% benötigt die folgenden Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Wenn Sie Ja drücken, erklären Sie sich damit einverstanden, dass %vehicleMake% nicht für Schäden oder Verletzungen der Privatsphäre haftet, die im Zusammenhang mit der Nutzung Ihrer Benutzerdaten durch %appName% entstehen. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab.",
+ "line1": "Zugriffsanfrage(n)",
+ "line2": "erlauben?"
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. Please press yes to allow or no to deny.",
+ "line1": "Grant Requested",
+ "line2": "Permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. \n\nIf you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "es-en": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?",
+ "textBody": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar. \n\n Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando el uso de los siguientes permisos e información del vehículo: %functionalGroupLabels%. Si pulsa sí, acepta que %vehicleMake% no será responsable de los daños o la pérdida de privacidad relacionados con el uso de sus datos por parte de %appName%. Pulse sí para permitir o no para denegar.",
+ "line1": "¿Conceder permisos",
+ "line2": "solicitados?"
+ },
+ "es-mx": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?"
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)",
+ "textBody": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)"
+ },
+ "it-it": {
+ "tts": "%appName% richiede l'uso delle seguenti informazioni e autorizzazioni sul veicolo: %functionalGroupLabels%. Se si preme Sì, si acconsente che %vehicleMake% non sarà responsabile per danni o perdita di privacy in relazione all'impiego dei dati da parte di %appName%. Premere Sì per consentire e No per negare.",
+ "line1": "Concedi autorizzaz.",
+ "line2": "richiesta(e)?"
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. Als u op Ja drukt, gaat u ermee akkoord dat %vehicleMake% in geen geval aansprakelijk gesteld kan worden voor schade of verlies van privacy als gevolg van het feit dat %appName% gebruik maakt van uw gegevens. Druk op Ja om dit toe te staan of Nee om te weigeren.",
+ "line1": "Aangevraagde",
+ "line2": "permissie(s) verlenen?"
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz pozwoleń: %functionalGroupLabels%. Naciśnięcie TAK oznacza zgodę na fakt, iż %vehicleMake% nie będzie ponosić odpowiedzialności za szkody ani utratę prywatności w związku z wykorzystaniem przez %appName% danych, należących do użytkownika. Naciśnij TAK w celu udzielenia zgody lub NIE w celu odrzucenia żądania.",
+ "line1": "Udzielić żądanych",
+ "line2": "pozwoleń?"
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando o uso das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se pressionar sim, você concorda que a %vehicleMake% não será responsável por danos ou perdas de privacidade relacionados ao uso dos seus dados por %appName%. Pressione sim para permitir ou não para negar.",
+ "line1": "Conceder permissão",
+ "line2": "solicitada?"
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar a utilização das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se premir “Sim”, concorda que %vehicleMake% não será responsável por quaisquer danos ou perda de privacidade relacionada com a utilização dos seus dados por parte de %appName%. Prima “Sim” para permitir ou “Não” para recusar.",
+ "line1": "Conceder permiss.",
+ "line2": "solicitada(s)?"
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Нажатием \"\"да\"\", Вы соглашаетесь, что %vehicleMake% не будет нести ответственность за какие-либо убытки или потерю прайвеси, связанные с использованием Ваших данных компанией %appName%. Нажмите \"\"Да\"\", если Вы согласны, или \"\"Нет\"\" - если не согласны.",
+ "line1": "Предост. заправш.",
+ "line2": "разрешения?"
+ },
+ "sv-se": {
+ "tts": "%appName% begär att få tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Om du trycker Ja godkänner du att %vehicleMake% ska hållas skadeslös för alla skador som kan uppstå eller eventuella integritetsintrång som uppstår när %appName% använder dina data. Tryck Ja för att godkänna eller Nej för att neka.",
+ "line1": "Vill du ge",
+ "line2": "tillstånd?"
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri kullanma isteğinde bulunuyor: %functionalGroupLabels%. Evet'e basarsanız, %appName%'in verilerinizi kullanması sonucunda oluşabilecek hasarlardan veya gizlilik kaybından %vehicleMake%'in sorumlu olmayacağını kabul etmiş olacaksınız. Lütfen kabul etmek için Evet'e veya reddetmek için Hayır'a basın.",
+ "line1": "İstenen izinler",
+ "line2": "verilsin mi?"
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求使用下列车辆信息和权限: %functionalGroupLabels%。如果您按“是”,则表示您同意。 %vehicleMake% 将不会对因 %appName% 使用您的数据而引起的任何损毁或隐私损失负责。 请按“是”允许或按“否”拒绝。",
+ "line1": "是否允许请求的",
+ "line2": "权限?"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。按「是」,表示您同意,如因 %appName% 使用您的資料導致任何損害或損失,%vehicleMake% 將不負賠償責任。同意請按「是」,拒絕請按「否」。",
+ "line1": "允許",
+ "line2": "授權請求?"
+ }
+ }
+ },
+ "AppPermissionsHelp": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% fordert folgende Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Im Einstellungsmenü der mobilen Apps können Sie diese Berechtigungen ändern und sich detaillierte Beschreibungen anhören. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press yes to grant permissions or no to deny."
+ },
+ "es-en": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando los siguientes permisos e información del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y escuchar descripciones detalladas en el menú de configuración de la aplicación móvil. Pulse sí para conceder el permiso o no para denegarlo."
+ },
+ "es-mx": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "it-it": {
+ "tts": "%appName% richiede le seguenti informazioni e autorizzazioni riguardo il veicolo: %functionalGroupLabels%. È possibile modificare tali autorizzazioni e ascoltare descrizioni dettagliate nel menu impostazioni delle app mobili. Premere Sì per concedere le autorizzazioni e No per negarle."
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. U kunt deze toestemmingen wijzigen en gedetailleerde beschrijvingen beluisteren in het instellingenmenu voor mobiele apps. Druk op Ja om permissies te verlenen of op Nee om te weigeren."
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz zezwoleń: %functionalGroupLabels%. W menu ustawień aplikacji mobilnych można zmienić owe zezwolenia i usłyszeć ich szczegółowy opis. Naciśnij TAK, aby wyrazić zgodę lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando as seguintes informações e permissões do veículo: %functionalGroupLabels%. Você pode alterar estas permissões e ouvir descrições detalhadas no menu de configurações de aplicativos móveis. Pressione sim para conceder as permissões ou não para negar."
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar as seguintes informações e permissões do veículo: %functionalGroupLabels%. Pode alterar estas permissões e ouvir descrições detalhadas no menu de definições das aplicações móveis. Prima \"\"Sim\"\" para permitir ou \"\"Não\"\" para recusar."
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Вы можете изменить эти разрешения и прослушать подробные их описания в меню настроек мобильного приложения. Нажмите \"\"да\"\", чтобы предоставить разрешения, или \"\"нет\"\", чтобы не предоставлять."
+ },
+ "sv-se": {
+ "tts": "%appName% begär tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Du kan ändra tillstånden och höra detaljerade beskrivningar i menyn för mobilappsinställningar. Tryck Ja för att ge tillstånd eller Nej för att neka."
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri istiyor: %functionalGroupLabels%. Bu izinleri değiştirebilir ve mobil uygulamalar ayarlar menüsünden ayrıntılı açıklamaları dinleyebilirsiniz. Lütfen izin vermek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求下列车辆信息和权限: %functionalGroupLabels%。您可在移动应用程序设置菜单中更改这些权限,并听取详细说明。请按“是”允许权限或按“否”拒绝。"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。您可在行動應用程式設定清單中更改這些許可,並聆聽詳細說明。給予許可請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsRevoked": {
+ "languages": {
+ "de-de": {
+ "tts": "Die Autorisierungsdaten der App wurden geändert. %appName% hat keinen Zugriff auf %functionalGroupLabels% mehr. Installieren Sie die neueste Version der App auf Ihrem Gerät.."
+ },
+ "en-au": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-gb": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-ie": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-us": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "es-en": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "es-es": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de que tiene la versión más reciente de la aplicación instalada en su dispositivo móvil."
+ },
+ "es-mx": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "fr-ca": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "fr-fr": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "it-it": {
+ "tts": "Le autorizzazioni dell'app sono cambiate. %appName% non è più in grado di accedere a %functionalGroupLabels%. Assicurarsi di avere la versione più recente dell'app installata sul dispositivo mobile."
+ },
+ "nl-nl": {
+ "tts": "De app-autorisaties zijn gewijzigd. %appName% heeft geen toegang meer tot %functionalGroupLabels%. Zorg ervoor dat u de meest recente app-versie op uw mobiele apparaat geïnstalleerd hebt."
+ },
+ "pl-pl": {
+ "tts": "Dane dostępu aplikacji zostały zmienione. %appName% nie ma już dostępu do %functionalGroupLabels%. Sprawdź, czy na telefonie komórkowym zainstalowano najnowszą wersję aplikacji."
+ },
+ "pt-br": {
+ "tts": "As autorizações dos aplicativos foram alteradas. %appName% não pode mais acessar %functionalGroupLabels%. Certifique-se de que a versão mais recente do aplicativo está instalada no seu dispositivo móvel."
+ },
+ "pt-pt": {
+ "tts": "As autorizações das aplicações mudaram. %appName% já não consegue aceder a %functionalGroupLabels%. Certifique-se de que tem a última versão da aplicação no seu dispositivo móvel."
+ },
+ "ru-ru": {
+ "tts": "Авторизации приложения изменены. %appName% больше не имеет доступа к %functionalGroupLabels%. Убедитесь, что на вашем мобильном устройстве установлена самая новая версия приложения."
+ },
+ "sv-se": {
+ "tts": "Appens behörigheter har ändrats. %appName% har inte längre åtkomst till %functionalGroupLabels%. Kontrollera att du har installerat den senaste versionen av appen på mobilenheten."
+ },
+ "tr-tr": {
+ "tts": "Uygulama yetkileri değişti. %appName% artık %functionalGroupLabels%'e erişemeyecek. Lütfen mobil aygıtınızda en son uygulama sürümünün yüklü olduğundan emin olun."
+ },
+ "zh-cn": {
+ "tts": "应用程序授权已变更。 %appName% 将不能再访问 %functionalGroupLabels%。 请确认您的移动设备上安装的应用程序是最新版本。"
+ },
+ "zh-tw": {
+ "tts": "應用程式授權已改變。%appName% 已無法進入 %functionalGroupLabels%。請確認您的行動裝置上安裝了最新版應用程式。"
+ }
+ }
+ },
+ "AppUnauthorized": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% ist nicht autorisiert und wird nicht mit SYNC funktionieren.",
+ "line1": "nicht autorisiert"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized",
+ "textBody": "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "Not Authorized",
+ "textBody": "This version of %appName% is no longer authorized to work with AppLink. Please update to the latest version of %appName%."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada",
+ "textBody": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no está autorizada y no funcionará con SYNC.",
+ "line1": "No autorizada"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada"
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée",
+ "textBody": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è autorizzata e non funziona con il SYNC.",
+ "line1": "non autorizzata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% is niet geautoriseerd en werkt niet met SYNC.",
+ "line1": "niet geautoriseerd"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie posiada autoryzacji i nie będzie działać z SYNC.",
+ "line1": "brak autoryzacji"
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não tem autorização e não funcionará com o SYNC.",
+ "line1": "não autorizado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não está autorizada e não funcionará com o SYNC.",
+ "line1": "não autorizada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не авторизирована и не будет работать с SYNC.",
+ "line1": "не авторизировано"
+ },
+ "sv-se": {
+ "tts": "Den här versionen av %appName% är inte godkänd och fungerar inte med SYNC.",
+ "line1": "är ej godkänd"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümüne izin verilmediğinden SYNC ile çalışamaz.",
+ "line1": "için izin yok"
+ },
+ "zh-cn": {
+ "tts": "此版本的%appName% 未得到授权,无法在SYNC上使用。",
+ "line1": "未得到授权"
+ },
+ "zh-tw": {
+ "tts": "%appName% 的版本未獲得授權,將無法透過 SYNC 使用。",
+ "line1": "無授權"
+ }
+ }
+ },
+ "AppUnsupported": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% wird von SYNC nicht unterstützt.",
+ "line1": "nicht unterstützt"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported",
+ "textBody": "This version of %appName% is not supported by SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "Not Supported",
+ "textBody": "Your version of %appName% is not supported by SYNC."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible",
+ "textBody": "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "No compatible"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible"
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible",
+ "textBody": "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è supportata dal SYNC.",
+ "line1": "non supportata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% wordt niet ondersteund door SYNC.",
+ "line1": "niet ondersteund"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie jest obsługiwana przez system SYNC.",
+ "line1": "aplikacja nie obsług."
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não é suportada pelo SYNC.",
+ "line1": "não suportado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não é suportado pelo SYNC.",
+ "line1": "não suportada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не поддерживается SYNC.",
+ "line1": "не поддерживается"
+ },
+ "sv-se": {
+ "tts": "SYNC har inte stöd för den här versionen av %appName%.",
+ "line1": "stöds ej"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümü SYNC tarafından desteklenmiyor.",
+ "line1": "desteklenmiyor"
+ },
+ "zh-cn": {
+ "tts": "SYNC不支持此版本的%appName%。",
+ "line1": "不受支持"
+ },
+ "zh-tw": {
+ "tts": "SYNC 不支援此版本的%appName% 。",
+ "line1": "不支援"
+ }
+ }
+ },
+ "DataConsent": {
+ "languages": {
+ "en-gb": {
+ "textBody": "Would you like to enable Mobile Apps on SYNC? To use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S. Updates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "en-us": {
+ "line1": "Enable Mobile Apps",
+ "line2": "on SYNC? (Uses Data)",
+ "textBody": "Would you like to enable Mobile Apps on SYNC?\n\nTo use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S.\n\nUpdates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "es-en": {
+ "textBody": "Para usar aplicaciones móviles con SYNC, este debe comunicarse con Ford al menos una vez al mes a través del plan de datos de su dispositivo móvil. Pueden aplicar tarifas normales. SYNC enviará su VIN y el número de módulo de SYNC a Ford de Estados Unidos de América. Las actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario. /r Presione Sí para permitir y No para denegar."
+ },
+ "fr-ca": {
+ "textBody": "Pour utiliser AppLink, SYNC devra communiquer avec Ford au moins une fois par mois en utilisant le forfait de données de votre appareil mobile. Les tarifs réguliers peuvent s’appliquer. SYNC enverra votre NIV et le numéro de votre module SYNC à Ford États-Unis. Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements. /r Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ }
+ }
+ },
+ "DataConsentHelp": {
+ "languages": {
+ "en-us": {
+ "textBody": "Updates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. See your Owner Guide for more information."
+ },
+ "es-en": {
+ "textBody": "Las actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario."
+ },
+ "fr-ca": {
+ "textBody": "Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements."
+ }
+ }
+ },
+ "DisableApps": {
+ "languages": {
+ "de-de": {
+ "tts": "Ausschalten der automatischen Updates führt zum Ausschalten von SYNC mobile Apps. Sie können Ihre mobilen Apps dann nicht mehr mit SYNC nutzen. Bitte drücken Sie Ja zur Bestätigung oder Nein, um abzubrechen.",
+ "line1": "Auto-Update",
+ "line2": "und Mobile Apps deaktivieren"
+ },
+ "en-au": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-gb": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-ie": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-us": {
+ "tts": "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel.",
+ "line1": "Disable Auto-Updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel."
+ },
+ "es-en": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?",
+ "textBody": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "es-es": {
+ "tts": "Si desactiva las actualizaciones automáticas, también se desactivará la sincronización de las aplicaciones móviles. No podrá utilizar ninguna aplicación móvil con SYNC. Pulse sí para confirmar o no para cancelar.",
+ "line1": "¿Desact. actual. auto",
+ "line2": "y apl. móviles?"
+ },
+ "es-mx": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?"
+ },
+ "fr-ca": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?",
+ "textBody": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "fr-fr": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?"
+ },
+ "it-it": {
+ "tts": "Disabilitando gli aggiornamenti automatici si disattiva anche la sincronizzazione delle app mobili. Non sarà possibile usare app mobili con il SYNC. Premere Sì per confermare e No per cancellare.",
+ "line1": "Disabilitare agg. aut.",
+ "line2": "e app mobili?"
+ },
+ "nl-nl": {
+ "tts": "Door automatische updates uit te schakelen, schakelt u ook SYNC-mobiele apps uit. U kunt dan geen mobiele apps meer gebruiken met SYNC. Druk op Ja om te bevestigen of op Nee om te annuleren.",
+ "line1": "Auto-updates en mob.",
+ "line2": "apps uitschakelen?"
+ },
+ "pl-pl": {
+ "tts": "Wyłączenie automatycznych aktualizacji spowoduje także wyłączenie aplikacji mobilnych SYNC. Korzystanie z mobilnych aplikacji za pomocą SYNC będzie niemożliwe. Naciśnij TAK, by potwierdzić lub NIE, by anulować.",
+ "line1": "Wył. automat. aktual.",
+ "line2": "i aplikacje mobilne?"
+ },
+ "pt-br": {
+ "tts": "Se as atualizações automáticas forem desativadas, os aplicativos também serão desativados. Você não poderá usar nenhum aplicativo com o SYNC. Pressione sim para confirmar ou não para cancelar.",
+ "line1": "Desativar atualizações",
+ "line2": "autom. e aplicativos?"
+ },
+ "pt-pt": {
+ "tts": "A desactivação das actualizações automáticas desactiva igualmente as aplicações móveis do SYNC. Não poderá utilizar quaisquer aplicações móveis com o SYNC. Prima \"\"Sim\"\" para confirmar ou \"\"Não\"\" para cancelar.",
+ "line1": "Desact. actual. autom.",
+ "line2": "e aplicações móveis?"
+ },
+ "ru-ru": {
+ "tts": "При отключении автоматических обновлений также будут отключены мобильные приложения sync. Вы не сможете использовать какие-либо мобильные приложения с SYNC. Нажмите \"\"Да\"\" для подтверждения или \"\"Нет\"\" для отмены.",
+ "line1": "Откл. автообновления",
+ "line2": "и мобил. прилож.?"
+ },
+ "sv-se": {
+ "tts": "Om du avaktiverar automatisk uppdatering avaktiverar du även synkning av mobilappar. Du kommer inte längre att kunna använda dina mobilappar med SYNC. Tryck Ja för att bekräfta eller Nej för att avbryta.",
+ "line1": "Avaktiverar autouppdat.",
+ "line2": "och mobilappar?"
+ },
+ "tr-tr": {
+ "tts": "Otomatik güncellemeleri devre dışı bırakırsanız sync mobil uygulamalar da devre dışı kalır. SYNC ile mobil uygulama kullanmanız mümkün olmaz. Lütfen onaylamak için Evet'e veya iptal etmek için Hayır'a basın.",
+ "line1": "Oto. güncelleme ve",
+ "line2": "mobil uygul. kapat?"
+ },
+ "zh-cn": {
+ "tts": "禁用自动更新同时也会禁用SYNC移动应用程序。您将无法在 SYNC 中使用任何移动应用程序。请按“是”确认或按“否”取消。",
+ "line1": "是否禁用自动更新和",
+ "line2": "移动应用程序?"
+ },
+ "zh-tw": {
+ "tts": "停用自動更新也將停用 sync 行動應用程式。您將無法透過 SYNC 使用任何行動應用程式。確認請按「是」,取消請按「否」。",
+ "line1": "停用自動更新",
+ "line2": "和行動應用程式?"
+ }
+ }
+ },
+ "DrivingCharacteristics": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahreigenschaften: Kraftstoffverbrauch, MyKey, Sicherheitsgurtstatus.",
+ "label": "Fahreigenschaften"
+ },
+ "en-au": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-gb": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-ie": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-us": {
+ "tts": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status.",
+ "label": "Driving Characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo",
+ "textBody": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a las siguientes características de conducción: Consumo de combustible, MyKey, Estado cinturones de seguridad.",
+ "label": "Características de conducción"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite",
+ "textBody": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti caratteristiche di guida: Consumo carburante, MyKey, Stato cinture di sicurezza.",
+ "label": "Caratteristiche di guida"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende rijkenmerken: Brandstofverbruik, MyKey, Veiligheidsgordelstatus.",
+ "label": "Rijkenmerken"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji dotyczących jazdy: Zużycie paliwa, MyKey, Stan pasów bezpieczeństwa.",
+ "label": "Informacje dotyczące stylu jazdy"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes características de condução: Consumo de combustível, MyKey, Estado do cinto de segurança.",
+ "label": "Características de condução"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações de condução: Consumo de combustível, MyKey, Estado dos cintos de segurança.",
+ "label": "Características de condução"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим характеристикам движения: Расход топлива, MyKey, Состояние ремней безопасности.",
+ "label": "Характеристики движения"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande köregenskaper: Bränsleförbrukning, MyKey, Bältesstatus.",
+ "label": "Köregenskaper"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu sürüş karakteristiklerine erişebilir: Yakıt tüketimi, MyKey, Emniyet kemeri durumu.",
+ "label": "Sürüş karakteristikleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列行驶特性: 油耗, MyKey, 安全带状态",
+ "label": "行驶特性"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取以下駕駛特性: 油耗, MyKey, 安全帶狀態",
+ "label": "駕駛特性"
+ }
+ }
+ },
+ "Location": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die GPS-Daten und die Geschwindigkeit des Fahrzeugs.",
+ "label": "GPS und Geschwindigkeit"
+ },
+ "en-au": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-gb": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "en-ie": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-us": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad",
+ "textBody": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder al GPS y la velocidad del vehículo.",
+ "label": "GPS y velocidad"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse",
+ "textBody": "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso a GPS e velocità del veicolo.",
+ "label": "GPS e velocità"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot gps en de snelheid van het voertuig.",
+ "label": "Gps en snelheid"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do modułu GPS i prędkości pojazdu.",
+ "label": "GPS i prędkość"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar o GPS e a velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder ao GPS e à velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к GPS и скорости автомобиля.",
+ "label": "GPS и скорость"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt fordonets GPS och hastighetsmätare.",
+ "label": "GPS och hastighet"
+ },
+ "tr-tr": {
+ "tts": "Bu uygulama aracın GPS ve hız bilgilerine erişebilir.",
+ "label": "GPS ve hız"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可以访问车辆 GPS 和车速信息。",
+ "label": "GPS 和车速"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取車輛的GPS和速度。",
+ "label": "GPS和車速"
+ }
+ }
+ },
+ "Notifications": {
+ "languages": {
+ "de-de": {
+ "tts": "Läuft die App im Hintergrund, kann Sie Benachrichtigungen senden.",
+ "label": "Push-Benachrichtigungen"
+ },
+ "en-au": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-gb": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "en-ie": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-us": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push",
+ "textBody": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede enviar notificaciones cuando se está ejecutando en segundo plano.",
+ "label": "Notificaciones push"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push"
+ },
+ "fr-ca": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications instantanées",
+ "textBody": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "fr-fr": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications push"
+ },
+ "it-it": {
+ "tts": "Un'app può inviare notifiche se eseguita in background.",
+ "label": "Notifiche push"
+ },
+ "nl-nl": {
+ "tts": "Een app kan meldingen versturen als deze op de achtergrond actief is.",
+ "label": "Push-meldingen"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może wysyłać powiadomienia, działając w tle.",
+ "label": "Powiadomienia Push"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode enviar notificações quando estiver sendo executado em segundo plano.",
+ "label": "Notificações Push"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue enviar notificações quando está activa em segundo plano.",
+ "label": "Notificações push"
+ },
+ "ru-ru": {
+ "tts": "Если приложение работает в фоновом режиме, оно может отправлять оповещения.",
+ "label": "Оповещения о пересылке"
+ },
+ "sv-se": {
+ "tts": "Appen kan skicka meddelanden när den körs i bakgrunden.",
+ "label": "Push-notiser"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama arka planda çalışırken bildirim gönderebilir.",
+ "label": "Anlık bildirimleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序在后台运行时可推送通知。",
+ "label": "推送通知"
+ },
+ "zh-tw": {
+ "tts": "車輛行進時,應用程式可在背景中傳送通知。",
+ "label": "傳送通知"
+ }
+ }
+ },
+ "SettingDisableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Updates deakt."
+ },
+ "en-au": {
+ "line1": "Disable updates"
+ },
+ "en-gb": {
+ "line1": "Disable updates"
+ },
+ "en-ie": {
+ "line1": "Disable updates"
+ },
+ "en-us": {
+ "line1": "Disable Updates",
+ "textBody": "Disable Updates"
+ },
+ "es-en": {
+ "line1": "Deshab. actual.",
+ "textBody": "Deshab. actual."
+ },
+ "es-es": {
+ "line1": "Desact. actual."
+ },
+ "es-mx": {
+ "line1": "Deshab. actual."
+ },
+ "fr-ca": {
+ "line1": "Désactiver MAJ",
+ "textBody": "Désactiver MAJ"
+ },
+ "fr-fr": {
+ "line1": "Désactiver màj"
+ },
+ "it-it": {
+ "line1": "Disabilita agg."
+ },
+ "nl-nl": {
+ "line1": "Upd. uitschak."
+ },
+ "pl-pl": {
+ "line1": "Wyłącz aktual."
+ },
+ "pt-br": {
+ "line1": "Desat. atualiz."
+ },
+ "pt-pt": {
+ "line1": "Desact. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Откл. обновл."
+ },
+ "sv-se": {
+ "line1": "Inaktivera uppd."
+ },
+ "tr-tr": {
+ "line1": "Güncell. Kapat"
+ },
+ "zh-cn": {
+ "line1": "禁用更新"
+ },
+ "zh-tw": {
+ "line1": "停用更新"
+ }
+ }
+ },
+ "SettingEnableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Apps aktivieren"
+ },
+ "en-au": {
+ "line1": "Enable Apps"
+ },
+ "en-gb": {
+ "line1": "Enable Apps"
+ },
+ "en-ie": {
+ "line1": "Enable Apps"
+ },
+ "en-us": {
+ "line1": "Enable Apps"
+ },
+ "es-en": {
+ "line1": "Hab. aplic."
+ },
+ "es-es": {
+ "line1": "Activar apl."
+ },
+ "es-mx": {
+ "line1": "Hab. aplic."
+ },
+ "fr-ca": {
+ "line1": "Activer app.",
+ "textBody": "Activer app."
+ },
+ "fr-fr": {
+ "line1": "Activer app."
+ },
+ "it-it": {
+ "line1": "Abilita app"
+ },
+ "nl-nl": {
+ "line1": "Apps inschak."
+ },
+ "pl-pl": {
+ "line1": "Włącz aplikacje"
+ },
+ "pt-br": {
+ "line1": "Ativar aplic."
+ },
+ "pt-pt": {
+ "line1": "Activar actualiz."
+ },
+ "ru-ru": {
+ "line1": "Вкл. прилож."
+ },
+ "sv-se": {
+ "line1": "Aktivera appar"
+ },
+ "tr-tr": {
+ "line1": "Uygulamaları aç"
+ },
+ "zh-cn": {
+ "line1": "启用应用程序"
+ },
+ "zh-tw": {
+ "line1": "啟用應用程式"
+ }
+ }
+ },
+ "SettingUpdateAuto": {
+ "languages": {
+ "de-de": {
+ "line1": "Update anford."
+ },
+ "en-au": {
+ "line1": "Request update"
+ },
+ "en-gb": {
+ "line1": "Request update"
+ },
+ "en-ie": {
+ "line1": "Request update"
+ },
+ "en-us": {
+ "line1": "Request Update",
+ "textBody": "Select `Update now` to receive app authorization information for your SYNC-enabled mobile apps. This may enable additional functionality depending on the app and your settings. If your phone has a working data connection, an update should complete in less than 1 minute."
+ },
+ "es-en": {
+ "line1": "Solicit. actualiz.",
+ "textBody": "Solicit. actualiz."
+ },
+ "es-es": {
+ "line1": "Solicitar actual."
+ },
+ "es-mx": {
+ "line1": "Solicit. actualiz."
+ },
+ "fr-ca": {
+ "line1": "Demander MAJ",
+ "textBody": "Demander MAJ"
+ },
+ "fr-fr": {
+ "line1": "Demander màj"
+ },
+ "it-it": {
+ "line1": "Rich. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Upd. aanvragen"
+ },
+ "pl-pl": {
+ "line1": "Zażądaj aktual."
+ },
+ "pt-br": {
+ "line1": "Solicitar atualiz."
+ },
+ "pt-pt": {
+ "line1": "Solicit. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Запрос на обн."
+ },
+ "sv-se": {
+ "line1": "Begär uppdat."
+ },
+ "tr-tr": {
+ "line1": "Güncelleme iste"
+ },
+ "zh-cn": {
+ "line1": "请求更新"
+ },
+ "zh-tw": {
+ "line1": "請求更新"
+ }
+ }
+ },
+ "StatusNeeded": {
+ "languages": {
+ "de-de": {
+ "line1": "Update benötigt"
+ },
+ "en-au": {
+ "line1": "Update needed"
+ },
+ "en-gb": {
+ "line1": "Update needed",
+ "textBody": "Update needed"
+ },
+ "en-ie": {
+ "line1": "Update needed"
+ },
+ "en-us": {
+ "line1": "Update Needed",
+ "textBody": "Update Needed"
+ },
+ "es-en": {
+ "line1": "Actualiz. neces.",
+ "textBody": "Actualiz. neces."
+ },
+ "es-es": {
+ "line1": "Actu. necesaria"
+ },
+ "es-mx": {
+ "line1": "Actualiz. neces."
+ },
+ "fr-ca": {
+ "line1": "Màj requise",
+ "textBody": "Màj requise"
+ },
+ "fr-fr": {
+ "line1": "Mise à jour requise"
+ },
+ "it-it": {
+ "line1": "Necess. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Update nodig"
+ },
+ "pl-pl": {
+ "line1": "Potrzeba aktual."
+ },
+ "pt-br": {
+ "line1": "Atualiz. necess."
+ },
+ "pt-pt": {
+ "line1": "Actual. necess."
+ },
+ "ru-ru": {
+ "line1": "Необх. обновл."
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs"
+ },
+ "tr-tr": {
+ "line1": "Güncellenmeli"
+ },
+ "zh-cn": {
+ "line1": "需要进行更新"
+ },
+ "zh-tw": {
+ "line1": "需更新"
+ }
+ }
+ },
+ "StatusPending": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktualisieren..."
+ },
+ "en-au": {
+ "line1": "Updating..."
+ },
+ "en-gb": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "en-ie": {
+ "line1": "Updating..."
+ },
+ "en-us": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "es-en": {
+ "line1": "Actualizando...",
+ "textBody": "Actualizando..."
+ },
+ "es-es": {
+ "line1": "Actualizando..."
+ },
+ "es-mx": {
+ "line1": "Actualizando..."
+ },
+ "fr-ca": {
+ "line1": "MAJ en cours...",
+ "textBody": "MAJ en cours..."
+ },
+ "fr-fr": {
+ "line1": "Màj en cours..."
+ },
+ "it-it": {
+ "line1": "Aggiornamento"
+ },
+ "nl-nl": {
+ "line1": "Updaten..."
+ },
+ "pl-pl": {
+ "line1": "Aktualizowanie"
+ },
+ "pt-br": {
+ "line1": "Atualizando..."
+ },
+ "pt-pt": {
+ "line1": "A actualizar..."
+ },
+ "ru-ru": {
+ "line1": "Обновление..."
+ },
+ "sv-se": {
+ "line1": "Uppdaterar..."
+ },
+ "tr-tr": {
+ "line1": "Güncelleniyor..."
+ },
+ "zh-cn": {
+ "line1": "正在更新......"
+ },
+ "zh-tw": {
+ "line1": "更新中..."
+ }
+ }
+ },
+ "StatusUpToDate": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktuelle Version"
+ },
+ "en-au": {
+ "line1": "Up-to-date"
+ },
+ "en-gb": {
+ "line1": "Up-to-date",
+ "textBody": "Up-to-date"
+ },
+ "en-ie": {
+ "line1": "Up-to-date"
+ },
+ "en-us": {
+ "line1": "Up-To-Date",
+ "textBody": "Up-To-Date"
+ },
+ "es-en": {
+ "line1": "Actualizado",
+ "textBody": "Actualizado"
+ },
+ "es-es": {
+ "line1": "Actualizada"
+ },
+ "es-mx": {
+ "line1": "Actualizado"
+ },
+ "fr-ca": {
+ "line1": "Déjà à jour",
+ "textBody": "Déjà à jour"
+ },
+ "fr-fr": {
+ "line1": "Déjà à jour"
+ },
+ "it-it": {
+ "line1": "più recente"
+ },
+ "nl-nl": {
+ "line1": "Up-to-date"
+ },
+ "pl-pl": {
+ "line1": "Aktualne"
+ },
+ "pt-br": {
+ "line1": "Atualizado"
+ },
+ "pt-pt": {
+ "line1": "Actualizado"
+ },
+ "ru-ru": {
+ "line1": "Обновлено"
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs ej"
+ },
+ "tr-tr": {
+ "line1": "Güncel"
+ },
+ "zh-cn": {
+ "line1": "最新更新"
+ },
+ "zh-tw": {
+ "line1": "更新最新"
+ }
+ }
+ },
+ "VehicleInfo": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahrzeuginformationen: Kraftstoff-Füllstand, Kraftstoffverbrauch, Motordrehzahl, Kilometerzähler, FIN, Außentemperatur, Gangstellung, Reifenluftdruck.",
+ "label": "Fahrzeuginformationen"
+ },
+ "en-au": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-gb": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure."
+ },
+ "en-ie": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-us": {
+ "tts": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo",
+ "textBody": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a la siguiente información del vehículo: Nivel de combustible, Ahorro de combustible, RPM del motor, Cuentakilómetros, VIN, Temperatura aire exterior, Marcha engranada, Presión de neumáticos.",
+ "label": "Información del vehículo"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo"
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus.",
+ "label": "Renseignements du véhicule",
+ "textBody": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Vitesse de moteur, Compteur kilométrique, NIV, Température extérieure, Position de vitesse, Pression des pneus.",
+ "label": "Renseignements du véhicule"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti informazioni del veicolo: Livello carburante, Consumi carburante, Numero giri motore, Contachilometri, VIN, Temperatura esterna, Posizione marcia, Pressione pneumatici.",
+ "label": "Informazioni sul veicolo"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende voertuiginformatie: Brandstofpeil, Brandstofverbruik, Motortoerental, Kilometerteller, VIN, Buitentemperatuur, Versnellingsstand, Bandenspanning.",
+ "label": "Voertuiginformatie"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji o pojeździe: Poziom paliwa, Zużycie paliwa, Obroty silnika, Licznik przebiegu, Numer VIN, Temperatura zewnętrzna, Aktualny bieg, Ciśnienie opon.",
+ "label": "Informacje o pojeździe"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes informações sobre o veículo: Nível de combustível, Economia de combustível, RPM do motor, Hodômetro, VIN, Temperatura externa, Posição das marchas, Pressão dos pneus.",
+ "label": "Informações sobre o veículo"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações do veículo: Nível de combustível, Poupança de combustível, RPM do motor, Conta-quilómetros, VIN, Temperatura exterior, Posição da mudança de velocidade, Pressão dos pneus.",
+ "label": "Informações do veículo"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим данным автомобиля: Уровень топлива, Економия топлива, Число оборотов двигателя, Одометр, Номер VIN, Температура за бортом, Положение передачи, Давление шин.",
+ "label": "Информация об автомобиле"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande fordonsinformation: Bränslenivå, Bränsleekonomi, Motorns varvtal, Vägmätare, VIN, Utetemperatur, Växelläge, Däcktryck.",
+ "label": "Fordonsinformation"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu araç bilgilerine erişebilir: Yakıt seviyesi, Yakıt ekonomisi, Motor devirleri, Kilometre sayacı, VIN, Dış sıcaklık, Vites konumu, Lastik basıncı.",
+ "label": "Araç bilgisi"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列车辆信息 : 燃油量, 燃油经济性, 发动机转速(RPM), 里程表, VIN, 车外温度, 档位, 胎压.",
+ "label": "车辆信息"
+ },
+ "zh-tw": {
+ "tts": "一個應用程式可存取以下車輛資訊 : 燃油存量, 燃油經濟性, 引擎轉速, 里程表, 車輛識別號碼, 車外溫度, 檔位, 胎壓.",
+ "label": "車輛資訊"
+ }
+ }
+ }
+ }
+ },
+ "app_policies": {
+ "default": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["Base-4"]
+ },
+ "device": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["DataConsent-2"]
+ },
+ "pre_DataConsent": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["BaseBeforeDataConsent"]
+ },
+ "1234": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": ["BaseBeforeDataConsent"],
+ "RequestType": [
+ "TRAFFIC_MESSAGE_CHANNEL",
+ "QUERY_APPS",
+ "LAUNCH_APP",
+ "PROPRIETARY",
+ "NAVIGATION",
+ "MEDIA",
+ "INVALID_REQUEST_TYPE"
+ ]
+ }
+ }
+ }
+ }
diff --git a/src/components/policy/test/counter_test.cc b/src/components/policy/test/counter_test.cc
new file mode 100644
index 0000000000..84b6d7fef4
--- /dev/null
+++ b/src/components/policy/test/counter_test.cc
@@ -0,0 +1,194 @@
+/* Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gmock/gmock.h"
+
+#include "policy/mock_statistics_manager.h"
+#include "policy/usage_statistics/counter.h"
+
+using ::testing::StrictMock;
+using ::testing::InSequence;
+
+namespace test {
+namespace components {
+namespace usage_statistics_test {
+
+using namespace usage_statistics;
+
+// TEST(A, B_C_D) { ... }
+// A - What you test
+// B - What you do
+// C - Input data
+// D - Expected result
+
+TEST(
+ StatisticsManagerIncrementMethod1Arg,
+ GlobalCounterOverloadedIncrement_CallONCE_StatisticsManagerIncrementCalledONCE) {
+ // Arrange
+ MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
+ GlobalCounter reboots_counter(msm, SYNC_REBOOTS);
+
+ // Assert
+ EXPECT_CALL(*msm, Increment(SYNC_REBOOTS));
+
+ // Act
+ ++reboots_counter;
+}
+
+TEST(
+ StatisticsManagerIncrementMethod1Arg,
+ GlobalCounterOverloadedIncrement_CallTWICE_StatisticsManagerIncrementCalledTWICE) {
+ // Arrange
+ MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
+ GlobalCounter reboots_counter(msm, SYNC_REBOOTS);
+
+ // Assert
+ EXPECT_CALL(*msm, Increment(SYNC_REBOOTS)).Times(2);
+
+ // Act
+ ++reboots_counter;
+ ++reboots_counter;
+}
+
+TEST(
+ StatisticsManagerIncrementMethod2Args,
+ AppCounterOverloadedIncrement_CallONCE_StatisticsManagerIncrementCalledONCE) {
+ // Arrange
+ MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
+ AppCounter user_selections_counter(msm, "HelloApp", USER_SELECTIONS);
+
+ // Assert
+ EXPECT_CALL(*msm, Increment("HelloApp", USER_SELECTIONS));
+
+ // Act
+ ++user_selections_counter;
+}
+
+TEST(
+ StatisticsManagerIncrementMethod2Args,
+ AppCounterOverloadedIncrement_CallTWICE_StatisticsManagerIncrementCalledTWICE) {
+ // Arrange
+ MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
+ AppCounter user_selections_counter(msm, "HelloApp", USER_SELECTIONS);
+
+ // Assert
+ EXPECT_CALL(*msm, Increment("HelloApp", USER_SELECTIONS)).Times(2);
+
+ // Act
+ ++user_selections_counter;
+ ++user_selections_counter;
+}
+//---
+TEST(StatisticsManagerSetMethod,
+ AppInfoUpdateMethod_CallONCE_StatisticsManagerSetMethodCalledONCE) {
+ // Arrange
+ MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
+ AppInfo gui_language_info(msm, "HelloApp", LANGUAGE_GUI);
+
+ // Assert
+ EXPECT_CALL(*msm, Set("HelloApp", LANGUAGE_GUI, "Klingon"));
+
+ // Act
+ gui_language_info.Update("Klingon");
+}
+
+TEST(StatisticsManagerSetMethod,
+ AppInfoUpdateMethod_CallTWICE_StatisticsManagerSetMethodCalledTWICE) {
+ // Arrange
+ MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
+ AppInfo gui_language_info(msm, "HelloApp", LANGUAGE_GUI);
+
+ // Assert
+ EXPECT_CALL(*msm, Set("HelloApp", LANGUAGE_GUI, "Klingon"));
+ EXPECT_CALL(*msm, Set("HelloApp", LANGUAGE_GUI, "UA"));
+
+ // Act
+ gui_language_info.Update("Klingon");
+ gui_language_info.Update("UA");
+}
+
+TEST(StatisticsManagerAddMethod,
+ AppStopwatchStartMethod_CallONCE_StatisticsManagerAddMethodCalledONCE) {
+ // Arrange
+ MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
+ const std::uint32_t time_out = 1;
+ AppStopwatchImpl hmi_full_stopwatch(msm, "HelloApp", time_out);
+
+ hmi_full_stopwatch.Start(SECONDS_HMI_FULL);
+ // Assert
+ EXPECT_CALL(*msm, Add("HelloApp", SECONDS_HMI_FULL, time_out));
+
+ // Act
+ hmi_full_stopwatch.WriteTime();
+}
+
+// Tests disabled due to uncorrect behavior of timer.
+// Will be undisabled after fix.
+TEST(StatisticsManagerAddMethod,
+ DISABLED_AppStopwatchSwitchMethod_Call_StatisticsManagerAddMethodCalled) {
+ // Arrange
+ MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
+ AppStopwatchImpl hmi_full_stopwatch(msm, "HelloApp");
+ hmi_full_stopwatch.Start(SECONDS_HMI_FULL);
+
+ hmi_full_stopwatch.Switch(SECONDS_HMI_FULL);
+ // Assert
+ EXPECT_CALL(*msm, Add("HelloApp", SECONDS_HMI_FULL, 60));
+
+ // Act
+ hmi_full_stopwatch.WriteTime();
+}
+
+TEST(
+ StatisticsManagerAddMethod,
+ DISABLED_AppStopwatchSwitchMethod_CallAnd1SecSleepAfter_StatisticsManagerAddMethodCalledWith1SecTimespan) {
+ // Arrange
+ MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
+ const std::uint32_t time_out = 1;
+ AppStopwatchImpl hmi_full_stopwatch(msm, "HelloApp", time_out);
+
+ // Act
+ hmi_full_stopwatch.Start(SECONDS_HMI_NONE);
+ // Assert
+ EXPECT_CALL(*msm, Add("HelloApp", SECONDS_HMI_NONE, time_out));
+ // Act
+ hmi_full_stopwatch.WriteTime();
+
+ hmi_full_stopwatch.Switch(SECONDS_HMI_BACKGROUND);
+ // Assert
+ EXPECT_CALL(*msm, Add("HelloApp", SECONDS_HMI_BACKGROUND, time_out));
+ // Act
+ hmi_full_stopwatch.WriteTime();
+}
+
+} // namespace usage_statistics_test
+} // namespace components
+} // namespace test
diff --git a/src/components/policy/test/generated_code_test.cc b/src/components/policy/test/generated_code_test.cc
index 5b590ce46c..8b1a4d7478 100644
--- a/src/components/policy/test/generated_code_test.cc
+++ b/src/components/policy/test/generated_code_test.cc
@@ -35,8 +35,8 @@
#include "json/reader.h"
#include "json/value.h"
-#include "./enums.h"
-#include "./types.h"
+#include "policy/policy_table/enums.h"
+#include "policy/policy_table/types.h"
#include "rpc_base/gtest_support.h"
using rpc::policy_table_interface_base::Table;
@@ -45,8 +45,7 @@ namespace test {
namespace components {
namespace policy {
-TEST(PolicyGeneratedCodeTest, DISABLED_TestValidPTPreloadJsonIsValid) {
- // TODO(AGaliuzov) APPLINK-10657 neet to enable this tests
+TEST(PolicyGeneratedCodeTest, TestValidPTPreloadJsonIsValid) {
std::ifstream json_file("sdl_preloaded_pt.json");
ASSERT_TRUE(json_file.is_open());
Json::Value valid_table;
@@ -57,8 +56,7 @@ TEST(PolicyGeneratedCodeTest, DISABLED_TestValidPTPreloadJsonIsValid) {
ASSERT_RPCTYPE_VALID(table);
}
-TEST(PolicyGeneratedCodeTest, DISABLED_TestValidPTUpdateJsonIsValid) {
- // TODO(AGaliuzov) APPLINK-10657 neet to enable this tests
+TEST(PolicyGeneratedCodeTest, TestValidPTUpdateJsonIsValid) {
std::ifstream json_file("valid_sdl_pt_update.json");
ASSERT_TRUE(json_file.is_open());
Json::Value valid_table;
diff --git a/src/components/policy/test/generated_code_with_sqlite_test.cc b/src/components/policy/test/generated_code_with_sqlite_test.cc
deleted file mode 100644
index 76737c366f..0000000000
--- a/src/components/policy/test/generated_code_with_sqlite_test.cc
+++ /dev/null
@@ -1,218 +0,0 @@
-/* Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <sqlite3.h>
-#include "gtest/gtest.h"
-#include "generated_code_with_sqlite_test.h"
-
-namespace rpc {
-
-class GeneratedCodeTest : public ::testing::Test {
- public:
- static void SetUpTestCase() {
- sqlite3* conn;
- sqlite3_open((kDatabaseName + ".sqlite").c_str(), &conn);
- sqlite3_exec(conn, kEndpointsCreation.c_str(), NULL, NULL, NULL);
- sqlite3_exec(conn, kEndpointsContent.c_str(), NULL, NULL, NULL);
- sqlite3_exec(conn, kAppPoliciesCreation.c_str(), NULL, NULL, NULL);
- sqlite3_exec(conn, kGroupsCreation.c_str(), NULL, NULL, NULL);
- sqlite3_close(conn);
- }
-
- static void TearDownTestCase() {
- remove((kDatabaseName + ".sqlite").c_str());
- }
-
- static const std::string kDatabaseName;
- static const std::string kEndpointsCreation;
- static const std::string kEndpointsContent;
- static const std::string kAppPoliciesCreation;
- static const std::string kGroupsCreation;
-};
-
-const std::string GeneratedCodeTest::kDatabaseName = "test_db";
-
-const std::string GeneratedCodeTest::kEndpointsCreation =
- "CREATE TABLE Endpoints ("
- "endpoint_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
- "service_id VARCHAR(45) NOT NULL,"
- "application_id VARCHAR(45),"
- "url VARCHAR(45) NOT NULL,"
- "is_default INTEGER NOT NULL CHECK(is_default>=0))";
-
-const std::string GeneratedCodeTest::kEndpointsContent =
- "INSERT INTO Endpoints "
- "VALUES (1, '0x07', null, 'http://test.example.com', 1)";
-
-const std::string GeneratedCodeTest::kAppPoliciesCreation =
- "CREATE TABLE AppPolicies ("
- "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
- "application_id VARCHAR(45),"
- "priority VARCHAR(45),"
- "is_default INTEGER NOT NULL CHECK(is_default>=0))";
-
-const std::string GeneratedCodeTest::kGroupsCreation = "CREATE TABLE Groups ("
- "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
- "application_id VARCHAR(45) NOT NULL,"
- "group_name VARCHAR(45) NOT NULL )";
-
-TEST_F(GeneratedCodeTest, FindSectionEndpoints_OpenDBSetDefaultUrl_ExpectDefaultUrl) {
-
- //arrange
- dbms::SQLDatabase db(GeneratedCodeTest::kDatabaseName);
-
- //assert
- EXPECT_TRUE(db.Open());
- policy_table::ServiceEndpoints ep;
-
- //assert
- EXPECT_TRUE(policy_table::FindSection(&db, ep));
- EXPECT_EQ(1u, ep.size());
-
- //act
- std::string url = ep["0x07"]["default"].front();
-
- //assert
- EXPECT_EQ("http://test.example.com", url);
-}
-
-TEST_F(GeneratedCodeTest, RemoveSectionEndpoints_RemoveSectionEndpoints_Expect0EndPoints) {
- //arrange
- dbms::SQLDatabase db(GeneratedCodeTest::kDatabaseName);
-
- //assert
- EXPECT_TRUE(db.Open());
-
- //act
- policy_table::ServiceEndpoints ep;
-
- //assert
- EXPECT_TRUE(policy_table::RemoveSection(&db, ep));
- dbms::SQLQuery sqlquery(&db);
-
- //act
- std::string check_query = "select count (*) from endpoints";
-
- //assert
- EXPECT_TRUE(sqlquery.Prepare(check_query));
- EXPECT_TRUE(sqlquery.Exec());
- // Index for binding starts from 1, index for results starts from 0
- EXPECT_EQ(0, sqlquery.GetInteger(0));
-}
-
-TEST_F(GeneratedCodeTest, UpdateSectionEndpoints_SetUrlPoint_ExpectPointEqualsUrl) {
-
- //arrange
- dbms::SQLDatabase db(GeneratedCodeTest::kDatabaseName);
-
- //assert
- EXPECT_TRUE(db.Open());
-
- //act
- std::string test_url = "http://url.example.com";
-
- policy_table::URL urls;
- urls.push_back(test_url);
-
- policy_table::URLList urllist;
- urllist["default"] = urls;
-
- policy_table::ServiceEndpoints ep;
- ep["0x07"] = urllist;
-
- //assert
- EXPECT_TRUE(policy_table::UpdateSection(&db, ep));
-
- dbms::SQLQuery sqlquery(&db);
- std::string num_of_records_check = "select count (*) from endpoints";
-
- //assert
- EXPECT_TRUE(sqlquery.Prepare(num_of_records_check));
- EXPECT_TRUE(sqlquery.Exec());
- // Index for binding starts from 1, index for results starts from 0
- EXPECT_EQ(1, sqlquery.GetInteger(0));
- EXPECT_TRUE(sqlquery.Reset());
-
-
- //act
- std::string url_check_query = "select * from endpoints";
-
- //assert
- EXPECT_TRUE(sqlquery.Prepare(url_check_query));
- EXPECT_TRUE(sqlquery.Exec());
- // Index for binding starts from 1, index for results starts from 0
- EXPECT_EQ(test_url, sqlquery.GetString(3));
-}
-
-TEST_F(GeneratedCodeTest, UpdateSectionAppPolicies_SetAppParams_ExpectDBHasThem) {
-
- //arrange
- dbms::SQLDatabase db(GeneratedCodeTest::kDatabaseName);
-
- //assert
- EXPECT_TRUE(db.Open());
-
- //act
- policy_table::ApplicationPolicies ap;
- const std::string application_id = "12345678";
- ap[application_id].groups.push_back("Base-4");
- ap[application_id].priority = policy_table::P_NORMAL;
-
- //assert
- EXPECT_TRUE(policy_table::UpdateSection(&db, ap));
-
- //act
- dbms::SQLQuery sqlquery(&db);
-
-
- //assert
- EXPECT_TRUE(sqlquery.Prepare("select count (*) from AppPolicies"));
- EXPECT_TRUE(sqlquery.Exec());
- // Index for binding starts from 1, index for results starts from 0
- EXPECT_EQ(1, sqlquery.GetInteger(0));
- EXPECT_TRUE(sqlquery.Reset());
-
- EXPECT_TRUE(sqlquery.Prepare("select count (*) from Groups"));
- EXPECT_TRUE(sqlquery.Exec());
- // Index for binding starts from 1, index for results starts from 0
- EXPECT_EQ(1, sqlquery.GetInteger(0));
- EXPECT_TRUE(sqlquery.Reset());
-
- EXPECT_TRUE(
- sqlquery.Prepare(
- "select application_id from Groups where group_name='Base-4'"));
- EXPECT_TRUE(sqlquery.Exec());
- // Index for binding starts from 1, index for results starts from 0
- EXPECT_EQ(application_id, sqlquery.GetString(0));
- EXPECT_TRUE(sqlquery.Reset());
-}
-
-} // namespace rpc
diff --git a/src/components/policy/test/include.cmake b/src/components/policy/test/include.cmake
index 0474df54dc..0c23af00b0 100644
--- a/src/components/policy/test/include.cmake
+++ b/src/components/policy/test/include.cmake
@@ -58,8 +58,8 @@ list(APPEND testSources
# ${POLICY_DIR}/test/shared_library_test.cc
)
- include_directories(${POLICY_DIR}/src/policy/policy_table/table_struct)
- list (APPEND testSources ${POLICY_DIR}/test/sql_pt_representation_test.cc)
+include_directories(${POLICY_DIR}/src/policy/policy_table/table_struct_ext)
+list (APPEND testSources ${POLICY_DIR}/test/sql_pt_ext_representation_test.cc)
if (CMAKE_SYSTEM_NAME STREQUAL "QNX")
list(REMOVE_ITEM test_exec_libraries dl)
@@ -86,4 +86,4 @@ else ()
endif()
file(COPY ${POLICY_DIR}/test/valid_sdl_pt_update.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
-file(COPY ${POLICY_DIR}/test/sdl_preloaded_pt.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR}) \ No newline at end of file
+file(COPY ${POLICY_DIR}/test/sdl_preloaded_pt.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
diff --git a/src/components/policy/test/include/driver_dbms.h b/src/components/policy/test/include/driver_dbms.h
index 5b1a0553dd..edd183dbd4 100644
--- a/src/components/policy/test/include/driver_dbms.h
+++ b/src/components/policy/test/include/driver_dbms.h
@@ -33,9 +33,9 @@
#define SRC_COMPONENTS_POLICY_TEST_INCLUDE_DRIVER_DBMS_H_
#ifdef __QNX__
-# include <qdb/qdb.h>
+#include <qdb/qdb.h>
#else // __QNX__
-# include <sqlite3.h>
+#include <sqlite3.h>
#endif // __QNX__
namespace test {
@@ -45,8 +45,7 @@ namespace policy {
#ifdef __QNX__
class DBMS {
public:
- explicit DBMS(std::string db_name) : db_name_(db_name), conn_(0) {
- }
+ explicit DBMS(std::string db_name) : db_name_(db_name), conn_(0) {}
~DBMS() {
Close();
}
@@ -61,7 +60,7 @@ class DBMS {
return -1 != qdb_statement(conn_, query);
}
int FetchOneInt(const char* query) {
- int stmt = qdb_stmt_init(conn_, query, strlen(query)+1);
+ int stmt = qdb_stmt_init(conn_, query, strlen(query) + 1);
qdb_stmt_exec(conn_, stmt, NULL, 0);
qdb_result_t* res = qdb_getresult(conn_);
void* ret = qdb_cell(res, 0, 0);
@@ -73,7 +72,7 @@ class DBMS {
return value;
}
double FetchOneDouble(const char* query) {
- int stmt = qdb_stmt_init(conn_, query, strlen(query)+1);
+ int stmt = qdb_stmt_init(conn_, query, strlen(query) + 1);
qdb_stmt_exec(conn_, stmt, NULL, 0);
qdb_result_t* res = qdb_getresult(conn_);
void* ret = qdb_cell(res, 0, 0);
@@ -86,7 +85,7 @@ class DBMS {
return value;
}
std::string FetchOneString(const char* query) {
- int stmt = qdb_stmt_init(conn_, query, strlen(query)+1);
+ int stmt = qdb_stmt_init(conn_, query, strlen(query) + 1);
qdb_stmt_exec(conn_, stmt, NULL, 0);
qdb_result_t* res = qdb_getresult(conn_);
void* ret = qdb_cell(res, 0, 0);
@@ -104,11 +103,10 @@ class DBMS {
qdb_hdl_t* conn_;
};
-#else // __QNX__
+#else // __QNX__
class DBMS {
public:
- explicit DBMS(std::string file_name) : file_name_(file_name), conn_(0) {
- }
+ explicit DBMS(std::string file_name) : file_name_(file_name), conn_(0) {}
~DBMS() {
Close();
}
diff --git a/src/components/policy/test/include/generated_code_with_sqlite_test.h b/src/components/policy/test/include/generated_code_with_sqlite_test.h
deleted file mode 100644
index ed231e92d3..0000000000
--- a/src/components/policy/test/include/generated_code_with_sqlite_test.h
+++ /dev/null
@@ -1,399 +0,0 @@
-/* Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_GENERATED_CODE_WITH_SQLITE_TEST_H_
-#define SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_GENERATED_CODE_WITH_SQLITE_TEST_H_
-
-#include <string>
-#include "./types.h"
-#include "rpc_base/rpc_base.h"
-#include "sqlite_wrapper/sql_query.h"
-#include "sqlite_wrapper/sql_database.h"
-
-namespace policy_table = rpc::policy_table_interface_base;
-namespace dbms = policy::dbms;
-
-namespace rpc {
-namespace policy_table_interface_base {
-
-bool FindSection(dbms::SQLDatabase* db, policy_table::ServiceEndpoints& ep) {
- /*
- * Following table structure is assumed:
- *
- * table Endpoints
- * index, service_type, application_id, url, is_default
- *
- * If url belongs to default section, application_id should be null and is_defaut = true
- * Otherwise application_id should be set and is_default = false
- */
-
- std::string query = "select * from Endpoints";
-
- dbms::SQLQuery sqlquery(db);
- sqlquery.Prepare(query);
- if (!sqlquery.Exec()) {
- return false;
- }
-
- /*
- * Following query result is assumed (data from wp1_policy_table.json):
- * 1, 0x07, null, http://applinkqa.trafficmanager.net/api/policies, true
- */
-
- policy_table::URL urls;
- urls.push_back(sqlquery.GetString(3));
-
- policy_table::URLList urllist;
- if (sqlquery.GetBoolean(4)) {
- urllist["default"] = urls;
- } else {
- urllist[sqlquery.GetString(2)] = urls;
- }
-
- policy_table::ServiceEndpoints new_ep;
- new_ep[sqlquery.GetString(1)] = urllist;
-
- ep = new_ep;
-
- return true;
-}
-
-bool FindSection(dbms::SQLDatabase* db, policy_table::ModuleConfig& mc) {
- policy_table::ModuleConfig new_mc;
- FindSection(db, new_mc.endpoints);
- mc = new_mc;
-
- return true;
-}
-
-bool RemoveSection(dbms::SQLDatabase* db,
- const policy_table::ApplicationPolicies& ap) {
- dbms::SQLQuery sqlquery(db);
- bool is_policies_removed = sqlquery.Exec("delete from AppPolicies");
- // bool is_nicknames_removed = sqlquery.Exec("delete from Nicknames");
- bool is_groups_removed = sqlquery.Exec("delete from Groups");
-
- return is_policies_removed /*&& is_nicknames_removed*/&& is_groups_removed;
-}
-
-bool RemoveSection(dbms::SQLDatabase* db,
- const policy_table::ServiceEndpoints& ep) {
- std::string query = "delete from Endpoints";
- dbms::SQLQuery sqlquery(db);
- return sqlquery.Exec(query);
-}
-
-bool RemoveSection(dbms::SQLDatabase* db,
- const policy_table::ModuleConfig& mc) {
- // std::string query = "delete * from ModuleConfig";
- // sqlite::SQLQuery sqlquery(db);
- // sqlquery.Exec(query);
-
- return RemoveSection(db, mc.endpoints);
-}
-
-bool RemoveSection(dbms::SQLDatabase* db,
- const policy_table::FunctionalGroupings& fg) {
- std::string query = "delete from FunctionalGroups";
- dbms::SQLQuery sqlquery(db);
- return sqlquery.Exec(query);
-}
-
-bool UpdateSection(dbms::SQLDatabase* db,
- const policy_table::ServiceEndpoints& ep) {
- /*
- * Following table structure is assumed:
- *
- * table Endpoints
- * index, service_type, application_id, url, is_default
- *
- * If url belongs to default section, application_id should be null and is_defaut = true
- * Otherwise application_id should be set and is_default = false
- */
-
- // According to documentation, we have to REPLACE this part on update coming,
- // so we delete all data first;
- if (!RemoveSection(db, ep)) {
- return false;
- }
-
- std::string query = "insert into Endpoints values(?,?,?,?,?)";
- dbms::SQLQuery sqlquery(db);
- sqlquery.Prepare(query);
-
- policy_table::ServiceEndpoints::const_iterator it_ep = ep.begin();
- policy_table::ServiceEndpoints::const_iterator it_ep_end = ep.end();
-
- // TODO: use define for int from stdint.h
- for (int index = 1; it_ep != it_ep_end; ++it_ep, ++index) {
- policy_table::URLList::const_iterator it_urllist = (*it_ep).second.begin();
- policy_table::URLList::const_iterator it_urllist_end =
- (*it_ep).second.end();
-
- for (; it_urllist != it_urllist_end; ++it_urllist) {
- policy_table::URL::const_iterator it_url = (*it_urllist).second.begin();
- policy_table::URL::const_iterator it_url_end = (*it_urllist).second.end();
-
- for (; it_url != it_url_end; ++it_url) {
- // Index binding
- sqlquery.Bind(0, index);
-
- // Service type binding
- sqlquery.Bind(1, (*it_ep).first);
-
- // Application_id and is_default binding
- std::string url_list_name = (*it_urllist).first;
- if ("default" == url_list_name) {
- sqlquery.Bind(2, "null");
- sqlquery.Bind(4, true);
- } else {
- sqlquery.Bind(2, url_list_name);
- sqlquery.Bind(4, false);
- }
-
- // URL binding
- sqlquery.Bind(3, (*it_url));
-
- if (sqlquery.Exec()) {
- sqlquery.Reset();
- } else {
- return false;
- }
- }
- }
- }
-
- return true;
-}
-
-bool UpdateSection(dbms::SQLDatabase* db,
- const policy_table::ModuleConfig& mc) {
- UpdateSection(db, mc.endpoints);
- return true;
-}
-
-bool UpdateSection(dbms::SQLDatabase* db,
- const policy_table::FunctionalGroupings& fg) {
- /*
- * Following table structure is assumed:
- *
- * table Rpcs - list of all available RPC commands
- * index, rpc
- *
- * table HmiLevels -list of all available hmi levels
- * index, hmi_level
- *
- * table Groups - list of functional group names
- * index, group_name
- *
- * table FunctionalGroups - list of functional groups
- * index, group_name_id, rpc_id, hmi_level_id
- *
- */
-
- // According to documentation, we have to REPLACE this part on update coming,
- // so we delete all data first;
- if (!RemoveSection(db, fg)) {
- return false;
- }
-
- std::string query = "insert into FunctionalGroups values("
- "?,"
- "(select index from Groups where group_name=?),"
- "(select index from Rpcs where rpc=?),"
- "(select index from HmiLevels where hmi_levels=?)";
-
- dbms::SQLQuery sqlquery(db);
- sqlquery.Prepare(query);
-
- policy_table::FunctionalGroupings::const_iterator it_fg = fg.begin();
- policy_table::FunctionalGroupings::const_iterator it_fg_end = fg.end();
-
- for (int index = 1; it_fg != it_fg_end; ++it_fg, ++index) {
- policy_table::Rpcs rpcs = (*it_fg).second;
- policy_table::Rpc::const_iterator it_rpcs = rpcs.rpcs.begin();
- policy_table::Rpc::const_iterator it_rpcs_end = rpcs.rpcs.end();
-
- for (; it_rpcs != it_rpcs_end; ++it_rpcs) {
- policy_table::RpcParameters rpc_params = (*it_rpcs).second;
-
- policy_table::HmiLevels::const_iterator it_hmi_levels = rpc_params
- .hmi_levels.begin();
- policy_table::HmiLevels::const_iterator it_hmi_levels_end = rpc_params
- .hmi_levels.end();
-
- for (; it_hmi_levels != it_hmi_levels_end; ++it_hmi_levels) {
- // Index binding
- sqlquery.Bind(0, index);
-
- // Group name binding
- sqlquery.Bind(1, (*it_fg).first);
-
- // RPC name binding
- sqlquery.Bind(2, (*it_rpcs).first);
-
- // Hmi levels binding
- sqlquery.Bind(3, (*it_hmi_levels));
- if (sqlquery.Exec()) {
- sqlquery.Reset();
- } else {
- return false;
- }
- }
- }
- }
-
- return true;
-}
-
-bool UpdateSection(dbms::SQLDatabase* db, const policy_table::Table& pt) {
- UpdateSection(db, pt.policy_table.module_config);
- UpdateSection(db, pt.policy_table.functional_groupings);
- return true;
-}
-
-bool UpdateSection(dbms::SQLDatabase* db,
- const policy_table::ApplicationPolicies& ap) {
- /*
- * Following structure is assumed:
- *
- * table Groups - list of functional groups for application
- * index, application_id, functional_group_id
- *
- * table Nicknames - list of nickname for application
- * index, application_id, nickname
- *
- * table AppPolicies - policies for applications
- * index, application_id, priority, is_default
- *
- */
-
- // According to documentation, we have to REPLACE this part on update coming,
- // so we delete all data first;
- if (!RemoveSection(db, ap)) {
- return false;
- }
-
- std::string groups_query = "insert into Groups values ("
- "?,"
- "?,"
- "?)";
- dbms::SQLQuery groups_sqlquery(db);
- groups_sqlquery.Prepare(groups_query);
-
- std::string nicknames_query = "insert into Nicknames values(?,?,?)";
- dbms::SQLQuery nicknames_sqlquery(db);
- nicknames_sqlquery.Prepare(nicknames_query);
-
- std::string app_policies_query = "insert into AppPolicies values(?,?,?,?)";
- dbms::SQLQuery app_policies_sqlquery(db);
- app_policies_sqlquery.Prepare(app_policies_query);
-
- policy_table::ApplicationPolicies::const_iterator it_ap = ap.begin();
- policy_table::ApplicationPolicies::const_iterator it_ap_end = ap.end();
-
- for (int index = 0; it_ap != it_ap_end; ++it_ap, ++index) {
- // Index binding for AppPolicies table
- app_policies_sqlquery.Bind(0, index);
-
- std::string app_policy_name = (*it_ap).first;
- bool is_default_policy = "default" == app_policy_name ? true : false;
- if (is_default_policy) {
- app_policies_sqlquery.Bind(1, "null");
- app_policies_sqlquery.Bind(3, true);
- } else {
- app_policies_sqlquery.Bind(1, app_policy_name);
- app_policies_sqlquery.Bind(3, false);
- }
-
- // Struct contains groups, nicknames, priority for application/default section
- policy_table::ApplicationParams app_params = (*it_ap).second;
-
- // Priority binding
- app_policies_sqlquery.Bind(2, app_params.priority);
- app_policies_sqlquery.Bind(2, "Dummy priority parameter");
-
- // Add record to AppPolicies table
- if (app_policies_sqlquery.Exec()) {
- app_policies_sqlquery.Reset();
- } else {
- return false;
- }
-
- if (!is_default_policy) {
- // Seems, there is generator issue with Optional type inheritance
- // It should have pubic inheritance from type T to have array
- // begin/end methods in its interface
- // To be discussed with I.Kozyrenko
-
- // policy_table::StringArray::const_iterator it_nicknames = app_params.nicknames.begin();
- // policy_table::StringArray::const_iterator it_nicknames_end = app_params.nicknames.end();
- //
- // for (int nick_index = 0;it_nicknames != it_nicknames_end; ++ it_nicknames, ++nick_index) {
- // nicknames_sqlquery.Bind(0, nick_index);
- // nicknames_sqlquery.Bind(1, app_policy_name);
- //
- // nicknames_sqlquery.Bind(2, (*it_nicknames));
- //
- // if (nicknames_sqlquery.Exec()) {
- // nicknames_sqlquery.Reset();
- // } else {
- // return false;
- // }
- // }
-
- policy_table::Strings::const_iterator it_groups =
- app_params.groups.begin();
- policy_table::Strings::const_iterator it_groups_end = app_params.groups
- .end();
-
- for (int group_index = 0; it_groups != it_groups_end;
- ++it_groups, ++group_index) {
- groups_sqlquery.Bind(0, group_index);
- groups_sqlquery.Bind(1, app_policy_name);
- groups_sqlquery.Bind(2, (*it_groups));
-
- if (groups_sqlquery.Exec()) {
- groups_sqlquery.Reset();
- } else {
- return false;
- }
- }
- }
- }
-
- return true;
-}
-
-} // namespace policy_table_interface_base
-} // namespace rpc
-
-#endif // SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_GENERATED_CODE_WITH_SQLITE_TEST_H_
diff --git a/src/components/policy/test/include/mock_app_stopwatch.h b/src/components/policy/test/include/mock_app_stopwatch.h
new file mode 100644
index 0000000000..481d887cb2
--- /dev/null
+++ b/src/components/policy/test/include/mock_app_stopwatch.h
@@ -0,0 +1,54 @@
+/* Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_POLICY_USAGE_STATISTICS_MOCK_APP_STOPWATCH_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_POLICY_USAGE_STATISTICS_MOCK_APP_STOPWATCH_H_
+
+#include "gmock/gmock.h"
+#include "policy/usage_statistics/app_stopwatch.h"
+#include "policy/usage_statistics/statistics_manager.h"
+
+namespace test {
+namespace components {
+namespace usage_statistics_test {
+
+class MockAppStopwatch : public usage_statistics::AppStopwatch {
+ public:
+ MOCK_METHOD1(Start, void(usage_statistics::AppStopwatchId stopwatch_type));
+ MOCK_METHOD1(Switch, void(usage_statistics::AppStopwatchId stopwatch_type));
+ MOCK_METHOD0(WriteTime, void());
+};
+
+} // namespace usage_statistics_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_INCLUDE_TEST_POLICY_USAGE_STATISTICS_MOCK_APP_STOPWATCH_H_
diff --git a/src/components/policy/test/include/mock_cache_manager.h b/src/components/policy/test/include/mock_cache_manager.h
index 0494eae4f4..095319a090 100644
--- a/src/components/policy/test/include/mock_cache_manager.h
+++ b/src/components/policy/test/include/mock_cache_manager.h
@@ -32,7 +32,6 @@
#ifndef SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_MOCK_CACHE_MANAGER_H_
#define SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_MOCK_CACHE_MANAGER_H_
-
#include <string>
#include <vector>
@@ -47,147 +46,160 @@ namespace policy {
class MockCacheManagerInterface : public CacheManagerInterface {
public:
MOCK_METHOD4(CheckPermissions,
- void(const PTString& app_id, const PTString& hmi_level, const PTString& rpc, CheckPermissionResult& result));
- MOCK_METHOD0(IsPTPreloaded,
- bool());
- MOCK_METHOD0(IgnitionCyclesBeforeExchange,
- int());
- MOCK_METHOD1(KilometersBeforeExchange,
- int(int current));
+ void(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ CheckPermissionResult& result));
+ MOCK_METHOD0(IsPTPreloaded, bool());
+ MOCK_METHOD0(IgnitionCyclesBeforeExchange, int());
+ MOCK_METHOD1(KilometersBeforeExchange, int(int current));
MOCK_METHOD2(SetCountersPassedForSuccessfulUpdate,
- bool(int kilometers, int days_after_epoch));
- MOCK_METHOD1(DaysBeforeExchange,
- int(int current));
- MOCK_METHOD0(IncrementIgnitionCycles,
- void());
- MOCK_METHOD0(ResetIgnitionCycles,
- void());
- MOCK_METHOD0(TimeoutResponse,
- int());
- MOCK_METHOD1(SecondsBetweenRetries,
- bool(std::vector<int> &seconds));
- MOCK_METHOD0(GetVehicleData,
- VehicleData());
- MOCK_METHOD1(SetVINValue,
- bool(const std::string& value));
+ bool(Counters counter, int value));
+ MOCK_METHOD1(DaysBeforeExchange, int(int current));
+ MOCK_METHOD0(IncrementIgnitionCycles, void());
+ MOCK_METHOD0(ResetIgnitionCycles, void());
+ MOCK_METHOD0(TimeoutResponse, int());
+ MOCK_METHOD1(SecondsBetweenRetries, bool(std::vector<int>& seconds));
+ MOCK_CONST_METHOD0(GetVehicleInfo, const VehicleInfo());
+ MOCK_METHOD1(SetVINValue, bool(const std::string& value));
MOCK_METHOD2(GetUserFriendlyMsg,
- std::vector<UserFriendlyMessage>(const std::vector<std::string>& msg_codes, const std::string& language));
+ std::vector<UserFriendlyMessage>(
+ const std::vector<std::string>& msg_codes,
+ const std::string& language));
+ MOCK_METHOD2(GetUpdateUrls, void(int service_type, EndpointUrls& end_points));
+ MOCK_METHOD1(
+ GetNotificationsNumber,
+ policy_table::NumberOfNotificationsType(const std::string& priority));
+ MOCK_CONST_METHOD2(GetPriority,
+ bool(const std::string& policy_app_id,
+ std::string& priority));
MOCK_METHOD2(GetServiceUrls,
- void(const std::string& service_type, EndpointUrls& end_points));
- MOCK_CONST_METHOD0(GetLockScreenIconUrl,
- std::string());
- MOCK_METHOD1(GetNotificationsNumber,
- int(const std::string& priority));
- MOCK_METHOD2(GetPriority,
- bool(const std::string& policy_app_id, std::string& priority));
- MOCK_METHOD1(Init,
- bool(const std::string& file_name));
- MOCK_METHOD0(GenerateSnapshot,
- utils::SharedPtr<policy_table::Table>());
- MOCK_METHOD1(ApplyUpdate,
- bool(const policy_table::Table& update_pt));
- MOCK_METHOD1(Save,
- bool(const policy_table::Table& table));
- MOCK_CONST_METHOD0(UpdateRequired,
- bool());
- MOCK_METHOD1(SaveUpdateRequired,
- void(bool status));
+ void(const std::string& service_type, EndpointUrls& end_points));
+ MOCK_CONST_METHOD0(GetLockScreenIconUrl, std::string());
+ MOCK_METHOD2(Init,
+ bool(const std::string& file_name,
+ const PolicySettings* settings));
+ MOCK_METHOD0(GenerateSnapshot, utils::SharedPtr<policy_table::Table>());
+ MOCK_METHOD1(ApplyUpdate, bool(const policy_table::Table& update_pt));
+ MOCK_METHOD1(Save, bool(const policy_table::Table& table));
+ MOCK_CONST_METHOD0(UpdateRequired, bool());
+ MOCK_METHOD1(SaveUpdateRequired, void(bool status));
MOCK_METHOD3(GetInitialAppData,
- bool(const std::string& app_id, StringArray& nicknames, StringArray& app_hmi_types));
- MOCK_CONST_METHOD1(IsApplicationRevoked,
- bool(const std::string& app_id));
+ bool(const std::string& app_id,
+ StringArray& nicknames,
+ StringArray& app_hmi_types));
+ MOCK_CONST_METHOD1(IsApplicationRevoked, bool(const std::string& app_id));
MOCK_METHOD1(GetFunctionalGroupings,
- bool(policy_table::FunctionalGroupings& groups));
- MOCK_CONST_METHOD1(IsApplicationRepresented,
- bool(const std::string& app_id));
- MOCK_METHOD1(IsDefaultPolicy,
- bool(const std::string& app_id));
- MOCK_METHOD1(SetIsDefault,
- bool(const std::string& app_id));
- MOCK_METHOD1(IsPredataPolicy,
- bool(const std::string& app_id));
- MOCK_METHOD1(SetDefaultPolicy,
- bool(const std::string& app_id));
- MOCK_METHOD1(CanAppKeepContext,
- bool(const std::string& app_id));
- MOCK_METHOD1(CanAppStealFocus,
- bool(const std::string& app_id));
- MOCK_METHOD2(GetDefaultHMI,
- bool(const std::string& app_id, std::string &default_hmi));
- MOCK_METHOD0(ResetUserConsent,
- bool());
- MOCK_METHOD3(GetUserPermissionsForDevice,
- bool(const std::string& device_id, StringArray &consented_groups, StringArray &disallowed_groups));
+ bool(policy_table::FunctionalGroupings& groups));
+ MOCK_CONST_METHOD1(IsApplicationRepresented, bool(const std::string& app_id));
+ MOCK_METHOD1(IsDefaultPolicy, bool(const std::string& app_id));
+ MOCK_METHOD1(SetIsDefault, bool(const std::string& app_id));
+ MOCK_METHOD1(IsPredataPolicy, bool(const std::string& app_id));
+ MOCK_METHOD1(SetDefaultPolicy, bool(const std::string& app_id));
+ MOCK_CONST_METHOD1(CanAppKeepContext, bool(const std::string& app_id));
+ MOCK_CONST_METHOD1(CanAppStealFocus, bool(const std::string& app_id));
+ MOCK_CONST_METHOD2(GetDefaultHMI,
+ bool(const std::string& app_id, std::string& default_hmi));
+ MOCK_METHOD0(ResetUserConsent, bool());
+ MOCK_CONST_METHOD3(GetUserPermissionsForDevice,
+ bool(const std::string& device_id,
+ StringArray& consented_groups,
+ StringArray& disallowed_groups));
MOCK_METHOD3(GetPermissionsForApp,
- bool(const std::string& device_id, const std::string& app_id, FunctionalIdType &group_types));
- MOCK_METHOD2(GetDeviceGroupsFromPolicies,
- bool(rpc::policy_table_interface_base::Strings &groups, rpc::policy_table_interface_base::Strings &preconsented_groups));
+ bool(const std::string& device_id,
+ const std::string& app_id,
+ FunctionalIdType& group_types));
+ MOCK_CONST_METHOD2(
+ GetDeviceGroupsFromPolicies,
+ bool(rpc::policy_table_interface_base::Strings& groups,
+ rpc::policy_table_interface_base::Strings& preconsented_groups));
+ MOCK_METHOD2(AddDevice,
+ bool(const std::string& device_id,
+ const std::string& connection_type));
MOCK_METHOD8(SetDeviceData,
- bool(const std::string& device_id, const std::string& hardware, const std::string& firmware, const std::string& os, const std::string& os_version, const std::string& carrier, const uint32_t number_of_ports, const std::string& connection_type));
+ bool(const std::string& device_id,
+ const std::string& hardware,
+ const std::string& firmware,
+ const std::string& os,
+ const std::string& os_version,
+ const std::string& carrier,
+ const uint32_t number_of_ports,
+ const std::string& connection_type));
MOCK_METHOD3(SetUserPermissionsForDevice,
- bool(const std::string& device_id, const StringArray& consented_groups, const StringArray& disallowed_groups));
+ bool(const std::string& device_id,
+ const StringArray& consented_groups,
+ const StringArray& disallowed_groups));
MOCK_METHOD2(ReactOnUserDevConsentForApp,
- bool(const std::string& app_id, bool is_device_allowed));
+ bool(const std::string& app_id, bool is_device_allowed));
MOCK_METHOD1(SetUserPermissionsForApp,
- bool(const PermissionConsent& permissions));
+ bool(const PermissionConsent& permissions));
MOCK_METHOD3(SetMetaInfo,
- bool(const std::string& ccpu_version, const std::string& wers_country_code, const std::string& language));
- MOCK_CONST_METHOD0(IsMetaInfoPresent,
- bool());
- MOCK_METHOD1(SetSystemLanguage,
- bool(const std::string& language));
- MOCK_METHOD1(Increment,
- void(usage_statistics::GlobalCounterId type));
+ bool(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language));
+ MOCK_CONST_METHOD0(IsMetaInfoPresent, bool());
+ MOCK_METHOD1(SetSystemLanguage, bool(const std::string& language));
+ MOCK_METHOD1(Increment, void(usage_statistics::GlobalCounterId type));
MOCK_METHOD2(Increment,
- void(const std::string& app_id, usage_statistics::AppCounterId type));
+ void(const std::string& app_id,
+ usage_statistics::AppCounterId type));
MOCK_METHOD3(Set,
- void(const std::string& app_id, usage_statistics::AppInfoId type, const std::string& value));
+ void(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value));
MOCK_METHOD3(Add,
- void(const std::string& app_id, usage_statistics::AppStopwatchId type, int seconds));
+ void(const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int seconds));
MOCK_METHOD2(CountUnconsentedGroups,
- int(const std::string& policy_app_id, const std::string& device_id));
- MOCK_METHOD1(GetFunctionalGroupNames,
- bool(FunctionalGroupNames& names));
+ int(const std::string& policy_app_id,
+ const std::string& device_id));
+ MOCK_METHOD1(GetFunctionalGroupNames, bool(FunctionalGroupNames& names));
MOCK_METHOD2(GetAllAppGroups,
- void(const std::string& app_id, FunctionalGroupIDs& all_group_ids));
+ void(const std::string& app_id,
+ FunctionalGroupIDs& all_group_ids));
MOCK_METHOD2(GetPreConsentedGroups,
- void(const std::string &app_id, FunctionalGroupIDs& preconsented_groups));
+ void(const std::string& app_id,
+ FunctionalGroupIDs& preconsented_groups));
MOCK_METHOD4(GetConsentedGroups,
- void(const std::string &device_id, const std::string &app_id, FunctionalGroupIDs& allowed_groups, FunctionalGroupIDs& disallowed_groups));
+ void(const std::string& device_id,
+ const std::string& app_id,
+ FunctionalGroupIDs& allowed_groups,
+ FunctionalGroupIDs& disallowed_groups));
MOCK_METHOD3(GetUnconsentedGroups,
- void(const std::string& device_id, const std::string& policy_app_id, FunctionalGroupIDs& unconsented_groups));
+ void(const std::string& device_id,
+ const std::string& policy_app_id,
+ FunctionalGroupIDs& unconsented_groups));
MOCK_METHOD2(RemoveAppConsentForGroup,
- void(const std::string& app_id, const std::string& group_name));
- MOCK_METHOD1(SetPredataPolicy,
- bool(const std::string& app_id));
- MOCK_METHOD0(CleanupUnpairedDevices,
- bool());
+ void(const std::string& app_id, const std::string& group_name));
+ MOCK_METHOD1(SetPredataPolicy, bool(const std::string& app_id));
+ MOCK_METHOD0(CleanupUnpairedDevices, bool());
MOCK_METHOD2(SetUnpairedDevice,
- bool(const std::string& device_id, bool unpaired));
- MOCK_METHOD1(UnpairedDevicesList,
- bool(DeviceIds& device_ids));
- MOCK_METHOD1(ResetPT,
- bool(const std::string& file_name));
- MOCK_METHOD0(LoadFromBackup,
- bool());
- MOCK_METHOD1(LoadFromFile,
- bool(const std::string& file_name));
- MOCK_METHOD0(Backup,
- void());
- MOCK_CONST_METHOD1(HeartBeatTimeout,
- uint16_t(const std::string& app_id));
+ bool(const std::string& device_id, bool unpaired));
+ MOCK_METHOD1(UnpairedDevicesList, bool(DeviceIds& device_ids));
+ MOCK_METHOD1(ResetPT, bool(const std::string& file_name));
+ MOCK_METHOD0(LoadFromBackup, bool());
+ MOCK_METHOD2(LoadFromFile,
+ bool(const std::string& file_name, policy_table::Table&));
+ MOCK_METHOD0(Backup, void());
+ MOCK_CONST_METHOD1(HeartBeatTimeout, uint32_t(const std::string& app_id));
MOCK_CONST_METHOD2(GetAppRequestTypes,
- void(const std::string& policy_app_id,
- std::vector<std::string>& request_types));
+ void(const std::string& policy_app_id,
+ std::vector<std::string>& request_types));
MOCK_METHOD1(GetHMIAppTypeAfterUpdate,
- void(std::map<std::string, StringArray>& app_hmi_types));
- MOCK_METHOD0(ResetCalculatedPermissions,
- void());
+ void(std::map<std::string, StringArray>& app_hmi_types));
+ MOCK_METHOD0(ResetCalculatedPermissions, void());
MOCK_METHOD3(AddCalculatedPermissions,
- void(const std::string& device_id, const std::string& policy_app_id, const policy::Permissions& permissions));
+ void(const std::string& device_id,
+ const std::string& policy_app_id,
+ const policy::Permissions& permissions));
MOCK_METHOD3(IsPermissionsCalculated,
- bool(const std::string& device_id, const std::string& policy_app_id, policy::Permissions& permission));
- MOCK_CONST_METHOD0(RemoteAppsUrl, std::string());
+ bool(const std::string& device_id,
+ const std::string& policy_app_id,
+ policy::Permissions& permission));
+ MOCK_CONST_METHOD0(GetPT, utils::SharedPtr<policy_table::Table>());
+ MOCK_CONST_METHOD0(GetCertificate, std::string());
+ MOCK_METHOD1(SetDecryptedCertificate, void(const std::string&));
};
} // namespace policy
diff --git a/src/components/policy/test/include/mock_policy_listener.h b/src/components/policy/test/include/mock_policy_listener.h
index 681b85740b..73905f4dcb 100644
--- a/src/components/policy/test/include/mock_policy_listener.h
+++ b/src/components/policy/test/include/mock_policy_listener.h
@@ -38,38 +38,44 @@
#include "policy/policy_listener.h"
#include "rpc_base/rpc_base.h"
-#include "./types.h"
+#include "policy/policy_table/types.h"
+#include "utils/custom_string.h"
namespace policy_table = ::rpc::policy_table_interface_base;
namespace policy {
+namespace custom_str = utils::custom_string;
+
class MockPolicyListener : public PolicyListener {
-public:
- MOCK_METHOD3(OnPermissionsUpdated, void(const std::string &policy_app_id,
- const Permissions &permissions,
- const policy::HMILevel &default_hmi));
- MOCK_METHOD2(OnPermissionsUpdated, void(const std::string &policy_app_id,
- const Permissions &permissions));
+ public:
+ MOCK_METHOD3(OnPermissionsUpdated,
+ void(const std::string& policy_app_id,
+ const Permissions& permissions,
+ const policy::HMILevel& default_hmi));
+ MOCK_METHOD2(OnPermissionsUpdated,
+ void(const std::string& policy_app_id,
+ const Permissions& permissions));
MOCK_METHOD1(OnPendingPermissionChange,
- void(const std::string &policy_app_id));
- MOCK_METHOD1(OnUpdateStatusChanged, void(const std::string &status));
+ void(const std::string& policy_app_id));
+ MOCK_METHOD1(OnUpdateStatusChanged, void(const std::string& status));
MOCK_METHOD1(OnCurrentDeviceIdUpdateRequired,
- std::string(const std::string &policy_app_id));
+ std::string(const std::string& policy_app_id));
MOCK_METHOD0(OnSystemInfoUpdateRequired, void());
- MOCK_METHOD1(GetAppName, std::string(const std::string &policy_app_id));
+ MOCK_METHOD1(GetAppName,
+ custom_str::CustomString(const std::string& policy_app_id));
MOCK_METHOD0(OnUserRequestedUpdateCheckRequired, void());
MOCK_METHOD2(OnDeviceConsentChanged,
- void(const std::string &device_id, bool is_allowed));
+ void(const std::string& device_id, bool is_allowed));
MOCK_METHOD1(OnUpdateHMIAppType, void(std::map<std::string, StringArray>));
- MOCK_METHOD1(GetAvailableApps, void(std::queue<std::string> &));
- MOCK_METHOD1(OnSnapshotCreated, void(const BinaryMessage &pt_string));
+ MOCK_METHOD1(GetAvailableApps, void(std::queue<std::string>&));
+ MOCK_METHOD1(OnSnapshotCreated, void(const BinaryMessage& pt_string));
MOCK_METHOD0(CanUpdate, bool());
- MOCK_METHOD1(OnCertificateUpdated, void(const std::string &));
+ MOCK_METHOD1(OnCertificateUpdated, void(const std::string&));
MOCK_CONST_METHOD2(SendOnAppPermissionsChanged,
- void(const AppPermissions &, const std::string &));
+ void(const AppPermissions&, const std::string&));
};
-} // namespace policy
+} // namespace policy
-#endif // SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_MOCK_POLICY_LISTENER_H_
+#endif // SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_MOCK_POLICY_LISTENER_H_
diff --git a/src/components/policy/test/include/mock_policy_manager.h b/src/components/policy/test/include/mock_policy_manager.h
new file mode 100644
index 0000000000..579e15fcca
--- /dev/null
+++ b/src/components/policy/test/include/mock_policy_manager.h
@@ -0,0 +1,179 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_MOCK_POLICY_MANAGER_H_
+#define SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_MOCK_POLICY_MANAGER_H_
+
+#include <string>
+#include <vector>
+#include "gmock/gmock.h"
+#include "policy/policy_listener.h"
+#include "policy/policy_types.h"
+#include "policy/usage_statistics/statistics_manager.h"
+
+#include "rpc_base/rpc_base.h"
+#include "policy/policy_table/types.h"
+#include "policy/policy_manager.h"
+
+namespace policy_table = ::rpc::policy_table_interface_base;
+
+namespace policy_manager {
+
+using namespace policy;
+
+class MockPolicyManager : public PolicyManager {
+ public:
+ MOCK_METHOD1(set_listener, void(PolicyListener* listener));
+ MOCK_METHOD2(InitPT,
+ bool(const std::string& file_name,
+ const PolicySettings* settings));
+ MOCK_METHOD2(LoadPT,
+ bool(const std::string& file, const BinaryMessage& pt_content));
+ MOCK_METHOD1(ResetPT, bool(const std::string& file_name));
+ MOCK_CONST_METHOD1(GetUpdateUrl, std::string(int service_type));
+ MOCK_METHOD2(GetUpdateUrls, void(int service_type, EndpointUrls& end_points));
+ MOCK_METHOD0(RequestPTUpdate, bool());
+ MOCK_METHOD5(CheckPermissions,
+ void(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ const RPCParams& rpc_params,
+ CheckPermissionResult& result));
+ MOCK_METHOD0(ResetUserConsent, bool());
+ MOCK_CONST_METHOD0(GetPolicyTableStatus, std::string());
+ MOCK_METHOD1(KmsChanged, void(int kilometers));
+ MOCK_METHOD0(IncrementIgnitionCycles, void());
+ MOCK_METHOD0(ForcePTExchange, std::string());
+ MOCK_METHOD0(ResetRetrySequence, void());
+ MOCK_METHOD0(NextRetryTimeout, int());
+ MOCK_METHOD0(TimeoutExchange, int());
+ MOCK_METHOD0(RetrySequenceDelaysSeconds, const std::vector<int>());
+ MOCK_METHOD0(OnExceededTimeout, void());
+ MOCK_METHOD0(OnUpdateStarted, void());
+ MOCK_CONST_METHOD1(GetUserConsentForDevice,
+ DeviceConsent(const std::string& device_id));
+ MOCK_METHOD3(
+ GetUserConsentForApp,
+ void(const std::string& device_id,
+ const std::string& policy_app_id,
+ std::vector<policy::FunctionalGroupPermission>& permissions));
+ MOCK_METHOD2(SetUserConsentForDevice,
+ void(const std::string& device_id, bool is_allowed));
+ MOCK_METHOD2(ReactOnUserDevConsentForApp,
+ bool(const std::string app_id, bool is_device_allowed));
+ MOCK_METHOD2(PTUpdatedAt, void(policy::Counters counter, int value));
+
+ MOCK_METHOD3(GetInitialAppData,
+ bool(const std::string&,
+ policy::StringArray*,
+ policy::StringArray*));
+
+ MOCK_METHOD2(AddDevice,
+ void(const std::string& device_id,
+ const std::string& connection_type));
+ MOCK_METHOD2(SetDeviceInfo,
+ void(const std::string& device_id,
+ const policy::DeviceInfo& device_info));
+ MOCK_METHOD1(SetUserConsentForApp,
+ void(const policy::PermissionConsent& permissions));
+ MOCK_CONST_METHOD2(GetDefaultHmi,
+ bool(const std::string& policy_app_id,
+ std::string* default_hmi));
+ MOCK_CONST_METHOD2(GetPriority,
+ bool(const std::string& policy_app_id,
+ std::string* priority));
+ MOCK_METHOD2(GetUserFriendlyMessages,
+ std::vector<policy::UserFriendlyMessage>(
+ const std::vector<std::string>& message_code,
+ const std::string& language));
+ MOCK_CONST_METHOD1(IsApplicationRevoked, bool(const std::string& app_id));
+ MOCK_METHOD3(
+ GetPermissionsForApp,
+ void(const std::string& device_id,
+ const std::string& policy_app_id,
+ std::vector<policy::FunctionalGroupPermission>& permissions));
+ MOCK_METHOD1(GetAppPermissionsChanges,
+ policy::AppPermissions(const std::string& policy_app_id));
+ MOCK_METHOD1(RemovePendingPermissionChanges, void(const std::string& app_id));
+ MOCK_CONST_METHOD1(GetCurrentDeviceId,
+ std::string&(const std::string& policy_app_id));
+ MOCK_METHOD1(SetSystemLanguage, void(const std::string& language));
+ MOCK_METHOD3(SetSystemInfo,
+ void(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& language));
+ MOCK_METHOD1(SendNotificationOnPermissionsUpdated,
+ void(const std::string& application_id));
+ MOCK_METHOD1(MarkUnpairedDevice, void(const std::string& device_id));
+ MOCK_METHOD1(AddApplication, void(const std::string& application_id));
+ MOCK_METHOD0(CleanupUnpairedDevices, bool());
+ MOCK_CONST_METHOD1(CanAppKeepContext, bool(const std::string& app_id));
+ MOCK_CONST_METHOD1(CanAppStealFocus, bool(const std::string& app_id));
+ MOCK_METHOD0(OnSystemReady, void());
+ MOCK_CONST_METHOD1(GetNotificationsNumber,
+ uint32_t(const std::string& priority));
+ MOCK_METHOD1(SetVINValue, void(const std::string& value));
+ MOCK_METHOD1(IsPredataPolicy, bool(const std::string& policy_app_id));
+ MOCK_CONST_METHOD1(HeartBeatTimeout, uint32_t(const std::string& app_id));
+ MOCK_METHOD1(SaveUpdateStatusRequired, void(bool is_update_needed));
+ MOCK_METHOD0(OnAppsSearchStarted, void());
+ MOCK_METHOD0(OnAppsSearchCompleted, void());
+ MOCK_METHOD1(OnAppRegisteredOnMobile,
+ void(const std::string& application_id));
+ MOCK_CONST_METHOD1(
+ GetAppRequestTypes,
+ const std::vector<std::string>(const std::string policy_app_id));
+ MOCK_CONST_METHOD0(GetVehicleInfo, const policy::VehicleInfo());
+ MOCK_CONST_METHOD0(RetrieveCertificate, std::string());
+ MOCK_METHOD1(SetDecryptedCertificate, void(const std::string&));
+ MOCK_METHOD0(ExceededIgnitionCycles, bool());
+ MOCK_METHOD0(ExceededDays, bool());
+ MOCK_METHOD0(StartPTExchange, void());
+ MOCK_METHOD1(Increment, void(usage_statistics::GlobalCounterId type));
+ MOCK_METHOD2(Increment,
+ void(const std::string& app_id,
+ usage_statistics::AppCounterId type));
+ MOCK_METHOD3(Set,
+ void(const std::string& app_id,
+ usage_statistics::AppInfoId type,
+ const std::string& value));
+ MOCK_METHOD3(Add,
+ void(const std::string& app_id,
+ usage_statistics::AppStopwatchId type,
+ int32_t timespan_seconds));
+ MOCK_CONST_METHOD0(get_settings, const PolicySettings&());
+ MOCK_METHOD1(set_settings, void(const PolicySettings* get_settings));
+};
+
+} // namespace policy_manager
+
+#endif // SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_MOCK_POLICY_MANAGER_H_
diff --git a/src/components/policy/test/include/mock_pt_ext_representation.h b/src/components/policy/test/include/mock_pt_ext_representation.h
index fd779dc1f0..4f6eb7e08f 100644
--- a/src/components/policy/test/include/mock_pt_ext_representation.h
+++ b/src/components/policy/test/include/mock_pt_ext_representation.h
@@ -32,7 +32,6 @@
#ifndef SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_MOCK_PT_EXT_REPRESENTATION_H_
#define SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_MOCK_PT_EXT_REPRESENTATION_H_
-
#include <string>
#include <vector>
@@ -40,91 +39,99 @@
#include "policy/pt_ext_representation.h"
#include "rpc_base/rpc_base.h"
-#include "./types.h"
+#include "policy/policy_table/types.h"
#include "mock_pt_representation.h"
namespace policy_table = ::rpc::policy_table_interface_base;
namespace policy {
class MockPTExtRepresentation : public MockPTRepresentation,
- public PTExtRepresentation {
+ public PTExtRepresentation {
public:
- MOCK_METHOD1(CanAppKeepContext,
- bool(const std::string& app_id));
- MOCK_METHOD1(CanAppStealFocus,
- bool(const std::string& app_id));
+ MOCK_METHOD1(CanAppKeepContext, bool(const std::string& app_id));
+ MOCK_METHOD1(CanAppStealFocus, bool(const std::string& app_id));
MOCK_METHOD2(GetDefaultHMI,
- bool(const std::string& app_id, std::string* default_hmi));
- MOCK_METHOD0(ResetUserConsent,
- bool());
+ bool(const std::string& app_id, std::string* default_hmi));
+ MOCK_METHOD0(ResetUserConsent, bool());
MOCK_METHOD0(ResetDeviceConsents, bool());
MOCK_METHOD0(ResetAppConsents, bool());
MOCK_METHOD3(GetUserPermissionsForDevice,
- bool(const std::string&, StringArray*, StringArray*));
+ bool(const std::string&, StringArray*, StringArray*));
MOCK_METHOD3(GetPermissionsForApp,
- bool(const std::string&, const std::string&,
- FunctionalIdType* group_types));
+ bool(const std::string&,
+ const std::string&,
+ FunctionalIdType* group_types));
MOCK_METHOD2(GetDeviceGroupsFromPolicies,
- bool(policy_table::Strings*, policy_table::Strings*));
- MOCK_METHOD2(GetUserFriendlyMsg,
+ bool(policy_table::Strings*, policy_table::Strings*));
+ MOCK_METHOD2(
+ GetUserFriendlyMsg,
std::vector<UserFriendlyMessage>(const std::vector<std::string>& msg_code,
- const std::string& language));
- MOCK_METHOD8(SetDeviceData, bool(const std::string& device_id,
- const std::string& hardware,
- const std::string& firmware,
- const std::string& os,
- const std::string& os_version,
- const std::string& carrier,
- const uint32_t number_of_ports,
- const std::string& connection_type));
+ const std::string& language));
+ MOCK_METHOD8(SetDeviceData,
+ bool(const std::string& device_id,
+ const std::string& hardware,
+ const std::string& firmware,
+ const std::string& os,
+ const std::string& os_version,
+ const std::string& carrier,
+ const uint32_t number_of_ports,
+ const std::string& connection_type));
MOCK_METHOD6(SetDeviceData,
- bool(const std::string&, const std::string&, const std::string&, const std::string&, const std::string&, const std::string&));
+ bool(const std::string&,
+ const std::string&,
+ const std::string&,
+ const std::string&,
+ const std::string&,
+ const std::string&));
MOCK_METHOD2(SetMaxNumberPorts,
- bool(const std::string& device_id, unsigned int number_of_ports));
+ bool(const std::string& device_id,
+ unsigned int number_of_ports));
MOCK_METHOD3(SetUserPermissionsForDevice,
- bool(const std::string&, const StringArray&, const StringArray&));
- MOCK_METHOD1(SetUserPermissionsForApp,
- bool(const PermissionConsent&));
- MOCK_METHOD1(IncreaseStatisticsData,
- bool(StatisticsType type));
+ bool(const std::string&,
+ const StringArray&,
+ const StringArray&));
+ MOCK_METHOD1(SetUserPermissionsForApp, bool(const PermissionConsent&));
+ MOCK_METHOD1(IncreaseStatisticsData, bool(StatisticsType type));
MOCK_METHOD3(SetAppRegistrationLanguage,
- bool(const std::string& app_id, LanguageType type, const std::string& language));
+ bool(const std::string& app_id,
+ LanguageType type,
+ const std::string& language));
MOCK_METHOD3(SetMetaInfo,
- bool(const std::string& ccpu_version, const std::string& wers_country_code, const std::string& vin));
- MOCK_METHOD0(IsMetaInfoPresent,
- bool());
- MOCK_METHOD1(SetSystemLanguage,
- bool(const std::string& language));
- MOCK_METHOD0(GetKmFromSuccessfulExchange,
- int());
- MOCK_METHOD0(GetDayFromScsExchange,
- int());
- MOCK_METHOD0(GetIgnitionsFromScsExchange,
- int());
- MOCK_CONST_METHOD1(Increment,
- void(const std::string& type));
+ bool(const std::string& ccpu_version,
+ const std::string& wers_country_code,
+ const std::string& vin));
+ MOCK_METHOD0(IsMetaInfoPresent, bool());
+ MOCK_METHOD1(SetSystemLanguage, bool(const std::string& language));
+ MOCK_METHOD0(GetKmFromSuccessfulExchange, int());
+ MOCK_METHOD0(GetDayFromScsExchange, int());
+ MOCK_METHOD0(GetIgnitionsFromScsExchange, int());
+ MOCK_CONST_METHOD1(Increment, void(const std::string& type));
MOCK_CONST_METHOD2(Increment,
- void(const std::string& app_id, const std::string& type));
+ void(const std::string& app_id, const std::string& type));
MOCK_CONST_METHOD3(Set,
- void(const std::string& app_id, const std::string& type, const std::string& value));
+ void(const std::string& app_id,
+ const std::string& type,
+ const std::string& value));
MOCK_CONST_METHOD3(Add,
- void(const std::string& app_id, const std::string& type, int seconds));
+ void(const std::string& app_id,
+ const std::string& type,
+ int seconds));
MOCK_CONST_METHOD3(CountUnconsentedGroups,
- bool(const std::string& app_id,
- const std::string& device_id,
- int* count));
- MOCK_METHOD1(GetFunctionalGroupNames,
- bool(FunctionalGroupNames& names));
- MOCK_CONST_METHOD1(CleanupUnpairedDevices,
- bool(const DeviceIds& device_ids));
+ bool(const std::string& app_id,
+ const std::string& device_id,
+ int* count));
+ MOCK_METHOD1(GetFunctionalGroupNames, bool(FunctionalGroupNames& names));
+ MOCK_CONST_METHOD1(CleanupUnpairedDevices, bool(const DeviceIds& device_ids));
MOCK_METHOD2(ReactOnUserDevConsentForApp,
- bool(const std::string& app_id, bool is_device_allowed));
+ bool(const std::string& app_id, bool is_device_allowed));
MOCK_METHOD1(SetPredataPolicy, bool(const std::string& app_id));
MOCK_METHOD2(SetIsPredata, bool(const std::string& app_id, bool is_predata));
- MOCK_CONST_METHOD2(SetUnpairedDevice, bool(const std::string& device_id, bool unpaired));
+ MOCK_CONST_METHOD2(SetUnpairedDevice,
+ bool(const std::string& device_id, bool unpaired));
MOCK_CONST_METHOD1(UnpairedDevicesList, bool(DeviceIds* device_ids));
- MOCK_CONST_METHOD2(RemoveAppConsentForGroup, bool(const std::string& policy_app_id,
- const std::string& functional_group));
+ MOCK_CONST_METHOD2(RemoveAppConsentForGroup,
+ bool(const std::string& policy_app_id,
+ const std::string& functional_group));
};
} // namespace policy
diff --git a/src/components/policy/test/include/mock_pt_representation.h b/src/components/policy/test/include/mock_pt_representation.h
index 720c646aba..045c901be2 100644
--- a/src/components/policy/test/include/mock_pt_representation.h
+++ b/src/components/policy/test/include/mock_pt_representation.h
@@ -39,7 +39,7 @@
#include "policy/pt_representation.h"
#include "rpc_base/rpc_base.h"
-#include "./types.h"
+#include "policy/policy_table/types.h"
namespace policy_table = ::rpc::policy_table_interface_base;
@@ -48,69 +48,52 @@ namespace policy {
class MockPTRepresentation : virtual public PTRepresentation {
public:
MOCK_METHOD4(CheckPermissions,
- void(const PTString& app_id,
- const PTString& hmi_level,
- const PTString& rpc,
- CheckPermissionResult& result));
- MOCK_METHOD0(IsPTPreloaded,
- bool());
- MOCK_METHOD0(IgnitionCyclesBeforeExchange,
- int());
- MOCK_METHOD1(KilometersBeforeExchange,
- int(int current));
+ void(const PTString& app_id,
+ const PTString& hmi_level,
+ const PTString& rpc,
+ CheckPermissionResult& result));
+ MOCK_METHOD0(IsPTPreloaded, bool());
+ MOCK_METHOD0(IgnitionCyclesBeforeExchange, int());
+ MOCK_METHOD1(KilometersBeforeExchange, int(int current));
MOCK_METHOD2(SetCountersPassedForSuccessfulUpdate,
- bool(int kilometers, int days_after_epoch));
- MOCK_METHOD1(DaysBeforeExchange,
- int(int current));
- MOCK_METHOD0(IncrementIgnitionCycles,
- void());
- MOCK_METHOD0(ResetIgnitionCycles,
- void());
- MOCK_METHOD0(TimeoutResponse,
- int());
- MOCK_METHOD1(SecondsBetweenRetries,
- bool(std::vector<int>* seconds));
+ bool(int kilometers, int days_after_epoch));
+ MOCK_METHOD1(DaysBeforeExchange, int(int current));
+ MOCK_METHOD0(IncrementIgnitionCycles, void());
+ MOCK_METHOD0(ResetIgnitionCycles, void());
+ MOCK_METHOD0(TimeoutResponse, int());
+ MOCK_METHOD1(SecondsBetweenRetries, bool(std::vector<int>* seconds));
MOCK_METHOD2(GetPriority,
- bool(const std::string& app_id, std::string* priority));
- MOCK_METHOD0(GetVehicleData,
- VehicleData());
- MOCK_METHOD1(SetVINValue,
- bool(const std::string& value));
- MOCK_METHOD2(GetUserFriendlyMsg,
+ bool(const std::string& app_id, std::string* priority));
+ MOCK_CONST_METHOD0(GetVehicleInfo, const VehicleInfo());
+ MOCK_METHOD1(SetVINValue, bool(const std::string& value));
+ MOCK_METHOD2(
+ GetUserFriendlyMsg,
std::vector<UserFriendlyMessage>(const std::vector<std::string>& msg_code,
- const std::string& language));
- MOCK_METHOD2(GetUpdateUrls,
- void(int service_type, EndpointUrls&));
- MOCK_METHOD1(GetNotificationsNumber,
- int(const std::string& priority));
- MOCK_METHOD0(Init,
- InitResult());
- MOCK_METHOD0(Close,
- bool());
- MOCK_METHOD0(Clear,
- bool());
- MOCK_METHOD0(Drop,
- bool());
- MOCK_CONST_METHOD0(GenerateSnapshot,
- utils::SharedPtr<policy_table::Table>());
- MOCK_METHOD1(Save,
- bool(const policy_table::Table& table));
- MOCK_CONST_METHOD0(UpdateRequired,
- bool());
- MOCK_METHOD1(SaveUpdateRequired,
- void(bool value));
+ const std::string& language));
+ MOCK_METHOD2(GetUpdateUrls, void(int service_type, EndpointUrls&));
+ MOCK_METHOD1(GetNotificationsNumber, int(const std::string& priority));
+ MOCK_METHOD0(Init, InitResult());
+ MOCK_METHOD0(Close, bool());
+ MOCK_METHOD0(Clear, bool());
+ MOCK_METHOD0(Drop, bool());
+ MOCK_CONST_METHOD0(GenerateSnapshot, utils::SharedPtr<policy_table::Table>());
+ MOCK_METHOD1(Save, bool(const policy_table::Table& table));
+ MOCK_CONST_METHOD0(UpdateRequired, bool());
+ MOCK_METHOD1(SaveUpdateRequired, void(bool value));
MOCK_METHOD3(GetInitialAppData,
- bool(const std::string& app_id, StringArray* nicknames, StringArray* app_types));
+ bool(const std::string& app_id,
+ StringArray* nicknames,
+ StringArray* app_types));
MOCK_METHOD4(SaveApplicationCustomData,
- bool(const std::string& app_id,
- bool is_revoked,
- bool is_default,
- bool is_predata));
+ bool(const std::string& app_id,
+ bool is_revoked,
+ bool is_default,
+ bool is_predata));
MOCK_CONST_METHOD1(IsApplicationRevoked, bool(const std::string& app_id));
MOCK_METHOD1(GetFunctionalGroupings,
- bool(policy_table::FunctionalGroupings& groups));
+ bool(policy_table::FunctionalGroupings& groups));
MOCK_CONST_METHOD1(IsApplicationRepresented, bool(const std::string& app_id));
MOCK_CONST_METHOD1(IsDefaultPolicy, bool(const std::string& app_id));
MOCK_METHOD1(SetDefaultPolicy, bool(const std::string& app_id));
diff --git a/src/components/policy/test/include/mock_statistics_manager.h b/src/components/policy/test/include/mock_statistics_manager.h
deleted file mode 100644
index 2de072f095..0000000000
--- a/src/components/policy/test/include/mock_statistics_manager.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/* Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_MOCK_STATISTICS_MANAGER_H_
-#define SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_MOCK_STATISTICS_MANAGER_H_
-
-#include <string>
-
-#include "gmock/gmock.h"
-
-#include "usage_statistics/statistics_manager.h"
-
-namespace usage_statistics {
-namespace test {
-
-class MockStatisticsManager: public StatisticsManager {
- public:
- MOCK_METHOD1(Increment, void(GlobalCounterId type));
- MOCK_METHOD2(Increment, void(const std::string& app_id, AppCounterId type));
- MOCK_METHOD3(Set, void(const std::string& app_id,
- AppInfoId type,
- const std::string& value));
- MOCK_METHOD3(Add, void(const std::string& app_id,
- AppStopwatchId type,
- int32_t timespan_seconds));
-};
-
-} // namespace test
-} // namespace usage_statistics
-
-#endif // SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_MOCK_STATISTICS_MANAGER_H_
diff --git a/src/components/policy/test/include/mock_update_status_manager.h b/src/components/policy/test/include/mock_update_status_manager.h
index 0050276807..aa6abd7301 100644
--- a/src/components/policy/test/include/mock_update_status_manager.h
+++ b/src/components/policy/test/include/mock_update_status_manager.h
@@ -40,26 +40,16 @@ namespace policy {
class MockUpdateStatusManager : public UpdateStatusManager {
public:
- MOCK_METHOD1(set_listener,
- void(PolicyListener* listener));
- MOCK_METHOD1(OnUpdateSentOut,
- void(uint32_t update_timeout));
- MOCK_METHOD0(OnUpdateTimeoutOccurs,
- void());
- MOCK_METHOD0(OnValidUpdateReceived,
- void());
- MOCK_METHOD0(OnWrongUpdateReceived,
- void());
- MOCK_METHOD1(OnResetDefaultPT,
- void(bool is_update_required));
- MOCK_METHOD0(OnResetRetrySequence,
- void());
- MOCK_METHOD0(OnNewApplicationAdded,
- void());
- MOCK_METHOD1(OnPolicyInit,
- void(bool is_update_required));
- MOCK_METHOD0(GetUpdateStatus,
- PolicyTableStatus());
+ MOCK_METHOD1(set_listener, void(PolicyListener* listener));
+ MOCK_METHOD1(OnUpdateSentOut, void(uint32_t update_timeout));
+ MOCK_METHOD0(OnUpdateTimeoutOccurs, void());
+ MOCK_METHOD0(OnValidUpdateReceived, void());
+ MOCK_METHOD0(OnWrongUpdateReceived, void());
+ MOCK_METHOD1(OnResetDefaultPT, void(bool is_update_required));
+ MOCK_METHOD0(OnResetRetrySequence, void());
+ MOCK_METHOD0(OnNewApplicationAdded, void());
+ MOCK_METHOD1(OnPolicyInit, void(bool is_update_required));
+ MOCK_METHOD0(GetUpdateStatus, PolicyTableStatus());
};
} // namespace policy
diff --git a/src/components/policy/test/policy.sql b/src/components/policy/test/policy.sql
deleted file mode 100644
index c9905f3f8d..0000000000
--- a/src/components/policy/test/policy.sql
+++ /dev/null
@@ -1,295 +0,0 @@
-BEGIN TRANSACTION;
- CREATE TABLE IF NOT EXISTS `device`(
- `id` VARCHAR(100) PRIMARY KEY NOT NULL,
- `hardware` VARCHAR(45),
- `firmware_rev` VARCHAR(45),
- `os` VARCHAR(45),
- `os_version` VARCHAR(45),
- `carrier` VARCHAR(45),
- `max_number_rfcom_ports` INTEGER ,
- `connection_type` VARCHAR(45),
- `unpaired` BOOL
- );
- CREATE TABLE IF NOT EXISTS `usage_and_error_count`(
- `count_of_iap_buffer_full` INTEGER,
- `count_sync_out_of_memory` INTEGER,
- `count_of_sync_reboots` INTEGER
- );
- INSERT OR IGNORE INTO `usage_and_error_count` (
- `count_of_iap_buffer_full`, `count_sync_out_of_memory`,
- `count_of_sync_reboots`) VALUES (0, 0, 0);
- CREATE TABLE IF NOT EXISTS `module_meta`(
- `ccpu_version` VARCHAR(45),
- `language` VARCHAR(45),
- `wers_country_code` VARCHAR(45),
- `pt_exchanged_at_odometer_x` INTEGER NOT NULL DEFAULT 0,
- `pt_exchanged_x_days_after_epoch` INTEGER NOT NULL DEFAULT 0,
- `ignition_cycles_since_last_exchange` INTEGER NOT NULL DEFAULT 0,
- `vin` VARCHAR(45),
- `flag_update_required` BOOL NOT NULL
- );
- INSERT OR IGNORE INTO `module_meta` (`pt_exchanged_at_odometer_x`,
- `pt_exchanged_x_days_after_epoch`, `ignition_cycles_since_last_exchange`,
- `flag_update_required`)
- VALUES (0, 0, 0, 0);
- CREATE TABLE IF NOT EXISTS `module_config`(
- `preloaded_pt` BOOL NOT NULL,
- `is_first_run` BOOL NOT NULL,
- `exchange_after_x_ignition_cycles` INTEGER NOT NULL,
- `exchange_after_x_kilometers` INTEGER NOT NULL,
- `exchange_after_x_days` INTEGER NOT NULL,
- `timeout_after_x_seconds` INTEGER NOT NULL,
- `vehicle_make` VARCHAR(45),
- `vehicle_model` VARCHAR(45),
- `vehicle_year` VARCHAR(4)
- );
- INSERT OR IGNORE INTO `module_config` (`preloaded_pt`, `is_first_run`,
- `exchange_after_x_ignition_cycles`, `exchange_after_x_kilometers`,
- `exchange_after_x_days`, `timeout_after_x_seconds`)
- VALUES(1, 1, 0, 0, 0, 0);
- CREATE TABLE IF NOT EXISTS `functional_group`(
- `id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
- `user_consent_prompt` TEXT UNIQUE ON CONFLICT REPLACE,
- `name` VARCHAR(100) NOT NULL
- );
- CREATE TABLE IF NOT EXISTS `priority`(
- `value` VARCHAR(45) PRIMARY KEY NOT NULL
- );
- INSERT OR IGNORE INTO `priority`(`value`) VALUES ('EMERGENCY');
- INSERT OR IGNORE INTO `priority`(`value`) VALUES ('NAVIGATION');
- INSERT OR IGNORE INTO `priority`(`value`) VALUES ('VOICECOMMUNICATION');
- INSERT OR IGNORE INTO `priority`(`value`) VALUES ('COMMUNICATION');
- INSERT OR IGNORE INTO `priority`(`value`) VALUES ('NORMAL');
- INSERT OR IGNORE INTO `priority`(`value`) VALUES ('NONE');
- CREATE TABLE IF NOT EXISTS `hmi_level`(
- `value` VARCHAR(45) PRIMARY KEY NOT NULL
- );
- INSERT OR IGNORE INTO `hmi_level`(`value`) VALUES ('FULL');
- INSERT OR IGNORE INTO `hmi_level`(`value`) VALUES ('LIMITED');
- INSERT OR IGNORE INTO `hmi_level`(`value`) VALUES ('BACKGROUND');
- INSERT OR IGNORE INTO `hmi_level`(`value`) VALUES ('NONE');
- CREATE TABLE IF NOT EXISTS `notifications_by_priority`(
- `priority_value` VARCHAR(45) PRIMARY KEY NOT NULL,
- `value` INTEGER NOT NULL,
- CONSTRAINT `fk_notifications_by_priority_priority1`
- FOREIGN KEY(`priority_value`)
- REFERENCES `priority`(`value`)
- );
- CREATE INDEX IF NOT EXISTS
- `notifications_by_priority.fk_notifications_by_priority_priority1_idx`
- ON `notifications_by_priority`(`priority_value`);
- CREATE TABLE IF NOT EXISTS `language`(
- `code` VARCHAR(25) PRIMARY KEY NOT NULL
- );
- CREATE TABLE IF NOT EXISTS `message_type`(
- `name` VARCHAR(45) PRIMARY KEY NOT NULL
- );
- CREATE TABLE IF NOT EXISTS `version`(
- `number` VARCHAR(45) NOT NULL
- );
- INSERT OR IGNORE INTO `version` (`number`) VALUES('0');
- CREATE TABLE IF NOT EXISTS `rpc`(
- `id` INTEGER PRIMARY KEY NOT NULL,
- `name` VARCHAR(45) NOT NULL,
- `parameter` VARCHAR(45),
- `hmi_level_value` VARCHAR(45) NOT NULL,
- `functional_group_id` INTEGER NOT NULL,
- CONSTRAINT `fk_rpc_hmi_level1`
- FOREIGN KEY(`hmi_level_value`)
- REFERENCES `hmi_level`(`value`),
- CONSTRAINT `fk_rpc_functional_group1`
- FOREIGN KEY(`functional_group_id`)
- REFERENCES `functional_group`(`id`)
- );
- CREATE INDEX IF NOT EXISTS `rpc.fk_rpc_hmi_level1_idx`
- ON `rpc`(`hmi_level_value`);
- CREATE INDEX IF NOT EXISTS `rpc.fk_rpc_functional_group1_idx`
- ON `rpc`(`functional_group_id`);
- CREATE INDEX `rpc.select_rpc_name_hmi_level`
- ON `rpc`(`name`,`hmi_level_value`);
- CREATE TABLE IF NOT EXISTS `application`(
- `id` VARCHAR(45) PRIMARY KEY NOT NULL,
- `keep_context` BOOLEAN,
- `steal_focus` BOOLEAN,
- `default_hmi` VARCHAR(45),
- `priority_value` VARCHAR(45),
- `is_revoked` BOOLEAN,
- `is_default` BOOLEAN,
- `is_predata` BOOLEAN,
- `memory_kb` INTEGER NOT NULL,
- `heart_beat_timeout_ms` INTEGER NOT NULL,
- `certificate` VARCHAR(45),
- CONSTRAINT `fk_application_hmi_level1`
- FOREIGN KEY(`default_hmi`)
- REFERENCES `hmi_level`(`value`),
- CONSTRAINT `fk_application_priorities1`
- FOREIGN KEY(`priority_value`)
- REFERENCES `priority`(`value`)
- );
- CREATE INDEX IF NOT EXISTS `application.fk_application_hmi_level1_idx`
- ON `application`(`default_hmi`);
- CREATE INDEX IF NOT EXISTS `application.fk_application_priorities1_idx`
- ON `application`(`priority_value`);
- CREATE TABLE IF NOT EXISTS `app_group`(
- `application_id` VARCHAR(45) NOT NULL,
- `functional_group_id` INTEGER NOT NULL,
- PRIMARY KEY(`application_id`,`functional_group_id`),
- CONSTRAINT `fk_application_has_functional_group_application1`
- FOREIGN KEY(`application_id`)
- REFERENCES `application`(`id`),
- CONSTRAINT `fk_application_has_functional_group_functional_group1`
- FOREIGN KEY(`functional_group_id`)
- REFERENCES `functional_group`(`id`)
- );
- CREATE INDEX IF NOT EXISTS `app_group.fk_application_has_functional_group_functional_group1_idx`
- ON `app_group`(`functional_group_id`);
- CREATE INDEX IF NOT EXISTS `app_group.fk_application_has_functional_group_application1_idx`
- ON `app_group`(`application_id`);
- CREATE TABLE IF NOT EXISTS `preconsented_group`(
- `application_id` VARCHAR(45) NOT NULL,
- `functional_group_id` INTEGER NOT NULL,
- PRIMARY KEY(`application_id`,`functional_group_id`),
- CONSTRAINT `fk_application_has_functional_group_application2`
- FOREIGN KEY(`application_id`)
- REFERENCES `application`(`id`),
- CONSTRAINT `fk_application_has_functional_group_functional_group2`
- FOREIGN KEY(`functional_group_id`)
- REFERENCES `functional_group`(`id`)
- );
- CREATE INDEX IF NOT EXISTS
- `preconsented_group.fk_application_has_functional_group_functional_group2_idx`
- ON `preconsented_group`(`functional_group_id`);
- CREATE INDEX IF NOT EXISTS
- `preconsented_group.fk_application_has_functional_group_application2_idx`
- ON `preconsented_group`(`application_id`);
- CREATE TABLE IF NOT EXISTS `seconds_between_retry`(
- `index` INTEGER PRIMARY KEY NOT NULL,
- `value` INTEGER NOT NULL
- );
- CREATE TABLE IF NOT EXISTS `device_consent_group`(
- `device_id` VARCHAR(100) NOT NULL,
- `functional_group_id` INTEGER NOT NULL,
- `is_consented` BOOL NOT NULL,
- `input` VARCHAR(45),
- `time_stamp` DATETIME DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY(`device_id`,`functional_group_id`),
- CONSTRAINT `fk_device_has_functional_group_device1`
- FOREIGN KEY(`device_id`)
- REFERENCES `device`(`id`),
- CONSTRAINT `fk_device_has_functional_group_functional_group1`
- FOREIGN KEY(`functional_group_id`)
- REFERENCES `functional_group`(`id`)
- );
- CREATE INDEX IF NOT EXISTS
- `device_consent_group.fk_device_has_functional_group_functional_group1_idx`
- ON `device_consent_group`(`functional_group_id`);
- CREATE INDEX IF NOT EXISTS
- `device_consent_group.fk_device_has_functional_group_device1_idx`
- ON `device_consent_group`(`device_id`);
- CREATE TABLE IF NOT EXISTS `app_level`(
- `application_id` VARCHAR(45) PRIMARY KEY NOT NULL,
- `minutes_in_hmi_full` INTEGER DEFAULT 0,
- `minutes_in_hmi_limited` INTEGER DEFAULT 0,
- `minutes_in_hmi_background` INTEGER DEFAULT 0,
- `minutes_in_hmi_none` INTEGER DEFAULT 0,
-
- `count_of_user_selections` INTEGER DEFAULT 0,
- `count_of_rejections_sync_out_of_memory` INTEGER DEFAULT 0,
- `count_of_rejections_nickname_mismatch` INTEGER DEFAULT 0,
- `count_of_rejections_duplicate_name` INTEGER DEFAULT 0,
- `count_of_rejected_rpcs_calls` INTEGER DEFAULT 0,
- `count_of_rpcs_sent_in_hmi_none` INTEGER DEFAULT 0,
- `count_of_removals_for_bad_behavior` INTEGER DEFAULT 0,
- `count_of_run_attempts_while_revoked` INTEGER DEFAULT 0,
- `app_registration_language_gui` VARCHAR(25),
- `app_registration_language_vui` VARCHAR(25),
- CONSTRAINT `fk_app_levels_application1`
- FOREIGN KEY(`application_id`)
- REFERENCES `application`(`id`),
- CONSTRAINT `fk_app_level_language1`
- FOREIGN KEY(`app_registration_language_gui`)
- REFERENCES `language`(`code`),
- CONSTRAINT `fk_app_level_language2`
- FOREIGN KEY(`app_registration_language_vui`)
- REFERENCES `language`(`code`)
- );
- CREATE INDEX IF NOT EXISTS `app_level.fk_app_levels_application1_idx`
- ON `app_level`(`application_id`);
- CREATE INDEX IF NOT EXISTS `app_level.fk_app_level_language1_idx`
- ON `app_level`(`app_registration_language_gui`);
- CREATE INDEX IF NOT EXISTS `app_level.fk_app_level_language2_idx`
- ON `app_level`(`app_registration_language_vui`);
- CREATE TABLE IF NOT EXISTS `nickname`(
- `name` VARCHAR(100) NOT NULL,
- `application_id` VARCHAR(45) NOT NULL,
- PRIMARY KEY(`name`,`application_id`),
- CONSTRAINT `fk_nickname_application1`
- FOREIGN KEY(`application_id`)
- REFERENCES `application`(`id`)
- );
- CREATE INDEX IF NOT EXISTS `nickname.fk_nickname_application1_idx`
- ON `nickname`(`application_id`);
- CREATE TABLE IF NOT EXISTS `app_type`(
- `name` VARCHAR(50) NOT NULL,
- `application_id` VARCHAR(45) NOT NULL,
- PRIMARY KEY(`name`,`application_id`),
- CONSTRAINT `fk_app_type_application1`
- FOREIGN KEY(`application_id`)
- REFERENCES `application`(`id`)
- );
- CREATE INDEX IF NOT EXISTS `app_type.fk_app_type_application1_idx`
- ON `app_type`(`application_id`);
- CREATE TABLE IF NOT EXISTS `consent_group`(
- `device_id` VARCHAR(100) NOT NULL,
- `application_id` VARCHAR(45) NOT NULL,
- `functional_group_id` INTEGER NOT NULL,
- `is_consented` BOOL NOT NULL,
- `input` VARCHAR(45),
- `time_stamp` DATETIME DEFAULT CURRENT_TIMESTAMP,
- PRIMARY KEY(`application_id`,`functional_group_id`,`device_id`),
- CONSTRAINT `fk_consent_group_device1`
- FOREIGN KEY(`device_id`)
- REFERENCES `device`(`id`),
- CONSTRAINT `fk_consent_group_application1`
- FOREIGN KEY(`application_id`)
- REFERENCES `application`(`id`),
- CONSTRAINT `fk_consent_group_functional_group1`
- FOREIGN KEY(`functional_group_id`)
- REFERENCES `functional_group`(`id`)
- );
- CREATE INDEX IF NOT EXISTS
- `consent_group.fk_consent_group_device1_idx`
- ON `device_consent_group`(`device_id`);
- CREATE INDEX IF NOT EXISTS `consent_group.fk_consent_group_functional_group1_idx`
- ON `consent_group`(`functional_group_id`);
- CREATE TABLE IF NOT EXISTS `endpoint`(
- `service` VARCHAR(100) NOT NULL,
- `url` VARCHAR(100) NOT NULL,
- `application_id` VARCHAR(45) NOT NULL,
- CONSTRAINT `fk_endpoint_application1`
- FOREIGN KEY(`application_id`)
- REFERENCES `application`(`id`)
- );
- CREATE INDEX IF NOT EXISTS `endpoint.fk_endpoint_application1_idx`
- ON `endpoint`(`application_id`);
- CREATE TABLE IF NOT EXISTS `message`(
- `id` INTEGER PRIMARY KEY NOT NULL,
- `tts` TEXT,
- `label` TEXT,
- `line1` TEXT,
- `line2` TEXT,
- `textBody` TEXT,
- `language_code` VARCHAR(25) NOT NULL,
- `message_type_name` VARCHAR(45) NOT NULL,
- CONSTRAINT `fk_messages_languages1`
- FOREIGN KEY(`language_code`)
- REFERENCES `language`(`code`),
- CONSTRAINT `fk_message_consumer_friendly_messages1`
- FOREIGN KEY(`message_type_name`)
- REFERENCES `message_type`(`name`)
- );
- CREATE INDEX IF NOT EXISTS `message.fk_messages_languages1_idx`
- ON `message`(`language_code`);
- CREATE INDEX IF NOT EXISTS `message.fk_message_consumer_friendly_messages1_idx`
- ON `message`(`message_type_name`);
-COMMIT;
diff --git a/src/components/policy/test/policy/CMakeLists.txt b/src/components/policy/test/policy/CMakeLists.txt
deleted file mode 100644
index e390901cfb..0000000000
--- a/src/components/policy/test/policy/CMakeLists.txt
+++ /dev/null
@@ -1,86 +0,0 @@
-include_directories(
- ./
- ./include
- ${LOG4CXX_INCLUDE_DIRECTORY}
- ${GMOCK_INCLUDE_DIRECTORY}
- ${JSONCPP_INCLUDE_DIRECTORY}
- ${CMAKE_SOURCE_DIR}/src/components/policy/src/policy/include/
- ${CMAKE_SOURCE_DIR}/src/components/rpc_base/include
- ${CMAKE_SOURCE_DIR}/src/components/policy/src/policy/sqlite_wrapper/include
- ${CMAKE_SOURCE_DIR}/src/components/policy/src/policy/qdb_wrapper/include
- ${CMAKE_SOURCE_DIR}/src/components/policy/src/policy/usage_statistics/include
- ${CMAKE_SOURCE_DIR}/src/components/utils/include/
-)
-
-set(LIBRARIES
- gtest
- gtest_main
- gmock
- gmock_main
- Policy
- ConfigProfile
- ${RTLIB}
-)
-
-set(SHARED_LIBRARY_LIBRARIES
- gtest
- gtest_main
- gmock
- gmock_main
- dl
-)
-
-if (CMAKE_SYSTEM_NAME STREQUAL "QNX")
- list(REMOVE_ITEM SHARED_LIBRARY_LIBRARIES dl)
-endif()
-
-set(SHARED_LIBRARY_SOURCES
- ./src/test_shared_library.cc
-)
-
-set(SQL_PT_REPRESENTATION_SOURCES
- ./src/test_sql_pt_representation.cc
-)
-
-set(GENERATED_CODE_SOURCES
- ./src/generated_code_test.cc
-)
-
-set(GENERATED_CODE_WITH_SQLITE_SOURCES
- ./src/generated_code_with_sqlite_test.cc
-)
-
-set(POLICY_MANAGER_IMPL_SOURCES
- ./src/test_policy_manager_impl.cc
-)
-
-set(STRESS_POLICY_MANAGER_IMPL_SOURCES
- ./src/test_stress_policy_manager_impl.cc
-)
-
-add_subdirectory(usage_statistics)
-
-
-
-if (CMAKE_SYSTEM_NAME STREQUAL "QNX")
- # --- Tests for QDB Wrapper
- add_subdirectory(qdb_wrapper)
- file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/qdbserver.sh DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
- file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/test-qdb.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
-else ()
- # --- Tests for SQLite Wrapper
- add_subdirectory(sqlite_wrapper)
- create_test("test_generated_code_with_sqlite" "${GENERATED_CODE_WITH_SQLITE_SOURCES}" "${LIBRARIES}")
-
- include_directories(${CMAKE_SOURCE_DIR}/src/components/policy/src/policy/policy_table/table_struct)
- # TODO(KKolodiy): test crashes in QNX and failed for extended policy
- create_test("test_stress_PolicyManagerImpl" "${STRESS_POLICY_MANAGER_IMPL_SOURCES}" "${LIBRARIES}")
-endif()
-
-create_test("test_generated_policy_code" "${GENERATED_CODE_SOURCES}" "${LIBRARIES}")
-create_test("test_SharedLibrary" "${SHARED_LIBRARY_SOURCES}" "${SHARED_LIBRARY_LIBRARIES}")
-create_test("test_SQLPTRepresentation" "${SQL_PT_REPRESENTATION_SOURCES}" "${LIBRARIES}")
-create_test("test_PolicyManagerImpl" "${POLICY_MANAGER_IMPL_SOURCES}" "${LIBRARIES}")
-
-file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/valid_sdl_pt_update.json DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
-file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/log4cxx.properties DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
diff --git a/src/components/policy/test/policy/qdb_wrapper/CMakeLists.txt b/src/components/policy/test/policy/qdb_wrapper/CMakeLists.txt
deleted file mode 100644
index 16191eaf50..0000000000
--- a/src/components/policy/test/policy/qdb_wrapper/CMakeLists.txt
+++ /dev/null
@@ -1,29 +0,0 @@
-find_package(Sqlite3 REQUIRED)
-
-include_directories(
- ${LOG4CXX_INCLUDE_DIRECTORY}
- ${GMOCK_INCLUDE_DIRECTORY}
- ${CMAKE_SOURCE_DIR}/src/components/policy/src/policy/qdb_wrapper/include
-)
-
-set(LIBRARIES
- gtest
- gtest_main
- gmock
- gmock_main
- dbms
-)
-
-set(DATABASE_SOURCES
- ./src/test_sql_database.cc
-)
-
-set(QUERY_SOURCES
- ./src/test_sql_query.cc
-)
-
-create_test("test_SQLDatabase" "${DATABASE_SOURCES}" "${LIBRARIES}")
-create_test("test_SQLQuery" "${QUERY_SOURCES}" "${LIBRARIES}")
-
-file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/../qdbserver.sh DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
-file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/../test-qdb.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
diff --git a/src/components/policy/test/policy/sqlite_wrapper/CMakeLists.txt b/src/components/policy/test/policy/sqlite_wrapper/CMakeLists.txt
deleted file mode 100644
index 40a901ed82..0000000000
--- a/src/components/policy/test/policy/sqlite_wrapper/CMakeLists.txt
+++ /dev/null
@@ -1,27 +0,0 @@
-find_package(Sqlite3 REQUIRED)
-
-include_directories(
- ${LOG4CXX_INCLUDE_DIRECTORY}
- ${GMOCK_INCLUDE_DIRECTORY}
- ${CMAKE_SOURCE_DIR}/src/components/policy/src/policy/sqlite_wrapper/include
-)
-
-set(LIBRARIES
- gtest
- gtest_main
- gmock
- gmock_main
- dbms
- sqlite3
-)
-
-set(DATABASE_SOURCES
- ./src/test_sql_database.cc
-)
-
-set(QUERY_SOURCES
- ./src/test_sql_query.cc
-)
-
-create_test("test_SQLDatabase" "${DATABASE_SOURCES}" "${LIBRARIES}")
-create_test("test_SQLQuery" "${QUERY_SOURCES}" "${LIBRARIES}")
diff --git a/src/components/policy/test/policy/usage_statistics/CMakeLists.txt b/src/components/policy/test/policy/usage_statistics/CMakeLists.txt
deleted file mode 100644
index 25717b4cad..0000000000
--- a/src/components/policy/test/policy/usage_statistics/CMakeLists.txt
+++ /dev/null
@@ -1,17 +0,0 @@
-include_directories(
- include
- ${LOG4CXX_INCLUDE_DIRECTORY}
- ${CMAKE_SOURCE_DIR}/src/components/policy/usage_statistics/include
- ${GMOCK_INCLUDE_DIRECTORY}
-)
-
-set(LIBRARIES
- gmock_main
- UsageStatistics
-)
-
-set(SOURCES
- src/test_counter.cc
-)
-
-create_test("test_counter" "${SOURCES}" "${LIBRARIES}")
diff --git a/src/components/policy/test/policy_manager_impl_stress_test.cc b/src/components/policy/test/policy_manager_impl_stress_test.cc
deleted file mode 100644
index 1f85f738c7..0000000000
--- a/src/components/policy/test/policy_manager_impl_stress_test.cc
+++ /dev/null
@@ -1,289 +0,0 @@
-/* Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "gtest/gtest.h"
-#include <fstream>
-#include "config_profile/profile.h"
-#include "mock_policy_listener.h"
-#include "policy/policy_manager_impl.h"
-
-using ::testing::_;
-using ::policy::PolicyManagerImpl;
-using ::policy::BinaryMessage;
-using ::policy::MockPolicyListener;
-
-namespace test {
-namespace components {
-namespace policy {
-
-class PolicyManagerImplStressTest : public ::testing::Test {
- protected:
- static const std::string kNameFile;
- static const int kNumberGroups = 3; //10;
- static const int kNumberFuncs = 4; //100;
- static const int kNumberApps = 5;
- static const int kNumberAppGroups = 5;
- static PolicyManagerImpl* manager;
- static MockPolicyListener* mock_listener;
-
- static void SetUpTestCase();
- static void TearDownTestCase();
- static void CreateTable(std::ofstream& ofs);
- static void CreateGroups(std::ofstream& ofs);
- static void CreateFuncs(std::ofstream& ofs);
- static void CreateApps(std::ofstream& ofs);
- static void CreateAppGroups(std::ofstream& ofs);
-};
-
-const std::string PolicyManagerImplStressTest::kNameFile =
- "sdl_preloaded_pt.json";
-PolicyManagerImpl* PolicyManagerImplStressTest::manager = 0;
-MockPolicyListener* PolicyManagerImplStressTest::mock_listener = 0;
-
-void PolicyManagerImplStressTest::SetUpTestCase() {
- std::ofstream ofs;
- ofs.open(kNameFile.c_str(), std::ofstream::out);
- CreateTable(ofs);
- ofs.close();
-
- profile::Profile::instance()->config_file_name("smartDeviceLink.ini");
-
- manager = new PolicyManagerImpl();
- mock_listener = new MockPolicyListener();
- manager->set_listener(mock_listener);
-
- //TODO(AGaliuzov) APPLINK-10657
- ASSERT_TRUE(manager->InitPT(kNameFile));
-}
-
-void PolicyManagerImplStressTest::TearDownTestCase() {
- delete manager;
- delete mock_listener;
- remove(kNameFile.c_str());
-#ifndef __QNX__
- remove("policy.sqlite");
-#endif // __QNX__
-}
-
-void PolicyManagerImplStressTest::CreateGroups(std::ofstream& ofs) {
- std::stringstream ss;
- std::string number;
- for (int i = 0; i < kNumberGroups - 1; ++i) {
- ss << i << std::endl;
- ss >> number;
- ofs << "\"Group-" << number << "\":{\n \t\"rpcs\":{\n";
- CreateFuncs(ofs);
- ofs << "} },\n";
- }
- ss << kNumberGroups - 1 << std::endl;
- ss >> number;
- ofs << "\"Group-" << number << "\":{\n \t\"rpcs\":{\n";
- CreateFuncs(ofs);
- ofs << "} }\n";
-}
-
-void PolicyManagerImplStressTest::CreateFuncs(std::ofstream& ofs) {
- std::string func = "{\n"
- "\t\t\"hmi_levels\":["
- "\"BACKGROUND\","
- "\"FULL\","
- "\"LIMITED\""
- "]"
- "}";
-
- std::stringstream ss;
- std::string number;
- for (int i = 0; i < kNumberFuncs - 1; ++i) {
- ss << i << std::endl;
- ss >> number;
- ofs << "\t\"Func-" << number << "\":" << func << ",\n";
- }
- ss << kNumberFuncs - 1 << std::endl;
- ss >> number;
- ofs << "\t\"Func-" << number << "\":" + func;
-}
-
-void PolicyManagerImplStressTest::CreateApps(std::ofstream& ofs) {
-
- ofs << "\"default\":{\n";
- ofs << "\"keep_context\": true,\n"
- "\"steal_focus\": true,\n"
- "\"priority\": \"NORMAL\",\n"
- "\"default_hmi\": \"FULL\",\n";
- ofs << "\"groups\":["
- "\"Group-1\""
- "]"
- "},\n";
-
- std::stringstream ss;
- std::string number;
- for (int i = 0; i < kNumberApps - 1; ++i) {
- ss << i << std::endl;
- ss >> number;
- ofs << "\"" << number << "\" : {";
- ofs << "\n\"keep_context\": true,\n"
- "\"steal_focus\": true,\n"
- "\"priority\": \"NORMAL\",\n"
- "\"default_hmi\": \"FULL\",\n";
-
- ofs << "\"groups\": ";
- CreateAppGroups(ofs);
- ofs << "},\n";
- }
- ss << kNumberApps - 1 << std::endl;
- ss >> number;
- ofs << "\"" << number << "\" : {";
- ofs << "\n\"keep_context\": true,\n"
- "\"steal_focus\": true,\n"
- "\"priority\": \"NORMAL\",\n"
- "\"default_hmi\": \"FULL\",\n";
-
- ofs << "\"groups\": ";
- CreateAppGroups(ofs);
- ofs << "}\n";
-}
-
-void PolicyManagerImplStressTest::CreateAppGroups(std::ofstream& ofs) {
- ofs << "[";
-
- std::stringstream ss;
- std::string number;
- std::set<int> app_groups;
- for (int i = 0; i < kNumberAppGroups; ++i) {
- app_groups.insert(rand() % kNumberGroups);
- }
-
- std::set<int>::const_iterator i = app_groups.begin();
- ss << *i << std::endl;
- ss >> number;
- ofs << "\"Group-" << number << "\"";
- ++i;
- for (; i != app_groups.end(); ++i) {
- ss << *i << std::endl;
- ss >> number;
- ofs << ",\"Group-" << number << "\"";
- }
- ofs << "]\n";
-}
-
-void PolicyManagerImplStressTest::CreateTable(std::ofstream& ofs) {
- ofs << "{"
- "\"policy_table\":{\n"
- "\"module_config\":{\n"
- "\t\"preloaded_pt\":true,\n"
- "\t\"endpoints\":{\n"
- "\t\t\"default\": {\n"
- "\t\t\t\"default\":["
- "\"http://sdl.net/api\""
- "]\n"
- "\t\t}\n"
- "\t},\n"
-
- "\"notifications_per_minute_by_priority\": {\n"
- "\t\"EMERGENCY\": 60,\n"
- "\t\"NAVIGATION\": 15,\n"
- "\t\"COMMUNICATION\": 6,\n"
- "\t\"NORMAL\": 4,\n"
- "\t\"NONE\": 0\n"
- "},\n"
-
- "\"exchange_after_x_ignition_cycles\": 40,\n"
- "\"exchange_after_x_kilometers\" : 2,\n"
- "\"exchange_after_x_days\" : 23,\n"
- "\"timeout_after_x_seconds\" : 20,\n"
- "\"seconds_between_retries\" : [10, 7, 5, 3, 1]\n"
- "},"
- "\"consumer_friendly_messages\":{\n"
- "\t\"version\":\"001.001.001\",\n"
- "\t\"messages\":{} },\n"
- "\"functional_groupings\":{\n";
-
- CreateGroups(ofs);
-
- ofs << "}, \"app_policies\":{";
-
- CreateApps(ofs);
-
- ofs << "} } }";
-}
-
-TEST_F(PolicyManagerImplStressTest, OneCheck_AppAndFunctuionExisting_RpcAllowed) {
- ::policy::RPCParams input_params;
- ::policy::CheckPermissionResult output;
- manager->CheckPermissions("2", "FULL", "Func-1", input_params, output);
- EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted);
-}
-
-TEST_F(PolicyManagerImplStressTest, NoApp_AppDoesNotExisted_RpcDissallowed) {
- ::policy::RPCParams input_params;
- ::policy::CheckPermissionResult output;
- manager->CheckPermissions("150", "FULL", "Func-88", input_params, output);
- EXPECT_EQ(::policy::kRpcDisallowed, output.hmi_level_permitted);
-}
-
-TEST_F(PolicyManagerImplStressTest, NoFunc_FuncDoesNotExisted_RpcDissallowed) {
- ::policy::RPCParams input_params;
- ::policy::CheckPermissionResult output;
- manager->CheckPermissions("2", "FULL", "Func-400", input_params, output);
- EXPECT_EQ(::policy::kRpcDisallowed, output.hmi_level_permitted);
-}
-
-TEST_F(PolicyManagerImplStressTest, NoHmi_HMIInLevelNone_RpcDissallowed) {
- ::policy::RPCParams input_params;
- ::policy::CheckPermissionResult output;
- manager->CheckPermissions("2", "NONE", "Func-88", input_params, output);
- EXPECT_EQ(::policy::kRpcDisallowed, output.hmi_level_permitted);
-}
-
-TEST_F(PolicyManagerImplStressTest, FewChecks_CheckSeveralFunctions_RpcAllowed) {
- const int kNumberOfCheckings = kNumberFuncs; //100;
- std::stringstream ss;
- int app, func;
- std::string app_number, func_number;
- for (int i = 0; i < kNumberOfCheckings; ++i) {
- app = rand() % kNumberApps;
- func = rand() % kNumberFuncs;
- ss << app << std::endl;
- ss >> app_number;
- ss << func << std::endl;
- ss >> func_number;
-
- ::policy::RPCParams input_params;
- ::policy::CheckPermissionResult output;
- manager->CheckPermissions(app_number, "FULL", "Func-" + func_number,
- input_params, output);
- EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted);
- }
-}
-
-} // namespace policy
-} // namespace components
-} // namespace test
diff --git a/src/components/policy/test/policy_manager_impl_test.cc b/src/components/policy/test/policy_manager_impl_test.cc
index 9bc30b3508..34bcc1127e 100644
--- a/src/components/policy/test/policy_manager_impl_test.cc
+++ b/src/components/policy/test/policy_manager_impl_test.cc
@@ -31,32 +31,45 @@
*/
#include <vector>
+#include <fstream>
+#include <string>
+#include <ctime>
+#include "json/reader.h"
+#include "json/writer.h"
#include "gtest/gtest.h"
+
+#include "policy/policy_manager_impl.h"
+#include "config_profile/profile.h"
+#include "policy/policy_table/enums.h"
+#include "policy/policy_table/types.h"
+#include "policy/mock_policy_settings.h"
#include "mock_policy_listener.h"
-#include "mock_pt_ext_representation.h"
#include "mock_cache_manager.h"
#include "mock_update_status_manager.h"
-#include "policy/policy_manager_impl.h"
-using ::testing::_;
-using ::testing::Return;
+#include "utils/macro.h"
+#include "utils/file_system.h"
+#include "utils/date_time.h"
+#include "utils/make_shared.h"
+#include "utils/gen_hash.h"
+
+using ::testing::ReturnRef;
using ::testing::DoAll;
using ::testing::SetArgReferee;
using ::testing::NiceMock;
+using ::testing::_;
+using ::testing::SetArgReferee;
using ::testing::AtLeast;
+using ::testing::Return;
-using ::policy::PTRepresentation;
using ::policy::MockPolicyListener;
-using ::policy::MockPTRepresentation;
-using ::policy::MockPTExtRepresentation;
-using ::policy::MockCacheManagerInterface;
+using ::policy::MockCacheManagerInterface;
using ::policy::MockUpdateStatusManager;
using ::policy::PolicyManagerImpl;
using ::policy::PolicyTable;
-using ::policy::EndpointUrls;
namespace policy_table = rpc::policy_table_interface_base;
@@ -64,29 +77,86 @@ namespace test {
namespace components {
namespace policy {
+namespace custom_str = utils::custom_string;
+
+typedef std::multimap<std::string, policy_table::Rpcs&>
+ UserConsentPromptToRpcsConnections;
+
+template <typename T>
+std::string NumberToString(T Number) {
+ std::ostringstream ss;
+ ss << Number;
+ return ss.str();
+}
+
+template <typename T>
+void SortAndCheckEquality(std::vector<T> first, std::vector<T> second) {
+ ASSERT_EQ(first.size(), second.size());
+ std::sort(first.begin(), first.end());
+ std::sort(second.begin(), second.end());
+ // Checks
+ for (uint32_t i = 0; i < first.size(); ++i) {
+ EXPECT_EQ(first[i], second[i]);
+ }
+}
+
+struct StringsForUpdate {
+ std::string new_field_value_;
+ std::string new_field_name_;
+ std::string new_date_;
+};
+
+char GenRandomString(const char* alphanum) {
+ const int stringLength = sizeof(alphanum) - 1;
+ return alphanum[rand() % stringLength];
+}
+
+struct StringsForUpdate CreateNewRandomData(StringsForUpdate& str) {
+ // Generate random date
+ srand(time(NULL));
+ unsigned int day = 1 + rand() % 31; // Day from 1 - 31
+ unsigned int month = 1 + rand() % 12; // Month from 1 - 12
+ unsigned int year = 1985 + rand() % 31; // Year from 1985 - 2015
+
+ // Convert date to string
+ str.new_date_ = NumberToString(year) + '-' + NumberToString(month) + '-' +
+ NumberToString(day);
+
+ // Create new field
+ unsigned int number = 1 + rand() % 100; // Number from 1 - 100
+ str.new_field_name_ += NumberToString(number);
+
+ // Create new field random value
+ const char alphanum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+
+ for (unsigned int i = 0; i < 5; ++i) {
+ str.new_field_value_ += GenRandomString(alphanum);
+ }
+ return str;
+}
+
class PolicyManagerImplTest : public ::testing::Test {
-protected:
- PolicyManagerImpl *manager;
- MockCacheManagerInterface *cache_manager;
- MockUpdateStatusManager update_manager;
- MockPolicyListener *listener;
+ public:
+ PolicyManagerImplTest() : device_id("08-00-27-CE-76-FE") {}
- void SetUp() {
- manager = new PolicyManagerImpl();
+ protected:
+ PolicyManagerImpl* manager;
+ MockCacheManagerInterface* cache_manager;
+ NiceMock<MockPolicyListener> listener;
+ const std::string device_id;
+ void SetUp() OVERRIDE {
+ manager = new PolicyManagerImpl();
+ manager->set_listener(&listener);
cache_manager = new MockCacheManagerInterface();
manager->set_cache_manager(cache_manager);
-
- listener = new MockPolicyListener();
- manager->set_listener(listener);
}
- void TearDown() {
+ void TearDown() OVERRIDE {
delete manager;
- delete listener;
}
- ::testing::AssertionResult IsValid(const policy_table::Table &table) {
+ ::testing::AssertionResult IsValid(const policy_table::Table& table) {
if (table.is_valid()) {
return ::testing::AssertionSuccess();
} else {
@@ -97,237 +167,1174 @@ protected:
}
};
-TEST_F(
- PolicyManagerImplTest,
- RefreshRetrySequence_SetSecondsBetweenRetries_ExpectRetryTimeoutSequenceWithSameSeconds) {
+class PolicyManagerImplTest2 : public ::testing::Test {
+ public:
+ PolicyManagerImplTest2()
+ : app_id1("123456789")
+ , app_id2("1766825573")
+ , dev_id1("XXX123456789ZZZ")
+ , dev_id2("08-00-27-CE-76-FE")
+ , PTU_request_types(Json::arrayValue) {}
+
+ protected:
+ PolicyManagerImpl* manager;
+ NiceMock<MockPolicyListener> listener;
+ std::vector<std::string> hmi_level;
+ std::vector<std::string> PT_request_types;
+ uint32_t PTU_request_types_size;
+ unsigned int index;
+ const std::string app_id1;
+ const std::string app_id2;
+ const std::string dev_id1;
+ const std::string dev_id2;
+ Json::Value PTU_request_types;
+ NiceMock<policy_handler_test::MockPolicySettings> policy_settings_;
+ const std::string kAppStorageFolder = "storage1";
+
+ void SetUp() OVERRIDE {
+ file_system::CreateDirectory("storage1");
+ file_system::DeleteFile("policy.sqlite");
+
+ manager = new PolicyManagerImpl();
+ ON_CALL(policy_settings_, app_storage_folder())
+ .WillByDefault(ReturnRef(kAppStorageFolder));
+ manager->set_listener(&listener);
+ const char* levels[] = {"BACKGROUND", "FULL", "LIMITED", "NONE"};
+ hmi_level.assign(levels, levels + sizeof(levels) / sizeof(levels[0]));
+ srand(time(NULL));
+ index = rand() % 3;
+ }
+
+ std::vector<std::string> JsonToVectorString(
+ const Json::Value& PTU_request_types) {
+ std::vector<std::string> result;
+ for (uint32_t i = 0; i < PTU_request_types.size(); ++i) {
+ result.push_back(PTU_request_types[i].asString());
+ }
+ return result;
+ }
+
+ const Json::Value GetPTU(std::string file_name) {
+ // Get PTU
+ std::ifstream ifile(file_name);
+ Json::Reader reader;
+ std::string json;
+ Json::Value root(Json::objectValue);
+ if (ifile.is_open() && reader.parse(ifile, root, true)) {
+ json = root.toStyledString();
+ }
+ ifile.close();
+ ::policy::BinaryMessage msg(json.begin(), json.end());
+ // Load Json to cache
+ EXPECT_TRUE(manager->LoadPT("file_pt_update.json", msg));
+ return root;
+ }
+
+ void CreateLocalPT(const std::string& file_name) {
+ file_system::remove_directory_content("storage1");
+ ON_CALL(policy_settings_, app_storage_folder())
+ .WillByDefault(ReturnRef(kAppStorageFolder));
+ ASSERT_TRUE(manager->InitPT(file_name, &policy_settings_));
+ }
+
+ void AddRTtoPT(const std::string& update_file_name,
+ const std::string& section_name,
+ const uint32_t rt_number,
+ const uint32_t invalid_rt_number) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ // Get RequestTypes from section of preloaded_pt app_policies
+ PT_request_types = manager->GetAppRequestTypes(section_name);
+ EXPECT_EQ(rt_number, PT_request_types.size());
+ Json::Value root = GetPTU(update_file_name);
+ // Get Request Types from JSON (PTU)
+ PTU_request_types =
+ root["policy_table"]["app_policies"][section_name]["RequestType"];
+ PTU_request_types_size = PTU_request_types.size();
+ PT_request_types.clear();
+ // Get RequestTypes from section of PT app policies after update
+ PT_request_types = manager->GetAppRequestTypes(section_name);
+ // Check number of RT in PTU and PT now are equal
+ ASSERT_EQ(PTU_request_types_size - invalid_rt_number,
+ PT_request_types.size());
+ }
+
+ void AddRTtoAppSectionPT(const std::string& update_file_name,
+ const std::string& section_name,
+ const uint32_t rt_number,
+ const uint32_t invalid_rt_number) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ // Add app
+ manager->AddApplication(section_name);
+ // Check app gets RequestTypes from pre_DataConsent of app_policies
+ // section
+ PT_request_types = manager->GetAppRequestTypes(section_name);
+ EXPECT_EQ(rt_number, PT_request_types.size());
+ EXPECT_CALL(listener, OnPendingPermissionChange(section_name)).Times(1);
+ Json::Value root = GetPTU(update_file_name);
+
+ // Get App Request Types from PTU
+ PTU_request_types =
+ root["policy_table"]["app_policies"][section_name]["RequestType"];
+ PTU_request_types_size = PTU_request_types.size();
+
+ PT_request_types.clear();
+ // Get RequestTypes from <app_id> section of app policies after PT update
+ PT_request_types = manager->GetAppRequestTypes(section_name);
+ // Check sizes of Request types of PT and PTU
+ ASSERT_EQ(PTU_request_types_size - invalid_rt_number,
+ PT_request_types.size());
+
+ ::policy::AppPermissions permissions =
+ manager->GetAppPermissionsChanges(section_name);
+ EXPECT_TRUE(permissions.requestTypeChanged);
+ }
- // arrange
- std::vector<int> seconds;
- seconds.push_back(50);
- seconds.push_back(100);
- seconds.push_back(200);
+ std::vector<policy_table::RequestType> PushRequestTypesToContainer(
+ const std::vector<std::string>& temp_result) {
+ policy_table::RequestType filtered_result;
+ std::vector<policy_table::RequestType> final_result;
+ for (uint32_t i = 0; i < temp_result.size(); ++i) {
+ if (policy_table::EnumFromJsonString(temp_result[i], &filtered_result)) {
+ final_result.push_back(filtered_result);
+ }
+ }
+ return final_result;
+ }
- // assert
- EXPECT_CALL(*cache_manager, TimeoutResponse()).WillOnce(Return(60));
- EXPECT_CALL(*cache_manager, SecondsBetweenRetries(_))
- .WillOnce(DoAll(SetArgReferee<0>(seconds), Return(true)));
+ void CheckResultForValidRT() {
+ // Convert Json Array to std::vector<std::string>
+ const std::vector<std::string>& result =
+ JsonToVectorString(PTU_request_types);
+ // Checks
+ SortAndCheckEquality(PT_request_types, result);
+ }
- // act
- manager->RefreshRetrySequence();
+ void CheckResultForInvalidRT() {
+ // Convert Json Array to std::vector<std::string>
+ const std::vector<std::string>& temp_result =
+ JsonToVectorString(PTU_request_types);
+ std::vector<policy_table::RequestType> result1 =
+ PushRequestTypesToContainer(temp_result);
+ std::vector<policy_table::RequestType> result2 =
+ PushRequestTypesToContainer(PT_request_types);
+ // Checks
+ SortAndCheckEquality(result1, result2);
+ }
+ void FillMultimapFromFunctionalGroupings(
+ UserConsentPromptToRpcsConnections& input_multimap,
+ policy_table::FunctionalGroupings& fg_table) {
+ policy_table::FunctionalGroupings::iterator fg_itter = fg_table.begin();
+ const policy_table::FunctionalGroupings::iterator fg_itter_end =
+ fg_table.end();
+ for (; fg_itter != fg_itter_end; ++fg_itter) {
+ // RPCS getting
+ policy_table::Rpcs& rpcs_ref = fg_itter->second;
+ // User_consent_prompt getting
+ rpc::Optional<rpc::String<1, 255> >& optional_ref =
+ rpcs_ref.user_consent_prompt;
+ rpc::String<1, 255>& ucp_string = *optional_ref;
+ const std::string& ucp_std_string =
+ static_cast<const std::string&>(ucp_string);
+ // Multimap inserting
+ input_multimap.insert(std::pair<std::string, policy_table::Rpcs&>(
+ ucp_std_string, rpcs_ref));
+ }
+ }
- // assert
- EXPECT_EQ(50, manager->NextRetryTimeout());
- EXPECT_EQ(100, manager->NextRetryTimeout());
- EXPECT_EQ(200, manager->NextRetryTimeout());
- EXPECT_EQ(0, manager->NextRetryTimeout());
+ void GetFunctionalGroupingsFromManager(
+ policy_table::FunctionalGroupings& input_functional_groupings) {
+ // Get cache
+ ::policy::CacheManagerInterfaceSPtr cache = manager->GetCache();
+ // Get table_snapshot
+ utils::SharedPtr<policy_table::Table> table = cache->GenerateSnapshot();
+ // Set functional groupings from policy table
+ input_functional_groupings = table->policy_table.functional_groupings;
+ }
+
+ void TearDown() OVERRIDE {
+ delete manager;
+ }
+};
+
+Json::Value CreatePTforLoad() {
+ const std::string load_table(
+ "{"
+ "\"policy_table\": {"
+ "\"module_config\": {"
+ "\"preloaded_pt\": true,"
+ "\"exchange_after_x_ignition_cycles\": 10,"
+ "\"exchange_after_x_kilometers\": 100,"
+ "\"exchange_after_x_days\": 5,"
+ "\"timeout_after_x_seconds\": 500,"
+ "\"seconds_between_retries\": [10, 20, 30],"
+ "\"endpoints\": {"
+ "\"0x00\": {"
+ "\"default\": [\"http://ford.com/cloud/default\"]"
+ "}"
+ "},"
+ "\"notifications_per_minute_by_priority\": {"
+ "\"emergency\": 1,"
+ "\"navigation\": 2,"
+ "\"VOICECOMM\": 3,"
+ "\"communication\": 4,"
+ "\"normal\": 5,"
+ "\"none\": 6"
+ "},"
+ "\"vehicle_make\" : \"MakeT\","
+ "\"vehicle_model\" : \"ModelT\","
+ "\"vehicle_year\": \"2014\""
+ "},"
+ "\"app_policies\": {"
+ "\"default\": {"
+ "\"memory_kb\": 50,"
+ "\"heart_beat_timeout_ms\": 100,"
+ "\"groups\": [\"default\"],"
+ "\"keep_context\": true,"
+ "\"steal_focus\": true,"
+ "\"priority\": \"EMERGENCY\","
+ "\"default_hmi\": \"FULL\","
+ "\"certificate\": \"sign\""
+ "}, "
+ "\"pre_DataConsent\": {"
+ "\"memory_kb\": 50,"
+ "\"heart_beat_timeout_ms\": 100,"
+ "\"groups\": [\"default\"],"
+ "\"keep_context\": true,"
+ "\"steal_focus\": true,"
+ "\"priority\": \"EMERGENCY\","
+ "\"default_hmi\": \"FULL\","
+ "\"certificate\": \"sign\""
+ "}, "
+ "\"device\": {"
+ "\"memory_kb\": 50,"
+ "\"heart_beat_timeout_ms\": 100,"
+ "\"groups\": [\"default\"],"
+ "\"keep_context\": true,"
+ "\"steal_focus\": true,"
+ "\"priority\": \"EMERGENCY\","
+ "\"default_hmi\": \"FULL\","
+ "\"certificate\": \"sign\""
+ "},"
+ "\"1234\": {"
+ "\"memory_kb\": 50,"
+ "\"heart_beat_timeout_ms\": 100,"
+ "\"groups\": [\"default\"],"
+ "\"keep_context\": true,"
+ "\"steal_focus\": true,"
+ "\"priority\": \"EMERGENCY\","
+ "\"default_hmi\": \"FULL\","
+ "\"certificate\": \"sign\""
+ "}"
+ "},"
+ "\"consumer_friendly_messages\": {"
+ "\"version\": \"1.2\""
+ "},"
+ "\"functional_groupings\": {"
+ "\"default\": {"
+ "\"rpcs\": {"
+ "\"Update\": {"
+ "\"hmi_levels\": [\"FULL\"],"
+ "\"parameters\" : [\"speed\"]"
+ "}"
+ "}"
+ "}"
+ "}"
+ "}"
+ "}");
+ Json::Value table(Json::objectValue);
+ Json::Reader reader;
+ EXPECT_TRUE(reader.parse(load_table, table));
+ return table;
}
-TEST_F(PolicyManagerImplTest, DISABLED_GetUpdateUrl) {
+TEST_F(PolicyManagerImplTest, GetNotificationsNumber) {
+ const std::string priority = "EMERGENCY";
+ const uint32_t notif_number = 100u;
+ EXPECT_CALL(*cache_manager, GetNotificationsNumber(priority))
+ .WillOnce(Return(notif_number));
- EXPECT_CALL(*cache_manager, GetServiceUrls("7", _));
- EXPECT_CALL(*cache_manager, GetServiceUrls("4", _));
+ EXPECT_EQ(notif_number, manager->GetNotificationsNumber(priority));
+}
- EndpointUrls ep_7;
+TEST_F(PolicyManagerImplTest2, GetNotificationsNumberAfterPTUpdate) {
+ // Arrange
+ Json::Value table = CreatePTforLoad();
+ policy_table::Table update(&table);
+ update.SetPolicyTableType(rpc::policy_table_interface_base::PT_UPDATE);
+ // Act
+ const std::string json = table.toStyledString();
+ ::policy::BinaryMessage msg(json.begin(), json.end());
+ EXPECT_CALL(listener, OnUpdateStatusChanged(_));
+ EXPECT_TRUE(manager->LoadPT("file_pt_update.json", msg));
+
+ std::string priority = "emergency";
+ uint32_t notif_number = manager->GetNotificationsNumber(priority);
+ EXPECT_EQ(1u, notif_number);
+
+ priority = "navigation";
+ notif_number = manager->GetNotificationsNumber(priority);
+ EXPECT_EQ(2u, notif_number);
+
+ priority = "emergency";
+ notif_number = manager->GetNotificationsNumber(priority);
+ EXPECT_EQ(1u, notif_number);
+
+ priority = "VOICECOMM";
+ notif_number = manager->GetNotificationsNumber(priority);
+ EXPECT_EQ(3u, notif_number);
- manager->GetServiceUrls("7", ep_7);
- EXPECT_EQ("http://policies.telematics.ford.com/api/policies", ep_7[0].url[0]);
+ priority = "normal";
+ notif_number = manager->GetNotificationsNumber(priority);
+ EXPECT_EQ(5u, notif_number);
- EndpointUrls ep_4;
- manager->GetServiceUrls("4", ep_4);
- EXPECT_EQ("http://policies.ford.com/api/policies", ep_4[0].url[0]);
+ priority = "none";
+ notif_number = manager->GetNotificationsNumber(priority);
+ EXPECT_EQ(6u, notif_number);
}
-TEST_F(PolicyManagerImplTest, ResetPT) {
- EXPECT_CALL(*cache_manager, ResetPT("filename"))
- .WillOnce(Return(true))
- .WillOnce(Return(false));
- EXPECT_CALL(*cache_manager, TimeoutResponse());
- EXPECT_CALL(*cache_manager, SecondsBetweenRetries(_));
+TEST_F(PolicyManagerImplTest2, IsAppRevoked_SetRevokedAppID_ExpectAppRevoked) {
+ // Arrange
+ std::ifstream ifile("sdl_preloaded_pt.json");
+ Json::Reader reader;
+ std::string json;
+ Json::Value root(Json::objectValue);
+ if (ifile.is_open() && reader.parse(ifile, root, true)) {
+ root["policy_table"]["app_policies"][app_id1] = Json::nullValue;
+ json = root.toStyledString();
+ }
+ ifile.close();
- EXPECT_TRUE(manager->ResetPT("filename"));
- EXPECT_FALSE(manager->ResetPT("filename"));
+ ::policy::BinaryMessage msg(json.begin(), json.end());
+ ASSERT_TRUE(manager->LoadPT("file_pt_update.json", msg));
+ EXPECT_TRUE(manager->IsApplicationRevoked(app_id1));
}
-TEST_F(PolicyManagerImplTest,
- CheckPermissions_SetHmiLevelFullForAlert_ExpectAllowedPermissions) {
+TEST_F(PolicyManagerImplTest2,
+ CheckPermissions_SetRevokedAppID_ExpectRPCDisallowed) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ (manager->GetCache())->AddDevice(dev_id1, "Bluetooth");
+ (manager->GetCache())
+ ->SetDeviceData(dev_id1,
+ "hardware IPX",
+ "v.8.0.1",
+ "Android",
+ "4.4.2",
+ "Life",
+ 2,
+ "Bluetooth");
+ EXPECT_CALL(listener, OnCurrentDeviceIdUpdateRequired(app_id1))
+ .WillRepeatedly(Return(dev_id1));
+ manager->SetUserConsentForDevice(dev_id1, true);
+ // Add app from consented device. App will be assigned with default policies
+ manager->AddApplication(app_id1);
+ // Check before action
+ policy_table::RpcParameters rpc_parameters;
+ rpc_parameters.hmi_levels.push_back(policy_table::HL_FULL);
+
+ policy_table::Rpc rpc;
+ rpc["Alert"] = rpc_parameters;
+
+ ::policy::RPCParams input_params;
+ ::policy::CheckPermissionResult output;
+
+ manager->CheckPermissions(
+ app_id1, std::string("FULL"), "Alert", input_params, output);
- // arrange
- ::policy::CheckPermissionResult expected;
- expected.hmi_level_permitted = ::policy::kRpcAllowed;
- expected.list_of_allowed_params.push_back("speed");
- expected.list_of_allowed_params.push_back("gps");
+ // Check RPC is allowed
+ EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted);
+ ASSERT_TRUE(output.list_of_allowed_params.empty());
+ // Act
+ std::ifstream ifile("sdl_preloaded_pt.json");
+ Json::Reader reader;
+ std::string json;
+ Json::Value root(Json::objectValue);
+ if (ifile.is_open() && reader.parse(ifile, root, true)) {
+ root["policy_table"]["app_policies"][app_id1] = Json::nullValue;
+ json = root.toStyledString();
+ }
+ ifile.close();
+
+ ::policy::BinaryMessage msg(json.begin(), json.end());
+ ASSERT_TRUE(manager->LoadPT("file_pt_update.json", msg));
+
+ manager->CheckPermissions(
+ app_id1, std::string("FULL"), "Alert", input_params, output);
+ // Check RPC is disallowed
+ EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted);
+ ASSERT_TRUE(output.list_of_allowed_params.empty());
+}
- // assert
- EXPECT_CALL(*cache_manager, CheckPermissions("12345678", "FULL", "Alert", _))
- .WillOnce(SetArgReferee<3>(expected));
+TEST_F(PolicyManagerImplTest2,
+ CheckPermissions_SetAppIDwithPolicies_ExpectRPCAllowed) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ manager->AddDevice(dev_id1, "Bluetooth");
- // act
+ ASSERT_TRUE((manager->GetCache())
+ ->SetDeviceData(dev_id1,
+ "hardware IPX",
+ "v.8.0.1",
+ "Android",
+ "4.4.2",
+ "Life",
+ 2,
+ "Bluetooth"));
+ EXPECT_CALL(listener, OnCurrentDeviceIdUpdateRequired("1234"))
+ .WillRepeatedly(Return(dev_id1));
+ manager->SetUserConsentForDevice(dev_id1, true);
+ // Add app from consented device. App will be assigned with default policies
+ manager->AddApplication("1234");
+ // Emulate PTU with new policies for app added above
+ std::ifstream ifile("sdl_preloaded_pt.json");
+ Json::Reader reader;
+ std::string json;
+ Json::Value root(Json::objectValue);
+ if (ifile.is_open() && reader.parse(ifile, root, true)) {
+ // Add AppID with policies
+ root["policy_table"]["app_policies"]["1234"] =
+ Json::Value(Json::objectValue);
+ root["policy_table"]["app_policies"]["1234"]["memory_kb"] = Json::Value(50);
+ root["policy_table"]["app_policies"]["1234"]["heart_beat_timeout_ms"] =
+ Json::Value(100);
+ root["policy_table"]["app_policies"]["1234"]["AppHMIType"] =
+ Json::Value(Json::arrayValue);
+ root["policy_table"]["app_policies"]["1234"]["AppHMIType"][0] =
+ Json::Value("MEDIA");
+ root["policy_table"]["app_policies"]["1234"]["groups"] =
+ Json::Value(Json::arrayValue);
+ root["policy_table"]["app_policies"]["1234"]["groups"][0] =
+ Json::Value("Base-4");
+ root["policy_table"]["app_policies"]["1234"]["priority"] =
+ Json::Value("EMERGENCY");
+ root["policy_table"]["app_policies"]["1234"]["default_hmi"] =
+ Json::Value("FULL");
+ root["policy_table"]["app_policies"]["1234"]["keep_context"] =
+ Json::Value(true);
+ root["policy_table"]["app_policies"]["1234"]["steal_focus"] =
+ Json::Value(true);
+ root["policy_table"]["app_policies"]["1234"]["certificate"] =
+ Json::Value("sign");
+ json = root.toStyledString();
+ }
+ ifile.close();
+
+ ::policy::BinaryMessage msg(json.begin(), json.end());
+ // Load Json to cache
+ EXPECT_TRUE(manager->LoadPT("file_pt_update.json", msg));
+
+ policy_table::RpcParameters rpc_parameters;
+ rpc_parameters.hmi_levels.push_back(policy_table::HL_FULL);
+
+ policy_table::Rpc rpc;
+ rpc["Alert"] = rpc_parameters;
::policy::RPCParams input_params;
::policy::CheckPermissionResult output;
- manager->CheckPermissions("12345678", "FULL", "Alert", input_params, output);
- // assert
+ (manager->GetCache())->AddDevice(dev_id1, "Bluetooth");
+ (manager->GetCache())
+ ->SetDeviceData(dev_id1,
+ "hardware IPX",
+ "v.8.0.1",
+ "Android",
+ "4.4.2",
+ "Life",
+ 2,
+ "Bluetooth");
+ manager->CheckPermissions(
+ std::string("1234"), std::string("FULL"), "Alert", input_params, output);
+ // Check RPC is allowed
EXPECT_EQ(::policy::kRpcAllowed, output.hmi_level_permitted);
+ // Check list of parameters empty
+ ASSERT_TRUE(output.list_of_allowed_params.empty());
+}
- ASSERT_TRUE(!output.list_of_allowed_params.empty());
- ASSERT_EQ(2u, output.list_of_allowed_params.size());
- EXPECT_EQ("speed", output.list_of_allowed_params[0]);
- EXPECT_EQ("gps", output.list_of_allowed_params[1]);
+TEST_F(PolicyManagerImplTest, IncrementGlobalCounter) {
+ // Assert
+ EXPECT_CALL(*cache_manager, Increment(usage_statistics::SYNC_REBOOTS));
+ manager->Increment(usage_statistics::SYNC_REBOOTS);
}
-TEST_F(PolicyManagerImplTest, LoadPT_SetPT_PTIsLoaded) {
+TEST_F(PolicyManagerImplTest, IncrementAppCounter) {
+ // Assert
+ EXPECT_CALL(*cache_manager,
+ Increment("12345", usage_statistics::USER_SELECTIONS));
+ manager->Increment("12345", usage_statistics::USER_SELECTIONS);
+}
- // arrange
- Json::Value table(Json::objectValue);
- table["policy_table"] = Json::Value(Json::objectValue);
-
- Json::Value &policy_table = table["policy_table"];
- policy_table["module_config"] = Json::Value(Json::objectValue);
- policy_table["functional_groupings"] = Json::Value(Json::objectValue);
- policy_table["consumer_friendly_messages"] = Json::Value(Json::objectValue);
- policy_table["app_policies"] = Json::Value(Json::objectValue);
-
- Json::Value &module_config = policy_table["module_config"];
- module_config["preloaded_pt"] = Json::Value(true);
- module_config["exchange_after_x_ignition_cycles"] = Json::Value(10);
- module_config["exchange_after_x_kilometers"] = Json::Value(100);
- module_config["exchange_after_x_days"] = Json::Value(5);
- module_config["timeout_after_x_seconds"] = Json::Value(500);
- module_config["seconds_between_retries"] = Json::Value(Json::arrayValue);
- module_config["seconds_between_retries"][0] = Json::Value(10);
- module_config["seconds_between_retries"][1] = Json::Value(20);
- module_config["seconds_between_retries"][2] = Json::Value(30);
- module_config["endpoints"] = Json::Value(Json::objectValue);
- module_config["endpoints"]["0x00"] = Json::Value(Json::objectValue);
- module_config["endpoints"]["0x00"]["default"] = Json::Value(Json::arrayValue);
- module_config["endpoints"]["0x00"]["default"][0] =
- Json::Value("http://ford.com/cloud/default");
- module_config["notifications_per_minute_by_priority"] =
- Json::Value(Json::objectValue);
- module_config["notifications_per_minute_by_priority"]["emergency"] =
- Json::Value(1);
- module_config["notifications_per_minute_by_priority"]["navigation"] =
- Json::Value(2);
- module_config["notifications_per_minute_by_priority"]["VOICECOMM"] =
- Json::Value(3);
- module_config["notifications_per_minute_by_priority"]["communication"] =
- Json::Value(4);
- module_config["notifications_per_minute_by_priority"]["normal"] =
- Json::Value(5);
- module_config["notifications_per_minute_by_priority"]["none"] =
- Json::Value(6);
- module_config["vehicle_make"] = Json::Value("MakeT");
- module_config["vehicle_model"] = Json::Value("ModelT");
- module_config["vehicle_year"] = Json::Value("2014");
-
- Json::Value &functional_groupings = policy_table["functional_groupings"];
- functional_groupings["default"] = Json::Value(Json::objectValue);
- Json::Value &default_group = functional_groupings["default"];
- default_group["rpcs"] = Json::Value(Json::objectValue);
- default_group["rpcs"]["Update"] = Json::Value(Json::objectValue);
- default_group["rpcs"]["Update"]["hmi_levels"] = Json::Value(Json::arrayValue);
- default_group["rpcs"]["Update"]["hmi_levels"][0] = Json::Value("FULL");
- default_group["rpcs"]["Update"]["parameters"] = Json::Value(Json::arrayValue);
- default_group["rpcs"]["Update"]["parameters"][0] = Json::Value("speed");
-
- Json::Value &consumer_friendly_messages =
- policy_table["consumer_friendly_messages"];
- consumer_friendly_messages["version"] = Json::Value("1.2");
-
- Json::Value &app_policies = policy_table["app_policies"];
- app_policies["default"] = Json::Value(Json::objectValue);
- app_policies["default"]["memory_kb"] = Json::Value(50);
- app_policies["default"]["heart_beat_timeout_ms"] = Json::Value(100);
- app_policies["default"]["groups"] = Json::Value(Json::arrayValue);
- app_policies["default"]["groups"][0] = Json::Value("default");
- app_policies["default"]["priority"] = Json::Value("EMERGENCY");
- app_policies["default"]["default_hmi"] = Json::Value("FULL");
- app_policies["default"]["keep_context"] = Json::Value(true);
- app_policies["default"]["steal_focus"] = Json::Value(true);
- app_policies["default"]["certificate"] = Json::Value("sign");
- app_policies["1234"] = Json::Value(Json::objectValue);
- app_policies["1234"]["memory_kb"] = Json::Value(50);
- app_policies["1234"]["heart_beat_timeout_ms"] = Json::Value(100);
- app_policies["1234"]["groups"] = Json::Value(Json::arrayValue);
- app_policies["1234"]["groups"][0] = Json::Value("default");
- app_policies["1234"]["priority"] = Json::Value("EMERGENCY");
- app_policies["1234"]["default_hmi"] = Json::Value("FULL");
- app_policies["1234"]["keep_context"] = Json::Value(true);
- app_policies["1234"]["steal_focus"] = Json::Value(true);
- app_policies["1234"]["certificate"] = Json::Value("sign");
+TEST_F(PolicyManagerImplTest, SetAppInfo) {
+ // Assert
+ EXPECT_CALL(*cache_manager,
+ Set("12345", usage_statistics::LANGUAGE_GUI, "de-de"));
+ manager->Set("12345", usage_statistics::LANGUAGE_GUI, "de-de");
+}
+TEST_F(PolicyManagerImplTest, AddAppStopwatch) {
+ // Assert
+ EXPECT_CALL(*cache_manager,
+ Add("12345", usage_statistics::SECONDS_HMI_FULL, 30));
+ manager->Add("12345", usage_statistics::SECONDS_HMI_FULL, 30);
+}
+
+TEST_F(PolicyManagerImplTest, ResetPT) {
+ EXPECT_CALL(*cache_manager, ResetPT("filename"))
+ .WillOnce(Return(true))
+ .WillOnce(Return(false));
+ EXPECT_CALL(*cache_manager, ResetCalculatedPermissions()).Times(AtLeast(1));
+ EXPECT_CALL(*cache_manager, TimeoutResponse());
+ EXPECT_CALL(*cache_manager, SecondsBetweenRetries(_));
+
+ EXPECT_TRUE(manager->ResetPT("filename"));
+ EXPECT_FALSE(manager->ResetPT("filename"));
+}
+
+TEST_F(PolicyManagerImplTest, LoadPT_SetPT_PTIsLoaded) {
+ // Arrange
+ Json::Value table = CreatePTforLoad();
policy_table::Table update(&table);
update.SetPolicyTableType(rpc::policy_table_interface_base::PT_UPDATE);
- // assert
+ // Assert
ASSERT_TRUE(IsValid(update));
- // act
- std::string json = table.toStyledString();
+ EXPECT_CALL(*cache_manager, GetHMIAppTypeAfterUpdate(_)).Times(AtLeast(1));
+
+ // Act
+ const std::string json = table.toStyledString();
::policy::BinaryMessage msg(json.begin(), json.end());
utils::SharedPtr<policy_table::Table> snapshot =
- new policy_table::Table(update.policy_table);
-
- // assert
+ utils::MakeShared<policy_table::Table>(update.policy_table);
+ // Assert
EXPECT_CALL(*cache_manager, GenerateSnapshot()).WillOnce(Return(snapshot));
EXPECT_CALL(*cache_manager, ApplyUpdate(_)).WillOnce(Return(true));
- EXPECT_CALL(*listener, GetAppName("1234")).WillOnce(Return(""));
- EXPECT_CALL(*listener, OnUpdateStatusChanged(_));
+ EXPECT_CALL(listener, GetAppName("1234"))
+ .WillOnce(Return(custom_str::CustomString("")));
+ EXPECT_CALL(listener, OnUpdateStatusChanged(_));
EXPECT_CALL(*cache_manager, SaveUpdateRequired(false));
EXPECT_CALL(*cache_manager, TimeoutResponse());
EXPECT_CALL(*cache_manager, SecondsBetweenRetries(_));
- TEST_F(PolicyManagerImplTest2, NextRetryTimeout_ExpectTimeoutsFromPT) {
- // Arrange
- std::ifstream ifile("sdl_preloaded_pt.json");
- Json::Reader reader;
- Json::Value root(Json::objectValue);
- if (ifile.is_open() && reader.parse(ifile, root, true)) {
- Json::Value seconds_between_retries = Json::Value(Json::arrayValue);
- seconds_between_retries =
- root["policy_table"]["module_config"]["seconds_between_retries"];
- uint32_t size = seconds_between_retries.size();
- CreateLocalPT("sdl_preloaded_pt.json");
+ EXPECT_TRUE(manager->LoadPT("file_pt_update.json", msg));
+}
- uint32_t waiting_timeout = 0u;
+TEST_F(PolicyManagerImplTest, LoadPT_SetInvalidUpdatePT_PTIsNotLoaded) {
+ // Arrange
+ Json::Value table(Json::objectValue);
- for (uint32_t retry_number = 0u; retry_number < size; ++retry_number) {
- waiting_timeout += seconds_between_retries[retry_number].asInt();
- waiting_timeout += manager->TimeoutExchange();
+ policy_table::Table update(&table);
+ update.SetPolicyTableType(rpc::policy_table_interface_base::PT_UPDATE);
- // it's in miliseconds
- EXPECT_EQ(waiting_timeout * date_time::DateTime::MILLISECONDS_IN_SECOND,
- manager->NextRetryTimeout());
- }
+ // Assert update is invalid
+ ASSERT_FALSE(IsValid(update));
+
+ // Act
+ std::string json = table.toStyledString();
+ ::policy::BinaryMessage msg(json.begin(), json.end());
+
+ // Assert
+ EXPECT_CALL(*cache_manager, GenerateSnapshot()).Times(0);
+ EXPECT_CALL(*cache_manager, ApplyUpdate(_)).Times(0);
+ EXPECT_CALL(listener, GetAppName(_)).Times(0);
+ EXPECT_CALL(listener, OnUpdateStatusChanged(_)).Times(1);
+ EXPECT_CALL(*cache_manager, SaveUpdateRequired(false)).Times(0);
+ EXPECT_CALL(*cache_manager, TimeoutResponse()).Times(0);
+ EXPECT_CALL(*cache_manager, SecondsBetweenRetries(_)).Times(0);
+ EXPECT_FALSE(manager->LoadPT("file_pt_update.json", msg));
+}
+
+TEST_F(PolicyManagerImplTest2,
+ KmsChanged_SetExceededKms_ExpectCorrectSchedule) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ ::policy::Counters counter = ::policy::Counters::KILOMETERS;
+ manager->PTUpdatedAt(counter, 50000);
+ EXPECT_EQ("UP_TO_DATE", manager->GetPolicyTableStatus());
+ // Set kms changed but not exceed limit
+ manager->KmsChanged(51500);
+ EXPECT_EQ("UP_TO_DATE", manager->GetPolicyTableStatus());
+ // Set kms changed and exceed limit
+ manager->KmsChanged(52500);
+ EXPECT_EQ("UPDATE_NEEDED", manager->GetPolicyTableStatus());
+}
+
+TEST_F(
+ PolicyManagerImplTest2,
+ AddApplication_AddNewApplicationFromDeviceWithoutConsent_ExpectUpdateRequired) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ manager->AddApplication(app_id1);
+ EXPECT_EQ("UPDATE_NEEDED", manager->GetPolicyTableStatus());
+}
+
+TEST_F(
+ PolicyManagerImplTest2,
+ ReactOnUserDevConsentForApp_AddNewApplicationFromDeviceWithConsent_ExpectDefault) {
+ // Arrange
+ // RequestTypes for default & preDataConsent are different
+ CreateLocalPT("ptu_requestType.json");
+ manager->AddApplication(app_id1);
+ EXPECT_FALSE(manager->IsPredataPolicy(app_id1));
+ manager->ReactOnUserDevConsentForApp(app_id1, true);
+ EXPECT_FALSE(manager->IsPredataPolicy(app_id1));
+ EXPECT_TRUE((manager->GetCache())->IsDefaultPolicy(app_id1));
+}
+
+TEST_F(
+ PolicyManagerImplTest2,
+ ReactOnUserDevConsentForApp_AddNewApplicationFromDeviceWithConsent_ExpectPreDataConsent) {
+ // Arrange
+ // RequestTypes for default & preDataConsent are the same
+ CreateLocalPT("ptu2_requestType.json");
+ manager->AddApplication(app_id1);
+ EXPECT_FALSE(manager->IsPredataPolicy(app_id1));
+ EXPECT_CALL(listener, OnPendingPermissionChange(app_id1)).Times(0);
+ manager->ReactOnUserDevConsentForApp(app_id1, true);
+ EXPECT_FALSE(manager->IsPredataPolicy(app_id1));
+ EXPECT_TRUE((manager->GetCache())->IsDefaultPolicy(app_id1));
+}
+
+TEST_F(
+ PolicyManagerImplTest2,
+ AddApplication_AddExistingApplicationFromDeviceWithoutConsent_ExpectNoUpdateRequired) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ EXPECT_EQ("UP_TO_DATE", manager->GetPolicyTableStatus());
+ GetPTU("valid_sdl_pt_update.json");
+ EXPECT_EQ("UP_TO_DATE", manager->GetPolicyTableStatus());
+ // Try to add existing app
+ manager->AddApplication(app_id2);
+ // Check no update required
+ EXPECT_EQ("UP_TO_DATE", manager->GetPolicyTableStatus());
+}
+
+TEST_F(PolicyManagerImplTest2,
+ PTUpdatedAt_DaysNotExceedLimit_ExpectNoUpdateRequired) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ TimevalStruct current_time = date_time::DateTime::getCurrentTime();
+ const int kSecondsInDay = 60 * 60 * 24;
+ int days = current_time.tv_sec / kSecondsInDay;
+ EXPECT_EQ("UP_TO_DATE", manager->GetPolicyTableStatus());
+
+ GetPTU("valid_sdl_pt_update.json");
+ EXPECT_EQ("UP_TO_DATE", manager->GetPolicyTableStatus());
+
+ manager->AddApplication(app_id2);
+ EXPECT_EQ("UP_TO_DATE", manager->GetPolicyTableStatus());
+ ::policy::Counters counter = ::policy::Counters::DAYS_AFTER_EPOCH;
+ // Set PT was updated 10 days ago (limit is 30 days for now)
+ // So no limit exceeded
+ manager->PTUpdatedAt(counter, days - 10);
+ manager->OnAppRegisteredOnMobile(app_id2);
+ EXPECT_EQ("UP_TO_DATE", manager->GetPolicyTableStatus());
+}
+
+TEST_F(PolicyManagerImplTest2, ForcePTExchange_ExpectUpdateNeeded) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ EXPECT_EQ("UP_TO_DATE", manager->GetPolicyTableStatus());
+ // Force OT Exchange
+ manager->ForcePTExchange();
+ // Check update required
+ EXPECT_EQ("UPDATE_NEEDED", manager->GetPolicyTableStatus());
+}
+
+TEST_F(PolicyManagerImplTest2, OnSystemReady) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ // Check
+ EXPECT_CALL(listener, OnSystemInfoUpdateRequired());
+ manager->OnSystemReady();
+}
+
+TEST_F(PolicyManagerImplTest2, ResetRetrySequence) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ manager->ResetRetrySequence();
+ EXPECT_EQ("UPDATE_NEEDED", manager->GetPolicyTableStatus());
+ manager->OnUpdateStarted();
+ EXPECT_EQ("UPDATING", manager->GetPolicyTableStatus());
+}
+
+TEST_F(PolicyManagerImplTest2, NextRetryTimeout_ExpectTimeoutsFromPT) {
+ // Arrange
+ std::ifstream ifile("sdl_preloaded_pt.json");
+ Json::Reader reader;
+ Json::Value root(Json::objectValue);
+ if (ifile.is_open() && reader.parse(ifile, root, true)) {
+ Json::Value seconds_between_retries = Json::Value(Json::arrayValue);
+ seconds_between_retries =
+ root["policy_table"]["module_config"]["seconds_between_retries"];
+ uint32_t size = seconds_between_retries.size();
+ CreateLocalPT("sdl_preloaded_pt.json");
+
+ uint32_t waiting_timeout = 0u;
+
+ for (uint32_t retry_number = 0u; retry_number < size; ++retry_number) {
+ waiting_timeout += seconds_between_retries[retry_number].asInt();
+ waiting_timeout += manager->TimeoutExchange();
+
+ // it's in miliseconds
+ EXPECT_EQ(waiting_timeout * date_time::DateTime::MILLISECONDS_IN_SECOND,
+ manager->NextRetryTimeout());
}
}
+}
- TEST_F(PolicyManagerImplTest,
- RequestPTUpdate_SetPT_GeneratedSnapshotAndPTUpdate) {
+TEST_F(PolicyManagerImplTest2, TimeOutExchange) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ // Check value taken from PT
+ EXPECT_EQ(70, manager->TimeoutExchange());
+}
- // arrange
- ::utils::SharedPtr<::policy_table::Table> p_table =
- new ::policy_table::Table();
+TEST_F(PolicyManagerImplTest2, UpdatedPreloadedPT_ExpectLPT_IsUpdated) {
+ // Arrange necessary pre-conditions
+ StringsForUpdate new_data;
+ new_data.new_field_name_ = "Notifications-";
+ CreateNewRandomData(new_data);
+ // Create Initial LocalPT from preloadedPT
+ CreateLocalPT("sdl_preloaded_pt.json");
+ // Update preloadedPT
+ std::ifstream ifile("sdl_preloaded_pt.json");
+ Json::Reader reader;
+ Json::Value root(Json::objectValue);
- // assert
- EXPECT_CALL(*cache_manager, GenerateSnapshot()).WillOnce(Return(p_table));
+ if (ifile.is_open() && reader.parse(ifile, root, true)) {
+ root["policy_table"]["module_config"]["preloaded_date"] =
+ new_data.new_date_;
+ Json::Value val(Json::objectValue);
+ Json::Value val2(Json::arrayValue);
+ val2[0] = hmi_level[index];
+ val[new_data.new_field_value_]["hmi_levels"] = val2;
+ root["policy_table"]["functional_groupings"][new_data
+ .new_field_name_]["rpcs"] =
+ val;
+ root["policy_table"]["functional_groupings"][new_data.new_field_name_]
+ ["user_consent_prompt"] = new_data.new_field_name_;
+ }
+ ifile.close();
- // act
- manager->RequestPTUpdate();
+ Json::StyledStreamWriter writer;
+ std::ofstream ofile("sdl_preloaded_pt.json");
+ writer.write(ofile, root);
+ ofile.flush();
+ ofile.close();
+
+ // Make PolicyManager to update LocalPT
+ EXPECT_TRUE(manager->InitPT("sdl_preloaded_pt.json", &policy_settings_));
+
+ // Arrange
+ ::policy::CacheManagerInterfaceSPtr cache = manager->GetCache();
+ utils::SharedPtr<policy_table::Table> table = cache->GenerateSnapshot();
+ // Get FunctionalGroupings
+ policy_table::FunctionalGroupings& fc =
+ table->policy_table.functional_groupings;
+ // Get RPCs for new added field in functional_group
+ policy_table::Rpcs& rpcs = fc[new_data.new_field_name_];
+ // Get user consent prompt
+ const std::string& ucp = *(rpcs.user_consent_prompt);
+ // Get Rpcs
+ policy_table::Rpc& rpc = rpcs.rpcs;
+ // Get RPC's parameters
+ policy_table::RpcParameters& rpc_param = rpc[new_data.new_field_value_];
+
+ // Check preloaded date
+ EXPECT_EQ(static_cast<std::string>(
+ *(table->policy_table.module_config.preloaded_date)),
+ new_data.new_date_);
+ // Check if new field exists in Local PT
+ EXPECT_TRUE(fc.find(new_data.new_field_name_) != fc.end());
+ // Check if user_consent_propmp is correct
+ EXPECT_EQ(new_data.new_field_name_, ucp);
+ // Check if new RPC exists
+ EXPECT_TRUE(rpc.find(new_data.new_field_value_) != rpc.end());
+ // Check HMI level of new RPC
+ EXPECT_EQ(index, static_cast<uint32_t>(rpc_param.hmi_levels[0]));
+ // Check if new field matches field added to preloaded PT
+ EXPECT_EQ(std::string((*(fc.find(new_data.new_field_name_))).first),
+ new_data.new_field_name_);
+}
+
+TEST_F(PolicyManagerImplTest2, GetPolicyTableStatus_ExpectUpToDate) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ // Check
+ EXPECT_EQ("UP_TO_DATE", manager->GetPolicyTableStatus());
+}
+
+TEST_F(PolicyManagerImplTest2,
+ RetrySequenceDelaysSeconds_Expect_CorrectValues) {
+ // Arrange
+ std::ifstream ifile("sdl_preloaded_pt.json");
+ Json::Reader reader;
+ Json::Value root(Json::objectValue);
+ if (ifile.is_open() && reader.parse(ifile, root, true)) {
+ Json::Value seconds_between_retries = Json::Value(Json::arrayValue);
+ seconds_between_retries =
+ root["policy_table"]["module_config"]["seconds_between_retries"];
+ uint32_t size = seconds_between_retries.size();
+ CreateLocalPT("sdl_preloaded_pt.json");
+ std::vector<int> delaySecs = manager->RetrySequenceDelaysSeconds();
+ // Check
+ ASSERT_EQ(size, delaySecs.size());
+ for (uint32_t i = 0; i < size; ++i) {
+ EXPECT_EQ(seconds_between_retries[i], delaySecs[i]);
+ }
}
+}
+
+TEST_F(PolicyManagerImplTest2,
+ OnExceededTimeout_GetPolicyTableStatus_ExpectUpdateNeeded) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ manager->OnExceededTimeout();
+ // Check
+ EXPECT_EQ("UPDATE_NEEDED", manager->GetPolicyTableStatus());
+}
+
+TEST_F(PolicyManagerImplTest2,
+ GetUserConsentForDevice_SetDeviceAllowed_ExpectReceivedConsentCorrect) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ ASSERT_TRUE((manager->GetCache())->AddDevice(dev_id2, "Bluetooth"));
+
+ ASSERT_TRUE((manager->GetCache())
+ ->SetDeviceData(dev_id2,
+ "hardware IPX",
+ "v.8.0.1",
+ "Android",
+ "4.4.2",
+ "Life",
+ 2,
+ "Bluetooth"));
+
+ manager->SetUserConsentForDevice(dev_id2, true);
+ ::policy::DeviceConsent consent = manager->GetUserConsentForDevice(dev_id2);
+ // Check
+ EXPECT_EQ(::policy::DeviceConsent::kDeviceAllowed, consent);
+}
- TEST_F(PolicyManagerImplTest, DISABLED_AddApplication) {
- // TODO(AOleynik): Implementation of method should be changed to avoid
- // using of snapshot
- // manager->AddApplication("12345678");
+TEST_F(PolicyManagerImplTest2,
+ GetDefaultHmi_SetDeviceAllowed_ExpectReceivedHmiCorrect) {
+ // Arrange
+ CreateLocalPT("ptu2_requestType.json");
+ manager->AddApplication(app_id2);
+ // Check if app has preData policy
+ EXPECT_FALSE(manager->IsPredataPolicy(app_id2));
+ std::string default_hmi1;
+ manager->GetDefaultHmi(app_id2, &default_hmi1);
+ EXPECT_EQ("", default_hmi1);
+ ASSERT_TRUE((manager->GetCache())->AddDevice(dev_id2, "Bluetooth"));
+ ASSERT_TRUE((manager->GetCache())
+ ->SetDeviceData(dev_id2,
+ "hardware IPX",
+ "v.8.0.1",
+ "Android",
+ "4.4.2",
+ "Life",
+ 2,
+ "Bluetooth"));
+ manager->SetUserConsentForDevice(dev_id2, true);
+ ::policy::DeviceConsent consent = manager->GetUserConsentForDevice(dev_id2);
+ // Check
+ EXPECT_EQ(::policy::DeviceConsent::kDeviceAllowed, consent);
+ EXPECT_CALL(listener, OnCurrentDeviceIdUpdateRequired(app_id2))
+ .WillRepeatedly(Return(dev_id2));
+ manager->AddApplication(app_id2);
+ EXPECT_TRUE((manager->GetCache())->IsDefaultPolicy(app_id2));
+ std::string default_hmi2;
+ manager->GetDefaultHmi(app_id2, &default_hmi2);
+ EXPECT_EQ("", default_hmi2);
+}
+
+TEST_F(PolicyManagerImplTest2,
+ GetDefaultPriority_SetDeviceAllowed_ExpectReceivedPriorityCorrect) {
+ // Arrange
+ CreateLocalPT("ptu2_requestType.json");
+ manager->AddApplication(app_id2);
+ // Check if app has preData policy
+ EXPECT_FALSE(manager->IsPredataPolicy(app_id2));
+ std::string priority1;
+ EXPECT_TRUE(manager->GetPriority(app_id2, &priority1));
+ EXPECT_EQ("EMERGENCY", priority1);
+ ASSERT_TRUE((manager->GetCache())->AddDevice(dev_id2, "Bluetooth"));
+ ASSERT_TRUE((manager->GetCache())
+ ->SetDeviceData(dev_id2,
+ "hardware IPX",
+ "v.8.0.1",
+ "Android",
+ "4.4.2",
+ "Life",
+ 2,
+ "Bluetooth"));
+ manager->SetUserConsentForDevice(dev_id2, true);
+ ::policy::DeviceConsent consent = manager->GetUserConsentForDevice(dev_id2);
+ // Check
+ EXPECT_EQ(::policy::DeviceConsent::kDeviceAllowed, consent);
+ EXPECT_CALL(listener, OnCurrentDeviceIdUpdateRequired(app_id2))
+ .WillRepeatedly(Return(dev_id2));
+ manager->AddApplication(app_id2);
+ EXPECT_TRUE((manager->GetCache())->IsDefaultPolicy(app_id2));
+ std::string priority2;
+ EXPECT_TRUE(manager->GetPriority(app_id2, &priority2));
+ EXPECT_EQ("EMERGENCY", priority2);
+}
+
+TEST_F(PolicyManagerImplTest2, GetInitialAppData_ExpectReceivedConsentCorrect) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ manager->AddApplication(app_id2);
+ ::policy::StringArray app_nicknames;
+ ::policy::StringArray app_hmi_types;
+ manager->GetInitialAppData(app_id2, &app_nicknames, &app_hmi_types);
+ // Expect Empty nicknames and AppHMITypes
+ EXPECT_EQ(0u, app_nicknames.size());
+ EXPECT_EQ(0u, app_hmi_types.size());
+
+ Json::Value root = GetPTU("valid_sdl_pt_update.json");
+
+ Json::Value appHmiTypes = Json::Value(Json::arrayValue);
+ appHmiTypes = root["policy_table"]["app_policies"][app_id2]["AppHMIType"];
+ uint32_t appHmiType_size = appHmiTypes.size();
+
+ Json::Value appNicknames = Json::Value(Json::arrayValue);
+ appNicknames = root["policy_table"]["app_policies"][app_id2]["nicknames"];
+ uint32_t appNicknames_size = appNicknames.size();
+
+ ::policy::StringArray app_nicknames1;
+ ::policy::StringArray app_hmi_types1;
+ manager->GetInitialAppData(app_id2, &app_nicknames1, &app_hmi_types1);
+ uint32_t nick_names_size = app_nicknames1.size();
+ uint32_t app_hmi_types_size = app_hmi_types1.size();
+ ASSERT_EQ(appHmiType_size, app_hmi_types_size);
+ ASSERT_EQ(appNicknames_size, nick_names_size);
+ ASSERT_GT(nick_names_size, 0u);
+ ASSERT_GT(app_hmi_types_size, 0u);
+ // Check nicknames match
+ for (uint32_t i = 0; i < nick_names_size; ++i) {
+ EXPECT_EQ(app_nicknames1[i], appNicknames[i].asString());
+ }
+ // Check AppHMITypes match
+ for (uint32_t i = 0; i < app_hmi_types_size; ++i) {
+ EXPECT_EQ(app_hmi_types1[i], appHmiTypes[i].asString());
}
+}
- TEST_F(PolicyManagerImplTest, DISABLED_GetPolicyTableStatus) {
- // TODO(AOleynik): Test is not finished, to be continued
- // manager->GetPolicyTableStatus();
+TEST_F(
+ PolicyManagerImplTest2,
+ CanAppKeepContext_AddAppFromUnconsentedDevice_ExpectAppCannotKeepContext) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ manager->AddApplication(app_id2);
+ // Check if app has preData policy
+ EXPECT_FALSE(manager->IsPredataPolicy(app_id2));
+ // Check keep context in preData policy
+ EXPECT_TRUE(manager->CanAppKeepContext(app_id2));
+}
+
+TEST_F(PolicyManagerImplTest2,
+ CanAppKeepContext_AddAppFromConsentedDevice_ExpectAppCannotKeepContext) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ ASSERT_TRUE((manager->GetCache())->AddDevice(dev_id2, "Bluetooth"));
+ manager->AddApplication(app_id2);
+ ASSERT_TRUE((manager->GetCache())
+ ->SetDeviceData(dev_id2,
+ "hardware IPX",
+ "v.8.0.1",
+ "Android",
+ "4.4.2",
+ "Life",
+ 2,
+ "Bluetooth"));
+ manager->SetUserConsentForDevice(dev_id2, true);
+ ::policy::DeviceConsent consent = manager->GetUserConsentForDevice(dev_id2);
+ EXPECT_EQ(::policy::DeviceConsent::kDeviceAllowed, consent);
+ EXPECT_CALL(listener, OnCurrentDeviceIdUpdateRequired(app_id2))
+ .WillRepeatedly(Return(dev_id2));
+ manager->AddApplication(app_id2);
+ EXPECT_TRUE((manager->GetCache())->IsDefaultPolicy(app_id2));
+ // Check keep context in default policy
+ EXPECT_TRUE(manager->CanAppKeepContext(app_id2));
+}
+
+TEST_F(PolicyManagerImplTest2,
+ CanAppKeepContext_SetPoliciesForAppUpdated_ExpectAppCanKeepContext) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ manager->AddApplication(app_id2);
+ GetPTU("valid_sdl_pt_update.json");
+ // Check keep context in updated policies for app
+ EXPECT_TRUE(manager->CanAppKeepContext(app_id2));
+}
+
+TEST_F(PolicyManagerImplTest2,
+ CanAppStealFocus_AddAppFromConsentedDevice_ExpectAppCannotStealFocus) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ ASSERT_TRUE((manager->GetCache())->AddDevice(dev_id2, "Bluetooth"));
+ manager->AddApplication(app_id2);
+ ASSERT_TRUE((manager->GetCache())
+ ->SetDeviceData(dev_id2,
+ "hardware IPX",
+ "v.8.0.1",
+ "Android",
+ "4.4.2",
+ "Life",
+ 2,
+ "Bluetooth"));
+ manager->SetUserConsentForDevice(dev_id2, true);
+ ::policy::DeviceConsent consent = manager->GetUserConsentForDevice(dev_id2);
+ EXPECT_EQ(::policy::DeviceConsent::kDeviceAllowed, consent);
+ EXPECT_CALL(listener, OnCurrentDeviceIdUpdateRequired(app_id2))
+ .WillRepeatedly(Return(dev_id2));
+ manager->AddApplication(app_id2);
+ EXPECT_TRUE((manager->GetCache())->IsDefaultPolicy(app_id2));
+ // Check keep context in default policy
+ EXPECT_TRUE(manager->CanAppStealFocus(app_id2));
+}
+
+TEST_F(PolicyManagerImplTest2,
+ CanAppStealFocus_SetPoliciesForAppUpdated_ExpectAppCanStealFocus) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ manager->AddApplication(app_id2);
+ GetPTU("valid_sdl_pt_update.json");
+ // Check keep context in updated policies for app
+ EXPECT_TRUE(manager->CanAppKeepContext(app_id2));
+}
+
+TEST_F(PolicyManagerImplTest2, GetCurrentDeviceId) {
+ // Arrange
+ EXPECT_CALL(listener, OnCurrentDeviceIdUpdateRequired(app_id2)).Times(2);
+ EXPECT_EQ(custom_str::CustomString(""), manager->GetCurrentDeviceId(app_id2));
+ EXPECT_EQ("", manager->GetCurrentDeviceId(app_id2));
+}
+
+TEST_F(PolicyManagerImplTest2,
+ GetVehicleInfo_SetVehicleInfo_ExpectReceivedInfoCorrect) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ GetPTU("valid_sdl_pt_update.json");
+ utils::SharedPtr<policy_table::Table> pt = (manager->GetCache())->GetPT();
+ policy_table::ModuleConfig& module_config = pt->policy_table.module_config;
+ ::policy::VehicleInfo vehicle_info = manager->GetVehicleInfo();
+
+ EXPECT_EQ(static_cast<std::string>(*module_config.vehicle_make),
+ vehicle_info.vehicle_make);
+ EXPECT_EQ(static_cast<std::string>(*module_config.vehicle_model),
+ vehicle_info.vehicle_model);
+ EXPECT_EQ(static_cast<std::string>(*module_config.vehicle_year),
+ vehicle_info.vehicle_year);
+}
+
+TEST_F(
+ PolicyManagerImplTest2,
+ GetPermissionsForApp_SetUserConsentForApp_ExpectReceivedPermissionsCorrect) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+
+ ASSERT_TRUE((manager->GetCache())->AddDevice(dev_id2, "Bluetooth"));
+ ASSERT_TRUE((manager->GetCache())
+ ->SetDeviceData(dev_id2,
+ "hardware IPX",
+ "v.8.0.1",
+ "Android",
+ "4.4.2",
+ "Life",
+ 2,
+ "Bluetooth"));
+
+ ::policy::StringArray consented_groups;
+ ::policy::StringArray disallowed_groups;
+ consented_groups.push_back(std::string("Notifications"));
+ (manager->GetCache())
+ ->SetUserPermissionsForDevice(
+ dev_id2, consented_groups, disallowed_groups);
+ manager->SetUserConsentForDevice(dev_id2, true);
+ EXPECT_CALL(listener, OnCurrentDeviceIdUpdateRequired(app_id2))
+ .WillRepeatedly(Return(dev_id2));
+ manager->AddApplication(app_id2);
+
+ GetPTU("valid_sdl_pt_update.json");
+ ::policy::PermissionConsent perm_consent;
+ perm_consent.device_id = dev_id2;
+ perm_consent.policy_app_id = app_id2;
+ perm_consent.consent_source = "VR";
+
+ ::policy::FunctionalGroupPermission group1_perm;
+ group1_perm.group_alias = "Notifications";
+ group1_perm.group_name = "Notifications";
+ group1_perm.group_id = ::utils::Djb2HashFromString("Notifications");
+ group1_perm.state = ::policy::GroupConsent::kGroupAllowed;
+
+ std::vector< ::policy::FunctionalGroupPermission> groups_permissions;
+ groups_permissions.push_back(group1_perm);
+ perm_consent.group_permissions = groups_permissions;
+
+ manager->SetUserConsentForApp(perm_consent);
+ manager->SendNotificationOnPermissionsUpdated(app_id2);
+ std::vector< ::policy::FunctionalGroupPermission> actual_groups_permissions;
+ std::vector< ::policy::FunctionalGroupPermission>::iterator it;
+ manager->GetPermissionsForApp(dev_id2, app_id2, actual_groups_permissions);
+ uint32_t index = 0;
+ for (; index < actual_groups_permissions.size(); ++index) {
+ if (actual_groups_permissions[index].group_id == group1_perm.group_id) {
+ break;
+ }
+ }
+ // Check
+ EXPECT_EQ(group1_perm.group_alias,
+ actual_groups_permissions[index].group_alias);
+ EXPECT_EQ(group1_perm.group_name,
+ actual_groups_permissions[index].group_name);
+ EXPECT_EQ(group1_perm.group_id, actual_groups_permissions[index].group_id);
+ EXPECT_EQ(group1_perm.state, actual_groups_permissions[index].state);
+}
+
+TEST_F(
+ PolicyManagerImplTest2,
+ HertBeatTimeout_AddApp_UpdateAppPolicies_ExpectReceivedHertBeatTimeoutCorrect) {
+ // Arrange
+ CreateLocalPT("sdl_preloaded_pt.json");
+ utils::SharedPtr<policy_table::Table> pt = (manager->GetCache())->GetPT();
+ ::policy_table::PolicyTableType type1 =
+ ::policy_table::PolicyTableType::PT_PRELOADED;
+ pt->SetPolicyTableType(type1);
+ if (!pt->is_valid()) {
+ std::cout << "\nPolicy table is not valid."
+ << "\n";
+ rpc::ValidationReport report("policy_table");
+ pt->ReportErrors(&report);
}
+ // Add new app
+ manager->AddApplication(app_id2);
+ uint32_t result = manager->HeartBeatTimeout(app_id2);
+ // By default hertbeat timeout is 0
+ EXPECT_EQ(0u, result);
+ Json::Value root = GetPTU("valid_sdl_pt_update.json");
+
+ ::policy_table::PolicyTableType type2 =
+ ::policy_table::PolicyTableType::PT_UPDATE;
+ pt->SetPolicyTableType(type2);
+ if (!pt->is_valid()) {
+ std::cout << "\nPolicy table is not valid."
+ << "\n";
+ rpc::ValidationReport report("policy_table");
+ pt->ReportErrors(&report);
+ }
+
+ Json::Value heart_beat_timeout = Json::Value(Json::uintValue);
+ heart_beat_timeout =
+ root["policy_table"]["app_policies"][app_id2]["heart_beat_timeout_ms"];
+ result = manager->HeartBeatTimeout(app_id2);
+ EXPECT_EQ(heart_beat_timeout.asUInt(), result);
}
-// namespace policy
-} // namespace components
-} // namespace test
+
+} // namespace policy
+} // namespace components
+} // namespace test
diff --git a/src/components/policy/test/ptu2_requestType.json b/src/components/policy/test/ptu2_requestType.json
new file mode 100644
index 0000000000..50364397fd
--- /dev/null
+++ b/src/components/policy/test/ptu2_requestType.json
@@ -0,0 +1,2615 @@
+{
+ "policy_table": {
+ "module_config": {
+ "preloaded_pt": true,
+ "preloaded_date": "2015-12-02",
+ "exchange_after_x_ignition_cycles": 100,
+ "exchange_after_x_kilometers": 1800,
+ "exchange_after_x_days": 30,
+ "timeout_after_x_seconds": 60,
+ "seconds_between_retries": [
+ 1,
+ 5,
+ 25,
+ 125,
+ 625
+ ],
+ "endpoints": {
+ "0x07": {
+ "default": [
+ "http://policies.telematics.ford.com/api/policies"
+ ]
+ },
+ "0x04": {
+ "default": [
+ "http://ivsu.software.ford.com/api/getsoftwareupdates"
+ ]
+ }
+ },
+ "notifications_per_minute_by_priority": {
+ "EMERGENCY": 60,
+ "NAVIGATION": 15,
+ "VOICECOM": 20,
+ "COMMUNICATION": 6,
+ "NORMAL": 4,
+ "NONE": 0
+ }
+ },
+ "functional_groupings": {
+ "Base-4": {
+ "rpcs": {
+ "AddCommand": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "AddSubMenu": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "Alert": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ChangeRegistration": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "CreateInteractionChoiceSet": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "DeleteCommand": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "DeleteFile": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "DeleteInteractionChoiceSet": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "DeleteSubMenu": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "EndAudioPassThru": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "GenericResponse": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ListFiles": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnAudioPassThru": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnButtonEvent": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED",
+ "BACKGROUND"
+ ]
+ },
+ "OnButtonPress": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED",
+ "BACKGROUND"
+ ]
+ },
+ "OnCommand": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnDriverDistraction": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnHashChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "PerformAudioPassThru": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "PerformInteraction": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "PutFile": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "ResetGlobalProperties": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "ScrollableMessage": {
+ "hmi_levels": [
+ "FULL"
+ ]
+ },
+ "SetAppIcon": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetGlobalProperties": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetMediaClockTimer": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED",
+ "BACKGROUND"
+ ]
+ },
+ "Show": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "Slider": {
+ "hmi_levels": [
+ "FULL"
+ ]
+ },
+ "Speak": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "SubscribeButton": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "SystemRequest": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "UnsubscribeButton": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "Location-1": {
+ "user_consent_prompt": "Location",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "gps",
+ "speed"
+ ]
+ },
+ "OnVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "gps",
+ "speed"
+ ]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "gps",
+ "speed"
+ ]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "gps",
+ "speed"
+ ]
+ }
+ }
+ },
+ "Notifications": {
+ "user_consent_prompt": "Notifications",
+ "rpcs": {
+ "Alert": {
+ "hmi_levels": [
+ "BACKGROUND"
+ ]
+ }
+ }
+ },
+ "DrivingCharacteristics-3": {
+ "user_consent_prompt": "DrivingCharacteristics",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "OnVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ }
+ }
+ },
+ "VehicleInfo-3": {
+ "user_consent_prompt": "VehicleInfo",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"
+ ]
+ },
+ "OnVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"
+ ]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"
+ ]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"
+ ]
+ }
+ }
+ },
+ "PropriataryData-1": {
+ "rpcs": {
+ "DiagnosticMessage": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "GetDTCs": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ReadDID": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "PropriataryData-2": {
+ "rpcs": {
+ "DiagnosticMessage": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "GetDTCs": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ReadDID": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "ProprietaryData-3": {
+ "rpcs": {
+ "GetDTCs": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ReadDID": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "Emergency-1": {
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "OnVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ }
+ }
+ },
+ "Navigation-1": {
+ "rpcs": {
+ "AlertManeuver": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ShowConstantTBT": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "UpdateTurnList": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "Base-6": {
+ "rpcs": {
+ "AddCommand": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "AddSubMenu": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "Alert": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ChangeRegistration": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "CreateInteractionChoiceSet": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "DeleteCommand": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "DeleteFile": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "DeleteInteractionChoiceSet": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "DeleteSubMenu": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "EndAudioPassThru": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "GenericResponse": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ListFiles": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnAudioPassThru": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnButtonEvent": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnButtonPress": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnCommand": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnDriverDistraction": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnSyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnTBTClientState": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "PerformAudioPassThru": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "PerformInteraction": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "PutFile": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "ResetGlobalProperties": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ScrollableMessage": {
+ "hmi_levels": [
+ "FULL"
+ ]
+ },
+ "SetAppIcon": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetGlobalProperties": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "SetMediaClockTimer": {
+ "hmi_levels": [
+ "FULL"
+ ]
+ },
+ "Show": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "Slider": {
+ "hmi_levels": [
+ "FULL"
+ ]
+ },
+ "Speak": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "SubscribeButton": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "SyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "UnsubscribeButton": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "OnKeyboardInputOnlyGroup": {
+ "rpcs": {
+ "OnKeyboardInput": {
+ "hmi_levels": [
+ "FULL"
+ ]
+ }
+ }
+ },
+ "OnTouchEventOnlyGroup": {
+ "rpcs": {
+ "OnTouchEvent": {
+ "hmi_levels": [
+ "FULL"
+ ]
+ }
+ }
+ },
+ "DiagnosticMessageOnly": {
+ "rpcs": {
+ "DiagnosticMessage": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "DataConsent-2": {
+ "user_consent_prompt": "DataConsent",
+ "rpcs": null
+ },
+ "BaseBeforeDataConsent": {
+ "rpcs": {
+ "ChangeRegistration": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "DeleteFile": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "ListFiles": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnHashChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "PutFile": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "ResetGlobalProperties": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetGlobalProperties": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetAppIcon": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SystemRequest": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ }
+ }
+ },
+ "SendLocation": {
+ "rpcs": {
+ "SendLocation": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "BackgroundAPT": {
+ "rpcs": {
+ "EndAudioPassThru": {
+ "hmi_levels": [
+ "BACKGROUND"
+ ]
+ },
+ "OnAudioPassThru": {
+ "hmi_levels": [
+ "BACKGROUND"
+ ]
+ },
+ "PerformAudioPassThru": {
+ "hmi_levels": [
+ "BACKGROUND"
+ ]
+ }
+ }
+ }
+ },
+ "consumer_friendly_messages": {
+ "version": "001.001.021",
+ "messages": {
+ "AppPermissions": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% benötigt die folgenden Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Wenn Sie Ja drücken, erklären Sie sich damit einverstanden, dass %vehicleMake% nicht für Schäden oder Verletzungen der Privatsphäre haftet, die im Zusammenhang mit der Nutzung Ihrer Benutzerdaten durch %appName% entstehen. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab.",
+ "line1": "Zugriffsanfrage(n)",
+ "line2": "erlauben?"
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. Please press yes to allow or no to deny.",
+ "line1": "Grant Requested",
+ "line2": "Permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. \n\nIf you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "es-en": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?",
+ "textBody": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar. \n\n Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando el uso de los siguientes permisos e información del vehículo: %functionalGroupLabels%. Si pulsa sí, acepta que %vehicleMake% no será responsable de los daños o la pérdida de privacidad relacionados con el uso de sus datos por parte de %appName%. Pulse sí para permitir o no para denegar.",
+ "line1": "¿Conceder permisos",
+ "line2": "solicitados?"
+ },
+ "es-mx": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?",
+ "textBody": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. \n\nSi presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles."
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)",
+ "textBody": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)"
+ },
+ "it-it": {
+ "tts": "%appName% richiede l'uso delle seguenti informazioni e autorizzazioni sul veicolo: %functionalGroupLabels%. Se si preme Sì, si acconsente che %vehicleMake% non sarà responsabile per danni o perdita di privacy in relazione all'impiego dei dati da parte di %appName%. Premere Sì per consentire e No per negare.",
+ "line1": "Concedi autorizzaz.",
+ "line2": "richiesta(e)?"
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. Als u op Ja drukt, gaat u ermee akkoord dat %vehicleMake% in geen geval aansprakelijk gesteld kan worden voor schade of verlies van privacy als gevolg van het feit dat %appName% gebruik maakt van uw gegevens. Druk op Ja om dit toe te staan of Nee om te weigeren.",
+ "line1": "Aangevraagde",
+ "line2": "permissie(s) verlenen?"
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz pozwoleń: %functionalGroupLabels%. Naciśnięcie TAK oznacza zgodę na fakt, iż %vehicleMake% nie będzie ponosić odpowiedzialności za szkody ani utratę prywatności w związku z wykorzystaniem przez %appName% danych, należących do użytkownika. Naciśnij TAK w celu udzielenia zgody lub NIE w celu odrzucenia żądania.",
+ "line1": "Udzielić żądanych",
+ "line2": "pozwoleń?"
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando o uso das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se pressionar sim, você concorda que a %vehicleMake% não será responsável por danos ou perdas de privacidade relacionados ao uso dos seus dados por %appName%. Pressione sim para permitir ou não para negar.",
+ "line1": "Conceder permissão",
+ "line2": "solicitada?"
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar a utilização das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se premir “Sim”, concorda que %vehicleMake% não será responsável por quaisquer danos ou perda de privacidade relacionada com a utilização dos seus dados por parte de %appName%. Prima “Sim” para permitir ou “Não” para recusar.",
+ "line1": "Conceder permiss.",
+ "line2": "solicitada(s)?"
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Нажатием \"\"да\"\", Вы соглашаетесь, что %vehicleMake% не будет нести ответственность за какие-либо убытки или потерю прайвеси, связанные с использованием Ваших данных компанией %appName%. Нажмите \"\"Да\"\", если Вы согласны, или \"\"Нет\"\" - если не согласны.",
+ "line1": "Предост. заправш.",
+ "line2": "разрешения?"
+ },
+ "sv-se": {
+ "tts": "%appName% begär att få tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Om du trycker Ja godkänner du att %vehicleMake% ska hållas skadeslös för alla skador som kan uppstå eller eventuella integritetsintrång som uppstår när %appName% använder dina data. Tryck Ja för att godkänna eller Nej för att neka.",
+ "line1": "Vill du ge",
+ "line2": "tillstånd?"
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri kullanma isteğinde bulunuyor: %functionalGroupLabels%. Evet'e basarsanız, %appName%'in verilerinizi kullanması sonucunda oluşabilecek hasarlardan veya gizlilik kaybından %vehicleMake%'in sorumlu olmayacağını kabul etmiş olacaksınız. Lütfen kabul etmek için Evet'e veya reddetmek için Hayır'a basın.",
+ "line1": "İstenen izinler",
+ "line2": "verilsin mi?"
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求使用下列车辆信息和权限: %functionalGroupLabels%。如果您按“是”,则表示您同意。 %vehicleMake% 将不会对因 %appName% 使用您的数据而引起的任何损毁或隐私损失负责。 请按“是”允许或按“否”拒绝。",
+ "line1": "是否允许请求的",
+ "line2": "权限?"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。按「是」,表示您同意,如因 %appName% 使用您的資料導致任何損害或損失,%vehicleMake% 將不負賠償責任。同意請按「是」,拒絕請按「否」。",
+ "line1": "允許",
+ "line2": "授權請求?"
+ }
+ }
+ },
+ "AppPermissionsHelp": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% fordert folgende Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Im Einstellungsmenü der mobilen Apps können Sie diese Berechtigungen ändern und sich detaillierte Beschreibungen anhören. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press yes to grant permissions or no to deny."
+ },
+ "es-en": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando los siguientes permisos e información del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y escuchar descripciones detalladas en el menú de configuración de la aplicación móvil. Pulse sí para conceder el permiso o no para denegarlo."
+ },
+ "es-mx": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "it-it": {
+ "tts": "%appName% richiede le seguenti informazioni e autorizzazioni riguardo il veicolo: %functionalGroupLabels%. È possibile modificare tali autorizzazioni e ascoltare descrizioni dettagliate nel menu impostazioni delle app mobili. Premere Sì per concedere le autorizzazioni e No per negarle."
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. U kunt deze toestemmingen wijzigen en gedetailleerde beschrijvingen beluisteren in het instellingenmenu voor mobiele apps. Druk op Ja om permissies te verlenen of op Nee om te weigeren."
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz zezwoleń: %functionalGroupLabels%. W menu ustawień aplikacji mobilnych można zmienić owe zezwolenia i usłyszeć ich szczegółowy opis. Naciśnij TAK, aby wyrazić zgodę lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando as seguintes informações e permissões do veículo: %functionalGroupLabels%. Você pode alterar estas permissões e ouvir descrições detalhadas no menu de configurações de aplicativos móveis. Pressione sim para conceder as permissões ou não para negar."
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar as seguintes informações e permissões do veículo: %functionalGroupLabels%. Pode alterar estas permissões e ouvir descrições detalhadas no menu de definições das aplicações móveis. Prima \"\"Sim\"\" para permitir ou \"\"Não\"\" para recusar."
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Вы можете изменить эти разрешения и прослушать подробные их описания в меню настроек мобильного приложения. Нажмите \"\"да\"\", чтобы предоставить разрешения, или \"\"нет\"\", чтобы не предоставлять."
+ },
+ "sv-se": {
+ "tts": "%appName% begär tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Du kan ändra tillstånden och höra detaljerade beskrivningar i menyn för mobilappsinställningar. Tryck Ja för att ge tillstånd eller Nej för att neka."
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri istiyor: %functionalGroupLabels%. Bu izinleri değiştirebilir ve mobil uygulamalar ayarlar menüsünden ayrıntılı açıklamaları dinleyebilirsiniz. Lütfen izin vermek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求下列车辆信息和权限: %functionalGroupLabels%。您可在移动应用程序设置菜单中更改这些权限,并听取详细说明。请按“是”允许权限或按“否”拒绝。"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。您可在行動應用程式設定清單中更改這些許可,並聆聽詳細說明。給予許可請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsRevoked": {
+ "languages": {
+ "de-de": {
+ "tts": "Die Autorisierungsdaten der App wurden geändert. %appName% hat keinen Zugriff auf %functionalGroupLabels% mehr. Installieren Sie die neueste Version der App auf Ihrem Gerät.."
+ },
+ "en-au": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-gb": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-ie": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-us": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "es-en": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "es-es": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de que tiene la versión más reciente de la aplicación instalada en su dispositivo móvil."
+ },
+ "es-mx": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "fr-ca": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "fr-fr": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "it-it": {
+ "tts": "Le autorizzazioni dell'app sono cambiate. %appName% non è più in grado di accedere a %functionalGroupLabels%. Assicurarsi di avere la versione più recente dell'app installata sul dispositivo mobile."
+ },
+ "nl-nl": {
+ "tts": "De app-autorisaties zijn gewijzigd. %appName% heeft geen toegang meer tot %functionalGroupLabels%. Zorg ervoor dat u de meest recente app-versie op uw mobiele apparaat geïnstalleerd hebt."
+ },
+ "pl-pl": {
+ "tts": "Dane dostępu aplikacji zostały zmienione. %appName% nie ma już dostępu do %functionalGroupLabels%. Sprawdź, czy na telefonie komórkowym zainstalowano najnowszą wersję aplikacji."
+ },
+ "pt-br": {
+ "tts": "As autorizações dos aplicativos foram alteradas. %appName% não pode mais acessar %functionalGroupLabels%. Certifique-se de que a versão mais recente do aplicativo está instalada no seu dispositivo móvel."
+ },
+ "pt-pt": {
+ "tts": "As autorizações das aplicações mudaram. %appName% já não consegue aceder a %functionalGroupLabels%. Certifique-se de que tem a última versão da aplicação no seu dispositivo móvel."
+ },
+ "ru-ru": {
+ "tts": "Авторизации приложения изменены. %appName% больше не имеет доступа к %functionalGroupLabels%. Убедитесь, что на вашем мобильном устройстве установлена самая новая версия приложения."
+ },
+ "sv-se": {
+ "tts": "Appens behörigheter har ändrats. %appName% har inte längre åtkomst till %functionalGroupLabels%. Kontrollera att du har installerat den senaste versionen av appen på mobilenheten."
+ },
+ "tr-tr": {
+ "tts": "Uygulama yetkileri değişti. %appName% artık %functionalGroupLabels%'e erişemeyecek. Lütfen mobil aygıtınızda en son uygulama sürümünün yüklü olduğundan emin olun."
+ },
+ "zh-cn": {
+ "tts": "应用程序授权已变更。 %appName% 将不能再访问 %functionalGroupLabels%。 请确认您的移动设备上安装的应用程序是最新版本。"
+ },
+ "zh-tw": {
+ "tts": "應用程式授權已改變。%appName% 已無法進入 %functionalGroupLabels%。請確認您的行動裝置上安裝了最新版應用程式。"
+ }
+ }
+ },
+ "AppUnauthorized": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% ist nicht autorisiert und wird nicht mit SYNC funktionieren.",
+ "line1": "nicht autorisiert"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized",
+ "textBody": "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "Not Authorized",
+ "textBody": "This version of %appName% is no longer authorized to work with AppLink. Please update to the latest version of %appName%."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada",
+ "textBody": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no está autorizada y no funcionará con SYNC.",
+ "line1": "No autorizada"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada",
+ "textBody": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée",
+ "textBody": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è autorizzata e non funziona con il SYNC.",
+ "line1": "non autorizzata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% is niet geautoriseerd en werkt niet met SYNC.",
+ "line1": "niet geautoriseerd"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie posiada autoryzacji i nie będzie działać z SYNC.",
+ "line1": "brak autoryzacji"
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não tem autorização e não funcionará com o SYNC.",
+ "line1": "não autorizado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não está autorizada e não funcionará com o SYNC.",
+ "line1": "não autorizada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не авторизирована и не будет работать с SYNC.",
+ "line1": "не авторизировано"
+ },
+ "sv-se": {
+ "tts": "Den här versionen av %appName% är inte godkänd och fungerar inte med SYNC.",
+ "line1": "är ej godkänd"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümüne izin verilmediğinden SYNC ile çalışamaz.",
+ "line1": "için izin yok"
+ },
+ "zh-cn": {
+ "tts": "此版本的%appName% 未得到授权,无法在SYNC上使用。",
+ "line1": "未得到授权"
+ },
+ "zh-tw": {
+ "tts": "%appName% 的版本未獲得授權,將無法透過 SYNC 使用。",
+ "line1": "無授權"
+ }
+ }
+ },
+ "AppUnsupported": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% wird von SYNC nicht unterstützt.",
+ "line1": "nicht unterstützt"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported",
+ "textBody": "This version of %appName% is not supported by SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "Not Supported",
+ "textBody": "Your version of %appName% is not supported by SYNC."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible",
+ "textBody": "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "No compatible"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible",
+ "textBody": "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible",
+ "textBody": "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è supportata dal SYNC.",
+ "line1": "non supportata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% wordt niet ondersteund door SYNC.",
+ "line1": "niet ondersteund"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie jest obsługiwana przez system SYNC.",
+ "line1": "aplikacja nie obsług."
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não é suportada pelo SYNC.",
+ "line1": "não suportado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não é suportado pelo SYNC.",
+ "line1": "não suportada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не поддерживается SYNC.",
+ "line1": "не поддерживается"
+ },
+ "sv-se": {
+ "tts": "SYNC har inte stöd för den här versionen av %appName%.",
+ "line1": "stöds ej"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümü SYNC tarafından desteklenmiyor.",
+ "line1": "desteklenmiyor"
+ },
+ "zh-cn": {
+ "tts": "SYNC不支持此版本的%appName%。",
+ "line1": "不受支持"
+ },
+ "zh-tw": {
+ "tts": "SYNC 不支援此版本的%appName% 。",
+ "line1": "不支援"
+ }
+ }
+ },
+ "DataConsent": {
+ "languages": {
+ "en-gb": {
+ "textBody": "Would you like to enable Mobile Apps on SYNC? To use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S. \r\n\r\nUpdates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "en-us": {
+ "line1": "Enable Mobile Apps",
+ "line2": "on SYNC? (Uses Data)",
+ "textBody": "Would you like to enable Mobile Apps on SYNC?\r\n\r\nTo use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S.\r\n\r\nUpdates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "es-mx": {
+ "textBody": "Para usar aplicaciones móviles con SYNC, este debe comunicarse con Ford al menos una vez al mes a través del plan de datos de su dispositivo móvil. Pueden aplicar tarifas normales. SYNC enviará su VIN y el número de módulo de SYNC a Ford de Estados Unidos de América. \n\nLas actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario. \n\nPresione Sí para permitir y No para denegar."
+ },
+ "fr-ca": {
+ "textBody": "Pour utiliser AppLink, SYNC devra communiquer avec Ford au moins une fois par mois en utilisant le forfait de données de votre appareil mobile. Les tarifs réguliers peuvent s’appliquer. SYNC enverra votre NIV et le numéro de votre module SYNC à Ford États-Unis. Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements.\r\n\r\nVeuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ }
+ }
+ },
+ "DataConsentHelp": {
+ "languages": {
+ "en-us": {
+ "textBody": "By enabling mobile apps, you consent to allowing SYNC to communicate with Ford at least once per month using your mobile device’s data plan. Disabling will stop all data usage, but you will not be able to use mobile apps on SYNC. See your Owner Guide for more information."
+ },
+ "es-mx": {
+ "textBody": "Las actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario."
+ },
+ "fr-ca": {
+ "textBody": "Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements."
+ }
+ }
+ },
+ "DisableApps": {
+ "languages": {
+ "de-de": {
+ "tts": "Ausschalten der automatischen Updates führt zum Ausschalten von SYNC mobile Apps. Sie können Ihre mobilen Apps dann nicht mehr mit SYNC nutzen. Bitte drücken Sie Ja zur Bestätigung oder Nein, um abzubrechen.",
+ "line1": "Auto-Update",
+ "line2": "und Mobile Apps deaktivieren"
+ },
+ "en-au": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-gb": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-ie": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-us": {
+ "tts": "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel.",
+ "line1": "Disable Auto-Updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "If you disable, you will not be able to use any mobile apps with SYNC and your vehicle will stop receiving mobile app permission updates via your device`s data plan. Please press yes to disable mobile apps or no to cancel."
+ },
+ "es-en": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?",
+ "textBody": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "es-es": {
+ "tts": "Si desactiva las actualizaciones automáticas, también se desactivará la sincronización de las aplicaciones móviles. No podrá utilizar ninguna aplicación móvil con SYNC. Pulse sí para confirmar o no para cancelar.",
+ "line1": "¿Desact. actual. auto",
+ "line2": "y apl. móviles?"
+ },
+ "es-mx": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?",
+ "textBody": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "fr-ca": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?",
+ "textBody": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "fr-fr": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?"
+ },
+ "it-it": {
+ "tts": "Disabilitando gli aggiornamenti automatici si disattiva anche la sincronizzazione delle app mobili. Non sarà possibile usare app mobili con il SYNC. Premere Sì per confermare e No per cancellare.",
+ "line1": "Disabilitare agg. aut.",
+ "line2": "e app mobili?"
+ },
+ "nl-nl": {
+ "tts": "Door automatische updates uit te schakelen, schakelt u ook SYNC-mobiele apps uit. U kunt dan geen mobiele apps meer gebruiken met SYNC. Druk op Ja om te bevestigen of op Nee om te annuleren.",
+ "line1": "Auto-updates en mob.",
+ "line2": "apps uitschakelen?"
+ },
+ "pl-pl": {
+ "tts": "Wyłączenie automatycznych aktualizacji spowoduje także wyłączenie aplikacji mobilnych SYNC. Korzystanie z mobilnych aplikacji za pomocą SYNC będzie niemożliwe. Naciśnij TAK, by potwierdzić lub NIE, by anulować.",
+ "line1": "Wył. automat. aktual.",
+ "line2": "i aplikacje mobilne?"
+ },
+ "pt-br": {
+ "tts": "Se as atualizações automáticas forem desativadas, os aplicativos também serão desativados. Você não poderá usar nenhum aplicativo com o SYNC. Pressione sim para confirmar ou não para cancelar.",
+ "line1": "Desativar atualizações",
+ "line2": "autom. e aplicativos?"
+ },
+ "pt-pt": {
+ "tts": "A desactivação das actualizações automáticas desactiva igualmente as aplicações móveis do SYNC. Não poderá utilizar quaisquer aplicações móveis com o SYNC. Prima \"\"Sim\"\" para confirmar ou \"\"Não\"\" para cancelar.",
+ "line1": "Desact. actual. autom.",
+ "line2": "e aplicações móveis?"
+ },
+ "ru-ru": {
+ "tts": "При отключении автоматических обновлений также будут отключены мобильные приложения sync. Вы не сможете использовать какие-либо мобильные приложения с SYNC. Нажмите \"\"Да\"\" для подтверждения или \"\"Нет\"\" для отмены.",
+ "line1": "Откл. автообновления",
+ "line2": "и мобил. прилож.?"
+ },
+ "sv-se": {
+ "tts": "Om du avaktiverar automatisk uppdatering avaktiverar du även synkning av mobilappar. Du kommer inte längre att kunna använda dina mobilappar med SYNC. Tryck Ja för att bekräfta eller Nej för att avbryta.",
+ "line1": "Avaktiverar autouppdat.",
+ "line2": "och mobilappar?"
+ },
+ "tr-tr": {
+ "tts": "Otomatik güncellemeleri devre dışı bırakırsanız sync mobil uygulamalar da devre dışı kalır. SYNC ile mobil uygulama kullanmanız mümkün olmaz. Lütfen onaylamak için Evet'e veya iptal etmek için Hayır'a basın.",
+ "line1": "Oto. güncelleme ve",
+ "line2": "mobil uygul. kapat?"
+ },
+ "zh-cn": {
+ "tts": "禁用自动更新同时也会禁用SYNC移动应用程序。您将无法在 SYNC 中使用任何移动应用程序。请按“是”确认或按“否”取消。",
+ "line1": "是否禁用自动更新和",
+ "line2": "移动应用程序?"
+ },
+ "zh-tw": {
+ "tts": "停用自動更新也將停用 sync 行動應用程式。您將無法透過 SYNC 使用任何行動應用程式。確認請按「是」,取消請按「否」。",
+ "line1": "停用自動更新",
+ "line2": "和行動應用程式?"
+ }
+ }
+ },
+ "DrivingCharacteristics": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahreigenschaften: Kraftstoffverbrauch, MyKey, Sicherheitsgurtstatus.",
+ "label": "Fahreigenschaften"
+ },
+ "en-au": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-gb": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-ie": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-us": {
+ "tts": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status.",
+ "label": "Driving Characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo",
+ "textBody": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a las siguientes características de conducción: Consumo de combustible, MyKey, Estado cinturones de seguridad.",
+ "label": "Características de conducción"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo",
+ "textBody": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite",
+ "textBody": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti caratteristiche di guida: Consumo carburante, MyKey, Stato cinture di sicurezza.",
+ "label": "Caratteristiche di guida"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende rijkenmerken: Brandstofverbruik, MyKey, Veiligheidsgordelstatus.",
+ "label": "Rijkenmerken"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji dotyczących jazdy: Zużycie paliwa, MyKey, Stan pasów bezpieczeństwa.",
+ "label": "Informacje dotyczące stylu jazdy"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes características de condução: Consumo de combustível, MyKey, Estado do cinto de segurança.",
+ "label": "Características de condução"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações de condução: Consumo de combustível, MyKey, Estado dos cintos de segurança.",
+ "label": "Características de condução"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим характеристикам движения: Расход топлива, MyKey, Состояние ремней безопасности.",
+ "label": "Характеристики движения"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande köregenskaper: Bränsleförbrukning, MyKey, Bältesstatus.",
+ "label": "Köregenskaper"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu sürüş karakteristiklerine erişebilir: Yakıt tüketimi, MyKey, Emniyet kemeri durumu.",
+ "label": "Sürüş karakteristikleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列行驶特性: 油耗, MyKey, 安全带状态",
+ "label": "行驶特性"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取以下駕駛特性: 油耗, MyKey, 安全帶狀態",
+ "label": "駕駛特性"
+ }
+ }
+ },
+ "Location": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die GPS-Daten und die Geschwindigkeit des Fahrzeugs.",
+ "label": "GPS und Geschwindigkeit"
+ },
+ "en-au": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-gb": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "en-ie": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-us": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad",
+ "textBody": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder al GPS y la velocidad del vehículo.",
+ "label": "GPS y velocidad"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad",
+ "textBody": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse",
+ "textBody": "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso a GPS e velocità del veicolo.",
+ "label": "GPS e velocità"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot gps en de snelheid van het voertuig.",
+ "label": "Gps en snelheid"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do modułu GPS i prędkości pojazdu.",
+ "label": "GPS i prędkość"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar o GPS e a velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder ao GPS e à velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к GPS и скорости автомобиля.",
+ "label": "GPS и скорость"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt fordonets GPS och hastighetsmätare.",
+ "label": "GPS och hastighet"
+ },
+ "tr-tr": {
+ "tts": "Bu uygulama aracın GPS ve hız bilgilerine erişebilir.",
+ "label": "GPS ve hız"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可以访问车辆 GPS 和车速信息。",
+ "label": "GPS 和车速"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取車輛的GPS和速度。",
+ "label": "GPS和車速"
+ }
+ }
+ },
+ "Notifications": {
+ "languages": {
+ "de-de": {
+ "tts": "Läuft die App im Hintergrund, kann Sie Benachrichtigungen senden.",
+ "label": "Push-Benachrichtigungen"
+ },
+ "en-au": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-gb": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "en-ie": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-us": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push",
+ "textBody": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede enviar notificaciones cuando se está ejecutando en segundo plano.",
+ "label": "Notificaciones push"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push",
+ "textBody": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "fr-ca": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications instantanées",
+ "textBody": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "fr-fr": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications push"
+ },
+ "it-it": {
+ "tts": "Un'app può inviare notifiche se eseguita in background.",
+ "label": "Notifiche push"
+ },
+ "nl-nl": {
+ "tts": "Een app kan meldingen versturen als deze op de achtergrond actief is.",
+ "label": "Push-meldingen"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może wysyłać powiadomienia, działając w tle.",
+ "label": "Powiadomienia Push"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode enviar notificações quando estiver sendo executado em segundo plano.",
+ "label": "Notificações Push"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue enviar notificações quando está activa em segundo plano.",
+ "label": "Notificações push"
+ },
+ "ru-ru": {
+ "tts": "Если приложение работает в фоновом режиме, оно может отправлять оповещения.",
+ "label": "Оповещения о пересылке"
+ },
+ "sv-se": {
+ "tts": "Appen kan skicka meddelanden när den körs i bakgrunden.",
+ "label": "Push-notiser"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama arka planda çalışırken bildirim gönderebilir.",
+ "label": "Anlık bildirimleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序在后台运行时可推送通知。",
+ "label": "推送通知"
+ },
+ "zh-tw": {
+ "tts": "車輛行進時,應用程式可在背景中傳送通知。",
+ "label": "傳送通知"
+ }
+ }
+ },
+ "SettingDisableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Updates deakt."
+ },
+ "en-au": {
+ "line1": "Disable updates"
+ },
+ "en-gb": {
+ "line1": "Disable updates"
+ },
+ "en-ie": {
+ "line1": "Disable updates"
+ },
+ "en-us": {
+ "line1": "Disable Updates",
+ "textBody": "Disable Updates"
+ },
+ "es-en": {
+ "line1": "Deshab. actual.",
+ "textBody": "Deshab. actual."
+ },
+ "es-es": {
+ "line1": "Desact. actual."
+ },
+ "es-mx": {
+ "line1": "Deshab. actual.",
+ "textBody": "Deshab. actual."
+ },
+ "fr-ca": {
+ "line1": "Désactiver MAJ",
+ "textBody": "Désactiver MAJ"
+ },
+ "fr-fr": {
+ "line1": "Désactiver màj"
+ },
+ "it-it": {
+ "line1": "Disabilita agg."
+ },
+ "nl-nl": {
+ "line1": "Upd. uitschak."
+ },
+ "pl-pl": {
+ "line1": "Wyłącz aktual."
+ },
+ "pt-br": {
+ "line1": "Desat. atualiz."
+ },
+ "pt-pt": {
+ "line1": "Desact. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Откл. обновл."
+ },
+ "sv-se": {
+ "line1": "Inaktivera uppd."
+ },
+ "tr-tr": {
+ "line1": "Güncell. Kapat"
+ },
+ "zh-cn": {
+ "line1": "禁用更新"
+ },
+ "zh-tw": {
+ "line1": "停用更新"
+ }
+ }
+ },
+ "SettingEnableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Apps aktivieren"
+ },
+ "en-au": {
+ "line1": "Enable Apps"
+ },
+ "en-gb": {
+ "line1": "Enable Apps"
+ },
+ "en-ie": {
+ "line1": "Enable Apps"
+ },
+ "en-us": {
+ "line1": "Enable Apps"
+ },
+ "es-en": {
+ "line1": "Hab. aplic."
+ },
+ "es-es": {
+ "line1": "Activar apl."
+ },
+ "es-mx": {
+ "line1": "Hab. aplic."
+ },
+ "fr-ca": {
+ "line1": "Activer app.",
+ "textBody": "Activer app."
+ },
+ "fr-fr": {
+ "line1": "Activer app."
+ },
+ "it-it": {
+ "line1": "Abilita app"
+ },
+ "nl-nl": {
+ "line1": "Apps inschak."
+ },
+ "pl-pl": {
+ "line1": "Włącz aplikacje"
+ },
+ "pt-br": {
+ "line1": "Ativar aplic."
+ },
+ "pt-pt": {
+ "line1": "Activar actualiz."
+ },
+ "ru-ru": {
+ "line1": "Вкл. прилож."
+ },
+ "sv-se": {
+ "line1": "Aktivera appar"
+ },
+ "tr-tr": {
+ "line1": "Uygulamaları aç"
+ },
+ "zh-cn": {
+ "line1": "启用应用程序"
+ },
+ "zh-tw": {
+ "line1": "啟用應用程式"
+ }
+ }
+ },
+ "SettingUpdateAuto": {
+ "languages": {
+ "de-de": {
+ "line1": "Update anford."
+ },
+ "en-au": {
+ "line1": "Request update"
+ },
+ "en-gb": {
+ "line1": "Request update"
+ },
+ "en-ie": {
+ "line1": "Request update"
+ },
+ "en-us": {
+ "line1": "Request Update",
+ "textBody": "Select `Update now` to receive app permissions for your SYNC-enabled mobile apps. This may enable additional functionality depending on the app and your settings. If your phone has a working data connection, an update should complete in less than 1 minute."
+ },
+ "es-en": {
+ "line1": "Solicit. actualiz.",
+ "textBody": "Solicit. actualiz."
+ },
+ "es-es": {
+ "line1": "Solicitar actual."
+ },
+ "es-mx": {
+ "line1": "Solicit. actualiz.",
+ "textBody": "Solicit. actualiz."
+ },
+ "fr-ca": {
+ "line1": "Demander MAJ",
+ "textBody": "Demander MAJ"
+ },
+ "fr-fr": {
+ "line1": "Demander màj"
+ },
+ "it-it": {
+ "line1": "Rich. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Upd. aanvragen"
+ },
+ "pl-pl": {
+ "line1": "Zażądaj aktual."
+ },
+ "pt-br": {
+ "line1": "Solicitar atualiz."
+ },
+ "pt-pt": {
+ "line1": "Solicit. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Запрос на обн."
+ },
+ "sv-se": {
+ "line1": "Begär uppdat."
+ },
+ "tr-tr": {
+ "line1": "Güncelleme iste"
+ },
+ "zh-cn": {
+ "line1": "请求更新"
+ },
+ "zh-tw": {
+ "line1": "請求更新"
+ }
+ }
+ },
+ "StatusNeeded": {
+ "languages": {
+ "de-de": {
+ "line1": "Update benötigt"
+ },
+ "en-au": {
+ "line1": "Update needed"
+ },
+ "en-gb": {
+ "line1": "Update needed",
+ "textBody": "Update needed"
+ },
+ "en-ie": {
+ "line1": "Update needed"
+ },
+ "en-us": {
+ "line1": "Update Needed",
+ "textBody": "Update Needed"
+ },
+ "es-en": {
+ "line1": "Actualiz. neces.",
+ "textBody": "Actualiz. neces."
+ },
+ "es-es": {
+ "line1": "Actu. necesaria"
+ },
+ "es-mx": {
+ "line1": "Actualiz. neces.",
+ "textBody": "Actualiz. neces."
+ },
+ "fr-ca": {
+ "line1": "Màj requise",
+ "textBody": "Màj requise"
+ },
+ "fr-fr": {
+ "line1": "Mise à jour requise"
+ },
+ "it-it": {
+ "line1": "Necess. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Update nodig"
+ },
+ "pl-pl": {
+ "line1": "Potrzeba aktual."
+ },
+ "pt-br": {
+ "line1": "Atualiz. necess."
+ },
+ "pt-pt": {
+ "line1": "Actual. necess."
+ },
+ "ru-ru": {
+ "line1": "Необх. обновл."
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs"
+ },
+ "tr-tr": {
+ "line1": "Güncellenmeli"
+ },
+ "zh-cn": {
+ "line1": "需要进行更新"
+ },
+ "zh-tw": {
+ "line1": "需更新"
+ }
+ }
+ },
+ "StatusPending": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktualisieren..."
+ },
+ "en-au": {
+ "line1": "Updating..."
+ },
+ "en-gb": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "en-ie": {
+ "line1": "Updating..."
+ },
+ "en-us": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "es-en": {
+ "line1": "Actualizando...",
+ "textBody": "Actualizando..."
+ },
+ "es-es": {
+ "line1": "Actualizando..."
+ },
+ "es-mx": {
+ "line1": "Actualizando...",
+ "textBody": "Actualizando..."
+ },
+ "fr-ca": {
+ "line1": "MAJ en cours...",
+ "textBody": "MAJ en cours..."
+ },
+ "fr-fr": {
+ "line1": "Màj en cours..."
+ },
+ "it-it": {
+ "line1": "Aggiornamento"
+ },
+ "nl-nl": {
+ "line1": "Updaten..."
+ },
+ "pl-pl": {
+ "line1": "Aktualizowanie"
+ },
+ "pt-br": {
+ "line1": "Atualizando..."
+ },
+ "pt-pt": {
+ "line1": "A actualizar..."
+ },
+ "ru-ru": {
+ "line1": "Обновление..."
+ },
+ "sv-se": {
+ "line1": "Uppdaterar..."
+ },
+ "tr-tr": {
+ "line1": "Güncelleniyor..."
+ },
+ "zh-cn": {
+ "line1": "正在更新......"
+ },
+ "zh-tw": {
+ "line1": "更新中..."
+ }
+ }
+ },
+ "StatusUpToDate": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktuelle Version"
+ },
+ "en-au": {
+ "line1": "Up-to-date"
+ },
+ "en-gb": {
+ "line1": "Up-to-date",
+ "textBody": "Up-to-date"
+ },
+ "en-ie": {
+ "line1": "Up-to-date"
+ },
+ "en-us": {
+ "line1": "Up-To-Date",
+ "textBody": "Up-To-Date"
+ },
+ "es-en": {
+ "line1": "Actualizado",
+ "textBody": "Actualizado"
+ },
+ "es-es": {
+ "line1": "Actualizada"
+ },
+ "es-mx": {
+ "line1": "Actualizado",
+ "textBody": "Actualizado"
+ },
+ "fr-ca": {
+ "line1": "Déjà à jour",
+ "textBody": "Déjà à jour"
+ },
+ "fr-fr": {
+ "line1": "Déjà à jour"
+ },
+ "it-it": {
+ "line1": "più recente"
+ },
+ "nl-nl": {
+ "line1": "Up-to-date"
+ },
+ "pl-pl": {
+ "line1": "Aktualne"
+ },
+ "pt-br": {
+ "line1": "Atualizado"
+ },
+ "pt-pt": {
+ "line1": "Actualizado"
+ },
+ "ru-ru": {
+ "line1": "Обновлено"
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs ej"
+ },
+ "tr-tr": {
+ "line1": "Güncel"
+ },
+ "zh-cn": {
+ "line1": "最新更新"
+ },
+ "zh-tw": {
+ "line1": "更新最新"
+ }
+ }
+ },
+ "VehicleInfo": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahrzeuginformationen: Kraftstoff-Füllstand, Kraftstoffverbrauch, Motordrehzahl, Kilometerzähler, FIN, Außentemperatur, Gangstellung, Reifenluftdruck.",
+ "label": "Fahrzeuginformationen"
+ },
+ "en-au": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-gb": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure."
+ },
+ "en-ie": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-us": {
+ "tts": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo",
+ "textBody": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a la siguiente información del vehículo: Nivel de combustible, Ahorro de combustible, RPM del motor, Cuentakilómetros, VIN, Temperatura aire exterior, Marcha engranada, Presión de neumáticos.",
+ "label": "Información del vehículo"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo",
+ "textBody": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus.",
+ "label": "Renseignements du véhicule",
+ "textBody": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Vitesse de moteur, Compteur kilométrique, NIV, Température extérieure, Position de vitesse, Pression des pneus.",
+ "label": "Renseignements du véhicule"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti informazioni del veicolo: Livello carburante, Consumi carburante, Numero giri motore, Contachilometri, VIN, Temperatura esterna, Posizione marcia, Pressione pneumatici.",
+ "label": "Informazioni sul veicolo"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende voertuiginformatie: Brandstofpeil, Brandstofverbruik, Motortoerental, Kilometerteller, VIN, Buitentemperatuur, Versnellingsstand, Bandenspanning.",
+ "label": "Voertuiginformatie"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji o pojeździe: Poziom paliwa, Zużycie paliwa, Obroty silnika, Licznik przebiegu, Numer VIN, Temperatura zewnętrzna, Aktualny bieg, Ciśnienie opon.",
+ "label": "Informacje o pojeździe"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes informações sobre o veículo: Nível de combustível, Economia de combustível, RPM do motor, Hodômetro, VIN, Temperatura externa, Posição das marchas, Pressão dos pneus.",
+ "label": "Informações sobre o veículo"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações do veículo: Nível de combustível, Poupança de combustível, RPM do motor, Conta-quilómetros, VIN, Temperatura exterior, Posição da mudança de velocidade, Pressão dos pneus.",
+ "label": "Informações do veículo"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим данным автомобиля: Уровень топлива, Економия топлива, Число оборотов двигателя, Одометр, Номер VIN, Температура за бортом, Положение передачи, Давление шин.",
+ "label": "Информация об автомобиле"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande fordonsinformation: Bränslenivå, Bränsleekonomi, Motorns varvtal, Vägmätare, VIN, Utetemperatur, Växelläge, Däcktryck.",
+ "label": "Fordonsinformation"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu araç bilgilerine erişebilir: Yakıt seviyesi, Yakıt ekonomisi, Motor devirleri, Kilometre sayacı, VIN, Dış sıcaklık, Vites konumu, Lastik basıncı.",
+ "label": "Araç bilgisi"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列车辆信息 : 燃油量, 燃油经济性, 发动机转速(RPM), 里程表, VIN, 车外温度, 档位, 胎压.",
+ "label": "车辆信息"
+ },
+ "zh-tw": {
+ "tts": "一個應用程式可存取以下車輛資訊 : 燃油存量, 燃油經濟性, 引擎轉速, 里程表, 車輛識別號碼, 車外溫度, 檔位, 胎壓.",
+ "label": "車輛資訊"
+ }
+ }
+ }
+ }
+ },
+ "app_policies": {
+ "default": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "EMERGENCY",
+ "default_hmi": "LIMITED",
+ "groups": [
+ "Base-4"
+ ],
+ "RequestType": [
+ "QUERY_APPS",
+ "LAUNCH_APP",
+ "PROPRIETARY"
+ ]
+ },
+ "device": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": [
+ "DataConsent-2"
+ ],
+ "preconsented_groups": [
+ "BaseBeforeDataConsent"
+ ]
+ },
+ "pre_DataConsent": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": [
+ "BaseBeforeDataConsent"
+ ],
+ "RequestType": [
+ "QUERY_APPS",
+ "LAUNCH_APP",
+ "PROPRIETARY"
+ ]
+ },
+ "584421907": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": [
+ "BaseBeforeDataConsent"
+ ],
+ "RequestType": [
+ "TRAFFIC_MESSAGE_CHANNEL",
+ "QUERY_APPS",
+ "LAUNCH_APP",
+ "PROPRIETARY"
+ ]
+ }
+ }
+ }
+}
diff --git a/src/components/policy/test/ptu_requestType.json b/src/components/policy/test/ptu_requestType.json
new file mode 100644
index 0000000000..44bd8356fe
--- /dev/null
+++ b/src/components/policy/test/ptu_requestType.json
@@ -0,0 +1,2610 @@
+{
+ "policy_table": {
+ "module_config": {
+ "preloaded_pt": true,
+ "preloaded_date": "2015-12-02",
+ "exchange_after_x_ignition_cycles": 100,
+ "exchange_after_x_kilometers": 1800,
+ "exchange_after_x_days": 30,
+ "timeout_after_x_seconds": 60,
+ "seconds_between_retries": [
+ 1,
+ 5,
+ 25,
+ 125,
+ 625
+ ],
+ "endpoints": {
+ "0x07": {
+ "default": [
+ "http://policies.telematics.ford.com/api/policies"
+ ]
+ },
+ "0x04": {
+ "default": [
+ "http://ivsu.software.ford.com/api/getsoftwareupdates"
+ ]
+ }
+ },
+ "notifications_per_minute_by_priority": {
+ "EMERGENCY": 60,
+ "NAVIGATION": 15,
+ "VOICECOM": 20,
+ "COMMUNICATION": 6,
+ "NORMAL": 4,
+ "NONE": 0
+ }
+ },
+ "functional_groupings": {
+ "Base-4": {
+ "rpcs": {
+ "AddCommand": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "AddSubMenu": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "Alert": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ChangeRegistration": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "CreateInteractionChoiceSet": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "DeleteCommand": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "DeleteFile": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "DeleteInteractionChoiceSet": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "DeleteSubMenu": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "EndAudioPassThru": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "GenericResponse": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ListFiles": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnAudioPassThru": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnButtonEvent": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED",
+ "BACKGROUND"
+ ]
+ },
+ "OnButtonPress": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED",
+ "BACKGROUND"
+ ]
+ },
+ "OnCommand": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnDriverDistraction": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnHashChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "PerformAudioPassThru": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "PerformInteraction": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "PutFile": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "ResetGlobalProperties": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "ScrollableMessage": {
+ "hmi_levels": [
+ "FULL"
+ ]
+ },
+ "SetAppIcon": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetGlobalProperties": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetMediaClockTimer": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED",
+ "BACKGROUND"
+ ]
+ },
+ "Show": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "Slider": {
+ "hmi_levels": [
+ "FULL"
+ ]
+ },
+ "Speak": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "SubscribeButton": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "SystemRequest": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "UnsubscribeButton": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "Location-1": {
+ "user_consent_prompt": "Location",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "gps",
+ "speed"
+ ]
+ },
+ "OnVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "gps",
+ "speed"
+ ]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "gps",
+ "speed"
+ ]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "gps",
+ "speed"
+ ]
+ }
+ }
+ },
+ "Notifications": {
+ "user_consent_prompt": "Notifications",
+ "rpcs": {
+ "Alert": {
+ "hmi_levels": [
+ "BACKGROUND"
+ ]
+ }
+ }
+ },
+ "DrivingCharacteristics-3": {
+ "user_consent_prompt": "DrivingCharacteristics",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "OnVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ }
+ }
+ },
+ "VehicleInfo-3": {
+ "user_consent_prompt": "VehicleInfo",
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"
+ ]
+ },
+ "OnVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"
+ ]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"
+ ]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "bodyInformation",
+ "deviceStatus",
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"
+ ]
+ }
+ }
+ },
+ "PropriataryData-1": {
+ "rpcs": {
+ "DiagnosticMessage": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "GetDTCs": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ReadDID": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "PropriataryData-2": {
+ "rpcs": {
+ "DiagnosticMessage": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "GetDTCs": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ReadDID": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "ProprietaryData-3": {
+ "rpcs": {
+ "GetDTCs": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ReadDID": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "Emergency-1": {
+ "rpcs": {
+ "GetVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "OnVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "SubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "UnsubscribeVehicleData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ],
+ "parameters": [
+ "airbagStatus",
+ "clusterModeStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ }
+ }
+ },
+ "Navigation-1": {
+ "rpcs": {
+ "AlertManeuver": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ShowConstantTBT": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "UpdateTurnList": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "Base-6": {
+ "rpcs": {
+ "AddCommand": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "AddSubMenu": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "Alert": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ChangeRegistration": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "CreateInteractionChoiceSet": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "DeleteCommand": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "DeleteFile": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "DeleteInteractionChoiceSet": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "DeleteSubMenu": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "EndAudioPassThru": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "GenericResponse": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ListFiles": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnAudioPassThru": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnButtonEvent": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnButtonPress": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnCommand": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnDriverDistraction": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnSyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnTBTClientState": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "PerformAudioPassThru": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "PerformInteraction": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "PutFile": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "ResetGlobalProperties": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "ScrollableMessage": {
+ "hmi_levels": [
+ "FULL"
+ ]
+ },
+ "SetAppIcon": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetGlobalProperties": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "SetMediaClockTimer": {
+ "hmi_levels": [
+ "FULL"
+ ]
+ },
+ "Show": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "Slider": {
+ "hmi_levels": [
+ "FULL"
+ ]
+ },
+ "Speak": {
+ "hmi_levels": [
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "SubscribeButton": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ },
+ "SyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "UnsubscribeButton": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "OnKeyboardInputOnlyGroup": {
+ "rpcs": {
+ "OnKeyboardInput": {
+ "hmi_levels": [
+ "FULL"
+ ]
+ }
+ }
+ },
+ "OnTouchEventOnlyGroup": {
+ "rpcs": {
+ "OnTouchEvent": {
+ "hmi_levels": [
+ "FULL"
+ ]
+ }
+ }
+ },
+ "DiagnosticMessageOnly": {
+ "rpcs": {
+ "DiagnosticMessage": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "DataConsent-2": {
+ "user_consent_prompt": "DataConsent",
+ "rpcs": null
+ },
+ "BaseBeforeDataConsent": {
+ "rpcs": {
+ "ChangeRegistration": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "DeleteFile": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "EncodedSyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "ListFiles": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnAppInterfaceUnregistered": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnEncodedSyncPData": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnHashChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnHMIStatus": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnLanguageChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnPermissionsChange": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "OnSystemRequest": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "PutFile": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "RegisterAppInterface": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "ResetGlobalProperties": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetGlobalProperties": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetAppIcon": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SetDisplayLayout": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "SystemRequest": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ },
+ "UnregisterAppInterface": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED",
+ "NONE"
+ ]
+ }
+ }
+ },
+ "SendLocation": {
+ "rpcs": {
+ "SendLocation": {
+ "hmi_levels": [
+ "BACKGROUND",
+ "FULL",
+ "LIMITED"
+ ]
+ }
+ }
+ },
+ "BackgroundAPT": {
+ "rpcs": {
+ "EndAudioPassThru": {
+ "hmi_levels": [
+ "BACKGROUND"
+ ]
+ },
+ "OnAudioPassThru": {
+ "hmi_levels": [
+ "BACKGROUND"
+ ]
+ },
+ "PerformAudioPassThru": {
+ "hmi_levels": [
+ "BACKGROUND"
+ ]
+ }
+ }
+ }
+ },
+ "consumer_friendly_messages": {
+ "version": "001.001.021",
+ "messages": {
+ "AppPermissions": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% benötigt die folgenden Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Wenn Sie Ja drücken, erklären Sie sich damit einverstanden, dass %vehicleMake% nicht für Schäden oder Verletzungen der Privatsphäre haftet, die im Zusammenhang mit der Nutzung Ihrer Benutzerdaten durch %appName% entstehen. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab.",
+ "line1": "Zugriffsanfrage(n)",
+ "line2": "erlauben?"
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%`s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny.",
+ "line1": "Grant requested",
+ "line2": "permission(s)?"
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. Please press yes to allow or no to deny.",
+ "line1": "Grant Requested",
+ "line2": "Permission(s)?",
+ "textBody": "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. \n\nIf you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%’s use of your data. You can change these permissions and hear detailed descriptions in the mobile apps settings menu."
+ },
+ "es-en": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?",
+ "textBody": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar. \n\n Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando el uso de los siguientes permisos e información del vehículo: %functionalGroupLabels%. Si pulsa sí, acepta que %vehicleMake% no será responsable de los daños o la pérdida de privacidad relacionados con el uso de sus datos por parte de %appName%. Pulse sí para permitir o no para denegar.",
+ "line1": "¿Conceder permisos",
+ "line2": "solicitados?"
+ },
+ "es-mx": {
+ "tts": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar.",
+ "line1": "¿Otorgar permiso(s)",
+ "line2": "solicitado(s)?",
+ "textBody": "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. \n\nSi presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles."
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)",
+ "textBody": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser.",
+ "line1": "Accorder permission(s)",
+ "line2": "demandée(s)"
+ },
+ "it-it": {
+ "tts": "%appName% richiede l'uso delle seguenti informazioni e autorizzazioni sul veicolo: %functionalGroupLabels%. Se si preme Sì, si acconsente che %vehicleMake% non sarà responsabile per danni o perdita di privacy in relazione all'impiego dei dati da parte di %appName%. Premere Sì per consentire e No per negare.",
+ "line1": "Concedi autorizzaz.",
+ "line2": "richiesta(e)?"
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. Als u op Ja drukt, gaat u ermee akkoord dat %vehicleMake% in geen geval aansprakelijk gesteld kan worden voor schade of verlies van privacy als gevolg van het feit dat %appName% gebruik maakt van uw gegevens. Druk op Ja om dit toe te staan of Nee om te weigeren.",
+ "line1": "Aangevraagde",
+ "line2": "permissie(s) verlenen?"
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz pozwoleń: %functionalGroupLabels%. Naciśnięcie TAK oznacza zgodę na fakt, iż %vehicleMake% nie będzie ponosić odpowiedzialności za szkody ani utratę prywatności w związku z wykorzystaniem przez %appName% danych, należących do użytkownika. Naciśnij TAK w celu udzielenia zgody lub NIE w celu odrzucenia żądania.",
+ "line1": "Udzielić żądanych",
+ "line2": "pozwoleń?"
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando o uso das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se pressionar sim, você concorda que a %vehicleMake% não será responsável por danos ou perdas de privacidade relacionados ao uso dos seus dados por %appName%. Pressione sim para permitir ou não para negar.",
+ "line1": "Conceder permissão",
+ "line2": "solicitada?"
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar a utilização das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se premir “Sim”, concorda que %vehicleMake% não será responsável por quaisquer danos ou perda de privacidade relacionada com a utilização dos seus dados por parte de %appName%. Prima “Sim” para permitir ou “Não” para recusar.",
+ "line1": "Conceder permiss.",
+ "line2": "solicitada(s)?"
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Нажатием \"\"да\"\", Вы соглашаетесь, что %vehicleMake% не будет нести ответственность за какие-либо убытки или потерю прайвеси, связанные с использованием Ваших данных компанией %appName%. Нажмите \"\"Да\"\", если Вы согласны, или \"\"Нет\"\" - если не согласны.",
+ "line1": "Предост. заправш.",
+ "line2": "разрешения?"
+ },
+ "sv-se": {
+ "tts": "%appName% begär att få tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Om du trycker Ja godkänner du att %vehicleMake% ska hållas skadeslös för alla skador som kan uppstå eller eventuella integritetsintrång som uppstår när %appName% använder dina data. Tryck Ja för att godkänna eller Nej för att neka.",
+ "line1": "Vill du ge",
+ "line2": "tillstånd?"
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri kullanma isteğinde bulunuyor: %functionalGroupLabels%. Evet'e basarsanız, %appName%'in verilerinizi kullanması sonucunda oluşabilecek hasarlardan veya gizlilik kaybından %vehicleMake%'in sorumlu olmayacağını kabul etmiş olacaksınız. Lütfen kabul etmek için Evet'e veya reddetmek için Hayır'a basın.",
+ "line1": "İstenen izinler",
+ "line2": "verilsin mi?"
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求使用下列车辆信息和权限: %functionalGroupLabels%。如果您按“是”,则表示您同意。 %vehicleMake% 将不会对因 %appName% 使用您的数据而引起的任何损毁或隐私损失负责。 请按“是”允许或按“否”拒绝。",
+ "line1": "是否允许请求的",
+ "line2": "权限?"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。按「是」,表示您同意,如因 %appName% 使用您的資料導致任何損害或損失,%vehicleMake% 將不負賠償責任。同意請按「是」,拒絕請按「否」。",
+ "line1": "允許",
+ "line2": "授權請求?"
+ }
+ }
+ },
+ "AppPermissionsHelp": {
+ "languages": {
+ "de-de": {
+ "tts": "%appName% fordert folgende Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Im Einstellungsmenü der mobilen Apps können Sie diese Berechtigungen ändern und sich detaillierte Beschreibungen anhören. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-gb": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-ie": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-us": {
+ "tts": "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press yes to grant permissions or no to deny."
+ },
+ "es-en": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "es-es": {
+ "tts": "%appName% está solicitando los siguientes permisos e información del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y escuchar descripciones detalladas en el menú de configuración de la aplicación móvil. Pulse sí para conceder el permiso o no para denegarlo."
+ },
+ "es-mx": {
+ "tts": "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "fr-ca": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "fr-fr": {
+ "tts": "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "it-it": {
+ "tts": "%appName% richiede le seguenti informazioni e autorizzazioni riguardo il veicolo: %functionalGroupLabels%. È possibile modificare tali autorizzazioni e ascoltare descrizioni dettagliate nel menu impostazioni delle app mobili. Premere Sì per concedere le autorizzazioni e No per negarle."
+ },
+ "nl-nl": {
+ "tts": "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. U kunt deze toestemmingen wijzigen en gedetailleerde beschrijvingen beluisteren in het instellingenmenu voor mobiele apps. Druk op Ja om permissies te verlenen of op Nee om te weigeren."
+ },
+ "pl-pl": {
+ "tts": "%appName% wymaga następujących informacji o pojeździe oraz zezwoleń: %functionalGroupLabels%. W menu ustawień aplikacji mobilnych można zmienić owe zezwolenia i usłyszeć ich szczegółowy opis. Naciśnij TAK, aby wyrazić zgodę lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br": {
+ "tts": "%appName% está solicitando as seguintes informações e permissões do veículo: %functionalGroupLabels%. Você pode alterar estas permissões e ouvir descrições detalhadas no menu de configurações de aplicativos móveis. Pressione sim para conceder as permissões ou não para negar."
+ },
+ "pt-pt": {
+ "tts": "%appName% está a solicitar as seguintes informações e permissões do veículo: %functionalGroupLabels%. Pode alterar estas permissões e ouvir descrições detalhadas no menu de definições das aplicações móveis. Prima \"\"Sim\"\" para permitir ou \"\"Não\"\" para recusar."
+ },
+ "ru-ru": {
+ "tts": "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Вы можете изменить эти разрешения и прослушать подробные их описания в меню настроек мобильного приложения. Нажмите \"\"да\"\", чтобы предоставить разрешения, или \"\"нет\"\", чтобы не предоставлять."
+ },
+ "sv-se": {
+ "tts": "%appName% begär tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Du kan ändra tillstånden och höra detaljerade beskrivningar i menyn för mobilappsinställningar. Tryck Ja för att ge tillstånd eller Nej för att neka."
+ },
+ "tr-tr": {
+ "tts": "%appName%, şu araç bilgilerini ve izinleri istiyor: %functionalGroupLabels%. Bu izinleri değiştirebilir ve mobil uygulamalar ayarlar menüsünden ayrıntılı açıklamaları dinleyebilirsiniz. Lütfen izin vermek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn": {
+ "tts": "%appName% 正在请求下列车辆信息和权限: %functionalGroupLabels%。您可在移动应用程序设置菜单中更改这些权限,并听取详细说明。请按“是”允许权限或按“否”拒绝。"
+ },
+ "zh-tw": {
+ "tts": "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。您可在行動應用程式設定清單中更改這些許可,並聆聽詳細說明。給予許可請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsRevoked": {
+ "languages": {
+ "de-de": {
+ "tts": "Die Autorisierungsdaten der App wurden geändert. %appName% hat keinen Zugriff auf %functionalGroupLabels% mehr. Installieren Sie die neueste Version der App auf Ihrem Gerät.."
+ },
+ "en-au": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-gb": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-ie": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-us": {
+ "tts": "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "es-en": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "es-es": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de que tiene la versión más reciente de la aplicación instalada en su dispositivo móvil."
+ },
+ "es-mx": {
+ "tts": "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "fr-ca": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "fr-fr": {
+ "tts": "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "it-it": {
+ "tts": "Le autorizzazioni dell'app sono cambiate. %appName% non è più in grado di accedere a %functionalGroupLabels%. Assicurarsi di avere la versione più recente dell'app installata sul dispositivo mobile."
+ },
+ "nl-nl": {
+ "tts": "De app-autorisaties zijn gewijzigd. %appName% heeft geen toegang meer tot %functionalGroupLabels%. Zorg ervoor dat u de meest recente app-versie op uw mobiele apparaat geïnstalleerd hebt."
+ },
+ "pl-pl": {
+ "tts": "Dane dostępu aplikacji zostały zmienione. %appName% nie ma już dostępu do %functionalGroupLabels%. Sprawdź, czy na telefonie komórkowym zainstalowano najnowszą wersję aplikacji."
+ },
+ "pt-br": {
+ "tts": "As autorizações dos aplicativos foram alteradas. %appName% não pode mais acessar %functionalGroupLabels%. Certifique-se de que a versão mais recente do aplicativo está instalada no seu dispositivo móvel."
+ },
+ "pt-pt": {
+ "tts": "As autorizações das aplicações mudaram. %appName% já não consegue aceder a %functionalGroupLabels%. Certifique-se de que tem a última versão da aplicação no seu dispositivo móvel."
+ },
+ "ru-ru": {
+ "tts": "Авторизации приложения изменены. %appName% больше не имеет доступа к %functionalGroupLabels%. Убедитесь, что на вашем мобильном устройстве установлена самая новая версия приложения."
+ },
+ "sv-se": {
+ "tts": "Appens behörigheter har ändrats. %appName% har inte längre åtkomst till %functionalGroupLabels%. Kontrollera att du har installerat den senaste versionen av appen på mobilenheten."
+ },
+ "tr-tr": {
+ "tts": "Uygulama yetkileri değişti. %appName% artık %functionalGroupLabels%'e erişemeyecek. Lütfen mobil aygıtınızda en son uygulama sürümünün yüklü olduğundan emin olun."
+ },
+ "zh-cn": {
+ "tts": "应用程序授权已变更。 %appName% 将不能再访问 %functionalGroupLabels%。 请确认您的移动设备上安装的应用程序是最新版本。"
+ },
+ "zh-tw": {
+ "tts": "應用程式授權已改變。%appName% 已無法進入 %functionalGroupLabels%。請確認您的行動裝置上安裝了最新版應用程式。"
+ }
+ }
+ },
+ "AppUnauthorized": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% ist nicht autorisiert und wird nicht mit SYNC funktionieren.",
+ "line1": "nicht autorisiert"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized",
+ "textBody": "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "not authorized"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not authorized and will not work with SYNC.",
+ "line1": "Not Authorized",
+ "textBody": "This version of %appName% is no longer authorized to work with AppLink. Please update to the latest version of %appName%."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada",
+ "textBody": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no está autorizada y no funcionará con SYNC.",
+ "line1": "No autorizada"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC.",
+ "line1": "no autorizada",
+ "textBody": "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée",
+ "textBody": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC.",
+ "line1": "non autorisée"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è autorizzata e non funziona con il SYNC.",
+ "line1": "non autorizzata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% is niet geautoriseerd en werkt niet met SYNC.",
+ "line1": "niet geautoriseerd"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie posiada autoryzacji i nie będzie działać z SYNC.",
+ "line1": "brak autoryzacji"
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não tem autorização e não funcionará com o SYNC.",
+ "line1": "não autorizado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não está autorizada e não funcionará com o SYNC.",
+ "line1": "não autorizada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не авторизирована и не будет работать с SYNC.",
+ "line1": "не авторизировано"
+ },
+ "sv-se": {
+ "tts": "Den här versionen av %appName% är inte godkänd och fungerar inte med SYNC.",
+ "line1": "är ej godkänd"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümüne izin verilmediğinden SYNC ile çalışamaz.",
+ "line1": "için izin yok"
+ },
+ "zh-cn": {
+ "tts": "此版本的%appName% 未得到授权,无法在SYNC上使用。",
+ "line1": "未得到授权"
+ },
+ "zh-tw": {
+ "tts": "%appName% 的版本未獲得授權,將無法透過 SYNC 使用。",
+ "line1": "無授權"
+ }
+ }
+ },
+ "AppUnsupported": {
+ "languages": {
+ "de-de": {
+ "tts": "Diese Version von %appName% wird von SYNC nicht unterstützt.",
+ "line1": "nicht unterstützt"
+ },
+ "en-au": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-gb": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported",
+ "textBody": "This version of %appName% is not supported by SYNC."
+ },
+ "en-ie": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "not supported"
+ },
+ "en-us": {
+ "tts": "This version of %appName% is not supported by SYNC.",
+ "line1": "Not Supported",
+ "textBody": "Your version of %appName% is not supported by SYNC."
+ },
+ "es-en": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible",
+ "textBody": "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-es": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "No compatible"
+ },
+ "es-mx": {
+ "tts": "Esta versión de %appName% no es compatible con SYNC.",
+ "line1": "no compatible",
+ "textBody": "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "fr-ca": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible",
+ "textBody": "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "fr-fr": {
+ "tts": "Cette version de %appName% n’est pas prise en charge par SYNC.",
+ "line1": "incompatible"
+ },
+ "it-it": {
+ "tts": "Questa versione di %appName% non è supportata dal SYNC.",
+ "line1": "non supportata"
+ },
+ "nl-nl": {
+ "tts": "Deze versie van %appName% wordt niet ondersteund door SYNC.",
+ "line1": "niet ondersteund"
+ },
+ "pl-pl": {
+ "tts": "Niniejsza wersja %appName% nie jest obsługiwana przez system SYNC.",
+ "line1": "aplikacja nie obsług."
+ },
+ "pt-br": {
+ "tts": "Esta versão do %appName% não é suportada pelo SYNC.",
+ "line1": "não suportado"
+ },
+ "pt-pt": {
+ "tts": "Esta versão de %appName% não é suportado pelo SYNC.",
+ "line1": "não suportada"
+ },
+ "ru-ru": {
+ "tts": "Эта версия %appName% не поддерживается SYNC.",
+ "line1": "не поддерживается"
+ },
+ "sv-se": {
+ "tts": "SYNC har inte stöd för den här versionen av %appName%.",
+ "line1": "stöds ej"
+ },
+ "tr-tr": {
+ "tts": "Bu %appName% sürümü SYNC tarafından desteklenmiyor.",
+ "line1": "desteklenmiyor"
+ },
+ "zh-cn": {
+ "tts": "SYNC不支持此版本的%appName%。",
+ "line1": "不受支持"
+ },
+ "zh-tw": {
+ "tts": "SYNC 不支援此版本的%appName% 。",
+ "line1": "不支援"
+ }
+ }
+ },
+ "DataConsent": {
+ "languages": {
+ "en-gb": {
+ "textBody": "Would you like to enable Mobile Apps on SYNC? To use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S. \r\n\r\nUpdates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "en-us": {
+ "line1": "Enable Mobile Apps",
+ "line2": "on SYNC? (Uses Data)",
+ "textBody": "Would you like to enable Mobile Apps on SYNC?\r\n\r\nTo use Mobile Apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device’s data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S.\r\n\r\nUpdates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC Settings menu. See your Owner Guide for more information."
+ },
+ "es-mx": {
+ "textBody": "Para usar aplicaciones móviles con SYNC, este debe comunicarse con Ford al menos una vez al mes a través del plan de datos de su dispositivo móvil. Pueden aplicar tarifas normales. SYNC enviará su VIN y el número de módulo de SYNC a Ford de Estados Unidos de América. \n\nLas actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario. \n\nPresione Sí para permitir y No para denegar."
+ },
+ "fr-ca": {
+ "textBody": "Pour utiliser AppLink, SYNC devra communiquer avec Ford au moins une fois par mois en utilisant le forfait de données de votre appareil mobile. Les tarifs réguliers peuvent s’appliquer. SYNC enverra votre NIV et le numéro de votre module SYNC à Ford États-Unis. Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements.\r\n\r\nVeuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ }
+ }
+ },
+ "DataConsentHelp": {
+ "languages": {
+ "en-us": {
+ "textBody": "By enabling mobile apps, you consent to allowing SYNC to communicate with Ford at least once per month using your mobile device’s data plan. Disabling will stop all data usage, but you will not be able to use mobile apps on SYNC. See your Owner Guide for more information."
+ },
+ "es-mx": {
+ "textBody": "Las actualizaciones tienen el tamaño aproximado de un mensaje de correo electrónico, y la frecuencia de las actualizaciones depende del uso de su vehículo y de si se encuentran nuevas aplicaciones en su dispositivo. Para obtener más información, consulte la Guía del propietario."
+ },
+ "fr-ca": {
+ "textBody": "Les mises à jour ont la taille d’un courriel et la fréquence des mises à jour dépend de l’utilisation de votre véhicule et si une nouvelle application se trouve sur votre appareil. Consultez le Guide de l’utilisateur pour obtenir d’autres renseignements."
+ }
+ }
+ },
+ "DisableApps": {
+ "languages": {
+ "de-de": {
+ "tts": "Ausschalten der automatischen Updates führt zum Ausschalten von SYNC mobile Apps. Sie können Ihre mobilen Apps dann nicht mehr mit SYNC nutzen. Bitte drücken Sie Ja zur Bestätigung oder Nein, um abzubrechen.",
+ "line1": "Auto-Update",
+ "line2": "und Mobile Apps deaktivieren"
+ },
+ "en-au": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-gb": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-ie": {
+ "tts": "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel.",
+ "line1": "Disable auto-updates",
+ "line2": "and Mobile Apps?"
+ },
+ "en-us": {
+ "tts": "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel.",
+ "line1": "Disable Auto-Updates",
+ "line2": "and Mobile Apps?",
+ "textBody": "If you disable, you will not be able to use any mobile apps with SYNC and your vehicle will stop receiving mobile app permission updates via your device`s data plan. Please press yes to disable mobile apps or no to cancel."
+ },
+ "es-en": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?",
+ "textBody": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "es-es": {
+ "tts": "Si desactiva las actualizaciones automáticas, también se desactivará la sincronización de las aplicaciones móviles. No podrá utilizar ninguna aplicación móvil con SYNC. Pulse sí para confirmar o no para cancelar.",
+ "line1": "¿Desact. actual. auto",
+ "line2": "y apl. móviles?"
+ },
+ "es-mx": {
+ "tts": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar.",
+ "line1": "¿Deshab. actualiz.",
+ "line2": "autom. y aplic. móv.?",
+ "textBody": "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "fr-ca": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?",
+ "textBody": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "fr-fr": {
+ "tts": "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler.",
+ "line1": "Désactiver màj autom.",
+ "line2": "et app. mobiles?"
+ },
+ "it-it": {
+ "tts": "Disabilitando gli aggiornamenti automatici si disattiva anche la sincronizzazione delle app mobili. Non sarà possibile usare app mobili con il SYNC. Premere Sì per confermare e No per cancellare.",
+ "line1": "Disabilitare agg. aut.",
+ "line2": "e app mobili?"
+ },
+ "nl-nl": {
+ "tts": "Door automatische updates uit te schakelen, schakelt u ook SYNC-mobiele apps uit. U kunt dan geen mobiele apps meer gebruiken met SYNC. Druk op Ja om te bevestigen of op Nee om te annuleren.",
+ "line1": "Auto-updates en mob.",
+ "line2": "apps uitschakelen?"
+ },
+ "pl-pl": {
+ "tts": "Wyłączenie automatycznych aktualizacji spowoduje także wyłączenie aplikacji mobilnych SYNC. Korzystanie z mobilnych aplikacji za pomocą SYNC będzie niemożliwe. Naciśnij TAK, by potwierdzić lub NIE, by anulować.",
+ "line1": "Wył. automat. aktual.",
+ "line2": "i aplikacje mobilne?"
+ },
+ "pt-br": {
+ "tts": "Se as atualizações automáticas forem desativadas, os aplicativos também serão desativados. Você não poderá usar nenhum aplicativo com o SYNC. Pressione sim para confirmar ou não para cancelar.",
+ "line1": "Desativar atualizações",
+ "line2": "autom. e aplicativos?"
+ },
+ "pt-pt": {
+ "tts": "A desactivação das actualizações automáticas desactiva igualmente as aplicações móveis do SYNC. Não poderá utilizar quaisquer aplicações móveis com o SYNC. Prima \"\"Sim\"\" para confirmar ou \"\"Não\"\" para cancelar.",
+ "line1": "Desact. actual. autom.",
+ "line2": "e aplicações móveis?"
+ },
+ "ru-ru": {
+ "tts": "При отключении автоматических обновлений также будут отключены мобильные приложения sync. Вы не сможете использовать какие-либо мобильные приложения с SYNC. Нажмите \"\"Да\"\" для подтверждения или \"\"Нет\"\" для отмены.",
+ "line1": "Откл. автообновления",
+ "line2": "и мобил. прилож.?"
+ },
+ "sv-se": {
+ "tts": "Om du avaktiverar automatisk uppdatering avaktiverar du även synkning av mobilappar. Du kommer inte längre att kunna använda dina mobilappar med SYNC. Tryck Ja för att bekräfta eller Nej för att avbryta.",
+ "line1": "Avaktiverar autouppdat.",
+ "line2": "och mobilappar?"
+ },
+ "tr-tr": {
+ "tts": "Otomatik güncellemeleri devre dışı bırakırsanız sync mobil uygulamalar da devre dışı kalır. SYNC ile mobil uygulama kullanmanız mümkün olmaz. Lütfen onaylamak için Evet'e veya iptal etmek için Hayır'a basın.",
+ "line1": "Oto. güncelleme ve",
+ "line2": "mobil uygul. kapat?"
+ },
+ "zh-cn": {
+ "tts": "禁用自动更新同时也会禁用SYNC移动应用程序。您将无法在 SYNC 中使用任何移动应用程序。请按“是”确认或按“否”取消。",
+ "line1": "是否禁用自动更新和",
+ "line2": "移动应用程序?"
+ },
+ "zh-tw": {
+ "tts": "停用自動更新也將停用 sync 行動應用程式。您將無法透過 SYNC 使用任何行動應用程式。確認請按「是」,取消請按「否」。",
+ "line1": "停用自動更新",
+ "line2": "和行動應用程式?"
+ }
+ }
+ },
+ "DrivingCharacteristics": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahreigenschaften: Kraftstoffverbrauch, MyKey, Sicherheitsgurtstatus.",
+ "label": "Fahreigenschaften"
+ },
+ "en-au": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-gb": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-ie": {
+ "tts": "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status.",
+ "label": "Driving characteristics"
+ },
+ "en-us": {
+ "tts": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status.",
+ "label": "Driving Characteristics",
+ "textBody": "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo",
+ "textBody": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a las siguientes características de conducción: Consumo de combustible, MyKey, Estado cinturones de seguridad.",
+ "label": "Características de conducción"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad.",
+ "label": "Características del manejo",
+ "textBody": "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite",
+ "textBody": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité.",
+ "label": "Caractéristiques de conduite"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti caratteristiche di guida: Consumo carburante, MyKey, Stato cinture di sicurezza.",
+ "label": "Caratteristiche di guida"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende rijkenmerken: Brandstofverbruik, MyKey, Veiligheidsgordelstatus.",
+ "label": "Rijkenmerken"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji dotyczących jazdy: Zużycie paliwa, MyKey, Stan pasów bezpieczeństwa.",
+ "label": "Informacje dotyczące stylu jazdy"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes características de condução: Consumo de combustível, MyKey, Estado do cinto de segurança.",
+ "label": "Características de condução"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações de condução: Consumo de combustível, MyKey, Estado dos cintos de segurança.",
+ "label": "Características de condução"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим характеристикам движения: Расход топлива, MyKey, Состояние ремней безопасности.",
+ "label": "Характеристики движения"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande köregenskaper: Bränsleförbrukning, MyKey, Bältesstatus.",
+ "label": "Köregenskaper"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu sürüş karakteristiklerine erişebilir: Yakıt tüketimi, MyKey, Emniyet kemeri durumu.",
+ "label": "Sürüş karakteristikleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列行驶特性: 油耗, MyKey, 安全带状态",
+ "label": "行驶特性"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取以下駕駛特性: 油耗, MyKey, 安全帶狀態",
+ "label": "駕駛特性"
+ }
+ }
+ },
+ "Location": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die GPS-Daten und die Geschwindigkeit des Fahrzeugs.",
+ "label": "GPS und Geschwindigkeit"
+ },
+ "en-au": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-gb": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "en-ie": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed"
+ },
+ "en-us": {
+ "tts": "An app can access vehicle GPS and speed.",
+ "label": "GPS and speed",
+ "textBody": "An app can access vehicle GPS and speed."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad",
+ "textBody": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder al GPS y la velocidad del vehículo.",
+ "label": "GPS y velocidad"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo.",
+ "label": "GPS y velocidad",
+ "textBody": "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse",
+ "textBody": "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder au GPS et à la vitesse du véhicule.",
+ "label": "GPS et vitesse"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso a GPS e velocità del veicolo.",
+ "label": "GPS e velocità"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot gps en de snelheid van het voertuig.",
+ "label": "Gps en snelheid"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do modułu GPS i prędkości pojazdu.",
+ "label": "GPS i prędkość"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar o GPS e a velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder ao GPS e à velocidade do veículo.",
+ "label": "GPS e velocidade"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к GPS и скорости автомобиля.",
+ "label": "GPS и скорость"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt fordonets GPS och hastighetsmätare.",
+ "label": "GPS och hastighet"
+ },
+ "tr-tr": {
+ "tts": "Bu uygulama aracın GPS ve hız bilgilerine erişebilir.",
+ "label": "GPS ve hız"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可以访问车辆 GPS 和车速信息。",
+ "label": "GPS 和车速"
+ },
+ "zh-tw": {
+ "tts": "應用程式可存取車輛的GPS和速度。",
+ "label": "GPS和車速"
+ }
+ }
+ },
+ "Notifications": {
+ "languages": {
+ "de-de": {
+ "tts": "Läuft die App im Hintergrund, kann Sie Benachrichtigungen senden.",
+ "label": "Push-Benachrichtigungen"
+ },
+ "en-au": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-gb": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "en-ie": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications"
+ },
+ "en-us": {
+ "tts": "An app can send notifications when running in the background.",
+ "label": "Push notifications",
+ "textBody": "An app can send notifications when running in the background."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push",
+ "textBody": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede enviar notificaciones cuando se está ejecutando en segundo plano.",
+ "label": "Notificaciones push"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano.",
+ "label": "Notificaciones tipo Push",
+ "textBody": "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "fr-ca": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications instantanées",
+ "textBody": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "fr-fr": {
+ "tts": "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan.",
+ "label": "Notifications push"
+ },
+ "it-it": {
+ "tts": "Un'app può inviare notifiche se eseguita in background.",
+ "label": "Notifiche push"
+ },
+ "nl-nl": {
+ "tts": "Een app kan meldingen versturen als deze op de achtergrond actief is.",
+ "label": "Push-meldingen"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może wysyłać powiadomienia, działając w tle.",
+ "label": "Powiadomienia Push"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode enviar notificações quando estiver sendo executado em segundo plano.",
+ "label": "Notificações Push"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue enviar notificações quando está activa em segundo plano.",
+ "label": "Notificações push"
+ },
+ "ru-ru": {
+ "tts": "Если приложение работает в фоновом режиме, оно может отправлять оповещения.",
+ "label": "Оповещения о пересылке"
+ },
+ "sv-se": {
+ "tts": "Appen kan skicka meddelanden när den körs i bakgrunden.",
+ "label": "Push-notiser"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama arka planda çalışırken bildirim gönderebilir.",
+ "label": "Anlık bildirimleri"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序在后台运行时可推送通知。",
+ "label": "推送通知"
+ },
+ "zh-tw": {
+ "tts": "車輛行進時,應用程式可在背景中傳送通知。",
+ "label": "傳送通知"
+ }
+ }
+ },
+ "SettingDisableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Updates deakt."
+ },
+ "en-au": {
+ "line1": "Disable updates"
+ },
+ "en-gb": {
+ "line1": "Disable updates"
+ },
+ "en-ie": {
+ "line1": "Disable updates"
+ },
+ "en-us": {
+ "line1": "Disable Updates",
+ "textBody": "Disable Updates"
+ },
+ "es-en": {
+ "line1": "Deshab. actual.",
+ "textBody": "Deshab. actual."
+ },
+ "es-es": {
+ "line1": "Desact. actual."
+ },
+ "es-mx": {
+ "line1": "Deshab. actual.",
+ "textBody": "Deshab. actual."
+ },
+ "fr-ca": {
+ "line1": "Désactiver MAJ",
+ "textBody": "Désactiver MAJ"
+ },
+ "fr-fr": {
+ "line1": "Désactiver màj"
+ },
+ "it-it": {
+ "line1": "Disabilita agg."
+ },
+ "nl-nl": {
+ "line1": "Upd. uitschak."
+ },
+ "pl-pl": {
+ "line1": "Wyłącz aktual."
+ },
+ "pt-br": {
+ "line1": "Desat. atualiz."
+ },
+ "pt-pt": {
+ "line1": "Desact. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Откл. обновл."
+ },
+ "sv-se": {
+ "line1": "Inaktivera uppd."
+ },
+ "tr-tr": {
+ "line1": "Güncell. Kapat"
+ },
+ "zh-cn": {
+ "line1": "禁用更新"
+ },
+ "zh-tw": {
+ "line1": "停用更新"
+ }
+ }
+ },
+ "SettingEnableUpdates": {
+ "languages": {
+ "de-de": {
+ "line1": "Apps aktivieren"
+ },
+ "en-au": {
+ "line1": "Enable Apps"
+ },
+ "en-gb": {
+ "line1": "Enable Apps"
+ },
+ "en-ie": {
+ "line1": "Enable Apps"
+ },
+ "en-us": {
+ "line1": "Enable Apps"
+ },
+ "es-en": {
+ "line1": "Hab. aplic."
+ },
+ "es-es": {
+ "line1": "Activar apl."
+ },
+ "es-mx": {
+ "line1": "Hab. aplic."
+ },
+ "fr-ca": {
+ "line1": "Activer app.",
+ "textBody": "Activer app."
+ },
+ "fr-fr": {
+ "line1": "Activer app."
+ },
+ "it-it": {
+ "line1": "Abilita app"
+ },
+ "nl-nl": {
+ "line1": "Apps inschak."
+ },
+ "pl-pl": {
+ "line1": "Włącz aplikacje"
+ },
+ "pt-br": {
+ "line1": "Ativar aplic."
+ },
+ "pt-pt": {
+ "line1": "Activar actualiz."
+ },
+ "ru-ru": {
+ "line1": "Вкл. прилож."
+ },
+ "sv-se": {
+ "line1": "Aktivera appar"
+ },
+ "tr-tr": {
+ "line1": "Uygulamaları aç"
+ },
+ "zh-cn": {
+ "line1": "启用应用程序"
+ },
+ "zh-tw": {
+ "line1": "啟用應用程式"
+ }
+ }
+ },
+ "SettingUpdateAuto": {
+ "languages": {
+ "de-de": {
+ "line1": "Update anford."
+ },
+ "en-au": {
+ "line1": "Request update"
+ },
+ "en-gb": {
+ "line1": "Request update"
+ },
+ "en-ie": {
+ "line1": "Request update"
+ },
+ "en-us": {
+ "line1": "Request Update",
+ "textBody": "Select `Update now` to receive app permissions for your SYNC-enabled mobile apps. This may enable additional functionality depending on the app and your settings. If your phone has a working data connection, an update should complete in less than 1 minute."
+ },
+ "es-en": {
+ "line1": "Solicit. actualiz.",
+ "textBody": "Solicit. actualiz."
+ },
+ "es-es": {
+ "line1": "Solicitar actual."
+ },
+ "es-mx": {
+ "line1": "Solicit. actualiz.",
+ "textBody": "Solicit. actualiz."
+ },
+ "fr-ca": {
+ "line1": "Demander MAJ",
+ "textBody": "Demander MAJ"
+ },
+ "fr-fr": {
+ "line1": "Demander màj"
+ },
+ "it-it": {
+ "line1": "Rich. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Upd. aanvragen"
+ },
+ "pl-pl": {
+ "line1": "Zażądaj aktual."
+ },
+ "pt-br": {
+ "line1": "Solicitar atualiz."
+ },
+ "pt-pt": {
+ "line1": "Solicit. actualiz."
+ },
+ "ru-ru": {
+ "line1": "Запрос на обн."
+ },
+ "sv-se": {
+ "line1": "Begär uppdat."
+ },
+ "tr-tr": {
+ "line1": "Güncelleme iste"
+ },
+ "zh-cn": {
+ "line1": "请求更新"
+ },
+ "zh-tw": {
+ "line1": "請求更新"
+ }
+ }
+ },
+ "StatusNeeded": {
+ "languages": {
+ "de-de": {
+ "line1": "Update benötigt"
+ },
+ "en-au": {
+ "line1": "Update needed"
+ },
+ "en-gb": {
+ "line1": "Update needed",
+ "textBody": "Update needed"
+ },
+ "en-ie": {
+ "line1": "Update needed"
+ },
+ "en-us": {
+ "line1": "Update Needed",
+ "textBody": "Update Needed"
+ },
+ "es-en": {
+ "line1": "Actualiz. neces.",
+ "textBody": "Actualiz. neces."
+ },
+ "es-es": {
+ "line1": "Actu. necesaria"
+ },
+ "es-mx": {
+ "line1": "Actualiz. neces.",
+ "textBody": "Actualiz. neces."
+ },
+ "fr-ca": {
+ "line1": "Màj requise",
+ "textBody": "Màj requise"
+ },
+ "fr-fr": {
+ "line1": "Mise à jour requise"
+ },
+ "it-it": {
+ "line1": "Necess. aggiorn."
+ },
+ "nl-nl": {
+ "line1": "Update nodig"
+ },
+ "pl-pl": {
+ "line1": "Potrzeba aktual."
+ },
+ "pt-br": {
+ "line1": "Atualiz. necess."
+ },
+ "pt-pt": {
+ "line1": "Actual. necess."
+ },
+ "ru-ru": {
+ "line1": "Необх. обновл."
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs"
+ },
+ "tr-tr": {
+ "line1": "Güncellenmeli"
+ },
+ "zh-cn": {
+ "line1": "需要进行更新"
+ },
+ "zh-tw": {
+ "line1": "需更新"
+ }
+ }
+ },
+ "StatusPending": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktualisieren..."
+ },
+ "en-au": {
+ "line1": "Updating..."
+ },
+ "en-gb": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "en-ie": {
+ "line1": "Updating..."
+ },
+ "en-us": {
+ "line1": "Updating...",
+ "textBody": "Updating..."
+ },
+ "es-en": {
+ "line1": "Actualizando...",
+ "textBody": "Actualizando..."
+ },
+ "es-es": {
+ "line1": "Actualizando..."
+ },
+ "es-mx": {
+ "line1": "Actualizando...",
+ "textBody": "Actualizando..."
+ },
+ "fr-ca": {
+ "line1": "MAJ en cours...",
+ "textBody": "MAJ en cours..."
+ },
+ "fr-fr": {
+ "line1": "Màj en cours..."
+ },
+ "it-it": {
+ "line1": "Aggiornamento"
+ },
+ "nl-nl": {
+ "line1": "Updaten..."
+ },
+ "pl-pl": {
+ "line1": "Aktualizowanie"
+ },
+ "pt-br": {
+ "line1": "Atualizando..."
+ },
+ "pt-pt": {
+ "line1": "A actualizar..."
+ },
+ "ru-ru": {
+ "line1": "Обновление..."
+ },
+ "sv-se": {
+ "line1": "Uppdaterar..."
+ },
+ "tr-tr": {
+ "line1": "Güncelleniyor..."
+ },
+ "zh-cn": {
+ "line1": "正在更新......"
+ },
+ "zh-tw": {
+ "line1": "更新中..."
+ }
+ }
+ },
+ "StatusUpToDate": {
+ "languages": {
+ "de-de": {
+ "line1": "Aktuelle Version"
+ },
+ "en-au": {
+ "line1": "Up-to-date"
+ },
+ "en-gb": {
+ "line1": "Up-to-date",
+ "textBody": "Up-to-date"
+ },
+ "en-ie": {
+ "line1": "Up-to-date"
+ },
+ "en-us": {
+ "line1": "Up-To-Date",
+ "textBody": "Up-To-Date"
+ },
+ "es-en": {
+ "line1": "Actualizado",
+ "textBody": "Actualizado"
+ },
+ "es-es": {
+ "line1": "Actualizada"
+ },
+ "es-mx": {
+ "line1": "Actualizado",
+ "textBody": "Actualizado"
+ },
+ "fr-ca": {
+ "line1": "Déjà à jour",
+ "textBody": "Déjà à jour"
+ },
+ "fr-fr": {
+ "line1": "Déjà à jour"
+ },
+ "it-it": {
+ "line1": "più recente"
+ },
+ "nl-nl": {
+ "line1": "Up-to-date"
+ },
+ "pl-pl": {
+ "line1": "Aktualne"
+ },
+ "pt-br": {
+ "line1": "Atualizado"
+ },
+ "pt-pt": {
+ "line1": "Actualizado"
+ },
+ "ru-ru": {
+ "line1": "Обновлено"
+ },
+ "sv-se": {
+ "line1": "Uppdat. krävs ej"
+ },
+ "tr-tr": {
+ "line1": "Güncel"
+ },
+ "zh-cn": {
+ "line1": "最新更新"
+ },
+ "zh-tw": {
+ "line1": "更新最新"
+ }
+ }
+ },
+ "VehicleInfo": {
+ "languages": {
+ "de-de": {
+ "tts": "Eine App hat Zugriff auf die folgenden Fahrzeuginformationen: Kraftstoff-Füllstand, Kraftstoffverbrauch, Motordrehzahl, Kilometerzähler, FIN, Außentemperatur, Gangstellung, Reifenluftdruck.",
+ "label": "Fahrzeuginformationen"
+ },
+ "en-au": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-gb": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tire pressure."
+ },
+ "en-ie": {
+ "tts": "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure.",
+ "label": "Vehicle information"
+ },
+ "en-us": {
+ "tts": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure.",
+ "label": "Vehicle information",
+ "textBody": "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure."
+ },
+ "es-en": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo",
+ "textBody": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "es-es": {
+ "tts": "Una aplicación puede acceder a la siguiente información del vehículo: Nivel de combustible, Ahorro de combustible, RPM del motor, Cuentakilómetros, VIN, Temperatura aire exterior, Marcha engranada, Presión de neumáticos.",
+ "label": "Información del vehículo"
+ },
+ "es-mx": {
+ "tts": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos.",
+ "label": "Información del vehículo",
+ "textBody": "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "fr-ca": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus.",
+ "label": "Renseignements du véhicule",
+ "textBody": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus."
+ },
+ "fr-fr": {
+ "tts": "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Vitesse de moteur, Compteur kilométrique, NIV, Température extérieure, Position de vitesse, Pression des pneus.",
+ "label": "Renseignements du véhicule"
+ },
+ "it-it": {
+ "tts": "Un'app può avere accesso alle seguenti informazioni del veicolo: Livello carburante, Consumi carburante, Numero giri motore, Contachilometri, VIN, Temperatura esterna, Posizione marcia, Pressione pneumatici.",
+ "label": "Informazioni sul veicolo"
+ },
+ "nl-nl": {
+ "tts": "Een app heeft toegang tot de volgende voertuiginformatie: Brandstofpeil, Brandstofverbruik, Motortoerental, Kilometerteller, VIN, Buitentemperatuur, Versnellingsstand, Bandenspanning.",
+ "label": "Voertuiginformatie"
+ },
+ "pl-pl": {
+ "tts": "Aplikacja może uzyskać dostęp do następujących informacji o pojeździe: Poziom paliwa, Zużycie paliwa, Obroty silnika, Licznik przebiegu, Numer VIN, Temperatura zewnętrzna, Aktualny bieg, Ciśnienie opon.",
+ "label": "Informacje o pojeździe"
+ },
+ "pt-br": {
+ "tts": "Um aplicativo pode acessar as seguintes informações sobre o veículo: Nível de combustível, Economia de combustível, RPM do motor, Hodômetro, VIN, Temperatura externa, Posição das marchas, Pressão dos pneus.",
+ "label": "Informações sobre o veículo"
+ },
+ "pt-pt": {
+ "tts": "Uma aplicação consegue aceder às seguintes informações do veículo: Nível de combustível, Poupança de combustível, RPM do motor, Conta-quilómetros, VIN, Temperatura exterior, Posição da mudança de velocidade, Pressão dos pneus.",
+ "label": "Informações do veículo"
+ },
+ "ru-ru": {
+ "tts": "Приложение имеет доступ к следующим данным автомобиля: Уровень топлива, Економия топлива, Число оборотов двигателя, Одометр, Номер VIN, Температура за бортом, Положение передачи, Давление шин.",
+ "label": "Информация об автомобиле"
+ },
+ "sv-se": {
+ "tts": "Appen kan komma åt följande fordonsinformation: Bränslenivå, Bränsleekonomi, Motorns varvtal, Vägmätare, VIN, Utetemperatur, Växelläge, Däcktryck.",
+ "label": "Fordonsinformation"
+ },
+ "tr-tr": {
+ "tts": "Bir uygulama şu araç bilgilerine erişebilir: Yakıt seviyesi, Yakıt ekonomisi, Motor devirleri, Kilometre sayacı, VIN, Dış sıcaklık, Vites konumu, Lastik basıncı.",
+ "label": "Araç bilgisi"
+ },
+ "zh-cn": {
+ "tts": "移动应用程序可访问下列车辆信息 : 燃油量, 燃油经济性, 发动机转速(RPM), 里程表, VIN, 车外温度, 档位, 胎压.",
+ "label": "车辆信息"
+ },
+ "zh-tw": {
+ "tts": "一個應用程式可存取以下車輛資訊 : 燃油存量, 燃油經濟性, 引擎轉速, 里程表, 車輛識別號碼, 車外溫度, 檔位, 胎壓.",
+ "label": "車輛資訊"
+ }
+ }
+ }
+ }
+ },
+ "app_policies": {
+ "default": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": [
+ "Base-4"
+ ],
+ "RequestType": [
+ "QUERY_APPS",
+ "LAUNCH_APP",
+ "PROPRIETARY"
+ ]
+ },
+ "device": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": [
+ "DataConsent-2"
+ ]
+ },
+ "pre_DataConsent": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": [
+ "BaseBeforeDataConsent"
+ ],
+ "RequestType": [
+ "PROPRIETARY"
+ ]
+ },
+ "584421907": {
+ "keep_context": false,
+ "steal_focus": false,
+ "priority": "NONE",
+ "default_hmi": "NONE",
+ "groups": [
+ "BaseBeforeDataConsent"
+ ],
+ "RequestType": [
+ "TRAFFIC_MESSAGE_CHANNEL",
+ "QUERY_APPS",
+ "LAUNCH_APP",
+ "PROPRIETARY"
+ ]
+ }
+ }
+ }
+} \ No newline at end of file
diff --git a/src/components/policy/test/qdb_wrapper/sql_database_test.cc b/src/components/policy/test/qdb_wrapper/sql_database_test.cc
deleted file mode 100644
index a732128f64..0000000000
--- a/src/components/policy/test/qdb_wrapper/sql_database_test.cc
+++ /dev/null
@@ -1,139 +0,0 @@
-/* Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <cstdlib>
-
-#include "gtest/gtest.h"
-
-#include "qdb_wrapper/sql_error.h"
-#include "qdb_wrapper/sql_database.h"
-
-using ::policy::dbms::SQLError;
-using ::policy::dbms::SQLDatabase;
-
-namespace test {
-namespace components {
-namespace policy {
-namespace dbms {
-
-::testing::AssertionResult IsError(SQLError error) {
- if (error.number() != ::policy::dbms::OK) {
- return ::testing::AssertionSuccess() << error.text();
- } else {
- return ::testing::AssertionFailure() << error.text();
- }
-}
-
-TEST(SQLDatabaseTest, OpenClose) {
- SQLDatabase db("test-database");
- bool ret = db.Open();
- EXPECT_FALSE(IsError(db.LastError()));
- ASSERT_TRUE(ret);
-
- db.Close();
- EXPECT_FALSE(IsError(db.LastError()));
-}
-
-TEST(SQLDatabaseTest, DoubleOpen) {
- SQLDatabase db("test-database");
- bool ret = db.Open();
- EXPECT_FALSE(IsError(db.LastError()));
- ASSERT_TRUE(ret);
- ret = db.Open();
- EXPECT_FALSE(IsError(db.LastError()));
- ASSERT_TRUE(ret);
- db.Close();
-}
-
-TEST(SQLDatabaseTest, DoubleClose) {
- SQLDatabase db("test-database");
- bool ret = db.Open();
- EXPECT_FALSE(IsError(db.LastError()));
- ASSERT_TRUE(ret);
-
- db.Close();
- EXPECT_FALSE(IsError(db.LastError()));
- db.Close();
- EXPECT_FALSE(IsError(db.LastError()));
-}
-
-TEST(SQLDatabaseTest, CloseWithoutOpen) {
- SQLDatabase db("test-database");
- db.Close();
- EXPECT_FALSE(IsError(db.LastError()));
-}
-
-TEST(SQLDatabaseTest, CommitTransaction) {
- SQLDatabase db("test-database");
- ASSERT_TRUE(db.Open());
- EXPECT_TRUE(db.BeginTransaction());
- EXPECT_FALSE(IsError(db.LastError()));
- EXPECT_TRUE(db.CommitTransaction());
- EXPECT_FALSE(IsError(db.LastError()));
- db.Close();
-}
-
-TEST(SQLDatabaseTest, RollbackTransaction) {
- SQLDatabase db("test-database");
- ASSERT_TRUE(db.Open());
- EXPECT_TRUE(db.BeginTransaction());
- EXPECT_FALSE(IsError(db.LastError()));
- EXPECT_TRUE(db.RollbackTransaction());
- EXPECT_FALSE(IsError(db.LastError()));
- db.Close();
-}
-
-TEST(SQLDatabaseTest, FailedCommitTransaction) {
- SQLDatabase db("test-database");
- ASSERT_TRUE(db.Open());
- EXPECT_FALSE(db.CommitTransaction());
- EXPECT_TRUE(IsError(db.LastError()));
- db.Close();
-}
-
-TEST(SQLDatabaseTest, FailedRollbackTransaction) {
- SQLDatabase db("test-database");
- ASSERT_TRUE(db.Open());
- EXPECT_FALSE(db.RollbackTransaction());
- EXPECT_TRUE(IsError(db.LastError()));
- db.Close();
-}
-
-TEST(SQLDatabaseTest, BadTransaction) {
- SQLDatabase db("test-database");
- EXPECT_FALSE(db.BeginTransaction());
- EXPECT_TRUE(IsError(db.LastError()));
-}
-
-} // namespace dbms
-} // namespace policy
-} // namespace components
-} // namespace test
diff --git a/src/components/policy/test/qdb_wrapper/sql_query_test.cc b/src/components/policy/test/qdb_wrapper/sql_query_test.cc
deleted file mode 100644
index 122241ea1f..0000000000
--- a/src/components/policy/test/qdb_wrapper/sql_query_test.cc
+++ /dev/null
@@ -1,301 +0,0 @@
-/* Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <qdb/qdb.h>
-#include <string>
-
-#include "gtest/gtest.h"
-
-#include "qdb_wrapper/sql_error.h"
-#include "qdb_wrapper/sql_database.h"
-#include "qdb_wrapper/sql_query.h"
-
-using ::policy::dbms::SQLError;
-using ::policy::dbms::SQLDatabase;
-using ::policy::dbms::SQLQuery;
-
-namespace test {
-namespace components {
-namespace policy {
-namespace dbms {
-
-class SQLQueryTest : public ::testing::Test {
- protected:
- static qdb_hdl_t* conn;
- static const std::string kDatabaseName;
-
- static void SetUpTestCase() {
- conn = qdb_connect(kDatabaseName.c_str(), 0);
- ASSERT_TRUE(conn);
- int ret = qdb_statement(conn, "CREATE TABLE testTable (integerValue INTEGER,"
- " doubleValue REAL, stringValue TEXT)");
- ASSERT_NE(-1, ret);
- }
-
- static void TearDownTestCase() {
- qdb_statement(conn, "DROP TABLE IF EXISTS testTable");
- qdb_disconnect(conn);
- }
-
- void SetUp() {
- qdb_statement(conn, "DELETE FROM testTable");
- }
-
- ::testing::AssertionResult IsError(SQLError error) {
- if (error.number() != ::policy::dbms::OK) {
- return ::testing::AssertionSuccess() << error.text();
- } else {
- return ::testing::AssertionFailure() << error.text();
- }
- }
-};
-
-qdb_hdl_t* SQLQueryTest::conn = 0;
-const std::string SQLQueryTest::kDatabaseName = "test-query";
-
-TEST_F(SQLQueryTest, Query) {
- const std::string kSelect("SELECT * FROM testTable WHERE integerValue = ?");
-
- SQLDatabase* db = new SQLDatabase(kDatabaseName);
- ASSERT_TRUE(db->Open());
-
- SQLQuery query(db);
- query.Prepare(kSelect);
- EXPECT_STREQ(kSelect.c_str(), query.query().c_str());
-}
-
-TEST_F(SQLQueryTest, ExecString) {
- const std::string kInsert("INSERT INTO testTable"
- " (integerValue, doubleValue, stringValue)"
- " VALUES(1, 1.1, 'one-один')");
-
- SQLDatabase* db = new SQLDatabase(kDatabaseName);
- ASSERT_TRUE(db->Open());
-
- SQLQuery query(db);
- EXPECT_TRUE(query.Exec(kInsert));
- EXPECT_FALSE(IsError(query.LastError()));
-}
-
-TEST_F(SQLQueryTest, BindInteger) {
- const std::string kInsert("INSERT INTO testTable (integerValue) VALUES (?)");
- const int kIntegerValue = 2;
-
- SQLDatabase* db = new SQLDatabase(kDatabaseName);
- ASSERT_TRUE(db->Open());
-
- SQLQuery query(db);
- EXPECT_TRUE(query.Prepare(kInsert));
- EXPECT_FALSE(IsError(query.LastError()));
- query.Bind(0, kIntegerValue);
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Exec());
- EXPECT_FALSE(IsError(query.LastError()));
-}
-
-TEST_F(SQLQueryTest, BindDouble) {
- const std::string kInsert("INSERT INTO testTable (doubleValue) VALUES (?)");
- const double kDoubleValue = 3.3;
-
- SQLDatabase* db = new SQLDatabase(kDatabaseName);
- ASSERT_TRUE(db->Open());
- SQLQuery query(db);
- EXPECT_TRUE(query.Prepare(kInsert));
- EXPECT_FALSE(IsError(query.LastError()));
- query.Bind(0, kDoubleValue);
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Exec());
- EXPECT_FALSE(IsError(query.LastError()));
-}
-
-TEST_F(SQLQueryTest, BindString) {
- const std::string kInsert("INSERT INTO testTable (stringValue) VALUES (?)");
- const std::string kStringValue = "four-четыре";
-
- SQLDatabase* db = new SQLDatabase(kDatabaseName);
- ASSERT_TRUE(db->Open());
-
- SQLQuery query(db);
- EXPECT_TRUE(query.Prepare(kInsert));
- EXPECT_FALSE(IsError(query.LastError()));
- query.Bind(0, kStringValue);
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Exec());
- EXPECT_FALSE(IsError(query.LastError()));
-}
-
-TEST_F(SQLQueryTest, BindAllTypes) {
- const std::string kInsert("INSERT INTO testTable (integerValue, doubleValue,"
- " stringValue) VALUES (?, ?, ?)");
- const int kIntegerValue = 5;
- const double kDoubleValue = 5.5;
- const std::string kStringValue = "five-пять";
-
- SQLDatabase* db = new SQLDatabase(kDatabaseName);
- ASSERT_TRUE(db->Open());
-
- SQLQuery query(db);
- EXPECT_TRUE(query.Prepare(kInsert));
- EXPECT_FALSE(IsError(query.LastError()));
- query.Bind(0, kIntegerValue);
- EXPECT_FALSE(IsError(query.LastError()));
- query.Bind(1, kDoubleValue);
- EXPECT_FALSE(IsError(query.LastError()));
- query.Bind(2, kStringValue);
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Exec());
- EXPECT_FALSE(IsError(query.LastError()));
-}
-
-TEST_F(SQLQueryTest, Value) {
- const char* insert = "INSERT INTO testTable "
- "(integerValue, doubleValue, stringValue) "
- "VALUES (6, 6.6, 'six-шесть');";
- ASSERT_NE(-1, qdb_statement(conn, insert));
-
- const std::string kSelect("SELECT integerValue, doubleValue, stringValue"
- " FROM testTable WHERE integerValue = 6");
- const int kIntegerValue = 6;
- const double kDoubleValue = 6.6;
- const std::string kStringValue = "six-шесть";
-
- SQLDatabase* db = new SQLDatabase(kDatabaseName);
- ASSERT_TRUE(db->Open());
-
- SQLQuery query(db);
- EXPECT_TRUE(query.Prepare(kSelect));
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Exec());
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_EQ(kIntegerValue, query.GetInteger(0));
- EXPECT_EQ(kDoubleValue, query.GetDouble(1));
- EXPECT_EQ(kStringValue, query.GetString(2));
- EXPECT_FALSE(query.Next());
- EXPECT_FALSE(IsError(query.LastError()));
-}
-
-TEST_F(SQLQueryTest, EmptySelect) {
- const std::string kSelect("SELECT integerValue, doubleValue, stringValue"
- " FROM testTable WHERE 0");
- SQLDatabase* db = new SQLDatabase(kDatabaseName);
- ASSERT_TRUE(db->Open());
-
- SQLQuery query(db);
- EXPECT_TRUE(query.Prepare(kSelect));
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Exec());
- EXPECT_FALSE(IsError(query.LastError()));
-}
-
-TEST_F(SQLQueryTest, NextAndBind) {
- const char* insert = "INSERT INTO testTable "
- "(integerValue, doubleValue, stringValue) "
- "VALUES (7, 7.7, 'seven-семь');";
- ASSERT_NE(-1, qdb_statement(conn, insert));
-
- const std::string kSelect("SELECT integerValue, doubleValue, stringValue"
- " FROM testTable WHERE integerValue = ?");
- const int kIntegerValue = 7;
- const double kDoubleValue = 7.7;
- const std::string kStringValue = "seven-семь";
-
- SQLDatabase* db = new SQLDatabase(kDatabaseName);
- ASSERT_TRUE(db->Open());
-
- SQLQuery query(db);
- ASSERT_TRUE(query.Prepare(kSelect));
- EXPECT_FALSE(IsError(query.LastError()));
- query.Bind(0, kIntegerValue);
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Exec());
- ASSERT_FALSE(IsError(query.LastError()));
- EXPECT_EQ(kIntegerValue, query.GetInteger(0));
- EXPECT_EQ(kDoubleValue, query.GetDouble(1));
- EXPECT_EQ(kStringValue, query.GetString(2));
- EXPECT_FALSE(query.Next());
- EXPECT_FALSE(IsError(query.LastError()));
-}
-
-TEST_F(SQLQueryTest, LastInsertId) {
- const char* create = "CREATE TABLE idTable ( "
- "id INTEGER PRIMARY KEY AUTOINCREMENT,"
- "value TEXT)";
- ASSERT_NE(-1, qdb_statement(conn, create));
-
- const int64_t kExpectId = 1;
- const std::string kValue("Test last id of insert row");
- const std::string kInsert("INSERT INTO idTable (value) VALUES(?)");
-
- SQLDatabase* db = new SQLDatabase(kDatabaseName);
- ASSERT_TRUE(db->Open());
-
- SQLQuery query(db);
- ASSERT_TRUE(query.Prepare(kInsert));
- EXPECT_FALSE(IsError(query.LastError()));
- query.Bind(0, kValue);
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Exec());
- ASSERT_FALSE(IsError(query.LastError()));
- EXPECT_EQ(kExpectId, query.LastInsertId());
-
- ASSERT_NE(-1, qdb_statement(conn, "DROP TABLE idTable"));
-}
-
-TEST_F(SQLQueryTest, BindNull) {
- const std::string kInsert("INSERT INTO testTable (`integerValue`)"
- " VALUES (?)");
- SQLDatabase* db = new SQLDatabase(kDatabaseName);
- ASSERT_TRUE(db->Open());
-
- SQLQuery query(db);
- ASSERT_TRUE(query.Prepare(kInsert));
- EXPECT_FALSE(IsError(query.LastError()));
- query.Bind(0);
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Exec());
- ASSERT_FALSE(IsError(query.LastError()));
-}
-
-TEST_F(SQLQueryTest, DoublePrepare) {
- SQLDatabase* db = new SQLDatabase(kDatabaseName);
- ASSERT_TRUE(db->Open());
-
- SQLQuery query(db);
- EXPECT_TRUE(query.Prepare("SELECT * FROM testTable"));
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Prepare("SELECT * FROM testTable"));
- EXPECT_FALSE(IsError(query.LastError()));
-}
-
-} // namespace dbms
-} // namespace policy
-} // namespace components
-} // namespace test
diff --git a/src/components/policy/test/qdbserver.sh b/src/components/policy/test/qdbserver.sh
deleted file mode 100755
index 3f0144106d..0000000000
--- a/src/components/policy/test/qdbserver.sh
+++ /dev/null
@@ -1,6 +0,0 @@
-# This script star QDB server for SDL
-# Need superuser to start qdb
-
-LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/qnx650/target/qnx6/x86/usr/lib
-export LD_LIBRARY_PATH
-/usr/sbin/qdb -c test-qdb.ini
diff --git a/src/components/policy/test/sdl_preloaded_pt.json b/src/components/policy/test/sdl_preloaded_pt.json
index 6ef60616c7..d6f34c12fc 100644
--- a/src/components/policy/test/sdl_preloaded_pt.json
+++ b/src/components/policy/test/sdl_preloaded_pt.json
@@ -2,10 +2,11 @@
"policy_table": {
"module_config": {
"preloaded_pt": true,
+ "preloaded_date": "2015-02-12",
"exchange_after_x_ignition_cycles": 100,
"exchange_after_x_kilometers": 1800,
"exchange_after_x_days": 30,
- "timeout_after_x_seconds": 60,
+ "timeout_after_x_seconds": 70,
"seconds_between_retries": [1,
5,
25,
@@ -1916,7 +1917,12 @@
"steal_focus": false,
"priority": "NONE",
"default_hmi": "NONE",
- "groups": ["Base-4"]
+ "groups": ["Base-4"],
+ "RequestType": [
+ "QUERY_APPS",
+ "LAUNCH_APP",
+ "PROPRIETARY"
+ ]
},
"device": {
"keep_context": false,
@@ -1930,7 +1936,8 @@
"steal_focus": false,
"priority": "NONE",
"default_hmi": "NONE",
- "groups": ["BaseBeforeDataConsent"]
+ "groups": ["BaseBeforeDataConsent"],
+ "RequestType": ["HTTP"]
}
}
}
diff --git a/src/components/policy/test/sdl_pt_first_update.json b/src/components/policy/test/sdl_pt_first_update.json
new file mode 100644
index 0000000000..e6817da0d3
--- /dev/null
+++ b/src/components/policy/test/sdl_pt_first_update.json
@@ -0,0 +1,1744 @@
+{
+ "policy_table" : {
+ "app_policies" : {
+ "1766825573" : {
+ "AppHMIType" : [ "MEDIA" ],
+ "certificate" : "akdjfhaliuygrglurng",
+ "default_hmi" : "BACKGROUND",
+ "groups" : [
+ "Notifications",
+ "Location-1",
+ "PropriataryData-1",
+ "Navigation-1",
+ "Base-4",
+ "VehicleInfo-3",
+ "DrivingCharacteristics-3",
+ "Emergency-1"
+ ],
+ "keep_context" : true,
+ "memory_kb" : 1000,
+ "nicknames" : [ "SyncProxyTester" ],
+ "priority" : "EMERGENCY",
+ "steal_focus" : true,
+ "heart_beat_timeout_ms": 5000
+ },
+ "default" : {
+ "default_hmi" : "NONE",
+ "groups" : [ "Base-4" ],
+ "keep_context" : false,
+ "memory_kb" : 1000,
+ "priority" : "NONE",
+ "steal_focus" : false
+ },
+ "device" : {
+ "default_hmi" : "NONE",
+ "groups" : [ "Base-4" ],
+ "memory_kb" : 1000,
+ "watchdog_timer_ms" : 20000,
+ "keep_context" : false,
+ "priority" : "NONE",
+ "steal_focus" : false
+ },
+ "pre_DataConsent" : {
+ "default_hmi" : "NONE",
+ "groups" : [ "pre_Base-1" ],
+ "keep_context" : false,
+ "memory_kb" : 1000,
+ "priority" : "NONE",
+ "steal_focus" : false
+ }
+ },
+ "consumer_friendly_messages" : {
+ "messages" : {
+ "AppPermissions" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Zugriffsanfrage(n)",
+ "line2" : "erlauben?",
+ "tts" : "%appName% benötigt die folgenden Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Wenn Sie Ja drücken, erklären Sie sich damit einverstanden, dass %vehicleMake% nicht für Schäden oder Verletzungen der Privatsphäre haftet, die im Zusammenhang mit der Nutzung Ihrer Benutzerdaten durch %appName% entstehen. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au" : {
+ "line1" : "Grant requested",
+ "line2" : "permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny."
+ },
+ "en-gb" : {
+ "line1" : "Grant requested",
+ "line2" : "permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny."
+ },
+ "en-ie" : {
+ "line1" : "Grant requested",
+ "line2" : "permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny."
+ },
+ "en-us" : {
+ "line1" : "Grant Requested",
+ "line2" : "Permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press yes to allow or no to deny."
+ },
+ "es-en" : {
+ "line1" : "¿Otorgar permiso(s)",
+ "line2" : "solicitado(s)?",
+ "tts" : "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar."
+ },
+ "es-es" : {
+ "line1" : "¿Conceder permisos",
+ "line2" : "solicitados?",
+ "tts" : "%appName% está solicitando el uso de los siguientes permisos e información del vehículo: %functionalGroupLabels%. Si pulsa sí, acepta que %vehicleMake% no será responsable de los daños o la pérdida de privacidad relacionados con el uso de sus datos por parte de %appName%. Pulse sí para permitir o no para denegar."
+ },
+ "es-mx" : {
+ "line1" : "¿Otorgar permiso(s)",
+ "line2" : "solicitado(s)?",
+ "tts" : "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar."
+ },
+ "fr-ca" : {
+ "line1" : "Accorder permission(s)",
+ "line2" : "demandée(s)",
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ },
+ "fr-fr" : {
+ "line1" : "Accorder permission(s)",
+ "line2" : "demandée(s)",
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ },
+ "it-it" : {
+ "line1" : "Concedi autorizzaz.",
+ "line2" : "richiesta(e)?",
+ "tts" : "%appName% richiede l'uso delle seguenti informazioni e autorizzazioni sul veicolo: %functionalGroupLabels%. Se si preme Sì, si acconsente che %vehicleMake% non sarà responsabile per danni o perdita di privacy in relazione all'impiego dei dati da parte di %appName%. Premere Sì per consentire e No per negare."
+ },
+ "nl-nl" : {
+ "line1" : "Aangevraagde",
+ "line2" : "permissie(s) verlenen?",
+ "tts" : "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. Als u op Ja drukt, gaat u ermee akkoord dat %vehicleMake% in geen geval aansprakelijk gesteld kan worden voor schade of verlies van privacy als gevolg van het feit dat %appName% gebruik maakt van uw gegevens. Druk op Ja om dit toe te staan of Nee om te weigeren."
+ },
+ "pl-pl" : {
+ "line1" : "Udzielić żądanych",
+ "line2" : "pozwoleń?",
+ "tts" : "%appName% wymaga następujących informacji o pojeździe oraz pozwoleń: %functionalGroupLabels%. Naciśnięcie TAK oznacza zgodę na fakt, iż %vehicleMake% nie będzie ponosić odpowiedzialności za szkody ani utratę prywatności w związku z wykorzystaniem przez %appName% danych, należących do użytkownika. Naciśnij TAK w celu udzielenia zgody lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br" : {
+ "line1" : "Conceder permissão",
+ "line2" : "solicitada?",
+ "tts" : "%appName% está solicitando o uso das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se pressionar sim, você concorda que a %vehicleMake% não será responsável por danos ou perdas de privacidade relacionados ao uso dos seus dados por %appName%. Pressione sim para permitir ou não para negar."
+ },
+ "pt-pt" : {
+ "line1" : "Conceder permiss.",
+ "line2" : "solicitada(s)?",
+ "tts" : "%appName% está a solicitar a utilização das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se premir “Sim”, concorda que %vehicleMake% não será responsável por quaisquer danos ou perda de privacidade relacionada com a utilização dos seus dados por parte de %appName%. Prima “Sim” para permitir ou “Não” para recusar."
+ },
+ "ru-ru" : {
+ "line1" : "Предост. заправш.",
+ "line2" : "разрешения?",
+ "tts" : "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Нажатием \"\"да\"\", Вы соглашаетесь, что %vehicleMake% не будет нести ответственность за какие-либо убытки или потерю прайвеси, связанные с использованием Ваших данных компанией %appName%. Нажмите \"\"Да\"\", если Вы согласны, или \"\"Нет\"\" - если не согласны."
+ },
+ "sv-se" : {
+ "line1" : "Vill du ge",
+ "line2" : "tillstånd?",
+ "tts" : "%appName% begär att få tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Om du trycker Ja godkänner du att %vehicleMake% ska hållas skadeslös för alla skador som kan uppstå eller eventuella integritetsintrång som uppstår när %appName% använder dina data. Tryck Ja för att godkänna eller Nej för att neka."
+ },
+ "tr-tr" : {
+ "line1" : "İstenen izinler",
+ "line2" : "verilsin mi?",
+ "tts" : "%appName%, şu araç bilgilerini ve izinleri kullanma isteğinde bulunuyor: %functionalGroupLabels%. Evet'e basarsanız, %appName%'in verilerinizi kullanması sonucunda oluşabilecek hasarlardan veya gizlilik kaybından %vehicleMake%'in sorumlu olmayacağını kabul etmiş olacaksınız. Lütfen kabul etmek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn" : {
+ "line1" : "是否允许请求的",
+ "line2" : "权限?",
+ "tts" : "%appName% 正在请求使用下列车辆信息和权限: %functionalGroupLabels%。如果您按“是”,则表示您同意。 %vehicleMake% 将不会对因 %appName% 使用您的数据而引起的任何损毁或隐私损失负责。 请按“是”允许或按“否”拒绝。"
+ },
+ "zh-tw" : {
+ "line1" : "允許",
+ "line2" : "授權請求?",
+ "tts" : "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。按「是」,表示您同意,如因 %appName% 使用您的資料導致任何損害或損失,%vehicleMake% 將不負賠償責任。同意請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsHelp" : {
+ "languages" : {
+ "de-de" : {
+ "tts" : "%appName% fordert folgende Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Im Einstellungsmenü der mobilen Apps können Sie diese Berechtigungen ändern und sich detaillierte Beschreibungen anhören. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-gb" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-ie" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-us" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press yes to grant permissions or no to deny."
+ },
+ "es-en" : {
+ "tts" : "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "es-es" : {
+ "tts" : "%appName% está solicitando los siguientes permisos e información del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y escuchar descripciones detalladas en el menú de configuración de la aplicación móvil. Pulse sí para conceder el permiso o no para denegarlo."
+ },
+ "es-mx" : {
+ "tts" : "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "fr-ca" : {
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "fr-fr" : {
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "it-it" : {
+ "tts" : "%appName% richiede le seguenti informazioni e autorizzazioni riguardo il veicolo: %functionalGroupLabels%. È possibile modificare tali autorizzazioni e ascoltare descrizioni dettagliate nel menu impostazioni delle app mobili. Premere Sì per concedere le autorizzazioni e No per negarle."
+ },
+ "nl-nl" : {
+ "tts" : "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. U kunt deze toestemmingen wijzigen en gedetailleerde beschrijvingen beluisteren in het instellingenmenu voor mobiele apps. Druk op Ja om permissies te verlenen of op Nee om te weigeren."
+ },
+ "pl-pl" : {
+ "tts" : "%appName% wymaga następujących informacji o pojeździe oraz zezwoleń: %functionalGroupLabels%. W menu ustawień aplikacji mobilnych można zmienić owe zezwolenia i usłyszeć ich szczegółowy opis. Naciśnij TAK, aby wyrazić zgodę lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br" : {
+ "tts" : "%appName% está solicitando as seguintes informações e permissões do veículo: %functionalGroupLabels%. Você pode alterar estas permissões e ouvir descrições detalhadas no menu de configurações de aplicativos móveis. Pressione sim para conceder as permissões ou não para negar."
+ },
+ "pt-pt" : {
+ "tts" : "%appName% está a solicitar as seguintes informações e permissões do veículo: %functionalGroupLabels%. Pode alterar estas permissões e ouvir descrições detalhadas no menu de definições das aplicações móveis. Prima \"\"Sim\"\" para permitir ou \"\"Não\"\" para recusar."
+ },
+ "ru-ru" : {
+ "tts" : "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Вы можете изменить эти разрешения и прослушать подробные их описания в меню настроек мобильного приложения. Нажмите \"\"да\"\", чтобы предоставить разрешения, или \"\"нет\"\", чтобы не предоставлять."
+ },
+ "sv-se" : {
+ "tts" : "%appName% begär tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Du kan ändra tillstånden och höra detaljerade beskrivningar i menyn för mobilappsinställningar. Tryck Ja för att ge tillstånd eller Nej för att neka."
+ },
+ "tr-tr" : {
+ "tts" : "%appName%, şu araç bilgilerini ve izinleri istiyor: %functionalGroupLabels%. Bu izinleri değiştirebilir ve mobil uygulamalar ayarlar menüsünden ayrıntılı açıklamaları dinleyebilirsiniz. Lütfen izin vermek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn" : {
+ "tts" : "%appName% 正在请求下列车辆信息和权限: %functionalGroupLabels%。您可在移动应用程序设置菜单中更改这些权限,并听取详细说明。请按“是”允许权限或按“否”拒绝。"
+ },
+ "zh-tw" : {
+ "tts" : "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。您可在行動應用程式設定清單中更改這些許可,並聆聽詳細說明。給予許可請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsRevoked" : {
+ "languages" : {
+ "de-de" : {
+ "tts" : "Die Autorisierungsdaten der App wurden geändert. %appName% hat keinen Zugriff auf %functionalGroupLabels% mehr. Installieren Sie die neueste Version der App auf Ihrem Gerät.."
+ },
+ "en-au" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-gb" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-ie" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-us" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "es-en" : {
+ "tts" : "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "es-es" : {
+ "tts" : "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de que tiene la versión más reciente de la aplicación instalada en su dispositivo móvil."
+ },
+ "es-mx" : {
+ "tts" : "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "fr-ca" : {
+ "tts" : "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "fr-fr" : {
+ "tts" : "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "it-it" : {
+ "tts" : "Le autorizzazioni dell'app sono cambiate. %appName% non è più in grado di accedere a %functionalGroupLabels%. Assicurarsi di avere la versione più recente dell'app installata sul dispositivo mobile."
+ },
+ "nl-nl" : {
+ "tts" : "De app-autorisaties zijn gewijzigd. %appName% heeft geen toegang meer tot %functionalGroupLabels%. Zorg ervoor dat u de meest recente app-versie op uw mobiele apparaat geïnstalleerd hebt."
+ },
+ "pl-pl" : {
+ "tts" : "Dane dostępu aplikacji zostały zmienione. %appName% nie ma już dostępu do %functionalGroupLabels%. Sprawdź, czy na telefonie komórkowym zainstalowano najnowszą wersję aplikacji."
+ },
+ "pt-br" : {
+ "tts" : "As autorizações dos aplicativos foram alteradas. %appName% não pode mais acessar %functionalGroupLabels%. Certifique-se de que a versão mais recente do aplicativo está instalada no seu dispositivo móvel."
+ },
+ "pt-pt" : {
+ "tts" : "As autorizações das aplicações mudaram. %appName% já não consegue aceder a %functionalGroupLabels%. Certifique-se de que tem a última versão da aplicação no seu dispositivo móvel."
+ },
+ "ru-ru" : {
+ "tts" : "Авторизации приложения изменены. %appName% больше не имеет доступа к %functionalGroupLabels%. Убедитесь, что на вашем мобильном устройстве установлена самая новая версия приложения."
+ },
+ "sv-se" : {
+ "tts" : "Appens behörigheter har ändrats. %appName% har inte längre åtkomst till %functionalGroupLabels%. Kontrollera att du har installerat den senaste versionen av appen på mobilenheten."
+ },
+ "tr-tr" : {
+ "tts" : "Uygulama yetkileri değişti. %appName% artık %functionalGroupLabels%'e erişemeyecek. Lütfen mobil aygıtınızda en son uygulama sürümünün yüklü olduğundan emin olun."
+ },
+ "zh-cn" : {
+ "tts" : "应用程序授权已变更。 %appName% 将不能再访问 %functionalGroupLabels%。 请确认您的移动设备上安装的应用程序是最新版本。"
+ },
+ "zh-tw" : {
+ "tts" : "應用程式授權已改變。%appName% 已無法進入 %functionalGroupLabels%。請確認您的行動裝置上安裝了最新版應用程式。"
+ }
+ }
+ },
+ "AppUnauthorized" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "nicht autorisiert",
+ "tts" : "Diese Version von %appName% ist nicht autorisiert und wird nicht mit SYNC funktionieren."
+ },
+ "en-au" : {
+ "line1" : "not authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-gb" : {
+ "line1" : "not authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-ie" : {
+ "line1" : "not authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-us" : {
+ "line1" : "Not Authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "es-en" : {
+ "line1" : "no autorizada",
+ "tts" : "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "es-es" : {
+ "line1" : "No autorizada",
+ "tts" : "Esta versión de %appName% no está autorizada y no funcionará con SYNC."
+ },
+ "es-mx" : {
+ "line1" : "no autorizada",
+ "tts" : "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "fr-ca" : {
+ "line1" : "non autorisée",
+ "tts" : "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "fr-fr" : {
+ "line1" : "non autorisée",
+ "tts" : "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "it-it" : {
+ "line1" : "non autorizzata",
+ "tts" : "Questa versione di %appName% non è autorizzata e non funziona con il SYNC."
+ },
+ "nl-nl" : {
+ "line1" : "niet geautoriseerd",
+ "tts" : "Deze versie van %appName% is niet geautoriseerd en werkt niet met SYNC."
+ },
+ "pl-pl" : {
+ "line1" : "brak autoryzacji",
+ "tts" : "Niniejsza wersja %appName% nie posiada autoryzacji i nie będzie działać z SYNC."
+ },
+ "pt-br" : {
+ "line1" : "não autorizado",
+ "tts" : "Esta versão do %appName% não tem autorização e não funcionará com o SYNC."
+ },
+ "pt-pt" : {
+ "line1" : "não autorizada",
+ "tts" : "Esta versão de %appName% não está autorizada e não funcionará com o SYNC."
+ },
+ "ru-ru" : {
+ "line1" : "не авторизировано",
+ "tts" : "Эта версия %appName% не авторизирована и не будет работать с SYNC."
+ },
+ "sv-se" : {
+ "line1" : "är ej godkänd",
+ "tts" : "Den här versionen av %appName% är inte godkänd och fungerar inte med SYNC."
+ },
+ "tr-tr" : {
+ "line1" : "için izin yok",
+ "tts" : "Bu %appName% sürümüne izin verilmediğinden SYNC ile çalışamaz."
+ },
+ "zh-cn" : {
+ "line1" : "未得到授权",
+ "tts" : "此版本的%appName% 未得到授权,无法在SYNC上使用。"
+ },
+ "zh-tw" : {
+ "line1" : "無授權",
+ "tts" : "%appName% 的版本未獲得授權,將無法透過 SYNC 使用。"
+ }
+ }
+ },
+ "AppUnsupported" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "nicht unterstützt",
+ "tts" : "Diese Version von %appName% wird von SYNC nicht unterstützt."
+ },
+ "en-au" : {
+ "line1" : "not supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "en-gb" : {
+ "line1" : "not supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "en-ie" : {
+ "line1" : "not supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "en-us" : {
+ "line1" : "Not Supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "es-en" : {
+ "line1" : "no compatible",
+ "tts" : "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-es" : {
+ "line1" : "No compatible",
+ "tts" : "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-mx" : {
+ "line1" : "no compatible",
+ "tts" : "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "fr-ca" : {
+ "line1" : "incompatible",
+ "tts" : "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "fr-fr" : {
+ "line1" : "incompatible",
+ "tts" : "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "it-it" : {
+ "line1" : "non supportata",
+ "tts" : "Questa versione di %appName% non è supportata dal SYNC."
+ },
+ "nl-nl" : {
+ "line1" : "niet ondersteund",
+ "tts" : "Deze versie van %appName% wordt niet ondersteund door SYNC."
+ },
+ "pl-pl" : {
+ "line1" : "aplikacja nie obsług.",
+ "tts" : "Niniejsza wersja %appName% nie jest obsługiwana przez system SYNC."
+ },
+ "pt-br" : {
+ "line1" : "não suportado",
+ "tts" : "Esta versão do %appName% não é suportada pelo SYNC."
+ },
+ "pt-pt" : {
+ "line1" : "não suportada",
+ "tts" : "Esta versão de %appName% não é suportado pelo SYNC."
+ },
+ "ru-ru" : {
+ "line1" : "не поддерживается",
+ "tts" : "Эта версия %appName% не поддерживается SYNC."
+ },
+ "sv-se" : {
+ "line1" : "stöds ej",
+ "tts" : "SYNC har inte stöd för den här versionen av %appName%."
+ },
+ "tr-tr" : {
+ "line1" : "desteklenmiyor",
+ "tts" : "Bu %appName% sürümü SYNC tarafından desteklenmiyor."
+ },
+ "zh-cn" : {
+ "line1" : "不受支持",
+ "tts" : "SYNC不支持此版本的%appName%。"
+ },
+ "zh-tw" : {
+ "line1" : "不支援",
+ "tts" : "SYNC 不支援此版本的%appName% 。"
+ }
+ }
+ },
+ "DataConsent" : {
+ "languages" : {
+ "en-us" : {
+ "line1" : "Enable Mobile Apps",
+ "line2" : "on SYNC? (Uses Data)",
+ "tts" : "To use mobile apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device's data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S. Please press yes or no, or help for more information. "
+ }
+ }
+ },
+ "DataConsentHelp" : {
+ "languages" : {
+ "en-us" : {
+ "tts" : "Updates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC mobile apps settings menu. See your Owner Guide for more information. "
+ }
+ }
+ },
+ "DisableApps" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Auto-Update",
+ "line2" : "und Mobile Apps deaktivieren",
+ "tts" : "Ausschalten der automatischen Updates führt zum Ausschalten von SYNC mobile Apps. Sie können Ihre mobilen Apps dann nicht mehr mit SYNC nutzen. Bitte drücken Sie Ja zur Bestätigung oder Nein, um abzubrechen."
+ },
+ "en-au" : {
+ "line1" : "Disable auto-updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-gb" : {
+ "line1" : "Disable auto-updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-ie" : {
+ "line1" : "Disable auto-updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-us" : {
+ "line1" : "Disable Auto-Updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel."
+ },
+ "es-en" : {
+ "line1" : "¿Deshab. actualiz.",
+ "line2" : "autom. y aplic. móv.?",
+ "tts" : "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "es-es" : {
+ "line1" : "¿Desact. actual. auto",
+ "line2" : "y apl. móviles?",
+ "tts" : "Si desactiva las actualizaciones automáticas, también se desactivará la sincronización de las aplicaciones móviles. No podrá utilizar ninguna aplicación móvil con SYNC. Pulse sí para confirmar o no para cancelar."
+ },
+ "es-mx" : {
+ "line1" : "¿Deshab. actualiz.",
+ "line2" : "autom. y aplic. móv.?",
+ "tts" : "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "fr-ca" : {
+ "line1" : "Désactiver màj autom.",
+ "line2" : "et app. mobiles?",
+ "tts" : "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "fr-fr" : {
+ "line1" : "Désactiver màj autom.",
+ "line2" : "et app. mobiles?",
+ "tts" : "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "it-it" : {
+ "line1" : "Disabilitare agg. aut.",
+ "line2" : "e app mobili?",
+ "tts" : "Disabilitando gli aggiornamenti automatici si disattiva anche la sincronizzazione delle app mobili. Non sarà possibile usare app mobili con il SYNC. Premere Sì per confermare e No per cancellare."
+ },
+ "nl-nl" : {
+ "line1" : "Auto-updates en mob.",
+ "line2" : "apps uitschakelen?",
+ "tts" : "Door automatische updates uit te schakelen, schakelt u ook SYNC-mobiele apps uit. U kunt dan geen mobiele apps meer gebruiken met SYNC. Druk op Ja om te bevestigen of op Nee om te annuleren."
+ },
+ "pl-pl" : {
+ "line1" : "Wył. automat. aktual.",
+ "line2" : "i aplikacje mobilne?",
+ "tts" : "Wyłączenie automatycznych aktualizacji spowoduje także wyłączenie aplikacji mobilnych SYNC. Korzystanie z mobilnych aplikacji za pomocą SYNC będzie niemożliwe. Naciśnij TAK, by potwierdzić lub NIE, by anulować."
+ },
+ "pt-br" : {
+ "line1" : "Desativar atualizações",
+ "line2" : "autom. e aplicativos?",
+ "tts" : "Se as atualizações automáticas forem desativadas, os aplicativos também serão desativados. Você não poderá usar nenhum aplicativo com o SYNC. Pressione sim para confirmar ou não para cancelar."
+ },
+ "pt-pt" : {
+ "line1" : "Desact. actual. autom.",
+ "line2" : "e aplicações móveis?",
+ "tts" : "A desactivação das actualizações automáticas desactiva igualmente as aplicações móveis do SYNC. Não poderá utilizar quaisquer aplicações móveis com o SYNC. Prima \"\"Sim\"\" para confirmar ou \"\"Não\"\" para cancelar."
+ },
+ "ru-ru" : {
+ "line1" : "Откл. автообновления",
+ "line2" : "и мобил. прилож.?",
+ "tts" : "При отключении автоматических обновлений также будут отключены мобильные приложения sync. Вы не сможете использовать какие-либо мобильные приложения с SYNC. Нажмите \"\"Да\"\" для подтверждения или \"\"Нет\"\" для отмены."
+ },
+ "sv-se" : {
+ "line1" : "Avaktiverar autouppdat.",
+ "line2" : "och mobilappar?",
+ "tts" : "Om du avaktiverar automatisk uppdatering avaktiverar du även synkning av mobilappar. Du kommer inte längre att kunna använda dina mobilappar med SYNC. Tryck Ja för att bekräfta eller Nej för att avbryta."
+ },
+ "tr-tr" : {
+ "line1" : "Oto. güncelleme ve",
+ "line2" : "mobil uygul. kapat?",
+ "tts" : "Otomatik güncellemeleri devre dışı bırakırsanız sync mobil uygulamalar da devre dışı kalır. SYNC ile mobil uygulama kullanmanız mümkün olmaz. Lütfen onaylamak için Evet'e veya iptal etmek için Hayır'a basın."
+ },
+ "zh-cn" : {
+ "line1" : "是否禁用自动更新和",
+ "line2" : "移动应用程序?",
+ "tts" : "禁用自动更新同时也会禁用SYNC移动应用程序。您将无法在 SYNC 中使用任何移动应用程序。请按“是”确认或按“否”取消。"
+ },
+ "zh-tw" : {
+ "line1" : "停用自動更新",
+ "line2" : "和行動應用程式?",
+ "tts" : "停用自動更新也將停用 sync 行動應用程式。您將無法透過 SYNC 使用任何行動應用程式。確認請按「是」,取消請按「否」。"
+ }
+ }
+ },
+ "DrivingCharacteristics" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "Fahreigenschaften",
+ "tts" : "Eine App hat Zugriff auf die folgenden Fahreigenschaften: Kraftstoffverbrauch, MyKey, Sicherheitsgurtstatus."
+ },
+ "en-au" : {
+ "label" : "Driving characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-gb" : {
+ "label" : "Driving characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-ie" : {
+ "label" : "Driving characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-us" : {
+ "label" : "Driving Characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status."
+ },
+ "es-en" : {
+ "label" : "Características del manejo",
+ "tts" : "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "es-es" : {
+ "label" : "Características de conducción",
+ "tts" : "Una aplicación puede acceder a las siguientes características de conducción: Consumo de combustible, MyKey, Estado cinturones de seguridad."
+ },
+ "es-mx" : {
+ "label" : "Características del manejo",
+ "tts" : "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "fr-ca" : {
+ "label" : "Caractéristiques de conduite",
+ "tts" : "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "fr-fr" : {
+ "label" : "Caractéristiques de conduite",
+ "tts" : "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "it-it" : {
+ "label" : "Caratteristiche di guida",
+ "tts" : "Un'app può avere accesso alle seguenti caratteristiche di guida: Consumo carburante, MyKey, Stato cinture di sicurezza."
+ },
+ "nl-nl" : {
+ "label" : "Rijkenmerken",
+ "tts" : "Een app heeft toegang tot de volgende rijkenmerken: Brandstofverbruik, MyKey, Veiligheidsgordelstatus."
+ },
+ "pl-pl" : {
+ "label" : "Informacje dotyczące stylu jazdy",
+ "tts" : "Aplikacja może uzyskać dostęp do następujących informacji dotyczących jazdy: Zużycie paliwa, MyKey, Stan pasów bezpieczeństwa."
+ },
+ "pt-br" : {
+ "label" : "Características de condução",
+ "tts" : "Um aplicativo pode acessar as seguintes características de condução: Consumo de combustível, MyKey, Estado do cinto de segurança."
+ },
+ "pt-pt" : {
+ "label" : "Características de condução",
+ "tts" : "Uma aplicação consegue aceder às seguintes informações de condução: Consumo de combustível, MyKey, Estado dos cintos de segurança."
+ },
+ "ru-ru" : {
+ "label" : "Характеристики движения",
+ "tts" : "Приложение имеет доступ к следующим характеристикам движения: Расход топлива, MyKey, Состояние ремней безопасности."
+ },
+ "sv-se" : {
+ "label" : "Köregenskaper",
+ "tts" : "Appen kan komma åt följande köregenskaper: Bränsleförbrukning, MyKey, Bältesstatus."
+ },
+ "tr-tr" : {
+ "label" : "Sürüş karakteristikleri",
+ "tts" : "Bir uygulama şu sürüş karakteristiklerine erişebilir: Yakıt tüketimi, MyKey, Emniyet kemeri durumu."
+ },
+ "zh-cn" : {
+ "label" : "行驶特性",
+ "tts" : "移动应用程序可访问下列行驶特性: 油耗, MyKey, 安全带状态"
+ },
+ "zh-tw" : {
+ "label" : "駕駛特性",
+ "tts" : "應用程式可存取以下駕駛特性: 油耗, MyKey, 安全帶狀態"
+ }
+ }
+ },
+ "Location" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "GPS und Geschwindigkeit",
+ "tts" : "Eine App hat Zugriff auf die GPS-Daten und die Geschwindigkeit des Fahrzeugs."
+ },
+ "en-au" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "en-gb" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "en-ie" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "en-us" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "es-en" : {
+ "label" : "GPS y velocidad",
+ "tts" : "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "es-es" : {
+ "label" : "GPS y velocidad",
+ "tts" : "Una aplicación puede acceder al GPS y la velocidad del vehículo."
+ },
+ "es-mx" : {
+ "label" : "GPS y velocidad",
+ "tts" : "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "fr-ca" : {
+ "label" : "GPS et vitesse",
+ "tts" : "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "fr-fr" : {
+ "label" : "GPS et vitesse",
+ "tts" : "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "it-it" : {
+ "label" : "GPS e velocità",
+ "tts" : "Un'app può avere accesso a GPS e velocità del veicolo."
+ },
+ "nl-nl" : {
+ "label" : "Gps en snelheid",
+ "tts" : "Een app heeft toegang tot gps en de snelheid van het voertuig."
+ },
+ "pl-pl" : {
+ "label" : "GPS i prędkość",
+ "tts" : "Aplikacja może uzyskać dostęp do modułu GPS i prędkości pojazdu."
+ },
+ "pt-br" : {
+ "label" : "GPS e velocidade",
+ "tts" : "Um aplicativo pode acessar o GPS e a velocidade do veículo."
+ },
+ "pt-pt" : {
+ "label" : "GPS e velocidade",
+ "tts" : "Uma aplicação consegue aceder ao GPS e à velocidade do veículo."
+ },
+ "ru-ru" : {
+ "label" : "GPS и скорость",
+ "tts" : "Приложение имеет доступ к GPS и скорости автомобиля."
+ },
+ "sv-se" : {
+ "label" : "GPS och hastighet",
+ "tts" : "Appen kan komma åt fordonets GPS och hastighetsmätare."
+ },
+ "tr-tr" : {
+ "label" : "GPS ve hız",
+ "tts" : "Bu uygulama aracın GPS ve hız bilgilerine erişebilir."
+ },
+ "zh-cn" : {
+ "label" : "GPS 和车速",
+ "tts" : "移动应用程序可以访问车辆 GPS 和车速信息。"
+ },
+ "zh-tw" : {
+ "label" : "GPS和車速",
+ "tts" : "應用程式可存取車輛的GPS和速度。"
+ }
+ }
+ },
+ "Notifications" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "Push-Benachrichtigungen",
+ "tts" : "Läuft die App im Hintergrund, kann Sie Benachrichtigungen senden."
+ },
+ "en-au" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "en-gb" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "en-ie" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "en-us" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "es-en" : {
+ "label" : "Notificaciones tipo Push",
+ "tts" : "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "es-es" : {
+ "label" : "Notificaciones push",
+ "tts" : "Una aplicación puede enviar notificaciones cuando se está ejecutando en segundo plano."
+ },
+ "es-mx" : {
+ "label" : "Notificaciones tipo Push",
+ "tts" : "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "fr-ca" : {
+ "label" : "Notifications instantanées",
+ "tts" : "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "fr-fr" : {
+ "label" : "Notifications push",
+ "tts" : "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "it-it" : {
+ "label" : "Notifiche push",
+ "tts" : "Un'app può inviare notifiche se eseguita in background."
+ },
+ "nl-nl" : {
+ "label" : "Push-meldingen",
+ "tts" : "Een app kan meldingen versturen als deze op de achtergrond actief is."
+ },
+ "pl-pl" : {
+ "label" : "Powiadomienia Push",
+ "tts" : "Aplikacja może wysyłać powiadomienia, działając w tle."
+ },
+ "pt-br" : {
+ "label" : "Notificações Push",
+ "tts" : "Um aplicativo pode enviar notificações quando estiver sendo executado em segundo plano."
+ },
+ "pt-pt" : {
+ "label" : "Notificações push",
+ "tts" : "Uma aplicação consegue enviar notificações quando está activa em segundo plano."
+ },
+ "ru-ru" : {
+ "label" : "Оповещения о пересылке",
+ "tts" : "Если приложение работает в фоновом режиме, оно может отправлять оповещения."
+ },
+ "sv-se" : {
+ "label" : "Push-notiser",
+ "tts" : "Appen kan skicka meddelanden när den körs i bakgrunden."
+ },
+ "tr-tr" : {
+ "label" : "Anlık bildirimleri",
+ "tts" : "Bir uygulama arka planda çalışırken bildirim gönderebilir."
+ },
+ "zh-cn" : {
+ "label" : "推送通知",
+ "tts" : "移动应用程序在后台运行时可推送通知。"
+ },
+ "zh-tw" : {
+ "label" : "傳送通知",
+ "tts" : "車輛行進時,應用程式可在背景中傳送通知。"
+ }
+ }
+ },
+ "SettingDisableUpdates" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Updates deakt."
+ },
+ "en-au" : {
+ "line1" : "Disable updates"
+ },
+ "en-gb" : {
+ "line1" : "Disable updates"
+ },
+ "en-ie" : {
+ "line1" : "Disable updates"
+ },
+ "en-us" : {
+ "line1" : "Disable Updates"
+ },
+ "es-en" : {
+ "line1" : "Deshab. actual."
+ },
+ "es-es" : {
+ "line1" : "Desact. actual."
+ },
+ "es-mx" : {
+ "line1" : "Deshab. actual."
+ },
+ "fr-ca" : {
+ "line1" : "Désactiver MAJ"
+ },
+ "fr-fr" : {
+ "line1" : "Désactiver màj"
+ },
+ "it-it" : {
+ "line1" : "Disabilita agg."
+ },
+ "nl-nl" : {
+ "line1" : "Upd. uitschak."
+ },
+ "pl-pl" : {
+ "line1" : "Wyłącz aktual."
+ },
+ "pt-br" : {
+ "line1" : "Desat. atualiz."
+ },
+ "pt-pt" : {
+ "line1" : "Desact. actualiz."
+ },
+ "ru-ru" : {
+ "line1" : "Откл. обновл."
+ },
+ "sv-se" : {
+ "line1" : "Inaktivera uppd."
+ },
+ "tr-tr" : {
+ "line1" : "Güncell. Kapat"
+ },
+ "zh-cn" : {
+ "line1" : "禁用更新"
+ },
+ "zh-tw" : {
+ "line1" : "停用更新"
+ }
+ }
+ },
+ "SettingEnableUpdates" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Apps aktivieren"
+ },
+ "en-au" : {
+ "line1" : "Enable Apps"
+ },
+ "en-gb" : {
+ "line1" : "Enable Apps"
+ },
+ "en-ie" : {
+ "line1" : "Enable Apps"
+ },
+ "en-us" : {
+ "line1" : "Enable Apps"
+ },
+ "es-en" : {
+ "line1" : "Hab. aplic."
+ },
+ "es-es" : {
+ "line1" : "Activar apl."
+ },
+ "es-mx" : {
+ "line1" : "Hab. aplic."
+ },
+ "fr-ca" : {
+ "line1" : "Activer app."
+ },
+ "fr-fr" : {
+ "line1" : "Activer app."
+ },
+ "it-it" : {
+ "line1" : "Abilita app"
+ },
+ "nl-nl" : {
+ "line1" : "Apps inschak."
+ },
+ "pl-pl" : {
+ "line1" : "Włącz aplikacje"
+ },
+ "pt-br" : {
+ "line1" : "Ativar aplic."
+ },
+ "pt-pt" : {
+ "line1" : "Activar actualiz."
+ },
+ "ru-ru" : {
+ "line1" : "Вкл. прилож."
+ },
+ "sv-se" : {
+ "line1" : "Aktivera appar"
+ },
+ "tr-tr" : {
+ "line1" : "Uygulamaları aç"
+ },
+ "zh-cn" : {
+ "line1" : "启用应用程序"
+ },
+ "zh-tw" : {
+ "line1" : "啟用應用程式"
+ }
+ }
+ },
+ "SettingUpdateAuto" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Update anford."
+ },
+ "en-au" : {
+ "line1" : "Request update"
+ },
+ "en-gb" : {
+ "line1" : "Request update"
+ },
+ "en-ie" : {
+ "line1" : "Request update"
+ },
+ "en-us" : {
+ "line1" : "Request Update"
+ },
+ "es-en" : {
+ "line1" : "Solicit. actualiz."
+ },
+ "es-es" : {
+ "line1" : "Solicitar actual."
+ },
+ "es-mx" : {
+ "line1" : "Solicit. actualiz."
+ },
+ "fr-ca" : {
+ "line1" : "Demander MAJ"
+ },
+ "fr-fr" : {
+ "line1" : "Demander màj"
+ },
+ "it-it" : {
+ "line1" : "Rich. aggiorn."
+ },
+ "nl-nl" : {
+ "line1" : "Upd. aanvragen"
+ },
+ "pl-pl" : {
+ "line1" : "Zażądaj aktual."
+ },
+ "pt-br" : {
+ "line1" : "Solicitar atualiz."
+ },
+ "pt-pt" : {
+ "line1" : "Solicit. actualiz."
+ },
+ "ru-ru" : {
+ "line1" : "Запрос на обн."
+ },
+ "sv-se" : {
+ "line1" : "Begär uppdat."
+ },
+ "tr-tr" : {
+ "line1" : "Güncelleme iste"
+ },
+ "zh-cn" : {
+ "line1" : "请求更新"
+ },
+ "zh-tw" : {
+ "line1" : "請求更新"
+ }
+ }
+ },
+ "StatusNeeded" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Update benötigt"
+ },
+ "en-au" : {
+ "line1" : "Update needed"
+ },
+ "en-gb" : {
+ "line1" : "Update needed"
+ },
+ "en-ie" : {
+ "line1" : "Update needed"
+ },
+ "en-us" : {
+ "line1" : "Update Needed"
+ },
+ "es-en" : {
+ "line1" : "Actualiz. neces."
+ },
+ "es-es" : {
+ "line1" : "Actu. necesaria"
+ },
+ "es-mx" : {
+ "line1" : "Actualiz. neces."
+ },
+ "fr-ca" : {
+ "line1" : "Màj requise"
+ },
+ "fr-fr" : {
+ "line1" : "Mise à jour requise"
+ },
+ "it-it" : {
+ "line1" : "Necess. aggiorn."
+ },
+ "nl-nl" : {
+ "line1" : "Update nodig"
+ },
+ "pl-pl" : {
+ "line1" : "Potrzeba aktual."
+ },
+ "pt-br" : {
+ "line1" : "Atualiz. necess."
+ },
+ "pt-pt" : {
+ "line1" : "Actual. necess."
+ },
+ "ru-ru" : {
+ "line1" : "Необх. обновл."
+ },
+ "sv-se" : {
+ "line1" : "Uppdat. krävs"
+ },
+ "tr-tr" : {
+ "line1" : "Güncellenmeli"
+ },
+ "zh-cn" : {
+ "line1" : "需要进行更新"
+ },
+ "zh-tw" : {
+ "line1" : "需更新"
+ }
+ }
+ },
+ "StatusPending" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Aktualisieren..."
+ },
+ "en-au" : {
+ "line1" : "Updating..."
+ },
+ "en-gb" : {
+ "line1" : "Updating..."
+ },
+ "en-ie" : {
+ "line1" : "Updating..."
+ },
+ "en-us" : {
+ "line1" : "Updating..."
+ },
+ "es-en" : {
+ "line1" : "Actualizando..."
+ },
+ "es-es" : {
+ "line1" : "Actualizando..."
+ },
+ "es-mx" : {
+ "line1" : "Actualizando..."
+ },
+ "fr-ca" : {
+ "line1" : "MAJ en cours..."
+ },
+ "fr-fr" : {
+ "line1" : "Màj en cours..."
+ },
+ "it-it" : {
+ "line1" : "Aggiornamento"
+ },
+ "nl-nl" : {
+ "line1" : "Updaten..."
+ },
+ "pl-pl" : {
+ "line1" : "Aktualizowanie"
+ },
+ "pt-br" : {
+ "line1" : "Atualizando..."
+ },
+ "pt-pt" : {
+ "line1" : "A actualizar..."
+ },
+ "ru-ru" : {
+ "line1" : "Обновление..."
+ },
+ "sv-se" : {
+ "line1" : "Uppdaterar..."
+ },
+ "tr-tr" : {
+ "line1" : "Güncelleniyor..."
+ },
+ "zh-cn" : {
+ "line1" : "正在更新......"
+ },
+ "zh-tw" : {
+ "line1" : "更新中..."
+ }
+ }
+ },
+ "StatusUpToDate" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Aktuelle Version"
+ },
+ "en-au" : {
+ "line1" : "Up-to-date"
+ },
+ "en-gb" : {
+ "line1" : "Up-to-date"
+ },
+ "en-ie" : {
+ "line1" : "Up-to-date"
+ },
+ "en-us" : {
+ "line1" : "Up-To-Date"
+ },
+ "es-en" : {
+ "line1" : "Actualizado"
+ },
+ "es-es" : {
+ "line1" : "Actualizada"
+ },
+ "es-mx" : {
+ "line1" : "Actualizado"
+ },
+ "fr-ca" : {
+ "line1" : "Déjà à jour"
+ },
+ "fr-fr" : {
+ "line1" : "Déjà à jour"
+ },
+ "it-it" : {
+ "line1" : "più recente"
+ },
+ "nl-nl" : {
+ "line1" : "Up-to-date"
+ },
+ "pl-pl" : {
+ "line1" : "Aktualne"
+ },
+ "pt-br" : {
+ "line1" : "Atualizado"
+ },
+ "pt-pt" : {
+ "line1" : "Actualizado"
+ },
+ "ru-ru" : {
+ "line1" : "Обновлено"
+ },
+ "sv-se" : {
+ "line1" : "Uppdat. krävs ej"
+ },
+ "tr-tr" : {
+ "line1" : "Güncel"
+ },
+ "zh-cn" : {
+ "line1" : "最新更新"
+ },
+ "zh-tw" : {
+ "line1" : "更新最新"
+ }
+ }
+ },
+ "VehicleInfo" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "Fahrzeuginformationen",
+ "tts" : "Eine App hat Zugriff auf die folgenden Fahrzeuginformationen: Kraftstoff-Füllstand, Kraftstoffverbrauch, Motordrehzahl, Kilometerzähler, FIN, Außentemperatur, Gangstellung, Reifenluftdruck."
+ },
+ "en-au" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure."
+ },
+ "en-gb" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure."
+ },
+ "en-ie" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure."
+ },
+ "en-us" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure."
+ },
+ "es-en" : {
+ "label" : "Información del vehículo",
+ "tts" : "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "es-es" : {
+ "label" : "Información del vehículo",
+ "tts" : "Una aplicación puede acceder a la siguiente información del vehículo: Nivel de combustible, Ahorro de combustible, RPM del motor, Cuentakilómetros, VIN, Temperatura aire exterior, Marcha engranada, Presión de neumáticos."
+ },
+ "es-mx" : {
+ "label" : "Información del vehículo",
+ "tts" : "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "fr-ca" : {
+ "label" : "Renseignements du véhicule",
+ "tts" : "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus."
+ },
+ "fr-fr" : {
+ "label" : "Renseignements du véhicule",
+ "tts" : "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Vitesse de moteur, Compteur kilométrique, NIV, Température extérieure, Position de vitesse, Pression des pneus."
+ },
+ "it-it" : {
+ "label" : "Informazioni sul veicolo",
+ "tts" : "Un'app può avere accesso alle seguenti informazioni del veicolo: Livello carburante, Consumi carburante, Numero giri motore, Contachilometri, VIN, Temperatura esterna, Posizione marcia, Pressione pneumatici."
+ },
+ "nl-nl" : {
+ "label" : "Voertuiginformatie",
+ "tts" : "Een app heeft toegang tot de volgende voertuiginformatie: Brandstofpeil, Brandstofverbruik, Motortoerental, Kilometerteller, VIN, Buitentemperatuur, Versnellingsstand, Bandenspanning."
+ },
+ "pl-pl" : {
+ "label" : "Informacje o pojeździe",
+ "tts" : "Aplikacja może uzyskać dostęp do następujących informacji o pojeździe: Poziom paliwa, Zużycie paliwa, Obroty silnika, Licznik przebiegu, Numer VIN, Temperatura zewnętrzna, Aktualny bieg, Ciśnienie opon."
+ },
+ "pt-br" : {
+ "label" : "Informações sobre o veículo",
+ "tts" : "Um aplicativo pode acessar as seguintes informações sobre o veículo: Nível de combustível, Economia de combustível, RPM do motor, Hodômetro, VIN, Temperatura externa, Posição das marchas, Pressão dos pneus."
+ },
+ "pt-pt" : {
+ "label" : "Informações do veículo",
+ "tts" : "Uma aplicação consegue aceder às seguintes informações do veículo: Nível de combustível, Poupança de combustível, RPM do motor, Conta-quilómetros, VIN, Temperatura exterior, Posição da mudança de velocidade, Pressão dos pneus."
+ },
+ "ru-ru" : {
+ "label" : "Информация об автомобиле",
+ "tts" : "Приложение имеет доступ к следующим данным автомобиля: Уровень топлива, Економия топлива, Число оборотов двигателя, Одометр, Номер VIN, Температура за бортом, Положение передачи, Давление шин."
+ },
+ "sv-se" : {
+ "label" : "Fordonsinformation",
+ "tts" : "Appen kan komma åt följande fordonsinformation: Bränslenivå, Bränsleekonomi, Motorns varvtal, Vägmätare, VIN, Utetemperatur, Växelläge, Däcktryck."
+ },
+ "tr-tr" : {
+ "label" : "Araç bilgisi",
+ "tts" : "Bir uygulama şu araç bilgilerine erişebilir: Yakıt seviyesi, Yakıt ekonomisi, Motor devirleri, Kilometre sayacı, VIN, Dış sıcaklık, Vites konumu, Lastik basıncı."
+ },
+ "zh-cn" : {
+ "label" : "车辆信息",
+ "tts" : "移动应用程序可访问下列车辆信息 : 燃油量, 燃油经济性, 发动机转速(RPM), 里程表, VIN, 车外温度, 档位, 胎压."
+ },
+ "zh-tw" : {
+ "label" : "車輛資訊",
+ "tts" : "一個應用程式可存取以下車輛資訊 : 燃油存量, 燃油經濟性, 引擎轉速, 里程表, 車輛識別號碼, 車外溫度, 檔位, 胎壓."
+ }
+ }
+ }
+ },
+ "version" : "001.001.015"
+ },
+ "functional_groupings" : {
+ "Base-4" : {
+ "rpcs" : {
+ "AddCommand" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "AddSubMenu" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "Alert" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "ChangeRegistration" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "CreateInteractionChoiceSet" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "DeleteCommand" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "DeleteFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "DeleteInteractionChoiceSet" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "DeleteSubMenu" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "EncodedSyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "EndAudioPassThru" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "GenericResponse" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ListFiles" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnAppInterfaceUnregistered" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnAudioPassThru" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "OnButtonEvent" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "OnButtonPress" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "OnCommand" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "OnDriverDistraction" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "OnEncodedSyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnHMIStatus" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnLanguageChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnPermissionsChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnSyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnTBTClientState" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "PerformAudioPassThru" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "PerformInteraction" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "PutFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "RegisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "ResetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ScrollableMessage" : {
+ "hmi_levels" : [ "FULL" ]
+ },
+ "SetAppIcon" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetDisplayLayout" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "SetMediaClockTimer" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "Show" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "Slider" : {
+ "hmi_levels" : [ "FULL" ]
+ },
+ "Speak" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "SubscribeButton" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "SyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "UnregisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "UnsubscribeButton" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ }
+ }
+ },
+ "DrivingCharacteristics-3" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ }
+ },
+ "user_consent_prompt" : "DrivingCharacteristics"
+ },
+ "Emergency-1" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ }
+ }
+ },
+ "Location-1" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ }
+ },
+ "user_consent_prompt" : "Location"
+ },
+ "Navigation-1" : {
+ "rpcs" : {
+ "AlertManeuver" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ShowConstantTBT" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "UpdateTurnList" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ }
+ }
+ },
+ "Notifications" : {
+ "rpcs" : {
+ "Alert" : {
+ "hmi_levels" : [ "BACKGROUND" ]
+ }
+ },
+ "user_consent_prompt" : "Notifications"
+ },
+ "Notifications-2" : {
+ "rpcs" : {
+ "Alert" : {
+ "hmi_levels" : [ "FULL" ]
+ }
+ },
+ "user_consent_prompt" : "Old_Notifications"
+ },
+ "Notifications-3" : {
+ "rpcs" : {
+ "Alert" : {
+ "hmi_levels" : [ "LIMITED" ]
+ }
+ },
+ "user_consent_prompt" : "Old_Notifications"
+ },
+ "Notifications-4" : {
+ "rpcs" : {
+ "Alert" : {
+ "hmi_levels" : [ "NONE" ]
+ }
+ },
+ "user_consent_prompt" : "New_Notifications"
+ },
+ "PropriataryData-1" : {
+ "rpcs" : {
+ "DiagnosticMessage" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "GetDTCs" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ReadDID" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ }
+ }
+ },
+ "VehicleInfo-3" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"
+ ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"
+ ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"
+ ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"
+ ]
+ }
+ },
+ "user_consent_prompt" : "VehicleInfo"
+ },
+ "pre_Base-1" : {
+ "rpcs" : {
+ "ChangeRegistration" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "DeleteFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "GenericResponse" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ListFiles" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnAppInterfaceUnregistered" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnLanguageChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnPermissionsChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "PutFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "RegisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "ResetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "SetAppIcon" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetDisplayLayout" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "UnregisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ }
+ }
+ }
+ },
+ "module_config" : {
+ "device_certificates" : {
+ "HUU40DAS7F970UEI17A73JH32L41K32JH4L1K234H3K4" : "aldhfkahfgkafrblgjr"
+ },
+ "endpoints" : {
+ "0x07" : {
+ "default" : [ "http://policies.telematics.ford.com/api/policies" ]
+ }
+ },
+ "exchange_after_x_days" : 30,
+ "exchange_after_x_ignition_cycles" : 100,
+ "exchange_after_x_kilometers" : 1800,
+ "notifications_per_minute_by_priority" : {
+ "COMMUNICATION" : 6,
+ "EMERGENCY" : 60,
+ "NAVIGATION" : 15,
+ "NONE" : 0,
+ "NORMAL" : 4,
+ "VOICECOMM" : 10
+ },
+ "seconds_between_retries" : [ 1, 5, 25, 125, 625 ],
+ "timeout_after_x_seconds" : 60,
+ "vehicle_make" : "Stark Industries",
+ "vehicle_model" : "E-Tron",
+ "vehicle_year" : "1992"
+ }
+ }
+}
diff --git a/src/components/policy/test/sdl_pt_second_update.json b/src/components/policy/test/sdl_pt_second_update.json
new file mode 100644
index 0000000000..d5f5f480f3
--- /dev/null
+++ b/src/components/policy/test/sdl_pt_second_update.json
@@ -0,0 +1,1744 @@
+{
+ "policy_table" : {
+ "app_policies" : {
+ "1766825573" : {
+ "AppHMIType" : [ "MEDIA" ],
+ "certificate" : "akdjfhaliuygrglurng",
+ "default_hmi" : "BACKGROUND",
+ "groups" : [
+ "Notifications",
+ "Location-1",
+ "PropriataryData-1",
+ "Navigation-1",
+ "Base-4",
+ "VehicleInfo-3",
+ "DrivingCharacteristics-3",
+ "Emergency-1"
+ ],
+ "keep_context" : true,
+ "memory_kb" : 1000,
+ "nicknames" : [ "SyncProxyTester" ],
+ "priority" : "EMERGENCY",
+ "steal_focus" : true,
+ "heart_beat_timeout_ms": 5000
+ },
+ "default" : {
+ "default_hmi" : "NONE",
+ "groups" : [ "Base-4" ],
+ "keep_context" : false,
+ "memory_kb" : 1000,
+ "priority" : "NONE",
+ "steal_focus" : false
+ },
+ "device" : {
+ "default_hmi" : "NONE",
+ "groups" : [ "Base-4" ],
+ "memory_kb" : 1000,
+ "watchdog_timer_ms" : 20000,
+ "keep_context" : false,
+ "priority" : "NONE",
+ "steal_focus" : false
+ },
+ "pre_DataConsent" : {
+ "default_hmi" : "NONE",
+ "groups" : [ "pre_Base-1" ],
+ "keep_context" : false,
+ "memory_kb" : 1000,
+ "priority" : "NONE",
+ "steal_focus" : false
+ }
+ },
+ "consumer_friendly_messages" : {
+ "messages" : {
+ "AppPermissions" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Zugriffsanfrage(n)",
+ "line2" : "erlauben?",
+ "tts" : "%appName% benötigt die folgenden Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Wenn Sie Ja drücken, erklären Sie sich damit einverstanden, dass %vehicleMake% nicht für Schäden oder Verletzungen der Privatsphäre haftet, die im Zusammenhang mit der Nutzung Ihrer Benutzerdaten durch %appName% entstehen. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au" : {
+ "line1" : "Grant requested",
+ "line2" : "permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny."
+ },
+ "en-gb" : {
+ "line1" : "Grant requested",
+ "line2" : "permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny."
+ },
+ "en-ie" : {
+ "line1" : "Grant requested",
+ "line2" : "permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny."
+ },
+ "en-us" : {
+ "line1" : "Grant Requested",
+ "line2" : "Permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press yes to allow or no to deny."
+ },
+ "es-en" : {
+ "line1" : "¿Otorgar permiso(s)",
+ "line2" : "solicitado(s)?",
+ "tts" : "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar."
+ },
+ "es-es" : {
+ "line1" : "¿Conceder permisos",
+ "line2" : "solicitados?",
+ "tts" : "%appName% está solicitando el uso de los siguientes permisos e información del vehículo: %functionalGroupLabels%. Si pulsa sí, acepta que %vehicleMake% no será responsable de los daños o la pérdida de privacidad relacionados con el uso de sus datos por parte de %appName%. Pulse sí para permitir o no para denegar."
+ },
+ "es-mx" : {
+ "line1" : "¿Otorgar permiso(s)",
+ "line2" : "solicitado(s)?",
+ "tts" : "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar."
+ },
+ "fr-ca" : {
+ "line1" : "Accorder permission(s)",
+ "line2" : "demandée(s)",
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ },
+ "fr-fr" : {
+ "line1" : "Accorder permission(s)",
+ "line2" : "demandée(s)",
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ },
+ "it-it" : {
+ "line1" : "Concedi autorizzaz.",
+ "line2" : "richiesta(e)?",
+ "tts" : "%appName% richiede l'uso delle seguenti informazioni e autorizzazioni sul veicolo: %functionalGroupLabels%. Se si preme Sì, si acconsente che %vehicleMake% non sarà responsabile per danni o perdita di privacy in relazione all'impiego dei dati da parte di %appName%. Premere Sì per consentire e No per negare."
+ },
+ "nl-nl" : {
+ "line1" : "Aangevraagde",
+ "line2" : "permissie(s) verlenen?",
+ "tts" : "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. Als u op Ja drukt, gaat u ermee akkoord dat %vehicleMake% in geen geval aansprakelijk gesteld kan worden voor schade of verlies van privacy als gevolg van het feit dat %appName% gebruik maakt van uw gegevens. Druk op Ja om dit toe te staan of Nee om te weigeren."
+ },
+ "pl-pl" : {
+ "line1" : "Udzielić żądanych",
+ "line2" : "pozwoleń?",
+ "tts" : "%appName% wymaga następujących informacji o pojeździe oraz pozwoleń: %functionalGroupLabels%. Naciśnięcie TAK oznacza zgodę na fakt, iż %vehicleMake% nie będzie ponosić odpowiedzialności za szkody ani utratę prywatności w związku z wykorzystaniem przez %appName% danych, należących do użytkownika. Naciśnij TAK w celu udzielenia zgody lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br" : {
+ "line1" : "Conceder permissão",
+ "line2" : "solicitada?",
+ "tts" : "%appName% está solicitando o uso das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se pressionar sim, você concorda que a %vehicleMake% não será responsável por danos ou perdas de privacidade relacionados ao uso dos seus dados por %appName%. Pressione sim para permitir ou não para negar."
+ },
+ "pt-pt" : {
+ "line1" : "Conceder permiss.",
+ "line2" : "solicitada(s)?",
+ "tts" : "%appName% está a solicitar a utilização das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se premir “Sim”, concorda que %vehicleMake% não será responsável por quaisquer danos ou perda de privacidade relacionada com a utilização dos seus dados por parte de %appName%. Prima “Sim” para permitir ou “Não” para recusar."
+ },
+ "ru-ru" : {
+ "line1" : "Предост. заправш.",
+ "line2" : "разрешения?",
+ "tts" : "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Нажатием \"\"да\"\", Вы соглашаетесь, что %vehicleMake% не будет нести ответственность за какие-либо убытки или потерю прайвеси, связанные с использованием Ваших данных компанией %appName%. Нажмите \"\"Да\"\", если Вы согласны, или \"\"Нет\"\" - если не согласны."
+ },
+ "sv-se" : {
+ "line1" : "Vill du ge",
+ "line2" : "tillstånd?",
+ "tts" : "%appName% begär att få tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Om du trycker Ja godkänner du att %vehicleMake% ska hållas skadeslös för alla skador som kan uppstå eller eventuella integritetsintrång som uppstår när %appName% använder dina data. Tryck Ja för att godkänna eller Nej för att neka."
+ },
+ "tr-tr" : {
+ "line1" : "İstenen izinler",
+ "line2" : "verilsin mi?",
+ "tts" : "%appName%, şu araç bilgilerini ve izinleri kullanma isteğinde bulunuyor: %functionalGroupLabels%. Evet'e basarsanız, %appName%'in verilerinizi kullanması sonucunda oluşabilecek hasarlardan veya gizlilik kaybından %vehicleMake%'in sorumlu olmayacağını kabul etmiş olacaksınız. Lütfen kabul etmek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn" : {
+ "line1" : "是否允许请求的",
+ "line2" : "权限?",
+ "tts" : "%appName% 正在请求使用下列车辆信息和权限: %functionalGroupLabels%。如果您按“是”,则表示您同意。 %vehicleMake% 将不会对因 %appName% 使用您的数据而引起的任何损毁或隐私损失负责。 请按“是”允许或按“否”拒绝。"
+ },
+ "zh-tw" : {
+ "line1" : "允許",
+ "line2" : "授權請求?",
+ "tts" : "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。按「是」,表示您同意,如因 %appName% 使用您的資料導致任何損害或損失,%vehicleMake% 將不負賠償責任。同意請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsHelp" : {
+ "languages" : {
+ "de-de" : {
+ "tts" : "%appName% fordert folgende Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Im Einstellungsmenü der mobilen Apps können Sie diese Berechtigungen ändern und sich detaillierte Beschreibungen anhören. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-gb" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-ie" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-us" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press yes to grant permissions or no to deny."
+ },
+ "es-en" : {
+ "tts" : "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "es-es" : {
+ "tts" : "%appName% está solicitando los siguientes permisos e información del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y escuchar descripciones detalladas en el menú de configuración de la aplicación móvil. Pulse sí para conceder el permiso o no para denegarlo."
+ },
+ "es-mx" : {
+ "tts" : "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "fr-ca" : {
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "fr-fr" : {
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "it-it" : {
+ "tts" : "%appName% richiede le seguenti informazioni e autorizzazioni riguardo il veicolo: %functionalGroupLabels%. È possibile modificare tali autorizzazioni e ascoltare descrizioni dettagliate nel menu impostazioni delle app mobili. Premere Sì per concedere le autorizzazioni e No per negarle."
+ },
+ "nl-nl" : {
+ "tts" : "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. U kunt deze toestemmingen wijzigen en gedetailleerde beschrijvingen beluisteren in het instellingenmenu voor mobiele apps. Druk op Ja om permissies te verlenen of op Nee om te weigeren."
+ },
+ "pl-pl" : {
+ "tts" : "%appName% wymaga następujących informacji o pojeździe oraz zezwoleń: %functionalGroupLabels%. W menu ustawień aplikacji mobilnych można zmienić owe zezwolenia i usłyszeć ich szczegółowy opis. Naciśnij TAK, aby wyrazić zgodę lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br" : {
+ "tts" : "%appName% está solicitando as seguintes informações e permissões do veículo: %functionalGroupLabels%. Você pode alterar estas permissões e ouvir descrições detalhadas no menu de configurações de aplicativos móveis. Pressione sim para conceder as permissões ou não para negar."
+ },
+ "pt-pt" : {
+ "tts" : "%appName% está a solicitar as seguintes informações e permissões do veículo: %functionalGroupLabels%. Pode alterar estas permissões e ouvir descrições detalhadas no menu de definições das aplicações móveis. Prima \"\"Sim\"\" para permitir ou \"\"Não\"\" para recusar."
+ },
+ "ru-ru" : {
+ "tts" : "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Вы можете изменить эти разрешения и прослушать подробные их описания в меню настроек мобильного приложения. Нажмите \"\"да\"\", чтобы предоставить разрешения, или \"\"нет\"\", чтобы не предоставлять."
+ },
+ "sv-se" : {
+ "tts" : "%appName% begär tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Du kan ändra tillstånden och höra detaljerade beskrivningar i menyn för mobilappsinställningar. Tryck Ja för att ge tillstånd eller Nej för att neka."
+ },
+ "tr-tr" : {
+ "tts" : "%appName%, şu araç bilgilerini ve izinleri istiyor: %functionalGroupLabels%. Bu izinleri değiştirebilir ve mobil uygulamalar ayarlar menüsünden ayrıntılı açıklamaları dinleyebilirsiniz. Lütfen izin vermek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn" : {
+ "tts" : "%appName% 正在请求下列车辆信息和权限: %functionalGroupLabels%。您可在移动应用程序设置菜单中更改这些权限,并听取详细说明。请按“是”允许权限或按“否”拒绝。"
+ },
+ "zh-tw" : {
+ "tts" : "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。您可在行動應用程式設定清單中更改這些許可,並聆聽詳細說明。給予許可請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsRevoked" : {
+ "languages" : {
+ "de-de" : {
+ "tts" : "Die Autorisierungsdaten der App wurden geändert. %appName% hat keinen Zugriff auf %functionalGroupLabels% mehr. Installieren Sie die neueste Version der App auf Ihrem Gerät.."
+ },
+ "en-au" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-gb" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-ie" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-us" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "es-en" : {
+ "tts" : "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "es-es" : {
+ "tts" : "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de que tiene la versión más reciente de la aplicación instalada en su dispositivo móvil."
+ },
+ "es-mx" : {
+ "tts" : "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "fr-ca" : {
+ "tts" : "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "fr-fr" : {
+ "tts" : "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "it-it" : {
+ "tts" : "Le autorizzazioni dell'app sono cambiate. %appName% non è più in grado di accedere a %functionalGroupLabels%. Assicurarsi di avere la versione più recente dell'app installata sul dispositivo mobile."
+ },
+ "nl-nl" : {
+ "tts" : "De app-autorisaties zijn gewijzigd. %appName% heeft geen toegang meer tot %functionalGroupLabels%. Zorg ervoor dat u de meest recente app-versie op uw mobiele apparaat geïnstalleerd hebt."
+ },
+ "pl-pl" : {
+ "tts" : "Dane dostępu aplikacji zostały zmienione. %appName% nie ma już dostępu do %functionalGroupLabels%. Sprawdź, czy na telefonie komórkowym zainstalowano najnowszą wersję aplikacji."
+ },
+ "pt-br" : {
+ "tts" : "As autorizações dos aplicativos foram alteradas. %appName% não pode mais acessar %functionalGroupLabels%. Certifique-se de que a versão mais recente do aplicativo está instalada no seu dispositivo móvel."
+ },
+ "pt-pt" : {
+ "tts" : "As autorizações das aplicações mudaram. %appName% já não consegue aceder a %functionalGroupLabels%. Certifique-se de que tem a última versão da aplicação no seu dispositivo móvel."
+ },
+ "ru-ru" : {
+ "tts" : "Авторизации приложения изменены. %appName% больше не имеет доступа к %functionalGroupLabels%. Убедитесь, что на вашем мобильном устройстве установлена самая новая версия приложения."
+ },
+ "sv-se" : {
+ "tts" : "Appens behörigheter har ändrats. %appName% har inte längre åtkomst till %functionalGroupLabels%. Kontrollera att du har installerat den senaste versionen av appen på mobilenheten."
+ },
+ "tr-tr" : {
+ "tts" : "Uygulama yetkileri değişti. %appName% artık %functionalGroupLabels%'e erişemeyecek. Lütfen mobil aygıtınızda en son uygulama sürümünün yüklü olduğundan emin olun."
+ },
+ "zh-cn" : {
+ "tts" : "应用程序授权已变更。 %appName% 将不能再访问 %functionalGroupLabels%。 请确认您的移动设备上安装的应用程序是最新版本。"
+ },
+ "zh-tw" : {
+ "tts" : "應用程式授權已改變。%appName% 已無法進入 %functionalGroupLabels%。請確認您的行動裝置上安裝了最新版應用程式。"
+ }
+ }
+ },
+ "AppUnauthorized" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "nicht autorisiert",
+ "tts" : "Diese Version von %appName% ist nicht autorisiert und wird nicht mit SYNC funktionieren."
+ },
+ "en-au" : {
+ "line1" : "not authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-gb" : {
+ "line1" : "not authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-ie" : {
+ "line1" : "not authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-us" : {
+ "line1" : "Not Authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "es-en" : {
+ "line1" : "no autorizada",
+ "tts" : "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "es-es" : {
+ "line1" : "No autorizada",
+ "tts" : "Esta versión de %appName% no está autorizada y no funcionará con SYNC."
+ },
+ "es-mx" : {
+ "line1" : "no autorizada",
+ "tts" : "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "fr-ca" : {
+ "line1" : "non autorisée",
+ "tts" : "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "fr-fr" : {
+ "line1" : "non autorisée",
+ "tts" : "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "it-it" : {
+ "line1" : "non autorizzata",
+ "tts" : "Questa versione di %appName% non è autorizzata e non funziona con il SYNC."
+ },
+ "nl-nl" : {
+ "line1" : "niet geautoriseerd",
+ "tts" : "Deze versie van %appName% is niet geautoriseerd en werkt niet met SYNC."
+ },
+ "pl-pl" : {
+ "line1" : "brak autoryzacji",
+ "tts" : "Niniejsza wersja %appName% nie posiada autoryzacji i nie będzie działać z SYNC."
+ },
+ "pt-br" : {
+ "line1" : "não autorizado",
+ "tts" : "Esta versão do %appName% não tem autorização e não funcionará com o SYNC."
+ },
+ "pt-pt" : {
+ "line1" : "não autorizada",
+ "tts" : "Esta versão de %appName% não está autorizada e não funcionará com o SYNC."
+ },
+ "ru-ru" : {
+ "line1" : "не авторизировано",
+ "tts" : "Эта версия %appName% не авторизирована и не будет работать с SYNC."
+ },
+ "sv-se" : {
+ "line1" : "är ej godkänd",
+ "tts" : "Den här versionen av %appName% är inte godkänd och fungerar inte med SYNC."
+ },
+ "tr-tr" : {
+ "line1" : "için izin yok",
+ "tts" : "Bu %appName% sürümüne izin verilmediğinden SYNC ile çalışamaz."
+ },
+ "zh-cn" : {
+ "line1" : "未得到授权",
+ "tts" : "此版本的%appName% 未得到授权,无法在SYNC上使用。"
+ },
+ "zh-tw" : {
+ "line1" : "無授權",
+ "tts" : "%appName% 的版本未獲得授權,將無法透過 SYNC 使用。"
+ }
+ }
+ },
+ "AppUnsupported" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "nicht unterstützt",
+ "tts" : "Diese Version von %appName% wird von SYNC nicht unterstützt."
+ },
+ "en-au" : {
+ "line1" : "not supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "en-gb" : {
+ "line1" : "not supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "en-ie" : {
+ "line1" : "not supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "en-us" : {
+ "line1" : "Not Supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "es-en" : {
+ "line1" : "no compatible",
+ "tts" : "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-es" : {
+ "line1" : "No compatible",
+ "tts" : "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-mx" : {
+ "line1" : "no compatible",
+ "tts" : "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "fr-ca" : {
+ "line1" : "incompatible",
+ "tts" : "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "fr-fr" : {
+ "line1" : "incompatible",
+ "tts" : "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "it-it" : {
+ "line1" : "non supportata",
+ "tts" : "Questa versione di %appName% non è supportata dal SYNC."
+ },
+ "nl-nl" : {
+ "line1" : "niet ondersteund",
+ "tts" : "Deze versie van %appName% wordt niet ondersteund door SYNC."
+ },
+ "pl-pl" : {
+ "line1" : "aplikacja nie obsług.",
+ "tts" : "Niniejsza wersja %appName% nie jest obsługiwana przez system SYNC."
+ },
+ "pt-br" : {
+ "line1" : "não suportado",
+ "tts" : "Esta versão do %appName% não é suportada pelo SYNC."
+ },
+ "pt-pt" : {
+ "line1" : "não suportada",
+ "tts" : "Esta versão de %appName% não é suportado pelo SYNC."
+ },
+ "ru-ru" : {
+ "line1" : "не поддерживается",
+ "tts" : "Эта версия %appName% не поддерживается SYNC."
+ },
+ "sv-se" : {
+ "line1" : "stöds ej",
+ "tts" : "SYNC har inte stöd för den här versionen av %appName%."
+ },
+ "tr-tr" : {
+ "line1" : "desteklenmiyor",
+ "tts" : "Bu %appName% sürümü SYNC tarafından desteklenmiyor."
+ },
+ "zh-cn" : {
+ "line1" : "不受支持",
+ "tts" : "SYNC不支持此版本的%appName%。"
+ },
+ "zh-tw" : {
+ "line1" : "不支援",
+ "tts" : "SYNC 不支援此版本的%appName% 。"
+ }
+ }
+ },
+ "DataConsent" : {
+ "languages" : {
+ "en-us" : {
+ "line1" : "Enable Mobile Apps",
+ "line2" : "on SYNC? (Uses Data)",
+ "tts" : "To use mobile apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device's data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S. Please press yes or no, or help for more information. "
+ }
+ }
+ },
+ "DataConsentHelp" : {
+ "languages" : {
+ "en-us" : {
+ "tts" : "Updates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC mobile apps settings menu. See your Owner Guide for more information. "
+ }
+ }
+ },
+ "DisableApps" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Auto-Update",
+ "line2" : "und Mobile Apps deaktivieren",
+ "tts" : "Ausschalten der automatischen Updates führt zum Ausschalten von SYNC mobile Apps. Sie können Ihre mobilen Apps dann nicht mehr mit SYNC nutzen. Bitte drücken Sie Ja zur Bestätigung oder Nein, um abzubrechen."
+ },
+ "en-au" : {
+ "line1" : "Disable auto-updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-gb" : {
+ "line1" : "Disable auto-updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-ie" : {
+ "line1" : "Disable auto-updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-us" : {
+ "line1" : "Disable Auto-Updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel."
+ },
+ "es-en" : {
+ "line1" : "¿Deshab. actualiz.",
+ "line2" : "autom. y aplic. móv.?",
+ "tts" : "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "es-es" : {
+ "line1" : "¿Desact. actual. auto",
+ "line2" : "y apl. móviles?",
+ "tts" : "Si desactiva las actualizaciones automáticas, también se desactivará la sincronización de las aplicaciones móviles. No podrá utilizar ninguna aplicación móvil con SYNC. Pulse sí para confirmar o no para cancelar."
+ },
+ "es-mx" : {
+ "line1" : "¿Deshab. actualiz.",
+ "line2" : "autom. y aplic. móv.?",
+ "tts" : "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "fr-ca" : {
+ "line1" : "Désactiver màj autom.",
+ "line2" : "et app. mobiles?",
+ "tts" : "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "fr-fr" : {
+ "line1" : "Désactiver màj autom.",
+ "line2" : "et app. mobiles?",
+ "tts" : "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "it-it" : {
+ "line1" : "Disabilitare agg. aut.",
+ "line2" : "e app mobili?",
+ "tts" : "Disabilitando gli aggiornamenti automatici si disattiva anche la sincronizzazione delle app mobili. Non sarà possibile usare app mobili con il SYNC. Premere Sì per confermare e No per cancellare."
+ },
+ "nl-nl" : {
+ "line1" : "Auto-updates en mob.",
+ "line2" : "apps uitschakelen?",
+ "tts" : "Door automatische updates uit te schakelen, schakelt u ook SYNC-mobiele apps uit. U kunt dan geen mobiele apps meer gebruiken met SYNC. Druk op Ja om te bevestigen of op Nee om te annuleren."
+ },
+ "pl-pl" : {
+ "line1" : "Wył. automat. aktual.",
+ "line2" : "i aplikacje mobilne?",
+ "tts" : "Wyłączenie automatycznych aktualizacji spowoduje także wyłączenie aplikacji mobilnych SYNC. Korzystanie z mobilnych aplikacji za pomocą SYNC będzie niemożliwe. Naciśnij TAK, by potwierdzić lub NIE, by anulować."
+ },
+ "pt-br" : {
+ "line1" : "Desativar atualizações",
+ "line2" : "autom. e aplicativos?",
+ "tts" : "Se as atualizações automáticas forem desativadas, os aplicativos também serão desativados. Você não poderá usar nenhum aplicativo com o SYNC. Pressione sim para confirmar ou não para cancelar."
+ },
+ "pt-pt" : {
+ "line1" : "Desact. actual. autom.",
+ "line2" : "e aplicações móveis?",
+ "tts" : "A desactivação das actualizações automáticas desactiva igualmente as aplicações móveis do SYNC. Não poderá utilizar quaisquer aplicações móveis com o SYNC. Prima \"\"Sim\"\" para confirmar ou \"\"Não\"\" para cancelar."
+ },
+ "ru-ru" : {
+ "line1" : "Откл. автообновления",
+ "line2" : "и мобил. прилож.?",
+ "tts" : "При отключении автоматических обновлений также будут отключены мобильные приложения sync. Вы не сможете использовать какие-либо мобильные приложения с SYNC. Нажмите \"\"Да\"\" для подтверждения или \"\"Нет\"\" для отмены."
+ },
+ "sv-se" : {
+ "line1" : "Avaktiverar autouppdat.",
+ "line2" : "och mobilappar?",
+ "tts" : "Om du avaktiverar automatisk uppdatering avaktiverar du även synkning av mobilappar. Du kommer inte längre att kunna använda dina mobilappar med SYNC. Tryck Ja för att bekräfta eller Nej för att avbryta."
+ },
+ "tr-tr" : {
+ "line1" : "Oto. güncelleme ve",
+ "line2" : "mobil uygul. kapat?",
+ "tts" : "Otomatik güncellemeleri devre dışı bırakırsanız sync mobil uygulamalar da devre dışı kalır. SYNC ile mobil uygulama kullanmanız mümkün olmaz. Lütfen onaylamak için Evet'e veya iptal etmek için Hayır'a basın."
+ },
+ "zh-cn" : {
+ "line1" : "是否禁用自动更新和",
+ "line2" : "移动应用程序?",
+ "tts" : "禁用自动更新同时也会禁用SYNC移动应用程序。您将无法在 SYNC 中使用任何移动应用程序。请按“是”确认或按“否”取消。"
+ },
+ "zh-tw" : {
+ "line1" : "停用自動更新",
+ "line2" : "和行動應用程式?",
+ "tts" : "停用自動更新也將停用 sync 行動應用程式。您將無法透過 SYNC 使用任何行動應用程式。確認請按「是」,取消請按「否」。"
+ }
+ }
+ },
+ "DrivingCharacteristics" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "Fahreigenschaften",
+ "tts" : "Eine App hat Zugriff auf die folgenden Fahreigenschaften: Kraftstoffverbrauch, MyKey, Sicherheitsgurtstatus."
+ },
+ "en-au" : {
+ "label" : "Driving characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-gb" : {
+ "label" : "Driving characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-ie" : {
+ "label" : "Driving characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-us" : {
+ "label" : "Driving Characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status."
+ },
+ "es-en" : {
+ "label" : "Características del manejo",
+ "tts" : "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "es-es" : {
+ "label" : "Características de conducción",
+ "tts" : "Una aplicación puede acceder a las siguientes características de conducción: Consumo de combustible, MyKey, Estado cinturones de seguridad."
+ },
+ "es-mx" : {
+ "label" : "Características del manejo",
+ "tts" : "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "fr-ca" : {
+ "label" : "Caractéristiques de conduite",
+ "tts" : "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "fr-fr" : {
+ "label" : "Caractéristiques de conduite",
+ "tts" : "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "it-it" : {
+ "label" : "Caratteristiche di guida",
+ "tts" : "Un'app può avere accesso alle seguenti caratteristiche di guida: Consumo carburante, MyKey, Stato cinture di sicurezza."
+ },
+ "nl-nl" : {
+ "label" : "Rijkenmerken",
+ "tts" : "Een app heeft toegang tot de volgende rijkenmerken: Brandstofverbruik, MyKey, Veiligheidsgordelstatus."
+ },
+ "pl-pl" : {
+ "label" : "Informacje dotyczące stylu jazdy",
+ "tts" : "Aplikacja może uzyskać dostęp do następujących informacji dotyczących jazdy: Zużycie paliwa, MyKey, Stan pasów bezpieczeństwa."
+ },
+ "pt-br" : {
+ "label" : "Características de condução",
+ "tts" : "Um aplicativo pode acessar as seguintes características de condução: Consumo de combustível, MyKey, Estado do cinto de segurança."
+ },
+ "pt-pt" : {
+ "label" : "Características de condução",
+ "tts" : "Uma aplicação consegue aceder às seguintes informações de condução: Consumo de combustível, MyKey, Estado dos cintos de segurança."
+ },
+ "ru-ru" : {
+ "label" : "Характеристики движения",
+ "tts" : "Приложение имеет доступ к следующим характеристикам движения: Расход топлива, MyKey, Состояние ремней безопасности."
+ },
+ "sv-se" : {
+ "label" : "Köregenskaper",
+ "tts" : "Appen kan komma åt följande köregenskaper: Bränsleförbrukning, MyKey, Bältesstatus."
+ },
+ "tr-tr" : {
+ "label" : "Sürüş karakteristikleri",
+ "tts" : "Bir uygulama şu sürüş karakteristiklerine erişebilir: Yakıt tüketimi, MyKey, Emniyet kemeri durumu."
+ },
+ "zh-cn" : {
+ "label" : "行驶特性",
+ "tts" : "移动应用程序可访问下列行驶特性: 油耗, MyKey, 安全带状态"
+ },
+ "zh-tw" : {
+ "label" : "駕駛特性",
+ "tts" : "應用程式可存取以下駕駛特性: 油耗, MyKey, 安全帶狀態"
+ }
+ }
+ },
+ "Location" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "GPS und Geschwindigkeit",
+ "tts" : "Eine App hat Zugriff auf die GPS-Daten und die Geschwindigkeit des Fahrzeugs."
+ },
+ "en-au" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "en-gb" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "en-ie" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "en-us" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "es-en" : {
+ "label" : "GPS y velocidad",
+ "tts" : "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "es-es" : {
+ "label" : "GPS y velocidad",
+ "tts" : "Una aplicación puede acceder al GPS y la velocidad del vehículo."
+ },
+ "es-mx" : {
+ "label" : "GPS y velocidad",
+ "tts" : "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "fr-ca" : {
+ "label" : "GPS et vitesse",
+ "tts" : "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "fr-fr" : {
+ "label" : "GPS et vitesse",
+ "tts" : "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "it-it" : {
+ "label" : "GPS e velocità",
+ "tts" : "Un'app può avere accesso a GPS e velocità del veicolo."
+ },
+ "nl-nl" : {
+ "label" : "Gps en snelheid",
+ "tts" : "Een app heeft toegang tot gps en de snelheid van het voertuig."
+ },
+ "pl-pl" : {
+ "label" : "GPS i prędkość",
+ "tts" : "Aplikacja może uzyskać dostęp do modułu GPS i prędkości pojazdu."
+ },
+ "pt-br" : {
+ "label" : "GPS e velocidade",
+ "tts" : "Um aplicativo pode acessar o GPS e a velocidade do veículo."
+ },
+ "pt-pt" : {
+ "label" : "GPS e velocidade",
+ "tts" : "Uma aplicação consegue aceder ao GPS e à velocidade do veículo."
+ },
+ "ru-ru" : {
+ "label" : "GPS и скорость",
+ "tts" : "Приложение имеет доступ к GPS и скорости автомобиля."
+ },
+ "sv-se" : {
+ "label" : "GPS och hastighet",
+ "tts" : "Appen kan komma åt fordonets GPS och hastighetsmätare."
+ },
+ "tr-tr" : {
+ "label" : "GPS ve hız",
+ "tts" : "Bu uygulama aracın GPS ve hız bilgilerine erişebilir."
+ },
+ "zh-cn" : {
+ "label" : "GPS 和车速",
+ "tts" : "移动应用程序可以访问车辆 GPS 和车速信息。"
+ },
+ "zh-tw" : {
+ "label" : "GPS和車速",
+ "tts" : "應用程式可存取車輛的GPS和速度。"
+ }
+ }
+ },
+ "Notifications" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "Push-Benachrichtigungen",
+ "tts" : "Läuft die App im Hintergrund, kann Sie Benachrichtigungen senden."
+ },
+ "en-au" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "en-gb" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "en-ie" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "en-us" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "es-en" : {
+ "label" : "Notificaciones tipo Push",
+ "tts" : "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "es-es" : {
+ "label" : "Notificaciones push",
+ "tts" : "Una aplicación puede enviar notificaciones cuando se está ejecutando en segundo plano."
+ },
+ "es-mx" : {
+ "label" : "Notificaciones tipo Push",
+ "tts" : "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "fr-ca" : {
+ "label" : "Notifications instantanées",
+ "tts" : "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "fr-fr" : {
+ "label" : "Notifications push",
+ "tts" : "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "it-it" : {
+ "label" : "Notifiche push",
+ "tts" : "Un'app può inviare notifiche se eseguita in background."
+ },
+ "nl-nl" : {
+ "label" : "Push-meldingen",
+ "tts" : "Een app kan meldingen versturen als deze op de achtergrond actief is."
+ },
+ "pl-pl" : {
+ "label" : "Powiadomienia Push",
+ "tts" : "Aplikacja może wysyłać powiadomienia, działając w tle."
+ },
+ "pt-br" : {
+ "label" : "Notificações Push",
+ "tts" : "Um aplicativo pode enviar notificações quando estiver sendo executado em segundo plano."
+ },
+ "pt-pt" : {
+ "label" : "Notificações push",
+ "tts" : "Uma aplicação consegue enviar notificações quando está activa em segundo plano."
+ },
+ "ru-ru" : {
+ "label" : "Оповещения о пересылке",
+ "tts" : "Если приложение работает в фоновом режиме, оно может отправлять оповещения."
+ },
+ "sv-se" : {
+ "label" : "Push-notiser",
+ "tts" : "Appen kan skicka meddelanden när den körs i bakgrunden."
+ },
+ "tr-tr" : {
+ "label" : "Anlık bildirimleri",
+ "tts" : "Bir uygulama arka planda çalışırken bildirim gönderebilir."
+ },
+ "zh-cn" : {
+ "label" : "推送通知",
+ "tts" : "移动应用程序在后台运行时可推送通知。"
+ },
+ "zh-tw" : {
+ "label" : "傳送通知",
+ "tts" : "車輛行進時,應用程式可在背景中傳送通知。"
+ }
+ }
+ },
+ "SettingDisableUpdates" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Updates deakt."
+ },
+ "en-au" : {
+ "line1" : "Disable updates"
+ },
+ "en-gb" : {
+ "line1" : "Disable updates"
+ },
+ "en-ie" : {
+ "line1" : "Disable updates"
+ },
+ "en-us" : {
+ "line1" : "Disable Updates"
+ },
+ "es-en" : {
+ "line1" : "Deshab. actual."
+ },
+ "es-es" : {
+ "line1" : "Desact. actual."
+ },
+ "es-mx" : {
+ "line1" : "Deshab. actual."
+ },
+ "fr-ca" : {
+ "line1" : "Désactiver MAJ"
+ },
+ "fr-fr" : {
+ "line1" : "Désactiver màj"
+ },
+ "it-it" : {
+ "line1" : "Disabilita agg."
+ },
+ "nl-nl" : {
+ "line1" : "Upd. uitschak."
+ },
+ "pl-pl" : {
+ "line1" : "Wyłącz aktual."
+ },
+ "pt-br" : {
+ "line1" : "Desat. atualiz."
+ },
+ "pt-pt" : {
+ "line1" : "Desact. actualiz."
+ },
+ "ru-ru" : {
+ "line1" : "Откл. обновл."
+ },
+ "sv-se" : {
+ "line1" : "Inaktivera uppd."
+ },
+ "tr-tr" : {
+ "line1" : "Güncell. Kapat"
+ },
+ "zh-cn" : {
+ "line1" : "禁用更新"
+ },
+ "zh-tw" : {
+ "line1" : "停用更新"
+ }
+ }
+ },
+ "SettingEnableUpdates" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Apps aktivieren"
+ },
+ "en-au" : {
+ "line1" : "Enable Apps"
+ },
+ "en-gb" : {
+ "line1" : "Enable Apps"
+ },
+ "en-ie" : {
+ "line1" : "Enable Apps"
+ },
+ "en-us" : {
+ "line1" : "Enable Apps"
+ },
+ "es-en" : {
+ "line1" : "Hab. aplic."
+ },
+ "es-es" : {
+ "line1" : "Activar apl."
+ },
+ "es-mx" : {
+ "line1" : "Hab. aplic."
+ },
+ "fr-ca" : {
+ "line1" : "Activer app."
+ },
+ "fr-fr" : {
+ "line1" : "Activer app."
+ },
+ "it-it" : {
+ "line1" : "Abilita app"
+ },
+ "nl-nl" : {
+ "line1" : "Apps inschak."
+ },
+ "pl-pl" : {
+ "line1" : "Włącz aplikacje"
+ },
+ "pt-br" : {
+ "line1" : "Ativar aplic."
+ },
+ "pt-pt" : {
+ "line1" : "Activar actualiz."
+ },
+ "ru-ru" : {
+ "line1" : "Вкл. прилож."
+ },
+ "sv-se" : {
+ "line1" : "Aktivera appar"
+ },
+ "tr-tr" : {
+ "line1" : "Uygulamaları aç"
+ },
+ "zh-cn" : {
+ "line1" : "启用应用程序"
+ },
+ "zh-tw" : {
+ "line1" : "啟用應用程式"
+ }
+ }
+ },
+ "SettingUpdateAuto" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Update anford."
+ },
+ "en-au" : {
+ "line1" : "Request update"
+ },
+ "en-gb" : {
+ "line1" : "Request update"
+ },
+ "en-ie" : {
+ "line1" : "Request update"
+ },
+ "en-us" : {
+ "line1" : "Request Update"
+ },
+ "es-en" : {
+ "line1" : "Solicit. actualiz."
+ },
+ "es-es" : {
+ "line1" : "Solicitar actual."
+ },
+ "es-mx" : {
+ "line1" : "Solicit. actualiz."
+ },
+ "fr-ca" : {
+ "line1" : "Demander MAJ"
+ },
+ "fr-fr" : {
+ "line1" : "Demander màj"
+ },
+ "it-it" : {
+ "line1" : "Rich. aggiorn."
+ },
+ "nl-nl" : {
+ "line1" : "Upd. aanvragen"
+ },
+ "pl-pl" : {
+ "line1" : "Zażądaj aktual."
+ },
+ "pt-br" : {
+ "line1" : "Solicitar atualiz."
+ },
+ "pt-pt" : {
+ "line1" : "Solicit. actualiz."
+ },
+ "ru-ru" : {
+ "line1" : "Запрос на обн."
+ },
+ "sv-se" : {
+ "line1" : "Begär uppdat."
+ },
+ "tr-tr" : {
+ "line1" : "Güncelleme iste"
+ },
+ "zh-cn" : {
+ "line1" : "请求更新"
+ },
+ "zh-tw" : {
+ "line1" : "請求更新"
+ }
+ }
+ },
+ "StatusNeeded" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Update benötigt"
+ },
+ "en-au" : {
+ "line1" : "Update needed"
+ },
+ "en-gb" : {
+ "line1" : "Update needed"
+ },
+ "en-ie" : {
+ "line1" : "Update needed"
+ },
+ "en-us" : {
+ "line1" : "Update Needed"
+ },
+ "es-en" : {
+ "line1" : "Actualiz. neces."
+ },
+ "es-es" : {
+ "line1" : "Actu. necesaria"
+ },
+ "es-mx" : {
+ "line1" : "Actualiz. neces."
+ },
+ "fr-ca" : {
+ "line1" : "Màj requise"
+ },
+ "fr-fr" : {
+ "line1" : "Mise à jour requise"
+ },
+ "it-it" : {
+ "line1" : "Necess. aggiorn."
+ },
+ "nl-nl" : {
+ "line1" : "Update nodig"
+ },
+ "pl-pl" : {
+ "line1" : "Potrzeba aktual."
+ },
+ "pt-br" : {
+ "line1" : "Atualiz. necess."
+ },
+ "pt-pt" : {
+ "line1" : "Actual. necess."
+ },
+ "ru-ru" : {
+ "line1" : "Необх. обновл."
+ },
+ "sv-se" : {
+ "line1" : "Uppdat. krävs"
+ },
+ "tr-tr" : {
+ "line1" : "Güncellenmeli"
+ },
+ "zh-cn" : {
+ "line1" : "需要进行更新"
+ },
+ "zh-tw" : {
+ "line1" : "需更新"
+ }
+ }
+ },
+ "StatusPending" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Aktualisieren..."
+ },
+ "en-au" : {
+ "line1" : "Updating..."
+ },
+ "en-gb" : {
+ "line1" : "Updating..."
+ },
+ "en-ie" : {
+ "line1" : "Updating..."
+ },
+ "en-us" : {
+ "line1" : "Updating..."
+ },
+ "es-en" : {
+ "line1" : "Actualizando..."
+ },
+ "es-es" : {
+ "line1" : "Actualizando..."
+ },
+ "es-mx" : {
+ "line1" : "Actualizando..."
+ },
+ "fr-ca" : {
+ "line1" : "MAJ en cours..."
+ },
+ "fr-fr" : {
+ "line1" : "Màj en cours..."
+ },
+ "it-it" : {
+ "line1" : "Aggiornamento"
+ },
+ "nl-nl" : {
+ "line1" : "Updaten..."
+ },
+ "pl-pl" : {
+ "line1" : "Aktualizowanie"
+ },
+ "pt-br" : {
+ "line1" : "Atualizando..."
+ },
+ "pt-pt" : {
+ "line1" : "A actualizar..."
+ },
+ "ru-ru" : {
+ "line1" : "Обновление..."
+ },
+ "sv-se" : {
+ "line1" : "Uppdaterar..."
+ },
+ "tr-tr" : {
+ "line1" : "Güncelleniyor..."
+ },
+ "zh-cn" : {
+ "line1" : "正在更新......"
+ },
+ "zh-tw" : {
+ "line1" : "更新中..."
+ }
+ }
+ },
+ "StatusUpToDate" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Aktuelle Version"
+ },
+ "en-au" : {
+ "line1" : "Up-to-date"
+ },
+ "en-gb" : {
+ "line1" : "Up-to-date"
+ },
+ "en-ie" : {
+ "line1" : "Up-to-date"
+ },
+ "en-us" : {
+ "line1" : "Up-To-Date"
+ },
+ "es-en" : {
+ "line1" : "Actualizado"
+ },
+ "es-es" : {
+ "line1" : "Actualizada"
+ },
+ "es-mx" : {
+ "line1" : "Actualizado"
+ },
+ "fr-ca" : {
+ "line1" : "Déjà à jour"
+ },
+ "fr-fr" : {
+ "line1" : "Déjà à jour"
+ },
+ "it-it" : {
+ "line1" : "più recente"
+ },
+ "nl-nl" : {
+ "line1" : "Up-to-date"
+ },
+ "pl-pl" : {
+ "line1" : "Aktualne"
+ },
+ "pt-br" : {
+ "line1" : "Atualizado"
+ },
+ "pt-pt" : {
+ "line1" : "Actualizado"
+ },
+ "ru-ru" : {
+ "line1" : "Обновлено"
+ },
+ "sv-se" : {
+ "line1" : "Uppdat. krävs ej"
+ },
+ "tr-tr" : {
+ "line1" : "Güncel"
+ },
+ "zh-cn" : {
+ "line1" : "最新更新"
+ },
+ "zh-tw" : {
+ "line1" : "更新最新"
+ }
+ }
+ },
+ "VehicleInfo" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "Fahrzeuginformationen",
+ "tts" : "Eine App hat Zugriff auf die folgenden Fahrzeuginformationen: Kraftstoff-Füllstand, Kraftstoffverbrauch, Motordrehzahl, Kilometerzähler, FIN, Außentemperatur, Gangstellung, Reifenluftdruck."
+ },
+ "en-au" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure."
+ },
+ "en-gb" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure."
+ },
+ "en-ie" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure."
+ },
+ "en-us" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure."
+ },
+ "es-en" : {
+ "label" : "Información del vehículo",
+ "tts" : "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "es-es" : {
+ "label" : "Información del vehículo",
+ "tts" : "Una aplicación puede acceder a la siguiente información del vehículo: Nivel de combustible, Ahorro de combustible, RPM del motor, Cuentakilómetros, VIN, Temperatura aire exterior, Marcha engranada, Presión de neumáticos."
+ },
+ "es-mx" : {
+ "label" : "Información del vehículo",
+ "tts" : "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "fr-ca" : {
+ "label" : "Renseignements du véhicule",
+ "tts" : "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus."
+ },
+ "fr-fr" : {
+ "label" : "Renseignements du véhicule",
+ "tts" : "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Vitesse de moteur, Compteur kilométrique, NIV, Température extérieure, Position de vitesse, Pression des pneus."
+ },
+ "it-it" : {
+ "label" : "Informazioni sul veicolo",
+ "tts" : "Un'app può avere accesso alle seguenti informazioni del veicolo: Livello carburante, Consumi carburante, Numero giri motore, Contachilometri, VIN, Temperatura esterna, Posizione marcia, Pressione pneumatici."
+ },
+ "nl-nl" : {
+ "label" : "Voertuiginformatie",
+ "tts" : "Een app heeft toegang tot de volgende voertuiginformatie: Brandstofpeil, Brandstofverbruik, Motortoerental, Kilometerteller, VIN, Buitentemperatuur, Versnellingsstand, Bandenspanning."
+ },
+ "pl-pl" : {
+ "label" : "Informacje o pojeździe",
+ "tts" : "Aplikacja może uzyskać dostęp do następujących informacji o pojeździe: Poziom paliwa, Zużycie paliwa, Obroty silnika, Licznik przebiegu, Numer VIN, Temperatura zewnętrzna, Aktualny bieg, Ciśnienie opon."
+ },
+ "pt-br" : {
+ "label" : "Informações sobre o veículo",
+ "tts" : "Um aplicativo pode acessar as seguintes informações sobre o veículo: Nível de combustível, Economia de combustível, RPM do motor, Hodômetro, VIN, Temperatura externa, Posição das marchas, Pressão dos pneus."
+ },
+ "pt-pt" : {
+ "label" : "Informações do veículo",
+ "tts" : "Uma aplicação consegue aceder às seguintes informações do veículo: Nível de combustível, Poupança de combustível, RPM do motor, Conta-quilómetros, VIN, Temperatura exterior, Posição da mudança de velocidade, Pressão dos pneus."
+ },
+ "ru-ru" : {
+ "label" : "Информация об автомобиле",
+ "tts" : "Приложение имеет доступ к следующим данным автомобиля: Уровень топлива, Економия топлива, Число оборотов двигателя, Одометр, Номер VIN, Температура за бортом, Положение передачи, Давление шин."
+ },
+ "sv-se" : {
+ "label" : "Fordonsinformation",
+ "tts" : "Appen kan komma åt följande fordonsinformation: Bränslenivå, Bränsleekonomi, Motorns varvtal, Vägmätare, VIN, Utetemperatur, Växelläge, Däcktryck."
+ },
+ "tr-tr" : {
+ "label" : "Araç bilgisi",
+ "tts" : "Bir uygulama şu araç bilgilerine erişebilir: Yakıt seviyesi, Yakıt ekonomisi, Motor devirleri, Kilometre sayacı, VIN, Dış sıcaklık, Vites konumu, Lastik basıncı."
+ },
+ "zh-cn" : {
+ "label" : "车辆信息",
+ "tts" : "移动应用程序可访问下列车辆信息 : 燃油量, 燃油经济性, 发动机转速(RPM), 里程表, VIN, 车外温度, 档位, 胎压."
+ },
+ "zh-tw" : {
+ "label" : "車輛資訊",
+ "tts" : "一個應用程式可存取以下車輛資訊 : 燃油存量, 燃油經濟性, 引擎轉速, 里程表, 車輛識別號碼, 車外溫度, 檔位, 胎壓."
+ }
+ }
+ }
+ },
+ "version" : "001.001.015"
+ },
+ "functional_groupings" : {
+ "Base-4" : {
+ "rpcs" : {
+ "AddCommand" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "AddSubMenu" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "Alert" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "ChangeRegistration" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "CreateInteractionChoiceSet" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "DeleteCommand" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "DeleteFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "DeleteInteractionChoiceSet" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "DeleteSubMenu" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "EncodedSyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "EndAudioPassThru" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "GenericResponse" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ListFiles" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnAppInterfaceUnregistered" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnAudioPassThru" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "OnButtonEvent" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "OnButtonPress" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "OnCommand" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "OnDriverDistraction" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "OnEncodedSyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnHMIStatus" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnLanguageChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnPermissionsChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnSyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnTBTClientState" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "PerformAudioPassThru" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "PerformInteraction" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "PutFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "RegisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "ResetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ScrollableMessage" : {
+ "hmi_levels" : [ "FULL" ]
+ },
+ "SetAppIcon" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetDisplayLayout" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "SetMediaClockTimer" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "Show" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "Slider" : {
+ "hmi_levels" : [ "FULL" ]
+ },
+ "Speak" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "SubscribeButton" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "SyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "UnregisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "UnsubscribeButton" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ }
+ }
+ },
+ "DrivingCharacteristics-3" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ }
+ },
+ "user_consent_prompt" : "DrivingCharacteristics"
+ },
+ "Emergency-1" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ }
+ }
+ },
+ "Location-1" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ }
+ },
+ "user_consent_prompt" : "Location"
+ },
+ "Navigation-1" : {
+ "rpcs" : {
+ "AlertManeuver" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ShowConstantTBT" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "UpdateTurnList" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ }
+ }
+ },
+ "Notifications" : {
+ "rpcs" : {
+ "Alert" : {
+ "hmi_levels" : [ "BACKGROUND" ]
+ }
+ },
+ "user_consent_prompt" : "Notifications"
+ },
+ "Notifications-2" : {
+ "rpcs" : {
+ "Alert" : {
+ "hmi_levels" : [ "FULL" ]
+ }
+ },
+ "user_consent_prompt" : "Old_Notifications"
+ },
+ "Notifications-3" : {
+ "rpcs" : {
+ "Alert" : {
+ "hmi_levels" : [ "LIMITED" ]
+ }
+ },
+ "user_consent_prompt" : "New_Notifications"
+ },
+ "Notifications-4" : {
+ "rpcs" : {
+ "Alert" : {
+ "hmi_levels" : [ "NONE" ]
+ }
+ },
+ "user_consent_prompt" : "New_Notifications"
+ },
+ "PropriataryData-1" : {
+ "rpcs" : {
+ "DiagnosticMessage" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "GetDTCs" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ReadDID" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ }
+ }
+ },
+ "VehicleInfo-3" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"
+ ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"
+ ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"
+ ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"
+ ]
+ }
+ },
+ "user_consent_prompt" : "VehicleInfo"
+ },
+ "pre_Base-1" : {
+ "rpcs" : {
+ "ChangeRegistration" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "DeleteFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "GenericResponse" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ListFiles" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnAppInterfaceUnregistered" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnLanguageChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnPermissionsChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "PutFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "RegisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "ResetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "SetAppIcon" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetDisplayLayout" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "UnregisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ }
+ }
+ }
+ },
+ "module_config" : {
+ "device_certificates" : {
+ "HUU40DAS7F970UEI17A73JH32L41K32JH4L1K234H3K4" : "aldhfkahfgkafrblgjr"
+ },
+ "endpoints" : {
+ "0x07" : {
+ "default" : [ "http://policies.telematics.ford.com/api/policies" ]
+ }
+ },
+ "exchange_after_x_days" : 30,
+ "exchange_after_x_ignition_cycles" : 100,
+ "exchange_after_x_kilometers" : 1800,
+ "notifications_per_minute_by_priority" : {
+ "COMMUNICATION" : 6,
+ "EMERGENCY" : 60,
+ "NAVIGATION" : 15,
+ "NONE" : 0,
+ "NORMAL" : 4,
+ "VOICECOMM" : 10
+ },
+ "seconds_between_retries" : [ 1, 5, 25, 125, 625 ],
+ "timeout_after_x_seconds" : 60,
+ "vehicle_make" : "Stark Industries",
+ "vehicle_model" : "E-Tron",
+ "vehicle_year" : "1992"
+ }
+ }
+}
diff --git a/src/components/policy/test/sdl_pt_update.json b/src/components/policy/test/sdl_pt_update.json
new file mode 100644
index 0000000000..a332f92382
--- /dev/null
+++ b/src/components/policy/test/sdl_pt_update.json
@@ -0,0 +1,1722 @@
+{
+ "policy_table" : {
+ "app_policies" : {
+ "1766825573" : {
+ "AppHMIType" : [ "MEDIA" ],
+ "certificate" : "akdjfhaliuygrglurng",
+ "default_hmi" : "BACKGROUND",
+ "groups" : [
+ "Notifications",
+ "Location-1",
+ "PropriataryData-1",
+ "Navigation-1",
+ "Base-4",
+ "VehicleInfo-3",
+ "DrivingCharacteristics-3",
+ "Emergency-1"
+ ],
+ "keep_context" : true,
+ "memory_kb" : 1000,
+ "nicknames" : [ "SyncProxyTester" ],
+ "priority" : "EMERGENCY",
+ "steal_focus" : true,
+ "watchdog_timer_ms" : 20000
+ },
+ "default" : {
+ "default_hmi" : "NONE",
+ "groups" : [ "Base-4" ],
+ "keep_context" : false,
+ "memory_kb" : 1000,
+ "priority" : "NONE",
+ "steal_focus" : false,
+ "watchdog_timer_ms" : 20000
+ },
+ "device" : {
+ "default_hmi" : "NONE",
+ "groups" : [ "Base-4" ],
+ "memory_kb" : 1000,
+ "watchdog_timer_ms" : 20000,
+ "keep_context" : false,
+ "priority" : "NONE",
+ "steal_focus" : false
+ },
+ "pre_DataConsent" : {
+ "default_hmi" : "NONE",
+ "groups" : [ "pre_Base-1" ],
+ "keep_context" : false,
+ "memory_kb" : 1000,
+ "priority" : "NONE",
+ "steal_focus" : false,
+ "watchdog_timer_ms" : 20000
+ }
+ },
+ "consumer_friendly_messages" : {
+ "messages" : {
+ "AppPermissions" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Zugriffsanfrage(n)",
+ "line2" : "erlauben?",
+ "tts" : "%appName% benötigt die folgenden Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Wenn Sie Ja drücken, erklären Sie sich damit einverstanden, dass %vehicleMake% nicht für Schäden oder Verletzungen der Privatsphäre haftet, die im Zusammenhang mit der Nutzung Ihrer Benutzerdaten durch %appName% entstehen. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au" : {
+ "line1" : "Grant requested",
+ "line2" : "permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny."
+ },
+ "en-gb" : {
+ "line1" : "Grant requested",
+ "line2" : "permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny."
+ },
+ "en-ie" : {
+ "line1" : "Grant requested",
+ "line2" : "permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press Yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press Yes to allow or No to deny."
+ },
+ "en-us" : {
+ "line1" : "Grant Requested",
+ "line2" : "Permission(s)?",
+ "tts" : "%appName% is requesting the use of the following vehicle information and permissions: %functionalGroupLabels%. If you press yes, you agree that %vehicleMake% will not be liable for any damages or loss of privacy related to %appName%'s use of your data. Please press yes to allow or no to deny."
+ },
+ "es-en" : {
+ "line1" : "¿Otorgar permiso(s)",
+ "line2" : "solicitado(s)?",
+ "tts" : "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar."
+ },
+ "es-es" : {
+ "line1" : "¿Conceder permisos",
+ "line2" : "solicitados?",
+ "tts" : "%appName% está solicitando el uso de los siguientes permisos e información del vehículo: %functionalGroupLabels%. Si pulsa sí, acepta que %vehicleMake% no será responsable de los daños o la pérdida de privacidad relacionados con el uso de sus datos por parte de %appName%. Pulse sí para permitir o no para denegar."
+ },
+ "es-mx" : {
+ "line1" : "¿Otorgar permiso(s)",
+ "line2" : "solicitado(s)?",
+ "tts" : "%appName% solicita el uso de la siguiente información y permisos del vehículo: %functionalGroupLabels%. Si presiona Sí, acepta que %vehicleMake% no se hará responsable por los daños o pérdidas de privacidad relacionados con el uso que %appName% haga de sus datos. Presione Sí para permitir y No para denegar."
+ },
+ "fr-ca" : {
+ "line1" : "Accorder permission(s)",
+ "line2" : "demandée(s)",
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ },
+ "fr-fr" : {
+ "line1" : "Accorder permission(s)",
+ "line2" : "demandée(s)",
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Si vous appuyez sur Oui, vous acceptez que %vehicleMake% ne sera pas responsable des dommages ou des pertes de confidentialité reliées à l’utilisation de vos données par %appName%. Veuillez appuyer sur Oui pour autoriser ou sur Non pour refuser."
+ },
+ "it-it" : {
+ "line1" : "Concedi autorizzaz.",
+ "line2" : "richiesta(e)?",
+ "tts" : "%appName% richiede l'uso delle seguenti informazioni e autorizzazioni sul veicolo: %functionalGroupLabels%. Se si preme Sì, si acconsente che %vehicleMake% non sarà responsabile per danni o perdita di privacy in relazione all'impiego dei dati da parte di %appName%. Premere Sì per consentire e No per negare."
+ },
+ "nl-nl" : {
+ "line1" : "Aangevraagde",
+ "line2" : "permissie(s) verlenen?",
+ "tts" : "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. Als u op Ja drukt, gaat u ermee akkoord dat %vehicleMake% in geen geval aansprakelijk gesteld kan worden voor schade of verlies van privacy als gevolg van het feit dat %appName% gebruik maakt van uw gegevens. Druk op Ja om dit toe te staan of Nee om te weigeren."
+ },
+ "pl-pl" : {
+ "line1" : "Udzielić żądanych",
+ "line2" : "pozwoleń?",
+ "tts" : "%appName% wymaga następujących informacji o pojeździe oraz pozwoleń: %functionalGroupLabels%. Naciśnięcie TAK oznacza zgodę na fakt, iż %vehicleMake% nie będzie ponosić odpowiedzialności za szkody ani utratę prywatności w związku z wykorzystaniem przez %appName% danych, należących do użytkownika. Naciśnij TAK w celu udzielenia zgody lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br" : {
+ "line1" : "Conceder permissão",
+ "line2" : "solicitada?",
+ "tts" : "%appName% está solicitando o uso das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se pressionar sim, você concorda que a %vehicleMake% não será responsável por danos ou perdas de privacidade relacionados ao uso dos seus dados por %appName%. Pressione sim para permitir ou não para negar."
+ },
+ "pt-pt" : {
+ "line1" : "Conceder permiss.",
+ "line2" : "solicitada(s)?",
+ "tts" : "%appName% está a solicitar a utilização das seguintes informações e permissões do veículo: %functionalGroupLabels%. Se premir “Sim”, concorda que %vehicleMake% não será responsável por quaisquer danos ou perda de privacidade relacionada com a utilização dos seus dados por parte de %appName%. Prima “Sim” para permitir ou “Não” para recusar."
+ },
+ "ru-ru" : {
+ "line1" : "Предост. заправш.",
+ "line2" : "разрешения?",
+ "tts" : "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Нажатием \"\"да\"\", Вы соглашаетесь, что %vehicleMake% не будет нести ответственность за какие-либо убытки или потерю прайвеси, связанные с использованием Ваших данных компанией %appName%. Нажмите \"\"Да\"\", если Вы согласны, или \"\"Нет\"\" - если не согласны."
+ },
+ "sv-se" : {
+ "line1" : "Vill du ge",
+ "line2" : "tillstånd?",
+ "tts" : "%appName% begär att få tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Om du trycker Ja godkänner du att %vehicleMake% ska hållas skadeslös för alla skador som kan uppstå eller eventuella integritetsintrång som uppstår när %appName% använder dina data. Tryck Ja för att godkänna eller Nej för att neka."
+ },
+ "tr-tr" : {
+ "line1" : "İstenen izinler",
+ "line2" : "verilsin mi?",
+ "tts" : "%appName%, şu araç bilgilerini ve izinleri kullanma isteğinde bulunuyor: %functionalGroupLabels%. Evet'e basarsanız, %appName%'in verilerinizi kullanması sonucunda oluşabilecek hasarlardan veya gizlilik kaybından %vehicleMake%'in sorumlu olmayacağını kabul etmiş olacaksınız. Lütfen kabul etmek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn" : {
+ "line1" : "是否允许请求的",
+ "line2" : "权限?",
+ "tts" : "%appName% 正在请求使用下列车辆信息和权限: %functionalGroupLabels%。如果您按“是”,则表示您同意。 %vehicleMake% 将不会对因 %appName% 使用您的数据而引起的任何损毁或隐私损失负责。 请按“是”允许或按“否”拒绝。"
+ },
+ "zh-tw" : {
+ "line1" : "允許",
+ "line2" : "授權請求?",
+ "tts" : "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。按「是」,表示您同意,如因 %appName% 使用您的資料導致任何損害或損失,%vehicleMake% 將不負賠償責任。同意請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsHelp" : {
+ "languages" : {
+ "de-de" : {
+ "tts" : "%appName% fordert folgende Fahrzeuginformationen und Zugriffsberechtigungen: %functionalGroupLabels%. Im Einstellungsmenü der mobilen Apps können Sie diese Berechtigungen ändern und sich detaillierte Beschreibungen anhören. Mit Ja stimmen Sie zu; mit Nein lehnen Sie ab."
+ },
+ "en-au" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-gb" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-ie" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press Yes to grant permissions or No to deny."
+ },
+ "en-us" : {
+ "tts" : "%appName% is requesting the following vehicle information and permissions: %functionalGroupLabels%. You can change these permissions and hear detailed descriptions in the mobile apps settings menu. Please press yes to grant permissions or no to deny."
+ },
+ "es-en" : {
+ "tts" : "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "es-es" : {
+ "tts" : "%appName% está solicitando los siguientes permisos e información del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y escuchar descripciones detalladas en el menú de configuración de la aplicación móvil. Pulse sí para conceder el permiso o no para denegarlo."
+ },
+ "es-mx" : {
+ "tts" : "%appName% solicita la siguiente información y permisos del vehículo: %functionalGroupLabels%. Puede cambiar estos permisos y consultar descripciones detalladas en el menú de configuración de las aplicaciones móviles. Presione Sí para otorgar permisos y No para denegar."
+ },
+ "fr-ca" : {
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "fr-fr" : {
+ "tts" : "%appName% demande d’utiliser les informations du véhicule et les permissions suivantes : %functionalGroupLabels%. Vous pouvez modifier ces permissions et entendre les descriptions détaillées dans le menu des réglages des applications mobiles. Veuillez appuyer sur Oui pour accorder les permissions ou sur Non pour refuser."
+ },
+ "it-it" : {
+ "tts" : "%appName% richiede le seguenti informazioni e autorizzazioni riguardo il veicolo: %functionalGroupLabels%. È possibile modificare tali autorizzazioni e ascoltare descrizioni dettagliate nel menu impostazioni delle app mobili. Premere Sì per concedere le autorizzazioni e No per negarle."
+ },
+ "nl-nl" : {
+ "tts" : "%appName% vraagt gebruikmaking van de volgende voertuiginformatie en toestemmingen aan: %functionalGroupLabels%. U kunt deze toestemmingen wijzigen en gedetailleerde beschrijvingen beluisteren in het instellingenmenu voor mobiele apps. Druk op Ja om permissies te verlenen of op Nee om te weigeren."
+ },
+ "pl-pl" : {
+ "tts" : "%appName% wymaga następujących informacji o pojeździe oraz zezwoleń: %functionalGroupLabels%. W menu ustawień aplikacji mobilnych można zmienić owe zezwolenia i usłyszeć ich szczegółowy opis. Naciśnij TAK, aby wyrazić zgodę lub NIE w celu odrzucenia żądania."
+ },
+ "pt-br" : {
+ "tts" : "%appName% está solicitando as seguintes informações e permissões do veículo: %functionalGroupLabels%. Você pode alterar estas permissões e ouvir descrições detalhadas no menu de configurações de aplicativos móveis. Pressione sim para conceder as permissões ou não para negar."
+ },
+ "pt-pt" : {
+ "tts" : "%appName% está a solicitar as seguintes informações e permissões do veículo: %functionalGroupLabels%. Pode alterar estas permissões e ouvir descrições detalhadas no menu de definições das aplicações móveis. Prima \"\"Sim\"\" para permitir ou \"\"Não\"\" para recusar."
+ },
+ "ru-ru" : {
+ "tts" : "%appName% запрашивает следующую информацию об автомобиле и разрешения: %functionalGroupLabels%. Вы можете изменить эти разрешения и прослушать подробные их описания в меню настроек мобильного приложения. Нажмите \"\"да\"\", чтобы предоставить разрешения, или \"\"нет\"\", чтобы не предоставлять."
+ },
+ "sv-se" : {
+ "tts" : "%appName% begär tillgång till följande fordonsinformation och tillstånd: %functionalGroupLabels%. Du kan ändra tillstånden och höra detaljerade beskrivningar i menyn för mobilappsinställningar. Tryck Ja för att ge tillstånd eller Nej för att neka."
+ },
+ "tr-tr" : {
+ "tts" : "%appName%, şu araç bilgilerini ve izinleri istiyor: %functionalGroupLabels%. Bu izinleri değiştirebilir ve mobil uygulamalar ayarlar menüsünden ayrıntılı açıklamaları dinleyebilirsiniz. Lütfen izin vermek için Evet'e veya reddetmek için Hayır'a basın."
+ },
+ "zh-cn" : {
+ "tts" : "%appName% 正在请求下列车辆信息和权限: %functionalGroupLabels%。您可在移动应用程序设置菜单中更改这些权限,并听取详细说明。请按“是”允许权限或按“否”拒绝。"
+ },
+ "zh-tw" : {
+ "tts" : "%appName% 正請求使用 %functionalGroupLabels% 的車輛資訊和許可。您可在行動應用程式設定清單中更改這些許可,並聆聽詳細說明。給予許可請按「是」,拒絕請按「否」。"
+ }
+ }
+ },
+ "AppPermissionsRevoked" : {
+ "languages" : {
+ "de-de" : {
+ "tts" : "Die Autorisierungsdaten der App wurden geändert. %appName% hat keinen Zugriff auf %functionalGroupLabels% mehr. Installieren Sie die neueste Version der App auf Ihrem Gerät.."
+ },
+ "en-au" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-gb" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-ie" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "en-us" : {
+ "tts" : "App authorizations have changed. %appName% can no longer access %functionalGroupLabels%. Please ensure you have the most recent app version installed on your mobile device."
+ },
+ "es-en" : {
+ "tts" : "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "es-es" : {
+ "tts" : "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de que tiene la versión más reciente de la aplicación instalada en su dispositivo móvil."
+ },
+ "es-mx" : {
+ "tts" : "Las autorizaciones de la aplicación han cambiado. %appName% ya no puede acceder a %functionalGroupLabels%. Asegúrese de haber instalado la versión más reciente de la aplicación en su dispositivo móvil."
+ },
+ "fr-ca" : {
+ "tts" : "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "fr-fr" : {
+ "tts" : "Les autorisations pour app ont changé. %appName% ne peut plus accéder à %functionalGroupLabels%. Veuillez vous assurer que la plus récente version de l’application est installée sur votre appareil mobile."
+ },
+ "it-it" : {
+ "tts" : "Le autorizzazioni dell'app sono cambiate. %appName% non è più in grado di accedere a %functionalGroupLabels%. Assicurarsi di avere la versione più recente dell'app installata sul dispositivo mobile."
+ },
+ "nl-nl" : {
+ "tts" : "De app-autorisaties zijn gewijzigd. %appName% heeft geen toegang meer tot %functionalGroupLabels%. Zorg ervoor dat u de meest recente app-versie op uw mobiele apparaat geïnstalleerd hebt."
+ },
+ "pl-pl" : {
+ "tts" : "Dane dostępu aplikacji zostały zmienione. %appName% nie ma już dostępu do %functionalGroupLabels%. Sprawdź, czy na telefonie komórkowym zainstalowano najnowszą wersję aplikacji."
+ },
+ "pt-br" : {
+ "tts" : "As autorizações dos aplicativos foram alteradas. %appName% não pode mais acessar %functionalGroupLabels%. Certifique-se de que a versão mais recente do aplicativo está instalada no seu dispositivo móvel."
+ },
+ "pt-pt" : {
+ "tts" : "As autorizações das aplicações mudaram. %appName% já não consegue aceder a %functionalGroupLabels%. Certifique-se de que tem a última versão da aplicação no seu dispositivo móvel."
+ },
+ "ru-ru" : {
+ "tts" : "Авторизации приложения изменены. %appName% больше не имеет доступа к %functionalGroupLabels%. Убедитесь, что на вашем мобильном устройстве установлена самая новая версия приложения."
+ },
+ "sv-se" : {
+ "tts" : "Appens behörigheter har ändrats. %appName% har inte längre åtkomst till %functionalGroupLabels%. Kontrollera att du har installerat den senaste versionen av appen på mobilenheten."
+ },
+ "tr-tr" : {
+ "tts" : "Uygulama yetkileri değişti. %appName% artık %functionalGroupLabels%'e erişemeyecek. Lütfen mobil aygıtınızda en son uygulama sürümünün yüklü olduğundan emin olun."
+ },
+ "zh-cn" : {
+ "tts" : "应用程序授权已变更。 %appName% 将不能再访问 %functionalGroupLabels%。 请确认您的移动设备上安装的应用程序是最新版本。"
+ },
+ "zh-tw" : {
+ "tts" : "應用程式授權已改變。%appName% 已無法進入 %functionalGroupLabels%。請確認您的行動裝置上安裝了最新版應用程式。"
+ }
+ }
+ },
+ "AppUnauthorized" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "nicht autorisiert",
+ "tts" : "Diese Version von %appName% ist nicht autorisiert und wird nicht mit SYNC funktionieren."
+ },
+ "en-au" : {
+ "line1" : "not authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-gb" : {
+ "line1" : "not authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-ie" : {
+ "line1" : "not authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "en-us" : {
+ "line1" : "Not Authorized",
+ "tts" : "This version of %appName% is not authorized and will not work with SYNC."
+ },
+ "es-en" : {
+ "line1" : "no autorizada",
+ "tts" : "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "es-es" : {
+ "line1" : "No autorizada",
+ "tts" : "Esta versión de %appName% no está autorizada y no funcionará con SYNC."
+ },
+ "es-mx" : {
+ "line1" : "no autorizada",
+ "tts" : "Esta versión de %appName% no tiene autorización y no funcionará con SYNC."
+ },
+ "fr-ca" : {
+ "line1" : "non autorisée",
+ "tts" : "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "fr-fr" : {
+ "line1" : "non autorisée",
+ "tts" : "Cette version de %appName% n’est pas autorisée et ne fonctionnera pas avec SYNC."
+ },
+ "it-it" : {
+ "line1" : "non autorizzata",
+ "tts" : "Questa versione di %appName% non è autorizzata e non funziona con il SYNC."
+ },
+ "nl-nl" : {
+ "line1" : "niet geautoriseerd",
+ "tts" : "Deze versie van %appName% is niet geautoriseerd en werkt niet met SYNC."
+ },
+ "pl-pl" : {
+ "line1" : "brak autoryzacji",
+ "tts" : "Niniejsza wersja %appName% nie posiada autoryzacji i nie będzie działać z SYNC."
+ },
+ "pt-br" : {
+ "line1" : "não autorizado",
+ "tts" : "Esta versão do %appName% não tem autorização e não funcionará com o SYNC."
+ },
+ "pt-pt" : {
+ "line1" : "não autorizada",
+ "tts" : "Esta versão de %appName% não está autorizada e não funcionará com o SYNC."
+ },
+ "ru-ru" : {
+ "line1" : "не авторизировано",
+ "tts" : "Эта версия %appName% не авторизирована и не будет работать с SYNC."
+ },
+ "sv-se" : {
+ "line1" : "är ej godkänd",
+ "tts" : "Den här versionen av %appName% är inte godkänd och fungerar inte med SYNC."
+ },
+ "tr-tr" : {
+ "line1" : "için izin yok",
+ "tts" : "Bu %appName% sürümüne izin verilmediğinden SYNC ile çalışamaz."
+ },
+ "zh-cn" : {
+ "line1" : "未得到授权",
+ "tts" : "此版本的%appName% 未得到授权,无法在SYNC上使用。"
+ },
+ "zh-tw" : {
+ "line1" : "無授權",
+ "tts" : "%appName% 的版本未獲得授權,將無法透過 SYNC 使用。"
+ }
+ }
+ },
+ "AppUnsupported" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "nicht unterstützt",
+ "tts" : "Diese Version von %appName% wird von SYNC nicht unterstützt."
+ },
+ "en-au" : {
+ "line1" : "not supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "en-gb" : {
+ "line1" : "not supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "en-ie" : {
+ "line1" : "not supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "en-us" : {
+ "line1" : "Not Supported",
+ "tts" : "This version of %appName% is not supported by SYNC."
+ },
+ "es-en" : {
+ "line1" : "no compatible",
+ "tts" : "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-es" : {
+ "line1" : "No compatible",
+ "tts" : "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "es-mx" : {
+ "line1" : "no compatible",
+ "tts" : "Esta versión de %appName% no es compatible con SYNC."
+ },
+ "fr-ca" : {
+ "line1" : "incompatible",
+ "tts" : "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "fr-fr" : {
+ "line1" : "incompatible",
+ "tts" : "Cette version de %appName% n’est pas prise en charge par SYNC."
+ },
+ "it-it" : {
+ "line1" : "non supportata",
+ "tts" : "Questa versione di %appName% non è supportata dal SYNC."
+ },
+ "nl-nl" : {
+ "line1" : "niet ondersteund",
+ "tts" : "Deze versie van %appName% wordt niet ondersteund door SYNC."
+ },
+ "pl-pl" : {
+ "line1" : "aplikacja nie obsług.",
+ "tts" : "Niniejsza wersja %appName% nie jest obsługiwana przez system SYNC."
+ },
+ "pt-br" : {
+ "line1" : "não suportado",
+ "tts" : "Esta versão do %appName% não é suportada pelo SYNC."
+ },
+ "pt-pt" : {
+ "line1" : "não suportada",
+ "tts" : "Esta versão de %appName% não é suportado pelo SYNC."
+ },
+ "ru-ru" : {
+ "line1" : "не поддерживается",
+ "tts" : "Эта версия %appName% не поддерживается SYNC."
+ },
+ "sv-se" : {
+ "line1" : "stöds ej",
+ "tts" : "SYNC har inte stöd för den här versionen av %appName%."
+ },
+ "tr-tr" : {
+ "line1" : "desteklenmiyor",
+ "tts" : "Bu %appName% sürümü SYNC tarafından desteklenmiyor."
+ },
+ "zh-cn" : {
+ "line1" : "不受支持",
+ "tts" : "SYNC不支持此版本的%appName%。"
+ },
+ "zh-tw" : {
+ "line1" : "不支援",
+ "tts" : "SYNC 不支援此版本的%appName% 。"
+ }
+ }
+ },
+ "DataConsent" : {
+ "languages" : {
+ "en-us" : {
+ "line1" : "Enable Mobile Apps",
+ "line2" : "on SYNC? (Uses Data)",
+ "tts" : "To use mobile apps with SYNC, SYNC will communicate with Ford at least once per month using your mobile device's data plan. Standard rates may apply. SYNC will send your VIN and SYNC module number to Ford U.S. Please press yes or no, or help for more information. "
+ }
+ }
+ },
+ "DataConsentHelp" : {
+ "languages" : {
+ "en-us" : {
+ "tts" : "Updates are about the size of an email, and the occurrence of updates depends on your vehicle usage and when a new app is found on your device. To turn on or off, visit the SYNC mobile apps settings menu. See your Owner Guide for more information. "
+ }
+ }
+ },
+ "DisableApps" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Auto-Update",
+ "line2" : "und Mobile Apps deaktivieren",
+ "tts" : "Ausschalten der automatischen Updates führt zum Ausschalten von SYNC mobile Apps. Sie können Ihre mobilen Apps dann nicht mehr mit SYNC nutzen. Bitte drücken Sie Ja zur Bestätigung oder Nein, um abzubrechen."
+ },
+ "en-au" : {
+ "line1" : "Disable auto-updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-gb" : {
+ "line1" : "Disable auto-updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-ie" : {
+ "line1" : "Disable auto-updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable SYNC mobile apps. You will not be able to use any mobile apps with SYNC. Please press Yes to confirm or No to cancel."
+ },
+ "en-us" : {
+ "line1" : "Disable Auto-Updates",
+ "line2" : "and Mobile Apps?",
+ "tts" : "Disabling automatic updates will also disable sync mobile apps. You will not be able to use any mobile apps with SYNC. Please press yes to confirm or no to cancel."
+ },
+ "es-en" : {
+ "line1" : "¿Deshab. actualiz.",
+ "line2" : "autom. y aplic. móv.?",
+ "tts" : "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "es-es" : {
+ "line1" : "¿Desact. actual. auto",
+ "line2" : "y apl. móviles?",
+ "tts" : "Si desactiva las actualizaciones automáticas, también se desactivará la sincronización de las aplicaciones móviles. No podrá utilizar ninguna aplicación móvil con SYNC. Pulse sí para confirmar o no para cancelar."
+ },
+ "es-mx" : {
+ "line1" : "¿Deshab. actualiz.",
+ "line2" : "autom. y aplic. móv.?",
+ "tts" : "Si se desactivan las actualizaciones automáticas, también se desactivarán las aplicaciones móviles de SYNC. No podrá usar ninguna aplicación móvil con SYNC. Presione Sí para confirmar o No para cancelar."
+ },
+ "fr-ca" : {
+ "line1" : "Désactiver màj autom.",
+ "line2" : "et app. mobiles?",
+ "tts" : "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "fr-fr" : {
+ "line1" : "Désactiver màj autom.",
+ "line2" : "et app. mobiles?",
+ "tts" : "La désactivation des mises à jour automatiques désactivera aussi les applications mobiles SYNC. Vous ne pourrez pas utiliser d’application mobile avec SYNC. Veuillez appuyer sur Oui pour confirmer ou sur Non pour annuler."
+ },
+ "it-it" : {
+ "line1" : "Disabilitare agg. aut.",
+ "line2" : "e app mobili?",
+ "tts" : "Disabilitando gli aggiornamenti automatici si disattiva anche la sincronizzazione delle app mobili. Non sarà possibile usare app mobili con il SYNC. Premere Sì per confermare e No per cancellare."
+ },
+ "nl-nl" : {
+ "line1" : "Auto-updates en mob.",
+ "line2" : "apps uitschakelen?",
+ "tts" : "Door automatische updates uit te schakelen, schakelt u ook SYNC-mobiele apps uit. U kunt dan geen mobiele apps meer gebruiken met SYNC. Druk op Ja om te bevestigen of op Nee om te annuleren."
+ },
+ "pl-pl" : {
+ "line1" : "Wył. automat. aktual.",
+ "line2" : "i aplikacje mobilne?",
+ "tts" : "Wyłączenie automatycznych aktualizacji spowoduje także wyłączenie aplikacji mobilnych SYNC. Korzystanie z mobilnych aplikacji za pomocą SYNC będzie niemożliwe. Naciśnij TAK, by potwierdzić lub NIE, by anulować."
+ },
+ "pt-br" : {
+ "line1" : "Desativar atualizações",
+ "line2" : "autom. e aplicativos?",
+ "tts" : "Se as atualizações automáticas forem desativadas, os aplicativos também serão desativados. Você não poderá usar nenhum aplicativo com o SYNC. Pressione sim para confirmar ou não para cancelar."
+ },
+ "pt-pt" : {
+ "line1" : "Desact. actual. autom.",
+ "line2" : "e aplicações móveis?",
+ "tts" : "A desactivação das actualizações automáticas desactiva igualmente as aplicações móveis do SYNC. Não poderá utilizar quaisquer aplicações móveis com o SYNC. Prima \"\"Sim\"\" para confirmar ou \"\"Não\"\" para cancelar."
+ },
+ "ru-ru" : {
+ "line1" : "Откл. автообновления",
+ "line2" : "и мобил. прилож.?",
+ "tts" : "При отключении автоматических обновлений также будут отключены мобильные приложения sync. Вы не сможете использовать какие-либо мобильные приложения с SYNC. Нажмите \"\"Да\"\" для подтверждения или \"\"Нет\"\" для отмены."
+ },
+ "sv-se" : {
+ "line1" : "Avaktiverar autouppdat.",
+ "line2" : "och mobilappar?",
+ "tts" : "Om du avaktiverar automatisk uppdatering avaktiverar du även synkning av mobilappar. Du kommer inte längre att kunna använda dina mobilappar med SYNC. Tryck Ja för att bekräfta eller Nej för att avbryta."
+ },
+ "tr-tr" : {
+ "line1" : "Oto. güncelleme ve",
+ "line2" : "mobil uygul. kapat?",
+ "tts" : "Otomatik güncellemeleri devre dışı bırakırsanız sync mobil uygulamalar da devre dışı kalır. SYNC ile mobil uygulama kullanmanız mümkün olmaz. Lütfen onaylamak için Evet'e veya iptal etmek için Hayır'a basın."
+ },
+ "zh-cn" : {
+ "line1" : "是否禁用自动更新和",
+ "line2" : "移动应用程序?",
+ "tts" : "禁用自动更新同时也会禁用SYNC移动应用程序。您将无法在 SYNC 中使用任何移动应用程序。请按“是”确认或按“否”取消。"
+ },
+ "zh-tw" : {
+ "line1" : "停用自動更新",
+ "line2" : "和行動應用程式?",
+ "tts" : "停用自動更新也將停用 sync 行動應用程式。您將無法透過 SYNC 使用任何行動應用程式。確認請按「是」,取消請按「否」。"
+ }
+ }
+ },
+ "DrivingCharacteristics" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "Fahreigenschaften",
+ "tts" : "Eine App hat Zugriff auf die folgenden Fahreigenschaften: Kraftstoffverbrauch, MyKey, Sicherheitsgurtstatus."
+ },
+ "en-au" : {
+ "label" : "Driving characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-gb" : {
+ "label" : "Driving characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-ie" : {
+ "label" : "Driving characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel consumption, MyKey, Seat belt status."
+ },
+ "en-us" : {
+ "label" : "Driving Characteristics",
+ "tts" : "An app can access the following driving characteristics: Fuel Consumption, MyKey, Seat Belt Status."
+ },
+ "es-en" : {
+ "label" : "Características del manejo",
+ "tts" : "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "es-es" : {
+ "label" : "Características de conducción",
+ "tts" : "Una aplicación puede acceder a las siguientes características de conducción: Consumo de combustible, MyKey, Estado cinturones de seguridad."
+ },
+ "es-mx" : {
+ "label" : "Características del manejo",
+ "tts" : "Las aplicaciones pueden acceder a las siguientes características del manejo: Consumo de combustible, MyKey, Estado del cinturón de seguridad."
+ },
+ "fr-ca" : {
+ "label" : "Caractéristiques de conduite",
+ "tts" : "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "fr-fr" : {
+ "label" : "Caractéristiques de conduite",
+ "tts" : "Une application peut accéder aux caractéristiques de conduite suivantes: Consommation de carburant, MyKey, État des ceintures de sécurité."
+ },
+ "it-it" : {
+ "label" : "Caratteristiche di guida",
+ "tts" : "Un'app può avere accesso alle seguenti caratteristiche di guida: Consumo carburante, MyKey, Stato cinture di sicurezza."
+ },
+ "nl-nl" : {
+ "label" : "Rijkenmerken",
+ "tts" : "Een app heeft toegang tot de volgende rijkenmerken: Brandstofverbruik, MyKey, Veiligheidsgordelstatus."
+ },
+ "pl-pl" : {
+ "label" : "Informacje dotyczące stylu jazdy",
+ "tts" : "Aplikacja może uzyskać dostęp do następujących informacji dotyczących jazdy: Zużycie paliwa, MyKey, Stan pasów bezpieczeństwa."
+ },
+ "pt-br" : {
+ "label" : "Características de condução",
+ "tts" : "Um aplicativo pode acessar as seguintes características de condução: Consumo de combustível, MyKey, Estado do cinto de segurança."
+ },
+ "pt-pt" : {
+ "label" : "Características de condução",
+ "tts" : "Uma aplicação consegue aceder às seguintes informações de condução: Consumo de combustível, MyKey, Estado dos cintos de segurança."
+ },
+ "ru-ru" : {
+ "label" : "Характеристики движения",
+ "tts" : "Приложение имеет доступ к следующим характеристикам движения: Расход топлива, MyKey, Состояние ремней безопасности."
+ },
+ "sv-se" : {
+ "label" : "Köregenskaper",
+ "tts" : "Appen kan komma åt följande köregenskaper: Bränsleförbrukning, MyKey, Bältesstatus."
+ },
+ "tr-tr" : {
+ "label" : "Sürüş karakteristikleri",
+ "tts" : "Bir uygulama şu sürüş karakteristiklerine erişebilir: Yakıt tüketimi, MyKey, Emniyet kemeri durumu."
+ },
+ "zh-cn" : {
+ "label" : "行驶特性",
+ "tts" : "移动应用程序可访问下列行驶特性: 油耗, MyKey, 安全带状态"
+ },
+ "zh-tw" : {
+ "label" : "駕駛特性",
+ "tts" : "應用程式可存取以下駕駛特性: 油耗, MyKey, 安全帶狀態"
+ }
+ }
+ },
+ "Location" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "GPS und Geschwindigkeit",
+ "tts" : "Eine App hat Zugriff auf die GPS-Daten und die Geschwindigkeit des Fahrzeugs."
+ },
+ "en-au" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "en-gb" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "en-ie" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "en-us" : {
+ "label" : "GPS and speed",
+ "tts" : "An app can access vehicle GPS and speed."
+ },
+ "es-en" : {
+ "label" : "GPS y velocidad",
+ "tts" : "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "es-es" : {
+ "label" : "GPS y velocidad",
+ "tts" : "Una aplicación puede acceder al GPS y la velocidad del vehículo."
+ },
+ "es-mx" : {
+ "label" : "GPS y velocidad",
+ "tts" : "Las aplicaciones pueden acceder al GPS y a la velocidad del vehículo."
+ },
+ "fr-ca" : {
+ "label" : "GPS et vitesse",
+ "tts" : "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "fr-fr" : {
+ "label" : "GPS et vitesse",
+ "tts" : "Une application peut accéder au GPS et à la vitesse du véhicule."
+ },
+ "it-it" : {
+ "label" : "GPS e velocità",
+ "tts" : "Un'app può avere accesso a GPS e velocità del veicolo."
+ },
+ "nl-nl" : {
+ "label" : "Gps en snelheid",
+ "tts" : "Een app heeft toegang tot gps en de snelheid van het voertuig."
+ },
+ "pl-pl" : {
+ "label" : "GPS i prędkość",
+ "tts" : "Aplikacja może uzyskać dostęp do modułu GPS i prędkości pojazdu."
+ },
+ "pt-br" : {
+ "label" : "GPS e velocidade",
+ "tts" : "Um aplicativo pode acessar o GPS e a velocidade do veículo."
+ },
+ "pt-pt" : {
+ "label" : "GPS e velocidade",
+ "tts" : "Uma aplicação consegue aceder ao GPS e à velocidade do veículo."
+ },
+ "ru-ru" : {
+ "label" : "GPS и скорость",
+ "tts" : "Приложение имеет доступ к GPS и скорости автомобиля."
+ },
+ "sv-se" : {
+ "label" : "GPS och hastighet",
+ "tts" : "Appen kan komma åt fordonets GPS och hastighetsmätare."
+ },
+ "tr-tr" : {
+ "label" : "GPS ve hız",
+ "tts" : "Bu uygulama aracın GPS ve hız bilgilerine erişebilir."
+ },
+ "zh-cn" : {
+ "label" : "GPS 和车速",
+ "tts" : "移动应用程序可以访问车辆 GPS 和车速信息。"
+ },
+ "zh-tw" : {
+ "label" : "GPS和車速",
+ "tts" : "應用程式可存取車輛的GPS和速度。"
+ }
+ }
+ },
+ "Notifications" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "Push-Benachrichtigungen",
+ "tts" : "Läuft die App im Hintergrund, kann Sie Benachrichtigungen senden."
+ },
+ "en-au" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "en-gb" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "en-ie" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "en-us" : {
+ "label" : "Push notifications",
+ "tts" : "An app can send notifications when running in the background."
+ },
+ "es-en" : {
+ "label" : "Notificaciones tipo Push",
+ "tts" : "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "es-es" : {
+ "label" : "Notificaciones push",
+ "tts" : "Una aplicación puede enviar notificaciones cuando se está ejecutando en segundo plano."
+ },
+ "es-mx" : {
+ "label" : "Notificaciones tipo Push",
+ "tts" : "Las aplicaciones pueden enviar notificaciones cuando se ejecutan en segundo plano."
+ },
+ "fr-ca" : {
+ "label" : "Notifications instantanées",
+ "tts" : "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "fr-fr" : {
+ "label" : "Notifications push",
+ "tts" : "Une application peut envoyer des avis lorsqu’elle fonctionne en arrière-plan."
+ },
+ "it-it" : {
+ "label" : "Notifiche push",
+ "tts" : "Un'app può inviare notifiche se eseguita in background."
+ },
+ "nl-nl" : {
+ "label" : "Push-meldingen",
+ "tts" : "Een app kan meldingen versturen als deze op de achtergrond actief is."
+ },
+ "pl-pl" : {
+ "label" : "Powiadomienia Push",
+ "tts" : "Aplikacja może wysyłać powiadomienia, działając w tle."
+ },
+ "pt-br" : {
+ "label" : "Notificações Push",
+ "tts" : "Um aplicativo pode enviar notificações quando estiver sendo executado em segundo plano."
+ },
+ "pt-pt" : {
+ "label" : "Notificações push",
+ "tts" : "Uma aplicação consegue enviar notificações quando está activa em segundo plano."
+ },
+ "ru-ru" : {
+ "label" : "Оповещения о пересылке",
+ "tts" : "Если приложение работает в фоновом режиме, оно может отправлять оповещения."
+ },
+ "sv-se" : {
+ "label" : "Push-notiser",
+ "tts" : "Appen kan skicka meddelanden när den körs i bakgrunden."
+ },
+ "tr-tr" : {
+ "label" : "Anlık bildirimleri",
+ "tts" : "Bir uygulama arka planda çalışırken bildirim gönderebilir."
+ },
+ "zh-cn" : {
+ "label" : "推送通知",
+ "tts" : "移动应用程序在后台运行时可推送通知。"
+ },
+ "zh-tw" : {
+ "label" : "傳送通知",
+ "tts" : "車輛行進時,應用程式可在背景中傳送通知。"
+ }
+ }
+ },
+ "SettingDisableUpdates" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Updates deakt."
+ },
+ "en-au" : {
+ "line1" : "Disable updates"
+ },
+ "en-gb" : {
+ "line1" : "Disable updates"
+ },
+ "en-ie" : {
+ "line1" : "Disable updates"
+ },
+ "en-us" : {
+ "line1" : "Disable Updates"
+ },
+ "es-en" : {
+ "line1" : "Deshab. actual."
+ },
+ "es-es" : {
+ "line1" : "Desact. actual."
+ },
+ "es-mx" : {
+ "line1" : "Deshab. actual."
+ },
+ "fr-ca" : {
+ "line1" : "Désactiver MAJ"
+ },
+ "fr-fr" : {
+ "line1" : "Désactiver màj"
+ },
+ "it-it" : {
+ "line1" : "Disabilita agg."
+ },
+ "nl-nl" : {
+ "line1" : "Upd. uitschak."
+ },
+ "pl-pl" : {
+ "line1" : "Wyłącz aktual."
+ },
+ "pt-br" : {
+ "line1" : "Desat. atualiz."
+ },
+ "pt-pt" : {
+ "line1" : "Desact. actualiz."
+ },
+ "ru-ru" : {
+ "line1" : "Откл. обновл."
+ },
+ "sv-se" : {
+ "line1" : "Inaktivera uppd."
+ },
+ "tr-tr" : {
+ "line1" : "Güncell. Kapat"
+ },
+ "zh-cn" : {
+ "line1" : "禁用更新"
+ },
+ "zh-tw" : {
+ "line1" : "停用更新"
+ }
+ }
+ },
+ "SettingEnableUpdates" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Apps aktivieren"
+ },
+ "en-au" : {
+ "line1" : "Enable Apps"
+ },
+ "en-gb" : {
+ "line1" : "Enable Apps"
+ },
+ "en-ie" : {
+ "line1" : "Enable Apps"
+ },
+ "en-us" : {
+ "line1" : "Enable Apps"
+ },
+ "es-en" : {
+ "line1" : "Hab. aplic."
+ },
+ "es-es" : {
+ "line1" : "Activar apl."
+ },
+ "es-mx" : {
+ "line1" : "Hab. aplic."
+ },
+ "fr-ca" : {
+ "line1" : "Activer app."
+ },
+ "fr-fr" : {
+ "line1" : "Activer app."
+ },
+ "it-it" : {
+ "line1" : "Abilita app"
+ },
+ "nl-nl" : {
+ "line1" : "Apps inschak."
+ },
+ "pl-pl" : {
+ "line1" : "Włącz aplikacje"
+ },
+ "pt-br" : {
+ "line1" : "Ativar aplic."
+ },
+ "pt-pt" : {
+ "line1" : "Activar actualiz."
+ },
+ "ru-ru" : {
+ "line1" : "Вкл. прилож."
+ },
+ "sv-se" : {
+ "line1" : "Aktivera appar"
+ },
+ "tr-tr" : {
+ "line1" : "Uygulamaları aç"
+ },
+ "zh-cn" : {
+ "line1" : "启用应用程序"
+ },
+ "zh-tw" : {
+ "line1" : "啟用應用程式"
+ }
+ }
+ },
+ "SettingUpdateAuto" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Update anford."
+ },
+ "en-au" : {
+ "line1" : "Request update"
+ },
+ "en-gb" : {
+ "line1" : "Request update"
+ },
+ "en-ie" : {
+ "line1" : "Request update"
+ },
+ "en-us" : {
+ "line1" : "Request Update"
+ },
+ "es-en" : {
+ "line1" : "Solicit. actualiz."
+ },
+ "es-es" : {
+ "line1" : "Solicitar actual."
+ },
+ "es-mx" : {
+ "line1" : "Solicit. actualiz."
+ },
+ "fr-ca" : {
+ "line1" : "Demander MAJ"
+ },
+ "fr-fr" : {
+ "line1" : "Demander màj"
+ },
+ "it-it" : {
+ "line1" : "Rich. aggiorn."
+ },
+ "nl-nl" : {
+ "line1" : "Upd. aanvragen"
+ },
+ "pl-pl" : {
+ "line1" : "Zażądaj aktual."
+ },
+ "pt-br" : {
+ "line1" : "Solicitar atualiz."
+ },
+ "pt-pt" : {
+ "line1" : "Solicit. actualiz."
+ },
+ "ru-ru" : {
+ "line1" : "Запрос на обн."
+ },
+ "sv-se" : {
+ "line1" : "Begär uppdat."
+ },
+ "tr-tr" : {
+ "line1" : "Güncelleme iste"
+ },
+ "zh-cn" : {
+ "line1" : "请求更新"
+ },
+ "zh-tw" : {
+ "line1" : "請求更新"
+ }
+ }
+ },
+ "StatusNeeded" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Update benötigt"
+ },
+ "en-au" : {
+ "line1" : "Update needed"
+ },
+ "en-gb" : {
+ "line1" : "Update needed"
+ },
+ "en-ie" : {
+ "line1" : "Update needed"
+ },
+ "en-us" : {
+ "line1" : "Update Needed"
+ },
+ "es-en" : {
+ "line1" : "Actualiz. neces."
+ },
+ "es-es" : {
+ "line1" : "Actu. necesaria"
+ },
+ "es-mx" : {
+ "line1" : "Actualiz. neces."
+ },
+ "fr-ca" : {
+ "line1" : "Màj requise"
+ },
+ "fr-fr" : {
+ "line1" : "Mise à jour requise"
+ },
+ "it-it" : {
+ "line1" : "Necess. aggiorn."
+ },
+ "nl-nl" : {
+ "line1" : "Update nodig"
+ },
+ "pl-pl" : {
+ "line1" : "Potrzeba aktual."
+ },
+ "pt-br" : {
+ "line1" : "Atualiz. necess."
+ },
+ "pt-pt" : {
+ "line1" : "Actual. necess."
+ },
+ "ru-ru" : {
+ "line1" : "Необх. обновл."
+ },
+ "sv-se" : {
+ "line1" : "Uppdat. krävs"
+ },
+ "tr-tr" : {
+ "line1" : "Güncellenmeli"
+ },
+ "zh-cn" : {
+ "line1" : "需要进行更新"
+ },
+ "zh-tw" : {
+ "line1" : "需更新"
+ }
+ }
+ },
+ "StatusPending" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Aktualisieren..."
+ },
+ "en-au" : {
+ "line1" : "Updating..."
+ },
+ "en-gb" : {
+ "line1" : "Updating..."
+ },
+ "en-ie" : {
+ "line1" : "Updating..."
+ },
+ "en-us" : {
+ "line1" : "Updating..."
+ },
+ "es-en" : {
+ "line1" : "Actualizando..."
+ },
+ "es-es" : {
+ "line1" : "Actualizando..."
+ },
+ "es-mx" : {
+ "line1" : "Actualizando..."
+ },
+ "fr-ca" : {
+ "line1" : "MAJ en cours..."
+ },
+ "fr-fr" : {
+ "line1" : "Màj en cours..."
+ },
+ "it-it" : {
+ "line1" : "Aggiornamento"
+ },
+ "nl-nl" : {
+ "line1" : "Updaten..."
+ },
+ "pl-pl" : {
+ "line1" : "Aktualizowanie"
+ },
+ "pt-br" : {
+ "line1" : "Atualizando..."
+ },
+ "pt-pt" : {
+ "line1" : "A actualizar..."
+ },
+ "ru-ru" : {
+ "line1" : "Обновление..."
+ },
+ "sv-se" : {
+ "line1" : "Uppdaterar..."
+ },
+ "tr-tr" : {
+ "line1" : "Güncelleniyor..."
+ },
+ "zh-cn" : {
+ "line1" : "正在更新......"
+ },
+ "zh-tw" : {
+ "line1" : "更新中..."
+ }
+ }
+ },
+ "StatusUpToDate" : {
+ "languages" : {
+ "de-de" : {
+ "line1" : "Aktuelle Version"
+ },
+ "en-au" : {
+ "line1" : "Up-to-date"
+ },
+ "en-gb" : {
+ "line1" : "Up-to-date"
+ },
+ "en-ie" : {
+ "line1" : "Up-to-date"
+ },
+ "en-us" : {
+ "line1" : "Up-To-Date"
+ },
+ "es-en" : {
+ "line1" : "Actualizado"
+ },
+ "es-es" : {
+ "line1" : "Actualizada"
+ },
+ "es-mx" : {
+ "line1" : "Actualizado"
+ },
+ "fr-ca" : {
+ "line1" : "Déjà à jour"
+ },
+ "fr-fr" : {
+ "line1" : "Déjà à jour"
+ },
+ "it-it" : {
+ "line1" : "più recente"
+ },
+ "nl-nl" : {
+ "line1" : "Up-to-date"
+ },
+ "pl-pl" : {
+ "line1" : "Aktualne"
+ },
+ "pt-br" : {
+ "line1" : "Atualizado"
+ },
+ "pt-pt" : {
+ "line1" : "Actualizado"
+ },
+ "ru-ru" : {
+ "line1" : "Обновлено"
+ },
+ "sv-se" : {
+ "line1" : "Uppdat. krävs ej"
+ },
+ "tr-tr" : {
+ "line1" : "Güncel"
+ },
+ "zh-cn" : {
+ "line1" : "最新更新"
+ },
+ "zh-tw" : {
+ "line1" : "更新最新"
+ }
+ }
+ },
+ "VehicleInfo" : {
+ "languages" : {
+ "de-de" : {
+ "label" : "Fahrzeuginformationen",
+ "tts" : "Eine App hat Zugriff auf die folgenden Fahrzeuginformationen: Kraftstoff-Füllstand, Kraftstoffverbrauch, Motordrehzahl, Kilometerzähler, FIN, Außentemperatur, Gangstellung, Reifenluftdruck."
+ },
+ "en-au" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure."
+ },
+ "en-gb" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure."
+ },
+ "en-ie" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel level, Fuel economy, Engine RPMs, Odometer, VIN, Outside air temperature, Gear position, Tyre pressure."
+ },
+ "en-us" : {
+ "label" : "Vehicle information",
+ "tts" : "An app can access the following vehicle information: Fuel Level, Fuel Economy, Engine RPMs, Odometer, VIN, External Temperature, Gear Position, Tire Pressure."
+ },
+ "es-en" : {
+ "label" : "Información del vehículo",
+ "tts" : "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "es-es" : {
+ "label" : "Información del vehículo",
+ "tts" : "Una aplicación puede acceder a la siguiente información del vehículo: Nivel de combustible, Ahorro de combustible, RPM del motor, Cuentakilómetros, VIN, Temperatura aire exterior, Marcha engranada, Presión de neumáticos."
+ },
+ "es-mx" : {
+ "label" : "Información del vehículo",
+ "tts" : "Las aplicaciones pueden acceder a la siguiente información del vehículo: Nivel de combustible, Economía de combustible, RPM del motor, Cuentakilómetros, Número de identificación del vehículo, Temperatura externa, Posición del cambio, Presión de los neumáticos."
+ },
+ "fr-ca" : {
+ "label" : "Renseignements du véhicule",
+ "tts" : "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Au régime du moteur, Odomètre, NIV, Température extérieure, Position d’embrayage, Pression des pneus."
+ },
+ "fr-fr" : {
+ "label" : "Renseignements du véhicule",
+ "tts" : "Une application peut accéder aux informations suivantes du véhicule: Niveau de carburant, Économie de carburant, Vitesse de moteur, Compteur kilométrique, NIV, Température extérieure, Position de vitesse, Pression des pneus."
+ },
+ "it-it" : {
+ "label" : "Informazioni sul veicolo",
+ "tts" : "Un'app può avere accesso alle seguenti informazioni del veicolo: Livello carburante, Consumi carburante, Numero giri motore, Contachilometri, VIN, Temperatura esterna, Posizione marcia, Pressione pneumatici."
+ },
+ "nl-nl" : {
+ "label" : "Voertuiginformatie",
+ "tts" : "Een app heeft toegang tot de volgende voertuiginformatie: Brandstofpeil, Brandstofverbruik, Motortoerental, Kilometerteller, VIN, Buitentemperatuur, Versnellingsstand, Bandenspanning."
+ },
+ "pl-pl" : {
+ "label" : "Informacje o pojeździe",
+ "tts" : "Aplikacja może uzyskać dostęp do następujących informacji o pojeździe: Poziom paliwa, Zużycie paliwa, Obroty silnika, Licznik przebiegu, Numer VIN, Temperatura zewnętrzna, Aktualny bieg, Ciśnienie opon."
+ },
+ "pt-br" : {
+ "label" : "Informações sobre o veículo",
+ "tts" : "Um aplicativo pode acessar as seguintes informações sobre o veículo: Nível de combustível, Economia de combustível, RPM do motor, Hodômetro, VIN, Temperatura externa, Posição das marchas, Pressão dos pneus."
+ },
+ "pt-pt" : {
+ "label" : "Informações do veículo",
+ "tts" : "Uma aplicação consegue aceder às seguintes informações do veículo: Nível de combustível, Poupança de combustível, RPM do motor, Conta-quilómetros, VIN, Temperatura exterior, Posição da mudança de velocidade, Pressão dos pneus."
+ },
+ "ru-ru" : {
+ "label" : "Информация об автомобиле",
+ "tts" : "Приложение имеет доступ к следующим данным автомобиля: Уровень топлива, Економия топлива, Число оборотов двигателя, Одометр, Номер VIN, Температура за бортом, Положение передачи, Давление шин."
+ },
+ "sv-se" : {
+ "label" : "Fordonsinformation",
+ "tts" : "Appen kan komma åt följande fordonsinformation: Bränslenivå, Bränsleekonomi, Motorns varvtal, Vägmätare, VIN, Utetemperatur, Växelläge, Däcktryck."
+ },
+ "tr-tr" : {
+ "label" : "Araç bilgisi",
+ "tts" : "Bir uygulama şu araç bilgilerine erişebilir: Yakıt seviyesi, Yakıt ekonomisi, Motor devirleri, Kilometre sayacı, VIN, Dış sıcaklık, Vites konumu, Lastik basıncı."
+ },
+ "zh-cn" : {
+ "label" : "车辆信息",
+ "tts" : "移动应用程序可访问下列车辆信息 : 燃油量, 燃油经济性, 发动机转速(RPM), 里程表, VIN, 车外温度, 档位, 胎压."
+ },
+ "zh-tw" : {
+ "label" : "車輛資訊",
+ "tts" : "一個應用程式可存取以下車輛資訊 : 燃油存量, 燃油經濟性, 引擎轉速, 里程表, 車輛識別號碼, 車外溫度, 檔位, 胎壓."
+ }
+ }
+ }
+ },
+ "version" : "001.001.015"
+ },
+ "functional_groupings" : {
+ "Base-4" : {
+ "rpcs" : {
+ "AddCommand" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "AddSubMenu" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "Alert" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "ChangeRegistration" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "CreateInteractionChoiceSet" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "DeleteCommand" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "DeleteFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "DeleteInteractionChoiceSet" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "DeleteSubMenu" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "EncodedSyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "EndAudioPassThru" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "GenericResponse" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ListFiles" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnAppInterfaceUnregistered" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnAudioPassThru" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "OnButtonEvent" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "OnButtonPress" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "OnCommand" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "OnDriverDistraction" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "OnEncodedSyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnHMIStatus" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnLanguageChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnPermissionsChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnSyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnTBTClientState" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "PerformAudioPassThru" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "PerformInteraction" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "PutFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "RegisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "ResetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ScrollableMessage" : {
+ "hmi_levels" : [ "FULL" ]
+ },
+ "SetAppIcon" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetDisplayLayout" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "SetMediaClockTimer" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "Show" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "Slider" : {
+ "hmi_levels" : [ "FULL" ]
+ },
+ "Speak" : {
+ "hmi_levels" : [ "FULL", "LIMITED" ]
+ },
+ "SubscribeButton" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "SyncPData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "UnregisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "UnsubscribeButton" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ }
+ }
+ },
+ "DrivingCharacteristics-3" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "accPedalPosition",
+ "beltStatus",
+ "driverBraking",
+ "myKey",
+ "prndl",
+ "rpm",
+ "steeringWheelAngle"
+ ]
+ }
+ },
+ "user_consent_prompt" : "DrivingCharacteristics"
+ },
+ "Emergency-1" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "airbagStatus",
+ "bodyInformation",
+ "clusterModeStatus",
+ "deviceStatus",
+ "eCallInfo",
+ "emergencyEvent"
+ ]
+ }
+ }
+ },
+ "Location-1" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [ "gps", "speed" ]
+ }
+ },
+ "user_consent_prompt" : "Location"
+ },
+ "Navigation-1" : {
+ "rpcs" : {
+ "AlertManeuver" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ShowConstantTBT" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "UpdateTurnList" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ }
+ }
+ },
+ "Notifications" : {
+ "rpcs" : {
+ "Alert" : {
+ "hmi_levels" : [ "BACKGROUND" ]
+ }
+ },
+ "user_consent_prompt" : "Notifications"
+ },
+ "PropriataryData-1" : {
+ "rpcs" : {
+ "DiagnosticMessage" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "GetDTCs" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ReadDID" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ }
+ }
+ },
+ "VehicleInfo-3" : {
+ "rpcs" : {
+ "GetVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"
+ ]
+ },
+ "OnVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "vin",
+ "wiperStatus"
+ ]
+ },
+ "SubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"
+ ]
+ },
+ "UnsubscribeVehicleData" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ],
+ "parameters" : [
+ "engineTorque",
+ "externalTemperature",
+ "fuelLevel",
+ "fuelLevel_State",
+ "headLampStatus",
+ "instantFuelConsumption",
+ "odometer",
+ "tirePressure",
+ "wiperStatus"
+ ]
+ }
+ },
+ "user_consent_prompt" : "VehicleInfo"
+ },
+ "pre_Base-1" : {
+ "rpcs" : {
+ "ChangeRegistration" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "DeleteFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "GenericResponse" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "ListFiles" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnAppInterfaceUnregistered" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnLanguageChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "OnPermissionsChange" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "PutFile" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "RegisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "ResetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "SetAppIcon" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetDisplayLayout" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ },
+ "SetGlobalProperties" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED" ]
+ },
+ "UnregisterAppInterface" : {
+ "hmi_levels" : [ "BACKGROUND", "FULL", "LIMITED", "NONE" ]
+ }
+ }
+ }
+ },
+ "module_config" : {
+ "device_certificates" : {
+ "HUU40DAS7F970UEI17A73JH32L41K32JH4L1K234H3K4" : "aldhfkahfgkafrblgjr"
+ },
+ "endpoints" : {
+ "0x07" : {
+ "default" : [ "http://policies.telematics.ford.com/api/policies" ]
+ }
+ },
+ "exchange_after_x_days" : 30,
+ "exchange_after_x_ignition_cycles" : 100,
+ "exchange_after_x_kilometers" : 1800,
+ "notifications_per_minute_by_priority" : {
+ "COMMUNICATION" : 6,
+ "EMERGENCY" : 60,
+ "NAVIGATION" : 15,
+ "NONE" : 0,
+ "NORMAL" : 4,
+ "VOICECOMM" : 10
+ },
+ "seconds_between_retries" : [ 1, 5, 25, 125, 625 ],
+ "timeout_after_x_seconds" : 60,
+ "vehicle_make" : "Stark Industries",
+ "vehicle_model" : "E-Tron",
+ "vehicle_year" : "1992"
+ }
+ }
+}
diff --git a/src/components/policy/test/shared_library_test.cc b/src/components/policy/test/shared_library_test.cc
index f8f77f1fda..f4177f0fd9 100644
--- a/src/components/policy/test/shared_library_test.cc
+++ b/src/components/policy/test/shared_library_test.cc
@@ -45,27 +45,28 @@ namespace policy {
}
}
-TEST(SharedLibraryTest, FullTest_OpenLibrarySetSymbolCloseLibrary_ExpectActsWithoutErrors) {
- //Arrange
- const std::string kLib = "../src/policy/libPolicy.so";
+TEST(SharedLibraryTest,
+ FullTest_OpenLibrarySetSymbolCloseLibrary_ExpectActsWithoutErrors) {
+ // Arrange
+ const std::string kLib = "../libPolicy.so";
void* handle = dlopen(kLib.c_str(), RTLD_LAZY);
- //Assert
+ // Assert
EXPECT_FALSE(IsError(dlerror()));
ASSERT_TRUE(handle);
- //Act
+ // Act
const std::string kSymbol = "CreateManager";
void* symbol = dlsym(handle, kSymbol.c_str());
- //Assert
+ // Assert
EXPECT_FALSE(IsError(dlerror()));
EXPECT_TRUE(symbol);
- //Act
+ // Act
int ret = dlclose(handle);
- //Assert
+ // Assert
EXPECT_FALSE(ret);
EXPECT_FALSE(IsError(dlerror()));
}
diff --git a/src/components/policy/test/smartDeviceLink2.ini b/src/components/policy/test/smartDeviceLink2.ini
new file mode 100644
index 0000000000..6aec231dbb
--- /dev/null
+++ b/src/components/policy/test/smartDeviceLink2.ini
@@ -0,0 +1,12 @@
+ [MAIN]
+; Contains output files, e.g. .wav
+AppStorageFolder = storage1
+
+[Policy]
+EnablePolicy = true
+PreloadedPT = sdl_preloaded_pt.json
+;PathToSnapshot = sdl_snapshot.json
+; Number of attempts to open policy DB
+;AttemptsToOpenPolicyDB = 5
+; Timeout between attempts during opening DB in milliseconds
+;OpenAttemptTimeoutMs = 500
diff --git a/src/components/policy/test/smartDeviceLink3.ini b/src/components/policy/test/smartDeviceLink3.ini
new file mode 100644
index 0000000000..d96694313a
--- /dev/null
+++ b/src/components/policy/test/smartDeviceLink3.ini
@@ -0,0 +1,12 @@
+ [MAIN]
+; Contains output files, e.g. .wav
+AppStorageFolder = storage123
+
+[Policy]
+EnablePolicy = true
+PreloadedPT = sdl_preloaded_pt.json
+;PathToSnapshot = sdl_snapshot.json
+; Number of attempts to open policy DB
+AttemptsToOpenPolicyDB = 8
+; Timeout between attempts during opening DB in milliseconds
+OpenAttemptTimeoutMs = 700 \ No newline at end of file
diff --git a/src/components/policy/test/sql_pt_ext_representation_test.cc b/src/components/policy/test/sql_pt_ext_representation_test.cc
deleted file mode 100644
index fddbc00142..0000000000
--- a/src/components/policy/test/sql_pt_ext_representation_test.cc
+++ /dev/null
@@ -1,378 +0,0 @@
-/* Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <vector>
-#include "gtest/gtest.h"
-#include <algorithm>
-#include "driver_dbms.h"
-#include "policy/sql_pt_ext_representation.h"
-
-using policy::SQLPTExtRepresentation;
-
-namespace test {
-namespace components {
-namespace policy {
-
-class SQLPTExtRepresentationTest : public ::testing::Test {
- protected:
- static DBMS* dbms;
- static SQLPTExtRepresentation* reps;
- static const std::string kDatabaseName;
-
- static void SetUpTestCase() {
- reps = new SQLPTExtRepresentation;
- dbms = new DBMS(kDatabaseName);
- EXPECT_EQ(::policy::SUCCESS, reps->Init());
- EXPECT_TRUE(dbms->Open());
- }
-
- static void TearDownTestCase() {
- EXPECT_TRUE(reps->Drop());
- EXPECT_TRUE(reps->Close());
- delete reps;
- dbms->Close();
- }
-};
-
-DBMS* SQLPTExtRepresentationTest::dbms = 0;
-SQLPTExtRepresentation* SQLPTExtRepresentationTest::reps = 0;
-#ifdef __QNX__
-const std::string SQLPTExtRepresentationTest::kDatabaseName = "policy";
-#else // __QNX__
-const std::string SQLPTExtRepresentationTest::kDatabaseName = "policy.sqlite";
-#endif // __QNX__
-
-::testing::AssertionResult IsValid(const policy_table::Table& table) {
- if (table.is_valid()) {
- return ::testing::AssertionSuccess();
- } else {
- ::rpc::ValidationReport report(" - table");
- table.ReportErrors(&report);
- return ::testing::AssertionFailure() << ::rpc::PrettyFormat(report);
- }
-}
-
-TEST_F(SQLPTExtRepresentationTest, GenerateSnapshot_SetPolicyTable_SnapshotIsPresent) {
-
- //arrange
- Json::Value table(Json::objectValue);
- table["policy_table"] = Json::Value(Json::objectValue);
-
- Json::Value& policy_table = table["policy_table"];
- policy_table["module_config"] = Json::Value(Json::objectValue);
- policy_table["functional_groupings"] = Json::Value(Json::objectValue);
- policy_table["consumer_friendly_messages"] = Json::Value(Json::objectValue);
- policy_table["app_policies"] = Json::Value(Json::objectValue);
-
- Json::Value& module_config = policy_table["module_config"];
- module_config["preloaded_pt"] = Json::Value(true);
- module_config["exchange_after_x_ignition_cycles"] = Json::Value(10);
- module_config["exchange_after_x_kilometers"] = Json::Value(100);
- module_config["exchange_after_x_days"] = Json::Value(5);
- module_config["timeout_after_x_seconds"] = Json::Value(500);
- module_config["seconds_between_retries"] = Json::Value(Json::arrayValue);
- module_config["seconds_between_retries"][0] = Json::Value(10);
- module_config["seconds_between_retries"][1] = Json::Value(20);
- module_config["seconds_between_retries"][2] = Json::Value(30);
- module_config["endpoints"] = Json::Value(Json::objectValue);
- module_config["endpoints"]["0x00"] = Json::Value(Json::objectValue);
- module_config["endpoints"]["0x00"]["default"] = Json::Value(Json::arrayValue);
- module_config["endpoints"]["0x00"]["default"][0] = Json::Value(
- "http://ford.com/cloud/default");
- module_config["notifications_per_minute_by_priority"] = Json::Value(
- Json::objectValue);
- module_config["notifications_per_minute_by_priority"]["emergency"] =
- Json::Value(1);
- module_config["notifications_per_minute_by_priority"]["navigation"] =
- Json::Value(2);
- module_config["notifications_per_minute_by_priority"]["VOICECOMM"] =
- Json::Value(3);
- module_config["notifications_per_minute_by_priority"]["communication"] =
- Json::Value(4);
- module_config["notifications_per_minute_by_priority"]["normal"] = Json::Value(
- 5);
- module_config["notifications_per_minute_by_priority"]["none"] = Json::Value(
- 6);
- module_config["vehicle_make"] = Json::Value("MakeT");
- module_config["vehicle_model"] = Json::Value("ModelT");
- module_config["vehicle_year"] = Json::Value("2014");
-
- Json::Value& functional_groupings = policy_table["functional_groupings"];
- functional_groupings["default"] = Json::Value(Json::objectValue);
- Json::Value& default_group = functional_groupings["default"];
- default_group["rpcs"] = Json::Value(Json::objectValue);
- default_group["rpcs"]["Update"] = Json::Value(Json::objectValue);
- default_group["rpcs"]["Update"]["hmi_levels"] = Json::Value(Json::arrayValue);
- default_group["rpcs"]["Update"]["hmi_levels"][0] = Json::Value("FULL");
- default_group["rpcs"]["Update"]["parameters"] = Json::Value(Json::arrayValue);
- default_group["rpcs"]["Update"]["parameters"][0] = Json::Value("speed");
-
- Json::Value& consumer_friendly_messages =
- policy_table["consumer_friendly_messages"];
- consumer_friendly_messages["version"] = Json::Value("1.2");
- consumer_friendly_messages["messages"] = Json::Value(Json::objectValue);
- consumer_friendly_messages["messages"]["MSG1"] = Json::Value(
- Json::objectValue);
- Json::Value& msg1 = consumer_friendly_messages["messages"]["MSG1"];
- msg1["languages"] = Json::Value(Json::objectValue);
- msg1["languages"]["en-us"] = Json::Value(Json::objectValue);
- msg1["languages"]["en-us"]["tts"] = Json::Value("TTS message");
- msg1["languages"]["en-us"]["label"] = Json::Value("LABEL message");
- msg1["languages"]["en-us"]["line1"] = Json::Value("LINE1 message");
- msg1["languages"]["en-us"]["line2"] = Json::Value("LINE2 message");
- msg1["languages"]["en-us"]["textBody"] = Json::Value("TEXTBODY message");
-
- Json::Value& app_policies = policy_table["app_policies"];
- app_policies["default"] = Json::Value(Json::objectValue);
- app_policies["default"]["memory_kb"] = Json::Value(50);
- app_policies["default"]["heart_beat_timeout_ms"] = Json::Value(10);
- app_policies["default"]["groups"] = Json::Value(Json::arrayValue);
- app_policies["default"]["groups"][0] = Json::Value("default");
- app_policies["default"]["priority"] = Json::Value("EMERGENCY");
- app_policies["default"]["default_hmi"] = Json::Value("FULL");
- app_policies["default"]["keep_context"] = Json::Value(true);
- app_policies["default"]["steal_focus"] = Json::Value(true);
- app_policies["default"]["certificate"] = Json::Value("sign");
-
- policy_table::Table update(&table);
- update.SetPolicyTableType(rpc::policy_table_interface_base::PT_UPDATE);
-
- //assert
- ASSERT_TRUE(IsValid(update));
- ASSERT_TRUE(reps->Save(update));
-
- //act
- utils::SharedPtr<policy_table::Table> snapshot = reps->GenerateSnapshot();
- snapshot->SetPolicyTableType(rpc::policy_table_interface_base::PT_SNAPSHOT);
-
- policy_table["module_meta"] = Json::Value(Json::objectValue);
- policy_table["usage_and_error_counts"] = Json::Value(Json::objectValue);
- policy_table["device_data"] = Json::Value(Json::objectValue);
-
- Json::Value& module_meta = policy_table["module_meta"];
- module_meta["ccpu_version"] = Json::Value("");
- module_meta["language"] = Json::Value("");
- module_meta["wers_country_code"] = Json::Value("");
- module_meta["pt_exchanged_at_odometer_x"] = Json::Value(0);
- module_meta["pt_exchanged_x_days_after_epoch"] = Json::Value(0);
- module_meta["ignition_cycles_since_last_exchange"] = Json::Value(0);
- module_meta["vin"] = Json::Value("");
-
- Json::Value& usage_and_error_counts = policy_table["usage_and_error_counts"];
- usage_and_error_counts["count_of_iap_buffer_full"] = Json::Value(0);
- usage_and_error_counts["count_sync_out_of_memory"] = Json::Value(0);
- usage_and_error_counts["count_of_sync_reboots"] = Json::Value(0);
-
- policy_table::Table expected(&table);
-
- //assert
- EXPECT_EQ(expected.ToJsonValue().toStyledString(),
- snapshot->ToJsonValue().toStyledString());
-}
-
-TEST_F(SQLPTExtRepresentationTest, CanAppKeepContext_InsertKeepContext_ExpectValuesThatSetInKeepContextParams) {
-
- //arrange
- const char* query_delete = "DELETE FROM `application`; ";
-
- //assert
- ASSERT_TRUE(dbms->Exec(query_delete));
-
- //act
- const char* query_insert = "INSERT INTO `application` (`id`, `memory_kb`,"
- " `heart_beat_timeout_ms`, `keep_context`) VALUES ('12345', 5, 10, 1)";
-
- //assert
- ASSERT_TRUE(dbms->Exec(query_insert));
- EXPECT_FALSE(reps->CanAppKeepContext("0"));
- EXPECT_TRUE(reps->CanAppKeepContext("12345"));
-}
-
-TEST_F(SQLPTExtRepresentationTest, CanAppStealFocus_SetStealFocus_ExpectValuesThatSetInStealFocusParam) {
-
- //arrange
- const char* query_delete = "DELETE FROM `application`; ";
-
- //assert
- ASSERT_TRUE(dbms->Exec(query_delete));
-
- //act
- const char* query_insert = "INSERT INTO `application` (`id`, `memory_kb`,"
- " `heart_beat_timeout_ms`, `steal_focus`) VALUES ('12345', 5, 10, 1)";
-
- //assert
- ASSERT_TRUE(dbms->Exec(query_insert));
- EXPECT_TRUE(reps->CanAppStealFocus("12345"));
- EXPECT_FALSE(reps->CanAppStealFocus("0"));
-}
-
-TEST_F(SQLPTExtRepresentationTest, IncrementGlobalCounter_IncrementThreeTimes_ExpectCountEqual3) {
-
- //arrange
- const char* query_update = "UPDATE `usage_and_error_count` SET"
- " `count_of_sync_reboots` = 0";
-
- //assert
- ASSERT_TRUE(dbms->Exec(query_update));
-
- //act
- reps->Increment("count_of_sync_reboots");
- reps->Increment("count_of_sync_reboots");
- reps->Increment("count_of_sync_reboots");
-
- const char* query_select =
- "SELECT `count_of_sync_reboots` FROM `usage_and_error_count`";
- //assert
- EXPECT_EQ(3, dbms->FetchOneInt(query_select));
-}
-
-TEST_F(SQLPTExtRepresentationTest, IncrementAppCounter_IncrementCountOfUserSelections3Times_ExpectCountEqual3) {
-
- //arrange
- const char* query_delete =
- "DELETE FROM `app_level` WHERE `application_id` = '12345'";
-
- //assert
- ASSERT_TRUE(dbms->Exec(query_delete));
-
- //act
- reps->Increment("12345", "count_of_user_selections");
- reps->Increment("12345", "count_of_user_selections");
- reps->Increment("12345", "count_of_user_selections");
-
- const char* query_select =
- "SELECT `count_of_user_selections` FROM `app_level`"
- " WHERE `application_id` = '12345'";
-
- //assert
- EXPECT_EQ(3, dbms->FetchOneInt(query_select));
-}
-
-TEST_F(SQLPTExtRepresentationTest, AppInfo_SetLanguageRuInGUIAndEnInVUI_ExpectRuInGUIAndEnInVUI) {
-
- //arrange
- const char* query_delete =
- "DELETE FROM `app_level` WHERE `application_id` = '12345'";
-
- //assert
- ASSERT_TRUE(dbms->Exec(query_delete));
-
- //act
- reps->Set("12345", "app_registration_language_gui", "ru-ru");
- reps->Set("12345", "app_registration_language_vui", "en-en");
-
- const char* query_select_gui = "SELECT `app_registration_language_gui`"
- " FROM `app_level` WHERE `application_id` = '12345'";
-
- const char* query_select_vui = "SELECT `app_registration_language_vui`"
- " FROM `app_level` WHERE `application_id` = '12345'";
-
- //assert
- EXPECT_EQ("ru-ru", dbms->FetchOneString(query_select_gui));
- EXPECT_EQ("en-en", dbms->FetchOneString(query_select_vui));
-}
-
-TEST_F(SQLPTExtRepresentationTest, AddAppStopwatch_Set10And60MinutesForStopwatch_Expect70Minutes) {
-
- //arrange
- const char* query_delete =
- "DELETE FROM `app_level` WHERE `application_id` = '12345'";
-
- //assert
- ASSERT_TRUE(dbms->Exec(query_delete));
-
- //act
- reps->Add("12345", "minutes_in_hmi_full", 10);
- reps->Add("12345", "minutes_in_hmi_full", 60);
-
- const char* query_select = "SELECT `minutes_in_hmi_full` FROM `app_level`"
- " WHERE `application_id` = '12345'";
-
- //assert
- EXPECT_EQ(70, dbms->FetchOneInt(query_select));
-}
-
-TEST_F(SQLPTExtRepresentationTest, SetUnpairedDevice_SetUnpairedDeviceId12345_ExpectUnpairedDeviceIdEquals12345) {
-
- //arrange
- const char* query_delete = "DELETE FROM `device`";
-
- //assert
- ASSERT_TRUE(dbms->Exec(query_delete));
-
- //act
- const char* query_insert = "INSERT INTO `device` (`id`) VALUES('12345')";
-
- //assert
- ASSERT_TRUE(dbms->Exec(query_insert));
- ASSERT_TRUE(reps->SetUnpairedDevice("12345", true));
-
- //act
- const char* query_select = "SELECT `id` FROM `device` WHERE `unpaired` = 1";
-
- //assert
- EXPECT_EQ("12345", dbms->FetchOneString(query_select));
-}
-
-TEST_F(SQLPTExtRepresentationTest, UnpairedDevicesList_SetUnpairedDevicesWithId12345AndId54321_Expect2UnpairedDevices) {
-
- //arrange
- const char* query_delete = "DELETE FROM `device`";
-
- //assert
- ASSERT_TRUE(dbms->Exec(query_delete));
-
- //act
- const char* query_insert = "INSERT INTO `device` (`id`, `unpaired`)"
- " VALUES('12345', 1)";
-
- //assert
- ASSERT_TRUE(dbms->Exec(query_insert));
-
- //act
- query_insert = "INSERT INTO `device` (`id`, `unpaired`) VALUES('54321', 1)";
-
- //assert
- ASSERT_TRUE(dbms->Exec(query_insert));
-
- //act
- std::vector < std::string > output;
-
- //assert
- ASSERT_TRUE(reps->UnpairedDevicesList(&output));
- ASSERT_EQ(2u, output.size());
- EXPECT_NE(output.end(), std::find(output.begin(), output.end(), "12345"));
- EXPECT_NE(output.end(), std::find(output.begin(), output.end(), "54321"));
-}
-
-} // namespace policy
-} // namespace components
-} // namespace test
diff --git a/src/components/policy/test/sql_pt_representation_test.cc b/src/components/policy/test/sql_pt_representation_test.cc
index 088975ecde..1f4df5d15d 100644
--- a/src/components/policy/test/sql_pt_representation_test.cc
+++ b/src/components/policy/test/sql_pt_representation_test.cc
@@ -1,4 +1,4 @@
-/* Copyright (c) 2014, Ford Motor Company
+/* Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,63 +30,206 @@
*/
#include <vector>
+#include <string>
+#include <algorithm>
+#include <fstream>
+#include <memory>
+#include <stdio.h>
+#include <sys/stat.h>
+
#include "gtest/gtest.h"
-#include "driver_dbms.h"
+#include "policy/test/include/driver_dbms.h"
#include "policy/sql_pt_representation.h"
#include "policy/policy_types.h"
+#include "policy/mock_policy_settings.h"
#include "json/writer.h"
#include "json/reader.h"
-
+#include "rpc_base/rpc_base.h"
+#include "policy/mock_policy_settings.h"
+#include "utils/shared_ptr.h"
+#include "utils/make_shared.h"
+#include "utils/file_system.h"
+#include "policy/policy_table/types.h"
+#include "policy/policy_table/enums.h"
+#include "rpc_base/rpc_base.h"
+#include "utils/sqlite_wrapper/sql_database.h"
+
+namespace policy_table = rpc::policy_table_interface_base;
using policy::SQLPTRepresentation;
using policy::CheckPermissionResult;
+using policy::UserFriendlyMessage;
using policy::EndpointUrls;
+using policy::VehicleInfo;
+
+using testing::ReturnRef;
+using testing::Return;
+using testing::NiceMock;
+using testing::Mock;
namespace test {
namespace components {
namespace policy {
-class SQLPTRepresentationTest : public ::testing::Test {
+class SQLPTRepresentationTest : public SQLPTRepresentation,
+ public ::testing::Test {
protected:
static DBMS* dbms;
static SQLPTRepresentation* reps;
static const std::string kDatabaseName;
+ // Gtest can show message that this object doesn't destroyed
+ static std::auto_ptr<policy_handler_test::MockPolicySettings>
+ policy_settings_;
static void SetUpTestCase() {
+ const std::string kAppStorageFolder = "storage1";
+ file_system::RemoveDirectory(kAppStorageFolder);
+ file_system::DeleteFile("policy.sqlite");
reps = new SQLPTRepresentation;
dbms = new DBMS(kDatabaseName);
- EXPECT_EQ(::policy::SUCCESS, reps->Init());
+ policy_settings_ = std::auto_ptr<policy_handler_test::MockPolicySettings>(
+ new policy_handler_test::MockPolicySettings());
+ ON_CALL(*policy_settings_, app_storage_folder())
+ .WillByDefault(ReturnRef(kAppStorageFolder));
+ EXPECT_EQ(::policy::SUCCESS, reps->Init(policy_settings_.get()));
EXPECT_TRUE(dbms->Open());
}
+ void TearDown() OVERRIDE {
+ EXPECT_TRUE(reps->Clear());
+ }
+
static void TearDownTestCase() {
EXPECT_TRUE(reps->Drop());
EXPECT_TRUE(reps->Close());
+ reps->RemoveDB();
delete reps;
dbms->Close();
+ policy_settings_.reset();
+ }
+
+ virtual utils::dbms::SQLDatabase* db() const {
+ return reps->db();
+ }
+
+ void GatherModuleMeta(policy_table::ModuleMeta* meta) const {
+ ::SQLPTRepresentation::GatherModuleMeta(meta);
+ }
+
+ void GatherModuleConfig(policy_table::ModuleConfig* config) const {
+ ::SQLPTRepresentation::GatherModuleConfig(config);
+ }
+
+ bool GatherUsageAndErrorCounts(
+ policy_table::UsageAndErrorCounts* counts) const {
+ return ::SQLPTRepresentation::GatherUsageAndErrorCounts(counts);
+ }
+
+ bool GatherApplicationPoliciesSection(
+ policy_table::ApplicationPoliciesSection* policies) const {
+ return ::SQLPTRepresentation::GatherApplicationPoliciesSection(policies);
+ }
+ virtual void GatherDeviceData(policy_table::DeviceData* data) const {
+ ::SQLPTRepresentation::GatherDeviceData(data);
+ }
+
+ virtual bool GatherConsumerFriendlyMessages(
+ policy_table::ConsumerFriendlyMessages* messages) const {
+ return ::SQLPTRepresentation::GatherConsumerFriendlyMessages(messages);
+ }
+
+ bool GatherAppGroup(const std::string& app_id,
+ policy_table::Strings* app_groups) const {
+ return ::SQLPTRepresentation::GatherAppGroup(app_id, app_groups);
+ }
+
+ bool GatherAppType(const std::string& app_id,
+ policy_table::AppHMITypes* app_types) const {
+ return ::SQLPTRepresentation::GatherAppType(app_id, app_types);
+ }
+
+ bool GatherRequestType(const std::string& app_id,
+ policy_table::RequestTypes* request_types) const {
+ return ::SQLPTRepresentation::GatherRequestType(app_id, request_types);
+ }
+
+ bool GatherNickName(const std::string& app_id,
+ policy_table::Strings* nicknames) const {
+ return ::SQLPTRepresentation::GatherNickName(app_id, nicknames);
+ }
+
+ void CheckAppPoliciesSection(
+ policy_table::ApplicationPoliciesSection& policies,
+ uint16_t apps_size,
+ policy_table::Priority prio,
+ const std::string& section,
+ uint16_t memory_kb,
+ uint32_t heart_beat_timeout_ms,
+ policy_table::Strings& groups) const {
+ if (section != "device") {
+ policy_table::ApplicationPolicies& apps = policies.apps;
+ EXPECT_EQ(apps_size, apps.size());
+ policy_table::ApplicationPolicies::iterator apps_iter =
+ apps.find(section);
+ ASSERT_TRUE(apps.end() != apps_iter);
+ policy_table::Strings& temp_groups = apps_iter->second.groups;
+ StringsCompare(groups, temp_groups);
+ EXPECT_EQ(0u, (*(apps_iter->second.nicknames)).size());
+ EXPECT_EQ(prio, apps_iter->second.priority);
+ EXPECT_EQ(0u, (*(apps_iter->second.AppHMIType)).size());
+ EXPECT_EQ(memory_kb, (*(apps_iter->second.memory_kb)));
+ EXPECT_EQ(heart_beat_timeout_ms,
+ (*(apps_iter->second.heart_beat_timeout_ms)));
+ } else {
+ policy_table::DevicePolicy& device = policies.device;
+ EXPECT_EQ(prio, device.priority);
+ }
+ }
+
+ void StringsCompare(policy_table::Strings& groups1,
+ policy_table::Strings& groups2) const {
+ EXPECT_EQ(groups1.size(), groups2.size());
+ std::sort(groups1.begin(), groups1.end());
+ std::sort(groups2.begin(), groups2.end());
+ EXPECT_TRUE(groups1 == groups2);
}
-void PolicyTableUpdatePrepare(Json::Value& table) {
+ void CheckAppGroups(const std::string& app_id,
+ policy_table::Strings& groups) {
+ policy_table::Strings app_groups;
+ GatherAppGroup(app_id, &app_groups);
+ StringsCompare(groups, app_groups);
+ }
+
+ void PolicyTableUpdatePrepare(Json::Value& table) {
+ // Root
table["policy_table"] = Json::Value(Json::objectValue);
+
+ // 1st level
Json::Value& policy_table = table["policy_table"];
policy_table["module_config"] = Json::Value(Json::objectValue);
policy_table["functional_groupings"] = Json::Value(Json::objectValue);
policy_table["consumer_friendly_messages"] = Json::Value(Json::objectValue);
policy_table["app_policies"] = Json::Value(Json::objectValue);
+ policy_table["usage_and_error_counts"] = Json::Value(Json::objectValue);
+ policy_table["device_data"] = Json::Value(Json::objectValue);
+ // 'module_config' section start
Json::Value& module_config = policy_table["module_config"];
module_config["preloaded_pt"] = Json::Value(false);
- module_config["preloaded_date"] = Json::Value("25-04-2015");
+ module_config["preloaded_date"] = Json::Value("");
module_config["exchange_after_x_ignition_cycles"] = Json::Value(10);
module_config["exchange_after_x_kilometers"] = Json::Value(100);
module_config["exchange_after_x_days"] = Json::Value(5);
module_config["timeout_after_x_seconds"] = Json::Value(500);
module_config["seconds_between_retries"] = Json::Value(Json::arrayValue);
+
Json::Value& seconds_between_retries =
module_config["seconds_between_retries"];
seconds_between_retries[0] = Json::Value(10);
seconds_between_retries[1] = Json::Value(20);
seconds_between_retries[2] = Json::Value(30);
module_config["endpoints"] = Json::Value(Json::objectValue);
+
Json::Value& endpoins = module_config["endpoints"];
endpoins["0x00"] = Json::Value(Json::objectValue);
endpoins["0x00"]["default"] = Json::Value(Json::arrayValue);
@@ -106,11 +249,13 @@ void PolicyTableUpdatePrepare(Json::Value& table) {
Json::Value(5);
module_config["notifications_per_minute_by_priority"]["none"] =
Json::Value(6);
- module_config["vehicle_make"] = Json::Value("MakeT");
- module_config["vehicle_model"] = Json::Value("ModelT");
- module_config["vehicle_year"] = Json::Value("2014");
- module_config["certificate"] = Json::Value("my_cert");
+ module_config["vehicle_make"] = Json::Value("");
+ module_config["vehicle_model"] = Json::Value("");
+ module_config["vehicle_year"] = Json::Value("");
+ module_config["certificate"] = Json::Value("encrypted_certificate_content");
+ // 'module_config' section end
+ // 'functional_groupings' section start
Json::Value& functional_groupings = policy_table["functional_groupings"];
functional_groupings["default"] = Json::Value(Json::objectValue);
Json::Value& default_group = functional_groupings["default"];
@@ -125,19 +270,16 @@ void PolicyTableUpdatePrepare(Json::Value& table) {
Json::Value& consumer_friendly_messages =
policy_table["consumer_friendly_messages"];
- consumer_friendly_messages["version"] = Json::Value("1.2");
+ consumer_friendly_messages["version"] = Json::Value("some_msg_version");
consumer_friendly_messages["messages"] = Json::Value(Json::objectValue);
- consumer_friendly_messages["messages"]["MSG1"] =
+ consumer_friendly_messages["messages"]["MSG_CODE"] =
Json::Value(Json::objectValue);
- Json::Value& msg1 = consumer_friendly_messages["messages"]["MSG1"];
+ Json::Value& msg1 = consumer_friendly_messages["messages"]["MSG_CODE"];
msg1["languages"] = Json::Value(Json::objectValue);
msg1["languages"]["en-us"] = Json::Value(Json::objectValue);
- msg1["languages"]["en-us"]["tts"] = Json::Value("TTS message");
- msg1["languages"]["en-us"]["label"] = Json::Value("LABEL message");
- msg1["languages"]["en-us"]["line1"] = Json::Value("LINE1 message");
- msg1["languages"]["en-us"]["line2"] = Json::Value("LINE2 message");
- msg1["languages"]["en-us"]["textBody"] = Json::Value("TEXTBODY message");
+ // 'functional_groupings' section end
+ // 'app_policies' section start
Json::Value& app_policies = policy_table["app_policies"];
app_policies["default"] = Json::Value(Json::objectValue);
app_policies["default"]["priority"] = Json::Value("EMERGENCY");
@@ -179,7 +321,22 @@ void PolicyTableUpdatePrepare(Json::Value& table) {
app_policies["device"]["default_hmi"] = Json::Value("FULL");
app_policies["device"]["keep_context"] = Json::Value(true);
app_policies["device"]["steal_focus"] = Json::Value(true);
+ // 'app_policies' section end
+
+ Json::Value& usage_and_error_counts =
+ policy_table["usage_and_error_counts"];
+ usage_and_error_counts["app_level"] = Json::Value(Json::objectValue);
+ usage_and_error_counts["app_level"]["some_app_id"] =
+ Json::Value(Json::objectValue);
+ usage_and_error_counts["app_level"]["some_app_id"]["count_of_tls_errors"] =
+ Json::Value(5);
+
+ Json::Value& device_data = policy_table["device_data"];
+ device_data["device_id_hash_1"] = Json::Value(Json::objectValue);
+ device_data["device_id_hash_2"] = Json::Value(Json::objectValue);
+ device_data["device_id_hash_3"] = Json::Value(Json::objectValue);
}
+
::testing::AssertionResult IsValid(const policy_table::Table& table) {
if (table.is_valid()) {
return ::testing::AssertionSuccess();
@@ -193,15 +350,120 @@ void PolicyTableUpdatePrepare(Json::Value& table) {
DBMS* SQLPTRepresentationTest::dbms = 0;
SQLPTRepresentation* SQLPTRepresentationTest::reps = 0;
-#ifdef __QNX__
-const std::string SQLPTRepresentationTest::kDatabaseName = "policy";
-#else // __QNX__
const std::string SQLPTRepresentationTest::kDatabaseName = "policy.sqlite";
-#endif // __QNX__
+std::auto_ptr<policy_handler_test::MockPolicySettings>
+ SQLPTRepresentationTest::policy_settings_;
-TEST_F(SQLPTRepresentationTest, CheckPermissionsAllowed_SetValuesInAppGroupRpcFunctionalGroup_GetEqualParamsInCheckPermissionResult) {
- //arrange
- const char* query = "INSERT OR REPLACE INTO `application` (`id`, `memory_kb`,"
+class SQLPTRepresentationTest2 : public ::testing::Test {
+ protected:
+ SQLPTRepresentationTest2()
+ : kAppStorageFolder("storage123")
+ , kOpenAttemptTimeoutMs(700u)
+ , kAttemptsToOpenPolicyDB(8u) {}
+
+ void SetUp() OVERRIDE {
+ file_system::CreateDirectory(kAppStorageFolder);
+ chmod(kAppStorageFolder.c_str(), 00000);
+ ON_CALL(policy_settings_, app_storage_folder())
+ .WillByDefault(ReturnRef(kAppStorageFolder));
+ ON_CALL(policy_settings_, open_attempt_timeout_ms())
+ .WillByDefault(Return(kOpenAttemptTimeoutMs));
+ ON_CALL(policy_settings_, attempts_to_open_policy_db())
+ .WillByDefault(Return(kAttemptsToOpenPolicyDB));
+ reps = new SQLPTRepresentation;
+ }
+
+ void TearDown() OVERRIDE {
+ file_system::RemoveDirectory(kAppStorageFolder, true);
+ delete reps;
+ }
+
+ SQLPTRepresentation* reps;
+ NiceMock<policy_handler_test::MockPolicySettings> policy_settings_;
+ const std::string kAppStorageFolder;
+ const uint16_t kOpenAttemptTimeoutMs;
+ const uint16_t kAttemptsToOpenPolicyDB;
+};
+
+// {AKozoriz} : Unknown behavior (must try 8 times, tried 2 and opened)
+TEST_F(SQLPTRepresentationTest2,
+ DISABLED_OpenAttemptTimeOut_ExpectCorrectNumber) {
+ EXPECT_EQ(::policy::FAIL, reps->Init(&policy_settings_));
+ // Check Actual attempts number made to try to open DB
+ EXPECT_EQ(kAttemptsToOpenPolicyDB, reps->open_counter());
+ // Check timeot value correctly read from config file.
+ EXPECT_EQ(700u, kOpenAttemptTimeoutMs);
+}
+
+TEST_F(SQLPTRepresentationTest,
+ RefreshDB_DropExistedPTThenRefreshDB_ExpectTablesWithInitialData) {
+ // Check
+ const char* query_select =
+ "SELECT COUNT(*) FROM sqlite_master WHERE `type` = 'table'";
+ // In normally created PT there are more than 0 tables
+ ASSERT_GT(dbms->FetchOneInt(query_select), 0);
+ ASSERT_TRUE(reps->Drop());
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select));
+ ASSERT_TRUE(reps->RefreshDB());
+ // Check PT structure destroyed and tables number is 0
+ ASSERT_EQ(25, dbms->FetchOneInt(query_select));
+ const char* query_select_count_of_iap_buffer_full =
+ "SELECT `count_of_iap_buffer_full` FROM `usage_and_error_count`";
+ const char* query_select_count_sync_out_of_memory =
+ "SELECT `count_sync_out_of_memory` FROM `usage_and_error_count`";
+ const char* query_select_count_of_sync_reboots =
+ "SELECT `count_of_sync_reboots` FROM `usage_and_error_count`";
+ const char* query_select_pt_exchanged_at_odometer_x =
+ "SELECT `pt_exchanged_at_odometer_x` FROM `module_meta`";
+ const char* query_select_pt_exchanged_x_days_after_epoch =
+ "SELECT `pt_exchanged_x_days_after_epoch` FROM `module_meta`";
+ const char* query_select_flag_update_required =
+ "SELECT `flag_update_required` FROM `module_meta`";
+ const char* query_select_ignition_cycles_since_last_exchange =
+ "SELECT `ignition_cycles_since_last_exchange` FROM `module_meta`";
+ const char* query_select_preloaded_pt =
+ "SELECT `preloaded_pt` FROM `module_config`";
+ const char* query_select_is_first_run =
+ "SELECT `is_first_run` FROM `module_config`";
+ const char* query_select_exchange_after_x_ignition_cycles =
+ "SELECT `exchange_after_x_ignition_cycles` FROM `module_config`";
+ const char* query_select_exchange_after_x_kilometers =
+ "SELECT `exchange_after_x_kilometers` FROM `module_config`";
+ const char* query_select_exchange_after_x_days =
+ "SELECT `exchange_after_x_days` FROM `module_config`";
+ const char* query_select_timeout_after_x_seconds =
+ "SELECT `timeout_after_x_seconds` FROM `module_config`";
+ const char* query_select_priorities = "SELECT COUNT(`value`) FROM `priority`";
+ const char* query_select_hmi_levels =
+ "SELECT COUNT(`value`) FROM `hmi_level`";
+ const char* query_select_version = "SELECT `number` FROM `version`";
+
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select_count_of_iap_buffer_full));
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select_count_sync_out_of_memory));
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select_count_of_sync_reboots));
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select_pt_exchanged_at_odometer_x));
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select_pt_exchanged_x_days_after_epoch));
+ ASSERT_EQ(
+ 0, dbms->FetchOneInt(query_select_ignition_cycles_since_last_exchange));
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select_flag_update_required));
+ ASSERT_EQ(1, dbms->FetchOneInt(query_select_preloaded_pt));
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select_is_first_run));
+ ASSERT_EQ(0,
+ dbms->FetchOneInt(query_select_exchange_after_x_ignition_cycles));
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select_exchange_after_x_kilometers));
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select_exchange_after_x_days));
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select_timeout_after_x_seconds));
+ ASSERT_EQ(6, dbms->FetchOneInt(query_select_priorities));
+ ASSERT_EQ(4, dbms->FetchOneInt(query_select_hmi_levels));
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select_version));
+}
+
+TEST_F(
+ SQLPTRepresentationTest,
+ CheckPermissionsAllowed_SetValuesInAppGroupRpcFunctionalGroup_GetEqualParamsInCheckPermissionResult) {
+ // Arrange
+ const char* query =
+ "INSERT OR REPLACE INTO `application` (`id`, `memory_kb`,"
" `heart_beat_timeout_ms`) VALUES ('12345', 5, 10); "
"INSERT OR REPLACE INTO functional_group (`id`, `name`)"
" VALUES (1, 'Base-4'); "
@@ -212,23 +474,26 @@ TEST_F(SQLPTRepresentationTest, CheckPermissionsAllowed_SetValuesInAppGroupRpcFu
"INSERT OR REPLACE INTO `rpc` (`name`, `parameter`, `hmi_level_value`,"
" `functional_group_id`) VALUES ('Update', 'speed', 'FULL', 1);";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query));
- //Act
+ // Act
CheckPermissionResult ret;
reps->CheckPermissions("12345", "FULL", "Update", ret);
- //assert
+ // Assert
EXPECT_TRUE(ret.hmi_level_permitted == ::policy::kRpcAllowed);
ASSERT_EQ(2u, ret.list_of_allowed_params.size());
EXPECT_EQ("gps", ret.list_of_allowed_params[0]);
EXPECT_EQ("speed", ret.list_of_allowed_params[1]);
}
-TEST_F(SQLPTRepresentationTest, CheckPermissionsAllowedWithoutParameters_SetLimitedPermissions_ExpectEmptyListOfAllowedParams) {
- //arrange
- const char* query = "INSERT OR REPLACE INTO `application` (`id`, `memory_kb`,"
+TEST_F(
+ SQLPTRepresentationTest,
+ CheckPermissionsAllowedWithoutParameters_SetLimitedPermissions_ExpectEmptyListOfAllowedParams) {
+ // Arrange
+ const char* query =
+ "INSERT OR REPLACE INTO `application` (`id`, `memory_kb`,"
" `heart_beat_timeout_ms`) VALUES ('12345', 5, 10); "
"INSERT OR REPLACE INTO functional_group (`id`, `name`)"
" VALUES (1, 'Base-4'); "
@@ -238,324 +503,997 @@ TEST_F(SQLPTRepresentationTest, CheckPermissionsAllowedWithoutParameters_SetLimi
"INSERT OR REPLACE INTO `rpc` (`name`, `hmi_level_value`,"
" `functional_group_id`) VALUES ('Update', 'LIMITED', 1);";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query));
- //act
+ // Act
CheckPermissionResult ret;
reps->CheckPermissions("12345", "LIMITED", "Update", ret);
- //assert
+ // Assert
EXPECT_TRUE(ret.hmi_level_permitted == ::policy::kRpcAllowed);
EXPECT_TRUE(ret.list_of_allowed_params.empty());
}
-TEST_F(SQLPTRepresentationTest, CheckPermissionsDisallowedWithoutParameters_DeletedAppGroupAndSetFULLLevel_ExpectHmiLevelIsDissalowed) {
-
- //arrange
+TEST_F(
+ SQLPTRepresentationTest,
+ CheckPermissionsDisallowedWithoutParameters_DeletedAppGroupAndSetFULLLevel_ExpectHmiLevelIsDissalowed) {
+ // Arrange
const char* query = "DELETE FROM `app_group`";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query));
- //act
+ // Act
CheckPermissionResult ret;
reps->CheckPermissions("12345", "FULL", "Update", ret);
- //assert
+ // Assert
EXPECT_EQ(::policy::kRpcDisallowed, ret.hmi_level_permitted);
EXPECT_TRUE(ret.list_of_allowed_params.empty());
}
-TEST_F(SQLPTRepresentationTest, PTPReloaded_UpdateModuleConfig_ReturnIsPTPreloadedTRUE) {
-
- //arrange
+TEST_F(SQLPTRepresentationTest,
+ PTPReloaded_UpdateModuleConfig_ReturnIsPTPreloadedTRUE) {
+ // Arrange
const char* query = "UPDATE `module_config` SET `preloaded_pt` = 1";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query));
EXPECT_TRUE(reps->IsPTPreloaded());
}
-TEST_F(SQLPTRepresentationTest, GetUpdateUrls_DeleteAndInsertEndpoints_ExpectUpdateUrls) {
-
- //arrange
+TEST_F(SQLPTRepresentationTest,
+ GetUpdateUrls_DeleteAndInsertEndpoints_ExpectUpdateUrls) {
+ // Arrange
const char* query_delete = "DELETE FROM `endpoint`; ";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_delete));
- //act
+ // Act
EndpointUrls ret = reps->GetUpdateUrls(7);
- //assert
+ // Assert
EXPECT_TRUE(ret.empty());
- //act
+ // Act
const char* query_insert =
"INSERT INTO `endpoint` (`application_id`, `url`, `service`) "
- " VALUES ('12345', 'http://ford.com/cloud/1', 7);"
- "INSERT INTO `endpoint` (`application_id`, `url`, `service`) "
- " VALUES ('12345', 'http://ford.com/cloud/2', 7);";
+ " VALUES ('12345', 'http://ford.com/cloud/1', 7);"
+ "INSERT INTO `endpoint` (`application_id`, `url`, `service`) "
+ " VALUES ('12345', 'http://ford.com/cloud/2', 7);";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_insert));
- //act
+ // Act
ret = reps->GetUpdateUrls(7);
- //assert
+ // Assert
ASSERT_EQ(2u, ret.size());
EXPECT_EQ("http://ford.com/cloud/1", ret[0].url[0]);
EXPECT_EQ("http://ford.com/cloud/2", ret[1].url[0]);
- //act
+ // Act
ret = reps->GetUpdateUrls(0);
- //assert
+ // Assert
EXPECT_TRUE(ret.empty());
}
-TEST_F(SQLPTRepresentationTest, IgnitionCyclesBeforeExchange_WithParametersOfQueryEqualZero) {
-
- //arrange
- const char* query_zeros = "UPDATE `module_meta` SET "
+TEST_F(SQLPTRepresentationTest,
+ IgnitionCyclesBeforeExchange_WithParametersOfQueryEqualZero) {
+ // Arrange
+ const char* query_zeros =
+ "UPDATE `module_meta` SET "
" `ignition_cycles_since_last_exchange` = 0; "
" UPDATE `module_config` SET `exchange_after_x_ignition_cycles` = 0";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_zeros));
EXPECT_EQ(0, reps->IgnitionCyclesBeforeExchange());
- //act
+ // Act
reps->IncrementIgnitionCycles();
- //assert
+ // Assert
EXPECT_EQ(0, reps->IgnitionCyclesBeforeExchange());
-
}
-TEST_F(SQLPTRepresentationTest, IgnitionCyclesBeforeExchange_WithParametersOfQueryAreLessLimit) {
-
- //arrange
- const char* query_less_limit = "UPDATE `module_meta` SET "
+TEST_F(SQLPTRepresentationTest,
+ IgnitionCyclesBeforeExchange_WithParametersOfQueryAreLessLimit) {
+ // Arrange
+ const char* query_less_limit =
+ "UPDATE `module_meta` SET "
" `ignition_cycles_since_last_exchange` = 5; "
" UPDATE `module_config` SET `exchange_after_x_ignition_cycles` = 10";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_less_limit));
EXPECT_EQ(5, reps->IgnitionCyclesBeforeExchange());
- //act
+ // Act
reps->IncrementIgnitionCycles();
- //assert
+ // Assert
EXPECT_EQ(4, reps->IgnitionCyclesBeforeExchange());
-
}
-TEST_F(SQLPTRepresentationTest, IgnitionCyclesBeforeExchange_WithLimitCountOfParametersOfQuery) {
-
- //arrange
- const char* query_limit = "UPDATE `module_meta` SET "
+TEST_F(SQLPTRepresentationTest,
+ IgnitionCyclesBeforeExchange_WithLimitCountOfParametersOfQuery) {
+ // Arrange
+ const char* query_limit =
+ "UPDATE `module_meta` SET "
" `ignition_cycles_since_last_exchange` = 9; "
" UPDATE `module_config` SET `exchange_after_x_ignition_cycles` = 10";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_limit));
EXPECT_EQ(1, reps->IgnitionCyclesBeforeExchange());
-
- //act
+ // Act
reps->IncrementIgnitionCycles();
-
- //assert
+ // Assert
EXPECT_EQ(0, reps->IgnitionCyclesBeforeExchange());
-
}
-TEST_F(SQLPTRepresentationTest, IgnitionCyclesBeforeExchange_WithMoreLimitCountOfParametersOfQuery) {
-
- //arrange
- const char* query_more_limit = "UPDATE `module_meta` SET "
+TEST_F(SQLPTRepresentationTest,
+ IgnitionCyclesBeforeExchange_WithMoreLimitCountOfParametersOfQuery) {
+ // Arrange
+ const char* query_more_limit =
+ "UPDATE `module_meta` SET "
" `ignition_cycles_since_last_exchange` = 12; "
" UPDATE `module_config` SET `exchange_after_x_ignition_cycles` = 10";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_more_limit));
+ // Chceck
EXPECT_EQ(0, reps->IgnitionCyclesBeforeExchange());
-
}
-TEST_F(SQLPTRepresentationTest, IgnitionCyclesBeforeExchange_WithNegativeLimitOfParametersOfQuery) {
-
- //arrange
- const char* query_negative_limit = "UPDATE `module_meta` SET "
+TEST_F(SQLPTRepresentationTest,
+ IgnitionCyclesBeforeExchange_WithNegativeLimitOfParametersOfQuery) {
+ // Arrange
+ const char* query_negative_limit =
+ "UPDATE `module_meta` SET "
" `ignition_cycles_since_last_exchange` = 3; "
" UPDATE `module_config` SET `exchange_after_x_ignition_cycles` = -1";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_negative_limit));
+ // Check
EXPECT_EQ(0, reps->IgnitionCyclesBeforeExchange());
}
-TEST_F(SQLPTRepresentationTest, IgnitionCyclesBeforeExchange_WithNegativeLimitOfCurrentParameterOfQuery) {
-
- //arrange
- const char* query_negative_current = "UPDATE `module_meta` SET "
+TEST_F(
+ SQLPTRepresentationTest,
+ IgnitionCyclesBeforeExchange_WithNegativeLimitOfCurrentParameterOfQuery) {
+ // Arrange
+ const char* query_negative_current =
+ "UPDATE `module_meta` SET "
" `ignition_cycles_since_last_exchange` = -1; "
" UPDATE `module_config` SET `exchange_after_x_ignition_cycles` = 2";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_negative_current));
+ // Check
EXPECT_EQ(0, reps->IgnitionCyclesBeforeExchange());
}
-TEST_F(SQLPTRepresentationTest, KilometersBeforeExchange_WithParametersOfQueryEqualZero) {
-
- //arrange
- const char* query_zeros = "UPDATE `module_meta` SET "
+TEST_F(SQLPTRepresentationTest,
+ KilometersBeforeExchange_WithParametersOfQueryEqualZero) {
+ // Arrange
+ const char* query_zeros =
+ "UPDATE `module_meta` SET "
" `pt_exchanged_at_odometer_x` = 0; "
" UPDATE `module_config` SET `exchange_after_x_kilometers` = 0";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_zeros));
+ // Checks
EXPECT_EQ(0, reps->KilometersBeforeExchange(0));
EXPECT_EQ(0, reps->KilometersBeforeExchange(-10));
EXPECT_EQ(0, reps->KilometersBeforeExchange(10));
}
-TEST_F(SQLPTRepresentationTest, KilometersBeforeExchange_QueryWithNegativeLimit) {
-
- //arrange
- const char* query_negative_limit = "UPDATE `module_meta` SET "
+TEST_F(SQLPTRepresentationTest,
+ KilometersBeforeExchange_QueryWithNegativeLimit) {
+ // Arrange
+ const char* query_negative_limit =
+ "UPDATE `module_meta` SET "
" `pt_exchanged_at_odometer_x` = 10; "
" UPDATE `module_config` SET `exchange_after_x_kilometers` = -10";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_negative_limit));
+ // Checks
EXPECT_EQ(0, reps->KilometersBeforeExchange(0));
EXPECT_EQ(0, reps->KilometersBeforeExchange(10));
}
-TEST_F(SQLPTRepresentationTest, KilometersBeforeExchange_QueryWithNegativeCurrentLimit) {
-
- //arrange
- const char* query_negative_last = "UPDATE `module_meta` SET "
+TEST_F(SQLPTRepresentationTest,
+ KilometersBeforeExchange_QueryWithNegativeCurrentLimit) {
+ // Arrange
+ const char* query_negative_last =
+ "UPDATE `module_meta` SET "
" `pt_exchanged_at_odometer_x` = -10; "
" UPDATE `module_config` SET `exchange_after_x_kilometers` = 20";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_negative_last));
+ // Checks
EXPECT_EQ(0, reps->KilometersBeforeExchange(0));
EXPECT_EQ(0, reps->KilometersBeforeExchange(10));
}
-TEST_F(SQLPTRepresentationTest, KilometersBeforeExchange_QueryWithLimitParameters) {
-
- //arrange
- const char* query_limit = "UPDATE `module_meta` SET "
+TEST_F(SQLPTRepresentationTest,
+ KilometersBeforeExchange_QueryWithLimitParameters) {
+ // Arrange
+ const char* query_limit =
+ "UPDATE `module_meta` SET "
" `pt_exchanged_at_odometer_x` = 10; "
" UPDATE `module_config` SET `exchange_after_x_kilometers` = 100";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_limit));
+ // Checks
EXPECT_EQ(0, reps->KilometersBeforeExchange(120));
EXPECT_EQ(60, reps->KilometersBeforeExchange(50));
EXPECT_EQ(0, reps->KilometersBeforeExchange(5));
}
-TEST_F(SQLPTRepresentationTest, DaysBeforeExchange_WithParametersOfQueryEqualZero) {
-
- //arrange
- const char* query_zeros = "UPDATE `module_meta` SET "
+TEST_F(SQLPTRepresentationTest,
+ DaysBeforeExchange_WithParametersOfQueryEqualZero) {
+ // Arrange
+ const char* query_zeros =
+ "UPDATE `module_meta` SET "
" `pt_exchanged_x_days_after_epoch` = 0; "
" UPDATE `module_config` SET `exchange_after_x_days` = 0";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_zeros));
+ // Checks
EXPECT_EQ(0, reps->DaysBeforeExchange(0));
EXPECT_EQ(0, reps->DaysBeforeExchange(-10));
EXPECT_EQ(0, reps->DaysBeforeExchange(10));
}
TEST_F(SQLPTRepresentationTest, DaysBeforeExchange_QueryWithNegativeLimit) {
-
- //arrange
- const char* query_negative_limit = "UPDATE `module_meta` SET "
+ // Arrange
+ const char* query_negative_limit =
+ "UPDATE `module_meta` SET "
" `pt_exchanged_x_days_after_epoch` = 10; "
" UPDATE `module_config` SET `exchange_after_x_days` = -10";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_negative_limit));
+ // Checks
EXPECT_EQ(0, reps->DaysBeforeExchange(0));
EXPECT_EQ(0, reps->DaysBeforeExchange(10));
}
-TEST_F(SQLPTRepresentationTest, DaysBeforeExchange_QueryWithNegativeCurrentLimit) {
-
- //arrange
- const char* query_negative_last = "UPDATE `module_meta` SET "
+TEST_F(SQLPTRepresentationTest,
+ DaysBeforeExchange_QueryWithNegativeCurrentLimit) {
+ // Arrange
+ const char* query_negative_last =
+ "UPDATE `module_meta` SET "
" `pt_exchanged_x_days_after_epoch` = -10; "
" UPDATE `module_config` SET `exchange_after_x_days` = 20";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_negative_last));
+ // Checks
EXPECT_EQ(0, reps->DaysBeforeExchange(0));
EXPECT_EQ(0, reps->DaysBeforeExchange(10));
}
TEST_F(SQLPTRepresentationTest, DaysBeforeExchange_QueryWithLimitParameters) {
-
- //arrange
- const char* query_limit = "UPDATE `module_meta` SET "
+ // Arrange
+ const char* query_limit =
+ "UPDATE `module_meta` SET "
" `pt_exchanged_x_days_after_epoch` = 10; "
" UPDATE `module_config` SET `exchange_after_x_days` = 100";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_limit));
+ // Checks
EXPECT_EQ(0, reps->DaysBeforeExchange(120));
EXPECT_EQ(60, reps->DaysBeforeExchange(50));
EXPECT_EQ(0, reps->DaysBeforeExchange(5));
}
-TEST_F(SQLPTRepresentationTest, SecondsBetweenRetries_DeletedAndInsertedSecondsBetweenRetry_ExpectCountOfSecondsEqualInserted) {
-
- //arrange
+TEST_F(
+ SQLPTRepresentationTest,
+ SecondsBetweenRetries_DeletedAndInsertedSecondsBetweenRetry_ExpectCountOfSecondsEqualInserted) {
+ // Arrange
std::vector<int> seconds;
const char* query_delete = "DELETE FROM `seconds_between_retry`; ";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_delete));
ASSERT_TRUE(reps->SecondsBetweenRetries(&seconds));
EXPECT_EQ(0u, seconds.size());
- //arrange
+ // Arrange
const char* query_insert =
"INSERT INTO `seconds_between_retry` (`index`, `value`) "
- " VALUES (0, 10); "
- "INSERT INTO `seconds_between_retry` (`index`, `value`) "
- " VALUES (1, 20); ";
+ " VALUES (0, 10); "
+ "INSERT INTO `seconds_between_retry` (`index`, `value`) "
+ " VALUES (1, 20); ";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query_insert));
ASSERT_TRUE(reps->SecondsBetweenRetries(&seconds));
+ // Checks
ASSERT_EQ(2u, seconds.size());
EXPECT_EQ(10, seconds[0]);
EXPECT_EQ(20, seconds[1]);
}
TEST_F(SQLPTRepresentationTest, TimeoutResponse_Set60Seconds_GetEqualTimeout) {
-
- //arrange
+ // Arrange
const char* query =
"UPDATE `module_config` SET `timeout_after_x_seconds` = 60";
- //assert
+ // Assert
ASSERT_TRUE(dbms->Exec(query));
+ // Check
EXPECT_EQ(60, reps->TimeoutResponse());
}
TEST_F(SQLPTRepresentationTest,
- GenerateSnapshot_SetPolicyTable_SnapshotIsPresent) {
+ IsPTPreloaded_SetPTPreloadedThenCheck_ExpectCorrectValue) {
+ // Arrange
+ const char* query_insert = "UPDATE `module_config` SET `preloaded_pt` = 1";
+ ASSERT_TRUE(dbms->Exec(query_insert));
+ // Check
+ ASSERT_TRUE(reps->IsPTPreloaded());
+}
+
+TEST_F(
+ SQLPTRepresentationTest,
+ SetCountersPassedForSuccessfulUpdate_SetCounters_ExpectValueChangedInPT) {
+ // Arrange
+ const char* query_select_odometer =
+ "SELECT `pt_exchanged_at_odometer_x` FROM`module_meta`";
+ const char* query_select_days_after_epoch =
+ "SELECT `pt_exchanged_x_days_after_epoch` FROM`module_meta`";
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select_odometer));
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select_days_after_epoch));
+ // Act
+ ASSERT_TRUE(reps->SetCountersPassedForSuccessfulUpdate(100, 10000));
+ ASSERT_EQ(100, dbms->FetchOneInt(query_select_odometer));
+ ASSERT_EQ(10000, dbms->FetchOneInt(query_select_days_after_epoch));
+}
+
+TEST_F(
+ SQLPTRepresentationTest,
+ IncrementIgnitionCycles_SetIgnitionCyclesValueThenIncrement_ExpectValueIncrementedInPT) {
+ // Arrange
+ const char* query_insert =
+ "UPDATE `module_meta` SET `ignition_cycles_since_last_exchange` = 54";
+ const char* query_select =
+ "SELECT `ignition_cycles_since_last_exchange`FROM `module_meta`";
+ ASSERT_TRUE(dbms->Exec(query_insert));
+ // Act
+ reps->IncrementIgnitionCycles();
+ // Check
+ ASSERT_EQ(55, dbms->FetchOneInt(query_select));
+}
+
+TEST_F(
+ SQLPTRepresentationTest,
+ ResetIgnitionCycles_SetIgnitionCyclesValueThenReset_ExpectZeroValueInPT) {
+ // Arrange
+ const char* query_insert =
+ "UPDATE `module_meta` SET `ignition_cycles_since_last_exchange` = 55";
+ const char* query_select =
+ "SELECT `ignition_cycles_since_last_exchange` FROM `module_meta`";
+ ASSERT_TRUE(dbms->Exec(query_insert));
+ // Act
+ reps->ResetIgnitionCycles();
+ // Check
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select));
+}
+
+TEST_F(SQLPTRepresentationTest,
+ GetUserFriendlyMsg_SetMsg_ExpectReceivedMsgSetInParams) {
+ // Arrange
+
+ const char* query_insert =
+ "INSERT INTO `message` (`language_code`, `message_type_name`) VALUES "
+ "('en-en', 'AppPermissions')";
+
+ ASSERT_TRUE(dbms->Exec(query_insert));
+ query_insert =
+ "INSERT INTO `message_type` (`name`) VALUES ('AppPermissions')";
+ ASSERT_TRUE(dbms->Exec(query_insert));
+ std::vector<std::string> msg_code;
+ msg_code.push_back("AppPermissions");
+ // Act
+ std::vector<UserFriendlyMessage> result =
+ reps->GetUserFriendlyMsg(msg_code, std::string("en-en"));
+ // Checks
+ ASSERT_EQ(1u, result.size());
+ EXPECT_EQ(result[0].message_code, "AppPermissions");
+}
+
+TEST_F(
+ SQLPTRepresentationTest,
+ GetNotificationNumber_SetNotificationsPriorities_ExpectReceivedValuesCorrect) {
+ // Arrange
+ const char* query_insert =
+ "INSERT INTO `notifications_by_priority` (`priority_value`, `value`) "
+ "VALUES ('NAVIGATION', 15) , "
+ "('COMMUNICATION', 6), ('EMERGENCY', 60), ('NONE', 0), ('NORMAL', 4), "
+ "('VOICECOMMUNICATION', 20)";
+
+ ASSERT_TRUE(dbms->Exec(query_insert));
+ EXPECT_EQ(6, reps->GetNotificationsNumber("COMMUNICATION"));
+ EXPECT_EQ(60, reps->GetNotificationsNumber("EMERGENCY"));
+ EXPECT_EQ(15, reps->GetNotificationsNumber("NAVIGATION"));
+ EXPECT_EQ(0, reps->GetNotificationsNumber("NONE"));
+ EXPECT_EQ(4, reps->GetNotificationsNumber("NORMAL"));
+ EXPECT_EQ(20, reps->GetNotificationsNumber("VOICECOMMUNICATION"));
+}
+
+TEST_F(SQLPTRepresentationTest,
+ GetPriority_SetAppsPrioritiesThenGet_ExpectReceivedValuesCorrect) {
+ // Arrange
+ const char* query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( 'default', 0, 0, 'NONE', 'NONE', 0, "
+ "0, "
+ "0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+
+ query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( 'pre_DataConsent', 0, 0, 'NONE', "
+ "'NONE', 0, 0, "
+ "0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+
+ query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( 'device', 0, 0, 'NONE', "
+ "'COMMUNICATION', 0, 0, "
+ "0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+
+ query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( '12345', 0, 0, 'NONE', 'EMERGENCY', "
+ "0, 0, "
+ "0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+
+ std::string priority;
+ // Checks
+ EXPECT_TRUE(reps->GetPriority("default", &priority));
+ EXPECT_EQ("NONE", priority);
+ EXPECT_TRUE(reps->GetPriority("pre_DataConsent", &priority));
+ EXPECT_EQ("NONE", priority);
+ EXPECT_TRUE(reps->GetPriority("device", &priority));
+ EXPECT_EQ("COMMUNICATION", priority);
+ EXPECT_TRUE(reps->GetPriority("12345", &priority));
+ EXPECT_EQ("EMERGENCY", priority);
+}
+
+namespace {
+const std::string kAppStorageFolder = "storage";
+}
+
+TEST(SQLPTRepresentationTest3, Init_InitNewDataBase_ExpectResultSuccess) {
+ // Arrange
+ NiceMock<policy_handler_test::MockPolicySettings> policy_settings_;
+ SQLPTRepresentation* reps;
+ reps = new SQLPTRepresentation;
+ // Checks
+ ON_CALL(policy_settings_, app_storage_folder())
+ .WillByDefault(ReturnRef(kAppStorageFolder));
+ EXPECT_EQ(::policy::SUCCESS, reps->Init(&policy_settings_));
+ EXPECT_EQ(::policy::EXISTS, reps->Init(&policy_settings_));
+ reps->RemoveDB();
+ delete reps;
+}
+
+TEST(SQLPTRepresentationTest3,
+ Init_TryInitNotExistingDataBase_ExpectResultFail) {
+ // Arrange
+ NiceMock<policy_handler_test::MockPolicySettings> policy_settings_;
+ ON_CALL(policy_settings_, app_storage_folder())
+ .WillByDefault(ReturnRef(kAppStorageFolder));
+ SQLPTRepresentation reps;
+ (reps.db())->set_path("/home/");
+ // Check
+ EXPECT_EQ(::policy::FAIL, reps.Init(&policy_settings_));
+}
+
+TEST(SQLPTRepresentationTest3,
+ Close_InitNewDataBaseThenClose_ExpectResultSuccess) {
+ // Arrange
+ NiceMock<policy_handler_test::MockPolicySettings> policy_settings_;
+ ON_CALL(policy_settings_, app_storage_folder())
+ .WillByDefault(ReturnRef(kAppStorageFolder));
+ SQLPTRepresentation reps;
+ EXPECT_EQ(::policy::SUCCESS, reps.Init(&policy_settings_));
+ EXPECT_TRUE(reps.Close());
+ utils::dbms::SQLError error(utils::dbms::Error::OK);
+ // Checks
+ EXPECT_EQ(error.number(), (reps.db()->LastError().number()));
+ reps.RemoveDB();
+}
+
+TEST_F(SQLPTRepresentationTest,
+ Clear_InitNewDataBaseThenClear_ExpectResultSuccess) {
+ // Arrange
+ const char* query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( 'default', 0, 0, 'NONE', 'NONE', 0, "
+ "0, "
+ "0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+
+ query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( 'pre_DataConsent', 0, 0, 'NONE', "
+ "'NONE', 0, 0, "
+ "0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+
+ query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( 'device', 0, 0, 'NONE', "
+ "'COMMUNICATION', 0, 0, "
+ "0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+
+ query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( '12345', 0, 0, 'NONE', 'EMERGENCY', "
+ "0, 0, "
+ "0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+
+ const char* query_insert =
+ "INSERT INTO `notifications_by_priority` (`priority_value`, `value`) "
+ "VALUES ('NAVIGATION', 15) , "
+ "('COMMUNICATION', 6), ('EMERGENCY', 60), ('NONE', 0), ('NORMAL', 4), "
+ "('VOICECOMMUNICATION', 20)";
+
+ ASSERT_TRUE(dbms->Exec(query_insert));
+ EXPECT_TRUE(reps->Clear());
+ utils::dbms::SQLError error(utils::dbms::Error::OK);
+ EXPECT_EQ(error.number(), (reps->db()->LastError().number()));
+}
+
+TEST_F(SQLPTRepresentationTest,
+ GetInitialAppData_SetData_ExpectCorrectValuesReceived) {
+ // Arrange
+ const char* query_insert =
+ "INSERT INTO `nickname` (`application_id`, `name`)"
+ "VALUES ('1111', 'first_app') , "
+ "('2222', 'second_app'), ('3333', 'third_app')";
+ ASSERT_TRUE(dbms->Exec(query_insert));
+
+ query_insert =
+ "INSERT INTO `app_type` (`application_id`, `name`)"
+ "VALUES ('1111', 'NAVIGATION') , "
+ "('1111', 'MEDIA'), ('3333', 'COMMUNICATION')";
+ ASSERT_TRUE(dbms->Exec(query_insert));
+ ::policy::StringArray nicknames;
+ ::policy::StringArray app_types;
+ ASSERT_TRUE(reps->GetInitialAppData("1111", &nicknames, &app_types));
+ EXPECT_EQ(1u, nicknames.size());
+ EXPECT_TRUE(nicknames.end() !=
+ std::find(nicknames.begin(), nicknames.end(), "first_app"));
+ EXPECT_EQ(2u, app_types.size());
+ EXPECT_TRUE(app_types.end() !=
+ std::find(app_types.begin(), app_types.end(), "NAVIGATION"));
+ EXPECT_TRUE(app_types.end() !=
+ std::find(app_types.begin(), app_types.end(), "MEDIA"));
+ nicknames.clear();
+ app_types.clear();
+ ASSERT_TRUE(reps->GetInitialAppData("2222", &nicknames, &app_types));
+ EXPECT_EQ(1u, nicknames.size());
+ EXPECT_TRUE(nicknames.end() !=
+ std::find(nicknames.begin(), nicknames.end(), "second_app"));
+ EXPECT_EQ(0u, app_types.size());
+ nicknames.clear();
+ app_types.clear();
+ ASSERT_TRUE(reps->GetInitialAppData("3333", &nicknames, &app_types));
+ EXPECT_EQ(1u, nicknames.size());
+ EXPECT_TRUE(nicknames.end() !=
+ std::find(nicknames.begin(), nicknames.end(), "third_app"));
+ EXPECT_EQ(1u, app_types.size());
+ EXPECT_TRUE(app_types.end() !=
+ std::find(app_types.begin(), app_types.end(), "COMMUNICATION"));
+}
+
+TEST_F(
+ SQLPTRepresentationTest,
+ GetFunctionalGroupings_SetFunctionalGroupings_ExpectCorrectValuesReceived) {
+ // Arrange
+ const char* query_insert =
+ "INSERT INTO `functional_group` (`id`, `user_consent_prompt`, `name`) "
+ "VALUES (73072936, null, 'SendLocation'), (1533011474, null, "
+ "'OnKeyboardInputOnlyGroup')";
+ ASSERT_TRUE(dbms->Exec(query_insert));
+
+ query_insert =
+ "INSERT INTO `rpc` (`name`, `hmi_level_value`, `functional_group_id`) "
+ "VALUES ('SendLocation', 'BACKGROUND', 73072936), ('SendLocation', "
+ "'FULL', 73072936), ('SendLocation', 'LIMITED', 73072936)";
+ ASSERT_TRUE(dbms->Exec(query_insert));
+
+ query_insert =
+ "INSERT INTO `rpc` (`name`, `hmi_level_value`, `functional_group_id`) "
+ "VALUES ('OnKeyboardInput', 'FULL', 1533011474)";
+ ASSERT_TRUE(dbms->Exec(query_insert));
+
+ policy_table::FunctionalGroupings func_groups;
+ ASSERT_TRUE(reps->GetFunctionalGroupings(func_groups));
+ EXPECT_EQ(2u, func_groups.size());
+ policy_table::FunctionalGroupings::iterator func_groups_it =
+ func_groups.find("SendLocation");
+ EXPECT_TRUE(func_groups.end() != func_groups_it);
+ policy_table::Rpcs& rpcs = func_groups_it->second;
+ EXPECT_EQ("", static_cast<std::string>(*rpcs.user_consent_prompt));
+ policy_table::Rpc& rpc = rpcs.rpcs;
+ EXPECT_EQ(1u, rpc.size());
+ policy_table::Rpc::const_iterator rpc_it = rpc.find("SendLocation");
+ EXPECT_TRUE(rpc.end() != rpc_it);
+ const policy_table::HmiLevels& hmi_levels1 = rpc_it->second.hmi_levels;
+ EXPECT_EQ(3u, hmi_levels1.size());
+ EXPECT_TRUE(hmi_levels1.end() !=
+ std::find(hmi_levels1.begin(),
+ hmi_levels1.end(),
+ policy_table::HmiLevel::HL_BACKGROUND));
+ EXPECT_TRUE(hmi_levels1.end() !=
+ std::find(hmi_levels1.begin(),
+ hmi_levels1.end(),
+ policy_table::HmiLevel::HL_LIMITED));
+ EXPECT_TRUE(hmi_levels1.end() != std::find(hmi_levels1.begin(),
+ hmi_levels1.end(),
+ policy_table::HmiLevel::HL_FULL));
+
+ func_groups_it = func_groups.find("OnKeyboardInputOnlyGroup");
+ EXPECT_TRUE(func_groups.end() != func_groups_it);
+ policy_table::Rpcs& rpcs2 = func_groups_it->second;
+ EXPECT_EQ("", static_cast<std::string>(*rpcs2.user_consent_prompt));
+ policy_table::Rpc& rpc2 = rpcs2.rpcs;
+ EXPECT_EQ(1u, rpc2.size());
+ rpc_it = rpc2.find("OnKeyboardInput");
+ EXPECT_TRUE(rpc2.end() != rpc_it);
+ const policy_table::HmiLevels& hmi_levels2 = rpc_it->second.hmi_levels;
+ EXPECT_EQ(1u, hmi_levels2.size());
+ EXPECT_TRUE(hmi_levels2.end() != std::find(hmi_levels2.begin(),
+ hmi_levels2.end(),
+ policy_table::HmiLevel::HL_FULL));
+}
+
+TEST_F(
+ SQLPTRepresentationTest,
+ UpdateRequired_SetUpdateNotRequiredFlagThenCheck_ExpectUpdateNotRequired) {
+ // Arrange
+ EXPECT_FALSE(reps->UpdateRequired());
+}
+
+TEST_F(SQLPTRepresentationTest,
+ UpdateRequired_SetUpdateRequiredFlagThenCheck_ExpectUpdateRequired) {
+ // Arrange
+ const char* query_insert =
+ "UPDATE `module_meta` SET `flag_update_required` = 1";
+ // Assert
+ ASSERT_TRUE(dbms->Exec(query_insert));
+ // Check
+ EXPECT_TRUE(reps->UpdateRequired());
+}
+
+TEST_F(SQLPTRepresentationTest,
+ SaveUpdateRequired_SaveUpdateRequired_ExpectCorrectValues) {
+ // Arrange
+ reps->SaveUpdateRequired(true);
+ // Check
+ EXPECT_TRUE(reps->UpdateRequired());
+ // Act
+ reps->SaveUpdateRequired(false);
+ // Check
+ EXPECT_FALSE(reps->UpdateRequired());
+}
+
+TEST_F(SQLPTRepresentationTest,
+ IsApplicationRepresented_Check_ExpectCorrectResult) {
+ // Arrange
+ const char* query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( 'default', 0, 0, 'NONE', 'NONE', 0, "
+ "0, "
+ "0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+
+ query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( 'device', 0, 0, 'NONE', "
+ "'COMMUNICATION', 0, 0, 0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+
+ query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( '12345', 0, 0, 'NONE', 'EMERGENCY', "
+ "0, 0, "
+ "0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+ // Checks
+ EXPECT_TRUE(reps->IsApplicationRepresented("default"));
+ EXPECT_TRUE(reps->IsApplicationRepresented("device"));
+ EXPECT_TRUE(reps->IsApplicationRepresented("12345"));
+ EXPECT_FALSE(reps->IsApplicationRepresented("1234"));
+}
+
+TEST_F(SQLPTRepresentationTest,
+ IsApplicationRevoked_CheckApps_ExpectCorrectResult) {
+ // Arrange
+ const char* query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( '7777', 0, 0, 'NONE', 'NONE', 1, "
+ "0, "
+ "0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+
+ query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( '12345', 0, 0, 'NONE', 'EMERGENCY', "
+ "0, 0, "
+ "0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+ // Checks
+ EXPECT_TRUE(reps->IsApplicationRevoked("7777"));
+ EXPECT_FALSE(reps->IsApplicationRevoked("12345"));
+}
+
+TEST_F(SQLPTRepresentationTest,
+ CopyApplication_CopyApplication_ExpectAppCopiedSuccesfully) {
+ // Arrange
+ const char* query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( 'default', 0, 0, 'NONE', 'NONE', 0, "
+ "1, "
+ "0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+
+ query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( '123', 1, 0, 'FULL', "
+ "'COMMUNICATION', 1, 1, 0, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+ EXPECT_FALSE(reps->IsApplicationRepresented("7777"));
+ EXPECT_FALSE(reps->IsApplicationRepresented("9999"));
+ // Act
+ EXPECT_TRUE(reps->CopyApplication("default", "7777"));
+ EXPECT_TRUE(reps->CopyApplication("123", "9999"));
+ // Checks
+ EXPECT_TRUE(reps->IsApplicationRepresented("7777"));
+ EXPECT_TRUE(reps->IsApplicationRepresented("9999"));
+ EXPECT_FALSE(reps->IsApplicationRevoked("7777"));
+ EXPECT_TRUE(reps->IsApplicationRevoked("9999"));
+ EXPECT_TRUE(reps->IsDefaultPolicy("7777"));
+ std::string priority1;
+ std::string priority2;
+ EXPECT_TRUE(reps->GetPriority("default", &priority1));
+ EXPECT_TRUE(reps->GetPriority("7777", &priority2));
+ EXPECT_EQ(priority1, priority2);
+ EXPECT_TRUE(reps->GetPriority("123", &priority1));
+ EXPECT_TRUE(reps->GetPriority("9999", &priority2));
+ EXPECT_EQ(priority1, priority2);
+}
+
+TEST_F(SQLPTRepresentationTest,
+ IsDefaultPolicy_SetAppPreDataThenCheck_ExpectNotDefaultPolicySet) {
+ // Arrange
+ const char* query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) VALUES( '12345', 0, 0, 'NONE', 'NONE', 0, "
+ "0, "
+ "1, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+ // Check
+ EXPECT_FALSE(reps->IsDefaultPolicy("12345"));
+}
+
+TEST_F(SQLPTRepresentationTest,
+ IsDefaultPolicy_SetAppDefaultThenCheck_ExpectNotDefaultPolicySet) {
+ // Arrange
+ const char* query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, `default_hmi`, `priority_value`, `is_revoked`, "
+ "`is_default`, `is_predata`, `memory_kb`, `heart_beat_timeout_ms`) "
+ "VALUES( '1234567', 0, 0, 'NONE', 'NONE', 0, 1, 0, 64, 10) ";
+
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+ // Check
+ EXPECT_TRUE(reps->IsDefaultPolicy("1234567"));
+}
+
+TEST_F(SQLPTRepresentationTest, Drop_DropExistedPT_ExpectZeroTables) {
+ // Check
+ const char* query_select =
+ "SELECT COUNT(*) FROM `sqlite_master` WHERE `type` = 'table'";
+ // In normally created PT there are more than 0 tables
+ ASSERT_TRUE(dbms->Exec(query_select));
+ ASSERT_GT(dbms->FetchOneInt(query_select), 0);
+ // Destroy schema
+ ASSERT_TRUE(reps->Drop());
+ // Check PT structure destroyed and tables number is 0
+ ASSERT_EQ(0, dbms->FetchOneInt(query_select));
+ // Restore schema
+ ASSERT_TRUE(reps->RefreshDB());
+}
+
+TEST_F(SQLPTRepresentationTest,
+ SetDefaultPolicy_SetDefaultPolicyThenCheck_ExpectDefaultPolicySet) {
+ // Arrange
+ const std::string kDefaultId = "default";
+ const std::string kAppId = "app_1234567";
+ const std::string kRequestType = "HTTP";
+ const std::string kHmiType = "MEDIA";
+
+ const std::string query_insert_default_app =
+ "INSERT INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, "
+ " `default_hmi`, `priority_value`, `is_revoked`, `is_default`, "
+ "`is_predata`, `memory_kb`, "
+ " `heart_beat_timeout_ms`) "
+ "VALUES( '" +
+ kDefaultId + "', 0, 0, 'NONE', 'NONE', 0, 0, 0, 64, 10) ";
+
+ ASSERT_TRUE(dbms->Exec(query_insert_default_app.c_str()));
+
+ const std::string query_insert_default_app_request_types =
+ "INSERT INTO `request_type` (`application_id`, `request_type`) "
+ "VALUES ('" +
+ kDefaultId + "', '" + kRequestType + "')";
+
+ ASSERT_TRUE(dbms->Exec(query_insert_default_app_request_types.c_str()));
+
+ const std::string query_insert_default_app_hmi_types =
+ "INSERT INTO `app_type` (`application_id`, `name`) "
+ "VALUES ('" +
+ kDefaultId + "', '" + kHmiType + "')";
+
+ ASSERT_TRUE(dbms->Exec(query_insert_default_app_hmi_types.c_str()));
+
+ const std::string query_insert_new_app =
+ "INSERT INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, `default_hmi`, `priority_value`, `is_revoked`, "
+ "`is_default`, `is_predata`, `memory_kb`, `heart_beat_timeout_ms`) "
+ "VALUES('" +
+ kAppId + "', 0, 0, 'NONE', 'NONE', 0, 0, 1, 64, 10)";
+
+ ASSERT_TRUE(dbms->Exec(query_insert_new_app.c_str()));
+
+ EXPECT_FALSE(reps->IsDefaultPolicy(kAppId));
+ // Act
+ ASSERT_TRUE(reps->SetDefaultPolicy(kAppId));
+ // Check
+ EXPECT_TRUE(reps->IsDefaultPolicy(kAppId));
+
+ policy_table::RequestTypes request_types;
+ GatherRequestType(kAppId, &request_types);
+ ASSERT_TRUE(1 == request_types.size());
+ EXPECT_EQ(policy_table::RT_HTTP, *request_types.begin());
+
+ policy_table::AppHMITypes hmi_types;
+ GatherAppType(kAppId, &hmi_types);
+ ASSERT_TRUE(1 == hmi_types.size());
+ EXPECT_EQ(policy_table::AHT_MEDIA, *hmi_types.begin());
+}
+
+TEST_F(SQLPTRepresentationTest,
+ SetPreloaded_SetPreloaded_ExpectPTSetToPreloaded) {
+ // Arrange
+ const char* query_insert = "UPDATE `module_config` SET `preloaded_pt` = 0";
+ ASSERT_TRUE(dbms->Exec(query_insert));
+ // Check
+ ASSERT_FALSE(reps->IsPTPreloaded());
+ // Act
+ reps->SetPreloaded(true);
+ // Check
+ ASSERT_TRUE(reps->IsPTPreloaded());
+ // Act
+ reps->SetPreloaded(false);
+ // Check
+ ASSERT_FALSE(reps->IsPTPreloaded());
+}
+
+TEST_F(SQLPTRepresentationTest,
+ SetIsDefault_SetIsDefault_ExpectDefaultFlagSet) {
+ // Arrange
+ const char* query_insert_app =
+ "INSERT OR IGNORE INTO `application`(`id`, `keep_context`, "
+ "`steal_focus`, `default_hmi`, `priority_value`, `is_revoked`, "
+ "`is_default`, `is_predata`, `memory_kb`, `heart_beat_timeout_ms`) "
+ "VALUES( '1234567', 0, 0, 'NONE', 'NONE', 0, 0, 1, 64, 10) ";
+ ASSERT_TRUE(dbms->Exec(query_insert_app));
+ const char* query_select =
+ "SELECT `is_default` FROM `application`WHERE`id`= '1234567' ";
+ EXPECT_EQ(0, dbms->FetchOneInt(query_select));
+ // Act
+ EXPECT_TRUE(reps->SetIsDefault("1234567", true));
+ // Check
+ EXPECT_EQ(1, dbms->FetchOneInt(query_select));
+ // Act
+ EXPECT_TRUE(reps->SetIsDefault("1234567", false));
+ // Check
+ EXPECT_EQ(0, dbms->FetchOneInt(query_select));
+}
+
+TEST(SQLPTRepresentationTest3, RemoveDB_RemoveDB_ExpectFileDeleted) {
+ // Arrange
+ policy_handler_test::MockPolicySettings policy_settings_;
+ SQLPTRepresentation* reps = new SQLPTRepresentation;
+ EXPECT_EQ(::policy::SUCCESS, reps->Init(&policy_settings_));
+ EXPECT_EQ(::policy::EXISTS, reps->Init(&policy_settings_));
+ std::string path = (reps->db())->get_path();
+ // Act
+ reps->RemoveDB();
+ // Check
+ EXPECT_FALSE(file_system::FileExists(path));
+ delete reps;
+}
+
+// TODO {AKozoriz} : Snapshot must have module meta section, but test
+// generates snapshot without it.
+TEST_F(SQLPTRepresentationTest,
+ DISABLED_GenerateSnapshot_SetPolicyTable_SnapshotIsPresent) {
// Arrange
Json::Value table(Json::objectValue);
PolicyTableUpdatePrepare(table);
@@ -564,7 +1502,7 @@ TEST_F(SQLPTRepresentationTest,
update.SetPolicyTableType(rpc::policy_table_interface_base::PT_UPDATE);
// Assert
- ASSERT_TRUE(IsValid(update));
+ // ASSERT_TRUE(IsValid(update));
ASSERT_TRUE(reps->Save(update));
// Act
@@ -599,6 +1537,167 @@ TEST_F(SQLPTRepresentationTest,
snapshot->ToJsonValue().toStyledString());
}
+TEST_F(SQLPTRepresentationTest, Save_SetPolicyTableThenSave_ExpectSavedToPT) {
+ // Arrange
+ Json::Value table(Json::objectValue);
+ PolicyTableUpdatePrepare(table);
+
+ policy_table::Table update(&table);
+ update.SetPolicyTableType(rpc::policy_table_interface_base::PT_UPDATE);
+ // Checks PT before Save
+ policy_table::FunctionalGroupings func_groups;
+ ASSERT_TRUE(reps->GetFunctionalGroupings(func_groups));
+ // Check functional groupings section
+ EXPECT_EQ(0u, func_groups.size());
+
+ policy_table::ApplicationPoliciesSection policies;
+ GatherApplicationPoliciesSection(&policies);
+ // Check ApplicationPoliciesSection
+ EXPECT_EQ(0u, policies.apps.size());
+ EXPECT_EQ(policy_table::Priority::P_EMERGENCY, policies.device.priority);
+
+ policy_table::ModuleConfig config;
+ GatherModuleConfig(&config);
+ // Check Module config section
+ EXPECT_TRUE(*config.preloaded_pt);
+ EXPECT_EQ(0, config.exchange_after_x_ignition_cycles);
+ EXPECT_EQ(0, config.exchange_after_x_kilometers);
+ EXPECT_EQ(0, config.exchange_after_x_days);
+ EXPECT_EQ(0, config.timeout_after_x_seconds);
+ EXPECT_EQ("", static_cast<std::string>(*config.vehicle_make));
+ EXPECT_EQ("", static_cast<std::string>(*config.vehicle_model));
+ EXPECT_EQ("", static_cast<std::string>(*config.vehicle_year));
+ EXPECT_EQ("", static_cast<std::string>(*config.preloaded_date));
+ EXPECT_EQ("", static_cast<std::string>(*config.certificate));
+ EXPECT_EQ(0u, config.seconds_between_retries.size());
+ EXPECT_EQ(0u, config.endpoints.size());
+ EXPECT_EQ(0u, config.notifications_per_minute_by_priority.size());
+
+ policy_table::ConsumerFriendlyMessages messages;
+ GatherConsumerFriendlyMessages(&messages);
+ EXPECT_EQ("0", static_cast<std::string>(messages.version));
+
+ policy_table::DeviceData devices;
+ GatherDeviceData(&devices);
+ EXPECT_EQ(0u, devices.size());
+
+ policy_table::UsageAndErrorCounts counts;
+ GatherUsageAndErrorCounts(&counts);
+ EXPECT_TRUE(0u == counts.app_level->size());
+
+ // ASSERT_TRUE(IsValid(update));
+ // Act
+ ASSERT_TRUE(reps->Save(update));
+
+ // Check Functional Groupings
+ ASSERT_TRUE(reps->GetFunctionalGroupings(func_groups));
+ // Checks
+ EXPECT_EQ(1u, func_groups.size());
+ policy_table::FunctionalGroupings::iterator func_groups_iter =
+ func_groups.find("default");
+ ASSERT_TRUE(func_groups.end() != func_groups_iter);
+ policy_table::Rpcs& rpcs = func_groups_iter->second;
+ EXPECT_EQ("", static_cast<std::string>(*rpcs.user_consent_prompt));
+ policy_table::Rpc& rpc = rpcs.rpcs;
+ EXPECT_EQ(1u, rpc.size());
+ policy_table::Rpc::const_iterator rpc_iter = rpc.find("Update");
+ EXPECT_TRUE(rpc.end() != rpc_iter);
+ const policy_table::HmiLevels& hmi_levels = rpc_iter->second.hmi_levels;
+ EXPECT_EQ(1u, hmi_levels.size());
+ EXPECT_TRUE(hmi_levels.end() != std::find(hmi_levels.begin(),
+ hmi_levels.end(),
+ policy_table::HmiLevel::HL_FULL));
+
+ const ::policy_table::Parameters& parameters = *(rpc_iter->second.parameters);
+ EXPECT_EQ(1u, parameters.size());
+ EXPECT_TRUE(parameters.end() != std::find(parameters.begin(),
+ parameters.end(),
+ policy_table::Parameter::P_SPEED));
+ // Check Application Policies Section
+ GatherApplicationPoliciesSection(&policies);
+ const uint32_t apps_size = 3u;
+
+ rpc::String<1ul, 255ul> str("default");
+ policy_table::Strings groups;
+ groups.push_back(str);
+ CheckAppPoliciesSection(policies,
+ apps_size,
+ policy_table::Priority::P_EMERGENCY,
+ "1234",
+ 150u,
+ 200u,
+ groups);
+ CheckAppPoliciesSection(policies,
+ apps_size,
+ policy_table::Priority::P_EMERGENCY,
+ "default",
+ 50u,
+ 100u,
+ groups);
+ CheckAppPoliciesSection(policies,
+ apps_size,
+ policy_table::Priority::P_EMERGENCY,
+ "pre_DataConsent",
+ 40u,
+ 90u,
+ groups);
+ CheckAppPoliciesSection(policies,
+ apps_size,
+ policy_table::Priority::P_EMERGENCY,
+ "device",
+ 0u,
+ 0u,
+ groups);
+
+ CheckAppGroups("1234", groups);
+ CheckAppGroups("default", groups);
+ CheckAppGroups("pre_DataConsent", groups);
+
+ GatherModuleConfig(&config);
+ // Check Module Config section
+ ASSERT_FALSE(*config.preloaded_pt);
+ ASSERT_EQ("encrypted_certificate_content",
+ static_cast<std::string>(*config.certificate));
+ ASSERT_EQ("", static_cast<std::string>(*config.preloaded_date));
+ ASSERT_EQ("", static_cast<std::string>(*config.vehicle_year));
+ ASSERT_EQ("", static_cast<std::string>(*config.vehicle_model));
+ ASSERT_EQ("", static_cast<std::string>(*config.vehicle_make));
+ ASSERT_EQ(10, config.exchange_after_x_ignition_cycles);
+ ASSERT_EQ(100, config.exchange_after_x_kilometers);
+ ASSERT_EQ(5, config.exchange_after_x_days);
+ ASSERT_EQ(500, config.timeout_after_x_seconds);
+ ASSERT_EQ(3u, config.seconds_between_retries.size());
+ ASSERT_EQ(10, config.seconds_between_retries[0]);
+ ASSERT_EQ(20, config.seconds_between_retries[1]);
+ ASSERT_EQ(30, config.seconds_between_retries[2]);
+ ASSERT_EQ(6u, config.notifications_per_minute_by_priority.size());
+ ASSERT_EQ(1, config.notifications_per_minute_by_priority["emergency"]);
+ ASSERT_EQ(2, config.notifications_per_minute_by_priority["navigation"]);
+ ASSERT_EQ(3, config.notifications_per_minute_by_priority["VOICECOMM"]);
+ ASSERT_EQ(4, config.notifications_per_minute_by_priority["communication"]);
+ ASSERT_EQ(5, config.notifications_per_minute_by_priority["normal"]);
+ ASSERT_EQ(6, config.notifications_per_minute_by_priority["none"]);
+ EXPECT_EQ(1u, config.endpoints.size());
+ policy_table::ServiceEndpoints& service_endpoints = config.endpoints;
+ EXPECT_EQ("0x00", service_endpoints.begin()->first);
+ policy_table::URLList& url_list = service_endpoints.begin()->second;
+ EXPECT_EQ("default", url_list.begin()->first);
+ policy_table::URL& url = url_list.begin()->second;
+ EXPECT_EQ("http://ford.com/cloud/default", static_cast<std::string>(url[0]));
+
+ GatherConsumerFriendlyMessages(&messages);
+ EXPECT_EQ("some_msg_version", static_cast<std::string>(messages.version));
+ EXPECT_TRUE(0u != messages.messages->size());
+ EXPECT_TRUE(0u != (*messages.messages)["MSG_CODE"].languages.size());
+
+ GatherUsageAndErrorCounts(&counts);
+ EXPECT_FALSE(0u == counts.app_level->size());
+ EXPECT_EQ(5u, (*counts.app_level)["some_app_id"].count_of_tls_errors);
+
+ GatherDeviceData(&devices);
+ EXPECT_EQ(3u, devices.size());
+}
+
} // namespace policy
} // namespace components
} // namespace test
diff --git a/src/components/policy/test/sqlite_wrapper/sql_database_test.cc b/src/components/policy/test/sqlite_wrapper/sql_database_test.cc
deleted file mode 100644
index 3bb633b2b1..0000000000
--- a/src/components/policy/test/sqlite_wrapper/sql_database_test.cc
+++ /dev/null
@@ -1,229 +0,0 @@
-/* Copyright (c) 2014, Ford Motor Company
-* All rights reserved.
-*
-* Redistribution and use in source and binary forms, with or without
-* modification, are permitted provided that the following conditions are met:
-*
-* Redistributions of source code must retain the above copyright notice, this
-* list of conditions and the following disclaimer.
-*
-* Redistributions in binary form must reproduce the above copyright notice,
-* this list of conditions and the following
-* disclaimer in the documentation and/or other materials provided with the
-* distribution.
-*
-* Neither the name of the Ford Motor Company nor the names of its contributors
-* may be used to endorse or promote products derived from this software
-* without specific prior written permission.
-*
-* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-* POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include "gtest/gtest.h"
-#include "sqlite_wrapper/sql_error.h"
-#include "sqlite_wrapper/sql_database.h"
-
-using ::policy::dbms::SQLError;
-using ::policy::dbms::SQLDatabase;
-
-namespace test {
-namespace components {
-namespace policy {
-namespace dbms {
-
-::testing::AssertionResult IsError(SQLError error) {
- if (error.number() != ::policy::dbms::OK) {
- return ::testing::AssertionSuccess() << error.text();
- } else {
- return ::testing::AssertionFailure() << error.text();
- }
-}
-
-TEST(SQLDatabaseTest, OpenCloseMemory_OpenAndCloseDB_ActsWithoutError) {
-
- //arrange
- SQLDatabase db;
- bool ret = db.Open();
-
- //assert
- EXPECT_FALSE(IsError(db.LastError()));
- ASSERT_TRUE(ret);
-
- //act
- db.Close();
-
- //assert
- EXPECT_FALSE(IsError(db.LastError()));
-}
-
-TEST(SQLDatabaseTest, OpenCloseFile_OpenAndCloseSpecifiedDB_ActsWithoutError) {
-
- //arrange
- SQLDatabase db("test-database");
- bool ret = db.Open();
-
- //assert
- EXPECT_FALSE(IsError(db.LastError()));
- ASSERT_TRUE(ret);
-
- //act
- db.Close();
-
- //assert
- EXPECT_FALSE(IsError(db.LastError()));
-
- remove("test-database.sqlite");
-}
-
-TEST(SQLDatabaseTest, OpenDBTwice_NoError) {
-
- //arrange
- SQLDatabase db;
- bool ret = db.Open();
-
- //assert
- EXPECT_FALSE(IsError(db.LastError()));
- ASSERT_TRUE(ret);
-
- //act
- ret = db.Open();
-
- //assert
- EXPECT_FALSE(IsError(db.LastError()));
- ASSERT_TRUE(ret);
-
- db.Close();
-}
-
-TEST(SQLDatabaseTest, CloseDBTwice_NoError) {
-
- //arrange
- SQLDatabase db;
- bool ret = db.Open();
-
- //assert
- EXPECT_FALSE(IsError(db.LastError()));
- ASSERT_TRUE(ret);
-
- //act
- db.Close();
-
- //assert
- EXPECT_FALSE(IsError(db.LastError()));
-
- //act
- db.Close();
-
- //assert
- EXPECT_FALSE(IsError(db.LastError()));
-}
-
-TEST(SQLDatabaseTest, Close_DBWasNotOpened_NoError) {
-
- //act
- SQLDatabase db;
- db.Close();
-
- //assert
- EXPECT_FALSE(IsError(db.LastError()));
-}
-
-TEST(SQLDatabaseTest, CommitTransaction_StartAndCommitTransaction_ExpectActsWithoutError) {
-
- //arrange
- SQLDatabase db;
-
- //assert
- ASSERT_TRUE(db.Open());
- EXPECT_TRUE(db.BeginTransaction());
- EXPECT_FALSE(IsError(db.LastError()));
- EXPECT_TRUE(db.CommitTransaction());
- EXPECT_FALSE(IsError(db.LastError()));
-
- db.Close();
-}
-
-TEST(SQLDatabaseTest, RollbackTransaction_StartAndRollbackTransaction_ExpectActsWithoutError) {
-
- //arrange
- SQLDatabase db;
-
- //assert
- ASSERT_TRUE(db.Open());
- EXPECT_TRUE(db.BeginTransaction());
- EXPECT_FALSE(IsError(db.LastError()));
- EXPECT_TRUE(db.RollbackTransaction());
- EXPECT_FALSE(IsError(db.LastError()));
-
- db.Close();
-}
-
-TEST(SQLDatabaseTest, FailedCommitTransaction_CommitTransactionWithoutBeginning_ExpectError) {
-
- //arrange
- SQLDatabase db;
-
- //assert
- ASSERT_TRUE(db.Open());
- EXPECT_FALSE(db.CommitTransaction());
- EXPECT_TRUE(IsError(db.LastError()));
-
- db.Close();
-}
-
-TEST(SQLDatabaseTest, FailedRollbackTransaction_RollbackTransactionWithoutBeginning_ExpectError) {
-
- //arrange
- SQLDatabase db;
-
- //assert
- ASSERT_TRUE(db.Open());
- EXPECT_FALSE(db.RollbackTransaction());
- EXPECT_TRUE(IsError(db.LastError()));
-
- db.Close();
-}
-
-TEST(SQLDatabaseTest, BadTransaction_BeginTransitionWithoutOpenDB_ExpectError) {
-
- //arrange
- SQLDatabase db;
-
- //assert
- EXPECT_FALSE(db.BeginTransaction());
- EXPECT_TRUE(IsError(db.LastError()));
-}
-
-TEST(SQLDatabaseTest, IsReadWrite_FirstOpenDBIsRWSecondIsNot) {
-
- //arrange
- SQLDatabase db("test-database");
-
- //assert
- ASSERT_TRUE(db.Open());
- EXPECT_TRUE(db.IsReadWrite());
- db.Close();
- chmod("test-database.sqlite", S_IRUSR);
-
- //assert
- ASSERT_TRUE(db.Open());
- EXPECT_FALSE(db.IsReadWrite());
-
- db.Close();
- remove("test-database.sqlite");
-}
-
-} // namespace dbms
-} // namespace policy
-} // namespace components
-} // namespace test
diff --git a/src/components/policy/test/sqlite_wrapper/sql_query_test.cc b/src/components/policy/test/sqlite_wrapper/sql_query_test.cc
deleted file mode 100644
index 83a3bf00cf..0000000000
--- a/src/components/policy/test/sqlite_wrapper/sql_query_test.cc
+++ /dev/null
@@ -1,375 +0,0 @@
-/* Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <sqlite3.h>
-#include <string>
-
-#include "gtest/gtest.h"
-
-#include "sqlite_wrapper/sql_error.h"
-#include "sqlite_wrapper/sql_database.h"
-#include "sqlite_wrapper/sql_query.h"
-
-using ::policy::dbms::SQLError;
-using ::policy::dbms::SQLDatabase;
-using ::policy::dbms::SQLQuery;
-
-namespace test {
-namespace components {
-namespace policy {
-namespace dbms {
-
-class SQLQueryTest : public ::testing::Test {
- protected:
- static sqlite3* conn;
- static const std::string kDatabaseName;
-
- static void SetUpTestCase() {
- sqlite3_open((kDatabaseName + ".sqlite").c_str(), &conn);
- sqlite3_exec(conn, "CREATE TABLE testTable (integerValue INTEGER,"
- " doubleValue REAL, stringValue TEXT)",
- NULL, NULL, NULL);
- }
-
- static void TearDownTestCase() {
- sqlite3_close(conn);
- remove((kDatabaseName + ".sqlite").c_str());
- }
-
- void SetUp() {
- sqlite3_exec(conn, "DELETE FROM testTable", NULL, NULL, NULL);
- }
-
- ::testing::AssertionResult IsError(SQLError error) {
- if (error.number() != ::policy::dbms::OK) {
- return ::testing::AssertionSuccess() << error.text();
- } else {
- return ::testing::AssertionFailure() << error.text();
- }
- }
-
- ::testing::AssertionResult IsDone(SQLError error) {
- if (error.number() == ::policy::dbms::DONE) {
- return ::testing::AssertionSuccess() << error.text();
- } else {
- return ::testing::AssertionFailure() << error.text();
- }
- }
-
- ::testing::AssertionResult IsRow(SQLError error) {
- if (error.number() == ::policy::dbms::ROW) {
- return ::testing::AssertionSuccess() << error.text();
- } else {
- return ::testing::AssertionFailure() << error.text();
- }
- }
-};
-
-sqlite3* SQLQueryTest::conn = 0;
-const std::string SQLQueryTest::kDatabaseName = "test-query";
-
-TEST_F(SQLQueryTest, Query_CreateQuery_QueryInDBEqualCreated) {
-
- //arrange
- const std::string kSelect("SELECT * FROM testTable WHERE integerValue = ?");
- SQLDatabase db(kDatabaseName);
-
- //assert
- ASSERT_TRUE(db.Open());
-
- //act
- SQLQuery query(&db);
- query.Prepare(kSelect);
-
- //assert
- EXPECT_STREQ(kSelect.c_str(), query.query().c_str());
-}
-
-TEST_F(SQLQueryTest, ExecString_ExecuteQuery_ActWithoutError) {
-
- //arrange
- const std::string kInsert("INSERT INTO testTable"
- " (integerValue, doubleValue, stringValue)"
- " VALUES(2, 3.4, 'five-пять')");
- SQLDatabase db(kDatabaseName);
- //assert
- ASSERT_TRUE(db.Open());
-
- //act
- SQLQuery query(&db);
-
- //assert
- EXPECT_TRUE(query.Exec(kInsert));
- EXPECT_FALSE(IsError(query.LastError()));
-}
-
-TEST_F(SQLQueryTest, Bind_BindSeveralQueries_ExpectExecutedQueriesWithoutErrors) {
-
- //arrange
- const std::string kInsert1("INSERT INTO testTable (integerValue) VALUES (?)");
- const std::string kInsert2("INSERT INTO testTable (doubleValue) VALUES (?)");
- const std::string kInsert3("INSERT INTO testTable (stringValue) VALUES (?)");
- const std::string kInsert4("INSERT INTO testTable (integerValue, doubleValue,"
- " stringValue) VALUES (?, ?, ?)");
- const int kIntegerValue = 1;
- const double kDoubleValue = 2.3;
- const std::string kStringValue = "four";
-
- SQLDatabase db(kDatabaseName);
-
- //assert
- ASSERT_TRUE(db.Open());
-
- //act
- SQLQuery query1(&db);
-
- //assert
- EXPECT_TRUE(query1.Prepare(kInsert1));
- EXPECT_FALSE(IsError(query1.LastError()));
- query1.Bind(0, kIntegerValue);
-
- //assert
- EXPECT_FALSE(IsError(query1.LastError()));
- EXPECT_TRUE(query1.Exec());
- EXPECT_TRUE(IsDone(query1.LastError()));
-
- //act
- SQLQuery query2(&db);
- //assert
- EXPECT_TRUE(query2.Prepare(kInsert2));
- EXPECT_FALSE(IsError(query2.LastError()));
- query2.Bind(0, kDoubleValue);
- //assert
- EXPECT_FALSE(IsError(query2.LastError()));
- EXPECT_TRUE(query2.Exec());
- EXPECT_TRUE(IsDone(query2.LastError()));
-
- //act
- SQLQuery query3(&db);
- EXPECT_TRUE(query3.Prepare(kInsert3));
- EXPECT_FALSE(IsError(query3.LastError()));
- query3.Bind(0, kStringValue);
- //assert
- EXPECT_FALSE(IsError(query3.LastError()));
- EXPECT_TRUE(query3.Exec());
- EXPECT_TRUE(IsDone(query3.LastError()));
-
- //act
- SQLQuery query4(&db);
- //assert
- EXPECT_TRUE(query4.Prepare(kInsert4));
- EXPECT_FALSE(IsError(query4.LastError()));
- query4.Bind(0, kIntegerValue);
- query4.Bind(1, kDoubleValue);
- query4.Bind(2, kStringValue);
- //assert
- EXPECT_FALSE(IsError(query4.LastError()));
- EXPECT_TRUE(query4.Exec());
- EXPECT_TRUE(IsDone(query4.LastError()));
-}
-
-TEST_F(SQLQueryTest, SetValue_InsertValues_ExpectDBHasInsertedValues) {
-
- //arrange
- const char* insert = "INSERT INTO testTable "
- "(integerValue, doubleValue, stringValue) "
- "VALUES (1, 2.3, 'four');";
-
- //assert
- ASSERT_EQ(SQLITE_OK, sqlite3_exec(conn, insert, NULL, NULL, NULL));
-
- //act
- const std::string kSelect("SELECT integerValue, doubleValue, stringValue"
- " FROM testTable");
- const int kIntegerValue = 1;
- const double kDoubleValue = 2.3;
- const std::string kStringValue = "four";
-
- SQLDatabase db(kDatabaseName);
-
- //assert
- ASSERT_TRUE(db.Open());
-
- //act
- SQLQuery query(&db);
-
- //assert
- EXPECT_TRUE(query.Prepare(kSelect));
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Exec());
- EXPECT_TRUE(IsRow(query.LastError()));
- EXPECT_EQ(kIntegerValue, query.GetInteger(0));
- EXPECT_EQ(kDoubleValue, query.GetDouble(1));
- EXPECT_EQ(kStringValue, query.GetString(2));
- EXPECT_FALSE(query.Next());
- EXPECT_TRUE(IsDone(query.LastError()));
-}
-
-TEST_F(SQLQueryTest, EmptySelect_SelectValuesEqual0_ExecWithoutErrors) {
-
- //arrange
- const std::string kSelect("SELECT integerValue, doubleValue, stringValue"
- " FROM testTable WHERE 0");
- SQLDatabase db(kDatabaseName);
-
- //assert
- ASSERT_TRUE(db.Open());
-
- //act
- SQLQuery query(&db);
-
- //assert
- EXPECT_TRUE(query.Prepare(kSelect));
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Exec());
- EXPECT_TRUE(IsDone(query.LastError()));
-}
-
-TEST_F(SQLQueryTest, NextAndBind_InsertValuesAndBindQuery_ExecWithoutErrorsAndBindingQueryIsLast) {
-
- //arrange
- const char* insert = "INSERT INTO testTable "
- "(integerValue, doubleValue, stringValue) "
- "VALUES (1, 2.3, 'four');";
-
- //assert
- ASSERT_EQ(SQLITE_OK, sqlite3_exec(conn, insert, NULL, NULL, NULL));
-
- const std::string kSelect("SELECT integerValue, doubleValue, stringValue"
- " FROM testTable WHERE stringValue = ?");
-
- //act
- const int kIntegerValue = 1;
- const double kDoubleValue = 2.3;
- const std::string kStringValue = "four";
-
- SQLDatabase db(kDatabaseName);
- ASSERT_TRUE(db.Open());
-
- SQLQuery query(&db);
-
- //assert
- ASSERT_TRUE(query.Prepare(kSelect));
- EXPECT_FALSE(IsError(query.LastError()));
- //act
- query.Bind(0, kStringValue);
- //assert
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Exec());
- ASSERT_TRUE(IsRow(query.LastError()));
- EXPECT_EQ(kIntegerValue, query.GetInteger(0));
- EXPECT_EQ(kDoubleValue, query.GetDouble(1));
- EXPECT_EQ(kStringValue, query.GetString(2));
- EXPECT_FALSE(query.Next());
- EXPECT_TRUE(IsDone(query.LastError()));
-}
-
-TEST_F(SQLQueryTest, LastInsertId_InsertValuesAndBindQuery_GetExpectedId) {
-
- //arrange
- const char* create = "CREATE TABLE idTable ( "
- "id INTEGER PRIMARY KEY AUTOINCREMENT,"
- "value TEXT)";
-
- //assert
- ASSERT_EQ(SQLITE_OK, sqlite3_exec(conn, create, NULL, NULL, NULL));
-
-
- const int64_t kExpectId = 1;
- const std::string kValue("Test last id of insert row");
- const std::string kInsert("INSERT INTO idTable (value) VALUES(?)");
-
- //act
- SQLDatabase db(kDatabaseName);
-
- //assert
- ASSERT_TRUE(db.Open());
-
- //act
- SQLQuery query(&db);
-
- //assert
- ASSERT_TRUE(query.Prepare(kInsert));
- EXPECT_FALSE(IsError(query.LastError()));
-
- //act
- query.Bind(0, kValue);
- //assert
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Exec());
- ASSERT_TRUE(IsDone(query.LastError()));
- EXPECT_EQ(kExpectId, query.LastInsertId());
-
- ASSERT_EQ(SQLITE_OK,
- sqlite3_exec(conn, "DROP TABLE idTable", NULL, NULL, NULL));
-}
-
-TEST_F(SQLQueryTest, BindNull_BindWithoutValue_ActWithoutErrors) {
-
- //arrange
- const std::string kInsert("INSERT INTO testTable (`integerValue`)"
- " VALUES (?)");
- SQLDatabase db(kDatabaseName);
- //assert
- ASSERT_TRUE(db.Open());
-
- //act
- SQLQuery query(&db);
-
- //assert
- ASSERT_TRUE(query.Prepare(kInsert));
- EXPECT_FALSE(IsError(query.LastError()));
- query.Bind(0);
- //assert
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Exec());
- ASSERT_TRUE(IsDone(query.LastError()));
-}
-
-TEST_F(SQLQueryTest, DoublePrepare_TwicePrepareQuery_ActWithoutErrors) {
-
- //arrange
- SQLDatabase db(kDatabaseName);
- //assert
- ASSERT_TRUE(db.Open());
- //act
- SQLQuery query(&db);
- //assert
- EXPECT_TRUE(query.Prepare("SELECT * FROM testTable"));
- EXPECT_FALSE(IsError(query.LastError()));
- EXPECT_TRUE(query.Prepare("SELECT * FROM testTable"));
- EXPECT_FALSE(IsError(query.LastError()));
-}
-
-} // namespace dbms
-} // namespace policy
-} // namespace components
-} // namespace test
diff --git a/src/components/policy/test/test-qdb.ini b/src/components/policy/test/test-qdb.ini
deleted file mode 100644
index 5f8c46c0cf..0000000000
--- a/src/components/policy/test/test-qdb.ini
+++ /dev/null
@@ -1,11 +0,0 @@
-# This config file for QDB
-# Format see in manual of QNX
-[policy]
-Filename=policy.db
-Schema File=policy.sql
-
-[test-database]
-Filename=test-database.sqlite
-
-[test-query]
-Filename=test-query.sqlite \ No newline at end of file
diff --git a/src/components/policy/test/update_status_manager_test.cc b/src/components/policy/test/update_status_manager_test.cc
new file mode 100644
index 0000000000..623cb974d8
--- /dev/null
+++ b/src/components/policy/test/update_status_manager_test.cc
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "mock_policy_listener.h"
+#include "policy/policy_manager_impl.h"
+#include "policy/update_status_manager.h"
+
+using ::policy::MockPolicyListener;
+
+namespace test {
+namespace components {
+namespace policy {
+
+using namespace ::policy;
+
+class UpdateStatusManagerTest : public ::testing::Test {
+ protected:
+ UpdateStatusManager* manager_;
+ PolicyTableStatus status_;
+ const uint32_t k_timeout_;
+
+ public:
+ UpdateStatusManagerTest() : k_timeout_(1) {}
+
+ void SetUp() {
+ manager_ = new UpdateStatusManager();
+ }
+
+ void TearDown() OVERRIDE {
+ delete manager_;
+ }
+};
+
+TEST_F(UpdateStatusManagerTest,
+ StringifiedUpdateStatus_SetStatuses_ExpectCorrectStringifiedStatuses) {
+ // Arrange
+ manager_->OnPolicyInit(false);
+ // Check
+ EXPECT_EQ("UP_TO_DATE", manager_->StringifiedUpdateStatus());
+ manager_->OnPolicyInit(true);
+ // Check
+ EXPECT_EQ("UPDATE_NEEDED", manager_->StringifiedUpdateStatus());
+ manager_->OnUpdateSentOut(k_timeout_);
+ // Check
+ EXPECT_EQ("UPDATING", manager_->StringifiedUpdateStatus());
+}
+
+TEST_F(UpdateStatusManagerTest,
+ OnAppSearchStartedCompleted_ExpectAppSearchCorrectStatus) {
+ // Arrange
+ manager_->OnAppsSearchStarted();
+ // Check
+ EXPECT_TRUE(manager_->IsAppsSearchInProgress());
+ // Arrange
+ manager_->OnAppsSearchCompleted();
+ // Check
+ EXPECT_FALSE(manager_->IsAppsSearchInProgress());
+}
+
+} // namespace policy
+} // namespace components
+} // namespace test
diff --git a/src/components/policy/test/usage_statistics_test.cc b/src/components/policy/test/usage_statistics_test.cc
deleted file mode 100644
index be9d9ff81f..0000000000
--- a/src/components/policy/test/usage_statistics_test.cc
+++ /dev/null
@@ -1,196 +0,0 @@
-/* Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-#include "gtest/gtest.h"
-
-#include "mock_statistics_manager.h"
-#include "usage_statistics/counter.h"
-
-using ::testing::StrictMock;
-using ::testing::InSequence;
-
-namespace usage_statistics {
-namespace test {
-
-// TEST(A, B_C_D) { ... }
-// A - What you test
-// B - What you do
-// C - Input data
-// D - Expected result
-
-TEST(StatisticsManagerIncrementMethod1Arg, GlobalCounterOverloadedIncrement_CallONCE_StatisticsManagerIncrementCalledONCE) {
- //Arrange
- MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
- GlobalCounter reboots_counter(msm, SYNC_REBOOTS);
-
- //Assert
- EXPECT_CALL(*msm, Increment(SYNC_REBOOTS));
-
- //Act
- ++reboots_counter;
-}
-
-TEST(StatisticsManagerIncrementMethod1Arg, GlobalCounterOverloadedIncrement_CallTWICE_StatisticsManagerIncrementCalledTWICE) {
- //Arrange
- MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
- GlobalCounter reboots_counter(msm, SYNC_REBOOTS);
-
- //Assert
- EXPECT_CALL(*msm, Increment(SYNC_REBOOTS)).Times(2);
-
- //Act
- ++reboots_counter;
- ++reboots_counter;
-}
-
-TEST(StatisticsManagerIncrementMethod2Args, AppCounterOverloadedIncrement_CallONCE_StatisticsManagerIncrementCalledONCE) {
- //Arrange
- MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
- AppCounter user_selections_counter(msm, "HelloApp", USER_SELECTIONS);
-
- //Assert
- EXPECT_CALL(*msm, Increment("HelloApp", USER_SELECTIONS));
-
- //Act
- ++user_selections_counter;
-}
-
-TEST(StatisticsManagerIncrementMethod2Args, AppCounterOverloadedIncrement_CallTWICE_StatisticsManagerIncrementCalledTWICE) {
- //Arrange
- MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
- AppCounter user_selections_counter(msm, "HelloApp", USER_SELECTIONS);
-
- //Assert
- EXPECT_CALL(*msm, Increment("HelloApp", USER_SELECTIONS)).Times(2);
-
- //Act
- ++user_selections_counter;
- ++user_selections_counter;
-}
-//---
-TEST(StatisticsManagerSetMethod, AppInfoUpdateMethod_CallONCE_StatisticsManagerSetMethodCalledONCE) {
- //Arrange
- MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
- AppInfo gui_language_info(msm, "HelloApp", LANGUAGE_GUI);
-
- //Assert
- EXPECT_CALL(*msm, Set("HelloApp", LANGUAGE_GUI, "Klingon"));
-
- //Act
- gui_language_info.Update("Klingon");
-}
-
-TEST(StatisticsManagerSetMethod, AppInfoUpdateMethod_CallTWICE_StatisticsManagerSetMethodCalledTWICE) {
- //Arrange
- MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
- AppInfo gui_language_info(msm, "HelloApp", LANGUAGE_GUI);
-
- //Assert
- EXPECT_CALL(*msm, Set("HelloApp", LANGUAGE_GUI, "Klingon"));
- EXPECT_CALL(*msm, Set("HelloApp", LANGUAGE_GUI, "UA"));
-
- //Act
- gui_language_info.Update("Klingon");
- gui_language_info.Update("UA");
-}
-
-
-TEST(StatisticsManagerAddMethod, DISABLED_AppStopwatchStartMethod_CallONCE_StatisticsManagerAddMethodCalledONCE) {
- //Arrange
- MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
- const std::uint32_t time_out = 1;
- AppStopwatch hmi_full_stopwatch(msm, "HelloApp", time_out);
-
- //Assert
- EXPECT_CALL(*msm, Add("HelloApp", SECONDS_HMI_FULL, 0));
-
- //Act
- hmi_full_stopwatch.Start(SECONDS_HMI_FULL);
-}
-
-TEST(StatisticsManagerAddMethod, DISABLED_AppStopwatchStartMethod_Call_StatisticsManagerAddMethodCALLED) {
- //Arrange
-
- MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
- const std::uint32_t time_out = 1;
- AppStopwatch hmi_full_stopwatch(msm, "HelloApp", time_out);
-
- //Assert
- EXPECT_CALL(*msm, Add("HelloApp", SECONDS_HMI_FULL, 0));
-
- //Act
- hmi_full_stopwatch.Start(SECONDS_HMI_FULL);
- sleep(2);
-}
-
-TEST(StatisticsManagerAddMethod, DISABLED_AppStopwatchSwitchMethod_Call_StatisticsManagerAddMethodCALLED) {
- //Arrange
- MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
- AppStopwatch hmi_full_stopwatch(msm, "HelloApp");
- hmi_full_stopwatch.Start(SECONDS_HMI_FULL);
-
- //Assert
- EXPECT_CALL(*msm, Add("HelloApp", SECONDS_HMI_FULL, 0)).Times(2); // Once in stop(), once in destructor
-
- //Act
- hmi_full_stopwatch.Switch(SECONDS_HMI_FULL);
-}
-
-TEST(StatisticsManagerAddMethod, DISABLED_AppStopwatchStartMethod_CallAnd1SecSleepAfter_StatisticsManagerAddMethodCalledWith1SecTimespan) {
- //Arrange
- MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
- AppStopwatch hmi_full_stopwatch(msm, "HelloApp");
-
- //Assert
- EXPECT_CALL(*msm, Add("HelloApp", SECONDS_HMI_FULL, 1));
-
- //Act
- hmi_full_stopwatch.Start(SECONDS_HMI_FULL);
- sleep(1);
-}
-
-
-TEST(StatisticsManagerAddMethod, DISABLED_AppStopwatchSwitchMethod_CallAnd1SecSleepAfter_StatisticsManagerAddMethodCalledWith1SecTimespan) {
- //Arrange
- MockStatisticsManager* msm = new StrictMock<MockStatisticsManager>();
- const std::uint32_t time_out = 1;
- AppStopwatch hmi_full_stopwatch(msm, "HelloApp", time_out);
-
- //Assert
- EXPECT_CALL(*msm, Add("HelloApp", SECONDS_HMI_NONE, 0));
- EXPECT_CALL(*msm, Add("HelloApp", SECONDS_HMI_BACKGROUND, 1));
-
- //Act
- hmi_full_stopwatch.Start(SECONDS_HMI_NONE);
- hmi_full_stopwatch.Switch(SECONDS_HMI_BACKGROUND);
- sleep(2);
-}
-} // namespace test
-} // namespace usage_statistics
diff --git a/src/components/policy/test/valid_sdl_pt_update.json b/src/components/policy/test/valid_sdl_pt_update.json
index 6556ad5106..56c728f104 100644
--- a/src/components/policy/test/valid_sdl_pt_update.json
+++ b/src/components/policy/test/valid_sdl_pt_update.json
@@ -20,7 +20,7 @@
"nicknames" : [ "SyncProxyTester" ],
"priority" : "EMERGENCY",
"steal_focus" : true,
- "watchdog_timer_ms" : 20000
+ "heart_beat_timeout_ms": 5000
},
"default" : {
"default_hmi" : "NONE",
@@ -28,8 +28,7 @@
"keep_context" : false,
"memory_kb" : 1000,
"priority" : "NONE",
- "steal_focus" : false,
- "watchdog_timer_ms" : 20000
+ "steal_focus" : false
},
"device" : {
"default_hmi" : "NONE",
@@ -46,8 +45,7 @@
"keep_context" : false,
"memory_kb" : 1000,
"priority" : "NONE",
- "steal_focus" : false,
- "watchdog_timer_ms" : 20000
+ "steal_focus" : false
}
},
"consumer_friendly_messages" : {
@@ -1712,7 +1710,6 @@
"NORMAL" : 4,
"VOICECOMM" : 10
},
- "preloaded_pt" : true,
"seconds_between_retries" : [ 1, 5, 25, 125, 625 ],
"timeout_after_x_seconds" : 60,
"vehicle_make" : "Stark Industries",
diff --git a/src/components/protocol/src/message_priority.cc b/src/components/protocol/src/message_priority.cc
index d76cde038c..893e624ed2 100644
--- a/src/components/protocol/src/message_priority.cc
+++ b/src/components/protocol/src/message_priority.cc
@@ -50,8 +50,7 @@ MessagePriority MessagePriority::FromServiceType(ServiceType service_type) {
}
MessagePriority::MessagePriority(const MessagePriority& that)
- : value_(that.value_) {
-}
+ : value_(that.value_) {}
size_t MessagePriority::OrderingValue() const {
return value_;
diff --git a/src/components/protocol/src/raw_message.cc b/src/components/protocol/src/raw_message.cc
index 7b1b8b087d..daffd0f2bd 100644
--- a/src/components/protocol/src/raw_message.cc
+++ b/src/components/protocol/src/raw_message.cc
@@ -36,16 +36,19 @@
namespace protocol_handler {
-RawMessage::RawMessage(uint32_t connection_key, uint32_t protocol_version,
- const uint8_t *const data_param, uint32_t data_sz,
- uint8_t type, uint32_t payload_size)
- : connection_key_(connection_key),
- data_(NULL),
- data_size_(data_sz),
- protocol_version_(protocol_version),
- service_type_(ServiceTypeFromByte(type)),
- payload_size_(payload_size),
- waiting_(false) {
+RawMessage::RawMessage(uint32_t connection_key,
+ uint32_t protocol_version,
+ const uint8_t* const data_param,
+ uint32_t data_sz,
+ uint8_t type,
+ uint32_t payload_size)
+ : connection_key_(connection_key)
+ , data_(NULL)
+ , data_size_(data_sz)
+ , protocol_version_(protocol_version)
+ , service_type_(ServiceTypeFromByte(type))
+ , payload_size_(payload_size)
+ , waiting_(false) {
if (data_param && data_sz > 0) {
data_ = new uint8_t[data_sz];
memcpy(data_, data_param, sizeof(*data_) * data_sz);
@@ -64,7 +67,7 @@ void RawMessage::set_connection_key(uint32_t key) {
connection_key_ = key;
}
-uint8_t *RawMessage::data() const {
+uint8_t* RawMessage::data() const {
return data_;
}
diff --git a/src/components/protocol/src/rpc_type.cc b/src/components/protocol/src/rpc_type.cc
index ce8ab898f5..bc1142ad5c 100644
--- a/src/components/protocol/src/rpc_type.cc
+++ b/src/components/protocol/src/rpc_type.cc
@@ -67,7 +67,7 @@ uint8_t RpcTypeToByte(RpcType type) {
return uint8_t(type);
}
-const char *RpcTypeToString(RpcType type) {
+const char* RpcTypeToString(RpcType type) {
switch (type) {
case kRpcTypeRequest:
return "kRpcTypeRequest";
@@ -80,7 +80,7 @@ const char *RpcTypeToString(RpcType type) {
}
}
-std::ostream &operator<<(std::ostream &os, RpcType rpc_type) {
+std::ostream& operator<<(std::ostream& os, RpcType rpc_type) {
return os << RpcTypeToString(rpc_type);
}
} // namespace protocol_handler
diff --git a/src/components/protocol/src/service_type.cc b/src/components/protocol/src/service_type.cc
index 09adae23be..8ca57f338b 100644
--- a/src/components/protocol/src/service_type.cc
+++ b/src/components/protocol/src/service_type.cc
@@ -36,7 +36,7 @@
namespace protocol_handler {
-CREATE_LOGGERPTR_GLOBAL(logger_, "ConnectionHandler")
+CREATE_LOGGERPTR_GLOBAL(logger_, "ProtocolHandler")
namespace {
// Check if provided service value is one of the specified
@@ -58,7 +58,7 @@ ServiceType ServiceTypeFromByte(uint8_t byte) {
ServiceType type = ServiceType(byte);
const bool valid_type = IsValid(type);
if (!valid_type) {
- LOG4CXX_INFO(logger_, "Invalid service type: "<< int32_t(byte));
+ LOG4CXX_INFO(logger_, "Invalid service type: " << int32_t(byte));
}
return valid_type ? type : kInvalidServiceType;
}
diff --git a/src/components/protocol_handler/CMakeLists.txt b/src/components/protocol_handler/CMakeLists.txt
index 10a18c48b6..a09a565844 100644
--- a/src/components/protocol_handler/CMakeLists.txt
+++ b/src/components/protocol_handler/CMakeLists.txt
@@ -34,7 +34,6 @@ include_directories(
${COMPONENTS_DIR}/utils/include/
${COMPONENTS_DIR}/protocol_handler/include/
${COMPONENTS_DIR}/connection_handler/include/
- ${COMPONENTS_DIR}/config_profile/include/
${LOG4CXX_INCLUDE_DIRECTORY}
)
@@ -43,6 +42,7 @@ set(SOURCES
${COMPONENTS_DIR}/protocol_handler/src/protocol_handler_impl.cc
${COMPONENTS_DIR}/protocol_handler/src/protocol_packet.cc
${COMPONENTS_DIR}/protocol_handler/src/protocol_payload.cc
+ ${COMPONENTS_DIR}/protocol_handler/src/multiframe_builder.cc
)
set(LIBRARIES
diff --git a/src/components/protocol_handler/include/protocol_handler/incoming_data_handler.h b/src/components/protocol_handler/include/protocol_handler/incoming_data_handler.h
index bd64db9063..4633be6c6e 100644
--- a/src/components/protocol_handler/include/protocol_handler/incoming_data_handler.h
+++ b/src/components/protocol_handler/include/protocol_handler/incoming_data_handler.h
@@ -32,7 +32,6 @@
#ifndef SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_INCOMING_DATA_HANDLER_H_
#define SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_INCOMING_DATA_HANDLER_H_
-#include <list>
#include <map>
#include <vector>
#include "utils/macro.h"
@@ -43,7 +42,8 @@ namespace protocol_handler {
/**
* \class IncomingDataHandler
- * \brief Class for contecat TM messages to ford frames and validate ford header data
+ * \brief Class for contecat TM messages to ford frames and validate ford header
+ * data
* IncomingDataHandler methods are reentrant and not thread-safe
*/
class IncomingDataHandler {
@@ -53,7 +53,8 @@ class IncomingDataHandler {
* @brief Setting additional validator for checking malformed packets
* \param validator pointer
*/
- void set_validator(const ProtocolPacket::ProtocolHeaderValidator *const validator);
+ void set_validator(
+ const ProtocolPacket::ProtocolHeaderValidator* const validator);
/**
* @brief Concatenate TM messages to ford frames and validate ford header data
* \param TM messages for converting to frames
@@ -65,25 +66,23 @@ class IncomingDataHandler {
* - RESULT_FAIL - packet serialization or validation error occurs
* \return list of complete, correct packets
*/
- std::list<ProtocolFramePtr> ProcessData(const RawMessage &tm_message,
- RESULT_CODE *result,
- size_t *malformed_occurrence);
+ ProtocolFramePtrList ProcessData(const RawMessage& tm_message,
+ RESULT_CODE* result,
+ size_t* malformed_occurrence);
/**
* @brief Add connection for data handling and verification
*/
- void AddConnection(
- const transport_manager::ConnectionUID connection_id);
+ void AddConnection(const transport_manager::ConnectionUID connection_id);
/**
* @brief Remove connection and all unhandled data
*/
- void RemoveConnection(
- const transport_manager::ConnectionUID connection_id);
+ void RemoveConnection(const transport_manager::ConnectionUID connection_id);
private:
/**
* @brief Returns size of frame to be formed from raw bytes.
*/
- static uint32_t GetPacketSize(const ProtocolPacket::ProtocolHeader &header);
+ static uint32_t GetPacketSize(const ProtocolPacket::ProtocolHeader& header);
/**
* @brief Try to create frame from incoming data
* \param incommung_data raw stream
@@ -95,16 +94,17 @@ class IncomingDataHandler {
* - RESULT_OK - one or more frames successfully created
* - RESULT_FAIL - packet serialization or validation error occurs
*/
- RESULT_CODE CreateFrame(std::vector<uint8_t> &incoming_data,
- std::list<ProtocolFramePtr> &out_frames,
- size_t &malformed_occurrence,
+ RESULT_CODE CreateFrame(std::vector<uint8_t>& incoming_data,
+ ProtocolFramePtrList& out_frames,
+ size_t& malformed_occurrence,
const transport_manager::ConnectionUID connection_id);
typedef std::map<transport_manager::ConnectionUID, std::vector<uint8_t> >
- ConnectionsDataMap;
+ ConnectionsDataMap;
ConnectionsDataMap connections_data_;
ProtocolPacket::ProtocolHeader header_;
- const ProtocolPacket::ProtocolHeaderValidator *validator_;
+ const ProtocolPacket::ProtocolHeaderValidator* validator_;
+ bool last_portion_of_data_was_malformed_;
DISALLOW_COPY_AND_ASSIGN(IncomingDataHandler);
};
} // namespace protocol_handler
diff --git a/src/components/protocol_handler/include/protocol_handler/multiframe_builder.h b/src/components/protocol_handler/include/protocol_handler/multiframe_builder.h
new file mode 100644
index 0000000000..bac37b508c
--- /dev/null
+++ b/src/components/protocol_handler/include/protocol_handler/multiframe_builder.h
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_MULTIFRAME_BUILDER_H_
+#define SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_MULTIFRAME_BUILDER_H_
+
+#include <map>
+#include <ostream> // std::basic_ostream
+#include <iterator> // std::ostream_iterator
+#include <algorithm> // std::copy
+
+#include "utils/date_time.h"
+#include "protocol_handler/protocol_packet.h"
+
+/**
+ *\namespace protocol_handlerHandler
+ *\brief Namespace for SmartDeviceLink ProtocolHandler related functionality.
+ */
+namespace protocol_handler {
+/**
+ * \brief Session identifier - contains connection identifier and
+ * session_id from protocol (can be used as hash)
+ */
+// TODO(EZamakhov): move SessionID to protocol_handler/protocol_packet.h
+typedef uint8_t SessionID;
+/**
+ * \brief Message identifier - unique to the session messages
+ */
+// TODO(EZamakhov): move MessageID to protocol_handler/session_observer.h
+typedef uint32_t MessageID;
+
+struct ProtocolFrameData {
+ ProtocolFramePtr frame;
+ TimevalStruct append_time;
+};
+/**
+ *\brief Map of frames with last frame data for messages received in multiple
+ *frames.
+ */
+typedef std::map<MessageID, ProtocolFrameData> MessageIDToFrameMap;
+/**
+ *\brief Map of frames with last frame data for messages received in multiple
+ *frames.
+ */
+typedef std::map<SessionID, MessageIDToFrameMap> SessionToFrameMap;
+/**
+ *\brief Map of frames with last frame data for messages received in multiple
+ *frames.
+ */
+typedef std::map<ConnectionID, SessionToFrameMap> MultiFrameMap;
+
+/**
+ * \class MultiFrameBuilder
+ * \brief Class for assembling consecutive frames according to
+ * messageID to complete multiframes.
+ */
+class MultiFrameBuilder {
+ public:
+ /**
+ * @brief Constructor
+ */
+ MultiFrameBuilder();
+
+ /**
+ *\brief Set timeout of waiting CONSECUTIVE frames
+ */
+ void set_waiting_timeout(const uint32_t consecutive_frame_wait_msecs);
+
+ /**
+ * @brief Add connection for pending data
+ * @return true on success
+ */
+ bool AddConnection(const ConnectionID connection_id);
+
+ /**
+ * @brief Clear all data related to connection_id
+ * @return true on success
+ */
+ bool RemoveConnection(const ConnectionID connection_id);
+
+ /**
+ *\brief Pop assembled and expired frames
+ */
+ ProtocolFramePtrList PopMultiframes();
+
+ /**
+ *\brief Handle Single or Consecutive frame
+ * @return RESULT_OK on success, or RESULT_FAIL in case of any error
+ */
+ RESULT_CODE AddFrame(const ProtocolFramePtr packet);
+
+ private:
+ RESULT_CODE HandleFirstFrame(const ProtocolFramePtr packet);
+ RESULT_CODE HandleConsecutiveFrame(const ProtocolFramePtr packet);
+
+ // Map of frames with last frame data for messages received in multiple
+ // frames.
+ MultiFrameMap multiframes_map_;
+ int64_t consecutive_frame_wait_msecs_;
+};
+
+template <typename _CharT>
+std::basic_ostream<_CharT>& operator<<(
+ std::basic_ostream<_CharT>& stream,
+ const protocol_handler::MultiFrameMap& map) {
+ if (map.empty()) {
+ stream << "{empty}";
+ return stream;
+ }
+ for (MultiFrameMap::const_iterator connection_it = map.begin();
+ connection_it != map.end();
+ ++connection_it) {
+ const SessionToFrameMap& session_map = connection_it->second;
+
+ for (SessionToFrameMap::const_iterator session_it = session_map.begin();
+ session_it != session_map.end();
+ ++session_it) {
+ const MessageIDToFrameMap& messageId_map = session_it->second;
+
+ for (MessageIDToFrameMap::const_iterator messageId_it =
+ messageId_map.begin();
+ messageId_it != messageId_map.end();
+ ++messageId_it) {
+ const ProtocolFrameData& frame_data = messageId_it->second;
+
+ stream << "ConnectionID: " << connection_it->first
+ << ", SessionID: " << static_cast<uint32_t>(session_it->first)
+ << ", MessageID: " << static_cast<uint32_t>(messageId_it->first)
+ << " msec, frame: " << frame_data.frame << std::endl;
+ }
+ }
+ }
+ return stream;
+}
+
+} // namespace protocol_handler
+#endif // SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_MULTIFRAME_BUILDER_H_
diff --git a/src/components/protocol_handler/include/protocol_handler/protocol_handler_impl.h b/src/components/protocol_handler/include/protocol_handler/protocol_handler_impl.h
index bff972ede4..cd50f98bdb 100644
--- a/src/components/protocol_handler/include/protocol_handler/protocol_handler_impl.h
+++ b/src/components/protocol_handler/include/protocol_handler/protocol_handler_impl.h
@@ -36,7 +36,9 @@
#include <map>
#include <memory>
#include <set>
-#include <list>
+#include <stdint.h>
+#include <utility> // std::make_pair
+#include <vector>
#include "utils/prioritized_queue.h"
#include "utils/message_queue.h"
#include "utils/threads/message_loop_thread.h"
@@ -45,20 +47,29 @@
#include "protocol_handler/protocol_handler.h"
#include "protocol_handler/protocol_packet.h"
+#include "protocol_handler/protocol_handler_settings.h"
#include "protocol_handler/session_observer.h"
#include "protocol_handler/protocol_observer.h"
#include "protocol_handler/incoming_data_handler.h"
+#include "protocol_handler/multiframe_builder.h"
#include "transport_manager/common.h"
#include "transport_manager/transport_manager.h"
#include "transport_manager/transport_manager_listener_empty.h"
-#ifdef TIME_TESTER
-#include "protocol_handler/time_metric_observer.h"
-#endif // TIME_TESTER
+#include "connection_handler/connection_handler.h"
+
+#ifdef TELEMETRY_MONITOR
+#include "protocol_handler/telemetry_observer.h"
+#include "telemetry_monitor/telemetry_observable.h"
+#endif // TELEMETRY_MONITOR
#ifdef ENABLE_SECURITY
#include "security_manager/security_manager.h"
#endif // ENABLE_SECURITY
+namespace connection_handler {
+class ConnectionHandlerImpl;
+} // namespace connection_handler
+
/**
*\namespace protocol_handlerHandler
*\brief Namespace for SmartDeviceLink ProtocolHandler related functionality.
@@ -84,34 +95,37 @@ namespace impl {
* TODO(ik): replace these with globally defined message types
* when we have them.
*/
-struct RawFordMessageFromMobile: public ProtocolFramePtr {
+struct RawFordMessageFromMobile : public ProtocolFramePtr {
+ RawFordMessageFromMobile() {}
explicit RawFordMessageFromMobile(const ProtocolFramePtr message)
- : ProtocolFramePtr(message) {}
+ : ProtocolFramePtr(message) {}
// PrioritizedQueue requires this method to decide which priority to assign
size_t PriorityOrder() const {
return MessagePriority::FromServiceType(
- ServiceTypeFromByte(get()->service_type())).OrderingValue();
+ ServiceTypeFromByte(get()->service_type())).OrderingValue();
}
};
-struct RawFordMessageToMobile: public ProtocolFramePtr {
+struct RawFordMessageToMobile : public ProtocolFramePtr {
+ RawFordMessageToMobile() : is_final(false) {}
explicit RawFordMessageToMobile(const ProtocolFramePtr message,
bool final_message)
- : ProtocolFramePtr(message), is_final(final_message) {}
+ : ProtocolFramePtr(message), is_final(final_message) {}
// PrioritizedQueue requires this method to decide which priority to assign
size_t PriorityOrder() const {
return MessagePriority::FromServiceType(
- ServiceTypeFromByte(get()->service_type())).OrderingValue();
+ ServiceTypeFromByte(get()->service_type())).OrderingValue();
}
- // Signals whether connection to mobile must be closed after processing this message
+ // Signals whether connection to mobile must be closed after processing this
+ // message
bool is_final;
};
// Short type names for prioritized message queues
-typedef threads::MessageLoopThread <
- utils::PrioritizedQueue<RawFordMessageFromMobile> > FromMobileQueue;
-typedef threads::MessageLoopThread <
- utils::PrioritizedQueue<RawFordMessageToMobile> > ToMobileQueue;
+typedef threads::MessageLoopThread<
+ utils::PrioritizedQueue<RawFordMessageFromMobile> > FromMobileQueue;
+typedef threads::MessageLoopThread<
+ utils::PrioritizedQueue<RawFordMessageToMobile> > ToMobileQueue;
} // namespace impl
/**
@@ -123,30 +137,27 @@ typedef threads::MessageLoopThread <
* about activities around sessions.
*/
class ProtocolHandlerImpl
- : public ProtocolHandler,
- public TransportManagerListenerEmpty,
- public impl::FromMobileQueue::Handler,
- public impl::ToMobileQueue::Handler {
+ : public ProtocolHandler,
+ public TransportManagerListenerEmpty,
+ public impl::FromMobileQueue::Handler,
+ public impl::ToMobileQueue::Handler
+#ifdef TELEMETRY_MONITOR
+ ,
+ public telemetry_monitor::TelemetryObservable<PHTelemetryObserver>
+#endif // TELEMETRY_MONITOR
+ {
public:
/**
- * \brief Constructor
- * \param transportManager Pointer to Transport layer handler for
- * \param message_frequency_time used as time for flood filtering
- * \param message_frequency_count used as maximum value of messages
- * per message_frequency_time period
- * \param malformed_message_filtering used for malformed filtering enabling
- * \param malformed_message_frequency_time used as time for malformed flood filtering
- * \param malformed_message_frequency_count used as maximum value of malformed
- * messages per message_frequency_time period
- * message exchange.
- */
- explicit ProtocolHandlerImpl(
- transport_manager::TransportManager *transport_manager_param,
- size_t message_frequency_time, size_t message_frequency_count,
- bool malformed_message_filtering,
- size_t malformed_message_frequency_time,
- size_t malformed_message_frequency_count);
-
+ * @brief Constructor
+ * @param settings reference to ProtocolHandlerSettingsImpl object
+ * @param session_observer reference to SessionObserver to access session
+ * information and controll session life cycle
+ * @param transportManager Pointer to Transport layer handler for
+ */
+ ProtocolHandlerImpl(const ProtocolHandlerSettings& settings,
+ protocol_handler::SessionObserver& session_observer,
+ connection_handler::ConnectionHandler& connection_handler,
+ transport_manager::TransportManager& transport_manager);
/**
* \brief Destructor
*/
@@ -157,28 +168,18 @@ class ProtocolHandlerImpl
* \param observer Pointer to object of the class implementing
* IProtocolObserver
*/
- void AddProtocolObserver(ProtocolObserver *observer);
-
- /**
- * \brief Removes pointer to higher layer handler for message exchange
- * \param observer Pointer to object of the class implementing
- * IProtocolObserver.
- */
- void RemoveProtocolObserver(ProtocolObserver *observer);
+ void AddProtocolObserver(ProtocolObserver* observer);
- /**
- * \brief Sets pointer for Connection Handler layer for managing sessions
- * \param observer Pointer to object of the class implementing
- * ISessionObserver
- */
- void set_session_observer(SessionObserver *observer);
+ void RemoveProtocolObserver(ProtocolObserver* observer) OVERRIDE;
#ifdef ENABLE_SECURITY
/**
- * \brief Sets pointer for SecurityManager layer for managing protection routine
+ * \brief Sets pointer for SecurityManager layer for managing protection
+ * routine
* \param security_manager Pointer to SecurityManager object
*/
- void set_security_manager(security_manager::SecurityManager *security_manager);
+ void set_security_manager(
+ security_manager::SecurityManager* security_manager);
#endif // ENABLE_SECURITY
/**
@@ -195,20 +196,21 @@ class ProtocolHandlerImpl
/**
* \brief Sends number of processed frames in case of binary nav streaming
- * \param connection_key Unique key used by other components as session identifier
+ * \param connection_key Unique key used by other components as session
+ * identifier
* \param number_of_frames Number of frames processed by
* streaming server and displayed to user.
*/
void SendFramesNumber(uint32_t connection_key, int32_t number_of_frames);
-#ifdef TIME_TESTER
+#ifdef TELEMETRY_MONITOR
/**
* @brief Setup observer for time metric.
*
* @param observer - pointer to observer
*/
- void SetTimeMetricObserver(PHMetricObserver *observer);
-#endif // TIME_TESTER
+ void SetTelemetryObserver(PHTelemetryObserver* observer);
+#endif // TELEMETRY_MONITOR
/*
* Prepare and send heartbeat message to mobile
@@ -248,6 +250,10 @@ class ProtocolHandlerImpl
uint8_t service_type,
bool protection);
+ const ProtocolHandlerSettings& get_settings() const OVERRIDE {
+ return settings_;
+ }
+
/**
* \brief Sends fail of starting session to mobile application
* \param connection_id Identifier of connection within which session
@@ -289,8 +295,11 @@ class ProtocolHandlerImpl
uint8_t protocol_version,
uint8_t service_type);
+ SessionObserver& get_session_observer() OVERRIDE;
+
private:
- void SendEndServicePrivate(int32_t connection_id, uint8_t session_id,
+ void SendEndServicePrivate(int32_t connection_id,
+ uint8_t session_id,
uint8_t service_type);
/*
@@ -305,22 +314,21 @@ class ProtocolHandlerImpl
*
* @param message Received message
**/
- virtual void OnTMMessageReceived(
- const RawMessagePtr message);
+ void OnTMMessageReceived(const RawMessagePtr message) OVERRIDE;
/**
* @brief Notifies about error on receiving message from TM.
*
* @param error Occurred error
**/
- virtual void OnTMMessageReceiveFailed(
- const transport_manager::DataReceiveError &error);
+ void OnTMMessageReceiveFailed(
+ const transport_manager::DataReceiveError& error) OVERRIDE;
/**
* @brief Notifies about successfully sending message.
*
**/
- virtual void OnTMMessageSend(const RawMessagePtr message);
+ void OnTMMessageSend(const RawMessagePtr message) OVERRIDE;
/**
* @brief Notifies about error occurred during
@@ -329,16 +337,15 @@ class ProtocolHandlerImpl
* @param error Describes occurred error.
* @param message Message during sending which error occurred.
**/
- virtual void OnTMMessageSendFailed(
- const transport_manager::DataSendError &error,
- const RawMessagePtr message);
+ void OnTMMessageSendFailed(const transport_manager::DataSendError& error,
+ const RawMessagePtr message) OVERRIDE;
- virtual void OnConnectionEstablished(
- const transport_manager::DeviceInfo &device_info,
- const transport_manager::ConnectionUID &connection_id);
+ void OnConnectionEstablished(
+ const transport_manager::DeviceInfo& device_info,
+ const transport_manager::ConnectionUID connection_id) OVERRIDE;
- virtual void OnConnectionClosed(
- const transport_manager::ConnectionUID &connection_id);
+ void OnConnectionClosed(
+ const transport_manager::ConnectionUID connection_id) OVERRIDE;
/**
* @brief Notifies subscribers about message
@@ -364,7 +371,7 @@ class ProtocolHandlerImpl
const uint32_t protocol_version,
const uint8_t service_type,
const size_t data_size,
- const uint8_t *data,
+ const uint8_t* data,
const bool is_final_message);
/**
@@ -385,7 +392,7 @@ class ProtocolHandlerImpl
const uint8_t protocol_version,
const uint8_t service_type,
const size_t data_size,
- const uint8_t *data,
+ const uint8_t* data,
const size_t max_frame_size,
const bool is_final_message);
@@ -403,9 +410,7 @@ class ProtocolHandlerImpl
* \param packet Received message with protocol header.
* \return \saRESULT_CODE Status of operation
*/
- RESULT_CODE HandleMessage(
- ConnectionID connection_id,
- const ProtocolFramePtr packet);
+ RESULT_CODE HandleMessage(const ProtocolFramePtr packet);
/**
* \brief Handles message received in single frame.
@@ -414,9 +419,7 @@ class ProtocolHandlerImpl
* \param packet Frame of message with protocol header.
* \return \saRESULT_CODE Status of operation
*/
- RESULT_CODE HandleSingleFrameMessage(
- ConnectionID connection_id,
- const ProtocolFramePtr packet);
+ RESULT_CODE HandleSingleFrameMessage(const ProtocolFramePtr packet);
/**
* \brief Handles message received in multiple frames. Collects all frames
* of message.
@@ -425,9 +428,7 @@ class ProtocolHandlerImpl
* \param packet Current frame of message with protocol header.
* \return \saRESULT_CODE Status of operation
*/
- RESULT_CODE HandleMultiFrameMessage(
- ConnectionID connection_id,
- const ProtocolFramePtr packet);
+ RESULT_CODE HandleMultiFrameMessage(const ProtocolFramePtr packet);
/**
* \brief Handles message received in single frame.
@@ -436,21 +437,17 @@ class ProtocolHandlerImpl
* \param packet Received message with protocol header.
* \return \saRESULT_CODE Status of operation
*/
- RESULT_CODE HandleControlMessage(
- ConnectionID connection_id,
- const ProtocolFramePtr packet);
+ RESULT_CODE HandleControlMessage(const ProtocolFramePtr packet);
+
+ RESULT_CODE HandleControlMessageEndSession(const ProtocolPacket& packet);
- RESULT_CODE HandleControlMessageEndSession(
- ConnectionID connection_id,
- const ProtocolPacket &packet);
+ RESULT_CODE HandleControlMessageEndServiceACK(const ProtocolPacket& packet);
- RESULT_CODE HandleControlMessageStartSession(
- ConnectionID connection_id,
- const ProtocolPacket &packet);
+ RESULT_CODE HandleControlMessageStartSession(const ProtocolPacket& packet);
- RESULT_CODE HandleControlMessageHeartBeat(
- ConnectionID connection_id,
- const ProtocolPacket &packet);
+ RESULT_CODE HandleControlMessageHeartBeat(const ProtocolPacket& packet);
+
+ void PopValideAndExpirateMultiframes();
// threads::MessageLoopThread<*>::Handler implementations
// CALLED ON raw_ford_messages_from_mobile_ thread!
@@ -467,12 +464,17 @@ class ProtocolHandlerImpl
RESULT_CODE DecryptFrame(ProtocolFramePtr packet);
#endif // ENABLE_SECURITY
- bool TrackMessage(const uint32_t &connection_key);
+ bool TrackMessage(const uint32_t& connection_key);
- bool TrackMalformedMessage(const uint32_t &connection_key,
+ bool TrackMalformedMessage(const uint32_t& connection_key,
const size_t count);
+ /**
+ * @brief Function returns supported SDL Protocol Version,
+ */
+ uint8_t SupportedSDLProtocolVersion() const;
+
+ const ProtocolHandlerSettings& settings_;
- private:
/**
*\brief Pointer on instance of class implementing IProtocolObserver
*\brief (JSON Handler)
@@ -481,19 +483,27 @@ class ProtocolHandlerImpl
/**
*\brief Pointer on instance of class implementing ISessionObserver
- *\brief (Connection Handler)
+ *\brief (Connection Handler).
+ * According to usage it can't be null
+ */
+ SessionObserver& session_observer_;
+
+ /**
+ *\brief Pointer on instance of Transport layer handler for message exchange.
+ *\brief Instance of class implementing Connection Handler t keep connection
+ *alive
*/
- SessionObserver *session_observer_;
+ connection_handler::ConnectionHandler& connection_handler_;
/**
*\brief Pointer on instance of Transport layer handler for message exchange.
*/
- transport_manager::TransportManager *transport_manager_;
+ transport_manager::TransportManager& transport_manager_;
/**
- *\brief Map of frames for messages received in multiple frames.
+ *\brief Assembling support class.
*/
- std::map<int32_t, ProtocolFramePtr> incomplete_multi_frame_messages_;
+ MultiFrameBuilder multiframe_builder_;
/**
* \brief Map of messages (frames) received over mobile nave session
@@ -526,22 +536,17 @@ class ProtocolHandlerImpl
/**
*\brief Connections that must be closed after their last messages were sent
*/
- std::list<uint32_t> ready_to_close_connections_;
+ std::vector<uint32_t> ready_to_close_connections_;
ProtocolPacket::ProtocolHeaderValidator protocol_header_validator_;
IncomingDataHandler incoming_data_handler_;
// Use uint32_t as application identifier
utils::MessageMeter<uint32_t> message_meter_;
- size_t message_max_frequency_;
- size_t message_frequency_time_;
- bool malformed_message_filtering_;
// Use uint32_t as connection identifier
utils::MessageMeter<uint32_t> malformed_message_meter_;
- size_t malformed_message_max_frequency_;
- size_t malformed_message_frequency_time_;
#ifdef ENABLE_SECURITY
- security_manager::SecurityManager *security_manager_;
+ security_manager::SecurityManager* security_manager_;
#endif // ENABLE_SECURITY
// Thread that pumps non-parsed messages coming from mobile side.
@@ -551,9 +556,9 @@ class ProtocolHandlerImpl
sync_primitives::Lock protocol_observers_lock_;
-#ifdef TIME_TESTER
- PHMetricObserver *metric_observer_;
-#endif // TIME_TESTER
+#ifdef TELEMETRY_MONITOR
+ PHTelemetryObserver* metric_observer_;
+#endif // TELEMETRY_MONITOR
};
} // namespace protocol_handler
#endif // SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_PROTOCOL_HANDLER_IMPL_H_
diff --git a/src/components/protocol_handler/include/protocol_handler/protocol_packet.h b/src/components/protocol_handler/include/protocol_handler/protocol_packet.h
index 0b4b253a84..f8696c46a0 100644
--- a/src/components/protocol_handler/include/protocol_handler/protocol_packet.h
+++ b/src/components/protocol_handler/include/protocol_handler/protocol_packet.h
@@ -33,6 +33,7 @@
#ifndef SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_PROTOCOL_PACKET_H_
#define SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_PROTOCOL_PACKET_H_
+#include <list>
#include "utils/macro.h"
#include "protocol/common.h"
#include "transport_manager/common.h"
@@ -58,7 +59,7 @@ class ProtocolPacket {
struct ProtocolData {
ProtocolData();
~ProtocolData();
- uint8_t *data;
+ uint8_t* data;
uint32_t totalDataBytes;
};
@@ -69,11 +70,14 @@ class ProtocolPacket {
class ProtocolHeader {
public:
ProtocolHeader();
- ProtocolHeader(uint8_t version, bool protection,
+ ProtocolHeader(uint8_t version,
+ bool protection,
uint8_t frameType,
uint8_t serviceType,
- uint8_t frameData, uint8_t sessionID,
- uint32_t dataSize, uint32_t messageID);
+ uint8_t frameData,
+ uint8_t sessionID,
+ uint32_t dataSize,
+ uint32_t messageID);
uint8_t version;
bool protection_flag;
uint8_t frameType;
@@ -82,7 +86,7 @@ class ProtocolPacket {
uint8_t sessionId;
uint32_t dataSize;
uint32_t messageId;
- void deserialize(const uint8_t *message, const size_t messageSize);
+ void deserialize(const uint8_t* message, const size_t messageSize);
};
/**
* \class ProtocolHeaderValidator
@@ -100,6 +104,7 @@ class ProtocolPacket {
* \brief Check ProtocolHeader according to protocol requiements
*/
RESULT_CODE validate(const ProtocolHeader& header) const;
+
private:
size_t max_payload_size_;
};
@@ -131,10 +136,15 @@ class ProtocolPacket {
* \param data Message string if provided
*/
ProtocolPacket(ConnectionID connection_id,
- uint8_t version, bool protection, uint8_t frameType,
- uint8_t serviceType, uint8_t frameData,
- uint8_t sessionId, uint32_t dataSize,
- uint32_t messageID, const uint8_t *data = 0);
+ uint8_t version,
+ bool protection,
+ uint8_t frameType,
+ uint8_t serviceType,
+ uint8_t frameData,
+ uint8_t sessionId,
+ uint32_t dataSize,
+ uint32_t messageID,
+ const uint8_t* data = 0);
/*Serialization*/
/**
@@ -149,7 +159,7 @@ class ProtocolPacket {
* \param chunkDataSize Size of current message string
* \return \saRESULT_CODE Status of serialization
*/
- RESULT_CODE appendData(uint8_t *chunkData, uint32_t chunkDataSize);
+ RESULT_CODE appendData(uint8_t* chunkData, uint32_t chunkDataSize);
/**
* \brief Getter of message size including protocol header
@@ -170,7 +180,7 @@ class ProtocolPacket {
* \param messageSize Incoming message size
* \return \saRESULT_CODE Status of serialization
*/
- RESULT_CODE deserializePacket(const uint8_t *message,
+ RESULT_CODE deserializePacket(const uint8_t* message,
const size_t messageSize);
/**
@@ -199,10 +209,13 @@ class ProtocolPacket {
uint8_t service_type() const;
/**
- *\brief Getter of frame data (start/end session, number of frame etc)
+ *\brief Getter and setter of frame data (start/end session, number of frame
+ *etc)
*/
uint8_t frame_data() const;
+ void set_frame_data(const uint8_t frame_data);
+
/**
*\brief Getter of session number
*/
@@ -221,7 +234,7 @@ class ProtocolPacket {
/**
*\brief Getter of message string
*/
- uint8_t *data() const;
+ uint8_t* data() const;
/**
*\brief Setter for size of multiframe message
@@ -231,8 +244,7 @@ class ProtocolPacket {
/**
*\brief Setter for new data
*/
- void set_data(const uint8_t *const new_data,
- const size_t new_data_size);
+ void set_data(const uint8_t* const new_data, const size_t new_data_size);
/**
*\brief Getter for size of multiframe message
@@ -243,13 +255,18 @@ class ProtocolPacket {
/**
* \brief Getter for Connection Identifier
*/
- uint8_t connection_id() const;
+ ConnectionID connection_id() const;
/**
* \brief Getter for data payload size
*/
uint32_t payload_size() const;
+ /**
+ * \brief Getter for full header information
+ */
+ const ProtocolHeader& packet_header() const;
+
private:
/**
*\brief Protocol header
@@ -275,8 +292,43 @@ class ProtocolPacket {
DISALLOW_COPY_AND_ASSIGN(ProtocolPacket);
};
} // namespace protocol_handler
-/**
- * @brief Type definition for variable that hold shared pointer to protocolol packet
- */
+ /**
+ * @brief Type definition for variable that hold shared pointer to protocolol
+ * packet
+ */
typedef utils::SharedPtr<protocol_handler::ProtocolPacket> ProtocolFramePtr;
+typedef std::list<ProtocolFramePtr> ProtocolFramePtrList;
+
+template <typename _CharT>
+std::basic_ostream<_CharT>& operator<<(
+ std::basic_ostream<_CharT>& stream,
+ const protocol_handler::ProtocolPacket::ProtocolHeader& header) {
+ stream << "Version: " << static_cast<uint32_t>(header.version)
+ << ", Protection: " << (header.protection_flag ? "ON" : "OFF")
+ << ", FrameType: " << static_cast<uint32_t>(header.frameType)
+ << ", ServiceType: " << static_cast<uint32_t>(header.serviceType)
+ << ", FrameData: " << static_cast<uint32_t>(header.frameData)
+ << ", SessionId: " << static_cast<uint32_t>(header.sessionId)
+ << ", DataSize: " << static_cast<uint32_t>(header.dataSize)
+ << ", MessageId: " << static_cast<uint32_t>(header.messageId);
+ return stream;
+}
+template <typename _CharT>
+std::basic_ostream<_CharT>& operator<<(
+ std::basic_ostream<_CharT>& stream,
+ const protocol_handler::ProtocolPacket& packet) {
+ stream << packet.packet_header()
+ << ", ConnectionID: " << static_cast<uint32_t>(packet.connection_id())
+ << ", TotalDataBytes: " << (packet.total_data_bytes())
+ << ", Data: " << static_cast<void*>(packet.data());
+ return stream;
+}
+template <typename _CharT>
+std::basic_ostream<_CharT>& operator<<(std::basic_ostream<_CharT>& stream,
+ const ProtocolFramePtr packet_ptr) {
+ if (packet_ptr) {
+ return stream << *packet_ptr;
+ }
+ return stream << "empty smart pointer";
+}
#endif // SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_PROTOCOL_PACKET_H_
diff --git a/src/components/protocol_handler/include/protocol_handler/protocol_payload.h b/src/components/protocol_handler/include/protocol_handler/protocol_payload.h
index 861d29d4d4..ed61d3588d 100644
--- a/src/components/protocol_handler/include/protocol_handler/protocol_payload.h
+++ b/src/components/protocol_handler/include/protocol_handler/protocol_payload.h
@@ -48,9 +48,11 @@ namespace protocol_handler {
// Applink Protocolv5 4.1.2 Protocol Payload Binary header
struct ProtocolPayloadHeaderV2 {
ProtocolPayloadHeaderV2()
- : rpc_type(kRpcTypeReserved),
- rpc_function_id(0), correlation_id(0), json_size(0) {}
- RpcType rpc_type;
+ : rpc_type(kRpcTypeReserved)
+ , rpc_function_id(0)
+ , correlation_id(0)
+ , json_size(0) {}
+ RpcType rpc_type;
uint32_t rpc_function_id;
uint32_t correlation_id;
uint32_t json_size;
@@ -66,14 +68,18 @@ struct ProtocolPayloadV2 {
// Procedures that extract and validate defined protocol structures from
// a bit stream.
// If error during parsing is detected, bit stream is marked as invalid
-void Extract(utils::BitStream *bs, ProtocolPayloadHeaderV2 *headerv2);
-void Extract(utils::BitStream *bs, ProtocolPayloadV2 *payload, size_t payload_size);
+void Extract(utils::BitStream* bs, ProtocolPayloadHeaderV2* headerv2);
+void Extract(utils::BitStream* bs,
+ ProtocolPayloadV2* payload,
+ size_t payload_size);
-std::ostream &operator<<(std::ostream &os, const ProtocolPayloadHeaderV2 &payload_header);
-std::ostream &operator<<(std::ostream &os, const ProtocolPayloadV2 &payload);
+std::ostream& operator<<(std::ostream& os,
+ const ProtocolPayloadHeaderV2& payload_header);
+std::ostream& operator<<(std::ostream& os, const ProtocolPayloadV2& payload);
-//Add for tests
+// Add for tests
size_t ProtocolPayloadV2SizeBits();
-} // namespace protocol_handler
+} // namespace protocol_handler
-#endif /* SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_PROTOCOL_PAYLOAD_H_ */
+#endif /* SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_PROTOCOL_PAYLOAD_H_ \
+ */
diff --git a/src/components/protocol_handler/include/protocol_handler/telemetry_observer.h b/src/components/protocol_handler/include/protocol_handler/telemetry_observer.h
new file mode 100644
index 0000000000..1f4c1ebcb5
--- /dev/null
+++ b/src/components/protocol_handler/include/protocol_handler/telemetry_observer.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_TIME_METRIC_OBSERVER_H_
+#define SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_TIME_METRIC_OBSERVER_H_
+#include "protocol/common.h"
+
+#include <stdint.h>
+#include "utils/date_time.h"
+
+namespace protocol_handler {
+
+class PHTelemetryObserver {
+ public:
+ struct MessageMetric {
+ RawMessagePtr raw_msg;
+ uint32_t message_id;
+ uint8_t connection_key;
+ TimevalStruct begin;
+ TimevalStruct end;
+ };
+ virtual void StartMessageProcess(uint32_t message_id,
+ const TimevalStruct& start_time) = 0;
+ virtual void EndMessageProcess(utils::SharedPtr<MessageMetric> m) = 0;
+ virtual ~PHTelemetryObserver() {}
+};
+} // protocol_handler
+#endif // SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_TIME_METRIC_OBSERVER_H_
diff --git a/src/components/protocol_handler/include/protocol_handler/time_metric_observer.h b/src/components/protocol_handler/include/protocol_handler/time_metric_observer.h
deleted file mode 100644
index 1d3d83ea48..0000000000
--- a/src/components/protocol_handler/include/protocol_handler/time_metric_observer.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_TIME_METRIC_OBSERVER_H_
-#define SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_TIME_METRIC_OBSERVER_H_
-#include "protocol/common.h"
-
-#include <stdint.h>
-#include "utils/date_time.h"
-
-namespace protocol_handler {
-
-class PHMetricObserver {
- public:
- struct MessageMetric {
- RawMessagePtr raw_msg;
- uint32_t message_id;
- uint8_t connection_key;
- TimevalStruct begin;
- TimevalStruct end;
- };
- virtual void StartMessageProcess(uint32_t message_id, const TimevalStruct &start_time) = 0;
- virtual void EndMessageProcess(utils::SharedPtr<MessageMetric> m) = 0;
- virtual ~PHMetricObserver(){}
-};
-} // protocol_handler
-#endif // SRC_COMPONENTS_PROTOCOL_HANDLER_INCLUDE_PROTOCOL_HANDLER_TIME_METRIC_OBSERVER_H_
diff --git a/src/components/protocol_handler/src/incoming_data_handler.cc b/src/components/protocol_handler/src/incoming_data_handler.cc
index 45dc4babff..e1d08a6ada 100644
--- a/src/components/protocol_handler/src/incoming_data_handler.cc
+++ b/src/components/protocol_handler/src/incoming_data_handler.cc
@@ -38,61 +38,66 @@ namespace protocol_handler {
CREATE_LOGGERPTR_GLOBAL(logger_, "ProtocolHandler")
IncomingDataHandler::IncomingDataHandler()
- : header_(), validator_(NULL) {}
+ : header_(), validator_(NULL), last_portion_of_data_was_malformed_(false) {}
void IncomingDataHandler::set_validator(
- const ProtocolPacket::ProtocolHeaderValidator *const validator) {
+ const ProtocolPacket::ProtocolHeaderValidator* const validator) {
validator_ = validator;
}
-static const size_t MIN_HEADER_SIZE = std::min(PROTOCOL_HEADER_V1_SIZE,
- PROTOCOL_HEADER_V2_SIZE);
+static const size_t MIN_HEADER_SIZE =
+ std::min(PROTOCOL_HEADER_V1_SIZE, PROTOCOL_HEADER_V2_SIZE);
-std::list<ProtocolFramePtr> IncomingDataHandler::ProcessData(
- const RawMessage &tm_message,
- RESULT_CODE *result,
- size_t *malformed_occurrence) {
+ProtocolFramePtrList IncomingDataHandler::ProcessData(
+ const RawMessage& tm_message,
+ RESULT_CODE* result,
+ size_t* malformed_occurrence) {
LOG4CXX_AUTO_TRACE(logger_);
DCHECK(result);
DCHECK(malformed_occurrence);
const transport_manager::ConnectionUID connection_id =
- tm_message.connection_key();
- const uint8_t *data = tm_message.data();
+ tm_message.connection_key();
+ const uint8_t* data = tm_message.data();
const size_t tm_message_size = tm_message.data_size();
if (tm_message_size == 0 || data == NULL) {
LOG4CXX_WARN(logger_, "Wrong raw message " << tm_message_size << " bytes");
*result = RESULT_FAIL;
- return std::list<ProtocolFramePtr>();
+ return ProtocolFramePtrList();
}
- LOG4CXX_DEBUG(logger_, "Processing incoming data of size "
- << tm_message_size << " for connection " << connection_id);
+ LOG4CXX_INFO(logger_,
+ "Processing incoming data of size "
+ << tm_message_size << " for connection " << connection_id);
ConnectionsDataMap::iterator it = connections_data_.find(connection_id);
if (connections_data_.end() == it) {
LOG4CXX_WARN(logger_, "ProcessData requested for unknown connection");
*result = RESULT_FAIL;
- return std::list<ProtocolFramePtr>();
+ return ProtocolFramePtrList();
}
- std::vector<uint8_t> &connection_data = it->second;
+ std::vector<uint8_t>& connection_data = it->second;
connection_data.insert(connection_data.end(), data, data + tm_message_size);
- LOG4CXX_DEBUG(logger_, "Total data size for connection "
- << connection_id << " is " << connection_data.size());
- std::list<ProtocolFramePtr> out_frames;
+ LOG4CXX_DEBUG(logger_,
+ "Total data size for connection " << connection_id << " is "
+ << connection_data.size());
+ ProtocolFramePtrList out_frames;
*malformed_occurrence = 0;
- *result = CreateFrame(connection_data, out_frames, *malformed_occurrence, connection_id);
- LOG4CXX_DEBUG(logger_, "New data size for connection " << connection_id
- << " is " << connection_data.size());
+ *result = CreateFrame(
+ connection_data, out_frames, *malformed_occurrence, connection_id);
+ LOG4CXX_DEBUG(logger_,
+ "New data size for connection " << connection_id << " is "
+ << connection_data.size());
if (!out_frames.empty()) {
- LOG4CXX_DEBUG(logger_, "Created and passed " << out_frames.size() <<
- " packets");
+ LOG4CXX_INFO(logger_,
+ "Created and passed " << out_frames.size() << " packets");
} else {
if (RESULT_DEFERRED == *result) {
- LOG4CXX_DEBUG(logger_,
- "No packets have been created. Waiting next portion of data.");
+ LOG4CXX_DEBUG(
+ logger_,
+ "No packets have been created. Waiting next portion of data.");
} else {
LOG4CXX_WARN(logger_, "No packets have been created.");
}
}
- if (*malformed_occurrence > 0u) {
+ if (*malformed_occurrence > 0u || last_portion_of_data_was_malformed_) {
*result = RESULT_MALFORMED_OCCURS;
} else {
*result = RESULT_OK;
@@ -101,20 +106,20 @@ std::list<ProtocolFramePtr> IncomingDataHandler::ProcessData(
}
void IncomingDataHandler::AddConnection(
- const transport_manager::ConnectionUID connection_id) {
+ const transport_manager::ConnectionUID connection_id) {
LOG4CXX_AUTO_TRACE(logger_);
// Add empty list of session to new connection
connections_data_[connection_id] = ConnectionsDataMap::mapped_type();
}
void IncomingDataHandler::RemoveConnection(
- const transport_manager::ConnectionUID connection_id) {
+ const transport_manager::ConnectionUID connection_id) {
LOG4CXX_AUTO_TRACE(logger_);
connections_data_.erase(connection_id);
}
uint32_t IncomingDataHandler::GetPacketSize(
- const ProtocolPacket::ProtocolHeader &header) {
+ const ProtocolPacket::ProtocolHeader& header) {
switch (header.version) {
case PROTOCOL_VERSION_1:
return header.dataSize + PROTOCOL_HEADER_V1_SIZE;
@@ -123,36 +128,40 @@ uint32_t IncomingDataHandler::GetPacketSize(
case PROTOCOL_VERSION_4:
return header.dataSize + PROTOCOL_HEADER_V2_SIZE;
default:
- LOG4CXX_WARN(logger_, "Unknown version");
+ LOG4CXX_WARN(logger_,
+ "Unknown version: " << static_cast<int>(header.version));
break;
}
return 0u;
}
RESULT_CODE IncomingDataHandler::CreateFrame(
- std::vector<uint8_t> &incoming_data,
- std::list<ProtocolFramePtr> &out_frames,
- size_t &malformed_occurrence,
+ std::vector<uint8_t>& incoming_data,
+ ProtocolFramePtrList& out_frames,
+ size_t& malformed_occurrence,
const transport_manager::ConnectionUID connection_id) {
LOG4CXX_AUTO_TRACE(logger_);
- bool correct_frame_occurs = true;
std::vector<uint8_t>::iterator data_it = incoming_data.begin();
size_t data_size = incoming_data.size();
+
while (data_size >= MIN_HEADER_SIZE) {
header_.deserialize(&*data_it, data_size);
const RESULT_CODE validate_result =
- validator_ ? validator_->validate(header_) : RESULT_OK;
+ validator_ ? validator_->validate(header_) : RESULT_OK;
if (validate_result != RESULT_OK) {
LOG4CXX_WARN(logger_, "Packet validation failed");
- if(correct_frame_occurs) {
+ if (!last_portion_of_data_was_malformed_) {
++malformed_occurrence;
+ LOG4CXX_DEBUG(logger_,
+ "Malformed message found " << malformed_occurrence);
}
- correct_frame_occurs = false;
+ last_portion_of_data_was_malformed_ = true;
++data_it;
--data_size;
- LOG4CXX_DEBUG(logger_, "Moved to the next byte " << std::hex
- << static_cast<const void *>(&*data_it));
+ LOG4CXX_DEBUG(logger_,
+ "Moved to the next byte "
+ << std::hex << static_cast<const void*>(&*data_it));
continue;
}
LOG4CXX_DEBUG(logger_, "Payload size " << header_.dataSize);
@@ -161,8 +170,9 @@ RESULT_CODE IncomingDataHandler::CreateFrame(
LOG4CXX_WARN(logger_, "Null packet size");
++data_it;
--data_size;
- LOG4CXX_DEBUG(logger_, "Moved to the next byte " << std::hex
- << static_cast<const void *>(&*data_it));
+ LOG4CXX_DEBUG(logger_,
+ "Moved to the next byte "
+ << std::hex << static_cast<const void*>(&*data_it));
continue;
}
if (data_size < packet_size) {
@@ -172,14 +182,19 @@ RESULT_CODE IncomingDataHandler::CreateFrame(
}
ProtocolFramePtr frame(new protocol_handler::ProtocolPacket(connection_id));
const RESULT_CODE deserialize_result =
- frame->deserializePacket(&*data_it, packet_size);
+ frame->deserializePacket(&*data_it, packet_size);
+ LOG4CXX_DEBUG(logger_, "Deserialized frame " << frame);
if (deserialize_result != RESULT_OK) {
LOG4CXX_WARN(logger_, "Packet deserialization failed");
incoming_data.erase(incoming_data.begin(), data_it);
return RESULT_FAIL;
}
+
out_frames.push_back(frame);
- correct_frame_occurs = true;
+ last_portion_of_data_was_malformed_ = false;
+ LOG4CXX_DEBUG(logger_,
+ "Frame added. "
+ << "Connection ID " << connection_id);
data_it += packet_size;
data_size -= packet_size;
diff --git a/src/components/protocol_handler/src/multiframe_builder.cc b/src/components/protocol_handler/src/multiframe_builder.cc
new file mode 100644
index 0000000000..5a1fc6d205
--- /dev/null
+++ b/src/components/protocol_handler/src/multiframe_builder.cc
@@ -0,0 +1,284 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "protocol_handler/multiframe_builder.h"
+
+#include <limits>
+
+#include "utils/logger.h"
+#include "utils/make_shared.h"
+#include "utils/lock.h"
+#include "utils/date_time.h"
+
+namespace protocol_handler {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "ProtocolHandler")
+
+MultiFrameBuilder::MultiFrameBuilder() : consecutive_frame_wait_msecs_(0u) {}
+
+void MultiFrameBuilder::set_waiting_timeout(
+ const uint32_t consecutive_frame_wait_msecs) {
+ consecutive_frame_wait_msecs_ =
+ static_cast<int64_t>(consecutive_frame_wait_msecs);
+ if (consecutive_frame_wait_msecs == 0) {
+ LOG4CXX_WARN(logger_, "Waiting timout disabled");
+ } else {
+ LOG4CXX_DEBUG(logger_,
+ "Waiting time in msec: " << consecutive_frame_wait_msecs_);
+ }
+}
+
+bool MultiFrameBuilder::AddConnection(const ConnectionID connection_id) {
+ LOG4CXX_DEBUG(logger_, "Adding connection_id: " << connection_id);
+ LOG4CXX_DEBUG(logger_, "Current state is: " << multiframes_map_);
+ const MultiFrameMap::const_iterator it = multiframes_map_.find(connection_id);
+ if (it != multiframes_map_.end()) {
+ LOG4CXX_ERROR(logger_, "Exists connection_id: " << connection_id);
+ return false;
+ }
+ multiframes_map_[connection_id] = SessionToFrameMap();
+ return true;
+}
+
+bool MultiFrameBuilder::RemoveConnection(const ConnectionID connection_id) {
+ LOG4CXX_DEBUG(logger_, "Removing connection_id: " << connection_id);
+ LOG4CXX_DEBUG(logger_, "Current state is: " << multiframes_map_);
+ const MultiFrameMap::iterator it = multiframes_map_.find(connection_id);
+ if (it == multiframes_map_.end()) {
+ LOG4CXX_ERROR(logger_, "Non-existent connection_id: " << connection_id);
+ return false;
+ }
+ const SessionToFrameMap& session_to_frame_map = it->second;
+ if (!session_to_frame_map.empty()) {
+ // FIXME(EZamakhov): Ask ReqManager - do we need to send GenericError
+ LOG4CXX_WARN(logger_,
+ "For connection_id: " << connection_id
+ << " waiting: " << multiframes_map_);
+ }
+ multiframes_map_.erase(it);
+ return true;
+}
+
+ProtocolFramePtrList MultiFrameBuilder::PopMultiframes() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_, "Current state is: " << multiframes_map_);
+ ProtocolFramePtrList outpute_frame_list;
+ for (MultiFrameMap::iterator connection_it = multiframes_map_.begin();
+ connection_it != multiframes_map_.end();
+ ++connection_it) {
+ LOG4CXX_TRACE(logger_, "Step over connection: " << connection_it->first);
+ SessionToFrameMap& session_map = connection_it->second;
+
+ for (SessionToFrameMap::iterator session_it = session_map.begin();
+ session_it != session_map.end();
+ ++session_it) {
+ LOG4CXX_TRACE(
+ logger_,
+ "Step over session: " << static_cast<int>(session_it->first));
+ MessageIDToFrameMap& messageId_map = session_it->second;
+
+ MessageIDToFrameMap::iterator messageId_it = messageId_map.begin();
+ while (messageId_it != messageId_map.end()) {
+ LOG4CXX_TRACE(logger_, "Step over messageId: " << messageId_it->first);
+ ProtocolFrameData& frame_data = messageId_it->second;
+ ProtocolFramePtr frame = frame_data.frame;
+
+ if (frame && frame->frame_data() == FRAME_DATA_LAST_CONSECUTIVE &&
+ frame->payload_size() > 0u) {
+ LOG4CXX_DEBUG(logger_, "Ready frame: " << frame);
+ outpute_frame_list.push_back(frame);
+ messageId_map.erase(messageId_it++);
+ continue;
+ }
+ if (consecutive_frame_wait_msecs_ != 0) {
+ LOG4CXX_TRACE(logger_, "Expiration verification");
+ const int64_t time_left =
+ date_time::DateTime::calculateTimeSpan(frame_data.append_time);
+ LOG4CXX_DEBUG(logger_, "mSecs left: " << time_left);
+ if (time_left >= consecutive_frame_wait_msecs_) {
+ LOG4CXX_WARN(logger_, "Expired frame: " << frame);
+ outpute_frame_list.push_back(frame);
+ messageId_map.erase(messageId_it++);
+ continue;
+ }
+ }
+ ++messageId_it;
+ } // iteration over messageId_map
+ } // iteration over session_map
+ } // iteration over multiframes_map_
+ LOG4CXX_DEBUG(logger_, "Result frames count: " << outpute_frame_list.size());
+ return outpute_frame_list;
+}
+
+RESULT_CODE MultiFrameBuilder::AddFrame(const ProtocolFramePtr packet) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_, "Handling frame: " << packet);
+ LOG4CXX_DEBUG(logger_, "Current state is: " << multiframes_map_);
+ if (!packet) {
+ LOG4CXX_ERROR(logger_, "Skip empty frame");
+ return RESULT_FAIL;
+ }
+ switch (packet->frame_type()) {
+ case FRAME_TYPE_FIRST:
+ LOG4CXX_TRACE(logger_, "FRAME_TYPE_FIRST");
+ return HandleFirstFrame(packet);
+ case FRAME_TYPE_CONSECUTIVE:
+ LOG4CXX_TRACE(logger_, "FRAME_TYPE_CONSECUTIVE");
+ return HandleConsecutiveFrame(packet);
+ default:
+ LOG4CXX_ERROR(logger_, "Frame is not FIRST or CONSECUTIVE :" << packet);
+ break;
+ }
+ return RESULT_FAIL;
+}
+
+RESULT_CODE MultiFrameBuilder::HandleFirstFrame(const ProtocolFramePtr packet) {
+ DCHECK_OR_RETURN(packet->frame_type() == FRAME_TYPE_FIRST, RESULT_FAIL);
+ LOG4CXX_DEBUG(logger_, "Waiting : " << multiframes_map_);
+ LOG4CXX_DEBUG(logger_, "Handling FIRST frame: " << packet);
+ if (packet->payload_size() != 0u) {
+ LOG4CXX_ERROR(logger_, "First frame shall have no data:" << packet);
+ return RESULT_FAIL;
+ }
+
+ const ConnectionID connection_id = packet->connection_id();
+ MultiFrameMap::iterator connection_it = multiframes_map_.find(connection_id);
+ if (connection_it == multiframes_map_.end()) {
+ LOG4CXX_ERROR(logger_, "Unknown connection_id: " << connection_id);
+ return RESULT_FAIL;
+ }
+ SessionToFrameMap& session_map = connection_it->second;
+
+ const SessionID session_id = packet->session_id();
+ // No need to verify session existance
+ MessageIDToFrameMap& messageId_map = session_map[session_id];
+
+ const MessageID message_id = packet->message_id();
+ MessageIDToFrameMap::iterator messageId_it = messageId_map.find(message_id);
+ if (messageId_it != messageId_map.end()) {
+ LOG4CXX_ERROR(logger_,
+ "Already waiting message for connection_id: "
+ << connection_id
+ << ", session_id: " << static_cast<int>(session_id)
+ << ", message_id: " << message_id);
+ return RESULT_FAIL;
+ }
+
+ LOG4CXX_DEBUG(logger_,
+ "Start waiting frames for connection_id: "
+ << connection_id
+ << ", session_id: " << static_cast<int>(session_id)
+ << ", message_id: " << message_id);
+ messageId_map[message_id] = {packet, date_time::DateTime::getCurrentTime()};
+ return RESULT_OK;
+}
+
+RESULT_CODE MultiFrameBuilder::HandleConsecutiveFrame(
+ const ProtocolFramePtr packet) {
+ DCHECK_OR_RETURN(packet->frame_type() == FRAME_TYPE_CONSECUTIVE, RESULT_FAIL);
+ LOG4CXX_DEBUG(logger_, "Handling CONSECUTIVE frame: " << packet);
+
+ const ConnectionID connection_id = packet->connection_id();
+ MultiFrameMap::iterator connection_it = multiframes_map_.find(connection_id);
+ if (connection_it == multiframes_map_.end()) {
+ LOG4CXX_ERROR(logger_, "Unknown connection_id: " << connection_id);
+ return RESULT_FAIL;
+ }
+ SessionToFrameMap& session_map = connection_it->second;
+
+ const SessionID session_id = packet->session_id();
+ // No need to verify session existance
+ MessageIDToFrameMap& messageId_map = session_map[session_id];
+
+ const MessageID message_id = packet->message_id();
+ MessageIDToFrameMap::iterator messageId_it = messageId_map.find(message_id);
+ if (messageId_it == messageId_map.end()) {
+ LOG4CXX_ERROR(logger_,
+ "No waiting message for connection_id: "
+ << connection_id
+ << ", session_id: " << static_cast<int>(session_id)
+ << ", message_id: " << message_id);
+ return RESULT_FAIL;
+ }
+
+ ProtocolFrameData& frame_data = messageId_it->second;
+ ProtocolFramePtr assembling_frame = frame_data.frame;
+ DCHECK_OR_RETURN(packet->message_id() == assembling_frame->message_id(),
+ RESULT_FAIL);
+
+ const uint8_t new_frame_data = packet->frame_data();
+ const bool is_last_consecutive =
+ (new_frame_data == FRAME_DATA_LAST_CONSECUTIVE);
+
+ if (is_last_consecutive) {
+ // TODO(EZamakhov): implement count of frames and result size verification
+ LOG4CXX_DEBUG(logger_, "Last CONSECUTIVE frame");
+ } else {
+ uint8_t previous_frame_data = assembling_frame->frame_data();
+ if (previous_frame_data == std::numeric_limits<uint8_t>::max()) {
+ previous_frame_data = 0u;
+ }
+ // The next frame data is bigger at 1
+ if (new_frame_data != (previous_frame_data + 1)) {
+ LOG4CXX_ERROR(logger_,
+ "Unexpected CONSECUTIVE frame for connection_id: "
+ << connection_id
+ << ", session_id: " << static_cast<int>(session_id)
+ << ", message_id: " << message_id
+ << ", frame: " << packet);
+ return RESULT_FAIL;
+ }
+ }
+
+ assembling_frame->set_frame_data(new_frame_data);
+
+ LOG4CXX_DEBUG(logger_,
+ "Appending " << packet->data_size() << " bytes "
+ << "; frame_data "
+ << static_cast<int>(new_frame_data)
+ << "; for connection_id: " << connection_id
+ << ", session_id: " << static_cast<int>(session_id)
+ << ", message_id: " << message_id);
+
+ if (assembling_frame->appendData(packet->data(), packet->data_size()) !=
+ RESULT_OK) {
+ LOG4CXX_ERROR(logger_, "Failed to append frame for multiframe message.");
+ return RESULT_FAIL;
+ }
+ LOG4CXX_INFO(logger_,
+ "Assembled frame with payload size: "
+ << assembling_frame->payload_size());
+ frame_data.append_time = date_time::DateTime::getCurrentTime();
+ return RESULT_OK;
+}
+
+} // namespace protocol_handler
diff --git a/src/components/protocol_handler/src/protocol_handler_impl.cc b/src/components/protocol_handler/src/protocol_handler_impl.cc
index 3289c6b4d8..aa2910722d 100644
--- a/src/components/protocol_handler/src/protocol_handler_impl.cc
+++ b/src/components/protocol_handler/src/protocol_handler_impl.cc
@@ -32,10 +32,10 @@
#include "protocol_handler/protocol_handler_impl.h"
#include <memory.h>
-#include <algorithm> // std::find
+#include <algorithm> // std::find
#include "connection_handler/connection_handler_impl.h"
-#include "config_profile/profile.h"
+#include "protocol_handler/session_observer.h"
#include "utils/byte_order.h"
#include "protocol/common.h"
@@ -52,80 +52,91 @@ CREATE_LOGGERPTR_GLOBAL(logger_, "ProtocolHandler")
* Function return packet data as std::string.
* If packet data is not printable return error message
*/
-std::string ConvertPacketDataToString(const uint8_t *data,
+std::string ConvertPacketDataToString(const uint8_t* data,
const size_t data_size);
-/**
- * @brief Function returns supported SDL Protocol Version,
- */
-uint8_t SupportedSDLProtocolVersion();
-
-
const size_t kStackSize = 32768;
ProtocolHandlerImpl::ProtocolHandlerImpl(
- transport_manager::TransportManager *transport_manager_param,
- size_t message_frequency_time, size_t message_frequency_count,
- bool malformed_message_filtering,
- size_t malformed_message_frequency_time, size_t malformed_message_frequency_count)
- : protocol_observers_(),
- session_observer_(0),
- transport_manager_(transport_manager_param),
- kPeriodForNaviAck(5),
- message_max_frequency_(message_frequency_count),
- message_frequency_time_(message_frequency_time),
- malformed_message_filtering_(malformed_message_filtering),
- malformed_message_max_frequency_(malformed_message_frequency_count),
- malformed_message_frequency_time_(malformed_message_frequency_time),
+ const ProtocolHandlerSettings& settings,
+ protocol_handler::SessionObserver& session_observer,
+ connection_handler::ConnectionHandler& connection_handler,
+ transport_manager::TransportManager& transport_manager)
+ : settings_(settings)
+ , protocol_observers_()
+ , session_observer_(session_observer)
+ , connection_handler_(connection_handler)
+ , transport_manager_(transport_manager)
+ , kPeriodForNaviAck(5)
+ ,
#ifdef ENABLE_SECURITY
- security_manager_(NULL),
+ security_manager_(NULL)
+ ,
#endif // ENABLE_SECURITY
- raw_ford_messages_from_mobile_("PH FromMobile", this,
- threads::ThreadOptions(kStackSize)),
- raw_ford_messages_to_mobile_("PH ToMobile", this,
- threads::ThreadOptions(kStackSize))
-#ifdef TIME_TESTER
- , metric_observer_(NULL)
-#endif // TIME_TESTER
+ raw_ford_messages_from_mobile_(
+ "PH FromMobile", this, threads::ThreadOptions(kStackSize))
+ , raw_ford_messages_to_mobile_(
+ "PH ToMobile", this, threads::ThreadOptions(kStackSize))
+#ifdef TELEMETRY_MONITOR
+ , metric_observer_(NULL)
+#endif // TELEMETRY_MONITOR
{
LOG4CXX_AUTO_TRACE(logger_);
- protocol_header_validator_.set_max_payload_size(profile::Profile::instance()->maximum_payload_size());
+ protocol_header_validator_.set_max_payload_size(
+ get_settings().maximum_payload_size());
incoming_data_handler_.set_validator(&protocol_header_validator_);
- if (message_frequency_time_ > 0u &&
- message_max_frequency_ > 0u) {
- message_meter_.set_time_range(message_frequency_time_);
- LOG4CXX_DEBUG(logger_, "Frequency meter is enabled ( " << message_max_frequency_
- << " per " << message_frequency_time_ << " mSecond)");
+ const size_t& message_frequency_count =
+ get_settings().message_frequency_count();
+ const size_t& message_frequency_time =
+ get_settings().message_frequency_time();
+
+ if (message_frequency_time > 0u && message_frequency_count > 0u) {
+ message_meter_.set_time_range(message_frequency_time);
+ LOG4CXX_DEBUG(logger_,
+ "Frequency meter is enabled ( "
+ << message_frequency_count << " per "
+ << message_frequency_time << " mSecond)");
} else {
LOG4CXX_WARN(logger_, "Frequency meter is disabled");
}
- if (malformed_message_filtering_) {
- if(malformed_message_frequency_time_ > 0u &&
- malformed_message_max_frequency_ > 0u) {
- malformed_message_meter_.set_time_range(malformed_message_frequency_time_);
- LOG4CXX_DEBUG(logger_, "Malformed frequency meter is enabled ( " << malformed_message_max_frequency_
- << " per " << malformed_message_frequency_time_ << " mSecond)");
+ const size_t& malformed_frequency_time =
+ get_settings().malformed_frequency_time();
+ const size_t& malformed_frequency_count =
+ get_settings().message_frequency_time();
+
+ if (get_settings().malformed_message_filtering()) {
+ if (malformed_frequency_time > 0u && malformed_frequency_count > 0u) {
+ malformed_message_meter_.set_time_range(malformed_frequency_time);
+ LOG4CXX_DEBUG(logger_,
+ "Malformed frequency meter is enabled ( "
+ << malformed_frequency_count << " per "
+ << malformed_frequency_time << " mSecond)");
} else {
LOG4CXX_WARN(logger_, "Malformed frequency meter is disabled");
}
} else {
- LOG4CXX_WARN(logger_, "Malformed message filtering is disabled."
- << "Connection will be close on first malformed message detection");
+ LOG4CXX_WARN(
+ logger_,
+ "Malformed message filtering is disabled."
+ << "Connection will be close on first malformed message detection");
}
+ multiframe_builder_.set_waiting_timeout(
+ get_settings().multiframe_waiting_timeout());
}
ProtocolHandlerImpl::~ProtocolHandlerImpl() {
sync_primitives::AutoLock lock(protocol_observers_lock_);
if (!protocol_observers_.empty()) {
- LOG4CXX_WARN(logger_, "Not all observers have unsubscribed"
+ LOG4CXX_WARN(logger_,
+ "Not all observers have unsubscribed"
" from ProtocolHandlerImpl");
}
}
-void ProtocolHandlerImpl::AddProtocolObserver(ProtocolObserver *observer) {
+void ProtocolHandlerImpl::AddProtocolObserver(ProtocolObserver* observer) {
if (!observer) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to IProtocolObserver.");
return;
@@ -144,34 +155,28 @@ void ProtocolHandlerImpl::RemoveProtocolObserver(ProtocolObserver* observer) {
protocol_observers_.erase(observer);
}
-void ProtocolHandlerImpl::set_session_observer(SessionObserver *observer) {
- if (!observer) {
- LOG4CXX_WARN(logger_, "Invalid (NULL) pointer to ISessionObserver.");
- // Do not return from here!
- }
- session_observer_ = observer;
-}
-
void set_hash_id(uint32_t hash_id, protocol_handler::ProtocolPacket& packet) {
- if (HASH_ID_NOT_SUPPORTED == hash_id ||
- HASH_ID_WRONG == hash_id) {
+ if (HASH_ID_NOT_SUPPORTED == hash_id || HASH_ID_WRONG == hash_id) {
return;
}
if (packet.protocol_version() < PROTOCOL_VERSION_2) {
- LOG4CXX_DEBUG(logger_, "Packet needs no hash data (protocol version less 2)");
+ LOG4CXX_DEBUG(logger_,
+ "Packet needs no hash data (protocol version less 2)");
return;
}
- LOG4CXX_DEBUG(logger_, "Set hash_id 0x" << std::hex << hash_id <<
- " to the packet 0x" << &packet);
+ LOG4CXX_DEBUG(logger_,
+ "Set hash_id 0x" << std::hex << hash_id << " to the packet 0x"
+ << &packet);
// Hash id shall be 4 bytes according Ford Protocol v8
DCHECK(sizeof(hash_id) == 4);
const uint32_t hash_id_be = LE_TO_BE32(hash_id);
- packet.set_data(reinterpret_cast<const uint8_t*>(&hash_id_be), sizeof(hash_id_be));
+ packet.set_data(reinterpret_cast<const uint8_t*>(&hash_id_be),
+ sizeof(hash_id_be));
}
void ProtocolHandlerImpl::SendStartSessionAck(ConnectionID connection_id,
uint8_t session_id,
- uint8_t ,
+ uint8_t,
uint32_t hash_id,
uint8_t service_type,
bool protection) {
@@ -179,10 +184,16 @@ void ProtocolHandlerImpl::SendStartSessionAck(ConnectionID connection_id,
uint8_t protocolVersion = SupportedSDLProtocolVersion();
- ProtocolFramePtr ptr(new protocol_handler::ProtocolPacket(connection_id,
- protocolVersion, protection, FRAME_TYPE_CONTROL,
- service_type, FRAME_DATA_START_SERVICE_ACK, session_id,
- 0u, message_counters_[session_id]++));
+ ProtocolFramePtr ptr(
+ new protocol_handler::ProtocolPacket(connection_id,
+ protocolVersion,
+ protection,
+ FRAME_TYPE_CONTROL,
+ service_type,
+ FRAME_DATA_START_SERVICE_ACK,
+ session_id,
+ 0u,
+ message_counters_[session_id]++));
set_hash_id(hash_id, *ptr);
@@ -190,10 +201,11 @@ void ProtocolHandlerImpl::SendStartSessionAck(ConnectionID connection_id,
impl::RawFordMessageToMobile(ptr, false));
LOG4CXX_DEBUG(logger_,
- "SendStartSessionAck() for connection " << connection_id
- << " for service_type " << static_cast<int32_t>(service_type)
- << " session_id " << static_cast<int32_t>(session_id)
- << " protection " << (protection ? "ON" : "OFF"));
+ "SendStartSessionAck() for connection "
+ << connection_id << " for service_type "
+ << static_cast<int32_t>(service_type) << " session_id "
+ << static_cast<int32_t>(session_id) << " protection "
+ << (protection ? "ON" : "OFF"));
}
void ProtocolHandlerImpl::SendStartSessionNAck(ConnectionID connection_id,
@@ -202,18 +214,25 @@ void ProtocolHandlerImpl::SendStartSessionNAck(ConnectionID connection_id,
uint8_t service_type) {
LOG4CXX_AUTO_TRACE(logger_);
- ProtocolFramePtr ptr(new protocol_handler::ProtocolPacket(connection_id,
- protocol_version, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- service_type, FRAME_DATA_START_SERVICE_NACK,
- session_id, 0u, message_counters_[session_id]++));
+ ProtocolFramePtr ptr(
+ new protocol_handler::ProtocolPacket(connection_id,
+ protocol_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ service_type,
+ FRAME_DATA_START_SERVICE_NACK,
+ session_id,
+ 0u,
+ message_counters_[session_id]++));
raw_ford_messages_to_mobile_.PostMessage(
impl::RawFordMessageToMobile(ptr, false));
LOG4CXX_DEBUG(logger_,
- "SendStartSessionNAck() for connection " << connection_id
- << " for service_type " << static_cast<int32_t>(service_type)
- << " session_id " << static_cast<int32_t>(session_id));
+ "SendStartSessionNAck() for connection "
+ << connection_id << " for service_type "
+ << static_cast<int32_t>(service_type) << " session_id "
+ << static_cast<int32_t>(session_id));
}
void ProtocolHandlerImpl::SendEndSessionNAck(ConnectionID connection_id,
@@ -222,17 +241,29 @@ void ProtocolHandlerImpl::SendEndSessionNAck(ConnectionID connection_id,
uint8_t service_type) {
LOG4CXX_AUTO_TRACE(logger_);
- ProtocolFramePtr ptr(new protocol_handler::ProtocolPacket(connection_id,
- protocol_version, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- service_type, FRAME_DATA_END_SERVICE_NACK,
- session_id, 0u, message_counters_[session_id]++));
+ ProtocolFramePtr ptr(
+ new protocol_handler::ProtocolPacket(connection_id,
+ protocol_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ service_type,
+ FRAME_DATA_END_SERVICE_NACK,
+ session_id,
+ 0u,
+ message_counters_[session_id]++));
raw_ford_messages_to_mobile_.PostMessage(
impl::RawFordMessageToMobile(ptr, false));
- LOG4CXX_DEBUG(logger_, "SendEndSessionNAck() for connection " << connection_id
- << " for service_type " << static_cast<int32_t>(service_type)
- << " session_id " << static_cast<int32_t>(session_id));
+ LOG4CXX_DEBUG(logger_,
+ "SendEndSessionNAck() for connection "
+ << connection_id << " for service_type "
+ << static_cast<int32_t>(service_type) << " session_id "
+ << static_cast<int32_t>(session_id));
+}
+
+SessionObserver& ProtocolHandlerImpl::get_session_observer() {
+ return session_observer_;
}
void ProtocolHandlerImpl::SendEndSessionAck(ConnectionID connection_id,
@@ -241,18 +272,25 @@ void ProtocolHandlerImpl::SendEndSessionAck(ConnectionID connection_id,
uint8_t service_type) {
LOG4CXX_AUTO_TRACE(logger_);
- ProtocolFramePtr ptr(new protocol_handler::ProtocolPacket(connection_id,
- protocol_version, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- service_type, FRAME_DATA_END_SERVICE_ACK, session_id,
- 0u, message_counters_[session_id]++));
+ ProtocolFramePtr ptr(
+ new protocol_handler::ProtocolPacket(connection_id,
+ protocol_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ service_type,
+ FRAME_DATA_END_SERVICE_ACK,
+ session_id,
+ 0u,
+ message_counters_[session_id]++));
raw_ford_messages_to_mobile_.PostMessage(
impl::RawFordMessageToMobile(ptr, false));
LOG4CXX_DEBUG(logger_,
- "SendEndSessionAck() for connection " << connection_id
- << " for service_type " << static_cast<int32_t>(service_type)
- << " session_id " << static_cast<int32_t>(session_id));
+ "SendEndSessionAck() for connection "
+ << connection_id << " for service_type "
+ << static_cast<int32_t>(service_type) << " session_id "
+ << static_cast<int32_t>(session_id));
}
void ProtocolHandlerImpl::SendEndServicePrivate(int32_t connection_id,
@@ -261,20 +299,29 @@ void ProtocolHandlerImpl::SendEndServicePrivate(int32_t connection_id,
LOG4CXX_AUTO_TRACE(logger_);
uint8_t protocol_version;
- if (session_observer_->ProtocolVersionUsed(connection_id,
- session_id, protocol_version)) {
- ProtocolFramePtr ptr(new protocol_handler::ProtocolPacket(connection_id,
- protocol_version, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- service_type, FRAME_DATA_END_SERVICE, session_id, 0,
- message_counters_[session_id]++));
+ if (session_observer_.ProtocolVersionUsed(
+ connection_id, session_id, protocol_version)) {
+ ProtocolFramePtr ptr(
+ new protocol_handler::ProtocolPacket(connection_id,
+ protocol_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ service_type,
+ FRAME_DATA_END_SERVICE,
+ session_id,
+ 0,
+ message_counters_[session_id]++));
raw_ford_messages_to_mobile_.PostMessage(
- impl::RawFordMessageToMobile(ptr, false));
- LOG4CXX_DEBUG(logger_, "SendEndSession() for connection " << connection_id
- << " for service_type " << service_type
- << " session_id " << static_cast<int32_t>(session_id));
+ impl::RawFordMessageToMobile(ptr, false));
+ LOG4CXX_DEBUG(logger_,
+ "SendEndSession() for connection "
+ << connection_id << " for service_type " << service_type
+ << " session_id " << static_cast<int32_t>(session_id));
} else {
- LOG4CXX_WARN(logger_, "SendEndSession is failed connection or session does not exist");
+ LOG4CXX_WARN(
+ logger_,
+ "SendEndSession is failed connection or session does not exist");
}
}
@@ -295,18 +342,26 @@ RESULT_CODE ProtocolHandlerImpl::SendHeartBeatAck(ConnectionID connection_id,
LOG4CXX_AUTO_TRACE(logger_);
uint8_t protocol_version;
- if (session_observer_->ProtocolVersionUsed(connection_id,
- session_id, protocol_version)) {
- ProtocolFramePtr ptr(new protocol_handler::ProtocolPacket(connection_id,
- protocol_version, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- SERVICE_TYPE_CONTROL, FRAME_DATA_HEART_BEAT_ACK, session_id,
- 0u, message_id));
-
- raw_ford_messages_to_mobile_.PostMessage(
- impl::RawFordMessageToMobile(ptr, false));
- return RESULT_OK;
- }
- LOG4CXX_WARN(logger_, "SendHeartBeatAck is failed connection or session does not exist");
+ if (session_observer_.ProtocolVersionUsed(
+ connection_id, session_id, protocol_version)) {
+ ProtocolFramePtr ptr(
+ new protocol_handler::ProtocolPacket(connection_id,
+ protocol_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ SERVICE_TYPE_CONTROL,
+ FRAME_DATA_HEART_BEAT_ACK,
+ session_id,
+ 0u,
+ message_id));
+
+ raw_ford_messages_to_mobile_.PostMessage(
+ impl::RawFordMessageToMobile(ptr, false));
+ return RESULT_OK;
+ }
+ LOG4CXX_WARN(
+ logger_,
+ "SendHeartBeatAck is failed connection or session does not exist");
return RESULT_FAIL;
}
@@ -314,80 +369,85 @@ void ProtocolHandlerImpl::SendHeartBeat(int32_t connection_id,
uint8_t session_id) {
LOG4CXX_AUTO_TRACE(logger_);
uint8_t protocol_version;
- if (session_observer_->ProtocolVersionUsed(connection_id,
- session_id, protocol_version)) {
- ProtocolFramePtr ptr(new protocol_handler::ProtocolPacket(connection_id,
- protocol_version, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- SERVICE_TYPE_CONTROL, FRAME_DATA_HEART_BEAT, session_id,
- 0u, message_counters_[session_id]++));
-
+ if (session_observer_.ProtocolVersionUsed(
+ connection_id, session_id, protocol_version)) {
+ ProtocolFramePtr ptr(
+ new protocol_handler::ProtocolPacket(connection_id,
+ protocol_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ SERVICE_TYPE_CONTROL,
+ FRAME_DATA_HEART_BEAT,
+ session_id,
+ 0u,
+ message_counters_[session_id]++));
raw_ford_messages_to_mobile_.PostMessage(
impl::RawFordMessageToMobile(ptr, false));
LOG4CXX_DEBUG(logger_, "SendHeartBeat finished successfully");
} else {
- LOG4CXX_WARN(logger_, "SendHeartBeat is failed connection or session does not exist");
+ LOG4CXX_WARN(
+ logger_,
+ "SendHeartBeat is failed connection or session does not exist");
}
}
void ProtocolHandlerImpl::SendMessageToMobileApp(const RawMessagePtr message,
bool final_message) {
-#ifdef TIME_TESTER
- const TimevalStruct start_time = date_time::DateTime::getCurrentTime();
-#endif // TIME_TESTER
+#ifdef TELEMETRY_MONITOR
+ const TimevalStruct start_time = date_time::DateTime::getCurrentTime();
+#endif // TELEMETRY_MONITOR
LOG4CXX_AUTO_TRACE(logger_);
if (!message) {
LOG4CXX_ERROR(logger_,
- "Invalid message for sending to mobile app is received.");
+ "Invalid message for sending to mobile app is received.");
return;
}
- if (!session_observer_) {
- LOG4CXX_ERROR(
- logger_,
- "Cannot handle message to mobile app:" <<
- " ISessionObserver doesn't exist.");
- return;
- }
uint32_t connection_handle = 0;
uint8_t sessionID = 0;
- session_observer_->PairFromKey(message->connection_key(), &connection_handle,
- &sessionID);
-#ifdef TIME_TESTER
+ session_observer_.PairFromKey(
+ message->connection_key(), &connection_handle, &sessionID);
+#ifdef TELEMETRY_MONITOR
uint32_t message_id = message_counters_[sessionID];
if (metric_observer_) {
metric_observer_->StartMessageProcess(message_id, start_time);
}
-#endif // TIME_TESTER
- const size_t max_frame_size =
- profile::Profile::instance()->maximum_payload_size();
+#endif // TELEMETRY_MONITOR
+ const size_t max_frame_size = get_settings().maximum_payload_size();
size_t frame_size = MAXIMUM_FRAME_DATA_V2_SIZE;
switch (message->protocol_version()) {
case PROTOCOL_VERSION_3:
case PROTOCOL_VERSION_4:
- frame_size = max_frame_size > MAXIMUM_FRAME_DATA_V2_SIZE ?
- max_frame_size : MAXIMUM_FRAME_DATA_V2_SIZE;
+ frame_size = max_frame_size > MAXIMUM_FRAME_DATA_V2_SIZE
+ ? max_frame_size
+ : MAXIMUM_FRAME_DATA_V2_SIZE;
break;
default:
break;
}
#ifdef ENABLE_SECURITY
- const security_manager::SSLContext *ssl_context = session_observer_->
- GetSSLContext(message->connection_key(), message->service_type());
+ const security_manager::SSLContext* ssl_context =
+ session_observer_.GetSSLContext(message->connection_key(),
+ message->service_type());
if (ssl_context && ssl_context->IsInitCompleted()) {
const size_t max_block_size = ssl_context->get_max_block_size(frame_size);
DCHECK(max_block_size > 0);
if (max_block_size > 0) {
frame_size = max_block_size;
- LOG4CXX_DEBUG(logger_, "Security set new optimal packet size " << frame_size);
+ LOG4CXX_DEBUG(logger_,
+ "Security set new optimal packet size " << frame_size);
} else {
- LOG4CXX_ERROR(logger_, "Security could not return max block size, use the origin one");
+ LOG4CXX_ERROR(
+ logger_,
+ "Security could not return max block size, use the origin one");
}
}
LOG4CXX_DEBUG(logger_, "Optimal packet size is " << frame_size);
#endif // ENABLE_SECURITY
if (message->data_size() <= frame_size) {
- RESULT_CODE result = SendSingleFrameMessage(connection_handle, sessionID,
+ RESULT_CODE result = SendSingleFrameMessage(connection_handle,
+ sessionID,
message->protocol_version(),
message->service_type(),
message->data_size(),
@@ -395,33 +455,35 @@ void ProtocolHandlerImpl::SendMessageToMobileApp(const RawMessagePtr message,
final_message);
if (result != RESULT_OK) {
LOG4CXX_ERROR(logger_,
- "ProtocolHandler failed to send single frame message.");
+ "ProtocolHandler failed to send single frame message.");
}
} else {
- LOG4CXX_DEBUG(
- logger_,
- "Message will be sent in multiple frames; max frame size is " << frame_size);
+ LOG4CXX_DEBUG(logger_,
+ "Message will be sent in multiple frames; max frame size is "
+ << frame_size);
- RESULT_CODE result = SendMultiFrameMessage(connection_handle, sessionID,
+ RESULT_CODE result = SendMultiFrameMessage(connection_handle,
+ sessionID,
message->protocol_version(),
message->service_type(),
message->data_size(),
message->data(),
- frame_size, final_message);
+ frame_size,
+ final_message);
if (result != RESULT_OK) {
LOG4CXX_ERROR(logger_,
- "ProtocolHandler failed to send multiframe messages.");
+ "ProtocolHandler failed to send multiframe messages.");
}
}
-#ifdef TIME_TESTER
- if (metric_observer_) {
- PHMetricObserver::MessageMetric *metric
- = new PHMetricObserver::MessageMetric();
- metric->message_id = message_id;
- metric->connection_key = message->connection_key();
- metric->raw_msg = message;
- metric_observer_->EndMessageProcess(metric);
- }
+#ifdef TELEMETRY_MONITOR
+ if (metric_observer_) {
+ PHTelemetryObserver::MessageMetric* metric =
+ new PHTelemetryObserver::MessageMetric();
+ metric->message_id = message_id;
+ metric->connection_key = message->connection_key();
+ metric->raw_msg = message;
+ metric_observer_->EndMessageProcess(metric);
+ }
#endif
}
@@ -429,47 +491,50 @@ void ProtocolHandlerImpl::OnTMMessageReceived(const RawMessagePtr tm_message) {
LOG4CXX_AUTO_TRACE(logger_);
if (!tm_message) {
- LOG4CXX_ERROR(
- logger_,
- "Invalid incoming message received in"
- << " ProtocolHandler from Transport Manager.");
+ LOG4CXX_ERROR(logger_,
+ "Invalid incoming message received in"
+ << " ProtocolHandler from Transport Manager.");
return;
}
const uint32_t connection_key = tm_message->connection_key();
LOG4CXX_DEBUG(logger_,
- "Received data from TM with connection id " << connection_key <<
- " msg data_size " << tm_message->data_size());
+ "Received data from TM with connection id "
+ << connection_key << " msg data_size "
+ << tm_message->data_size());
RESULT_CODE result;
- size_t malformed_occurs = false;
- const std::list<ProtocolFramePtr> protocol_frames =
- incoming_data_handler_.ProcessData(*tm_message, &result, &malformed_occurs);
- LOG4CXX_DEBUG(logger_, "Proccessed " << protocol_frames.size() << "frames");
+ size_t malformed_occurs = 0u;
+ const ProtocolFramePtrList protocol_frames =
+ incoming_data_handler_.ProcessData(
+ *tm_message, &result, &malformed_occurs);
+ LOG4CXX_DEBUG(logger_, "Proccessed " << protocol_frames.size() << " frames");
if (result != RESULT_OK) {
if (result == RESULT_MALFORMED_OCCURS) {
- LOG4CXX_WARN(logger_, "Malformed message occurs, connection id "
- << connection_key);
- if (!malformed_message_filtering_) {
+ LOG4CXX_WARN(logger_,
+ "Malformed message occurs, connection id "
+ << connection_key);
+ if (!get_settings().malformed_message_filtering()) {
LOG4CXX_DEBUG(logger_, "Malformed message filterign disabled");
- if (session_observer_) {
- session_observer_->OnMalformedMessageCallback(connection_key);
+ session_observer_.OnMalformedMessageCallback(connection_key);
+ // For tracking only malformed occurrence check outpute
+ } else {
+ if (malformed_occurs > 0) {
+ TrackMalformedMessage(connection_key, malformed_occurs);
}
- // For tracking only malformed occurrence check outpute
- } else if(!protocol_frames.empty()) {
- TrackMalformedMessage(connection_key, malformed_occurs);
}
} else {
LOG4CXX_ERROR(logger_, "Incoming data processing failed.");
- transport_manager_->DisconnectForce(connection_key);
+ transport_manager_.DisconnectForce(connection_key);
}
}
- for (std::list<ProtocolFramePtr>::const_iterator it =
- protocol_frames.begin(); it != protocol_frames.end(); ++it) {
-#ifdef TIME_TESTER
+ for (ProtocolFramePtrList::const_iterator it = protocol_frames.begin();
+ it != protocol_frames.end();
+ ++it) {
+#ifdef TELEMETRY_MONITOR
const TimevalStruct start_time = date_time::DateTime::getCurrentTime();
-#endif // TIME_TESTER
+#endif // TELEMETRY_MONITOR
ProtocolFramePtr frame = *it;
#ifdef ENABLE_SECURITY
const RESULT_CODE result = DecryptFrame(frame);
@@ -479,18 +544,18 @@ void ProtocolHandlerImpl::OnTMMessageReceived(const RawMessagePtr tm_message) {
}
#endif // ENABLE_SECURITY
impl::RawFordMessageFromMobile msg(frame);
-#ifdef TIME_TESTER
+#ifdef TELEMETRY_MONITOR
if (metric_observer_) {
metric_observer_->StartMessageProcess(msg->message_id(), start_time);
}
-#endif // TIME_TESTER
+#endif // TELEMETRY_MONITOR
raw_ford_messages_from_mobile_.PostMessage(msg);
}
}
void ProtocolHandlerImpl::OnTMMessageReceiveFailed(
- const transport_manager::DataReceiveError &error) {
+ const transport_manager::DataReceiveError& error) {
// TODO(PV): implement
LOG4CXX_ERROR(logger_, "Received error on attemping to recieve message.");
}
@@ -498,9 +563,16 @@ void ProtocolHandlerImpl::OnTMMessageReceiveFailed(
void ProtocolHandlerImpl::NotifySubscribers(const RawMessagePtr message) {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock lock(protocol_observers_lock_);
+ if (protocol_observers_.empty()) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Cannot handle multiframe message: no IProtocolObserver is set.");
+ }
for (ProtocolObservers::iterator it = protocol_observers_.begin();
- protocol_observers_.end() != it; ++it) {
- (*it)->OnMessageReceived(message);
+ protocol_observers_.end() != it;
+ ++it) {
+ ProtocolObserver* observe = *it;
+ observe->OnMessageReceived(message);
}
}
@@ -510,23 +582,23 @@ void ProtocolHandlerImpl::OnTMMessageSend(const RawMessagePtr message) {
uint32_t connection_handle = 0;
uint8_t sessionID = 0;
- session_observer_->PairFromKey(message->connection_key(),
- &connection_handle,
- &sessionID);
+ session_observer_.PairFromKey(
+ message->connection_key(), &connection_handle, &sessionID);
- std::list<uint32_t>::iterator connection_it =
+ std::vector<uint32_t>::iterator connection_it =
std::find(ready_to_close_connections_.begin(),
- ready_to_close_connections_.end(), connection_handle);
+ ready_to_close_connections_.end(),
+ connection_handle);
if (ready_to_close_connections_.end() != connection_it) {
ready_to_close_connections_.erase(connection_it);
- transport_manager_->Disconnect(connection_handle);
+ transport_manager_.Disconnect(connection_handle);
return;
}
ProtocolPacket sent_message(message->connection_key());
- const RESULT_CODE result = sent_message.deserializePacket(message->data(),
- message->data_size());
+ const RESULT_CODE result =
+ sent_message.deserializePacket(message->data(), message->data_size());
if (result != RESULT_OK) {
LOG4CXX_ERROR(logger_, "Error while message deserialization.");
return;
@@ -537,40 +609,47 @@ void ProtocolHandlerImpl::OnTMMessageSend(const RawMessagePtr message) {
if (sessions_last_message_id_.end() != it) {
uint32_t last_message_id = it->second;
sessions_last_message_id_.erase(it);
- if ((sent_message.message_id() == last_message_id) &&
+ if ((sent_message.message_id() == last_message_id) &&
((FRAME_TYPE_SINGLE == sent_message.frame_type()) ||
- ((FRAME_TYPE_CONSECUTIVE == sent_message.frame_type()) &&
- (0 == sent_message.frame_data())))) {
+ ((FRAME_TYPE_CONSECUTIVE == sent_message.frame_type()) &&
+ (0 == sent_message.frame_data())))) {
ready_to_close_connections_.push_back(connection_handle);
SendEndSession(connection_handle, sent_message.session_id());
}
}
sync_primitives::AutoLock lock(protocol_observers_lock_);
for (ProtocolObservers::iterator it = protocol_observers_.begin();
- protocol_observers_.end() != it; ++it) {
+ protocol_observers_.end() != it;
+ ++it) {
(*it)->OnMobileMessageSent(message);
}
}
void ProtocolHandlerImpl::OnTMMessageSendFailed(
- const transport_manager::DataSendError &error,
+ const transport_manager::DataSendError& error,
const RawMessagePtr message) {
+ DCHECK_OR_RETURN_VOID(message);
// TODO(PV): implement
- LOG4CXX_ERROR(logger_, "Sending message " << message->data_size()
- << " bytes failed: " << error.text());
+ LOG4CXX_ERROR(logger_,
+ "Sending message " << message->data_size()
+ << "bytes failed, connection_key "
+ << message->connection_key()
+ << "Error_text: " << error.text());
}
void ProtocolHandlerImpl::OnConnectionEstablished(
- const transport_manager::DeviceInfo &device_info,
- const transport_manager::ConnectionUID &connection_id) {
+ const transport_manager::DeviceInfo& device_info,
+ const transport_manager::ConnectionUID connection_id) {
incoming_data_handler_.AddConnection(connection_id);
+ multiframe_builder_.AddConnection(connection_id);
}
void ProtocolHandlerImpl::OnConnectionClosed(
- const transport_manager::ConnectionUID &connection_id) {
+ const transport_manager::ConnectionUID connection_id) {
incoming_data_handler_.RemoveConnection(connection_id);
message_meter_.ClearIdentifiers();
malformed_message_meter_.ClearIdentifiers();
+ multiframe_builder_.RemoveConnection(connection_id);
}
RESULT_CODE ProtocolHandlerImpl::SendFrame(const ProtocolFramePtr packet) {
@@ -588,40 +667,49 @@ RESULT_CODE ProtocolHandlerImpl::SendFrame(const ProtocolFramePtr packet) {
}
#endif // ENABLE_SECURITY
- LOG4CXX_DEBUG(logger_, "Packet to be sent: " <<
- ConvertPacketDataToString(packet->data(), packet->data_size()) <<
- " of size: " << packet->data_size());
+ LOG4CXX_DEBUG(
+ logger_,
+ "Packet to be sent: "
+ << ConvertPacketDataToString(packet->data(), packet->data_size())
+ << " of size: " << packet->data_size());
const RawMessagePtr message_to_send = packet->serializePacket();
if (!message_to_send) {
LOG4CXX_ERROR(logger_, "Serialization error");
- return RESULT_FAIL;
- };
- LOG4CXX_DEBUG(logger_,
- "Message to send with connection id " <<
- static_cast<int>(packet->connection_id()));
-
- if (!transport_manager_) {
- LOG4CXX_WARN(logger_, "No Transport Manager found.");
return RESULT_FAIL;
}
+ LOG4CXX_DEBUG(logger_,
+ "Message to send with connection id "
+ << static_cast<int>(packet->connection_id()));
+
if (transport_manager::E_SUCCESS !=
- transport_manager_->SendMessageToDevice(message_to_send)) {
+ transport_manager_.SendMessageToDevice(message_to_send)) {
LOG4CXX_WARN(logger_, "Can't send message to device");
return RESULT_FAIL;
- };
+ }
return RESULT_OK;
}
RESULT_CODE ProtocolHandlerImpl::SendSingleFrameMessage(
- const ConnectionID connection_id, const uint8_t session_id,
- const uint32_t protocol_version, const uint8_t service_type,
- const size_t data_size, const uint8_t *data,
+ const ConnectionID connection_id,
+ const uint8_t session_id,
+ const uint32_t protocol_version,
+ const uint8_t service_type,
+ const size_t data_size,
+ const uint8_t* data,
const bool is_final_message) {
LOG4CXX_AUTO_TRACE(logger_);
- ProtocolFramePtr ptr(new protocol_handler::ProtocolPacket(connection_id,
- protocol_version, PROTECTION_OFF, FRAME_TYPE_SINGLE, service_type, FRAME_DATA_SINGLE,
- session_id, data_size, message_counters_[session_id]++, data));
+ ProtocolFramePtr ptr(
+ new protocol_handler::ProtocolPacket(connection_id,
+ protocol_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ service_type,
+ FRAME_DATA_SINGLE,
+ session_id,
+ data_size,
+ message_counters_[session_id]++,
+ data));
raw_ford_messages_to_mobile_.PostMessage(
impl::RawFordMessageToMobile(ptr, is_final_message));
@@ -629,14 +717,19 @@ RESULT_CODE ProtocolHandlerImpl::SendSingleFrameMessage(
}
RESULT_CODE ProtocolHandlerImpl::SendMultiFrameMessage(
- const ConnectionID connection_id, const uint8_t session_id,
- const uint8_t protocol_version, const uint8_t service_type,
- const size_t data_size, const uint8_t *data,
- const size_t max_frame_size, const bool is_final_message) {
+ const ConnectionID connection_id,
+ const uint8_t session_id,
+ const uint8_t protocol_version,
+ const uint8_t service_type,
+ const size_t data_size,
+ const uint8_t* data,
+ const size_t max_frame_size,
+ const bool is_final_message) {
LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(
- logger_, " data size " << data_size << " max_frame_size " << max_frame_size);
+ LOG4CXX_DEBUG(logger_,
+ " data size " << data_size << " max_frame_size "
+ << max_frame_size);
// remainder of last frame
const size_t lastframe_remainder = data_size % max_frame_size;
@@ -645,13 +738,12 @@ RESULT_CODE ProtocolHandlerImpl::SendMultiFrameMessage(
lastframe_remainder > 0 ? lastframe_remainder : max_frame_size;
const size_t frames_count = data_size / max_frame_size +
- // add last frame if not empty
- (lastframe_remainder > 0 ? 1 : 0);
+ // add last frame if not empty
+ (lastframe_remainder > 0 ? 1 : 0);
- LOG4CXX_DEBUG(
- logger_,
- "Data " << data_size << " bytes in " << frames_count <<
- " frames with last frame size " << lastframe_size);
+ LOG4CXX_DEBUG(logger_,
+ "Data " << data_size << " bytes in " << frames_count
+ << " frames with last frame size " << lastframe_size);
DCHECK(max_frame_size >= FIRST_FRAME_DATA_SIZE);
DCHECK(FIRST_FRAME_DATA_SIZE >= 8);
@@ -666,13 +758,20 @@ RESULT_CODE ProtocolHandlerImpl::SendMultiFrameMessage(
out_data[6] = frames_count >> 8;
out_data[7] = frames_count;
- // TODO(EZamakhov): investigate message_id for CONSECUTIVE frames - APPLINK-9531
+ // TODO(EZamakhov): investigate message_id for CONSECUTIVE frames -
+ // APPLINK-9531
const uint8_t message_id = message_counters_[session_id]++;
const ProtocolFramePtr firstPacket(
- new protocol_handler::ProtocolPacket(
- connection_id, protocol_version, PROTECTION_OFF, FRAME_TYPE_FIRST,
- service_type, FRAME_DATA_FIRST, session_id, FIRST_FRAME_DATA_SIZE,
- message_id, out_data));
+ new protocol_handler::ProtocolPacket(connection_id,
+ protocol_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_FIRST,
+ service_type,
+ FRAME_DATA_FIRST,
+ session_id,
+ FIRST_FRAME_DATA_SIZE,
+ message_id,
+ out_data));
raw_ford_messages_to_mobile_.PostMessage(
impl::RawFordMessageToMobile(firstPacket, false));
@@ -681,41 +780,46 @@ RESULT_CODE ProtocolHandlerImpl::SendMultiFrameMessage(
for (uint32_t i = 0; i < frames_count; ++i) {
const bool is_last_frame = (i == (frames_count - 1));
const size_t frame_size = is_last_frame ? lastframe_size : max_frame_size;
- const uint8_t data_type =
- is_last_frame
- ? FRAME_DATA_LAST_CONSECUTIVE
- : (i % FRAME_DATA_MAX_CONSECUTIVE + 1);
+ const uint8_t data_type = is_last_frame
+ ? FRAME_DATA_LAST_CONSECUTIVE
+ : (i % FRAME_DATA_MAX_CONSECUTIVE + 1);
const bool is_final_packet = is_last_frame ? is_final_message : false;
- const ProtocolFramePtr ptr(new protocol_handler::ProtocolPacket(connection_id,
- protocol_version, PROTECTION_OFF, FRAME_TYPE_CONSECUTIVE,
- service_type, data_type, session_id, frame_size, message_id,
- data + max_frame_size * i));
+ const ProtocolFramePtr ptr(
+ new protocol_handler::ProtocolPacket(connection_id,
+ protocol_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONSECUTIVE,
+ service_type,
+ data_type,
+ session_id,
+ frame_size,
+ message_id,
+ data + max_frame_size * i));
raw_ford_messages_to_mobile_.PostMessage(
- impl::RawFordMessageToMobile(ptr, is_final_packet));
+ impl::RawFordMessageToMobile(ptr, is_final_packet));
LOG4CXX_DEBUG(logger_, '#' << i << " frame is sent.");
}
return RESULT_OK;
}
-RESULT_CODE ProtocolHandlerImpl::HandleMessage(ConnectionID connection_id,
- const ProtocolFramePtr packet) {
- LOG4CXX_AUTO_TRACE(logger_);
+RESULT_CODE ProtocolHandlerImpl::HandleMessage(const ProtocolFramePtr packet) {
+ DCHECK_OR_RETURN(packet, RESULT_UNKNOWN);
+ LOG4CXX_DEBUG(logger_, "Handling message " << packet);
switch (packet->frame_type()) {
case FRAME_TYPE_CONTROL:
- LOG4CXX_TRACE(logger_, "handleMessage() - case FRAME_TYPE_CONTROL");
- return HandleControlMessage(connection_id, packet);
+ LOG4CXX_TRACE(logger_, "FRAME_TYPE_CONTROL");
+ return HandleControlMessage(packet);
case FRAME_TYPE_SINGLE:
- LOG4CXX_TRACE(logger_, "handleMessage() - case FRAME_TYPE_SINGLE");
- return HandleSingleFrameMessage(connection_id, packet);
+ LOG4CXX_TRACE(logger_, "FRAME_TYPE_SINGLE");
+ return HandleSingleFrameMessage(packet);
case FRAME_TYPE_FIRST:
case FRAME_TYPE_CONSECUTIVE:
- LOG4CXX_TRACE(logger_, "handleMessage() - case FRAME_TYPE_FIRST or FRAME_TYPE_CONSECUTIVE");
- return HandleMultiFrameMessage(connection_id, packet);
+ LOG4CXX_TRACE(logger_, "FRAME_TYPE_FIRST or FRAME_TYPE_CONSECUTIVE");
+ return HandleMultiFrameMessage(packet);
default: {
- LOG4CXX_WARN(logger_, "handleMessage() - case unknown frame type"
- << packet->frame_type());
+ LOG4CXX_WARN(logger_, "Unknown frame type" << packet->frame_type());
return RESULT_FAIL;
}
}
@@ -723,42 +827,36 @@ RESULT_CODE ProtocolHandlerImpl::HandleMessage(ConnectionID connection_id,
}
RESULT_CODE ProtocolHandlerImpl::HandleSingleFrameMessage(
- ConnectionID connection_id, const ProtocolFramePtr packet) {
+ const ProtocolFramePtr packet) {
LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(logger_,
- "FRAME_TYPE_SINGLE message of size " << packet->data_size() << "; message "
- << ConvertPacketDataToString(packet->data(), packet->data_size()));
-
- if (!session_observer_) {
- LOG4CXX_ERROR(logger_,
- "Cannot handle message from Transport"
- << " Manager: ISessionObserver doesn't exist.");
- return RESULT_FAIL;
- }
-
- const uint32_t connection_key =
- session_observer_->KeyFromPair(connection_id, packet->session_id());
-
- const RawMessagePtr rawMessage(
- new RawMessage(connection_key,
- packet->protocol_version(),
- packet->data(),
- packet->total_data_bytes(),
- packet->service_type(),
- packet->payload_size()));
+ LOG4CXX_DEBUG(
+ logger_,
+ "FRAME_TYPE_SINGLE message of size "
+ << packet->data_size() << "; message "
+ << ConvertPacketDataToString(packet->data(), packet->data_size()));
+
+ const uint32_t connection_key = session_observer_.KeyFromPair(
+ packet->connection_id(), packet->session_id());
+
+ const RawMessagePtr rawMessage(new RawMessage(connection_key,
+ packet->protocol_version(),
+ packet->data(),
+ packet->total_data_bytes(),
+ packet->service_type(),
+ packet->payload_size()));
if (!rawMessage) {
return RESULT_FAIL;
}
-#ifdef TIME_TESTER
- if (metric_observer_) {
- PHMetricObserver::MessageMetric *metric
- = new PHMetricObserver::MessageMetric();
- metric->message_id = packet->message_id();
- metric->connection_key = connection_key;
- metric->raw_msg = rawMessage;
- metric_observer_->EndMessageProcess(metric);
- }
+#ifdef TELEMETRY_MONITOR
+ if (metric_observer_) {
+ PHTelemetryObserver::MessageMetric* metric =
+ new PHTelemetryObserver::MessageMetric();
+ metric->message_id = packet->message_id();
+ metric->connection_key = connection_key;
+ metric->raw_msg = rawMessage;
+ metric_observer_->EndMessageProcess(metric);
+ }
#endif
// TODO(EZamakhov): check service in session
@@ -767,133 +865,59 @@ RESULT_CODE ProtocolHandlerImpl::HandleSingleFrameMessage(
}
RESULT_CODE ProtocolHandlerImpl::HandleMultiFrameMessage(
- ConnectionID connection_id, const ProtocolFramePtr packet) {
+ const ProtocolFramePtr packet) {
LOG4CXX_AUTO_TRACE(logger_);
- if (!session_observer_) {
- LOG4CXX_ERROR(logger_, "No ISessionObserver set.");
- return RESULT_FAIL;
+ if (multiframe_builder_.AddFrame(packet) != RESULT_OK) {
+ LOG4CXX_WARN(logger_, "Frame assembling issue");
}
- const uint32_t key = session_observer_->KeyFromPair(connection_id,
- packet->session_id());
- LOG4CXX_DEBUG(
- logger_,
- "Packet " << packet << "; session id " << static_cast<int32_t>(key));
-
- if (packet->frame_type() == FRAME_TYPE_FIRST) {
- LOG4CXX_DEBUG(logger_, "handleMultiFrameMessage() - FRAME_TYPE_FIRST "
- << packet->data_size());
- incomplete_multi_frame_messages_[key] = packet;
- } else {
- LOG4CXX_DEBUG(logger_, "handleMultiFrameMessage() - Consecutive frame");
-
- std::map<int32_t, ProtocolFramePtr>::iterator it =
- incomplete_multi_frame_messages_.find(key);
-
- if (it == incomplete_multi_frame_messages_.end()) {
- LOG4CXX_ERROR(
- logger_, "Frame of multiframe message for non-existing session id");
- return RESULT_FAIL;
- }
-
- if (it->second->appendData(packet->data(), packet->data_size())
- != RESULT_OK) {
- LOG4CXX_ERROR(logger_,
- "Failed to append frame for multiframe message.");
- return RESULT_FAIL;
- }
-
- if (packet->frame_data() == FRAME_DATA_LAST_CONSECUTIVE) {
- LOG4CXX_DEBUG(
- logger_,
- "Last frame of multiframe message size " << packet->data_size()
- << "; connection key " << key);
- {
- sync_primitives::AutoLock lock(protocol_observers_lock_);
- if (protocol_observers_.empty()) {
- LOG4CXX_ERROR(
- logger_,
- "Cannot handle multiframe message: no IProtocolObserver is set.");
- return RESULT_FAIL;
- }
- }
-
- ProtocolFramePtr completePacket = it->second;
- const uint32_t connection_key =
- session_observer_->KeyFromPair(connection_id,
- completePacket->session_id());
- const RawMessagePtr rawMessage(
- new RawMessage(connection_key,
- completePacket->protocol_version(),
- completePacket->data(),
- completePacket->total_data_bytes(),
- completePacket->service_type(),
- completePacket->payload_size()));
-
- LOG4CXX_DEBUG(logger_,
- "total_data_bytes " << completePacket->total_data_bytes() <<
- " packet_size " << completePacket->packet_size() <<
- " data size " << completePacket->data_size() <<
- " payload_size " << completePacket->payload_size());
-
- if (!rawMessage) {
- return RESULT_FAIL;
- }
-
-#ifdef TIME_TESTER
- if (metric_observer_) {
- PHMetricObserver::MessageMetric *metric =
- new PHMetricObserver::MessageMetric();
- metric->raw_msg = rawMessage;
- metric_observer_->EndMessageProcess(metric);
- }
-#endif // TIME_TESTER
- // TODO(EZamakhov): check service in session
- NotifySubscribers(rawMessage);
-
- incomplete_multi_frame_messages_.erase(it);
- }
- }
return RESULT_OK;
}
RESULT_CODE ProtocolHandlerImpl::HandleControlMessage(
- ConnectionID connection_id, const ProtocolFramePtr packet) {
+ const ProtocolFramePtr packet) {
LOG4CXX_AUTO_TRACE(logger_);
- if (!session_observer_) {
- LOG4CXX_ERROR(logger_, "ISessionObserver is not set.");
- return RESULT_FAIL;
- }
-
+ // TODO{ALeshin}: Rename "Session" to "Service" on PH, CH, AM levels
switch (packet->frame_data()) {
- case FRAME_DATA_START_SERVICE:
- return HandleControlMessageStartSession(connection_id, *(packet.get()));
- case FRAME_DATA_END_SERVICE:
- return HandleControlMessageEndSession(connection_id, *(packet.get()));
+ case FRAME_DATA_START_SERVICE: {
+ LOG4CXX_TRACE(logger_, "FrameData: StartService");
+ return HandleControlMessageStartSession(*packet);
+ }
+ case FRAME_DATA_END_SERVICE: {
+ LOG4CXX_TRACE(logger_, "FrameData: StopService");
+ return HandleControlMessageEndSession(*packet);
+ }
+ case FRAME_DATA_END_SERVICE_ACK: {
+ LOG4CXX_TRACE(logger_, "FrameData: StopService ACK");
+ return HandleControlMessageEndServiceACK(*packet);
+ }
case FRAME_DATA_HEART_BEAT: {
- LOG4CXX_DEBUG(logger_,
- "Received heart beat for connection " << connection_id);
- return HandleControlMessageHeartBeat(connection_id, *(packet.get()));
+ LOG4CXX_TRACE(logger_, "FrameData: Heartbeat");
+ return HandleControlMessageHeartBeat(*packet);
}
case FRAME_DATA_HEART_BEAT_ACK: {
- LOG4CXX_DEBUG(logger_, "Received heart beat ack from mobile app"
- " for connection " << connection_id);
+ LOG4CXX_TRACE(logger_, "FrameData Heartbeat ACK");
+ LOG4CXX_DEBUG(logger_,
+ "Received Heartbeat ACK from mobile,"
+ " connection: "
+ << packet->connection_id());
return RESULT_OK;
}
default:
LOG4CXX_WARN(logger_,
- "Control message of type " << static_cast<int>(packet->frame_data())
- << " ignored");
+ "Control message of type "
+ << static_cast<int>(packet->frame_data()) << " ignored");
return RESULT_OK;
}
return RESULT_OK;
}
-uint32_t get_hash_id(const ProtocolPacket &packet) {
+uint32_t get_hash_id(const ProtocolPacket& packet) {
if (packet.protocol_version() < PROTOCOL_VERSION_2) {
- LOG4CXX_DEBUG(logger_, "Packet without hash data (protocol version less 2)");
+ LOG4CXX_DEBUG(logger_,
+ "Packet without hash data (protocol version less 2)");
return HASH_ID_NOT_SUPPORTED;
}
if (packet.data_size() < 4) {
@@ -907,30 +931,56 @@ uint32_t get_hash_id(const ProtocolPacket &packet) {
}
RESULT_CODE ProtocolHandlerImpl::HandleControlMessageEndSession(
- ConnectionID connection_id, const ProtocolPacket &packet) {
+ const ProtocolPacket& packet) {
LOG4CXX_AUTO_TRACE(logger_);
const uint8_t current_session_id = packet.session_id();
const uint32_t hash_id = get_hash_id(packet);
const ServiceType service_type = ServiceTypeFromByte(packet.service_type());
- const uint32_t session_key = session_observer_->OnSessionEndedCallback(
+ const ConnectionID connection_id = packet.connection_id();
+ const uint32_t session_key = session_observer_.OnSessionEndedCallback(
connection_id, current_session_id, hash_id, service_type);
// TODO(EZamakhov): add clean up output queue (for removed service)
if (session_key != 0) {
- SendEndSessionAck( connection_id, current_session_id,
- packet.protocol_version(), service_type);
+ SendEndSessionAck(connection_id,
+ current_session_id,
+ packet.protocol_version(),
+ service_type);
message_counters_.erase(current_session_id);
} else {
- LOG4CXX_WARN(
- logger_,
- "Refused to end session " << static_cast<int>(service_type) << " type.");
- SendEndSessionNAck(connection_id, current_session_id, packet.protocol_version(),
+ LOG4CXX_WARN(logger_,
+ "Refused to end session " << static_cast<int>(service_type)
+ << " type.");
+ SendEndSessionNAck(connection_id,
+ current_session_id,
+ packet.protocol_version(),
service_type);
}
return RESULT_OK;
}
+
+RESULT_CODE ProtocolHandlerImpl::HandleControlMessageEndServiceACK(
+ const ProtocolPacket& packet) {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ const uint8_t current_session_id = packet.session_id();
+ const uint32_t hash_id = get_hash_id(packet);
+ const ServiceType service_type = ServiceTypeFromByte(packet.service_type());
+ const ConnectionID connection_id = packet.connection_id();
+
+ const uint32_t session_key = session_observer_.OnSessionEndedCallback(
+ connection_id, current_session_id, hash_id, service_type);
+
+ if (0 == session_key) {
+ LOG4CXX_WARN(logger_, "Refused to end service");
+ return RESULT_FAIL;
+ }
+
+ return RESULT_OK;
+}
+
#ifdef ENABLE_SECURITY
namespace {
/**
@@ -939,95 +989,111 @@ namespace {
*/
class StartSessionHandler : public security_manager::SecurityManagerListener {
public:
- StartSessionHandler(
- uint32_t connection_key,
- ProtocolHandlerImpl *protocol_handler,
- SessionObserver *session_observer,
- ConnectionID connection_id,
- int32_t session_id,
- uint8_t protocol_version,
- uint32_t hash_id,
- ServiceType service_type)
- : connection_key_(connection_key),
- protocol_handler_(protocol_handler),
- session_observer_(session_observer),
- connection_id_(connection_id),
- session_id_(session_id),
- protocol_version_(protocol_version),
- hash_id_(hash_id),
- service_type_(service_type) {
- }
- bool OnHandshakeDone(const uint32_t connection_key, const bool success) OVERRIDE {
+ StartSessionHandler(uint32_t connection_key,
+ ProtocolHandlerImpl* protocol_handler,
+ SessionObserver& session_observer,
+ ConnectionID connection_id,
+ int32_t session_id,
+ uint8_t protocol_version,
+ uint32_t hash_id,
+ ServiceType service_type,
+ const std::vector<int>& force_protected_service)
+ : connection_key_(connection_key)
+ , protocol_handler_(protocol_handler)
+ , session_observer_(session_observer)
+ , connection_id_(connection_id)
+ , session_id_(session_id)
+ , protocol_version_(protocol_version)
+ , hash_id_(hash_id)
+ , service_type_(service_type)
+ , force_protected_service_(force_protected_service) {}
+
+ bool OnHandshakeDone(
+ const uint32_t connection_key,
+ security_manager::SSLContext::HandshakeResult result) OVERRIDE {
if (connection_key != connection_key_) {
return false;
}
+ const bool success =
+ result == security_manager::SSLContext::Handshake_Result_Success;
// check current service protection
const bool was_service_protection_enabled =
- session_observer_->GetSSLContext(connection_key_, service_type_) != NULL;
+ session_observer_.GetSSLContext(connection_key_, service_type_) != NULL;
if (was_service_protection_enabled) {
- // On Success handshake
- if (success) {
-// const std::string error_text("Connection is already protected");
-// LOG4CXX_WARN(logger_, error_text << ", key " << connection_key);
-// security_manager_->SendInternalError(
-// connection_key, security_manager::SecurityManager::ERROR_SERVICE_ALREADY_PROTECTED, error_text);
- protocol_handler_->SendStartSessionNAck(connection_id_, session_id_,
- protocol_version_, service_type_);
+ if (!success) {
+ protocol_handler_->SendStartSessionNAck(
+ connection_id_, session_id_, protocol_version_, service_type_);
} else {
// Could not be success handshake and not already protected service
NOTREACHED();
}
} else {
if (success) {
- session_observer_->SetProtectionFlag(connection_key_, service_type_);
+ session_observer_.SetProtectionFlag(connection_key_, service_type_);
}
- protocol_handler_->SendStartSessionAck(connection_id_, session_id_,
- protocol_version_, hash_id_, service_type_, success);
+ protocol_handler_->SendStartSessionAck(connection_id_,
+ session_id_,
+ protocol_version_,
+ hash_id_,
+ service_type_,
+ success);
}
delete this;
return true;
}
+ void OnCertificateUpdateRequired() OVERRIDE {}
+
+ virtual const std::vector<int>& force_protected_service() const {
+ return force_protected_service_;
+ }
+
private:
const uint32_t connection_key_;
- ProtocolHandlerImpl *protocol_handler_;
- SessionObserver *session_observer_;
+ ProtocolHandlerImpl* protocol_handler_;
+ SessionObserver& session_observer_;
const ConnectionID connection_id_;
const int32_t session_id_;
const uint8_t protocol_version_;
const uint32_t hash_id_;
const ServiceType service_type_;
+ const std::vector<int> force_protected_service_;
};
} // namespace
#endif // ENABLE_SECURITY
RESULT_CODE ProtocolHandlerImpl::HandleControlMessageStartSession(
- ConnectionID connection_id, const ProtocolPacket &packet) {
- LOG4CXX_DEBUG(logger_,
- "Protocol version: " <<
- static_cast<int>(packet.protocol_version()));
+ const ProtocolPacket& packet) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(
+ logger_,
+ "Protocol version:" << static_cast<int>(packet.protocol_version()));
const ServiceType service_type = ServiceTypeFromByte(packet.service_type());
const uint8_t protocol_version = packet.protocol_version();
#ifdef ENABLE_SECURITY
const bool protection =
// Protocolo version 1 is not support protection
- (protocol_version > PROTOCOL_VERSION_1) ? packet.protection_flag() : false;
+ (protocol_version > PROTOCOL_VERSION_1) ? packet.protection_flag()
+ : false;
#else
const bool protection = false;
#endif // ENABLE_SECURITY
- DCHECK(session_observer_);
uint32_t hash_id;
- const uint32_t session_id = session_observer_->OnSessionStartedCallback(
- connection_id, packet.session_id(), service_type, protection, &hash_id);
+ const ConnectionID connection_id = packet.connection_id();
+ const uint32_t session_id = session_observer_.OnSessionStartedCallback(
+ connection_id, packet.session_id(), service_type, protection, &hash_id);
if (0 == session_id) {
- LOG4CXX_WARN_EXT(logger_, "Refused to create service " <<
- static_cast<int32_t>(service_type) << " type.");
- SendStartSessionNAck(connection_id, packet.session_id(),
- protocol_version, packet.service_type());
+ LOG4CXX_WARN(logger_,
+ "Refused by session_observer to create service "
+ << static_cast<int32_t>(service_type) << " type.");
+ SendStartSessionNAck(connection_id,
+ packet.session_id(),
+ protocol_version,
+ packet.service_type());
return RESULT_OK;
}
@@ -1035,84 +1101,145 @@ RESULT_CODE ProtocolHandlerImpl::HandleControlMessageStartSession(
// for packet is encrypted and security plugin is enable
if (protection && security_manager_) {
const uint32_t connection_key =
- session_observer_->KeyFromPair(connection_id, session_id);
+ session_observer_.KeyFromPair(connection_id, session_id);
- security_manager::SSLContext *ssl_context =
+ security_manager::SSLContext* ssl_context =
security_manager_->CreateSSLContext(connection_key);
if (!ssl_context) {
const std::string error("CreateSSLContext failed");
LOG4CXX_ERROR(logger_, error);
security_manager_->SendInternalError(
- connection_key, security_manager::SecurityManager::ERROR_INTERNAL, error);
+ connection_key,
+ security_manager::SecurityManager::ERROR_INTERNAL,
+ error);
// Start service without protection
- SendStartSessionAck(connection_id, session_id, packet.protocol_version(),
- hash_id, packet.service_type(), PROTECTION_OFF);
+ SendStartSessionAck(connection_id,
+ session_id,
+ packet.protocol_version(),
+ hash_id,
+ packet.service_type(),
+ PROTECTION_OFF);
return RESULT_OK;
}
if (ssl_context->IsInitCompleted()) {
// mark service as protected
- session_observer_->SetProtectionFlag(connection_key, service_type);
+ session_observer_.SetProtectionFlag(connection_key, service_type);
// Start service as protected with current SSLContext
- SendStartSessionAck(connection_id, session_id, packet.protocol_version(),
- hash_id, packet.service_type(), PROTECTION_ON);
+ SendStartSessionAck(connection_id,
+ session_id,
+ packet.protocol_version(),
+ hash_id,
+ packet.service_type(),
+ PROTECTION_ON);
} else {
security_manager_->AddListener(
- new StartSessionHandler(
- connection_key, this, session_observer_,
- connection_id, session_id, packet.protocol_version(),
- hash_id, service_type));
+ new StartSessionHandler(connection_key,
+ this,
+ session_observer_,
+ connection_id,
+ session_id,
+ packet.protocol_version(),
+ hash_id,
+ service_type,
+ get_settings().force_protected_service()));
if (!ssl_context->IsHandshakePending()) {
// Start handshake process
security_manager_->StartHandshake(connection_key);
}
}
- LOG4CXX_DEBUG(logger_, "Protection establishing for connection "
- << connection_key << " is in progress");
+ LOG4CXX_DEBUG(logger_,
+ "Protection establishing for connection "
+ << connection_key << " is in progress");
return RESULT_OK;
}
#endif // ENABLE_SECURITY
// Start service without protection
- SendStartSessionAck(connection_id, session_id, packet.protocol_version(),
- hash_id, packet.service_type(), PROTECTION_OFF);
+ SendStartSessionAck(connection_id,
+ session_id,
+ packet.protocol_version(),
+ hash_id,
+ packet.service_type(),
+ PROTECTION_OFF);
return RESULT_OK;
}
RESULT_CODE ProtocolHandlerImpl::HandleControlMessageHeartBeat(
- ConnectionID connection_id, const ProtocolPacket &packet) {
- LOG4CXX_DEBUG(
- logger_,
- "Sending heart beat acknowledgment for connection " << connection_id);
+ const ProtocolPacket& packet) {
+ const ConnectionID connection_id = packet.connection_id();
+ LOG4CXX_DEBUG(logger_,
+ "Sending heart beat acknowledgment for connection "
+ << connection_id);
uint8_t protocol_version;
- if (session_observer_->ProtocolVersionUsed(
- connection_id, packet.session_id(), protocol_version)) {
+ if (session_observer_.ProtocolVersionUsed(
+ connection_id, packet.session_id(), protocol_version)) {
// TODO(EZamakhov): investigate message_id for HeartBeatAck
if (PROTOCOL_VERSION_3 == protocol_version ||
PROTOCOL_VERSION_4 == protocol_version) {
- return SendHeartBeatAck(connection_id, packet.session_id(),
- packet.message_id());
- }
- else {
+ return SendHeartBeatAck(
+ connection_id, packet.session_id(), packet.message_id());
+ } else {
LOG4CXX_WARN(logger_, "HeartBeat is not supported");
return RESULT_HEARTBEAT_IS_NOT_SUPPORTED;
}
} else {
- LOG4CXX_WARN(logger_, "SendHeartBeatAck is failed connection or session does not exist");
+ LOG4CXX_WARN(
+ logger_,
+ "SendHeartBeatAck is failed connection or session does not exist");
return RESULT_FAIL;
}
}
+void ProtocolHandlerImpl::PopValideAndExpirateMultiframes() {
+ const ProtocolFramePtrList& frame_list = multiframe_builder_.PopMultiframes();
+ for (ProtocolFramePtrList::const_iterator it = frame_list.begin();
+ it != frame_list.end();
+ ++it) {
+ const ProtocolFramePtr frame = *it;
+ DCHECK(frame);
+ if (!frame) {
+ continue;
+ }
+
+ const uint32_t connection_key = session_observer_.KeyFromPair(
+ frame->connection_id(), frame->session_id());
+ LOG4CXX_DEBUG(logger_,
+ "Result frame" << frame << "for connection "
+ << connection_key);
+ const RawMessagePtr rawMessage(new RawMessage(connection_key,
+ frame->protocol_version(),
+ frame->data(),
+ frame->total_data_bytes(),
+ frame->service_type(),
+ frame->payload_size()));
+ DCHECK(rawMessage);
+
+#ifdef TELEMETRY_MONITOR
+ if (metric_observer_) {
+ PHTelemetryObserver::MessageMetric* metric =
+ new PHTelemetryObserver::MessageMetric();
+ metric->raw_msg = rawMessage;
+ metric_observer_->EndMessageProcess(metric);
+ }
+#endif // TELEMETRY_MONITOR
+ NotifySubscribers(rawMessage);
+ }
+}
+
bool ProtocolHandlerImpl::TrackMessage(const uint32_t& connection_key) {
LOG4CXX_AUTO_TRACE(logger_);
- if (message_frequency_time_ > 0u &&
- message_max_frequency_ > 0u) {
- const size_t message_frequency = message_meter_.TrackMessage(connection_key);
- LOG4CXX_DEBUG(logger_, "Frequency of " << connection_key << " is " << message_frequency);
- if (message_frequency > message_max_frequency_) {
- LOG4CXX_WARN(logger_, "Frequency of " << connection_key << " is marked as high.");
- if (session_observer_) {
- session_observer_->OnApplicationFloodCallBack(connection_key);
- }
+ const size_t& frequency_time = get_settings().message_frequency_time();
+ const size_t& frequency_count = get_settings().message_frequency_count();
+ if (frequency_time > 0u && frequency_count > 0u) {
+ const size_t message_frequency =
+ message_meter_.TrackMessage(connection_key);
+ LOG4CXX_DEBUG(logger_,
+ "Frequency of " << connection_key << " is "
+ << message_frequency);
+ if (message_frequency > frequency_count) {
+ LOG4CXX_WARN(logger_,
+ "Frequency of " << connection_key << " is marked as high.");
+ session_observer_.OnApplicationFloodCallBack(connection_key);
message_meter_.RemoveIdentifier(connection_key);
return true;
}
@@ -1120,22 +1247,24 @@ bool ProtocolHandlerImpl::TrackMessage(const uint32_t& connection_key) {
return false;
}
-bool ProtocolHandlerImpl::TrackMalformedMessage(const uint32_t &connection_key,
+bool ProtocolHandlerImpl::TrackMalformedMessage(const uint32_t& connection_key,
const size_t count) {
+ const size_t& malformed_frequency_count =
+ get_settings().malformed_frequency_count();
LOG4CXX_AUTO_TRACE(logger_);
- if (malformed_message_frequency_time_ > 0u &&
- malformed_message_max_frequency_ > 0u) {
+ if (get_settings().malformed_frequency_time() > 0u &&
+ malformed_frequency_count > 0u) {
const size_t malformed_message_frequency =
malformed_message_meter_.TrackMessages(connection_key, count);
- LOG4CXX_DEBUG(logger_, "Malformed frequency of " << connection_key
- << " is " << malformed_message_frequency);
- if (!malformed_message_filtering_ ||
- malformed_message_frequency > malformed_message_max_frequency_) {
- LOG4CXX_WARN(logger_, "Malformed frequency of " << connection_key
- << " is marked as high.");
- if (session_observer_) {
- session_observer_->OnMalformedMessageCallback(connection_key);
- }
+ LOG4CXX_DEBUG(logger_,
+ "Malformed frequency of " << connection_key << " is "
+ << malformed_message_frequency);
+ if (!get_settings().malformed_message_filtering() ||
+ malformed_message_frequency > malformed_frequency_count) {
+ LOG4CXX_WARN(logger_,
+ "Malformed frequency of " << connection_key
+ << " is marked as high.");
+ session_observer_.OnMalformedMessageCallback(connection_key);
malformed_message_meter_.RemoveIdentifier(connection_key);
return true;
}
@@ -1143,45 +1272,36 @@ bool ProtocolHandlerImpl::TrackMalformedMessage(const uint32_t &connection_key,
return false;
}
-void ProtocolHandlerImpl::Handle(
- const impl::RawFordMessageFromMobile message) {
+void ProtocolHandlerImpl::Handle(const impl::RawFordMessageFromMobile message) {
LOG4CXX_AUTO_TRACE(logger_);
- if (NULL == session_observer_) {
- LOG4CXX_WARN(logger_, "Session Observer is NULL");
- return;
- }
-
switch (message->service_type()) {
case kMobileNav:
case kAudio:
break;
default: {
- const uint32_t connection_key = session_observer_->KeyFromPair(
- message->connection_id(), message->session_id());
- if (TrackMessage(connection_key)) {
- return;
- }
+ const uint32_t connection_key = session_observer_.KeyFromPair(
+ message->connection_id(), message->session_id());
+ if (TrackMessage(connection_key)) {
+ return;
}
- break;
+ } break;
}
-
- connection_handler::ConnectionHandlerImpl *connection_handler =
- connection_handler::ConnectionHandlerImpl::instance();
LOG4CXX_DEBUG(logger_, "Message : " << message.get());
const uint8_t c_id = message->connection_id();
const uint32_t m_id = message->session_id();
- if (session_observer_->IsHeartBeatSupported(c_id, m_id)) {
- connection_handler->KeepConnectionAlive(c_id, m_id);
+ if (session_observer_.IsHeartBeatSupported(c_id, m_id)) {
+ connection_handler_.KeepConnectionAlive(c_id, m_id);
}
// TODO(EZamakhov): remove dublication of IncomingDataHandler logic
if (((0 != message->data()) && (0 != message->data_size())) ||
FRAME_TYPE_CONTROL == message->frame_type() ||
FRAME_TYPE_FIRST == message->frame_type()) {
- LOG4CXX_DEBUG(logger_, "Packet: dataSize " << message->data_size());
- HandleMessage(message->connection_id(), message);
+ LOG4CXX_DEBUG(logger_, "Packet: dataSize " << message->data_size());
+ HandleMessage(message);
+ PopValideAndExpirateMultiframes();
} else {
LOG4CXX_WARN(logger_,
"handleMessagesFromMobileApp() - incorrect or NULL data");
@@ -1189,17 +1309,18 @@ void ProtocolHandlerImpl::Handle(
}
void ProtocolHandlerImpl::Handle(const impl::RawFordMessageToMobile message) {
- LOG4CXX_DEBUG(
- logger_,
- "Message to mobile app: connection id " <<
- static_cast<int>(message->connection_id()) << ";"
- " dataSize: " << message->data_size() << " ;"
- " protocolVersion " << static_cast<int>(message->protocol_version()));
+ LOG4CXX_DEBUG(logger_,
+ "Message to mobile app: connection id "
+ << static_cast<int>(message->connection_id())
+ << ";"
+ " dataSize: " << message->data_size()
+ << " ;"
+ " protocolVersion "
+ << static_cast<int>(message->protocol_version()));
if (message.is_final) {
- sessions_last_message_id_.insert(
- std::pair<uint8_t, uint32_t>(message->session_id(),
- message->message_id()));
+ sessions_last_message_id_.insert(std::pair<uint8_t, uint32_t>(
+ message->session_id(), message->message_id()));
}
SendFrame(message);
@@ -1224,40 +1345,40 @@ RESULT_CODE ProtocolHandlerImpl::EncryptFrame(ProtocolFramePtr packet) {
DCHECK(packet);
// Control frames and data over control service shall be unprotected
if (packet->service_type() == kControl ||
- packet->frame_type() == FRAME_TYPE_CONTROL) {
+ packet->frame_type() == FRAME_TYPE_CONTROL) {
return RESULT_OK;
}
- if (!session_observer_) {
- LOG4CXX_WARN(logger_, "No session_observer_ set.");
- return RESULT_FAIL;
- }
if (!security_manager_) {
LOG4CXX_WARN(logger_, "No security_manager_ set.");
return RESULT_FAIL;
}
- const uint32_t connection_key = session_observer_->KeyFromPair(
- packet->connection_id(), packet->session_id());
- security_manager::SSLContext *context = session_observer_->GetSSLContext(
- connection_key, ServiceTypeFromByte(packet->service_type()));
+ const uint32_t connection_key = session_observer_.KeyFromPair(
+ packet->connection_id(), packet->session_id());
+ security_manager::SSLContext* context = session_observer_.GetSSLContext(
+ connection_key, ServiceTypeFromByte(packet->service_type()));
if (!context || !context->IsInitCompleted()) {
return RESULT_OK;
}
- const uint8_t *out_data;
+ const uint8_t* out_data;
size_t out_data_size;
- if (!context->Encrypt(packet->data(), packet->data_size(),
- &out_data, &out_data_size)) {
+ if (!context->Encrypt(
+ packet->data(), packet->data_size(), &out_data, &out_data_size)) {
const std::string error_text(context->LastError());
LOG4CXX_ERROR(logger_, "Enryption failed: " << error_text);
- security_manager_->SendInternalError(connection_key,
- security_manager::SecurityManager::ERROR_ENCRYPTION_FAILED, error_text);
+ security_manager_->SendInternalError(
+ connection_key,
+ security_manager::SecurityManager::ERROR_ENCRYPTION_FAILED,
+ error_text);
// Close session to prevent usage unprotected service/session
- session_observer_->OnSessionEndedCallback(
- packet->connection_id(), packet->session_id(),
- packet->message_id(), kRpc);
+ session_observer_.OnSessionEndedCallback(packet->connection_id(),
+ packet->session_id(),
+ packet->message_id(),
+ kRpc);
return RESULT_OK;
- };
- LOG4CXX_DEBUG(logger_, "Encrypted " << packet->data_size() << " bytes to "
- << out_data_size << " bytes");
+ }
+ LOG4CXX_DEBUG(logger_,
+ "Encrypted " << packet->data_size() << " bytes to "
+ << out_data_size << " bytes");
DCHECK(out_data);
DCHECK(out_data_size);
packet->set_protection_flag(true);
@@ -1268,46 +1389,49 @@ RESULT_CODE ProtocolHandlerImpl::EncryptFrame(ProtocolFramePtr packet) {
RESULT_CODE ProtocolHandlerImpl::DecryptFrame(ProtocolFramePtr packet) {
DCHECK(packet);
if (!packet->protection_flag() ||
- // Control frames and data over control service shall be unprotected
- packet->service_type() == kControl ||
- packet->frame_type() == FRAME_TYPE_CONTROL) {
+ // Control frames and data over control service shall be unprotected
+ packet->service_type() == kControl ||
+ packet->frame_type() == FRAME_TYPE_CONTROL) {
return RESULT_OK;
}
- if (!session_observer_) {
- LOG4CXX_WARN(logger_, "No session_observer_ set.");
- return RESULT_FAIL;
- }
if (!security_manager_) {
LOG4CXX_WARN(logger_, "No security_manager_ set.");
return RESULT_FAIL;
}
- const uint32_t connection_key = session_observer_->KeyFromPair(
- packet->connection_id(), packet->session_id());
- security_manager::SSLContext *context = session_observer_->GetSSLContext(
- connection_key, ServiceTypeFromByte(packet->service_type()));
+ const uint32_t connection_key = session_observer_.KeyFromPair(
+ packet->connection_id(), packet->session_id());
+ security_manager::SSLContext* context = session_observer_.GetSSLContext(
+ connection_key, ServiceTypeFromByte(packet->service_type()));
if (!context || !context->IsInitCompleted()) {
const std::string error_text("Fail decryption for unprotected service ");
- LOG4CXX_ERROR(logger_, error_text << static_cast<int>(packet->service_type()));
- security_manager_->SendInternalError(connection_key,
- security_manager::SecurityManager::ERROR_SERVICE_NOT_PROTECTED, error_text);
+ LOG4CXX_ERROR(logger_,
+ error_text << static_cast<int>(packet->service_type()));
+ security_manager_->SendInternalError(
+ connection_key,
+ security_manager::SecurityManager::ERROR_SERVICE_NOT_PROTECTED,
+ error_text);
return RESULT_ENCRYPTION_FAILED;
}
- const uint8_t *out_data;
+ const uint8_t* out_data;
size_t out_data_size;
- if (!context->Decrypt(packet->data(), packet->data_size(),
- &out_data, &out_data_size)) {
+ if (!context->Decrypt(
+ packet->data(), packet->data_size(), &out_data, &out_data_size)) {
const std::string error_text(context->LastError());
LOG4CXX_ERROR(logger_, "Decryption failed: " << error_text);
- security_manager_->SendInternalError(connection_key,
- security_manager::SecurityManager::ERROR_DECRYPTION_FAILED, error_text);
+ security_manager_->SendInternalError(
+ connection_key,
+ security_manager::SecurityManager::ERROR_DECRYPTION_FAILED,
+ error_text);
// Close session to prevent usage unprotected service/session
- session_observer_->OnSessionEndedCallback(
- packet->connection_id(), packet->session_id(),
- packet->message_id(), kRpc);
+ session_observer_.OnSessionEndedCallback(packet->connection_id(),
+ packet->session_id(),
+ packet->message_id(),
+ kRpc);
return RESULT_ENCRYPTION_FAILED;
- };
- LOG4CXX_DEBUG(logger_, "Decrypted " << packet->data_size() << " bytes to "
- << out_data_size << " bytes");
+ }
+ LOG4CXX_DEBUG(logger_,
+ "Decrypted " << packet->data_size() << " bytes to "
+ << out_data_size << " bytes");
DCHECK(out_data);
DCHECK(out_data_size);
packet->set_data(out_data, out_data_size);
@@ -1317,48 +1441,56 @@ RESULT_CODE ProtocolHandlerImpl::DecryptFrame(ProtocolFramePtr packet) {
void ProtocolHandlerImpl::SendFramesNumber(uint32_t connection_key,
int32_t number_of_frames) {
- LOG4CXX_DEBUG(logger_,
- "SendFramesNumber MobileNaviAck for session " << connection_key);
+ LOG4CXX_DEBUG(
+ logger_, "SendFramesNumber MobileNaviAck for session " << connection_key);
- // TODO(EZamakhov): add protocol version check - to avoid send for PROTOCOL_VERSION_1
+ // TODO(EZamakhov): add protocol version check - to avoid send for
+ // PROTOCOL_VERSION_1
transport_manager::ConnectionUID connection_id = 0;
uint8_t session_id = 0;
- session_observer_->PairFromKey(connection_key, &connection_id, &session_id);
+ session_observer_.PairFromKey(connection_key, &connection_id, &session_id);
uint8_t protocol_version;
- if (session_observer_->ProtocolVersionUsed(connection_id, session_id,
- protocol_version)) {
- ProtocolFramePtr ptr(new protocol_handler::ProtocolPacket(connection_id,
- protocol_version, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- SERVICE_TYPE_NAVI, FRAME_DATA_SERVICE_DATA_ACK,
- session_id, 0, message_counters_[session_id]++));
+ if (session_observer_.ProtocolVersionUsed(
+ connection_id, session_id, protocol_version)) {
+ ProtocolFramePtr ptr(
+ new protocol_handler::ProtocolPacket(connection_id,
+ protocol_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ SERVICE_TYPE_NAVI,
+ FRAME_DATA_SERVICE_DATA_ACK,
+ session_id,
+ 0,
+ message_counters_[session_id]++));
// Flow control data shall be 4 bytes according Ford Protocol
DCHECK(sizeof(number_of_frames) == 4);
number_of_frames = LE_TO_BE32(number_of_frames);
ptr->set_data(reinterpret_cast<const uint8_t*>(&number_of_frames),
- sizeof(number_of_frames));
- raw_ford_messages_to_mobile_.PostMessage(
- impl::RawFordMessageToMobile(ptr, false));
- LOG4CXX_DEBUG(logger_, "SendFramesNumber finished successfully");
+ sizeof(number_of_frames));
+ raw_ford_messages_to_mobile_.PostMessage(
+ impl::RawFordMessageToMobile(ptr, false));
+ LOG4CXX_DEBUG(logger_, "SendFramesNumber finished successfully");
} else {
- LOG4CXX_WARN(logger_, "SendFramesNumber is failed connection or session does not exist");
+ LOG4CXX_WARN(
+ logger_,
+ "SendFramesNumber is failed connection or session does not exist");
}
-
}
-#ifdef TIME_TESTER
-void ProtocolHandlerImpl::SetTimeMetricObserver(PHMetricObserver *observer) {
+#ifdef TELEMETRY_MONITOR
+void ProtocolHandlerImpl::SetTelemetryObserver(PHTelemetryObserver* observer) {
metric_observer_ = observer;
}
-#endif // TIME_TESTER
+#endif // TELEMETRY_MONITOR
-std::string ConvertPacketDataToString(const uint8_t *data,
+std::string ConvertPacketDataToString(const uint8_t* data,
const size_t data_size) {
if (0 == data_size)
return std::string();
bool is_printable_array = true;
std::locale loc;
- const char *text = reinterpret_cast<const char*>(data);
+ const char* text = reinterpret_cast<const char*>(data);
// Check data for printability
for (size_t i = 0; i < data_size; ++i) {
if (!std::isprint(text[i], loc)) {
@@ -1366,15 +1498,16 @@ std::string ConvertPacketDataToString(const uint8_t *data,
break;
}
}
- return is_printable_array ? std::string(text, data_size) : std::string("is raw data");
+ return is_printable_array ? std::string(text, data_size)
+ : std::string("is raw data");
}
-uint8_t SupportedSDLProtocolVersion() {
+uint8_t ProtocolHandlerImpl::SupportedSDLProtocolVersion() const {
LOG4CXX_AUTO_TRACE(logger_);
- bool heart_beat_support =
- (0 != profile::Profile::instance()->heart_beat_timeout());
- bool sdl4_support = profile::Profile::instance()->enable_protocol_4();
+ bool heart_beat_support = (0 != get_settings().heart_beat_timeout());
+
+ bool sdl4_support = get_settings().enable_protocol_4();
if (sdl4_support) {
return PROTOCOL_VERSION_4;
diff --git a/src/components/protocol_handler/src/protocol_packet.cc b/src/components/protocol_handler/src/protocol_packet.cc
index a31678ec6e..d766cf18c4 100644
--- a/src/components/protocol_handler/src/protocol_packet.cc
+++ b/src/components/protocol_handler/src/protocol_packet.cc
@@ -33,6 +33,7 @@
#include <stdint.h>
#include <memory.h>
#include <new>
+#include <memory>
#include <cstring>
#include <limits>
@@ -43,50 +44,58 @@
namespace protocol_handler {
-ProtocolPacket::ProtocolData::ProtocolData()
- : data(NULL), totalDataBytes(0u) { }
+CREATE_LOGGERPTR_GLOBAL(logger_, "ProtocolHandler")
+
+ProtocolPacket::ProtocolData::ProtocolData() : data(NULL), totalDataBytes(0u) {}
ProtocolPacket::ProtocolData::~ProtocolData() {
delete[] data;
}
ProtocolPacket::ProtocolHeader::ProtocolHeader()
- : version(0x00),
- protection_flag(PROTECTION_OFF),
- frameType(0x00),
- serviceType(0x00),
- frameData(0x00),
- sessionId(0x00),
- dataSize(0x00),
- messageId(0x00) {
-}
-
-ProtocolPacket::ProtocolHeader::ProtocolHeader(
- uint8_t version, bool protection, uint8_t frameType, uint8_t serviceType,
- uint8_t frameData, uint8_t sessionID, uint32_t dataSize, uint32_t messageID)
- : version(version),
- protection_flag(protection),
- frameType(frameType),
- serviceType(serviceType),
- frameData(frameData),
- sessionId(sessionID),
- dataSize(dataSize),
- messageId(messageID) {
-}
+ : version(0x00)
+ , protection_flag(PROTECTION_OFF)
+ , frameType(0x00)
+ , serviceType(0x00)
+ , frameData(0x00)
+ , sessionId(0x00)
+ , dataSize(0x00)
+ , messageId(0x00) {}
+
+ProtocolPacket::ProtocolHeader::ProtocolHeader(uint8_t version,
+ bool protection,
+ uint8_t frameType,
+ uint8_t serviceType,
+ uint8_t frameData,
+ uint8_t sessionID,
+ uint32_t dataSize,
+ uint32_t messageID)
+ : version(version)
+ , protection_flag(protection)
+ , frameType(frameType)
+ , serviceType(serviceType)
+ , frameData(frameData)
+ , sessionId(sessionID)
+ , dataSize(dataSize)
+ , messageId(messageID) {}
inline uint32_t read_be_uint32(const uint8_t* const data) {
// Int value read byte per byte
// reintercast for non-4 byte address alignment lead to UB on arm platform
uint32_t value = data[3];
- value += (data[2] << 8);
+ value += (data[2] << 8);
value += (data[1] << 16);
value += (data[0] << 24);
return value;
}
-void ProtocolPacket::ProtocolHeader::deserialize(
- const uint8_t* message, const size_t messageSize) {
+void ProtocolPacket::ProtocolHeader::deserialize(const uint8_t* message,
+ const size_t messageSize) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(message);
if (messageSize < PROTOCOL_HEADER_V1_SIZE) {
+ LOG4CXX_DEBUG(logger_,
+ "Message size less " << PROTOCOL_HEADER_V1_SIZE << " bytes");
return;
}
// first 4 bits
@@ -97,33 +106,36 @@ void ProtocolPacket::ProtocolHeader::deserialize(
frameType = message[0] & 0x07u;
serviceType = message[1];
- frameData = message[2];
- sessionId = message[3];
+ frameData = message[2];
+ sessionId = message[3];
// FIXME(EZamakhov): usage for FirstFrame message
dataSize = read_be_uint32(message + 4);
switch (version) {
case PROTOCOL_VERSION_2:
case PROTOCOL_VERSION_3:
- case PROTOCOL_VERSION_4:{
- if (messageSize < PROTOCOL_HEADER_V2_SIZE) {
- return;
- }
- messageId = read_be_uint32(message + 8);
+ case PROTOCOL_VERSION_4: {
+ if (messageSize < PROTOCOL_HEADER_V2_SIZE) {
+ LOG4CXX_DEBUG(logger_,
+ "Message size less " << PROTOCOL_HEADER_V2_SIZE
+ << " bytes");
+ return;
}
- break;
+ messageId = read_be_uint32(message + 8);
+ } break;
default:
+ LOG4CXX_WARN(logger_, "Unknown version:" << static_cast<int>(version));
messageId = 0;
break;
}
}
ProtocolPacket::ProtocolHeaderValidator::ProtocolHeaderValidator()
- : max_payload_size_(std::numeric_limits<size_t>::max()) {
-}
+ : max_payload_size_(std::numeric_limits<size_t>::max()) {}
void ProtocolPacket::ProtocolHeaderValidator::set_max_payload_size(
const size_t max_payload_size) {
+ LOG4CXX_DEBUG(logger_, "New maximum payload size is " << max_payload_size);
max_payload_size_ = max_payload_size;
}
@@ -133,6 +145,7 @@ size_t ProtocolPacket::ProtocolHeaderValidator::max_payload_size() const {
RESULT_CODE ProtocolPacket::ProtocolHeaderValidator::validate(
const ProtocolHeader& header) const {
+ LOG4CXX_DEBUG(logger_, "Validating header - " << header);
// expected payload size will be calculated depending
// on used protocol version
size_t payload_size = MAXIMUM_FRAME_DATA_V2_SIZE;
@@ -143,45 +156,63 @@ RESULT_CODE ProtocolPacket::ProtocolHeaderValidator::validate(
break;
case PROTOCOL_VERSION_3:
case PROTOCOL_VERSION_4:
- payload_size = max_payload_size_ > MAXIMUM_FRAME_DATA_V2_SIZE ?
- max_payload_size_ : MAXIMUM_FRAME_DATA_V2_SIZE;
+ payload_size = max_payload_size_ > MAXIMUM_FRAME_DATA_V2_SIZE
+ ? max_payload_size_
+ : MAXIMUM_FRAME_DATA_V2_SIZE;
break;
default:
+ LOG4CXX_WARN(logger_,
+ "Unknown version:" << static_cast<int>(header.version));
return RESULT_FAIL;
}
- // ServiceType shall be equal 0x0 (Control), 0x07 (RPC), 0x0A (PCM), 0x0B (Video), 0x0F (Bulk)
+ // ServiceType shall be equal 0x0 (Control), 0x07 (RPC), 0x0A (PCM), 0x0B
+ // (Video), 0x0F (Bulk)
if (ServiceTypeFromByte(header.serviceType) == kInvalidServiceType) {
+ LOG4CXX_WARN(logger_,
+ "Invalide service type"
+ << static_cast<int>(header.serviceType));
return RESULT_FAIL;
}
// Check frame info for each frame type
- // Frame type shall be 0x00 (Control), 0x01 (Single), 0x02 (First), 0x03 (Consecutive)
- // For Control frames Frame info value shall be from 0x00 to 0x06 or 0xFE(Data Ack), 0xFF(HB Ack)
+ // Frame type shall be 0x00 (Control), 0x01 (Single), 0x02 (First), 0x03
+ // (Consecutive)
+ // For Control frames Frame info value shall be from 0x00 to 0x06 or 0xFE(Data
+ // Ack), 0xFF(HB Ack)
// For Single and First frames Frame info value shall be equal 0x00
switch (header.frameType) {
- case FRAME_TYPE_CONTROL : {
- switch (header.frameData) {
- case FRAME_DATA_HEART_BEAT:
- case FRAME_DATA_START_SERVICE:
- case FRAME_DATA_START_SERVICE_ACK:
- case FRAME_DATA_START_SERVICE_NACK:
- case FRAME_DATA_END_SERVICE:
- case FRAME_DATA_END_SERVICE_ACK:
- case FRAME_DATA_END_SERVICE_NACK:
- case FRAME_DATA_SERVICE_DATA_ACK:
- case FRAME_DATA_HEART_BEAT_ACK:
- break;
- default:
- return RESULT_FAIL;
- }
- break;
+ case FRAME_TYPE_CONTROL: {
+ switch (header.frameData) {
+ case FRAME_DATA_HEART_BEAT:
+ case FRAME_DATA_START_SERVICE:
+ case FRAME_DATA_START_SERVICE_ACK:
+ case FRAME_DATA_START_SERVICE_NACK:
+ case FRAME_DATA_END_SERVICE:
+ case FRAME_DATA_END_SERVICE_ACK:
+ case FRAME_DATA_END_SERVICE_NACK:
+ case FRAME_DATA_SERVICE_DATA_ACK:
+ case FRAME_DATA_HEART_BEAT_ACK:
+ break;
+ default:
+ LOG4CXX_WARN(logger_,
+ "FRAME_TYPE_CONTROL - Invalide frame data "
+ << static_cast<int>(header.frameData));
+ return RESULT_FAIL;
}
+ break;
+ }
case FRAME_TYPE_SINGLE:
if (header.frameData != FRAME_DATA_SINGLE) {
+ LOG4CXX_WARN(logger_,
+ "FRAME_TYPE_SINGLE - Invalide frame data "
+ << static_cast<int>(header.frameData));
return RESULT_FAIL;
}
break;
case FRAME_TYPE_FIRST:
if (header.frameData != FRAME_DATA_FIRST) {
+ LOG4CXX_WARN(logger_,
+ "FRAME_TYPE_FIRST - Invalide frame data "
+ << static_cast<int>(header.frameData));
return RESULT_FAIL;
}
break;
@@ -189,6 +220,8 @@ RESULT_CODE ProtocolPacket::ProtocolHeaderValidator::validate(
// Could have any FrameInfo value
break;
default:
+ LOG4CXX_WARN(logger_,
+ "Unknown frame type " << static_cast<int>(header.frameType));
// All other Frame type is invalid
return RESULT_FAIL;
}
@@ -196,56 +229,75 @@ RESULT_CODE ProtocolPacket::ProtocolHeaderValidator::validate(
// For Single and Consecutive Data Size value shall be greater than 0x00
// and shall be less than payload size
if (header.dataSize > payload_size) {
+ LOG4CXX_WARN(logger_,
+ "Packet data size is "
+ << header.dataSize
+ << " and bigger than allowed payload size " << payload_size
+ << " bytes");
return RESULT_FAIL;
}
switch (header.frameType) {
case FRAME_TYPE_SINGLE:
case FRAME_TYPE_CONSECUTIVE:
- if (header.dataSize <= 0) {
+ if (header.dataSize <= 0u) {
+ LOG4CXX_WARN(logger_,
+ "Data size of Single and Consecutive frame shall be not "
+ "equal 0 byte ");
return RESULT_FAIL;
}
break;
default:
break;
}
- // Message ID be equal or greater than 0x01 (not actual for 1 protocol version and Control frames)
- if (FRAME_TYPE_CONTROL != header.frameType && PROTOCOL_VERSION_1 != header.version
- && header.messageId <= 0) {
- // Message ID shall be greater than 0x00, but not implemented in SPT
- // TODO(EZamakhov): return on fix on mobile side - APPLINK-9990
- return RESULT_FAIL;
+ // Message ID be equal or greater than 0x01 (not actual for 1 protocol version
+ // and Control frames)
+ if (header.messageId <= 0) {
+ if (FRAME_TYPE_CONTROL != header.frameType &&
+ PROTOCOL_VERSION_1 != header.version) {
+ LOG4CXX_WARN(logger_, "Message ID shall be greater than 0x00");
+ // Message ID shall be greater than 0x00, but not implemented in SPT
+ return RESULT_FAIL;
+ }
}
+ LOG4CXX_DEBUG(logger_, "Message header is completely correct.");
return RESULT_OK;
}
-ProtocolPacket::ProtocolPacket()
- : payload_size_(0), connection_id_(0) {
-}
+ProtocolPacket::ProtocolPacket() : payload_size_(0u), connection_id_(0u) {}
ProtocolPacket::ProtocolPacket(ConnectionID connection_id,
- uint8_t version, bool protection,
+ uint8_t version,
+ bool protection,
uint8_t frameType,
uint8_t serviceType,
- uint8_t frameData, uint8_t sessionID,
- uint32_t dataSize, uint32_t messageID,
- const uint8_t *data)
- : packet_header_(version, protection, frameType, serviceType,
- frameData, sessionID, dataSize, messageID),
- packet_data_(),
- payload_size_(0),
- connection_id_(connection_id) {
+ uint8_t frameData,
+ uint8_t sessionID,
+ uint32_t dataSize,
+ uint32_t messageID,
+ const uint8_t* data)
+ : packet_header_(version,
+ protection,
+ frameType,
+ serviceType,
+ frameData,
+ sessionID,
+ dataSize,
+ messageID)
+ , packet_data_()
+ , payload_size_(0)
+ , connection_id_(connection_id) {
set_data(data, dataSize);
}
ProtocolPacket::ProtocolPacket(ConnectionID connection_id)
- : packet_header_(),
- packet_data_(),
- payload_size_(0),
- connection_id_(connection_id) {
-}
+ : packet_header_()
+ , packet_data_()
+ , payload_size_(0)
+ , connection_id_(connection_id) {}
// Serialization
RawMessagePtr ProtocolPacket::serializePacket() const {
+ LOG4CXX_AUTO_TRACE(logger_);
// TODO(EZamakhov): Move header serialization to ProtocolHeader
// version is low byte
const uint8_t version_byte = packet_header_.version << 4;
@@ -271,11 +323,12 @@ RawMessagePtr ProtocolPacket::serializePacket() const {
header[offset++] = packet_header_.messageId >> 16;
header[offset++] = packet_header_.messageId >> 8;
header[offset++] = packet_header_.messageId;
- };
+ }
- size_t total_packet_size = offset + (packet_data_.data ? packet_data_.totalDataBytes : 0);
+ size_t total_packet_size =
+ offset + (packet_data_.data ? packet_data_.totalDataBytes : 0);
- uint8_t *packet = new (std::nothrow) uint8_t[total_packet_size];
+ uint8_t* packet = new (std::nothrow) uint8_t[total_packet_size];
if (!packet) {
return RawMessagePtr();
}
@@ -285,16 +338,17 @@ RawMessagePtr ProtocolPacket::serializePacket() const {
memcpy(packet + offset, packet_data_.data, packet_data_.totalDataBytes);
}
- const RawMessagePtr out_message(
- new RawMessage(
- connection_id(), packet_header_.version,
- packet, total_packet_size, packet_header_.serviceType) );
+ const RawMessagePtr out_message(new RawMessage(connection_id(),
+ packet_header_.version,
+ packet,
+ total_packet_size,
+ packet_header_.serviceType));
delete[] packet;
return out_message;
}
-RESULT_CODE ProtocolPacket::appendData(uint8_t *chunkData,
+RESULT_CODE ProtocolPacket::appendData(uint8_t* chunkData,
uint32_t chunkDataSize) {
if (payload_size_ + chunkDataSize <= packet_data_.totalDataBytes) {
if (chunkData && chunkDataSize > 0) {
@@ -322,14 +376,15 @@ bool ProtocolPacket::operator==(const ProtocolPacket& other) const {
packet_header_.frameData == other.packet_header_.frameData &&
packet_header_.sessionId == other.packet_header_.sessionId &&
packet_header_.dataSize == other.packet_header_.dataSize &&
- packet_header_.messageId == other.packet_header_.messageId &&
+ packet_header_.messageId == other.packet_header_.messageId &&
packet_data_.totalDataBytes == other.packet_data_.totalDataBytes) {
if (other.packet_data_.totalDataBytes == 0) {
return true;
}
// Compare payload data
if (packet_data_.data && other.packet_data_.data &&
- 0 == memcmp(packet_data_.data, other.packet_data_.data,
+ 0 == memcmp(packet_data_.data,
+ other.packet_data_.data,
packet_data_.totalDataBytes)) {
return true;
}
@@ -337,34 +392,25 @@ bool ProtocolPacket::operator==(const ProtocolPacket& other) const {
return false;
}
-RESULT_CODE ProtocolPacket::deserializePacket(
- const uint8_t *message, const size_t messageSize) {
+RESULT_CODE ProtocolPacket::deserializePacket(const uint8_t* message,
+ const size_t messageSize) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN(message, RESULT_FAIL);
packet_header_.deserialize(message, messageSize);
- const uint8_t offset =
- packet_header_.version == PROTOCOL_VERSION_1 ? PROTOCOL_HEADER_V1_SIZE
- : PROTOCOL_HEADER_V2_SIZE;
+ const uint8_t offset = packet_header_.version == PROTOCOL_VERSION_1
+ ? PROTOCOL_HEADER_V1_SIZE
+ : PROTOCOL_HEADER_V2_SIZE;
packet_data_.totalDataBytes = packet_header_.dataSize;
uint32_t dataPayloadSize = 0;
- if ((offset < messageSize) &&
- packet_header_.frameType != FRAME_TYPE_FIRST) {
+ if ((offset < messageSize) && packet_header_.frameType != FRAME_TYPE_FIRST) {
dataPayloadSize = messageSize - offset;
}
- uint8_t *data = NULL;
- if (dataPayloadSize) {
- data = new (std::nothrow) uint8_t[dataPayloadSize];
- if (!data) {
- return RESULT_FAIL;
- }
- memcpy(data, message + offset, dataPayloadSize);
- payload_size_ = dataPayloadSize;
- }
-
if (packet_header_.frameType == FRAME_TYPE_FIRST) {
payload_size_ = 0;
- const uint8_t *data = message + offset;
+ const uint8_t* data = message + offset;
uint32_t total_data_bytes = data[0] << 24;
total_data_bytes |= data[1] << 16;
total_data_bytes |= data[2] << 8;
@@ -373,9 +419,11 @@ RESULT_CODE ProtocolPacket::deserializePacket(
if (0 == packet_data_.data) {
return RESULT_FAIL;
}
- } else {
+ } else if (dataPayloadSize) {
delete[] packet_data_.data;
- packet_data_.data = data;
+ packet_data_.data = new (std::nothrow) uint8_t[dataPayloadSize];
+ memcpy(packet_data_.data, message + offset, dataPayloadSize);
+ payload_size_ = dataPayloadSize;
}
return RESULT_OK;
@@ -405,6 +453,10 @@ uint8_t ProtocolPacket::frame_data() const {
return packet_header_.frameData;
}
+void ProtocolPacket::set_frame_data(const uint8_t frame_data) {
+ packet_header_.frameData = frame_data;
+}
+
uint8_t ProtocolPacket::session_id() const {
return packet_header_.sessionId;
}
@@ -417,7 +469,7 @@ uint32_t ProtocolPacket::message_id() const {
return packet_header_.messageId;
}
-uint8_t *ProtocolPacket::data() const {
+uint8_t* ProtocolPacket::data() const {
return packet_data_.data;
}
@@ -429,8 +481,8 @@ void ProtocolPacket::set_total_data_bytes(size_t dataBytes) {
}
}
-void ProtocolPacket::set_data(
- const uint8_t *const new_data, const size_t new_data_size) {
+void ProtocolPacket::set_data(const uint8_t* const new_data,
+ const size_t new_data_size) {
if (new_data_size && new_data) {
packet_header_.dataSize = packet_data_.totalDataBytes = new_data_size;
delete[] packet_data_.data;
@@ -448,7 +500,7 @@ uint32_t ProtocolPacket::total_data_bytes() const {
return packet_data_.totalDataBytes;
}
-uint8_t ProtocolPacket::connection_id() const {
+ConnectionID ProtocolPacket::connection_id() const {
return connection_id_;
}
@@ -456,5 +508,8 @@ uint32_t ProtocolPacket::payload_size() const {
return payload_size_;
}
-// End of Deserialization
+const ProtocolPacket::ProtocolHeader& ProtocolPacket::packet_header() const {
+ return packet_header_;
+}
+
} // namespace protocol_handler
diff --git a/src/components/protocol_handler/src/protocol_payload.cc b/src/components/protocol_handler/src/protocol_payload.cc
index 9fb77c81ee..aa011bdf0f 100644
--- a/src/components/protocol_handler/src/protocol_payload.cc
+++ b/src/components/protocol_handler/src/protocol_payload.cc
@@ -38,19 +38,17 @@
namespace {
// Protocol header field sizes
-static const size_t kRpcTypeBits = 4;
+static const size_t kRpcTypeBits = 4;
static const size_t kRpcFunctionIdBits = 32 - kRpcTypeBits;
static const size_t kCorrelationIdBits = 32;
-static const size_t kJsonSizeBits = 32;
-static const size_t PayloadHeaderBits = kRpcTypeBits +
- kRpcFunctionIdBits +
- kCorrelationIdBits +
- kJsonSizeBits;
+static const size_t kJsonSizeBits = 32;
+static const size_t PayloadHeaderBits =
+ kRpcTypeBits + kRpcFunctionIdBits + kCorrelationIdBits + kJsonSizeBits;
}
namespace protocol_handler {
-void Extract(utils::BitStream *bs, ProtocolPayloadHeaderV2 *headerv2) {
+void Extract(utils::BitStream* bs, ProtocolPayloadHeaderV2* headerv2) {
DCHECK(bs && headerv2);
if (headerv2 && bs && *bs) {
uint8_t rpc_type;
@@ -61,36 +59,38 @@ void Extract(utils::BitStream *bs, ProtocolPayloadHeaderV2 *headerv2) {
return;
}
utils::Extract(bs, &headerv2->rpc_function_id, kRpcFunctionIdBits);
- utils::Extract(bs, &headerv2->correlation_id); // kCorrelationIdBits
- utils::Extract(bs, &headerv2->json_size); // kJsonSizeBits
+ utils::Extract(bs, &headerv2->correlation_id); // kCorrelationIdBits
+ utils::Extract(bs, &headerv2->json_size); // kJsonSizeBits
}
}
-void Extract(utils::BitStream *bs, ProtocolPayloadV2 *payload,
+void Extract(utils::BitStream* bs,
+ ProtocolPayloadV2* payload,
size_t payload_size) {
DCHECK(bs && payload);
if (payload && bs && *bs) {
Extract(bs, &payload->header);
utils::Extract(bs, &payload->json, payload->header.json_size);
- size_t data_size = payload_size - payload->header.json_size -
- PayloadHeaderBits / CHAR_BIT;
+ size_t data_size =
+ payload_size - payload->header.json_size - PayloadHeaderBits / CHAR_BIT;
utils::Extract(bs, &payload->data, data_size);
}
}
-std::ostream &operator<<(std::ostream &os,
- const ProtocolPayloadHeaderV2 &payload_header) {
- return os << "(ProtocolPayloadHeaderV2" << " rpc_type: "
- << payload_header.rpc_type << ", rpc_function_id: "
- << payload_header.rpc_function_id << ", correlation_id: "
- << payload_header.correlation_id << ", json_size: "
- << payload_header.json_size << ")";
+std::ostream& operator<<(std::ostream& os,
+ const ProtocolPayloadHeaderV2& payload_header) {
+ return os << "(ProtocolPayloadHeaderV2"
+ << " rpc_type: " << payload_header.rpc_type
+ << ", rpc_function_id: " << payload_header.rpc_function_id
+ << ", correlation_id: " << payload_header.correlation_id
+ << ", json_size: " << payload_header.json_size << ")";
}
-std::ostream &operator<<(std::ostream &os, const ProtocolPayloadV2 &payload) {
- return os << "(ProtocolPayloadV2" << " header: " << payload.header
- << ", json (bytes): " << payload.json.size() << ", data (bytes): "
- << payload.data.size() << ")";
+std::ostream& operator<<(std::ostream& os, const ProtocolPayloadV2& payload) {
+ return os << "(ProtocolPayloadV2"
+ << " header: " << payload.header
+ << ", json (bytes): " << payload.json.size()
+ << ", data (bytes): " << payload.data.size() << ")";
}
size_t ProtocolPayloadV2SizeBits() {
diff --git a/src/components/protocol_handler/test/CMakeLists.txt b/src/components/protocol_handler/test/CMakeLists.txt
index 935ae5c475..87d91bfd54 100644
--- a/src/components/protocol_handler/test/CMakeLists.txt
+++ b/src/components/protocol_handler/test/CMakeLists.txt
@@ -1,4 +1,4 @@
-# Copyright (c) 2015, Ford Motor Company
+# Copyright (c) 2016, Ford Motor Company
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
@@ -28,16 +28,19 @@
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
-if(BUILD_TESTS)
+if (BUILD_TESTS)
-include_directories(
+include_directories (
+ include
+ ${COMPONENTS_DIR}/resumption/include
${GMOCK_INCLUDE_DIRECTORY}
${COMPONENTS_DIR}/protocol_handler/include
${COMPONENTS_DIR}/protocol_handler/test/include
${COMPONENTS_DIR}/include/protocol
+ ${JSONCPP_INCLUDE_DIRECTORY}
)
-set(LIBRARIES
+set (LIBRARIES
gmock
ProtocolHandler
connectionHandler
@@ -46,14 +49,15 @@ set(LIBRARIES
ProtocolLibrary
)
-set(SOURCES
+set (SOURCES
incoming_data_handler_test.cc
protocol_header_validator_test.cc
- #protocol_handler_tm_test.cc
+ protocol_handler_tm_test.cc
protocol_packet_test.cc
protocol_payload_test.cc
+ multiframe_builder_test.cc
)
-create_test("protocol_handler_test" "${SOURCES}" "${LIBRARIES}")
+create_test ("protocol_handler_test" "${SOURCES}" "${LIBRARIES}")
-endif()
+endif ()
diff --git a/src/components/protocol_handler/test/include/control_message_matcher.h b/src/components/protocol_handler/test/include/control_message_matcher.h
deleted file mode 100644
index 9239d0847f..0000000000
--- a/src/components/protocol_handler/test/include/control_message_matcher.h
+++ /dev/null
@@ -1,144 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef TEST_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_CONTROL_MESSAGE_MATCHER_H_
-#define TEST_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_CONTROL_MESSAGE_MATCHER_H_
-
-#include <gmock/gmock.h>
-#include <string>
-#include <vector>
-#include "protocol/raw_message.h"
-#include "protocol_handler/protocol_packet.h"
-
-namespace test {
-namespace components {
-namespace protocol_handler_test {
-/*
- * Matcher for checking RawMessage with ControlMessage
- * Check error id
- */
-
-MATCHER_P2(ControlMessage, ExpectedFrameData, ExpectedEncryption,
- (std::string(ExpectedEncryption ? "Protected" : "Unprotected")
- + " control message ")) {
- // Nack shall be always with flag protected off
- DCHECK(ExpectedFrameData != 0x03 /*FRAME_DATA_START_SERVICE_NACK*/ ||
- !ExpectedEncryption);
- const ::protocol_handler::RawMessagePtr message = arg;
- ::protocol_handler::ProtocolPacket packet(message->connection_key());
- const protocol_handler::RESULT_CODE result =
- packet.deserializePacket(message->data(), message->data_size());
- if (result != protocol_handler::RESULT_OK) {
- *result_listener << "Error while message deserialization.";
- return false;
- }
- if (::protocol_handler::FRAME_TYPE_CONTROL != packet.frame_type()) {
- *result_listener << "Is not control message";
- return false;
- }
- if (ExpectedFrameData != packet.frame_data()) {
- *result_listener << "Control message with data 0x"
- << std::hex << static_cast<int>(packet.frame_data())
- << ", not 0x"
- << std::hex << static_cast<int>(ExpectedFrameData);
- return false;
- }
- if (ExpectedEncryption != packet.protection_flag()) {
- *result_listener << "Control message is " <<
- (ExpectedEncryption ? "" : "not ") << "protected";
- return false;
- }
- return true;
-}
-
-
-
-MATCHER_P4(ControlMessage, ExpectedFrameData, ExpectedEncryption,
- ConnectionKey, VectorMatcher,
- (std::string(ExpectedEncryption ? "Protected" : "Unprotected")
- + " control message ")) {
- // Nack shall be always with flag protected off
- DCHECK(ExpectedFrameData != 0x03 /*FRAME_DATA_START_SERVICE_NACK*/ ||
- !ExpectedEncryption);
-
- const ::protocol_handler::RawMessagePtr message = arg;
- ::protocol_handler::ProtocolPacket packet(message->connection_key());
- const protocol_handler::RESULT_CODE result =
- packet.deserializePacket(message->data(), message->data_size());
- if (result != protocol_handler::RESULT_OK) {
- *result_listener << "Error while message deserialization.";
- return false;
- }
-
- if (::protocol_handler::FRAME_TYPE_CONTROL != packet.frame_type()) {
- *result_listener << "Is not control message";
- return false;
- }
- if (ExpectedFrameData != packet.frame_data()) {
- *result_listener << "Control message with data 0x"
- << std::hex << static_cast<int>(packet.frame_data())
- << ", not 0x"
- << std::hex << static_cast<int>(ExpectedFrameData);
- return false;
- }
- if (ExpectedEncryption != packet.protection_flag()) {
- *result_listener << "Control message is " <<
- (ExpectedEncryption ? "" : "not ") << "protected";
- return false;
- }
- if (ConnectionKey != message->connection_key()) {
- *result_listener << "Message for connection_id " << message->connection_key() <<
- ", expected for connection_id " << ConnectionKey;
- return false;
- }
- std::vector<uint8_t> data_vector;
- if (packet.data() && packet.data_size()) {
- data_vector.assign(packet.data(), packet.data() + packet.data_size());
- }
- ::testing::Matcher<std::vector<uint8_t> > m = VectorMatcher;
- if (!m.Matches(data_vector)) {
- *result_listener << "Message with " << data_vector.size()
- << " byte data : 0x";
- for (size_t i = 0u; i < data_vector.size(); ++i) {
- *result_listener << std::hex << static_cast<int>(data_vector[i]);
- }
- return false;
- }
- return true;
-}
-
-
-
-
-} // namespace protocol_handler_test
-} // namespace components
-} // namespace test
-#endif // TEST_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_CONTROL_MESSAGE_MATCHER_H_
diff --git a/src/components/protocol_handler/test/include/protocol_handler/control_message_matcher.h b/src/components/protocol_handler/test/include/protocol_handler/control_message_matcher.h
new file mode 100644
index 0000000000..8f68003ada
--- /dev/null
+++ b/src/components/protocol_handler/test/include/protocol_handler/control_message_matcher.h
@@ -0,0 +1,207 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef SRC_COMPONENTS_PROTOCOL_HANDLER_TEST_INCLUDE_PROTOCOL_HANDLER_CONTROL_MESSAGE_MATCHER_H_
+#define SRC_COMPONENTS_PROTOCOL_HANDLER_TEST_INCLUDE_PROTOCOL_HANDLER_CONTROL_MESSAGE_MATCHER_H_
+
+#include "gmock/gmock.h"
+#include <ios>
+#include <string>
+#include <vector>
+#include "protocol/raw_message.h"
+#include "protocol_handler/protocol_packet.h"
+
+namespace test {
+namespace components {
+namespace protocol_handler_test {
+
+using protocol_handler::ProtocolPacket;
+using protocol_handler::RawMessagePtr;
+using protocol_handler::RESULT_CODE;
+using protocol_handler::FRAME_TYPE_CONTROL;
+using protocol_handler::FRAME_DATA_START_SERVICE_NACK;
+
+bool CheckRegularMatches(const ProtocolPacket& packet,
+ RESULT_CODE result,
+ testing::MatchResultListener& result_listener,
+ uint8_t ExpectedFrameType,
+ uint8_t ExpectedFrameData,
+ uint8_t ExpectedEncryption) {
+ if (result != protocol_handler::RESULT_OK) {
+ result_listener << "Error while message deserialization.";
+ return false;
+ }
+ if (ExpectedFrameType != packet.frame_type()) {
+ result_listener << "Message with frame type 0x" << std::hex
+ << static_cast<int>(packet.frame_type()) << ", not 0x"
+ << std::hex << static_cast<int>(ExpectedFrameType);
+ return false;
+ }
+ if (ExpectedFrameData != packet.frame_data()) {
+ result_listener << "Message with data 0x" << std::hex
+ << static_cast<int>(packet.frame_data()) << ", not 0x"
+ << std::hex << static_cast<int>(ExpectedFrameData);
+ return false;
+ }
+ if (ExpectedEncryption != packet.protection_flag()) {
+ result_listener << "Message is " << (ExpectedEncryption ? "" : "not ")
+ << "protected";
+ return false;
+ }
+ return true;
+}
+
+/*
+ * Matcher for checking RawMessage with ControlMessage
+ * Check error id
+ */
+
+MATCHER_P2(ControlMessage,
+ ExpectedFrameData,
+ ExpectedEncryption,
+ (std::string(ExpectedEncryption ? "Protected" : "Unprotected") +
+ " control message ")) {
+ // Nack shall be always with flag protected off
+ if (ExpectedFrameData == FRAME_DATA_START_SERVICE_NACK &&
+ ExpectedEncryption) {
+ *result_listener << "NACK message with PROTECTION_ON flag";
+ return false;
+ }
+ const RawMessagePtr message = arg;
+ ProtocolPacket packet(message->connection_key());
+ const RESULT_CODE result =
+ packet.deserializePacket(message->data(), message->data_size());
+
+ if (!CheckRegularMatches(packet,
+ result,
+ *result_listener,
+ FRAME_TYPE_CONTROL,
+ ExpectedFrameData,
+ ExpectedEncryption)) {
+ return false;
+ }
+ return true;
+}
+
+MATCHER_P4(ControlMessage,
+ ExpectedFrameData,
+ ExpectedEncryption,
+ ConnectionKey,
+ VectorMatcher,
+ (std::string(ExpectedEncryption ? "Protected" : "Unprotected") +
+ " control message ")) {
+ // Nack shall be always with flag protected off
+ if (ExpectedFrameData == FRAME_DATA_START_SERVICE_NACK &&
+ ExpectedEncryption) {
+ *result_listener << "NACK message with PROTECTION_ON flag";
+ return false;
+ }
+ const RawMessagePtr message = arg;
+ ProtocolPacket packet(message->connection_key());
+ const RESULT_CODE result =
+ packet.deserializePacket(message->data(), message->data_size());
+
+ if (!CheckRegularMatches(packet,
+ result,
+ *result_listener,
+ FRAME_TYPE_CONTROL,
+ ExpectedFrameData,
+ ExpectedEncryption)) {
+ return false;
+ }
+
+ if (ConnectionKey != message->connection_key()) {
+ *result_listener << "Message for connection_id "
+ << message->connection_key()
+ << ", expected for connection_id " << ConnectionKey;
+ return false;
+ }
+ std::vector<uint8_t> data_vector;
+ if (packet.data() && packet.data_size()) {
+ data_vector.assign(packet.data(), packet.data() + packet.data_size());
+ }
+ ::testing::Matcher<std::vector<uint8_t> > m = VectorMatcher;
+ if (!m.Matches(data_vector)) {
+ *result_listener << "Message with " << data_vector.size()
+ << " byte data : 0x";
+ for (size_t i = 0u; i < data_vector.size(); ++i) {
+ *result_listener << std::hex << static_cast<int>(data_vector[i]);
+ }
+ return false;
+ }
+ return true;
+}
+
+/*
+ * Matcher for checking RawMessage with any ExpectedMessage
+ */
+
+MATCHER_P4(ExpectedMessage,
+ ExpectedFrameType,
+ ExpectedFrameData,
+ ExpectedEncryption,
+ ExpectedServiceType,
+ (std::string(ExpectedEncryption ? "Protected" : "Unprotected") +
+ " message ")) {
+ // Nack shall be always with flag protected off
+ if (ExpectedFrameType == FRAME_TYPE_CONTROL &&
+ ExpectedFrameData == FRAME_DATA_START_SERVICE_NACK &&
+ ExpectedEncryption) {
+ *result_listener << "NACK message with PROTECTION_ON flag";
+ return false;
+ }
+ const RawMessagePtr message = arg;
+ ProtocolPacket packet(message->connection_key());
+ const RESULT_CODE result =
+ packet.deserializePacket(message->data(), message->data_size());
+
+ if (!CheckRegularMatches(packet,
+ result,
+ *result_listener,
+ ExpectedFrameType,
+ ExpectedFrameData,
+ ExpectedEncryption)) {
+ return false;
+ }
+ if (ExpectedServiceType != packet.service_type()) {
+ *result_listener << "Service type is 0x" << std::hex
+ << static_cast<int>(packet.service_type()) << ", not 0x"
+ << std::hex << static_cast<int>(ExpectedServiceType);
+ return false;
+ }
+ return true;
+}
+
+} // namespace protocol_handler_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_PROTOCOL_HANDLER_TEST_INCLUDE_PROTOCOL_HANDLER_CONTROL_MESSAGE_MATCHER_H_
diff --git a/src/components/protocol_handler/test/include/protocol_handler/mock_telemetry_observer.h b/src/components/protocol_handler/test/include/protocol_handler/mock_telemetry_observer.h
new file mode 100644
index 0000000000..40d662ac9f
--- /dev/null
+++ b/src/components/protocol_handler/test/include/protocol_handler/mock_telemetry_observer.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_INCLUDE_TEST_PROTOCOL_HANDLER_MOCK_TIME_METRIC_OBSERVER_H_
+#define SRC_COMPONENTS_INCLUDE_TEST_PROTOCOL_HANDLER_MOCK_TIME_METRIC_OBSERVER_H_
+
+#include "gmock/gmock.h"
+#include "protocol_handler/time_metric_observer.h"
+#include "utils/shared_ptr.h"
+
+namespace test {
+namespace components {
+namespace protocol_handler_test {
+
+class MockPHTelemetryObserver : public ::protocol_handler::PHTelemetryObserver {
+ public:
+ MOCK_METHOD2(StartMessageProcess, void(uint32_t, const TimevalStruct&));
+ MOCK_METHOD2(EndMessageProcess, void(utils::SharedPtr<MessageMetric>));
+};
+
+} // namespace protocol_handler_test
+} // namespace components
+} // namespace test
+
+- #endif // SRC_COMPONENTS_INCLUDE_TEST_PROTOCOL_HANDLER_MOCK_TIME_METRIC_OBSERVER_H_
diff --git a/src/components/protocol_handler/test/include/protocol_handler/protocol_observer_mock.h b/src/components/protocol_handler/test/include/protocol_handler/protocol_observer_mock.h
new file mode 100644
index 0000000000..9f99ee41f8
--- /dev/null
+++ b/src/components/protocol_handler/test/include/protocol_handler/protocol_observer_mock.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_PROTOCOL_HANDLER_TEST_INCLUDE_PROTOCOL_OBSERVER_MOCK_H_
+#define SRC_COMPONENTS_PROTOCOL_HANDLER_TEST_INCLUDE_PROTOCOL_OBSERVER_MOCK_H_
+
+#include <gmock/gmock.h>
+#include <string>
+#include "protocol_handler/protocol_observer.h"
+
+namespace test {
+namespace components {
+namespace protocol_handler_test {
+
+/*
+ * MOCK implementation of ::protocol_handler::ProtocolObserver interface
+ */
+class ProtocolObserverMock : public ::protocol_handler::ProtocolObserver {
+ public:
+ MOCK_METHOD1(OnMessageReceived,
+ void(const ::protocol_handler::RawMessagePtr));
+ MOCK_METHOD1(OnMobileMessageSent,
+ void(const ::protocol_handler::RawMessagePtr));
+};
+} // namespace protocol_handler_test
+} // namespace components
+} // namespace test
+#endif // SRC_COMPONENTS_PROTOCOL_HANDLER_TEST_INCLUDE_PROTOCOL_OBSERVER_MOCK_H_
diff --git a/src/components/protocol_handler/test/include/protocol_handler_mock.h b/src/components/protocol_handler/test/include/protocol_handler_mock.h
deleted file mode 100644
index 41b7c491a4..0000000000
--- a/src/components/protocol_handler/test/include/protocol_handler_mock.h
+++ /dev/null
@@ -1,234 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-#ifndef SRC_COMPONENTS_PROTOCOL_HANDLER_TEST_INCLUDE_PROTOCOL_HANDLER_MOCK_H_
-#define SRC_COMPONENTS_PROTOCOL_HANDLER_TEST_INCLUDE_PROTOCOL_HANDLER_MOCK_H_
-
-#include <gmock/gmock.h>
-#include "transport_manager/transport_manager.h"
-#include "protocol_handler/session_observer.h"
-#include "protocol_handler/protocol_packet.h"
-
-namespace test {
-namespace components {
-namespace protocol_handler_test {
-
-using namespace protocol_handler;
-using namespace transport_manager;
-
-/*
- * MOCK implementation of ::protocol_handler::ProtocolObserver interface
- */
-
-class ProtocolHandlerMock : public protocol_handler::ProtocolHandler {
- public:
- MOCK_METHOD2(SendMessageToMobileApp,
- void(const ::protocol_handler::RawMessagePtr message,
- bool final_message));
- MOCK_METHOD1(AddProtocolObserver,
- void(::protocol_handler::ProtocolObserver *observer));
- MOCK_METHOD1(RemoveProtocolObserver,
- void(::protocol_handler::ProtocolObserver *observer));
- MOCK_METHOD2(SendFramesNumber,
- void(uint32_t connection_key, int32_t number_of_frames));
- MOCK_METHOD2(SendHeartBeat,
- void(int32_t connection_id, uint8_t session_id));
- MOCK_METHOD2(SendEndSession,
- void(int32_t connection_id, uint8_t session_id));
- MOCK_METHOD3(SendEndService,
- void(int32_t connection_id, uint8_t session_id, uint8_t service_type));
-};
-
-/*
- * MOCK implementation of transport_manager::TransportManager interface
- */
-class TransportManagerMock : public TransportManager {
- public:
- MOCK_METHOD0(Init,
- int());
- MOCK_METHOD0(SearchDevices,
- int());
- MOCK_METHOD1(ConnectDevice,
- int(const DeviceHandle&));
- MOCK_METHOD1(DisconnectDevice,
- int(const DeviceHandle&));
- MOCK_METHOD1(Disconnect,
- int(const ConnectionUID &));
- MOCK_METHOD1(DisconnectForce,
- int(const ConnectionUID &));
- MOCK_METHOD1(SendMessageToDevice,
- int(const ::protocol_handler::RawMessagePtr));
- MOCK_METHOD1(ReceiveEventFromDevice,
- int(const TransportAdapterEvent&));
- MOCK_METHOD1(AddTransportAdapter,
- int(transport_adapter::TransportAdapter *));
- MOCK_METHOD1(AddEventListener,
- int(TransportManagerListener *));
- MOCK_METHOD0(Stop,
- int());
- MOCK_METHOD1(RemoveDevice,
- int(const DeviceHandle& ));
- MOCK_CONST_METHOD1(Visibility,
- int(const bool &));
- MOCK_METHOD0(Reinit,
- int());
-};
-
-/*
- * MOCK implementation of protocol_handler::SessionObserver interface
- */
-class SessionObserverMock : public protocol_handler::SessionObserver {
- public:
-#ifdef ENABLE_SECURITY
- MOCK_METHOD2(SetSSLContext,
- int (const uint32_t& key,
- security_manager::SSLContext* context));
- MOCK_METHOD2(GetSSLContext,
- security_manager::SSLContext* (
- const uint32_t& key,
- const protocol_handler::ServiceType& service_type));
-#endif // ENABLE_SECURITY
- MOCK_METHOD2(SetProtectionFlag,
- void(
- const uint32_t& key,
- const protocol_handler::ServiceType& service_type));
- MOCK_METHOD5(OnSessionStartedCallback,
- uint32_t(
- const transport_manager::ConnectionUID &connection_handle,
- const uint8_t session_id,
- const ::protocol_handler::ServiceType &service_type,
- const bool is_protected, uint32_t* hash_id));
- MOCK_METHOD4(OnSessionEndedCallback,
- uint32_t(
- const transport_manager::ConnectionUID& connection_handle,
- const uint8_t sessionId,
- const uint32_t& hashCode,
- const protocol_handler::ServiceType& service_type));
- MOCK_METHOD1(OnApplicationFloodCallBack,
- void(const uint32_t&));
- MOCK_METHOD1(OnMalformedMessageCallback,
- void(const uint32_t&));
- MOCK_METHOD2(KeyFromPair,
- uint32_t(
- transport_manager::ConnectionUID connection_handle,
- uint8_t sessionId));
- MOCK_METHOD3(PairFromKey,
- void(
- uint32_t key,
- transport_manager::ConnectionUID* connection_handle,
- uint8_t* sessionId));
- MOCK_METHOD4(GetDataOnSessionKey,
- int32_t(uint32_t key,
- uint32_t* app_id,
- std::list<int32_t>* sessions_list,
- uint32_t* device_id));
- MOCK_METHOD5(GetDataOnDeviceID,
- int32_t(
- uint32_t device_handle,
- std::string *device_name,
- std::list<uint32_t> *applications_list,
- std::string *mac_address,
- std::string *connection_type));
- MOCK_METHOD2(IsHeartBeatSupported,
- bool( transport_manager::ConnectionUID connection_handle,
- uint8_t session_id));
- MOCK_METHOD3(ProtocolVersionUsed,
- bool( uint32_t connection_id,
- uint8_t session_id, uint8_t& protocol_version));
- MOCK_CONST_METHOD1(GetHandshakeContext,
- security_manager::SSLContext::HandshakeContext (const uint32_t key) );
-};
-
-#ifdef ENABLE_SECURITY
-/*
- * MOCK implementation of security_manager::SecurityManager
- */
-class SecurityManagerMock : public security_manager::SecurityManager {
- public:
- MOCK_METHOD1(AddListener,
- void(security_manager::SecurityManagerListener *));
- MOCK_METHOD1(CreateSSLContext,
- security_manager::SSLContext*(const uint32_t &));
- MOCK_METHOD1(StartHandshake,
- void(uint32_t));
- MOCK_METHOD4(SendInternalError,
- void(const uint32_t ,
- const uint8_t&,
- const std::string&,
- const uint32_t ));
-
- MOCK_METHOD1(set_session_observer,
- void(::protocol_handler::SessionObserver *));
- MOCK_METHOD1(set_protocol_handler,
- void(::protocol_handler::ProtocolHandler *));
- MOCK_METHOD1(set_crypto_manager,
- void(::security_manager::CryptoManager *));
- MOCK_METHOD1(RemoveListener,
- void(::security_manager::SecurityManagerListener *));
- // protocol_handler::ProtocolObserver part
- MOCK_METHOD1(OnMessageReceived,
- void(const ::protocol_handler::RawMessagePtr));
- MOCK_METHOD1(OnMobileMessageSent,
- void(const ::protocol_handler::RawMessagePtr));
-};
-
-class SSLContextMock : public security_manager::SSLContext {
- public:
- MOCK_CONST_METHOD0(mode, int ());
- MOCK_METHOD2(StartHandshake,
- security_manager::SSLContext::HandshakeResult (
- const uint8_t** const, size_t*));
- MOCK_METHOD4(DoHandshakeStep,
- security_manager::SSLContext::HandshakeResult (
- const uint8_t* const, size_t,
- const uint8_t** const, size_t*));
- MOCK_METHOD4(Encrypt,
- bool (const uint8_t* const, size_t,
- const uint8_t** const, size_t*));
- MOCK_METHOD4(Decrypt,
- bool (const uint8_t* const, size_t,
- const uint8_t** const, size_t*));
- MOCK_CONST_METHOD1(get_max_block_size, size_t (size_t));
- MOCK_CONST_METHOD0(IsInitCompleted, bool());
- MOCK_CONST_METHOD0(IsHandshakePending, bool());
- MOCK_CONST_METHOD0(LastError,
- std::string());
- MOCK_METHOD0(ResetConnection,
- void());
- MOCK_METHOD1(SetHandshakeContext, void (const HandshakeContext& hsh_ctx));
-};
-#endif // ENABLE_SECURITY
-}
- // namespace test
-} // namespace components
-} // namespace protocol_handler_test
-#endif // SRC_COMPONENTS_PROTOCOL_HANDLER_TEST_INCLUDE_PROTOCOL_HANDLER_MOCK_H_
-
diff --git a/src/components/protocol_handler/test/include/protocol_observer_mock.h b/src/components/protocol_handler/test/include/protocol_observer_mock.h
deleted file mode 100644
index c415e66e40..0000000000
--- a/src/components/protocol_handler/test/include/protocol_observer_mock.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_PROTOCOL_HANDLER_TEST_INCLUDE_PROTOCOL_OBSERVER_MOCK_H_
-#define SRC_COMPONENTS_PROTOCOL_HANDLER_TEST_INCLUDE_PROTOCOL_OBSERVER_MOCK_H_
-
-#include <gmock/gmock.h>
-#include <string>
-#include "protocol_handler/protocol_observer.h"
-
-namespace test {
-namespace components {
-namespace protocol_handler_test {
-
-/*
- * MOCK implementation of ::protocol_handler::ProtocolObserver interface
- */
-class ProtocolObserverMock : public ::protocol_handler::ProtocolObserver {
- public:
- MOCK_METHOD1(OnMessageReceived,
- void(const ::protocol_handler::RawMessagePtr));
- MOCK_METHOD1(OnMobileMessageSent,
- void(const ::protocol_handler::RawMessagePtr));
-};
-} // namespace protocol_handler_test
-} // namespace components
-} // namespace test
-#endif //SRC_COMPONENTS_PROTOCOL_HANDLER_TEST_INCLUDE_PROTOCOL_OBSERVER_MOCK_H_
diff --git a/src/components/protocol_handler/test/include/session_observer_mock.h b/src/components/protocol_handler/test/include/session_observer_mock.h
deleted file mode 100644
index 383ebaa161..0000000000
--- a/src/components/protocol_handler/test/include/session_observer_mock.h
+++ /dev/null
@@ -1,112 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TEST_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_SESSION_OBSERVER_MOCK_H_
-#define TEST_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_SESSION_OBSERVER_MOCK_H_
-
-#include <gmock/gmock.h>
-#include <string>
-#include <list>
-#include "protocol_handler/session_observer.h"
-
-namespace test {
-namespace components {
-namespace protocol_handler_test {
-/*
- * MOCK implementation of ::protocol_handler::SessionObserver interface
- */
-class SessionObserverMock: public ::protocol_handler::SessionObserver {
- public:
- MOCK_METHOD5(OnSessionStartedCallback,
- uint32_t(
- const transport_manager::ConnectionUID &connection_handle,
- const uint8_t session_id,
- const ::protocol_handler::ServiceType &service_type,
- const bool is_protected, uint32_t* hash_id));
- MOCK_METHOD4(OnSessionEndedCallback,
- uint32_t(
- const transport_manager::ConnectionUID &connection_handle,
- const uint8_t sessionId,
- const uint32_t &hashCode,
- const ::protocol_handler::ServiceType &service_type));
- MOCK_METHOD1(OnApplicationFloodCallBack,
- void(const uint32_t&));
- MOCK_METHOD1(OnMalformedMessageCallback,
- void(const uint32_t&));
- MOCK_METHOD2(KeyFromPair,
- uint32_t(
- transport_manager::ConnectionUID connection_handle,
- uint8_t sessionId));
- MOCK_METHOD3(PairFromKey,
- void(
- uint32_t key,
- transport_manager::ConnectionUID *connection_handle,
- uint8_t *sessionId));
- MOCK_METHOD4(GetDataOnSessionKey,
- int32_t(uint32_t key,
- uint32_t *app_id,
- std::list<int32_t> *sessions_list,
- uint32_t *device_id));
- MOCK_METHOD5(GetDataOnDeviceID,
- int32_t(
- uint32_t device_handle,
- std::string *device_name,
- std::list<uint32_t> *applications_list,
- std::string *mac_address,
- std::string *connection_type));
- MOCK_METHOD2(IsHeartBeatSupported,
- bool(transport_manager::ConnectionUID connection_handle,
- uint8_t session_id));
- MOCK_METHOD3(ProtocolVersionUsed,
- bool ( uint32_t connection_id,
- uint8_t session_id, uint8_t& protocol_version));
-#ifdef ENABLE_SECURITY
- MOCK_METHOD2(SetSSLContext,
- int(const uint32_t &key,
- ::security_manager::SSLContext *context));
- MOCK_METHOD2(GetSSLContext,
- ::security_manager::SSLContext * (
- const uint32_t &key,
- const ::protocol_handler::ServiceType &service_type));
- MOCK_METHOD2(SetProtectionFlag,
- void(
- const uint32_t &key,
- const ::protocol_handler::ServiceType &service_type));
- MOCK_CONST_METHOD1(GetHandshakeContext,
- security_manager::SSLContext::HandshakeContext (const uint32_t key) );
-
-#endif // ENABLE_SECURITY
-};
-} // namespace protocol_handler_test
-} // namespace components
-} // namespace test
-#endif // TEST_COMPONENTS_INCLUDE_PROTOCOL_HANDLER_SESSION_OBSERVER_MOCK_H_
diff --git a/src/components/protocol_handler/test/incoming_data_handler_test.cc b/src/components/protocol_handler/test/incoming_data_handler_test.cc
index e45b11f7a1..66f5aea712 100644
--- a/src/components/protocol_handler/test/incoming_data_handler_test.cc
+++ b/src/components/protocol_handler/test/incoming_data_handler_test.cc
@@ -65,10 +65,11 @@ class IncomingDataHandlerTest : public ::testing::Test {
delete[] some_data;
delete[] some_data2;
}
- void ProcessData(transport_manager::ConnectionUID uid, const uint8_t *const data,
- const uint32_t data_size ) {
- actual_frames = data_handler.ProcessData(RawMessage(uid, 0, data, data_size),
- &result_code, &malformed_occurs);
+ void ProcessData(transport_manager::ConnectionUID uid,
+ const uint8_t* const data,
+ const uint32_t data_size) {
+ actual_frames = data_handler.ProcessData(
+ RawMessage(uid, 0, data, data_size), &result_code, &malformed_occurs);
}
void AppendPacketToTMData(const ProtocolPacket& packet) {
@@ -116,35 +117,44 @@ TEST_F(IncomingDataHandlerTest, NullData) {
TEST_F(IncomingDataHandlerTest, DataForUnknownConnection) {
size_t malformed_count = 0;
- actual_frames = data_handler.ProcessData(RawMessage(uid_unknown, 0, NULL, 0),
- &result_code, &malformed_count);
+ actual_frames = data_handler.ProcessData(
+ RawMessage(uid_unknown, 0, NULL, 0), &result_code, &malformed_count);
EXPECT_EQ(RESULT_FAIL, result_code);
EXPECT_EQ(malformed_count, 0u);
EXPECT_TRUE(actual_frames.empty());
AppendPacketToTMData(ProtocolPacket());
- actual_frames = data_handler.ProcessData(RawMessage(uid_unknown, 0, tm_data.data(), tm_data.size()),
- &result_code, &malformed_count);
+ actual_frames = data_handler.ProcessData(
+ RawMessage(uid_unknown, 0, tm_data.data(), tm_data.size()),
+ &result_code,
+ &malformed_count);
EXPECT_EQ(RESULT_FAIL, result_code);
EXPECT_EQ(malformed_count, 0u);
EXPECT_TRUE(actual_frames.empty());
}
TEST_F(IncomingDataHandlerTest, Heartbeat_per_byte) {
- const ProtocolPacket hb_packet(uid1, PROTOCOL_VERSION_1, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u,
- protov1_message_id, NULL);
+ const ProtocolPacket hb_packet(uid1,
+ PROTOCOL_VERSION_1,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
+ protov1_message_id,
+ NULL);
const size_t hb_count = 100;
for (size_t i = 0; i < hb_count; ++i) {
AppendPacketToTMData(hb_packet);
// Send per 1 byte (except last byte)
for (size_t i = 0; i < tm_data.size() - 1; ++i) {
- ProcessData(uid1, &tm_data[i] , 1);
+ ProcessData(uid1, &tm_data[i], 1);
EXPECT_EQ(RESULT_OK, result_code);
EXPECT_EQ(malformed_occurs, 0u);
EXPECT_TRUE(actual_frames.empty());
}
- ProcessData(uid1, &*(tm_data.end()-1), 1);
+ ProcessData(uid1, &*(tm_data.end() - 1), 1);
EXPECT_EQ(RESULT_OK, result_code);
EXPECT_EQ(malformed_occurs, 0u);
EXPECT_EQ(1u, actual_frames.size());
@@ -154,9 +164,16 @@ TEST_F(IncomingDataHandlerTest, Heartbeat_per_byte) {
}
TEST_F(IncomingDataHandlerTest, Heartbeat_pack) {
- const ProtocolPacket hb_packet(uid1, PROTOCOL_VERSION_2, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u,
- some_message_id, NULL);
+ const ProtocolPacket hb_packet(uid1,
+ PROTOCOL_VERSION_2,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
+ some_message_id,
+ NULL);
const size_t hb_count = 100;
for (size_t i = 0u; i < hb_count; ++i) {
AppendPacketToTMData(hb_packet);
@@ -165,7 +182,9 @@ TEST_F(IncomingDataHandlerTest, Heartbeat_pack) {
EXPECT_EQ(RESULT_OK, result_code);
EXPECT_EQ(malformed_occurs, 0u);
EXPECT_EQ(hb_count, actual_frames.size());
- for (FrameList::iterator it = actual_frames.begin(); it != actual_frames.end(); ++it) {
+ for (FrameList::iterator it = actual_frames.begin();
+ it != actual_frames.end();
+ ++it) {
EXPECT_EQ(hb_packet, **it);
}
}
@@ -173,30 +192,52 @@ TEST_F(IncomingDataHandlerTest, Heartbeat_pack) {
TEST_F(IncomingDataHandlerTest, MixedPayloadData_TwoConnections) {
FrameList mobile_packets;
// single packet RPC
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_1, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kRpc, FRAME_DATA_SINGLE, some_session_id, some_data_size,
- protov1_message_id, some_data));
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_1,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kRpc,
+ FRAME_DATA_SINGLE,
+ some_session_id,
+ some_data_size,
+ protov1_message_id,
+ some_data));
// consecutive packet Audio
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_2, PROTECTION_ON, FRAME_TYPE_CONSECUTIVE,
- kAudio, FRAME_DATA_LAST_CONSECUTIVE, ++some_session_id, some_data2_size,
- some_message_id, some_data2));
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_2,
+ PROTECTION_ON,
+ FRAME_TYPE_CONSECUTIVE,
+ kAudio,
+ FRAME_DATA_LAST_CONSECUTIVE,
+ ++some_session_id,
+ some_data2_size,
+ some_message_id,
+ some_data2));
// single packet Nav
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_SINGLE,
- kMobileNav, FRAME_DATA_SINGLE, ++some_session_id, some_data_size,
- ++some_message_id, some_data));
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_SINGLE,
+ kMobileNav,
+ FRAME_DATA_SINGLE,
+ ++some_session_id,
+ some_data_size,
+ ++some_message_id,
+ some_data));
// consecutive packet Bulk
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_CONSECUTIVE,
- kBulk, FRAME_DATA_LAST_CONSECUTIVE, ++some_session_id, some_data2_size,
- ++some_message_id, some_data2));
- for (FrameList::iterator it = mobile_packets.begin(); it != mobile_packets.end(); ++it) {
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_CONSECUTIVE,
+ kBulk,
+ FRAME_DATA_LAST_CONSECUTIVE,
+ ++some_session_id,
+ some_data2_size,
+ ++some_message_id,
+ some_data2));
+ for (FrameList::iterator it = mobile_packets.begin();
+ it != mobile_packets.end();
+ ++it) {
AppendPacketToTMData(**it);
}
ProcessData(uid1, &tm_data[0], tm_data.size());
@@ -204,29 +245,39 @@ TEST_F(IncomingDataHandlerTest, MixedPayloadData_TwoConnections) {
EXPECT_EQ(malformed_occurs, 0u);
EXPECT_EQ(mobile_packets.size(), actual_frames.size());
FrameList::iterator it_exp = mobile_packets.begin();
- for (FrameList::const_iterator it = actual_frames.begin(); it != actual_frames.end();
+ for (FrameList::const_iterator it = actual_frames.begin();
+ it != actual_frames.end();
++it, ++it_exp) {
// TODO(EZamakhov): investigate valgrind warning (unitialized value)
- EXPECT_EQ(**it, **it_exp)
- << "Element number " << std::distance(mobile_packets.begin(), it_exp);
+ EXPECT_EQ(**it, **it_exp) << "Element number "
+ << std::distance(mobile_packets.begin(), it_exp);
}
}
-// TODO(EZamakhov): add validator abstraction and replace next test with check only return frames
+// TODO(EZamakhov): add validator abstraction and replace next test with check
+// only return frames
-// Protocol version shall be from 1 to 3
-TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_Version) {
+// Protocol version shall be from 1 to 4
+TEST_F(IncomingDataHandlerTest, MalformedPacket_Version) {
FrameList malformed_packets;
std::vector<uint8_t> malformed_versions;
malformed_versions.push_back(0);
- for (uint8_t version = PROTOCOL_VERSION_3 + 1; version <= PROTOCOL_VERSION_MAX; ++version) {
+ for (uint8_t version = PROTOCOL_VERSION_4 + 1;
+ version <= PROTOCOL_VERSION_MAX;
+ ++version) {
malformed_versions.push_back(version);
}
for (size_t i = 0; i < malformed_versions.size(); ++i) {
- malformed_packets.push_back(
- new ProtocolPacket(
- uid1, malformed_versions[i], PROTECTION_OFF, FRAME_TYPE_CONTROL, kControl,
- FRAME_DATA_HEART_BEAT, some_session_id, 0u, some_message_id, NULL));
+ malformed_packets.push_back(new ProtocolPacket(uid1,
+ malformed_versions[i],
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
+ some_message_id,
+ NULL));
}
// We count malformed only first time when it occurs after correct message
@@ -237,7 +288,8 @@ TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_Version) {
EXPECT_EQ(0u, actual_frames.size());
++it;
- // All next data will be one large malformed message which we've already counted
+ // All next data will be one large malformed message which we've already
+ // counted
for (; it != malformed_packets.end(); ++it) {
ProcessPacket(**it);
EXPECT_EQ(RESULT_MALFORMED_OCCURS, result_code)
@@ -249,11 +301,13 @@ TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_Version) {
}
}
-// ServiceType shall be equal 0x0 (Control), 0x07 (RPC), 0x0A (PCM), 0x0B (Video), 0x0F (Bulk)
-TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_ServiceType) {
+// ServiceType shall be equal 0x0 (Control), 0x07 (RPC), 0x0A (PCM), 0x0B
+// (Video), 0x0F (Bulk)
+TEST_F(IncomingDataHandlerTest, MalformedPacket_ServiceType) {
FrameList malformed_packets;
std::vector<uint8_t> malformed_serv_types;
- for (uint8_t service_type = kControl + 1; service_type < kRpc; ++service_type) {
+ for (uint8_t service_type = kControl + 1; service_type < kRpc;
+ ++service_type) {
malformed_serv_types.push_back(service_type);
}
malformed_serv_types.push_back(0x08);
@@ -262,11 +316,16 @@ TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_ServiceType) {
malformed_serv_types.push_back(0x0D);
malformed_serv_types.push_back(0x0E);
for (size_t i = 0; i < malformed_serv_types.size(); ++i) {
- malformed_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- malformed_serv_types[i], FRAME_DATA_HEART_BEAT, some_session_id, 0u,
- some_message_id, NULL));
+ malformed_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ malformed_serv_types[i],
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
+ some_message_id,
+ NULL));
}
// We count malformed only first time when it occurs after correct message
@@ -277,7 +336,8 @@ TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_ServiceType) {
EXPECT_EQ(0u, actual_frames.size());
++it;
- // All next data will be one large malformed message which we've already counted
+ // All next data will be one large malformed message which we've already
+ // counted
for (; it != malformed_packets.end(); ++it) {
ProcessPacket(**it);
EXPECT_EQ(RESULT_MALFORMED_OCCURS, result_code)
@@ -289,19 +349,27 @@ TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_ServiceType) {
}
}
-// Frame type shall be 0x00 (Control), 0x01 (Single), 0x02 (First), 0x03 (Consecutive)
-TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_FrameType) {
+// Frame type shall be 0x00 (Control), 0x01 (Single), 0x02 (First), 0x03
+// (Consecutive)
+TEST_F(IncomingDataHandlerTest, MalformedPacket_FrameType) {
FrameList malformed_packets;
std::vector<uint8_t> malformed_frame_types;
for (uint8_t frame_type = FRAME_TYPE_CONSECUTIVE + 1;
- frame_type <= FRAME_TYPE_MAX_VALUE; ++frame_type) {
+ frame_type <= FRAME_TYPE_MAX_VALUE;
+ ++frame_type) {
malformed_frame_types.push_back(frame_type);
}
for (size_t i = 0; i < malformed_frame_types.size(); ++i) {
- malformed_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, malformed_frame_types[i],
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u, some_message_id, NULL));
+ malformed_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ malformed_frame_types[i],
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
+ some_message_id,
+ NULL));
}
// We count malformed only first time when it occurs after correct message
@@ -312,7 +380,8 @@ TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_FrameType) {
EXPECT_EQ(0u, actual_frames.size());
++it;
- // All next data will be one large malformed message which we've already counted
+ // All next data will be one large malformed message which we've already
+ // counted
for (; it != malformed_packets.end(); ++it) {
ProcessPacket(**it);
EXPECT_EQ(RESULT_MALFORMED_OCCURS, result_code)
@@ -324,19 +393,27 @@ TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_FrameType) {
}
}
-// For Control frames Frame info value shall be from 0x00 to 0x06 or 0xFE(Data Ack), 0xFF(HB Ack)
-TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_ControlFrame) {
+// For Control frames Frame info value shall be from 0x00 to 0x06 or 0xFE(Data
+// Ack), 0xFF(HB Ack)
+TEST_F(IncomingDataHandlerTest, MalformedPacket_ControlFrame) {
FrameList malformed_packets;
std::vector<uint8_t> malformed_frame_data;
for (uint8_t frame_type = FRAME_DATA_END_SERVICE_NACK + 1;
- frame_type < FRAME_DATA_SERVICE_DATA_ACK; ++frame_type) {
+ frame_type < FRAME_DATA_SERVICE_DATA_ACK;
+ ++frame_type) {
malformed_frame_data.push_back(frame_type);
}
for (size_t i = 0; i < malformed_frame_data.size(); ++i) {
- malformed_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_CONTROL, kControl,
- malformed_frame_data[i], some_session_id, 0u, some_message_id, NULL));
+ malformed_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ malformed_frame_data[i],
+ some_session_id,
+ 0u,
+ some_message_id,
+ NULL));
}
// We count malformed only first time when it occurs after correct message
@@ -347,7 +424,8 @@ TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_ControlFrame) {
EXPECT_EQ(0u, actual_frames.size());
++it;
- // All next data will be one large malformed message which we've already counted
+ // All next data will be one large malformed message which we've already
+ // counted
for (; it != malformed_packets.end(); ++it) {
ProcessPacket(**it);
EXPECT_EQ(RESULT_MALFORMED_OCCURS, result_code)
@@ -360,19 +438,26 @@ TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_ControlFrame) {
}
// For Single and First frames Frame info value shall be equal 0x00
-TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_SingleFrame) {
+TEST_F(IncomingDataHandlerTest, MalformedPacket_SingleFrame) {
FrameList malformed_packets;
std::vector<uint8_t> malformed_frame_data;
for (uint8_t frame_type = FRAME_DATA_SINGLE + 1;
- frame_type < FRAME_DATA_MAX_VALUE; ++frame_type) {
+ frame_type < FRAME_DATA_MAX_VALUE;
+ ++frame_type) {
malformed_frame_data.push_back(frame_type);
}
malformed_frame_data.push_back(FRAME_DATA_MAX_VALUE);
for (size_t i = 0; i < malformed_frame_data.size(); ++i) {
- malformed_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_SINGLE, kControl,
- malformed_frame_data[i], some_session_id, 0u, some_message_id, NULL));
+ malformed_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ malformed_frame_data[i],
+ some_session_id,
+ 0u,
+ some_message_id,
+ NULL));
}
// We count malformed only first time when it occurs after correct message
@@ -383,7 +468,8 @@ TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_SingleFrame) {
EXPECT_EQ(0u, actual_frames.size());
++it;
- // All next data will be one large malformed message which we've already counted
+ // All next data will be one large malformed message which we've already
+ // counted
for (; it != malformed_packets.end(); ++it) {
ProcessPacket(**it);
EXPECT_EQ(RESULT_MALFORMED_OCCURS, result_code)
@@ -396,19 +482,26 @@ TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_SingleFrame) {
}
// For Single and First frames Frame info value shall be equal 0x00
-TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_FirstFrame) {
+TEST_F(IncomingDataHandlerTest, MalformedPacket_FirstFrame) {
FrameList malformed_packets;
std::vector<uint8_t> malformed_frame_data;
for (uint8_t frame_type = FRAME_DATA_FIRST + 1;
- frame_type < FRAME_DATA_MAX_VALUE; ++frame_type) {
+ frame_type < FRAME_DATA_MAX_VALUE;
+ ++frame_type) {
malformed_frame_data.push_back(frame_type);
}
malformed_frame_data.push_back(FRAME_DATA_MAX_VALUE);
for (size_t i = 0; i < malformed_frame_data.size(); ++i) {
- malformed_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_SINGLE, kControl,
- malformed_frame_data[i], some_session_id, 0u, some_message_id, NULL));
+ malformed_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ malformed_frame_data[i],
+ some_session_id,
+ 0u,
+ some_message_id,
+ NULL));
}
// We count malformed only first time when it occurs after correct message
@@ -419,7 +512,8 @@ TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_FirstFrame) {
EXPECT_EQ(0u, actual_frames.size());
++it;
- // All next data will be one large malformed message which we've already counted
+ // All next data will be one large malformed message which we've already
+ // counted
for (; it != malformed_packets.end(); ++it) {
ProcessPacket(**it);
EXPECT_EQ(RESULT_MALFORMED_OCCURS, result_code)
@@ -435,71 +529,106 @@ TEST_F(IncomingDataHandlerTest, DISABLED_MalformedPacket_FirstFrame) {
TEST_F(IncomingDataHandlerTest, MalformedPacket_AdditionalByte) {
FrameList mobile_packets;
// single packet RPC
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_1, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kRpc, FRAME_DATA_SINGLE, some_session_id, some_data_size,
- protov1_message_id, some_data));
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_1,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kRpc,
+ FRAME_DATA_SINGLE,
+ some_session_id,
+ some_data_size,
+ protov1_message_id,
+ some_data));
AppendPacketToTMData(*mobile_packets.back());
// Add malformed byte
tm_data.insert(tm_data.end(), 1, 0x1);
// consecutive packet Audio
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_2, PROTECTION_ON, FRAME_TYPE_CONSECUTIVE,
- kAudio, FRAME_DATA_LAST_CONSECUTIVE, ++some_session_id, some_data2_size,
- some_message_id, some_data2));
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_2,
+ PROTECTION_ON,
+ FRAME_TYPE_CONSECUTIVE,
+ kAudio,
+ FRAME_DATA_LAST_CONSECUTIVE,
+ ++some_session_id,
+ some_data2_size,
+ some_message_id,
+ some_data2));
AppendPacketToTMData(*mobile_packets.back());
// Add malformed bytes
tm_data.insert(tm_data.end(), 2, 0x2);
// single packet Nav
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_SINGLE,
- kMobileNav, FRAME_DATA_SINGLE, ++some_session_id, some_data_size,
- ++some_message_id, some_data));
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_SINGLE,
+ kMobileNav,
+ FRAME_DATA_SINGLE,
+ ++some_session_id,
+ some_data_size,
+ ++some_message_id,
+ some_data));
AppendPacketToTMData(*mobile_packets.back());
// Add malformed bytes
tm_data.insert(tm_data.end(), 3, 0x3);
// consecutive packet Bulk
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_CONSECUTIVE,
- kBulk, FRAME_DATA_LAST_CONSECUTIVE, ++some_session_id, some_data2_size,
- ++some_message_id, some_data2));
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_CONSECUTIVE,
+ kBulk,
+ FRAME_DATA_LAST_CONSECUTIVE,
+ ++some_session_id,
+ some_data2_size,
+ ++some_message_id,
+ some_data2));
AppendPacketToTMData(*mobile_packets.back());
// Add malformed bytes
tm_data.insert(tm_data.end(), 4, 0x4);
// single packet RPC
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_1, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kRpc, FRAME_DATA_HEART_BEAT, some_session_id, some_data_size,
- protov1_message_id, some_data));
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_1,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kRpc,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ some_data_size,
+ protov1_message_id,
+ some_data));
AppendPacketToTMData(*mobile_packets.back());
// Add malformed bytes
tm_data.insert(tm_data.end(), 5, 0x5);
// single packet Audio
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_1, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kAudio, FRAME_DATA_HEART_BEAT, some_session_id, some_data_size,
- protov1_message_id, some_data));
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_1,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kAudio,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ some_data_size,
+ protov1_message_id,
+ some_data));
AppendPacketToTMData(*mobile_packets.back());
// Add malformed bytes
tm_data.insert(tm_data.end(), 6, 0x6);
// single packet RPC
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_1, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kRpc, FRAME_DATA_SINGLE, some_session_id, some_data_size,
- protov1_message_id, some_data));
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_1,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kRpc,
+ FRAME_DATA_SINGLE,
+ some_session_id,
+ some_data_size,
+ protov1_message_id,
+ some_data));
AppendPacketToTMData(*mobile_packets.back());
ProcessData(uid1, &tm_data[0], tm_data.size());
@@ -509,11 +638,12 @@ TEST_F(IncomingDataHandlerTest, MalformedPacket_AdditionalByte) {
EXPECT_EQ(malformed_occurs, 6u);
FrameList::iterator it_exp = mobile_packets.begin();
- for (FrameList::const_iterator it = actual_frames.begin(); it != actual_frames.end();
+ for (FrameList::const_iterator it = actual_frames.begin();
+ it != actual_frames.end();
++it, ++it_exp) {
// TODO(EZamakhov): investigate valgrind warning (unitialized value)
- EXPECT_EQ(**it, **it_exp)
- << "Element number " << std::distance(mobile_packets.begin(), it_exp);
+ EXPECT_EQ(**it, **it_exp) << "Element number "
+ << std::distance(mobile_packets.begin(), it_exp);
}
}
@@ -521,51 +651,83 @@ TEST_F(IncomingDataHandlerTest, MalformedPacket_AdditionalByte) {
TEST_F(IncomingDataHandlerTest, MalformedPacket_Mix) {
FrameList mobile_packets;
// single packet RPC
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_1, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kRpc, FRAME_DATA_SINGLE, some_session_id, some_data_size,
- protov1_message_id, some_data));
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_1,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kRpc,
+ FRAME_DATA_SINGLE,
+ some_session_id,
+ some_data_size,
+ protov1_message_id,
+ some_data));
AppendPacketToTMData(*mobile_packets.back());
// consecutive packet Audio
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_2, PROTECTION_ON, FRAME_TYPE_CONSECUTIVE,
- kAudio, FRAME_DATA_LAST_CONSECUTIVE, ++some_session_id, some_data2_size,
- some_message_id, some_data2));
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_2,
+ PROTECTION_ON,
+ FRAME_TYPE_CONSECUTIVE,
+ kAudio,
+ FRAME_DATA_LAST_CONSECUTIVE,
+ ++some_session_id,
+ some_data2_size,
+ some_message_id,
+ some_data2));
AppendPacketToTMData(*mobile_packets.back());
// Malformed packet 1
const uint8_t malformed_version = PROTOCOL_VERSION_MAX;
- const ProtocolPacket malformed_packet1(
- uid1, malformed_version, PROTECTION_ON, FRAME_TYPE_SINGLE,
- kMobileNav, FRAME_DATA_SINGLE, ++some_session_id, some_data_size,
- ++some_message_id, some_data);
+ const ProtocolPacket malformed_packet1(uid1,
+ malformed_version,
+ PROTECTION_ON,
+ FRAME_TYPE_SINGLE,
+ kMobileNav,
+ FRAME_DATA_SINGLE,
+ ++some_session_id,
+ some_data_size,
+ ++some_message_id,
+ some_data);
AppendPacketToTMData(malformed_packet1);
// consecutive packet Bulk
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_CONSECUTIVE,
- kBulk, FRAME_DATA_LAST_CONSECUTIVE, ++some_session_id, some_data2_size,
- ++some_message_id, some_data2));
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_CONSECUTIVE,
+ kBulk,
+ FRAME_DATA_LAST_CONSECUTIVE,
+ ++some_session_id,
+ some_data2_size,
+ ++some_message_id,
+ some_data2));
AppendPacketToTMData(*mobile_packets.back());
// Malformed packet 2
const uint8_t malformed_type = FRAME_TYPE_MAX_VALUE;
- ProtocolPacket malformed_packet2(
- uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, malformed_type,
- kRpc, FRAME_DATA_HEART_BEAT, some_session_id, some_data_size,
- protov1_message_id, some_data);
+ ProtocolPacket malformed_packet2(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ malformed_type,
+ kRpc,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ some_data_size,
+ protov1_message_id,
+ some_data);
AppendPacketToTMData(malformed_packet2);
// Audio packet
- mobile_packets.push_back(
- new ProtocolPacket(
- uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kAudio, FRAME_DATA_HEART_BEAT, some_session_id, some_data_size,
- protov1_message_id, some_data));
+ mobile_packets.push_back(new ProtocolPacket(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kAudio,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ some_data_size,
+ protov1_message_id,
+ some_data));
AppendPacketToTMData(*mobile_packets.back());
ProcessData(uid1, &tm_data[0], tm_data.size());
@@ -573,21 +735,29 @@ TEST_F(IncomingDataHandlerTest, MalformedPacket_Mix) {
EXPECT_EQ(malformed_occurs, 2u);
EXPECT_EQ(mobile_packets.size(), actual_frames.size());
FrameList::iterator it_exp = mobile_packets.begin();
- for (FrameList::const_iterator it = actual_frames.begin(); it != actual_frames.end();
+ for (FrameList::const_iterator it = actual_frames.begin();
+ it != actual_frames.end();
++it, ++it_exp) {
// TODO(EZamakhov): investigate valgrind warning (unitialized value)
- EXPECT_EQ(**it, **it_exp)
- << "Element number " << std::distance(mobile_packets.begin(), it_exp);
+ EXPECT_EQ(**it, **it_exp) << "Element number "
+ << std::distance(mobile_packets.begin(), it_exp);
}
}
-TEST_F(IncomingDataHandlerTest, OnePortionOfData_CorrectAndMalformed_OneMalformedCounted) {
+TEST_F(IncomingDataHandlerTest,
+ OnePortionOfData_CorrectAndMalformed_OneMalformedCounted) {
// Arrange
- ProtocolPacket correct_hb_packet_(uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u,
+ ProtocolPacket correct_hb_packet_(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
some_message_id);
AppendPacketToTMData(correct_hb_packet_);
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
// Act
ProcessData(uid1, &tm_data[0], tm_data.size());
@@ -598,12 +768,19 @@ TEST_F(IncomingDataHandlerTest, OnePortionOfData_CorrectAndMalformed_OneMalforme
EXPECT_EQ(1u, actual_frames.size());
}
-TEST_F(IncomingDataHandlerTest, FirstPortionOfData_MalformedAndCorrect_OneMalformedCounted) {
+TEST_F(IncomingDataHandlerTest,
+ FirstPortionOfData_MalformedAndCorrect_OneMalformedCounted) {
// Arrange
- ProtocolPacket correct_hb_packet_(uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u,
+ ProtocolPacket correct_hb_packet_(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
some_message_id);
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
AppendPacketToTMData(correct_hb_packet_);
// Act
@@ -615,13 +792,20 @@ TEST_F(IncomingDataHandlerTest, FirstPortionOfData_MalformedAndCorrect_OneMalfor
EXPECT_EQ(1u, actual_frames.size());
}
-TEST_F(IncomingDataHandlerTest, OnePortionOfData_CorrectMalformedCorrect_OneMalformedCounted) {
+TEST_F(IncomingDataHandlerTest,
+ OnePortionOfData_CorrectMalformedCorrect_OneMalformedCounted) {
// Arrange
- ProtocolPacket correct_hb_packet_(uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u,
+ ProtocolPacket correct_hb_packet_(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
some_message_id);
AppendPacketToTMData(correct_hb_packet_);
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
AppendPacketToTMData(correct_hb_packet_);
// Act
@@ -633,15 +817,22 @@ TEST_F(IncomingDataHandlerTest, OnePortionOfData_CorrectMalformedCorrect_OneMalf
EXPECT_EQ(2u, actual_frames.size());
}
-TEST_F(IncomingDataHandlerTest, OnePortionOfData_CorrectMalformedCorrectMalformed_TwoMalformedCounted) {
+TEST_F(IncomingDataHandlerTest,
+ OnePortionOfData_CorrectMalformedCorrectMalformed_TwoMalformedCounted) {
// Arrange
- ProtocolPacket correct_hb_packet_(uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u,
+ ProtocolPacket correct_hb_packet_(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
some_message_id);
AppendPacketToTMData(correct_hb_packet_);
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
AppendPacketToTMData(correct_hb_packet_);
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
// Act
ProcessData(uid1, &tm_data[0], tm_data.size());
@@ -652,14 +843,21 @@ TEST_F(IncomingDataHandlerTest, OnePortionOfData_CorrectMalformedCorrectMalforme
EXPECT_EQ(2u, actual_frames.size());
}
-TEST_F(IncomingDataHandlerTest, OnePortionOfData_MalformedCorrectMalformedCorrect_TwoMalformedCounted) {
+TEST_F(IncomingDataHandlerTest,
+ OnePortionOfData_MalformedCorrectMalformedCorrect_TwoMalformedCounted) {
// Arrange
- ProtocolPacket correct_hb_packet_(uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u,
+ ProtocolPacket correct_hb_packet_(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
some_message_id);
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
AppendPacketToTMData(correct_hb_packet_);
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
AppendPacketToTMData(correct_hb_packet_);
// Act
@@ -671,13 +869,21 @@ TEST_F(IncomingDataHandlerTest, OnePortionOfData_MalformedCorrectMalformedCorrec
EXPECT_EQ(2u, actual_frames.size());
}
-TEST_F(IncomingDataHandlerTest, DISABLED_TwoPortionsOfData_CorrectMalformedANDCorrectMalformed_TwoMalformedCounted) {
+TEST_F(
+ IncomingDataHandlerTest,
+ TwoPortionsOfData_CorrectMalformedANDCorrectMalformed_TwoMalformedCounted) {
// Arrange
- ProtocolPacket correct_hb_packet_(uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u,
+ ProtocolPacket correct_hb_packet_(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
some_message_id);
AppendPacketToTMData(correct_hb_packet_);
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
// Act
ProcessData(uid1, &tm_data[0], tm_data.size());
@@ -690,7 +896,7 @@ TEST_F(IncomingDataHandlerTest, DISABLED_TwoPortionsOfData_CorrectMalformedANDCo
// Arrange
tm_data.clear();
AppendPacketToTMData(correct_hb_packet_);
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
// Act
ProcessData(uid1, &tm_data[0], tm_data.size());
@@ -701,13 +907,21 @@ TEST_F(IncomingDataHandlerTest, DISABLED_TwoPortionsOfData_CorrectMalformedANDCo
EXPECT_EQ(1u, actual_frames.size());
}
-TEST_F(IncomingDataHandlerTest, DISABLED_TwoPortionsOfData_CorrectMalformedANDMalformedCorrect_OneMalformedCounted) {
+TEST_F(
+ IncomingDataHandlerTest,
+ TwoPortionsOfData_CorrectMalformedANDMalformedCorrect_OneMalformedCounted) {
// Arrange
- ProtocolPacket correct_hb_packet_(uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u,
+ ProtocolPacket correct_hb_packet_(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
some_message_id);
AppendPacketToTMData(correct_hb_packet_);
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
// Act
ProcessData(uid1, &tm_data[0], tm_data.size());
@@ -719,7 +933,7 @@ TEST_F(IncomingDataHandlerTest, DISABLED_TwoPortionsOfData_CorrectMalformedANDMa
// Arrange
tm_data.clear();
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
AppendPacketToTMData(correct_hb_packet_);
// Act
@@ -731,12 +945,20 @@ TEST_F(IncomingDataHandlerTest, DISABLED_TwoPortionsOfData_CorrectMalformedANDMa
EXPECT_EQ(1u, actual_frames.size());
}
-TEST_F(IncomingDataHandlerTest, TwoPortionsOfData_MalformedCorrectANDMalformedCorrect_TwoMalformedCounted) {
+TEST_F(
+ IncomingDataHandlerTest,
+ TwoPortionsOfData_MalformedCorrectANDMalformedCorrect_TwoMalformedCounted) {
// Arrange
- ProtocolPacket correct_hb_packet_(uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u,
+ ProtocolPacket correct_hb_packet_(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
some_message_id);
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
AppendPacketToTMData(correct_hb_packet_);
// Act
@@ -749,7 +971,7 @@ TEST_F(IncomingDataHandlerTest, TwoPortionsOfData_MalformedCorrectANDMalformedCo
// Arrange
tm_data.clear();
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
AppendPacketToTMData(correct_hb_packet_);
// Act
@@ -761,12 +983,20 @@ TEST_F(IncomingDataHandlerTest, TwoPortionsOfData_MalformedCorrectANDMalformedCo
EXPECT_EQ(1u, actual_frames.size());
}
-TEST_F(IncomingDataHandlerTest, TwoPortionsOfData_MalformedCorrectANDCorrectMalformed_TwoMalformedCounted) {
+TEST_F(
+ IncomingDataHandlerTest,
+ TwoPortionsOfData_MalformedCorrectANDCorrectMalformed_TwoMalformedCounted) {
// Arrange
- ProtocolPacket correct_hb_packet_(uid1, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u,
+ ProtocolPacket correct_hb_packet_(uid1,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
some_message_id);
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
AppendPacketToTMData(correct_hb_packet_);
// Act
@@ -780,7 +1010,7 @@ TEST_F(IncomingDataHandlerTest, TwoPortionsOfData_MalformedCorrectANDCorrectMalf
// Arrange
tm_data.clear();
AppendPacketToTMData(correct_hb_packet_);
- tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
+ tm_data.insert(tm_data.end(), 12, 0xFF); // 12 bytes of malformed data
// Act
ProcessData(uid1, &tm_data[0], tm_data.size());
diff --git a/src/components/protocol_handler/test/multiframe_builder_test.cc b/src/components/protocol_handler/test/multiframe_builder_test.cc
new file mode 100644
index 0000000000..ad8a39f79a
--- /dev/null
+++ b/src/components/protocol_handler/test/multiframe_builder_test.cc
@@ -0,0 +1,540 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "gtest/gtest.h"
+#include <vector>
+#include <map>
+#include <algorithm>
+#include <utility>
+#include <limits>
+#include "utils/make_shared.h"
+#include "protocol_handler/multiframe_builder.h"
+
+namespace test {
+namespace components {
+namespace protocol_handler_test {
+
+using namespace protocol_handler;
+
+typedef std::vector<ConnectionID> ConnectionList;
+typedef std::vector<uint8_t> UCharDataVector;
+
+struct MutiframeData {
+ UCharDataVector binary_data;
+ ProtocolFramePtrList multiframes;
+};
+
+/**
+ *\brief Map of MutiframeData by MessageID key
+ */
+typedef std::map<MessageID, MutiframeData> MessageIDToMutiframeDataTestMap;
+/**
+ *\brief Map of MessageIDToMutiframeDataMap by SessionID key
+ */
+typedef std::map<SessionID, MessageIDToMutiframeDataTestMap>
+ SessionToMutiframeDataTestMap;
+/**
+ *\brief Map of SessionToMutiframeDataMap by ConnectionID key
+ */
+typedef std::map<ConnectionID, SessionToMutiframeDataTestMap> MultiFrameTestMap;
+
+template <typename IntegerType>
+std::vector<IntegerType> GetTestVector() {
+ // Prepare array with a few minimals, middle and a few maximum values
+ const IntegerType array[] = {std::numeric_limits<IntegerType>::min(),
+ std::numeric_limits<IntegerType>::min() + 1,
+ std::numeric_limits<IntegerType>::max() / 2,
+ std::numeric_limits<IntegerType>::max() - 1,
+ std::numeric_limits<IntegerType>::max()};
+ return std::vector<IntegerType>(array,
+ array + sizeof(array) / sizeof(array[0]));
+}
+
+template <typename IntegerType>
+struct Incrementor {
+ IntegerType value;
+ explicit Incrementor(const IntegerType value = 0u) : value(value) {}
+ IntegerType operator()() {
+ return ++value;
+ }
+};
+
+class MultiFrameBuilderTest : public ::testing::Test {
+ protected:
+ void SetUp() OVERRIDE {
+ const std::vector<ConnectionID> connections = GetTestVector<ConnectionID>();
+ const std::vector<SessionID> sessions = GetTestVector<SessionID>();
+ const std::vector<MessageID> messages = GetTestVector<MessageID>();
+
+ MutiframeData some_data;
+
+ const uint8_t protocol_version = PROTOCOL_VERSION_2;
+ const uint8_t service_type = SERVICE_TYPE_RPC;
+
+ // We need 255+ messages for rolling over max uint8_t value
+ int multi_frames_count = std::numeric_limits<uint8_t>::max() * 2;
+
+ // Prepare C connections with S sessions with M messages data
+ for (size_t c = 0; c < connections.size(); ++c) {
+ const ConnectionID connection_id = connections[c];
+
+ SessionToMutiframeDataTestMap sessions_map;
+ for (size_t s = 0; s < sessions.size(); ++s) {
+ const SessionID session_id = sessions[s];
+
+ MessageIDToMutiframeDataTestMap messages_map;
+ for (size_t m = 0; m < messages.size(); ++m) {
+ const MessageID message_id = messages[m];
+
+ UCharDataVector& data_vector = some_data.binary_data;
+ // Sahll not be 1 consecutive frame
+ ASSERT_GT(multi_frames_count, 1);
+ data_vector.resize(++multi_frames_count * mtu_);
+
+ std::generate(
+ data_vector.begin(), data_vector.end(), Incrementor<uint8_t>(0u));
+
+ PrepareMultiFrames(connection_id,
+ protocol_version,
+ service_type,
+ session_id,
+ message_id,
+ mtu_,
+ data_vector,
+ some_data.multiframes);
+ messages_map.insert(std::make_pair(message_id, some_data));
+ }
+ sessions_map.insert(std::make_pair(session_id, messages_map));
+ }
+ test_data_map_.insert(std::make_pair(connection_id, sessions_map));
+ }
+ }
+
+ void VerifyConsecutiveAdd(const MutiframeData& multiframe_data) {
+ const ProtocolFramePtrList& multiframes = multiframe_data.multiframes;
+ const UCharDataVector& binary_data = multiframe_data.binary_data;
+ ASSERT_FALSE(multiframes.empty());
+
+ // Frame of multiframe loop
+ ProtocolFramePtrList::const_iterator it = multiframes.begin();
+ // Skip last final frame
+ const ProtocolFramePtrList::const_iterator it_last = --(multiframes.end());
+ while (it != it_last) {
+ const ProtocolFramePtr frame = *it;
+ ASSERT_TRUE(frame);
+ EXPECT_EQ(RESULT_OK, multiframe_builder_.AddFrame(frame))
+ << "Non final CONSECUTIVE frame: " << frame;
+ EXPECT_EQ(ProtocolFramePtrList(), multiframe_builder_.PopMultiframes())
+ << "Non final CONSECUTIVE frame: " << frame;
+ ++it;
+ // Skip last final frame
+ }
+
+ const ProtocolFramePtr final_frame = multiframes.back();
+
+ EXPECT_EQ(RESULT_OK, multiframe_builder_.AddFrame(final_frame))
+ << "Final CONSECUTIVE frame: " << final_frame;
+
+ const ProtocolFramePtrList& multiframe_list =
+ multiframe_builder_.PopMultiframes();
+ ASSERT_EQ(1u, multiframe_list.size());
+
+ const ProtocolFramePtr result_multiframe = multiframe_list.front();
+ EXPECT_EQ(binary_data,
+ UCharDataVector(result_multiframe->data(),
+ result_multiframe->data() +
+ result_multiframe->payload_size()));
+ }
+
+ // Support method for first and consecutive frame disassembling
+ void PrepareMultiFrames(const ConnectionID connection_id,
+ const uint8_t protocol_version,
+ const uint8_t service_type,
+ const uint8_t session_id,
+ const uint32_t message_id,
+ const size_t max_payload_size,
+ const UCharDataVector& data,
+ ProtocolFramePtrList& out_frames) {
+ ASSERT_LT(FIRST_FRAME_DATA_SIZE, max_payload_size);
+
+ // TODO(EZamakhov): move to the separate class
+ const size_t data_size = data.size();
+ // remainder of last frame
+ const size_t lastframe_remainder = data_size % max_payload_size;
+ // size of last frame (full fill or not)
+ const size_t lastframe_size =
+ lastframe_remainder > 0 ? lastframe_remainder : max_payload_size;
+
+ const size_t frames_count = data_size / max_payload_size +
+ // add last frame if not empty
+ (lastframe_remainder > 0 ? 1 : 0);
+
+ uint8_t out_data[FIRST_FRAME_DATA_SIZE];
+ out_data[0] = data_size >> 24;
+ out_data[1] = data_size >> 16;
+ out_data[2] = data_size >> 8;
+ out_data[3] = data_size;
+
+ out_data[4] = frames_count >> 24;
+ out_data[5] = frames_count >> 16;
+ out_data[6] = frames_count >> 8;
+ out_data[7] = frames_count;
+
+ ProtocolFramePtr first_frame(new ProtocolPacket(connection_id,
+ protocol_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_FIRST,
+ service_type,
+ FRAME_DATA_FIRST,
+ session_id,
+ FIRST_FRAME_DATA_SIZE,
+ message_id,
+ out_data));
+ // Note: PHIMpl already prepare First frames the total_data_bytes on
+ // desirialization
+ first_frame->set_total_data_bytes(data_size);
+
+ out_frames.clear();
+ out_frames.push_back(first_frame);
+
+ for (size_t i = 0; i < frames_count; ++i) {
+ const bool is_last_frame = ((frames_count - 1) == i);
+ const size_t frame_size =
+ is_last_frame ? lastframe_size : max_payload_size;
+ const uint8_t data_type = is_last_frame
+ ? FRAME_DATA_LAST_CONSECUTIVE
+ : (i % FRAME_DATA_MAX_CONSECUTIVE + 1);
+
+ const ProtocolFramePtr consecutive_frame(
+ new ProtocolPacket(connection_id,
+ protocol_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONSECUTIVE,
+ service_type,
+ data_type,
+ session_id,
+ frame_size,
+ message_id,
+ &data[max_payload_size * i]));
+ out_frames.push_back(consecutive_frame);
+ }
+ }
+
+ void AddConnections() {
+ for (MultiFrameTestMap::iterator connection_it = test_data_map_.begin();
+ connection_it != test_data_map_.end();
+ ++connection_it) {
+ const ConnectionID connection_id = connection_it->first;
+ ASSERT_TRUE(multiframe_builder_.AddConnection(connection_id));
+ }
+ }
+
+ MultiFrameBuilder multiframe_builder_;
+ MultiFrameTestMap test_data_map_;
+ static size_t mtu_;
+};
+
+size_t MultiFrameBuilderTest::mtu_ = 10;
+
+TEST_F(MultiFrameBuilderTest, Pop_Frames_From_Empty_builder) {
+ EXPECT_EQ(ProtocolFramePtrList(), multiframe_builder_.PopMultiframes());
+}
+
+TEST_F(MultiFrameBuilderTest, Pop_Frames_with_existing_connections) {
+ AddConnections();
+ EXPECT_EQ(ProtocolFramePtrList(), multiframe_builder_.PopMultiframes());
+}
+
+TEST_F(MultiFrameBuilderTest, Add_EmptyFrame) {
+ EXPECT_EQ(RESULT_FAIL, multiframe_builder_.AddFrame(ProtocolFramePtr()));
+ EXPECT_EQ(ProtocolFramePtrList(), multiframe_builder_.PopMultiframes());
+}
+
+TEST_F(MultiFrameBuilderTest, Add_NonSingleOrConsecutive_Frames) {
+ UCharDataVector types;
+ types.reserve(std::numeric_limits<uint8_t>::max());
+ for (uint8_t type = std::numeric_limits<uint8_t>::min();
+ type < std::numeric_limits<uint8_t>::max();
+ ++type) {
+ if (type != FRAME_TYPE_FIRST && type != FRAME_TYPE_CONSECUTIVE) {
+ types.push_back(type);
+ }
+ }
+
+ for (UCharDataVector::iterator it = types.begin(); it != types.end(); ++it) {
+ const uint8_t frame_type = *it;
+ const ProtocolFramePtr unexpected_frame(
+ new ProtocolPacket(0u,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ frame_type,
+ SERVICE_TYPE_RPC,
+ FRAME_DATA_FIRST,
+ 0u,
+ 0u,
+ 0u));
+ EXPECT_EQ(RESULT_FAIL, multiframe_builder_.AddFrame(unexpected_frame))
+ << "Unexpected frame: " << unexpected_frame;
+
+ EXPECT_EQ(ProtocolFramePtrList(), multiframe_builder_.PopMultiframes())
+ << "Unexpected frame: " << unexpected_frame;
+ }
+}
+
+TEST_F(MultiFrameBuilderTest, Add_FirstFrames_NoConnections) {
+ for (MultiFrameTestMap::iterator connection_it = test_data_map_.begin();
+ connection_it != test_data_map_.end();
+ ++connection_it) {
+ SessionToMutiframeDataTestMap& session_map = connection_it->second;
+ const ConnectionID connection_id = connection_it->first;
+
+ for (SessionToMutiframeDataTestMap::iterator session_it =
+ session_map.begin();
+ session_it != session_map.end();
+ ++session_it) {
+ MessageIDToMutiframeDataTestMap& messageId_map = session_it->second;
+
+ for (MessageIDToMutiframeDataTestMap::iterator messageId_it =
+ messageId_map.begin();
+ messageId_it != messageId_map.end();
+ ++messageId_it) {
+ const MutiframeData& multiframe_data = messageId_it->second;
+
+ const ProtocolFramePtrList& multiframes = multiframe_data.multiframes;
+ ASSERT_FALSE(multiframes.empty());
+ const ProtocolFramePtr first_frame = multiframes.front();
+ ASSERT_TRUE(first_frame);
+ EXPECT_EQ(RESULT_FAIL, multiframe_builder_.AddFrame(first_frame))
+ << "Non-existed connection " << connection_id
+ << "- to be skipped first frame: " << first_frame;
+
+ EXPECT_EQ(ProtocolFramePtrList(), multiframe_builder_.PopMultiframes())
+ << "First frame: " << first_frame;
+ }
+ }
+ }
+}
+
+TEST_F(MultiFrameBuilderTest, Add_FirstFrames_only) {
+ AddConnections();
+ for (MultiFrameTestMap::iterator connection_it = test_data_map_.begin();
+ connection_it != test_data_map_.end();
+ ++connection_it) {
+ SessionToMutiframeDataTestMap& session_map = connection_it->second;
+
+ for (SessionToMutiframeDataTestMap::iterator session_it =
+ session_map.begin();
+ session_it != session_map.end();
+ ++session_it) {
+ MessageIDToMutiframeDataTestMap& messageId_map = session_it->second;
+
+ for (MessageIDToMutiframeDataTestMap::iterator messageId_it =
+ messageId_map.begin();
+ messageId_it != messageId_map.end();
+ ++messageId_it) {
+ const MutiframeData& multiframe_data = messageId_it->second;
+
+ const ProtocolFramePtrList& multiframes = multiframe_data.multiframes;
+ ASSERT_FALSE(multiframes.empty());
+ const ProtocolFramePtr first_frame = multiframes.front();
+ ASSERT_TRUE(first_frame);
+ EXPECT_EQ(RESULT_OK, multiframe_builder_.AddFrame(first_frame))
+ << "First frame: " << first_frame;
+
+ EXPECT_EQ(ProtocolFramePtrList(), multiframe_builder_.PopMultiframes())
+ << "First frame: " << first_frame;
+ }
+ }
+ }
+}
+
+TEST_F(MultiFrameBuilderTest, Add_ConsecutiveFrame) {
+ ASSERT_FALSE(test_data_map_.empty());
+ const ConnectionID& connection_id = test_data_map_.begin()->first;
+ SessionToMutiframeDataTestMap& session_map = test_data_map_.begin()->second;
+
+ ASSERT_TRUE(multiframe_builder_.AddConnection(connection_id));
+ ASSERT_FALSE(session_map.empty());
+ MessageIDToMutiframeDataTestMap& messageId_map = session_map.begin()->second;
+
+ ASSERT_FALSE(messageId_map.empty());
+ const MutiframeData& multiframe_data = messageId_map.begin()->second;
+
+ VerifyConsecutiveAdd(multiframe_data);
+}
+
+TEST_F(MultiFrameBuilderTest, Add_ConsecutiveFrames_OneByOne) {
+ AddConnections();
+ for (MultiFrameTestMap::iterator connection_it = test_data_map_.begin();
+ connection_it != test_data_map_.end();
+ ++connection_it) {
+ SessionToMutiframeDataTestMap& session_map = connection_it->second;
+
+ for (SessionToMutiframeDataTestMap::iterator session_it =
+ session_map.begin();
+ session_it != session_map.end();
+ ++session_it) {
+ MessageIDToMutiframeDataTestMap& messageId_map = session_it->second;
+
+ for (MessageIDToMutiframeDataTestMap::iterator messageId_it =
+ messageId_map.begin();
+ messageId_it != messageId_map.end();
+ ++messageId_it) {
+ const MutiframeData& multiframe_data = messageId_it->second;
+
+ VerifyConsecutiveAdd(multiframe_data);
+ }
+ }
+ }
+}
+
+TEST_F(MultiFrameBuilderTest, Add_ConsecutiveFrames_per1) {
+ AddConnections();
+ ASSERT_FALSE(test_data_map_.empty());
+ // After processing each frame we remove it from messageId_it
+ // After processing all session data - it removes from session_map
+ // and so on
+ // TODO(Ezamakhov): optimize speed of test by skipping erasing data
+ while (!test_data_map_.empty()) {
+ MultiFrameTestMap::iterator connection_it = test_data_map_.begin();
+ while (connection_it != test_data_map_.end()) {
+ SessionToMutiframeDataTestMap& session_map = connection_it->second;
+
+ SessionToMutiframeDataTestMap::iterator session_it = session_map.begin();
+ while (session_it != session_map.end()) {
+ MessageIDToMutiframeDataTestMap& messageId_map = session_it->second;
+
+ MessageIDToMutiframeDataTestMap::iterator messageId_it =
+ messageId_map.begin();
+ while (messageId_it != messageId_map.end()) {
+ MutiframeData& multiframe_data = messageId_it->second;
+ ProtocolFramePtrList& multiframes = multiframe_data.multiframes;
+ ASSERT_FALSE(multiframes.empty());
+
+ const ProtocolFramePtr frame = multiframes.front();
+ ASSERT_TRUE(frame);
+
+ EXPECT_EQ(RESULT_OK, multiframe_builder_.AddFrame(frame))
+ << "Frame: " << frame;
+
+ multiframes.pop_front();
+
+ // If all frames are assembled
+ if (multiframes.empty()) {
+ const ProtocolFramePtrList& multiframe_list =
+ multiframe_builder_.PopMultiframes();
+ ASSERT_EQ(1u, multiframe_list.size());
+
+ const ProtocolFramePtr result_multiframe = multiframe_list.front();
+ const UCharDataVector& binary_data = multiframe_data.binary_data;
+ EXPECT_EQ(binary_data,
+ UCharDataVector(result_multiframe->data(),
+ result_multiframe->data() +
+ result_multiframe->payload_size()));
+ messageId_map.erase(messageId_it++);
+ } else {
+ // Multiframe is not completed
+ EXPECT_EQ(ProtocolFramePtrList(),
+ multiframe_builder_.PopMultiframes())
+ << "Frame: " << frame;
+ ++messageId_it;
+ }
+ }
+ if (messageId_map.empty()) {
+ session_map.erase(session_it++);
+ } else {
+ ++session_it;
+ }
+ }
+ if (session_map.empty()) {
+ test_data_map_.erase(connection_it++);
+ } else {
+ ++connection_it;
+ }
+ }
+ }
+}
+
+TEST_F(MultiFrameBuilderTest, FrameExpired_OneMSec) {
+ multiframe_builder_.set_waiting_timeout(1);
+
+ ASSERT_FALSE(test_data_map_.empty());
+ const ConnectionID& connection_id = test_data_map_.begin()->first;
+ SessionToMutiframeDataTestMap& session_map = test_data_map_.begin()->second;
+
+ ASSERT_TRUE(multiframe_builder_.AddConnection(connection_id));
+
+ ASSERT_FALSE(session_map.empty());
+ MessageIDToMutiframeDataTestMap& messageId_map = session_map.begin()->second;
+
+ ASSERT_FALSE(messageId_map.empty());
+ const MutiframeData& multiframe_data = messageId_map.begin()->second;
+
+ const ProtocolFramePtrList& multiframes = multiframe_data.multiframes;
+ ASSERT_FALSE(multiframes.empty());
+ const ProtocolFramePtr first_frame = multiframes.front();
+ ASSERT_TRUE(first_frame);
+ EXPECT_EQ(RESULT_OK, multiframe_builder_.AddFrame(first_frame))
+ << "First frame: " << first_frame;
+
+ // Wait frame expire
+ usleep(1000);
+ const ProtocolFramePtrList& list = multiframe_builder_.PopMultiframes();
+ ASSERT_FALSE(list.empty());
+ EXPECT_EQ(first_frame, list.front());
+}
+
+TEST_F(MultiFrameBuilderTest, RemoveConnection_NoConnection_ResultFail) {
+ // Arrange
+ const ConnectionID& connection_id = test_data_map_.begin()->first;
+ // Act
+ const bool connection_result =
+ multiframe_builder_.RemoveConnection(connection_id);
+ // Assert
+ ASSERT_FALSE(connection_result);
+}
+
+TEST_F(MultiFrameBuilderTest, RemoveConnection_Successful) {
+ // Arrange
+ const ConnectionID& connection_id = test_data_map_.begin()->first;
+ // Variable test_data_map initially contains IDs of not existed in
+ // MultiframeBuilder connections
+ ASSERT_TRUE(multiframe_builder_.AddConnection(connection_id));
+ // Act
+ const bool connection_result =
+ multiframe_builder_.RemoveConnection(connection_id);
+ // Assert
+ ASSERT_TRUE(connection_result);
+}
+
+} // namespace protocol_handler_test
+} // namespace components
+} // namespace test
diff --git a/src/components/protocol_handler/test/protocol_handler_tm_test.cc b/src/components/protocol_handler/test/protocol_handler_tm_test.cc
index 4ef070c52f..1a7be866d9 100644
--- a/src/components/protocol_handler/test/protocol_handler_tm_test.cc
+++ b/src/components/protocol_handler/test/protocol_handler_tm_test.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -29,50 +29,112 @@
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include <gtest/gtest.h>
+#include "gtest/gtest.h"
#include <string>
+#include "protocol_handler/protocol_handler.h"
#include "protocol_handler/protocol_handler_impl.h"
#include "protocol/common.h"
-#include "control_message_matcher.h"
-#include "protocol_handler_mock.h"
-#include "protocol_observer_mock.h"
-
+#include "protocol_handler/control_message_matcher.h"
+#include "protocol_handler/mock_protocol_handler.h"
+#include "protocol_handler/protocol_observer_mock.h"
+#include "protocol_handler/mock_protocol_handler_settings.h"
+#include "protocol_handler/mock_session_observer.h"
+#include "connection_handler/mock_connection_handler.h"
+#include "security_manager/mock_security_manager.h"
+#include "security_manager/mock_ssl_context.h"
+#include "transport_manager/mock_transport_manager.h"
+#include "utils/make_shared.h"
namespace test {
namespace components {
namespace protocol_handler_test {
-// id passed as NULL for new session establishing
-#define NEW_SESSION_ID 0u
-#define SESSION_START_REJECT 0u
-
-using namespace ::protocol_handler;
-using namespace ::transport_manager;
+// Id passed as NULL for new session establishing
+#define NEW_SESSION_ID 0u
+#define SESSION_START_REJECT 0u
+// Protocol Handler Entities
+using protocol_handler::ProtocolHandlerImpl;
+using protocol_handler::ServiceType;
+using protocol_handler::RawMessage;
+using protocol_handler::RawMessagePtr;
+using protocol_handler::PROTECTION_ON;
+using protocol_handler::PROTECTION_OFF;
+using protocol_handler::PROTOCOL_VERSION_1;
+using protocol_handler::PROTOCOL_VERSION_2;
+using protocol_handler::PROTOCOL_VERSION_3;
+using protocol_handler::PROTOCOL_VERSION_MAX;
+using protocol_handler::FRAME_TYPE_CONTROL;
+using protocol_handler::FRAME_TYPE_SINGLE;
+using protocol_handler::FRAME_TYPE_FIRST;
+using protocol_handler::FRAME_TYPE_CONSECUTIVE;
+using protocol_handler::FRAME_TYPE_MAX_VALUE;
+using protocol_handler::MAXIMUM_FRAME_DATA_V2_SIZE;
+using protocol_handler::FRAME_DATA_START_SERVICE;
+using protocol_handler::FRAME_DATA_START_SERVICE_ACK;
+using protocol_handler::FRAME_DATA_END_SERVICE_NACK;
+using protocol_handler::FRAME_DATA_END_SERVICE_ACK;
+using protocol_handler::FRAME_DATA_END_SERVICE;
+using protocol_handler::FRAME_DATA_HEART_BEAT;
+using protocol_handler::FRAME_DATA_HEART_BEAT_ACK;
+using protocol_handler::FRAME_DATA_SINGLE;
+using protocol_handler::FRAME_DATA_FIRST;
+using protocol_handler::FRAME_DATA_LAST_CONSECUTIVE;
+using protocol_handler::kRpc;
+using protocol_handler::kControl;
+using protocol_handler::kAudio;
+using protocol_handler::kMobileNav;
+using protocol_handler::kBulk;
+using protocol_handler::kInvalidServiceType;
// For TM states
-using ::transport_manager::TransportManagerListener;
+using transport_manager::TransportManagerListener;
+using transport_manager::E_SUCCESS;
+using transport_manager::DeviceInfo;
+// For CH entities
+using connection_handler::DeviceHandle;
+// Google Testing Framework Entities
using ::testing::Return;
+using ::testing::ReturnRefOfCopy;
using ::testing::ReturnNull;
using ::testing::AnyOf;
-using ::testing::Ge;
-using ::testing::Le;
+using ::testing::DoAll;
using ::testing::_;
using ::testing::Invoke;
+using ::testing::SetArgReferee;
+using ::testing::SetArgPointee;
+
+typedef std::vector<uint8_t> UCharDataVector;
class ProtocolHandlerImplTest : public ::testing::Test {
protected:
- void InitProtocolHandlerImpl(
- const size_t period_msec, const size_t max_messages,
- bool malformed_message_filtering = false,
- const size_t malformd_period_msec = 0u,
- const size_t malformd_max_messages = 0u) {
+ void InitProtocolHandlerImpl(const size_t period_msec,
+ const size_t max_messages,
+ bool malformed_message_filtering = false,
+ const size_t malformd_period_msec = 0u,
+ const size_t malformd_max_messages = 0u,
+ const int32_t multiframe_waiting_timeout = 0,
+ const size_t maximum_payload_size = 0u) {
+ ON_CALL(protocol_handler_settings_mock, maximum_payload_size())
+ .WillByDefault(Return(maximum_payload_size));
+ ON_CALL(protocol_handler_settings_mock, message_frequency_time())
+ .WillByDefault(Return(period_msec));
+ ON_CALL(protocol_handler_settings_mock, message_frequency_count())
+ .WillByDefault(Return(max_messages));
+ ON_CALL(protocol_handler_settings_mock, malformed_message_filtering())
+ .WillByDefault(Return(malformed_message_filtering));
+ ON_CALL(protocol_handler_settings_mock, malformed_frequency_time())
+ .WillByDefault(Return(malformd_period_msec));
+ ON_CALL(protocol_handler_settings_mock, malformed_frequency_count())
+ .WillByDefault(Return(malformd_max_messages));
+ ON_CALL(protocol_handler_settings_mock, multiframe_waiting_timeout())
+ .WillByDefault(Return(multiframe_waiting_timeout));
protocol_handler_impl.reset(
- new ProtocolHandlerImpl(&transport_manager_mock,
- period_msec, max_messages,
- malformed_message_filtering,
- malformd_period_msec, malformd_max_messages));
- protocol_handler_impl->set_session_observer(&session_observer_mock);
+ new ProtocolHandlerImpl(protocol_handler_settings_mock,
+ session_observer_mock,
+ connection_handler_mock,
+ transport_manager_mock));
tm_listener = protocol_handler_impl.get();
}
+
void SetUp() OVERRIDE {
InitProtocolHandlerImpl(0u, 0u);
connection_id = 0xAu;
@@ -81,15 +143,16 @@ class ProtocolHandlerImplTest : public ::testing::Test {
message_id = 0xABCDEFu;
some_data.resize(256, 0xAB);
- // expect ConnectionHandler support methods call (conversion, check heartbeat)
- EXPECT_CALL(session_observer_mock,
- KeyFromPair(connection_id, _)).
- //return some connection_key
- WillRepeatedly(Return(connection_key));
- EXPECT_CALL(session_observer_mock,
- IsHeartBeatSupported(connection_id, _)).
- //return false to avoid call KeepConnectionAlive
- WillRepeatedly(Return(false));
+ // Expect ConnectionHandler support methods call (conversion, check
+ // heartbeat)
+ EXPECT_CALL(session_observer_mock, KeyFromPair(connection_id, _))
+ .
+ // Return some connection_key
+ WillRepeatedly(Return(connection_key));
+ EXPECT_CALL(session_observer_mock, IsHeartBeatSupported(connection_id, _))
+ .
+ // Return false to avoid call KeepConnectionAlive
+ WillRepeatedly(Return(false));
}
void TearDown() OVERRIDE {
@@ -99,10 +162,11 @@ class ProtocolHandlerImplTest : public ::testing::Test {
// Emulate connection establish
void AddConnection() {
- tm_listener->OnConnectionEstablished(
- DeviceInfo(DeviceHandle(1u), std::string("mac"), std::string("name"),
- std::string("BTMAC")),
- connection_id);
+ tm_listener->OnConnectionEstablished(DeviceInfo(DeviceHandle(1u),
+ std::string("mac"),
+ std::string("name"),
+ std::string("BTMAC")),
+ connection_id);
}
void AddSession() {
AddConnection();
@@ -111,23 +175,29 @@ class ProtocolHandlerImplTest : public ::testing::Test {
// For enabled protection callback shall use protection ON
const bool callback_protection_flag = PROTECTION_ON;
#else
- // For disabled protection callback shall ignore protection income flad and use protection OFF
+ // For disabled protection callback shall ignore protection income flad and
+ // use protection OFF
const bool callback_protection_flag = PROTECTION_OFF;
#endif // ENABLE_SECURITY
- // expect ConnectionHandler check
+ // Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
- OnSessionStartedCallback(connection_id, NEW_SESSION_ID, start_service,
- callback_protection_flag, _)).
- //return sessions start success
- WillOnce(Return(session_id));
-
- // expect send Ack with PROTECTION_OFF (on no Security Manager)
+ OnSessionStartedCallback(connection_id,
+ NEW_SESSION_ID,
+ start_service,
+ callback_protection_flag,
+ _))
+ .
+ // Return sessions start success
+ WillOnce(Return(session_id));
+
+ // Expect send Ack with PROTECTION_OFF (on no Security Manager)
EXPECT_CALL(transport_manager_mock,
- SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF)))
+ SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_ACK,
+ PROTECTION_OFF)))
.WillOnce(Return(E_SUCCESS));
- SendControlMessage(PROTECTION_ON, start_service, NEW_SESSION_ID,
- FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
}
#ifdef ENABLE_SECURITY
@@ -136,54 +206,91 @@ class ProtocolHandlerImplTest : public ::testing::Test {
protocol_handler_impl->set_security_manager(&security_manager_mock);
}
#endif // ENABLE_SECURITY
- void SendTMMessage(uint8_t connection_id, uint8_t version, bool protection,
- uint8_t frameType, uint8_t serviceType, uint8_t frameData,
- uint8_t sessionId, uint32_t dataSize, uint32_t messageID,
- const uint8_t *data = 0) {
+ void SendTMMessage(uint8_t connection_id,
+ uint8_t version,
+ bool protection,
+ uint8_t frameType,
+ uint8_t serviceType,
+ uint8_t frameData,
+ uint8_t sessionId,
+ uint32_t dataSize,
+ uint32_t messageID,
+ const uint8_t* data = 0) {
// Create packet
- const ProtocolPacket packet(connection_id, version, protection, frameType,
- serviceType, frameData, sessionId, dataSize,
- messageID, data);
- // Emulate resive packet from transoprt manager
+ const ProtocolPacket packet(connection_id,
+ version,
+ protection,
+ frameType,
+ serviceType,
+ frameData,
+ sessionId,
+ dataSize,
+ messageID,
+ data);
+ // Emulate receive packet from transoprt manager
tm_listener->OnTMMessageReceived(packet.serializePacket());
}
- void SendControlMessage(bool protection, uint8_t service_type,
- uint8_t sessionId, uint32_t frame_data,
- uint32_t dataSize = 0u, const uint8_t *data = NULL) {
- SendTMMessage(connection_id, PROTOCOL_VERSION_3, protection,
- FRAME_TYPE_CONTROL, service_type, frame_data, sessionId,
- dataSize, message_id, data);
+
+ void SetProtocolVersion2() {
+ // Set protocol version 2
+ ON_CALL(protocol_handler_settings_mock, max_supported_protocol_version())
+ .WillByDefault(Return(PROTOCOL_VERSION_2));
+ }
+
+ void SendControlMessage(bool protection,
+ uint8_t service_type,
+ uint8_t sessionId,
+ uint32_t frame_data,
+ uint32_t dataSize = 0u,
+ const uint8_t* data = NULL) {
+ SendTMMessage(connection_id,
+ PROTOCOL_VERSION_3,
+ protection,
+ FRAME_TYPE_CONTROL,
+ service_type,
+ frame_data,
+ sessionId,
+ dataSize,
+ message_id,
+ data);
}
+ testing::NiceMock<MockProtocolHandlerSettings> protocol_handler_settings_mock;
::utils::SharedPtr<ProtocolHandlerImpl> protocol_handler_impl;
TransportManagerListener* tm_listener;
// Uniq connection
::transport_manager::ConnectionUID connection_id;
- // id of established session
+ // Id of established session
uint8_t session_id;
- // uniq id as connection_id and session_id in one
+ // Uniq id as connection_id and session_id in one
uint32_t connection_key;
uint32_t message_id;
- std::vector<uint8_t> some_data;
+ UCharDataVector some_data;
// Strict mocks (same as all methods EXPECT_CALL().Times(0))
- testing::StrictMock<protocol_handler_test::TransportManagerMock> transport_manager_mock;
- testing::StrictMock<protocol_handler_test::SessionObserverMock> session_observer_mock;
+ testing::NiceMock<connection_handler_test::MockConnectionHandler>
+ connection_handler_mock;
+ testing::StrictMock<transport_manager_test::MockTransportManager>
+ transport_manager_mock;
+ testing::StrictMock<protocol_handler_test::MockSessionObserver>
+ session_observer_mock;
#ifdef ENABLE_SECURITY
- testing::NiceMock<protocol_handler_test::SecurityManagerMock> security_manager_mock;
- testing::NiceMock<protocol_handler_test::SSLContextMock> ssl_context_mock;
+ testing::NiceMock<security_manager_test::MockSecurityManager>
+ security_manager_mock;
+ testing::NiceMock<security_manager_test::MockSSLContext> ssl_context_mock;
#endif // ENABLE_SECURITY
};
#ifdef ENABLE_SECURITY
class OnHandshakeDoneFunctor {
-public:
+ public:
OnHandshakeDoneFunctor(const uint32_t connection_key,
security_manager::SSLContext::HandshakeResult error)
- : connection_key(connection_key), result(error) {}
- void operator()(security_manager::SecurityManagerListener * listener) const {
+ : connection_key(connection_key), result(error) {}
+ void operator()(security_manager::SecurityManagerListener* listener) const {
listener->OnHandshakeDone(connection_key, result);
}
-private:
+
+ private:
const uint32_t connection_key;
const security_manager::SSLContext::HandshakeResult result;
};
@@ -199,48 +306,63 @@ TEST_F(ProtocolHandlerImplTest, RecieveEmptyRawMessage) {
* ProtocolHandler shall disconnect on no connection
*/
TEST_F(ProtocolHandlerImplTest, RecieveOnUnknownConnection) {
- EXPECT_CALL(transport_manager_mock, DisconnectForce(connection_id)).
- WillOnce(Return(E_SUCCESS));
+ EXPECT_CALL(transport_manager_mock, DisconnectForce(connection_id))
+ .WillOnce(Return(E_SUCCESS));
- SendTMMessage(connection_id, PROTOCOL_VERSION_3, PROTECTION_OFF,
- FRAME_TYPE_CONTROL, kRpc, FRAME_DATA_START_SERVICE,
- NEW_SESSION_ID, 0, message_id);
+ SendTMMessage(connection_id,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kRpc,
+ FRAME_DATA_START_SERVICE,
+ NEW_SESSION_ID,
+ 0,
+ message_id);
}
/*
* ProtocolHandler shall send NAck on session_observer rejection
* Check protection flag OFF for all services from kControl to kBulk
*/
-TEST_F(ProtocolHandlerImplTest, StartSession_Unprotected_SessionObserverReject) {
+TEST_F(ProtocolHandlerImplTest,
+ StartSession_Unprotected_SessionObserverReject) {
const int call_times = 5;
AddConnection();
- // expect ConnectionHandler check
- EXPECT_CALL(session_observer_mock,
- OnSessionStartedCallback(
- connection_id, NEW_SESSION_ID, AnyOf(kControl, kRpc, kAudio,
- kMobileNav, kBulk), PROTECTION_OFF, _)).Times(call_times).
- //return sessions start rejection
+ // Expect ConnectionHandler check
+ EXPECT_CALL(
+ session_observer_mock,
+ OnSessionStartedCallback(connection_id,
+ NEW_SESSION_ID,
+ AnyOf(kControl, kRpc, kAudio, kMobileNav, kBulk),
+ PROTECTION_OFF,
+ _))
+ .Times(call_times)
+ .
+ // Return sessions start rejection
WillRepeatedly(Return(SESSION_START_REJECT));
- // expect send NAck
+ // Expect send NAck
EXPECT_CALL(transport_manager_mock,
- SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_NACK, PROTECTION_OFF)))
- .Times(call_times).WillRepeatedly(Return(E_SUCCESS));
-
- SendControlMessage(PROTECTION_OFF, kControl, NEW_SESSION_ID,
- FRAME_DATA_START_SERVICE);
- SendControlMessage(PROTECTION_OFF, kRpc, NEW_SESSION_ID,
- FRAME_DATA_START_SERVICE);
- SendControlMessage(PROTECTION_OFF, kAudio, NEW_SESSION_ID,
- FRAME_DATA_START_SERVICE);
- SendControlMessage(PROTECTION_OFF, kMobileNav, NEW_SESSION_ID,
- FRAME_DATA_START_SERVICE);
- SendControlMessage(PROTECTION_OFF, kBulk, NEW_SESSION_ID,
- FRAME_DATA_START_SERVICE);
+ SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_NACK,
+ PROTECTION_OFF)))
+ .Times(call_times)
+ .WillRepeatedly(Return(E_SUCCESS));
+
+ SendControlMessage(
+ PROTECTION_OFF, kControl, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_OFF, kRpc, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_OFF, kAudio, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_OFF, kMobileNav, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_OFF, kBulk, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
}
/*
* ProtocolHandler shall send NAck on session_observer rejection
* Emulate getting PROTECTION_ON and check protection flag OFF in NAck
- * For ENABLE_SECURITY=OFF session_observer shall be called with protection flag OFF
+ * For ENABLE_SECURITY=OFF session_observer shall be called with protection flag
+ * OFF
*/
TEST_F(ProtocolHandlerImplTest, StartSession_Protected_SessionObserverReject) {
const int call_times = 5;
@@ -249,65 +371,80 @@ TEST_F(ProtocolHandlerImplTest, StartSession_Protected_SessionObserverReject) {
// For enabled protection callback shall use protection ON
const bool callback_protection_flag = PROTECTION_ON;
#else
- // For disabled protection callback shall ignore protection income flad and use protection OFF
+ // For disabled protection callback shall ignore protection income flag and
+ // use protection OFF
const bool callback_protection_flag = PROTECTION_OFF;
#endif // ENABLE_SECURITY
- // expect ConnectionHandler check
- EXPECT_CALL(session_observer_mock,
- OnSessionStartedCallback(
- connection_id, NEW_SESSION_ID, AnyOf(kControl, kRpc, kAudio,
- kMobileNav, kBulk), callback_protection_flag, _)).Times(
- call_times).
- //return sessions start rejection
+ // Expect ConnectionHandler check
+ EXPECT_CALL(
+ session_observer_mock,
+ OnSessionStartedCallback(connection_id,
+ NEW_SESSION_ID,
+ AnyOf(kControl, kRpc, kAudio, kMobileNav, kBulk),
+ callback_protection_flag,
+ _))
+ .Times(call_times)
+ .
+ // Return sessions start rejection
WillRepeatedly(Return(SESSION_START_REJECT));
- // expect send NAck with encryption OFF
+ // Expect send NAck with encryption OFF
EXPECT_CALL(transport_manager_mock,
- SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_NACK, PROTECTION_OFF)))
- .Times(call_times).WillRepeatedly(Return(E_SUCCESS));
-
- SendControlMessage(PROTECTION_ON, kControl, NEW_SESSION_ID,
- FRAME_DATA_START_SERVICE);
- SendControlMessage(PROTECTION_ON, kRpc, NEW_SESSION_ID,
- FRAME_DATA_START_SERVICE);
- SendControlMessage(PROTECTION_ON, kAudio, NEW_SESSION_ID,
- FRAME_DATA_START_SERVICE);
- SendControlMessage(PROTECTION_ON, kMobileNav, NEW_SESSION_ID,
- FRAME_DATA_START_SERVICE);
- SendControlMessage(PROTECTION_ON, kBulk, NEW_SESSION_ID,
- FRAME_DATA_START_SERVICE);
+ SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_NACK,
+ PROTECTION_OFF)))
+ .Times(call_times)
+ .WillRepeatedly(Return(E_SUCCESS));
+
+ SendControlMessage(
+ PROTECTION_ON, kControl, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_ON, kRpc, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_ON, kAudio, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_ON, kMobileNav, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_ON, kBulk, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
}
/*
* ProtocolHandler shall send Ack on session_observer accept
* Check protection flag OFF
*/
-TEST_F(ProtocolHandlerImplTest, StartSession_Unprotected_SessionObserverAccept) {
+TEST_F(ProtocolHandlerImplTest,
+ StartSession_Unprotected_SessionObserverAccept) {
AddConnection();
const ServiceType start_service = kRpc;
- // expect ConnectionHandler check
- EXPECT_CALL(session_observer_mock,
- OnSessionStartedCallback(connection_id, NEW_SESSION_ID, start_service, PROTECTION_OFF, _))
+ // Expect ConnectionHandler check
+ EXPECT_CALL(
+ session_observer_mock,
+ OnSessionStartedCallback(
+ connection_id, NEW_SESSION_ID, start_service, PROTECTION_OFF, _))
.
- //return sessions start success
- WillOnce(Return(session_id));
+ // Return sessions start success
+ WillOnce(Return(session_id));
- // expect send Ack
+ SetProtocolVersion2();
+ // Expect send Ack
EXPECT_CALL(transport_manager_mock,
- SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF)))
+ SendMessageToDevice(
+ ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF)))
.WillOnce(Return(E_SUCCESS));
- SendControlMessage(PROTECTION_OFF, start_service, NEW_SESSION_ID,
- FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_OFF, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
}
/*
* ProtocolHandler shall send Ack on session_observer accept
* Emulate getting PROTECTION_ON and check protection flag OFF in Ack
- * For ENABLE_SECURITY=OFF session_observer shall be called with protection flag OFF
+ * For ENABLE_SECURITY=OFF session_observer shall be called with protection flag
+ * OFF
*/
TEST_F(ProtocolHandlerImplTest, StartSession_Protected_SessionObserverAccept) {
+ SetProtocolVersion2();
AddSession();
}
-// TODO(EZamakhov): add test for get_hash_id/set_hash_id from protocol_handler_impl.cc
+// TODO(EZamakhov): add test for get_hash_id/set_hash_id from
+// protocol_handler_impl.cc
/*
* ProtocolHandler shall send NAck on session_observer rejection
*/
@@ -315,19 +452,22 @@ TEST_F(ProtocolHandlerImplTest, EndSession_SessionObserverReject) {
AddSession();
const ServiceType service = kRpc;
- // expect ConnectionHandler check
+ // Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
- OnSessionEndedCallback(connection_id, session_id, _, service)).
- // reject session start
- WillOnce(Return(SESSION_START_REJECT));
+ OnSessionEndedCallback(connection_id, session_id, _, service))
+ .
+ // reject session start
+ WillOnce(Return(SESSION_START_REJECT));
- // expect send NAck
+ SetProtocolVersion2();
+ // Expect send NAck
EXPECT_CALL(transport_manager_mock,
- SendMessageToDevice(ControlMessage(FRAME_DATA_END_SERVICE_NACK, PROTECTION_OFF)))
+ SendMessageToDevice(
+ ControlMessage(FRAME_DATA_END_SERVICE_NACK, PROTECTION_OFF)))
.WillOnce(Return(E_SUCCESS));
- SendControlMessage(PROTECTION_OFF, service, session_id,
- FRAME_DATA_END_SERVICE);
+ SendControlMessage(
+ PROTECTION_OFF, service, session_id, FRAME_DATA_END_SERVICE);
}
/*
* ProtocolHandler shall send NAck on wrong hash code
@@ -336,19 +476,22 @@ TEST_F(ProtocolHandlerImplTest, EndSession_Success) {
AddSession();
const ServiceType service = kRpc;
- // expect ConnectionHandler check
+ // Expect ConnectionHandler check
EXPECT_CALL(session_observer_mock,
- OnSessionEndedCallback(connection_id, session_id, _, service)).
- // return sessions start success
- WillOnce(Return(connection_key));
+ OnSessionEndedCallback(connection_id, session_id, _, service))
+ .
+ // return sessions start success
+ WillOnce(Return(connection_key));
- // expect send Ack
+ SetProtocolVersion2();
+ // Expect send Ack
EXPECT_CALL(transport_manager_mock,
- SendMessageToDevice(ControlMessage(FRAME_DATA_END_SERVICE_ACK, PROTECTION_OFF)))
+ SendMessageToDevice(
+ ControlMessage(FRAME_DATA_END_SERVICE_ACK, PROTECTION_OFF)))
.WillOnce(Return(E_SUCCESS));
- SendControlMessage(PROTECTION_OFF, service, session_id,
- FRAME_DATA_END_SERVICE);
+ SendControlMessage(
+ PROTECTION_OFF, service, session_id, FRAME_DATA_END_SERVICE);
}
#ifdef ENABLE_SECURITY
@@ -361,40 +504,59 @@ TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionProtocoloV1) {
// Add security manager
AddSecurityManager();
const ServiceType start_service = kRpc;
- // expect ConnectionHandler check
- EXPECT_CALL(session_observer_mock,
- OnSessionStartedCallback(connection_id, NEW_SESSION_ID, start_service, PROTECTION_OFF, _)).
- //return sessions start success
- WillOnce(Return(session_id));
+ // Expect ConnectionHandler check
+ EXPECT_CALL(
+ session_observer_mock,
+ OnSessionStartedCallback(
+ connection_id, NEW_SESSION_ID, start_service, PROTECTION_OFF, _))
+ .
+ // Return sessions start success
+ WillOnce(Return(session_id));
- // expect send Ack with PROTECTION_OFF (on no Security Manager)
+ SetProtocolVersion2();
+ // Expect send Ack with PROTECTION_OFF (on no Security Manager)
EXPECT_CALL(transport_manager_mock,
- SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF))).
- WillOnce(Return(E_SUCCESS));
+ SendMessageToDevice(
+ ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF)))
+ .WillOnce(Return(E_SUCCESS));
- SendTMMessage(connection_id, PROTOCOL_VERSION_1, PROTECTION_ON, FRAME_TYPE_CONTROL,
- start_service, FRAME_DATA_START_SERVICE, NEW_SESSION_ID, 0, message_id);
+ SendTMMessage(connection_id,
+ PROTOCOL_VERSION_1,
+ PROTECTION_ON,
+ FRAME_TYPE_CONTROL,
+ start_service,
+ FRAME_DATA_START_SERVICE,
+ NEW_SESSION_ID,
+ 0,
+ message_id);
}
/*
- * ProtocolHandler shall not call Security logics on start session with PROTECTION_OFF
+ * ProtocolHandler shall not call Security logics on start session with
+ * PROTECTION_OFF
*/
TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionUnprotected) {
AddConnection();
// Add security manager
AddSecurityManager();
const ServiceType start_service = kRpc;
- // expect ConnectionHandler check
- EXPECT_CALL(session_observer_mock,
- OnSessionStartedCallback(connection_id, NEW_SESSION_ID, start_service, PROTECTION_OFF, _)).
- //return sessions start success
- WillOnce(Return(session_id));
+ // Expect ConnectionHandler check
+ EXPECT_CALL(
+ session_observer_mock,
+ OnSessionStartedCallback(
+ connection_id, NEW_SESSION_ID, start_service, PROTECTION_OFF, _))
+ .
+ // Return sessions start success
+ WillOnce(Return(session_id));
- // expect send Ack with PROTECTION_OFF (on no Security Manager)
+ SetProtocolVersion2();
+ // Expect send Ack with PROTECTION_OFF (on no Security Manager)
EXPECT_CALL(transport_manager_mock,
- SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF))).
- WillOnce(Return(E_SUCCESS));
+ SendMessageToDevice(
+ ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF)))
+ .WillOnce(Return(E_SUCCESS));
- SendControlMessage(PROTECTION_OFF, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_OFF, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
}
/*
* ProtocolHandler shall send Ack with PROTECTION_OFF on fail SLL creation
@@ -403,430 +565,547 @@ TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionProtected_Fail) {
AddConnection();
AddSecurityManager();
const ServiceType start_service = kRpc;
- // expect ConnectionHandler check
- EXPECT_CALL(session_observer_mock,
- OnSessionStartedCallback(connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _)).
- //return sessions start success
- WillOnce(Return(session_id));
+ // Expect ConnectionHandler check
+ EXPECT_CALL(
+ session_observer_mock,
+ OnSessionStartedCallback(
+ connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _))
+ .
+ // Return sessions start success
+ WillOnce(Return(session_id));
- // expect start protection for unprotected session
- EXPECT_CALL(security_manager_mock,
- CreateSSLContext(connection_key)).
- //return fail protection
- WillOnce(ReturnNull());
+ SetProtocolVersion2();
+ // Expect start protection for unprotected session
+ EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key))
+ .
+ // Return fail protection
+ WillOnce(ReturnNull());
- // expect send Ack with PROTECTION_OFF (on fail SLL creation)
+ // Expect send Ack with PROTECTION_OFF (on fail SLL creation)
EXPECT_CALL(transport_manager_mock,
- SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF))).
- WillOnce(Return(E_SUCCESS));
+ SendMessageToDevice(
+ ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF)))
+ .WillOnce(Return(E_SUCCESS));
- SendControlMessage(PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
}
/*
- * ProtocolHandler shall send Ack with PROTECTION_ON on already established and initialized SLLContext
+ * ProtocolHandler shall send Ack with PROTECTION_ON on already established and
+ * initialized SLLContext
*/
-TEST_F(ProtocolHandlerImplTest,SecurityEnable_StartSessionProtected_SSLInitialized) {
+TEST_F(ProtocolHandlerImplTest,
+ SecurityEnable_StartSessionProtected_SSLInitialized) {
AddConnection();
AddSecurityManager();
const ServiceType start_service = kRpc;
- // expect ConnectionHandler check
- EXPECT_CALL(session_observer_mock,
- OnSessionStartedCallback(connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _)).
- //return sessions start success
- WillOnce(Return(session_id));
+ // Expect ConnectionHandler check
+ EXPECT_CALL(
+ session_observer_mock,
+ OnSessionStartedCallback(
+ connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _))
+ .
+ // Return sessions start success
+ WillOnce(Return(session_id));
+ SetProtocolVersion2();
// call new SSLContext creation
- EXPECT_CALL(security_manager_mock,
- CreateSSLContext(connection_key)).
- //return new SSLContext
- WillOnce(Return(&ssl_context_mock));
+ EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key))
+ .
+ // Return new SSLContext
+ WillOnce(Return(&ssl_context_mock));
- // initilization check
- EXPECT_CALL(ssl_context_mock,
- IsInitCompleted()).
- //emulate SSL is initilized
- WillOnce(Return(true));
+ // Initilization check
+ EXPECT_CALL(ssl_context_mock, IsInitCompleted())
+ .
+ // emulate SSL is initilized
+ WillOnce(Return(true));
// Expect service protection enable
EXPECT_CALL(session_observer_mock,
- SetProtectionFlag(connection_key, start_service));
+ SetProtectionFlag(connection_key, start_service));
- // expect send Ack with PROTECTION_ON (on SSL is initilized)
+ // Expect send Ack with PROTECTION_ON (on SSL is initilized)
EXPECT_CALL(transport_manager_mock,
- SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON))).
- WillOnce(Return(E_SUCCESS));
+ SendMessageToDevice(
+ ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON)))
+ .WillOnce(Return(E_SUCCESS));
- SendControlMessage(PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
}
/*
* ProtocolHandler shall send Ack with PROTECTION_OFF on session handshhake fail
*/
-TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionProtected_HandshakeFail) {
+TEST_F(ProtocolHandlerImplTest,
+ SecurityEnable_StartSessionProtected_HandshakeFail) {
AddConnection();
AddSecurityManager();
const ServiceType start_service = kRpc;
- // expect ConnectionHandler check
- EXPECT_CALL(session_observer_mock,
- OnSessionStartedCallback(connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _)).
- //return sessions start success
- WillOnce(Return(session_id));
+ // Expect ConnectionHandler check
+ EXPECT_CALL(
+ session_observer_mock,
+ OnSessionStartedCallback(
+ connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _))
+ .
+ // Return sessions start success
+ WillOnce(Return(session_id));
+
+ std::vector<int> services;
+ // TODO(AKutsan) : APPLINK-21398 use named constants instead of magic numbers
+ services.push_back(0x0A);
+ services.push_back(0x0B);
+ ON_CALL(protocol_handler_settings_mock, force_protected_service())
+ .WillByDefault(ReturnRefOfCopy(services));
// call new SSLContext creation
- EXPECT_CALL(security_manager_mock,
- CreateSSLContext(connection_key)).
- //return new SSLContext
- WillOnce(Return(&ssl_context_mock));
+ EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key))
+ .
+ // Return new SSLContext
+ WillOnce(Return(&ssl_context_mock));
- // initilization check
- EXPECT_CALL(ssl_context_mock,
- IsInitCompleted()).
- //emulate SSL is not initilized
- WillOnce(Return(false));
+ // Initilization check
+ EXPECT_CALL(ssl_context_mock, IsInitCompleted())
+ .
+ // emulate SSL is not initilized
+ WillOnce(Return(false));
// Pending handshake check
- EXPECT_CALL(ssl_context_mock,
- IsHandshakePending()).
- //emulate is pending
- WillOnce(Return(true));
-
- // expect add listener for handshake result
- EXPECT_CALL(security_manager_mock,
- AddListener(_))
- // emulate handshake fail
- .WillOnce(Invoke(OnHandshakeDoneFunctor(
- connection_key,
- security_manager::SSLContext::Handshake_Result_Fail)));
+ EXPECT_CALL(ssl_context_mock, IsHandshakePending())
+ .
+ // emulate is pending
+ WillOnce(Return(true));
+
+ // Expect add listener for handshake result
+ EXPECT_CALL(security_manager_mock, AddListener(_))
+ // Emulate handshake fail
+ .WillOnce(Invoke(OnHandshakeDoneFunctor(
+ connection_key,
+ security_manager::SSLContext::Handshake_Result_Fail)));
// Listener check SSLContext
EXPECT_CALL(session_observer_mock,
- GetSSLContext(connection_key, start_service)).
- // emulate protection for service is not enabled
- WillOnce(ReturnNull());
+ GetSSLContext(connection_key, start_service))
+ .
+ // Emulate protection for service is not enabled
+ WillOnce(ReturnNull());
- // expect send Ack with PROTECTION_OFF (on fail handshake)
+ // Expect send Ack with PROTECTION_OFF (on fail handshake)
EXPECT_CALL(transport_manager_mock,
- SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF))).
- WillOnce(Return(E_SUCCESS));
+ SendMessageToDevice(
+ ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_OFF)))
+ .WillOnce(Return(E_SUCCESS));
- SendControlMessage(PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
}
/*
- * ProtocolHandler shall send Ack with PROTECTION_ON on session handshhake success
+ * ProtocolHandler shall send Ack with PROTECTION_ON on session handshhake
+ * success
*/
-TEST_F(ProtocolHandlerImplTest, SecurityEnable_StartSessionProtected_HandshakeSuccess) {
+TEST_F(ProtocolHandlerImplTest,
+ SecurityEnable_StartSessionProtected_HandshakeSuccess) {
AddConnection();
AddSecurityManager();
const ServiceType start_service = kRpc;
- // expect ConnectionHandler check
- EXPECT_CALL(session_observer_mock,
- OnSessionStartedCallback(connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _)).
- //return sessions start success
- WillOnce(Return(session_id));
+
+ // No services are protected
+ std::vector<int> services;
+ ON_CALL(protocol_handler_settings_mock, force_protected_service())
+ .WillByDefault(ReturnRefOfCopy(services));
+
+ // Expect ConnectionHandler check
+ EXPECT_CALL(
+ session_observer_mock,
+ OnSessionStartedCallback(
+ connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _))
+ .
+ // Return sessions start success
+ WillOnce(Return(session_id));
// call new SSLContext creation
- EXPECT_CALL(security_manager_mock,
- CreateSSLContext(connection_key)).
- //return new SSLContext
- WillOnce(Return(&ssl_context_mock));
+ EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key))
+ .
+ // Return new SSLContext
+ WillOnce(Return(&ssl_context_mock));
- // initilization check
- EXPECT_CALL(ssl_context_mock,
- IsInitCompleted()).
- //emulate SSL is not initilized
- WillOnce(Return(false));
+ // Initilization check
+ EXPECT_CALL(ssl_context_mock, IsInitCompleted())
+ .
+ // emulate SSL is not initilized
+ WillOnce(Return(false));
// Pending handshake check
- EXPECT_CALL(ssl_context_mock,
- IsHandshakePending()).
- //emulate is pending
- WillOnce(Return(true));
-
- // expect add listener for handshake result
- EXPECT_CALL(security_manager_mock,
- AddListener(_))
- // emulate handshake fail
- .WillOnce(Invoke(OnHandshakeDoneFunctor(
- connection_key,
- security_manager::SSLContext::Handshake_Result_Success)));
+ EXPECT_CALL(ssl_context_mock, IsHandshakePending())
+ .
+ // emulate is pending
+ WillOnce(Return(true));
+
+ // Expect add listener for handshake result
+ EXPECT_CALL(security_manager_mock, AddListener(_))
+ // Emulate handshake fail
+ .WillOnce(Invoke(OnHandshakeDoneFunctor(
+ connection_key,
+ security_manager::SSLContext::Handshake_Result_Success)));
// Listener check SSLContext
EXPECT_CALL(session_observer_mock,
- GetSSLContext(connection_key, start_service)).
- // emulate protection for service is not enabled
- WillOnce(ReturnNull());
+ GetSSLContext(connection_key, start_service))
+ .
+ // Emulate protection for service is not enabled
+ WillOnce(ReturnNull());
// Expect service protection enable
EXPECT_CALL(session_observer_mock,
- SetProtectionFlag(connection_key, start_service));
+ SetProtectionFlag(connection_key, start_service));
- // expect send Ack with PROTECTION_OFF (on fail handshake)
+ // Expect send Ack with PROTECTION_OFF (on fail handshake)
EXPECT_CALL(transport_manager_mock,
- SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON))).
- WillOnce(Return(E_SUCCESS));
+ SendMessageToDevice(
+ ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON)))
+ .WillOnce(Return(E_SUCCESS));
- SendControlMessage(PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
}
/*
- * ProtocolHandler shall send Ack with PROTECTION_ON on session handshhake success
+ * ProtocolHandler shall send Ack with PROTECTION_ON on session handshhake
+ * success
*/
-TEST_F(ProtocolHandlerImplTest,
+TEST_F(
+ ProtocolHandlerImplTest,
SecurityEnable_StartSessionProtected_HandshakeSuccess_ServiceProtectedBefore) {
AddConnection();
AddSecurityManager();
const ServiceType start_service = kRpc;
- // expect ConnectionHandler check
- EXPECT_CALL(session_observer_mock,
- OnSessionStartedCallback(connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _)).
- //return sessions start success
- WillOnce(Return(session_id));
+
+ std::vector<int> services;
+ ON_CALL(protocol_handler_settings_mock, force_protected_service())
+ .WillByDefault(ReturnRefOfCopy(services));
+
+ // Expect ConnectionHandler check
+ EXPECT_CALL(
+ session_observer_mock,
+ OnSessionStartedCallback(
+ connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _))
+ .
+ // Return sessions start success
+ WillOnce(Return(session_id));
// call new SSLContext creation
- EXPECT_CALL(security_manager_mock,
- CreateSSLContext(connection_key)).
- //return new SSLContext
- WillOnce(Return(&ssl_context_mock));
+ EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key))
+ .
+ // Return new SSLContext
+ WillOnce(Return(&ssl_context_mock));
- // initilization check
- EXPECT_CALL(ssl_context_mock,
- IsInitCompleted()).
- //emulate SSL is not initilized
- WillOnce(Return(false));
+ // Initilization check
+ EXPECT_CALL(ssl_context_mock, IsInitCompleted())
+ .
+ // emulate SSL is not initilized
+ WillOnce(Return(false));
// Pending handshake check
- EXPECT_CALL(ssl_context_mock,
- IsHandshakePending()).
- //emulate is pending
- WillOnce(Return(true));
-
- // expect add listener for handshake result
- EXPECT_CALL(security_manager_mock,
- AddListener(_))
- // emulate handshake fail
- .WillOnce(Invoke(OnHandshakeDoneFunctor(
- connection_key,
- security_manager::SSLContext::Handshake_Result_Success)));
+ EXPECT_CALL(ssl_context_mock, IsHandshakePending())
+ .
+ // emulate is pending
+ WillOnce(Return(true));
+
+ // Expect add listener for handshake result
+ EXPECT_CALL(security_manager_mock, AddListener(_))
+ // Emulate handshake fail
+ .WillOnce(Invoke(OnHandshakeDoneFunctor(
+ connection_key,
+ security_manager::SSLContext::Handshake_Result_Success)));
// Listener check SSLContext
EXPECT_CALL(session_observer_mock,
- GetSSLContext(connection_key, start_service)).
- // emulate protection for service is not enabled
- WillOnce(ReturnNull());
+ GetSSLContext(connection_key, start_service))
+ .
+ // Emulate protection for service is not enabled
+ WillOnce(ReturnNull());
// Expect service protection enable
EXPECT_CALL(session_observer_mock,
- SetProtectionFlag(connection_key, start_service));
+ SetProtectionFlag(connection_key, start_service));
- // expect send Ack with PROTECTION_OFF (on fail handshake)
+ // Expect send Ack with PROTECTION_OFF (on fail handshake)
EXPECT_CALL(transport_manager_mock,
- SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON))).
- WillOnce(Return(E_SUCCESS));
+ SendMessageToDevice(
+ ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON)))
+ .WillOnce(Return(E_SUCCESS));
- SendControlMessage(PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
}
/*
- * ProtocolHandler shall send Ack with PROTECTION_ON on session handshhake success
+ * ProtocolHandler shall send Ack with PROTECTION_ON on session handshhake
+ * success
*/
TEST_F(ProtocolHandlerImplTest,
- SecurityEnable_StartSessionProtected_HandshakeSuccess_SSLIsNotPending) {
+ SecurityEnable_StartSessionProtected_HandshakeSuccess_SSLIsNotPending) {
AddConnection();
AddSecurityManager();
const ServiceType start_service = kRpc;
- // expect ConnectionHandler check
- EXPECT_CALL(session_observer_mock,
- OnSessionStartedCallback(connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _)).
- //return sessions start success
- WillOnce(Return(session_id));
+
+ std::vector<int> services;
+ ON_CALL(protocol_handler_settings_mock, force_protected_service())
+ .WillByDefault(ReturnRefOfCopy(services));
+
+ // Expect ConnectionHandler check
+ EXPECT_CALL(
+ session_observer_mock,
+ OnSessionStartedCallback(
+ connection_id, NEW_SESSION_ID, start_service, PROTECTION_ON, _))
+ .
+ // Return sessions start success
+ WillOnce(Return(session_id));
// call new SSLContext creation
- EXPECT_CALL(security_manager_mock,
- CreateSSLContext(connection_key)).
- //return new SSLContext
- WillOnce(Return(&ssl_context_mock));
+ EXPECT_CALL(security_manager_mock, CreateSSLContext(connection_key))
+ .
+ // Return new SSLContext
+ WillOnce(Return(&ssl_context_mock));
- // initilization check
- EXPECT_CALL(ssl_context_mock,
- IsInitCompleted()).
- //emulate SSL is not initilized
- WillOnce(Return(false));
+ // Initilization check
+ EXPECT_CALL(ssl_context_mock, IsInitCompleted())
+ .
+ // emulate SSL is not initilized
+ WillOnce(Return(false));
// Pending handshake check
- EXPECT_CALL(ssl_context_mock,
- IsHandshakePending()).
- //emulate is pending
- WillOnce(Return(false));
+ EXPECT_CALL(ssl_context_mock, IsHandshakePending())
+ .
+ // emulate is pending
+ WillOnce(Return(false));
// Wait restart handshake operation
- EXPECT_CALL(security_manager_mock,
- StartHandshake(connection_key));
+ EXPECT_CALL(security_manager_mock, StartHandshake(connection_key));
- // expect add listener for handshake result
- EXPECT_CALL(security_manager_mock,
- AddListener(_))
- // emulate handshake fail
- .WillOnce(Invoke(OnHandshakeDoneFunctor(
- connection_key,
- security_manager::SSLContext::Handshake_Result_Success)));
+ // Expect add listener for handshake result
+ EXPECT_CALL(security_manager_mock, AddListener(_))
+ // Emulate handshake fail
+ .WillOnce(Invoke(OnHandshakeDoneFunctor(
+ connection_key,
+ security_manager::SSLContext::Handshake_Result_Success)));
// Listener check SSLContext
EXPECT_CALL(session_observer_mock,
- GetSSLContext(connection_key, start_service)).
- // emulate protection for service is not enabled
- WillOnce(ReturnNull());
+ GetSSLContext(connection_key, start_service))
+ .
+ // Emulate protection for service is not enabled
+ WillOnce(ReturnNull());
// Expect service protection enable
EXPECT_CALL(session_observer_mock,
- SetProtectionFlag(connection_key, start_service));
+ SetProtectionFlag(connection_key, start_service));
- // expect send Ack with PROTECTION_OFF (on fail handshake)
+ // Expect send Ack with PROTECTION_OFF (on fail handshake)
EXPECT_CALL(transport_manager_mock,
- SendMessageToDevice(ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON))).
- WillOnce(Return(E_SUCCESS));
+ SendMessageToDevice(
+ ControlMessage(FRAME_DATA_START_SERVICE_ACK, PROTECTION_ON)))
+ .WillOnce(Return(E_SUCCESS));
- SendControlMessage(PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
+ SendControlMessage(
+ PROTECTION_ON, start_service, NEW_SESSION_ID, FRAME_DATA_START_SERVICE);
}
#endif // ENABLE_SECURITY
-TEST_F(ProtocolHandlerImplTest,
- FloodVerification) {
+TEST_F(ProtocolHandlerImplTest, FloodVerification) {
const size_t period_msec = 10000;
const size_t max_messages = 1000;
InitProtocolHandlerImpl(period_msec, max_messages);
AddConnection();
AddSession();
- // expect flood notification to CH
- EXPECT_CALL(session_observer_mock,
- OnApplicationFloodCallBack(connection_key)).
- Times(1);
+ // Expect flood notification to CH
+ EXPECT_CALL(session_observer_mock, OnApplicationFloodCallBack(connection_key))
+ .Times(1);
+
+ ON_CALL(protocol_handler_settings_mock, message_frequency_time())
+ .WillByDefault(Return(period_msec));
+ ON_CALL(protocol_handler_settings_mock, message_frequency_count())
+ .WillByDefault(Return(max_messages));
for (size_t i = 0; i < max_messages + 1; ++i) {
- SendTMMessage(connection_id, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kControl, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
}
}
-TEST_F(ProtocolHandlerImplTest,
- FloodVerification_ThresholdValue) {
+TEST_F(ProtocolHandlerImplTest, FloodVerification_ThresholdValue) {
const size_t period_msec = 10000;
const size_t max_messages = 1000;
InitProtocolHandlerImpl(period_msec, max_messages);
AddConnection();
AddSession();
- // expect NO flood notification to CH
+ ON_CALL(protocol_handler_settings_mock, message_frequency_time())
+ .WillByDefault(Return(period_msec));
+ ON_CALL(protocol_handler_settings_mock, message_frequency_count())
+ .WillByDefault(Return(max_messages));
+
+ // Expect NO flood notification to CH
+ EXPECT_CALL(session_observer_mock, OnApplicationFloodCallBack(connection_key))
+ .Times(0);
for (size_t i = 0; i < max_messages - 1; ++i) {
- SendTMMessage(connection_id, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kControl, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
}
}
-TEST_F(ProtocolHandlerImplTest,
- FloodVerification_VideoFrameSkip) {
+TEST_F(ProtocolHandlerImplTest, FloodVerification_VideoFrameSkip) {
const size_t period_msec = 10000;
const size_t max_messages = 1000;
InitProtocolHandlerImpl(period_msec, max_messages);
AddConnection();
AddSession();
- // expect NO flood notification to CH on video data streaming
+ // Expect NO flood notification to CH on video data streaming
for (size_t i = 0; i < max_messages + 1; ++i) {
- SendTMMessage(connection_id, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kMobileNav, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kMobileNav,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
}
}
-TEST_F(ProtocolHandlerImplTest,
- FloodVerification_AudioFrameSkip) {
+TEST_F(ProtocolHandlerImplTest, FloodVerification_AudioFrameSkip) {
const size_t period_msec = 10000;
const size_t max_messages = 1000;
InitProtocolHandlerImpl(period_msec, max_messages);
AddConnection();
AddSession();
- // expect NO flood notification to CH on video data streaming
+ // Expect NO flood notification to CH on video data streaming
for (size_t i = 0; i < max_messages + 1; ++i) {
- SendTMMessage(connection_id, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kAudio, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kAudio,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
}
}
-TEST_F(ProtocolHandlerImplTest,
- FloodVerificationDisable) {
+TEST_F(ProtocolHandlerImplTest, FloodVerificationDisable) {
const size_t period_msec = 0;
const size_t max_messages = 0;
InitProtocolHandlerImpl(period_msec, max_messages);
AddConnection();
AddSession();
- // expect NO flood notification to session observer
+ // Expect NO flood notification to session observer
for (size_t i = 0; i < max_messages + 1; ++i) {
- SendTMMessage(connection_id, PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kControl, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
}
}
-
-TEST_F(ProtocolHandlerImplTest,
- MalformedVerificationDisable) {
+TEST_F(ProtocolHandlerImplTest, MalformedVerificationDisable) {
const size_t period_msec = 10000;
const size_t max_messages = 100;
InitProtocolHandlerImpl(0u, 0u, false, period_msec, max_messages);
AddConnection();
AddSession();
- // expect malformed notification to CH
- EXPECT_CALL(session_observer_mock,
- OnMalformedMessageCallback(connection_id)).
- Times(max_messages);
+ // Expect malformed notification to CH
+ EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id))
+ .Times(max_messages);
const uint8_t malformed_version = PROTOCOL_VERSION_MAX;
for (size_t i = 0; i < max_messages; ++i) {
- SendTMMessage(connection_id, malformed_version, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kControl, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ malformed_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
}
}
-TEST_F(ProtocolHandlerImplTest,
- MalformedLimitVerification) {
+TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification) {
const size_t period_msec = 10000;
const size_t max_messages = 100;
InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages);
AddConnection();
AddSession();
- // expect malformed notification to CH
- EXPECT_CALL(session_observer_mock,
- OnMalformedMessageCallback(connection_id)).
- Times(1);
+ // Expect malformed notification to CH
+ EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id))
+ .Times(1);
// Sending malformed packets
const uint8_t malformed_version = PROTOCOL_VERSION_MAX;
for (size_t i = 0; i < max_messages * 2; ++i) {
// Malformed message
- SendTMMessage(connection_id, malformed_version, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kControl, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ malformed_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
// Common message
- SendTMMessage(connection_id, PROTOCOL_VERSION_1, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kControl, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ PROTOCOL_VERSION_1,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
}
}
-TEST_F(ProtocolHandlerImplTest,
- MalformedLimitVerification_MalformedStock) {
+TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_MalformedStock) {
const size_t period_msec = 10000;
const size_t max_messages = 100;
InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages);
AddConnection();
AddSession();
- // expect malformed notification to CH
- EXPECT_CALL(session_observer_mock,
- OnMalformedMessageCallback(connection_id)).
- Times(1);
+ // Expect malformed notification to CH
+ EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id))
+ .Times(1);
// Sending malformed packets
const uint8_t malformed_version = PROTOCOL_VERSION_MAX;
@@ -834,37 +1113,63 @@ TEST_F(ProtocolHandlerImplTest,
const uint8_t malformed_service_type = kInvalidServiceType;
for (size_t i = 0; i < max_messages * 2; ++i) {
// Malformed message 1
- SendTMMessage(connection_id, malformed_version, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kControl, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ malformed_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
// Malformed message 2
- SendTMMessage(connection_id, PROTOCOL_VERSION_1, PROTECTION_OFF, malformed_frame_type,
- kControl, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ PROTOCOL_VERSION_1,
+ PROTECTION_OFF,
+ malformed_frame_type,
+ kControl,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
// Malformed message 3
- SendTMMessage(connection_id, PROTOCOL_VERSION_1, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- malformed_service_type, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ PROTOCOL_VERSION_1,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ malformed_service_type,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
// Common message
- SendTMMessage(connection_id, PROTOCOL_VERSION_1, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kControl, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ PROTOCOL_VERSION_1,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
}
}
-TEST_F(ProtocolHandlerImplTest,
- MalformedLimitVerification_MalformedOnly) {
+TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_MalformedOnly) {
const size_t period_msec = 10000;
const size_t max_messages = 100;
InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages);
AddConnection();
AddSession();
- // expect NO malformed notification to CH
- EXPECT_CALL(session_observer_mock,
- OnMalformedMessageCallback(connection_id)).
- Times(0);
+ // Expect NO malformed notification to CH
+ EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id))
+ .Times(0);
// Sending malformed packets
const uint8_t malformed_version = PROTOCOL_VERSION_MAX;
@@ -872,65 +1177,318 @@ TEST_F(ProtocolHandlerImplTest,
const uint8_t malformed_service_type = kInvalidServiceType;
for (size_t i = 0; i < max_messages * 2; ++i) {
// Malformed message 1
- SendTMMessage(connection_id, malformed_version, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kControl, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ malformed_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
// Malformed message 2
- SendTMMessage(connection_id, PROTOCOL_VERSION_1, PROTECTION_OFF, malformed_frame_type,
- kControl, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ PROTOCOL_VERSION_1,
+ PROTECTION_OFF,
+ malformed_frame_type,
+ kControl,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
// Malformed message 3
- SendTMMessage(connection_id, PROTOCOL_VERSION_1, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- malformed_service_type, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ PROTOCOL_VERSION_1,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ malformed_service_type,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
// No common message
}
}
-TEST_F(ProtocolHandlerImplTest,
- MalformedLimitVerification_NullTimePeriod) {
+TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_NullTimePeriod) {
const size_t period_msec = 0;
const size_t max_messages = 1000;
InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages);
AddConnection();
AddSession();
- // expect no malformed notification to CH
- EXPECT_CALL(session_observer_mock,
- OnMalformedMessageCallback(connection_id)).
- Times(0);
+ // Expect no malformed notification to CH
+ EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id))
+ .Times(0);
// Sending malformed packets
const uint8_t malformed_version = PROTOCOL_VERSION_MAX;
for (size_t i = 0; i < max_messages + 1; ++i) {
- SendTMMessage(connection_id, malformed_version, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kControl, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ malformed_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
}
}
-TEST_F(ProtocolHandlerImplTest,
- MalformedLimitVerification_NullCount) {
+TEST_F(ProtocolHandlerImplTest, MalformedLimitVerification_NullCount) {
const size_t period_msec = 10000;
const size_t max_messages = 0;
InitProtocolHandlerImpl(0u, 0u, true, period_msec, max_messages);
AddConnection();
AddSession();
- // expect no malformed notification to CH
- EXPECT_CALL(session_observer_mock,
- OnMalformedMessageCallback(connection_id)).
- Times(0);
+ // Expect no malformed notification to CH
+ EXPECT_CALL(session_observer_mock, OnMalformedMessageCallback(connection_id))
+ .Times(0);
// Sending malformed packets
const uint8_t malformed_version = PROTOCOL_VERSION_MAX;
for (size_t i = 0; i < max_messages + 1; ++i) {
- SendTMMessage(connection_id, malformed_version, PROTECTION_OFF, FRAME_TYPE_SINGLE,
- kControl, FRAME_DATA_SINGLE, session_id,
- some_data.size(), message_id, &some_data[0]);
+ SendTMMessage(connection_id,
+ malformed_version,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ session_id,
+ some_data.size(),
+ message_id,
+ &some_data[0]);
}
}
-} // namespace test
-} // namespace components
+TEST_F(ProtocolHandlerImplTest,
+ SendEndServicePrivate_NoConnection_MessageNotSent) {
+ // Expect check connection with ProtocolVersionUsed
+ EXPECT_CALL(session_observer_mock,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(false));
+ // Expect not send End Service
+ EXPECT_CALL(transport_manager_mock, SendMessageToDevice(_)).Times(0);
+ // Act
+ protocol_handler_impl->SendEndSession(connection_id, session_id);
+}
+
+TEST_F(ProtocolHandlerImplTest, SendEndServicePrivate_EndSession_MessageSent) {
+ // Arrange
+ AddSession();
+ // Expect check connection with ProtocolVersionUsed
+ EXPECT_CALL(session_observer_mock,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(true));
+ // Expect send End Service
+ EXPECT_CALL(
+ transport_manager_mock,
+ SendMessageToDevice(ExpectedMessage(
+ FRAME_TYPE_CONTROL, FRAME_DATA_END_SERVICE, PROTECTION_OFF, kRpc)))
+ .WillOnce(Return(E_SUCCESS));
+ // Act
+ protocol_handler_impl->SendEndSession(connection_id, session_id);
+}
+
+TEST_F(ProtocolHandlerImplTest,
+ SendEndServicePrivate_ServiceTypeControl_MessageSent) {
+ // Arrange
+ AddSession();
+ // Expect check connection with ProtocolVersionUsed
+ EXPECT_CALL(session_observer_mock,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(true));
+ // Expect send End Service
+ EXPECT_CALL(transport_manager_mock,
+ SendMessageToDevice(ExpectedMessage(FRAME_TYPE_CONTROL,
+ FRAME_DATA_END_SERVICE,
+ PROTECTION_OFF,
+ kControl)))
+ .WillOnce(Return(E_SUCCESS));
+ // Act
+ protocol_handler_impl->SendEndService(connection_id, session_id, kControl);
+}
+
+TEST_F(ProtocolHandlerImplTest, SendHeartBeat_NoConnection_NotSent) {
+ // Expect check connection with ProtocolVersionUsed
+ EXPECT_CALL(session_observer_mock,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(false));
+ // Expect not send HeartBeat
+ EXPECT_CALL(transport_manager_mock, SendMessageToDevice(_)).Times(0);
+ // Act
+ protocol_handler_impl->SendHeartBeat(connection_id, session_id);
+}
+
+TEST_F(ProtocolHandlerImplTest, SendHeartBeat_Successful) {
+ // Arrange
+ AddSession();
+ // Expect check connection with ProtocolVersionUsed
+ EXPECT_CALL(session_observer_mock,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(true));
+ // Expect send HeartBeat
+ EXPECT_CALL(
+ transport_manager_mock,
+ SendMessageToDevice(ExpectedMessage(
+ FRAME_TYPE_CONTROL, FRAME_DATA_HEART_BEAT, PROTECTION_OFF, kControl)))
+ .WillOnce(Return(E_SUCCESS));
+ // Act
+ protocol_handler_impl->SendHeartBeat(connection_id, session_id);
+}
+
+TEST_F(ProtocolHandlerImplTest, SendHeartBeatAck_Successful) {
+ // Arrange
+ AddSession();
+ // Expect double check connection and protocol version with
+ // ProtocolVersionUsed
+ EXPECT_CALL(session_observer_mock, ProtocolVersionUsed(connection_id, _, _))
+ .WillRepeatedly(
+ DoAll(SetArgReferee<2>(PROTOCOL_VERSION_3), Return(true)));
+ // Expect send HeartBeatAck
+ EXPECT_CALL(transport_manager_mock,
+ SendMessageToDevice(ExpectedMessage(FRAME_TYPE_CONTROL,
+ FRAME_DATA_HEART_BEAT_ACK,
+ PROTECTION_OFF,
+ kControl)))
+ .WillOnce(Return(E_SUCCESS));
+ // Act
+ SendControlMessage(
+ PROTECTION_OFF, kControl, session_id, FRAME_DATA_HEART_BEAT);
+}
+
+TEST_F(ProtocolHandlerImplTest, SendHeartBeatAck_WrongProtocolVersion_NotSent) {
+ // Arrange
+ AddSession();
+ // Expect two checks of connection and protocol version with
+ // ProtocolVersionUsed
+ EXPECT_CALL(session_observer_mock, ProtocolVersionUsed(connection_id, _, _))
+ .Times(2)
+ .WillRepeatedly(
+ DoAll(SetArgReferee<2>(PROTOCOL_VERSION_1), Return(true)));
+ // Expect not send HeartBeatAck
+ EXPECT_CALL(transport_manager_mock,
+ SendMessageToDevice(ExpectedMessage(FRAME_TYPE_CONTROL,
+ FRAME_DATA_HEART_BEAT_ACK,
+ PROTECTION_OFF,
+ kControl))).Times(0);
+ // Act
+ SendControlMessage(
+ PROTECTION_OFF, kControl, session_id, FRAME_DATA_HEART_BEAT);
+ SendControlMessage(
+ PROTECTION_OFF, kControl, session_id, FRAME_DATA_HEART_BEAT);
+}
+
+TEST_F(ProtocolHandlerImplTest,
+ SendMessageToMobileApp_SendSingleControlMessage) {
+ // Arrange
+ AddSession();
+ const bool is_final = true;
+ const uint32_t total_data_size = 1;
+ UCharDataVector data(total_data_size);
+ RawMessagePtr message = utils::MakeShared<RawMessage>(
+ connection_key, PROTOCOL_VERSION_3, &data[0], total_data_size, kControl);
+ // Expect getting pair from key from session observer
+ EXPECT_CALL(session_observer_mock,
+ PairFromKey(message->connection_key(), _, _))
+ .WillOnce(
+ DoAll(SetArgPointee<1>(connection_id), SetArgPointee<2>(session_id)));
+// Expect getting ssl context
+#ifdef ENABLE_SECURITY
+ EXPECT_CALL(session_observer_mock,
+ GetSSLContext(message->connection_key(), message->service_type()))
+ .WillOnce(Return(&ssl_context_mock));
+#endif // ENABLE_SECURITY
+ // Expect send message to mobile
+ EXPECT_CALL(
+ transport_manager_mock,
+ SendMessageToDevice(ExpectedMessage(
+ FRAME_TYPE_SINGLE, FRAME_DATA_SINGLE, PROTECTION_OFF, kControl)))
+ .WillOnce(Return(E_SUCCESS));
+ // Act
+ protocol_handler_impl->SendMessageToMobileApp(message, is_final);
+}
+
+TEST_F(ProtocolHandlerImplTest,
+ SendMessageToMobileApp_SendSingleNonControlMessage) {
+ // Arrange
+ AddSession();
+ const bool is_final = true;
+ const uint32_t total_data_size = 1;
+ UCharDataVector data(total_data_size);
+ RawMessagePtr message = utils::MakeShared<RawMessage>(
+ connection_key, PROTOCOL_VERSION_3, &data[0], total_data_size, kRpc);
+ // Expect getting pair from key from session observer
+ EXPECT_CALL(session_observer_mock,
+ PairFromKey(message->connection_key(), _, _))
+ .WillOnce(
+ DoAll(SetArgPointee<1>(connection_id), SetArgPointee<2>(session_id)));
+// Expect getting ssl context
+#ifdef ENABLE_SECURITY
+ EXPECT_CALL(session_observer_mock,
+ GetSSLContext(message->connection_key(), message->service_type()))
+ .Times(2)
+ .WillRepeatedly(Return(&ssl_context_mock));
+ AddSecurityManager();
+#endif // ENABLE_SECURITY
+ // Expect send message to mobile
+ EXPECT_CALL(transport_manager_mock,
+ SendMessageToDevice(ExpectedMessage(
+ FRAME_TYPE_SINGLE, FRAME_DATA_SINGLE, PROTECTION_OFF, kRpc)))
+ .WillOnce(Return(E_SUCCESS));
+ // Act
+ protocol_handler_impl->SendMessageToMobileApp(message, is_final);
+}
+
+TEST_F(ProtocolHandlerImplTest, SendMessageToMobileApp_SendMultiframeMessage) {
+ // Arrange
+ AddSession();
+ const bool is_final = true;
+ const uint32_t total_data_size = MAXIMUM_FRAME_DATA_V2_SIZE * 2;
+ UCharDataVector data(total_data_size);
+ const uint8_t first_consecutive_frame = 0x01;
+ RawMessagePtr message = utils::MakeShared<RawMessage>(
+ connection_key, PROTOCOL_VERSION_3, &data[0], total_data_size, kBulk);
+ // Expect getting pair from key from session observer
+ EXPECT_CALL(session_observer_mock,
+ PairFromKey(message->connection_key(), _, _))
+ .WillOnce(
+ DoAll(SetArgPointee<1>(connection_id), SetArgPointee<2>(session_id)));
+// Expect getting ssl context
+#ifdef ENABLE_SECURITY
+ EXPECT_CALL(session_observer_mock,
+ GetSSLContext(message->connection_key(), message->service_type()))
+ .Times(4)
+ .WillRepeatedly(Return(&ssl_context_mock));
+ AddSecurityManager();
+#endif // ENABLE_SECURITY
+ // Expect sending message frame by frame to mobile
+ EXPECT_CALL(transport_manager_mock,
+ SendMessageToDevice(ExpectedMessage(
+ FRAME_TYPE_FIRST, FRAME_DATA_FIRST, PROTECTION_OFF, kBulk)))
+ .WillOnce(Return(E_SUCCESS));
+ EXPECT_CALL(transport_manager_mock,
+ SendMessageToDevice(ExpectedMessage(FRAME_TYPE_CONSECUTIVE,
+ first_consecutive_frame,
+ PROTECTION_OFF,
+ kBulk)))
+ .WillOnce(Return(E_SUCCESS));
+ EXPECT_CALL(transport_manager_mock,
+ SendMessageToDevice(ExpectedMessage(FRAME_TYPE_CONSECUTIVE,
+ FRAME_DATA_LAST_CONSECUTIVE,
+ PROTECTION_OFF,
+ kBulk)))
+ .WillOnce(Return(E_SUCCESS));
+ // Act
+ protocol_handler_impl->SendMessageToMobileApp(message, is_final);
+}
+
} // namespace protocol_handler_test
+} // namespace components
+} // namespace test
diff --git a/src/components/protocol_handler/test/protocol_header_validator_test.cc b/src/components/protocol_handler/test/protocol_header_validator_test.cc
index 0f38ae98ab..40b0f34846 100644
--- a/src/components/protocol_handler/test/protocol_header_validator_test.cc
+++ b/src/components/protocol_handler/test/protocol_header_validator_test.cc
@@ -38,7 +38,7 @@
#include "protocol_handler/protocol_packet.h"
namespace {
- const size_t MAXIMUM_FRAME_DATA_V3_SIZE = 131072;
+const size_t MAXIMUM_FRAME_DATA_V3_SIZE = 131072;
}
namespace test {
@@ -67,28 +67,37 @@ TEST_F(ProtocolHeaderValidatorTest, MaxPayloadSizeSetGet) {
}
}
-// Protocol version shall be from 1 to 3
+// Protocol version shall be from 1 to 4
TEST_F(ProtocolHeaderValidatorTest, Malformed_Version) {
std::vector<uint8_t> malformed_versions;
malformed_versions.push_back(0);
- for (uint8_t version = PROTOCOL_VERSION_4 + 1; version <= PROTOCOL_VERSION_MAX; ++version) {
+ for (uint8_t version = PROTOCOL_VERSION_4 + 1;
+ version <= PROTOCOL_VERSION_MAX;
+ ++version) {
malformed_versions.push_back(version);
}
for (size_t i = 0; i < malformed_versions.size(); ++i) {
const ProtocolPacket::ProtocolHeader malformed_message_header(
- malformed_versions[i], PROTECTION_OFF, FRAME_TYPE_CONTROL, kControl,
- FRAME_DATA_HEART_BEAT, some_session_id, 0u, some_message_id);
+ malformed_versions[i],
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
+ some_message_id);
EXPECT_EQ(RESULT_FAIL, header_validator.validate(malformed_message_header))
<< "Malformed version " << malformed_message_header.version;
-
}
}
-// ServiceType shall be equal 0x0 (Control), 0x07 (RPC), 0x0A (PCM), 0x0B (Video), 0x0F (Bulk)
+// ServiceType shall be equal 0x0 (Control), 0x07 (RPC), 0x0A (PCM), 0x0B
+// (Video), 0x0F (Bulk)
TEST_F(ProtocolHeaderValidatorTest, Malformed_ServiceType) {
std::vector<uint8_t> malformed_serv_types;
- for (uint8_t service_type = kControl + 1; service_type < kRpc; ++service_type) {
+ for (uint8_t service_type = kControl + 1; service_type < kRpc;
+ ++service_type) {
malformed_serv_types.push_back(service_type);
}
malformed_serv_types.push_back(0x08);
@@ -99,58 +108,89 @@ TEST_F(ProtocolHeaderValidatorTest, Malformed_ServiceType) {
for (size_t i = 0; i < malformed_serv_types.size(); ++i) {
const ProtocolPacket::ProtocolHeader malformed_message_header(
- PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_CONTROL, malformed_serv_types[i],
- FRAME_DATA_HEART_BEAT, some_session_id, 0u, some_message_id);
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ malformed_serv_types[i],
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
+ some_message_id);
EXPECT_EQ(RESULT_FAIL, header_validator.validate(malformed_message_header))
<< "Malformed service type " << malformed_message_header.serviceType;
}
}
-// Frame type shall be 0x00 (Control), 0x01 (Single), 0x02 (First), 0x03 (Consecutive)
+// Frame type shall be 0x00 (Control), 0x01 (Single), 0x02 (First), 0x03
+// (Consecutive)
TEST_F(ProtocolHeaderValidatorTest, Malformed_FrameType) {
std::vector<uint8_t> malformed_frame_types;
for (uint8_t frame_type = FRAME_TYPE_CONSECUTIVE + 1;
- frame_type <= FRAME_TYPE_MAX_VALUE; ++frame_type) {
+ frame_type <= FRAME_TYPE_MAX_VALUE;
+ ++frame_type) {
malformed_frame_types.push_back(frame_type);
}
for (size_t i = 0; i < malformed_frame_types.size(); ++i) {
const ProtocolPacket::ProtocolHeader malformed_message_header(
- PROTOCOL_VERSION_3, PROTECTION_OFF, malformed_frame_types[i],
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u, some_message_id);
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ malformed_frame_types[i],
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
+ some_message_id);
EXPECT_EQ(RESULT_FAIL, header_validator.validate(malformed_message_header))
<< "Malformed frame type " << malformed_message_header.frameType;
}
}
-// For Control frames Frame info value shall be from 0x00 to 0x06 or 0xFE(Data Ack), 0xFF(HB Ack)
+// For Control frames Frame info value shall be from 0x00 to 0x06 or 0xFE(Data
+// Ack), 0xFF(HB Ack)
TEST_F(ProtocolHeaderValidatorTest, Malformed_ControlFrame) {
std::vector<uint8_t> malformed_frame_data;
for (uint8_t frame_type = FRAME_DATA_END_SERVICE_NACK + 1;
- frame_type < FRAME_DATA_SERVICE_DATA_ACK; ++frame_type) {
+ frame_type < FRAME_DATA_SERVICE_DATA_ACK;
+ ++frame_type) {
malformed_frame_data.push_back(frame_type);
}
for (size_t i = 0; i < malformed_frame_data.size(); ++i) {
const ProtocolPacket::ProtocolHeader malformed_message_header(
- PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_CONTROL, kControl,
- malformed_frame_data[i], some_session_id, 0u, some_message_id);
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ malformed_frame_data[i],
+ some_session_id,
+ 0u,
+ some_message_id);
EXPECT_EQ(RESULT_FAIL, header_validator.validate(malformed_message_header))
- << "Malformed Control frame with data " << malformed_message_header.frameData;
+ << "Malformed Control frame with data "
+ << malformed_message_header.frameData;
}
}
// For Single and First frames Frame info value shall be equal 0x00
TEST_F(ProtocolHeaderValidatorTest, Malformed_SingleFrame) {
std::vector<uint8_t> malformed_frame_data;
for (uint8_t frame_type = FRAME_DATA_SINGLE + 1;
- frame_type < FRAME_DATA_MAX_VALUE; ++frame_type) {
+ frame_type < FRAME_DATA_MAX_VALUE;
+ ++frame_type) {
malformed_frame_data.push_back(frame_type);
}
malformed_frame_data.push_back(FRAME_DATA_MAX_VALUE);
for (size_t i = 0; i < malformed_frame_data.size(); ++i) {
const ProtocolPacket::ProtocolHeader malformed_message_header(
- PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_SINGLE, kControl,
- malformed_frame_data[i], some_session_id, 0u, some_message_id);
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ malformed_frame_data[i],
+ some_session_id,
+ 0u,
+ some_message_id);
EXPECT_EQ(RESULT_FAIL, header_validator.validate(malformed_message_header))
- << "Malformed Single frame with data " << malformed_message_header.frameData;
+ << "Malformed Single frame with data "
+ << malformed_message_header.frameData;
// All malformed messages shall be ignored
}
}
@@ -159,40 +199,68 @@ TEST_F(ProtocolHeaderValidatorTest, Malformed_SingleFrame) {
TEST_F(ProtocolHeaderValidatorTest, Malformed_FirstFrame) {
std::vector<uint8_t> malformed_frame_data;
for (uint8_t frame_type = FRAME_DATA_FIRST + 1;
- frame_type < FRAME_DATA_MAX_VALUE; ++frame_type) {
+ frame_type < FRAME_DATA_MAX_VALUE;
+ ++frame_type) {
malformed_frame_data.push_back(frame_type);
}
malformed_frame_data.push_back(FRAME_DATA_MAX_VALUE);
for (size_t i = 0; i < malformed_frame_data.size(); ++i) {
const ProtocolPacket::ProtocolHeader malformed_message_header(
- PROTOCOL_VERSION_3, PROTECTION_OFF, FRAME_TYPE_SINGLE, kControl,
- malformed_frame_data[i], some_session_id, 0u, some_message_id);
+ PROTOCOL_VERSION_3,
+ PROTECTION_OFF,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ malformed_frame_data[i],
+ some_session_id,
+ 0u,
+ some_message_id);
EXPECT_EQ(RESULT_FAIL, header_validator.validate(malformed_message_header))
- << "Malformed First frame with data " << malformed_message_header.frameData;
+ << "Malformed First frame with data "
+ << malformed_message_header.frameData;
}
}
TEST_F(ProtocolHeaderValidatorTest, Malformed_ControlFrame_EmptyPayload) {
const size_t payload_size = 0u;
const ProtocolPacket::ProtocolHeader control_message_header(
- PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_CONTROL, kControl,
- FRAME_DATA_HEART_BEAT, some_session_id, payload_size, some_message_id);
- const ProtocolPacket::ProtocolHeader single_message_header(
- PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_SINGLE, kControl,
- FRAME_DATA_SINGLE, some_session_id, payload_size, some_message_id);
+ PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ payload_size,
+ some_message_id);
+ const ProtocolPacket::ProtocolHeader single_message_header(PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ some_session_id,
+ payload_size,
+ some_message_id);
const ProtocolPacket::ProtocolHeader consecutive_message_header(
- PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_CONSECUTIVE, kControl,
- FRAME_DATA_LAST_CONSECUTIVE, some_session_id, payload_size, some_message_id);
+ PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_CONSECUTIVE,
+ kControl,
+ FRAME_DATA_LAST_CONSECUTIVE,
+ some_session_id,
+ payload_size,
+ some_message_id);
- for (size_t max_payload_size = 0; max_payload_size < MAXIMUM_FRAME_DATA_V3_SIZE * 2;
+ for (size_t max_payload_size = 0;
+ max_payload_size < MAXIMUM_FRAME_DATA_V3_SIZE * 2;
++max_payload_size) {
- header_validator.set_max_payload_size(MAXIMUM_FRAME_DATA_V3_SIZE + max_payload_size);
+ header_validator.set_max_payload_size(MAXIMUM_FRAME_DATA_V3_SIZE +
+ max_payload_size);
// For Control frames Data Size value could be zero
EXPECT_EQ(RESULT_OK, header_validator.validate(control_message_header));
// For Control frames Data Size value could be zero
EXPECT_EQ(RESULT_FAIL, header_validator.validate(single_message_header));
- EXPECT_EQ(RESULT_FAIL, header_validator.validate(consecutive_message_header));
+ EXPECT_EQ(RESULT_FAIL,
+ header_validator.validate(consecutive_message_header));
}
}
@@ -200,14 +268,31 @@ TEST_F(ProtocolHeaderValidatorTest, Malformed_ControlFrame_EmptyPayload) {
TEST_F(ProtocolHeaderValidatorTest, Malformed_Payload_V2) {
const size_t payload_size = MAXIMUM_FRAME_DATA_V2_SIZE;
const ProtocolPacket::ProtocolHeader control_message_header(
- PROTOCOL_VERSION_2, PROTECTION_ON, FRAME_TYPE_CONTROL, kControl,
- FRAME_DATA_HEART_BEAT, some_session_id, payload_size, some_message_id);
- const ProtocolPacket::ProtocolHeader single_message_header(
- PROTOCOL_VERSION_2, PROTECTION_ON, FRAME_TYPE_SINGLE, kControl,
- FRAME_DATA_SINGLE, some_session_id, payload_size, some_message_id);
+ PROTOCOL_VERSION_2,
+ PROTECTION_ON,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ payload_size,
+ some_message_id);
+ const ProtocolPacket::ProtocolHeader single_message_header(PROTOCOL_VERSION_2,
+ PROTECTION_ON,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ some_session_id,
+ payload_size,
+ some_message_id);
const ProtocolPacket::ProtocolHeader consecutive_message_header(
- PROTOCOL_VERSION_2, PROTECTION_ON, FRAME_TYPE_CONSECUTIVE, kControl,
- FRAME_DATA_LAST_CONSECUTIVE, some_session_id, payload_size, some_message_id);
+ PROTOCOL_VERSION_2,
+ PROTECTION_ON,
+ FRAME_TYPE_CONSECUTIVE,
+ kControl,
+ FRAME_DATA_LAST_CONSECUTIVE,
+ some_session_id,
+ payload_size,
+ some_message_id);
for (size_t max_payload_size = 0;
max_payload_size < MAXIMUM_FRAME_DATA_V3_SIZE * 2;
@@ -222,14 +307,31 @@ TEST_F(ProtocolHeaderValidatorTest, Malformed_Payload_V2) {
TEST_F(ProtocolHeaderValidatorTest, Malformed_Payload_V3) {
const size_t payload_size = MAXIMUM_FRAME_DATA_V3_SIZE;
const ProtocolPacket::ProtocolHeader control_message_header(
- PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_CONTROL, kControl,
- FRAME_DATA_HEART_BEAT, some_session_id, payload_size, some_message_id);
- const ProtocolPacket::ProtocolHeader single_message_header(
- PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_SINGLE, kControl,
- FRAME_DATA_SINGLE, some_session_id, payload_size, some_message_id);
+ PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ payload_size,
+ some_message_id);
+ const ProtocolPacket::ProtocolHeader single_message_header(PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ some_session_id,
+ payload_size,
+ some_message_id);
const ProtocolPacket::ProtocolHeader consecutive_message_header(
- PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_CONSECUTIVE, kControl,
- FRAME_DATA_LAST_CONSECUTIVE, some_session_id, payload_size, some_message_id);
+ PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_CONSECUTIVE,
+ kControl,
+ FRAME_DATA_LAST_CONSECUTIVE,
+ some_session_id,
+ payload_size,
+ some_message_id);
for (size_t max_payload_size = 0;
max_payload_size < MAXIMUM_FRAME_DATA_V3_SIZE;
@@ -237,7 +339,8 @@ TEST_F(ProtocolHeaderValidatorTest, Malformed_Payload_V3) {
header_validator.set_max_payload_size(max_payload_size);
EXPECT_EQ(RESULT_FAIL, header_validator.validate(control_message_header));
EXPECT_EQ(RESULT_FAIL, header_validator.validate(single_message_header));
- EXPECT_EQ(RESULT_FAIL, header_validator.validate(consecutive_message_header));
+ EXPECT_EQ(RESULT_FAIL,
+ header_validator.validate(consecutive_message_header));
}
for (size_t max_payload_size = MAXIMUM_FRAME_DATA_V3_SIZE;
@@ -253,14 +356,31 @@ TEST_F(ProtocolHeaderValidatorTest, Malformed_Payload_V3) {
TEST_F(ProtocolHeaderValidatorTest, Malformed_Payload_V3_with_V2_size) {
const size_t payload_size = MAXIMUM_FRAME_DATA_V2_SIZE;
const ProtocolPacket::ProtocolHeader control_message_header(
- PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_CONTROL, kControl,
- FRAME_DATA_HEART_BEAT, some_session_id, payload_size, some_message_id);
- const ProtocolPacket::ProtocolHeader single_message_header(
- PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_SINGLE, kControl,
- FRAME_DATA_SINGLE, some_session_id, payload_size, some_message_id);
+ PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_CONTROL,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ payload_size,
+ some_message_id);
+ const ProtocolPacket::ProtocolHeader single_message_header(PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_SINGLE,
+ kControl,
+ FRAME_DATA_SINGLE,
+ some_session_id,
+ payload_size,
+ some_message_id);
const ProtocolPacket::ProtocolHeader consecutive_message_header(
- PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_CONSECUTIVE, kControl,
- FRAME_DATA_LAST_CONSECUTIVE, some_session_id, payload_size, some_message_id);
+ PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_CONSECUTIVE,
+ kControl,
+ FRAME_DATA_LAST_CONSECUTIVE,
+ some_session_id,
+ payload_size,
+ some_message_id);
for (size_t max_payload_size = 0;
max_payload_size < MAXIMUM_FRAME_DATA_V3_SIZE * 2;
@@ -275,9 +395,14 @@ TEST_F(ProtocolHeaderValidatorTest, Malformed_Payload_V3_with_V2_size) {
// Message ID be equal or greater than 0x01
TEST_F(ProtocolHeaderValidatorTest, Malformed_MessageID) {
const uint32_t malformed_message_id = 0x0u;
- ProtocolPacket::ProtocolHeader message_header(
- PROTOCOL_VERSION_3, PROTECTION_ON, FRAME_TYPE_FIRST, kControl,
- FRAME_DATA_HEART_BEAT, some_session_id, 0u, malformed_message_id);
+ ProtocolPacket::ProtocolHeader message_header(PROTOCOL_VERSION_3,
+ PROTECTION_ON,
+ FRAME_TYPE_FIRST,
+ kControl,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id,
+ 0u,
+ malformed_message_id);
message_header.frameType = FRAME_TYPE_FIRST;
message_header.version = PROTOCOL_VERSION_1;
diff --git a/src/components/protocol_handler/test/protocol_packet_test.cc b/src/components/protocol_handler/test/protocol_packet_test.cc
index 66fbe6f0a1..7819c4b5b0 100644
--- a/src/components/protocol_handler/test/protocol_packet_test.cc
+++ b/src/components/protocol_handler/test/protocol_packet_test.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,45 +30,84 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include <gtest/gtest.h>
+#include "gtest/gtest.h"
#include <vector>
-#include <list>
#include "utils/macro.h"
#include "protocol_handler/protocol_packet.h"
+#include "protocol/common.h"
namespace test {
namespace components {
namespace protocol_handler_test {
-using namespace ::protocol_handler;
+
+using protocol_handler::RawMessagePtr;
+using protocol_handler::ProtocolPacket;
+using protocol_handler::ConnectionID;
+using protocol_handler::FRAME_TYPE_MAX_VALUE;
+using protocol_handler::FRAME_DATA_FIRST;
+using protocol_handler::FRAME_TYPE_FIRST;
+using protocol_handler::PROTOCOL_VERSION_1;
+using protocol_handler::PROTOCOL_VERSION_3;
+using protocol_handler::PROTECTION_OFF;
+using protocol_handler::RESULT_CODE;
+using protocol_handler::RESULT_OK;
+using protocol_handler::RESULT_FAIL;
+using protocol_handler::FRAME_TYPE_CONTROL;
+using protocol_handler::kControl;
+using protocol_handler::kRpc;
+using protocol_handler::kAudio;
+using protocol_handler::kMobileNav;
+using protocol_handler::kBulk;
+using protocol_handler::kInvalidServiceType;
+using protocol_handler::FRAME_DATA_HEART_BEAT;
+using protocol_handler::FRAME_DATA_START_SERVICE_ACK;
+using protocol_handler::FRAME_DATA_LAST_CONSECUTIVE;
+using protocol_handler::PROTOCOL_HEADER_V1_SIZE;
+using protocol_handler::PROTOCOL_HEADER_V2_SIZE;
+using protocol_handler::PROTOCOL_VERSION_MAX;
class ProtocolPacketTest : public ::testing::Test {
protected:
void SetUp() OVERRIDE {
- some_message_id = 0xABCDEF0;
- some_session_id = 0xFEDCBA0;
- some_connection_id = 10;
+ some_message_id_ = 0xABCDEF0;
+ some_session_id_ = 0xFEDCBA0;
+ some_connection_id_ = 10;
+ }
+
+ RawMessagePtr GetRawMessage(uint8_t version,
+ uint8_t frame_type,
+ uint8_t service_type) {
+ ProtocolPacket prot_packet(some_connection_id_,
+ version,
+ PROTECTION_OFF,
+ frame_type,
+ service_type,
+ FRAME_DATA_HEART_BEAT,
+ some_session_id_,
+ 0u,
+ some_message_id_);
+ EXPECT_EQ(frame_type, prot_packet.frame_type());
+ return prot_packet.serializePacket();
}
- uint32_t some_message_id;
- uint32_t some_session_id;
- ConnectionID some_connection_id;
+
+ const uint8_t zero_test_data_element_ = 0x0u;
+ uint32_t some_message_id_;
+ uint32_t some_session_id_;
+ ConnectionID some_connection_id_;
};
TEST_F(ProtocolPacketTest, SerializePacketWithDiffVersions) {
- RawMessagePtr res;
uint8_t version = PROTOCOL_VERSION_1;
for (; version <= PROTOCOL_VERSION_MAX; ++version) {
- ProtocolPacket prot_packet(
- some_connection_id, version, PROTECTION_OFF, FRAME_TYPE_CONTROL,
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u, some_message_id);
- res = prot_packet.serializePacket();
- EXPECT_EQ(res->protocol_version(), version);
- EXPECT_EQ(res->service_type(), kControl);
- EXPECT_EQ(res->connection_key(), some_connection_id);
+ RawMessagePtr res = GetRawMessage(version, FRAME_TYPE_CONTROL, kControl);
+ EXPECT_EQ(version, res->protocol_version());
+ EXPECT_EQ(kControl, res->service_type());
+ EXPECT_EQ(some_connection_id_, res->connection_key());
if (res->protocol_version() == PROTOCOL_VERSION_1) {
- EXPECT_EQ(res->data_size(), 8u);
+ EXPECT_EQ(PROTOCOL_HEADER_V1_SIZE, res->data_size());
} else {
- EXPECT_EQ(res->data_size(), 12u);
+ EXPECT_EQ(PROTOCOL_HEADER_V2_SIZE, res->data_size());
}
}
}
@@ -77,22 +116,18 @@ TEST_F(ProtocolPacketTest, SerializePacketWithDiffVersions) {
// (Video), 0x0F (Bulk)
TEST_F(ProtocolPacketTest, SerializePacketWithDiffServiceType) {
std::vector<uint8_t> serv_types;
- serv_types.push_back(0x0);
- serv_types.push_back(0x07);
- serv_types.push_back(0x0A);
- serv_types.push_back(0x0B);
- serv_types.push_back(0x0F);
+ serv_types.push_back(kControl);
+ serv_types.push_back(kRpc);
+ serv_types.push_back(kAudio);
+ serv_types.push_back(kMobileNav);
+ serv_types.push_back(kBulk);
- RawMessagePtr res;
for (size_t i = 0; i < serv_types.size(); ++i) {
- ProtocolPacket prot_packet(some_connection_id, PROTOCOL_VERSION_3,
- PROTECTION_OFF, FRAME_TYPE_CONTROL,
- serv_types[i], FRAME_DATA_HEART_BEAT,
- some_session_id, 0u, some_message_id);
- res = prot_packet.serializePacket();
+ RawMessagePtr res =
+ GetRawMessage(PROTOCOL_VERSION_3, FRAME_TYPE_CONTROL, serv_types[i]);
EXPECT_EQ(PROTOCOL_VERSION_3, res->protocol_version());
EXPECT_EQ(serv_types[i], res->service_type());
- EXPECT_EQ(12u, res->data_size());
+ EXPECT_EQ(PROTOCOL_HEADER_V2_SIZE, res->data_size());
}
}
@@ -108,74 +143,65 @@ TEST_F(ProtocolPacketTest, SerializePacketWithWrongServiceType) {
serv_types.push_back(0x0D);
serv_types.push_back(0x0E);
- RawMessagePtr res;
for (size_t i = 0; i < serv_types.size(); ++i) {
- ProtocolPacket prot_packet(some_connection_id, PROTOCOL_VERSION_3,
- PROTECTION_OFF, FRAME_TYPE_CONTROL,
- serv_types[i], FRAME_DATA_HEART_BEAT,
- some_session_id, 0u, some_message_id);
- res = prot_packet.serializePacket();
+ RawMessagePtr res =
+ GetRawMessage(PROTOCOL_VERSION_3, FRAME_TYPE_CONTROL, serv_types[i]);
EXPECT_EQ(PROTOCOL_VERSION_3, res->protocol_version());
EXPECT_EQ(kInvalidServiceType, res->service_type());
}
}
TEST_F(ProtocolPacketTest, SetPacketWithDiffFrameType) {
- RawMessagePtr res;
uint8_t frame_type;
for (frame_type = FRAME_TYPE_CONTROL + 1; frame_type <= FRAME_TYPE_MAX_VALUE;
++frame_type) {
- ProtocolPacket prot_packet(
- some_connection_id, PROTOCOL_VERSION_3, PROTECTION_OFF, frame_type,
- kControl, FRAME_DATA_HEART_BEAT, some_session_id, 0u, some_message_id);
- res = prot_packet.serializePacket();
+ RawMessagePtr res = GetRawMessage(PROTOCOL_VERSION_3, frame_type, kControl);
EXPECT_EQ(PROTOCOL_VERSION_3, res->protocol_version());
EXPECT_EQ(kControl, res->service_type());
- EXPECT_EQ(frame_type, prot_packet.frame_type());
}
}
TEST_F(ProtocolPacketTest, AppendDataToEmptyPacket) {
// Set version, serviceType, frameData, sessionId
- uint8_t session_id = 1u;
- uint8_t some_data[] = {0x0, 0x07, 0x02, session_id};
+ const uint8_t session_id = 1u;
+ uint8_t some_data[] = {
+ zero_test_data_element_, kRpc, FRAME_DATA_START_SERVICE_ACK, session_id};
ProtocolPacket protocol_packet;
RESULT_CODE res = protocol_packet.appendData(some_data, sizeof(some_data));
EXPECT_EQ(RESULT_FAIL, res);
}
TEST_F(ProtocolPacketTest, SetTotalDataBytes) {
- uint8_t new_data_size = 10u;
+ const uint8_t new_data_size = 10u;
ProtocolPacket protocol_packet;
protocol_packet.set_total_data_bytes(new_data_size);
-
EXPECT_EQ(new_data_size, protocol_packet.total_data_bytes());
}
TEST_F(ProtocolPacketTest, AppendDataToPacketWithNonZeroSize) {
// Set version, serviceType, frameData, sessionId
- uint8_t session_id = 1u;
- uint8_t some_data[] = {0x0, 0x07, FRAME_TYPE_CONTROL, session_id};
+ const uint8_t session_id = 1u;
+ uint8_t some_data[] = {
+ zero_test_data_element_, kRpc, FRAME_DATA_LAST_CONSECUTIVE, session_id};
ProtocolPacket protocol_packet;
protocol_packet.set_total_data_bytes(sizeof(some_data) + 1);
RESULT_CODE res = protocol_packet.appendData(some_data, sizeof(some_data));
EXPECT_EQ(RESULT_OK, res);
-
- EXPECT_EQ(0x0, protocol_packet.data()[0]);
- EXPECT_EQ(0x07, protocol_packet.data()[1]);
- EXPECT_EQ(FRAME_TYPE_CONTROL, protocol_packet.data()[2]);
+ EXPECT_EQ(zero_test_data_element_, protocol_packet.data()[0]);
+ EXPECT_EQ(kRpc, protocol_packet.data()[1]);
+ EXPECT_EQ(FRAME_DATA_LAST_CONSECUTIVE, protocol_packet.data()[2]);
EXPECT_EQ(session_id, protocol_packet.data()[3]);
}
TEST_F(ProtocolPacketTest, SetData) {
- uint8_t session_id = 1u;
- uint8_t some_data[] = {0x0, 0x07, FRAME_TYPE_CONTROL, session_id};
+ const uint8_t session_id = 1u;
+ uint8_t some_data[] = {
+ zero_test_data_element_, kRpc, FRAME_DATA_HEART_BEAT, session_id};
ProtocolPacket protocol_packet;
protocol_packet.set_data(some_data, sizeof(some_data));
-
- EXPECT_EQ(0x0, protocol_packet.data()[0]);
- EXPECT_EQ(0x07, protocol_packet.data()[1]);
- EXPECT_EQ(FRAME_TYPE_CONTROL, protocol_packet.data()[2]);
+ EXPECT_EQ(zero_test_data_element_, protocol_packet.data()[0]);
+ EXPECT_EQ(kRpc, protocol_packet.data()[1]);
+ EXPECT_EQ(FRAME_DATA_HEART_BEAT, protocol_packet.data()[2]);
EXPECT_EQ(session_id, protocol_packet.data()[3]);
}
@@ -188,14 +214,49 @@ TEST_F(ProtocolPacketTest, DeserializeZeroPacket) {
TEST_F(ProtocolPacketTest, DeserializeNonZeroPacket) {
// Set header, serviceType, frameData, sessionId
- uint8_t session_id = 1u;
- uint8_t some_message[] = {0x21, 0x07, 0x02, session_id};
+ const uint8_t session_id = 1u;
+ const uint8_t version_frame_type = 0x21;
+ uint8_t some_message[] = {
+ version_frame_type, kRpc, FRAME_DATA_START_SERVICE_ACK, session_id};
ProtocolPacket protocol_packet;
RESULT_CODE res =
protocol_packet.deserializePacket(some_message, PROTOCOL_HEADER_V2_SIZE);
EXPECT_EQ(RESULT_OK, res);
}
+TEST_F(ProtocolPacketTest, DeserializePacket_FrameTypeFirst_ResultOK) {
+ // Arrange
+ const uint8_t session_id = 1u;
+ const uint8_t data_size = 1u;
+ const uint8_t version_frame_type = 0x22;
+ // Set protol version - 2 and frame type - first
+ uint8_t message[] = {version_frame_type,
+ kRpc,
+ FRAME_DATA_FIRST,
+ session_id,
+ zero_test_data_element_,
+ zero_test_data_element_,
+ zero_test_data_element_,
+ zero_test_data_element_,
+ zero_test_data_element_,
+ zero_test_data_element_,
+ zero_test_data_element_,
+ zero_test_data_element_,
+ zero_test_data_element_,
+ zero_test_data_element_,
+ zero_test_data_element_,
+ data_size,
+ zero_test_data_element_};
+ ProtocolPacket protocol_packet;
+ // Act
+ RESULT_CODE res =
+ protocol_packet.deserializePacket(message, PROTOCOL_HEADER_V2_SIZE);
+ uint8_t frame_type = protocol_packet.frame_type();
+ // Assert
+ EXPECT_EQ(FRAME_TYPE_FIRST, frame_type);
+ EXPECT_EQ(RESULT_OK, res);
+}
+
} // namespace protocol_handler_test
} // namespace components
} // namespace test
diff --git a/src/components/protocol_handler/test/protocol_payload_test.cc b/src/components/protocol_handler/test/protocol_payload_test.cc
index 3b973e1061..e56f8aadff 100644
--- a/src/components/protocol_handler/test/protocol_payload_test.cc
+++ b/src/components/protocol_handler/test/protocol_payload_test.cc
@@ -49,7 +49,8 @@ void prepare_data(uint8_t* data_for_sending, ProtocolPayloadV2& message) {
uint8_t offset = 0;
uint32_t function_id = message.header.rpc_function_id;
- data_for_sending[offset++] = ((rpc_type_flag << 4) & 0xF0) | (function_id >> 24);
+ data_for_sending[offset++] =
+ ((rpc_type_flag << 4) & 0xF0) | (function_id >> 24);
data_for_sending[offset++] = function_id >> 16;
data_for_sending[offset++] = function_id >> 8;
data_for_sending[offset++] = function_id;
@@ -67,12 +68,13 @@ void prepare_data(uint8_t* data_for_sending, ProtocolPayloadV2& message) {
data_for_sending[offset++] = jsonSize;
if (message.json.length() != 0) {
- memcpy(data_for_sending + offset, message.json.c_str(),
- message.json.size());
+ memcpy(
+ data_for_sending + offset, message.json.c_str(), message.json.size());
}
if (message.data.size() != 0) {
- uint8_t* current_pointer = data_for_sending + offset + message.json.length();
+ uint8_t* current_pointer =
+ data_for_sending + offset + message.json.length();
u_int32_t binarySize = message.data.size();
for (uint32_t i = 0; i < binarySize; ++i) {
current_pointer[i] = message.data[i];
@@ -163,7 +165,7 @@ TEST(ProtocolPayloadTest, ExtractCorrectProtocolWithoutDataWithJSON) {
const size_t data_for_sending_size = PROTOCOL_HEADER_V2_SIZE +
prot_payload_test.data.size() +
prot_payload_test.json.length();
- uint8_t *data_for_sending = new uint8_t[data_for_sending_size];
+ uint8_t* data_for_sending = new uint8_t[data_for_sending_size];
prepare_data(data_for_sending, prot_payload_test);
BitStream bs(data_for_sending, data_for_sending_size);
diff --git a/src/components/qt_hmi/References/Work/bananasnacks/main.cpp b/src/components/qt_hmi/References/Work/bananasnacks/main.cpp
index faa3f175be..bb40110e13 100644
--- a/src/components/qt_hmi/References/Work/bananasnacks/main.cpp
+++ b/src/components/qt_hmi/References/Work/bananasnacks/main.cpp
@@ -2,16 +2,15 @@
#include <QQmlContext>
#include "qtquick2applicationviewer.h"
-int main(int argc, char *argv[])
-{
- QGuiApplication app(argc, argv);
+int main(int argc, char* argv[]) {
+ QGuiApplication app(argc, argv);
- QtQuick2ApplicationViewer viewer;
+ QtQuick2ApplicationViewer viewer;
- viewer.addImportPath(QStringLiteral("plugins"));
+ viewer.addImportPath(QStringLiteral("plugins"));
- viewer.setMainQmlFile(QStringLiteral("qml/Bananas/main.qml"));
- viewer.showExpanded();
+ viewer.setMainQmlFile(QStringLiteral("qml/Bananas/main.qml"));
+ viewer.showExpanded();
- return app.exec();
+ return app.exec();
}
diff --git a/src/components/qt_hmi/References/Work/bananasnacks/qtquick2applicationviewer/qtquick2applicationviewer.cpp b/src/components/qt_hmi/References/Work/bananasnacks/qtquick2applicationviewer/qtquick2applicationviewer.cpp
index 547602d83c..8fcc4a6d38 100644
--- a/src/components/qt_hmi/References/Work/bananasnacks/qtquick2applicationviewer/qtquick2applicationviewer.cpp
+++ b/src/components/qt_hmi/References/Work/bananasnacks/qtquick2applicationviewer/qtquick2applicationviewer.cpp
@@ -1,7 +1,8 @@
// checksum 0x56a9 version 0x80001
/*
This file was generated by the Qt Quick 2 Application wizard of Qt Creator.
- QtQuick2ApplicationViewer is a convenience class containing mobile device specific
+ QtQuick2ApplicationViewer is a convenience class containing mobile device
+ specific
code such as screen orientation handling. Also QML paths and debugging are
handled here.
It is recommended not to modify this file, since newer versions of Qt Creator
@@ -14,57 +15,50 @@
#include <QtCore/QDir>
#include <QtQml/QQmlEngine>
-class QtQuick2ApplicationViewerPrivate
-{
- QString mainQmlFile;
- friend class QtQuick2ApplicationViewer;
- static QString adjustPath(const QString &path);
+class QtQuick2ApplicationViewerPrivate {
+ QString mainQmlFile;
+ friend class QtQuick2ApplicationViewer;
+ static QString adjustPath(const QString& path);
};
-QString QtQuick2ApplicationViewerPrivate::adjustPath(const QString &path)
-{
+QString QtQuick2ApplicationViewerPrivate::adjustPath(const QString& path) {
#if defined(Q_OS_MAC)
- if (!QDir::isAbsolutePath(path))
- return QString::fromLatin1("%1/../Resources/%2")
- .arg(QCoreApplication::applicationDirPath(), path);
+ if (!QDir::isAbsolutePath(path))
+ return QString::fromLatin1("%1/../Resources/%2")
+ .arg(QCoreApplication::applicationDirPath(), path);
#elif defined(Q_OS_UNIX)
- const QString pathInInstallDir =
- QString::fromLatin1("%1/../%2").arg(QCoreApplication::applicationDirPath(), path);
- if (QFileInfo(pathInInstallDir).exists())
- return pathInInstallDir;
+ const QString pathInInstallDir =
+ QString::fromLatin1("%1/../%2")
+ .arg(QCoreApplication::applicationDirPath(), path);
+ if (QFileInfo(pathInInstallDir).exists())
+ return pathInInstallDir;
#endif
- return path;
+ return path;
}
-QtQuick2ApplicationViewer::QtQuick2ApplicationViewer(QWindow *parent)
- : QQuickView(parent)
- , d(new QtQuick2ApplicationViewerPrivate())
-{
- connect(engine(), SIGNAL(quit()), SLOT(close()));
- setResizeMode(QQuickView::SizeRootObjectToView);
+QtQuick2ApplicationViewer::QtQuick2ApplicationViewer(QWindow* parent)
+ : QQuickView(parent), d(new QtQuick2ApplicationViewerPrivate()) {
+ connect(engine(), SIGNAL(quit()), SLOT(close()));
+ setResizeMode(QQuickView::SizeRootObjectToView);
}
-QtQuick2ApplicationViewer::~QtQuick2ApplicationViewer()
-{
- delete d;
+QtQuick2ApplicationViewer::~QtQuick2ApplicationViewer() {
+ delete d;
}
-void QtQuick2ApplicationViewer::setMainQmlFile(const QString &file)
-{
- d->mainQmlFile = QtQuick2ApplicationViewerPrivate::adjustPath(file);
- setSource(QUrl::fromLocalFile(d->mainQmlFile));
+void QtQuick2ApplicationViewer::setMainQmlFile(const QString& file) {
+ d->mainQmlFile = QtQuick2ApplicationViewerPrivate::adjustPath(file);
+ setSource(QUrl::fromLocalFile(d->mainQmlFile));
}
-void QtQuick2ApplicationViewer::addImportPath(const QString &path)
-{
- engine()->addImportPath(QtQuick2ApplicationViewerPrivate::adjustPath(path));
+void QtQuick2ApplicationViewer::addImportPath(const QString& path) {
+ engine()->addImportPath(QtQuick2ApplicationViewerPrivate::adjustPath(path));
}
-void QtQuick2ApplicationViewer::showExpanded()
-{
+void QtQuick2ApplicationViewer::showExpanded() {
#if defined(Q_WS_SIMULATOR)
- showFullScreen();
+ showFullScreen();
#else
- show();
+ show();
#endif
}
diff --git a/src/components/qt_hmi/References/Work/bananasnacks/qtquick2applicationviewer/qtquick2applicationviewer.h b/src/components/qt_hmi/References/Work/bananasnacks/qtquick2applicationviewer/qtquick2applicationviewer.h
index bd6c50f54f..42287e8d79 100644
--- a/src/components/qt_hmi/References/Work/bananasnacks/qtquick2applicationviewer/qtquick2applicationviewer.h
+++ b/src/components/qt_hmi/References/Work/bananasnacks/qtquick2applicationviewer/qtquick2applicationviewer.h
@@ -1,7 +1,8 @@
// checksum 0xfde6 version 0x80001
/*
This file was generated by the Qt Quick 2 Application wizard of Qt Creator.
- QtQuick2ApplicationViewer is a convenience class containing mobile device specific
+ QtQuick2ApplicationViewer is a convenience class containing mobile device
+ specific
code such as screen orientation handling. Also QML paths and debugging are
handled here.
It is recommended not to modify this file, since newer versions of Qt Creator
@@ -13,21 +14,20 @@
#include <QtQuick/QQuickView>
-class QtQuick2ApplicationViewer : public QQuickView
-{
- Q_OBJECT
+class QtQuick2ApplicationViewer : public QQuickView {
+ Q_OBJECT
-public:
- explicit QtQuick2ApplicationViewer(QWindow *parent = 0);
- virtual ~QtQuick2ApplicationViewer();
+ public:
+ explicit QtQuick2ApplicationViewer(QWindow* parent = 0);
+ virtual ~QtQuick2ApplicationViewer();
- void setMainQmlFile(const QString &file);
- void addImportPath(const QString &path);
+ void setMainQmlFile(const QString& file);
+ void addImportPath(const QString& path);
- void showExpanded();
+ void showExpanded();
-private:
- class QtQuick2ApplicationViewerPrivate *d;
+ private:
+ class QtQuick2ApplicationViewerPrivate* d;
};
-#endif // QTQUICK2APPLICATIONVIEWER_H
+#endif // QTQUICK2APPLICATIONVIEWER_H
diff --git a/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsServer.cpp b/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsServer.cpp
index 5e86daa2f3..9c4eed8cc1 100644
--- a/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsServer.cpp
+++ b/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsServer.cpp
@@ -6,465 +6,451 @@
#include <QCryptographicHash>
#include <QDateTime>
-const QString QWsServer::regExpResourceNameStr( QLatin1String("^GET\\s(.*)\\sHTTP/1.1\r\n") );
-const QString QWsServer::regExpHostStr( QLatin1String("\r\nHost:\\s(.+(:\\d+)?)\r\n") );
-const QString QWsServer::regExpKeyStr( QLatin1String("\r\nSec-WebSocket-Key:\\s(.{24})\r\n") );
-const QString QWsServer::regExpKey1Str( QLatin1String("\r\nSec-WebSocket-Key1:\\s(.+)\r\n") );
-const QString QWsServer::regExpKey2Str( QLatin1String("\r\nSec-WebSocket-Key2:\\s(.+)\r\n") );
-const QString QWsServer::regExpKey3Str( QLatin1String("\r\n(.{8})$") );
-const QString QWsServer::regExpVersionStr( QLatin1String("\r\nSec-WebSocket-Version:\\s(\\d+)\r\n") );
-const QString QWsServer::regExpOriginStr( QLatin1String("\r\nSec-WebSocket-Origin:\\s(.+)\r\n") );
-const QString QWsServer::regExpOrigin2Str( QLatin1String("\r\nOrigin:\\s(.+)\r\n") );
-const QString QWsServer::regExpProtocolStr( QLatin1String("\r\nSec-WebSocket-Protocol:\\s(.+)\r\n") );
-const QString QWsServer::regExpExtensionsStr( QLatin1String("\r\nSec-WebSocket-Extensions:\\s(.+)\r\n") );
-
-QWsServer::QWsServer(QObject * parent)
- : QObject(parent)
-{
- tcpServer = new QTcpServer(this);
- connect( tcpServer, SIGNAL(newConnection()), this, SLOT(newTcpConnection()) );
- qsrand( QDateTime::currentMSecsSinceEpoch() );
+const QString QWsServer::regExpResourceNameStr(
+ QLatin1String("^GET\\s(.*)\\sHTTP/1.1\r\n"));
+const QString QWsServer::regExpHostStr(
+ QLatin1String("\r\nHost:\\s(.+(:\\d+)?)\r\n"));
+const QString QWsServer::regExpKeyStr(
+ QLatin1String("\r\nSec-WebSocket-Key:\\s(.{24})\r\n"));
+const QString QWsServer::regExpKey1Str(
+ QLatin1String("\r\nSec-WebSocket-Key1:\\s(.+)\r\n"));
+const QString QWsServer::regExpKey2Str(
+ QLatin1String("\r\nSec-WebSocket-Key2:\\s(.+)\r\n"));
+const QString QWsServer::regExpKey3Str(QLatin1String("\r\n(.{8})$"));
+const QString QWsServer::regExpVersionStr(
+ QLatin1String("\r\nSec-WebSocket-Version:\\s(\\d+)\r\n"));
+const QString QWsServer::regExpOriginStr(
+ QLatin1String("\r\nSec-WebSocket-Origin:\\s(.+)\r\n"));
+const QString QWsServer::regExpOrigin2Str(
+ QLatin1String("\r\nOrigin:\\s(.+)\r\n"));
+const QString QWsServer::regExpProtocolStr(
+ QLatin1String("\r\nSec-WebSocket-Protocol:\\s(.+)\r\n"));
+const QString QWsServer::regExpExtensionsStr(
+ QLatin1String("\r\nSec-WebSocket-Extensions:\\s(.+)\r\n"));
+
+QWsServer::QWsServer(QObject* parent) : QObject(parent) {
+ tcpServer = new QTcpServer(this);
+ connect(tcpServer, SIGNAL(newConnection()), this, SLOT(newTcpConnection()));
+ qsrand(QDateTime::currentMSecsSinceEpoch());
}
-QWsServer::~QWsServer()
-{
- tcpServer->deleteLater();
+QWsServer::~QWsServer() {
+ tcpServer->deleteLater();
}
-bool QWsServer::listen(const QHostAddress & address, quint16 port)
-{
- return tcpServer->listen(address, port);
+bool QWsServer::listen(const QHostAddress& address, quint16 port) {
+ return tcpServer->listen(address, port);
}
-void QWsServer::close()
-{
- tcpServer->close();
+void QWsServer::close() {
+ tcpServer->close();
}
-QAbstractSocket::SocketError QWsServer::serverError()
-{
- return tcpServer->serverError();
+QAbstractSocket::SocketError QWsServer::serverError() {
+ return tcpServer->serverError();
}
-QString QWsServer::errorString()
-{
- return tcpServer->errorString();
+QString QWsServer::errorString() {
+ return tcpServer->errorString();
}
-void QWsServer::newTcpConnection()
-{
- QTcpSocket * tcpSocket = tcpServer->nextPendingConnection();
- connect( tcpSocket, SIGNAL(readyRead()), this, SLOT(dataReceived()) );
- headerBuffer.insert( tcpSocket, QStringList() );
+void QWsServer::newTcpConnection() {
+ QTcpSocket* tcpSocket = tcpServer->nextPendingConnection();
+ connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(dataReceived()));
+ headerBuffer.insert(tcpSocket, QStringList());
}
-void QWsServer::closeTcpConnection()
-{
- QTcpSocket * tcpSocket = qobject_cast<QTcpSocket*>( sender() );
- if (tcpSocket == 0)
- return;
+void QWsServer::closeTcpConnection() {
+ QTcpSocket* tcpSocket = qobject_cast<QTcpSocket*>(sender());
+ if (tcpSocket == 0)
+ return;
- tcpSocket->close();
+ tcpSocket->close();
}
-void QWsServer::dataReceived()
-{
- QTcpSocket * tcpSocket = qobject_cast<QTcpSocket*>( sender() );
- if (tcpSocket == 0)
- return;
-
- bool allHeadersFetched = false;
-
- const QLatin1String emptyLine("\r\n");
-
- while ( tcpSocket->canReadLine() )
- {
- QString line = tcpSocket->readLine();
-
- if (line == emptyLine)
- {
- allHeadersFetched = true;
- break;
- }
-
- headerBuffer[ tcpSocket ].append(line);
- }
-
- if (!allHeadersFetched)
- return;
-
- QString request( headerBuffer[ tcpSocket ].join("") );
-
- QRegExp regExp;
- regExp.setMinimal( true );
-
- // Extract mandatory datas
- // Version
- regExp.setPattern( QWsServer::regExpVersionStr );
- regExp.indexIn(request);
- QString versionStr = regExp.cap(1);
- EWebsocketVersion version;
- if ( ! versionStr.isEmpty() )
- {
- version = (EWebsocketVersion)versionStr.toInt();
- }
- else if ( tcpSocket->bytesAvailable() >= 8 )
- {
- version = WS_V0;
- request.append( tcpSocket->read(8) );
- }
- else
- {
- version = WS_VUnknow;
- }
-
- // Resource name
- regExp.setPattern( QWsServer::regExpResourceNameStr );
- regExp.indexIn(request);
- QString resourceName = regExp.cap(1);
-
- // Host (address & port)
- regExp.setPattern( QWsServer::regExpHostStr );
- regExp.indexIn(request);
- QString host = regExp.cap(1);
- QStringList hostTmp = host.split(':');
- QString hostAddress = hostTmp[0];
- QString hostPort;
- if ( hostTmp.size() > 1 )
- hostPort = hostTmp.last(); // fix for IPv6
-
- // Key
- QString key, key1, key2, key3;
- if ( version >= WS_V4 )
- {
- regExp.setPattern( QWsServer::regExpKeyStr );
- regExp.indexIn(request);
- key = regExp.cap(1);
- }
- else
- {
- regExp.setPattern( QWsServer::regExpKey1Str );
- regExp.indexIn(request);
- key1 = regExp.cap(1);
- regExp.setPattern( QWsServer::regExpKey2Str );
- regExp.indexIn(request);
- key2 = regExp.cap(1);
- regExp.setPattern( QWsServer::regExpKey3Str );
- regExp.indexIn(request);
- key3 = regExp.cap(1);
- }
-
- ////////////////////////////////////////////////////////////////////
-
- // If the mandatory fields are not specified, we abord the connection to the Websocket server
- if ( version == WS_VUnknow || resourceName.isEmpty() || hostAddress.isEmpty() || ( key.isEmpty() && ( key1.isEmpty() || key2.isEmpty() || key3.isEmpty() ) ) )
- {
- // Send bad request response
- QString response = QWsServer::composeBadRequestResponse( QList<EWebsocketVersion>() << WS_V6 << WS_V7 << WS_V8 << WS_V13 );
- tcpSocket->write( response.toUtf8() );
- tcpSocket->flush();
- return;
- }
-
- ////////////////////////////////////////////////////////////////////
-
- // Extract optional datas
-
- // Origin
- regExp.setPattern( QWsServer::regExpOriginStr );
- if ( regExp.indexIn(request) == -1 )
- {
- regExp.setPattern( QWsServer::regExpOrigin2Str );
- regExp.indexIn(request);
- }
- QString origin = regExp.cap(1);
-
- // Protocol
- regExp.setPattern( QWsServer::regExpProtocolStr );
- regExp.indexIn(request);
- QString protocol = regExp.cap(1);
-
- // Extensions
- regExp.setPattern( QWsServer::regExpExtensionsStr );
- regExp.indexIn(request);
- QString extensions = regExp.cap(1);
-
- ////////////////////////////////////////////////////////////////////
-
- // Compose opening handshake response
- QString response;
-
- if ( version >= WS_V6 )
- {
- QString accept = computeAcceptV4( key );
- response = QWsServer::composeOpeningHandshakeResponseV6( accept, protocol );
- }
- else if ( version >= WS_V4 )
- {
- QString accept = computeAcceptV4( key );
- QString nonce = generateNonce();
- response = QWsServer::composeOpeningHandshakeResponseV4( accept, nonce, protocol );
- }
- else
- {
- QString accept = computeAcceptV0( key1, key2, key3 );
- response = QWsServer::composeOpeningHandshakeResponseV0( accept, origin, hostAddress, hostPort, resourceName , protocol );
- }
-
- // Handshake OK, disconnect readyRead
- disconnect( tcpSocket, SIGNAL(readyRead()), this, SLOT(dataReceived()) );
-
- // Send opening handshake response
- if ( version == WS_V0 )
- tcpSocket->write( response.toLatin1() );
- else
- tcpSocket->write( response.toUtf8() );
- tcpSocket->flush();
-
- QWsSocket * wsSocket = new QWsSocket( this, tcpSocket, version );
- wsSocket->setResourceName( resourceName );
- wsSocket->setHost( host );
- wsSocket->setHostAddress( hostAddress );
- wsSocket->setHostPort( hostPort.toInt() );
- wsSocket->setOrigin( origin );
- wsSocket->setProtocol( protocol );
- wsSocket->setExtensions( extensions );
- wsSocket->serverSideSocket = true;
-
- // ORIGINAL CODE
- //int socketDescriptor = tcpSocket->socketDescriptor();
- //incomingConnection( socketDescriptor );
-
- // CHANGED CODE FOR LINUX COMPATIBILITY
- addPendingConnection( wsSocket );
- emit newConnection();
+void QWsServer::dataReceived() {
+ QTcpSocket* tcpSocket = qobject_cast<QTcpSocket*>(sender());
+ if (tcpSocket == 0)
+ return;
+
+ bool allHeadersFetched = false;
+
+ const QLatin1String emptyLine("\r\n");
+
+ while (tcpSocket->canReadLine()) {
+ QString line = tcpSocket->readLine();
+
+ if (line == emptyLine) {
+ allHeadersFetched = true;
+ break;
+ }
+
+ headerBuffer[tcpSocket].append(line);
+ }
+
+ if (!allHeadersFetched)
+ return;
+
+ QString request(headerBuffer[tcpSocket].join(""));
+
+ QRegExp regExp;
+ regExp.setMinimal(true);
+
+ // Extract mandatory datas
+ // Version
+ regExp.setPattern(QWsServer::regExpVersionStr);
+ regExp.indexIn(request);
+ QString versionStr = regExp.cap(1);
+ EWebsocketVersion version;
+ if (!versionStr.isEmpty()) {
+ version = (EWebsocketVersion)versionStr.toInt();
+ } else if (tcpSocket->bytesAvailable() >= 8) {
+ version = WS_V0;
+ request.append(tcpSocket->read(8));
+ } else {
+ version = WS_VUnknow;
+ }
+
+ // Resource name
+ regExp.setPattern(QWsServer::regExpResourceNameStr);
+ regExp.indexIn(request);
+ QString resourceName = regExp.cap(1);
+
+ // Host (address & port)
+ regExp.setPattern(QWsServer::regExpHostStr);
+ regExp.indexIn(request);
+ QString host = regExp.cap(1);
+ QStringList hostTmp = host.split(':');
+ QString hostAddress = hostTmp[0];
+ QString hostPort;
+ if (hostTmp.size() > 1)
+ hostPort = hostTmp.last(); // fix for IPv6
+
+ // Key
+ QString key, key1, key2, key3;
+ if (version >= WS_V4) {
+ regExp.setPattern(QWsServer::regExpKeyStr);
+ regExp.indexIn(request);
+ key = regExp.cap(1);
+ } else {
+ regExp.setPattern(QWsServer::regExpKey1Str);
+ regExp.indexIn(request);
+ key1 = regExp.cap(1);
+ regExp.setPattern(QWsServer::regExpKey2Str);
+ regExp.indexIn(request);
+ key2 = regExp.cap(1);
+ regExp.setPattern(QWsServer::regExpKey3Str);
+ regExp.indexIn(request);
+ key3 = regExp.cap(1);
+ }
+
+ ////////////////////////////////////////////////////////////////////
+
+ // If the mandatory fields are not specified, we abord the connection to the
+ // Websocket server
+ if (version == WS_VUnknow || resourceName.isEmpty() ||
+ hostAddress.isEmpty() ||
+ (key.isEmpty() && (key1.isEmpty() || key2.isEmpty() || key3.isEmpty()))) {
+ // Send bad request response
+ QString response = QWsServer::composeBadRequestResponse(
+ QList<EWebsocketVersion>() << WS_V6 << WS_V7 << WS_V8 << WS_V13);
+ tcpSocket->write(response.toUtf8());
+ tcpSocket->flush();
+ return;
+ }
+
+ ////////////////////////////////////////////////////////////////////
+
+ // Extract optional datas
+
+ // Origin
+ regExp.setPattern(QWsServer::regExpOriginStr);
+ if (regExp.indexIn(request) == -1) {
+ regExp.setPattern(QWsServer::regExpOrigin2Str);
+ regExp.indexIn(request);
+ }
+ QString origin = regExp.cap(1);
+
+ // Protocol
+ regExp.setPattern(QWsServer::regExpProtocolStr);
+ regExp.indexIn(request);
+ QString protocol = regExp.cap(1);
+
+ // Extensions
+ regExp.setPattern(QWsServer::regExpExtensionsStr);
+ regExp.indexIn(request);
+ QString extensions = regExp.cap(1);
+
+ ////////////////////////////////////////////////////////////////////
+
+ // Compose opening handshake response
+ QString response;
+
+ if (version >= WS_V6) {
+ QString accept = computeAcceptV4(key);
+ response = QWsServer::composeOpeningHandshakeResponseV6(accept, protocol);
+ } else if (version >= WS_V4) {
+ QString accept = computeAcceptV4(key);
+ QString nonce = generateNonce();
+ response =
+ QWsServer::composeOpeningHandshakeResponseV4(accept, nonce, protocol);
+ } else {
+ QString accept = computeAcceptV0(key1, key2, key3);
+ response = QWsServer::composeOpeningHandshakeResponseV0(
+ accept, origin, hostAddress, hostPort, resourceName, protocol);
+ }
+
+ // Handshake OK, disconnect readyRead
+ disconnect(tcpSocket, SIGNAL(readyRead()), this, SLOT(dataReceived()));
+
+ // Send opening handshake response
+ if (version == WS_V0)
+ tcpSocket->write(response.toLatin1());
+ else
+ tcpSocket->write(response.toUtf8());
+ tcpSocket->flush();
+
+ QWsSocket* wsSocket = new QWsSocket(this, tcpSocket, version);
+ wsSocket->setResourceName(resourceName);
+ wsSocket->setHost(host);
+ wsSocket->setHostAddress(hostAddress);
+ wsSocket->setHostPort(hostPort.toInt());
+ wsSocket->setOrigin(origin);
+ wsSocket->setProtocol(protocol);
+ wsSocket->setExtensions(extensions);
+ wsSocket->serverSideSocket = true;
+
+ // ORIGINAL CODE
+ // int socketDescriptor = tcpSocket->socketDescriptor();
+ // incomingConnection( socketDescriptor );
+
+ // CHANGED CODE FOR LINUX COMPATIBILITY
+ addPendingConnection(wsSocket);
+ emit newConnection();
}
-void QWsServer::incomingConnection( int socketDescriptor )
-{
- QTcpSocket * tcpSocket = new QTcpSocket( tcpServer );
- tcpSocket->setSocketDescriptor( socketDescriptor, QAbstractSocket::ConnectedState );
- QWsSocket * wsSocket = new QWsSocket( this, tcpSocket );
+void QWsServer::incomingConnection(int socketDescriptor) {
+ QTcpSocket* tcpSocket = new QTcpSocket(tcpServer);
+ tcpSocket->setSocketDescriptor(socketDescriptor,
+ QAbstractSocket::ConnectedState);
+ QWsSocket* wsSocket = new QWsSocket(this, tcpSocket);
- addPendingConnection( wsSocket );
- emit newConnection();
+ addPendingConnection(wsSocket);
+ emit newConnection();
}
-void QWsServer::addPendingConnection( QWsSocket * socket )
-{
- if ( pendingConnections.size() < maxPendingConnections() )
- pendingConnections.enqueue( socket );
+void QWsServer::addPendingConnection(QWsSocket* socket) {
+ if (pendingConnections.size() < maxPendingConnections())
+ pendingConnections.enqueue(socket);
}
-QWsSocket * QWsServer::nextPendingConnection()
-{
- return pendingConnections.dequeue();
+QWsSocket* QWsServer::nextPendingConnection() {
+ return pendingConnections.dequeue();
}
-bool QWsServer::hasPendingConnections()
-{
- if ( pendingConnections.size() > 0 )
- return true;
- return false;
+bool QWsServer::hasPendingConnections() {
+ if (pendingConnections.size() > 0)
+ return true;
+ return false;
}
-int QWsServer::maxPendingConnections()
-{
- return tcpServer->maxPendingConnections();
+int QWsServer::maxPendingConnections() {
+ return tcpServer->maxPendingConnections();
}
-bool QWsServer::isListening()
-{
- return tcpServer->isListening();
+bool QWsServer::isListening() {
+ return tcpServer->isListening();
}
-QNetworkProxy QWsServer::proxy()
-{
- return tcpServer->proxy();
+QNetworkProxy QWsServer::proxy() {
+ return tcpServer->proxy();
}
-QHostAddress QWsServer::serverAddress()
-{
- return tcpServer->serverAddress();
+QHostAddress QWsServer::serverAddress() {
+ return tcpServer->serverAddress();
}
-quint16 QWsServer::serverPort()
-{
- return tcpServer->serverPort();
+quint16 QWsServer::serverPort() {
+ return tcpServer->serverPort();
}
-void QWsServer::setMaxPendingConnections( int numConnections )
-{
- tcpServer->setMaxPendingConnections( numConnections );
+void QWsServer::setMaxPendingConnections(int numConnections) {
+ tcpServer->setMaxPendingConnections(numConnections);
}
-void QWsServer::setProxy( const QNetworkProxy & networkProxy )
-{
- tcpServer->setProxy( networkProxy );
+void QWsServer::setProxy(const QNetworkProxy& networkProxy) {
+ tcpServer->setProxy(networkProxy);
}
-bool QWsServer::setSocketDescriptor( int socketDescriptor )
-{
- return tcpServer->setSocketDescriptor( socketDescriptor );
+bool QWsServer::setSocketDescriptor(int socketDescriptor) {
+ return tcpServer->setSocketDescriptor(socketDescriptor);
}
-int QWsServer::socketDescriptor()
-{
- return tcpServer->socketDescriptor();
+int QWsServer::socketDescriptor() {
+ return tcpServer->socketDescriptor();
}
-bool QWsServer::waitForNewConnection( int msec, bool * timedOut )
-{
- return tcpServer->waitForNewConnection( msec, timedOut );
+bool QWsServer::waitForNewConnection(int msec, bool* timedOut) {
+ return tcpServer->waitForNewConnection(msec, timedOut);
}
-QString QWsServer::computeAcceptV0( QString key1, QString key2, QString key3 )
-{
- QString numStr1;
- QString numStr2;
+QString QWsServer::computeAcceptV0(QString key1, QString key2, QString key3) {
+ QString numStr1;
+ QString numStr2;
- QChar carac;
- for ( int i=0 ; i<key1.size() ; i++ )
- {
- carac = key1[ i ];
- if ( carac.isDigit() )
- numStr1.append( carac );
- }
- for ( int i=0 ; i<key2.size() ; i++ )
- {
- carac = key2[ i ];
- if ( carac.isDigit() )
- numStr2.append( carac );
- }
+ QChar carac;
+ for (int i = 0; i < key1.size(); i++) {
+ carac = key1[i];
+ if (carac.isDigit())
+ numStr1.append(carac);
+ }
+ for (int i = 0; i < key2.size(); i++) {
+ carac = key2[i];
+ if (carac.isDigit())
+ numStr2.append(carac);
+ }
- quint32 num1 = numStr1.toUInt();
- quint32 num2 = numStr2.toUInt();
+ quint32 num1 = numStr1.toUInt();
+ quint32 num2 = numStr2.toUInt();
- int numSpaces1 = key1.count( ' ' );
- int numSpaces2 = key2.count( ' ' );
+ int numSpaces1 = key1.count(' ');
+ int numSpaces2 = key2.count(' ');
- num1 /= numSpaces1;
- num2 /= numSpaces2;
+ num1 /= numSpaces1;
+ num2 /= numSpaces2;
- QString concat = serializeInt( num1 ) + serializeInt( num2 ) + key3;
+ QString concat = serializeInt(num1) + serializeInt(num2) + key3;
- QByteArray md5 = QCryptographicHash::hash( concat.toLatin1(), QCryptographicHash::Md5 );
+ QByteArray md5 =
+ QCryptographicHash::hash(concat.toLatin1(), QCryptographicHash::Md5);
- return QString( md5 );
+ return QString(md5);
}
-QString QWsServer::computeAcceptV4(QString key)
-{
- key += QLatin1String("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
- QByteArray hash = QCryptographicHash::hash ( key.toUtf8(), QCryptographicHash::Sha1 );
- return hash.toBase64();
+QString QWsServer::computeAcceptV4(QString key) {
+ key += QLatin1String("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
+ QByteArray hash =
+ QCryptographicHash::hash(key.toUtf8(), QCryptographicHash::Sha1);
+ return hash.toBase64();
}
-QString QWsServer::generateNonce()
-{
- qsrand( QDateTime::currentDateTime().toTime_t() );
+QString QWsServer::generateNonce() {
+ qsrand(QDateTime::currentDateTime().toTime_t());
- QByteArray nonce;
- int i = 16;
+ QByteArray nonce;
+ int i = 16;
- while( i-- )
- {
- nonce.append( qrand() % 0x100 );
- }
+ while (i--) {
+ nonce.append(qrand() % 0x100);
+ }
- return QString( nonce.toBase64() );
+ return QString(nonce.toBase64());
}
-QByteArray QWsServer::serializeInt( quint32 number, quint8 nbBytes )
-{
- QByteArray ba;
- quint8 currentNbBytes = 0;
- while (number > 0 && currentNbBytes < nbBytes)
- {
- char car = static_cast<char>(number & 0xFF);
- ba.prepend( car );
- number = number >> 8;
- currentNbBytes++;
- }
- char car = 0x00;
- while (currentNbBytes < nbBytes)
- {
- ba.prepend( car );
- currentNbBytes++;
- }
- return ba;
+QByteArray QWsServer::serializeInt(quint32 number, quint8 nbBytes) {
+ QByteArray ba;
+ quint8 currentNbBytes = 0;
+ while (number > 0 && currentNbBytes < nbBytes) {
+ char car = static_cast<char>(number & 0xFF);
+ ba.prepend(car);
+ number = number >> 8;
+ currentNbBytes++;
+ }
+ char car = 0x00;
+ while (currentNbBytes < nbBytes) {
+ ba.prepend(car);
+ currentNbBytes++;
+ }
+ return ba;
}
-QString QWsServer::composeOpeningHandshakeResponseV0( QString accept, QString origin, QString hostAddress, QString hostPort, QString resourceName, QString protocol )
-{
- QString response;
-
- response.append( QLatin1String("HTTP/1.1 101 WebSocket Protocol Handshake\r\n") );
- response.append( QLatin1String("Upgrade: Websocket\r\n") );
- response.append( QLatin1String("Connection: Upgrade\r\n") );
- response.append( QLatin1String("Sec-WebSocket-Origin: ") + origin + QLatin1String("\r\n") );
- response.append( QLatin1String("Sec-WebSocket-Location: ws://") + hostAddress);
- if (!hostPort.isEmpty())
- response.append(QLatin1String(":") + hostPort);
- response.append(resourceName + QLatin1String("\r\n"));
- if ( ! protocol.isEmpty() )
- response.append( QLatin1String("Sec-WebSocket-Protocol: ") + protocol + QLatin1String("\r\n") );
- response.append( QLatin1String("\r\n") );
- response.append( accept );
-
- return response;
+QString QWsServer::composeOpeningHandshakeResponseV0(QString accept,
+ QString origin,
+ QString hostAddress,
+ QString hostPort,
+ QString resourceName,
+ QString protocol) {
+ QString response;
+
+ response.append(
+ QLatin1String("HTTP/1.1 101 WebSocket Protocol Handshake\r\n"));
+ response.append(QLatin1String("Upgrade: Websocket\r\n"));
+ response.append(QLatin1String("Connection: Upgrade\r\n"));
+ response.append(QLatin1String("Sec-WebSocket-Origin: ") + origin +
+ QLatin1String("\r\n"));
+ response.append(QLatin1String("Sec-WebSocket-Location: ws://") + hostAddress);
+ if (!hostPort.isEmpty())
+ response.append(QLatin1String(":") + hostPort);
+ response.append(resourceName + QLatin1String("\r\n"));
+ if (!protocol.isEmpty())
+ response.append(QLatin1String("Sec-WebSocket-Protocol: ") + protocol +
+ QLatin1String("\r\n"));
+ response.append(QLatin1String("\r\n"));
+ response.append(accept);
+
+ return response;
}
-QString QWsServer::composeOpeningHandshakeResponseV4( QString accept, QString nonce, QString protocol, QString extensions )
-{
- QString response;
-
- response.append( QLatin1String("HTTP/1.1 101 Switching Protocols\r\n") );
- response.append( QLatin1String("Upgrade: websocket\r\n") );
- response.append( QLatin1String("Connection: Upgrade\r\n") );
- response.append( QLatin1String("Sec-WebSocket-Accept: ") + accept + QLatin1String("\r\n") );
- response.append( QLatin1String("Sec-WebSocket-Nonce: ") + nonce + QLatin1String("\r\n") );
- if ( ! protocol.isEmpty() )
- response.append( QLatin1String("Sec-WebSocket-Protocol: ") + protocol + QLatin1String("\r\n") );
- if ( ! extensions.isEmpty() )
- response.append( QLatin1String("Sec-WebSocket-Extensions: ") + extensions + QLatin1String("\r\n") );
- response.append( QLatin1String("\r\n") );
-
- return response;
+QString QWsServer::composeOpeningHandshakeResponseV4(QString accept,
+ QString nonce,
+ QString protocol,
+ QString extensions) {
+ QString response;
+
+ response.append(QLatin1String("HTTP/1.1 101 Switching Protocols\r\n"));
+ response.append(QLatin1String("Upgrade: websocket\r\n"));
+ response.append(QLatin1String("Connection: Upgrade\r\n"));
+ response.append(QLatin1String("Sec-WebSocket-Accept: ") + accept +
+ QLatin1String("\r\n"));
+ response.append(QLatin1String("Sec-WebSocket-Nonce: ") + nonce +
+ QLatin1String("\r\n"));
+ if (!protocol.isEmpty())
+ response.append(QLatin1String("Sec-WebSocket-Protocol: ") + protocol +
+ QLatin1String("\r\n"));
+ if (!extensions.isEmpty())
+ response.append(QLatin1String("Sec-WebSocket-Extensions: ") + extensions +
+ QLatin1String("\r\n"));
+ response.append(QLatin1String("\r\n"));
+
+ return response;
}
-QString QWsServer::composeOpeningHandshakeResponseV6( QString accept, QString protocol, QString extensions )
-{
- QString response;
-
- response.append( QLatin1String("HTTP/1.1 101 Switching Protocols\r\n") );
- response.append( QLatin1String("Upgrade: websocket\r\n") );
- response.append( QLatin1String("Connection: Upgrade\r\n") );
- response.append( QLatin1String("Sec-WebSocket-Accept: ") + accept + QLatin1String("\r\n") );
- if ( ! protocol.isEmpty() )
- response.append( QLatin1String("Sec-WebSocket-Protocol: ") + protocol + QLatin1String("\r\n") );
- if ( ! extensions.isEmpty() )
- response.append( QLatin1String("Sec-WebSocket-Extensions: ") + extensions + QLatin1String("\r\n") );
- response.append( QLatin1String("\r\n") );
-
- return response;
+QString QWsServer::composeOpeningHandshakeResponseV6(QString accept,
+ QString protocol,
+ QString extensions) {
+ QString response;
+
+ response.append(QLatin1String("HTTP/1.1 101 Switching Protocols\r\n"));
+ response.append(QLatin1String("Upgrade: websocket\r\n"));
+ response.append(QLatin1String("Connection: Upgrade\r\n"));
+ response.append(QLatin1String("Sec-WebSocket-Accept: ") + accept +
+ QLatin1String("\r\n"));
+ if (!protocol.isEmpty())
+ response.append(QLatin1String("Sec-WebSocket-Protocol: ") + protocol +
+ QLatin1String("\r\n"));
+ if (!extensions.isEmpty())
+ response.append(QLatin1String("Sec-WebSocket-Extensions: ") + extensions +
+ QLatin1String("\r\n"));
+ response.append(QLatin1String("\r\n"));
+
+ return response;
}
-QString QWsServer::composeBadRequestResponse( QList<EWebsocketVersion> versions )
-{
- QString response;
-
- response.append( QLatin1String("HTTP/1.1 400 Bad Request\r\n") );
- if ( ! versions.isEmpty() )
- {
- QString versionsStr = QString::number( (int)versions.takeLast() );
- int i = versions.size();
- while ( i-- )
- {
- versionsStr.append( QLatin1String(", ") + QString::number( (int)versions.takeLast() ) );
- }
- response.append( QLatin1String("Sec-WebSocket-Version: ") + versionsStr + QLatin1String("\r\n") );
- }
-
- return response;
+QString QWsServer::composeBadRequestResponse(
+ QList<EWebsocketVersion> versions) {
+ QString response;
+
+ response.append(QLatin1String("HTTP/1.1 400 Bad Request\r\n"));
+ if (!versions.isEmpty()) {
+ QString versionsStr = QString::number((int)versions.takeLast());
+ int i = versions.size();
+ while (i--) {
+ versionsStr.append(QLatin1String(", ") +
+ QString::number((int)versions.takeLast()));
+ }
+ response.append(QLatin1String("Sec-WebSocket-Version: ") + versionsStr +
+ QLatin1String("\r\n"));
+ }
+
+ return response;
}
diff --git a/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsServer.h b/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsServer.h
index c526c747ab..f37dd4b5b2 100644
--- a/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsServer.h
+++ b/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsServer.h
@@ -11,77 +11,88 @@
#include "QWsSocket.h"
-class QWsServer : public QObject
-{
- Q_OBJECT
+class QWsServer : public QObject {
+ Q_OBJECT
-public:
- // ctor
- QWsServer(QObject * parent = 0);
- // dtor
- virtual ~QWsServer();
+ public:
+ // ctor
+ QWsServer(QObject* parent = 0);
+ // dtor
+ virtual ~QWsServer();
- // public functions
- void close();
- QString errorString();
- bool hasPendingConnections();
- bool isListening();
- bool listen(const QHostAddress & address = QHostAddress::Any, quint16 port = 0);
- int maxPendingConnections();
- virtual QWsSocket * nextPendingConnection();
- QNetworkProxy proxy();
- QHostAddress serverAddress();
- QAbstractSocket::SocketError serverError();
- quint16 serverPort();
- void setMaxPendingConnections( int numConnections );
- void setProxy( const QNetworkProxy & networkProxy );
- bool setSocketDescriptor( int socketDescriptor );
- int socketDescriptor();
- bool waitForNewConnection( int msec = 0, bool * timedOut = 0 );
+ // public functions
+ void close();
+ QString errorString();
+ bool hasPendingConnections();
+ bool isListening();
+ bool listen(const QHostAddress& address = QHostAddress::Any,
+ quint16 port = 0);
+ int maxPendingConnections();
+ virtual QWsSocket* nextPendingConnection();
+ QNetworkProxy proxy();
+ QHostAddress serverAddress();
+ QAbstractSocket::SocketError serverError();
+ quint16 serverPort();
+ void setMaxPendingConnections(int numConnections);
+ void setProxy(const QNetworkProxy& networkProxy);
+ bool setSocketDescriptor(int socketDescriptor);
+ int socketDescriptor();
+ bool waitForNewConnection(int msec = 0, bool* timedOut = 0);
signals:
- void newConnection();
+ void newConnection();
-protected:
- // protected functions
- void addPendingConnection( QWsSocket * socket );
- virtual void incomingConnection( int socketDescriptor );
+ protected:
+ // protected functions
+ void addPendingConnection(QWsSocket* socket);
+ virtual void incomingConnection(int socketDescriptor);
-private slots:
- // private slots
- void newTcpConnection();
- void closeTcpConnection();
- void dataReceived();
+ private slots:
+ // private slots
+ void newTcpConnection();
+ void closeTcpConnection();
+ void dataReceived();
-private:
- // private attributes
- QTcpServer * tcpServer;
- QQueue<QWsSocket*> pendingConnections;
- QMap<const QTcpSocket*, QStringList> headerBuffer;
+ private:
+ // private attributes
+ QTcpServer* tcpServer;
+ QQueue<QWsSocket*> pendingConnections;
+ QMap<const QTcpSocket*, QStringList> headerBuffer;
-public:
- // public static functions
- static QByteArray serializeInt( quint32 number, quint8 nbBytes = 4 );
- static QString computeAcceptV0( QString key1, QString key2, QString thirdPart );
- static QString computeAcceptV4( QString key );
- static QString generateNonce();
- static QString composeOpeningHandshakeResponseV0( QString accept, QString origin, QString hostAddress, QString hostPort, QString resourceName, QString protocol = "" );
- static QString composeOpeningHandshakeResponseV4( QString accept, QString nonce, QString protocol = "", QString extensions = "" );
- static QString composeOpeningHandshakeResponseV6( QString accept, QString protocol = "", QString extensions = "" );
- static QString composeBadRequestResponse( QList<EWebsocketVersion> versions = QList<EWebsocketVersion>() );
+ public:
+ // public static functions
+ static QByteArray serializeInt(quint32 number, quint8 nbBytes = 4);
+ static QString computeAcceptV0(QString key1, QString key2, QString thirdPart);
+ static QString computeAcceptV4(QString key);
+ static QString generateNonce();
+ static QString composeOpeningHandshakeResponseV0(QString accept,
+ QString origin,
+ QString hostAddress,
+ QString hostPort,
+ QString resourceName,
+ QString protocol = "");
+ static QString composeOpeningHandshakeResponseV4(QString accept,
+ QString nonce,
+ QString protocol = "",
+ QString extensions = "");
+ static QString composeOpeningHandshakeResponseV6(QString accept,
+ QString protocol = "",
+ QString extensions = "");
+ static QString composeBadRequestResponse(
+ QList<EWebsocketVersion> versions = QList<EWebsocketVersion>());
- // public static vars
- static const QString regExpResourceNameStr;
- static const QString regExpHostStr;
- static const QString regExpKeyStr;
- static const QString regExpKey1Str;
- static const QString regExpKey2Str;
- static const QString regExpKey3Str;
- static const QString regExpVersionStr;
- static const QString regExpOriginStr;
- static const QString regExpOrigin2Str;
- static const QString regExpProtocolStr;
- static const QString regExpExtensionsStr;
+ // public static vars
+ static const QString regExpResourceNameStr;
+ static const QString regExpHostStr;
+ static const QString regExpKeyStr;
+ static const QString regExpKey1Str;
+ static const QString regExpKey2Str;
+ static const QString regExpKey3Str;
+ static const QString regExpVersionStr;
+ static const QString regExpOriginStr;
+ static const QString regExpOrigin2Str;
+ static const QString regExpProtocolStr;
+ static const QString regExpExtensionsStr;
};
-#endif // QWSSERVER_H
+#endif // QWSSERVER_H
diff --git a/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsSocket.cpp b/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsSocket.cpp
index 540b909e09..428f559517 100644
--- a/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsSocket.cpp
+++ b/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsSocket.cpp
@@ -6,787 +6,744 @@
#include "QWsServer.h"
int QWsSocket::maxBytesPerFrame = 1400;
-const QString QWsSocket::regExpAcceptStr(QLatin1String("Sec-WebSocket-Accept:\\s(.{28})\r\n"));
+const QString QWsSocket::regExpAcceptStr(
+ QLatin1String("Sec-WebSocket-Accept:\\s(.{28})\r\n"));
const QString QWsSocket::regExpUpgradeStr(QLatin1String("Upgrade:\\s(.+)\r\n"));
-const QString QWsSocket::regExpConnectionStr(QLatin1String("Connection:\\s(.+)\r\n"));
-
-QWsSocket::QWsSocket( QObject * parent, QTcpSocket * socket, EWebsocketVersion ws_v ) :
- QAbstractSocket( QAbstractSocket::UnknownSocketType, parent ),
- tcpSocket( socket ? socket : new QTcpSocket(this) ),
- _version( ws_v ),
- _hostPort( -1 ),
- closingHandshakeSent( false ),
- closingHandshakeReceived( false ),
- readingState( HeaderPending ),
- isFinalFragment( false ),
- hasMask( false ),
- payloadLength( 0 ),
- maskingKey( 4, 0 ),
- serverSideSocket( false )
-{
- tcpSocket->setParent( this );
-
- QAbstractSocket::setSocketState( tcpSocket->state() );
- QAbstractSocket::setPeerAddress( tcpSocket->peerAddress() );
- QAbstractSocket::setPeerPort( tcpSocket->peerPort() );
-
- if ( _version == WS_V0 )
- connect( tcpSocket, SIGNAL(readyRead()), this, SLOT(processDataV0()) );
- else if ( _version >= WS_V4 )
- connect( tcpSocket, SIGNAL(readyRead()), this, SLOT(processDataV4()) );
- connect( tcpSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SIGNAL(error(QAbstractSocket::SocketError)) );
- connect( tcpSocket, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)), this, SIGNAL(proxyAuthenticationRequired(const QNetworkProxy &, QAuthenticator *)) );
- connect( tcpSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), this, SLOT(processTcpStateChanged(QAbstractSocket::SocketState)) );
- connect( tcpSocket, SIGNAL(readChannelFinished()), this, SIGNAL(readChannelFinished()) );
- connect( tcpSocket, SIGNAL(hostFound()), this, SIGNAL(hostFound()) );
-}
-
-QWsSocket::~QWsSocket()
-{
- QAbstractSocket::SocketState state = QAbstractSocket::state();
- if ( state != QAbstractSocket::UnconnectedState )
- {
- qDebug() << "CloseAway, socket destroyed in server";
- close( CloseGoingAway, QLatin1String("The server destroyed the socket.") );
- tcpSocket->abort();
- QAbstractSocket::setSocketState( QAbstractSocket::UnconnectedState );
- QAbstractSocket::stateChanged( QAbstractSocket::UnconnectedState );
- emit QAbstractSocket::disconnected();
- }
-}
-
-void QWsSocket::connectToHost( const QString & hostName, quint16 port, OpenMode mode )
-{
- QWsSocket::connectToHost( QHostAddress(hostName), port, mode );
-}
-
-void QWsSocket::connectToHost( const QHostAddress &address, quint16 port, OpenMode mode )
-{
- handshakeResponse.clear();
- setPeerAddress( address );
- setPeerPort( port );
- setOpenMode( mode );
- tcpSocket->connectToHost( address, port, mode );
-}
-
-void QWsSocket::disconnectFromHost()
-{
- QWsSocket::close();
-}
-
-void QWsSocket::abort( QString reason )
-{
- QWsSocket::close( CloseAbnormalDisconnection, reason );
- tcpSocket->abort();
-}
-
-void QWsSocket::close( ECloseStatusCode closeStatusCode, QString reason )
-{
- if ( QAbstractSocket::state() == QAbstractSocket::UnconnectedState )
- return;
-
- if ( ! closingHandshakeSent )
- {
- switch ( _version )
- {
- case WS_V4:
- case WS_V5:
- case WS_V6:
- case WS_V7:
- case WS_V8:
- case WS_V13:
- {
- // Compose and send close frame
- QByteArray BA;
-
- // Body
- if ( closeStatusCode == NoCloseStatusCode )
- {
- // Header
- BA.append( QWsSocket::composeHeader( true, OpClose, 0 ) );
- }
- else
- {
- // Header
- QByteArray maskingKey;
- if ( ! serverSideSocket )
- maskingKey = QWsSocket::generateMaskingKey();
- BA.append( QWsSocket::composeHeader( true, OpClose, reason.size() + 2, maskingKey ) );
-
- QByteArray body;
-
- // Close status code (optional)
- body.append( QWsServer::serializeInt( (int)closeStatusCode, 2 ) );
-
- // Reason (optional)
- if ( reason.size() )
- {
- QByteArray reason_ba = reason.toUtf8();
- if ( ! serverSideSocket )
- {
- reason_ba = QWsSocket::mask( reason_ba, maskingKey );
- }
- body.append( reason_ba );
- }
-
- BA.append( body );
- }
-
- // Send closing handshake
- tcpSocket->write( BA );
-
- break;
- }
- case WS_V0:
- {
- QByteArray closeFrame;
- closeFrame.append( (char)0xFF );
- closeFrame.append( (char)0x00 );
- tcpSocket->write( closeFrame );
- break;
- }
- default:
- {
- break;
- }
- }
-
- closingHandshakeSent = true;
- }
-
- if ( QAbstractSocket::state() != QAbstractSocket::ClosingState )
- {
- QAbstractSocket::setSocketState( QAbstractSocket::ClosingState );
- emit QAbstractSocket::stateChanged( QAbstractSocket::ClosingState );
- emit QAbstractSocket::aboutToClose();
- }
-
- if ( closingHandshakeSent && closingHandshakeReceived )
- {
- QAbstractSocket::setSocketState( QAbstractSocket::UnconnectedState );
- emit stateChanged( QAbstractSocket::UnconnectedState );
- emit disconnected();
- tcpSocket->disconnectFromHost();
- }
-}
-
-qint64 QWsSocket::write( const QString & string )
-{
- if ( _version == WS_V0 )
- {
- return QWsSocket::write( string.toUtf8() );
- }
-
- const QList<QByteArray>& framesList = QWsSocket::composeFrames( string.toUtf8(), false, maxBytesPerFrame );
- return writeFrames( framesList );
-}
-
-qint64 QWsSocket::write( const QByteArray & byteArray )
-{
- if ( _version == WS_V0 )
- {
- QByteArray BA;
- BA.append( (char)0x00 );
- BA.append( byteArray );
- BA.append( (char)0xFF );
- return writeFrame( BA );
- }
-
- const QList<QByteArray>& framesList = QWsSocket::composeFrames( byteArray, true, maxBytesPerFrame );
-
- qint64 nbBytesWritten = writeFrames( framesList );
- emit bytesWritten( nbBytesWritten );
-
- return nbBytesWritten;
-}
-
-void QWsSocket::processHandshake()
-{
- //copy from QWsServer::dataReceived();
- QTcpSocket * tcpSocket = qobject_cast<QTcpSocket*>( sender() );
- if (tcpSocket == 0)
- return;
-
- bool allHeadersFetched = false;
-
- const QLatin1String emptyLine("\r\n");
-
- while ( tcpSocket->canReadLine() )
- {
- QString line = tcpSocket->readLine();
-
- if (line == emptyLine)
- {
- allHeadersFetched = true;
- break;
- }
-
- handshakeResponse.append(line);
- }
-
- if (!allHeadersFetched)
- return;
-
- QRegExp regExp;
- regExp.setMinimal( true );
-
- // check accept field
- regExp.setPattern(regExpAcceptStr);
- regExp.indexIn(handshakeResponse);
- QString acceptFromServer = regExp.cap(1);
-
- // check upgrade field
- regExp.setPattern(regExpUpgradeStr);
- regExp.indexIn(handshakeResponse);
- QString upgrade = regExp.cap(1);
-
- // check connection field
- regExp.setPattern(regExpConnectionStr);
- regExp.indexIn(handshakeResponse);
- QString connection = regExp.cap(1);
-
- // check extensions field
- regExp.setPattern(QWsServer::regExpExtensionsStr);
- regExp.indexIn(handshakeResponse);
- QString extensions = regExp.cap(1);
-
- //TODO: check extensions field
- // If the mandatory params are not setted, we abord the connection to the Websocket server
- if((acceptFromServer.isEmpty()) || (!upgrade.contains(QLatin1String("websocket"), Qt::CaseInsensitive)) ||
- (!connection.contains(QLatin1String("Upgrade"), Qt::CaseInsensitive)))
- {
- // emit error(QAbstractSocket::ConnectionRefusedError);
- // return;
- }
-
- //TODO: check HTTP code
-
- //TODO: check protocol field
-
- QString accept = QWsServer::computeAcceptV4(key);
- if(accept != acceptFromServer)
- {
- // emit error(QAbstractSocket::ConnectionRefusedError);
- // return;
- }
-
- // handshake procedure succeeded
- QAbstractSocket::setSocketState( QAbstractSocket::ConnectedState );
- emit QAbstractSocket::stateChanged( QAbstractSocket::ConnectedState );
- emit QAbstractSocket::connected();
-}
-
-void QWsSocket::processDataV0()
-{
- if( state() == QAbstractSocket::ConnectingState )
- {
- processHandshake();
- return;
- }
-
- QByteArray BA, buffer;
- quint8 type, b = 0x00;
-
- BA = tcpSocket->read(1); //TODO: refactor like processDataV4
- type = BA[0];
-
- if ( ( type & 0x80 ) == 0x00 ) // MSB of type not set
- {
- if ( type != 0x00 )
- {
- // ABORT CONNEXION
- tcpSocket->readAll();
- return;
- }
-
- // read data
- do
- {
- BA = tcpSocket->read(1);
- b = BA[0];
- if ( b != 0xFF )
- buffer.append( b );
- } while ( b != 0xFF );
-
- currentFrame.append( buffer );
- }
- else // MSB of type set
- {
- if ( type != 0xFF )
- {
- // ERROR, ABORT CONNEXION
- close();
- return;
- }
-
- quint8 length = 0x00;
-
- bool bIsNotZero = true;
- do
- {
- BA = tcpSocket->read(1);
- b = BA[0];
- bIsNotZero = ( b != 0x00 ? true : false );
- if ( bIsNotZero ) // b must be != 0
- {
- quint8 b_v = b & 0x7F;
- length *= 128;
- length += b_v;
- }
- } while ( ( ( b & 0x80 ) == 0x80 ) && bIsNotZero );
-
- BA = tcpSocket->read(length); // discard this bytes
- }
-
- if ( currentFrame.size() > 0 )
- {
- emit frameReceived( QString::fromUtf8(currentFrame) );
- currentFrame.clear();
- }
-
- if ( tcpSocket->bytesAvailable() )
- processDataV0();
-}
-
-void QWsSocket::processDataV4()
-{
- if( state() == QAbstractSocket::ConnectingState )
- {
- processHandshake();
- }
- else
- while (true)
- switch ( readingState ) {
- case HeaderPending: {
- if (tcpSocket->bytesAvailable() < 2)
- return;
-
- // END, RSV1-3, Opcode
- char header[2];
- tcpSocket->read(header, 2); // XXX: Handle return value
- isFinalFragment = (header[0] & 0x80) != 0;
- opcode = static_cast<EOpcode>(header[0] & 0x0F);
-
- // Mask, PayloadLength
- hasMask = (header[1] & 0x80) != 0;
- quint8 length = (header[1] & 0x7F);
-
- switch (length)
- {
- case 126:
- readingState = PayloadLengthPending;
- break;
- case 127:
- readingState = BigPayloadLenghPending;
- break;
- default:
- payloadLength = length;
- readingState = MaskPending;
- break;
- }
- }; break;
- case PayloadLengthPending: {
- if (tcpSocket->bytesAvailable() < 2)
- return;
-
- uchar length[2];
- tcpSocket->read(reinterpret_cast<char *>(length), 2); // XXX: Handle return value
- payloadLength = qFromBigEndian<quint16>(reinterpret_cast<const uchar *>(length));
- readingState = MaskPending;
- }; break;
- case BigPayloadLenghPending: {
- if (tcpSocket->bytesAvailable() < 8)
- return;
-
- uchar length[8];
- tcpSocket->read(reinterpret_cast<char *>(length), 8); // XXX: Handle return value
- // Most significant bit must be set to 0 as per http://tools.ietf.org/html/rfc6455#section-5.2
- // XXX: Check for that?
- payloadLength = qFromBigEndian<quint64>(length) & ~(1LL << 63);
- readingState = MaskPending;
- }; break;
- case MaskPending: {
- if (!hasMask) {
- readingState = PayloadBodyPending;
- break;
- }
-
- if (tcpSocket->bytesAvailable() < 4)
- return;
-
- tcpSocket->read(maskingKey.data(), 4); // XXX: Handle return value
-
- if ( opcode == OpClose )
- {
- readingState = CloseDataPending;
- }
- else
- {
- readingState = PayloadBodyPending;
- }
- }; /* Intentional fall-through */
- case PayloadBodyPending: {
- // TODO: Handle large payloads
- if (tcpSocket->bytesAvailable() < static_cast<qint32>(payloadLength))
- return;
-
- if ( opcode == OpClose )
- {
- if ( payloadLength >= 2 && tcpSocket->bytesAvailable() >= 2 )
- {
- uchar bytes[2];
- tcpSocket->read( reinterpret_cast<char *>(bytes), 2 );
- closeStatusCode = (ECloseStatusCode)qFromBigEndian<quint16>( reinterpret_cast<const uchar *>(bytes) );
- }
- else
- {
- closeStatusCode = NoCloseStatusCode;
- }
- }
-
- QByteArray ApplicationData = tcpSocket->read( payloadLength );
- if ( hasMask )
- ApplicationData = QWsSocket::mask( ApplicationData, maskingKey );
- currentFrame.append( ApplicationData );
-
- readingState = HeaderPending;
-
- if ( !isFinalFragment )
- break;
-
- switch ( opcode )
- {
- case OpBinary:
- emit frameReceived( currentFrame );
- break;
- case OpText:
- emit frameReceived( QString::fromUtf8(currentFrame) );
- break;
- case OpPing:
- write( QWsSocket::composeHeader( true, OpPong, 0 ) );
- break;
- case OpPong:
- emit pong( pingTimer.elapsed() );
- break;
- case OpClose:
- closingHandshakeReceived = true;
- close( closeStatusCode );
- break;
- default:
- // DO NOTHING
- break;
- }
-
- currentFrame.clear();
- }; break;
- case CloseDataPending:
- default:
- break;
- } /* while (true) switch */
-}
-
-qint64 QWsSocket::writeFrame ( const QByteArray & byteArray )
-{
- return tcpSocket->write( byteArray );
-}
-
-qint64 QWsSocket::writeFrames ( const QList<QByteArray> & framesList )
-{
- qint64 nbBytesWritten = 0;
- for ( int i=0 ; i<framesList.size() ; i++ )
- {
- nbBytesWritten += writeFrame( framesList[i] );
- }
- return nbBytesWritten;
-}
-
-void QWsSocket::processTcpStateChanged( QAbstractSocket::SocketState tcpSocketState )
-{
- QAbstractSocket::SocketState wsSocketState = QAbstractSocket::state();
- switch ( tcpSocketState )
- {
- case QAbstractSocket::HostLookupState:
- {
- QAbstractSocket::setSocketState( QAbstractSocket::HostLookupState );
- emit QAbstractSocket::stateChanged( QAbstractSocket::HostLookupState );
- break;
- }
- case QAbstractSocket::ConnectingState:
- {
- QAbstractSocket::setSocketState( QAbstractSocket::ConnectingState );
- emit QAbstractSocket::stateChanged( QAbstractSocket::ConnectingState );
- break;
- }
- case QAbstractSocket::ConnectedState:
- {
- if ( wsSocketState == QAbstractSocket::ConnectingState )
- {
- key = QWsServer::generateNonce();
- QString handshake = composeOpeningHandShake( QLatin1String("/"), QLatin1String("example.com"), QString(), QString(), key );
- tcpSocket->write( handshake.toUtf8() );
- }
- break;
- }
- case QAbstractSocket::ClosingState:
- {
- if ( wsSocketState == QAbstractSocket::ConnectedState )
- {
- QWsSocket::close( CloseGoingAway );
- QAbstractSocket::setSocketState( QAbstractSocket::ClosingState );
- emit QAbstractSocket::stateChanged( QAbstractSocket::ClosingState );
- emit QAbstractSocket::aboutToClose();
- }
- break;
- }
- case QAbstractSocket::UnconnectedState:
- {
- if ( wsSocketState != QAbstractSocket::UnconnectedState )
- {
- QAbstractSocket::setSocketError( QAbstractSocket::NetworkError );
- emit QAbstractSocket::error( QAbstractSocket::NetworkError );
- QAbstractSocket::setSocketState( QAbstractSocket::UnconnectedState );
- emit QAbstractSocket::stateChanged( QAbstractSocket::UnconnectedState );
- emit QAbstractSocket::disconnected();
- }
- closingHandshakeSent = false;
- closingHandshakeReceived = false;
- break;
- }
- default:
- break;
- }
-}
-
-QByteArray QWsSocket::generateMaskingKey()
-{
- QByteArray key;
- for ( int i=0 ; i<4 ; i++ )
- {
- key.append( qrand() % 0x100 );
- }
- return key;
-}
-
-QByteArray QWsSocket::generateMaskingKeyV4( QString key, QString nonce )
-{
- QString concat = key + nonce + QLatin1String("61AC5F19-FBBA-4540-B96F-6561F1AB40A8");
- QByteArray hash = QCryptographicHash::hash ( concat.toUtf8(), QCryptographicHash::Sha1 );
- return hash;
-}
-
-QByteArray QWsSocket::mask( QByteArray & data, QByteArray & maskingKey )
-{
- QByteArray result;
- result.reserve( data.size() );
-
- for ( int i=0 ; i<data.size() ; i++ )
- {
- result[i] = ( data[i] ^ maskingKey[ i % 4 ] );
- }
-
- return result;
-}
-
-QList<QByteArray> QWsSocket::composeFrames( QByteArray byteArray, bool asBinary, int maxFrameBytes )
-{
- if ( maxFrameBytes == 0 )
- maxFrameBytes = maxBytesPerFrame;
-
- QList<QByteArray> framesList;
-
- QByteArray maskingKey;
-
- int nbFrames = byteArray.size() / maxFrameBytes + 1;
-
- for ( int i=0 ; i<nbFrames ; i++ )
- {
- QByteArray BA;
-
- // end, size
- bool end = false;
- quint64 size = maxFrameBytes;
- EOpcode opcode = OpContinue;
- if ( i == nbFrames-1 ) // for multi-frames
- {
- end = true;
- size = byteArray.size();
- }
- if ( i == 0 )
- {
- if ( asBinary )
- opcode = OpBinary;
- else
- opcode = OpText;
- }
-
- // Header
- BA.append( QWsSocket::composeHeader( end, opcode, size, maskingKey ) );
-
- // Application Data
- QByteArray dataForThisFrame = byteArray.left( size );
- byteArray.remove( 0, size );
-
- //dataForThisFrame = QWsSocket::mask( dataForThisFrame, maskingKey );
- BA.append( dataForThisFrame );
-
- framesList << BA;
- }
-
- return framesList;
-}
-
-QByteArray QWsSocket::composeHeader( bool end, EOpcode opcode, quint64 payloadLength, QByteArray maskingKey )
-{
- QByteArray BA;
- quint8 byte;
-
- // end, RSV1-3, Opcode
- byte = 0x00;
- // end
- if ( end )
- byte = (byte | 0x80);
- // Opcode
- byte = (byte | opcode);
- BA.append( byte );
-
- // Mask, PayloadLength
- byte = 0x00;
- QByteArray BAsize;
- // Mask
- if ( maskingKey.size() == 4 )
- byte = (byte | 0x80);
- // PayloadLength
- if ( payloadLength <= 125 )
- {
- byte = (byte | payloadLength);
- }
- // Extended payloadLength
- else
- {
- // 2 bytes
- if ( payloadLength <= 0xFFFF )
- {
- byte = ( byte | 126 );
- BAsize.append( ( payloadLength >> 1*8 ) & 0xFF );
- BAsize.append( ( payloadLength >> 0*8 ) & 0xFF );
- }
- // 8 bytes
- else if ( payloadLength <= 0x7FFFFFFF )
- {
- byte = ( byte | 127 );
- BAsize.append( ( payloadLength >> 7*8 ) & 0xFF );
- BAsize.append( ( payloadLength >> 6*8 ) & 0xFF );
- BAsize.append( ( payloadLength >> 5*8 ) & 0xFF );
- BAsize.append( ( payloadLength >> 4*8 ) & 0xFF );
- BAsize.append( ( payloadLength >> 3*8 ) & 0xFF );
- BAsize.append( ( payloadLength >> 2*8 ) & 0xFF );
- BAsize.append( ( payloadLength >> 1*8 ) & 0xFF );
- BAsize.append( ( payloadLength >> 0*8 ) & 0xFF );
- }
- }
- BA.append( byte );
- BA.append( BAsize );
-
- // Masking
- if ( maskingKey.size() == 4 )
- BA.append( maskingKey );
-
- return BA;
-}
-
-void QWsSocket::ping()
-{
- pingTimer.restart();
- QByteArray pingFrame = QWsSocket::composeHeader( true, OpPing, 0 );
- writeFrame( pingFrame );
-}
-
-void QWsSocket::setResourceName( QString rn )
-{
- _resourceName = rn;
-}
-
-void QWsSocket::setHost( QString h )
-{
- _host = h;
-}
-
-void QWsSocket::setHostAddress( QString ha )
-{
- _hostAddress = ha;
-}
-
-void QWsSocket::setHostPort( int hp )
-{
- _hostPort = hp;
-}
-
-void QWsSocket::setOrigin( QString o )
-{
- _origin = o;
+const QString QWsSocket::regExpConnectionStr(
+ QLatin1String("Connection:\\s(.+)\r\n"));
+
+QWsSocket::QWsSocket(QObject* parent,
+ QTcpSocket* socket,
+ EWebsocketVersion ws_v)
+ : QAbstractSocket(QAbstractSocket::UnknownSocketType, parent)
+ , tcpSocket(socket ? socket : new QTcpSocket(this))
+ , _version(ws_v)
+ , _hostPort(-1)
+ , closingHandshakeSent(false)
+ , closingHandshakeReceived(false)
+ , readingState(HeaderPending)
+ , isFinalFragment(false)
+ , hasMask(false)
+ , payloadLength(0)
+ , maskingKey(4, 0)
+ , serverSideSocket(false) {
+ tcpSocket->setParent(this);
+
+ QAbstractSocket::setSocketState(tcpSocket->state());
+ QAbstractSocket::setPeerAddress(tcpSocket->peerAddress());
+ QAbstractSocket::setPeerPort(tcpSocket->peerPort());
+
+ if (_version == WS_V0)
+ connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(processDataV0()));
+ else if (_version >= WS_V4)
+ connect(tcpSocket, SIGNAL(readyRead()), this, SLOT(processDataV4()));
+ connect(tcpSocket,
+ SIGNAL(error(QAbstractSocket::SocketError)),
+ this,
+ SIGNAL(error(QAbstractSocket::SocketError)));
+ connect(tcpSocket,
+ SIGNAL(proxyAuthenticationRequired(const QNetworkProxy&,
+ QAuthenticator*)),
+ this,
+ SIGNAL(proxyAuthenticationRequired(const QNetworkProxy&,
+ QAuthenticator*)));
+ connect(tcpSocket,
+ SIGNAL(stateChanged(QAbstractSocket::SocketState)),
+ this,
+ SLOT(processTcpStateChanged(QAbstractSocket::SocketState)));
+ connect(tcpSocket,
+ SIGNAL(readChannelFinished()),
+ this,
+ SIGNAL(readChannelFinished()));
+ connect(tcpSocket, SIGNAL(hostFound()), this, SIGNAL(hostFound()));
+}
+
+QWsSocket::~QWsSocket() {
+ QAbstractSocket::SocketState state = QAbstractSocket::state();
+ if (state != QAbstractSocket::UnconnectedState) {
+ qDebug() << "CloseAway, socket destroyed in server";
+ close(CloseGoingAway, QLatin1String("The server destroyed the socket."));
+ tcpSocket->abort();
+ QAbstractSocket::setSocketState(QAbstractSocket::UnconnectedState);
+ QAbstractSocket::stateChanged(QAbstractSocket::UnconnectedState);
+ emit QAbstractSocket::disconnected();
+ }
+}
+
+void QWsSocket::connectToHost(const QString& hostName,
+ quint16 port,
+ OpenMode mode) {
+ QWsSocket::connectToHost(QHostAddress(hostName), port, mode);
+}
+
+void QWsSocket::connectToHost(const QHostAddress& address,
+ quint16 port,
+ OpenMode mode) {
+ handshakeResponse.clear();
+ setPeerAddress(address);
+ setPeerPort(port);
+ setOpenMode(mode);
+ tcpSocket->connectToHost(address, port, mode);
+}
+
+void QWsSocket::disconnectFromHost() {
+ QWsSocket::close();
+}
+
+void QWsSocket::abort(QString reason) {
+ QWsSocket::close(CloseAbnormalDisconnection, reason);
+ tcpSocket->abort();
+}
+
+void QWsSocket::close(ECloseStatusCode closeStatusCode, QString reason) {
+ if (QAbstractSocket::state() == QAbstractSocket::UnconnectedState)
+ return;
+
+ if (!closingHandshakeSent) {
+ switch (_version) {
+ case WS_V4:
+ case WS_V5:
+ case WS_V6:
+ case WS_V7:
+ case WS_V8:
+ case WS_V13: {
+ // Compose and send close frame
+ QByteArray BA;
+
+ // Body
+ if (closeStatusCode == NoCloseStatusCode) {
+ // Header
+ BA.append(QWsSocket::composeHeader(true, OpClose, 0));
+ } else {
+ // Header
+ QByteArray maskingKey;
+ if (!serverSideSocket)
+ maskingKey = QWsSocket::generateMaskingKey();
+ BA.append(QWsSocket::composeHeader(
+ true, OpClose, reason.size() + 2, maskingKey));
+
+ QByteArray body;
+
+ // Close status code (optional)
+ body.append(QWsServer::serializeInt((int)closeStatusCode, 2));
+
+ // Reason (optional)
+ if (reason.size()) {
+ QByteArray reason_ba = reason.toUtf8();
+ if (!serverSideSocket) {
+ reason_ba = QWsSocket::mask(reason_ba, maskingKey);
+ }
+ body.append(reason_ba);
+ }
+
+ BA.append(body);
+ }
+
+ // Send closing handshake
+ tcpSocket->write(BA);
+
+ break;
+ }
+ case WS_V0: {
+ QByteArray closeFrame;
+ closeFrame.append((char)0xFF);
+ closeFrame.append((char)0x00);
+ tcpSocket->write(closeFrame);
+ break;
+ }
+ default: { break; }
+ }
+
+ closingHandshakeSent = true;
+ }
+
+ if (QAbstractSocket::state() != QAbstractSocket::ClosingState) {
+ QAbstractSocket::setSocketState(QAbstractSocket::ClosingState);
+ emit QAbstractSocket::stateChanged(QAbstractSocket::ClosingState);
+ emit QAbstractSocket::aboutToClose();
+ }
+
+ if (closingHandshakeSent && closingHandshakeReceived) {
+ QAbstractSocket::setSocketState(QAbstractSocket::UnconnectedState);
+ emit stateChanged(QAbstractSocket::UnconnectedState);
+ emit disconnected();
+ tcpSocket->disconnectFromHost();
+ }
+}
+
+qint64 QWsSocket::write(const QString& string) {
+ if (_version == WS_V0) {
+ return QWsSocket::write(string.toUtf8());
+ }
+
+ const QList<QByteArray>& framesList =
+ QWsSocket::composeFrames(string.toUtf8(), false, maxBytesPerFrame);
+ return writeFrames(framesList);
+}
+
+qint64 QWsSocket::write(const QByteArray& byteArray) {
+ if (_version == WS_V0) {
+ QByteArray BA;
+ BA.append((char)0x00);
+ BA.append(byteArray);
+ BA.append((char)0xFF);
+ return writeFrame(BA);
+ }
+
+ const QList<QByteArray>& framesList =
+ QWsSocket::composeFrames(byteArray, true, maxBytesPerFrame);
+
+ qint64 nbBytesWritten = writeFrames(framesList);
+ emit bytesWritten(nbBytesWritten);
+
+ return nbBytesWritten;
+}
+
+void QWsSocket::processHandshake() {
+ // copy from QWsServer::dataReceived();
+ QTcpSocket* tcpSocket = qobject_cast<QTcpSocket*>(sender());
+ if (tcpSocket == 0)
+ return;
+
+ bool allHeadersFetched = false;
+
+ const QLatin1String emptyLine("\r\n");
+
+ while (tcpSocket->canReadLine()) {
+ QString line = tcpSocket->readLine();
+
+ if (line == emptyLine) {
+ allHeadersFetched = true;
+ break;
+ }
+
+ handshakeResponse.append(line);
+ }
+
+ if (!allHeadersFetched)
+ return;
+
+ QRegExp regExp;
+ regExp.setMinimal(true);
+
+ // check accept field
+ regExp.setPattern(regExpAcceptStr);
+ regExp.indexIn(handshakeResponse);
+ QString acceptFromServer = regExp.cap(1);
+
+ // check upgrade field
+ regExp.setPattern(regExpUpgradeStr);
+ regExp.indexIn(handshakeResponse);
+ QString upgrade = regExp.cap(1);
+
+ // check connection field
+ regExp.setPattern(regExpConnectionStr);
+ regExp.indexIn(handshakeResponse);
+ QString connection = regExp.cap(1);
+
+ // check extensions field
+ regExp.setPattern(QWsServer::regExpExtensionsStr);
+ regExp.indexIn(handshakeResponse);
+ QString extensions = regExp.cap(1);
+
+ // TODO: check extensions field
+ // If the mandatory params are not setted, we abord the connection to the
+ // Websocket server
+ if ((acceptFromServer.isEmpty()) ||
+ (!upgrade.contains(QLatin1String("websocket"), Qt::CaseInsensitive)) ||
+ (!connection.contains(QLatin1String("Upgrade"), Qt::CaseInsensitive))) {
+ // emit error(QAbstractSocket::ConnectionRefusedError);
+ // return;
+ }
+
+ // TODO: check HTTP code
+
+ // TODO: check protocol field
+
+ QString accept = QWsServer::computeAcceptV4(key);
+ if (accept != acceptFromServer) {
+ // emit error(QAbstractSocket::ConnectionRefusedError);
+ // return;
+ }
+
+ // handshake procedure succeeded
+ QAbstractSocket::setSocketState(QAbstractSocket::ConnectedState);
+ emit QAbstractSocket::stateChanged(QAbstractSocket::ConnectedState);
+ emit QAbstractSocket::connected();
+}
+
+void QWsSocket::processDataV0() {
+ if (state() == QAbstractSocket::ConnectingState) {
+ processHandshake();
+ return;
+ }
+
+ QByteArray BA, buffer;
+ quint8 type, b = 0x00;
+
+ BA = tcpSocket->read(1); // TODO: refactor like processDataV4
+ type = BA[0];
+
+ if ((type & 0x80) == 0x00) // MSB of type not set
+ {
+ if (type != 0x00) {
+ // ABORT CONNEXION
+ tcpSocket->readAll();
+ return;
+ }
+
+ // read data
+ do {
+ BA = tcpSocket->read(1);
+ b = BA[0];
+ if (b != 0xFF)
+ buffer.append(b);
+ } while (b != 0xFF);
+
+ currentFrame.append(buffer);
+ } else // MSB of type set
+ {
+ if (type != 0xFF) {
+ // ERROR, ABORT CONNEXION
+ close();
+ return;
+ }
+
+ quint8 length = 0x00;
+
+ bool bIsNotZero = true;
+ do {
+ BA = tcpSocket->read(1);
+ b = BA[0];
+ bIsNotZero = (b != 0x00 ? true : false);
+ if (bIsNotZero) // b must be != 0
+ {
+ quint8 b_v = b & 0x7F;
+ length *= 128;
+ length += b_v;
+ }
+ } while (((b & 0x80) == 0x80) && bIsNotZero);
+
+ BA = tcpSocket->read(length); // discard this bytes
+ }
+
+ if (currentFrame.size() > 0) {
+ emit frameReceived(QString::fromUtf8(currentFrame));
+ currentFrame.clear();
+ }
+
+ if (tcpSocket->bytesAvailable())
+ processDataV0();
+}
+
+void QWsSocket::processDataV4() {
+ if (state() == QAbstractSocket::ConnectingState) {
+ processHandshake();
+ } else
+ while (true)
+ switch (readingState) {
+ case HeaderPending: {
+ if (tcpSocket->bytesAvailable() < 2)
+ return;
+
+ // END, RSV1-3, Opcode
+ char header[2];
+ tcpSocket->read(header, 2); // XXX: Handle return value
+ isFinalFragment = (header[0] & 0x80) != 0;
+ opcode = static_cast<EOpcode>(header[0] & 0x0F);
+
+ // Mask, PayloadLength
+ hasMask = (header[1] & 0x80) != 0;
+ quint8 length = (header[1] & 0x7F);
+
+ switch (length) {
+ case 126:
+ readingState = PayloadLengthPending;
+ break;
+ case 127:
+ readingState = BigPayloadLenghPending;
+ break;
+ default:
+ payloadLength = length;
+ readingState = MaskPending;
+ break;
+ }
+ }; break;
+ case PayloadLengthPending: {
+ if (tcpSocket->bytesAvailable() < 2)
+ return;
+
+ uchar length[2];
+ tcpSocket->read(reinterpret_cast<char*>(length),
+ 2); // XXX: Handle return value
+ payloadLength =
+ qFromBigEndian<quint16>(reinterpret_cast<const uchar*>(length));
+ readingState = MaskPending;
+ }; break;
+ case BigPayloadLenghPending: {
+ if (tcpSocket->bytesAvailable() < 8)
+ return;
+
+ uchar length[8];
+ tcpSocket->read(reinterpret_cast<char*>(length),
+ 8); // XXX: Handle return value
+ // Most significant bit must be set to 0 as per
+ // http://tools.ietf.org/html/rfc6455#section-5.2
+ // XXX: Check for that?
+ payloadLength = qFromBigEndian<quint64>(length) & ~(1LL << 63);
+ readingState = MaskPending;
+ }; break;
+ case MaskPending: {
+ if (!hasMask) {
+ readingState = PayloadBodyPending;
+ break;
+ }
+
+ if (tcpSocket->bytesAvailable() < 4)
+ return;
+
+ tcpSocket->read(maskingKey.data(), 4); // XXX: Handle return value
+
+ if (opcode == OpClose) {
+ readingState = CloseDataPending;
+ } else {
+ readingState = PayloadBodyPending;
+ }
+ }; /* Intentional fall-through */
+ case PayloadBodyPending: {
+ // TODO: Handle large payloads
+ if (tcpSocket->bytesAvailable() < static_cast<qint32>(payloadLength))
+ return;
+
+ if (opcode == OpClose) {
+ if (payloadLength >= 2 && tcpSocket->bytesAvailable() >= 2) {
+ uchar bytes[2];
+ tcpSocket->read(reinterpret_cast<char*>(bytes), 2);
+ closeStatusCode = (ECloseStatusCode)qFromBigEndian<quint16>(
+ reinterpret_cast<const uchar*>(bytes));
+ } else {
+ closeStatusCode = NoCloseStatusCode;
+ }
+ }
+
+ QByteArray ApplicationData = tcpSocket->read(payloadLength);
+ if (hasMask)
+ ApplicationData = QWsSocket::mask(ApplicationData, maskingKey);
+ currentFrame.append(ApplicationData);
+
+ readingState = HeaderPending;
+
+ if (!isFinalFragment)
+ break;
+
+ switch (opcode) {
+ case OpBinary:
+ emit frameReceived(currentFrame);
+ break;
+ case OpText:
+ emit frameReceived(QString::fromUtf8(currentFrame));
+ break;
+ case OpPing:
+ write(QWsSocket::composeHeader(true, OpPong, 0));
+ break;
+ case OpPong:
+ emit pong(pingTimer.elapsed());
+ break;
+ case OpClose:
+ closingHandshakeReceived = true;
+ close(closeStatusCode);
+ break;
+ default:
+ // DO NOTHING
+ break;
+ }
+
+ currentFrame.clear();
+ }; break;
+ case CloseDataPending:
+ default:
+ break;
+ } /* while (true) switch */
+}
+
+qint64 QWsSocket::writeFrame(const QByteArray& byteArray) {
+ return tcpSocket->write(byteArray);
+}
+
+qint64 QWsSocket::writeFrames(const QList<QByteArray>& framesList) {
+ qint64 nbBytesWritten = 0;
+ for (int i = 0; i < framesList.size(); i++) {
+ nbBytesWritten += writeFrame(framesList[i]);
+ }
+ return nbBytesWritten;
+}
+
+void QWsSocket::processTcpStateChanged(
+ QAbstractSocket::SocketState tcpSocketState) {
+ QAbstractSocket::SocketState wsSocketState = QAbstractSocket::state();
+ switch (tcpSocketState) {
+ case QAbstractSocket::HostLookupState: {
+ QAbstractSocket::setSocketState(QAbstractSocket::HostLookupState);
+ emit QAbstractSocket::stateChanged(QAbstractSocket::HostLookupState);
+ break;
+ }
+ case QAbstractSocket::ConnectingState: {
+ QAbstractSocket::setSocketState(QAbstractSocket::ConnectingState);
+ emit QAbstractSocket::stateChanged(QAbstractSocket::ConnectingState);
+ break;
+ }
+ case QAbstractSocket::ConnectedState: {
+ if (wsSocketState == QAbstractSocket::ConnectingState) {
+ key = QWsServer::generateNonce();
+ QString handshake =
+ composeOpeningHandShake(QLatin1String("/"),
+ QLatin1String("example.com"),
+ QString(),
+ QString(),
+ key);
+ tcpSocket->write(handshake.toUtf8());
+ }
+ break;
+ }
+ case QAbstractSocket::ClosingState: {
+ if (wsSocketState == QAbstractSocket::ConnectedState) {
+ QWsSocket::close(CloseGoingAway);
+ QAbstractSocket::setSocketState(QAbstractSocket::ClosingState);
+ emit QAbstractSocket::stateChanged(QAbstractSocket::ClosingState);
+ emit QAbstractSocket::aboutToClose();
+ }
+ break;
+ }
+ case QAbstractSocket::UnconnectedState: {
+ if (wsSocketState != QAbstractSocket::UnconnectedState) {
+ QAbstractSocket::setSocketError(QAbstractSocket::NetworkError);
+ emit QAbstractSocket::error(QAbstractSocket::NetworkError);
+ QAbstractSocket::setSocketState(QAbstractSocket::UnconnectedState);
+ emit QAbstractSocket::stateChanged(QAbstractSocket::UnconnectedState);
+ emit QAbstractSocket::disconnected();
+ }
+ closingHandshakeSent = false;
+ closingHandshakeReceived = false;
+ break;
+ }
+ default:
+ break;
+ }
+}
+
+QByteArray QWsSocket::generateMaskingKey() {
+ QByteArray key;
+ for (int i = 0; i < 4; i++) {
+ key.append(qrand() % 0x100);
+ }
+ return key;
+}
+
+QByteArray QWsSocket::generateMaskingKeyV4(QString key, QString nonce) {
+ QString concat =
+ key + nonce + QLatin1String("61AC5F19-FBBA-4540-B96F-6561F1AB40A8");
+ QByteArray hash =
+ QCryptographicHash::hash(concat.toUtf8(), QCryptographicHash::Sha1);
+ return hash;
+}
+
+QByteArray QWsSocket::mask(QByteArray& data, QByteArray& maskingKey) {
+ QByteArray result;
+ result.reserve(data.size());
+
+ for (int i = 0; i < data.size(); i++) {
+ result[i] = (data[i] ^ maskingKey[i % 4]);
+ }
+
+ return result;
+}
+
+QList<QByteArray> QWsSocket::composeFrames(QByteArray byteArray,
+ bool asBinary,
+ int maxFrameBytes) {
+ if (maxFrameBytes == 0)
+ maxFrameBytes = maxBytesPerFrame;
+
+ QList<QByteArray> framesList;
+
+ QByteArray maskingKey;
+
+ int nbFrames = byteArray.size() / maxFrameBytes + 1;
+
+ for (int i = 0; i < nbFrames; i++) {
+ QByteArray BA;
+
+ // end, size
+ bool end = false;
+ quint64 size = maxFrameBytes;
+ EOpcode opcode = OpContinue;
+ if (i == nbFrames - 1) // for multi-frames
+ {
+ end = true;
+ size = byteArray.size();
+ }
+ if (i == 0) {
+ if (asBinary)
+ opcode = OpBinary;
+ else
+ opcode = OpText;
+ }
+
+ // Header
+ BA.append(QWsSocket::composeHeader(end, opcode, size, maskingKey));
+
+ // Application Data
+ QByteArray dataForThisFrame = byteArray.left(size);
+ byteArray.remove(0, size);
+
+ // dataForThisFrame = QWsSocket::mask( dataForThisFrame, maskingKey );
+ BA.append(dataForThisFrame);
+
+ framesList << BA;
+ }
+
+ return framesList;
+}
+
+QByteArray QWsSocket::composeHeader(bool end,
+ EOpcode opcode,
+ quint64 payloadLength,
+ QByteArray maskingKey) {
+ QByteArray BA;
+ quint8 byte;
+
+ // end, RSV1-3, Opcode
+ byte = 0x00;
+ // end
+ if (end)
+ byte = (byte | 0x80);
+ // Opcode
+ byte = (byte | opcode);
+ BA.append(byte);
+
+ // Mask, PayloadLength
+ byte = 0x00;
+ QByteArray BAsize;
+ // Mask
+ if (maskingKey.size() == 4)
+ byte = (byte | 0x80);
+ // PayloadLength
+ if (payloadLength <= 125) {
+ byte = (byte | payloadLength);
+ }
+ // Extended payloadLength
+ else {
+ // 2 bytes
+ if (payloadLength <= 0xFFFF) {
+ byte = (byte | 126);
+ BAsize.append((payloadLength >> 1 * 8) & 0xFF);
+ BAsize.append((payloadLength >> 0 * 8) & 0xFF);
+ }
+ // 8 bytes
+ else if (payloadLength <= 0x7FFFFFFF) {
+ byte = (byte | 127);
+ BAsize.append((payloadLength >> 7 * 8) & 0xFF);
+ BAsize.append((payloadLength >> 6 * 8) & 0xFF);
+ BAsize.append((payloadLength >> 5 * 8) & 0xFF);
+ BAsize.append((payloadLength >> 4 * 8) & 0xFF);
+ BAsize.append((payloadLength >> 3 * 8) & 0xFF);
+ BAsize.append((payloadLength >> 2 * 8) & 0xFF);
+ BAsize.append((payloadLength >> 1 * 8) & 0xFF);
+ BAsize.append((payloadLength >> 0 * 8) & 0xFF);
+ }
+ }
+ BA.append(byte);
+ BA.append(BAsize);
+
+ // Masking
+ if (maskingKey.size() == 4)
+ BA.append(maskingKey);
+
+ return BA;
+}
+
+void QWsSocket::ping() {
+ pingTimer.restart();
+ QByteArray pingFrame = QWsSocket::composeHeader(true, OpPing, 0);
+ writeFrame(pingFrame);
+}
+
+void QWsSocket::setResourceName(QString rn) {
+ _resourceName = rn;
+}
+
+void QWsSocket::setHost(QString h) {
+ _host = h;
+}
+
+void QWsSocket::setHostAddress(QString ha) {
+ _hostAddress = ha;
+}
+
+void QWsSocket::setHostPort(int hp) {
+ _hostPort = hp;
+}
+
+void QWsSocket::setOrigin(QString o) {
+ _origin = o;
}
-void QWsSocket::setProtocol( QString p )
-{
- _protocol = p;
+void QWsSocket::setProtocol(QString p) {
+ _protocol = p;
}
-void QWsSocket::setExtensions( QString e )
-{
- _extensions = e;
+void QWsSocket::setExtensions(QString e) {
+ _extensions = e;
}
-EWebsocketVersion QWsSocket::version()
-{
- return _version;
+EWebsocketVersion QWsSocket::version() {
+ return _version;
}
-QString QWsSocket::resourceName()
-{
- return _resourceName;
+QString QWsSocket::resourceName() {
+ return _resourceName;
}
-QString QWsSocket::host()
-{
- return _host;
+QString QWsSocket::host() {
+ return _host;
}
-QString QWsSocket::hostAddress()
-{
- return _hostAddress;
+QString QWsSocket::hostAddress() {
+ return _hostAddress;
}
-int QWsSocket::hostPort()
-{
- return _hostPort;
+int QWsSocket::hostPort() {
+ return _hostPort;
}
-QString QWsSocket::origin()
-{
- return _origin;
+QString QWsSocket::origin() {
+ return _origin;
}
-QString QWsSocket::protocol()
-{
- return _protocol;
+QString QWsSocket::protocol() {
+ return _protocol;
}
-QString QWsSocket::extensions()
-{
- return _extensions;
+QString QWsSocket::extensions() {
+ return _extensions;
}
-QString QWsSocket::composeOpeningHandShake( QString resourceName, QString host, QString origin, QString extensions, QString key )
-{
- QString hs;
- hs.append(QLatin1String("GET ") + resourceName + QLatin1String(" HTTP/1.1\r\n"));
- hs.append(QLatin1String("Host: ") + host + "\r\n");
- hs.append(QLatin1String("Upgrade: websocket\r\n"));
- hs.append(QLatin1String("Connection: Upgrade\r\n"));
- hs.append(QLatin1String("Sec-WebSocket-Key: ") + key + QLatin1String("\r\n"));
- hs.append(QLatin1String("Origin: ") + origin + QLatin1String("\r\n"));
- hs.append(QLatin1String("Sec-WebSocket-Extensions: ") + extensions + QLatin1String("\r\n"));
- hs.append(QLatin1String("Sec-WebSocket-Version: 13\r\n"));
- hs.append(QLatin1String("\r\n"));
- return hs;
+QString QWsSocket::composeOpeningHandShake(QString resourceName,
+ QString host,
+ QString origin,
+ QString extensions,
+ QString key) {
+ QString hs;
+ hs.append(QLatin1String("GET ") + resourceName +
+ QLatin1String(" HTTP/1.1\r\n"));
+ hs.append(QLatin1String("Host: ") + host + "\r\n");
+ hs.append(QLatin1String("Upgrade: websocket\r\n"));
+ hs.append(QLatin1String("Connection: Upgrade\r\n"));
+ hs.append(QLatin1String("Sec-WebSocket-Key: ") + key + QLatin1String("\r\n"));
+ hs.append(QLatin1String("Origin: ") + origin + QLatin1String("\r\n"));
+ hs.append(QLatin1String("Sec-WebSocket-Extensions: ") + extensions +
+ QLatin1String("\r\n"));
+ hs.append(QLatin1String("Sec-WebSocket-Version: 13\r\n"));
+ hs.append(QLatin1String("\r\n"));
+ return hs;
}
diff --git a/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsSocket.h b/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsSocket.h
index 4bc095aa19..cdd19db38a 100644
--- a/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsSocket.h
+++ b/src/components/qt_hmi/References/Work/fordsdlcore/QtWebsocket/QWsSocket.h
@@ -5,166 +5,177 @@
#include <QHostAddress>
#include <QTime>
-enum EWebsocketVersion
-{
- WS_VUnknow = -1,
- WS_V0 = 0,
- WS_V4 = 4,
- WS_V5 = 5,
- WS_V6 = 6,
- WS_V7 = 7,
- WS_V8 = 8,
- WS_V13 = 13
+enum EWebsocketVersion {
+ WS_VUnknow = -1,
+ WS_V0 = 0,
+ WS_V4 = 4,
+ WS_V5 = 5,
+ WS_V6 = 6,
+ WS_V7 = 7,
+ WS_V8 = 8,
+ WS_V13 = 13
};
-class QWsSocket : public QAbstractSocket
-{
- Q_OBJECT
-
- friend class QWsServer;
-
-public:
- enum EOpcode
- {
- OpContinue = 0x0,
- OpText = 0x1,
- OpBinary = 0x2,
- OpReserved3 = 0x3,
- OpReserved4 = 0x4,
- OpReserved5 = 0x5,
- OpReserved6 = 0x6,
- OpReserved7 = 0x7,
- OpClose = 0x8,
- OpPing = 0x9,
- OpPong = 0xA,
- OpReservedB = 0xB,
- OpReservedV = 0xC,
- OpReservedD = 0xD,
- OpReservedE = 0xE,
- OpReservedF = 0xF
- };
- enum ECloseStatusCode
- {
- NoCloseStatusCode = 0,
- CloseNormal = 1000,
- CloseGoingAway = 1001,
- CloseProtocolError = 1002,
- CloseDataTypeNotSupported = 1003,
- CloseReserved1004 = 1004,
- CloseMissingStatusCode = 1005,
- CloseAbnormalDisconnection = 1006,
- CloseWrongDataType = 1007,
- ClosePolicyViolated = 1008,
- CloseTooMuchData = 1009,
- CloseMissingExtension = 1010,
- CloseBadOperation = 1011,
- CloseTLSHandshakeFailed = 1015
- };
-
-public:
- // ctor
- QWsSocket( QObject * parent = 0, QTcpSocket * socket = 0, EWebsocketVersion ws_v = WS_V13 );
- // dtor
- virtual ~QWsSocket();
-
- // Public methods
- EWebsocketVersion version();
- QString resourceName();
- QString host();
- QString hostAddress();
- int hostPort();
- QString origin();
- QString protocol();
- QString extensions();
-
- void setResourceName( QString rn );
- void setHost( QString h );
- void setHostAddress( QString ha );
- void setHostPort( int hp );
- void setOrigin( QString o );
- void setProtocol( QString p );
- void setExtensions( QString e );
-
- qint64 write( const QString & string ); // write data as text
- qint64 write( const QByteArray & byteArray ); // write data as binary
-
-public slots:
- void connectToHost( const QString & hostName, quint16 port, OpenMode mode = ReadWrite );
- void connectToHost( const QHostAddress & address, quint16 port, OpenMode mode = ReadWrite );
- void disconnectFromHost();
- void abort( QString reason = QString() );
- void ping();
+class QWsSocket : public QAbstractSocket {
+ Q_OBJECT
+
+ friend class QWsServer;
+
+ public:
+ enum EOpcode {
+ OpContinue = 0x0,
+ OpText = 0x1,
+ OpBinary = 0x2,
+ OpReserved3 = 0x3,
+ OpReserved4 = 0x4,
+ OpReserved5 = 0x5,
+ OpReserved6 = 0x6,
+ OpReserved7 = 0x7,
+ OpClose = 0x8,
+ OpPing = 0x9,
+ OpPong = 0xA,
+ OpReservedB = 0xB,
+ OpReservedV = 0xC,
+ OpReservedD = 0xD,
+ OpReservedE = 0xE,
+ OpReservedF = 0xF
+ };
+ enum ECloseStatusCode {
+ NoCloseStatusCode = 0,
+ CloseNormal = 1000,
+ CloseGoingAway = 1001,
+ CloseProtocolError = 1002,
+ CloseDataTypeNotSupported = 1003,
+ CloseReserved1004 = 1004,
+ CloseMissingStatusCode = 1005,
+ CloseAbnormalDisconnection = 1006,
+ CloseWrongDataType = 1007,
+ ClosePolicyViolated = 1008,
+ CloseTooMuchData = 1009,
+ CloseMissingExtension = 1010,
+ CloseBadOperation = 1011,
+ CloseTLSHandshakeFailed = 1015
+ };
+
+ public:
+ // ctor
+ QWsSocket(QObject* parent = 0,
+ QTcpSocket* socket = 0,
+ EWebsocketVersion ws_v = WS_V13);
+ // dtor
+ virtual ~QWsSocket();
+
+ // Public methods
+ EWebsocketVersion version();
+ QString resourceName();
+ QString host();
+ QString hostAddress();
+ int hostPort();
+ QString origin();
+ QString protocol();
+ QString extensions();
+
+ void setResourceName(QString rn);
+ void setHost(QString h);
+ void setHostAddress(QString ha);
+ void setHostPort(int hp);
+ void setOrigin(QString o);
+ void setProtocol(QString p);
+ void setExtensions(QString e);
+
+ qint64 write(const QString& string); // write data as text
+ qint64 write(const QByteArray& byteArray); // write data as binary
+
+ public slots:
+ void connectToHost(const QString& hostName,
+ quint16 port,
+ OpenMode mode = ReadWrite);
+ void connectToHost(const QHostAddress& address,
+ quint16 port,
+ OpenMode mode = ReadWrite);
+ void disconnectFromHost();
+ void abort(QString reason = QString());
+ void ping();
signals:
- void frameReceived(QString frame);
- void frameReceived(QByteArray frame);
- void pong(quint64 elapsedTime);
-
-protected:
- qint64 writeFrames ( const QList<QByteArray> & framesList );
- qint64 writeFrame ( const QByteArray & byteArray );
-
-protected slots:
- virtual void close( ECloseStatusCode closeStatusCode = NoCloseStatusCode, QString reason = QString() );
- void processDataV0();
- void processDataV4();
- void processHandshake();
- void processTcpStateChanged( QAbstractSocket::SocketState socketState );
-
-private:
- enum EReadingState
- {
- HeaderPending,
- PayloadLengthPending,
- BigPayloadLenghPending,
- MaskPending,
- PayloadBodyPending,
- CloseDataPending
- };
-
- // private vars
- QTcpSocket * tcpSocket;
- QByteArray currentFrame;
- QTime pingTimer;
-
- EWebsocketVersion _version;
- QString _resourceName;
- QString _host;
- QString _hostAddress;
- int _hostPort;
- QString _origin;
- QString _protocol;
- QString _extensions;
- bool serverSideSocket;
-
- bool closingHandshakeSent;
- bool closingHandshakeReceived;
-
- EReadingState readingState;
- EOpcode opcode;
- bool isFinalFragment;
- bool hasMask;
- quint64 payloadLength;
- QByteArray maskingKey;
- ECloseStatusCode closeStatusCode;
-
- static const QString regExpAcceptStr;
- static const QString regExpUpgradeStr;
- static const QString regExpConnectionStr;
- QString handshakeResponse;
- QString key;
-
-public:
- // Static functions
- static QByteArray generateMaskingKey();
- static QByteArray generateMaskingKeyV4( QString key, QString nonce );
- static QByteArray mask( QByteArray & data, QByteArray & maskingKey );
- static QList<QByteArray> composeFrames( QByteArray byteArray, bool asBinary = false, int maxFrameBytes = 0 );
- static QByteArray composeHeader( bool end, EOpcode opcode, quint64 payloadLength, QByteArray maskingKey = QByteArray() );
- static QString composeOpeningHandShake( QString resourceName, QString host, QString origin, QString extensions, QString key );
-
- // static vars
- static int maxBytesPerFrame;
+ void frameReceived(QString frame);
+ void frameReceived(QByteArray frame);
+ void pong(quint64 elapsedTime);
+
+ protected:
+ qint64 writeFrames(const QList<QByteArray>& framesList);
+ qint64 writeFrame(const QByteArray& byteArray);
+
+ protected slots:
+ virtual void close(ECloseStatusCode closeStatusCode = NoCloseStatusCode,
+ QString reason = QString());
+ void processDataV0();
+ void processDataV4();
+ void processHandshake();
+ void processTcpStateChanged(QAbstractSocket::SocketState socketState);
+
+ private:
+ enum EReadingState {
+ HeaderPending,
+ PayloadLengthPending,
+ BigPayloadLenghPending,
+ MaskPending,
+ PayloadBodyPending,
+ CloseDataPending
+ };
+
+ // private vars
+ QTcpSocket* tcpSocket;
+ QByteArray currentFrame;
+ QTime pingTimer;
+
+ EWebsocketVersion _version;
+ QString _resourceName;
+ QString _host;
+ QString _hostAddress;
+ int _hostPort;
+ QString _origin;
+ QString _protocol;
+ QString _extensions;
+ bool serverSideSocket;
+
+ bool closingHandshakeSent;
+ bool closingHandshakeReceived;
+
+ EReadingState readingState;
+ EOpcode opcode;
+ bool isFinalFragment;
+ bool hasMask;
+ quint64 payloadLength;
+ QByteArray maskingKey;
+ ECloseStatusCode closeStatusCode;
+
+ static const QString regExpAcceptStr;
+ static const QString regExpUpgradeStr;
+ static const QString regExpConnectionStr;
+ QString handshakeResponse;
+ QString key;
+
+ public:
+ // Static functions
+ static QByteArray generateMaskingKey();
+ static QByteArray generateMaskingKeyV4(QString key, QString nonce);
+ static QByteArray mask(QByteArray& data, QByteArray& maskingKey);
+ static QList<QByteArray> composeFrames(QByteArray byteArray,
+ bool asBinary = false,
+ int maxFrameBytes = 0);
+ static QByteArray composeHeader(bool end,
+ EOpcode opcode,
+ quint64 payloadLength,
+ QByteArray maskingKey = QByteArray());
+ static QString composeOpeningHandShake(QString resourceName,
+ QString host,
+ QString origin,
+ QString extensions,
+ QString key);
+
+ // static vars
+ static int maxBytesPerFrame;
};
-#endif // QWSSOCKET_H
+#endif // QWSSOCKET_H
diff --git a/src/components/qt_hmi/References/Work/fordsdlcore/fordsdlcore_plugin.cpp b/src/components/qt_hmi/References/Work/fordsdlcore/fordsdlcore_plugin.cpp
index a89d1efcb4..003b098d47 100644
--- a/src/components/qt_hmi/References/Work/fordsdlcore/fordsdlcore_plugin.cpp
+++ b/src/components/qt_hmi/References/Work/fordsdlcore/fordsdlcore_plugin.cpp
@@ -6,26 +6,25 @@
#include <QQmlEngine>
#include <QQmlContext>
-QObject* sdlSingleton(QQmlEngine * engine, QJSEngine * js) {
- Q_UNUSED(engine)
- Q_UNUSED(js)
+QObject* sdlSingleton(QQmlEngine* engine, QJSEngine* js) {
+ Q_UNUSED(engine)
+ Q_UNUSED(js)
- engine->rootContext()->setContextProperty("MediaApps", SmartDeviceLink::getInstance().getMediaApps());
+ engine->rootContext()->setContextProperty(
+ "MediaApps", SmartDeviceLink::getInstance().getMediaApps());
- return (QObject *) &SmartDeviceLink::getInstance();
+ return (QObject*)&SmartDeviceLink::getInstance();
}
-QObject* mediaAppsSingleton(QQmlEngine * engine, QJSEngine * js) {
- Q_UNUSED(engine)
- Q_UNUSED(js)
+QObject* mediaAppsSingleton(QQmlEngine* engine, QJSEngine* js) {
+ Q_UNUSED(engine)
+ Q_UNUSED(js)
- return (QObject *) SmartDeviceLink::getInstance().getMediaApps();
+ return (QObject*)SmartDeviceLink::getInstance().getMediaApps();
}
-void FordSdlCorePlugin::registerTypes(const char *uri)
-{
- qmlRegisterSingletonType<SdlAppsListModel>(uri, 1, 0, "MediaApps", mediaAppsSingleton);
- qmlRegisterSingletonType<SmartDeviceLink>(uri, 1, 0, "AppLink", sdlSingleton);
+void FordSdlCorePlugin::registerTypes(const char* uri) {
+ qmlRegisterSingletonType<SdlAppsListModel>(
+ uri, 1, 0, "MediaApps", mediaAppsSingleton);
+ qmlRegisterSingletonType<SmartDeviceLink>(uri, 1, 0, "AppLink", sdlSingleton);
}
-
-
diff --git a/src/components/qt_hmi/References/Work/fordsdlcore/fordsdlcore_plugin.h b/src/components/qt_hmi/References/Work/fordsdlcore/fordsdlcore_plugin.h
index 655dcb5178..2c8bf39d28 100644
--- a/src/components/qt_hmi/References/Work/fordsdlcore/fordsdlcore_plugin.h
+++ b/src/components/qt_hmi/References/Work/fordsdlcore/fordsdlcore_plugin.h
@@ -3,14 +3,12 @@
#include <QQmlExtensionPlugin>
-class FordSdlCorePlugin : public QQmlExtensionPlugin
-{
- Q_OBJECT
- Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface")
-
-public:
- void registerTypes(const char *uri);
-};
+class FordSdlCorePlugin : public QQmlExtensionPlugin {
+ Q_OBJECT
+ Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface")
-#endif // FORDSDLCORE_PLUGIN_H
+ public:
+ void registerTypes(const char* uri);
+};
+#endif // FORDSDLCORE_PLUGIN_H
diff --git a/src/components/qt_hmi/References/Work/fordsdlcore/sdlalert.cpp b/src/components/qt_hmi/References/Work/fordsdlcore/sdlalert.cpp
index f625c16b41..ec4350df77 100644
--- a/src/components/qt_hmi/References/Work/fordsdlcore/sdlalert.cpp
+++ b/src/components/qt_hmi/References/Work/fordsdlcore/sdlalert.cpp
@@ -1,6 +1,3 @@
#include "sdlalert.h"
-SdlAlert::SdlAlert(QObject *parent) :
- QQuickItem()
-{
-}
+SdlAlert::SdlAlert(QObject* parent) : QQuickItem() {}
diff --git a/src/components/qt_hmi/References/Work/fordsdlcore/sdlalert.h b/src/components/qt_hmi/References/Work/fordsdlcore/sdlalert.h
index cb46236db1..9c32718c56 100644
--- a/src/components/qt_hmi/References/Work/fordsdlcore/sdlalert.h
+++ b/src/components/qt_hmi/References/Work/fordsdlcore/sdlalert.h
@@ -3,16 +3,14 @@
#include <QQuickItem>
-class SdlAlert : public QQuickItem
-{
- Q_OBJECT
-public:
- explicit SdlAlert(QObject *parent = 0);
-
+class SdlAlert : public QQuickItem {
+ Q_OBJECT
+ public:
+ explicit SdlAlert(QObject* parent = 0);
+
signals:
-
-public slots:
-
+
+ public slots:
};
-#endif // SDLALERT_H
+#endif // SDLALERT_H
diff --git a/src/components/qt_hmi/References/Work/fordsdlcore/sdlappslistmodel.cpp b/src/components/qt_hmi/References/Work/fordsdlcore/sdlappslistmodel.cpp
index 104b31abe0..419908339e 100644
--- a/src/components/qt_hmi/References/Work/fordsdlcore/sdlappslistmodel.cpp
+++ b/src/components/qt_hmi/References/Work/fordsdlcore/sdlappslistmodel.cpp
@@ -1,6 +1,4 @@
#include "sdlappslistmodel.h"
-SdlAppsListModel::SdlAppsListModel(QObject *parent) :
- QAbstractListModel(parent)
-{
-}
+SdlAppsListModel::SdlAppsListModel(QObject* parent)
+ : QAbstractListModel(parent) {}
diff --git a/src/components/qt_hmi/References/Work/fordsdlcore/sdlappslistmodel.h b/src/components/qt_hmi/References/Work/fordsdlcore/sdlappslistmodel.h
index 9b213e666e..b78aeeec01 100644
--- a/src/components/qt_hmi/References/Work/fordsdlcore/sdlappslistmodel.h
+++ b/src/components/qt_hmi/References/Work/fordsdlcore/sdlappslistmodel.h
@@ -4,44 +4,44 @@
#include <QAbstractListModel>
#include <QStringList>
-class SdlAppsListModel : public QAbstractListModel
-{
- Q_OBJECT
-public:
- explicit SdlAppsListModel(QObject *parent = 0);
-
- int rowCount(const QModelIndex &parent) const { return m_data.size(); }
-
- QVariant data(const QModelIndex &index, int role) const {
- return m_data.values().at(index.row());
- }
-
- virtual QHash<int, QByteArray> roleNames() const {
- QHash<int, QByteArray> roles;
- roles['t'] = "text";
- return roles;
- }
-
- void append(int id, QString string) {
- beginResetModel();
- m_data.clear();
- m_data[id] = string;
- endResetModel();
- }
-
- void clear() {
- beginResetModel();
- m_data.clear();
- endResetModel();
- }
-
+class SdlAppsListModel : public QAbstractListModel {
+ Q_OBJECT
+ public:
+ explicit SdlAppsListModel(QObject* parent = 0);
+
+ int rowCount(const QModelIndex& parent) const {
+ return m_data.size();
+ }
+
+ QVariant data(const QModelIndex& index, int role) const {
+ return m_data.values().at(index.row());
+ }
+
+ virtual QHash<int, QByteArray> roleNames() const {
+ QHash<int, QByteArray> roles;
+ roles['t'] = "text";
+ return roles;
+ }
+
+ void append(int id, QString string) {
+ beginResetModel();
+ m_data.clear();
+ m_data[id] = string;
+ endResetModel();
+ }
+
+ void clear() {
+ beginResetModel();
+ m_data.clear();
+ endResetModel();
+ }
+
signals:
-
-public slots:
-private:
- QHash<int, QString> m_data;
-
+ public slots:
+
+ private:
+ QHash<int, QString> m_data;
};
-#endif // SDLAPPSLISTMODEL_H
+#endif // SDLAPPSLISTMODEL_H
diff --git a/src/components/qt_hmi/References/Work/fordsdlcore/smartdevicelink.cpp b/src/components/qt_hmi/References/Work/fordsdlcore/smartdevicelink.cpp
index 57cb8ac507..5ee8c455e9 100644
--- a/src/components/qt_hmi/References/Work/fordsdlcore/smartdevicelink.cpp
+++ b/src/components/qt_hmi/References/Work/fordsdlcore/smartdevicelink.cpp
@@ -5,259 +5,382 @@
#include <QJsonObject>
#include <unistd.h>
-SmartDeviceLink::SmartDeviceLink(QQuickItem *parent):
- QObject(parent)
-{
- connect(&m_ws_basic, SIGNAL(connected()), this, SLOT(basic_connected()));
- connect(&m_ws_basic, SIGNAL(frameReceived(QString)), this, SLOT(basic_receive(QString)));
- connect(&m_ws_basic, SIGNAL(disconnected()), this, SLOT(disconnected()));
-
- connect(&m_ws_buttons, SIGNAL(connected()), this, SLOT(buttons_connected()));
- connect(&m_ws_buttons, SIGNAL(frameReceived(QString)), this, SLOT(buttons_receive(QString)));
- connect(&m_ws_buttons, SIGNAL(disconnected()), this, SLOT(disconnected()));
-
- connect(&m_ws_tts, SIGNAL(connected()), this, SLOT(tts_connected()));
- connect(&m_ws_tts, SIGNAL(frameReceived(QString)), this, SLOT(tts_receive(QString)));
- connect(&m_ws_tts, SIGNAL(disconnected()), this, SLOT(disconnected()));
-
- connect(&m_ws_vehicle, SIGNAL(connected()), this, SLOT(vehicle_connected()));
- connect(&m_ws_vehicle, SIGNAL(frameReceived(QString)), this, SLOT(vehicle_receive(QString)));
- connect(&m_ws_vehicle, SIGNAL(disconnected()), this, SLOT(disconnected()));
-
- connect(&m_ws_ui, SIGNAL(connected()), this, SLOT(ui_connected()));
- connect(&m_ws_ui, SIGNAL(frameReceived(QString)), this, SLOT(ui_receive(QString)));
- connect(&m_ws_ui, SIGNAL(disconnected()), this, SLOT(disconnected()));
-
- connect(&m_ws_vr, SIGNAL(connected()), this, SLOT(vr_connected()));
- connect(&m_ws_vr, SIGNAL(frameReceived(QString)), this, SLOT(vr_receive(QString)));
- connect(&m_ws_vr, SIGNAL(disconnected()), this, SLOT(disconnected()));
-
- connect(this, SIGNAL(newAppAvailable(int, QString)), this, SLOT(registerApp(int,QString)));
-
- m_ws_buttons.connectToHost( QLatin1String("127.0.0.1"), 8087 );
- m_ws_tts.connectToHost( QLatin1String("127.0.0.1"), 8087 );
- m_ws_vr.connectToHost( QLatin1String("127.0.0.1"), 8087 );
- m_ws_basic.connectToHost( QLatin1String("127.0.0.1"), 8087 );
- m_ws_vehicle.connectToHost( QLatin1String("127.0.0.1"), 8087 );
- m_ws_ui.connectToHost( QLatin1String("127.0.0.1"), 8087 );
+SmartDeviceLink::SmartDeviceLink(QQuickItem* parent) : QObject(parent) {
+ connect(&m_ws_basic, SIGNAL(connected()), this, SLOT(basic_connected()));
+ connect(&m_ws_basic,
+ SIGNAL(frameReceived(QString)),
+ this,
+ SLOT(basic_receive(QString)));
+ connect(&m_ws_basic, SIGNAL(disconnected()), this, SLOT(disconnected()));
+
+ connect(&m_ws_buttons, SIGNAL(connected()), this, SLOT(buttons_connected()));
+ connect(&m_ws_buttons,
+ SIGNAL(frameReceived(QString)),
+ this,
+ SLOT(buttons_receive(QString)));
+ connect(&m_ws_buttons, SIGNAL(disconnected()), this, SLOT(disconnected()));
+
+ connect(&m_ws_tts, SIGNAL(connected()), this, SLOT(tts_connected()));
+ connect(&m_ws_tts,
+ SIGNAL(frameReceived(QString)),
+ this,
+ SLOT(tts_receive(QString)));
+ connect(&m_ws_tts, SIGNAL(disconnected()), this, SLOT(disconnected()));
+
+ connect(&m_ws_vehicle, SIGNAL(connected()), this, SLOT(vehicle_connected()));
+ connect(&m_ws_vehicle,
+ SIGNAL(frameReceived(QString)),
+ this,
+ SLOT(vehicle_receive(QString)));
+ connect(&m_ws_vehicle, SIGNAL(disconnected()), this, SLOT(disconnected()));
+
+ connect(&m_ws_ui, SIGNAL(connected()), this, SLOT(ui_connected()));
+ connect(&m_ws_ui,
+ SIGNAL(frameReceived(QString)),
+ this,
+ SLOT(ui_receive(QString)));
+ connect(&m_ws_ui, SIGNAL(disconnected()), this, SLOT(disconnected()));
+
+ connect(&m_ws_vr, SIGNAL(connected()), this, SLOT(vr_connected()));
+ connect(&m_ws_vr,
+ SIGNAL(frameReceived(QString)),
+ this,
+ SLOT(vr_receive(QString)));
+ connect(&m_ws_vr, SIGNAL(disconnected()), this, SLOT(disconnected()));
+
+ connect(this,
+ SIGNAL(newAppAvailable(int, QString)),
+ this,
+ SLOT(registerApp(int, QString)));
+
+ m_ws_buttons.connectToHost(QLatin1String("127.0.0.1"), 8087);
+ m_ws_tts.connectToHost(QLatin1String("127.0.0.1"), 8087);
+ m_ws_vr.connectToHost(QLatin1String("127.0.0.1"), 8087);
+ m_ws_basic.connectToHost(QLatin1String("127.0.0.1"), 8087);
+ m_ws_vehicle.connectToHost(QLatin1String("127.0.0.1"), 8087);
+ m_ws_ui.connectToHost(QLatin1String("127.0.0.1"), 8087);
}
-SmartDeviceLink::~SmartDeviceLink()
-{
- qDebug() << "SmartDeviceLink destroyed";
+SmartDeviceLink::~SmartDeviceLink() {
+ qDebug() << "SmartDeviceLink destroyed";
}
void SmartDeviceLink::basic_connected() {
- basic_send("{\"jsonrpc\":\"2.0\",\"id\":600,\"method\":\"MB.registerComponent\",\"params\":{\"componentName\":\"BasicCommunicationClient\"}}");
+ basic_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":600,\"method\":\"MB.registerComponent\","
+ "\"params\":{\"componentName\":\"BasicCommunicationClient\"}}");
}
void SmartDeviceLink::buttons_connected() {
- buttons_send("{\"jsonrpc\":\"2.0\",\"id\":200,\"method\":\"MB.registerComponent\",\"params\":{\"componentName\":\"Buttons\"}}");
+ buttons_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":200,\"method\":\"MB.registerComponent\","
+ "\"params\":{\"componentName\":\"Buttons\"}}");
}
void SmartDeviceLink::tts_connected() {
- tts_send("{\"jsonrpc\":\"2.0\",\"id\":300,\"method\":\"MB.registerComponent\",\"params\":{\"componentName\":\"TTS\"}}");
+ tts_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":300,\"method\":\"MB.registerComponent\","
+ "\"params\":{\"componentName\":\"TTS\"}}");
}
void SmartDeviceLink::vehicle_connected() {
- vehicle_send("{\"jsonrpc\":\"2.0\",\"id\":700,\"method\":\"MB.registerComponent\",\"params\":{\"componentName\":\"VehicleInfo\"}}");
+ vehicle_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":700,\"method\":\"MB.registerComponent\","
+ "\"params\":{\"componentName\":\"VehicleInfo\"}}");
}
void SmartDeviceLink::ui_connected() {
- ui_send("{\"jsonrpc\":\"2.0\",\"id\":400,\"method\":\"MB.registerComponent\",\"params\":{\"componentName\":\"UI\"}}");
+ ui_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":400,\"method\":\"MB.registerComponent\","
+ "\"params\":{\"componentName\":\"UI\"}}");
}
void SmartDeviceLink::vr_connected() {
- vr_send("{\"jsonrpc\":\"2.0\",\"id\":500,\"method\":\"MB.registerComponent\",\"params\":{\"componentName\":\"VR\"}}");
+ vr_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":500,\"method\":\"MB.registerComponent\","
+ "\"params\":{\"componentName\":\"VR\"}}");
}
void SmartDeviceLink::basic_send(QString message) {
- qDebug() << "Sending (basic):" << message;
- m_ws_basic.write(message.append('\n'));
+ qDebug() << "Sending (basic):" << message;
+ m_ws_basic.write(message.append('\n'));
}
void SmartDeviceLink::buttons_send(QString message) {
- qDebug() << "Sending (buttons):" << message;
- m_ws_buttons.write(message.append('\n'));
+ qDebug() << "Sending (buttons):" << message;
+ m_ws_buttons.write(message.append('\n'));
}
void SmartDeviceLink::tts_send(QString message) {
- qDebug() << "Sending (tts):" << message;
- m_ws_tts.write(message.append('\n'));
+ qDebug() << "Sending (tts):" << message;
+ m_ws_tts.write(message.append('\n'));
}
void SmartDeviceLink::vehicle_send(QString message) {
- qDebug() << "Sending (vehicle):" << message;
- m_ws_vehicle.write(message.append('\n'));
+ qDebug() << "Sending (vehicle):" << message;
+ m_ws_vehicle.write(message.append('\n'));
}
void SmartDeviceLink::ui_send(QString message) {
- qDebug() << "Sending (ui):" << message;
- m_ws_ui.write(message.append('\n'));
+ qDebug() << "Sending (ui):" << message;
+ m_ws_ui.write(message.append('\n'));
}
void SmartDeviceLink::vr_send(QString message) {
- qDebug() << "Sending (vr):" << message;
- m_ws_vr.write(message.append('\n'));
+ qDebug() << "Sending (vr):" << message;
+ m_ws_vr.write(message.append('\n'));
}
void SmartDeviceLink::basic_receive(QString message) {
- qDebug() << "Receiving(basic):" << message;
- QJsonObject root = QJsonDocument::fromJson(message.toLocal8Bit()).object();
- int id = root.value("id").toDouble();
- int result = root.value("result").toDouble();
- QString method = root.value("method").toString();
-
- if (id == 600) {
- char *reg, *unreg, *update;
-
- asprintf(&reg, "{\"jsonrpc\":\"2.0\",\"id\":%i,\"method\":\"MB.subscribeTo\",\"params\":{\"propertyName\":\"BasicCommunication.OnAppRegistered\"}}", result+1);
- basic_send(reg);
- free(reg);
-
- asprintf(&unreg, "{\"jsonrpc\":\"2.0\",\"id\":%i,\"method\":\"MB.subscribeTo\",\"params\":{\"propertyName\":\"BasicCommunication.OnAppUnregistered\"}}", result+2);
- basic_send(unreg);
- free(unreg);
-
- asprintf(&update, "{\"jsonrpc\":\"2.0\",\"id\":%i,\"method\":\"MB.subscribeTo\",\"params\":{\"propertyName\":\"BasicCommunication.OnDeviceListUpdated\"}} ", result+3);
- basic_send(update);
- free(update);
- }
- else if (method.compare("BasicCommunication.OnAppRegistered") == 0) {
- QJsonObject params = root.value("params").toObject();
- QJsonObject application = params.value("application").toObject();
- QString appName = application.value("appName").toString();
- int appId = application.value("appId").toDouble();
-
- char * update;
- asprintf(&update, "{\"jsonrpc\":\"2.0\",\"id\":3000,\"method\":\"BasicCommunication.ActivateApp\",\"params\":{\"appName\":\"%s\",\"appId\":%i}}", appName.toLocal8Bit().data(), appId);
- basic_send(update);
- free(update);
- emit newAppAvailable(appId, appName);
- }
- else if (method.compare("BasicCommunication.OnAppUnregistered") == 0) {
- m_media_apps.clear();
- }
+ qDebug() << "Receiving(basic):" << message;
+ QJsonObject root = QJsonDocument::fromJson(message.toLocal8Bit()).object();
+ int id = root.value("id").toDouble();
+ int result = root.value("result").toDouble();
+ QString method = root.value("method").toString();
+
+ if (id == 600) {
+ char* reg, *unreg, *update;
+
+ asprintf(&reg,
+ "{\"jsonrpc\":\"2.0\",\"id\":%i,\"method\":\"MB.subscribeTo\","
+ "\"params\":{\"propertyName\":\"BasicCommunication."
+ "OnAppRegistered\"}}",
+ result + 1);
+ basic_send(reg);
+ free(reg);
+
+ asprintf(&unreg,
+ "{\"jsonrpc\":\"2.0\",\"id\":%i,\"method\":\"MB.subscribeTo\","
+ "\"params\":{\"propertyName\":\"BasicCommunication."
+ "OnAppUnregistered\"}}",
+ result + 2);
+ basic_send(unreg);
+ free(unreg);
+
+ asprintf(&update,
+ "{\"jsonrpc\":\"2.0\",\"id\":%i,\"method\":\"MB.subscribeTo\","
+ "\"params\":{\"propertyName\":\"BasicCommunication."
+ "OnDeviceListUpdated\"}} ",
+ result + 3);
+ basic_send(update);
+ free(update);
+ } else if (method.compare("BasicCommunication.OnAppRegistered") == 0) {
+ QJsonObject params = root.value("params").toObject();
+ QJsonObject application = params.value("application").toObject();
+ QString appName = application.value("appName").toString();
+ int appId = application.value("appId").toDouble();
+
+ char* update;
+ asprintf(&update,
+ "{\"jsonrpc\":\"2.0\",\"id\":3000,\"method\":\"BasicCommunication."
+ "ActivateApp\",\"params\":{\"appName\":\"%s\",\"appId\":%i}}",
+ appName.toLocal8Bit().data(),
+ appId);
+ basic_send(update);
+ free(update);
+ emit newAppAvailable(appId, appName);
+ } else if (method.compare("BasicCommunication.OnAppUnregistered") == 0) {
+ m_media_apps.clear();
+ }
}
void SmartDeviceLink::buttons_receive(QString message) {
- qDebug() << "Receiving(buttons):" << message;
- QJsonObject root = QJsonDocument::fromJson(message.toLocal8Bit()).object();
- int id = root.value("id").toDouble();
- QString method = root.value("method").toString();
-
- if (method.compare("Buttons.GetCapabilities") == 0) {
- buttons_send("{\"jsonrpc\":\"2.0\",\"id\":19,\"result\":{\"capabilities\":[{\"name\":\"PRESET_0\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":\"PRESET_1\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":\"PRESET_2\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":\"PRESET_3\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":\"PRESET_4\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":\"PRESET_5\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":\"PRESET_6\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":\"PRESET_7\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":\"PRESET_8\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":\"PRESET_9\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":\"OK\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":\"SEEKLEFT\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":\"SEEKRIGHT\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":\"TUNEUP\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":\"TUNEDOWN\",\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true}],\"presetBankCapabilities\":{\"onScreenPresetsAvailable\":true},\"method\":\"Buttons.GetCapabilitiesResponse\",\"resultCode\":\"SUCCESS\"}}");
- }
+ qDebug() << "Receiving(buttons):" << message;
+ QJsonObject root = QJsonDocument::fromJson(message.toLocal8Bit()).object();
+ int id = root.value("id").toDouble();
+ QString method = root.value("method").toString();
+
+ if (method.compare("Buttons.GetCapabilities") == 0) {
+ buttons_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":19,\"result\":{\"capabilities\":[{"
+ "\"name\":\"PRESET_0\",\"shortPressAvailable\":true,"
+ "\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":"
+ "\"PRESET_1\",\"shortPressAvailable\":true,\"longPressAvailable\":true,"
+ "\"upDownAvailable\":true},{\"name\":\"PRESET_2\","
+ "\"shortPressAvailable\":true,\"longPressAvailable\":true,"
+ "\"upDownAvailable\":true},{\"name\":\"PRESET_3\","
+ "\"shortPressAvailable\":true,\"longPressAvailable\":true,"
+ "\"upDownAvailable\":true},{\"name\":\"PRESET_4\","
+ "\"shortPressAvailable\":true,\"longPressAvailable\":true,"
+ "\"upDownAvailable\":true},{\"name\":\"PRESET_5\","
+ "\"shortPressAvailable\":true,\"longPressAvailable\":true,"
+ "\"upDownAvailable\":true},{\"name\":\"PRESET_6\","
+ "\"shortPressAvailable\":true,\"longPressAvailable\":true,"
+ "\"upDownAvailable\":true},{\"name\":\"PRESET_7\","
+ "\"shortPressAvailable\":true,\"longPressAvailable\":true,"
+ "\"upDownAvailable\":true},{\"name\":\"PRESET_8\","
+ "\"shortPressAvailable\":true,\"longPressAvailable\":true,"
+ "\"upDownAvailable\":true},{\"name\":\"PRESET_9\","
+ "\"shortPressAvailable\":true,\"longPressAvailable\":true,"
+ "\"upDownAvailable\":true},{\"name\":\"OK\",\"shortPressAvailable\":"
+ "true,\"longPressAvailable\":true,\"upDownAvailable\":true},{\"name\":"
+ "\"SEEKLEFT\",\"shortPressAvailable\":true,\"longPressAvailable\":true,"
+ "\"upDownAvailable\":true},{\"name\":\"SEEKRIGHT\","
+ "\"shortPressAvailable\":true,\"longPressAvailable\":true,"
+ "\"upDownAvailable\":true},{\"name\":\"TUNEUP\","
+ "\"shortPressAvailable\":true,\"longPressAvailable\":true,"
+ "\"upDownAvailable\":true},{\"name\":\"TUNEDOWN\","
+ "\"shortPressAvailable\":true,\"longPressAvailable\":true,"
+ "\"upDownAvailable\":true}],\"presetBankCapabilities\":{"
+ "\"onScreenPresetsAvailable\":true},\"method\":\"Buttons."
+ "GetCapabilitiesResponse\",\"resultCode\":\"SUCCESS\"}}");
+ }
}
void SmartDeviceLink::tts_receive(QString message) {
- qDebug() << "Receiving(tts):" << message;
- QJsonObject root = QJsonDocument::fromJson(message.toLocal8Bit()).object();
- int id = root.value("id").toDouble();
- QString method = root.value("method").toString();
-
- if (method.compare("TTS.GetCapabilities") == 0) {
- tts_send("{\"jsonrpc\":\"2.0\",\"id\":18,\"result\":{\"capabilities\":[\"TEXT\"],\"resultCode\":\"SUCCESS\",\"method\":\"TTS.GetCapabilitiesResponse\"}}");
- }
- else if (method.compare("TTS.GetLanguage") == 0) {
- tts_send("{\"jsonrpc\":\"2.0\",\"id\":26,\"result\":{\"resultCode\":\"SUCCESS\",\"method\":\"TTS.GetLanguageResponse\",\"language\":\"EN-US\"}}");
- }
- else if (method.compare("TTS.GetSupportedLanguages") == 0) {
- tts_send("{\"jsonrpc\":\"2.0\",\"id\":22,\"result\":{\"resultCode\":\"SUCCESS\",\"method\":\"TTS.GetSupportedLanguagesResponse\",\"languages\":[\"EN-US\",\"ES-MX\",\"FR-CA\",\"DE-EU\",\"ES-EU\",\"EN-EU\",\"RU-RU\",\"TR-TR\",\"PL-EU\",\"FR-EU\",\"IT-EU\",\"SV-EU\",\"PT-EU\",\"NL-EU\",\"EN-AU\",\"ZH-CN\",\"ZH-TW\",\"JA-JP\",\"AR\",\"KO-KR\"]}}");
- }
-
+ qDebug() << "Receiving(tts):" << message;
+ QJsonObject root = QJsonDocument::fromJson(message.toLocal8Bit()).object();
+ int id = root.value("id").toDouble();
+ QString method = root.value("method").toString();
+
+ if (method.compare("TTS.GetCapabilities") == 0) {
+ tts_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":18,\"result\":{\"capabilities\":[\"TEXT\"]"
+ ",\"resultCode\":\"SUCCESS\",\"method\":\"TTS."
+ "GetCapabilitiesResponse\"}}");
+ } else if (method.compare("TTS.GetLanguage") == 0) {
+ tts_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":26,\"result\":{\"resultCode\":\"SUCCESS\","
+ "\"method\":\"TTS.GetLanguageResponse\",\"language\":\"EN-US\"}}");
+ } else if (method.compare("TTS.GetSupportedLanguages") == 0) {
+ tts_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":22,\"result\":{\"resultCode\":\"SUCCESS\","
+ "\"method\":\"TTS.GetSupportedLanguagesResponse\",\"languages\":[\"EN-"
+ "US\",\"ES-MX\",\"FR-CA\",\"DE-EU\",\"ES-EU\",\"EN-EU\",\"RU-RU\",\"TR-"
+ "TR\",\"PL-EU\",\"FR-EU\",\"IT-EU\",\"SV-EU\",\"PT-EU\",\"NL-EU\",\"EN-"
+ "AU\",\"ZH-CN\",\"ZH-TW\",\"JA-JP\",\"AR\",\"KO-KR\"]}}");
+ }
}
void SmartDeviceLink::vehicle_receive(QString message) {
- qDebug() << "Receiving(vehicle):" << message;
- QJsonObject root = QJsonDocument::fromJson(message.toLocal8Bit()).object();
- int id = root.value("id").toDouble();
- QString method = root.value("method").toString();
-
- if (method.compare("VehicleInfo.GetVehicleType") == 0) {
- vehicle_send("{\"jsonrpc\":\"2.0\",\"id\":20,\"result\":{\"resultCode\":\"SUCCESS\",\"method\":\"VehicleInfo.GetVehicleTypeResponse\",\"vehicleType\":{\"make\":\"Ford\",\"model\":\"Fiesta\",\"modelYear\":\"2013\",\"trim\":\"SE\"}}}");
- }
+ qDebug() << "Receiving(vehicle):" << message;
+ QJsonObject root = QJsonDocument::fromJson(message.toLocal8Bit()).object();
+ int id = root.value("id").toDouble();
+ QString method = root.value("method").toString();
+
+ if (method.compare("VehicleInfo.GetVehicleType") == 0) {
+ vehicle_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":20,\"result\":{\"resultCode\":\"SUCCESS\","
+ "\"method\":\"VehicleInfo.GetVehicleTypeResponse\",\"vehicleType\":{"
+ "\"make\":\"Ford\",\"model\":\"Fiesta\",\"modelYear\":\"2013\","
+ "\"trim\":\"SE\"}}}");
+ }
}
void SmartDeviceLink::ui_receive(QString message) {
- qDebug() << "Receiving(ui):" << message;
- QJsonObject root = QJsonDocument::fromJson(message.toLocal8Bit()).object();
- int id = root.value("id").toDouble();
- int result = root.value("result").toDouble();
- QString method = root.value("method").toString();
-
- if (id == 400) {
- char *onchoise;
- asprintf(&onchoise, "{\"jsonrpc\":\"2.0\",\"id\":%i,\"method\":\"MB.subscribeTo\",\"params\":{\"propertyName\":\"VR.OnChoise\"}}", result + 1);
- ui_send(onchoise);
- free(onchoise);
-
- ui_send("{\"jsonrpc\":\"2.0\",\"method\":\"UI.OnReady\"}");
- }
- else if (method.compare("UI.GetCapabilities") == 0) {
- ui_send("{\"jsonrpc\":\"2.0\",\"id\":16,\"result\":{\"displayCapabilities\":{\"displayType\":\"GEN2_8_DMA\",\"textFields\":[{\"name\":\"mainField1\",\"characterSet\":\"TYPE2SET\",\"width\":1,\"rows\":1},{\"name\":\"mainField2\",\"characterSet\":\"TYPE2SET\",\"width\":1,\"rows\":1},{\"name\":\"statusBar\",\"characterSet\":\"TYPE2SET\",\"width\":1,\"rows\":1},{\"name\":\"mediaClock\",\"characterSet\":\"TYPE2SET\",\"width\":1,\"rows\":1},{\"name\":\"mediaTrack\",\"characterSet\":\"TYPE2SET\",\"width\":1,\"rows\":1},{\"name\":\"alertText1\",\"characterSet\":\"TYPE2SET\",\"width\":1,\"rows\":1},{\"name\":\"alertText2\",\"characterSet\":\"TYPE2SET\",\"width\":1,\"rows\":1}],\"mediaClockFormats\":[\"CLOCK1\",\"CLOCK2\",\"CLOCKTEXT1\",\"CLOCKTEXT2\",\"CLOCKTEXT3\"]},\"hmiZoneCapabilities\":[\"FRONT\",\"BACK\"],\"softButtonCapabilities\":[{\"shortPressAvailable\":true,\"longPressAvailable\":true,\"upDownAvailable\":true,\"imageSupported\":true}],\"method\":\"UI.GetCapabilitiesResponse\",\"resultCode\":\"SUCCESS\"}}");
- }
- else if (method.compare("UI.GetSupportedLanguages") == 0) {
- ui_send("{\"jsonrpc\":\"2.0\",\"id\":21,\"result\":{\"resultCode\":\"SUCCESS\",\"method\":\"UI.GetSupportedLanguagesResponse\",\"languages\":[\"EN-US\",\"ES-MX\",\"FR-CA\",\"DE-EU\",\"ES-EU\",\"EN-EU\",\"RU-RU\",\"TR-TR\",\"PL-EU\",\"FR-EU\",\"IT-EU\",\"SV-EU\",\"PT-EU\",\"NL-EU\",\"EN-AU\",\"ZH-CN\",\"ZH-TW\",\"JA-JP\",\"AR\",\"KO-KR\"]}}");
- }
- else if (method.compare("UI.GetLanguage") == 0) {
- ui_send("{\"jsonrpc\":\"2.0\",\"id\":24,\"result\":{\"resultCode\":\"SUCCESS\",\"method\":\"UI.GetLanguageResponse\",\"hmiDisplayLanguage\":\"EN-US\"}}");
- }
- else if (method.compare("UI.Show") == 0) {
- QJsonObject params = root.value("params").toObject();
- setShow1(params.value("mainField1").toString());
- setShow2(params.value("mainField2").toString());
- char* response;
- asprintf(&response, "{\"jsonrpc\":\"2.0\",\"id\":%i,\"result\":{\"resultCode\":\"SUCCESS\",\"method\":\"UI.ShowResponse\"}}", id);
- ui_send(response);
- free(response);
- }
- else if (method.compare("UI.Alert") == 0) {
- QJsonObject params = root.value("params").toObject();
- QString message(params.value("AlertText1").toString());
- message.append("\n").append(params.value("AlertText2").toString());
- char * response;
- asprintf(&response, "{\"jsonrpc\":\"2.0\",\"id\":%i,\"result\":{\"resultCode\":\"SUCCESS\",\"method\":\"UI.AlertResponse\"}}", id);
- ui_send(response);
- free(response);
- emit alert(message);
- }
-
+ qDebug() << "Receiving(ui):" << message;
+ QJsonObject root = QJsonDocument::fromJson(message.toLocal8Bit()).object();
+ int id = root.value("id").toDouble();
+ int result = root.value("result").toDouble();
+ QString method = root.value("method").toString();
+
+ if (id == 400) {
+ char* onchoise;
+ asprintf(&onchoise,
+ "{\"jsonrpc\":\"2.0\",\"id\":%i,\"method\":\"MB.subscribeTo\","
+ "\"params\":{\"propertyName\":\"VR.OnChoise\"}}",
+ result + 1);
+ ui_send(onchoise);
+ free(onchoise);
+
+ ui_send("{\"jsonrpc\":\"2.0\",\"method\":\"UI.OnReady\"}");
+ } else if (method.compare("UI.GetCapabilities") == 0) {
+ ui_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":16,\"result\":{\"displayCapabilities\":{"
+ "\"displayType\":\"GEN2_8_DMA\",\"textFields\":[{\"name\":"
+ "\"mainField1\",\"characterSet\":\"TYPE2SET\",\"width\":1,\"rows\":1},{"
+ "\"name\":\"mainField2\",\"characterSet\":\"TYPE2SET\",\"width\":1,"
+ "\"rows\":1},{\"name\":\"statusBar\",\"characterSet\":\"TYPE2SET\","
+ "\"width\":1,\"rows\":1},{\"name\":\"mediaClock\",\"characterSet\":"
+ "\"TYPE2SET\",\"width\":1,\"rows\":1},{\"name\":\"mediaTrack\","
+ "\"characterSet\":\"TYPE2SET\",\"width\":1,\"rows\":1},{\"name\":"
+ "\"alertText1\",\"characterSet\":\"TYPE2SET\",\"width\":1,\"rows\":1},{"
+ "\"name\":\"alertText2\",\"characterSet\":\"TYPE2SET\",\"width\":1,"
+ "\"rows\":1}],\"mediaClockFormats\":[\"CLOCK1\",\"CLOCK2\","
+ "\"CLOCKTEXT1\",\"CLOCKTEXT2\",\"CLOCKTEXT3\"]},"
+ "\"hmiZoneCapabilities\":[\"FRONT\",\"BACK\"],"
+ "\"softButtonCapabilities\":[{\"shortPressAvailable\":true,"
+ "\"longPressAvailable\":true,\"upDownAvailable\":true,"
+ "\"imageSupported\":true}],\"method\":\"UI.GetCapabilitiesResponse\","
+ "\"resultCode\":\"SUCCESS\"}}");
+ } else if (method.compare("UI.GetSupportedLanguages") == 0) {
+ ui_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":21,\"result\":{\"resultCode\":\"SUCCESS\","
+ "\"method\":\"UI.GetSupportedLanguagesResponse\",\"languages\":[\"EN-"
+ "US\",\"ES-MX\",\"FR-CA\",\"DE-EU\",\"ES-EU\",\"EN-EU\",\"RU-RU\",\"TR-"
+ "TR\",\"PL-EU\",\"FR-EU\",\"IT-EU\",\"SV-EU\",\"PT-EU\",\"NL-EU\",\"EN-"
+ "AU\",\"ZH-CN\",\"ZH-TW\",\"JA-JP\",\"AR\",\"KO-KR\"]}}");
+ } else if (method.compare("UI.GetLanguage") == 0) {
+ ui_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":24,\"result\":{\"resultCode\":\"SUCCESS\","
+ "\"method\":\"UI.GetLanguageResponse\",\"hmiDisplayLanguage\":\"EN-"
+ "US\"}}");
+ } else if (method.compare("UI.Show") == 0) {
+ QJsonObject params = root.value("params").toObject();
+ setShow1(params.value("mainField1").toString());
+ setShow2(params.value("mainField2").toString());
+ char* response;
+ asprintf(&response,
+ "{\"jsonrpc\":\"2.0\",\"id\":%i,\"result\":{\"resultCode\":"
+ "\"SUCCESS\",\"method\":\"UI.ShowResponse\"}}",
+ id);
+ ui_send(response);
+ free(response);
+ } else if (method.compare("UI.Alert") == 0) {
+ QJsonObject params = root.value("params").toObject();
+ QString message(params.value("AlertText1").toString());
+ message.append("\n").append(params.value("AlertText2").toString());
+ char* response;
+ asprintf(&response,
+ "{\"jsonrpc\":\"2.0\",\"id\":%i,\"result\":{\"resultCode\":"
+ "\"SUCCESS\",\"method\":\"UI.AlertResponse\"}}",
+ id);
+ ui_send(response);
+ free(response);
+ emit alert(message);
+ }
}
void SmartDeviceLink::vr_receive(QString message) {
- qDebug() << "Receiving(vr):" << message;
- QJsonObject root = QJsonDocument::fromJson(message.toLocal8Bit()).object();
- int id = root.value("id").toDouble();
- QString method = root.value("method").toString();
-
- if (method.compare("VR.GetCapabilities") == 0) {
- vr_send("{\"jsonrpc\":\"2.0\",\"id\":17,\"result\":{\"capabilities\":[\"TEXT\"],\"method\":\"VR.GetCapabilitiesResponse\",\"resultCode\":\"SUCCESS\"}}");
- }
- else if (method.compare("VR.GetSupportedLanguages") == 0) {
- vr_send("{\"jsonrpc\":\"2.0\",\"id\":23,\"result\":{\"resultCode\":\"SUCCESS\",\"method\":\"VR.GetSupportedLanguagesResponse\",\"languages\":[\"EN-US\",\"ES-MX\",\"FR-CA\",\"DE-EU\",\"ES-EU\",\"EN-EU\",\"RU-RU\",\"TR-TR\",\"PL-EU\",\"FR-EU\",\"IT-EU\",\"SV-EU\",\"PT-EU\",\"NL-EU\",\"EN-AU\",\"ZH-CN\",\"ZH-TW\",\"JA-JP\",\"AR\",\"KO-KR\"]}}");
- }
- else if (method.compare("VR.GetLanguage") == 0) {
- vr_send("{\"jsonrpc\":\"2.0\",\"id\":25,\"result\":{\"resultCode\":\"SUCCESS\",\"method\":\"VR.GetLanguageResponse\",\"language\":\"EN-US\"}}");
- }
+ qDebug() << "Receiving(vr):" << message;
+ QJsonObject root = QJsonDocument::fromJson(message.toLocal8Bit()).object();
+ int id = root.value("id").toDouble();
+ QString method = root.value("method").toString();
+
+ if (method.compare("VR.GetCapabilities") == 0) {
+ vr_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":17,\"result\":{\"capabilities\":[\"TEXT\"]"
+ ",\"method\":\"VR.GetCapabilitiesResponse\",\"resultCode\":\"SUCCESS\"}"
+ "}");
+ } else if (method.compare("VR.GetSupportedLanguages") == 0) {
+ vr_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":23,\"result\":{\"resultCode\":\"SUCCESS\","
+ "\"method\":\"VR.GetSupportedLanguagesResponse\",\"languages\":[\"EN-"
+ "US\",\"ES-MX\",\"FR-CA\",\"DE-EU\",\"ES-EU\",\"EN-EU\",\"RU-RU\",\"TR-"
+ "TR\",\"PL-EU\",\"FR-EU\",\"IT-EU\",\"SV-EU\",\"PT-EU\",\"NL-EU\",\"EN-"
+ "AU\",\"ZH-CN\",\"ZH-TW\",\"JA-JP\",\"AR\",\"KO-KR\"]}}");
+ } else if (method.compare("VR.GetLanguage") == 0) {
+ vr_send(
+ "{\"jsonrpc\":\"2.0\",\"id\":25,\"result\":{\"resultCode\":\"SUCCESS\","
+ "\"method\":\"VR.GetLanguageResponse\",\"language\":\"EN-US\"}}");
+ }
}
void SmartDeviceLink::registerApp(int appId, QString appName) {
- qDebug() << "New app registered:" << appName;
- m_media_apps.append(appId, appName);
+ qDebug() << "New app registered:" << appName;
+ m_media_apps.append(appId, appName);
}
void SmartDeviceLink::setShow1(QString show) {
- m_show1 = show;
- emit show1Changed(show);
+ m_show1 = show;
+ emit show1Changed(show);
}
void SmartDeviceLink::setShow2(QString show) {
- m_show2 = show;
- emit show2Changed(show);
+ m_show2 = show;
+ emit show2Changed(show);
}
void SmartDeviceLink::disconnected() {
- qDebug() << "Websocket disconnected";
+ qDebug() << "Websocket disconnected";
}
diff --git a/src/components/qt_hmi/References/Work/fordsdlcore/smartdevicelink.h b/src/components/qt_hmi/References/Work/fordsdlcore/smartdevicelink.h
index f2e7f1b2b4..18ad605f40 100644
--- a/src/components/qt_hmi/References/Work/fordsdlcore/smartdevicelink.h
+++ b/src/components/qt_hmi/References/Work/fordsdlcore/smartdevicelink.h
@@ -6,70 +6,75 @@
#include "QtWebsocket/QWsSocket.h"
#include "sdlappslistmodel.h"
-class SmartDeviceLink : public QObject
-{
- Q_OBJECT
- Q_PROPERTY(QString show1 READ getShow1 NOTIFY show1Changed)
- Q_PROPERTY(QString show2 READ getShow2 NOTIFY show2Changed)
+class SmartDeviceLink : public QObject {
+ Q_OBJECT
+ Q_PROPERTY(QString show1 READ getShow1 NOTIFY show1Changed)
+ Q_PROPERTY(QString show2 READ getShow2 NOTIFY show2Changed)
-public:
- SmartDeviceLink(QQuickItem *parent = 0);
- ~SmartDeviceLink();
+ public:
+ SmartDeviceLink(QQuickItem* parent = 0);
+ ~SmartDeviceLink();
- static SmartDeviceLink& getInstance() {
- static SmartDeviceLink instance;
- return instance;
- }
+ static SmartDeviceLink& getInstance() {
+ static SmartDeviceLink instance;
+ return instance;
+ }
- SdlAppsListModel* getMediaApps() { return &m_media_apps; }
- QString getShow1() { return m_show1; }
- QString getShow2() { return m_show2; }
+ SdlAppsListModel* getMediaApps() {
+ return &m_media_apps;
+ }
+ QString getShow1() {
+ return m_show1;
+ }
+ QString getShow2() {
+ return m_show2;
+ }
-private:
- QWsSocket m_ws_basic;
- QWsSocket m_ws_tts;
- QWsSocket m_ws_buttons;
- QWsSocket m_ws_vehicle;
- QWsSocket m_ws_ui;
- QWsSocket m_ws_vr;
+ private:
+ QWsSocket m_ws_basic;
+ QWsSocket m_ws_tts;
+ QWsSocket m_ws_buttons;
+ QWsSocket m_ws_vehicle;
+ QWsSocket m_ws_ui;
+ QWsSocket m_ws_vr;
- SdlAppsListModel m_media_apps;
+ SdlAppsListModel m_media_apps;
- QString m_show1;
- QString m_show2;
+ QString m_show1;
+ QString m_show2;
- void basic_send(QString message);
- void tts_send(QString message);
- void buttons_send(QString message);
- void vehicle_send(QString message);
- void ui_send(QString message);
- void vr_send(QString message);
- void setShow1(QString);
- void setShow2(QString);
+ void basic_send(QString message);
+ void tts_send(QString message);
+ void buttons_send(QString message);
+ void vehicle_send(QString message);
+ void ui_send(QString message);
+ void vr_send(QString message);
+ void setShow1(QString);
+ void setShow2(QString);
-public slots:
- void basic_connected();
- void tts_connected();
- void buttons_connected();
- void vehicle_connected();
- void ui_connected();
- void vr_connected();
+ public slots:
+ void basic_connected();
+ void tts_connected();
+ void buttons_connected();
+ void vehicle_connected();
+ void ui_connected();
+ void vr_connected();
- void basic_receive(QString);
- void tts_receive(QString);
- void buttons_receive(QString);
- void vehicle_receive(QString);
- void ui_receive(QString);
- void vr_receive(QString);
- void registerApp(int, QString);
+ void basic_receive(QString);
+ void tts_receive(QString);
+ void buttons_receive(QString);
+ void vehicle_receive(QString);
+ void ui_receive(QString);
+ void vr_receive(QString);
+ void registerApp(int, QString);
- void disconnected();
+ void disconnected();
signals:
- void show1Changed(QString);
- void show2Changed(QString);
- void newAppAvailable(int, QString);
- void alert(QString message);
+ void show1Changed(QString);
+ void show2Changed(QString);
+ void newAppAvailable(int, QString);
+ void alert(QString message);
};
-#endif // SMARTDEVICELINK_H
+#endif // SMARTDEVICELINK_H
diff --git a/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_controller.cc b/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_controller.cc
index d026f4bbb5..60f07783a9 100644
--- a/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_controller.cc
+++ b/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_controller.cc
@@ -36,11 +36,11 @@
#include "interfaces/QT_HMI_API.h"
#include <QtDBus/QDBusConnection>
-DBusController::DBusController(QObject *parent)
- : QObject(parent),
- message(NULL) {}
+DBusController::DBusController(QObject* parent)
+ : QObject(parent), message(NULL) {}
-void DBusController::addMessage(const QDBusMessage& message, fillRoutine fill,
+void DBusController::addMessage(const QDBusMessage& message,
+ fillRoutine fill,
int async_uid) {
delayedReply reply;
reply.message = message;
@@ -54,11 +54,11 @@ void DBusController::sendReply(QVariant asyncObject, QVariant data) {
if (it != replies_.end()) {
QDBusMessage msg = it->second.message.createReply();
if (!it->second.fill(msg, data.toMap())) {
- QDBusConnection::sessionBus()
- .send(it->second.message.createErrorReply(QDBusError::InternalError,
- QString::number(hmi_apis::Common_Result::INVALID_DATA)));
+ QDBusConnection::sessionBus().send(it->second.message.createErrorReply(
+ QDBusError::InternalError,
+ QString::number(hmi_apis::Common_Result::INVALID_DATA)));
} else {
- QDBusConnection::sessionBus().send(msg);
+ QDBusConnection::sessionBus().send(msg);
}
replies_.erase(it);
}
@@ -69,15 +69,17 @@ void DBusController::sendReply(QVariant data) {
return;
QDBusMessage msg = message->createReply();
if (!fill(msg, data.toMap())) {
- QDBusConnection::sessionBus()
- .send(message->createErrorReply(QDBusError::InternalError,
- QString::number(hmi_apis::Common_Result::INVALID_DATA)));
+ QDBusConnection::sessionBus().send(message->createErrorReply(
+ QDBusError::InternalError,
+ QString::number(hmi_apis::Common_Result::INVALID_DATA)));
} else {
QDBusConnection::sessionBus().send(msg);
}
}
-void DBusController::sendError(QVariant asyncObject, QVariant code, QVariant message) {
+void DBusController::sendError(QVariant asyncObject,
+ QVariant code,
+ QVariant message) {
int uid = asyncObject.toMap()["__async_uid"].toInt();
std::map<int, delayedReply>::iterator it = replies_.find(uid);
if (it != replies_.end()) {
diff --git a/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_controller.h b/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_controller.h
index ecda598670..937bab5f90 100644
--- a/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_controller.h
+++ b/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_controller.h
@@ -41,7 +41,7 @@
typedef bool (*fillRoutine)(QDBusMessage&, const QVariantMap&);
-class DBusController: public QObject {
+class DBusController : public QObject {
struct delayedReply {
QDBusMessage message;
fillRoutine fill;
@@ -49,12 +49,14 @@ class DBusController: public QObject {
Q_OBJECT
public:
- explicit DBusController(QObject *parent = 0);
+ explicit DBusController(QObject* parent = 0);
void addMessage(const QDBusMessage& message, fillRoutine fill, int async_uid);
Q_INVOKABLE void sendReply(QVariant asyncObject, QVariant data);
Q_INVOKABLE void sendReply(QVariant data);
Q_INVOKABLE void sendError(QVariant asyncObject, QVariant code);
- Q_INVOKABLE void sendError(QVariant asyncObject, QVariant code, QVariant message);
+ Q_INVOKABLE void sendError(QVariant asyncObject,
+ QVariant code,
+ QVariant message);
const QDBusMessage* message;
fillRoutine fill;
diff --git a/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_plugin.cc b/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_plugin.cc
index 0f41a28e73..5cc4dadb1e 100644
--- a/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_plugin.cc
+++ b/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_plugin.cc
@@ -48,18 +48,18 @@
#include <QtDBus/QDBusConnection>
#if QT_4
-# include <QtDeclarative/QDeclarativeContext>
-# include <QtDeclarative/QDeclarativeListReference>
-# include <QtDeclarative/QDeclarativeEngine>
+#include <QtDeclarative/QDeclarativeContext>
+#include <QtDeclarative/QDeclarativeListReference>
+#include <QtDeclarative/QDeclarativeEngine>
#elif QT_5
-# include <QtQml/QQmlContext>
-# include <QtQml/QQmlListReference>
-# include <QtQml/QQmlEngine>
+#include <QtQml/QQmlContext>
+#include <QtQml/QQmlListReference>
+#include <QtQml/QQmlEngine>
#endif // QT_VERSION
-log4cxx::LoggerPtr logger_ = log4cxx::LoggerPtr(
- log4cxx::Logger::getLogger("DBusPlugin"));
+log4cxx::LoggerPtr logger_ =
+ log4cxx::LoggerPtr(log4cxx::Logger::getLogger("DBusPlugin"));
-void DbusPlugin::registerTypes(const char *uri) {
+void DbusPlugin::registerTypes(const char* uri) {
log4cxx::PropertyConfigurator::configure("log4cxx.properties");
// @uri sdl.core.api
@@ -87,9 +87,9 @@ void DbusPlugin::registerTypes(const char *uri) {
HmiProxy::api_adaptors_.SetDBusController(dbusController_);
}
-void DbusPlugin::initializeEngine(Engine *engine, const char *uri) {
- engine->rootContext()->setContextProperty("DBus", dbusController_);
- engine->rootContext()->setContextProperty("RequestToSDL", requestToSDL_);
+void DbusPlugin::initializeEngine(Engine* engine, const char* uri) {
+ engine->rootContext()->setContextProperty("DBus", dbusController_);
+ engine->rootContext()->setContextProperty("RequestToSDL", requestToSDL_);
}
#if QT_4
diff --git a/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_plugin.h b/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_plugin.h
index ef2a925956..2b5bba6235 100644
--- a/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_plugin.h
+++ b/src/components/qt_hmi/qml_plugins/dbus_adapter/dbus_plugin.h
@@ -38,11 +38,11 @@
#include "qt_version.h"
#if QT_4
-# include <QtDeclarative/QDeclarativeExtensionPlugin>
+#include <QtDeclarative/QDeclarativeExtensionPlugin>
typedef QDeclarativeExtensionPlugin ExtensionPlugin;
typedef QDeclarativeEngine Engine;
#elif QT_5
-# include <QtQml/QQmlExtensionPlugin>
+#include <QtQml/QQmlExtensionPlugin>
typedef QQmlExtensionPlugin ExtensionPlugin;
typedef QQmlEngine Engine;
#endif // QT_VERSION
@@ -58,13 +58,12 @@ class DbusPlugin : public ExtensionPlugin, public QDBusContext {
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface")
#endif // QT_5
- DBusController *dbusController_;
- RequestToSDL *requestToSDL_;
+ DBusController* dbusController_;
+ RequestToSDL* requestToSDL_;
public:
- void registerTypes(const char *uri);
- void initializeEngine(Engine *engine, const char *uri);
+ void registerTypes(const char* uri);
+ void initializeEngine(Engine* engine, const char* uri);
};
#endif // SRC_COMPONENTS_QT_HMI_QML_PLUGINS_DBUS_ADAPTER_DBUS_PLUGIN_H_
-
diff --git a/src/components/qt_hmi/qml_plugins/dbus_adapter/hmi_proxy.cc b/src/components/qt_hmi/qml_plugins/dbus_adapter/hmi_proxy.cc
index 8b6cfd57d4..e196e5c5de 100644
--- a/src/components/qt_hmi/qml_plugins/dbus_adapter/hmi_proxy.cc
+++ b/src/components/qt_hmi/qml_plugins/dbus_adapter/hmi_proxy.cc
@@ -37,8 +37,7 @@
ApiAdaptors HmiProxy::api_adaptors_;
-HmiProxy::HmiProxy(Item *parent)
- : Item(parent) {}
+HmiProxy::HmiProxy(Item* parent) : Item(parent) {}
void HmiProxy::componentComplete() {
Item::componentComplete();
diff --git a/src/components/qt_hmi/qml_plugins/dbus_adapter/hmi_proxy.h b/src/components/qt_hmi/qml_plugins/dbus_adapter/hmi_proxy.h
index 886d523157..d7277d017b 100644
--- a/src/components/qt_hmi/qml_plugins/dbus_adapter/hmi_proxy.h
+++ b/src/components/qt_hmi/qml_plugins/dbus_adapter/hmi_proxy.h
@@ -39,10 +39,10 @@
#include "qml_dbus.h"
#if QT_4
-# include <QtDeclarative/QDeclarativeItem>
+#include <QtDeclarative/QDeclarativeItem>
typedef QDeclarativeItem Item;
#elif QT_5
-# include <QtQuick/QQuickItem>
+#include <QtQuick/QQuickItem>
typedef QQuickItem Item;
#endif // QT_VERSION
@@ -51,7 +51,7 @@ class HmiProxy : public Item {
Q_DISABLE_COPY(HmiProxy)
public:
- explicit HmiProxy(Item *parent = 0);
+ explicit HmiProxy(Item* parent = 0);
static ApiAdaptors api_adaptors_;
protected:
@@ -61,4 +61,3 @@ class HmiProxy : public Item {
QML_DECLARE_TYPE(HmiProxy)
#endif // SRC_COMPONENTS_QT_HMI_QML_PLUGINS_DBUS_ADAPTER_HMI_PROXY_H_
-
diff --git a/src/components/qt_hmi/qml_plugins/dbus_adapter/metatype.h b/src/components/qt_hmi/qml_plugins/dbus_adapter/metatype.h
index 5224da7f55..b127cea1a8 100644
--- a/src/components/qt_hmi/qml_plugins/dbus_adapter/metatype.h
+++ b/src/components/qt_hmi/qml_plugins/dbus_adapter/metatype.h
@@ -35,25 +35,25 @@
#include <QMetaType>
-template<typename T>
+template <typename T>
QMetaType::Type metatype();
-template<>
+template <>
inline QMetaType::Type metatype<int>() {
return QMetaType::Int;
}
-template<>
+template <>
inline QMetaType::Type metatype<QString>() {
return QMetaType::QString;
}
-template<>
+template <>
inline QMetaType::Type metatype<bool>() {
return QMetaType::Bool;
}
-template<>
+template <>
inline QMetaType::Type metatype<double>() {
return QMetaType::Double;
}
diff --git a/src/components/qt_hmi/qml_plugins/dbus_adapter/optional_argument.h b/src/components/qt_hmi/qml_plugins/dbus_adapter/optional_argument.h
index b9360c3eb4..ea6f68bb31 100644
--- a/src/components/qt_hmi/qml_plugins/dbus_adapter/optional_argument.h
+++ b/src/components/qt_hmi/qml_plugins/dbus_adapter/optional_argument.h
@@ -38,38 +38,34 @@
#include "qt_version.h"
#include <QtDBus/QDBusArgument>
-template<class T>
+template <class T>
struct OptionalArgument {
T val;
bool presence;
- explicit OptionalArgument(const T& value)
- : val(value),
- presence(true) {}
- OptionalArgument()
- : presence(false) {}
+ explicit OptionalArgument(const T& value) : val(value), presence(true) {}
+ OptionalArgument() : presence(false) {}
};
-template<class T>
-inline
-QDBusArgument& operator << (QDBusArgument& arg, const OptionalArgument<T>& o) {
+template <class T>
+inline QDBusArgument& operator<<(QDBusArgument& arg,
+ const OptionalArgument<T>& o) {
arg.beginStructure();
arg << o.presence << o.val;
arg.endStructure();
return arg;
}
-template<class T>
-inline
-const QDBusArgument& operator >> (const QDBusArgument& arg, OptionalArgument<T>& o) {
+template <class T>
+inline const QDBusArgument& operator>>(const QDBusArgument& arg,
+ OptionalArgument<T>& o) {
arg.beginStructure();
arg >> o.presence >> o.val;
arg.endStructure();
return arg;
}
-template<class T>
-inline
-bool VariantToValue(const QVariant& variant, OptionalArgument<T>& o) {
+template <class T>
+inline bool VariantToValue(const QVariant& variant, OptionalArgument<T>& o) {
if (variant.isNull()) {
o.presence = false;
return true;
@@ -80,7 +76,7 @@ bool VariantToValue(const QVariant& variant, OptionalArgument<T>& o) {
#if QT_4
Q_DECLARE_METATYPE(QList<int>)
-#endif // QT_4
+#endif // QT_4
Q_DECLARE_METATYPE(OptionalArgument<int>)
Q_DECLARE_METATYPE(OptionalArgument<QString>)
diff --git a/src/components/qt_hmi/qml_plugins/dbus_adapter/qml_dbus_common.h b/src/components/qt_hmi/qml_plugins/dbus_adapter/qml_dbus_common.h
index eb9b93929f..fa9692f9d9 100644
--- a/src/components/qt_hmi/qml_plugins/dbus_adapter/qml_dbus_common.h
+++ b/src/components/qt_hmi/qml_plugins/dbus_adapter/qml_dbus_common.h
@@ -70,8 +70,7 @@ enum ErrorCode {
inline void RaiseDbusError(QObject* adaptor, int code, const QString& message) {
QDBusContext* context = dynamic_cast<QDBusContext*>(adaptor->parent());
if (context) {
- context->sendErrorReply(QString::number(static_cast<int>(code)),
- message);
+ context->sendErrorReply(QString::number(static_cast<int>(code)), message);
}
}
@@ -79,31 +78,39 @@ inline void RaiseDbusError(QObject* adaptor, int code) {
RaiseDbusError(adaptor, code, "");
}
-template<typename T>
+template <typename T>
inline void PutArgToMap(QVariantMap& map, const char* name, const T& v) {
map.insert(name, QVariant::fromValue(v));
}
inline bool GetArgFromMap(const QVariantMap& map, const char* name, int& v) {
QVariantMap::const_iterator it = map.find(name);
- if (map.end() == it) return false;
- if (it->type() != QVariant::Int) return false;
+ if (map.end() == it)
+ return false;
+ if (it->type() != QVariant::Int)
+ return false;
v = it->toInt();
return true;
}
-inline bool GetArgFromMap(const QVariantMap& map, const char* name, QString& v) {
+inline bool GetArgFromMap(const QVariantMap& map,
+ const char* name,
+ QString& v) {
QVariantMap::const_iterator it = map.find(name);
- if (map.end() == it) return false;
- if (it->type() != QVariant::String) return false;
+ if (map.end() == it)
+ return false;
+ if (it->type() != QVariant::String)
+ return false;
v = it->toString();
return true;
}
inline bool GetArgFromMap(const QVariantMap& map, const char* name, bool& v) {
QVariantMap::const_iterator it = map.find(name);
- if (map.end() == it) return false;
- if (it->type() != QVariant::Bool) return false;
+ if (map.end() == it)
+ return false;
+ if (it->type() != QVariant::Bool)
+ return false;
v = it->toBool();
return true;
}
@@ -111,78 +118,87 @@ inline bool GetArgFromMap(const QVariantMap& map, const char* name, bool& v) {
inline bool isNumber(QVariant v) {
QVariant::Type t = v.type();
return (t == QVariant::Double) || (t == QVariant::Int) ||
- (t == QVariant::UInt) || (t == QVariant::LongLong) ||
+ (t == QVariant::UInt) || (t == QVariant::LongLong) ||
(t == QVariant::ULongLong);
}
inline bool GetArgFromMap(const QVariantMap& map, const char* name, double& v) {
QVariantMap::const_iterator it = map.find(name);
- if (map.end() == it) return false;
- if (!isNumber(*it)) return false;
+ if (map.end() == it)
+ return false;
+ if (!isNumber(*it))
+ return false;
v = it->toDouble();
return true;
}
inline bool VariantToValue(const QVariant& variant, int& v) {
- if (variant.type() != QVariant::Int) return false;
- v = variant.toInt();
- return true;
+ if (variant.type() != QVariant::Int)
+ return false;
+ v = variant.toInt();
+ return true;
}
inline bool VariantToValue(const QVariant& variant, QString& v) {
- if (variant.type() != QVariant::String) return false;
- v = variant.toString();
- return true;
+ if (variant.type() != QVariant::String)
+ return false;
+ v = variant.toString();
+ return true;
}
inline bool VariantToValue(const QVariant& variant, bool& v) {
- if (variant.type() != QVariant::Bool) return false;
- v = variant.toBool();
- return true;
+ if (variant.type() != QVariant::Bool)
+ return false;
+ v = variant.toBool();
+ return true;
}
inline bool VariantToValue(const QVariant& variant, double& v) {
- if (variant.type() != QVariant::Double) return false;
- v = variant.toDouble();
- return true;
+ if (variant.type() != QVariant::Double)
+ return false;
+ v = variant.toDouble();
+ return true;
}
inline bool VariantToValue(const QVariant& variant, QStringList& v) {
- if (variant.type() != QVariant::List) return false;
+ if (variant.type() != QVariant::List)
+ return false;
QList<QVariant> list = variant.toList();
for (QList<QVariant>::const_iterator i = list.begin(); i != list.end(); ++i) {
- if (i->type() != QVariant::String) return false;
+ if (i->type() != QVariant::String)
+ return false;
v.append(i->toString());
}
return true;
}
-template<typename T>
+template <typename T>
bool VariantToValue(const QVariant& variant, QList<T>& v) {
- if (variant.type() != QVariant::List) return false;
- QList<T> spare;
- QList<QVariant> list = variant.toList();
- for (QList<QVariant>::const_iterator i = list.begin(); i != list.end(); ++i) {
- QVariant::Type type = i->type();
-// Although this function is declared as returning QVariant::Type(obsolete),
-// the return value should be interpreted as QMetaType::Type.
-// (http://qt-project.org/doc/qt-5.0/qtcore/qvariant.html#type)
- QMetaType::Type type_casted = static_cast<QMetaType::Type>(type);
- if (type_casted != metatype<T>()) {
- return false;
- }
- spare.append(i->value<T>());
+ if (variant.type() != QVariant::List)
+ return false;
+ QList<T> spare;
+ QList<QVariant> list = variant.toList();
+ for (QList<QVariant>::const_iterator i = list.begin(); i != list.end(); ++i) {
+ QVariant::Type type = i->type();
+ // Although this function is declared as returning QVariant::Type(obsolete),
+ // the return value should be interpreted as QMetaType::Type.
+ // (http://qt-project.org/doc/qt-5.0/qtcore/qvariant.html#type)
+ QMetaType::Type type_casted = static_cast<QMetaType::Type>(type);
+ if (type_casted != metatype<T>()) {
+ return false;
}
- v.swap(spare);
- return true;
+ spare.append(i->value<T>());
+ }
+ v.swap(spare);
+ return true;
}
-template<typename T>
+template <typename T>
inline QVariant ValueToVariant(const T& v) {
- return QVariant::fromValue(v);
+ return QVariant::fromValue(v);
}
-template<typename T>
+template <typename T>
inline QVariant ValueToVariant(const QList<T>& v) {
QList<QVariant> list;
for (typename QList<T>::const_iterator i = v.begin(); i != v.end(); ++i)
@@ -190,7 +206,7 @@ inline QVariant ValueToVariant(const QList<T>& v) {
return QVariant::fromValue(list);
}
-template<typename T>
+template <typename T>
inline void PutArgToMap(QVariantMap& map, const char* name, const QList<T>& v) {
QList<QVariant> list;
for (typename QList<T>::const_iterator i = v.begin(); i != v.end(); ++i)
@@ -198,31 +214,38 @@ inline void PutArgToMap(QVariantMap& map, const char* name, const QList<T>& v) {
map.insert(name, QVariant::fromValue(list));
}
-template<typename T>
-inline bool GetArgFromMap(const QVariantMap& map, const char* name, QList<T>& v) {
+template <typename T>
+inline bool GetArgFromMap(const QVariantMap& map,
+ const char* name,
+ QList<T>& v) {
QVariantMap::const_iterator it = map.find(name);
- if (map.end() == it) return false;
+ if (map.end() == it)
+ return false;
const QVariant& variant = *it;
- if (variant.type() != QVariant::List) return false;
+ if (variant.type() != QVariant::List)
+ return false;
QList<QVariant> list = variant.toList();
for (QList<QVariant>::const_iterator i = list.begin(); i != list.end(); ++i) {
T t;
bool ok = VariantToValue(*i, t);
- if (!ok) return false;
+ if (!ok)
+ return false;
v.append(t);
}
return true;
}
-template<typename T>
-inline void PutArgToMap(QVariantMap& map, const char* name,
+template <typename T>
+inline void PutArgToMap(QVariantMap& map,
+ const char* name,
const OptionalArgument<T>& v) {
if (v.presence)
map.insert(name, ValueToVariant(v.val));
}
-template<typename T>
-inline bool GetArgFromMap(const QVariantMap& map, const char* name,
+template <typename T>
+inline bool GetArgFromMap(const QVariantMap& map,
+ const char* name,
OptionalArgument<T>& v) {
QVariantMap::const_iterator it = map.find(name);
if (map.end() == it || !it->isValid()) {
diff --git a/src/components/qt_hmi/qml_plugins/dbus_adapter/qt_version.h b/src/components/qt_hmi/qml_plugins/dbus_adapter/qt_version.h
index 4eff83bd5b..c41eea7403 100644
--- a/src/components/qt_hmi/qml_plugins/dbus_adapter/qt_version.h
+++ b/src/components/qt_hmi/qml_plugins/dbus_adapter/qt_version.h
@@ -37,11 +37,12 @@
#include <qglobal.h>
-#define QT_4 ((QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)) && \
- (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)))
+#define QT_4 \
+ ((QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)) && \
+ (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)))
-#define QT_5 ((QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) && \
- (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)))
+#define QT_5 \
+ ((QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) && \
+ (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)))
#endif // SRC_COMPONENTS_QT_HMI_QML_PLUGINS_DBUS_ADAPTER_QT_VERSION_H_
-
diff --git a/src/components/qt_hmi/qml_plugins/dbus_adapter/stream_qvariant.cc b/src/components/qt_hmi/qml_plugins/dbus_adapter/stream_qvariant.cc
index b60f5226c4..ec049b9533 100644
--- a/src/components/qt_hmi/qml_plugins/dbus_adapter/stream_qvariant.cc
+++ b/src/components/qt_hmi/qml_plugins/dbus_adapter/stream_qvariant.cc
@@ -35,33 +35,33 @@
std::basic_ostream<char>& operator<<(std::basic_ostream<char>& os,
const QVariant& value) {
switch (value.type()) {
- case QVariant::Map: {
- os << "{ ";
- QVariantMap structure = value.toMap();
- QMapIterator<QString, QVariant> i(structure);
- while (i.hasNext()) {
- i.next();
- os << i.key() << ":" << i.value();
- if (i.hasNext()) {
- os << ", ";
+ case QVariant::Map: {
+ os << "{ ";
+ QVariantMap structure = value.toMap();
+ QMapIterator<QString, QVariant> i(structure);
+ while (i.hasNext()) {
+ i.next();
+ os << i.key() << ":" << i.value();
+ if (i.hasNext()) {
+ os << ", ";
+ }
}
- }
- os << " }";
- } break;
- case QVariant::List: {
- os << "[ ";
- QVariantList array = value.toList();
- QListIterator<QVariant> i(array);
- while (i.hasNext()) {
- os << i.next();
- if (i.hasNext()) {
- os << ", ";
+ os << " }";
+ } break;
+ case QVariant::List: {
+ os << "[ ";
+ QVariantList array = value.toList();
+ QListIterator<QVariant> i(array);
+ while (i.hasNext()) {
+ os << i.next();
+ if (i.hasNext()) {
+ os << ", ";
+ }
}
- }
- os << " ]";
- } break;
- default:
- os << value.toString().toLatin1().data();
+ os << " ]";
+ } break;
+ default:
+ os << value.toString().toLatin1().data();
}
return os;
diff --git a/src/components/qt_hmi/qml_plugins/hw_buttons/attributed_mouse_event.cc b/src/components/qt_hmi/qml_plugins/hw_buttons/attributed_mouse_event.cc
index bcde90930f..899fc5b615 100644
--- a/src/components/qt_hmi/qml_plugins/hw_buttons/attributed_mouse_event.cc
+++ b/src/components/qt_hmi/qml_plugins/hw_buttons/attributed_mouse_event.cc
@@ -34,6 +34,6 @@
#include "attributed_mouse_event.h"
-Item *AttributedMouseEvent::item() const {
- return item_;
+Item* AttributedMouseEvent::item() const {
+ return item_;
}
diff --git a/src/components/qt_hmi/qml_plugins/hw_buttons/attributed_mouse_event.h b/src/components/qt_hmi/qml_plugins/hw_buttons/attributed_mouse_event.h
index 2d2babc29f..0486397058 100644
--- a/src/components/qt_hmi/qml_plugins/hw_buttons/attributed_mouse_event.h
+++ b/src/components/qt_hmi/qml_plugins/hw_buttons/attributed_mouse_event.h
@@ -38,10 +38,10 @@
#include <QtCore/QObject>
#if QT_4
-# include <QtDeclarative/QDeclarativeItem>
+#include <QtDeclarative/QDeclarativeItem>
typedef QDeclarativeItem Item;
#elif QT_5
-# include <QtQuick/QQuickItem>
+#include <QtQuick/QQuickItem>
typedef QQuickItem Item;
#endif // QT_VERSION
@@ -50,12 +50,12 @@ class AttributedMouseEvent : public QObject {
Q_PROPERTY(Item* item READ item)
public:
- explicit AttributedMouseEvent(Item *item) : item_(item) {}
+ explicit AttributedMouseEvent(Item* item) : item_(item) {}
- Item *item() const;
+ Item* item() const;
private:
- Item *item_;
+ Item* item_;
Q_DISABLE_COPY(AttributedMouseEvent)
};
diff --git a/src/components/qt_hmi/qml_plugins/hw_buttons/hmi_hwbuttons.cc b/src/components/qt_hmi/qml_plugins/hw_buttons/hmi_hwbuttons.cc
index bf63c12cb1..62a090a509 100644
--- a/src/components/qt_hmi/qml_plugins/hw_buttons/hmi_hwbuttons.cc
+++ b/src/components/qt_hmi/qml_plugins/hw_buttons/hmi_hwbuttons.cc
@@ -35,16 +35,16 @@
#include "hmi_hwbuttons.h"
#if QT_4
-# include <QtDeclarative/qdeclarative.h>
-# include <QtGui/QGraphicsColorizeEffect>
+#include <QtDeclarative/qdeclarative.h>
+#include <QtGui/QGraphicsColorizeEffect>
#elif QT_5
-# include <QtQml>
+#include <QtQml>
#endif // QT_VERSION
#include "masked_container.h"
#include "attributed_mouse_event.h"
-void HmiHWButtons::registerTypes(const char *uri) {
+void HmiHWButtons::registerTypes(const char* uri) {
// @uri com.ford.hmi_framework
qmlRegisterType<MaskedContainer>(uri, 1, 0, "MaskedContainer");
qmlRegisterType<AttributedMouseEvent>();
diff --git a/src/components/qt_hmi/qml_plugins/hw_buttons/hmi_hwbuttons.h b/src/components/qt_hmi/qml_plugins/hw_buttons/hmi_hwbuttons.h
index cf8f0b5f4b..0cf71807c4 100644
--- a/src/components/qt_hmi/qml_plugins/hw_buttons/hmi_hwbuttons.h
+++ b/src/components/qt_hmi/qml_plugins/hw_buttons/hmi_hwbuttons.h
@@ -38,10 +38,10 @@
#include "qt_version.h"
#if QT_4
-# include <QtDeclarative/QDeclarativeExtensionPlugin>
+#include <QtDeclarative/QDeclarativeExtensionPlugin>
typedef QDeclarativeExtensionPlugin ExtensionPlugin;
#elif QT_5
-# include <QtQml/QQmlExtensionPlugin>
+#include <QtQml/QQmlExtensionPlugin>
typedef QQmlExtensionPlugin ExtensionPlugin;
#endif // QT_VERSION
@@ -52,8 +52,7 @@ class HmiHWButtons : public ExtensionPlugin {
#endif // QT_5
public:
- void registerTypes(const char *uri);
+ void registerTypes(const char* uri);
};
#endif // SRC_COMPONENTS_QT_HMI_QML_PLUGINS_HW_BUTTONS_HMI_HWBUTTONS_H_
-
diff --git a/src/components/qt_hmi/qml_plugins/hw_buttons/masked_container.cc b/src/components/qt_hmi/qml_plugins/hw_buttons/masked_container.cc
index 0d144ff84c..f80e80907e 100644
--- a/src/components/qt_hmi/qml_plugins/hw_buttons/masked_container.cc
+++ b/src/components/qt_hmi/qml_plugins/hw_buttons/masked_container.cc
@@ -35,74 +35,73 @@
#include "masked_container.h"
#if QT_4
-# include <QtCore/QPointF>
-# include <QtGui/QGraphicsSceneMouseEvent>
-# define IMAGE "QDeclarativeImage"
+#include <QtCore/QPointF>
+#include <QtGui/QGraphicsSceneMouseEvent>
+#define IMAGE "QDeclarativeImage"
#elif QT_5
-# include <QtGui/QImage>
-# include <QtCore/QEvent>
-# define IMAGE "QQuickImage"
+#include <QtGui/QImage>
+#include <QtCore/QEvent>
+#define IMAGE "QQuickImage"
#endif // QT_VERSION
-MaskedContainer::MaskedContainer(Item *parent)
- : Item(parent),
- mask_(NULL) {
+MaskedContainer::MaskedContainer(Item* parent) : Item(parent), mask_(NULL) {
setAcceptedMouseButtons(Qt::LeftButton);
}
void MaskedContainer::componentComplete() {
- Item::componentComplete();
-
- for (QObjectList::ConstIterator it = children().begin();
- it != children().end(); ++it) {
- Item *item = qobject_cast<Item*>(*it);
- if (item && item->inherits(IMAGE) && item->isVisible()) {
- images_.push_back(item);
- }
+ Item::componentComplete();
+
+ for (QObjectList::ConstIterator it = children().begin();
+ it != children().end();
+ ++it) {
+ Item* item = qobject_cast<Item*>(*it);
+ if (item && item->inherits(IMAGE) && item->isVisible()) {
+ images_.push_back(item);
}
+ }
- int height = this->height();
- int width =this->width();
-
- for (size_t i = 0; i < images_.size(); ++i) {
- Item *item = images_[i];
- int itemWidth = item->width();
- int itemHeight = item->height();
- int itemX = item->x();
- int itemY = item->y();
- if (height < itemHeight + itemY)
- height = itemHeight + itemY;
- if (width < itemWidth + itemX)
- width = itemWidth + itemX;
- }
+ int height = this->height();
+ int width = this->width();
+
+ for (size_t i = 0; i < images_.size(); ++i) {
+ Item* item = images_[i];
+ int itemWidth = item->width();
+ int itemHeight = item->height();
+ int itemX = item->x();
+ int itemY = item->y();
+ if (height < itemHeight + itemY)
+ height = itemHeight + itemY;
+ if (width < itemWidth + itemX)
+ width = itemWidth + itemX;
+ }
- setHeight(height);
- setWidth(width);
-
- mask_ = new int[height * width];
- std::fill(mask_, mask_ + height * width, -1);
-
- for (size_t i = 0; i < images_.size(); ++i) {
- Item *item = images_[i];
- int itemWidth = item->width();
- int itemHeight = item->height();
- int itemX = item->x();
- int itemY = item->y();
-
- QUrl url = item->property("source").toUrl();
- QImage img(url.path());
- const QRgb* bits = reinterpret_cast<const QRgb*>(img.constBits());
- for (int x = 0; x < itemWidth; ++x) {
- for (int y = 0; y < itemHeight; ++y) {
- if (qAlpha(bits[y * itemWidth + x]) > 128) {
- mask_[(itemY + y) * width + (x + itemX)] = i;
- }
- }
+ setHeight(height);
+ setWidth(width);
+
+ mask_ = new int[height * width];
+ std::fill(mask_, mask_ + height * width, -1);
+
+ for (size_t i = 0; i < images_.size(); ++i) {
+ Item* item = images_[i];
+ int itemWidth = item->width();
+ int itemHeight = item->height();
+ int itemX = item->x();
+ int itemY = item->y();
+
+ QUrl url = item->property("source").toUrl();
+ QImage img(url.path());
+ const QRgb* bits = reinterpret_cast<const QRgb*>(img.constBits());
+ for (int x = 0; x < itemWidth; ++x) {
+ for (int y = 0; y < itemHeight; ++y) {
+ if (qAlpha(bits[y * itemWidth + x]) > 128) {
+ mask_[(itemY + y) * width + (x + itemX)] = i;
}
+ }
}
+ }
}
-void MaskedContainer::mousePressEvent(MouseEvent *mouse) {
+void MaskedContainer::mousePressEvent(MouseEvent* mouse) {
#if QT_4
qreal x = mouse->pos().x();
qreal y = mouse->pos().y();
@@ -126,7 +125,7 @@ void MaskedContainer::mousePressEvent(MouseEvent *mouse) {
}
}
-void MaskedContainer::mouseReleaseEvent(MouseEvent *mouse) {
+void MaskedContainer::mouseReleaseEvent(MouseEvent* mouse) {
#if QT_4
qreal x = mouse->pos().x();
qreal y = mouse->pos().y();
@@ -152,4 +151,3 @@ void MaskedContainer::mouseReleaseEvent(MouseEvent *mouse) {
MaskedContainer::~MaskedContainer() {
delete[] mask_;
}
-
diff --git a/src/components/qt_hmi/qml_plugins/hw_buttons/masked_container.h b/src/components/qt_hmi/qml_plugins/hw_buttons/masked_container.h
index 0048bdda2a..ae5303a693 100644
--- a/src/components/qt_hmi/qml_plugins/hw_buttons/masked_container.h
+++ b/src/components/qt_hmi/qml_plugins/hw_buttons/masked_container.h
@@ -41,11 +41,11 @@
#include "qt_version.h"
#if QT_4
-# include <QtDeclarative/QDeclarativeItem>
+#include <QtDeclarative/QDeclarativeItem>
typedef QDeclarativeItem Item;
typedef QGraphicsSceneMouseEvent MouseEvent;
#elif QT_5
-# include <QtQuick/QQuickItem>
+#include <QtQuick/QQuickItem>
typedef QQuickItem Item;
typedef QMouseEvent MouseEvent;
#endif
@@ -57,21 +57,21 @@ class MaskedContainer : public Item {
Q_DISABLE_COPY(MaskedContainer)
public:
- explicit MaskedContainer(Item *parent = 0);
+ explicit MaskedContainer(Item* parent = 0);
~MaskedContainer();
- signals:
- void pressed(AttributedMouseEvent *attr);
- void released(AttributedMouseEvent *attr);
+signals:
+ void pressed(AttributedMouseEvent* attr);
+ void released(AttributedMouseEvent* attr);
protected:
virtual void componentComplete();
- virtual void mousePressEvent(MouseEvent *event);
- virtual void mouseReleaseEvent(MouseEvent *event);
+ virtual void mousePressEvent(MouseEvent* event);
+ virtual void mouseReleaseEvent(MouseEvent* event);
private:
std::vector<Item*> images_;
- int *mask_;
+ int* mask_;
#if QT_4
int indexOfMask(qreal x, qreal y) const {
diff --git a/src/components/qt_hmi/qml_plugins/hw_buttons/qt_version.h b/src/components/qt_hmi/qml_plugins/hw_buttons/qt_version.h
index fb2751504d..a700a87919 100644
--- a/src/components/qt_hmi/qml_plugins/hw_buttons/qt_version.h
+++ b/src/components/qt_hmi/qml_plugins/hw_buttons/qt_version.h
@@ -37,11 +37,12 @@
#include <qglobal.h>
-#define QT_4 ((QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)) && \
- (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)))
+#define QT_4 \
+ ((QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)) && \
+ (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)))
-#define QT_5 ((QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) && \
- (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)))
+#define QT_5 \
+ ((QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) && \
+ (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)))
#endif // SRC_COMPONENTS_QT_HMI_QML_PLUGINS_HW_BUTTONS_QT_VERSION_H_
-
diff --git a/src/components/qt_hmi/qml_plugins/log4cxx/log4cxx_plugin.cc b/src/components/qt_hmi/qml_plugins/log4cxx/log4cxx_plugin.cc
index da863e2e26..8b7efe23d7 100644
--- a/src/components/qt_hmi/qml_plugins/log4cxx/log4cxx_plugin.cc
+++ b/src/components/qt_hmi/qml_plugins/log4cxx/log4cxx_plugin.cc
@@ -37,58 +37,58 @@
#include <log4cxx/log4cxx.h>
#include <log4cxx/propertyconfigurator.h>
-log4cxx::LoggerPtr logger_ = log4cxx::LoggerPtr(
- log4cxx::Logger::getLogger("Log4cxxPlugin"));
+log4cxx::LoggerPtr logger_ =
+ log4cxx::LoggerPtr(log4cxx::Logger::getLogger("Log4cxxPlugin"));
#if QT_4
-void smartLogger(QtMsgType type, const char *msg) {
+void smartLogger(QtMsgType type, const char* msg) {
log4cxx::spi::LocationInfo location("", "", -1);
switch (type) {
- case QtDebugMsg:
- (*logger_).debug(msg, location);
- break;
- case QtWarningMsg:
- (*logger_).warn(msg, location);
- break;
- case QtCriticalMsg:
- (*logger_).error(msg, location);
- break;
- case QtFatalMsg:
- (*logger_).fatal(msg, location);
- break;
- default:
- (*logger_).info(msg, location);
- break;
+ case QtDebugMsg:
+ (*logger_).debug(msg, location);
+ break;
+ case QtWarningMsg:
+ (*logger_).warn(msg, location);
+ break;
+ case QtCriticalMsg:
+ (*logger_).error(msg, location);
+ break;
+ case QtFatalMsg:
+ (*logger_).fatal(msg, location);
+ break;
+ default:
+ (*logger_).info(msg, location);
+ break;
}
}
#elif QT_5
-void smartLogger(QtMsgType type, const QMessageLogContext &context,
- const QString &msg) {
- log4cxx::spi::LocationInfo location(context.file,
- context.function ? context.function : "",
- context.line);
+void smartLogger(QtMsgType type,
+ const QMessageLogContext& context,
+ const QString& msg) {
+ log4cxx::spi::LocationInfo location(
+ context.file, context.function ? context.function : "", context.line);
switch (type) {
- case QtDebugMsg:
- (*logger_).debug(msg.toStdString(), location);
- break;
- case QtWarningMsg:
- (*logger_).warn(msg.toStdString(), location);
- break;
- case QtCriticalMsg:
- (*logger_).error(msg.toStdString(), location);
- break;
- case QtFatalMsg:
- (*logger_).fatal(msg.toStdString(), location);
- break;
- default:
- (*logger_).info(msg.toStdString(), location);
- break;
+ case QtDebugMsg:
+ (*logger_).debug(msg.toStdString(), location);
+ break;
+ case QtWarningMsg:
+ (*logger_).warn(msg.toStdString(), location);
+ break;
+ case QtCriticalMsg:
+ (*logger_).error(msg.toStdString(), location);
+ break;
+ case QtFatalMsg:
+ (*logger_).fatal(msg.toStdString(), location);
+ break;
+ default:
+ (*logger_).info(msg.toStdString(), location);
+ break;
}
}
#endif // QT_VERSION
-void Log4cxxPlugin::registerTypes(const char *uri) {
+void Log4cxxPlugin::registerTypes(const char* uri) {
log4cxx::PropertyConfigurator::configure("log4cxx.properties");
#if QT_4
diff --git a/src/components/qt_hmi/qml_plugins/log4cxx/log4cxx_plugin.h b/src/components/qt_hmi/qml_plugins/log4cxx/log4cxx_plugin.h
index fc82352f0c..e8d1ff3347 100644
--- a/src/components/qt_hmi/qml_plugins/log4cxx/log4cxx_plugin.h
+++ b/src/components/qt_hmi/qml_plugins/log4cxx/log4cxx_plugin.h
@@ -37,19 +37,21 @@
#include <qglobal.h>
-#define QT_4 ((QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)) && \
- (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)))
+#define QT_4 \
+ ((QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)) && \
+ (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)))
-#define QT_5 ((QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) && \
- (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)))
+#define QT_5 \
+ ((QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) && \
+ (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)))
#if QT_4
-# include <QtDeclarative/qdeclarative.h>
-# include <QtDeclarative/QDeclarativeExtensionPlugin>
+#include <QtDeclarative/qdeclarative.h>
+#include <QtDeclarative/QDeclarativeExtensionPlugin>
typedef QDeclarativeExtensionPlugin ExtensionPlugin;
#elif QT_5
-# include <QtQml/qqml.h>
-# include <QtQml/QQmlExtensionPlugin>
+#include <QtQml/qqml.h>
+#include <QtQml/QQmlExtensionPlugin>
typedef QQmlExtensionPlugin ExtensionPlugin;
#endif // QT_VERSION
@@ -58,7 +60,7 @@ class Logger : public QObject {
Q_DISABLE_COPY(Logger)
public:
- explicit Logger(QObject *parent = 0) : QObject(parent) {}
+ explicit Logger(QObject* parent = 0) : QObject(parent) {}
};
class Log4cxxPlugin : public ExtensionPlugin {
@@ -68,10 +70,9 @@ class Log4cxxPlugin : public ExtensionPlugin {
#endif // QT_5
public:
- void registerTypes(const char *uri);
+ void registerTypes(const char* uri);
};
QML_DECLARE_TYPE(Logger)
#endif // SRC_COMPONENTS_QT_HMI_QML_PLUGINS_LOG4CXX_LOG4CXX_PLUGIN_H_
-
diff --git a/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier.cc b/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier.cc
index f51db76b99..46b057dcca 100644
--- a/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier.cc
+++ b/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier.cc
@@ -41,10 +41,11 @@
void NamedPipeNotifier::run() {
int fd = ::open(name_.toLocal8Bit().constData(), O_RDONLY);
- if (-1 == fd) { // if open() fails
+ if (-1 == fd) { // if open() fails
if ((errno != ENOENT) // we can only manage lack of pipe
- || (-1 == ::mkfifo(name_.toLocal8Bit().constData(), 0666))
- || (-1 == (fd = ::open(name_.toLocal8Bit().constData(), O_RDONLY)))) {
+ ||
+ (-1 == ::mkfifo(name_.toLocal8Bit().constData(), 0666)) ||
+ (-1 == (fd = ::open(name_.toLocal8Bit().constData(), O_RDONLY)))) {
emit openFailed();
return;
}
@@ -52,7 +53,7 @@ void NamedPipeNotifier::run() {
::fd_set readfds;
FD_ZERO(&readfds);
FD_SET(fd, &readfds);
-// this select() is supposed to block till pipe is empty
+ // this select() is supposed to block till pipe is empty
if (::select(fd + 1, &readfds, 0, 0, 0) > 0) {
emit readyRead();
}
diff --git a/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier.h b/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier.h
index 993bb3cb31..cdca06466f 100644
--- a/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier.h
+++ b/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier.h
@@ -45,7 +45,9 @@ class NamedPipeNotifier : public QThread {
public:
explicit NamedPipeNotifier(QObject* parent = 0) : QThread(parent) {}
- const QString& name() const { return name_; }
+ const QString& name() const {
+ return name_;
+ }
void set_name(const QString& name) {
if (name_ != name) {
name_ = name;
@@ -56,7 +58,7 @@ class NamedPipeNotifier : public QThread {
protected:
virtual void run();
- signals:
+signals:
void nameChanged();
void readyRead();
void openFailed();
diff --git a/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier_plugin.cc b/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier_plugin.cc
index 8aa2b4cf76..dacb11ad93 100644
--- a/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier_plugin.cc
+++ b/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier_plugin.cc
@@ -35,16 +35,16 @@
#include "named_pipe_notifier_plugin.h"
#if QT_4
-# include <QtDeclarative/qdeclarative.h>
+#include <QtDeclarative/qdeclarative.h>
#elif QT_5
-# include <QtQml/qqml.h>
+#include <QtQml/qqml.h>
#endif // QT_VERSION
#include "named_pipe_notifier.h"
void NamedPipeNotifierPlugin::registerTypes(const char* uri) {
- // @uri com.ford.sdl.hmi.named_pipe_notifier
- qmlRegisterType<NamedPipeNotifier>(uri, 1, 0, "NamedPipeNotifier");
+ // @uri com.ford.sdl.hmi.named_pipe_notifier
+ qmlRegisterType<NamedPipeNotifier>(uri, 1, 0, "NamedPipeNotifier");
}
#if QT_4
diff --git a/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier_plugin.h b/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier_plugin.h
index 6c64d531ac..426df483a2 100644
--- a/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier_plugin.h
+++ b/src/components/qt_hmi/qml_plugins/named_pipe_notifier/named_pipe_notifier_plugin.h
@@ -38,10 +38,10 @@
#include "qt_version.h"
#if QT_4
-# include <QtDeclarative/QDeclarativeExtensionPlugin>
+#include <QtDeclarative/QDeclarativeExtensionPlugin>
typedef QDeclarativeExtensionPlugin ExtensionPlugin;
#elif QT_5
-# include <QtQml/QQmlExtensionPlugin>
+#include <QtQml/QQmlExtensionPlugin>
typedef QQmlExtensionPlugin ExtensionPlugin;
#endif // QT_5
diff --git a/src/components/qt_hmi/qml_plugins/named_pipe_notifier/qt_version.h b/src/components/qt_hmi/qml_plugins/named_pipe_notifier/qt_version.h
index 91533346c0..0e2456d732 100644
--- a/src/components/qt_hmi/qml_plugins/named_pipe_notifier/qt_version.h
+++ b/src/components/qt_hmi/qml_plugins/named_pipe_notifier/qt_version.h
@@ -37,11 +37,12 @@
#include <qglobal.h>
-#define QT_4 ((QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)) && \
- (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)))
+#define QT_4 \
+ ((QT_VERSION >= QT_VERSION_CHECK(4, 8, 0)) && \
+ (QT_VERSION < QT_VERSION_CHECK(5, 0, 0)))
-#define QT_5 ((QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) && \
- (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)))
+#define QT_5 \
+ ((QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) && \
+ (QT_VERSION < QT_VERSION_CHECK(6, 0, 0)))
#endif // SRC_COMPONENTS_QT_HMI_QML_PLUGINS_NAMED_PIPE_NOTIFIER_QT_VERSION_H_
-
diff --git a/src/components/resumption/include/resumption/last_state.h b/src/components/resumption/include/resumption/last_state.h
index 5183f1a1da..a331d9291c 100644
--- a/src/components/resumption/include/resumption/last_state.h
+++ b/src/components/resumption/include/resumption/last_state.h
@@ -36,14 +36,24 @@
#include <string>
#include "utils/macro.h"
-#include "utils/singleton.h"
#include "json/json.h"
namespace resumption {
-class LastState : public utils::Singleton<LastState> {
+class LastState {
public:
/**
+ * @brief Constructor
+ */
+ LastState(const std::string& app_storage_folder,
+ const std::string& app_info_storage);
+
+ /**
+ * @brief Destructor
+ */
+ ~LastState();
+
+ /**
* @brief Saving dictionary to filesystem
*/
void SaveToFileSystem();
@@ -54,25 +64,15 @@ class LastState : public utils::Singleton<LastState> {
Json::Value dictionary;
private:
+ DISALLOW_COPY_AND_ASSIGN(LastState);
/**
* @brief Load dictionary from filesystem
*/
void LoadFromFileSystem();
- /**
- * @brief Private default constructor
- */
- LastState();
-
- /**
- * @brief Private destructor
- */
- ~LastState();
-
- DISALLOW_COPY_AND_ASSIGN(LastState);
-
- FRIEND_BASE_SINGLETON_CLASS(LastState);
+ std::string app_storage_folder_;
+ std::string app_info_storage_;
};
} // namespace resumption
diff --git a/src/components/resumption/src/last_state.cc b/src/components/resumption/src/last_state.cc
index 7d609fe84f..c1b8534bfc 100644
--- a/src/components/resumption/src/last_state.cc
+++ b/src/components/resumption/src/last_state.cc
@@ -31,52 +31,47 @@
*/
#include "resumption/last_state.h"
-#include "config_profile/profile.h"
#include "utils/file_system.h"
#include "utils/logger.h"
namespace resumption {
-CREATE_LOGGERPTR_GLOBAL(logger_, "LastState");
+CREATE_LOGGERPTR_GLOBAL(logger_, "Resumption")
-void LastState::SaveToFileSystem() {
+LastState::LastState(const std::string& app_storage_folder,
+ const std::string& app_info_storage)
+ : app_storage_folder_(app_storage_folder)
+ , app_info_storage_(app_info_storage) {
+ LoadFromFileSystem();
LOG4CXX_AUTO_TRACE(logger_);
- const std::string file =
- profile::Profile::instance()->app_info_storage();
- const std::string& str = dictionary.toStyledString();
- const std::vector<uint8_t> char_vector_pdata(
- str.begin(), str.end());
-
- DCHECK(file_system::CreateDirectoryRecursively(
- profile::Profile::instance()->app_storage_folder()));
+}
- LOG4CXX_INFO(logger_, "LastState::SaveToFileSystem " << file
- << str);
+LastState::~LastState() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ SaveToFileSystem();
+}
- DCHECK(file_system::Write(file, char_vector_pdata));
+void LastState::SaveToFileSystem() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ const std::string& str = dictionary.toStyledString();
+ const std::vector<uint8_t> char_vector_pdata(str.begin(), str.end());
+ DCHECK(file_system::CreateDirectoryRecursively(app_storage_folder_));
+ LOG4CXX_INFO(logger_,
+ "LastState::SaveToFileSystem " << app_info_storage_ << str);
+ DCHECK(file_system::Write(app_info_storage_, char_vector_pdata));
}
void LastState::LoadFromFileSystem() {
- const std::string file =
- profile::Profile::instance()->app_info_storage();
std::string buffer;
- bool result = file_system::ReadFile(file, buffer);
+ bool result = file_system::ReadFile(app_info_storage_, buffer);
Json::Reader m_reader;
if (result && m_reader.parse(buffer, dictionary)) {
- LOG4CXX_INFO(logger_, "Valid last state was found."
- << dictionary.toStyledString());
+ LOG4CXX_INFO(logger_,
+ "Valid last state was found." << dictionary.toStyledString());
return;
}
LOG4CXX_WARN(logger_, "No valid last state was found.");
}
-LastState::LastState() {
- LoadFromFileSystem();
-}
-
-LastState::~LastState() {
- SaveToFileSystem();
-}
-
-}
+} // resumption
diff --git a/src/components/resumption/test/CMakeLists.txt b/src/components/resumption/test/CMakeLists.txt
index c7b7f52db7..6fa1c07381 100644
--- a/src/components/resumption/test/CMakeLists.txt
+++ b/src/components/resumption/test/CMakeLists.txt
@@ -47,6 +47,7 @@ set(LIBRARIES
Utils
Resumption
jsoncpp
+ ConfigProfile
)
set(SOURCES
diff --git a/src/components/resumption/test/last_state_test.cc b/src/components/resumption/test/last_state_test.cc
index d2b7f10ce4..78acc68c90 100644
--- a/src/components/resumption/test/last_state_test.cc
+++ b/src/components/resumption/test/last_state_test.cc
@@ -30,66 +30,86 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
+#include <string>
+
#include "gtest/gtest.h"
+
#include "resumption/last_state.h"
-#include "config_profile/profile.h"
#include "utils/file_system.h"
namespace test {
namespace components {
-namespace resumption {
+namespace resumption_test {
using namespace ::resumption;
using namespace ::Json;
+const std::string kAppStorageFolder = "app_storage_folder";
+const std::string kAppInfoStorageFile = "app_info_storage";
class LastStateTest : public ::testing::Test {
- public:
- virtual void SetUp() {
- ASSERT_TRUE(::file_system::CreateFile("./app_info.dat"));
- ::profile::Profile::instance()->UpdateValues();
+ protected:
+ LastStateTest()
+ : empty_dictionary_("null\n")
+ , app_info_dat_file_("app_info.dat")
+ , last_state_(kAppStorageFolder, kAppInfoStorageFile) {}
+
+ static void SetUpTestCase() {
+ file_system::DeleteFile(kAppInfoStorageFile);
+ file_system::RemoveDirectory(kAppStorageFolder);
}
- virtual void TearDown() {
- EXPECT_TRUE(::file_system::DeleteFile("./app_info.dat"));
+ void SetUp() OVERRIDE {
+ ASSERT_TRUE(file_system::CreateFile(app_info_dat_file_));
}
+
+ void TearDown() OVERRIDE {
+ EXPECT_TRUE(file_system::DeleteFile((app_info_dat_file_)));
+ }
+
+ const std::string empty_dictionary_;
+ const std::string app_info_dat_file_;
+
+ resumption::LastState last_state_;
};
TEST_F(LastStateTest, Basic) {
- Value& dictionary = LastState::instance()->dictionary;
- EXPECT_EQ("null\n", dictionary.toStyledString());
+ const Value& dictionary = last_state_.dictionary;
+ EXPECT_EQ(empty_dictionary_, dictionary.toStyledString());
}
TEST_F(LastStateTest, SetGetData) {
{
- Value& dictionary = LastState::instance()->dictionary;
- Value bluetooth_info = dictionary["TransportManager"]["BluetoothAdapter"];
- EXPECT_EQ("null\n", bluetooth_info.toStyledString());
+ const Value& dictionary = last_state_.dictionary;
+ const Value& bluetooth_info =
+ dictionary["TransportManager"]["BluetoothAdapter"];
+ EXPECT_EQ(empty_dictionary_, bluetooth_info.toStyledString());
- Value tcp_adapter_info =
+ const Value& tcp_adapter_info =
dictionary["TransportManager"]["TcpAdapter"]["devices"];
- EXPECT_EQ("null\n", tcp_adapter_info.toStyledString());
+ EXPECT_EQ(empty_dictionary_, tcp_adapter_info.toStyledString());
- Value resumption_time = dictionary["resumption"]["last_ign_off_time"];
+ const Value& resumption_time =
+ dictionary["resumption"]["last_ign_off_time"];
EXPECT_EQ("null\n", resumption_time.toStyledString());
- Value resumption_list = dictionary["resumption"]["resume_app_list"];
+ const Value& resumption_list = dictionary["resumption"]["resume_app_list"];
EXPECT_EQ("null\n", resumption_list.toStyledString());
Value test_value;
test_value["name"] = "test_device";
- LastState::instance()
- ->dictionary["TransportManager"]["TcpAdapter"]["devices"] = test_value;
- LastState::instance()
- ->dictionary["TransportManager"]["BluetoothAdapter"]["devices"] =
+ last_state_.dictionary["TransportManager"]["TcpAdapter"]["devices"] =
+ test_value;
+ last_state_.dictionary["TransportManager"]["BluetoothAdapter"]["devices"] =
"bluetooth_device";
- LastState::instance()->SaveToFileSystem();
+ last_state_.SaveToFileSystem();
}
- Value& dictionary = LastState::instance()->dictionary;
+ const Value& dictionary = last_state_.dictionary;
- Value bluetooth_info = dictionary["TransportManager"]["BluetoothAdapter"];
- Value tcp_adapter_info = dictionary["TransportManager"]["TcpAdapter"];
+ const Value& bluetooth_info =
+ dictionary["TransportManager"]["BluetoothAdapter"];
+ const Value& tcp_adapter_info = dictionary["TransportManager"]["TcpAdapter"];
EXPECT_EQ("{\n \"devices\" : \"bluetooth_device\"\n}\n",
bluetooth_info.toStyledString());
EXPECT_EQ(
@@ -97,6 +117,6 @@ TEST_F(LastStateTest, SetGetData) {
tcp_adapter_info.toStyledString());
}
-} // namespace resumption
+} // namespace resumption_test
} // namespace components
} // namespace test
diff --git a/src/components/rpc_base/include/rpc_base/gtest_support.h b/src/components/rpc_base/include/rpc_base/gtest_support.h
index daea5d3884..04ad1219b5 100644
--- a/src/components/rpc_base/include/rpc_base/gtest_support.h
+++ b/src/components/rpc_base/include/rpc_base/gtest_support.h
@@ -39,9 +39,9 @@
// A predicate-formatter for asserting that intergen generated
// object is valid
-template<typename T>
+template <typename T>
::testing::AssertionResult AssertRpcObjValid(const char* obj_expr,
- const T& obj) {
+ const T& obj) {
if (obj.is_valid())
return ::testing::AssertionSuccess();
@@ -49,8 +49,8 @@ template<typename T>
obj.ReportErrors(&report);
return ::testing::AssertionFailure()
- << obj_expr << " failed validation. Violations are:\n"
- << rpc::PrettyFormat(report);
+ << obj_expr << " failed validation. Violations are:\n"
+ << rpc::PrettyFormat(report);
}
#define ASSERT_RPCTYPE_VALID(object) \
diff --git a/src/components/rpc_base/include/rpc_base/rpc_base.h b/src/components/rpc_base/include/rpc_base/rpc_base.h
index 019f7edc0e..883c2ec4bf 100644
--- a/src/components/rpc_base/include/rpc_base/rpc_base.h
+++ b/src/components/rpc_base/include/rpc_base/rpc_base.h
@@ -52,47 +52,58 @@ class ValidationReport;
namespace policy_table_interface_base {
- enum PolicyTableType {
- INVALID_PT_TYPE = -1,
- PT_PRELOADED,
- PT_UPDATE,
- PT_SNAPSHOT
- };
- const std::string ommited_validation_info = "should be ommited in ";
- const std::string required_validation_info = "is required in ";
-
- std::string PolicyTableTypeToString(const PolicyTableType pt_type);
-
+enum PolicyTableType {
+ INVALID_PT_TYPE = -1,
+ PT_PRELOADED,
+ PT_UPDATE,
+ PT_SNAPSHOT
+};
+const std::string ommited_validation_info = "should be ommited in ";
+const std::string required_validation_info = "is required in ";
+std::string PolicyTableTypeToString(const PolicyTableType pt_type);
}
-template<typename T> class Range;
+template <typename T>
+class Range;
class PrimitiveType;
class CompositeType;
class Boolean;
-template<typename T, T minval, T maxval> class Integer;
-template<int64_t minnum, int64_t maxnum,
- int64_t minden = 1, int64_t maxden = 1> class Float;
-template<size_t minlen, size_t maxlen> class String;
-template<typename T> class Enum;
-template<typename T, size_t minsize, size_t maxsize> class Array;
-template<typename T, size_t minsize, size_t maxsize> class Map;
-template<typename T> class Nullable;
-template<typename T> class Optional;
-template<typename T> class Stringifyable;
-
-template<typename T>
+template <typename T, T minval, T maxval>
+class Integer;
+template <int64_t minnum,
+ int64_t maxnum,
+ int64_t minden = 1,
+ int64_t maxden = 1>
+class Float;
+template <size_t minlen, size_t maxlen>
+class String;
+template <typename T>
+class Enum;
+template <typename T, size_t minsize, size_t maxsize>
+class Array;
+template <typename T, size_t minsize, size_t maxsize>
+class Map;
+template <typename T>
+class Nullable;
+template <typename T>
+class Optional;
+template <typename T>
+class Stringifyable;
+
+template <typename T>
class Range {
- public:
- // Methods
- Range(const T min, const T max);
- T min() const;
- T max() const;
- template<typename U>
- bool Includes(U val) const;
- private:
- T min_;
- T max_;
+ public:
+ // Methods
+ Range(const T min, const T max);
+ T min() const;
+ T max() const;
+ template <typename U>
+ bool Includes(U val) const;
+
+ private:
+ T min_;
+ T max_;
};
/*
@@ -100,316 +111,326 @@ class Range {
* tell whether descendant object was initialized
*/
class PrimitiveType {
- public:
- bool is_initialized() const;
- bool is_valid() const;
- void ReportErrors(ValidationReport* report) const;
- policy_table_interface_base::PolicyTableType GetPolicyTableType() const;
- virtual void SetPolicyTableType(policy_table_interface_base::PolicyTableType pt_type);
-
- protected:
- enum ValueState {
- kUninitialized,
- kInvalid,
- kValid
- };
- explicit PrimitiveType(ValueState value_state);
- static ValueState InitHelper(bool is_next);
- static ValueState InitHelper(const Json::Value* value,
- bool (Json::Value::*type_check)() const);
-
- protected:
- ValueState value_state_;
- policy_table_interface_base::PolicyTableType policy_table_type_;
+ public:
+ bool is_initialized() const;
+ bool is_valid() const;
+ void ReportErrors(ValidationReport* report) const;
+ policy_table_interface_base::PolicyTableType GetPolicyTableType() const;
+ virtual void SetPolicyTableType(
+ policy_table_interface_base::PolicyTableType pt_type);
+
+ protected:
+ enum ValueState { kUninitialized, kInvalid, kValid };
+ explicit PrimitiveType(ValueState value_state);
+ static ValueState InitHelper(bool is_next);
+ static ValueState InitHelper(const Json::Value* value,
+ bool (Json::Value::*type_check)() const);
+
+ protected:
+ ValueState value_state_;
+ policy_table_interface_base::PolicyTableType policy_table_type_;
};
/*
* Base class for all composite types (arrays and all user-defined types)
*/
class CompositeType {
- public:
- void mark_initialized();
- void ReportErrors(ValidationReport* report) const;
- policy_table_interface_base::PolicyTableType GetPolicyTableType() const;
- virtual void SetPolicyTableType(policy_table_interface_base::PolicyTableType pt_type);
-
- protected:
- enum InitializationState {
- kUninitialized,
- kInitialized,
- kInvalidInitialized
- };
- explicit CompositeType(InitializationState init_state);
- virtual ~CompositeType(){}
- static InitializationState InitHelper(bool is_next);
- static InitializationState InitHelper(const Json::Value* value,
- bool (Json::Value::*type_check)() const);
- protected:
- mutable InitializationState initialization_state__;
- policy_table_interface_base::PolicyTableType policy_table_type_;
-
+ public:
+ void mark_initialized();
+ void ReportErrors(ValidationReport* report) const;
+ policy_table_interface_base::PolicyTableType GetPolicyTableType() const;
+ virtual void SetPolicyTableType(
+ policy_table_interface_base::PolicyTableType pt_type);
+
+ protected:
+ enum InitializationState {
+ kUninitialized,
+ kInitialized,
+ kInvalidInitialized
+ };
+ explicit CompositeType(InitializationState init_state);
+ virtual ~CompositeType() {}
+ static InitializationState InitHelper(bool is_next);
+ static InitializationState InitHelper(const Json::Value* value,
+ bool (Json::Value::*type_check)()
+ const);
+
+ protected:
+ mutable InitializationState initialization_state__;
+ policy_table_interface_base::PolicyTableType policy_table_type_;
};
/*
* Class that holds primitive boolean value. It is always valid.
*/
class Boolean : public PrimitiveType {
- public:
- // Types
- typedef bool ValueType;
- public:
- // Methods
- Boolean();
- explicit Boolean(bool value);
- explicit Boolean(const Json::Value* value);
- explicit Boolean(dbus::MessageReader* reader);
- Boolean(const Json::Value* value, bool def_value);
- Boolean& operator=(bool new_val);
- operator bool() const;
- Json::Value ToJsonValue() const;
- void ToDbusWriter(dbus::MessageWriter* writer) const;
-
- private:
- // Fields
- ValueType value_;
+ public:
+ // Types
+ typedef bool ValueType;
+
+ public:
+ // Methods
+ Boolean();
+ explicit Boolean(bool value);
+ explicit Boolean(const Json::Value* value);
+ explicit Boolean(dbus::MessageReader* reader);
+ Boolean(const Json::Value* value, bool def_value);
+ Boolean& operator=(bool new_val);
+ operator bool() const;
+ Json::Value ToJsonValue() const;
+ void ToDbusWriter(dbus::MessageWriter* writer) const;
+
+ private:
+ // Fields
+ ValueType value_;
};
-template<typename T, T minval, T maxval>
+template <typename T, T minval, T maxval>
class Integer : public PrimitiveType {
- public:
- // Types
- typedef T IntType;
- public:
- // Methods
- Integer();
- explicit Integer(IntType value);
- Integer(const Integer& value);
- explicit Integer(const Json::Value* value);
- explicit Integer(dbus::MessageReader* reader);
- Integer(const Json::Value* value, IntType def_value);
- Integer& operator=(IntType new_val);
- Integer& operator=(const Integer& new_val);
- Integer& operator++();
- Integer& operator+=(int value);
- operator IntType() const;
- Json::Value ToJsonValue() const;
- void ToDbusWriter(dbus::MessageWriter* writer) const;
-
- private:
- IntType value_;
- static const Range<T> range_;
+ public:
+ // Types
+ typedef T IntType;
+
+ public:
+ // Methods
+ Integer();
+ explicit Integer(IntType value);
+ Integer(const Integer& value);
+ explicit Integer(const Json::Value* value);
+ explicit Integer(dbus::MessageReader* reader);
+ Integer(const Json::Value* value, IntType def_value);
+ Integer& operator=(IntType new_val);
+ Integer& operator=(const Integer& new_val);
+ Integer& operator++();
+ Integer& operator+=(int value);
+ operator IntType() const;
+ Json::Value ToJsonValue() const;
+ void ToDbusWriter(dbus::MessageWriter* writer) const;
+
+ private:
+ IntType value_;
+ static const Range<T> range_;
};
-template<int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
+template <int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
class Float : public PrimitiveType {
- public:
- // Methods
- Float();
- explicit Float(double value);
- explicit Float(const Json::Value* value);
- explicit Float(dbus::MessageReader* reader);
- Float(const Json::Value* value, double def_value);
- Float& operator=(double new_val);
- operator double() const;
- Json::Value ToJsonValue() const;
- void ToDbusWriter(dbus::MessageWriter* writer) const;
-
- private:
- double value_;
- static const Range<double> range_;
+ public:
+ // Methods
+ Float();
+ explicit Float(double value);
+ explicit Float(const Json::Value* value);
+ explicit Float(dbus::MessageReader* reader);
+ Float(const Json::Value* value, double def_value);
+ Float& operator=(double new_val);
+ operator double() const;
+ Json::Value ToJsonValue() const;
+ void ToDbusWriter(dbus::MessageWriter* writer) const;
+
+ private:
+ double value_;
+ static const Range<double> range_;
};
-template<size_t minlen, size_t maxlen>
+template <size_t minlen, size_t maxlen>
class String : public PrimitiveType {
- public:
- // Methods
- String();
- explicit String(const std::string& value);
- explicit String(const char* value);
- explicit String(const Json::Value* value);
- explicit String(dbus::MessageReader* reader);
- String(const Json::Value* value, const std::string& def_value);
- bool operator<(String new_val);
- String& operator=(const std::string& new_val);
- String& operator=(const String& new_val);
- bool operator==(const String& rhs);
- operator const std::string& () const;
- Json::Value ToJsonValue() const;
- void ToDbusWriter(dbus::MessageWriter* writer) const;
-
- private:
- std::string value_;
- static const Range<size_t> length_range_;
+ public:
+ // Methods
+ String();
+ explicit String(const std::string& value);
+ explicit String(const char* value);
+ explicit String(const Json::Value* value);
+ explicit String(dbus::MessageReader* reader);
+ String(const Json::Value* value, const std::string& def_value);
+ bool operator<(const String& new_val) const;
+ String& operator=(const std::string& new_val);
+ String& operator=(const String& new_val);
+ bool operator==(const String& rhs) const;
+ operator const std::string&() const;
+ Json::Value ToJsonValue() const;
+ void ToDbusWriter(dbus::MessageWriter* writer) const;
+
+ private:
+ std::string value_;
+ static const Range<size_t> length_range_;
};
-template<typename T>
+template <typename T>
class Enum : public PrimitiveType {
- public:
- // Types
- typedef T EnumType;
- public:
- // Methods
- Enum();
- explicit Enum(EnumType value);
- explicit Enum(const Json::Value* value);
- explicit Enum(dbus::MessageReader* reader);
- Enum(const Json::Value* value, EnumType def_value);
- Enum& operator=(EnumType new_val);
- operator EnumType() const;
- Json::Value ToJsonValue() const;
- void ToDbusWriter(dbus::MessageWriter* writer) const;
-
- private:
- // Fields
- EnumType value_;
+ public:
+ // Types
+ typedef T EnumType;
+
+ public:
+ // Methods
+ Enum();
+ explicit Enum(EnumType value);
+ explicit Enum(const Json::Value* value);
+ explicit Enum(dbus::MessageReader* reader);
+ Enum(const Json::Value* value, EnumType def_value);
+ Enum& operator=(const EnumType& new_val);
+ operator EnumType() const;
+ Json::Value ToJsonValue() const;
+ void ToDbusWriter(dbus::MessageWriter* writer) const;
+
+ private:
+ // Fields
+ EnumType value_;
};
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
class Array : public std::vector<T>, public CompositeType {
- public:
- // Types
- typedef std::vector<T> ArrayType;
- public:
- // Methods
- Array();
- // Need const and non-const versions to beat all-type accepting constructor
- explicit Array(Json::Value* value);
- explicit Array(const Json::Value* value);
- explicit Array(dbus::MessageReader* reader);
- template<typename U>
- explicit Array(const U& value);
- template<typename U>
- Array& operator=(const U& that);
- using ArrayType::push_back;
- template<typename U>
- void push_back(const U& value);
- Json::Value ToJsonValue() const;
- void ToDbusWriter(dbus::MessageWriter* writer) const;
-
- bool is_valid() const;
- bool is_initialized() const;
- void ReportErrors(ValidationReport* report) const;
- virtual void SetPolicyTableType(policy_table_interface_base::PolicyTableType pt_type);
+ public:
+ // Types
+ typedef std::vector<T> ArrayType;
+
+ public:
+ // Methods
+ Array();
+ // Need const and non-const versions to beat all-type accepting constructor
+ explicit Array(Json::Value* value);
+ explicit Array(const Json::Value* value);
+ explicit Array(dbus::MessageReader* reader);
+ template <typename U>
+ explicit Array(const U& value);
+ template <typename U>
+ Array& operator=(const U& that);
+ using ArrayType::push_back;
+ template <typename U>
+ void push_back(const U& value);
+ Json::Value ToJsonValue() const;
+ void ToDbusWriter(dbus::MessageWriter* writer) const;
+
+ bool is_valid() const;
+ bool is_initialized() const;
+ void ReportErrors(ValidationReport* report) const;
+ virtual void SetPolicyTableType(
+ policy_table_interface_base::PolicyTableType pt_type);
};
-template<typename T, size_t minsize, size_t maxsize>
-class Map : public std::map<std::string, T>, public CompositeType {
- public:
- // Types
- typedef Map<T, minsize, maxsize> Frankenbase;
- typedef std::map<std::string, T> MapType;
- public:
- // Methods
- Map();
- // Need const and non-const versions to beat all-type accepting constructor
- explicit Map(Json::Value* value);
- explicit Map(const Json::Value* value);
- explicit Map(dbus::MessageReader* reader);
- template<typename U>
- explicit Map(const U& value);
- template<typename U>
- Map& operator=(const U& that);
- using MapType::insert;
- template<typename U>
- void insert(const std::pair<std::string, U>& value);
- Json::Value ToJsonValue() const;
- void ToDbusWriter(dbus::MessageWriter* writer) const;
-
- bool is_valid() const;
- bool is_initialized() const;
- void ReportErrors(ValidationReport* report) const;
- virtual void SetPolicyTableType(policy_table_interface_base::PolicyTableType pt_type);
+template <typename T, size_t minsize, size_t maxsize>
+class Map : public std::map<std::string, T>, public CompositeType {
+ public:
+ // Types
+ typedef Map<T, minsize, maxsize> Frankenbase;
+ typedef std::map<std::string, T> MapType;
+
+ public:
+ // Methods
+ Map();
+ // Need const and non-const versions to beat all-type accepting constructor
+ explicit Map(Json::Value* value);
+ explicit Map(const Json::Value* value);
+ explicit Map(dbus::MessageReader* reader);
+ template <typename U>
+ explicit Map(const U& value);
+ template <typename U>
+ Map& operator=(const U& that);
+ using MapType::insert;
+ template <typename U>
+ void insert(const std::pair<std::string, U>& value);
+ Json::Value ToJsonValue() const;
+ void ToDbusWriter(dbus::MessageWriter* writer) const;
+
+ bool is_valid() const;
+ bool is_initialized() const;
+ void ReportErrors(ValidationReport* report) const;
+ virtual void SetPolicyTableType(
+ policy_table_interface_base::PolicyTableType pt_type);
};
-template<typename T>
+template <typename T>
class Nullable : public T {
- public:
- // Methods
- Nullable();
- explicit Nullable(dbus::MessageReader* reader);
- // Need const and non-const versions to beat all-type accepting constructor
- explicit Nullable(Json::Value* value);
- explicit Nullable(const Json::Value* value);
- template<typename U>
- explicit Nullable(const U& value);
- template<typename U>
- Nullable(const Json::Value* value, const U& def_value);
- template<typename U>
- Nullable& operator=(const U& new_val);
- Json::Value ToJsonValue() const;
-
- bool is_valid() const;
- bool is_initialized() const;
- bool is_null() const;
- void set_to_null();
- void ReportErrors(ValidationReport* report) const;
- private:
- bool marked_null_;
+ public:
+ // Methods
+ Nullable();
+ explicit Nullable(dbus::MessageReader* reader);
+ // Need const and non-const versions to beat all-type accepting constructor
+ explicit Nullable(Json::Value* value);
+ explicit Nullable(const Json::Value* value);
+ template <typename U>
+ explicit Nullable(const U& value);
+ template <typename U>
+ Nullable(const Json::Value* value, const U& def_value);
+ template <typename U>
+ Nullable& operator=(const U& new_val);
+ Json::Value ToJsonValue() const;
+
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool is_null() const;
+ void set_to_null();
+ void ReportErrors(ValidationReport* report) const;
+
+ private:
+ bool marked_null_;
};
-template<typename T>
+template <typename T>
class Stringifyable : public T {
- public:
- // Methods
- Stringifyable();
- explicit Stringifyable(dbus::MessageReader* reader);
- // Need const and non-const versions to beat all-type accepting constructor
- explicit Stringifyable(Json::Value* value);
- explicit Stringifyable(const Json::Value* value);
- template<typename U>
- explicit Stringifyable(const U& value);
- template<typename U>
- Stringifyable(const Json::Value* value, const U& def_value);
- template<typename U>
- Stringifyable& operator=(const U& new_val);
- Json::Value ToJsonValue() const;
-
- bool is_valid() const;
- bool is_initialized() const;
- bool is_string() const;
- std::string get_string() const;
- void set_to_string(const std::string& input);
- void ReportErrors(ValidationReport* report) const;
- private:
- std::string predefined_string_;
+ public:
+ // Methods
+ Stringifyable();
+ explicit Stringifyable(dbus::MessageReader* reader);
+ // Need const and non-const versions to beat all-type accepting constructor
+ explicit Stringifyable(Json::Value* value);
+ explicit Stringifyable(const Json::Value* value);
+ template <typename U>
+ explicit Stringifyable(const U& value);
+ template <typename U>
+ Stringifyable(const Json::Value* value, const U& def_value);
+ template <typename U>
+ Stringifyable& operator=(const U& new_val);
+ Json::Value ToJsonValue() const;
+
+ bool is_valid() const;
+ bool is_initialized() const;
+ bool is_string() const;
+ std::string get_string() const;
+ void set_to_string(const std::string& input);
+ void ReportErrors(ValidationReport* report) const;
+
+ private:
+ std::string predefined_string_;
};
-template<typename T>
+template <typename T>
class Optional {
- public:
- // Methods
- Optional();
- explicit Optional(dbus::MessageReader* reader);
- template<typename U>
- explicit Optional(const U& value);
- template<typename U>
- Optional(const Json::Value* value, const U& def_value);
- Json::Value ToJsonValue() const;
-
- void ToDbusWriter(dbus::MessageWriter* writer) const;
-
- // Pointer semantics
- T& operator*();
- const T& operator*() const;
- T* operator->();
- const T* operator->() const;
-
- void assign_if_valid(const Optional<T>& value);
- // For pointer-like 'if (optional_value)' tests
- // Better than operator bool because bool can be implicitly
- // casted to integral types
- operator const void* () const;
-
- bool is_valid() const;
- bool is_initialized() const;
- void ReportErrors(ValidationReport* report) const;
- policy_table_interface_base::PolicyTableType GetPolicyTableType() const;
- virtual void SetPolicyTableType(policy_table_interface_base::PolicyTableType pt_type);
-
- protected:
- policy_table_interface_base::PolicyTableType policy_table_type_;
- private:
- T value_;
+ public:
+ // Methods
+ Optional();
+ explicit Optional(dbus::MessageReader* reader);
+ template <typename U>
+ explicit Optional(const U& value);
+ template <typename U>
+ Optional(const Json::Value* value, const U& def_value);
+ Json::Value ToJsonValue() const;
+
+ void ToDbusWriter(dbus::MessageWriter* writer) const;
+
+ // Pointer semantics
+ T& operator*();
+ const T& operator*() const;
+ T* operator->();
+ const T* operator->() const;
+
+ void assign_if_valid(const Optional<T>& value);
+ // For pointer-like 'if (optional_value)' tests
+ // Better than operator bool because bool can be implicitly
+ // casted to integral types
+ operator const void*() const;
+
+ bool is_valid() const;
+ bool is_initialized() const;
+ void ReportErrors(ValidationReport* report) const;
+ policy_table_interface_base::PolicyTableType GetPolicyTableType() const;
+ virtual void SetPolicyTableType(
+ policy_table_interface_base::PolicyTableType pt_type);
+
+ protected:
+ policy_table_interface_base::PolicyTableType policy_table_type_;
+
+ private:
+ T value_;
};
} // namespace rpc
diff --git a/src/components/rpc_base/include/rpc_base/rpc_base_dbus_inl.h b/src/components/rpc_base/include/rpc_base/rpc_base_dbus_inl.h
index 5f9c45a060..2b968dd034 100644
--- a/src/components/rpc_base/include/rpc_base/rpc_base_dbus_inl.h
+++ b/src/components/rpc_base/include/rpc_base/rpc_base_dbus_inl.h
@@ -45,28 +45,32 @@ inline PrimitiveType::ValueState PrimitiveType::InitHelper(bool is_next) {
}
// static
-inline CompositeType::InitializationState CompositeType::InitHelper(bool is_next) {
+inline CompositeType::InitializationState CompositeType::InitHelper(
+ bool is_next) {
return is_next ? kInitialized : kUninitialized;
}
namespace impl {
-
// Helper functions to statically map int types to appropriate
// MessageReader functions
// Non-specialized versions doesn't have implementation
// Tells if next element of reader is of type T
-template<typename T> inline bool NextIs(const dbus::MessageReader& reader);
+template <typename T>
+inline bool NextIs(const dbus::MessageReader& reader);
// Takes next element of type T from reader
-template<typename T> inline T Take(dbus::MessageReader* reader);
+template <typename T>
+inline T Take(dbus::MessageReader* reader);
-template<> inline bool NextIs<int8_t>(const dbus::MessageReader& reader) {
+template <>
+inline bool NextIs<int8_t>(const dbus::MessageReader& reader) {
return reader.NextIsByte();
}
-template<> inline int8_t Take<int8_t>(dbus::MessageReader* reader) {
+template <>
+inline int8_t Take<int8_t>(dbus::MessageReader* reader) {
return static_cast<int8_t>(reader->TakeByte());
}
@@ -74,11 +78,13 @@ inline void Put(int8_t val, dbus::MessageWriter* writer) {
writer->PutByte(static_cast<uint8_t>(val));
}
-template<> inline bool NextIs<uint8_t>(const dbus::MessageReader& reader) {
+template <>
+inline bool NextIs<uint8_t>(const dbus::MessageReader& reader) {
return reader.NextIsByte();
}
-template<> inline uint8_t Take<uint8_t>(dbus::MessageReader* reader) {
+template <>
+inline uint8_t Take<uint8_t>(dbus::MessageReader* reader) {
return reader->TakeByte();
}
@@ -86,11 +92,13 @@ inline void Put(uint8_t val, dbus::MessageWriter* writer) {
writer->PutByte(val);
}
-template<> inline bool NextIs<int16_t>(const dbus::MessageReader& reader) {
+template <>
+inline bool NextIs<int16_t>(const dbus::MessageReader& reader) {
return reader.NextIsInt16();
}
-template<> inline int16_t Take<int16_t>(dbus::MessageReader* reader) {
+template <>
+inline int16_t Take<int16_t>(dbus::MessageReader* reader) {
return reader->TakeInt16();
}
@@ -98,11 +106,13 @@ inline void Put(int16_t val, dbus::MessageWriter* writer) {
writer->PutInt16(val);
}
-template<> inline bool NextIs<uint16_t>(const dbus::MessageReader& reader) {
+template <>
+inline bool NextIs<uint16_t>(const dbus::MessageReader& reader) {
return reader.NextIsUint16();
}
-template<> inline uint16_t Take<uint16_t>(dbus::MessageReader* reader) {
+template <>
+inline uint16_t Take<uint16_t>(dbus::MessageReader* reader) {
return reader->TakeUint16();
}
@@ -110,11 +120,13 @@ inline void Put(uint16_t val, dbus::MessageWriter* writer) {
writer->PutUint16(val);
}
-template<> inline bool NextIs<int32_t>(const dbus::MessageReader& reader) {
+template <>
+inline bool NextIs<int32_t>(const dbus::MessageReader& reader) {
return reader.NextIsInt32();
}
-template<> inline int32_t Take<int32_t>(dbus::MessageReader* reader) {
+template <>
+inline int32_t Take<int32_t>(dbus::MessageReader* reader) {
return reader->TakeInt32();
}
@@ -122,11 +134,13 @@ inline void Put(int32_t val, dbus::MessageWriter* writer) {
writer->PutInt32(val);
}
-template<> inline bool NextIs<uint32_t>(const dbus::MessageReader& reader) {
+template <>
+inline bool NextIs<uint32_t>(const dbus::MessageReader& reader) {
return reader.NextIsUint32();
}
-template<> inline uint32_t Take<uint32_t>(dbus::MessageReader* reader) {
+template <>
+inline uint32_t Take<uint32_t>(dbus::MessageReader* reader) {
return reader->TakeUint32();
}
@@ -134,11 +148,13 @@ inline void Put(uint32_t val, dbus::MessageWriter* writer) {
writer->PutUint32(val);
}
-template<> inline bool NextIs<int64_t>(const dbus::MessageReader& reader) {
+template <>
+inline bool NextIs<int64_t>(const dbus::MessageReader& reader) {
return reader.NextIsInt64();
}
-template<> inline int64_t Take<int64_t>(dbus::MessageReader* reader) {
+template <>
+inline int64_t Take<int64_t>(dbus::MessageReader* reader) {
return reader->TakeInt64();
}
@@ -146,11 +162,13 @@ inline void Put(int64_t val, dbus::MessageWriter* writer) {
writer->PutInt64(val);
}
-template<> inline bool NextIs<uint64_t>(const dbus::MessageReader& reader) {
+template <>
+inline bool NextIs<uint64_t>(const dbus::MessageReader& reader) {
return reader.NextIsUint64();
}
-template<> inline uint64_t Take<uint64_t>(dbus::MessageReader* reader) {
+template <>
+inline uint64_t Take<uint64_t>(dbus::MessageReader* reader) {
return reader->TakeUint64();
}
@@ -158,7 +176,8 @@ inline void Put(uint64_t val, dbus::MessageWriter* writer) {
writer->PutUint64(val);
}
-template<> inline std::string Take<std::string>(dbus::MessageReader* reader) {
+template <>
+inline std::string Take<std::string>(dbus::MessageReader* reader) {
return reader->TakeString();
}
@@ -167,66 +186,103 @@ inline void Put(const std::string val, dbus::MessageWriter* writer) {
}
// Type to DBus type id mappers
-template<typename T> char DbusTypeCode();
-template<> inline char DbusTypeCode<bool>() { return DBUS_TYPE_BOOLEAN; }
+template <typename T>
+char DbusTypeCode();
+template <>
+inline char DbusTypeCode<bool>() {
+ return DBUS_TYPE_BOOLEAN;
+}
// There is no dbus type for signed byte, map to unsigned
-template<> inline char DbusTypeCode<int8_t>() { return DBUS_TYPE_BYTE; }
-template<> inline char DbusTypeCode<uint8_t>() { return DBUS_TYPE_BYTE; }
-template<> inline char DbusTypeCode<int16_t>() { return DBUS_TYPE_INT16; }
-template<> inline char DbusTypeCode<uint16_t>() { return DBUS_TYPE_UINT16; }
-template<> inline char DbusTypeCode<int32_t>() { return DBUS_TYPE_INT32; }
-template<> inline char DbusTypeCode<uint32_t>() { return DBUS_TYPE_UINT32; }
-template<> inline char DbusTypeCode<int64_t>() { return DBUS_TYPE_INT64; }
-template<> inline char DbusTypeCode<uint64_t>() { return DBUS_TYPE_UINT64; }
-template<> inline char DbusTypeCode<double>() { return DBUS_TYPE_DOUBLE; }
-template<> inline char DbusTypeCode<std::string>() { return DBUS_TYPE_STRING; }
-template<> inline char DbusTypeCode<const std::string>() { return DBUS_TYPE_STRING; }
+template <>
+inline char DbusTypeCode<int8_t>() {
+ return DBUS_TYPE_BYTE;
+}
+template <>
+inline char DbusTypeCode<uint8_t>() {
+ return DBUS_TYPE_BYTE;
+}
+template <>
+inline char DbusTypeCode<int16_t>() {
+ return DBUS_TYPE_INT16;
+}
+template <>
+inline char DbusTypeCode<uint16_t>() {
+ return DBUS_TYPE_UINT16;
+}
+template <>
+inline char DbusTypeCode<int32_t>() {
+ return DBUS_TYPE_INT32;
+}
+template <>
+inline char DbusTypeCode<uint32_t>() {
+ return DBUS_TYPE_UINT32;
+}
+template <>
+inline char DbusTypeCode<int64_t>() {
+ return DBUS_TYPE_INT64;
+}
+template <>
+inline char DbusTypeCode<uint64_t>() {
+ return DBUS_TYPE_UINT64;
+}
+template <>
+inline char DbusTypeCode<double>() {
+ return DBUS_TYPE_DOUBLE;
+}
+template <>
+inline char DbusTypeCode<std::string>() {
+ return DBUS_TYPE_STRING;
+}
+template <>
+inline char DbusTypeCode<const std::string>() {
+ return DBUS_TYPE_STRING;
+}
// Non-specialized template supposes there is static
// void GetDbusSignature(std::string*) method in T
-template<typename T>
+template <typename T>
struct DbusSignatureHelper {
static void DbusSignature(std::string* signature) {
T::GetDbusSignature(signature);
}
};
-template<>
+template <>
struct DbusSignatureHelper<Boolean> {
static void DbusSignature(std::string* signature) {
(*signature) += rpc::impl::DbusTypeCode<bool>();
}
};
-template<typename T, T minval, T maxval>
+template <typename T, T minval, T maxval>
struct DbusSignatureHelper<Integer<T, minval, maxval> > {
static void DbusSignature(std::string* signature) {
(*signature) += rpc::impl::DbusTypeCode<T>();
}
};
-template<int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
+template <int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
struct DbusSignatureHelper<Float<minnum, maxnum, minden, maxden> > {
static void DbusSignature(std::string* signature) {
(*signature) += rpc::impl::DbusTypeCode<double>();
}
};
-template<typename T>
+template <typename T>
struct DbusSignatureHelper<Enum<T> > {
static void DbusSignature(std::string* signature) {
(*signature) += rpc::impl::DbusTypeCode<int32_t>();
}
};
-template<size_t minlen, size_t maxlen>
+template <size_t minlen, size_t maxlen>
struct DbusSignatureHelper<String<minlen, maxlen> > {
static void DbusSignature(std::string* signature) {
(*signature) += rpc::impl::DbusTypeCode<std::string>();
}
};
-template<typename K, typename V>
+template <typename K, typename V>
struct DbusSignatureHelper<std::pair<K, V> > {
static void DbusSignature(std::string* signature) {
(*signature) += DBUS_DICT_ENTRY_BEGIN_CHAR;
@@ -236,7 +292,7 @@ struct DbusSignatureHelper<std::pair<K, V> > {
}
};
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
struct DbusSignatureHelper<Array<T, minsize, maxsize> > {
static void DbusSignature(std::string* signature) {
(*signature) += DBUS_TYPE_ARRAY;
@@ -244,16 +300,16 @@ struct DbusSignatureHelper<Array<T, minsize, maxsize> > {
}
};
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
struct DbusSignatureHelper<Map<T, minsize, maxsize> > {
static void DbusSignature(std::string* signature) {
(*signature) += DBUS_TYPE_ARRAY;
- rpc::impl::DbusSignatureHelper<
- typename Map<T, minsize, maxsize>::value_type>::DbusSignature(signature);
+ rpc::impl::DbusSignatureHelper<typename Map<T, minsize, maxsize>::
+ value_type>::DbusSignature(signature);
}
};
-template<typename T>
+template <typename T>
struct DbusSignatureHelper<Optional<T> > {
static void DbusSignature(std::string* signature) {
(*signature) += DBUS_STRUCT_BEGIN_CHAR;
@@ -263,7 +319,7 @@ struct DbusSignatureHelper<Optional<T> > {
}
};
-template<typename T>
+template <typename T>
struct DbusSignatureHelper<Nullable<T> > {
static void DbusSignature(std::string* signature) {
(*signature) += DBUS_STRUCT_BEGIN_CHAR;
@@ -274,7 +330,7 @@ struct DbusSignatureHelper<Nullable<T> > {
};
// Helper Optional type initialization functipon
-template<typename T>
+template <typename T>
T TakeOptional(dbus::MessageReader* reader) {
dbus::MessageReader struct_reader = reader->TakeStructReader();
bool available = struct_reader.TakeBool();
@@ -283,7 +339,7 @@ T TakeOptional(dbus::MessageReader* reader) {
}
// Helper Nullable type initialization functipon
-template<typename T>
+template <typename T>
bool TakeNullable(dbus::MessageReader* reader) {
dbus::MessageReader struct_reader = reader->TakeStructReader();
bool is_null = struct_reader.TakeBool();
@@ -292,69 +348,67 @@ bool TakeNullable(dbus::MessageReader* reader) {
} // namespace impl
-
// Helper function that outputs dbus signature for type T
-template<typename T>
+template <typename T>
void DbusSignature(std::string* signature) {
impl::DbusSignatureHelper<T>::DbusSignature(signature);
}
// Type constructors
inline Boolean::Boolean(dbus::MessageReader* reader)
- : PrimitiveType(InitHelper(reader->NextIsBool())),
- value_(reader->TakeBool()) {
-}
+ : PrimitiveType(InitHelper(reader->NextIsBool()))
+ , value_(reader->TakeBool()) {}
-template<typename T, T minval, T maxval>
+template <typename T, T minval, T maxval>
inline Integer<T, minval, maxval>::Integer(dbus::MessageReader* reader)
- : PrimitiveType(InitHelper(impl::NextIs<IntType>(*reader))),
- value_(impl::Take<IntType>(reader)) {
+ : PrimitiveType(InitHelper(impl::NextIs<IntType>(*reader)))
+ , value_(impl::Take<IntType>(reader)) {
if (is_valid()) {
value_state_ = range_.Includes(value_) ? kValid : kInvalid;
}
}
-template<int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
+template <int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
inline Float<minnum, maxnum, minden, maxden>::Float(dbus::MessageReader* reader)
- : PrimitiveType(InitHelper(reader->NextIsDouble())),
- value_(reader->TakeDouble()) {
+ : PrimitiveType(InitHelper(reader->NextIsDouble()))
+ , value_(reader->TakeDouble()) {
if (is_valid()) {
value_state_ = range_.Includes(value_) ? kValid : kInvalid;
}
}
-template<size_t minlen, size_t maxlen>
+template <size_t minlen, size_t maxlen>
inline String<minlen, maxlen>::String(dbus::MessageReader* reader)
- : PrimitiveType(InitHelper(reader->NextIsString())),
- value_(reader->TakeString()) {
+ : PrimitiveType(InitHelper(reader->NextIsString()))
+ , value_(reader->TakeString()) {
if (is_valid()) {
value_state_ = length_range_.Includes(value_.length()) ? kValid : kInvalid;
}
}
-template<typename T>
+template <typename T>
inline Enum<T>::Enum(dbus::MessageReader* reader)
- : PrimitiveType(InitHelper(reader->NextIsInt32())),
- value_(EnumType(reader->TakeInt32())) {
+ : PrimitiveType(InitHelper(reader->NextIsInt32()))
+ , value_(EnumType(reader->TakeInt32())) {
if (is_valid()) {
value_state_ = IsValidEnum(value_) ? kValid : kInvalid;
}
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
inline Array<T, minsize, maxsize>::Array(dbus::MessageReader* reader)
: CompositeType(InitHelper(reader->NextIsArray())) {
dbus::MessageReader array_reader = reader->TakeArrayReader();
if (array_reader.has_failed()) {
push_back(T());
} else {
- while(array_reader.HasNext()) {
+ while (array_reader.HasNext()) {
push_back(T(&array_reader));
}
}
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
inline Map<T, minsize, maxsize>::Map(dbus::MessageReader* reader)
: CompositeType(InitHelper(reader->NextIsStruct())) {
// Map key-value pairs are serialized into array
@@ -362,7 +416,7 @@ inline Map<T, minsize, maxsize>::Map(dbus::MessageReader* reader)
if (array_reader.has_failed()) {
this->insert(typename MapType::value_type("", T()));
} else {
- while(array_reader.HasNext()) {
+ while (array_reader.HasNext()) {
dbus::MessageReader dictvalue_reader = array_reader.TakeDictEntryReader();
typename MapType::key_type key =
impl::Take<typename MapType::key_type>(&dictvalue_reader);
@@ -371,64 +425,62 @@ inline Map<T, minsize, maxsize>::Map(dbus::MessageReader* reader)
}
}
-template<typename T>
+template <typename T>
inline Nullable<T>::Nullable(dbus::MessageReader* reader)
- : T(reader),
- marked_null_(impl::TakeNullable<T>(reader)){
-}
+ : T(reader), marked_null_(impl::TakeNullable<T>(reader)) {}
-template<typename T>
+template <typename T>
inline Optional<T>::Optional(dbus::MessageReader* reader)
- : value_(impl::TakeOptional<T>(reader)){
-}
+ : value_(impl::TakeOptional<T>(reader)) {}
// MessageWriter serializers
inline void Boolean::ToDbusWriter(dbus::MessageWriter* writer) const {
writer->PutBool(value_);
}
-template<typename T, T minval, T maxval>
+template <typename T, T minval, T maxval>
inline void Integer<T, minval, maxval>::ToDbusWriter(
dbus::MessageWriter* writer) const {
impl::Put(value_, writer);
}
-template<int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
+template <int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
inline void Float<minnum, maxnum, minden, maxden>::ToDbusWriter(
dbus::MessageWriter* writer) const {
writer->PutDouble(value_);
}
-template<size_t minlen, size_t maxlen>
+template <size_t minlen, size_t maxlen>
inline void String<minlen, maxlen>::ToDbusWriter(
dbus::MessageWriter* writer) const {
writer->PutString(value_);
}
-template<typename T>
+template <typename T>
inline void Enum<T>::ToDbusWriter(dbus::MessageWriter* writer) const {
writer->PutInt32(static_cast<int32_t>(value_));
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
inline void Array<T, minsize, maxsize>::ToDbusWriter(
dbus::MessageWriter* writer) const {
std::string array_signature;
DbusSignature<typename ArrayType::value_type>(&array_signature);
- dbus::MessageWriter array_writer(writer, dbus::kArray,
- array_signature.c_str());
- for (typename ArrayType::const_iterator i = this->begin(); i != this->end(); ++i) {
+ dbus::MessageWriter array_writer(
+ writer, dbus::kArray, array_signature.c_str());
+ for (typename ArrayType::const_iterator i = this->begin(); i != this->end();
+ ++i) {
i->ToDbusWriter(&array_writer);
}
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
inline void Map<T, minsize, maxsize>::ToDbusWriter(
dbus::MessageWriter* writer) const {
std::string array_signature;
DbusSignature<typename MapType::value_type>(&array_signature);
- dbus::MessageWriter array_writer(writer, dbus::kArray,
- array_signature.c_str());
+ dbus::MessageWriter array_writer(
+ writer, dbus::kArray, array_signature.c_str());
for (typename MapType::const_iterator i = this->begin(); i != this->end();
++i) {
dbus::MessageWriter dictentry_writer(&array_writer, dbus::kDictEntry, NULL);
@@ -437,7 +489,7 @@ inline void Map<T, minsize, maxsize>::ToDbusWriter(
}
}
-template<typename T>
+template <typename T>
inline void Optional<T>::ToDbusWriter(dbus::MessageWriter* writer) const {
dbus::MessageWriter struct_writer(writer, dbus::kStruct, NULL);
struct_writer.PutBool(value_.is_initialized());
@@ -446,4 +498,4 @@ inline void Optional<T>::ToDbusWriter(dbus::MessageWriter* writer) const {
} // namespace rpc
-#endif // RPC_BASE_DBUS_INL_H_
+#endif // RPC_BASE_DBUS_INL_H_
diff --git a/src/components/rpc_base/include/rpc_base/rpc_base_inl.h b/src/components/rpc_base/include/rpc_base/rpc_base_inl.h
index 2241a4707b..a9ff484eb0 100644
--- a/src/components/rpc_base/include/rpc_base/rpc_base_inl.h
+++ b/src/components/rpc_base/include/rpc_base/rpc_base_inl.h
@@ -47,9 +47,7 @@ namespace rpc {
*/
template <typename T>
Range<T>::Range(T min, T max)
- : min_(min),
- max_(max) {
-}
+ : min_(min), max_(max) {}
template <typename T>
T Range<T>::min() const {
@@ -67,14 +65,12 @@ bool Range<T>::Includes(U val) const {
return min() <= val && val <= max();
}
-
/*
* PrimitiveType base class
*/
inline PrimitiveType::PrimitiveType(ValueState value_state)
- : value_state_(value_state),
- policy_table_type_(policy_table_interface_base::PT_PRELOADED) {
-}
+ : value_state_(value_state)
+ , policy_table_type_(policy_table_interface_base::PT_PRELOADED) {}
inline bool PrimitiveType::is_initialized() const {
return value_state_ != kUninitialized;
@@ -113,9 +109,8 @@ inline void CompositeType::mark_initialized() {
}
inline CompositeType::CompositeType(InitializationState init_state)
- : initialization_state__(init_state),
- policy_table_type_(policy_table_interface_base::PT_PRELOADED) {
-}
+ : initialization_state__(init_state)
+ , policy_table_type_(policy_table_interface_base::PT_PRELOADED) {}
inline void CompositeType::ReportErrors(ValidationReport* report) const {
switch (initialization_state__) {
@@ -140,14 +135,9 @@ inline void CompositeType::ReportErrors(ValidationReport* report) const {
/*
* Boolean class
*/
-inline Boolean::Boolean()
- : PrimitiveType(kUninitialized),
- value_(false) {
-}
+inline Boolean::Boolean() : PrimitiveType(kUninitialized), value_(false) {}
-inline Boolean::Boolean(bool value)
- : PrimitiveType(kValid), value_(value) {
-}
+inline Boolean::Boolean(bool value) : PrimitiveType(kValid), value_(value) {}
inline Boolean& Boolean::operator=(bool new_val) {
value_ = new_val;
@@ -162,48 +152,50 @@ inline Boolean::operator bool() const {
/*
* Integer class
*/
-template<typename T, T minval, T maxval>
+template <typename T, T minval, T maxval>
const Range<T> Integer<T, minval, maxval>::range_(minval, maxval);
-template<typename T, T minval, T maxval>
+template <typename T, T minval, T maxval>
Integer<T, minval, maxval>::Integer()
- : PrimitiveType(kUninitialized),
- value_(range_.min()) {
-}
+ : PrimitiveType(kUninitialized), value_(range_.min()) {}
-template<typename T, T minval, T maxval>
+template <typename T, T minval, T maxval>
Integer<T, minval, maxval>::Integer(IntType value)
- : PrimitiveType(range_.Includes(value) ? kValid : kInvalid),
- value_(value) {
-}
+ : PrimitiveType(range_.Includes(value) ? kValid : kInvalid)
+ , value_(value) {}
-template<typename T, T minval, T maxval>
-Integer<T, minval, maxval>& Integer<T, minval, maxval>::operator=(IntType new_val) {
+template <typename T, T minval, T maxval>
+Integer<T, minval, maxval>& Integer<T, minval, maxval>::operator=(
+ IntType new_val) {
value_ = new_val;
value_state_ = range_.Includes(value_) ? kValid : kInvalid;
return *this;
}
-template<typename T, T minval, T maxval>
-Integer<T, minval, maxval>& Integer<T, minval, maxval>::operator=(const Integer& new_val) {
+template <typename T, T minval, T maxval>
+Integer<T, minval, maxval>& Integer<T, minval, maxval>::operator=(
+ const Integer& new_val) {
this->value_ = new_val.value_;
- this->value_state_= range_.Includes(new_val.value_) ? kValid : kInvalid;
+ if (new_val.is_initialized()) {
+ this->value_state_ = range_.Includes(new_val.value_) ? kValid : kInvalid;
+ }
+
return *this;
}
-template<typename T, T minval, T maxval>
+template <typename T, T minval, T maxval>
Integer<T, minval, maxval>& Integer<T, minval, maxval>::operator++() {
++value_;
return *this;
}
-template<typename T, T minval, T maxval>
+template <typename T, T minval, T maxval>
Integer<T, minval, maxval>& Integer<T, minval, maxval>::operator+=(int value) {
value_ += value;
return *this;
}
-template<typename T, T minval, T maxval>
+template <typename T, T minval, T maxval>
Integer<T, minval, maxval>::operator IntType() const {
return value_;
}
@@ -211,32 +203,28 @@ Integer<T, minval, maxval>::operator IntType() const {
/*
* Float class
*/
-template<int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
+template <int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
const Range<double> Float<minnum, maxnum, minden, maxden>::range_(
- (double(minnum)/minden), (double(maxnum)/maxden));
+ (double(minnum) / minden), (double(maxnum) / maxden));
-
-template<int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
+template <int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
Float<minnum, maxnum, minden, maxden>::Float()
- : PrimitiveType(kUninitialized),
- value_(range_.min()) {
-}
+ : PrimitiveType(kUninitialized), value_(range_.min()) {}
-template<int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
+template <int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
Float<minnum, maxnum, minden, maxden>::Float(double value)
- : PrimitiveType(range_.Includes(value) ? kValid : kInvalid),
- value_(value) {
-}
+ : PrimitiveType(range_.Includes(value) ? kValid : kInvalid)
+ , value_(value) {}
-template<int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
-Float<minnum, maxnum, minden, maxden>&
-Float<minnum, maxnum, minden, maxden>::operator=(double new_val) {
+template <int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
+Float<minnum, maxnum, minden, maxden>& Float<minnum, maxnum, minden, maxden>::
+operator=(double new_val) {
value_ = new_val;
value_state_ = range_.Includes(new_val) ? kValid : kInvalid;
return *this;
}
-template<int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
+template <int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
Float<minnum, maxnum, minden, maxden>::operator double() const {
return value_;
}
@@ -244,52 +232,54 @@ Float<minnum, maxnum, minden, maxden>::operator double() const {
/*
* String class
*/
-template<size_t minlen, size_t maxlen>
+template <size_t minlen, size_t maxlen>
const Range<size_t> String<minlen, maxlen>::length_range_(minlen, maxlen);
-template<size_t minlen, size_t maxlen>
+template <size_t minlen, size_t maxlen>
String<minlen, maxlen>::String()
- : PrimitiveType(kUninitialized) {
-}
+ : PrimitiveType(kUninitialized) {}
-template<size_t minlen, size_t maxlen>
+template <size_t minlen, size_t maxlen>
String<minlen, maxlen>::String(const std::string& value)
- : PrimitiveType(length_range_.Includes(value.length()) ? kValid : kInvalid),
- value_(value) {
-}
+ : PrimitiveType(length_range_.Includes(value.length()) ? kValid : kInvalid)
+ , value_(value) {}
-template<size_t minlen, size_t maxlen>
+template <size_t minlen, size_t maxlen>
String<minlen, maxlen>::String(const char* value)
- : PrimitiveType(kUninitialized),
- value_(value) {
+ : PrimitiveType(kUninitialized), value_(value) {
value_state_ = length_range_.Includes(value_.length()) ? kValid : kInvalid;
}
-template<size_t minlen, size_t maxlen>
-bool String<minlen, maxlen>::operator<(String new_val) {
+template <size_t minlen, size_t maxlen>
+bool String<minlen, maxlen>::operator<(const String& new_val) const {
return value_ < new_val.value_;
}
-template<size_t minlen, size_t maxlen>
-String<minlen, maxlen>& String<minlen, maxlen>::operator=(const std::string& new_val) {
+template <size_t minlen, size_t maxlen>
+String<minlen, maxlen>& String<minlen, maxlen>::operator=(
+ const std::string& new_val) {
value_ = new_val;
value_state_ = length_range_.Includes(new_val.length()) ? kValid : kInvalid;
return *this;
}
-template<size_t minlen, size_t maxlen>
-String<minlen, maxlen>& String<minlen, maxlen>::operator=(const String& new_val) {
+template <size_t minlen, size_t maxlen>
+String<minlen, maxlen>& String<minlen, maxlen>::operator=(
+ const String& new_val) {
+ if (*this == new_val) {
+ return *this;
+ }
value_.assign(new_val.value_);
value_state_ = new_val.value_state_;
return *this;
}
-template<size_t minlen, size_t maxlen>
-bool String<minlen, maxlen>::operator==(const String& rhs) {
+template <size_t minlen, size_t maxlen>
+bool String<minlen, maxlen>::operator==(const String& rhs) const {
return value_ == rhs.value_;
}
-template<size_t minlen, size_t maxlen>
+template <size_t minlen, size_t maxlen>
String<minlen, maxlen>::operator const std::string&() const {
return value_;
}
@@ -297,26 +287,22 @@ String<minlen, maxlen>::operator const std::string&() const {
/*
* Enum class
*/
-template<typename T>
+template <typename T>
Enum<T>::Enum()
- : PrimitiveType(kUninitialized),
- value_(EnumType()) {
-}
+ : PrimitiveType(kUninitialized), value_(EnumType()) {}
-template<typename T>
+template <typename T>
Enum<T>::Enum(EnumType value)
- : PrimitiveType(IsValidEnum(value) ? kValid : kInvalid),
- value_(value) {
-}
+ : PrimitiveType(IsValidEnum(value) ? kValid : kInvalid), value_(value) {}
-template<typename T>
-Enum<T>& Enum<T>::operator=(EnumType new_val) {
+template <typename T>
+Enum<T>& Enum<T>::operator=(const EnumType& new_val) {
value_ = new_val;
value_state_ = IsValidEnum(value_) ? kValid : kInvalid;
return *this;
}
-template<typename T>
+template <typename T>
Enum<T>::operator EnumType() const {
return value_;
}
@@ -324,33 +310,30 @@ Enum<T>::operator EnumType() const {
/*
* Array class
*/
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
Array<T, minsize, maxsize>::Array()
- : CompositeType(kUninitialized) {
-}
+ : CompositeType(kUninitialized) {}
-template<typename T, size_t minsize, size_t maxsize>
-template<typename U>
+template <typename T, size_t minsize, size_t maxsize>
+template <typename U>
Array<T, minsize, maxsize>::Array(const U& value)
- : ArrayType(value.begin(), value.end()),
- CompositeType(kUninitialized) {
-}
+ : ArrayType(value.begin(), value.end()), CompositeType(kUninitialized) {}
-template<typename T, size_t minsize, size_t maxsize>
-template<typename U>
-Array<T, minsize, maxsize>&
-Array<T, minsize, maxsize>::operator=(const U& that) {
+template <typename T, size_t minsize, size_t maxsize>
+template <typename U>
+Array<T, minsize, maxsize>& Array<T, minsize, maxsize>::operator=(
+ const U& that) {
this->assign(that.begin(), that.end());
return *this;
}
-template<typename T, size_t minsize, size_t maxsize>
-template<typename U>
+template <typename T, size_t minsize, size_t maxsize>
+template <typename U>
void Array<T, minsize, maxsize>::push_back(const U& value) {
ArrayType::push_back(T(value));
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
bool Array<T, minsize, maxsize>::is_valid() const {
// Empty array might be valid only if marked initialized
if (this->empty() && (initialization_state__ != kInitialized)) {
@@ -361,8 +344,8 @@ bool Array<T, minsize, maxsize>::is_valid() const {
return false;
}
// All array elements must be valid
- for (typename ArrayType::const_iterator i = this->begin();
- i != this->end(); ++i) {
+ for (typename ArrayType::const_iterator i = this->begin(); i != this->end();
+ ++i) {
if (!i->is_valid()) {
return false;
}
@@ -370,7 +353,7 @@ bool Array<T, minsize, maxsize>::is_valid() const {
return true;
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
bool Array<T, minsize, maxsize>::is_initialized() const {
// Array that is not empty is initialized for sure
if (!this->empty()) {
@@ -383,7 +366,7 @@ bool Array<T, minsize, maxsize>::is_initialized() const {
return false;
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
void Array<T, minsize, maxsize>::ReportErrors(ValidationReport* report) const {
if (this->empty()) {
CompositeType::ReportErrors(report);
@@ -395,54 +378,50 @@ void Array<T, minsize, maxsize>::ReportErrors(ValidationReport* report) const {
}
}
for (size_t i = 0; i != this->size(); ++i) {
- const T& elem = this->operator [](i);
+ const T& elem = this->operator[](i);
if (!elem.is_valid()) {
char elem_idx[32] = {};
snprintf(elem_idx, 32, "[%zu]", i);
- ValidationReport& elem_report =
- report->ReportSubobject(elem_idx);
+ ValidationReport& elem_report = report->ReportSubobject(elem_idx);
elem.ReportErrors(&elem_report);
}
}
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
void Array<T, minsize, maxsize>::SetPolicyTableType(
rpc::policy_table_interface_base::PolicyTableType pt_type) {
-
- for (typename ArrayType::iterator it = this->begin();
- it != this->end(); ++it) {
- it->SetPolicyTableType(pt_type);
+ for (typename ArrayType::iterator it = this->begin(); it != this->end();
+ ++it) {
+ it->SetPolicyTableType(pt_type);
}
}
/*
* Map class
*/
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
Map<T, minsize, maxsize>::Map()
- : CompositeType(kUninitialized) {
-}
+ : CompositeType(kUninitialized) {}
-template<typename T, size_t minsize, size_t maxsize>
-template<typename U>
+template <typename T, size_t minsize, size_t maxsize>
+template <typename U>
Map<T, minsize, maxsize>::Map(const U& value)
: CompositeType(kUninitialized) {
for (typename U::const_iterator i = value.begin(), e = value.end(); i != e;
- ++i) {
+ ++i) {
// Explicitly convert that value to T because all rpc_types have explicit
// constructors
insert(typename MapType::value_type(i->first, T(i->second)));
}
}
-template<typename T, size_t minsize, size_t maxsize>
-template<typename U>
-Map<T, minsize, maxsize>&
-Map<T, minsize, maxsize>::operator=(const U& that) {
+template <typename T, size_t minsize, size_t maxsize>
+template <typename U>
+Map<T, minsize, maxsize>& Map<T, minsize, maxsize>::operator=(const U& that) {
this->clear();
for (typename U::const_iterator i = that.begin(), e = that.end(); i != e;
- ++i) {
+ ++i) {
// Explicitly convert that value to T because all rpc_types have explicit
// constructors
insert(typename MapType::value_type(i->first, T(i->second)));
@@ -450,13 +429,13 @@ Map<T, minsize, maxsize>::operator=(const U& that) {
return *this;
}
-template<typename T, size_t minsize, size_t maxsize>
-template<typename U>
+template <typename T, size_t minsize, size_t maxsize>
+template <typename U>
void Map<T, minsize, maxsize>::insert(const std::pair<std::string, U>& value) {
MapType::insert(typename MapType::value_type(value.first, T(value.second)));
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
bool Map<T, minsize, maxsize>::is_valid() const {
// Empty map might be valid only if marked initialized
if (this->empty() && (initialization_state__ != kInitialized)) {
@@ -467,8 +446,7 @@ bool Map<T, minsize, maxsize>::is_valid() const {
return false;
}
// All map elements must be valid
- for (typename Map::const_iterator i = this->begin();
- i != this->end(); ++i) {
+ for (typename Map::const_iterator i = this->begin(); i != this->end(); ++i) {
if (!i->second.is_valid()) {
return false;
}
@@ -476,7 +454,7 @@ bool Map<T, minsize, maxsize>::is_valid() const {
return true;
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
bool Map<T, minsize, maxsize>::is_initialized() const {
// Map that is not empty is initialized for sure
if (!this->empty()) {
@@ -489,7 +467,7 @@ bool Map<T, minsize, maxsize>::is_initialized() const {
return false;
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
void Map<T, minsize, maxsize>::ReportErrors(ValidationReport* report) const {
if (this->empty()) {
CompositeType::ReportErrors(report);
@@ -500,8 +478,7 @@ void Map<T, minsize, maxsize>::ReportErrors(ValidationReport* report) const {
// No error
}
}
- for (typename Map::const_iterator i = this->begin();
- i != this->end(); ++i) {
+ for (typename Map::const_iterator i = this->begin(); i != this->end(); ++i) {
if (!i->second.is_valid()) {
std::string elem_name = "[\"" + i->first + "\"]";
ValidationReport& elem_report = report->ReportSubobject(elem_name);
@@ -510,11 +487,10 @@ void Map<T, minsize, maxsize>::ReportErrors(ValidationReport* report) const {
}
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
void Map<T, minsize, maxsize>::SetPolicyTableType(
rpc::policy_table_interface_base::PolicyTableType pt_type) {
- for (typename Map::iterator it = this->begin();
- it != this->end(); ++it) {
+ for (typename Map::iterator it = this->begin(); it != this->end(); ++it) {
it->second.SetPolicyTableType(pt_type);
}
}
@@ -522,46 +498,43 @@ void Map<T, minsize, maxsize>::SetPolicyTableType(
/*
* Nullable class
*/
-template<typename T>
+template <typename T>
Nullable<T>::Nullable()
- : marked_null_(false) {
-}
+ : marked_null_(false) {}
-template<typename T>
-template<typename U>
+template <typename T>
+template <typename U>
Nullable<T>::Nullable(const U& value)
- : T(value),
- marked_null_(false) {
-}
+ : T(value), marked_null_(false) {}
-template<typename T>
-template<typename U>
+template <typename T>
+template <typename U>
Nullable<T>& Nullable<T>::operator=(const U& new_val) {
this->T::operator=(new_val);
return *this;
}
-template<typename T>
+template <typename T>
bool Nullable<T>::is_valid() const {
return is_null() || T::is_valid();
}
-template<typename T>
+template <typename T>
bool Nullable<T>::is_initialized() const {
return is_null() || T::is_initialized();
}
-template<typename T>
+template <typename T>
bool Nullable<T>::is_null() const {
return marked_null_;
}
-template<typename T>
+template <typename T>
void Nullable<T>::set_to_null() {
marked_null_ = true;
}
-template<typename T>
+template <typename T>
void Nullable<T>::ReportErrors(ValidationReport* report) const {
if (marked_null_) {
// No error
@@ -573,59 +546,57 @@ void Nullable<T>::ReportErrors(ValidationReport* report) const {
/*
* Optional class
*/
-template<typename T>
-Optional<T>::Optional() {
-}
+template <typename T>
+Optional<T>::Optional() {}
-template<typename T>
-template<typename U>
+template <typename T>
+template <typename U>
Optional<T>::Optional(const U& value)
- : value_(value) {
-}
+ : value_(value) {}
-template<typename T>
+template <typename T>
T& Optional<T>::operator*() {
return value_;
}
-template<typename T>
+template <typename T>
const T& Optional<T>::operator*() const {
return value_;
}
-template<typename T>
+template <typename T>
T* Optional<T>::operator->() {
return &value_;
}
-template<typename T>
+template <typename T>
const T* Optional<T>::operator->() const {
return &value_;
}
-template<typename T>
+template <typename T>
void Optional<T>::assign_if_valid(const Optional<T>& value) {
if (value.is_initialized()) {
value_ = value.value_;
}
}
-template<typename T>
+template <typename T>
Optional<T>::operator const void*() const {
return is_initialized() ? &value_ : NULL;
}
-template<typename T>
+template <typename T>
bool Optional<T>::is_valid() const {
return !value_.is_initialized() || value_.is_valid();
}
-template<typename T>
+template <typename T>
bool Optional<T>::is_initialized() const {
return value_.is_initialized();
}
-template<typename T>
+template <typename T>
void Optional<T>::ReportErrors(ValidationReport* report) const {
if (!is_initialized()) {
// No error
@@ -633,13 +604,15 @@ void Optional<T>::ReportErrors(ValidationReport* report) const {
value_.ReportErrors(report);
}
}
-template<typename T>
-inline rpc::policy_table_interface_base::PolicyTableType Optional<T>::GetPolicyTableType() const {
+template <typename T>
+inline rpc::policy_table_interface_base::PolicyTableType
+Optional<T>::GetPolicyTableType() const {
return policy_table_type_;
}
-template<typename T>
-void rpc::Optional<T>::SetPolicyTableType(rpc::policy_table_interface_base::PolicyTableType pt_type) {
+template <typename T>
+void rpc::Optional<T>::SetPolicyTableType(
+ rpc::policy_table_interface_base::PolicyTableType pt_type) {
policy_table_type_ = pt_type;
value_.SetPolicyTableType(pt_type);
}
@@ -647,51 +620,48 @@ void rpc::Optional<T>::SetPolicyTableType(rpc::policy_table_interface_base::Poli
/*
* Stringifyable class
*/
-template<typename T>
+template <typename T>
Stringifyable<T>::Stringifyable()
- : predefined_string_("") {
-}
+ : predefined_string_("") {}
-template<typename T>
-template<typename U>
+template <typename T>
+template <typename U>
Stringifyable<T>::Stringifyable(const U& value)
- : T(value),
- predefined_string_("") {
-}
+ : T(value), predefined_string_("") {}
-template<typename T>
-template<typename U>
+template <typename T>
+template <typename U>
Stringifyable<T>& Stringifyable<T>::operator=(const U& new_val) {
this->T::operator=(new_val);
return *this;
}
-template<typename T>
+template <typename T>
bool Stringifyable<T>::is_valid() const {
return is_string() || T::is_valid();
}
-template<typename T>
+template <typename T>
bool Stringifyable<T>::is_initialized() const {
return is_string() || T::is_initialized();
}
-template<typename T>
+template <typename T>
bool Stringifyable<T>::is_string() const {
return !predefined_string_.empty();
}
-template<typename T>
+template <typename T>
std::string Stringifyable<T>::get_string() const {
return predefined_string_;
}
-template<typename T>
+template <typename T>
void Stringifyable<T>::set_to_string(const std::string& input) {
predefined_string_ = input;
}
-template<typename T>
+template <typename T>
void Stringifyable<T>::ReportErrors(ValidationReport* report) const {
if (is_string()) {
// No error
@@ -702,6 +672,4 @@ void Stringifyable<T>::ReportErrors(ValidationReport* report) const {
} // namespace rpc
-
-
#endif /* VALIDATED_TYPES_INL_H_ */
diff --git a/src/components/rpc_base/include/rpc_base/rpc_base_json_inl.h b/src/components/rpc_base/include/rpc_base/rpc_base_json_inl.h
index b5fd9a567a..b9fcac4b6a 100644
--- a/src/components/rpc_base/include/rpc_base/rpc_base_json_inl.h
+++ b/src/components/rpc_base/include/rpc_base/rpc_base_json_inl.h
@@ -40,8 +40,7 @@ namespace rpc {
// static
inline PrimitiveType::ValueState PrimitiveType::InitHelper(
- const Json::Value* value,
- bool (Json::Value::*type_check)() const) {
+ const Json::Value* value, bool (Json::Value::*type_check)() const) {
if (!value) {
return kUninitialized;
} else if ((value->*type_check)()) {
@@ -51,18 +50,19 @@ inline PrimitiveType::ValueState PrimitiveType::InitHelper(
}
}
-inline policy_table_interface_base::PolicyTableType PrimitiveType::GetPolicyTableType() const {
+inline policy_table_interface_base::PolicyTableType
+PrimitiveType::GetPolicyTableType() const {
return policy_table_type_;
}
-inline void PrimitiveType::SetPolicyTableType(policy_table_interface_base::PolicyTableType pt_type) {
+inline void PrimitiveType::SetPolicyTableType(
+ policy_table_interface_base::PolicyTableType pt_type) {
policy_table_type_ = pt_type;
}
// static
inline CompositeType::InitializationState CompositeType::InitHelper(
- const Json::Value* value,
- bool (Json::Value::*type_check)() const) {
+ const Json::Value* value, bool (Json::Value::*type_check)() const) {
if (!value) {
return kUninitialized;
} else if ((value->*type_check)()) {
@@ -77,11 +77,13 @@ inline CompositeType::InitializationState CompositeType::InitHelper(
}
}
-inline policy_table_interface_base::PolicyTableType CompositeType::GetPolicyTableType() const {
+inline policy_table_interface_base::PolicyTableType
+CompositeType::GetPolicyTableType() const {
return policy_table_type_;
}
-inline void CompositeType::SetPolicyTableType(policy_table_interface_base::PolicyTableType pt_type) {
+inline void CompositeType::SetPolicyTableType(
+ policy_table_interface_base::PolicyTableType pt_type) {
policy_table_type_ = pt_type;
}
@@ -95,7 +97,7 @@ inline const Json::Value* ValueMember(const Json::Value* value,
return NULL;
}
-template<class T>
+template <class T>
inline void WriteJsonField(const char* field_name,
const T& field,
Json::Value* json_value) {
@@ -107,13 +109,12 @@ inline void WriteJsonField(const char* field_name,
} // namespace impl
inline Boolean::Boolean(const Json::Value* value)
- : PrimitiveType(InitHelper(value, &Json::Value::isBool)),
- value_(is_valid() ? value->asBool() : bool()) {
-}
+ : PrimitiveType(InitHelper(value, &Json::Value::isBool))
+ , value_(is_valid() ? value->asBool() : bool()) {}
inline Boolean::Boolean(const Json::Value* value, bool def_value)
- : PrimitiveType(InitHelper(value, &Json::Value::isBool)),
- value_(is_valid() ? value->asBool() : def_value) {
+ : PrimitiveType(InitHelper(value, &Json::Value::isBool))
+ , value_(is_valid() ? value->asBool() : def_value) {
// If there is no value, mark it as valid and use def_value
if (!is_initialized()) {
value_state_ = kValid;
@@ -124,10 +125,9 @@ inline Json::Value Boolean::ToJsonValue() const {
return Json::Value(value_);
}
-template<typename T, T minval, T maxval>
+template <typename T, T minval, T maxval>
Integer<T, minval, maxval>::Integer(const Json::Value* value)
- : PrimitiveType(InitHelper(value, &Json::Value::isInt)),
- value_() {
+ : PrimitiveType(InitHelper(value, &Json::Value::isInt)), value_() {
if (is_valid()) {
Json::Value::Int64 intval = value->asInt64();
if (range_.Includes(intval)) {
@@ -138,16 +138,14 @@ Integer<T, minval, maxval>::Integer(const Json::Value* value)
}
}
-template<typename T, T minval, T maxval>
+template <typename T, T minval, T maxval>
Integer<T, minval, maxval>::Integer(const Integer& val)
- : PrimitiveType(range_.Includes(val.value_) ? kValid : kInvalid),
- value_(val.value_) {
-}
+ : PrimitiveType(range_.Includes(val.value_) ? kValid : kInvalid)
+ , value_(val.value_) {}
-template<typename T, T minval, T maxval>
+template <typename T, T minval, T maxval>
Integer<T, minval, maxval>::Integer(const Json::Value* value, IntType def_value)
- : PrimitiveType(InitHelper(value, &Json::Value::isInt)),
- value_(def_value) {
+ : PrimitiveType(InitHelper(value, &Json::Value::isInt)), value_(def_value) {
if (!is_initialized()) {
value_state_ = kValid;
} else if (is_valid()) {
@@ -160,26 +158,25 @@ Integer<T, minval, maxval>::Integer(const Json::Value* value, IntType def_value)
}
}
-template<typename T, T minval, T maxval>
+template <typename T, T minval, T maxval>
Json::Value Integer<T, minval, maxval>::ToJsonValue() const {
return Json::Value(Json::Int64(value_));
}
-template<int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
+template <int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
Float<minnum, maxnum, minden, maxden>::Float(const Json::Value* value)
- : PrimitiveType(InitHelper(value, &Json::Value::isDouble)),
- value_() {
+ : PrimitiveType(InitHelper(value, &Json::Value::isDouble)), value_() {
if (is_valid()) {
value_ = value->asDouble();
value_state_ = range_.Includes(value_) ? kValid : kInvalid;
}
}
-template<int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
+template <int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
Float<minnum, maxnum, minden, maxden>::Float(const Json::Value* value,
- double def_value)
- : PrimitiveType(InitHelper(value, &Json::Value::isDouble)),
- value_(def_value) {
+ double def_value)
+ : PrimitiveType(InitHelper(value, &Json::Value::isDouble))
+ , value_(def_value) {
if (!is_initialized()) {
value_state_ = kValid;
} else if (is_valid()) {
@@ -188,24 +185,25 @@ Float<minnum, maxnum, minden, maxden>::Float(const Json::Value* value,
}
}
-template<int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
+template <int64_t minnum, int64_t maxnum, int64_t minden, int64_t maxden>
Json::Value Float<minnum, maxnum, minden, maxden>::ToJsonValue() const {
return Json::Value(value_);
}
-template<size_t minlen, size_t maxlen>
+template <size_t minlen, size_t maxlen>
String<minlen, maxlen>::String(const Json::Value* value)
- : PrimitiveType(InitHelper(value, &Json::Value::isString)),
- value_(is_valid() ? value->asString() : std::string()) {
+ : PrimitiveType(InitHelper(value, &Json::Value::isString))
+ , value_(is_valid() ? value->asString() : std::string()) {
if (is_valid()) {
value_state_ = length_range_.Includes(value_.length()) ? kValid : kInvalid;
}
}
-template<size_t minlen, size_t maxlen>
-String<minlen, maxlen>::String(const Json::Value* value, const std::string& def_value)
- : PrimitiveType(InitHelper(value, &Json::Value::isString)),
- value_(def_value) {
+template <size_t minlen, size_t maxlen>
+String<minlen, maxlen>::String(const Json::Value* value,
+ const std::string& def_value)
+ : PrimitiveType(InitHelper(value, &Json::Value::isString))
+ , value_(def_value) {
if (!is_initialized()) {
value_state_ = kValid;
} else if (is_valid()) {
@@ -213,42 +211,42 @@ String<minlen, maxlen>::String(const Json::Value* value, const std::string& def_
}
}
-template<size_t minlen, size_t maxlen>
+template <size_t minlen, size_t maxlen>
Json::Value String<minlen, maxlen>::ToJsonValue() const {
return Json::Value(value_);
}
-template<typename T>
+template <typename T>
Enum<T>::Enum(const Json::Value* value)
- : PrimitiveType(InitHelper(value, &Json::Value::isString)),
- value_(EnumType()) {
+ : PrimitiveType(InitHelper(value, &Json::Value::isString))
+ , value_(EnumType()) {
if (is_valid()) {
value_state_ =
- EnumFromJsonString(value->asString(), &value_) ? kValid : kInvalid;
+ EnumFromJsonString(value->asString(), &value_) ? kValid : kInvalid;
}
}
-template<typename T>
+template <typename T>
Enum<T>::Enum(const Json::Value* value, EnumType def_value)
- : PrimitiveType(InitHelper(value, &Json::Value::isString)),
- value_(def_value) {
+ : PrimitiveType(InitHelper(value, &Json::Value::isString))
+ , value_(def_value) {
if (!is_initialized()) {
value_state_ = kValid;
} else if (is_valid()) {
value_state_ =
- EnumFromJsonString(value->asString(), &value_) ? kValid : kInvalid;
+ EnumFromJsonString(value->asString(), &value_) ? kValid : kInvalid;
}
}
-template<typename T>
+template <typename T>
Json::Value Enum<T>::ToJsonValue() const {
return Json::Value(Json::StaticString(EnumToJsonString(value_)));
}
// Non-const version
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
Array<T, minsize, maxsize>::Array(Json::Value* value)
- : CompositeType(InitHelper(value, &Json::Value::isArray)) {
+ : CompositeType(InitHelper(value, &Json::Value::isArray)) {
if (value) {
if (value->isArray()) {
this->reserve(value->size());
@@ -263,13 +261,14 @@ Array<T, minsize, maxsize>::Array(Json::Value* value)
}
// Const version, must be identical to the non-const version
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
Array<T, minsize, maxsize>::Array(const Json::Value* value)
- : CompositeType(InitHelper(value, &Json::Value::isArray)) {
+ : CompositeType(InitHelper(value, &Json::Value::isArray)) {
if (value) {
if (value->isArray()) {
this->reserve(value->size());
- for (Json::Value::const_iterator i = value->begin(); i != value->end(); ++i) {
+ for (Json::Value::const_iterator i = value->begin(); i != value->end();
+ ++i) {
push_back(&*i);
}
} else {
@@ -279,20 +278,20 @@ Array<T, minsize, maxsize>::Array(const Json::Value* value)
}
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
Json::Value Array<T, minsize, maxsize>::ToJsonValue() const {
Json::Value array(Json::arrayValue);
array.resize(this->size());
for (size_t i = 0; i != this->size(); ++i) {
- array[Json::ArrayIndex(i)] = (this->operator [](i)).ToJsonValue();
+ array[Json::ArrayIndex(i)] = (this->operator[](i)).ToJsonValue();
}
return array;
}
// Non-const version
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
Map<T, minsize, maxsize>::Map(Json::Value* value)
- : CompositeType(InitHelper(value, &Json::Value::isObject)) {
+ : CompositeType(InitHelper(value, &Json::Value::isObject)) {
if (value) {
if (value->isObject()) {
for (Json::Value::iterator i = value->begin(); i != value->end(); ++i) {
@@ -305,12 +304,13 @@ Map<T, minsize, maxsize>::Map(Json::Value* value)
}
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
Map<T, minsize, maxsize>::Map(const Json::Value* value)
- : CompositeType(InitHelper(value, &Json::Value::isObject)) {
+ : CompositeType(InitHelper(value, &Json::Value::isObject)) {
if (value) {
if (value->isObject()) {
- for (Json::Value::const_iterator i = value->begin(); i != value->end(); ++i) {
+ for (Json::Value::const_iterator i = value->begin(); i != value->end();
+ ++i) {
this->insert(typename MapType::value_type(i.key().asString(), T(&*i)));
}
} else {
@@ -320,70 +320,64 @@ Map<T, minsize, maxsize>::Map(const Json::Value* value)
}
}
-template<typename T, size_t minsize, size_t maxsize>
+template <typename T, size_t minsize, size_t maxsize>
Json::Value Map<T, minsize, maxsize>::ToJsonValue() const {
Json::Value map(Json::objectValue);
- for (typename MapType::const_iterator i = this->begin(); i != this->end(); ++i) {
+ for (typename MapType::const_iterator i = this->begin(); i != this->end();
+ ++i) {
map[i->first] = i->second.ToJsonValue();
}
return map;
}
-template<typename T>
+template <typename T>
Nullable<T>::Nullable(const Json::Value* value)
- : T(value),
- marked_null_(value != NULL&& value->isNull()) {
-}
+ : T(value), marked_null_(value != NULL && value->isNull()) {}
-template<typename T>
+template <typename T>
Nullable<T>::Nullable(Json::Value* value)
- : T(value),
- marked_null_(value != NULL&& value->isNull()) {
-}
+ : T(value), marked_null_(value != NULL && value->isNull()) {}
-template<typename T>
-template<typename U>
+template <typename T>
+template <typename U>
Nullable<T>::Nullable(const Json::Value* value, const U& def_value)
- : T(value, def_value),
- marked_null_(value != NULL&& value->isNull()) {
-}
+ : T(value, def_value), marked_null_(value != NULL && value->isNull()) {}
-template<typename T>
+template <typename T>
inline Json::Value Nullable<T>::ToJsonValue() const {
return marked_null_ ? Json::Value::null : T::ToJsonValue();
}
-template<typename T>
-template<typename U>
+template <typename T>
+template <typename U>
Optional<T>::Optional(const Json::Value* value, const U& def_value)
- : value_(value, def_value) {
-}
+ : value_(value, def_value) {}
-template<typename T>
+template <typename T>
inline Json::Value Optional<T>::ToJsonValue() const {
return value_.ToJsonValue();
}
-template<typename T>
+template <typename T>
Stringifyable<T>::Stringifyable(const Json::Value* value)
- : T(NULL != value&& !value->isString() ? value : NULL),
- predefined_string_(NULL != value&& value->isString() ? value->asString() : "") {
-}
+ : T(NULL != value && !value->isString() ? value : NULL)
+ , predefined_string_(NULL != value && value->isString() ? value->asString()
+ : "") {}
-template<typename T>
+template <typename T>
Stringifyable<T>::Stringifyable(Json::Value* value)
- : T(NULL != value&& !value->isString() ? value : NULL),
- predefined_string_(NULL != value&& value->isString() ? value->asString() : "") {
-}
+ : T(NULL != value && !value->isString() ? value : NULL)
+ , predefined_string_(NULL != value && value->isString() ? value->asString()
+ : "") {}
-template<typename T>
-template<typename U>
+template <typename T>
+template <typename U>
Stringifyable<T>::Stringifyable(const Json::Value* value, const U& def_value)
- : T(NULL != value&& !value->isString() ? (value, def_value) : NULL),
- predefined_string_(NULL != value&& value->isString() ? value->asString() : "") {
-}
+ : T(NULL != value && !value->isString() ? (value, def_value) : NULL)
+ , predefined_string_(NULL != value && value->isString() ? value->asString()
+ : "") {}
-template<typename T>
+template <typename T>
inline Json::Value Stringifyable<T>::ToJsonValue() const {
return predefined_string_.empty() ? T::ToJsonValue() : predefined_string_;
}
diff --git a/src/components/rpc_base/include/rpc_base/rpc_message.h b/src/components/rpc_base/include/rpc_base/rpc_message.h
index 18ace4552a..7b5ed2e375 100644
--- a/src/components/rpc_base/include/rpc_base/rpc_message.h
+++ b/src/components/rpc_base/include/rpc_base/rpc_message.h
@@ -41,17 +41,13 @@ class Value;
namespace rpc {
-enum MessageType {
- kRequest = 0,
- kResponse = 1,
- kNotification = 2
-};
+enum MessageType { kRequest = 0, kResponse = 1, kNotification = 2 };
// Base class for all RPC messages
// Has methods to identify interface this message belongs to
// And message ID
class Message {
-public:
+ public:
// Type of message
virtual MessageType message_type() const = 0;
// Numerical function identifier, unique to the interface
@@ -69,26 +65,34 @@ public:
// Base class for all interface-specific requests
class RequestBase : public Message, public CompositeType {
public:
- explicit RequestBase(InitializationState init_state): CompositeType(init_state) {}
+ explicit RequestBase(InitializationState init_state)
+ : CompositeType(init_state) {}
// Message interface
- MessageType message_type() const { return kRequest; }
+ MessageType message_type() const {
+ return kRequest;
+ }
virtual ~RequestBase() {}
};
// Base class for all interface-specific responses
class ResponseBase : public Message, public CompositeType {
public:
- ResponseBase(InitializationState init_state): CompositeType(init_state) {}
+ ResponseBase(InitializationState init_state) : CompositeType(init_state) {}
// Message interface
- MessageType message_type() const { return kResponse; }
+ MessageType message_type() const {
+ return kResponse;
+ }
virtual ~ResponseBase() {}
};
// Base class for all interface-specific notifications
class NotificationBase : public Message, public CompositeType {
public:
- explicit NotificationBase(InitializationState init_state): CompositeType(init_state) {}
- MessageType message_type() const { return kNotification; }
+ explicit NotificationBase(InitializationState init_state)
+ : CompositeType(init_state) {}
+ MessageType message_type() const {
+ return kNotification;
+ }
// Message interface
virtual ~NotificationBase() {}
};
diff --git a/src/components/rpc_base/include/rpc_base/validation_report.h b/src/components/rpc_base/include/rpc_base/validation_report.h
index b8a9c4d1cd..941c8f61cc 100644
--- a/src/components/rpc_base/include/rpc_base/validation_report.h
+++ b/src/components/rpc_base/include/rpc_base/validation_report.h
@@ -49,7 +49,8 @@ class ValidationReport {
void set_validation_info(const std::string& info);
const ValidationReports& subobject_reports() const;
ValidationReport& ReportSubobject(const std::string& object_name);
-private:
+
+ private:
std::string object_name_;
std::string validation_info_;
ValidationReports subobject_reports_;
@@ -61,8 +62,8 @@ std::string PrettyFormat(const ValidationReport& report);
namespace impl {
inline void PrettyFormat(const ValidationReport& report,
- const std::string& parent_path,
- std::string* result) {
+ const std::string& parent_path,
+ std::string* result) {
std::string object_path = parent_path;
if (!object_path.empty() && report.object_name()[0] != '[') {
object_path.append(".");
@@ -76,15 +77,16 @@ inline void PrettyFormat(const ValidationReport& report,
}
const ValidationReports& subreports = report.subobject_reports();
for (ValidationReports::const_iterator i = subreports.begin(),
- end = subreports.end(); i != end; ++i) {
+ end = subreports.end();
+ i != end;
+ ++i) {
PrettyFormat(*i, object_path, result);
}
}
} // namespace impl
inline ValidationReport::ValidationReport(const std::string& object_name)
- : object_name_(object_name) {
-}
+ : object_name_(object_name) {}
inline const std::string& ValidationReport::object_name() const {
return object_name_;
@@ -98,7 +100,8 @@ inline void ValidationReport::set_validation_info(const std::string& info) {
validation_info_ = info;
}
-inline const std::list<ValidationReport>& ValidationReport::subobject_reports() const {
+inline const std::list<ValidationReport>& ValidationReport::subobject_reports()
+ const {
return subobject_reports_;
}
diff --git a/src/components/rpc_base/src/rpc_base/rpc_base.cc b/src/components/rpc_base/src/rpc_base/rpc_base.cc
index f2290780ed..d506bea377 100644
--- a/src/components/rpc_base/src/rpc_base/rpc_base.cc
+++ b/src/components/rpc_base/src/rpc_base/rpc_base.cc
@@ -32,6 +32,4 @@
#include "rpc_base/rpc_base.h"
-namespace rpc {
-
-} // namespace rpc
+namespace rpc {} // namespace rpc
diff --git a/src/components/rpc_base/test/rpc_base_dbus_test.cc b/src/components/rpc_base/test/rpc_base_dbus_test.cc
index e217eff476..f26ce25c5d 100644
--- a/src/components/rpc_base/test/rpc_base_dbus_test.cc
+++ b/src/components/rpc_base/test/rpc_base_dbus_test.cc
@@ -38,11 +38,7 @@ namespace test {
using namespace rpc;
using namespace dbus;
-enum TestEnum {
- kValue0,
- kValue1,
- kInvalidValue
-};
+enum TestEnum { kValue0, kValue1, kInvalidValue };
bool IsValidEnum(TestEnum val) {
return val == kValue0 || val == kValue1;
@@ -74,8 +70,7 @@ const char* EnumToJsonString(TestEnum enm) {
struct DbusDeserialization : public testing::Test {
dbus::MessageRef msgref;
DbusDeserialization()
- : msgref(dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_CALL)) {
- }
+ : msgref(dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_CALL)) {}
};
TEST_F(DbusDeserialization, DeserializeBool) {
@@ -97,7 +92,7 @@ TEST_F(DbusDeserialization, DeserializeByte) {
}
{
dbus::MessageReader reader(msgref);
- Integer < uint8_t, 1, 220 > byte(&reader);
+ Integer<uint8_t, 1, 220> byte(&reader);
ASSERT_TRUE(byte.is_initialized());
ASSERT_TRUE(byte.is_valid());
ASSERT_EQ(byte, 200);
@@ -113,7 +108,7 @@ TEST_F(DbusDeserialization, DeserializeInt64) {
}
{
dbus::MessageReader reader(msgref);
- Integer < int64_t, -5, 220 > int64(&reader);
+ Integer<int64_t, -5, 220> int64(&reader);
ASSERT_TRUE(int64.is_initialized());
ASSERT_TRUE(int64.is_valid());
ASSERT_EQ(int64, -1);
@@ -129,7 +124,7 @@ TEST_F(DbusDeserialization, DeserializeFloat) {
}
{
dbus::MessageReader reader(msgref);
- Float < 3, 4 > pi(&reader);
+ Float<3, 4> pi(&reader);
ASSERT_TRUE(pi.is_initialized());
ASSERT_TRUE(pi.is_valid());
ASSERT_DOUBLE_EQ(pi, 3.14);
@@ -145,7 +140,7 @@ TEST_F(DbusDeserialization, DeserializeString) {
}
{
dbus::MessageReader reader(msgref);
- String < 3, 10 > hello(&reader);
+ String<3, 10> hello(&reader);
ASSERT_TRUE(hello.is_initialized());
ASSERT_TRUE(hello.is_valid());
ASSERT_EQ(std::string(hello), "Hello");
@@ -174,9 +169,9 @@ TEST_F(DbusDeserialization, DeserializeArray) {
{
dbus::MessageWriter writer(msgref);
std::string array_signature;
- rpc::DbusSignature<Integer<int32_t, 1, 50> >(&array_signature);
- dbus::MessageWriter array_writer(&writer, dbus::kArray,
- array_signature.c_str());
+ rpc::DbusSignature<Integer<int32_t, 1, 50>>(&array_signature);
+ dbus::MessageWriter array_writer(
+ &writer, dbus::kArray, array_signature.c_str());
array_writer.PutInt32(5);
array_writer.PutInt32(33);
}
@@ -190,7 +185,6 @@ TEST_F(DbusDeserialization, DeserializeArray) {
ASSERT_EQ(array.size(), 2u);
ASSERT_EQ(array[0], 5);
ASSERT_EQ(array[1], 33);
-
}
}
@@ -198,15 +192,15 @@ TEST_F(DbusDeserialization, DeserializeArrayOfArrays) {
{
dbus::MessageWriter writer(msgref);
std::string array_signature;
- rpc::DbusSignature<Array<Integer<int32_t, 1, 50>, 1, 5> >(&array_signature);
- dbus::MessageWriter array_writer(&writer, dbus::kArray,
- array_signature.c_str());
+ rpc::DbusSignature<Array<Integer<int32_t, 1, 50>, 1, 5>>(&array_signature);
+ dbus::MessageWriter array_writer(
+ &writer, dbus::kArray, array_signature.c_str());
int val = 5;
for (int i = 0; i < 2; ++i) {
std::string subarray_signature;
- rpc::DbusSignature<Integer<int32_t, 1, 50> >(&subarray_signature);
- dbus::MessageWriter subarray_wirter(&array_writer, dbus::kArray,
- subarray_signature.c_str());
+ rpc::DbusSignature<Integer<int32_t, 1, 50>>(&subarray_signature);
+ dbus::MessageWriter subarray_wirter(
+ &array_writer, dbus::kArray, subarray_signature.c_str());
subarray_wirter.PutInt32(val++);
subarray_wirter.PutInt32(val++);
@@ -226,7 +220,6 @@ TEST_F(DbusDeserialization, DeserializeArrayOfArrays) {
ASSERT_EQ(array[0][1], 6);
ASSERT_EQ(array[1][0], 7);
ASSERT_EQ(array[1][1], 8);
-
}
}
@@ -235,9 +228,9 @@ TEST_F(DbusDeserialization, DeserializeMap) {
dbus::MessageWriter writer(msgref);
std::string dict_signature;
rpc::DbusSignature<Map<Enum<TestEnum>, 1, 5>::value_type>(&dict_signature);
- dbus::MessageWriter array_writer(&writer, dbus::kArray,
- dict_signature.c_str());
- const char* keys[] = { "Hello", "World" };
+ dbus::MessageWriter array_writer(
+ &writer, dbus::kArray, dict_signature.c_str());
+ const char* keys[] = {"Hello", "World"};
int val = 0;
for (int i = 0; i < 2; ++i) {
dbus::MessageWriter dictval_wirter(&array_writer, dbus::kDictEntry, NULL);
@@ -255,7 +248,6 @@ TEST_F(DbusDeserialization, DeserializeMap) {
ASSERT_EQ(amap.size(), 2u);
ASSERT_EQ(amap["Hello"], kValue0);
ASSERT_EQ(amap["World"], kValue1);
-
}
}
@@ -283,7 +275,7 @@ TEST_F(DbusDeserialization, DeserializeOptionalString) {
}
{
dbus::MessageReader reader(msgref);
- Optional < String<1, 100> > readback(&reader);
+ Optional<String<1, 100>> readback(&reader);
ASSERT_TRUE(readback.is_initialized());
ASSERT_TRUE(readback.is_valid());
ASSERT_EQ(std::string(*readback), "Hello dear");
@@ -301,16 +293,14 @@ TEST_F(DbusDeserialization, DeserializeOptionalInt) {
}
{
dbus::MessageReader reader(msgref);
- Optional < Integer<int32_t, 1, 90>> readback(&reader);
+ Optional<Integer<int32_t, 1, 90>> readback(&reader);
ASSERT_FALSE(readback.is_initialized());
ASSERT_TRUE(readback.is_valid());
ASSERT_FALSE(reader.has_failed());
ASSERT_FALSE(reader.HasNext());
-
}
}
-
TEST_F(DbusDeserialization, SerializeDeserializeBool) {
{
Boolean true_bool(true);
@@ -330,13 +320,13 @@ TEST_F(DbusDeserialization, SerializeDeserializeBool) {
TEST_F(DbusDeserialization, SerializeDeserializeInt8t) {
{
- Integer < int8_t, 1, 100 > int8(42);
+ Integer<int8_t, 1, 100> int8(42);
dbus::MessageWriter writer(msgref);
int8.ToDbusWriter(&writer);
}
{
dbus::MessageReader reader(msgref);
- Integer < int8_t, 1, 100 > readback(&reader);
+ Integer<int8_t, 1, 100> readback(&reader);
ASSERT_TRUE(readback.is_initialized());
ASSERT_TRUE(readback.is_valid());
ASSERT_EQ(readback, 42);
@@ -347,13 +337,13 @@ TEST_F(DbusDeserialization, SerializeDeserializeInt8t) {
TEST_F(DbusDeserialization, BadSerializeDeserializeInt8t) {
{
- Integer < int8_t, 1, 12 > int8(42);
+ Integer<int8_t, 1, 12> int8(42);
dbus::MessageWriter writer(msgref);
int8.ToDbusWriter(&writer);
}
{
dbus::MessageReader reader(msgref);
- Integer < int8_t, 1, 12 > readback(&reader);
+ Integer<int8_t, 1, 12> readback(&reader);
ASSERT_TRUE(readback.is_initialized());
ASSERT_FALSE(readback.is_valid());
ASSERT_FALSE(reader.has_failed());
@@ -363,13 +353,13 @@ TEST_F(DbusDeserialization, BadSerializeDeserializeInt8t) {
TEST_F(DbusDeserialization, SerializeDeserializeInt64t) {
{
- Integer < int64_t, 1, 0xFFFFFFFFFF > int64(0xFFFFFFFFF1);
+ Integer<int64_t, 1, 0xFFFFFFFFFF> int64(0xFFFFFFFFF1);
dbus::MessageWriter writer(msgref);
int64.ToDbusWriter(&writer);
}
{
dbus::MessageReader reader(msgref);
- Integer < int64_t, 1, 0xFFFFFFFFFF > readback(&reader);
+ Integer<int64_t, 1, 0xFFFFFFFFFF> readback(&reader);
ASSERT_TRUE(readback.is_initialized());
ASSERT_TRUE(readback.is_valid());
ASSERT_EQ(readback, 0xFFFFFFFFF1);
@@ -378,16 +368,15 @@ TEST_F(DbusDeserialization, SerializeDeserializeInt64t) {
}
}
-
TEST_F(DbusDeserialization, SerializeDeserializeDouble) {
{
- Float < 1, 5 > flt(3.14);
+ Float<1, 5> flt(3.14);
dbus::MessageWriter writer(msgref);
flt.ToDbusWriter(&writer);
}
{
dbus::MessageReader reader(msgref);
- Float < 1, 5 > readback(&reader);
+ Float<1, 5> readback(&reader);
ASSERT_TRUE(readback.is_initialized());
ASSERT_TRUE(readback.is_valid());
ASSERT_DOUBLE_EQ(readback, 3.14);
@@ -398,13 +387,13 @@ TEST_F(DbusDeserialization, SerializeDeserializeDouble) {
TEST_F(DbusDeserialization, SerializeDeserializeString) {
{
- String < 1, 12 > hello("Hello");
+ String<1, 12> hello("Hello");
dbus::MessageWriter writer(msgref);
hello.ToDbusWriter(&writer);
}
{
dbus::MessageReader reader(msgref);
- String < 1, 12 > readback(&reader);
+ String<1, 12> readback(&reader);
ASSERT_TRUE(readback.is_initialized());
ASSERT_TRUE(readback.is_valid());
ASSERT_EQ(std::string(readback), "Hello");
@@ -505,61 +494,61 @@ TEST(ValidatedTypes, TestBooleanDbusSignature) {
TEST(ValidatedTypes, TestIntDbusSignature) {
std::string sign;
- DbusSignature<Integer<int32_t, 1, 2> >(&sign);
+ DbusSignature<Integer<int32_t, 1, 2>>(&sign);
ASSERT_EQ(sign, "i");
}
TEST(ValidatedTypes, TestFloatDbusSignature) {
std::string sign;
- DbusSignature<Float<1, 2> >(&sign);
+ DbusSignature<Float<1, 2>>(&sign);
ASSERT_EQ(sign, "d");
}
TEST(ValidatedTypes, TestStringDbusSignature) {
std::string sign;
- DbusSignature<String<1, 2> >(&sign);
+ DbusSignature<String<1, 2>>(&sign);
ASSERT_EQ(sign, "s");
}
TEST(ValidatedTypes, TestEnumDbusSignature) {
std::string sign;
- DbusSignature<Enum<TestEnum> >(&sign);
+ DbusSignature<Enum<TestEnum>>(&sign);
ASSERT_EQ(sign, "i");
}
TEST(ValidatedTypes, TestIntArrayDbusSignature) {
std::string sign;
- DbusSignature<Array<Integer<int32_t, 1, 2>, 1, 3> >(&sign);
+ DbusSignature<Array<Integer<int32_t, 1, 2>, 1, 3>>(&sign);
ASSERT_EQ(sign, "ai");
}
TEST(ValidatedTypes, TestIntArrayArrayDbusSignature) {
std::string sign;
- DbusSignature<Array<Array<Integer<int32_t, 1, 2>, 1, 3>, 4, 5> >(&sign);
+ DbusSignature<Array<Array<Integer<int32_t, 1, 2>, 1, 3>, 4, 5>>(&sign);
ASSERT_EQ(sign, "aai");
}
TEST(ValidatedTypes, TestMapDbusSignature) {
std::string sign;
- DbusSignature<Map<Integer<int32_t, 1, 2>, 3, 4> >(&sign);
+ DbusSignature<Map<Integer<int32_t, 1, 2>, 3, 4>>(&sign);
ASSERT_EQ(sign, "a{si}");
}
TEST(ValidatedTypes, TestMandatoryEnumDbusSignature) {
std::string sign;
- DbusSignature<Enum<TestEnum> >(&sign);
+ DbusSignature<Enum<TestEnum>>(&sign);
ASSERT_EQ(sign, "i");
}
TEST(ValidatedTypes, TestOptionalEnumDbusSignature) {
std::string sign;
- DbusSignature<Optional<Enum<TestEnum> > >(&sign);
+ DbusSignature<Optional<Enum<TestEnum>>>(&sign);
ASSERT_EQ(sign, "(bi)");
}
TEST(ValidatedTypes, TestOptionalFloatArrayDbusSignature) {
std::string sign;
- DbusSignature<Optional<Array<Float<1, 2>, 3, 4> > >(&sign);
+ DbusSignature<Optional<Array<Float<1, 2>, 3, 4>>>(&sign);
ASSERT_EQ(sign, "(bad)");
}
@@ -571,9 +560,7 @@ TEST(DbusMessageConstructionTest, DbusMessageConstruction) {
class DbusTest : public testing::Test {
public:
dbus::MessageRef msgref;
- DbusTest()
- : msgref(dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_CALL)) {
- }
+ DbusTest() : msgref(dbus_message_new(DBUS_MESSAGE_TYPE_METHOD_CALL)) {}
};
TEST_F(DbusTest, DbusWriterConstructionTest) {
@@ -637,8 +624,8 @@ TEST_F(DbusTest, DbusMultipleParamsReadWrite) {
TEST_F(DbusTest, DbusArrayTest) {
{
dbus::MessageWriter writer(msgref);
- dbus::MessageWriter array_writer(&writer, dbus::kArray,
- DBUS_TYPE_INT16_AS_STRING);
+ dbus::MessageWriter array_writer(
+ &writer, dbus::kArray, DBUS_TYPE_INT16_AS_STRING);
array_writer.PutInt16(3);
array_writer.PutInt16(4);
array_writer.PutInt16(5);
diff --git a/src/components/rpc_base/test/rpc_base_json_test.cc b/src/components/rpc_base/test/rpc_base_json_test.cc
index 3a536937ba..07ac0418e0 100644
--- a/src/components/rpc_base/test/rpc_base_json_test.cc
+++ b/src/components/rpc_base/test/rpc_base_json_test.cc
@@ -39,11 +39,7 @@ using namespace rpc;
using Json::Value;
namespace {
-enum TestEnum {
- kValue0,
- kValue1,
- kInvalidValue
-};
+enum TestEnum { kValue0, kValue1, kInvalidValue };
bool EnumFromJsonString(const std::string& value, TestEnum* enm) {
if (value == "kValue0") {
@@ -58,10 +54,13 @@ bool EnumFromJsonString(const std::string& value, TestEnum* enm) {
}
const char* EnumToJsonString(TestEnum enm) {
- switch(enm) {
- case kValue0: return "kValue0";
- case kValue1: return "kValue1";
- default: return "UNKNOWN";
+ switch (enm) {
+ case kValue0:
+ return "kValue0";
+ case kValue1:
+ return "kValue1";
+ default:
+ return "UNKNOWN";
}
}
@@ -272,7 +271,7 @@ TEST(ValidatedTypesJson, MandatoryMapNullTest) {
TEST(ValidatedTypesJson, OptionalMapAbsentValueTest) {
Value* novalue = NULL;
- Optional< Map<String<1, 32>, 0, 5> > map(novalue);
+ Optional<Map<String<1, 32>, 0, 5> > map(novalue);
ASSERT_FALSE(map.is_initialized());
ASSERT_TRUE(map.is_valid());
}
@@ -305,7 +304,7 @@ TEST(ValidatedTypesJson, MapFromNonArrayJsonTest) {
TEST(ValidatedTypesJson, OptionalBoolFromJsonTest) {
Value bool_value(true);
- Optional< Boolean > optional_bool;
+ Optional<Boolean> optional_bool;
*optional_bool = Boolean(&bool_value);
ASSERT_TRUE(optional_bool.is_initialized());
ASSERT_TRUE(optional_bool.is_valid());
@@ -316,7 +315,7 @@ TEST(ValidatedTypesJson, OptionalBoolFromJsonTest) {
TEST(ValidatedTypesJson, OptionalBoolFromAbsentValueTest) {
Value* none = NULL;
- Optional< Boolean > optional_bool;
+ Optional<Boolean> optional_bool;
*optional_bool = Boolean(none);
ASSERT_FALSE(optional_bool.is_initialized());
// It is ok for Optional value to be absent
@@ -324,7 +323,7 @@ TEST(ValidatedTypesJson, OptionalBoolFromAbsentValueTest) {
}
TEST(ValidatedTypesJson, OptionalBoolFromNullValueTest) {
- Optional< Boolean > optional_bool;
+ Optional<Boolean> optional_bool;
*optional_bool = Boolean(&Value::null);
ASSERT_TRUE(optional_bool.is_initialized());
// Optional values should not be absent
@@ -332,7 +331,7 @@ TEST(ValidatedTypesJson, OptionalBoolFromNullValueTest) {
}
TEST(ValidatedTypesJson, NullableIntFromNullValueTest) {
- Nullable< Integer<int8_t, 1, 15> > nullable_int(&Value::null);
+ Nullable<Integer<int8_t, 1, 15> > nullable_int(&Value::null);
ASSERT_TRUE(nullable_int.is_initialized());
ASSERT_TRUE(nullable_int.is_valid());
ASSERT_TRUE(nullable_int.is_null());
@@ -340,7 +339,7 @@ TEST(ValidatedTypesJson, NullableIntFromNullValueTest) {
TEST(ValidatedTypesJson, NullableIntFromNonNullValueTest) {
Value json(3);
- Nullable< Integer<int8_t, 1, 15> > nullable_int(&json);
+ Nullable<Integer<int8_t, 1, 15> > nullable_int(&json);
ASSERT_TRUE(nullable_int.is_initialized());
ASSERT_TRUE(nullable_int.is_valid());
ASSERT_FALSE(nullable_int.is_null());
@@ -349,7 +348,7 @@ TEST(ValidatedTypesJson, NullableIntFromNonNullValueTest) {
TEST(ValidatedTypesJson, NullableIntFromAbsentValueTest) {
Value* noval = NULL;
- Nullable< Integer<int8_t, 1, 15> > nullable_int(noval);
+ Nullable<Integer<int8_t, 1, 15> > nullable_int(noval);
ASSERT_FALSE(nullable_int.is_initialized());
ASSERT_FALSE(nullable_int.is_valid());
ASSERT_FALSE(nullable_int.is_null());
@@ -357,8 +356,8 @@ TEST(ValidatedTypesJson, NullableIntFromAbsentValueTest) {
TEST(ValidatedTypesJson, OptionalIntFromJsonTest) {
Value int_value(42);
- Optional< Integer<int64_t, 42, 43> > optional_int;
- *optional_int = Integer<int64_t, 42, 43> (&int_value);
+ Optional<Integer<int64_t, 42, 43> > optional_int;
+ *optional_int = Integer<int64_t, 42, 43>(&int_value);
ASSERT_TRUE(optional_int.is_initialized());
ASSERT_TRUE(optional_int.is_valid());
Value readback = optional_int->ToJsonValue();
@@ -366,8 +365,4 @@ TEST(ValidatedTypesJson, OptionalIntFromJsonTest) {
ASSERT_EQ(readback.asInt(), 42);
}
-
} // namespace test
-
-
-
diff --git a/src/components/rpc_base/test/rpc_base_test.cc b/src/components/rpc_base/test/rpc_base_test.cc
index 553dacb85d..37a64b319e 100644
--- a/src/components/rpc_base/test/rpc_base_test.cc
+++ b/src/components/rpc_base/test/rpc_base_test.cc
@@ -40,11 +40,7 @@ using namespace rpc;
namespace {
-enum TestEnum {
- kValue0,
- kValue1,
- kInvalidValue
-};
+enum TestEnum { kValue0, kValue1, kInvalidValue };
bool IsValidEnum(TestEnum val) {
return val == kValue0 || val == kValue1;
@@ -190,7 +186,7 @@ TEST(ValidatedTypes, TestArrayInitializingConstructor) {
}
TEST(ValidatedTypes, TestOptionalEmptyArray) {
- Optional< Array<Integer<int8_t, 0, 10>, 0, 5> > ai;
+ Optional<Array<Integer<int8_t, 0, 10>, 0, 5> > ai;
ASSERT_RPCTYPE_VALID(ai);
ASSERT_FALSE(ai.is_initialized());
Json::FastWriter fw;
@@ -220,10 +216,10 @@ TEST(ValidatedTypes, TestMap) {
}
TEST(ValidatedTypes, TestMapInitializingConstructor) {
- std::map< std::string, std::string > init_map;
+ std::map<std::string, std::string> init_map;
init_map["a"] = "Hello";
init_map["b"] = "World";
- Map<String<1, 6>, 2, 10 > map(init_map);
+ Map<String<1, 6>, 2, 10> map(init_map);
ASSERT_TRUE(map.is_initialized());
ASSERT_RPCTYPE_VALID(map);
}
@@ -251,7 +247,7 @@ TEST(ValidatedTypes, TestEnumConstructor) {
}
TEST(ValidatedTypes, TestNullableConstructor) {
- Nullable< Integer<int8_t, 2, 10> >nullable_int;
+ Nullable<Integer<int8_t, 2, 10> > nullable_int;
ASSERT_FALSE(nullable_int.is_initialized());
ASSERT_FALSE(nullable_int.is_null());
ASSERT_FALSE(nullable_int.is_valid());
@@ -266,7 +262,7 @@ TEST(ValidatedTypes, TestNullableConstructor) {
}
TEST(ValidatedTypes, TestOptionalNullableConstructor) {
- Optional< Nullable< Integer<int8_t, 2, 10> > > optional_nullable_int;
+ Optional<Nullable<Integer<int8_t, 2, 10> > > optional_nullable_int;
ASSERT_FALSE(optional_nullable_int.is_initialized());
ASSERT_FALSE(optional_nullable_int->is_null());
ASSERT_RPCTYPE_VALID(optional_nullable_int);
@@ -286,7 +282,7 @@ TEST(ValidatedTypes, TestOptionalNullableConstructor) {
}
TEST(ValidatedTypes, TestOptionalConstructor) {
- Optional< Integer<int16_t, 3, 15> > optional_int;
+ Optional<Integer<int16_t, 3, 15> > optional_int;
ASSERT_FALSE(optional_int.is_initialized());
ASSERT_RPCTYPE_VALID(optional_int);
*optional_int = 42;
@@ -300,7 +296,7 @@ TEST(ValidatedTypes, TestOptionalConstructor) {
}
TEST(ValidatedTypes, TestOptionalInitializingConstructor) {
- Optional< String<1, 12> > optional_string("Hello world");
+ Optional<String<1, 12> > optional_string("Hello world");
ASSERT_TRUE(optional_string.is_initialized());
ASSERT_RPCTYPE_VALID(optional_string);
std::string value = *optional_string;
@@ -334,7 +330,7 @@ TEST(ValidatedTypes, ReportIncorrectInitializedIntType) {
}
TEST(ValidatedTypes, ReportUninitializedOptionalType) {
- Optional< Integer<int8_t, 1, 3> > val;
+ Optional<Integer<int8_t, 1, 3> > val;
ASSERT_RPCTYPE_VALID(val);
ValidationReport report("val");
val.ReportErrors(&report);
@@ -342,7 +338,7 @@ TEST(ValidatedTypes, ReportUninitializedOptionalType) {
}
TEST(ValidatedTypes, ReportIncorrectInitializedOptionalType) {
- Optional< Integer<int8_t, 1, 3> > val(5);
+ Optional<Integer<int8_t, 1, 3> > val(5);
ASSERT_FALSE(val.is_valid());
ValidationReport report("val");
val.ReportErrors(&report);
@@ -350,7 +346,7 @@ TEST(ValidatedTypes, ReportIncorrectInitializedOptionalType) {
}
TEST(ValidatedTypes, ReportUninitializedNullableIntType) {
- Nullable< Integer<int8_t, 1, 3> > val;
+ Nullable<Integer<int8_t, 1, 3> > val;
ASSERT_FALSE(val.is_valid());
ValidationReport report("val");
val.ReportErrors(&report);
@@ -358,7 +354,7 @@ TEST(ValidatedTypes, ReportUninitializedNullableIntType) {
}
TEST(ValidatedTypes, ReportNullInitializedNullableIntType) {
- Nullable< Integer<int8_t, 1, 3> > val;
+ Nullable<Integer<int8_t, 1, 3> > val;
val.set_to_null();
ASSERT_RPCTYPE_VALID(val);
ValidationReport report("val");
@@ -367,7 +363,7 @@ TEST(ValidatedTypes, ReportNullInitializedNullableIntType) {
}
TEST(ValidatedTypes, ReportNoninitializedIntArray) {
- Array< Enum<TestEnum>, 1, 3 > array;
+ Array<Enum<TestEnum>, 1, 3> array;
ASSERT_FALSE(array.is_valid());
ValidationReport report("array");
array.ReportErrors(&report);
@@ -375,7 +371,7 @@ TEST(ValidatedTypes, ReportNoninitializedIntArray) {
}
TEST(ValidatedTypes, ReportIncorrectlyInitializedIntArray1) {
- Array< Integer<int8_t, 1, 10>, 1, 3 > array;
+ Array<Integer<int8_t, 1, 10>, 1, 3> array;
array.push_back(11);
ASSERT_FALSE(array.is_valid());
ValidationReport report("array");
@@ -384,7 +380,7 @@ TEST(ValidatedTypes, ReportIncorrectlyInitializedIntArray1) {
}
TEST(ValidatedTypes, ReportIncorrectlyInitializedIntArray2) {
- Array< Integer<int8_t, 1, 10>, 1, 3 > array;
+ Array<Integer<int8_t, 1, 10>, 1, 3> array;
array.push_back(1);
array.push_back(2);
array.push_back(3);
@@ -396,42 +392,47 @@ TEST(ValidatedTypes, ReportIncorrectlyInitializedIntArray2) {
}
TEST(ValidatedTypes, ReportIncorrectlyInitializedArray3) {
- Array< Integer<int8_t, 1, 10>, 1, 3 > array;
+ Array<Integer<int8_t, 1, 10>, 1, 3> array;
array.push_back(1);
array.push_back(2);
array.push_back(42);
array.push_back(4);
ValidationReport report("array");
array.ReportErrors(&report);
- ASSERT_EQ("array: array has invalid size\n"
- "array[2]: value initialized incorrectly\n", PrettyFormat(report));
+ ASSERT_EQ(
+ "array: array has invalid size\n"
+ "array[2]: value initialized incorrectly\n",
+ PrettyFormat(report));
}
TEST(ValidatedTypes, ReportUninitializedMap) {
- Map< Integer<int8_t, 1, 10>, 1, 3 > map;
+ Map<Integer<int8_t, 1, 10>, 1, 3> map;
ValidationReport report("map");
map.ReportErrors(&report);
ASSERT_EQ("map: object is not initialized\n", PrettyFormat(report));
}
TEST(ValidatedTypes, ReportIncorrectlyInitializedMap1) {
- Map< Integer<int8_t, 1, 10>, 1, 3 > map;
+ Map<Integer<int8_t, 1, 10>, 1, 3> map;
map["aha"] = 42;
ValidationReport report("map");
map.ReportErrors(&report);
- ASSERT_EQ("map[\"aha\"]: value initialized incorrectly\n", PrettyFormat(report));
+ ASSERT_EQ("map[\"aha\"]: value initialized incorrectly\n",
+ PrettyFormat(report));
}
TEST(ValidatedTypes, ReportIncorrectlyInitializedMap2) {
- Map< Integer<int8_t, 1, 10>, 1, 3 > map;
+ Map<Integer<int8_t, 1, 10>, 1, 3> map;
map["aha"] = 3;
map["haha"] = 12;
map["muhahaha"] = 17;
map["muhahaha"] = 22;
ValidationReport report("map");
map.ReportErrors(&report);
- ASSERT_EQ("map[\"haha\"]: value initialized incorrectly\n"
- "map[\"muhahaha\"]: value initialized incorrectly\n", PrettyFormat(report));
+ ASSERT_EQ(
+ "map[\"haha\"]: value initialized incorrectly\n"
+ "map[\"muhahaha\"]: value initialized incorrectly\n",
+ PrettyFormat(report));
}
} // namespace codegen
diff --git a/src/components/rpc_base/test/validation_report_test.cc b/src/components/rpc_base/test/validation_report_test.cc
index 1493de3957..e7dded342c 100644
--- a/src/components/rpc_base/test/validation_report_test.cc
+++ b/src/components/rpc_base/test/validation_report_test.cc
@@ -50,10 +50,12 @@ class ValidationReportTest : public testing::Test {
static const std::string parent_object_name_;
static void SetUpTestCase() {
- report_ = new ValidationReport(object_name_);
- report_2 = new ValidationReport(object_name_2);
+ report_ = new ValidationReport(object_name_);
+ report_2 = new ValidationReport(object_name_2);
+ }
+ virtual void TearDown() {
+ ClearReports();
}
- virtual void TearDown() { ClearReports(); }
void ClearReports() {
ValidationReports& temp =
@@ -61,16 +63,17 @@ class ValidationReportTest : public testing::Test {
temp.clear();
}
- void GeneratePrettyFormatResult(std::string& result, const std::string& parent_name,
- const std::string& obj_name, const std::string& val_info) {
+ void GeneratePrettyFormatResult(std::string& result,
+ const std::string& parent_name,
+ const std::string& obj_name,
+ const std::string& val_info) {
std::string temp;
if (obj_name[0] != '[') {
- temp = ".";
+ temp = ".";
} else {
- temp = "";
+ temp = "";
}
- result = parent_name + temp + obj_name + ":" + " " +
- val_info + "\n";
+ result = parent_name + temp + obj_name + ":" + " " + val_info + "\n";
}
void ClearValidationInfo() {
@@ -101,7 +104,6 @@ const std::string ValidationReportTest::test_validation_info_ =
"test_validation_info";
const std::string ValidationReportTest::parent_object_name_ = "test_parent";
-
TEST_F(ValidationReportTest, Ctor_and_object_name_test_ExpectDataCorrect) {
EXPECT_EQ(object_name_, report_->object_name());
}
@@ -145,9 +147,11 @@ TEST_F(ValidationReportTest, PrettyFormat_ExpectDataCorrect) {
impl::PrettyFormat(*report_, parent_object_name_, &result1);
impl::PrettyFormat(*report_2, parent_object_name_, &result2);
std::string temp1;
- GeneratePrettyFormatResult(temp1, parent_object_name_, object_name_, test_validation_info_);
+ GeneratePrettyFormatResult(
+ temp1, parent_object_name_, object_name_, test_validation_info_);
std::string temp2;
- GeneratePrettyFormatResult(temp2, parent_object_name_, object_name_2, test_validation_info_);
+ GeneratePrettyFormatResult(
+ temp2, parent_object_name_, object_name_2, test_validation_info_);
// Checks
EXPECT_EQ(temp1, result1);
EXPECT_EQ(temp2, result2);
diff --git a/src/components/security_manager/CMakeLists.txt b/src/components/security_manager/CMakeLists.txt
index 6973a98e07..3cc6178931 100644
--- a/src/components/security_manager/CMakeLists.txt
+++ b/src/components/security_manager/CMakeLists.txt
@@ -33,7 +33,9 @@ include_directories(
include/
${COMPONENTS_DIR}/protocol_handler/include/
${COMPONENTS_DIR}/connection_handler/include
+ ${COMPONENTS_DIR}/config_profile/include/
${COMPONENTS_DIR}/utils/include/
+ ${COMPONENTS_DIR}/application_manager/include/
${JSONCPP_INCLUDE_DIRECTORY}
${CMAKE_SOURCE_DIR}/src/thirdPartyLibs/jsoncpp/include
${APR_INCLUDE_DIRECTORY}
@@ -51,4 +53,4 @@ target_link_libraries(SecurityManager crypto ssl ProtocolHandler jsoncpp Protoco
if(BUILD_TESTS)
add_subdirectory(test)
-endif() \ No newline at end of file
+endif()
diff --git a/src/components/security_manager/include/security_manager/crypto_manager_impl.h b/src/components/security_manager/include/security_manager/crypto_manager_impl.h
index 43bb63ef67..6aea2e28b1 100644
--- a/src/components/security_manager/include/security_manager/crypto_manager_impl.h
+++ b/src/components/security_manager/include/security_manager/crypto_manager_impl.h
@@ -42,66 +42,97 @@
#include "security_manager/crypto_manager.h"
#include "security_manager/ssl_context.h"
+#include "security_manager/security_manager_settings.h"
+
#include "utils/macro.h"
#include "utils/lock.h"
+#include "utils/shared_ptr.h"
namespace security_manager {
class CryptoManagerImpl : public CryptoManager {
private:
class SSLContextImpl : public SSLContext {
public:
- SSLContextImpl(SSL *conn, Mode mode);
+ SSLContextImpl(SSL* conn, Mode mode, size_t maximum_payload_size);
+ ~SSLContextImpl();
virtual HandshakeResult StartHandshake(const uint8_t** const out_data,
- size_t *out_data_size);
- virtual HandshakeResult DoHandshakeStep(const uint8_t *const in_data,
+ size_t* out_data_size);
+ virtual HandshakeResult DoHandshakeStep(const uint8_t* const in_data,
size_t in_data_size,
const uint8_t** const out_data,
- size_t *out_data_size);
- virtual bool Encrypt(const uint8_t *const in_data, size_t in_data_size,
- const uint8_t ** const out_data, size_t *out_data_size);
- virtual bool Decrypt(const uint8_t *const in_data, size_t in_data_size,
- const uint8_t ** const out_data, size_t *out_data_size);
- virtual bool IsInitCompleted() const;
- virtual bool IsHandshakePending() const;
- virtual size_t get_max_block_size(size_t mtu) const;
- virtual std::string LastError() const;
- virtual ~SSLContextImpl();
+ size_t* out_data_size) OVERRIDE;
+ bool Encrypt(const uint8_t* const in_data,
+ size_t in_data_size,
+ const uint8_t** const out_data,
+ size_t* out_data_size) OVERRIDE;
+ bool Decrypt(const uint8_t* const in_data,
+ size_t in_data_size,
+ const uint8_t** const out_data,
+ size_t* out_data_size) OVERRIDE;
+ bool IsInitCompleted() const OVERRIDE;
+ bool IsHandshakePending() const OVERRIDE;
+ size_t get_max_block_size(size_t mtu) const OVERRIDE;
+ std::string LastError() const OVERRIDE;
+ void ResetConnection() OVERRIDE;
+ void SetHandshakeContext(const HandshakeContext& hsh_ctx) OVERRIDE;
+
+ void PrintCertData(X509* cert, const std::string& cert_owner);
private:
- typedef size_t(*BlockSizeGetter)(size_t);
+ void PrintCertInfo();
+ HandshakeResult CheckCertContext();
+ bool ReadHandshakeData(const uint8_t** const out_data,
+ size_t* out_data_size);
+ bool WriteHandshakeData(const uint8_t* const in_data, size_t in_data_size);
+ HandshakeResult PerformHandshake();
+ typedef size_t (*BlockSizeGetter)(size_t);
void EnsureBufferSizeEnough(size_t size);
- SSL *connection_;
- BIO *bioIn_;
- BIO *bioOut_;
- BIO *bioFilter_;
+ void SetHandshakeError(const int error);
+ HandshakeResult openssl_error_convert_to_internal(const long error);
+
+ std::string GetTextBy(X509_NAME* name, int object) const;
+
+ SSL* connection_;
+ BIO* bioIn_;
+ BIO* bioOut_;
+ BIO* bioFilter_;
mutable sync_primitives::Lock bio_locker;
size_t buffer_size_;
- uint8_t *buffer_;
+ uint8_t* buffer_;
bool is_handshake_pending_;
Mode mode_;
+ mutable std::string last_error_;
BlockSizeGetter max_block_size_;
static std::map<std::string, BlockSizeGetter> max_block_sizes;
static std::map<std::string, BlockSizeGetter> create_max_block_sizes();
+ HandshakeContext hsh_context_;
DISALLOW_COPY_AND_ASSIGN(SSLContextImpl);
};
public:
- CryptoManagerImpl();
- virtual bool Init(Mode mode,
- Protocol protocol,
- const std::string &cert_filename,
- const std::string &key_filename,
- const std::string &ciphers_list,
- bool verify_peer);
- virtual void Finish();
- virtual SSLContext *CreateSSLContext();
- virtual void ReleaseSSLContext(SSLContext *context);
- virtual std::string LastError() const;
+ explicit CryptoManagerImpl(
+ const utils::SharedPtr<const CryptoManagerSettings> set);
+ ~CryptoManagerImpl();
+
+ bool Init() OVERRIDE;
+ bool OnCertificateUpdated(const std::string& data) OVERRIDE;
+ SSLContext* CreateSSLContext() OVERRIDE;
+ void ReleaseSSLContext(SSLContext* context) OVERRIDE;
+ std::string LastError() const OVERRIDE;
+ virtual bool IsCertificateUpdateRequired() const OVERRIDE;
+ virtual const CryptoManagerSettings& get_settings() const OVERRIDE;
private:
- SSL_CTX *context_;
- Mode mode_;
+ bool set_certificate(const std::string& cert_data);
+
+ int pull_number_from_buf(char* buf, int* idx);
+ void asn1_time_to_tm(ASN1_TIME* time);
+
+ const utils::SharedPtr<const CryptoManagerSettings> settings_;
+ SSL_CTX* context_;
+ mutable struct tm expiration_time_;
static uint32_t instance_count_;
+ static sync_primitives::Lock instance_lock_;
DISALLOW_COPY_AND_ASSIGN(CryptoManagerImpl);
};
} // namespace security_manager
diff --git a/src/components/security_manager/include/security_manager/crypto_manager_settings_impl.h b/src/components/security_manager/include/security_manager/crypto_manager_settings_impl.h
new file mode 100644
index 0000000000..1e4699b77a
--- /dev/null
+++ b/src/components/security_manager/include/security_manager/crypto_manager_settings_impl.h
@@ -0,0 +1,65 @@
+
+#ifndef SRC_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_CRYPTO_MANAGER_SETTINGS_IMPL_H_
+#define SRC_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_CRYPTO_MANAGER_SETTINGS_IMPL_H_
+#include "security_manager/security_manager_settings.h"
+#include "config_profile/profile.h"
+
+namespace security_manager {
+
+class CryptoManagerSettingsImpl : public CryptoManagerSettings {
+ public:
+ CryptoManagerSettingsImpl(const profile::Profile& profile,
+ const std::string& certificate_data)
+ : profile_(profile), certificate_data_(certificate_data) {}
+
+ // CryptoManagerSettings interface
+ Mode security_manager_mode() const OVERRIDE {
+ return profile_.ssl_mode() == "SERVER" ? security_manager::SERVER
+ : security_manager::CLIENT;
+ }
+ Protocol security_manager_protocol_name() const OVERRIDE {
+ CREATE_LOGGERPTR_LOCAL(logger_, "SecurityManager")
+
+ const std::string& protocol_str = profile_.security_manager_protocol_name();
+ if (protocol_str == "TLSv1.0") {
+ return security_manager::TLSv1;
+ }
+ if (protocol_str == "TLSv1.1") {
+ return security_manager::TLSv1_1;
+ }
+ if (protocol_str == "TLSv1.2") {
+ return security_manager::TLSv1_2;
+ }
+ if (protocol_str == "SSLv3") {
+ return security_manager::SSLv3;
+ }
+ LOG4CXX_ERROR(
+ logger_,
+ "Unknown protocol: " << profile_.security_manager_protocol_name());
+ return static_cast<security_manager::Protocol>(-1);
+ }
+ bool verify_peer() const OVERRIDE {
+ return profile_.verify_peer();
+ }
+ const std::string& certificate_data() const OVERRIDE {
+ return certificate_data_;
+ }
+ const std::string& ciphers_list() const OVERRIDE {
+ return profile_.ciphers_list();
+ }
+ const std::string& ca_cert_path() const OVERRIDE {
+ return profile_.ca_cert_path();
+ }
+ size_t update_before_hours() const OVERRIDE {
+ return profile_.update_before_hours();
+ }
+ size_t maximum_payload_size() const OVERRIDE {
+ return profile_.maximum_payload_size();
+ }
+
+ private:
+ const profile::Profile& profile_;
+ const std::string certificate_data_;
+};
+}
+#endif // SRC_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_CRYPTO_MANAGER_SETTINGS_IMPL_H_
diff --git a/src/components/security_manager/include/security_manager/security_manager_impl.h b/src/components/security_manager/include/security_manager/security_manager_impl.h
index 2aa03087eb..d4231ffaa0 100644
--- a/src/components/security_manager/include/security_manager/security_manager_impl.h
+++ b/src/components/security_manager/include/security_manager/security_manager_impl.h
@@ -51,9 +51,10 @@ namespace security_manager {
* \brief SecurityMessageQueue and SecurityMessageLoop are support typedefs
* for thread working
*/
-struct SecurityMessage: public SecurityQueryPtr {
- explicit SecurityMessage(const SecurityQueryPtr &message)
- : SecurityQueryPtr(message) {}
+struct SecurityMessage : public SecurityQueryPtr {
+ SecurityMessage() {}
+ explicit SecurityMessage(const SecurityQueryPtr& message)
+ : SecurityQueryPtr(message) {}
// PrioritizedQueue requires this method to decide which priority to assign
size_t PriorityOrder() const {
return 0;
@@ -65,9 +66,8 @@ typedef threads::MessageLoopThread<SecurityMessageQueue> SecurityMessageLoop;
/**
* \brief SecurityManagerImpl class implements SecurityManager interface
*/
-class SecurityManagerImpl
- : public SecurityManager,
- public SecurityMessageLoop::Handler {
+class SecurityManagerImpl : public SecurityManager,
+ public SecurityMessageLoop::Handler {
public:
/**
* \brief Constructor
@@ -78,7 +78,8 @@ class SecurityManagerImpl
* Overriden ProtocolObserver::OnMessageReceived method
* \param message Message with supporting params received
*/
- void OnMessageReceived(const ::protocol_handler::RawMessagePtr message) OVERRIDE;
+ void OnMessageReceived(
+ const ::protocol_handler::RawMessagePtr message) OVERRIDE;
/**
* \brief Post message to Mobile Application
* Empty *overriden ProtocolObserver::OnMessageReceived method
@@ -91,28 +92,29 @@ class SecurityManagerImpl
* \param session_observer pointer to object of the class implementing
*/
void set_session_observer(
- protocol_handler::SessionObserver *observer) OVERRIDE;
+ protocol_handler::SessionObserver* observer) OVERRIDE;
/**
* \brief Sets pointer for Protocol Handler layer for sending
* \param protocol_handler pointer to object of the class implementing
*/
void set_protocol_handler(
- protocol_handler::ProtocolHandler *protocol_handler_) OVERRIDE;
+ protocol_handler::ProtocolHandler* protocol_handler_) OVERRIDE;
/**
* \brief Sets pointer for CryptoManager for handling SSLContext
* \param crypto_manager pointer to object of the class implementing
*/
- void set_crypto_manager(CryptoManager *crypto_manager) OVERRIDE;
+ void set_crypto_manager(CryptoManager* crypto_manager) OVERRIDE;
/**
* \brief Sends InternallError with text message to mobile application
- * \param connection_key Unique key used by other components as session identifier
+ * \param connection_key Unique key used by other components as session
+ * identifier
* \param error_id unique error identifier
* \param erorr_text SSL impelmentation error text
* \param seq_number received from Mobile Application
*/
void SendInternalError(const uint32_t connection_key,
- const uint8_t &error_id,
- const std::string &erorr_text,
+ const uint8_t& error_id,
+ const std::string& erorr_text,
const uint32_t seq_number) OVERRIDE;
using SecurityManager::SendInternalError;
@@ -127,10 +129,11 @@ class SecurityManagerImpl
/**
* \brief Create new SSLContext for connection or return exists
* Do not notify listeners, send security error on occure
- * \param connection_key Unique key used by other components as session identifier
+ * \param connection_key Unique key used by other components as session
+ * identifier
* @return new \c SSLContext or \c NULL on any error
*/
- SSLContext *CreateSSLContext(const uint32_t &connection_key) OVERRIDE;
+ SSLContext* CreateSSLContext(const uint32_t& connection_key) OVERRIDE;
/**
* \brief Start handshake as SSL client
@@ -140,50 +143,61 @@ class SecurityManagerImpl
/**
* \brief Add/Remove for SecurityManagerListener
*/
- void AddListener(SecurityManagerListener *const listener) OVERRIDE;
- void RemoveListener(SecurityManagerListener *const listener) OVERRIDE;
+ void AddListener(SecurityManagerListener* const listener) OVERRIDE;
+ void RemoveListener(SecurityManagerListener* const listener) OVERRIDE;
/**
* \brief Notifiers for listeners
- * \param connection_key Unique key used by other components as session identifier
+ * \param connection_key Unique key used by other components as session
+ * identifier
* \param success result of connection protection
*/
- void NotifyListenersOnHandshakeDone(const uint32_t &connection_key,
- const bool success);
+ void NotifyListenersOnHandshakeDone(const uint32_t& connection_key,
+ SSLContext::HandshakeResult error);
+
+ /**
+ * @brief Notifiers for listeners.
+ * Allows to notify that certificate should be updated
+ */
+ void NotifyOnCertififcateUpdateRequired();
+
/**
* @brief SecurityConfigSection
* @return Session name in config file
*/
- static const char *ConfigSection();
+ static const char* ConfigSection();
+
private:
/**
* \brief Sends Handshake binary data to mobile application
- * \param connection_key Unique key used by other components as session identifier
+ * \param connection_key Unique key used by other components as session
+ * identifier
* \param data pointer to binary data array
* \param data_size size of binary data array
* \param seq_number received from Mobile Application
*/
void SendHandshakeBinData(const uint32_t connection_key,
- const uint8_t *const data,
+ const uint8_t* const data,
const size_t data_size,
const uint32_t seq_number = 0);
/**
* \brief Parse SecurityMessage as HandshakeData request
* \param inMessage SecurityMessage with binary data of handshake
*/
- bool ProccessHandshakeData(const SecurityMessage &inMessage);
+ bool ProccessHandshakeData(const SecurityMessage& inMessage);
/**
* \brief Parse InternalError from mobile side
* \param inMessage SecurityMessage with binary data of handshake
*/
- bool ProccessInternalError(const SecurityMessage &inMessage);
+ bool ProccessInternalError(const SecurityMessage& inMessage);
/**
* \brief Sends security query
* Create new array as concatenation of header and binary data
* \param query SecurityQuery for sending via Control service
- * \param connection_key Unique key used by other components as session identifier
+ * \param connection_key Unique key used by other components as session
+ * identifier
*/
- void SendQuery(const SecurityQuery &query, const uint32_t connection_key);
+ void SendQuery(const SecurityQuery& query, const uint32_t connection_key);
// Thread that pumps handshake data
SecurityMessageLoop security_messages_;
@@ -191,19 +205,19 @@ class SecurityManagerImpl
/**
*\brief Pointer on instance of class implementing SessionObserver
*/
- protocol_handler::SessionObserver *session_observer_;
+ protocol_handler::SessionObserver* session_observer_;
/**
*\brief Pointer on instance of class implementing CryptoManager
*/
- security_manager::CryptoManager *crypto_manager_;
+ security_manager::CryptoManager* crypto_manager_;
/**
*\brief Pointer on instance of class implementing ProtocolHandler
*/
- protocol_handler::ProtocolHandler *protocol_handler_;
+ protocol_handler::ProtocolHandler* protocol_handler_;
/**
*\brief List of listeners for notify handshake done result
*/
- std::list<SecurityManagerListener *> listeners_;
+ std::list<SecurityManagerListener*> listeners_;
DISALLOW_COPY_AND_ASSIGN(SecurityManagerImpl);
};
} // namespace security_manager
diff --git a/src/components/security_manager/include/security_manager/security_query.h b/src/components/security_manager/include/security_manager/security_query.h
deleted file mode 100644
index c9f0b5843f..0000000000
--- a/src/components/security_manager/include/security_manager/security_query.h
+++ /dev/null
@@ -1,186 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_SECURITY_QUERY_H_
-#define SRC_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_SECURITY_QUERY_H_
-
-#include <stdint.h>
-#include <cstddef>
-#include <vector>
-#include <string>
-#include "utils/shared_ptr.h"
-
-namespace security_manager {
-/**
- * \brief SecurityQuery is wrapper for handling Mobile messages
- * as security queries
- */
-class SecurityQuery {
- public:
- /**
- * \brief QueryType is 1 byte type of income query
- * Equal RPC Type (Ford Binary Header Definition)
- */
- enum QueryType {
- REQUEST = 0x00,
- RESPONSE = 0x10,
- NOTIFICATION = 0x20,
- INVALID_QUERY_TYPE = 0xFF
- };
- /**
- * \brief QueryId is 3 byte identifier of income query
- * Equal RPC Function ID (Ford Binary Header Definition)
- */
- enum QueryId {
- SEND_HANDSHAKE_DATA = 0x1,
- SEND_INTERNAL_ERROR = 0x2,
- INVALID_QUERY_ID = 0xFFFFFF
- };
- /**
- * \brief QueryHeader is 12 byte header of security query
- * Equal Ford Binary Header Definition
- */
- struct QueryHeader {
- QueryHeader();
- QueryHeader(uint8_t queryType, uint32_t queryId,
- uint32_t seqNumber = 0, uint32_t jsonSize= 0);
- // TODO(EZamakhov): check bitfield correctness on other endianness platform
- uint32_t query_type:8;
- uint32_t query_id:24; // API function identifier
- uint32_t seq_number; // request sequential number
- uint32_t json_size;
- };
-
- /**
- * \brief Constructor
- */
- SecurityQuery();
- /**
- * \brief Constructor with header and connection_key
- * \param connection_key Unique key used by other components as session identifier
- * \param header QueryHeader
- */
- SecurityQuery(const QueryHeader &header, const uint32_t connection_key);
- /**
- * \brief Constructor with header, connection_key and query binary data
- * \param connection_key Unique key used by other components as session identifier
- * \param raw_data pointer to binary data array
- * \param raw_data_size size of binary data array
- * \param header QueryHeader
- */
- SecurityQuery(const QueryHeader &header, const uint32_t connection_key,
- const uint8_t *const raw_data, const size_t raw_data_size);
- /**
- * \brief Serialize income from Mobile Application data
- * as query with header and binary data or json message
- * \param raw_data pointer to binary data array
- * \param raw_data_size size of binary data array
- * \return \c true on correct parse and \c false on wrong size of data
- */
- bool SerializeQuery(const uint8_t *const raw_data, const size_t raw_data_size);
- /**
- * \brief Deserialize query for sending to Mobile Application
- * \return \c vector of uint8_t data (serialized header data and send_data))
- */
- const std::vector<uint8_t> DeserializeQuery() const;
- /**
- * \brief Set binary data. (No header modification)
- * \param binary_data pointer to binary data array
- * \param bin_data_size size of binary data array
- */
- void set_data(const uint8_t *const binary_data, const size_t bin_data_size);
- /**
- * \brief Set json data. (No header modification)
- * \param json_message string with json error
- */
- void set_json_message(const std::string &json_message);
- /**
- * \brief Set connection key
- * \param connection_key Unique key used by other components as session identifier
- */
- void set_connection_key(const uint32_t connection_key);
- /**
- * \brief Set query header
- * \param header of query
- */
- void set_header(const QueryHeader &header);
- /**
- * \brief Get query header
- * \return header of query
- */
- const QueryHeader &get_header() const;
- /**
- * \brief Get query binary data (without header data)
- * \return const pointer to const binary data
- */
- const uint8_t *get_data() const;
- /**
- * \brief Get query binary data size
- * \return size of binary data
- */
- size_t get_data_size() const;
- /**
- * \brief Get json string data (without header data)
- * \return const pointer to const binary data
- */
- const std::string &get_json_message() const;
- /**
- * \brief Get connection key
- * \return Unique key used by other components as session identifier
- */
- uint32_t get_connection_key() const;
-
- private:
- /**
- *\brief 12 byte header of security query
- * Equal Ford Binary Header Definition
- */
- QueryHeader header_;
- /**
- *\brief nique key used by other components as session identifier
- */
- uint32_t connection_key_;
- /**
- *\brief Binary data of query (without header info)
- */
- std::vector<uint8_t> data_;
- /**
- *\brief JSON (string) value of query
- */
- std::string json_message_;
-};
-/**
-*\brief SmartPointer wrapper
-*/
-typedef utils::SharedPtr<SecurityQuery> SecurityQueryPtr;
-} // namespace security_manager
-#endif // SRC_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_SECURITY_QUERY_H_
diff --git a/src/components/security_manager/src/crypto_manager_impl.cc b/src/components/security_manager/src/crypto_manager_impl.cc
index 69121a7b19..f44198953b 100644
--- a/src/components/security_manager/src/crypto_manager_impl.cc
+++ b/src/components/security_manager/src/crypto_manager_impl.cc
@@ -31,143 +31,205 @@
*/
#include "security_manager/crypto_manager_impl.h"
+
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
+#include <openssl/pkcs12.h>
+
+#include <fstream>
+#include <iostream>
+#include <stdio.h>
+#include <ctime>
#include "security_manager/security_manager.h"
+
#include "utils/logger.h"
#include "utils/atomic.h"
+#include "utils/macro.h"
+#include "utils/scope_guard.h"
+#include "utils/date_time.h"
-#define TLS1_1_MINIMAL_VERSION 0x1000103fL
-#define CONST_SSL_METHOD_MINIMAL_VERSION 0x00909000L
+#define TLS1_1_MINIMAL_VERSION 0x1000103fL
+#define CONST_SSL_METHOD_MINIMAL_VERSION 0x00909000L
namespace security_manager {
-CREATE_LOGGERPTR_GLOBAL(logger_, "CryptoManagerImpl")
+CREATE_LOGGERPTR_GLOBAL(logger_, "SecurityManager")
uint32_t CryptoManagerImpl::instance_count_ = 0;
+sync_primitives::Lock CryptoManagerImpl::instance_lock_;
-CryptoManagerImpl::CryptoManagerImpl()
- : context_(NULL), mode_(CLIENT) {
+namespace {
+int debug_callback(int preverify_ok, X509_STORE_CTX* ctx) {
+ if (!preverify_ok) {
+ const int error = X509_STORE_CTX_get_error(ctx);
+ UNUSED(error);
+ LOG4CXX_WARN(logger_,
+ "Certificate verification failed with error "
+ << error << " \"" << X509_verify_cert_error_string(error)
+ << '"');
+ }
+ return preverify_ok;
}
-bool CryptoManagerImpl::Init(Mode mode,
- Protocol protocol,
- const std::string &cert_filename,
- const std::string &key_filename,
- const std::string &ciphers_list,
- bool verify_peer) {
- if (atomic_post_inc(&instance_count_) == 0) {
+void free_ctx(SSL_CTX** ctx) {
+ if (ctx) {
+ SSL_CTX_free(*ctx);
+ *ctx = NULL;
+ }
+}
+}
+
+CryptoManagerImpl::CryptoManagerImpl(
+ const utils::SharedPtr<const CryptoManagerSettings> set)
+ : settings_(set), context_(NULL) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(instance_lock_);
+ instance_count_++;
+ if (instance_count_ == 1) {
+ LOG4CXX_DEBUG(logger_, "Openssl engine initialization");
SSL_load_error_strings();
ERR_load_BIO_strings();
OpenSSL_add_all_algorithms();
SSL_library_init();
}
+}
- mode_ = mode;
+CryptoManagerImpl::~CryptoManagerImpl() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock lock(instance_lock_);
+ LOG4CXX_DEBUG(logger_, "Deinitilization");
+ if (!context_) {
+ LOG4CXX_WARN(logger_, "Manager is not initialized");
+ } else {
+ SSL_CTX_free(context_);
+ }
+ instance_count_--;
+ if (instance_count_ == 0) {
+ LOG4CXX_DEBUG(logger_, "Openssl engine deinitialization");
+ EVP_cleanup();
+ ERR_free_strings();
+ }
+}
+
+bool CryptoManagerImpl::Init() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ const Mode mode = get_settings().security_manager_mode();
const bool is_server = (mode == SERVER);
+ if (is_server) {
+ LOG4CXX_DEBUG(logger_, "Server mode");
+ } else {
+ LOG4CXX_DEBUG(logger_, "Client mode");
+ }
+ LOG4CXX_DEBUG(logger_,
+ "Peer verification "
+ << (get_settings().verify_peer() ? "enabled" : "disabled"));
+ LOG4CXX_DEBUG(logger_,
+ "CA certificate file is \"" << get_settings().ca_cert_path()
+ << '"');
+
#if OPENSSL_VERSION_NUMBER < CONST_SSL_METHOD_MINIMAL_VERSION
- SSL_METHOD *method;
+ SSL_METHOD* method;
#else
- const SSL_METHOD *method;
+ const SSL_METHOD* method;
#endif
- switch (protocol) {
+ switch (get_settings().security_manager_protocol_name()) {
case SSLv3:
- method = is_server ?
- SSLv3_server_method() :
- SSLv3_client_method();
+ method = is_server ? SSLv3_server_method() : SSLv3_client_method();
break;
case TLSv1:
- method = is_server ?
- TLSv1_server_method() :
- TLSv1_client_method();
+ method = is_server ? TLSv1_server_method() : TLSv1_client_method();
break;
case TLSv1_1:
#if OPENSSL_VERSION_NUMBER < TLS1_1_MINIMAL_VERSION
- LOG4CXX_WARN(logger_,
- "OpenSSL has no TLSv1.1 with version lower 1.0.1, set TLSv1.0");
- method = is_server ?
- TLSv1_server_method() :
- TLSv1_client_method();
+ LOG4CXX_WARN(
+ logger_,
+ "OpenSSL has no TLSv1.1 with version lower 1.0.1, set TLSv1.0");
+ method = is_server ? TLSv1_server_method() : TLSv1_client_method();
#else
- method = is_server ?
- TLSv1_1_server_method() :
- TLSv1_1_client_method();
+ method = is_server ? TLSv1_1_server_method() : TLSv1_1_client_method();
#endif
break;
case TLSv1_2:
#if OPENSSL_VERSION_NUMBER < TLS1_1_MINIMAL_VERSION
- LOG4CXX_WARN(logger_,
- "OpenSSL has no TLSv1.2 with version lower 1.0.1, set TLSv1.0");
- method = is_server ?
- TLSv1_server_method() :
- TLSv1_client_method();
+ LOG4CXX_WARN(
+ logger_,
+ "OpenSSL has no TLSv1.2 with version lower 1.0.1, set TLSv1.0");
+ method = is_server ? TLSv1_server_method() : TLSv1_client_method();
#else
- method = is_server ?
- TLSv1_2_server_method() :
- TLSv1_2_client_method();
+ method = is_server ? TLSv1_2_server_method() : TLSv1_2_client_method();
#endif
break;
default:
- LOG4CXX_ERROR(logger_, "Unknown protocol: " << protocol);
+ LOG4CXX_ERROR(logger_,
+ "Unknown protocol: "
+ << get_settings().security_manager_protocol_name());
return false;
}
+ if (context_) {
+ free_ctx(&context_);
+ }
context_ = SSL_CTX_new(method);
+ utils::ScopeGuard guard = utils::MakeGuard(free_ctx, &context_);
+
// Disable SSL2 as deprecated
SSL_CTX_set_options(context_, SSL_OP_NO_SSLv2);
- if (cert_filename.empty()) {
- LOG4CXX_WARN(logger_, "Empty certificate path");
+ set_certificate(get_settings().certificate_data());
+
+ if (get_settings().ciphers_list().empty()) {
+ LOG4CXX_WARN(logger_, "Empty ciphers list");
} else {
- LOG4CXX_INFO(logger_, "Certificate path: " << cert_filename);
- if (!SSL_CTX_use_certificate_file(context_, cert_filename.c_str(),
- SSL_FILETYPE_PEM)) {
- LOG4CXX_ERROR(logger_, "Could not use certificate " << cert_filename);
+ LOG4CXX_DEBUG(logger_, "Cipher list: " << get_settings().ciphers_list());
+ if (!SSL_CTX_set_cipher_list(context_,
+ get_settings().ciphers_list().c_str())) {
+ LOG4CXX_ERROR(
+ logger_,
+ "Could not set cipher list: " << get_settings().ciphers_list());
return false;
}
}
- if (key_filename.empty()) {
- LOG4CXX_WARN(logger_, "Empty key path");
- } else {
- LOG4CXX_INFO(logger_, "Key path: " << key_filename);
- if (!SSL_CTX_use_PrivateKey_file(context_, key_filename.c_str(),
- SSL_FILETYPE_PEM)) {
- LOG4CXX_ERROR(logger_, "Could not use key " << key_filename);
- return false;
- }
- if (!SSL_CTX_check_private_key(context_)) {
- LOG4CXX_ERROR(logger_, "Could not use certificate " << cert_filename);
- return false;
- }
+ if (get_settings().ca_cert_path().empty()) {
+ LOG4CXX_WARN(logger_, "Setting up empty CA certificate location");
}
- if (ciphers_list.empty()) {
- LOG4CXX_WARN(logger_, "Empty ciphers list");
- } else {
- LOG4CXX_INFO(logger_, "Cipher list: " << ciphers_list);
- if (!SSL_CTX_set_cipher_list(context_, ciphers_list.c_str())) {
- LOG4CXX_ERROR(logger_, "Could not set cipher list: " << ciphers_list);
- return false;
- }
+ LOG4CXX_DEBUG(logger_, "Setting up CA certificate location");
+ const int result = SSL_CTX_load_verify_locations(
+ context_, NULL, get_settings().ca_cert_path().c_str());
+
+ if (!result) {
+ const unsigned long error = ERR_get_error();
+ UNUSED(error);
+ LOG4CXX_WARN(logger_,
+ "Wrong certificate file '"
+ << get_settings().ca_cert_path() << "', err 0x" << std::hex
+ << error << " \"" << ERR_reason_error_string(error)
+ << '"');
}
- // TODO(EZamakhov): add loading SSL_VERIFY_FAIL_IF_NO_PEER_CERT from INI
- const int verify_mode = verify_peer
- ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT
- : SSL_VERIFY_NONE;
- SSL_CTX_set_verify(context_, verify_mode, NULL);
+ guard.Dismiss();
+ const int verify_mode =
+ get_settings().verify_peer()
+ ? SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT
+ : SSL_VERIFY_NONE;
+ LOG4CXX_DEBUG(logger_,
+ "Setting up peer verification in mode: " << verify_mode);
+ SSL_CTX_set_verify(context_, verify_mode, &debug_callback);
return true;
}
-void CryptoManagerImpl::Finish() {
- SSL_CTX_free(context_);
- if (atomic_post_dec(&instance_count_) == 1) {
- EVP_cleanup();
- ERR_free_strings();
+bool CryptoManagerImpl::OnCertificateUpdated(const std::string& data) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!context_) {
+ LOG4CXX_WARN(logger_, "Not initialized");
+ return false;
}
+
+ return set_certificate(data);
}
SSLContext* CryptoManagerImpl::CreateSSLContext() {
@@ -175,19 +237,21 @@ SSLContext* CryptoManagerImpl::CreateSSLContext() {
return NULL;
}
- SSL *conn = SSL_new(context_);
+ SSL* conn = SSL_new(context_);
if (conn == NULL)
return NULL;
- if (mode_ == SERVER) {
+ if (get_settings().security_manager_mode() == SERVER) {
SSL_set_accept_state(conn);
} else {
SSL_set_connect_state(conn);
}
- return new SSLContextImpl(conn, mode_);
+ return new SSLContextImpl(conn,
+ get_settings().security_manager_mode(),
+ get_settings().maximum_payload_size());
}
-void CryptoManagerImpl::ReleaseSSLContext(SSLContext *context) {
+void CryptoManagerImpl::ReleaseSSLContext(SSLContext* context) {
delete context;
}
@@ -195,8 +259,142 @@ std::string CryptoManagerImpl::LastError() const {
if (!context_) {
return std::string("Initialization is not completed");
}
- const char *reason = ERR_reason_error_string(ERR_get_error());
+ const char* reason = ERR_reason_error_string(ERR_get_error());
return std::string(reason ? reason : "");
}
+bool CryptoManagerImpl::IsCertificateUpdateRequired() const {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ const time_t cert_date = mktime(&expiration_time_);
+
+ if (cert_date == -1) {
+ LOG4CXX_WARN(logger_,
+ "The certifiacte expiration time cannot be represented.");
+ return false;
+ }
+ const time_t now = time(NULL);
+ const double seconds = difftime(cert_date, now);
+
+ LOG4CXX_DEBUG(logger_,
+ "Certificate expiration time: " << asctime(&expiration_time_));
+ LOG4CXX_DEBUG(logger_,
+ "Host time: " << asctime(localtime(&now))
+ << ". Seconds before expiration: " << seconds);
+ if (seconds < 0) {
+ LOG4CXX_WARN(logger_, "Certificate is already expired.");
+ return true;
+ }
+
+ return seconds <= (get_settings().update_before_hours() *
+ date_time::DateTime::SECONDS_IN_HOUR);
+}
+
+const CryptoManagerSettings& CryptoManagerImpl::get_settings() const {
+ return *settings_;
+}
+
+bool CryptoManagerImpl::set_certificate(const std::string& cert_data) {
+ if (cert_data.empty()) {
+ LOG4CXX_WARN(logger_, "Empty certificate");
+ return false;
+ }
+
+ BIO* bio = BIO_new(BIO_f_base64());
+ BIO* bmem = BIO_new_mem_buf((char*)cert_data.c_str(), cert_data.length());
+ bmem = BIO_push(bio, bmem);
+
+ char* buf = new char[cert_data.length()];
+ int len = BIO_read(bmem, buf, cert_data.length());
+
+ BIO* bio_cert = BIO_new(BIO_s_mem());
+ if (NULL == bio_cert) {
+ LOG4CXX_WARN(logger_, "Unable to update certificate. BIO not created");
+ return false;
+ }
+
+ utils::ScopeGuard bio_guard = utils::MakeGuard(BIO_free, bio_cert);
+ UNUSED(bio_guard)
+ int k = 0;
+ if ((k = BIO_write(bio_cert, buf, len)) <= 0) {
+ LOG4CXX_WARN(logger_, "Unable to write into BIO");
+ return false;
+ }
+
+ PKCS12* p12 = d2i_PKCS12_bio(bio_cert, NULL);
+ if (NULL == p12) {
+ LOG4CXX_ERROR(logger_, "Unable to parse certificate");
+ return false;
+ }
+
+ EVP_PKEY* pkey = NULL;
+ X509* cert = NULL;
+ PKCS12_parse(p12, NULL, &pkey, &cert, NULL);
+
+ if (NULL == cert || NULL == pkey) {
+ LOG4CXX_WARN(logger_, "Either certificate or key not valid.");
+ return false;
+ }
+
+ if (!SSL_CTX_use_certificate(context_, cert)) {
+ LOG4CXX_WARN(logger_, "Could not use certificate");
+ return false;
+ }
+
+ asn1_time_to_tm(X509_get_notAfter(cert));
+
+ if (!SSL_CTX_use_PrivateKey(context_, pkey)) {
+ LOG4CXX_ERROR(logger_, "Could not use key");
+ return false;
+ }
+ if (!SSL_CTX_check_private_key(context_)) {
+ LOG4CXX_ERROR(logger_, "Could not use certificate ");
+ return false;
+ }
+ return true;
+}
+
+int CryptoManagerImpl::pull_number_from_buf(char* buf, int* idx) {
+ if (!idx) {
+ return 0;
+ }
+ const int val = ((buf[*idx] - '0') * 10) + buf[(*idx) + 1] - '0';
+ *idx = *idx + 2;
+ return val;
+}
+
+void CryptoManagerImpl::asn1_time_to_tm(ASN1_TIME* time) {
+ char* buf = (char*)time->data;
+ int index = 0;
+ const int year = pull_number_from_buf(buf, &index);
+ if (V_ASN1_GENERALIZEDTIME == time->type) {
+ expiration_time_.tm_year =
+ (year * 100 - 1900) + pull_number_from_buf(buf, &index);
+ } else {
+ expiration_time_.tm_year = year < 50 ? year + 100 : year;
+ }
+
+ const int mon = pull_number_from_buf(buf, &index);
+ const int day = pull_number_from_buf(buf, &index);
+ const int hour = pull_number_from_buf(buf, &index);
+ const int mn = pull_number_from_buf(buf, &index);
+
+ expiration_time_.tm_mon = mon - 1;
+ expiration_time_.tm_mday = day;
+ expiration_time_.tm_hour = hour;
+ expiration_time_.tm_min = mn;
+
+ if (buf[index] == 'Z') {
+ expiration_time_.tm_sec = 0;
+ }
+ if ((buf[index] == '+') || (buf[index] == '-')) {
+ const int mn = pull_number_from_buf(buf, &index);
+ const int mn1 = pull_number_from_buf(buf, &index);
+ expiration_time_.tm_sec = (mn * 3600) + (mn1 * 60);
+ } else {
+ const int sec = pull_number_from_buf(buf, &index);
+ expiration_time_.tm_sec = sec;
+ }
+}
+
} // namespace security_manager
diff --git a/src/components/security_manager/src/security_manager_impl.cc b/src/components/security_manager/src/security_manager_impl.cc
index dee1770e70..556cc291d1 100644
--- a/src/components/security_manager/src/security_manager_impl.cc
+++ b/src/components/security_manager/src/security_manager_impl.cc
@@ -45,9 +45,10 @@ static const char* kErrId = "id";
static const char* kErrText = "text";
SecurityManagerImpl::SecurityManagerImpl()
- : security_messages_("SecurityManager", this),
- session_observer_(NULL), crypto_manager_(NULL), protocol_handler_(NULL) {
-}
+ : security_messages_("SecurityManager", this)
+ , session_observer_(NULL)
+ , crypto_manager_(NULL)
+ , protocol_handler_(NULL) {}
void SecurityManagerImpl::OnMessageReceived(
const ::protocol_handler::RawMessagePtr message) {
@@ -56,14 +57,14 @@ void SecurityManagerImpl::OnMessageReceived(
}
SecurityMessage securityMessagePtr(new SecurityQuery());
- const bool result = securityMessagePtr->SerializeQuery(
- message->data(), message->data_size());
+ const bool result =
+ securityMessagePtr->SerializeQuery(message->data(), message->data_size());
if (!result) {
// result will be false only if data less then query header
const std::string error_text("Incorrect message received");
LOG4CXX_ERROR(logger_, error_text);
- SendInternalError(message->connection_key(),
- ERROR_INVALID_QUERY_SIZE, error_text);
+ SendInternalError(
+ message->connection_key(), ERROR_INVALID_QUERY_SIZE, error_text);
return;
}
securityMessagePtr->set_connection_key(message->connection_key());
@@ -73,11 +74,10 @@ void SecurityManagerImpl::OnMessageReceived(
}
void SecurityManagerImpl::OnMobileMessageSent(
- const ::protocol_handler::RawMessagePtr ) {
-}
+ const ::protocol_handler::RawMessagePtr) {}
void SecurityManagerImpl::set_session_observer(
- protocol_handler::SessionObserver *observer) {
+ protocol_handler::SessionObserver* observer) {
if (!observer) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to SessionObserver.");
return;
@@ -86,7 +86,7 @@ void SecurityManagerImpl::set_session_observer(
}
void SecurityManagerImpl::set_protocol_handler(
- protocol_handler::ProtocolHandler *handler) {
+ protocol_handler::ProtocolHandler* handler) {
if (!handler) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to ProtocolHandler.");
return;
@@ -94,7 +94,7 @@ void SecurityManagerImpl::set_protocol_handler(
protocol_handler_ = handler;
}
-void SecurityManagerImpl::set_crypto_manager(CryptoManager *crypto_manager) {
+void SecurityManagerImpl::set_crypto_manager(CryptoManager* crypto_manager) {
if (!crypto_manager) {
LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to CryptoManager.");
return;
@@ -105,11 +105,11 @@ void SecurityManagerImpl::set_crypto_manager(CryptoManager *crypto_manager) {
void SecurityManagerImpl::Handle(const SecurityMessage message) {
DCHECK(message);
LOG4CXX_INFO(logger_, "Received Security message from Mobile side");
- if (!crypto_manager_) {
+ if (!crypto_manager_) {
const std::string error_text("Invalid (NULL) CryptoManager.");
LOG4CXX_ERROR(logger_, error_text);
- SendInternalError(message->get_connection_key(),
- ERROR_NOT_SUPPORTED, error_text);
+ SendInternalError(
+ message->get_connection_key(), ERROR_NOT_SUPPORTED, error_text);
return;
}
switch (message->get_header().query_id) {
@@ -128,21 +128,21 @@ void SecurityManagerImpl::Handle(const SecurityMessage message) {
const std::string error_text("Unknown query identifier.");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(message->get_connection_key(),
- ERROR_INVALID_QUERY_ID, error_text,
+ ERROR_INVALID_QUERY_ID,
+ error_text,
message->get_header().seq_number);
- }
- break;
- }
+ } break;
+ }
}
-security_manager::SSLContext *SecurityManagerImpl::CreateSSLContext(
- const uint32_t &connection_key) {
+security_manager::SSLContext* SecurityManagerImpl::CreateSSLContext(
+ const uint32_t& connection_key) {
LOG4CXX_INFO(logger_, "ProtectService processing");
DCHECK(session_observer_);
DCHECK(crypto_manager_);
- security_manager::SSLContext *ssl_context =
- session_observer_->GetSSLContext(connection_key, protocol_handler::kControl);
+ security_manager::SSLContext* ssl_context = session_observer_->GetSSLContext(
+ connection_key, protocol_handler::kControl);
// return exists SSLCOntext for current connection/session
if (ssl_context) {
return ssl_context;
@@ -153,12 +153,12 @@ security_manager::SSLContext *SecurityManagerImpl::CreateSSLContext(
const std::string error_text("CryptoManager could not create SSL context.");
LOG4CXX_ERROR(logger_, error_text);
// Generate response query and post to security_messages_
- SendInternalError(connection_key, ERROR_INTERNAL,
- error_text);
+ SendInternalError(connection_key, ERROR_INTERNAL, error_text);
return NULL;
}
- const int result = session_observer_->SetSSLContext(connection_key, ssl_context);
+ const int result =
+ session_observer_->SetSSLContext(connection_key, ssl_context);
if (ERROR_SUCCESS != result) {
// delete SSLContext on any error
crypto_manager_->ReleaseSSLContext(ssl_context);
@@ -167,38 +167,51 @@ security_manager::SSLContext *SecurityManagerImpl::CreateSSLContext(
}
DCHECK(session_observer_->GetSSLContext(connection_key,
protocol_handler::kControl));
- LOG4CXX_DEBUG(logger_, "Set SSL context to connection_key " << connection_key);
+ LOG4CXX_DEBUG(logger_,
+ "Set SSL context to connection_key " << connection_key);
return ssl_context;
}
void SecurityManagerImpl::StartHandshake(uint32_t connection_key) {
DCHECK(session_observer_);
LOG4CXX_INFO(logger_, "StartHandshake: connection_key " << connection_key);
- security_manager::SSLContext *ssl_context =
- session_observer_->GetSSLContext(connection_key,
- protocol_handler::kControl);
+ security_manager::SSLContext* ssl_context = session_observer_->GetSSLContext(
+ connection_key, protocol_handler::kControl);
if (!ssl_context) {
- const std::string error_text("StartHandshake failed, "
- "connection is not protected");
+ const std::string error_text(
+ "StartHandshake failed, "
+ "connection is not protected");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
- NotifyListenersOnHandshakeDone(connection_key, false);
+ NotifyListenersOnHandshakeDone(connection_key,
+ SSLContext::Handshake_Result_Fail);
return;
}
+ if (crypto_manager_->IsCertificateUpdateRequired()) {
+ NotifyOnCertififcateUpdateRequired();
+ }
+
if (ssl_context->IsInitCompleted()) {
- NotifyListenersOnHandshakeDone(connection_key, true);
+ NotifyListenersOnHandshakeDone(connection_key,
+ SSLContext::Handshake_Result_Success);
return;
}
+
+ ssl_context->SetHandshakeContext(
+ session_observer_->GetHandshakeContext(connection_key));
+
size_t data_size = 0;
- const uint8_t *data = NULL;
+ const uint8_t* data = NULL;
+
const security_manager::SSLContext::HandshakeResult result =
ssl_context->StartHandshake(&data, &data_size);
if (security_manager::SSLContext::Handshake_Result_Success != result) {
const std::string error_text("StartHandshake failed, handshake step fail");
LOG4CXX_ERROR(logger_, error_text);
SendInternalError(connection_key, ERROR_INTERNAL, error_text);
- NotifyListenersOnHandshakeDone(connection_key, false);
+ NotifyListenersOnHandshakeDone(connection_key,
+ SSLContext::Handshake_Result_Fail);
return;
}
// for client mode will be generated output data
@@ -206,26 +219,29 @@ void SecurityManagerImpl::StartHandshake(uint32_t connection_key) {
SendHandshakeBinData(connection_key, data, data_size);
}
}
-void SecurityManagerImpl::AddListener(SecurityManagerListener *const listener) {
+void SecurityManagerImpl::AddListener(SecurityManagerListener* const listener) {
if (!listener) {
- LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to SecurityManagerListener.");
+ LOG4CXX_ERROR(logger_,
+ "Invalid (NULL) pointer to SecurityManagerListener.");
return;
}
listeners_.push_back(listener);
}
-void SecurityManagerImpl::RemoveListener(SecurityManagerListener *const listener) {
+void SecurityManagerImpl::RemoveListener(
+ SecurityManagerListener* const listener) {
if (!listener) {
- LOG4CXX_ERROR(logger_, "Invalid (NULL) pointer to SecurityManagerListener.");
+ LOG4CXX_ERROR(logger_,
+ "Invalid (NULL) pointer to SecurityManagerListener.");
return;
}
listeners_.remove(listener);
}
-void SecurityManagerImpl::NotifyListenersOnHandshakeDone(const uint32_t &connection_key,
- const bool success) {
- LOG4CXX_TRACE(logger_, "NotifyListenersOnHandshakeDone");
+void SecurityManagerImpl::NotifyListenersOnHandshakeDone(
+ const uint32_t& connection_key, SSLContext::HandshakeResult error) {
+ LOG4CXX_AUTO_TRACE(logger_);
std::list<SecurityManagerListener*>::iterator it = listeners_.begin();
while (it != listeners_.end()) {
- if ((*it)->OnHandshakeDone(connection_key, success)) {
+ if ((*it)->OnHandshakeDone(connection_key, error)) {
// On get notification remove listener
it = listeners_.erase(it);
} else {
@@ -234,140 +250,166 @@ void SecurityManagerImpl::NotifyListenersOnHandshakeDone(const uint32_t &connect
}
}
-bool SecurityManagerImpl::ProccessHandshakeData(const SecurityMessage &inMessage) {
+void SecurityManagerImpl::NotifyOnCertififcateUpdateRequired() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ std::list<SecurityManagerListener*>::iterator it = listeners_.begin();
+ while (it != listeners_.end()) {
+ (*it)->OnCertificateUpdateRequired();
+ ++it;
+ }
+}
+
+bool SecurityManagerImpl::ProccessHandshakeData(
+ const SecurityMessage& inMessage) {
LOG4CXX_INFO(logger_, "SendHandshakeData processing");
DCHECK(inMessage);
- DCHECK(inMessage->get_header().query_id == SecurityQuery::SEND_HANDSHAKE_DATA);
+ DCHECK(inMessage->get_header().query_id ==
+ SecurityQuery::SEND_HANDSHAKE_DATA);
const uint32_t seqNumber = inMessage->get_header().seq_number;
const uint32_t connection_key = inMessage->get_connection_key();
- LOG4CXX_DEBUG(logger_, "Received " << inMessage->get_data_size()
- << " bytes handshake data ");
+ LOG4CXX_DEBUG(logger_,
+ "Received " << inMessage->get_data_size()
+ << " bytes handshake data ");
if (!inMessage->get_data_size()) {
const std::string error_text("SendHandshakeData: null arguments size.");
LOG4CXX_ERROR(logger_, error_text);
- SendInternalError(connection_key, ERROR_INVALID_QUERY_SIZE,
- error_text, seqNumber);
+ SendInternalError(
+ connection_key, ERROR_INVALID_QUERY_SIZE, error_text, seqNumber);
return false;
}
DCHECK(session_observer_);
- SSLContext *sslContext =
- session_observer_->GetSSLContext(connection_key,
- protocol_handler::kControl);
+ SSLContext* sslContext = session_observer_->GetSSLContext(
+ connection_key, protocol_handler::kControl);
if (!sslContext) {
const std::string error_text("SendHandshakeData: No ssl context.");
LOG4CXX_ERROR(logger_, error_text);
- SendInternalError(connection_key, ERROR_SERVICE_NOT_PROTECTED,
- error_text, seqNumber);
- NotifyListenersOnHandshakeDone(connection_key, false);
+ SendInternalError(
+ connection_key, ERROR_SERVICE_NOT_PROTECTED, error_text, seqNumber);
+ NotifyListenersOnHandshakeDone(connection_key,
+ SSLContext::Handshake_Result_Fail);
return false;
}
size_t out_data_size;
- const uint8_t *out_data;
+ const uint8_t* out_data;
const SSLContext::HandshakeResult handshake_result =
- sslContext->DoHandshakeStep(inMessage->get_data(), inMessage->get_data_size(),
- &out_data, &out_data_size);
+ sslContext->DoHandshakeStep(inMessage->get_data(),
+ inMessage->get_data_size(),
+ &out_data,
+ &out_data_size);
if (handshake_result == SSLContext::Handshake_Result_AbnormalFail) {
// Do not return handshake data on AbnormalFail or null returned values
const std::string erorr_text(sslContext->LastError());
- LOG4CXX_ERROR(logger_, "SendHandshakeData: Handshake failed: " << erorr_text);
- SendInternalError(connection_key,
- ERROR_SSL_INVALID_DATA, erorr_text, seqNumber);
- NotifyListenersOnHandshakeDone(connection_key, false);
+ LOG4CXX_ERROR(logger_,
+ "SendHandshakeData: Handshake failed: " << erorr_text);
+ SendInternalError(
+ connection_key, ERROR_SSL_INVALID_DATA, erorr_text, seqNumber);
+ NotifyListenersOnHandshakeDone(connection_key,
+ SSLContext::Handshake_Result_Fail);
// no handshake data to send
return false;
}
if (sslContext->IsInitCompleted()) {
// On handshake success
LOG4CXX_DEBUG(logger_, "SSL initialization finished success.");
- NotifyListenersOnHandshakeDone(connection_key, true);
- } else if (handshake_result == SSLContext::Handshake_Result_Fail) {
+ NotifyListenersOnHandshakeDone(connection_key,
+ SSLContext::Handshake_Result_Success);
+ } else if (handshake_result != SSLContext::Handshake_Result_Success) {
// On handshake fail
LOG4CXX_WARN(logger_, "SSL initialization finished with fail.");
- NotifyListenersOnHandshakeDone(connection_key, false);
+ NotifyListenersOnHandshakeDone(connection_key, handshake_result);
}
if (out_data && out_data_size) {
// answer with the same seqNumber as income message
- SendHandshakeBinData(connection_key, out_data, out_data_size,
- seqNumber);
+ SendHandshakeBinData(connection_key, out_data, out_data_size, seqNumber);
}
return true;
}
-bool SecurityManagerImpl::ProccessInternalError(const SecurityMessage &inMessage) {
- LOG4CXX_INFO(logger_, "Received InternalError with Json message"
- << inMessage->get_json_message());
+bool SecurityManagerImpl::ProccessInternalError(
+ const SecurityMessage& inMessage) {
+ LOG4CXX_INFO(logger_,
+ "Received InternalError with Json message"
+ << inMessage->get_json_message());
Json::Value root;
Json::Reader reader;
const bool parsingSuccessful =
reader.parse(inMessage->get_json_message(), root);
if (!parsingSuccessful)
return false;
- LOG4CXX_DEBUG(logger_, "Received InternalError id " << root[kErrId].asString()
- << ", text: " << root[kErrText].asString());
+ LOG4CXX_DEBUG(logger_,
+ "Received InternalError id "
+ << root[kErrId].asString()
+ << ", text: " << root[kErrText].asString());
return true;
}
-void SecurityManagerImpl::SendHandshakeBinData(
- const uint32_t connection_key, const uint8_t *const data,
- const size_t data_size, const uint32_t seq_number) {
- const SecurityQuery::QueryHeader header(
- SecurityQuery::NOTIFICATION,
- SecurityQuery::SEND_HANDSHAKE_DATA, seq_number);
- DCHECK(data_size < 1024 * 1024 *1024 );
- const SecurityQuery query = SecurityQuery(header, connection_key, data, data_size);
+void SecurityManagerImpl::SendHandshakeBinData(const uint32_t connection_key,
+ const uint8_t* const data,
+ const size_t data_size,
+ const uint32_t seq_number) {
+ const SecurityQuery::QueryHeader header(SecurityQuery::NOTIFICATION,
+ SecurityQuery::SEND_HANDSHAKE_DATA,
+ seq_number);
+ DCHECK(data_size < 1024 * 1024 * 1024);
+ const SecurityQuery query =
+ SecurityQuery(header, connection_key, data, data_size);
SendQuery(query, connection_key);
LOG4CXX_DEBUG(logger_, "Sent " << data_size << " bytes handshake data ");
}
void SecurityManagerImpl::SendInternalError(const uint32_t connection_key,
- const uint8_t &error_id,
- const std::string &erorr_text,
- const uint32_t seq_number) {
+ const uint8_t& error_id,
+ const std::string& erorr_text,
+ const uint32_t seq_number) {
Json::Value value;
- value[kErrId] = error_id;
+ value[kErrId] = error_id;
value[kErrText] = erorr_text;
const std::string error_str = value.toStyledString();
- SecurityQuery::QueryHeader header(SecurityQuery::NOTIFICATION,
- SecurityQuery::SEND_INTERNAL_ERROR,
- // header save json size only (exclude last byte)
- seq_number, error_str.size());
+ SecurityQuery::QueryHeader header(
+ SecurityQuery::NOTIFICATION,
+ SecurityQuery::SEND_INTERNAL_ERROR,
+ // header save json size only (exclude last byte)
+ seq_number,
+ error_str.size());
// Raw data is json string and error id at last byte
std::vector<uint8_t> data_sending(error_str.size() + 1);
memcpy(&data_sending[0], error_str.c_str(), error_str.size());
- data_sending[data_sending.size()-1] = error_id;
+ data_sending[data_sending.size() - 1] = error_id;
- const SecurityQuery query(header, connection_key,
- &data_sending[0], data_sending.size());
+ const SecurityQuery query(
+ header, connection_key, &data_sending[0], data_sending.size());
SendQuery(query, connection_key);
- LOG4CXX_DEBUG(logger_, "Sent Internal error id " << static_cast<int>(error_id)
- << " : \"" << erorr_text << "\".");
+ LOG4CXX_DEBUG(logger_,
+ "Sent Internal error id " << static_cast<int>(error_id)
+ << " : \"" << erorr_text << "\".");
}
void SecurityManagerImpl::SendQuery(const SecurityQuery& query,
- const uint32_t connection_key) {
+ const uint32_t connection_key) {
const std::vector<uint8_t> data_sending = query.DeserializeQuery();
uint32_t connection_handle = 0;
uint8_t sessionID = 0;
uint8_t protocol_version;
- session_observer_->PairFromKey(connection_key, &connection_handle,
- &sessionID);
- if (session_observer_->ProtocolVersionUsed(connection_handle, sessionID,
- protocol_version)) {
+ session_observer_->PairFromKey(
+ connection_key, &connection_handle, &sessionID);
+ if (session_observer_->ProtocolVersionUsed(
+ connection_handle, sessionID, protocol_version)) {
const ::protocol_handler::RawMessagePtr rawMessagePtr(
- new protocol_handler::RawMessage(connection_key,
- protocol_version,
- &data_sending[0], data_sending.size(),
- protocol_handler::kControl));
+ new protocol_handler::RawMessage(connection_key,
+ protocol_version,
+ &data_sending[0],
+ data_sending.size(),
+ protocol_handler::kControl));
DCHECK(protocol_handler_);
// Add RawMessage to ProtocolHandler message query
protocol_handler_->SendMessageToMobileApp(rawMessagePtr, false);
}
}
-const char *SecurityManagerImpl::ConfigSection() {
+const char* SecurityManagerImpl::ConfigSection() {
return "Security Manager";
}
diff --git a/src/components/security_manager/src/security_query.cc b/src/components/security_manager/src/security_query.cc
index cd4da03c15..60233dde5e 100644
--- a/src/components/security_manager/src/security_query.cc
+++ b/src/components/security_manager/src/security_query.cc
@@ -38,35 +38,37 @@
namespace security_manager {
SecurityQuery::QueryHeader::QueryHeader()
- : query_type(INVALID_QUERY_TYPE), query_id(INVALID_QUERY_ID),
- seq_number(0), json_size(0) {
-}
-
-SecurityQuery::QueryHeader::QueryHeader(uint8_t queryType, uint32_t queryId,
- uint32_t seqNumber, uint32_t jsonSize)
- : query_type(queryType), query_id(queryId),
- seq_number(seqNumber), json_size(jsonSize) {
-}
+ : query_type(INVALID_QUERY_TYPE)
+ , query_id(INVALID_QUERY_ID)
+ , seq_number(0)
+ , json_size(0) {}
+
+SecurityQuery::QueryHeader::QueryHeader(uint8_t queryType,
+ uint32_t queryId,
+ uint32_t seqNumber,
+ uint32_t jsonSize)
+ : query_type(queryType)
+ , query_id(queryId)
+ , seq_number(seqNumber)
+ , json_size(jsonSize) {}
SecurityQuery::SecurityQuery()
- : header_(INVALID_QUERY_TYPE, INVALID_QUERY_ID, 0), connection_key_(0) {
-}
+ : header_(INVALID_QUERY_TYPE, INVALID_QUERY_ID, 0), connection_key_(0) {}
-SecurityQuery::SecurityQuery(const SecurityQuery::QueryHeader &header,
+SecurityQuery::SecurityQuery(const SecurityQuery::QueryHeader& header,
const uint32_t connection_key,
- const uint8_t *const raw_data,
+ const uint8_t* const raw_data,
const size_t raw_data_size)
- : header_(header), connection_key_(connection_key),
- data_(raw_data, raw_data + raw_data_size) {
-}
+ : header_(header)
+ , connection_key_(connection_key)
+ , data_(raw_data, raw_data + raw_data_size) {}
-SecurityQuery::SecurityQuery(const SecurityQuery::QueryHeader &header,
+SecurityQuery::SecurityQuery(const SecurityQuery::QueryHeader& header,
const uint32_t connection_key)
- : header_(header), connection_key_(connection_key) {
-}
+ : header_(header), connection_key_(connection_key) {}
-bool SecurityQuery::SerializeQuery(const uint8_t *const raw_data,
- const size_t raw_data_size) {
+bool SecurityQuery::SerializeQuery(const uint8_t* const raw_data,
+ const size_t raw_data_size) {
const size_t header_size = sizeof(QueryHeader);
if (raw_data_size < header_size || !raw_data) {
return false;
@@ -74,21 +76,21 @@ bool SecurityQuery::SerializeQuery(const uint8_t *const raw_data,
const uint8_t query_type = raw_data[0];
switch (query_type) {
case REQUEST:
- header_.query_type = REQUEST;
+ header_.query_type = REQUEST;
break;
case RESPONSE:
- header_.query_type = RESPONSE;
+ header_.query_type = RESPONSE;
break;
case NOTIFICATION:
- header_.query_type = NOTIFICATION;
+ header_.query_type = NOTIFICATION;
break;
default:
header_.query_type = INVALID_QUERY_TYPE;
break;
}
// Convert to Little-Endian and clean high byte
- const uint32_t query_id = 0x00FFFFFF &
- BE_TO_LE32(*reinterpret_cast<const uint32_t*>(raw_data));
+ const uint32_t query_id =
+ 0x00FFFFFF & BE_TO_LE32(*reinterpret_cast<const uint32_t*>(raw_data));
switch (query_id) {
case SEND_HANDSHAKE_DATA:
header_.query_id = SEND_HANDSHAKE_DATA;
@@ -100,22 +102,25 @@ bool SecurityQuery::SerializeQuery(const uint8_t *const raw_data,
header_.query_id = INVALID_QUERY_ID;
break;
}
- header_.seq_number = BE_TO_LE32(*reinterpret_cast<const uint32_t*>(raw_data + 4));
- header_.json_size = BE_TO_LE32(*reinterpret_cast<const uint32_t*>(raw_data + 8));
+ header_.seq_number =
+ BE_TO_LE32(*reinterpret_cast<const uint32_t*>(raw_data + 4));
+ header_.json_size =
+ BE_TO_LE32(*reinterpret_cast<const uint32_t*>(raw_data + 8));
if (header_.json_size > raw_data_size - header_size)
return false;
if (header_.json_size > 0) {
- const char *const json_data =
+ const char* const json_data =
reinterpret_cast<const char*>(raw_data + header_size);
json_message_.assign(json_data, json_data + header_.json_size);
}
- const uint32_t bin_data_size = raw_data_size - (header_size + header_.json_size);
+ const uint32_t bin_data_size =
+ raw_data_size - (header_size + header_.json_size);
if (bin_data_size > 0) {
- const char *const bin_data =
- reinterpret_cast<const char*>(raw_data + header_size + header_.json_size);
+ const char* const bin_data = reinterpret_cast<const char*>(
+ raw_data + header_size + header_.json_size);
data_.assign(bin_data, bin_data + bin_data_size);
}
return true;
@@ -124,31 +129,33 @@ bool SecurityQuery::SerializeQuery(const uint8_t *const raw_data,
const std::vector<uint8_t> SecurityQuery::DeserializeQuery() const {
SecurityQuery::QueryHeader deserialize_header(header_);
const uint32_t tmp = deserialize_header.query_id << 8;
- deserialize_header.query_id = LE_TO_BE32(tmp);
+ deserialize_header.query_id = LE_TO_BE32(tmp);
deserialize_header.seq_number = LE_TO_BE32(deserialize_header.seq_number);
- deserialize_header.json_size = LE_TO_BE32(deserialize_header.json_size);
+ deserialize_header.json_size = LE_TO_BE32(deserialize_header.json_size);
const size_t header_size = sizeof(deserialize_header);
// vector of header and raw_data
- std::vector<uint8_t> data_sending(header_size + data_.size() + json_message_.size());
+ std::vector<uint8_t> data_sending(header_size + data_.size() +
+ json_message_.size());
// copy header
memcpy(&data_sending[0], &deserialize_header, header_size);
// copy binary data
std::copy(data_.begin(), data_.end(), data_sending.begin() + header_size);
// copy text (json) data
- std::copy(json_message_.begin(), json_message_.end(),
+ std::copy(json_message_.begin(),
+ json_message_.end(),
data_sending.begin() + header_size + data_.size());
return data_sending;
}
-void SecurityQuery::set_data(const uint8_t *const binary_data,
- const size_t bin_data_size) {
- DCHECK(binary_data);
- DCHECK(bin_data_size);
- data_.assign(binary_data, binary_data + bin_data_size);
+void SecurityQuery::set_data(const uint8_t* const binary_data,
+ const size_t bin_data_size) {
+ DCHECK(binary_data);
+ DCHECK(bin_data_size);
+ data_.assign(binary_data, binary_data + bin_data_size);
}
-void SecurityQuery::set_json_message(const std::string &json_message) {
+void SecurityQuery::set_json_message(const std::string& json_message) {
json_message_ = json_message;
}
@@ -156,11 +163,11 @@ void SecurityQuery::set_connection_key(const uint32_t connection_key) {
connection_key_ = connection_key;
}
-void SecurityQuery::set_header(const SecurityQuery::QueryHeader &header) {
+void SecurityQuery::set_header(const SecurityQuery::QueryHeader& header) {
header_ = header;
}
-const SecurityQuery::QueryHeader &SecurityQuery::get_header() const {
+const SecurityQuery::QueryHeader& SecurityQuery::get_header() const {
return header_;
}
@@ -172,7 +179,7 @@ size_t SecurityQuery::get_data_size() const {
return data_.size();
}
-const std::string &SecurityQuery::get_json_message() const {
+const std::string& SecurityQuery::get_json_message() const {
return json_message_;
}
diff --git a/src/components/security_manager/src/ssl_context_impl.cc b/src/components/security_manager/src/ssl_context_impl.cc
index 09c2efd196..6f53234867 100644
--- a/src/components/security_manager/src/ssl_context_impl.cc
+++ b/src/components/security_manager/src/ssl_context_impl.cc
@@ -37,22 +37,25 @@
#include <openssl/err.h>
#include <memory.h>
#include <map>
+#include <algorithm>
#include "utils/macro.h"
namespace security_manager {
-CryptoManagerImpl::SSLContextImpl::SSLContextImpl(SSL *conn, Mode mode)
- : connection_(conn),
- bioIn_(BIO_new(BIO_s_mem())),
- bioOut_(BIO_new(BIO_s_mem())),
- bioFilter_(NULL),
- // TODO(EZamakhov): get MTU by parameter (from transport)
- // default buffer size is TCP MTU
- buffer_size_(1500),
- buffer_(new uint8_t[buffer_size_]),
- is_handshake_pending_(false),
- mode_(mode) {
+CREATE_LOGGERPTR_GLOBAL(logger_, "SecurityManager")
+
+CryptoManagerImpl::SSLContextImpl::SSLContextImpl(SSL* conn,
+ Mode mode,
+ size_t maximum_payload_size)
+ : connection_(conn)
+ , bioIn_(BIO_new(BIO_s_mem()))
+ , bioOut_(BIO_new(BIO_s_mem()))
+ , bioFilter_(NULL)
+ , buffer_size_(maximum_payload_size)
+ , buffer_(new uint8_t[buffer_size_])
+ , is_handshake_pending_(false)
+ , mode_(mode) {
SSL_set_bio(connection_, bioIn_, bioOut_);
}
@@ -60,7 +63,7 @@ std::string CryptoManagerImpl::SSLContextImpl::LastError() const {
if (!IsInitCompleted()) {
return std::string("Initialization is not completed");
}
- const char *reason = ERR_reason_error_string(ERR_get_error());
+ const char* reason = ERR_reason_error_string(ERR_get_error());
return std::string(reason ? reason : "");
}
@@ -69,137 +72,273 @@ bool CryptoManagerImpl::SSLContextImpl::IsInitCompleted() const {
return SSL_is_init_finished(connection_);
}
-SSLContext::HandshakeResult CryptoManagerImpl::SSLContextImpl::
-StartHandshake(const uint8_t** const out_data, size_t *out_data_size) {
+SSLContext::HandshakeResult CryptoManagerImpl::SSLContextImpl::StartHandshake(
+ const uint8_t** const out_data, size_t* out_data_size) {
is_handshake_pending_ = true;
return DoHandshakeStep(NULL, 0, out_data, out_data_size);
}
namespace {
- size_t aes128_gcm_sha256_max_block_size(size_t mtu) {
- if (mtu < 29)
- return 0;
- return mtu - 29;
- }
- size_t rc4_md5_max_block_size(size_t mtu) {
- if (mtu < 21)
- return 0;
- return mtu - 21;
- }
- size_t rc4_sha_max_block_size(size_t mtu) {
- if (mtu < 25)
- return 0;
- return mtu - 25;
- }
- size_t seed_sha_max_block_size(size_t mtu) {
- if (mtu < 53)
- return 0;
- return ((mtu - 37) & 0xfffffff0) - 5;
- }
- size_t aes128_sha256_max_block_size(size_t mtu) {
- if (mtu < 69)
- return 0;
- return ((mtu - 53) & 0xfffffff0) - 1;
- }
- size_t des_cbc3_sha_max_block_size(size_t mtu) {
- if (mtu < 37)
- return 0;
- return ((mtu - 29) & 0xfffffff8) - 5;
- }
+size_t aes128_gcm_sha256_max_block_size(size_t mtu) {
+ if (mtu < 29)
+ return 0;
+ return mtu - 29;
+}
+size_t rc4_md5_max_block_size(size_t mtu) {
+ if (mtu < 21)
+ return 0;
+ return mtu - 21;
+}
+size_t rc4_sha_max_block_size(size_t mtu) {
+ if (mtu < 25)
+ return 0;
+ return mtu - 25;
+}
+size_t seed_sha_max_block_size(size_t mtu) {
+ if (mtu < 53)
+ return 0;
+ return ((mtu - 37) & 0xfffffff0) - 5;
+}
+size_t aes128_sha256_max_block_size(size_t mtu) {
+ if (mtu < 69)
+ return 0;
+ return ((mtu - 53) & 0xfffffff0) - 1;
+}
+size_t des_cbc3_sha_max_block_size(size_t mtu) {
+ if (mtu < 37)
+ return 0;
+ return ((mtu - 29) & 0xfffffff8) - 5;
+}
} // namespace
std::map<std::string, CryptoManagerImpl::SSLContextImpl::BlockSizeGetter>
CryptoManagerImpl::SSLContextImpl::create_max_block_sizes() {
std::map<std::string, CryptoManagerImpl::SSLContextImpl::BlockSizeGetter> rc;
- rc.insert(std::make_pair("AES128-GCM-SHA256", aes128_gcm_sha256_max_block_size));
- rc.insert(std::make_pair("AES128-SHA256", aes128_sha256_max_block_size));
- rc.insert(std::make_pair("AES128-SHA", seed_sha_max_block_size));
- rc.insert(std::make_pair("AES256-GCM-SHA384", aes128_gcm_sha256_max_block_size));
- rc.insert(std::make_pair("AES256-SHA256", aes128_sha256_max_block_size));
- rc.insert(std::make_pair("AES256-SHA", seed_sha_max_block_size));
- rc.insert(std::make_pair("CAMELLIA128-SHA", seed_sha_max_block_size));
- rc.insert(std::make_pair("CAMELLIA256-SHA", seed_sha_max_block_size));
- rc.insert(std::make_pair("DES-CBC3-SHA", des_cbc3_sha_max_block_size));
- rc.insert(std::make_pair("DES-CBC-SHA", des_cbc3_sha_max_block_size));
- rc.insert(std::make_pair("RC4-MD5", rc4_md5_max_block_size));
- rc.insert(std::make_pair("RC4-SHA", rc4_sha_max_block_size));
- rc.insert(std::make_pair("SEED-SHA", seed_sha_max_block_size));
+ rc.insert(
+ std::make_pair("AES128-GCM-SHA256", aes128_gcm_sha256_max_block_size));
+ rc.insert(std::make_pair("AES128-SHA256", aes128_sha256_max_block_size));
+ rc.insert(std::make_pair("AES128-SHA", seed_sha_max_block_size));
+ rc.insert(
+ std::make_pair("AES256-GCM-SHA384", aes128_gcm_sha256_max_block_size));
+ rc.insert(std::make_pair("AES256-SHA256", aes128_sha256_max_block_size));
+ rc.insert(std::make_pair("AES256-SHA", seed_sha_max_block_size));
+ rc.insert(std::make_pair("CAMELLIA128-SHA", seed_sha_max_block_size));
+ rc.insert(std::make_pair("CAMELLIA256-SHA", seed_sha_max_block_size));
+ rc.insert(std::make_pair("DES-CBC3-SHA", des_cbc3_sha_max_block_size));
+ rc.insert(std::make_pair("DES-CBC-SHA", des_cbc3_sha_max_block_size));
+ rc.insert(std::make_pair("RC4-MD5", rc4_md5_max_block_size));
+ rc.insert(std::make_pair("RC4-SHA", rc4_sha_max_block_size));
+ rc.insert(std::make_pair("SEED-SHA", seed_sha_max_block_size));
return rc;
}
std::map<std::string, CryptoManagerImpl::SSLContextImpl::BlockSizeGetter>
-CryptoManagerImpl::SSLContextImpl::max_block_sizes =
- CryptoManagerImpl::SSLContextImpl::create_max_block_sizes();
+ CryptoManagerImpl::SSLContextImpl::max_block_sizes =
+ CryptoManagerImpl::SSLContextImpl::create_max_block_sizes();
+
+void CryptoManagerImpl::SSLContextImpl::PrintCertData(
+ X509* cert, const std::string& cert_owner) {
+ if (cert) {
+ X509_NAME* subj_name = X509_get_subject_name(cert);
+ char* subj = X509_NAME_oneline(subj_name, NULL, 0);
+ if (subj) {
+ std::replace(subj, subj + strlen(subj), '/', ' ');
+ LOG4CXX_DEBUG(logger_, cert_owner << " subject:" << subj);
+ OPENSSL_free(subj);
+ }
+ char* issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
+ if (issuer) {
+ std::replace(issuer, issuer + strlen(issuer), '/', ' ');
+ LOG4CXX_DEBUG(logger_, cert_owner << " issuer:" << issuer);
+ OPENSSL_free(issuer);
+ }
-SSLContext::HandshakeResult CryptoManagerImpl::SSLContextImpl::
-DoHandshakeStep(const uint8_t* const in_data, size_t in_data_size,
- const uint8_t** const out_data, size_t* out_data_size) {
- DCHECK(out_data);
- DCHECK(out_data_size);
- *out_data = NULL;
- *out_data_size = 0;
- // TODO(Ezamakhov): add test - hanshake fail -> restart StartHandshake
- sync_primitives::AutoLock locker(bio_locker);
- if (SSL_is_init_finished(connection_)) {
- is_handshake_pending_ = false;
- return SSLContext::Handshake_Result_Success;
+ ASN1_TIME* notBefore = X509_get_notBefore(cert);
+ ASN1_TIME* notAfter = X509_get_notAfter(cert);
+
+ if (notBefore) {
+ LOG4CXX_DEBUG(logger_, " Start date: " << (char*)notBefore->data);
+ }
+ if (notAfter) {
+ LOG4CXX_DEBUG(logger_, " End date: " << (char*)notAfter->data);
+ }
}
+}
+
+void CryptoManagerImpl::SSLContextImpl::PrintCertInfo() {
+ PrintCertData(SSL_get_certificate(connection_), "HU's");
+
+ STACK_OF(X509)* peer_certs = SSL_get_peer_cert_chain(connection_);
+ while (sk_X509_num(peer_certs) > 0) {
+ X509* cert = sk_X509_pop(peer_certs);
+ PrintCertData(cert, "SERVERS");
+ }
+}
+
+SSLContext::HandshakeResult
+CryptoManagerImpl::SSLContextImpl::CheckCertContext() {
+ X509* cert = SSL_get_peer_certificate(connection_);
+ if (!cert) {
+ // According to the openssl documentation the peer certificate
+ // might be ommitted for the SERVER but required for the cient.
+ return CLIENT == mode_ ? Handshake_Result_Fail : Handshake_Result_Success;
+ }
+
+ X509_NAME* subj_name = X509_get_subject_name(cert);
+
+ const std::string& cn = GetTextBy(subj_name, NID_commonName);
+ const std::string& sn = GetTextBy(subj_name, NID_serialNumber);
+
+ if (!(hsh_context_.expected_cn.CompareIgnoreCase(cn.c_str()))) {
+ LOG4CXX_ERROR(logger_,
+ "Trying to run handshake with wrong app name: "
+ << cn << ". Expected app name: "
+ << hsh_context_.expected_cn.AsMBString());
+ return Handshake_Result_AppNameMismatch;
+ }
+
+ if (!(hsh_context_.expected_sn.CompareIgnoreCase(sn.c_str()))) {
+ LOG4CXX_ERROR(logger_,
+ "Trying to run handshake with wrong app id: "
+ << sn << ". Expected app id: "
+ << hsh_context_.expected_sn.AsMBString());
+ return Handshake_Result_AppIDMismatch;
+ }
+ return Handshake_Result_Success;
+}
+
+bool CryptoManagerImpl::SSLContextImpl::ReadHandshakeData(
+ const uint8_t** const out_data, size_t* out_data_size) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ const size_t pend = BIO_ctrl_pending(bioOut_);
+ LOG4CXX_DEBUG(logger_, "Available " << pend << " bytes for handshake");
+
+ if (pend > 0) {
+ LOG4CXX_DEBUG(logger_, "Reading handshake data");
+ EnsureBufferSizeEnough(pend);
+
+ const int read_count = BIO_read(bioOut_, buffer_, pend);
+ if (read_count == static_cast<int>(pend)) {
+ *out_data_size = read_count;
+ *out_data = buffer_;
+ } else {
+ LOG4CXX_WARN(logger_, "BIO read fail");
+ is_handshake_pending_ = false;
+ ResetConnection();
+ return false;
+ }
+ }
+
+ return true;
+}
+bool CryptoManagerImpl::SSLContextImpl::WriteHandshakeData(
+ const uint8_t* const in_data, size_t in_data_size) {
+ LOG4CXX_AUTO_TRACE(logger_);
if (in_data && in_data_size) {
const int ret = BIO_write(bioIn_, in_data, in_data_size);
if (ret <= 0) {
is_handshake_pending_ = false;
- SSL_clear(connection_);
- return SSLContext::Handshake_Result_AbnormalFail;
+ ResetConnection();
+ return Handshake_Result_AbnormalFail;
}
}
+ return true;
+}
+SSLContext::HandshakeResult
+CryptoManagerImpl::SSLContextImpl::PerformHandshake() {
const int handshake_result = SSL_do_handshake(connection_);
if (handshake_result == 1) {
+ const HandshakeResult result = CheckCertContext();
+ if (result != Handshake_Result_Success) {
+ ResetConnection();
+ is_handshake_pending_ = false;
+ return result;
+ }
+
+ LOG4CXX_DEBUG(logger_, "SSL handshake successfully finished");
// Handshake is successful
bioFilter_ = BIO_new(BIO_f_ssl());
BIO_set_ssl(bioFilter_, connection_, BIO_NOCLOSE);
- const SSL_CIPHER *cipher = SSL_get_current_cipher(connection_);
+ const SSL_CIPHER* cipher = SSL_get_current_cipher(connection_);
max_block_size_ = max_block_sizes[SSL_CIPHER_get_name(cipher)];
is_handshake_pending_ = false;
+
} else if (handshake_result == 0) {
SSL_clear(connection_);
is_handshake_pending_ = false;
- return SSLContext::Handshake_Result_Fail;
- } else if (SSL_get_error(connection_, handshake_result) != SSL_ERROR_WANT_READ) {
- SSL_clear(connection_);
- is_handshake_pending_ = false;
- return SSLContext::Handshake_Result_AbnormalFail;
+ return Handshake_Result_Fail;
+ } else {
+ const int error = SSL_get_error(connection_, handshake_result);
+ if (error != SSL_ERROR_WANT_READ) {
+ const long error = SSL_get_verify_result(connection_);
+ SetHandshakeError(error);
+ LOG4CXX_WARN(logger_,
+ "Handshake failed with error "
+ << " -> " << SSL_get_error(connection_, error) << " \""
+ << LastError() << '"');
+ ResetConnection();
+ is_handshake_pending_ = false;
+
+ // In case error happened but ssl verification shows OK
+ // method will return AbnormalFail.
+ if (X509_V_OK == error) {
+ return Handshake_Result_AbnormalFail;
+ }
+ return openssl_error_convert_to_internal(error);
+ }
}
+ return Handshake_Result_Success;
+}
- const size_t pend = BIO_ctrl_pending(bioOut_);
+SSLContext::HandshakeResult CryptoManagerImpl::SSLContextImpl::DoHandshakeStep(
+ const uint8_t* const in_data,
+ size_t in_data_size,
+ const uint8_t** const out_data,
+ size_t* out_data_size) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK(out_data);
+ DCHECK(out_data_size);
+ *out_data = NULL;
+ *out_data_size = 0;
- if (pend) {
- EnsureBufferSizeEnough(pend);
+ // TODO(Ezamakhov): add test - hanshake fail -> restart StartHandshake
+ {
+ sync_primitives::AutoLock locker(bio_locker);
- const int read_count = BIO_read(bioOut_, buffer_, pend);
- if (read_count == static_cast<int>(pend)) {
- *out_data_size = read_count;
- *out_data = buffer_;
- } else {
+ if (SSL_is_init_finished(connection_)) {
+ LOG4CXX_DEBUG(logger_, "SSL initilization is finished");
is_handshake_pending_ = false;
- SSL_clear(connection_);
- return SSLContext::Handshake_Result_AbnormalFail;
+ return Handshake_Result_Success;
}
}
- return SSLContext::Handshake_Result_Success;
-}
+ if (!WriteHandshakeData(in_data, in_data_size)) {
+ return Handshake_Result_AbnormalFail;
+ }
-bool CryptoManagerImpl::SSLContextImpl::Encrypt(
- const uint8_t * const in_data, size_t in_data_size,
- const uint8_t ** const out_data, size_t *out_data_size) {
+ PrintCertInfo();
+ const HandshakeResult res = PerformHandshake();
+ if (res != Handshake_Result_Success) {
+ return res;
+ }
+
+ if (!ReadHandshakeData(out_data, out_data_size)) {
+ return Handshake_Result_AbnormalFail;
+ }
+
+ return res;
+}
+
+bool CryptoManagerImpl::SSLContextImpl::Encrypt(const uint8_t* const in_data,
+ size_t in_data_size,
+ const uint8_t** const out_data,
+ size_t* out_data_size) {
sync_primitives::AutoLock locker(bio_locker);
- if (!SSL_is_init_finished(connection_) ||
- !in_data ||
- !in_data_size) {
+ if (!SSL_is_init_finished(connection_) || !in_data || !in_data_size) {
return false;
}
@@ -220,10 +359,10 @@ bool CryptoManagerImpl::SSLContextImpl::Encrypt(
return true;
}
-bool CryptoManagerImpl::SSLContextImpl::Decrypt(
- const uint8_t * const in_data, size_t in_data_size,
- const uint8_t ** const out_data, size_t *out_data_size) {
-
+bool CryptoManagerImpl::SSLContextImpl::Decrypt(const uint8_t* const in_data,
+ size_t in_data_size,
+ const uint8_t** const out_data,
+ size_t* out_data_size) {
sync_primitives::AutoLock locker(bio_locker);
if (!SSL_is_init_finished(connection_)) {
return false;
@@ -274,14 +413,94 @@ CryptoManagerImpl::SSLContextImpl::~SSLContextImpl() {
delete[] buffer_;
}
+void CryptoManagerImpl::SSLContextImpl::SetHandshakeError(const int error) {
+ const char* error_str = X509_verify_cert_error_string(error);
+ if (error_str) {
+ last_error_ = error_str;
+ } else {
+ // Error will be updated with the next LastError call
+ last_error_.clear();
+ }
+}
+
+void CryptoManagerImpl::SSLContextImpl::ResetConnection() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ const int shutdown_result = SSL_shutdown(connection_);
+ if (shutdown_result != 1) {
+ const size_t pend = BIO_ctrl_pending(bioOut_);
+ LOG4CXX_DEBUG(logger_, "Available " << pend << " bytes for shutdown");
+ if (pend > 0) {
+ LOG4CXX_DEBUG(logger_, "Reading shutdown data");
+ EnsureBufferSizeEnough(pend);
+ BIO_read(bioOut_, buffer_, pend);
+ }
+ SSL_shutdown(connection_);
+ }
+ LOG4CXX_DEBUG(logger_, "SSL connection recreation");
+ SSL_CTX* ssl_context = connection_->ctx;
+ SSL_free(connection_);
+ connection_ = SSL_new(ssl_context);
+ if (mode_ == SERVER) {
+ SSL_set_accept_state(connection_);
+ } else {
+ SSL_set_connect_state(connection_);
+ }
+ bioIn_ = BIO_new(BIO_s_mem());
+ bioOut_ = BIO_new(BIO_s_mem());
+ SSL_set_bio(connection_, bioIn_, bioOut_);
+}
+
+void CryptoManagerImpl::SSLContextImpl::SetHandshakeContext(
+ const SSLContext::HandshakeContext& hsh_ctx) {
+ hsh_context_ = hsh_ctx;
+}
+
void CryptoManagerImpl::SSLContextImpl::EnsureBufferSizeEnough(size_t size) {
if (buffer_size_ < size) {
delete[] buffer_;
- buffer_ = new(std::nothrow) uint8_t[size];
+ buffer_ = new (std::nothrow) uint8_t[size];
if (buffer_) {
buffer_size_ = size;
}
}
}
+SSLContext::HandshakeResult
+CryptoManagerImpl::SSLContextImpl::openssl_error_convert_to_internal(
+ const long error) {
+ switch (error) {
+ case X509_V_ERR_CERT_HAS_EXPIRED:
+ return Handshake_Result_CertExpired;
+ case X509_V_ERR_CERT_NOT_YET_VALID:
+ return Handshake_Result_NotYetValid;
+ case X509_V_ERR_SUBJECT_ISSUER_MISMATCH:
+ case X509_V_ERR_CERT_SIGNATURE_FAILURE:
+ case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
+ case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
+ return Handshake_Result_CertNotSigned;
+ default:
+ return Handshake_Result_Fail;
+ }
+}
+
+std::string CryptoManagerImpl::SSLContextImpl::GetTextBy(X509_NAME* name,
+ int object) const {
+ const int req_len = X509_NAME_get_text_by_NID(name, object, NULL, 0);
+
+ if (-1 == req_len) {
+ LOG4CXX_WARN(logger_,
+ "Unable to obtain object: " << object << " from certificate");
+ return std::string();
+ }
+
+ std::vector<char> data;
+ data.resize(req_len + 1);
+ X509_NAME_get_text_by_NID(name, object, &data.front(), data.size());
+
+ std::string str(data.begin(), data.end() - 1);
+
+ std::transform(str.begin(), str.end(), str.begin(), ::tolower);
+ return str;
+}
+
} // namespace security_manager
diff --git a/src/components/security_manager/test/CMakeLists.txt b/src/components/security_manager/test/CMakeLists.txt
index 6554bb797f..6707e5ea5a 100644
--- a/src/components/security_manager/test/CMakeLists.txt
+++ b/src/components/security_manager/test/CMakeLists.txt
@@ -35,14 +35,17 @@ include_directories(
${COMPONENTS_DIR}/protocol_handler/test/include
${COMPONENTS_DIR}/transport_manager/test/include
${COMPONENTS_DIR}/security_manager/include
- include
+ ${COMPONENTS_DIR}/resumption/include
+ ${JSONCPP_INCLUDE_DIRECTORY}
)
set(SOURCES
- #${COMPONENTS_DIR}/security_manager/test/crypto_manager_impl_test.cc
- #${COMPONENTS_DIR}/security_manager/test/security_manager_test.cc
- #${COMPONENTS_DIR}/security_manager/test/security_query_test.cc
+ ${COMPONENTS_DIR}/security_manager/test/crypto_manager_impl_test.cc
+ ${COMPONENTS_DIR}/security_manager/test/security_manager_test.cc
+ ${COMPONENTS_DIR}/security_manager/test/security_query_test.cc
${COMPONENTS_DIR}/security_manager/test/security_query_matcher.cc
+ ${COMPONENTS_DIR}/security_manager/test/ssl_context_test.cc
+ ${COMPONENTS_DIR}/security_manager/test/ssl_certificate_handshake_test.cc
)
set(LIBRARIES
@@ -55,12 +58,17 @@ set(CERT_LIST
${CMAKE_SOURCE_DIR}/mykey.pem
)
+add_custom_target(generate_certificates
+ COMMAND ${CMAKE_SOURCE_DIR}/tools/Utils/generate_test_certificates.py
+ -d=${CMAKE_CURRENT_BINARY_DIR} -s
+ WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
+)
+
foreach( file_i ${CERT_LIST})
file(COPY ${file_i} DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
endforeach( file_i )
-add_library (test_security_manager ${SOURCES})
-target_link_libraries (test_security_manager ${LIBRARIES} )
create_test (security_manager_test "${SOURCES}" "${LIBRARIES}")
+add_dependencies(security_manager_test generate_certificates)
endif ()
diff --git a/src/components/security_manager/test/crypto_manager_impl_test.cc b/src/components/security_manager/test/crypto_manager_impl_test.cc
index 52ac42b418..27f91866ac 100644
--- a/src/components/security_manager/test/crypto_manager_impl_test.cc
+++ b/src/components/security_manager/test/crypto_manager_impl_test.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,433 +30,239 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include <gtest/gtest.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <unistd.h>
-
-#include "security_manager/crypto_manager.h"
-#include "security_manager/crypto_manager_impl.h"
-#include "security_manager/ssl_context.h"
-
#ifdef __QNXNTO__
#include <openssl/ssl3.h>
#else
-#include <openssl/tls1.h>
-#endif
+#include <openssl/ssl.h>
+#endif //__QNXNTO__
+#include <limits>
+#include <fstream>
+#include <sstream>
+
+#include "gtest/gtest.h"
+#include "security_manager/crypto_manager_impl.h"
+#include "security_manager/mock_security_manager_settings.h"
+
+using ::testing::Return;
+using ::testing::ReturnRef;
+using ::testing::NiceMock;
+
+namespace {
+const size_t kUpdatesBeforeHour = 24;
+const std::string kAllCiphers = "ALL";
+const std::string kCaCertPath = "";
#ifdef __QNXNTO__
-#define FORD_CIPHER SSL3_TXT_RSA_DES_192_CBC3_SHA
+const std::string kFordCipher = SSL3_TXT_RSA_DES_192_CBC3_SHA;
#else
// Used cipher from ford protocol requirement
-#define FORD_CIPHER TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384
+const std::string kFordCipher = TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384;
#endif
-
-#define ALL_CIPHERS "ALL"
+}
namespace test {
namespace components {
-namespace security_manager_test {
+namespace crypto_manager_test {
-namespace {
-bool isErrorFatal(SSL *connection, int res) {
- const int error = SSL_get_error(connection, res);
- return (error != SSL_ERROR_WANT_READ && error != SSL_ERROR_WANT_WRITE);
-}
-}
-// TODO(EZamakhov): May be split to SSLContext and Cryptomanager tests (separate files)
-// TODO(EZamakhov): add test for EnsureBufferSizeEnough
-class SSLTest : public testing::Test {
+class CryptoManagerTest : public testing::Test {
protected:
static void SetUpTestCase() {
- crypto_manager = new security_manager::CryptoManagerImpl();
- const bool crypto_manager_initialization = crypto_manager->Init(
- security_manager::SERVER, security_manager::TLSv1_2, "mycert.pem",
- "mykey.pem", FORD_CIPHER, false);
- EXPECT_TRUE(crypto_manager_initialization);
-
- client_manager = new security_manager::CryptoManagerImpl();
- const bool client_manager_initialization = client_manager->Init(
- security_manager::CLIENT, security_manager::TLSv1_2, "", "",
- FORD_CIPHER,
- false);
- EXPECT_TRUE(client_manager_initialization);
+ std::ifstream certificate_file("server/spt_credential.p12.enc");
+ ASSERT_TRUE(certificate_file.is_open())
+ << "Could not open certificate data file";
+
+ const std::string certificate(
+ (std::istreambuf_iterator<char>(certificate_file)),
+ std::istreambuf_iterator<char>());
+ ASSERT_FALSE(certificate.empty()) << "Certificate data file is empty";
+ certificate_data_base64_ = certificate;
}
- static void TearDownTestCase() {
- crypto_manager->Finish();
- client_manager->Finish();
- delete crypto_manager;
- delete client_manager;
+ void SetUp() OVERRIDE {
+ ASSERT_FALSE(certificate_data_base64_.empty());
+ mock_security_manager_settings_ =
+ new NiceMock<security_manager_test::MockCryptoManagerSettings>();
+ utils::SharedPtr<security_manager::CryptoManagerSettings> scrypto =
+ utils::SharedPtr<security_manager::CryptoManagerSettings>::
+ static_pointer_cast<security_manager::CryptoManagerSettings>(
+ mock_security_manager_settings_);
+ crypto_manager_ = new security_manager::CryptoManagerImpl(scrypto);
}
- virtual void SetUp() {
- server_ctx = crypto_manager->CreateSSLContext();
- client_ctx = client_manager->CreateSSLContext();
+ void TearDown() OVERRIDE {
+ delete mock_security_manager_settings_;
+ testing::Mock::AsyncVerifyAndClearExpectations(1000);
}
- virtual void TearDown() {
- crypto_manager->ReleaseSSLContext(server_ctx);
- client_manager->ReleaseSSLContext(client_ctx);
+ void InitSecurityManager() {
+ SetInitialValues(
+ security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
+ const bool crypto_manager_initialization = crypto_manager_->Init();
+ ASSERT_TRUE(crypto_manager_initialization);
}
- static security_manager::CryptoManager* crypto_manager;
- static security_manager::CryptoManager* client_manager;
- security_manager::SSLContext *server_ctx;
- security_manager::SSLContext *client_ctx;
-};
+ void SetInitialValues(security_manager::Mode mode,
+ security_manager::Protocol protocol,
+ const std::string& cipher) {
+ ON_CALL(*mock_security_manager_settings_, security_manager_mode())
+ .WillByDefault(Return(mode));
+ ON_CALL(*mock_security_manager_settings_, security_manager_protocol_name())
+ .WillByDefault(Return(protocol));
+ ON_CALL(*mock_security_manager_settings_, certificate_data())
+ .WillByDefault(ReturnRef(certificate_data_base64_));
+ ON_CALL(*mock_security_manager_settings_, ciphers_list())
+ .WillByDefault(ReturnRef(cipher));
+ ON_CALL(*mock_security_manager_settings_, ca_cert_path())
+ .WillByDefault(ReturnRef(kCaCertPath));
+ ON_CALL(*mock_security_manager_settings_, verify_peer())
+ .WillByDefault(Return(false));
+ }
+
+ security_manager::CryptoManager* crypto_manager_;
+ static std::string certificate_data_base64_;
-security_manager::CryptoManager* SSLTest::crypto_manager;
-security_manager::CryptoManager* SSLTest::client_manager;
+ NiceMock<security_manager_test::MockCryptoManagerSettings>*
+ mock_security_manager_settings_;
+};
+std::string CryptoManagerTest::certificate_data_base64_;
-TEST(CryptoManagerTest, UsingBeforeInit) {
- security_manager::CryptoManager *crypto_manager = new security_manager::CryptoManagerImpl();
- EXPECT_TRUE(crypto_manager->CreateSSLContext() == NULL);
- EXPECT_EQ(crypto_manager->LastError(), std::string ("Initialization is not completed"));
- delete crypto_manager;
+TEST_F(CryptoManagerTest, UsingBeforeInit) {
+ EXPECT_TRUE(crypto_manager_->CreateSSLContext() == NULL);
+ EXPECT_EQ(std::string("Initialization is not completed"),
+ crypto_manager_->LastError());
}
-TEST(CryptoManagerTest, WrongInit) {
- security_manager::CryptoManager *crypto_manager = new security_manager::CryptoManagerImpl();
+TEST_F(CryptoManagerTest, WrongInit) {
+ // We have to cast (-1) to security_manager::Protocol Enum to be accepted by
+ // crypto_manager_->Init(...)
+ // Unknown protocol version
+ security_manager::Protocol UNKNOWN =
+ static_cast<security_manager::Protocol>(-1);
- //We have to cast (-1) to security_manager::Protocol Enum to be accepted by crypto_manager->Init(...)
- security_manager::Protocol UNKNOWN = static_cast<security_manager::Protocol>(-1);
+ EXPECT_CALL(*mock_security_manager_settings_, security_manager_mode())
+ .WillRepeatedly(Return(security_manager::SERVER));
+ EXPECT_CALL(*mock_security_manager_settings_,
+ security_manager_protocol_name()).WillOnce(Return(UNKNOWN));
+ EXPECT_FALSE(crypto_manager_->Init());
- // Unknown protocol version
- EXPECT_FALSE(crypto_manager->Init(security_manager::SERVER, UNKNOWN,
- "mycert.pem", "mykey.pem", FORD_CIPHER, false));
-
- EXPECT_FALSE(crypto_manager->LastError().empty());
- // Unexistent cert file
- EXPECT_FALSE(crypto_manager->Init(security_manager::SERVER, security_manager::TLSv1_2,
- "unexists_file.pem", "mykey.pem", FORD_CIPHER, false));
- EXPECT_FALSE(crypto_manager->LastError().empty());
- // Unexistent key file
- EXPECT_FALSE(crypto_manager->Init(security_manager::SERVER, security_manager::TLSv1_2,
- "mycert.pem", "unexists_file.pem", FORD_CIPHER, false));
- EXPECT_FALSE(crypto_manager->LastError().empty());
+ EXPECT_NE(std::string(), crypto_manager_->LastError());
// Unexistent cipher value
- EXPECT_FALSE(crypto_manager->Init(security_manager::SERVER, security_manager::TLSv1_2,
- "mycert.pem", "mykey.pem", "INVALID_UNKNOWN_CIPHER", false));
- EXPECT_FALSE(crypto_manager->LastError().empty());
+ const std::string invalid_cipher = "INVALID_UNKNOWN_CIPHER";
+ EXPECT_CALL(*mock_security_manager_settings_,
+ security_manager_protocol_name())
+ .WillOnce(Return(security_manager::TLSv1_2));
+ EXPECT_CALL(*mock_security_manager_settings_, certificate_data())
+ .WillOnce(ReturnRef(certificate_data_base64_));
+ EXPECT_CALL(*mock_security_manager_settings_, ciphers_list())
+ .WillRepeatedly(ReturnRef(invalid_cipher));
+ EXPECT_FALSE(crypto_manager_->Init());
+
+ EXPECT_NE(std::string(), crypto_manager_->LastError());
+}
- delete crypto_manager;
+// #ifndef __QNXNTO__
+TEST_F(CryptoManagerTest, CorrectInit) {
+ // Empty cert and key values for SERVER
+ SetInitialValues(
+ security_manager::SERVER, security_manager::TLSv1_2, kFordCipher);
+ EXPECT_TRUE(crypto_manager_->Init());
+
+ // Recall init
+ SetInitialValues(
+ security_manager::CLIENT, security_manager::TLSv1_2, kFordCipher);
+ EXPECT_TRUE(crypto_manager_->Init());
+
+ // Recall init with other protocols
+ SetInitialValues(
+ security_manager::CLIENT, security_manager::TLSv1_2, kFordCipher);
+ EXPECT_TRUE(crypto_manager_->Init());
+
+ SetInitialValues(
+ security_manager::CLIENT, security_manager::TLSv1_1, kFordCipher);
+ EXPECT_TRUE(crypto_manager_->Init());
+
+ // Cipher value
+ SetInitialValues(
+ security_manager::SERVER, security_manager::TLSv1_2, kAllCiphers);
+ EXPECT_TRUE(crypto_manager_->Init());
}
+// #endif // __QNX__
-//TEST(CryptoManagerTest, CorrectInit) {
-// security_manager::CryptoManager *crypto_manager = new security_manager::CryptoManagerImpl();
-// // Empty cert and key values for SERVER
-// EXPECT_TRUE(crypto_manager->Init(security_manager::SERVER, security_manager::TLSv1_2,
-// "", "", FORD_CIPHER, false));
-// EXPECT_TRUE(crypto_manager->LastError().empty());
-// // Recall init
-// EXPECT_TRUE(crypto_manager->Init(security_manager::CLIENT, security_manager::TLSv1_2,
-// "", "", FORD_CIPHER, false));
-// EXPECT_TRUE(crypto_manager->LastError().empty());
-// // Recall init with other protocols
-// EXPECT_TRUE(crypto_manager->Init(security_manager::CLIENT, security_manager::TLSv1_1,
-// "", "", FORD_CIPHER, false));
-// EXPECT_TRUE(crypto_manager->LastError().empty());
-// EXPECT_TRUE(crypto_manager->Init(security_manager::CLIENT, security_manager::TLSv1,
-// "", "", FORD_CIPHER, false));
-// EXPECT_TRUE(crypto_manager->LastError().empty());
-
-// // Cipher value
-// EXPECT_TRUE(crypto_manager->Init(security_manager::SERVER, security_manager::TLSv1_2,
-// "mycert.pem", "mykey.pem", ALL_CIPHERS, false));
-// EXPECT_TRUE(crypto_manager->LastError().empty());
-// delete crypto_manager;
-//}
-
-TEST(CryptoManagerTest, ReleaseNull) {
- using security_manager::CryptoManager;
- using security_manager::CryptoManagerImpl;
-
- CryptoManager *cm = new CryptoManagerImpl();
- EXPECT_NO_THROW(cm->ReleaseSSLContext(NULL));
- delete cm;
+TEST_F(CryptoManagerTest, ReleaseSSLContext_Null) {
+ EXPECT_NO_THROW(crypto_manager_->ReleaseSSLContext(NULL));
}
-TEST_F(SSLTest, BrokenHandshake) {
- const uint8_t *server_buf;
- const uint8_t *client_buf;
- size_t server_buf_len;
- size_t client_buf_len;
- ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
- client_ctx->StartHandshake(&client_buf,
- &client_buf_len));
- ASSERT_FALSE(client_buf == NULL);
- ASSERT_GT(client_buf_len, 0u);
- // Broke 3 bytes for get abnormal fail of handshake
- const_cast<uint8_t*>(client_buf)[0] ^= 0xFF;
- const_cast<uint8_t*>(client_buf)[client_buf_len / 2] ^= 0xFF;
- const_cast<uint8_t*>(client_buf)[client_buf_len - 1] ^= 0xFF;
- ASSERT_EQ(security_manager::SSLContext::Handshake_Result_AbnormalFail,
- server_ctx->DoHandshakeStep(client_buf,
- client_buf_len,
- &server_buf,
- &server_buf_len));
+TEST_F(CryptoManagerTest, CreateReleaseSSLContext) {
+ const size_t max_payload_size = 1000u;
+ SetInitialValues(
+ security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
+ EXPECT_TRUE(crypto_manager_->Init());
+ EXPECT_CALL(*mock_security_manager_settings_, security_manager_mode())
+ .Times(2)
+ .WillRepeatedly(Return(security_manager::CLIENT));
+ EXPECT_CALL(*mock_security_manager_settings_, maximum_payload_size())
+ .Times(1)
+ .WillRepeatedly(Return(max_payload_size));
+
+ security_manager::SSLContext* context = crypto_manager_->CreateSSLContext();
+ EXPECT_TRUE(context);
+ EXPECT_NO_THROW(crypto_manager_->ReleaseSSLContext(context));
}
-// TODO(EZamakhov): split to SSL/TLS1/1.1/1.2 tests
-// TODO{ALeshin}: APPLINK-10846
-//TEST_F(SSLTest, Positive) {
-
-// const uint8_t *server_buf;
-// const uint8_t *client_buf;
-// size_t server_buf_len;
-// size_t client_buf_len;
-// ASSERT_EQ(client_ctx->StartHandshake(&client_buf,
-// &client_buf_len),
-// security_manager::SSLContext::Handshake_Result_Success);
-// ASSERT_FALSE(client_buf == NULL);
-// ASSERT_GT(client_buf_len, 0u);
-
-// for (;;) {
-// ASSERT_EQ(server_ctx->DoHandshakeStep(client_buf,
-// client_buf_len,
-// &server_buf,
-// &server_buf_len),
-// security_manager::SSLContext::Handshake_Result_Success);
-// ASSERT_FALSE(server_buf == NULL);
-// ASSERT_GT(server_buf_len, 0u);
-
-// ASSERT_EQ(client_ctx->DoHandshakeStep(server_buf,
-// server_buf_len,
-// &client_buf,
-// &client_buf_len),
-// security_manager::SSLContext::Handshake_Result_Success);
-// if (server_ctx->IsInitCompleted()) {
-// break;
-// }
-
-// ASSERT_FALSE(client_buf == NULL);
-// ASSERT_GT(client_buf_len, 0u);
-// }
-// // expect empty buffers after init complete
-// ASSERT_TRUE(client_buf == NULL);
-// ASSERT_EQ(client_buf_len, 0u);
-// // expect both side initialization complete
-// EXPECT_TRUE(client_ctx->IsInitCompleted());
-// EXPECT_TRUE(server_ctx->IsInitCompleted());
-
-// // Encrypt text on client side
-// const uint8_t *text = reinterpret_cast<const uint8_t*>("abra");
-// const uint8_t *encrypted_text = 0;
-// size_t text_len = 4;
-// size_t encrypted_text_len;
-// EXPECT_TRUE(client_ctx->Encrypt(text, text_len, &encrypted_text, &encrypted_text_len));
-
-// ASSERT_NE(encrypted_text, (void*)NULL);
-// ASSERT_GT(encrypted_text_len, 0u);
-
-// // Decrypt text on server side
-// EXPECT_TRUE(server_ctx->Decrypt(encrypted_text, encrypted_text_len, &text, &text_len));
-// ASSERT_NE(text, (void*)NULL);
-// ASSERT_GT(text_len, 0u);
-
-// ASSERT_EQ(strncmp(reinterpret_cast<const char*>(text),
-// "abra",
-// 4), 0);
-//}
-
-//TODO{Aleshin}: APPLINK-10846
-//TEST_F(SSLTest, EcncryptionFail) {
-
-// const uint8_t *server_buf;
-// const uint8_t *client_buf;
-// size_t server_buf_len;
-// size_t client_buf_len;
-// ASSERT_EQ(client_ctx->StartHandshake(&client_buf,
-// &client_buf_len),
-// security_manager::SSLContext::Handshake_Result_Success);
-
-// while (!server_ctx->IsInitCompleted()) {
-// ASSERT_FALSE(client_buf == NULL);
-// ASSERT_GT(client_buf_len, 0u);
-// ASSERT_EQ(server_ctx->DoHandshakeStep(client_buf, client_buf_len,
-// &server_buf, &server_buf_len),
-// security_manager::SSLContext::Handshake_Result_Success);
-// ASSERT_FALSE(server_buf == NULL);
-// ASSERT_GT(server_buf_len, 0u);
-
-// ASSERT_EQ(client_ctx->DoHandshakeStep(server_buf, server_buf_len,
-// &client_buf, &client_buf_len),
-// security_manager::SSLContext::Handshake_Result_Success);
-// }
-// // expect empty buffers after init complete
-// ASSERT_TRUE(client_buf == NULL);
-// ASSERT_EQ(client_buf_len, 0u);
-// // expect both side initialization complete
-// EXPECT_TRUE(client_ctx->IsInitCompleted());
-// EXPECT_TRUE(server_ctx->IsInitCompleted());
-
-// // Encrypt text on client side
-// const uint8_t *text = reinterpret_cast<const uint8_t*>("abra");
-// const uint8_t *encrypted_text = 0;
-// size_t text_len = 4;
-// size_t encrypted_text_len;
-// EXPECT_TRUE(client_ctx->Encrypt(text, text_len, &encrypted_text, &encrypted_text_len));
-// ASSERT_NE(encrypted_text, (void*)NULL);
-// ASSERT_GT(encrypted_text_len, 0u);
-
-// std::vector<uint8_t> broken(encrypted_text, encrypted_text + encrypted_text_len);
-// // Broke message
-// broken[encrypted_text_len / 2] ^= 0xFF;
-
-// const uint8_t *out_text;
-// size_t out_text_size;
-// // Decrypt broken text on server side
-// EXPECT_FALSE(server_ctx->Decrypt(&broken[0], broken.size(), &out_text, &out_text_size));
-
-// // Check after broken message that server encryption and decryption fail
-// // Encrypte message on server side
-// EXPECT_FALSE(server_ctx->Decrypt(encrypted_text, encrypted_text_len, &out_text, &out_text_size));
-// EXPECT_FALSE(server_ctx->Encrypt(text, text_len, &encrypted_text, &encrypted_text_len));
-//}
+TEST_F(CryptoManagerTest, OnCertificateUpdated) {
+ InitSecurityManager();
+ EXPECT_TRUE(crypto_manager_->OnCertificateUpdated(certificate_data_base64_));
+}
-/*
- TEST_F(SSLTest, DISABLED_BadData) {
- using security_manager::LastError;
- int res = 0;
-
- uint8_t *outBuf = new uint8_t[1024 * 1024];
- const uint8_t *inBuf;
-
- for(;;) {
- res = SSL_do_handshake(connection);
- if (res >= 0) {
- break;
- }
-
- if (isErrorFatal(connection, res)) {
- break;
- }
-
- size_t outLen = BIO_ctrl_pending(bioOut);
- if (outLen) {
- BIO_read(bioOut, outBuf, outLen);
- }
- size_t inLen;
- server_ctx->DoHandshakeStep(outBuf, outLen, &inBuf, &inLen);
- EXPECT_TRUE(inBuf != NULL);
-
- if (inLen) {
- BIO_write(bioIn, inBuf, inLen);
- }
- }
- delete[] outBuf;
-
- EXPECT_EQ(res, 1);
-
- BIO *bioF = BIO_new(BIO_f_ssl());
- BIO_set_ssl(bioF, connection, BIO_NOCLOSE);
-
- const char *text = "Hello, it's the text to be encrypted";
- uint8_t *encryptedText = new uint8_t[1024];
- const uint8_t *decryptedText;
- size_t text_len;
-
- // Encrypt text on client side
- BIO_write(bioF, text, sizeof(text));
- text_len = BIO_ctrl_pending(bioOut);
- size_t len = BIO_read(bioOut, encryptedText, text_len);
-
- // Make improvements
- encryptedText[len / 3] ^= 0x80;
-
- // Decrypt text on server
- server_ctx->Decrypt(encryptedText, len, &decryptedText, &text_len);
-
- delete[] encryptedText;
-
- EXPECT_FALSE(decryptedText == NULL);
- EXPECT_GT(LastError().length(), 0u);
- delete[] encryptedText;
- }
-
-
-
- TEST_F(SSLTest, Positive2) {
- using security_manager::LastError;
- int res = 0;
-
- uint8_t *outBuf = new uint8_t[1024 * 1024];
- const uint8_t *inBuf;
-
- for(;;) {
- res = SSL_do_handshake(connection);
- if (res >= 0) {
- break;
- }
-
- if (isErrorFatal(connection, res)) {
- break;
- }
-
- size_t outLen = BIO_ctrl_pending(bioOut);
- if (outLen) {
- BIO_read(bioOut, outBuf, outLen);
- }
- size_t inLen;
- server_ctx->DoHandshakeStep(outBuf, outLen, &inBuf, &inLen);
- EXPECT_TRUE(inBuf != NULL);
-
- if (inLen) {
- BIO_write(bioIn, inBuf, inLen);
- }
- }
- delete[] outBuf;
-
- EXPECT_EQ(res, 1);
-
- EXPECT_NE(SSL_is_init_finished(connection), 0u);
-
- BIO *bioF = BIO_new(BIO_f_ssl());
- BIO_set_ssl(bioF, connection, BIO_NOCLOSE);
-
- const int N =1000;
- int last_max = 0;
- int min_oh = N , max_oh = 0;
- for (int l = 1; l < N; ++l) {
- char *text = new char[l+1];
- text[l]='\0';
- uint8_t *encryptedText = new uint8_t[1024*N];
- const uint8_t *decryptedText;
- size_t text_len;
- // Encrypt text on client side
- BIO_write(bioF, text, l);
- text_len = BIO_ctrl_pending(bioOut);
- size_t len = BIO_read(bioOut, encryptedText, text_len);
- const int temp = len - l;
- min_oh = temp < min_oh ? temp : min_oh;
- max_oh = temp > max_oh ? temp : max_oh;
- if (last_max < len) {
- std::cout << l << "->" << len;
- if (l > 1) {
- std::cout << ", last overhead = " << last_max << "-" << l-1
- << " = " << last_max - (l - 1) << "bytes || ";
- std::cout << " overhead = " << len << "-" << l
- << " = " << len - l << "bytes";
- }
- std::cout << std::endl;
- last_max = len;
-
- // Decrypt text on server
- server_ctx->Decrypt(encryptedText, len, &decryptedText, &text_len);
- const_cast<uint8_t*>(decryptedText)[text_len] = 0;
-
- EXPECT_TRUE(decryptedText != NULL);
- EXPECT_EQ(strcmp(reinterpret_cast<const char*>(decryptedText), text), 0u);
- delete[] text;
- }
- std::cout << " min = " << min_oh << ", max = " << max_oh << std::endl;
- }
- //*/
+TEST_F(CryptoManagerTest, OnCertificateUpdated_UpdateNotRequired) {
+ size_t updates_before = 0;
+ SetInitialValues(
+ security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
+ ASSERT_TRUE(crypto_manager_->Init());
+
+ EXPECT_CALL(*mock_security_manager_settings_, update_before_hours())
+ .WillOnce(Return(updates_before));
+
+ EXPECT_FALSE(crypto_manager_->IsCertificateUpdateRequired());
+ size_t max_updates_ = std::numeric_limits<size_t>::max();
+ SetInitialValues(
+ security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
+ EXPECT_CALL(*mock_security_manager_settings_, update_before_hours())
+ .WillOnce(Return(max_updates_));
+ ASSERT_TRUE(crypto_manager_->Init());
+
+ EXPECT_TRUE(crypto_manager_->IsCertificateUpdateRequired());
}
- // namespace crypto_manager_test
-} // namespace components
-} // namespace test
+TEST_F(CryptoManagerTest, OnCertificateUpdated_NotInitialized) {
+ EXPECT_FALSE(crypto_manager_->OnCertificateUpdated(certificate_data_base64_));
+}
+
+TEST_F(CryptoManagerTest, OnCertificateUpdated_NullString) {
+ InitSecurityManager();
+ EXPECT_FALSE(crypto_manager_->OnCertificateUpdated(std::string()));
+}
+
+TEST_F(CryptoManagerTest, OnCertificateUpdated_MalformedSign) {
+ InitSecurityManager();
+ // Corrupt the middle symbol
+ certificate_data_base64_[certificate_data_base64_.size() / 2] = '?';
+
+ EXPECT_FALSE(crypto_manager_->OnCertificateUpdated(certificate_data_base64_));
+}
+
+TEST_F(CryptoManagerTest, OnCertificateUpdated_WrongInitFolder) {
+ SetInitialValues(
+ security_manager::CLIENT, security_manager::TLSv1_2, kAllCiphers);
+ ASSERT_TRUE(crypto_manager_->Init());
+
+ const std::string certificate = "wrong_data";
+ ASSERT_FALSE(certificate.empty());
+
+ EXPECT_FALSE(crypto_manager_->OnCertificateUpdated(certificate));
+}
+
+} // namespace crypto_manager_test
+} // namespace components
+} // namespace test
diff --git a/src/components/security_manager/test/include/security_manager_mock.h b/src/components/security_manager/test/include/security_manager_mock.h
deleted file mode 100644
index 886b022c37..0000000000
--- a/src/components/security_manager/test/include/security_manager_mock.h
+++ /dev/null
@@ -1,311 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TEST_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_SECURITY_MANAGER_MOCK_H_
-#define TEST_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_SECURITY_MANAGER_MOCK_H_
-
-#include <gmock/gmock.h>
-#include <string>
-#include <list>
-#include "utils/byte_order.h"
-#include "security_manager/security_manager.h"
-#include "security_manager/ssl_context.h"
-#include "security_manager/security_query.h"
-
-namespace test {
-namespace components {
-namespace security_manager_test {
-
-/*
- * MOCK implementation of ::security_manager::SecurityManager
- */
-class SecurityManagerMock : public ::security_manager::SecurityManager {
- public:
- MOCK_METHOD1(set_session_observer,
- void(::protocol_handler::SessionObserver *));
- MOCK_METHOD1(set_protocol_handler,
- void(::protocol_handler::ProtocolHandler *));
- MOCK_METHOD1(set_crypto_manager,
- void(::security_manager::CryptoManager *));
- MOCK_METHOD4(SendInternalError,
- void(const uint32_t ,
- const uint8_t &,
- const std::string &,
- const uint32_t));
- MOCK_METHOD1(CreateSSLContext,
- ::security_manager::SSLContext * (const uint32_t &));
- MOCK_METHOD1(StartHandshake,
- void(uint32_t));
- MOCK_METHOD1(AddListener,
- void(::security_manager::SecurityManagerListener *));
- MOCK_METHOD1(RemoveListener,
- void(::security_manager::SecurityManagerListener *));
- // protocol_handler::ProtocolObserver part
- MOCK_METHOD1(OnMessageReceived,
- void(const ::protocol_handler::RawMessagePtr));
- MOCK_METHOD1(OnMobileMessageSent,
- void(const ::protocol_handler::RawMessagePtr));
-};
-
-/*
- * MOCK implementation of protocol_handler::SessionObserver interface
- */
-class SessionObserverMock : public protocol_handler::SessionObserver {
- public:
- MOCK_METHOD2(SetSSLContext,
- int (const uint32_t& key,
- security_manager::SSLContext* context));
- MOCK_METHOD2(GetSSLContext,
- security_manager::SSLContext* (
- const uint32_t& key,
- const protocol_handler::ServiceType& service_type));
- MOCK_METHOD2(SetProtectionFlag,
- void(
- const uint32_t& key,
- const protocol_handler::ServiceType& service_type));
- MOCK_METHOD5(OnSessionStartedCallback,
-
- uint32_t(
- const transport_manager::ConnectionUID &connection_handle,
- const uint8_t session_id,
- const ::protocol_handler::ServiceType &service_type,
- const bool is_protected, uint32_t* hash_id));
-
- MOCK_METHOD4(OnSessionEndedCallback,
- uint32_t(
- const transport_manager::ConnectionUID& connection_handle,
- const uint8_t sessionId,
- const uint32_t& hashCode,
- const protocol_handler::ServiceType& service_type));
-
- MOCK_METHOD1(OnApplicationFloodCallBack,
- void(const uint32_t&));
-
- MOCK_METHOD1(OnMalformedMessageCallback,
- void(const uint32_t&));
-
- MOCK_METHOD2(KeyFromPair,
- uint32_t(
- transport_manager::ConnectionUID connection_handle,
- uint8_t sessionId));
- MOCK_METHOD3(PairFromKey,
- void(
- uint32_t key,
- transport_manager::ConnectionUID* connection_handle,
- uint8_t* sessionId));
- MOCK_METHOD4(GetDataOnSessionKey,
- int32_t(uint32_t key,
- uint32_t* app_id,
- std::list<int32_t>* sessions_list,
- uint32_t* device_id));
-
- MOCK_METHOD4(GetDataOnDeviceID,
- int32_t(
- uint32_t device_handle,
- std::string* device_name,
- std::list<uint32_t>* applications_list,
- std::string* mac_address));
-
- MOCK_METHOD5(GetDataOnDeviceID,
- int32_t(
- uint32_t device_handle,
- std::string *device_name,
- std::list<uint32_t> *applications_list,
- std::string *mac_address,
- std::string *connection_type));
-
- MOCK_METHOD2(IsHeartBeatSupported,
- bool( transport_manager::ConnectionUID connection_handle,
- uint8_t session_id));
-
- MOCK_METHOD3(ProtocolVersionUsed,
- bool(uint32_t connection_id, uint8_t session_id,
- uint8_t& protocol_version));
-};
-/*
- * MOCK implementation of protocol_handler::ProtocolObserver interface
- */
-class ProtocoloObserverMock : public protocol_handler::ProtocolHandler {
- public:
- MOCK_METHOD2(SendMessageToMobileApp,
- void(const protocol_handler::RawMessagePtr message,
- bool final_message));
- MOCK_METHOD1(AddProtocolObserver,
- void(protocol_handler::ProtocolObserver* observer));
- MOCK_METHOD1(RemoveProtocolObserver,
- void(protocol_handler::ProtocolObserver* observer));
- MOCK_METHOD2(SendFramesNumber,
- void(uint32_t connection_key, int32_t number_of_frames));
- MOCK_METHOD2(SendHeartBeat,
- void(int32_t connection_id, uint8_t session_id));
- MOCK_METHOD2(SendEndSession,
- void(int32_t connection_id, uint8_t session_id));
-};
-/*
- * MOCK implementation of security_manager::SSLContext interface
- */
-class CryptoManagerMock : public security_manager::CryptoManager {
- public:
- MOCK_METHOD6(Init,
- bool (security_manager::Mode mode,
- security_manager::Protocol protocol,
- const std::string& cert_filename,
- const std::string& key_filename,
- const std::string& ciphers_list,
- bool verify_peer));
- MOCK_METHOD0(Finish,
- void ());
- MOCK_METHOD0(CreateSSLContext,
- security_manager::SSLContext* ());
- MOCK_METHOD1(ReleaseSSLContext,
- void(security_manager::SSLContext*));
- MOCK_CONST_METHOD0(LastError,
- std::string());
-};
-/*
- * MOCK implementation of security_manager::SSLContext interface
- */
-class SSLContextMock : public security_manager::SSLContext {
- public:
- MOCK_CONST_METHOD0(mode, int ());
- MOCK_METHOD2(StartHandshake,
- security_manager::SSLContext::HandshakeResult (
- const uint8_t** const, size_t*));
- MOCK_METHOD4(DoHandshakeStep,
- security_manager::SSLContext::HandshakeResult (
- const uint8_t* const, size_t,
- const uint8_t** const, size_t*));
- MOCK_METHOD4(Encrypt,
- bool (const uint8_t* const, size_t,
- const uint8_t** const, size_t*));
- MOCK_METHOD4(Decrypt,
- bool (const uint8_t* const, size_t,
- const uint8_t** const, size_t*));
- MOCK_CONST_METHOD1(get_max_block_size, size_t (size_t));
- MOCK_CONST_METHOD0(IsInitCompleted, bool());
- MOCK_CONST_METHOD0(IsHandshakePending, bool());
- MOCK_CONST_METHOD0(LastError,
- std::string());
-};
-/*
- * MOCK implementation of security_manager::SecurityManagerListener
- */
-class SMListenerMock : public security_manager::SecurityManagerListener {
- public:
- MOCK_METHOD2(OnHandshakeDone,
- bool(uint32_t connection_key,
- bool success));
-};
-
-/*
- * Matcher for RawMessages
- * Check binary data of RawMessages
- */
-MATCHER_P2(RawMessageEq, exp_data, exp_data_size,
- std::string(negation ? "is not" : "is") + " RawMessages "){
- const size_t arg_data_size = arg->data_size();
- if (arg_data_size != exp_data_size) {
- *result_listener << "Got " << arg_data_size << " bytes "
- << " expected " << exp_data_size << " bytes";
- return false;
- }
- const uint8_t *arg_data = arg->data();
- for (int i = 0; i < arg_data_size; ++i) {
- if (arg_data[i] != exp_data[i]) {
- *result_listener << "Fail in " << i << " byte";
- return false;
- }
- }
- return true;
-}
-
-/*
- * Matcher for checking RawMessage with InternalError Query
- * Check error id
- */
-MATCHER_P(InternalErrorWithErrId, expectedErrorId,
- std::string(negation ? "is not" : "is")
- + " InternalError with selected error" ){
- const size_t header_size = sizeof(security_manager::SecurityQuery::QueryHeader);
- if (arg->data_size() <= header_size) {
- *result_listener << "Size " << arg->data_size()
- << " bytes less or equal sizeof(QueryHeader)="
- << header_size;
- return false;
- }
- const uint8_t *data = arg->data();
- const uint8_t query_type = data[0];
- if (security_manager::SecurityQuery::NOTIFICATION != query_type) {
- *result_listener << "RawMessage is not notification, type=0x"
- << std::hex << static_cast<int>(query_type);
- return false;
- }
- // Read Big-Endian number
- const uint32_t query_id = data[1] << 16 |
- data[2] << 8 |
- data[3];
- if (security_manager::SecurityQuery::SEND_INTERNAL_ERROR != query_id) {
- *result_listener << "Notification is not InternalError, id=0x"
- << std::hex << query_id;
- return false;
- }
- const uint32_t json_size = data[8] << 24 |
- data[9] << 16 |
- data[10] << 8 |
- data[11];
- if (header_size + json_size >= arg->data_size()) {
- *result_listener << "InternalError contains only JSON data.";
- return false;
- }
- // Read err_id as bin data number
- const uint8_t* err_id =
- reinterpret_cast<const uint8_t*>(data + header_size + json_size);
- if (expectedErrorId != *err_id) {
- *result_listener << "InternalError id " << static_cast<int>(*err_id)
- << " and not equal error " << expectedErrorId;
- return false;
- }
- return true;
-}
-
-} // namespace security_manager_test
-} // namespace components
-} // namespace test
-/*
- * Matcher for checking QueryHeader equal in GTests
- */
-::testing::AssertionResult QueryHeader_EQ(
- const char* m_expr, const char* n_expr,
- const ::security_manager::SecurityQuery::QueryHeader& q1,
- const ::security_manager::SecurityQuery::QueryHeader& q2);
-
-#endif // TEST_COMPONENTS_SECURITY_MANAGER_INCLUDE_SECURITY_MANAGER_SECURITY_MANAGER_MOCK_H_
diff --git a/src/components/security_manager/test/mycert.pem b/src/components/security_manager/test/mycert.pem
new file mode 100644
index 0000000000..fe8be6970e
--- /dev/null
+++ b/src/components/security_manager/test/mycert.pem
@@ -0,0 +1,22 @@
+-----BEGIN CERTIFICATE-----
+MIIDlDCCAnwCCQDIe7AwFpWRlDANBgkqhkiG9w0BAQUFADCBizELMAkGA1UEBhMC
+UlUxEzARBgNVBAgMClNvbWUtU3RhdGUxGTAXBgNVBAcMEFNhaW50LVBldGVyc2J1
+cmcxDzANBgNVBAoMBkx1eG9mdDEXMBUGA1UEAwwORG1pdHJ5IENobWVyZXYxIjAg
+BgkqhkiG9w0BCQEWE2RjaG1lcmV2QGx1eG9mdC5jb20wHhcNMTQwMjI1MDkxODUz
+WhcNMTYxMTIyMDkxODUzWjCBizELMAkGA1UEBhMCUlUxEzARBgNVBAgMClNvbWUt
+U3RhdGUxGTAXBgNVBAcMEFNhaW50LVBldGVyc2J1cmcxDzANBgNVBAoMBkx1eG9m
+dDEXMBUGA1UEAwwORG1pdHJ5IENobWVyZXYxIjAgBgkqhkiG9w0BCQEWE2RjaG1l
+cmV2QGx1eG9mdC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCn
+Mu9wNmXKaKOnefSv5iT8G2ESLjq+eYlxys/XAnDfkmnlgGYAcPno+XMhRj/lNV/c
+3A0L/R4631GFJA8vaM8m9Bn47FrPP4AXIHEQh9acA4qXiLfhhA8+9PPt4xVkjQYj
+bmexBLqDvRgT3MJwwFecUn/UABBlVZRCspn+6DkjiodbgmBOqyi1p0ng8BFeUbEH
++fLQVILCX3pjnMiP2bBtvq/7njgZT2luVtAAcOdRwRTuZT0YbgaXrHYsOa6VYDl1
+I0uOcdD8qENBXtBnykEqH+jZtKu6Rej1DsGOYWqz3AAaGiR1GJauNBxh+4v+i/eB
+0aCIA8T8qUqyuVVg48S/AgMBAAEwDQYJKoZIhvcNAQEFBQADggEBACliraOJYijK
+yS+Sl6S6pFRqdF/evPdYF6zDJlM3P+/9qHoEy751vbBTzRkVbC/azyiZLwQMuyED
+6oCpkI7MqnrRip1ZelGx9K7ChaHOpX/QRN+3eqiDhzvMTGd2nPJf9np4xi8SJpGP
+UUROYI5fToIY5MaOKuOIR2a6c8xIuLWMG1XKJxXrRetLJZDgBqQPkuqaZIjYCY+q
+HQRjNUFNX4Mc453tKd90gFLGI3fxs1fJDIRSGfKJsj0qc+amSz4Sgiz4QUBcUQKd
+hJxUpStYhliZGZchEopLsShtIGfKKFaaPCIOTpVAwSr1oIDm9lpkdxeuQfedKT5f
+ZZmkez2pAF8=
+-----END CERTIFICATE-----
diff --git a/src/components/security_manager/test/mykey.pem b/src/components/security_manager/test/mykey.pem
new file mode 100644
index 0000000000..20c89546b4
--- /dev/null
+++ b/src/components/security_manager/test/mykey.pem
@@ -0,0 +1,27 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIEowIBAAKCAQEApzLvcDZlymijp3n0r+Yk/BthEi46vnmJccrP1wJw35Jp5YBm
+AHD56PlzIUY/5TVf3NwNC/0eOt9RhSQPL2jPJvQZ+Oxazz+AFyBxEIfWnAOKl4i3
+4YQPPvTz7eMVZI0GI25nsQS6g70YE9zCcMBXnFJ/1AAQZVWUQrKZ/ug5I4qHW4Jg
+TqsotadJ4PARXlGxB/ny0FSCwl96Y5zIj9mwbb6v+544GU9pblbQAHDnUcEU7mU9
+GG4Gl6x2LDmulWA5dSNLjnHQ/KhDQV7QZ8pBKh/o2bSrukXo9Q7BjmFqs9wAGhok
+dRiWrjQcYfuL/ov3gdGgiAPE/KlKsrlVYOPEvwIDAQABAoIBAQCAjkNXzhuZ87bR
+UI34qUYKqaqLZgw45A3v9naz5OaQoGzXz0+eSz98CECjdvYt8EoS8Qb/DtGthoOR
+kVYzp6yPUOSfZmu0Kij8ny8P/MHgF0D6nl50ASwPxhu/7vhF5cCwgXUswGwAWuYm
+b3j5ZIp4YV5zzNDOeWyTk+uf+UHltqFD7Ae4M9z58r17/OWhva5mtusTuuEYjzC6
+AE/fsOC0gLNSM4+SfclfCkHpH+GikzNMSQ2H0hlXllPmR73BoC6N6aoY5hQWBLV7
+LxtYbJqx7TAqRyypBQekjJe36roRetXtzy3i6V/y69045td5kk70cVjmFhl79475
+82rnRLHBAoGBANgq4axr5OotTUmPkGd0afoaWSRPJfiTTdNeMkqTzM6zIcVLSKhB
+78ERwdDD9FOu+Bgivg4DlpmH7ArWn8QNDtdkhmPfKYfTqX6qH7AK4cybvYICMlct
+EdW4TvKm/ZB3mrVOP9JVPjdyFMp+Je6N+qp1w+ui9mxX8pWnrC/+DfTvAoGBAMYC
+GFjnw/O9hjF2Mb00qUarmM+reJZMXv/pVik+cm0eAiYvgGvKbAYkIXwdb7rLBw9k
+baJmxP0PrAoXy5TpPdfROqPwrRCyReKymKkEZeTpONgD0s8MbX167ovZu1OQVKQo
+IyJeUzWa0kpglnbL2lLVu49x8jWHDJdYhmkDNE0xAoGAR4ux07qGMoe5693rYoJi
+TRgJZv4XSDWg7ZNgu9Q9VjBtvfoT2zSvoMw6xNkGdegUTxC4rLS9VKVrF48/o8ja
+n6my3T1QZpdEoxq1kDOZ1nm5eF03wii1nXH6F0/z3qvndZingPsbs4g7n2WvMkyl
+qWN+6++s9eEJ9kRftia1AdsCgYAUnU05nE97RcT9y0dcYmopMF5FaJ2yUBsn23wb
+6SNylsg0f4eIMVfTv9k4mbvzH4YJpTQAz2A81G/d0SJhy3Kj0GWhgcIS1eyOsHdS
+SWHuVhWT77n30lxnzu+c4bst9P3K5V7bCiTxlL/F/I5NqeV98ECJq5xC1F+MNiww
+LKQ6UQKBgC2zL59Vf8QnRkRN0gOUfs3ejrLcxFRzTXvcKqcHtbaqzCs3qSNC6UvV
+wjBazEwQCo1wnM81X8uT5fLhnjXebWtnYexQo5P38PiaqTQDgrbAdhP5P8NwRCXM
+G3SNEz0XeL27jmWjf0VJdwD0LuHXYhcwAWq4alhJ024rjgVHwOze
+-----END RSA PRIVATE KEY-----
diff --git a/src/components/security_manager/test/security_manager_test.cc b/src/components/security_manager/test/security_manager_test.cc
index 30f81ee62e..b5f9ae2e78 100644
--- a/src/components/security_manager/test/security_manager_test.cc
+++ b/src/components/security_manager/test/security_manager_test.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,30 +30,47 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include <gtest/gtest.h>
#include <string>
+#include "gtest/gtest.h"
#include "utils/byte_order.h"
#include "protocol/common.h"
#include "security_manager/security_manager_impl.h"
-#include "protocol_handler_mock.h"
-#include "protocol_observer_mock.h"
-#include "include/security_manager_mock.h"
-#include "transport_manager_mock.h"
-
-// TODO(EZamakhov): add test on get correct/wrong InternalError
-// TODO(EZamakhov): check connection_key the same and seq_number
-// TODO(EZamakhov): check ::SendData with correct query_id and query_type
+#include "protocol_handler/mock_protocol_handler.h"
+#include "protocol_handler/mock_session_observer.h"
+#include "security_manager/mock_security_manager.h"
+#include "security_manager/mock_ssl_context.h"
+#include "security_manager/mock_crypto_manager.h"
+#include "security_manager/mock_security_manager_listener.h"
+#include "utils/make_shared.h"
namespace test {
namespace components {
namespace security_manager_test {
-using namespace ::protocol_handler;
-using ::protocol_handler::ServiceType;
-using namespace ::transport_manager;
-using namespace ::security_manager;
+using protocol_handler::PROTOCOL_VERSION_2;
+using protocol_handler::ServiceType;
+using protocol_handler::kControl;
+using protocol_handler::kRpc;
+using protocol_handler::kAudio;
+using protocol_handler::kMobileNav;
+using protocol_handler::kBulk;
+using protocol_handler::kInvalidServiceType;
+using protocol_handler::RawMessagePtr;
+using protocol_handler::RawMessage;
+
+using security_manager::SecurityQuery;
+using security_manager::SSLContext;
+using security_manager::SecurityManager;
+using security_manager::SecurityManagerImpl;
+
+using security_manager_test::InternalErrorWithErrId;
+using ::testing::Return;
+using ::testing::ReturnNull;
+using ::testing::DoAll;
+using ::testing::SetArgPointee;
+using ::testing::_;
// Sample data for handshake data emulation
const int32_t key = 0x1;
@@ -62,24 +79,14 @@ const ServiceType secureServiceType = kControl;
const uint32_t protocolVersion = PROTOCOL_VERSION_2;
const bool is_final = false;
-const uint8_t handshake_data[] = { 0x1, 0x2, 0x3, 0x4, 0x5 };
-const size_t handshake_data_size = sizeof(handshake_data)
- / sizeof(handshake_data[0]);
-
-uint8_t handshake_data_out[] = { 0x6, 0x7, 0x8 };
-uint8_t *handshake_data_out_pointer = handshake_data_out;
-const size_t handshake_data_out_size = sizeof(handshake_data_out)
- / sizeof(handshake_data_out[0]);
+const uint8_t handshake_data[] = {0x1, 0x2, 0x3, 0x4, 0x5};
+const size_t handshake_data_size =
+ sizeof(handshake_data) / sizeof(handshake_data[0]);
-using ::security_manager::SecurityQuery;
-using security_manager_test::InternalErrorWithErrId;
-using ::testing::Return;
-using ::testing::ReturnNull;
-using ::testing::DoAll;
-using ::testing::SetArgPointee;
-using ::testing::_;
-using ::security_manager::SecurityManager;
-using ::security_manager::SecurityManagerImpl;
+uint8_t handshake_data_out[] = {0x6, 0x7, 0x8};
+uint8_t* handshake_data_out_pointer = handshake_data_out;
+const size_t handshake_data_out_size =
+ sizeof(handshake_data_out) / sizeof(handshake_data_out[0]);
class SecurityManagerTest : public ::testing::Test {
protected:
@@ -91,20 +98,22 @@ class SecurityManagerTest : public ::testing::Test {
}
void TearDown() OVERRIDE {
// Wait call methods in thread
- usleep(100000);
+ testing::Mock::AsyncVerifyAndClearExpectations(1000);
}
- void SetMockCryptoManger() {
+ void SetMockCryptoManager() {
+ EXPECT_CALL(mock_crypto_manager, IsCertificateUpdateRequired())
+ .WillRepeatedly(Return(false));
security_manager_->set_crypto_manager(&mock_crypto_manager);
}
/*
* Wrapper for fast emulate recieve SecurityManager::OnMessageReceived
*/
- void call_OnMessageReceived(const uint8_t* const data, uint32_t dataSize,
+ void call_OnMessageReceived(const uint8_t* const data,
+ uint32_t dataSize,
const ServiceType serviceType) {
- const ::protocol_handler::RawMessagePtr rawMessagePtr(
- new ::protocol_handler::RawMessage(key, protocolVersion, data, dataSize,
- serviceType));
+ const RawMessagePtr rawMessagePtr(utils::MakeShared<RawMessage>(
+ key, protocolVersion, data, dataSize, serviceType));
security_manager_->OnMessageReceived(rawMessagePtr);
}
/*
@@ -130,7 +139,7 @@ class SecurityManagerTest : public ::testing::Test {
/*
* Wrapper for fast emulate recieve Handshake
*/
- void EmulateMobileMessageHandShake(const uint8_t* const data,
+ void EmulateMobileMessageHandshake(const uint8_t* const data,
const uint32_t data_size,
const int repeat_count = 1) {
const SecurityQuery::QueryHeader header(SecurityQuery::NOTIFICATION,
@@ -142,12 +151,18 @@ class SecurityManagerTest : public ::testing::Test {
}
::utils::SharedPtr<SecurityManagerImpl> security_manager_;
// Strict mocks (same as all methods EXPECT_CALL().Times(0))
- testing::StrictMock<protocol_handler_test::SessionObserverMock> mock_session_observer;
- testing::StrictMock<protocol_handler_test::ProtocolHandlerMock> mock_protocol_handler;
- testing::StrictMock<security_manager_test::CryptoManagerMock> mock_crypto_manager;
- testing::StrictMock<security_manager_test::SSLContextMock> mock_ssl_context_new;
- testing::StrictMock<security_manager_test::SSLContextMock> mock_ssl_context_exists;
- testing::StrictMock<security_manager_test::SMListenerMock> mock_sm_listener;
+ testing::StrictMock<protocol_handler_test::MockSessionObserver>
+ mock_session_observer;
+ testing::StrictMock<protocol_handler_test::MockProtocolHandler>
+ mock_protocol_handler;
+ testing::StrictMock<security_manager_test::MockCryptoManager>
+ mock_crypto_manager;
+ testing::StrictMock<security_manager_test::MockSSLContext>
+ mock_ssl_context_new;
+ testing::StrictMock<security_manager_test::MockSSLContext>
+ mock_ssl_context_exists;
+ testing::StrictMock<security_manager_test::MockSecurityManagerListener>
+ mock_sm_listener;
};
// Test Bodies
@@ -186,12 +201,14 @@ TEST_F(SecurityManagerTest, Listeners_NoListeners) {
security_manager_->RemoveListener(&mock_sm_listener);
// Expect no calls
- testing::StrictMock<SMListenerMock> mock_listener2;
+ testing::StrictMock<MockSecurityManagerListener> mock_listener2;
security_manager_->AddListener(&mock_listener2);
security_manager_->RemoveListener(&mock_listener2);
- security_manager_->NotifyListenersOnHandshakeDone(key, true);
- security_manager_->NotifyListenersOnHandshakeDone(key, false);
+ security_manager_->NotifyListenersOnHandshakeDone(
+ key, SSLContext::Handshake_Result_Success);
+ security_manager_->NotifyListenersOnHandshakeDone(
+ key, SSLContext::Handshake_Result_Fail);
}
/*
* Notifying two listeners
@@ -200,23 +217,32 @@ TEST_F(SecurityManagerTest, Listeners_Notifying) {
// Check correct removing listener
security_manager_->RemoveListener(&mock_sm_listener);
- testing::StrictMock<SMListenerMock> mock_listener1;
- testing::StrictMock<SMListenerMock> mock_listener2;
+ testing::StrictMock<MockSecurityManagerListener> mock_listener1;
+ testing::StrictMock<MockSecurityManagerListener> mock_listener2;
- const bool first_call_value = true;
+ const SSLContext::HandshakeResult first_call_value =
+ SSLContext::Handshake_Result_Success;
// Expect call both listeners on 1st call
- EXPECT_CALL(mock_listener1, OnHandshakeDone(key, first_call_value)).
- // Emulate false (reject) result
- WillOnce(Return(false));
- EXPECT_CALL(mock_listener2, OnHandshakeDone(key, first_call_value)).
- // Emulate true (accept) result
- WillOnce(Return(true));
-
- const bool second_call_value = false;
+ EXPECT_CALL(mock_listener1, OnHandshakeDone(key, first_call_value))
+ .
+ // Emulate false (reject) result
+ WillOnce(Return(false));
+ EXPECT_CALL(mock_listener2, OnHandshakeDone(key, first_call_value))
+ .
+ // Emulate true (accept) result
+ WillOnce(Return(true));
+
+ // First listener was not removed from listener list
+ // So this callback wil lbe either call.
+ EXPECT_CALL(mock_listener1, OnCertificateUpdateRequired());
+
+ const SSLContext::HandshakeResult second_call_value =
+ SSLContext::Handshake_Result_Fail;
// Expect call last listener on 2d call
- EXPECT_CALL(mock_listener1, OnHandshakeDone(key, second_call_value)).
- // Emulate false (reject) result
- WillOnce(Return(true));
+ EXPECT_CALL(mock_listener1, OnHandshakeDone(key, second_call_value))
+ .
+ // Emulate false (reject) result
+ WillOnce(Return(true));
// Expect no call 3d call
@@ -224,11 +250,16 @@ TEST_F(SecurityManagerTest, Listeners_Notifying) {
security_manager_->AddListener(&mock_listener2);
// 1st call
security_manager_->NotifyListenersOnHandshakeDone(key, first_call_value);
+ security_manager_->NotifyOnCertififcateUpdateRequired();
// 2nd call
security_manager_->NotifyListenersOnHandshakeDone(key, second_call_value);
+ security_manager_->NotifyOnCertififcateUpdateRequired();
// 3nd call
- security_manager_->NotifyListenersOnHandshakeDone(key, false);
+ security_manager_->NotifyListenersOnHandshakeDone(
+ key, SSLContext::Handshake_Result_Fail);
+ security_manager_->NotifyOnCertififcateUpdateRequired();
}
+
/*
* SecurityManager with NULL CryptoManager shall send
* InternallError (ERROR_NOT_SUPPORTED) on any Query
@@ -237,14 +268,16 @@ TEST_F(SecurityManagerTest, SecurityManager_NULLCryptoManager) {
// Expect InternalError with ERROR_ID
uint32_t connection_id = 0;
uint8_t session_id = 0;
- //uint8_t protocol_version = 0;
+ // uint8_t protocol_version = 0;
EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _));
- EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id,_)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_session_observer,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(true));
- EXPECT_CALL(
- mock_protocol_handler,
- SendMessageToMobileApp( InternalErrorWithErrId( SecurityManager::ERROR_NOT_SUPPORTED), is_final));
+ EXPECT_CALL(mock_protocol_handler,
+ SendMessageToMobileApp(
+ InternalErrorWithErrId(SecurityManager::ERROR_NOT_SUPPORTED),
+ is_final));
const SecurityQuery::QueryHeader header(SecurityQuery::REQUEST,
// It could be any query id
SecurityQuery::INVALID_QUERY_ID);
@@ -255,8 +288,9 @@ TEST_F(SecurityManagerTest, SecurityManager_NULLCryptoManager) {
* Shall skip all OnMobileMessageSent
*/
TEST_F(SecurityManagerTest, OnMobileMessageSent) {
- const ::protocol_handler::RawMessagePtr rawMessagePtr(
- new ::protocol_handler::RawMessage(key, protocolVersion, NULL, 0));
+ const uint8_t* data_param = NULL;
+ const RawMessagePtr rawMessagePtr(
+ utils::MakeShared<RawMessage>(key, protocolVersion, data_param, 0));
security_manager_->OnMobileMessageSent(rawMessagePtr);
}
/*
@@ -276,14 +310,17 @@ TEST_F(SecurityManagerTest, GetWrongServiceType) {
TEST_F(SecurityManagerTest, GetEmptyQuery) {
uint32_t connection_id = 0;
uint8_t session_id = 0;
- //uint8_t protocol_version = 0;
+ // uint8_t protocol_version = 0;
EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _));
- EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id,_)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_session_observer,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(true));
- EXPECT_CALL(
- mock_protocol_handler,
- SendMessageToMobileApp( InternalErrorWithErrId( SecurityManager::ERROR_INVALID_QUERY_SIZE), is_final));
+ EXPECT_CALL(
+ mock_protocol_handler,
+ SendMessageToMobileApp(
+ InternalErrorWithErrId(SecurityManager::ERROR_INVALID_QUERY_SIZE),
+ is_final));
// Call with NULL data
call_OnMessageReceived(NULL, 0, secureServiceType);
}
@@ -291,20 +328,22 @@ TEST_F(SecurityManagerTest, GetEmptyQuery) {
* Shall send InternallError on null data recieved
*/
TEST_F(SecurityManagerTest, GetWrongJSONSize) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
uint32_t connection_id = 0;
uint8_t session_id = 0;
- //uint8_t protocol_version = 0;
+ // uint8_t protocol_version = 0;
EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _));
- EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id,_)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_session_observer,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(true));
// Expect InternalError with ERROR_ID
EXPECT_CALL(
- mock_protocol_handler,
- SendMessageToMobileApp( InternalErrorWithErrId( SecurityManager::ERROR_INVALID_QUERY_SIZE), is_final));
- SecurityQuery::QueryHeader header(
- SecurityQuery::REQUEST,
- SecurityQuery::INVALID_QUERY_ID);
+ mock_protocol_handler,
+ SendMessageToMobileApp(
+ InternalErrorWithErrId(SecurityManager::ERROR_INVALID_QUERY_SIZE),
+ is_final));
+ SecurityQuery::QueryHeader header(SecurityQuery::REQUEST,
+ SecurityQuery::INVALID_QUERY_ID);
header.json_size = 0x0FFFFFFF;
EmulateMobileMessage(header, NULL, 0);
}
@@ -312,20 +351,22 @@ TEST_F(SecurityManagerTest, GetWrongJSONSize) {
* Shall send InternallError on INVALID_QUERY_ID
*/
TEST_F(SecurityManagerTest, GetInvalidQueryId) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
uint32_t connection_id = 0;
uint8_t session_id = 0;
- //uint8_t protocol_version = 0;
+ // uint8_t protocol_version = 0;
EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _));
- EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id,_)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_session_observer,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(true));
// Expect InternalError with ERROR_ID
EXPECT_CALL(
- mock_protocol_handler,
- SendMessageToMobileApp( InternalErrorWithErrId( SecurityManager::ERROR_INVALID_QUERY_ID), is_final));
- const SecurityQuery::QueryHeader header(
- SecurityQuery::REQUEST,
- SecurityQuery::INVALID_QUERY_ID);
+ mock_protocol_handler,
+ SendMessageToMobileApp(
+ InternalErrorWithErrId(SecurityManager::ERROR_INVALID_QUERY_ID),
+ is_final));
+ const SecurityQuery::QueryHeader header(SecurityQuery::REQUEST,
+ SecurityQuery::INVALID_QUERY_ID);
const uint8_t data = 0;
EmulateMobileMessage(header, &data, 1);
}
@@ -334,111 +375,121 @@ TEST_F(SecurityManagerTest, GetInvalidQueryId) {
* CreateSSLContext for already protected connections
*/
TEST_F(SecurityManagerTest, CreateSSLContext_ServiceAlreadyProtected) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
// Return mock SSLContext
- EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl)).
- WillOnce(Return(&mock_ssl_context_new));
+ EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl))
+ .WillOnce(Return(&mock_ssl_context_new));
- const security_manager::SSLContext* rezult = security_manager_->CreateSSLContext(key);
- EXPECT_EQ(rezult, &mock_ssl_context_new);
+ const SSLContext* result = security_manager_->CreateSSLContext(key);
+ EXPECT_EQ(&mock_ssl_context_new, result);
}
/*
* Shall send Internall Error on error create SSL
*/
TEST_F(SecurityManagerTest, CreateSSLContext_ErrorCreateSSL) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
// Expect InternalError with ERROR_ID
uint32_t connection_id = 0;
uint8_t session_id = 0;
- //uint8_t protocol_version = 0;
+ // uint8_t protocol_version = 0;
EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _));
- EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id,_)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_session_observer,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(true));
EXPECT_CALL(
- mock_protocol_handler,
- SendMessageToMobileApp( InternalErrorWithErrId( SecurityManager::ERROR_INTERNAL), is_final));
+ mock_protocol_handler,
+ SendMessageToMobileApp(
+ InternalErrorWithErrId(SecurityManager::ERROR_INTERNAL), is_final));
// Emulate SessionObserver and CryptoManager result
- EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl)).
- WillOnce(ReturnNull());
- EXPECT_CALL(mock_crypto_manager, CreateSSLContext()).
- WillOnce(ReturnNull());
+ EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl))
+ .WillOnce(ReturnNull());
+ EXPECT_CALL(mock_crypto_manager, CreateSSLContext()).WillOnce(ReturnNull());
- const bool rezult = security_manager_->CreateSSLContext(key);
- EXPECT_FALSE(rezult);
+ const SSLContext* result = security_manager_->CreateSSLContext(key);
+ EXPECT_EQ(NULL, result);
}
/*
* Shall send InternalError with SERVICE_NOT_FOUND
* on getting any Error with call SetSSLContext
*/
TEST_F(SecurityManagerTest, CreateSSLContext_SetSSLContextError) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
// Expect InternalError with ERROR_ID
uint32_t connection_id = 0;
uint8_t session_id = 0;
- //uint8_t protocol_version = 0;
+ // uint8_t protocol_version = 0;
EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _));
- EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id,_)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_session_observer,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(true));
EXPECT_CALL(
- mock_protocol_handler,
- SendMessageToMobileApp( InternalErrorWithErrId( SecurityManager::ERROR_UNKWOWN_INTERNAL_ERROR), is_final));
+ mock_protocol_handler,
+ SendMessageToMobileApp(
+ InternalErrorWithErrId(SecurityManager::ERROR_UNKNOWN_INTERNAL_ERROR),
+ is_final));
// Emulate SessionObserver and CryptoManager result
- EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl)).
- WillOnce(ReturnNull());
- EXPECT_CALL(mock_crypto_manager, CreateSSLContext()).
- WillOnce(Return(&mock_ssl_context_new));
+ EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl))
+ .WillOnce(ReturnNull());
+ EXPECT_CALL(mock_crypto_manager, CreateSSLContext())
+ .WillOnce(Return(&mock_ssl_context_new));
EXPECT_CALL(mock_crypto_manager, ReleaseSSLContext(&mock_ssl_context_new));
- EXPECT_CALL(mock_session_observer, SetSSLContext(key, &mock_ssl_context_new)).
- WillOnce(Return(SecurityManager::ERROR_UNKWOWN_INTERNAL_ERROR));
+ EXPECT_CALL(mock_session_observer, SetSSLContext(key, &mock_ssl_context_new))
+ .WillOnce(Return(SecurityManager::ERROR_UNKNOWN_INTERNAL_ERROR));
- const bool rezult = security_manager_->CreateSSLContext(key);
- EXPECT_FALSE(rezult);
+ const SSLContext* result = security_manager_->CreateSSLContext(key);
+ EXPECT_EQ(NULL, result);
}
/*
* Shall protect connection on correct call CreateSSLContext
*/
TEST_F(SecurityManagerTest, CreateSSLContext_Success) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
// Expect no Errors
// Expect no notifying listeners - it will be done after handshake
// Emulate SessionObserver and CryptoManager result
- EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl)).
- WillOnce(ReturnNull()).
+ EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl))
+ .WillOnce(ReturnNull())
+ .
// additional check for debug code
WillOnce(Return(&mock_ssl_context_exists));
- EXPECT_CALL(mock_crypto_manager, CreateSSLContext()).
- WillOnce(Return(&mock_ssl_context_new));
- EXPECT_CALL(mock_session_observer, SetSSLContext(key, &mock_ssl_context_new)).
- WillOnce(Return(SecurityManager::ERROR_SUCCESS));
+ EXPECT_CALL(mock_crypto_manager, CreateSSLContext())
+ .WillOnce(Return(&mock_ssl_context_new));
+ EXPECT_CALL(mock_session_observer, SetSSLContext(key, &mock_ssl_context_new))
+ .WillOnce(Return(SecurityManager::ERROR_SUCCESS));
- const bool rezult = security_manager_->CreateSSLContext(key);
- EXPECT_TRUE(rezult);
+ const SSLContext* result = security_manager_->CreateSSLContext(key);
+ EXPECT_EQ(&mock_ssl_context_new, result);
}
/*
* Shall send InternallError on call StartHandshake for uprotected service
*/
TEST_F(SecurityManagerTest, StartHandshake_ServiceStillUnprotected) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
uint32_t connection_id = 0;
uint8_t session_id = 0;
- //uint8_t protocol_version = 0;
+ // uint8_t protocol_version = 0;
EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _));
- EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id,_)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_session_observer,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(true));
// Expect InternalError with ERROR_INTERNAL
- EXPECT_CALL(mock_protocol_handler,
- SendMessageToMobileApp( InternalErrorWithErrId( SecurityManager::ERROR_INTERNAL), is_final));
+ EXPECT_CALL(
+ mock_protocol_handler,
+ SendMessageToMobileApp(
+ InternalErrorWithErrId(SecurityManager::ERROR_INTERNAL), is_final));
// Expect notifying listeners (unsuccess)
- EXPECT_CALL(mock_sm_listener, OnHandshakeDone(key, false)).WillOnce(Return(true));
+ EXPECT_CALL(mock_sm_listener,
+ OnHandshakeDone(key, SSLContext::Handshake_Result_Fail))
+ .WillOnce(Return(true));
// Emulate SessionObserver result
- EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl)).
- WillOnce(ReturnNull());
+ EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl))
+ .WillOnce(ReturnNull());
security_manager_->StartHandshake(key);
}
@@ -446,32 +497,38 @@ TEST_F(SecurityManagerTest, StartHandshake_ServiceStillUnprotected) {
* Shall send InternallError on SSL error and notify listeners
*/
TEST_F(SecurityManagerTest, StartHandshake_SSLInternalError) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
uint32_t connection_id = 0;
uint8_t session_id = 0;
- //uint8_t protocol_version = 0;
+ // uint8_t protocol_version = 0;
EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _));
- EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id,_)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_session_observer, GetHandshakeContext(key))
+ .WillOnce(Return(SSLContext::HandshakeContext()));
+ EXPECT_CALL(mock_session_observer,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(true));
// Expect InternalError with ERROR_ID
EXPECT_CALL(
- mock_protocol_handler,
- SendMessageToMobileApp( InternalErrorWithErrId( SecurityManager::ERROR_INTERNAL), is_final));
+ mock_protocol_handler,
+ SendMessageToMobileApp(
+ InternalErrorWithErrId(SecurityManager::ERROR_INTERNAL), is_final));
// Expect notifying listeners (unsuccess)
- EXPECT_CALL(mock_sm_listener, OnHandshakeDone(key, false)).WillOnce(Return(true));
+ EXPECT_CALL(mock_sm_listener,
+ OnHandshakeDone(key, SSLContext::Handshake_Result_Fail))
+ .WillOnce(Return(true));
// Emulate SessionObserver result
- EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl)).
- WillOnce(Return(&mock_ssl_context_exists));
- EXPECT_CALL(mock_ssl_context_exists, IsInitCompleted()).
- WillOnce(Return(false));
- EXPECT_CALL(mock_ssl_context_exists, StartHandshake(_, _)).
- WillOnce(DoAll(SetArgPointee<0>(handshake_data_out_pointer),
- SetArgPointee<1>(handshake_data_out_size),
- Return(security_manager::SSLContext::
- Handshake_Result_Fail)));
+ EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl))
+ .WillOnce(Return(&mock_ssl_context_exists));
+ EXPECT_CALL(mock_ssl_context_exists, IsInitCompleted())
+ .WillOnce(Return(false));
+ EXPECT_CALL(mock_ssl_context_exists, SetHandshakeContext(_));
+ EXPECT_CALL(mock_ssl_context_exists, StartHandshake(_, _))
+ .WillOnce(DoAll(SetArgPointee<0>(handshake_data_out_pointer),
+ SetArgPointee<1>(handshake_data_out_size),
+ Return(SSLContext::Handshake_Result_Fail)));
security_manager_->StartHandshake(key);
}
@@ -479,59 +536,67 @@ TEST_F(SecurityManagerTest, StartHandshake_SSLInternalError) {
* Shall send data on call StartHandshake
*/
TEST_F(SecurityManagerTest, StartHandshake_SSLInitIsNotComplete) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
uint32_t connection_id = 0;
uint8_t session_id = 0;
- //uint8_t protocol_version = 0;
+ // uint8_t protocol_version = 0;
EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _));
- EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id,_)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_session_observer, GetHandshakeContext(key))
+ .Times(3)
+ .WillRepeatedly(Return(SSLContext::HandshakeContext()));
+ EXPECT_CALL(mock_session_observer,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(true));
// Expect send one message (with correct pointer and size data)
EXPECT_CALL(mock_protocol_handler, SendMessageToMobileApp(_, is_final));
// Return mock SSLContext
- EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl)).Times(3).
- WillRepeatedly(Return(&mock_ssl_context_exists));
+ EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl))
+ .Times(3)
+ .WillRepeatedly(Return(&mock_ssl_context_exists));
// Expect initialization check on each call StartHandshake
- EXPECT_CALL(mock_ssl_context_exists, IsInitCompleted()).Times(3).
- WillRepeatedly(Return(false));
+ EXPECT_CALL(mock_ssl_context_exists, IsInitCompleted())
+ .Times(3)
+ .WillRepeatedly(Return(false));
+ EXPECT_CALL(mock_ssl_context_exists, SetHandshakeContext(_)).Times(3);
// Emulate SSLContext::StartHandshake with different parameters
// Only on both correct - data and size shall be send message to mobile app
- EXPECT_CALL(mock_ssl_context_exists, StartHandshake(_, _)).
- WillOnce(DoAll(SetArgPointee<0>(handshake_data_out_pointer),
- SetArgPointee<1>(0),
- Return(security_manager::SSLContext::
- Handshake_Result_Success))).
- WillOnce(DoAll(SetArgPointee<0>((uint8_t*)NULL),
- SetArgPointee<1>(handshake_data_out_size),
- Return(security_manager::SSLContext::
- Handshake_Result_Success))).
- WillOnce(DoAll(SetArgPointee<0>(handshake_data_out_pointer),
- SetArgPointee<1>(handshake_data_out_size),
- Return(security_manager::SSLContext::
- Handshake_Result_Success)));
+ EXPECT_CALL(mock_ssl_context_exists, StartHandshake(_, _))
+ .WillOnce(DoAll(SetArgPointee<0>(handshake_data_out_pointer),
+ SetArgPointee<1>(0),
+ Return(SSLContext::Handshake_Result_Success)))
+ .WillOnce(DoAll(SetArgPointee<0>((uint8_t*)NULL),
+ SetArgPointee<1>(handshake_data_out_size),
+ Return(SSLContext::Handshake_Result_Success)))
+ .WillOnce(DoAll(SetArgPointee<0>(handshake_data_out_pointer),
+ SetArgPointee<1>(handshake_data_out_size),
+ Return(SSLContext::Handshake_Result_Success)));
security_manager_->StartHandshake(key);
security_manager_->StartHandshake(key);
security_manager_->StartHandshake(key);
}
/*
- * Shall notify listeners on call StartHandshake after SSLContext initialization complete
+ * Shall notify listeners on call StartHandshake after SSLContext initialization
+ * complete
*/
TEST_F(SecurityManagerTest, StartHandshake_SSLInitIsComplete) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
// Expect no message send
// Expect notifying listeners (success)
- EXPECT_CALL(mock_sm_listener, OnHandshakeDone(key, true)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_sm_listener,
+ OnHandshakeDone(key, SSLContext::Handshake_Result_Success))
+ .WillOnce(Return(true));
// Emulate SessionObserver result
- EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl)).
- WillOnce(Return(&mock_ssl_context_exists));
- EXPECT_CALL(mock_ssl_context_exists, IsInitCompleted()).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl))
+ .WillOnce(Return(&mock_ssl_context_exists));
+ EXPECT_CALL(mock_ssl_context_exists, IsInitCompleted())
+ .WillOnce(Return(true));
+ EXPECT_CALL(mock_crypto_manager, IsCertificateUpdateRequired())
+ .WillOnce(Return(false));
security_manager_->StartHandshake(key);
}
@@ -540,19 +605,22 @@ TEST_F(SecurityManagerTest, StartHandshake_SSLInitIsComplete) {
* getting SEND_HANDSHAKE_DATA with NULL data
*/
TEST_F(SecurityManagerTest, ProccessHandshakeData_WrongDataSize) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
uint32_t connection_id = 0;
uint8_t session_id = 0;
- //uint8_t protocol_version = 0;
+ // uint8_t protocol_version = 0;
EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _));
- EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id,_)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_session_observer,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(true));
// Expect InternalError with ERROR_ID
EXPECT_CALL(
- mock_protocol_handler,
- SendMessageToMobileApp( InternalErrorWithErrId( SecurityManager::ERROR_INVALID_QUERY_SIZE), is_final));
- EmulateMobileMessageHandShake(NULL, 0);
+ mock_protocol_handler,
+ SendMessageToMobileApp(
+ InternalErrorWithErrId(SecurityManager::ERROR_INVALID_QUERY_SIZE),
+ is_final));
+ EmulateMobileMessageHandshake(NULL, 0);
}
/*
* Shall send InternallError on
@@ -560,28 +628,32 @@ TEST_F(SecurityManagerTest, ProccessHandshakeData_WrongDataSize) {
* for service which is not protected
*/
TEST_F(SecurityManagerTest, ProccessHandshakeData_ServiceNotProtected) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
// Expect InternalError with ERROR_ID
uint32_t connection_id = 0;
uint8_t session_id = 0;
- //uint8_t protocol_version = 0;
+ // uint8_t protocol_version = 0;
EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _));
- EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id,_)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_session_observer,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .WillOnce(Return(true));
EXPECT_CALL(
- mock_protocol_handler,
- SendMessageToMobileApp( InternalErrorWithErrId( SecurityManager::ERROR_SERVICE_NOT_PROTECTED), is_final));
+ mock_protocol_handler,
+ SendMessageToMobileApp(
+ InternalErrorWithErrId(SecurityManager::ERROR_SERVICE_NOT_PROTECTED),
+ is_final));
// Expect notifying listeners (unsuccess)
- EXPECT_CALL(mock_sm_listener, OnHandshakeDone(key, false)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_sm_listener,
+ OnHandshakeDone(key, SSLContext::Handshake_Result_Fail))
+ .WillOnce(Return(true));
// Emulate SessionObserver result
- EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl)).
- WillOnce(ReturnNull());
+ EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl))
+ .WillOnce(ReturnNull());
const uint8_t data[] = {0x1, 0x2};
- EmulateMobileMessageHandShake(data, sizeof(data)/sizeof(data[0]));
+ EmulateMobileMessageHandshake(data, sizeof(data) / sizeof(data[0]));
}
/*
* Shall send InternallError on getting
@@ -589,235 +661,237 @@ TEST_F(SecurityManagerTest, ProccessHandshakeData_ServiceNotProtected) {
* data (DoHandshakeStep return NULL pointer)
*/
TEST_F(SecurityManagerTest, ProccessHandshakeData_InvalidData) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
// Count handshake calls
const int handshake_emulates = 4;
uint32_t connection_id = 0;
uint8_t session_id = 0;
- //uint8_t protocol_version = 0;
- EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _)).
- Times(handshake_emulates);
- EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id,_)).
- Times(handshake_emulates).
- WillRepeatedly(Return(true));
+ // uint8_t protocol_version = 0;
+ EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _))
+ .Times(handshake_emulates);
+ EXPECT_CALL(mock_session_observer,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .Times(handshake_emulates)
+ .WillRepeatedly(Return(true));
// Expect InternalError with ERROR_ID
EXPECT_CALL(
- mock_protocol_handler,
- SendMessageToMobileApp( InternalErrorWithErrId( SecurityManager::ERROR_SSL_INVALID_DATA), is_final)).
- Times(handshake_emulates);
+ mock_protocol_handler,
+ SendMessageToMobileApp(
+ InternalErrorWithErrId(SecurityManager::ERROR_SSL_INVALID_DATA),
+ is_final)).Times(handshake_emulates);
// Expect notifying listeners (unsuccess)
- EXPECT_CALL(mock_sm_listener, OnHandshakeDone(key, false)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_sm_listener,
+ OnHandshakeDone(key, SSLContext::Handshake_Result_Fail))
+ .WillOnce(Return(true));
// Emulate SessionObserver and CryptoManager result
- EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl)).
- Times(handshake_emulates).
- WillRepeatedly(Return(&mock_ssl_context_exists));
+ EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl))
+ .Times(handshake_emulates)
+ .WillRepeatedly(Return(&mock_ssl_context_exists));
// Emulate DoHandshakeStep fail logics
EXPECT_CALL(
- mock_ssl_context_exists, DoHandshakeStep(_, handshake_data_size, _, _)).
- WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
- SetArgPointee<3>(handshake_data_out_size),
- Return(security_manager::SSLContext::
- Handshake_Result_AbnormalFail))).
- WillOnce(DoAll(SetArgPointee<2>((uint8_t*)NULL),
- SetArgPointee<3>(handshake_data_out_size),
- Return(security_manager::SSLContext::
- Handshake_Result_AbnormalFail))).
- WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
- SetArgPointee<3>(0),
- Return(security_manager::SSLContext::
- Handshake_Result_AbnormalFail))).
- WillOnce(DoAll(SetArgPointee<2>((uint8_t*)NULL),
- SetArgPointee<3>(0),
- Return(security_manager::SSLContext::
- Handshake_Result_AbnormalFail)));
-
+ mock_ssl_context_exists,
+ DoHandshakeStep(HandshakeStepEq(handshake_data, handshake_data_size),
+ handshake_data_size,
+ _,
+ _))
+ .WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
+ SetArgPointee<3>(handshake_data_out_size),
+ Return(SSLContext::Handshake_Result_AbnormalFail)))
+ .WillOnce(DoAll(SetArgPointee<2>((uint8_t*)NULL),
+ SetArgPointee<3>(handshake_data_out_size),
+ Return(SSLContext::Handshake_Result_AbnormalFail)))
+ .WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
+ SetArgPointee<3>(0),
+ Return(SSLContext::Handshake_Result_AbnormalFail)))
+ .WillOnce(DoAll(SetArgPointee<2>((uint8_t*)NULL),
+ SetArgPointee<3>(0),
+ Return(SSLContext::Handshake_Result_AbnormalFail)));
// On each wrong handshake will be asked error
- EXPECT_CALL(mock_ssl_context_exists, LastError()).
- Times(handshake_emulates);
+ EXPECT_CALL(mock_ssl_context_exists, LastError()).Times(handshake_emulates);
// Emulate handshare #handshake_emulates times for 5 cases
- EmulateMobileMessageHandShake(handshake_data, handshake_data_size,
- handshake_emulates);
+ EmulateMobileMessageHandshake(
+ handshake_data, handshake_data_size, handshake_emulates);
}
/*
* Shall send HandshakeData on getting SEND_HANDSHAKE_DATA from mobile side
* with correct handshake data Check Fail and sussecc states
*/
TEST_F(SecurityManagerTest, ProccessHandshakeData_Answer) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
// Count handshake calls
const int handshake_emulates = 2;
uint32_t connection_id = 0;
uint8_t session_id = 0;
- //uint8_t protocol_version = 0;
- EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _)).
- Times(handshake_emulates);
- EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id,_)).
- Times(handshake_emulates).
- WillRepeatedly(Return(true));
-
- // Expect InternalError with ERROR_ID
- EXPECT_CALL(mock_protocol_handler, SendMessageToMobileApp(
- // FIXME : !!!
- _, is_final)).
- Times(handshake_emulates);
+ // uint8_t protocol_version = 0;
+ EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _))
+ .Times(handshake_emulates);
+ EXPECT_CALL(mock_session_observer,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .Times(handshake_emulates)
+ .WillRepeatedly(Return(true));
+
+ // Get size of raw message after
+ const size_t raw_message_size = 15;
+ EXPECT_CALL(mock_protocol_handler,
+ SendMessageToMobileApp(RawMessageEqSize(raw_message_size),
+ is_final)).Times(handshake_emulates);
// Expect notifying listeners (unsuccess)
- EXPECT_CALL(mock_sm_listener, OnHandshakeDone(key, false)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_sm_listener,
+ OnHandshakeDone(key, SSLContext::Handshake_Result_Fail))
+ .WillOnce(Return(true));
// Emulate SessionObserver and CryptoManager result
- EXPECT_CALL(mock_ssl_context_exists, IsInitCompleted()).
- Times(handshake_emulates).
- WillRepeatedly(Return(false));
- EXPECT_CALL(
- mock_session_observer, GetSSLContext(key, kControl)).
- Times(handshake_emulates).
- WillRepeatedly(Return(&mock_ssl_context_exists));
+ EXPECT_CALL(mock_ssl_context_exists, IsInitCompleted())
+ .Times(handshake_emulates)
+ .WillRepeatedly(Return(false));
+ EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl))
+ .Times(handshake_emulates)
+ .WillRepeatedly(Return(&mock_ssl_context_exists));
// Emulate DoHandshakeStep correct logics
EXPECT_CALL(
- mock_ssl_context_exists, DoHandshakeStep(_, handshake_data_size, _, _)).
- WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
- SetArgPointee<3>(handshake_data_out_size),
- Return(security_manager::SSLContext::
- Handshake_Result_Success))).
- WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
- SetArgPointee<3>(handshake_data_out_size),
- Return(security_manager::SSLContext::
- Handshake_Result_Fail)));
-
- EmulateMobileMessageHandShake(handshake_data, handshake_data_size,
- handshake_emulates);
+ mock_ssl_context_exists,
+ DoHandshakeStep(HandshakeStepEq(handshake_data, handshake_data_size),
+ handshake_data_size,
+ _,
+ _))
+ .WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
+ SetArgPointee<3>(handshake_data_out_size),
+ Return(SSLContext::Handshake_Result_Success)))
+ .WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
+ SetArgPointee<3>(handshake_data_out_size),
+ Return(SSLContext::Handshake_Result_Fail)));
+
+ EmulateMobileMessageHandshake(
+ handshake_data, handshake_data_size, handshake_emulates);
}
/*
* Shall call all listeners on success end handshake
* and return handshake data
* Check Fail and sussecc states
*/
-TEST_F(SecurityManagerTest, ProccessHandshakeData_HandShakeFinished) {
- SetMockCryptoManger();
+TEST_F(SecurityManagerTest, ProccessHandshakeData_HandshakeFinished) {
+ SetMockCryptoManager();
// Count handshake calls
const int handshake_emulates = 6;
// Expect no errors
// Expect notifying listeners (success)
- EXPECT_CALL(mock_sm_listener, OnHandshakeDone(key, true)).
- WillOnce(Return(true));
+ EXPECT_CALL(mock_sm_listener,
+ OnHandshakeDone(key, SSLContext::Handshake_Result_Success))
+ .WillOnce(Return(true));
// Emulate SessionObserver and CryptoManager result
+ EXPECT_CALL(mock_session_observer, GetSSLContext(key, kControl))
+ .Times(handshake_emulates)
+ .WillRepeatedly(Return(&mock_ssl_context_exists));
+ EXPECT_CALL(mock_ssl_context_exists, IsInitCompleted())
+ .Times(handshake_emulates)
+ .WillRepeatedly(Return(true));
+
EXPECT_CALL(
- mock_session_observer, GetSSLContext(key, kControl)).
- Times(handshake_emulates).
- WillRepeatedly(Return(&mock_ssl_context_exists));
- EXPECT_CALL(
- mock_ssl_context_exists, IsInitCompleted()).
- Times(handshake_emulates).
- WillRepeatedly(Return(true));
- // FIXME(EZamakhov): add DoHandshakeStep matcher for compare handshake data
- EXPECT_CALL(
- mock_ssl_context_exists, DoHandshakeStep(_, handshake_data_size, _, _)).
- // two states with correct out data
- WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
- SetArgPointee<3>(handshake_data_out_size),
- Return(security_manager::SSLContext::
- Handshake_Result_Success))).
- WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
- SetArgPointee<3>(handshake_data_out_size),
- Return(security_manager::SSLContext::
- Handshake_Result_Fail))).
- // two states with with null pointer data
- WillOnce(DoAll(SetArgPointee<2>((uint8_t*)NULL),
- SetArgPointee<3>(handshake_data_out_size),
- Return(security_manager::SSLContext::
- Handshake_Result_Success))).
- WillOnce(DoAll(SetArgPointee<2>((uint8_t*)NULL),
- SetArgPointee<3>(handshake_data_out_size),
- Return(security_manager::SSLContext::
- Handshake_Result_Fail))).
- // two states with with null data size
- WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
- SetArgPointee<3>(0),
- Return(security_manager::SSLContext::
- Handshake_Result_Success))).
- WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
- SetArgPointee<3>(0),
- Return(security_manager::SSLContext::
- Handshake_Result_Success)));
+ mock_ssl_context_exists,
+ DoHandshakeStep(HandshakeStepEq(handshake_data, handshake_data_size),
+ handshake_data_size,
+ _,
+ _))
+ .
+ // two states with correct out data
+ WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
+ SetArgPointee<3>(handshake_data_out_size),
+ Return(SSLContext::Handshake_Result_Success)))
+ .WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
+ SetArgPointee<3>(handshake_data_out_size),
+ Return(SSLContext::Handshake_Result_Fail)))
+ .
+ // two states with with null pointer data
+ WillOnce(DoAll(SetArgPointee<2>((uint8_t*)NULL),
+ SetArgPointee<3>(handshake_data_out_size),
+ Return(SSLContext::Handshake_Result_Success)))
+ .WillOnce(DoAll(SetArgPointee<2>((uint8_t*)NULL),
+ SetArgPointee<3>(handshake_data_out_size),
+ Return(SSLContext::Handshake_Result_Fail)))
+ .
+ // two states with with null data size
+ WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
+ SetArgPointee<3>(0),
+ Return(SSLContext::Handshake_Result_Success)))
+ .WillOnce(DoAll(SetArgPointee<2>(handshake_data_out_pointer),
+ SetArgPointee<3>(0),
+ Return(SSLContext::Handshake_Result_Success)));
// Expect send two message (with correct pointer and size data)
uint32_t connection_id = 0;
uint8_t session_id = 0;
- //uint8_t protocol_version = 0;
- EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _)).
- Times(2);
- EXPECT_CALL(mock_session_observer, ProtocolVersionUsed(connection_id, session_id,_)).
- Times(2).
- WillRepeatedly(Return(true));
+ // uint8_t protocol_version = 0;
+ EXPECT_CALL(mock_session_observer, PairFromKey(key, _, _)).Times(2);
+ EXPECT_CALL(mock_session_observer,
+ ProtocolVersionUsed(connection_id, session_id, _))
+ .Times(2)
+ .WillRepeatedly(Return(true));
- EXPECT_CALL(
- mock_protocol_handler, SendMessageToMobileApp(_, is_final)).
- Times(2);
+ EXPECT_CALL(mock_protocol_handler, SendMessageToMobileApp(_, is_final))
+ .Times(2);
// Expect NO InternalError with ERROR_ID
- EmulateMobileMessageHandShake(handshake_data, handshake_data_size, handshake_emulates);
+ EmulateMobileMessageHandshake(
+ handshake_data, handshake_data_size, handshake_emulates);
}
/*
* Shall not any query on getting empty SEND_INTERNAL_ERROR
*/
TEST_F(SecurityManagerTest, GetInternalError_NullData) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
- const SecurityQuery::QueryHeader header( SecurityQuery::NOTIFICATION,
- SecurityQuery::SEND_INTERNAL_ERROR, 0);
+ const SecurityQuery::QueryHeader header(
+ SecurityQuery::NOTIFICATION, SecurityQuery::SEND_INTERNAL_ERROR, 0);
EmulateMobileMessage(header, NULL, 0);
}
/*
* Shall not send any query on getting SEND_INTERNAL_ERROR
*/
TEST_F(SecurityManagerTest, GetInternalError) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
- const SecurityQuery::QueryHeader header( SecurityQuery::NOTIFICATION,
- SecurityQuery::SEND_INTERNAL_ERROR, 0);
+ const SecurityQuery::QueryHeader header(
+ SecurityQuery::NOTIFICATION, SecurityQuery::SEND_INTERNAL_ERROR, 0);
const uint8_t data[] = {0x1, 0x2};
- EmulateMobileMessage(header, data, sizeof(data)/sizeof(data[0]));
+ EmulateMobileMessage(header, data, sizeof(data) / sizeof(data[0]));
}
/*
* Shall not send any query on getting SEND_INTERNAL_ERROR with error string
*/
TEST_F(SecurityManagerTest, GetInternalError_WithErrText) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
- SecurityQuery::QueryHeader header( SecurityQuery::NOTIFICATION,
- SecurityQuery::SEND_INTERNAL_ERROR, 0);
+ SecurityQuery::QueryHeader header(
+ SecurityQuery::NOTIFICATION, SecurityQuery::SEND_INTERNAL_ERROR, 0);
std::string error("JSON wrong string");
header.json_size = error.size();
- EmulateMobileMessage(header,
- reinterpret_cast<const uint8_t*>(error.c_str()),
- error.size());
+ EmulateMobileMessage(
+ header, reinterpret_cast<const uint8_t*>(error.c_str()), error.size());
}
/*
* Shall not send any query on getting SEND_INTERNAL_ERROR with error string
*/
TEST_F(SecurityManagerTest, GetInternalError_WithErrJSONText) {
- SetMockCryptoManger();
+ SetMockCryptoManager();
- SecurityQuery::QueryHeader header( SecurityQuery::NOTIFICATION,
- SecurityQuery::SEND_INTERNAL_ERROR, 0);
+ SecurityQuery::QueryHeader header(
+ SecurityQuery::NOTIFICATION, SecurityQuery::SEND_INTERNAL_ERROR, 0);
std::string error(" { \"id\": 1 } ");
header.json_size = error.size();
- EmulateMobileMessage(header,
- reinterpret_cast<const uint8_t*>(error.c_str()),
- error.size());
+ EmulateMobileMessage(
+ header, reinterpret_cast<const uint8_t*>(error.c_str()), error.size());
}
-} // namespace security_manager_test
-} // namespace components
-} // namespace test
+} // namespace security_manager_test
+} // namespace components
+} // namespace test
diff --git a/src/components/security_manager/test/security_query_matcher.cc b/src/components/security_manager/test/security_query_matcher.cc
index 2320e83439..3b7f4dd298 100644
--- a/src/components/security_manager/test/security_query_matcher.cc
+++ b/src/components/security_manager/test/security_query_matcher.cc
@@ -30,8 +30,9 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include <gmock/gmock.h>
#include <string>
+
+#include "gmock/gmock.h"
#include "utils/byte_order.h"
#include "security_manager/security_query.h"
@@ -43,81 +44,80 @@ namespace security_manager_test {
* Matcher for checking RawMessage with InternalError Query
* Check error id
*/
-MATCHER_P(InternalErrorWithErrId, expectedErrorId,
- std::string(negation ? "is not" : "is")
- + " InternalError with selected error" ){
+MATCHER_P(InternalErrorWithErrId,
+ expectedErrorId,
+ std::string(negation ? "is not" : "is") +
+ " InternalError with selected error") {
const size_t header_size =
- sizeof(security_manager::SecurityQuery::QueryHeader);
+ sizeof(security_manager::SecurityQuery::QueryHeader);
if (arg->data_size() <= header_size) {
*result_listener << "Size " << arg->data_size()
- << " bytes less or equal sizeof(QueryHeader)="
- << header_size;
+ << " bytes less or equal sizeof(QueryHeader)="
+ << header_size;
return false;
}
- const uint8_t *data = arg->data();
+ const uint8_t* data = arg->data();
const uint8_t query_type = data[0];
if (security_manager::SecurityQuery::NOTIFICATION != query_type) {
- *result_listener << "RawMessage is not notification, type=0x"
- << std::hex << static_cast<int>(query_type);
+ *result_listener << "RawMessage is not notification, type=0x" << std::hex
+ << static_cast<int>(query_type);
return false;
}
// Read Big-Endian number
- const uint32_t query_id = data[1] << 16 |
- data[2] << 8 |
- data[3];
+ const uint32_t query_id = data[1] << 16 | data[2] << 8 | data[3];
if (security_manager::SecurityQuery::SEND_INTERNAL_ERROR != query_id) {
- *result_listener << "Notification is not InternalError, id=0x"
- << std::hex << query_id;
+ *result_listener << "Notification is not InternalError, id=0x" << std::hex
+ << query_id;
return false;
}
- const uint32_t json_size = data[8] << 24 |
- data[9] << 16 |
- data[10] << 8 |
- data[11];
+ const uint32_t json_size =
+ data[8] << 24 | data[9] << 16 | data[10] << 8 | data[11];
if (header_size + json_size >= arg->data_size()) {
*result_listener << "InternalError contains only JSON data.";
return false;
}
// Read err_id as bin data number
- const uint8_t *err_id =
- reinterpret_cast<const uint8_t *>(data + header_size + json_size);
+ const uint8_t* err_id =
+ reinterpret_cast<const uint8_t*>(data + header_size + json_size);
if (expectedErrorId != *err_id) {
*result_listener << "InternalError id " << static_cast<int>(*err_id)
- << " and not equal error " << expectedErrorId;
+ << " and not equal error " << expectedErrorId;
return false;
}
return true;
}
-} // namespace security_manager_test
-} // namespace components
-} // namespace test
-/*
- * Matcher for checking QueryHeader equal in GTests
- */
+} // namespace security_manager_test
+} // namespace components
+} // namespace test
+ /*
+ * Matcher for checking QueryHeader equal in GTests
+ */
::testing::AssertionResult QueryHeader_EQ(
- const char *m_expr, const char *n_expr,
- const ::security_manager::SecurityQuery::QueryHeader &q1,
- const ::security_manager::SecurityQuery::QueryHeader &q2);
+ const char* m_expr,
+ const char* n_expr,
+ const ::security_manager::SecurityQuery::QueryHeader& q1,
+ const ::security_manager::SecurityQuery::QueryHeader& q2);
::testing::AssertionResult QueryHeader_EQ(
- const char* m_expr, const char* n_expr,
- const ::security_manager::SecurityQuery::QueryHeader& q1,
- const ::security_manager::SecurityQuery::QueryHeader& q2) {
+ const char* m_expr,
+ const char* n_expr,
+ const ::security_manager::SecurityQuery::QueryHeader& q1,
+ const ::security_manager::SecurityQuery::QueryHeader& q2) {
::testing::AssertionResult fail_result = ::testing::AssertionFailure();
fail_result << "(\"" << m_expr << " and \"" << n_expr << "\") are not equal "
<< " : different ";
if (q1.json_size != q2.json_size)
- return fail_result << "json_size_1=" << q1.json_size << ", json_size_2="
- << q2.json_size;
+ return fail_result << "json_size_1=" << q1.json_size
+ << ", json_size_2=" << q2.json_size;
if (q1.query_id != q2.query_id)
- return fail_result << "query_id_1=" << q1.query_id << ", query_id_2="
- << q2.query_id;
+ return fail_result << "query_id_1=" << q1.query_id
+ << ", query_id_2=" << q2.query_id;
if (q1.query_type != q2.query_type)
- return fail_result << "query_type_1=" << q1.query_type << ", query_type_2="
- << q2.query_type;
+ return fail_result << "query_type_1=" << q1.query_type
+ << ", query_type_2=" << q2.query_type;
if (q1.seq_number != q2.seq_number)
- return fail_result << "seq_number_1=" << q1.seq_number << ", seq_number_2="
- << q2.seq_number;
+ return fail_result << "seq_number_1=" << q1.seq_number
+ << ", seq_number_2=" << q2.seq_number;
return ::testing::AssertionSuccess();
}
diff --git a/src/components/security_manager/test/security_query_test.cc b/src/components/security_manager/test/security_query_test.cc
index 6db076fd52..80da10ea72 100644
--- a/src/components/security_manager/test/security_query_test.cc
+++ b/src/components/security_manager/test/security_query_test.cc
@@ -30,16 +30,17 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include <gtest/gtest.h>
#include <vector>
#include <string>
+
+#include "gtest/gtest.h"
#include "security_manager/security_query.h"
#include "protocol_handler/protocol_payload.h"
#include "utils/byte_order.h"
-#include "include/security_manager_mock.h"
+#include "security_manager/mock_security_manager.h"
// Test values for compare after serialization and byteorder conversion
-#define SEQ_NUMBER 0x12345678u
+#define SEQ_NUMBER 0x12345678u
#define CONNECTION_KEY 0xABCDEF0u
namespace test {
@@ -68,7 +69,7 @@ class SecurityQueryTest : public ::testing::Test {
* Used for handling header and data array to byte array for serialization
*/
std::vector<uint8_t> DeserializeData(SecurityQuery::QueryHeader header,
- const uint8_t * const binary_data,
+ const uint8_t* const binary_data,
const size_t bin_data_size) const {
// convert to Big-Endian (network) order
const uint32_t query_id = header.query_id << 8;
@@ -91,8 +92,8 @@ class SecurityQueryTest : public ::testing::Test {
* for correct working on Mobile side (3*8 byte)
*/
TEST_F(SecurityQueryTest, Equal_RPCHeader) {
- ASSERT_EQ(sizeof(SecurityQuery::QueryHeader)*8,
- ::protocol_handler::ProtocolPayloadV2SizeBits());
+ ASSERT_EQ(sizeof(SecurityQuery::QueryHeader) * 8,
+ ::protocol_handler::ProtocolPayloadV2SizeBits());
}
/*
* Security QueryHeader default construction
@@ -107,16 +108,16 @@ TEST_F(SecurityQueryTest, QueryHeaderConstructor) {
*/
TEST_F(SecurityQueryTest, QueryHeaderConstructor2) {
SecurityQuery::QueryHeader new_header(SecurityQuery::NOTIFICATION,
- SecurityQuery::SEND_HANDSHAKE_DATA,
- SEQ_NUMBER);
+ SecurityQuery::SEND_HANDSHAKE_DATA,
+ SEQ_NUMBER);
ASSERT_EQ(new_header.query_type, SecurityQuery::NOTIFICATION);
ASSERT_EQ(new_header.query_id, SecurityQuery::SEND_HANDSHAKE_DATA);
ASSERT_EQ(new_header.seq_number, SEQ_NUMBER);
ASSERT_EQ(new_header.json_size, 0u);
SecurityQuery::QueryHeader new_header2(SecurityQuery::RESPONSE,
- SecurityQuery::SEND_INTERNAL_ERROR,
- SEQ_NUMBER + 1);
+ SecurityQuery::SEND_INTERNAL_ERROR,
+ SEQ_NUMBER + 1);
ASSERT_EQ(new_header2.query_type, SecurityQuery::RESPONSE);
ASSERT_EQ(new_header2.query_id, SecurityQuery::SEND_INTERNAL_ERROR);
ASSERT_EQ(new_header2.seq_number, SEQ_NUMBER + 1);
@@ -138,7 +139,7 @@ TEST_F(SecurityQueryTest, QueryConstructor) {
ASSERT_EQ(query.get_connection_key(), 0u);
ASSERT_EQ(query.get_data_size(), 0u);
- ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t *>(NULL));
+ ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t*>(NULL));
ASSERT_TRUE(query.get_json_message().empty());
EXPECT_PRED_FORMAT2(QueryHeader_EQ, query.get_header(), invalid_header);
@@ -155,7 +156,7 @@ TEST_F(SecurityQueryTest, QueryConstructor2) {
ASSERT_EQ(query.get_connection_key(), CONNECTION_KEY);
ASSERT_EQ(query.get_data_size(), 0u);
- ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t *>(NULL));
+ ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t*>(NULL));
ASSERT_TRUE(query.get_json_message().empty());
EXPECT_PRED_FORMAT2(QueryHeader_EQ, query.get_header(), init_header);
@@ -169,17 +170,14 @@ TEST_F(SecurityQueryTest, QueryConstructor2) {
*/
TEST_F(SecurityQueryTest, QueryConstructor3) {
uint8_t raw_data[] = {0x0, 0x1, 0x2};
- const size_t raw_data_size =
- sizeof(raw_data)/sizeof(raw_data[0]);
+ const size_t raw_data_size = sizeof(raw_data) / sizeof(raw_data[0]);
- SecurityQuery query(init_header,
- CONNECTION_KEY,
- raw_data, raw_data_size);
+ SecurityQuery query(init_header, CONNECTION_KEY, raw_data, raw_data_size);
ASSERT_EQ(query.get_connection_key(), CONNECTION_KEY);
ASSERT_EQ(query.get_data_size(), raw_data_size);
// query shall handle own array of byte data
- ASSERT_NE(query.get_data(), reinterpret_cast<uint8_t *>(NULL));
+ ASSERT_NE(query.get_data(), reinterpret_cast<uint8_t*>(NULL));
for (size_t i = 0; i < raw_data_size; ++i) {
ASSERT_EQ(query.get_data()[i], raw_data[i]);
}
@@ -188,7 +186,7 @@ TEST_F(SecurityQueryTest, QueryConstructor3) {
// Deserialization shall return vector equal header + data array
const std::vector<uint8_t> vector =
- DeserializeData(init_header, raw_data, raw_data_size);
+ DeserializeData(init_header, raw_data, raw_data_size);
const std::vector<uint8_t> deserialize_vector = query.DeserializeQuery();
ASSERT_EQ(deserialize_vector, vector);
}
@@ -198,8 +196,7 @@ TEST_F(SecurityQueryTest, QueryConstructor3) {
TEST_F(SecurityQueryTest, Setters) {
const std::string str = "test example string";
uint8_t raw_data[] = {0x6, 0x7, 0x8};
- const size_t raw_data_size =
- sizeof(raw_data)/sizeof(raw_data[0]);
+ const size_t raw_data_size = sizeof(raw_data) / sizeof(raw_data[0]);
SecurityQuery query;
query.set_connection_key(CONNECTION_KEY);
@@ -210,7 +207,7 @@ TEST_F(SecurityQueryTest, Setters) {
ASSERT_EQ(query.get_connection_key(), CONNECTION_KEY);
ASSERT_EQ(query.get_data_size(), raw_data_size);
// query shall handle own array of byte data
- ASSERT_NE(query.get_data(), reinterpret_cast<uint8_t *>(NULL));
+ ASSERT_NE(query.get_data(), reinterpret_cast<uint8_t*>(NULL));
for (size_t i = 0; i < raw_data_size; ++i) {
ASSERT_EQ(query.get_data()[i], raw_data[i]);
}
@@ -228,7 +225,7 @@ TEST_F(SecurityQueryTest, Parse_NullData) {
// check side-effects
ASSERT_EQ(query.get_connection_key(), 0u);
ASSERT_EQ(query.get_data_size(), 0u);
- ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t *>(NULL));
+ ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t*>(NULL));
ASSERT_TRUE(query.get_json_message().empty());
EXPECT_PRED_FORMAT2(QueryHeader_EQ, query.get_header(), invalid_header);
}
@@ -245,7 +242,7 @@ TEST_F(SecurityQueryTest, Parse_LessHeaderData) {
// check side-effects
ASSERT_EQ(query.get_connection_key(), 0u);
ASSERT_EQ(query.get_data_size(), 0u);
- ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t *>(NULL));
+ ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t*>(NULL));
ASSERT_TRUE(query.get_json_message().empty());
EXPECT_PRED_FORMAT2(QueryHeader_EQ, query.get_header(), invalid_header);
}
@@ -253,8 +250,7 @@ TEST_F(SecurityQueryTest, Parse_LessHeaderData) {
* SecurityQuery serializes data equal header size
*/
TEST_F(SecurityQueryTest, Parse_HeaderData) {
- const std::vector<uint8_t> vector =
- DeserializeData(init_header, NULL, 0u);
+ const std::vector<uint8_t> vector = DeserializeData(init_header, NULL, 0u);
SecurityQuery query;
const bool result = query.SerializeQuery(&vector[0], vector.size());
@@ -263,7 +259,7 @@ TEST_F(SecurityQueryTest, Parse_HeaderData) {
// check side-effects
ASSERT_EQ(query.get_connection_key(), 0u);
ASSERT_EQ(query.get_data_size(), 0u);
- ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t *>(NULL));
+ ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t*>(NULL));
ASSERT_TRUE(query.get_json_message().empty());
EXPECT_PRED_FORMAT2(QueryHeader_EQ, query.get_header(), init_header);
@@ -277,8 +273,7 @@ TEST_F(SecurityQueryTest, Parse_HeaderData) {
TEST_F(SecurityQueryTest, Parse_HeaderDataWrong) {
// Wrong json size
init_header.json_size = 0x0FFFFFFF;
- const std::vector<uint8_t> vector =
- DeserializeData(init_header, NULL, 0u);
+ const std::vector<uint8_t> vector = DeserializeData(init_header, NULL, 0u);
SecurityQuery query;
const bool result = query.SerializeQuery(&vector[0], vector.size());
@@ -287,7 +282,7 @@ TEST_F(SecurityQueryTest, Parse_HeaderDataWrong) {
// check side-effects
ASSERT_EQ(query.get_connection_key(), 0u);
ASSERT_EQ(query.get_data_size(), 0u);
- ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t *>(NULL));
+ ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t*>(NULL));
ASSERT_TRUE(query.get_json_message().empty());
EXPECT_PRED_FORMAT2(QueryHeader_EQ, query.get_header(), init_header);
@@ -307,11 +302,10 @@ TEST_F(SecurityQueryTest, Parse_InvalidQuery) {
// some sample data
uint8_t raw_data[] = {0x6, 0x7, 0x8};
- const size_t raw_data_size =
- sizeof(raw_data)/sizeof(raw_data[0]);
+ const size_t raw_data_size = sizeof(raw_data) / sizeof(raw_data[0]);
const std::vector<uint8_t> vector =
- DeserializeData(invalid_query_header, raw_data, raw_data_size);
+ DeserializeData(invalid_query_header, raw_data, raw_data_size);
SecurityQuery query;
const bool result = query.SerializeQuery(&vector[0], vector.size());
@@ -320,9 +314,9 @@ TEST_F(SecurityQueryTest, Parse_InvalidQuery) {
EXPECT_PRED_FORMAT2(QueryHeader_EQ, query.get_header(), invalid_query_header);
ASSERT_EQ(query.get_data_size(), raw_data_size);
// query shall handle own array of byte data
- ASSERT_NE(query.get_data(), reinterpret_cast<uint8_t *>(NULL));
+ ASSERT_NE(query.get_data(), reinterpret_cast<uint8_t*>(NULL));
for (size_t i = 0; i < raw_data_size; ++i) {
- ASSERT_EQ(query.get_data()[i], raw_data[+ i]);
+ ASSERT_EQ(query.get_data()[i], raw_data[+i]);
}
// check side-effects
ASSERT_EQ(query.get_connection_key(), 0u);
@@ -344,7 +338,7 @@ TEST_F(SecurityQueryTest, Parse_InvalidQuery_UnknownTypeId) {
SEQ_NUMBER);
const std::vector<uint8_t> vector =
- DeserializeData(invalid_type_id_header, NULL, 0u);
+ DeserializeData(invalid_type_id_header, NULL, 0u);
SecurityQuery query;
const bool result = query.SerializeQuery(&vector[0], vector.size());
@@ -352,10 +346,11 @@ TEST_F(SecurityQueryTest, Parse_InvalidQuery_UnknownTypeId) {
// Parse set all unknown types and ids to INVALID_QUERY_ID
invalid_type_id_header.query_type = SecurityQuery::INVALID_QUERY_TYPE;
invalid_type_id_header.query_id = SecurityQuery::INVALID_QUERY_ID;
- EXPECT_PRED_FORMAT2(QueryHeader_EQ, query.get_header(), invalid_type_id_header);
+ EXPECT_PRED_FORMAT2(
+ QueryHeader_EQ, query.get_header(), invalid_type_id_header);
// check side-effects
ASSERT_EQ(query.get_data_size(), 0u);
- ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t *>(NULL));
+ ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t*>(NULL));
ASSERT_EQ(query.get_connection_key(), 0u);
ASSERT_TRUE(query.get_json_message().empty());
}
@@ -370,7 +365,7 @@ TEST_F(SecurityQueryTest, Parse_InvalidQuery_UnknownId_Response) {
SecurityQuery::INVALID_QUERY_ID - 2,
SEQ_NUMBER);
const std::vector<uint8_t> vector =
- DeserializeData(invalid_id_header, NULL, 0u);
+ DeserializeData(invalid_id_header, NULL, 0u);
SecurityQuery query;
const bool result = query.SerializeQuery(&vector[0], vector.size());
@@ -380,7 +375,7 @@ TEST_F(SecurityQueryTest, Parse_InvalidQuery_UnknownId_Response) {
EXPECT_PRED_FORMAT2(QueryHeader_EQ, query.get_header(), invalid_id_header);
// check side-effects
ASSERT_EQ(query.get_data_size(), 0u);
- ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t *>(NULL));
+ ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t*>(NULL));
ASSERT_EQ(query.get_connection_key(), 0u);
ASSERT_TRUE(query.get_json_message().empty());
}
@@ -395,11 +390,10 @@ TEST_F(SecurityQueryTest, Parse_Handshake) {
SEQ_NUMBER);
// some sample data
uint8_t raw_data[] = {0x6, 0x7, 0x8};
- const size_t raw_data_size =
- sizeof(raw_data)/sizeof(raw_data[0]);
+ const size_t raw_data_size = sizeof(raw_data) / sizeof(raw_data[0]);
const std::vector<uint8_t> vector =
- DeserializeData(handshake_header, raw_data, raw_data_size);
+ DeserializeData(handshake_header, raw_data, raw_data_size);
SecurityQuery query;
const bool result = query.SerializeQuery(&vector[0], vector.size());
@@ -407,9 +401,9 @@ TEST_F(SecurityQueryTest, Parse_Handshake) {
EXPECT_PRED_FORMAT2(QueryHeader_EQ, query.get_header(), handshake_header);
ASSERT_EQ(query.get_data_size(), raw_data_size);
// query shall handle own array of byte data
- ASSERT_NE(query.get_data(), reinterpret_cast<uint8_t *>(NULL));
+ ASSERT_NE(query.get_data(), reinterpret_cast<uint8_t*>(NULL));
for (size_t i = 0; i < raw_data_size; ++i) {
- ASSERT_EQ(query.get_data()[i], raw_data[+ i]);
+ ASSERT_EQ(query.get_data()[i], raw_data[+i]);
}
// check side-effects
ASSERT_EQ(query.get_connection_key(), 0u);
@@ -426,23 +420,22 @@ TEST_F(SecurityQueryTest, Parse_Handshake) {
TEST_F(SecurityQueryTest, Parse_InternalError) {
std::string error_str = "{some error}";
SecurityQuery::QueryHeader internal_error_header(
- SecurityQuery::REQUEST,
- SecurityQuery::SEND_INTERNAL_ERROR,
- SEQ_NUMBER);
+ SecurityQuery::REQUEST, SecurityQuery::SEND_INTERNAL_ERROR, SEQ_NUMBER);
internal_error_header.json_size = error_str.size();
const uint8_t* raw_data = reinterpret_cast<const uint8_t*>(error_str.c_str());
const std::vector<uint8_t> vector =
- DeserializeData(internal_error_header, raw_data, error_str.size());
+ DeserializeData(internal_error_header, raw_data, error_str.size());
SecurityQuery query;
const bool result = query.SerializeQuery(&vector[0], vector.size());
ASSERT_TRUE(result);
- EXPECT_PRED_FORMAT2(QueryHeader_EQ, query.get_header(), internal_error_header);
+ EXPECT_PRED_FORMAT2(
+ QueryHeader_EQ, query.get_header(), internal_error_header);
// check side-effects
ASSERT_EQ(query.get_data_size(), 0u);
- ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t *>(NULL));
+ ASSERT_EQ(query.get_data(), reinterpret_cast<uint8_t*>(NULL));
ASSERT_EQ(query.get_connection_key(), 0u);
ASSERT_EQ(query.get_json_message(), error_str);
@@ -451,6 +444,6 @@ TEST_F(SecurityQueryTest, Parse_InternalError) {
ASSERT_EQ(deserialize_vector, vector);
}
-} // namespace security_manager_test
-} // namespace components
-} // namespace test
+} // namespace security_manager_test
+} // namespace components
+} // namespace test
diff --git a/src/components/security_manager/test/ssl_certificate_handshake_test.cc b/src/components/security_manager/test/ssl_certificate_handshake_test.cc
new file mode 100644
index 0000000000..3d62dd5d6a
--- /dev/null
+++ b/src/components/security_manager/test/ssl_certificate_handshake_test.cc
@@ -0,0 +1,583 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <fstream>
+#include <sstream>
+
+#include "gtest/gtest.h"
+#include "security_manager/crypto_manager_impl.h"
+#include "security_manager/mock_security_manager_settings.h"
+#include "utils/custom_string.h"
+
+using ::testing::Return;
+using ::testing::ReturnRef;
+
+namespace test {
+namespace components {
+namespace ssl_handshake_test {
+namespace custom_str = utils::custom_string;
+// Use this macro for correct line printing
+// in case of fail insize of the #method
+#define GTEST_TRACE(method) \
+ do { \
+ SCOPED_TRACE(""); \
+ method; \
+ } while (false)
+
+namespace {
+const std::string server_ca_cert_filename = "server";
+const std::string client_ca_cert_filename = "client";
+const std::string client_certificate = "client/client_credential.p12.enc";
+const std::string server_certificate = "server/spt_credential.p12.enc";
+const std::string server_unsigned_cert_file =
+ "server/spt_credential_unsigned.p12.enc";
+const std::string server_expired_cert_file =
+ "server/spt_credential_expired.p12.enc";
+
+const bool verify_peer = true;
+const bool skip_peer_verification = false;
+
+const size_t updates_before_hour = 24;
+
+} // namespace
+
+class SSLHandshakeTest : public testing::Test {
+ protected:
+ void SetUp() OVERRIDE {
+ mock_server_manager_settings = new testing::NiceMock<
+ security_manager_test::MockCryptoManagerSettings>();
+
+ server_manager = new security_manager::CryptoManagerImpl(
+ utils::SharedPtr<security_manager::CryptoManagerSettings>(
+ mock_server_manager_settings));
+ ASSERT_TRUE(server_manager);
+ mock_client_manager_settings = new testing::NiceMock<
+ security_manager_test::MockCryptoManagerSettings>();
+
+ client_manager = new security_manager::CryptoManagerImpl(
+ utils::SharedPtr<security_manager::CryptoManagerSettings>(
+ mock_client_manager_settings));
+ ASSERT_TRUE(client_manager);
+ server_ctx = NULL;
+ client_ctx = NULL;
+ }
+
+ void TearDown() OVERRIDE {
+ server_manager->ReleaseSSLContext(server_ctx);
+ delete server_manager;
+ client_manager->ReleaseSSLContext(client_ctx);
+ delete client_manager;
+ }
+
+ void SetServerInitialValues(const security_manager::Protocol protocol,
+ const std::string cert,
+ const std::string server_ciphers_list,
+ const bool verify_peer,
+ const std::string& ca_certificate_path) {
+ server_certificate_ = cert;
+ server_ciphers_list_ = server_ciphers_list;
+ server_ca_certificate_path_ = ca_certificate_path;
+
+ ON_CALL(*mock_server_manager_settings, security_manager_mode())
+ .WillByDefault(Return(security_manager::SERVER));
+ ON_CALL(*mock_server_manager_settings, security_manager_protocol_name())
+ .WillByDefault(Return(protocol));
+ ON_CALL(*mock_server_manager_settings, certificate_data())
+ .WillByDefault(ReturnRef(server_certificate_));
+ ON_CALL(*mock_server_manager_settings, ciphers_list())
+ .WillByDefault(ReturnRef(server_ciphers_list_));
+ ON_CALL(*mock_server_manager_settings, ca_cert_path())
+ .WillByDefault(ReturnRef(server_ca_certificate_path_));
+ ON_CALL(*mock_server_manager_settings, verify_peer())
+ .WillByDefault(Return(verify_peer));
+ }
+ void SetClientInitialValues(const security_manager::Protocol protocol,
+ const std::string certificate,
+ const std::string client_ciphers_list,
+ const bool verify_peer,
+ const std::string& ca_certificate_path) {
+ client_certificate_ = certificate;
+ client_ciphers_list_ = client_ciphers_list;
+ client_ca_certificate_path_ = ca_certificate_path;
+
+ ON_CALL(*mock_client_manager_settings, security_manager_mode())
+ .WillByDefault(Return(security_manager::CLIENT));
+ ON_CALL(*mock_client_manager_settings, security_manager_protocol_name())
+ .WillByDefault(Return(protocol));
+ ON_CALL(*mock_client_manager_settings, certificate_data())
+ .WillByDefault(ReturnRef(client_certificate_));
+ ON_CALL(*mock_client_manager_settings, ciphers_list())
+ .WillByDefault(ReturnRef(client_ciphers_list_));
+ ON_CALL(*mock_client_manager_settings, ca_cert_path())
+ .WillByDefault(ReturnRef(client_ca_certificate_path_));
+ ON_CALL(*mock_client_manager_settings, verify_peer())
+ .WillByDefault(Return(verify_peer));
+ }
+
+ bool InitServerManagers(security_manager::Protocol protocol,
+ const std::string& cert_filename,
+ const std::string& ciphers_list,
+ const bool verify_peer,
+ const std::string& ca_certificate_path) {
+ std::ifstream cert(cert_filename);
+ std::stringstream ss;
+ if (cert.is_open()) {
+ ss << cert.rdbuf();
+ }
+ cert.close();
+ SetServerInitialValues(
+ protocol, ss.str(), ciphers_list, verify_peer, ca_certificate_path);
+ const bool initialized = server_manager->Init();
+
+ if (!initialized) {
+ return false;
+ }
+
+ server_ctx = server_manager->CreateSSLContext();
+
+ if (!server_ctx) {
+ return false;
+ }
+
+ server_ctx->SetHandshakeContext(
+ security_manager::SSLContext::HandshakeContext(
+ custom_str::CustomString("SPT"),
+ custom_str::CustomString("client")));
+
+ return true;
+ }
+
+ bool InitClientManagers(security_manager::Protocol protocol,
+ const std::string& cert_filename,
+ const std::string& ciphers_list,
+ const bool verify_peer,
+ const std::string& ca_certificate_path) {
+ std::ifstream cert(cert_filename);
+ std::stringstream certificate;
+ if (cert.is_open()) {
+ certificate << cert.rdbuf();
+ }
+ cert.close();
+ SetClientInitialValues(protocol,
+ certificate.str(),
+ ciphers_list,
+ verify_peer,
+ ca_certificate_path);
+ const bool initialized = client_manager->Init();
+ if (!initialized) {
+ return false;
+ }
+
+ client_ctx = client_manager->CreateSSLContext();
+ if (!client_ctx) {
+ return false;
+ }
+
+ client_ctx->SetHandshakeContext(
+ security_manager::SSLContext::HandshakeContext(
+ custom_str::CustomString("SPT"),
+ custom_str::CustomString("server")));
+
+ return true;
+ }
+
+ void ResetConnections() {
+ ASSERT_NO_THROW(server_ctx->ResetConnection());
+ ASSERT_NO_THROW(client_ctx->ResetConnection());
+ }
+
+ void StartHandshake() {
+ using security_manager::SSLContext;
+
+ ASSERT_EQ(SSLContext::Handshake_Result_Success,
+ client_ctx->StartHandshake(&client_buf, &client_buf_len));
+ ASSERT_FALSE(client_buf == NULL);
+ ASSERT_GT(client_buf_len, 0u);
+ }
+
+ void HandshakeProcedure_Success() {
+ using security_manager::SSLContext;
+ StartHandshake();
+
+ while (true) {
+ ASSERT_EQ(SSLContext::Handshake_Result_Success,
+ server_ctx->DoHandshakeStep(
+ client_buf, client_buf_len, &server_buf, &server_buf_len))
+ << ERR_reason_error_string(ERR_get_error());
+ ASSERT_FALSE(server_buf == NULL);
+ ASSERT_GT(server_buf_len, 0u);
+
+ ASSERT_EQ(SSLContext::Handshake_Result_Success,
+ client_ctx->DoHandshakeStep(
+ server_buf, server_buf_len, &client_buf, &client_buf_len))
+ << ERR_reason_error_string(ERR_get_error());
+ if (server_ctx->IsInitCompleted()) {
+ break;
+ }
+
+ ASSERT_FALSE(client_buf == NULL);
+ ASSERT_GT(client_buf_len, 0u);
+ }
+ }
+
+ void HandshakeProcedure_ServerSideFail() {
+ using security_manager::SSLContext;
+
+ StartHandshake();
+
+ while (true) {
+ const SSLContext::HandshakeResult result = server_ctx->DoHandshakeStep(
+ client_buf, client_buf_len, &server_buf, &server_buf_len);
+ ASSERT_FALSE(server_ctx->IsInitCompleted())
+ << "Expected server side handshake fail";
+
+ // First few handshake will be successful
+ if (result != SSLContext::Handshake_Result_Success) {
+ // Test successfully passed with handshake fail
+ return;
+ }
+ ASSERT_FALSE(server_buf == NULL);
+ ASSERT_GT(server_buf_len, 0u);
+
+ ASSERT_EQ(SSLContext::Handshake_Result_Success,
+ client_ctx->DoHandshakeStep(
+ server_buf, server_buf_len, &client_buf, &client_buf_len))
+ << ERR_reason_error_string(ERR_get_error());
+ ASSERT_FALSE(client_ctx->IsInitCompleted())
+ << "Expected server side handshake fail";
+
+ ASSERT_FALSE(client_buf == NULL);
+ ASSERT_GT(client_buf_len, 0u);
+ }
+ FAIL() << "Expected server side handshake fail";
+ }
+
+ void HandshakeProcedure_ClientSideFail(
+ security_manager::SSLContext::HandshakeResult expected_result) {
+ using security_manager::SSLContext;
+
+ StartHandshake();
+
+ while (true) {
+ ASSERT_EQ(SSLContext::Handshake_Result_Success,
+ server_ctx->DoHandshakeStep(
+ client_buf, client_buf_len, &server_buf, &server_buf_len))
+ << ERR_reason_error_string(ERR_get_error());
+
+ ASSERT_FALSE(server_buf == NULL);
+ ASSERT_GT(server_buf_len, 0u);
+
+ const SSLContext::HandshakeResult result = client_ctx->DoHandshakeStep(
+ server_buf, server_buf_len, &client_buf, &client_buf_len);
+ ASSERT_FALSE(client_ctx->IsInitCompleted())
+ << "Expected client side handshake fail";
+
+ // First few handsahke will be successful
+ if (result != SSLContext::Handshake_Result_Success) {
+ // Test successfully passed with handshake fail
+ ASSERT_EQ(expected_result, result);
+ return;
+ }
+
+ ASSERT_FALSE(client_buf == NULL);
+ ASSERT_GT(client_buf_len, 0u);
+ }
+ FAIL() << "Expected client side handshake fail";
+ }
+
+ security_manager::CryptoManager* server_manager;
+ security_manager::CryptoManager* client_manager;
+ security_manager::SSLContext* server_ctx;
+ security_manager::SSLContext* client_ctx;
+ testing::NiceMock<security_manager_test::MockCryptoManagerSettings>*
+ mock_server_manager_settings;
+ testing::NiceMock<security_manager_test::MockCryptoManagerSettings>*
+ mock_client_manager_settings;
+
+ const uint8_t* server_buf;
+ const uint8_t* client_buf;
+ size_t server_buf_len;
+ size_t client_buf_len;
+
+ std::string server_certificate_;
+ std::string server_ciphers_list_;
+ std::string server_ca_certificate_path_;
+
+ std::string client_certificate_;
+ std::string client_ciphers_list_;
+ std::string client_ca_certificate_path_;
+};
+
+TEST_F(SSLHandshakeTest, NoVerification) {
+ ASSERT_TRUE(InitServerManagers(security_manager::TLSv1_2,
+ server_certificate,
+ "ALL",
+ skip_peer_verification,
+ ""))
+ << server_manager->LastError();
+ ASSERT_TRUE(InitClientManagers(security_manager::TLSv1_2,
+ client_certificate,
+ "ALL",
+ skip_peer_verification,
+ ""))
+ << client_manager->LastError();
+
+ GTEST_TRACE(HandshakeProcedure_Success());
+}
+
+TEST_F(SSLHandshakeTest, CAVerification_ServerSide) {
+ ASSERT_TRUE(InitServerManagers(security_manager::TLSv1_2,
+ server_certificate,
+ "ALL",
+ verify_peer,
+ client_ca_cert_filename))
+ << server_manager->LastError();
+ ASSERT_TRUE(InitClientManagers(security_manager::TLSv1_2,
+ client_certificate,
+ "ALL",
+ skip_peer_verification,
+ ""))
+ << client_manager->LastError();
+
+ GTEST_TRACE(HandshakeProcedure_Success());
+}
+
+TEST_F(SSLHandshakeTest, CAVerification_ServerSide_NoCACertificate) {
+ ASSERT_TRUE(InitServerManagers(security_manager::TLSv1_2,
+ server_certificate,
+ "ALL",
+ verify_peer,
+ "unex"))
+ << server_manager->LastError();
+ ASSERT_TRUE(InitClientManagers(security_manager::TLSv1_2,
+ client_certificate,
+ "ALL",
+ skip_peer_verification,
+ ""))
+ << client_manager->LastError();
+
+ GTEST_TRACE(HandshakeProcedure_ServerSideFail());
+ ASSERT_TRUE(InitServerManagers(security_manager::TLSv1_2,
+ server_certificate,
+ "ALL",
+ verify_peer,
+ client_ca_cert_filename))
+ << server_manager->LastError();
+
+ GTEST_TRACE(ResetConnections());
+
+ GTEST_TRACE(HandshakeProcedure_Success());
+}
+
+TEST_F(SSLHandshakeTest, CAVerification_ClientSide) {
+ ASSERT_TRUE(InitServerManagers(security_manager::TLSv1_2,
+ server_certificate,
+ "ALL",
+ verify_peer,
+ client_ca_cert_filename))
+ << server_manager->LastError();
+ ASSERT_TRUE(InitClientManagers(security_manager::TLSv1_2,
+ client_certificate,
+ "ALL",
+ verify_peer,
+ server_ca_cert_filename))
+ << client_manager->LastError();
+
+ GTEST_TRACE(HandshakeProcedure_Success());
+}
+
+TEST_F(SSLHandshakeTest, CAVerification_ClientSide_NoCACertificate) {
+ ASSERT_TRUE(InitServerManagers(security_manager::TLSv1_2,
+ server_certificate,
+ "ALL",
+ skip_peer_verification,
+ ""))
+ << server_manager->LastError();
+ ASSERT_TRUE(InitClientManagers(security_manager::TLSv1_2,
+ client_certificate,
+ "ALL",
+ verify_peer,
+ "client_ca_cert_filename"))
+ << client_manager->LastError();
+
+ GTEST_TRACE(HandshakeProcedure_ClientSideFail(
+ security_manager::SSLContext::Handshake_Result_Fail));
+
+ ASSERT_TRUE(InitClientManagers(security_manager::TLSv1_2,
+ client_certificate,
+ "ALL",
+ verify_peer,
+ server_ca_cert_filename))
+ << client_manager->LastError();
+
+ GTEST_TRACE(ResetConnections());
+
+ GTEST_TRACE(HandshakeProcedure_Success());
+}
+
+TEST_F(SSLHandshakeTest, CAVerification_BothSides) {
+ ASSERT_TRUE(InitServerManagers(security_manager::TLSv1_2,
+ server_certificate,
+ "ALL",
+ verify_peer,
+ client_ca_cert_filename))
+ << server_manager->LastError();
+ ASSERT_TRUE(InitClientManagers(security_manager::TLSv1_2,
+ client_certificate,
+ "ALL",
+ verify_peer,
+ server_ca_cert_filename))
+ << client_manager->LastError();
+
+ GTEST_TRACE(HandshakeProcedure_Success());
+}
+
+TEST_F(SSLHandshakeTest, UnsignedCert) {
+ ASSERT_TRUE(InitServerManagers(security_manager::TLSv1_2,
+ server_unsigned_cert_file,
+ "ALL",
+ skip_peer_verification,
+ ""))
+ << server_manager->LastError();
+ ASSERT_TRUE(InitClientManagers(security_manager::TLSv1_2,
+ client_certificate,
+ "ALL",
+ verify_peer,
+ client_ca_cert_filename))
+ << client_manager->LastError();
+ GTEST_TRACE(HandshakeProcedure_ClientSideFail(
+ security_manager::SSLContext::Handshake_Result_CertNotSigned));
+}
+
+TEST_F(SSLHandshakeTest, ExpiredCert) {
+ ASSERT_TRUE(InitServerManagers(security_manager::TLSv1_2,
+ server_expired_cert_file,
+ "ALL",
+ verify_peer,
+ client_ca_cert_filename))
+ << server_manager->LastError();
+ ASSERT_TRUE(InitClientManagers(security_manager::TLSv1_2,
+ client_certificate,
+ "ALL",
+ verify_peer,
+ server_ca_cert_filename))
+ << client_manager->LastError();
+
+ GTEST_TRACE(HandshakeProcedure_ClientSideFail(
+ security_manager::SSLContext::Handshake_Result_CertExpired));
+}
+
+TEST_F(SSLHandshakeTest, AppNameAndAppIDInvalid) {
+ ASSERT_TRUE(InitServerManagers(security_manager::TLSv1_2,
+ server_certificate,
+ "ALL",
+ verify_peer,
+ client_ca_cert_filename))
+ << server_manager->LastError();
+ ASSERT_TRUE(InitClientManagers(security_manager::TLSv1_2,
+ client_certificate,
+ "ALL",
+ verify_peer,
+ server_ca_cert_filename))
+ << client_manager->LastError();
+
+ client_ctx->SetHandshakeContext(
+ security_manager::SSLContext::HandshakeContext(
+ custom_str::CustomString("server"),
+ custom_str::CustomString("Wrong")));
+
+ GTEST_TRACE(HandshakeProcedure_ClientSideFail(
+ security_manager::SSLContext::Handshake_Result_AppNameMismatch));
+
+ ResetConnections();
+ client_ctx->SetHandshakeContext(
+ security_manager::SSLContext::HandshakeContext(
+ custom_str::CustomString("Wrong"),
+ custom_str::CustomString("server")));
+
+ GTEST_TRACE(HandshakeProcedure_ClientSideFail(
+ security_manager::SSLContext::Handshake_Result_AppIDMismatch));
+}
+
+TEST_F(SSLHandshakeTest, NoVerification_ResetConnection) {
+ ASSERT_TRUE(InitServerManagers(security_manager::TLSv1_2,
+ server_certificate,
+ "ALL",
+ skip_peer_verification,
+ ""))
+ << server_manager->LastError();
+ ASSERT_TRUE(InitClientManagers(security_manager::TLSv1_2,
+ client_certificate,
+ "ALL",
+ skip_peer_verification,
+ ""))
+ << client_manager->LastError();
+
+ const int times = 100;
+ for (int i = 0; i < times; ++i) {
+ // Expect success handshake
+ GTEST_TRACE(HandshakeProcedure_Success());
+
+ // Reset SSl connections
+ GTEST_TRACE(ResetConnections());
+ }
+}
+
+TEST_F(SSLHandshakeTest, CAVerification_BothSides_ResetConnection) {
+ ASSERT_TRUE(InitServerManagers(security_manager::TLSv1_2,
+ server_certificate,
+ "ALL",
+ verify_peer,
+ client_ca_cert_filename))
+ << server_manager->LastError();
+ ASSERT_TRUE(InitClientManagers(security_manager::TLSv1_2,
+ client_certificate,
+ "ALL",
+ skip_peer_verification,
+ server_ca_cert_filename))
+ << client_manager->LastError();
+
+ const int times = 100;
+ for (int i = 0; i < times; ++i) {
+ // Expect success handshake
+ GTEST_TRACE(HandshakeProcedure_Success());
+
+ // Reset SSl connections
+ GTEST_TRACE(ResetConnections());
+ }
+}
+
+// TODO(EZamakhov): add fail tests -broken or not full ca certificate chain
+
+} // namespace ssl_handshake_test
+} // namespace components
+} // namespace test
diff --git a/src/components/security_manager/test/ssl_context_test.cc b/src/components/security_manager/test/ssl_context_test.cc
new file mode 100644
index 0000000000..b35da3fc61
--- /dev/null
+++ b/src/components/security_manager/test/ssl_context_test.cc
@@ -0,0 +1,535 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include <fstream>
+#include <sstream>
+#include <string>
+#include <openssl/ssl.h>
+
+#include "security_manager/crypto_manager.h"
+#include "security_manager/crypto_manager_impl.h"
+#include "security_manager/ssl_context.h"
+#include "utils/custom_string.h"
+#include "security_manager/mock_security_manager_settings.h"
+#include "utils/shared_ptr.h"
+#include "utils/make_shared.h"
+
+using ::testing::Return;
+using ::testing::ReturnRef;
+using ::testing::NiceMock;
+
+namespace {
+const size_t kUpdatesBeforeHour = 24;
+const std::string kCaPath = "";
+const uint8_t* kServerBuf;
+const uint8_t* kClientBuf;
+const std::string kAllCiphers = "ALL";
+size_t server_buf_len;
+size_t client_buf_len;
+#ifdef __QNXNTO__
+const std::string kFordCipher = SSL3_TXT_RSA_DES_192_CBC3_SHA;
+#else
+// Used cipher from ford protocol requirement
+const std::string kFordCipher = TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384;
+#endif
+} // namespace
+
+namespace test {
+namespace components {
+namespace ssl_context_test {
+namespace custom_str = utils::custom_string;
+
+struct ProtocolAndCipher {
+ security_manager::Protocol server_protocol;
+ security_manager::Protocol client_protocol;
+ std::string server_ciphers_list;
+ std::string client_ciphers_list;
+
+ ProtocolAndCipher(security_manager::Protocol s_protocol,
+ security_manager::Protocol c_protocol,
+ std::string s_ciphers_list,
+ std::string c_ciphers_list)
+ : server_protocol(s_protocol)
+ , client_protocol(c_protocol)
+ , server_ciphers_list(s_ciphers_list)
+ , client_ciphers_list(c_ciphers_list) {}
+};
+
+class SSLTest : public testing::Test {
+ protected:
+ static void SetUpTestCase() {
+ std::ifstream certificate_file("server/spt_credential_unsigned.p12");
+ std::stringstream certificate;
+ if (certificate_file.is_open()) {
+ certificate << certificate_file.rdbuf();
+ }
+ certificate_file.close();
+ certificate_data_base64_ = certificate.str();
+ ASSERT_FALSE(certificate_data_base64_.empty())
+ << "Certificate data file is empty";
+ }
+
+ virtual void SetUp() OVERRIDE {
+ mock_crypto_manager_settings_ = utils::MakeShared<
+ NiceMock<security_manager_test::MockCryptoManagerSettings>>();
+ utils::SharedPtr<security_manager::CryptoManagerSettings> crypto_set(
+ mock_crypto_manager_settings_);
+ crypto_manager_ = new security_manager::CryptoManagerImpl(crypto_set);
+
+ EXPECT_CALL(*mock_crypto_manager_settings_, security_manager_mode())
+ .WillOnce(Return(security_manager::SERVER));
+ EXPECT_CALL(*mock_crypto_manager_settings_,
+ security_manager_protocol_name())
+ .WillOnce(Return(security_manager::TLSv1_2));
+ EXPECT_CALL(*mock_crypto_manager_settings_, certificate_data())
+ .WillOnce(ReturnRef(certificate_data_base64_));
+ EXPECT_CALL(*mock_crypto_manager_settings_, ciphers_list())
+ .WillRepeatedly(ReturnRef(kAllCiphers));
+ EXPECT_CALL(*mock_crypto_manager_settings_, ca_cert_path())
+ .WillRepeatedly(ReturnRef(kCaPath));
+ EXPECT_CALL(*mock_crypto_manager_settings_, verify_peer())
+ .WillOnce(Return(false));
+ const bool crypto_manager_initialization = crypto_manager_->Init();
+ EXPECT_TRUE(crypto_manager_initialization);
+
+ mock_client_manager_settings_ = utils::MakeShared<
+ NiceMock<security_manager_test::MockCryptoManagerSettings>>();
+ utils::SharedPtr<security_manager::CryptoManagerSettings> client_crypto(
+ mock_client_manager_settings_);
+ client_manager_ = new security_manager::CryptoManagerImpl(client_crypto);
+
+ EXPECT_CALL(*mock_client_manager_settings_, security_manager_mode())
+ .WillOnce(Return(security_manager::CLIENT));
+ EXPECT_CALL(*mock_client_manager_settings_,
+ security_manager_protocol_name())
+ .WillOnce(Return(security_manager::TLSv1_2));
+ EXPECT_CALL(*mock_client_manager_settings_, certificate_data())
+ .WillOnce(ReturnRef(certificate_data_base64_));
+ EXPECT_CALL(*mock_client_manager_settings_, ciphers_list())
+ .WillRepeatedly(ReturnRef(kAllCiphers));
+ EXPECT_CALL(*mock_client_manager_settings_, ca_cert_path())
+ .Times(2)
+ .WillRepeatedly(ReturnRef(kCaPath));
+ EXPECT_CALL(*mock_client_manager_settings_, verify_peer())
+ .WillOnce(Return(false));
+ const bool client_manager_initialization = client_manager_->Init();
+ EXPECT_TRUE(client_manager_initialization);
+
+ ON_CALL(*mock_crypto_manager_settings_, maximum_payload_size())
+ .WillByDefault(Return(kMaximumPayloadSize));
+ ON_CALL(*mock_client_manager_settings_, maximum_payload_size())
+ .WillByDefault(Return(kMaximumPayloadSize));
+ EXPECT_CALL(*mock_crypto_manager_settings_, security_manager_mode())
+ .WillRepeatedly(Return(security_manager::SERVER));
+ server_ctx = crypto_manager_->CreateSSLContext();
+ EXPECT_CALL(*mock_client_manager_settings_, security_manager_mode())
+ .Times(2)
+ .WillRepeatedly(Return(security_manager::CLIENT));
+ client_ctx = client_manager_->CreateSSLContext();
+
+ using custom_str::CustomString;
+ security_manager::SSLContext::HandshakeContext ctx(CustomString("SPT"),
+ CustomString("client"));
+ server_ctx->SetHandshakeContext(ctx);
+
+ ctx.expected_cn = "server";
+ client_ctx->SetHandshakeContext(ctx);
+
+ kServerBuf = NULL;
+ kClientBuf = NULL;
+ server_buf_len = 0u;
+ client_buf_len = 0u;
+ }
+
+ void TearDown() OVERRIDE {
+ crypto_manager_->ReleaseSSLContext(server_ctx);
+ client_manager_->ReleaseSSLContext(client_ctx);
+
+ delete crypto_manager_;
+ delete client_manager_;
+ }
+
+ const size_t kMaximumPayloadSize = 1000u;
+ security_manager::CryptoManager* crypto_manager_;
+ security_manager::CryptoManager* client_manager_;
+ utils::SharedPtr<NiceMock<security_manager_test::MockCryptoManagerSettings>>
+ mock_crypto_manager_settings_;
+ utils::SharedPtr<NiceMock<security_manager_test::MockCryptoManagerSettings>>
+ mock_client_manager_settings_;
+ security_manager::SSLContext* server_ctx;
+ security_manager::SSLContext* client_ctx;
+
+ static std::string certificate_data_base64_;
+};
+std::string SSLTest::certificate_data_base64_;
+
+// StartHandshake() fails when client and server protocols are not TLSv1_2
+class SSLTestParam : public testing::TestWithParam<ProtocolAndCipher> {
+ protected:
+ virtual void SetUp() OVERRIDE {
+ std::ifstream certificate_file("server/spt_credential.p12");
+ ASSERT_TRUE(certificate_file.is_open())
+ << "Could not open certificate data file";
+
+ const std::string certificate(
+ (std::istreambuf_iterator<char>(certificate_file)),
+ std::istreambuf_iterator<char>());
+ certificate_file.close();
+ ASSERT_FALSE(certificate.empty()) << "Certificate data file is empty";
+ certificate_data_base64_ = certificate;
+
+ mock_crypto_manager_settings_ = utils::MakeShared<
+ NiceMock<security_manager_test::MockCryptoManagerSettings>>();
+ utils::SharedPtr<security_manager::CryptoManagerSettings> server_crypto(
+ mock_crypto_manager_settings_);
+ crypto_manager = new security_manager::CryptoManagerImpl(server_crypto);
+
+ SetServerInitialValues(GetParam().server_protocol,
+ GetParam().server_ciphers_list);
+
+ const bool crypto_manager_initialization = crypto_manager->Init();
+ EXPECT_TRUE(crypto_manager_initialization);
+
+ mock_client_manager_settings_ = utils::MakeShared<
+ NiceMock<security_manager_test::MockCryptoManagerSettings>>();
+
+ utils::SharedPtr<security_manager::CryptoManagerSettings> client_crypto(
+ mock_client_manager_settings_);
+ client_manager = new security_manager::CryptoManagerImpl(client_crypto);
+
+ SetClientInitialValues(GetParam().client_protocol,
+ GetParam().client_ciphers_list);
+
+ const bool client_manager_initialization = client_manager->Init();
+ EXPECT_TRUE(client_manager_initialization);
+
+ server_ctx = crypto_manager->CreateSSLContext();
+ client_ctx = client_manager->CreateSSLContext();
+
+ using custom_str::CustomString;
+ security_manager::SSLContext::HandshakeContext ctx(CustomString("SPT"),
+ CustomString("client"));
+ server_ctx->SetHandshakeContext(ctx);
+
+ ctx.expected_cn = "server";
+ client_ctx->SetHandshakeContext(ctx);
+
+ kServerBuf = NULL;
+ kClientBuf = NULL;
+ server_buf_len = 0u;
+ client_buf_len = 0u;
+ }
+
+ void TearDown() OVERRIDE {
+ crypto_manager->ReleaseSSLContext(server_ctx);
+ client_manager->ReleaseSSLContext(client_ctx);
+
+ delete crypto_manager;
+ delete client_manager;
+ }
+
+ void SetServerInitialValues(security_manager::Protocol protocol,
+ const std::string& server_ciphers_list) {
+ ON_CALL(*mock_crypto_manager_settings_, security_manager_mode())
+ .WillByDefault(Return(security_manager::SERVER));
+ ON_CALL(*mock_crypto_manager_settings_, security_manager_protocol_name())
+ .WillByDefault(Return(protocol));
+ ON_CALL(*mock_crypto_manager_settings_, certificate_data())
+ .WillByDefault(ReturnRef(certificate_data_base64_));
+ ON_CALL(*mock_crypto_manager_settings_, ciphers_list())
+ .WillByDefault(ReturnRef(server_ciphers_list));
+ ON_CALL(*mock_crypto_manager_settings_, ca_cert_path())
+ .WillByDefault(ReturnRef(kCaPath));
+ ON_CALL(*mock_crypto_manager_settings_, verify_peer())
+ .WillByDefault(Return(false));
+ }
+ void SetClientInitialValues(security_manager::Protocol protocol,
+ const std::string& client_ciphers_list) {
+ ON_CALL(*mock_client_manager_settings_, security_manager_mode())
+ .WillByDefault(Return(security_manager::CLIENT));
+ ON_CALL(*mock_client_manager_settings_, security_manager_protocol_name())
+ .WillByDefault(Return(protocol));
+ ON_CALL(*mock_client_manager_settings_, certificate_data())
+ .WillByDefault(ReturnRef(certificate_data_base64_));
+ ON_CALL(*mock_client_manager_settings_, ciphers_list())
+ .WillByDefault(ReturnRef(client_ciphers_list));
+ ON_CALL(*mock_client_manager_settings_, ca_cert_path())
+ .WillByDefault(ReturnRef(kCaPath));
+ ON_CALL(*mock_client_manager_settings_, verify_peer())
+ .WillByDefault(Return(false));
+ }
+
+ utils::SharedPtr<NiceMock<security_manager_test::MockCryptoManagerSettings>>
+ mock_crypto_manager_settings_;
+ utils::SharedPtr<NiceMock<security_manager_test::MockCryptoManagerSettings>>
+ mock_client_manager_settings_;
+ security_manager::CryptoManager* crypto_manager;
+ security_manager::CryptoManager* client_manager;
+ security_manager::SSLContext* server_ctx;
+ security_manager::SSLContext* client_ctx;
+ std::string certificate_data_base64_;
+};
+
+class SSLTestForTLS1_2 : public SSLTestParam {};
+
+// This case fails starting because we can handshake only with TLSv1_2 protocol.
+INSTANTIATE_TEST_CASE_P(
+ CorrectProtocolAndCiphers,
+ SSLTestParam,
+ ::testing::Values(ProtocolAndCipher(security_manager::TLSv1,
+ security_manager::TLSv1,
+ kFordCipher,
+ kFordCipher),
+ ProtocolAndCipher(security_manager::TLSv1_1,
+ security_manager::TLSv1_1,
+ kFordCipher,
+ kFordCipher),
+ ProtocolAndCipher(security_manager::SSLv3,
+ security_manager::SSLv3,
+ kFordCipher,
+ kFordCipher)));
+
+INSTANTIATE_TEST_CASE_P(
+ IncorrectProtocolAndCiphers,
+ SSLTestParam,
+ ::testing::Values(ProtocolAndCipher(security_manager::TLSv1,
+ security_manager::TLSv1_1,
+ kFordCipher,
+ kFordCipher),
+ ProtocolAndCipher(security_manager::TLSv1,
+ security_manager::SSLv3,
+ kFordCipher,
+ kFordCipher),
+ ProtocolAndCipher(security_manager::TLSv1_1,
+ security_manager::TLSv1,
+ kFordCipher,
+ kFordCipher),
+ ProtocolAndCipher(security_manager::TLSv1_1,
+ security_manager::SSLv3,
+ kFordCipher,
+ kFordCipher),
+ ProtocolAndCipher(security_manager::TLSv1_2,
+ security_manager::TLSv1,
+ kFordCipher,
+ kFordCipher),
+ ProtocolAndCipher(security_manager::TLSv1_2,
+ security_manager::TLSv1_1,
+ kFordCipher,
+ kFordCipher),
+ ProtocolAndCipher(security_manager::TLSv1_2,
+ security_manager::SSLv3,
+ kFordCipher,
+ kFordCipher),
+ ProtocolAndCipher(security_manager::SSLv3,
+ security_manager::TLSv1,
+ kFordCipher,
+ kFordCipher),
+ ProtocolAndCipher(security_manager::SSLv3,
+ security_manager::TLSv1_1,
+ kFordCipher,
+ kFordCipher)));
+
+TEST_F(SSLTest, OnTSL2Protocol_BrokenHandshake) {
+ ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
+ client_ctx->StartHandshake(&kClientBuf, &client_buf_len));
+ ASSERT_FALSE(NULL == kClientBuf);
+ ASSERT_LT(0u, client_buf_len);
+ // Broke 3 bytes for get abnormal fail of handshake
+ const_cast<uint8_t*>(kClientBuf)[0] ^= 0xFF;
+ const_cast<uint8_t*>(kClientBuf)[client_buf_len / 2] ^= 0xFF;
+ const_cast<uint8_t*>(kClientBuf)[client_buf_len - 1] ^= 0xFF;
+ ASSERT_EQ(security_manager::SSLContext::Handshake_Result_AbnormalFail,
+ server_ctx->DoHandshakeStep(
+ kClientBuf, client_buf_len, &kServerBuf, &server_buf_len));
+ EXPECT_EQ("Initialization is not completed", server_ctx->LastError());
+ EXPECT_EQ("Initialization is not completed", client_ctx->LastError());
+}
+
+// TODO {AKozoriz} : Unexpected uncomplited init of SSL component.
+// In this and next tests.
+// Must be fixed after merge to develop.
+TEST_F(SSLTest, DISABLED_OnTSL2Protocol_Positive) {
+ ASSERT_EQ(client_ctx->StartHandshake(&kClientBuf, &client_buf_len),
+ security_manager::SSLContext::Handshake_Result_Success);
+ ASSERT_FALSE(NULL == kClientBuf);
+ ASSERT_LT(0u, client_buf_len);
+ EXPECT_TRUE(server_ctx->IsInitCompleted());
+
+ while (true) {
+ const security_manager::SSLContext::HandshakeResult server_result =
+ server_ctx->DoHandshakeStep(
+ kClientBuf, client_buf_len, &kServerBuf, &server_buf_len);
+ ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
+ server_result);
+ ASSERT_FALSE(NULL == kServerBuf);
+ ASSERT_LT(0u, server_buf_len);
+
+ const security_manager::SSLContext::HandshakeResult client_result =
+ client_ctx->DoHandshakeStep(
+ kServerBuf, server_buf_len, &kClientBuf, &client_buf_len);
+ ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
+ client_result);
+ if (server_ctx->IsInitCompleted()) {
+ break;
+ }
+
+ ASSERT_FALSE(NULL == kClientBuf);
+ ASSERT_LT(0u, client_buf_len);
+ }
+ // Expect empty buffers after init complete
+ ASSERT_TRUE(NULL == kClientBuf);
+ ASSERT_EQ(0u, client_buf_len);
+ // expect both side initialization complete
+ EXPECT_TRUE(client_ctx->IsInitCompleted());
+ EXPECT_TRUE(server_ctx->IsInitCompleted());
+
+ // Encrypt text on client side
+ const uint8_t* text = reinterpret_cast<const uint8_t*>("abra");
+ const uint8_t* encrypted_text = 0;
+ size_t text_len = 4;
+ size_t encrypted_text_len;
+ EXPECT_TRUE(client_ctx->Encrypt(
+ text, text_len, &encrypted_text, &encrypted_text_len));
+
+ ASSERT_NE(reinterpret_cast<void*>(NULL), encrypted_text);
+ ASSERT_LT(0u, encrypted_text_len);
+
+ // Decrypt text on server side
+ EXPECT_TRUE(server_ctx->Decrypt(
+ encrypted_text, encrypted_text_len, &text, &text_len));
+ ASSERT_NE(reinterpret_cast<void*>(NULL), text);
+ ASSERT_LT(0u, text_len);
+
+ ASSERT_EQ(strncmp(reinterpret_cast<const char*>(text), "abra", 4), 0);
+}
+
+TEST_F(SSLTest, DISABLED_OnTSL2Protocol_EcncryptionFail) {
+ ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
+ client_ctx->StartHandshake(&kClientBuf, &client_buf_len));
+
+ while (!server_ctx->IsInitCompleted()) {
+ ASSERT_FALSE(NULL == kClientBuf);
+ ASSERT_LT(0u, client_buf_len);
+ ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
+ server_ctx->DoHandshakeStep(
+ kClientBuf, client_buf_len, &kServerBuf, &server_buf_len));
+ ASSERT_FALSE(NULL == kServerBuf);
+ ASSERT_LT(0u, server_buf_len);
+
+ ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
+ client_ctx->DoHandshakeStep(
+ kServerBuf, server_buf_len, &kClientBuf, &client_buf_len));
+ }
+ // Expect empty buffers after init complete
+ ASSERT_TRUE(NULL == kClientBuf);
+ ASSERT_EQ(0u, client_buf_len);
+ // Expect both side initialization complete
+ EXPECT_TRUE(client_ctx->IsInitCompleted());
+ EXPECT_TRUE(server_ctx->IsInitCompleted());
+
+ // Encrypt text on client side
+ const uint8_t* text = reinterpret_cast<const uint8_t*>("abra");
+ const uint8_t* encrypted_text = 0;
+ size_t text_len = 4;
+ size_t encrypted_text_len;
+ EXPECT_TRUE(client_ctx->Encrypt(
+ text, text_len, &encrypted_text, &encrypted_text_len));
+ ASSERT_NE(reinterpret_cast<void*>(NULL), encrypted_text);
+ ASSERT_LT(0u, encrypted_text_len);
+
+ std::vector<uint8_t> broken(encrypted_text,
+ encrypted_text + encrypted_text_len);
+ // Broke message
+ broken[encrypted_text_len / 2] ^= 0xFF;
+
+ const uint8_t* out_text;
+ size_t out_text_size;
+ // Decrypt broken text on server side
+ EXPECT_FALSE(server_ctx->Decrypt(
+ &broken[0], broken.size(), &out_text, &out_text_size));
+
+ // Check after broken message that server encryption and decryption fail
+ // Encrypte message on server side
+ EXPECT_FALSE(server_ctx->Decrypt(
+ encrypted_text, encrypted_text_len, &out_text, &out_text_size));
+ EXPECT_FALSE(server_ctx->Encrypt(
+ text, text_len, &encrypted_text, &encrypted_text_len));
+}
+
+TEST_P(SSLTestParam, ClientAndServerNotTLSv1_2_HandshakeFailed) {
+ ASSERT_EQ(security_manager::SSLContext::Handshake_Result_AbnormalFail,
+ client_ctx->StartHandshake(&kClientBuf, &client_buf_len));
+ EXPECT_TRUE(NULL == kClientBuf);
+ EXPECT_EQ(0u, client_buf_len);
+ ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
+ server_ctx->DoHandshakeStep(
+ kClientBuf, client_buf_len, &kServerBuf, &server_buf_len));
+ EXPECT_TRUE(NULL == kServerBuf);
+ EXPECT_EQ(0u, server_buf_len);
+
+ EXPECT_FALSE(server_ctx->IsInitCompleted());
+}
+
+INSTANTIATE_TEST_CASE_P(
+ ServerProtocolTLSv12,
+ SSLTestForTLS1_2,
+ ::testing::Values(ProtocolAndCipher(security_manager::TLSv1,
+ security_manager::TLSv1_2,
+ kFordCipher,
+ kFordCipher),
+ ProtocolAndCipher(security_manager::TLSv1_1,
+ security_manager::TLSv1_2,
+ kFordCipher,
+ kFordCipher),
+ ProtocolAndCipher(security_manager::SSLv3,
+ security_manager::TLSv1_2,
+ kFordCipher,
+ kFordCipher)));
+
+TEST_P(SSLTestForTLS1_2, HandshakeFailed) {
+ ASSERT_EQ(security_manager::SSLContext::Handshake_Result_Success,
+ client_ctx->StartHandshake(&kClientBuf, &client_buf_len));
+ EXPECT_FALSE(NULL == kClientBuf);
+ ASSERT_LT(0u, client_buf_len);
+ ASSERT_EQ(security_manager::SSLContext::Handshake_Result_AbnormalFail,
+ server_ctx->DoHandshakeStep(
+ kClientBuf, client_buf_len, &kServerBuf, &server_buf_len));
+ EXPECT_TRUE(NULL == kServerBuf);
+ EXPECT_EQ(0u, server_buf_len);
+
+ EXPECT_FALSE(server_ctx->IsInitCompleted());
+}
+
+} // namespace ssl_context_test
+} // namespace components
+} // namespace test
diff --git a/src/components/smart_objects/include/smart_objects/always_false_schema_item.h b/src/components/smart_objects/include/smart_objects/always_false_schema_item.h
index c4babbf8b4..dfbf4ba43e 100644
--- a/src/components/smart_objects/include/smart_objects/always_false_schema_item.h
+++ b/src/components/smart_objects/include/smart_objects/always_false_schema_item.h
@@ -54,6 +54,7 @@ class CAlwaysFalseSchemaItem : public ISchemaItem {
* @return Errors::ERROR
**/
Errors::eType validate(const SmartObject& Object) OVERRIDE;
+
private:
CAlwaysFalseSchemaItem();
DISALLOW_COPY_AND_ASSIGN(CAlwaysFalseSchemaItem);
diff --git a/src/components/smart_objects/include/smart_objects/always_true_schema_item.h b/src/components/smart_objects/include/smart_objects/always_true_schema_item.h
index 1b5fa8a765..3dd598d7bd 100644
--- a/src/components/smart_objects/include/smart_objects/always_true_schema_item.h
+++ b/src/components/smart_objects/include/smart_objects/always_true_schema_item.h
@@ -54,6 +54,7 @@ class CAlwaysTrueSchemaItem : public ISchemaItem {
* @return NsSmartObjects::Errors::eType
**/
Errors::eType validate(const SmartObject& Object) OVERRIDE;
+
private:
CAlwaysTrueSchemaItem();
DISALLOW_COPY_AND_ASSIGN(CAlwaysTrueSchemaItem);
diff --git a/src/components/smart_objects/include/smart_objects/array_schema_item.h b/src/components/smart_objects/include/smart_objects/array_schema_item.h
index 6454693b38..0d3a651d56 100644
--- a/src/components/smart_objects/include/smart_objects/array_schema_item.h
+++ b/src/components/smart_objects/include/smart_objects/array_schema_item.h
@@ -57,8 +57,10 @@ class CArraySchemaItem : public ISchemaItem {
**/
static utils::SharedPtr<CArraySchemaItem> create(
const ISchemaItemPtr ElementSchemaItem = CAlwaysTrueSchemaItem::create(),
- const TSchemaItemParameter<size_t>& MinSize = TSchemaItemParameter<size_t>(),
- const TSchemaItemParameter<size_t>& MaxSize = TSchemaItemParameter<size_t>());
+ const TSchemaItemParameter<size_t>& MinSize =
+ TSchemaItemParameter<size_t>(),
+ const TSchemaItemParameter<size_t>& MaxSize =
+ TSchemaItemParameter<size_t>());
/**
* @brief Validate smart object.
@@ -77,7 +79,8 @@ class CArraySchemaItem : public ISchemaItem {
* @param RemoveFakeParameters contains true if need to remove fake parameters
* from smart object otherwise contains false.
**/
- void applySchema(SmartObject& Object, const bool RemoveFakeParameters) OVERRIDE;
+ void applySchema(SmartObject& Object,
+ const bool RemoveFakeParameters) OVERRIDE;
/**
* @brief Unapply schema.
diff --git a/src/components/smart_objects/include/smart_objects/bool_schema_item.h b/src/components/smart_objects/include/smart_objects/bool_schema_item.h
index bb0dbd6653..eca5a0e063 100644
--- a/src/components/smart_objects/include/smart_objects/bool_schema_item.h
+++ b/src/components/smart_objects/include/smart_objects/bool_schema_item.h
@@ -50,13 +50,14 @@ class CBoolSchemaItem : public CDefaultSchemaItem<bool> {
* @return Shared pointer to a new schema item.
**/
static utils::SharedPtr<CBoolSchemaItem> create(
- const TSchemaItemParameter<bool>& DefaultValue =
- TSchemaItemParameter<bool>());
+ const TSchemaItemParameter<bool>& DefaultValue =
+ TSchemaItemParameter<bool>());
private:
explicit CBoolSchemaItem(const TSchemaItemParameter<bool>& DefaultValue);
SmartType getSmartType() const OVERRIDE;
bool getDefaultValue() const OVERRIDE;
+
private:
DISALLOW_COPY_AND_ASSIGN(CBoolSchemaItem);
};
diff --git a/src/components/smart_objects/include/smart_objects/default_shema_item.h b/src/components/smart_objects/include/smart_objects/default_shema_item.h
index 5065e27684..857354a4e6 100644
--- a/src/components/smart_objects/include/smart_objects/default_shema_item.h
+++ b/src/components/smart_objects/include/smart_objects/default_shema_item.h
@@ -45,7 +45,7 @@ namespace NsSmartObjects {
/**
* @brief Default schema item.
**/
-template<typename Type>
+template <typename Type>
class CDefaultSchemaItem : public ISchemaItem {
public:
typedef TSchemaItemParameter<Type> ParameterType;
@@ -93,17 +93,17 @@ class CDefaultSchemaItem : public ISchemaItem {
DISALLOW_COPY_AND_ASSIGN(CDefaultSchemaItem<Type>);
};
-template<typename Type>
+template <typename Type>
CDefaultSchemaItem<Type>::CDefaultSchemaItem(const ParameterType& DefaultValue)
- : mDefaultValue(DefaultValue) {
-}
+ : mDefaultValue(DefaultValue) {}
-template<typename Type>
+template <typename Type>
Errors::eType CDefaultSchemaItem<Type>::validate(const SmartObject& Object) {
- return (getSmartType() == Object.getType()) ? Errors::OK : Errors::INVALID_VALUE;
+ return (getSmartType() == Object.getType()) ? Errors::OK
+ : Errors::INVALID_VALUE;
}
-template<typename Type>
+template <typename Type>
bool CDefaultSchemaItem<Type>::setDefaultValue(SmartObject& Object) {
Type value;
if (mDefaultValue.getValue(value)) {
@@ -113,9 +113,9 @@ bool CDefaultSchemaItem<Type>::setDefaultValue(SmartObject& Object) {
return false;
}
-template<typename Type>
+template <typename Type>
void CDefaultSchemaItem<Type>::BuildObjectBySchema(
- const SmartObject& pattern_object, SmartObject& result_object) {
+ const SmartObject& pattern_object, SmartObject& result_object) {
if (getSmartType() == pattern_object.getType()) {
result_object = pattern_object;
} else {
diff --git a/src/components/smart_objects/include/smart_objects/enum_schema_item.h b/src/components/smart_objects/include/smart_objects/enum_schema_item.h
index c303061152..a0d6d94017 100644
--- a/src/components/smart_objects/include/smart_objects/enum_schema_item.h
+++ b/src/components/smart_objects/include/smart_objects/enum_schema_item.h
@@ -42,16 +42,16 @@
#include "utils/shared_ptr.h"
#include "smart_objects/default_shema_item.h"
-
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
-template <typename EnumType> class EnumConversionHelper;
+template <typename EnumType>
+class EnumConversionHelper;
/**
* @brief Enumeration schema item.
* @tparam EnumType Enumeration type.
**/
-template<typename EnumType>
+template <typename EnumType>
class TEnumSchemaItem : public CDefaultSchemaItem<EnumType> {
public:
/**
@@ -61,9 +61,9 @@ class TEnumSchemaItem : public CDefaultSchemaItem<EnumType> {
* @return Shared pointer to a new schema item.
**/
static utils::SharedPtr<TEnumSchemaItem> create(
- const std::set<EnumType>& AllowedElements,
- const TSchemaItemParameter<EnumType>& DefaultValue =
- TSchemaItemParameter<EnumType>());
+ const std::set<EnumType>& AllowedElements,
+ const TSchemaItemParameter<EnumType>& DefaultValue =
+ TSchemaItemParameter<EnumType>());
/**
* @brief Validate smart object.
* @param Object Object to validate.
@@ -79,7 +79,8 @@ class TEnumSchemaItem : public CDefaultSchemaItem<EnumType> {
* @param RemoveFakeParameters contains true if need to remove fake parameters
* from smart object otherwise contains false.
**/
- void applySchema(SmartObject& Object, const bool RemoveFakeParameters) OVERRIDE;
+ void applySchema(SmartObject& Object,
+ const bool RemoveFakeParameters) OVERRIDE;
/**
* @brief Unapply schema.
* @param Object Object to unapply schema.
@@ -129,7 +130,8 @@ class EnumConversionHelper {
}
static bool CStringToEnum(const char* str, EnumType* value) {
- typename CStringToEnumMap::const_iterator it = cstring_to_enum_map().find(str);
+ typename CStringToEnumMap::const_iterator it =
+ cstring_to_enum_map().find(str);
if (it == cstring_to_enum_map().end()) {
return false;
}
@@ -140,7 +142,8 @@ class EnumConversionHelper {
}
static bool EnumToCString(EnumType value, const char** str) {
- typename EnumToCStringMap::const_iterator it = enum_to_cstring_map().find(value);
+ typename EnumToCStringMap::const_iterator it =
+ enum_to_cstring_map().find(value);
if (it == enum_to_cstring_map().end()) {
return false;
}
@@ -172,7 +175,7 @@ class EnumConversionHelper {
static const CStringToEnumMap cstring_to_enum_map_;
struct Size {
- enum {value = sizeof(cstring_values_) / sizeof(cstring_values_[0])};
+ enum { value = sizeof(cstring_values_) / sizeof(cstring_values_[0]) };
};
static EnumToCStringMap InitEnumToCStringMap() {
@@ -195,28 +198,28 @@ class EnumConversionHelper {
DISALLOW_COPY_AND_ASSIGN(EnumConversionHelper<EnumType>);
};
-
-template<typename EnumType>
+template <typename EnumType>
utils::SharedPtr<TEnumSchemaItem<EnumType> > TEnumSchemaItem<EnumType>::create(
- const std::set<EnumType>& AllowedElements,
- const TSchemaItemParameter<EnumType>& DefaultValue) {
+ const std::set<EnumType>& AllowedElements,
+ const TSchemaItemParameter<EnumType>& DefaultValue) {
return new TEnumSchemaItem<EnumType>(AllowedElements, DefaultValue);
}
-template<typename EnumType>
+template <typename EnumType>
Errors::eType TEnumSchemaItem<EnumType>::validate(const SmartObject& Object) {
if (SmartType_Integer != Object.getType()) {
return Errors::INVALID_VALUE;
}
- if (mAllowedElements.find(static_cast<EnumType>(Object.asInt()))
- == mAllowedElements.end()) {
+ if (mAllowedElements.find(static_cast<EnumType>(Object.asInt())) ==
+ mAllowedElements.end()) {
return Errors::OUT_OF_RANGE;
}
return Errors::OK;
}
-template<typename EnumType>
-void TEnumSchemaItem<EnumType>::applySchema(SmartObject& Object, const bool RemoveFakeParameters) {
+template <typename EnumType>
+void TEnumSchemaItem<EnumType>::applySchema(SmartObject& Object,
+ const bool RemoveFakeParameters) {
if (SmartType_String == Object.getType()) {
EnumType enum_val = static_cast<EnumType>(-1);
if (ConversionHelper::StringToEnum(Object.asString(), &enum_val)) {
@@ -225,32 +228,32 @@ void TEnumSchemaItem<EnumType>::applySchema(SmartObject& Object, const bool Remo
}
}
-template<typename EnumType>
+template <typename EnumType>
void TEnumSchemaItem<EnumType>::unapplySchema(SmartObject& Object) {
if (SmartType_Integer == Object.getType()) {
const char* str;
- if (ConversionHelper::EnumToCString(static_cast<EnumType>(Object.asInt()), &str)) {
+ if (ConversionHelper::EnumToCString(static_cast<EnumType>(Object.asInt()),
+ &str)) {
Object = str;
}
}
}
-template<typename EnumType>
+template <typename EnumType>
SmartType TEnumSchemaItem<EnumType>::getSmartType() const {
return SmartType_Integer;
}
-template<typename EnumType>
+template <typename EnumType>
EnumType TEnumSchemaItem<EnumType>::getDefaultValue() const {
return EnumType::INVALID_ENUM;
}
-template<typename EnumType>
+template <typename EnumType>
TEnumSchemaItem<EnumType>::TEnumSchemaItem(
- const std::set<EnumType>& AllowedElements,
- const TSchemaItemParameter<EnumType>& DefaultValue)
- : CDefaultSchemaItem<EnumType>(DefaultValue),
- mAllowedElements(AllowedElements) {
-}
+ const std::set<EnumType>& AllowedElements,
+ const TSchemaItemParameter<EnumType>& DefaultValue)
+ : CDefaultSchemaItem<EnumType>(DefaultValue)
+ , mAllowedElements(AllowedElements) {}
} // namespace NsSmartObjects
} // namespace NsSmartDeviceLink
diff --git a/src/components/smart_objects/include/smart_objects/errors.h b/src/components/smart_objects/include/smart_objects/errors.h
index fe8a04b692..5d22d2386e 100644
--- a/src/components/smart_objects/include/smart_objects/errors.h
+++ b/src/components/smart_objects/include/smart_objects/errors.h
@@ -35,7 +35,8 @@ namespace NsSmartDeviceLink {
namespace NsSmartObjects {
namespace Errors {
/**
- * @brief Enumeration that provides information about SmartObject validation errors
+ * @brief Enumeration that provides information about SmartObject validation
+ *errors
**/
enum eType {
/**
diff --git a/src/components/smart_objects/include/smart_objects/number_schema_item.h b/src/components/smart_objects/include/smart_objects/number_schema_item.h
index fb4d287fe4..01d6c08daa 100644
--- a/src/components/smart_objects/include/smart_objects/number_schema_item.h
+++ b/src/components/smart_objects/include/smart_objects/number_schema_item.h
@@ -34,10 +34,11 @@
#define SRC_COMPONENTS_SMART_OBJECTS_INCLUDE_SMART_OBJECTS_NUMBER_SCHEMA_ITEM_H_
#include <typeinfo>
-
+#include <limits>
#include "utils/shared_ptr.h"
#include "smart_objects/default_shema_item.h"
#include "smart_objects/schema_item_parameter.h"
+#include "utils/convert_utils.h"
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
@@ -45,7 +46,7 @@ namespace NsSmartObjects {
* @brief Number schema item.
* @tparam NumberType Number type.
**/
-template<typename NumberType>
+template <typename NumberType>
class TNumberSchemaItem : public CDefaultSchemaItem<NumberType> {
public:
/**
@@ -56,10 +57,12 @@ class TNumberSchemaItem : public CDefaultSchemaItem<NumberType> {
* @return Shared pointer to a new schema item.
**/
static utils::SharedPtr<TNumberSchemaItem> create(
- const TSchemaItemParameter<NumberType>& MinValue = TSchemaItemParameter <NumberType > (),
- const TSchemaItemParameter<NumberType>& MaxValue = TSchemaItemParameter <NumberType > (),
- const TSchemaItemParameter<NumberType>& DefaultValue =
- TSchemaItemParameter<NumberType>());
+ const TSchemaItemParameter<NumberType>& MinValue =
+ TSchemaItemParameter<NumberType>(),
+ const TSchemaItemParameter<NumberType>& MaxValue =
+ TSchemaItemParameter<NumberType>(),
+ const TSchemaItemParameter<NumberType>& DefaultValue =
+ TSchemaItemParameter<NumberType>());
/**
* @brief Validate smart object.
@@ -98,45 +101,47 @@ class TNumberSchemaItem : public CDefaultSchemaItem<NumberType> {
DISALLOW_COPY_AND_ASSIGN(TNumberSchemaItem);
};
-template<typename NumberType>
-utils::SharedPtr<TNumberSchemaItem<NumberType> >
-TNumberSchemaItem<NumberType>::create(
- const TSchemaItemParameter<NumberType>& MinValue,
- const TSchemaItemParameter<NumberType>& MaxValue,
- const TSchemaItemParameter<NumberType>& DefaultValue) {
+template <typename NumberType>
+utils::SharedPtr<TNumberSchemaItem<NumberType> > TNumberSchemaItem<
+ NumberType>::create(const TSchemaItemParameter<NumberType>& MinValue,
+ const TSchemaItemParameter<NumberType>& MaxValue,
+ const TSchemaItemParameter<NumberType>& DefaultValue) {
return new TNumberSchemaItem<NumberType>(MinValue, MaxValue, DefaultValue);
}
-template<typename NumberType>
+template <typename NumberType>
bool TNumberSchemaItem<NumberType>::isValidNumberType(SmartType type) {
NumberType value(0);
- if ((SmartType_Double == type) &&
- (typeid(double) == typeid(value))) {
- return true;
+ if ((SmartType_Double == type) && (typeid(double) == typeid(value))) {
+ return true;
} else if ((SmartType_Integer == type) &&
- (typeid(int32_t) == typeid(value) ||
- typeid(uint32_t) == typeid(value) ||
- typeid(int64_t) == typeid(value))) {
- return true;
+ (typeid(int32_t) == typeid(value) ||
+ typeid(uint32_t) == typeid(value) ||
+ typeid(int64_t) == typeid(value) ||
+ typeid(double) == typeid(value))) {
+ return true;
} else {
- return false;
+ return false;
}
}
-template<typename NumberType>
-Errors::eType TNumberSchemaItem<NumberType>::validate(const SmartObject& Object) {
+template <typename NumberType>
+Errors::eType TNumberSchemaItem<NumberType>::validate(
+ const SmartObject& Object) {
if (!isValidNumberType(Object.getType())) {
return Errors::INVALID_VALUE;
}
NumberType value(0);
if (typeid(int32_t) == typeid(value)) {
- value = Object.asInt();
+ value = utils::SafeStaticCast<int64_t, int32_t>(Object.asInt());
} else if (typeid(uint32_t) == typeid(value)) {
- value = Object.asUInt();
+ value = utils::SafeStaticCast<uint64_t, uint32_t>(Object.asUInt());
} else if (typeid(double) == typeid(value)) {
value = Object.asDouble();
} else if (typeid(int64_t) == typeid(value)) {
- value = Object.asInt64();
+ value = Object.asInt();
+ } else if (typeid(uint64_t) == typeid(value)) {
+ value = Object.asUInt();
} else {
NOTREACHED();
}
@@ -152,17 +157,16 @@ Errors::eType TNumberSchemaItem<NumberType>::validate(const SmartObject& Object)
return Errors::OK;
}
-template<typename NumberType>
+template <typename NumberType>
TNumberSchemaItem<NumberType>::TNumberSchemaItem(
- const TSchemaItemParameter<NumberType>& MinValue,
- const TSchemaItemParameter<NumberType>& MaxValue,
- const TSchemaItemParameter<NumberType>& DefaultValue)
- : CDefaultSchemaItem<NumberType>(DefaultValue),
- mMinValue(MinValue),
- mMaxValue(MaxValue) {
-}
-
-template<typename NumberType>
+ const TSchemaItemParameter<NumberType>& MinValue,
+ const TSchemaItemParameter<NumberType>& MaxValue,
+ const TSchemaItemParameter<NumberType>& DefaultValue)
+ : CDefaultSchemaItem<NumberType>(DefaultValue)
+ , mMinValue(MinValue)
+ , mMaxValue(MaxValue) {}
+
+template <typename NumberType>
NumberType TNumberSchemaItem<NumberType>::getDefaultValue() const {
return NumberType(0);
}
@@ -171,21 +175,21 @@ NumberType TNumberSchemaItem<NumberType>::getDefaultValue() const {
* @brief Specialization of getSmartType for number types.
* @return SmartType.
**/
-template<typename NumberType>
+template <typename NumberType>
SmartType TNumberSchemaItem<NumberType>::getSmartType() const {
DCHECK(!"Wrong type of template class");
return SmartType_Invalid;
}
-template<>
+template <>
SmartType TNumberSchemaItem<int32_t>::getSmartType() const;
-template<>
+template <>
SmartType TNumberSchemaItem<uint32_t>::getSmartType() const;
-template<>
-SmartType TNumberSchemaItem<uint32_t>::getSmartType() const;
+template <>
+SmartType TNumberSchemaItem<int64_t>::getSmartType() const;
-template<>
+template <>
SmartType TNumberSchemaItem<double>::getSmartType() const;
} // namespace NsSmartObjects
diff --git a/src/components/smart_objects/include/smart_objects/object_schema_item.h b/src/components/smart_objects/include/smart_objects/object_schema_item.h
index 6e16e6a2a2..549166e723 100644
--- a/src/components/smart_objects/include/smart_objects/object_schema_item.h
+++ b/src/components/smart_objects/include/smart_objects/object_schema_item.h
@@ -63,8 +63,7 @@ class CObjectSchemaItem : public ISchemaItem {
* @param IsMandatory true if member is mandatory, false
* otherwise. Defaults to true.
**/
- SMember(const ISchemaItemPtr SchemaItem,
- const bool IsMandatory = true);
+ SMember(const ISchemaItemPtr SchemaItem, const bool IsMandatory = true);
/**
* @brief Member schema item.
**/
@@ -96,7 +95,8 @@ class CObjectSchemaItem : public ISchemaItem {
* @param RemoveFakeParameters contains true if need to remove fake parameters
* from smart object otherwise contains false.
**/
- void applySchema(SmartObject& Object, const bool RemoveFakeParameters) OVERRIDE;
+ void applySchema(SmartObject& Object,
+ const bool RemoveFakeParameters) OVERRIDE;
/**
* @brief Unapply schema.
* @param Object Object to unapply schema.
@@ -131,7 +131,8 @@ class CObjectSchemaItem : public ISchemaItem {
void RemoveFakeParams(SmartObject& Object);
/**
- * @brief Map of member name to SMember structure describing the object member.
+ * @brief Map of member name to SMember structure describing the object
+ *member.
**/
const Members mMembers;
DISALLOW_COPY_AND_ASSIGN(CObjectSchemaItem);
diff --git a/src/components/smart_objects/include/smart_objects/schema_item.h b/src/components/smart_objects/include/smart_objects/schema_item.h
index 92b1495909..08610f244e 100644
--- a/src/components/smart_objects/include/smart_objects/schema_item.h
+++ b/src/components/smart_objects/include/smart_objects/schema_item.h
@@ -80,8 +80,9 @@ class ISchemaItem {
* @param RemoveFakeParameters contains true if need to remove fake parameters
* from smart object otherwise contains false.
**/
- virtual void applySchema(NsSmartDeviceLink::NsSmartObjects::SmartObject& Object,
- const bool RemoveFakeParameters);
+ virtual void applySchema(
+ NsSmartDeviceLink::NsSmartObjects::SmartObject& Object,
+ const bool RemoveFakeParameters);
/**
* @brief Unapply schema.
@@ -98,8 +99,8 @@ class ISchemaItem {
* @param pattern_object pattern object
* @param result_object object to build
*/
- virtual void BuildObjectBySchema(
- const SmartObject& pattern_object, SmartObject& result_object);
+ virtual void BuildObjectBySchema(const SmartObject& pattern_object,
+ SmartObject& result_object);
/**
* @brief Get value param, depends of children
@@ -108,7 +109,7 @@ class ISchemaItem {
*/
virtual size_t GetMemberSize();
- virtual ~ISchemaItem() { }
+ virtual ~ISchemaItem() {}
};
typedef utils::SharedPtr<ISchemaItem> ISchemaItemPtr;
} // namespace NsSmartObjects
diff --git a/src/components/smart_objects/include/smart_objects/schema_item_parameter.h b/src/components/smart_objects/include/smart_objects/schema_item_parameter.h
index 7ae359b740..49fdb9541b 100644
--- a/src/components/smart_objects/include/smart_objects/schema_item_parameter.h
+++ b/src/components/smart_objects/include/smart_objects/schema_item_parameter.h
@@ -42,7 +42,7 @@ namespace NsSmartObjects {
* etc. which may be unspecified.
* @tparam ParameterType Type of a parameter.
*/
-template<typename ParameterType>
+template <typename ParameterType>
class TSchemaItemParameter FINAL {
public:
/**
@@ -79,20 +79,16 @@ class TSchemaItemParameter FINAL {
const ParameterType mValue;
};
-template<typename ParameterType>
+template <typename ParameterType>
TSchemaItemParameter<ParameterType>::TSchemaItemParameter()
- : mIsSpecified(false),
- mValue() {
-}
+ : mIsSpecified(false), mValue() {}
-template<typename ParameterType>
+template <typename ParameterType>
TSchemaItemParameter<ParameterType>::TSchemaItemParameter(
const ParameterType& ParameterValue)
- : mIsSpecified(true),
- mValue(ParameterValue) {
-}
+ : mIsSpecified(true), mValue(ParameterValue) {}
-template<typename ParameterType>
+template <typename ParameterType>
bool TSchemaItemParameter<ParameterType>::getValue(ParameterType& Value) const {
if (mIsSpecified) {
Value = mValue;
diff --git a/src/components/smart_objects/include/smart_objects/smart_object.h b/src/components/smart_objects/include/smart_objects/smart_object.h
index bd70b7ea11..688550b040 100644
--- a/src/components/smart_objects/include/smart_objects/smart_object.h
+++ b/src/components/smart_objects/include/smart_objects/smart_object.h
@@ -39,9 +39,13 @@
#include <map>
#include "smart_objects/smart_schema.h"
+#include "utils/custom_string.h"
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
+
+namespace custom_str = utils::custom_string;
+
class SmartObject;
/**
@@ -89,12 +93,19 @@ enum SmartType {
SmartType_Array = 7,
/**
- * @brief Binary data value. Gives possibility for object to store binary data.
+ * @brief Binary data value. Gives possibility for object to store binary
+ *data.
**/
SmartType_Binary = 8,
/**
- * @brief Invalid value. Represents invalid object that cannot change his type.
+ * @brief Unsigned Integer value.
+ **/
+ SmartType_UInteger = 9,
+
+ /**
+ * @brief Invalid value. Represents invalid object that cannot change his
+ *type.
**/
SmartType_Invalid = -1
};
@@ -124,9 +135,12 @@ typedef std::vector<SmartObjectSPtr> SmartObjectList;
/**
* @brief Main SmartObject class
*
- * This class act as Variant type from other languages and can be used as primitive type
- * like bool, int32_t, char, double, string and as complex type like array and map.
+ * This class act as Variant type from other languages and can be used as
+ *primitive type
+ * like bool, int32_t, char, double, string and as complex type like array and
+ *map.
**/
+
class SmartObject FINAL {
public:
/**
@@ -149,7 +163,7 @@ class SmartObject FINAL {
*
* @param pointer
**/
- template<typename UnknownType>
+ template <typename UnknownType>
SmartObject(const UnknownType&);
/**
@@ -192,14 +206,14 @@ class SmartObject FINAL {
*
* @param InitialValue Initial object value
**/
- explicit SmartObject(int32_t InitialValue);
+ explicit SmartObject(const int32_t InitialValue);
/**
- * @brief Returns current object converted to int32_t
+ * @brief Returns current object converted to int64_t
*
- * @return int32_t
+ * @return int64_t
**/
- int32_t asInt() const;
+ int64_t asInt() const;
/**
* @brief Assignment operator for type: int32_t
@@ -207,7 +221,7 @@ class SmartObject FINAL {
* @param NewValue New object value
* @return SmartObject&
**/
- SmartObject& operator=(int32_t NewValue);
+ SmartObject& operator=(const int32_t NewValue);
/**
* @brief Comparison operator for comparing object with integer value
@@ -215,7 +229,7 @@ class SmartObject FINAL {
* @param Value Value to compare object with
* @return bool
**/
- bool operator==(int32_t Value) const;
+ bool operator==(const int32_t Value) const;
// Support of type: uint32_t
/**
@@ -223,14 +237,14 @@ class SmartObject FINAL {
*
* @param InitialValue Initial object value
**/
- explicit SmartObject(uint32_t InitialValue);
+ explicit SmartObject(const uint32_t InitialValue);
/**
- * @brief Returns current object converted to uint32_t int32_t
+ * @brief Returns current object converted to uint64_t
*
- * @return double
+ * @return uint64_t
**/
- uint32_t asUInt() const;
+ uint64_t asUInt() const;
/**
* @brief Assignment operator for type: int32_t
@@ -238,7 +252,7 @@ class SmartObject FINAL {
* @param NewValue New object value
* @return SmartObject&
**/
- SmartObject& operator=(uint32_t NewValue);
+ SmartObject& operator=(const uint32_t NewValue);
/**
* @brief Comparison operator for comparing object with uint32_t value
@@ -246,7 +260,7 @@ class SmartObject FINAL {
* @param Value Value to compare object with
* @return bool
**/
- bool operator==(uint32_t Value) const;
+ bool operator==(const uint32_t Value) const;
/**
* @name Support of type: int64_t
@@ -257,7 +271,7 @@ class SmartObject FINAL {
*
* @param InitialValue Initial object value
**/
- explicit SmartObject(int64_t InitialValue);
+ explicit SmartObject(const int64_t InitialValue);
/**
* @brief Returns current object converted to int64_t
@@ -272,7 +286,7 @@ class SmartObject FINAL {
* @param NewValue New object value
* @return SmartObject&
**/
- SmartObject& operator=(int64_t NewValue);
+ SmartObject& operator=(const int64_t NewValue);
/**
* @brief Comparison operator for comparing object with integer value
@@ -280,7 +294,20 @@ class SmartObject FINAL {
* @param Value Value to compare object with
* @return bool
**/
- bool operator==(int64_t Value) const;
+ bool operator==(const int64_t Value) const;
+
+ /**
+ * @name Support of type: uint64_t
+ * @{
+ **/
+
+ /**
+ * @brief Assignment operator for type: uint64_t
+ *
+ * @param NewValue New object value
+ * @return SmartObject&
+ **/
+ SmartObject& operator=(const uint64_t NewValue);
/** @} */
@@ -401,6 +428,13 @@ class SmartObject FINAL {
explicit SmartObject(const std::string& InitialValue);
/**
+ * @brief Constructor for creating object of type: CustomString
+ *
+ * @param InitialValue Initial object value
+ **/
+ explicit SmartObject(const custom_str::CustomString& InitialValue);
+
+ /**
* @brief Constructor for creating object of type: string
*
* @param InitialValue Initial object value
@@ -408,6 +442,13 @@ class SmartObject FINAL {
explicit SmartObject(const char* InitialValue);
/**
+ * @brief Returns current object converted to CustomString
+ *
+ * @return custom_str::CustomString
+ **/
+ custom_str::CustomString asCustomString() const;
+
+ /**
* @brief Returns current object converted to string
*
* @return std::string
@@ -423,6 +464,14 @@ class SmartObject FINAL {
const char* asCharArray() const;
/**
+ * @brief Assignment operator for type: CustomString
+ *
+ * @param NewValue New object value
+ * @return SmartObject&
+ **/
+ SmartObject& operator=(const custom_str::CustomString& NewValue);
+
+ /**
* @brief Assignment operator for type: string
*
* @param NewValue New object value
@@ -673,7 +722,7 @@ class SmartObject FINAL {
* @param Other value to be compared with
* @return bool Result of nequation
**/
- template<typename Type>
+ template <typename Type>
bool operator!=(const Type& Other) const {
return !(*this == Other);
}
@@ -697,7 +746,8 @@ class SmartObject FINAL {
/**
* @brief Converts object to int32_t type
*
- * @return int32_t Converted value or invalid_int_value if conversion not possible
+ * @return int32_t Converted value or invalid_int_value if conversion not
+ *possible
**/
inline int64_t convert_int() const;
/** @} */
@@ -719,7 +769,8 @@ class SmartObject FINAL {
/**
* @brief Converts object to char type
*
- * @return int32_t Converted value or invalid_char_value if conversion not possible
+ * @return int32_t Converted value or invalid_char_value if conversion not
+ *possible
**/
inline char convert_char() const;
/** @} */
@@ -741,7 +792,8 @@ class SmartObject FINAL {
/**
* @brief Converts object to double type
*
- * @return int32_t Converted value or invalid_double_value if conversion not possible
+ * @return int32_t Converted value or invalid_double_value if conversion not
+ *possible
**/
inline double convert_double() const;
/** @} */
@@ -763,16 +815,13 @@ class SmartObject FINAL {
/**
* @brief Converts object to bool type
*
- * @return int32_t Converted value or invalid_bool_value if conversion not possible
+ * @return int32_t Converted value or invalid_bool_value if conversion not
+ *possible
**/
inline bool convert_bool() const;
/** @} */
/**
- * @name Support of type: string (internal)
- * @{
- */
- /**
* @brief Sets new string value to the object.
*
* This method changes also internal object type
@@ -780,10 +829,10 @@ class SmartObject FINAL {
* @param NewValue New object value
* @return void
**/
- inline void set_value_string(const std::string& NewValue);
+ inline void set_value_string(const custom_str::CustomString& NewValue);
/**
- * @brief Sets new string value to the object.
+ * @brief Sets new CustomString value to the object.
*
* This method changes also internal object type
*
@@ -795,12 +844,21 @@ class SmartObject FINAL {
/**
* @brief Converts object to string type
*
- * @return int32_t Converted value or invalid_string_value if conversion not possible
+ * @return int32_t Converted value or invalid_string_value if conversion not
+ *possible
**/
inline std::string convert_string() const;
/** @} */
/**
+ * @brief Converts object to CustomString type
+ *
+ * @return CustomString Converted value or
+ * invalid_string_value if conversion not possible
+ **/
+ inline custom_str::CustomString convert_custom_string() const;
+
+ /**
* @name Support of type: binary (internal)
* @{
*/
@@ -817,7 +875,8 @@ class SmartObject FINAL {
/**
* @brief Converts object to binary type
*
- * @return int32_t Converted value or invalid_binary_value if conversion not possible
+ * @return int32_t Converted value or invalid_binary_value if conversion not
+ *possible
**/
inline SmartBinary convert_binary() const;
@@ -843,7 +902,7 @@ class SmartObject FINAL {
* @param Value Pointer to string to convert
* @return double
**/
- static double convert_string_to_double(const std::string* Value);
+ static double convert_string_to_double(const custom_str::CustomString* Value);
/**
* @brief Converts string to int64_t
@@ -851,7 +910,8 @@ class SmartObject FINAL {
* @param Value Pointer to string to convert
* @return int64_t int64_t
**/
- static uint64_t convert_string_to_integer(const std::string* Value);
+ static uint64_t convert_string_to_integer(
+ const custom_str::CustomString* Value);
/**
* @brief Converts double value to string
@@ -901,7 +961,7 @@ class SmartObject FINAL {
bool bool_value;
char char_value;
int64_t int_value;
- std::string* str_value;
+ custom_str::CustomString* str_value;
SmartArray* array_value;
SmartMap* map_value;
SmartBinary* binary_value;
diff --git a/src/components/smart_objects/include/smart_objects/string_schema_item.h b/src/components/smart_objects/include/smart_objects/string_schema_item.h
index dbcfcbf9f9..7fad8491a5 100644
--- a/src/components/smart_objects/include/smart_objects/string_schema_item.h
+++ b/src/components/smart_objects/include/smart_objects/string_schema_item.h
@@ -55,10 +55,12 @@ class CStringSchemaItem : public CDefaultSchemaItem<std::string> {
* @return Shared pointer to a new schema item.
**/
static utils::SharedPtr<CStringSchemaItem> create(
- const TSchemaItemParameter<size_t>& MinLength = TSchemaItemParameter<size_t>(),
- const TSchemaItemParameter<size_t>& MaxLength = TSchemaItemParameter<size_t>(),
- const TSchemaItemParameter<std::string>& DefaultValue =
- TSchemaItemParameter<std::string>());
+ const TSchemaItemParameter<size_t>& MinLength =
+ TSchemaItemParameter<size_t>(),
+ const TSchemaItemParameter<size_t>& MaxLength =
+ TSchemaItemParameter<size_t>(),
+ const TSchemaItemParameter<std::string>& DefaultValue =
+ TSchemaItemParameter<std::string>());
/**
* @brief Validate smart object.
* @param Object Object to validate.
diff --git a/src/components/smart_objects/src/always_false_schema_item.cc b/src/components/smart_objects/src/always_false_schema_item.cc
index d4313fb4c0..59e50e10c2 100644
--- a/src/components/smart_objects/src/always_false_schema_item.cc
+++ b/src/components/smart_objects/src/always_false_schema_item.cc
@@ -35,8 +35,7 @@
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
-CAlwaysFalseSchemaItem::CAlwaysFalseSchemaItem() {
-}
+CAlwaysFalseSchemaItem::CAlwaysFalseSchemaItem() {}
utils::SharedPtr<CAlwaysFalseSchemaItem> CAlwaysFalseSchemaItem::create() {
return new CAlwaysFalseSchemaItem();
diff --git a/src/components/smart_objects/src/always_true_schema_item.cc b/src/components/smart_objects/src/always_true_schema_item.cc
index 8f77919443..a474b0e157 100644
--- a/src/components/smart_objects/src/always_true_schema_item.cc
+++ b/src/components/smart_objects/src/always_true_schema_item.cc
@@ -33,8 +33,7 @@
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
-CAlwaysTrueSchemaItem::CAlwaysTrueSchemaItem() {
-}
+CAlwaysTrueSchemaItem::CAlwaysTrueSchemaItem() {}
utils::SharedPtr<CAlwaysTrueSchemaItem> CAlwaysTrueSchemaItem::create() {
return new CAlwaysTrueSchemaItem();
diff --git a/src/components/smart_objects/src/array_schema_item.cc b/src/components/smart_objects/src/array_schema_item.cc
index d85454bd1a..105cacb25c 100644
--- a/src/components/smart_objects/src/array_schema_item.cc
+++ b/src/components/smart_objects/src/array_schema_item.cc
@@ -57,7 +57,7 @@ Errors::eType CArraySchemaItem::validate(const SmartObject& Object) {
for (size_t i = 0u; i < array_len; ++i) {
const Errors::eType result =
- mElementSchemaItem->validate(Object.getElement(i));
+ mElementSchemaItem->validate(Object.getElement(i));
if (Errors::OK != result) {
return result;
}
@@ -82,8 +82,8 @@ void CArraySchemaItem::unapplySchema(SmartObject& Object) {
}
}
-void CArraySchemaItem::BuildObjectBySchema(
- const SmartObject& pattern_object, SmartObject& result_object) {
+void CArraySchemaItem::BuildObjectBySchema(const SmartObject& pattern_object,
+ SmartObject& result_object) {
if (SmartType_Array == pattern_object.getType()) {
const size_t array_len = pattern_object.length();
if (array_len > 0) {
@@ -101,10 +101,9 @@ void CArraySchemaItem::BuildObjectBySchema(
CArraySchemaItem::CArraySchemaItem(const ISchemaItemPtr ElementSchemaItem,
const TSchemaItemParameter<size_t>& MinSize,
const TSchemaItemParameter<size_t>& MaxSize)
- : mElementSchemaItem(ElementSchemaItem),
- mMinSize(MinSize),
- mMaxSize(MaxSize) {
-}
+ : mElementSchemaItem(ElementSchemaItem)
+ , mMinSize(MinSize)
+ , mMaxSize(MaxSize) {}
} // namespace NsSmartObjects
} // namespace NsSmartDeviceLink
diff --git a/src/components/smart_objects/src/bool_schema_item.cc b/src/components/smart_objects/src/bool_schema_item.cc
index 845cf9f5cc..c1da95528a 100644
--- a/src/components/smart_objects/src/bool_schema_item.cc
+++ b/src/components/smart_objects/src/bool_schema_item.cc
@@ -36,14 +36,12 @@ namespace NsSmartDeviceLink {
namespace NsSmartObjects {
utils::SharedPtr<CBoolSchemaItem> CBoolSchemaItem::create(
- const TSchemaItemParameter<bool> & DefaultValue) {
+ const TSchemaItemParameter<bool>& DefaultValue) {
return new CBoolSchemaItem(DefaultValue);
}
-CBoolSchemaItem::CBoolSchemaItem(
- const TSchemaItemParameter<bool>& DefaultValue)
- : CDefaultSchemaItem<bool>(DefaultValue) {
-}
+CBoolSchemaItem::CBoolSchemaItem(const TSchemaItemParameter<bool>& DefaultValue)
+ : CDefaultSchemaItem<bool>(DefaultValue) {}
SmartType CBoolSchemaItem::getSmartType() const {
return SmartType_Boolean;
diff --git a/src/components/smart_objects/src/number_schema_item.cc b/src/components/smart_objects/src/number_schema_item.cc
index e3a85caadc..78be9fe85d 100644
--- a/src/components/smart_objects/src/number_schema_item.cc
+++ b/src/components/smart_objects/src/number_schema_item.cc
@@ -34,19 +34,23 @@
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
-template<> SmartType TNumberSchemaItem<int32_t>::getSmartType() const {
+template <>
+SmartType TNumberSchemaItem<int32_t>::getSmartType() const {
return SmartType_Integer;
}
-template<> SmartType TNumberSchemaItem<uint32_t>::getSmartType() const {
+template <>
+SmartType TNumberSchemaItem<uint32_t>::getSmartType() const {
return SmartType_Integer;
}
-template<> SmartType TNumberSchemaItem<int64_t>::getSmartType() const {
+template <>
+SmartType TNumberSchemaItem<int64_t>::getSmartType() const {
return SmartType_Integer;
}
-template<> SmartType TNumberSchemaItem<double>::getSmartType() const {
+template <>
+SmartType TNumberSchemaItem<double>::getSmartType() const {
return SmartType_Double;
}
diff --git a/src/components/smart_objects/src/object_schema_item.cc b/src/components/smart_objects/src/object_schema_item.cc
index f2cc3eac41..f0c17faaea 100644
--- a/src/components/smart_objects/src/object_schema_item.cc
+++ b/src/components/smart_objects/src/object_schema_item.cc
@@ -45,17 +45,14 @@ namespace NsSmartDeviceLink {
namespace NsSmartObjects {
CObjectSchemaItem::SMember::SMember()
- : mSchemaItem(CAlwaysFalseSchemaItem::create()),
- mIsMandatory(true) {
-}
+ : mSchemaItem(CAlwaysFalseSchemaItem::create()), mIsMandatory(true) {}
CObjectSchemaItem::SMember::SMember(const ISchemaItemPtr SchemaItem,
const bool IsMandatory)
- : mSchemaItem(SchemaItem),
- mIsMandatory(IsMandatory) {
-}
+ : mSchemaItem(SchemaItem), mIsMandatory(IsMandatory) {}
-utils::SharedPtr<CObjectSchemaItem> CObjectSchemaItem::create(const Members& members) {
+utils::SharedPtr<CObjectSchemaItem> CObjectSchemaItem::create(
+ const Members& members) {
return new CObjectSchemaItem(members);
}
@@ -66,7 +63,8 @@ Errors::eType CObjectSchemaItem::validate(const SmartObject& object) {
std::set<std::string> object_keys = object.enumerate();
- for (Members::const_iterator it = mMembers.begin(); it != mMembers.end(); ++it) {
+ for (Members::const_iterator it = mMembers.begin(); it != mMembers.end();
+ ++it) {
const std::string& key = it->first;
const SMember& member = it->second;
@@ -98,7 +96,8 @@ void CObjectSchemaItem::applySchema(SmartObject& Object,
}
SmartObject default_value;
- for (Members::const_iterator it = mMembers.begin(); it != mMembers.end(); ++it) {
+ for (Members::const_iterator it = mMembers.begin(); it != mMembers.end();
+ ++it) {
const std::string& key = it->first;
const SMember& member = it->second;
if (!Object.keyExists(key)) {
@@ -127,7 +126,8 @@ void CObjectSchemaItem::unapplySchema(SmartObject& Object) {
}
}
- for (Members::const_iterator it = mMembers.begin(); it != mMembers.end(); ++it) {
+ for (Members::const_iterator it = mMembers.begin(); it != mMembers.end();
+ ++it) {
const std::string& key = it->first;
const SMember& member = it->second;
if (Object.keyExists(key)) {
@@ -136,18 +136,19 @@ void CObjectSchemaItem::unapplySchema(SmartObject& Object) {
}
}
-void CObjectSchemaItem::BuildObjectBySchema(
- const SmartObject& pattern_object, SmartObject& result_object) {
+void CObjectSchemaItem::BuildObjectBySchema(const SmartObject& pattern_object,
+ SmartObject& result_object) {
result_object = SmartObject(SmartType_Map);
const bool pattern_is_map = SmartType_Map == pattern_object.getType();
- for (Members::const_iterator it = mMembers.begin(); it != mMembers.end(); ++it) {
+ for (Members::const_iterator it = mMembers.begin(); it != mMembers.end();
+ ++it) {
const std::string& key = it->first;
const SMember& member = it->second;
const bool pattern_exists = pattern_is_map && pattern_object.keyExists(key);
member.mSchemaItem->BuildObjectBySchema(
- pattern_exists ? pattern_object.getElement(key) : SmartObject(),
- result_object[key]);
+ pattern_exists ? pattern_object.getElement(key) : SmartObject(),
+ result_object[key]);
}
}
@@ -156,17 +157,17 @@ size_t CObjectSchemaItem::GetMemberSize() {
}
CObjectSchemaItem::CObjectSchemaItem(const Members& members)
- : mMembers(members) {}
+ : mMembers(members) {}
void CObjectSchemaItem::RemoveFakeParams(SmartObject& Object) {
- for (SmartMap::const_iterator it = Object.map_begin(); it != Object.map_end(); ) {
+ for (SmartMap::const_iterator it = Object.map_begin();
+ it != Object.map_end();) {
const std::string& key = it->first;
if (mMembers.end() == mMembers.find(key)
// FIXME(EZamakhov): Remove illegal usage of filed in AM
- && key.compare(connection_key) != 0
- && key.compare(binary_data) != 0
- && key.compare(app_id) != 0
- ) {
+ &&
+ key.compare(connection_key) != 0 && key.compare(binary_data) != 0 &&
+ key.compare(app_id) != 0) {
++it;
Object.erase(key);
} else {
diff --git a/src/components/smart_objects/src/schema_item.cc b/src/components/smart_objects/src/schema_item.cc
index a78afe1f2c..8c0bc0edb3 100644
--- a/src/components/smart_objects/src/schema_item.cc
+++ b/src/components/smart_objects/src/schema_item.cc
@@ -47,15 +47,13 @@ bool ISchemaItem::hasDefaultValue(SmartObject& Object) {
return false;
}
-void ISchemaItem::applySchema(SmartObject& Object, const bool RemoveFakeParameters) {
-}
+void ISchemaItem::applySchema(SmartObject& Object,
+ const bool RemoveFakeParameters) {}
-void ISchemaItem::unapplySchema(SmartObject& Object) {
-}
+void ISchemaItem::unapplySchema(SmartObject& Object) {}
void ISchemaItem::BuildObjectBySchema(const SmartObject& pattern_object,
- SmartObject& result_object) {
-}
+ SmartObject& result_object) {}
size_t ISchemaItem::GetMemberSize() {
return 0;
diff --git a/src/components/smart_objects/src/smart_object.cc b/src/components/smart_objects/src/smart_object.cc
index 264652e448..5c90de5671 100644
--- a/src/components/smart_objects/src/smart_object.cc
+++ b/src/components/smart_objects/src/smart_object.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -50,28 +50,26 @@ namespace NsSmartObjects {
**/
static const char* invalid_cstr_value = "";
-SmartObject::SmartObject()
- : m_type(SmartType_Null),
- m_schema() {
+SmartObject::SmartObject() : m_type(SmartType_Null), m_schema() {
m_data.str_value = NULL;
}
SmartObject::SmartObject(const SmartObject& Other)
- : m_type(SmartType_Null),
- m_schema() {
+ : m_type(SmartType_Null), m_schema() {
m_data.str_value = NULL;
duplicate(Other);
}
-SmartObject::SmartObject(SmartType Type)
- : m_type(SmartType_Null),
- m_schema() {
+SmartObject::SmartObject(SmartType Type) : m_type(SmartType_Null), m_schema() {
switch (Type) {
case SmartType_Null:
break;
case SmartType_Integer:
set_value_integer(0);
break;
+ case SmartType_UInteger:
+ set_value_integer(0);
+ break;
case SmartType_Double:
set_value_double(0);
break;
@@ -82,7 +80,7 @@ SmartObject::SmartObject(SmartType Type)
set_value_char(' ');
break;
case SmartType_String:
- set_value_string("");
+ set_value_string(custom_str::CustomString());
break;
case SmartType_Map:
m_data.map_value = new SmartMap();
@@ -121,6 +119,8 @@ bool SmartObject::operator==(const SmartObject& Other) const {
switch (m_type) {
case SmartType_Integer:
return m_data.int_value == Other.m_data.int_value;
+ case SmartType_UInteger:
+ return m_data.int_value == Other.m_data.int_value;
case SmartType_Double:
return m_data.double_value == Other.m_data.double_value;
case SmartType_Boolean:
@@ -134,17 +134,19 @@ bool SmartObject::operator==(const SmartObject& Other) const {
return true;
if (m_data.map_value->size() != Other.m_data.map_value->size())
return false;
- return std::equal(m_data.map_value->begin(), m_data.map_value->end(),
+ return std::equal(m_data.map_value->begin(),
+ m_data.map_value->end(),
Other.m_data.map_value->begin());
- }
+ }
case SmartType_Array: {
if (m_data.array_value == Other.m_data.array_value)
return true;
if (m_data.array_value->size() != Other.m_data.array_value->size())
return false;
- return std::equal(m_data.array_value->begin(), m_data.array_value->end(),
+ return std::equal(m_data.array_value->begin(),
+ m_data.array_value->end(),
Other.m_data.array_value->begin());
- }
+ }
case SmartType_Binary: {
if (m_data.binary_value == Other.m_data.binary_value)
return true;
@@ -153,7 +155,7 @@ bool SmartObject::operator==(const SmartObject& Other) const {
return std::equal(m_data.binary_value->begin(),
m_data.binary_value->end(),
Other.m_data.binary_value->begin());
- }
+ }
case SmartType_Null:
return true;
case SmartType_Invalid:
@@ -165,24 +167,18 @@ bool SmartObject::operator==(const SmartObject& Other) const {
return false;
}
-// =============================================================
-// INTEGER TYPE SUPPORT
-// =============================================================
SmartObject::SmartObject(int32_t InitialValue)
- : m_type(SmartType_Null),
- m_schema() {
+ : m_type(SmartType_Null), m_schema() {
m_data.str_value = NULL;
set_value_integer(InitialValue);
}
-int32_t SmartObject::asInt() const {
+int64_t SmartObject::asInt() const {
const int64_t convert = convert_int();
if (invalid_int64_value == convert) {
return invalid_int_value;
}
- DCHECK(convert >= std::numeric_limits<int32_t>::min());
- DCHECK(convert <= std::numeric_limits<int32_t>::max());
- return static_cast<int32_t>(convert);
+ return convert;
}
SmartObject& SmartObject::operator=(const int32_t NewValue) {
@@ -201,7 +197,12 @@ bool SmartObject::operator==(const int32_t Value) const {
}
void SmartObject::set_value_integer(int64_t NewValue) {
- set_new_type(SmartType_Integer);
+ if (NewValue > std::numeric_limits<int32_t>::max() &&
+ NewValue <= std::numeric_limits<uint32_t>::max()) {
+ set_new_type(SmartType_UInteger);
+ } else {
+ set_new_type(SmartType_Integer);
+ }
m_data.int_value = NewValue;
}
@@ -213,6 +214,8 @@ int64_t SmartObject::convert_int() const {
return (m_data.bool_value == true) ? 1 : 0;
case SmartType_Integer:
return m_data.int_value;
+ case SmartType_UInteger:
+ return m_data.int_value;
case SmartType_Double:
return static_cast<int64_t>(m_data.double_value);
default:
@@ -221,24 +224,18 @@ int64_t SmartObject::convert_int() const {
return invalid_int64_value;
}
-// =============================================================
-// uint32_t TYPE SUPPORT
-// =============================================================
SmartObject::SmartObject(uint32_t InitialValue)
- : m_type(SmartType_Null),
- m_schema() {
+ : m_type(SmartType_Null), m_schema() {
m_data.str_value = NULL;
set_value_integer(InitialValue);
}
-uint32_t SmartObject::asUInt() const {
+uint64_t SmartObject::asUInt() const {
const int64_t convert = convert_int();
- if (invalid_int64_value == convert) {
+ if (convert <= invalid_int_value) {
return invalid_unsigned_int_value;
}
- DCHECK(convert >= std::numeric_limits<uint32_t>::min());
- DCHECK(convert <= std::numeric_limits<uint32_t>::max());
- return static_cast<uint32_t>(convert);
+ return static_cast<uint64_t>(convert);
}
SmartObject& SmartObject::operator=(const uint32_t NewValue) {
@@ -256,20 +253,12 @@ bool SmartObject::operator==(const uint32_t Value) const {
return comp == static_cast<int64_t>(Value);
}
-// =============================================================
-// int64_t TYPE SUPPORT
-// =============================================================
SmartObject::SmartObject(int64_t InitialValue)
- : m_type(SmartType_Null),
- m_schema() {
+ : m_type(SmartType_Null), m_schema() {
m_data.str_value = NULL;
set_value_integer(InitialValue);
}
-int64_t SmartObject::asInt64() const {
- return convert_int();
-}
-
SmartObject& SmartObject::operator=(const int64_t NewValue) {
if (m_type != SmartType_Invalid) {
set_value_integer(NewValue);
@@ -285,12 +274,15 @@ bool SmartObject::operator==(const int64_t Value) const {
return comp == Value;
}
-// =============================================================
-// DOUBLE TYPE SUPPORT
-// =============================================================
+SmartObject& SmartObject::operator=(const uint64_t NewValue) {
+ if (m_type != SmartType_Invalid) {
+ set_value_integer(NewValue);
+ }
+ return *this;
+}
+
SmartObject::SmartObject(double InitialValue)
- : m_type(SmartType_Null),
- m_schema() {
+ : m_type(SmartType_Null), m_schema() {
m_data.str_value = NULL;
set_value_double(InitialValue);
}
@@ -335,13 +327,8 @@ double SmartObject::convert_double() const {
return invalid_double_value;
}
-// =============================================================
-// BOOL TYPE SUPPORT
-// =============================================================
-
SmartObject::SmartObject(bool InitialValue)
- : m_type(SmartType_Null),
- m_schema() {
+ : m_type(SmartType_Null), m_schema() {
m_data.str_value = NULL;
set_value_bool(InitialValue);
}
@@ -385,13 +372,8 @@ bool SmartObject::convert_bool() const {
return invalid_bool_value;
}
-// =============================================================
-// CHAR TYPE SUPPORT
-// =============================================================
-
SmartObject::SmartObject(char InitialValue)
- : m_type(SmartType_Null),
- m_schema() {
+ : m_type(SmartType_Null), m_schema() {
m_data.str_value = NULL;
set_value_char(InitialValue);
}
@@ -423,9 +405,10 @@ void SmartObject::set_value_char(char NewValue) {
char SmartObject::convert_char() const {
switch (m_type) {
case SmartType_String:
- return
- (m_data.str_value->length() == 1) ?
- m_data.str_value->at(0) : invalid_char_value;
+ return (m_data.str_value->length() == 1 &&
+ m_data.str_value->is_ascii_string())
+ ? m_data.str_value->at(0)
+ : invalid_char_value;
case SmartType_Character:
return m_data.char_value;
default:
@@ -438,17 +421,26 @@ char SmartObject::convert_char() const {
// STD::STRING TYPE SUPPORT
// =============================================================
-SmartObject::SmartObject(const std::string& InitialValue)
- : m_type(SmartType_Null),
- m_schema() {
+SmartObject::SmartObject(const custom_str::CustomString& InitialValue)
+ : m_type(SmartType_Null), m_schema() {
m_data.str_value = NULL;
set_value_string(InitialValue);
}
+SmartObject::SmartObject(const std::string& InitialValue)
+ : m_type(SmartType_Null), m_schema() {
+ m_data.str_value = NULL;
+ set_value_string(custom_str::CustomString(InitialValue));
+}
+
std::string SmartObject::asString() const {
return convert_string();
}
+custom_str::CustomString SmartObject::asCustomString() const {
+ return convert_custom_string();
+}
+
const char* SmartObject::asCharArray() const {
if (m_data.str_value != NULL) {
return m_data.str_value->c_str();
@@ -458,50 +450,65 @@ const char* SmartObject::asCharArray() const {
SmartObject& SmartObject::operator=(const std::string& NewValue) {
if (m_type != SmartType_Invalid) {
+ set_value_string(custom_str::CustomString(NewValue));
+ }
+ return *this;
+}
+
+SmartObject& SmartObject::operator=(const custom_str::CustomString& NewValue) {
+ if (m_type != SmartType_Invalid) {
set_value_string(NewValue);
}
return *this;
}
bool SmartObject::operator==(const std::string& Value) const {
- const std::string comp = convert_string();
+ const custom_str::CustomString& comp(convert_custom_string());
if (comp == invalid_string_value) {
return false;
}
return comp == Value;
}
-void SmartObject::set_value_string(const std::string& NewValue) {
+void SmartObject::set_value_string(const custom_str::CustomString& NewValue) {
set_new_type(SmartType_String);
- m_data.str_value = new std::string(NewValue);
+ m_data.str_value = new custom_str::CustomString(NewValue);
}
std::string SmartObject::convert_string() const {
switch (m_type) {
- case SmartType_String:
- return *(m_data.str_value);
case SmartType_Integer: {
- std::stringstream stream;
- stream << m_data.int_value;
- return stream.str();
- }
+ std::stringstream stream;
+ stream << m_data.int_value;
+ return stream.str();
+ }
case SmartType_Character:
return std::string(1, m_data.char_value);
case SmartType_Double:
return convert_double_to_string(m_data.double_value);
+ case SmartType_String:
+ return (m_data.str_value)->AsMBString();
default:
break;
}
return NsSmartDeviceLink::NsSmartObjects::invalid_cstr_value;
}
+custom_str::CustomString SmartObject::convert_custom_string() const {
+ switch (m_type) {
+ case SmartType_String:
+ return *(m_data.str_value);
+ default:
+ return custom_str::CustomString(convert_string());
+ }
+}
+
// =============================================================
// CHAR* TYPE SUPPORT
// =============================================================
SmartObject::SmartObject(const char* const InitialValue)
- : m_type(SmartType_Null),
- m_schema() {
+ : m_type(SmartType_Null), m_schema() {
m_data.str_value = NULL;
set_value_cstr(InitialValue);
return;
@@ -515,7 +522,7 @@ SmartObject& SmartObject::operator=(const char* NewValue) {
}
bool SmartObject::operator==(const char* Value) const {
- const std::string comp = convert_string();
+ const custom_str::CustomString& comp(convert_custom_string());
if (comp == invalid_string_value) {
return false;
}
@@ -523,15 +530,15 @@ bool SmartObject::operator==(const char* Value) const {
}
void SmartObject::set_value_cstr(const char* NewValue) {
- set_value_string(NewValue ? std::string(NewValue) : std::string());
+ set_value_string(NewValue ? custom_str::CustomString(NewValue)
+ : custom_str::CustomString());
}
// =============================================================
// BINARY TYPE SUPPORT
// =============================================================
SmartObject::SmartObject(const SmartBinary& InitialValue)
- : m_type(SmartType_Null),
- m_schema() {
+ : m_type(SmartType_Null), m_schema() {
m_data.str_value = NULL;
set_value_binary(InitialValue);
}
@@ -622,7 +629,7 @@ SmartObject& SmartObject::operator[](const std::string& Key) {
return handle_map_access(Key);
}
-const SmartObject& SmartObject::operator[] (const std::string& Key) const {
+const SmartObject& SmartObject::operator[](const std::string& Key) const {
return getElement(Key);
}
@@ -683,7 +690,7 @@ void SmartObject::duplicate(const SmartObject& OtherObject) {
SmartData newData;
const SmartType newType = OtherObject.m_type;
switch (newType) {
- case SmartType_Null: // on duplicate empty SmartObject
+ case SmartType_Null: // on duplicate empty SmartObject
return;
case SmartType_Map:
newData.map_value = new SmartMap(*OtherObject.m_data.map_value);
@@ -704,7 +711,8 @@ void SmartObject::duplicate(const SmartObject& OtherObject) {
newData.char_value = OtherObject.m_data.char_value;
break;
case SmartType_String:
- newData.str_value = new std::string(*OtherObject.m_data.str_value);
+ newData.str_value =
+ new custom_str::CustomString(*OtherObject.m_data.str_value);
break;
case SmartType_Binary:
newData.binary_value = new SmartBinary(*OtherObject.m_data.binary_value);
@@ -777,8 +785,9 @@ void SmartObject::set_new_type(SmartType NewType) {
m_type = NewType;
}
-double SmartObject::convert_string_to_double(const std::string* Value) {
- if (!Value || Value->empty()) {
+double SmartObject::convert_string_to_double(
+ const custom_str::CustomString* Value) {
+ if (!Value || Value->empty() || !(Value->is_ascii_string())) {
return invalid_double_value;
}
@@ -811,12 +820,13 @@ std::string SmartObject::convert_double_to_string(const double& Value) {
return s;
}
-uint64_t SmartObject::convert_string_to_integer(const std::string* Value) {
- if (!Value || Value->empty()) {
+uint64_t SmartObject::convert_string_to_integer(
+ const custom_str::CustomString* Value) {
+ if (!Value || Value->empty() || !(Value->is_ascii_string())) {
return invalid_int64_value;
}
int64_t result;
- std::stringstream stream(*Value);
+ std::stringstream stream(Value->AsMBString());
stream >> result;
if (stream.eof()) {
return result;
@@ -828,20 +838,18 @@ SmartType SmartObject::getType() const {
return m_type;
}
-std::string SmartObject::OperatorToTransform(const SmartMap::value_type &pair) {
- return pair.first;
+std::string SmartObject::OperatorToTransform(const SmartMap::value_type& pair) {
+ return pair.first;
}
std::set<std::string> SmartObject::enumerate() const {
std::set<std::string> keys;
if (m_type == SmartType_Map) {
- std::transform(
- m_data.map_value->begin(),
- m_data.map_value->end(),
- std::inserter(keys, keys.end()),
- &SmartObject::OperatorToTransform
- );
+ std::transform(m_data.map_value->begin(),
+ m_data.map_value->end(),
+ std::inserter(keys, keys.end()),
+ &SmartObject::OperatorToTransform);
}
return keys;
}
diff --git a/src/components/smart_objects/src/smart_schema.cc b/src/components/smart_objects/src/smart_schema.cc
index 3a9cd22a0a..be24ceb076 100644
--- a/src/components/smart_objects/src/smart_schema.cc
+++ b/src/components/smart_objects/src/smart_schema.cc
@@ -35,13 +35,10 @@
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
-CSmartSchema::CSmartSchema()
- : mSchemaItem(CAlwaysTrueSchemaItem::create()) {
-}
+CSmartSchema::CSmartSchema() : mSchemaItem(CAlwaysTrueSchemaItem::create()) {}
CSmartSchema::CSmartSchema(const ISchemaItemPtr SchemaItem)
- : mSchemaItem(SchemaItem) {
-}
+ : mSchemaItem(SchemaItem) {}
Errors::eType CSmartSchema::validate(const SmartObject& object) const {
return mSchemaItem->validate(object);
@@ -51,7 +48,8 @@ void CSmartSchema::setSchemaItem(const ISchemaItemPtr schemaItem) {
mSchemaItem = schemaItem;
}
-void CSmartSchema::applySchema(SmartObject& Object, const bool RemoveFakeParameters) {
+void CSmartSchema::applySchema(SmartObject& Object,
+ const bool RemoveFakeParameters) {
mSchemaItem->applySchema(Object, RemoveFakeParameters);
}
diff --git a/src/components/smart_objects/src/string_schema_item.cc b/src/components/smart_objects/src/string_schema_item.cc
index c9c00e8896..3fac3a6cde 100644
--- a/src/components/smart_objects/src/string_schema_item.cc
+++ b/src/components/smart_objects/src/string_schema_item.cc
@@ -31,10 +31,13 @@
*/
#include "smart_objects/smart_object.h"
#include "smart_objects/string_schema_item.h"
+#include "utils/custom_string.h"
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
+namespace custom_str = utils::custom_string;
+
utils::SharedPtr<CStringSchemaItem> CStringSchemaItem::create(
const TSchemaItemParameter<size_t>& MinLength,
const TSchemaItemParameter<size_t>& MaxLength,
@@ -47,7 +50,7 @@ Errors::eType CStringSchemaItem::validate(const SmartObject& Object) {
return Errors::INVALID_VALUE;
}
- const std::string value = Object.asString();
+ const custom_str::CustomString value = Object.asCustomString();
size_t length;
if (mMinLength.getValue(length) && (value.size() < length)) {
@@ -71,10 +74,9 @@ CStringSchemaItem::CStringSchemaItem(
const TSchemaItemParameter<size_t>& MinLength,
const TSchemaItemParameter<size_t>& MaxLength,
const TSchemaItemParameter<std::string>& DefaultValue)
- : CDefaultSchemaItem<std::string>(DefaultValue),
- mMinLength(MinLength),
- mMaxLength(MaxLength) {
-}
+ : CDefaultSchemaItem<std::string>(DefaultValue)
+ , mMinLength(MinLength)
+ , mMaxLength(MaxLength) {}
} // namespace NsSmartObjects
} // namespace NsSmartDeviceLink
diff --git a/src/components/smart_objects/test/ArraySchemaItem_test.cc b/src/components/smart_objects/test/ArraySchemaItem_test.cc
index f153a4c4a7..c4c7254cb8 100644
--- a/src/components/smart_objects/test/ArraySchemaItem_test.cc
+++ b/src/components/smart_objects/test/ArraySchemaItem_test.cc
@@ -50,7 +50,8 @@ TEST(test_no_default_value, test_ArraySchemaItemTest) {
using namespace NsSmartDeviceLink::NsSmartObjects;
SmartObject obj;
- ISchemaItemPtr item = CArraySchemaItem::create(); // No schema item, no min and max size
+ ISchemaItemPtr item =
+ CArraySchemaItem::create(); // No schema item, no min and max size
obj[0] = 38;
obj[1] = true;
@@ -97,20 +98,20 @@ TEST(test_no_default_value, test_ArraySchemaItemTest) {
EXPECT_FALSE(obj[3][1].asBool());
EXPECT_EQ(std::string("Another String"), obj[3][2].asString());
- //Object - valid string
+ // Object - valid string
obj = "New valid string";
ASSERT_EQ(std::string("New valid string"), obj.asString());
resultType = item->validate(obj);
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
- //Obj - bool
+ // Obj - bool
obj = true;
resultType = item->validate(obj);
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
- //Object - number
+ // Object - number
obj = 3.1415926;
resultType = item->validate(obj);
@@ -221,7 +222,8 @@ TEST(test_array_with_max_size, test_ArraySchemaItemTest) {
ISchemaItemPtr item = CArraySchemaItem::create(
CStringSchemaItem::create(TSchemaItemParameter<size_t>(),
TSchemaItemParameter<size_t>(25)),
- TSchemaItemParameter<size_t>(), TSchemaItemParameter<size_t>(3)); // No min size
+ TSchemaItemParameter<size_t>(),
+ TSchemaItemParameter<size_t>(3)); // No min size
obj[0] = "Some String";
@@ -259,7 +261,8 @@ TEST(test_array_with_min_and_max_size, test_ArraySchemaItemTest) {
ISchemaItemPtr item = CArraySchemaItem::create(
CStringSchemaItem::create(TSchemaItemParameter<size_t>(),
TSchemaItemParameter<size_t>(25)),
- TSchemaItemParameter<size_t>(2), TSchemaItemParameter<size_t>(4));
+ TSchemaItemParameter<size_t>(2),
+ TSchemaItemParameter<size_t>(4));
obj[0] = "Some String";
@@ -300,7 +303,8 @@ TEST(test_map_validate, test_ArraySchemaItemTest) {
ISchemaItemPtr item = CArraySchemaItem::create(
CStringSchemaItem::create(TSchemaItemParameter<size_t>(),
TSchemaItemParameter<size_t>(25)),
- TSchemaItemParameter<size_t>(2), TSchemaItemParameter<size_t>(4));
+ TSchemaItemParameter<size_t>(2),
+ TSchemaItemParameter<size_t>(4));
obj["array"][0] = "Some String";
@@ -339,4 +343,3 @@ TEST(test_map_validate, test_ArraySchemaItemTest) {
} // namespace SmartObjects
} // namespace components
} // namespace test
-
diff --git a/src/components/smart_objects/test/BoolSchemaItem_test.cc b/src/components/smart_objects/test/BoolSchemaItem_test.cc
index c56dd9aa2d..fa9c6a3d5d 100644
--- a/src/components/smart_objects/test/BoolSchemaItem_test.cc
+++ b/src/components/smart_objects/test/BoolSchemaItem_test.cc
@@ -48,14 +48,17 @@ using NsSmartDeviceLink::NsSmartObjects::ISchemaItemPtr;
/**
* Test BoolSchemaItem no default value
*
- * Create SchemaItem without default value. Method setDefaultValue should always return false
+ * Create SchemaItem without default value. Method setDefaultValue should always
+ *return false
* and leave SmartObject in previous state.
**/
TEST(test_no_default_value, test_BoolSchemaItemTest) {
NsSmartDeviceLink::NsSmartObjects::SmartObject obj;
ISchemaItemPtr item =
- NsSmartDeviceLink::NsSmartObjects::CBoolSchemaItem::create(); // No default value
+ NsSmartDeviceLink::NsSmartObjects::CBoolSchemaItem::create(); // No
+ // default
+ // value
obj = 5;
ASSERT_EQ(5, obj.asInt());
@@ -89,16 +92,19 @@ TEST(test_no_default_value, test_BoolSchemaItemTest) {
/**
* Test BoolSchemaItem with default value
*
- * Create SchemaItem with default value. Method setDefaultValue should return true,
+ * Create SchemaItem with default value. Method setDefaultValue should return
+ *true,
* Bool SmartObject should contain default value.
- * Not bool SmartObject should converted to BoolObject and setted up by default value.
+ * Not bool SmartObject should converted to BoolObject and setted up by default
+ *value.
**/
TEST(test_item_with_default_value, test_BoolSchemaItemTest) {
NsSmartDeviceLink::NsSmartObjects::SmartObject obj;
ISchemaItemPtr item =
NsSmartDeviceLink::NsSmartObjects::CBoolSchemaItem::create(
- NsSmartDeviceLink::NsSmartObjects::TSchemaItemParameter<bool>(false)); // Default value = false
+ NsSmartDeviceLink::NsSmartObjects::TSchemaItemParameter<bool>(
+ false)); // Default value = false
obj = 5;
ASSERT_EQ(5, obj.asInt());
@@ -135,7 +141,8 @@ TEST(test_map_validate, test_BoolSchemaItemTest) {
NsSmartDeviceLink::NsSmartObjects::SmartObject obj;
ISchemaItemPtr item =
NsSmartDeviceLink::NsSmartObjects::CBoolSchemaItem::create(
- NsSmartDeviceLink::NsSmartObjects::TSchemaItemParameter<bool>(false)); // Default value = false
+ NsSmartDeviceLink::NsSmartObjects::TSchemaItemParameter<bool>(
+ false)); // Default value = false
obj["aa"] = true;
ASSERT_TRUE(obj["aa"].asBool());
diff --git a/src/components/smart_objects/test/CObjectSchemaItem_test.cc b/src/components/smart_objects/test/CObjectSchemaItem_test.cc
index b5e1286ee1..b3777ad028 100644
--- a/src/components/smart_objects/test/CObjectSchemaItem_test.cc
+++ b/src/components/smart_objects/test/CObjectSchemaItem_test.cc
@@ -43,7 +43,7 @@
#include "smart_objects/schema_item_parameter.h"
#include "smart_objects/object_schema_item.h"
#include "formatters/generic_json_formatter.h"
-#include "formatters/CSmartFactory.hpp"
+#include "formatters/CSmartFactory.h"
namespace formatters = NsSmartDeviceLink::NsJSONHandler::Formatters;
namespace smartobj = NsSmartDeviceLink::NsSmartObjects;
@@ -120,8 +120,8 @@ class ObjectSchemaItemTest : public ::testing::Test {
CObjectSchemaItem::Members paramsMembersMap;
paramsMembersMap[S_FUNCTION_ID] = CObjectSchemaItem::SMember(
TEnumSchemaItem<FunctionID::eType>::create(function_values), true);
- paramsMembersMap[S_CORRELATION_ID] = CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(), true);
+ paramsMembersMap[S_CORRELATION_ID] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
paramsMembersMap[S_PROTOCOL_VERSION] = CObjectSchemaItem::SMember(
TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(1),
TSchemaItemParameter<int>(2)),
@@ -134,8 +134,8 @@ class ObjectSchemaItemTest : public ::testing::Test {
CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
TSchemaItemParameter<size_t>(10)),
false);
- schemaMembersMap[Keys::SUCCESS] = CObjectSchemaItem::SMember(
- CBoolSchemaItem::create(), false);
+ schemaMembersMap[Keys::SUCCESS] =
+ CObjectSchemaItem::SMember(CBoolSchemaItem::create(), false);
CObjectSchemaItem::Members rootMembersMap;
rootMembersMap[S_PARAMS] = CObjectSchemaItem::SMember(
@@ -313,7 +313,6 @@ TEST_F(ObjectSchemaItemTest, validation_unexpected_param_remove) {
EXPECT_TRUE(obj[S_MSG_PARAMS].keyExists(Keys::SUCCESS));
EXPECT_EQ(Errors::OK, schema_item->validate(obj));
-
obj[fake1] = SmartObject(static_cast<int64_t>(0));
obj[S_PARAMS][fake2] = SmartObject("123");
obj[S_MSG_PARAMS][fake3] = true;
@@ -368,9 +367,11 @@ TEST_F(ObjectSchemaItemTest, test_strings_to_enum_conversion) {
EnumConversionHelper<FunctionID::eType>::cstring_to_enum_map();
for (Results::const_iterator res_it = results.begin();
- res_it != results.end(); ++res_it) {
+ res_it != results.end();
+ ++res_it) {
for (Functions::const_iterator func_it = functions.begin();
- func_it != functions.end(); ++func_it) {
+ func_it != functions.end();
+ ++func_it) {
const char* const function_str = func_it->first;
const char* const result_type_str = res_it->first;
const FunctionID::eType function_type = func_it->second;
@@ -401,7 +402,7 @@ TEST_F(ObjectSchemaItemTest, test_strings_to_enum_conversion) {
}
}
// ----------------------------------------------------------------------------
-}// namespace SchemaItem
+} // namespace SchemaItem
} // namespace SmartObjects
} // namespace components
} // namespace test
@@ -412,50 +413,74 @@ namespace NsSmartObjects {
namespace FunctionID = test::components::SmartObjects::SchemaItem::FunctionID;
typedef EnumConversionHelper<FunctionID::eType> FunctionConvertor;
-template<>
-const FunctionConvertor::EnumToCStringMap FunctionConvertor::enum_to_cstring_map_ =
- FunctionConvertor::InitEnumToCStringMap();
-
-template<>
-const FunctionConvertor::CStringToEnumMap FunctionConvertor::cstring_to_enum_map_ =
- FunctionConvertor::InitCStringToEnumMap();
-
-template<>
-const char* const FunctionConvertor::cstring_values_[] =
- { "Function0", "Function1", "Function2", "Function3", "Function4",
- "Function5", "Function6" };
-
-template<>
+template <>
+const FunctionConvertor::EnumToCStringMap
+ FunctionConvertor::enum_to_cstring_map_ =
+ FunctionConvertor::InitEnumToCStringMap();
+
+template <>
+const FunctionConvertor::CStringToEnumMap
+ FunctionConvertor::cstring_to_enum_map_ =
+ FunctionConvertor::InitCStringToEnumMap();
+
+template <>
+const char* const FunctionConvertor::cstring_values_[] = {"Function0",
+ "Function1",
+ "Function2",
+ "Function3",
+ "Function4",
+ "Function5",
+ "Function6"};
+
+template <>
const FunctionID::eType FunctionConvertor::enum_values_[] = {
- FunctionID::Function0, FunctionID::Function1, FunctionID::Function2,
- FunctionID::Function3, FunctionID::Function4, FunctionID::Function5,
- FunctionID::Function6 };
+ FunctionID::Function0,
+ FunctionID::Function1,
+ FunctionID::Function2,
+ FunctionID::Function3,
+ FunctionID::Function4,
+ FunctionID::Function5,
+ FunctionID::Function6};
// ----------------------------------------------------------------------------
namespace ResultType = test::components::SmartObjects::SchemaItem::ResultType;
typedef EnumConversionHelper<ResultType::eType> ResultTypeConvertor;
-template<>
-const ResultTypeConvertor::EnumToCStringMap ResultTypeConvertor::enum_to_cstring_map_ =
- ResultTypeConvertor::InitEnumToCStringMap();
+template <>
+const ResultTypeConvertor::EnumToCStringMap
+ ResultTypeConvertor::enum_to_cstring_map_ =
+ ResultTypeConvertor::InitEnumToCStringMap();
-template<>
-const ResultTypeConvertor::CStringToEnumMap ResultTypeConvertor::cstring_to_enum_map_ =
- ResultTypeConvertor::InitCStringToEnumMap();
+template <>
+const ResultTypeConvertor::CStringToEnumMap
+ ResultTypeConvertor::cstring_to_enum_map_ =
+ ResultTypeConvertor::InitCStringToEnumMap();
-template<>
+template <>
const char* const ResultTypeConvertor::cstring_values_[] = {
- "APPLICATION_NOT_REGISTERED", "SUCCESS", "TOO_MANY_PENDING_REQUESTS",
- "REJECTED", "INVALID_DATA", "OUT_OF_MEMORY", "ABORTED", "USER_DISALLOWED",
- "GENERIC_ERROR", "DISALLOWED" };
-
-template<>
+ "APPLICATION_NOT_REGISTERED",
+ "SUCCESS",
+ "TOO_MANY_PENDING_REQUESTS",
+ "REJECTED",
+ "INVALID_DATA",
+ "OUT_OF_MEMORY",
+ "ABORTED",
+ "USER_DISALLOWED",
+ "GENERIC_ERROR",
+ "DISALLOWED"};
+
+template <>
const ResultType::eType ResultTypeConvertor::enum_values_[] = {
- ResultType::APPLICATION_NOT_REGISTERED, ResultType::SUCCESS,
- ResultType::TOO_MANY_PENDING_REQUESTS, ResultType::REJECTED,
- ResultType::INVALID_DATA, ResultType::OUT_OF_MEMORY, ResultType::ABORTED,
- ResultType::USER_DISALLOWED, ResultType::GENERIC_ERROR,
- ResultType::DISALLOWED };
+ ResultType::APPLICATION_NOT_REGISTERED,
+ ResultType::SUCCESS,
+ ResultType::TOO_MANY_PENDING_REQUESTS,
+ ResultType::REJECTED,
+ ResultType::INVALID_DATA,
+ ResultType::OUT_OF_MEMORY,
+ ResultType::ABORTED,
+ ResultType::USER_DISALLOWED,
+ ResultType::GENERIC_ERROR,
+ ResultType::DISALLOWED};
} // namespace NsSmartObjects
} // namespace NsSmartDeviceLink
diff --git a/src/components/smart_objects/test/EnumSchemaItem_test.cc b/src/components/smart_objects/test/EnumSchemaItem_test.cc
index 6d007b74b6..24cde07193 100644
--- a/src/components/smart_objects/test/EnumSchemaItem_test.cc
+++ b/src/components/smart_objects/test/EnumSchemaItem_test.cc
@@ -71,8 +71,7 @@ class EnumSchemaItemTest : public ::testing::Test {
testEnum.insert(TestType::APP_UNAUTHORIZED);
}
- virtual void SetUp() {
- }
+ virtual void SetUp() {}
std::set<TestType::eType> testEnum;
};
@@ -80,9 +79,11 @@ class EnumSchemaItemTest : public ::testing::Test {
/**
* Test EnumSchemaItem
*
- * Create SchemaItem with default value. Method setDefaultValue should return true,
+ * Create SchemaItem with default value. Method setDefaultValue should return
+ *true,
* SmartObject should contain default value.
- * Not Enum SmartObject should converted to intObject and setted up by the default value.
+ * Not Enum SmartObject should converted to intObject and setted up by the
+ *default value.
**/
TEST_F(EnumSchemaItemTest, test_item_with_default_value) {
SmartObject obj;
@@ -90,7 +91,7 @@ TEST_F(EnumSchemaItemTest, test_item_with_default_value) {
testEnum,
TSchemaItemParameter<TestType::eType>(TestType::FACTORY_DEFAULTS));
- //Object - valid enum
+ // Object - valid enum
obj = TestType::BLUETOOTH_OFF;
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
@@ -98,7 +99,7 @@ TEST_F(EnumSchemaItemTest, test_item_with_default_value) {
EXPECT_TRUE(resDefault);
EXPECT_EQ(TestType::FACTORY_DEFAULTS, obj.asInt());
- //Obj - bool
+ // Obj - bool
obj = true;
resultType = item->validate(obj);
@@ -107,7 +108,7 @@ TEST_F(EnumSchemaItemTest, test_item_with_default_value) {
EXPECT_TRUE(resDefault);
EXPECT_EQ(TestType::FACTORY_DEFAULTS, obj.asInt());
- //Object - number
+ // Object - number
obj = 3.1415926;
resultType = item->validate(obj);
@@ -117,7 +118,7 @@ TEST_F(EnumSchemaItemTest, test_item_with_default_value) {
EXPECT_TRUE(resDefault);
EXPECT_EQ(TestType::FACTORY_DEFAULTS, obj.asInt());
- //Object - string
+ // Object - string
obj = "Some string";
resultType = item->validate(obj);
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
@@ -130,7 +131,8 @@ TEST_F(EnumSchemaItemTest, test_item_with_default_value) {
/**
* Test EnumSchemaItem with default value
*
- * Create SchemaItem without default value. Method setDefaultValue should return false,
+ * Create SchemaItem without default value. Method setDefaultValue should return
+ *false,
* SmartObject should contain previous value.
**/
TEST_F(EnumSchemaItemTest, test_item_without_default_value) {
@@ -139,7 +141,7 @@ TEST_F(EnumSchemaItemTest, test_item_without_default_value) {
ISchemaItemPtr item = TEnumSchemaItem<TestType::eType>::create(
testEnum, TSchemaItemParameter<TestType::eType>());
- //Object - valid enum
+ // Object - valid enum
obj = TestType::BLUETOOTH_OFF;
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
@@ -147,7 +149,7 @@ TEST_F(EnumSchemaItemTest, test_item_without_default_value) {
EXPECT_FALSE(resDefault);
EXPECT_EQ(TestType::BLUETOOTH_OFF, obj.asInt());
- //Obj - bool
+ // Obj - bool
obj = true;
resultType = item->validate(obj);
@@ -156,7 +158,7 @@ TEST_F(EnumSchemaItemTest, test_item_without_default_value) {
EXPECT_FALSE(resDefault);
EXPECT_TRUE(obj.asBool());
- //Object - number
+ // Object - number
obj = 3.1415926;
resultType = item->validate(obj);
@@ -166,7 +168,7 @@ TEST_F(EnumSchemaItemTest, test_item_without_default_value) {
EXPECT_FALSE(resDefault);
EXPECT_EQ(3.1415926, obj.asDouble());
- //Object - string
+ // Object - string
obj = "Some string";
resultType = item->validate(obj);
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
@@ -175,12 +177,12 @@ TEST_F(EnumSchemaItemTest, test_item_without_default_value) {
EXPECT_FALSE(resDefault);
EXPECT_EQ(std::string("Some string"), obj.asString());
- //Object - int in range of enum
+ // Object - int in range of enum
obj = 6;
resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object - int out of enum range
+ // Object - int out of enum range
obj = 15;
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
@@ -196,7 +198,7 @@ TEST_F(EnumSchemaItemTest, test_apply_unapply_schema) {
testEnum,
TSchemaItemParameter<TestType::eType>(TestType::FACTORY_DEFAULTS));
- //Object - valid enum
+ // Object - valid enum
obj = TestType::BLUETOOTH_OFF;
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
@@ -226,7 +228,6 @@ TEST_F(EnumSchemaItemTest, test_apply_unapply_schema) {
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
EXPECT_EQ(std::string("ENOUGH_REQUESTS"), obj.asString());
}
-
}
}
}
@@ -235,38 +236,45 @@ TEST_F(EnumSchemaItemTest, test_apply_unapply_schema) {
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
-template<>
-const EnumConversionHelper<
- test::components::SmartObjects::SchemaItem::TestType::eType>::EnumToCStringMap EnumConversionHelper<
- test::components::SmartObjects::SchemaItem::TestType::eType>::enum_to_cstring_map_ =
- EnumConversionHelper<
- test::components::SmartObjects::SchemaItem::TestType::eType>::InitEnumToCStringMap();
-
-template<>
-const EnumConversionHelper<
- test::components::SmartObjects::SchemaItem::TestType::eType>::CStringToEnumMap EnumConversionHelper<
- test::components::SmartObjects::SchemaItem::TestType::eType>::cstring_to_enum_map_ =
- EnumConversionHelper<
- test::components::SmartObjects::SchemaItem::TestType::eType>::InitCStringToEnumMap();
-
-template<>
+template <>
+const EnumConversionHelper<test::components::SmartObjects::SchemaItem::
+ TestType::eType>::EnumToCStringMap
+ EnumConversionHelper<test::components::SmartObjects::SchemaItem::TestType::
+ eType>::enum_to_cstring_map_ =
+ EnumConversionHelper<test::components::SmartObjects::SchemaItem::
+ TestType::eType>::InitEnumToCStringMap();
+
+template <>
+const EnumConversionHelper<test::components::SmartObjects::SchemaItem::
+ TestType::eType>::CStringToEnumMap
+ EnumConversionHelper<test::components::SmartObjects::SchemaItem::TestType::
+ eType>::cstring_to_enum_map_ =
+ EnumConversionHelper<test::components::SmartObjects::SchemaItem::
+ TestType::eType>::InitCStringToEnumMap();
+
+template <>
const char* const EnumConversionHelper<
- test::components::SmartObjects::SchemaItem::TestType::eType>::cstring_values_[] =
- { "USER_EXIT", "IGNITION_OFF", "BLUETOOTH_OFF", "USB_DISCONNECTED",
- "TOO_MANY_REQUESTS", "MASTER_RESET", "FACTORY_DEFAULTS",
- "APP_UNAUTHORIZED" };
-
-template<>
-const test::components::SmartObjects::SchemaItem::TestType::eType EnumConversionHelper<
- test::components::SmartObjects::SchemaItem::TestType::eType>::enum_values_[] =
- { test::components::SmartObjects::SchemaItem::TestType::USER_EXIT,
+ test::components::SmartObjects::SchemaItem::TestType::eType>::
+ cstring_values_[] = {"USER_EXIT",
+ "IGNITION_OFF",
+ "BLUETOOTH_OFF",
+ "USB_DISCONNECTED",
+ "TOO_MANY_REQUESTS",
+ "MASTER_RESET",
+ "FACTORY_DEFAULTS",
+ "APP_UNAUTHORIZED"};
+
+template <>
+const test::components::SmartObjects::SchemaItem::TestType::eType
+ EnumConversionHelper<test::components::SmartObjects::SchemaItem::TestType::
+ eType>::enum_values_[] = {
+ test::components::SmartObjects::SchemaItem::TestType::USER_EXIT,
test::components::SmartObjects::SchemaItem::TestType::IGNITION_OFF,
test::components::SmartObjects::SchemaItem::TestType::BLUETOOTH_OFF,
test::components::SmartObjects::SchemaItem::TestType::USB_DISCONNECTED,
test::components::SmartObjects::SchemaItem::TestType::TOO_MANY_REQUESTS,
test::components::SmartObjects::SchemaItem::TestType::MASTER_RESET,
test::components::SmartObjects::SchemaItem::TestType::FACTORY_DEFAULTS,
- test::components::SmartObjects::SchemaItem::TestType::APP_UNAUTHORIZED };
-
+ test::components::SmartObjects::SchemaItem::TestType::APP_UNAUTHORIZED};
}
}
diff --git a/src/components/smart_objects/test/NumberSchemaItem_test.cc b/src/components/smart_objects/test/NumberSchemaItem_test.cc
index cc56228694..2c4b24e927 100644
--- a/src/components/smart_objects/test/NumberSchemaItem_test.cc
+++ b/src/components/smart_objects/test/NumberSchemaItem_test.cc
@@ -46,7 +46,8 @@ using NsSmartDeviceLink::NsSmartObjects::ISchemaItemPtr;
/**
* Test NumberSchemaItem as INT with no default value
*
- * Create SchemaItem without default value. Method setDefaultValue should always return false
+ * Create SchemaItem without default value. Method setDefaultValue should always
+ *return false
* and leave SmartObject in previous state.
**/
TEST(test_int_no_default_value, test_NumberSchemaItemTest) {
@@ -54,30 +55,31 @@ TEST(test_int_no_default_value, test_NumberSchemaItemTest) {
SmartObject obj;
- ISchemaItemPtr item = TNumberSchemaItem<int>::create(); // No default value, no min, no max
+ ISchemaItemPtr item =
+ TNumberSchemaItem<int>::create(); // No default value, no min, no max
- //Object int
+ // Object int
obj = 5;
ASSERT_EQ(5, obj.asInt());
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Obj bool
+ // Obj bool
obj = true;
ASSERT_TRUE(obj.asBool());
resultType = item->validate(obj);
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
- //Set default value
+ // Set default value
bool resDefault = item->setDefaultValue(obj);
EXPECT_FALSE(resDefault);
resultType = item->validate(obj);
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
EXPECT_TRUE(obj.asBool());
- //Obj string
+ // Obj string
obj = "Test";
ASSERT_EQ(std::string("Test"), obj.asString());
@@ -100,21 +102,21 @@ TEST(test_int_min_value, test_NumberSchemaItemTest) {
ISchemaItemPtr item = TNumberSchemaItem<int>::create(
TSchemaItemParameter<int>(10)); // No default value, no max value
- //Object int correct
+ // Object int correct
obj = 15;
ASSERT_EQ(15, obj.asInt());
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object int incorrect
+ // Object int incorrect
obj = 9;
ASSERT_EQ(9, obj.asInt());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
- //Object int correct
+ // Object int correct
obj = 10;
ASSERT_EQ(10, obj.asInt());
@@ -131,23 +133,24 @@ TEST(test_int_max_value, test_NumberSchemaItemTest) {
SmartObject obj;
ISchemaItemPtr item = TNumberSchemaItem<int>::create(
- TSchemaItemParameter<int>(), TSchemaItemParameter<int>(749)); // No default value, no min value
+ TSchemaItemParameter<int>(),
+ TSchemaItemParameter<int>(749)); // No default value, no min value
- //Object int correct
+ // Object int correct
obj = 749;
ASSERT_EQ(749, obj.asInt());
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object int incorrect
+ // Object int incorrect
obj = 750;
ASSERT_EQ(750, obj.asInt());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
- //Object int correct
+ // Object int correct
obj = -750;
ASSERT_EQ(-750, obj.asInt());
@@ -164,36 +167,36 @@ TEST(test_int_min_max_value, test_NumberSchemaItemTest) {
SmartObject obj;
ISchemaItemPtr item = TNumberSchemaItem<int>::create(
- TSchemaItemParameter<int>(-949), TSchemaItemParameter<int>(749)); // No default value
+ TSchemaItemParameter<int>(-949),
+ TSchemaItemParameter<int>(749)); // No default value
- //Object int correct
+ // Object int correct
obj = 749;
ASSERT_EQ(749, obj.asInt());
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object int incorrect
+ // Object int incorrect
obj = 750;
ASSERT_EQ(750, obj.asInt());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
- //Object int correct
+ // Object int correct
obj = -949;
ASSERT_EQ(-949, obj.asInt());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object int incorrect
+ // Object int incorrect
obj = -950;
ASSERT_EQ(-950, obj.asInt());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
-
}
/**
@@ -204,46 +207,47 @@ TEST(test_int_correct_default_value, test_NumberSchemaItemTest) {
SmartObject obj;
- ISchemaItemPtr item = TNumberSchemaItem<int>::create(
- TSchemaItemParameter<int>(-12000), TSchemaItemParameter<int>(100),
- TSchemaItemParameter<int>(-38));
+ ISchemaItemPtr item =
+ TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(-12000),
+ TSchemaItemParameter<int>(100),
+ TSchemaItemParameter<int>(-38));
- //Object int correct
+ // Object int correct
obj = -12000;
ASSERT_EQ(-12000, obj.asInt());
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object int incorrect
+ // Object int incorrect
obj = -12001;
ASSERT_EQ(-12001, obj.asInt());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
- //Object int correct
+ // Object int correct
obj = 100;
ASSERT_EQ(100, obj.asInt());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object int incorrect
+ // Object int incorrect
obj = 101;
ASSERT_EQ(101, obj.asInt());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
- //Set default value
+ // Set default value
bool resDefault = item->setDefaultValue(obj);
EXPECT_TRUE(resDefault);
resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
EXPECT_EQ(-38, obj.asInt());
- //Object string
+ // Object string
obj = "string";
resultType = item->validate(obj);
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
@@ -263,45 +267,46 @@ TEST(test_int_default_value_out_of_range, test_NumberSchemaItemTest) {
SmartObject obj;
ISchemaItemPtr item = TNumberSchemaItem<int>::create(
- TSchemaItemParameter<int>(90), TSchemaItemParameter<int>(100),
+ TSchemaItemParameter<int>(90),
+ TSchemaItemParameter<int>(100),
TSchemaItemParameter<int>(50)); // Default value out of range
- //Object int correct
+ // Object int correct
obj = 90;
ASSERT_EQ(90, obj.asInt());
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object int incorrect
+ // Object int incorrect
obj = 89;
ASSERT_EQ(89, obj.asInt());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
- //Object int correct
+ // Object int correct
obj = 100;
ASSERT_EQ(100, obj.asInt());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object int incorrect
+ // Object int incorrect
obj = 101;
ASSERT_EQ(101, obj.asInt());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
- //Set default value
+ // Set default value
bool resDefault = item->setDefaultValue(obj);
EXPECT_TRUE(resDefault);
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
EXPECT_EQ(50, obj.asInt());
- //Object string
+ // Object string
obj = "string";
resultType = item->validate(obj);
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
@@ -317,9 +322,10 @@ TEST(test_int_map_validate, test_NumberSchemaItemTest) {
SmartObject obj;
- ISchemaItemPtr item = TNumberSchemaItem<int>::create(
- TSchemaItemParameter<int>(-120), TSchemaItemParameter<int>(100),
- TSchemaItemParameter<int>(-38));
+ ISchemaItemPtr item =
+ TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(-120),
+ TSchemaItemParameter<int>(100),
+ TSchemaItemParameter<int>(-38));
obj["min"] = -120;
obj["out_of_min"] = -121;
@@ -337,7 +343,7 @@ TEST(test_int_map_validate, test_NumberSchemaItemTest) {
resultType = item->validate(obj);
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
- //Set default value
+ // Set default value
bool resDefault = item->setDefaultValue(obj["aa"]);
EXPECT_TRUE(resDefault);
EXPECT_EQ(-38, obj["aa"].asInt());
@@ -361,9 +367,10 @@ TEST(test_int_array_validate, test_NumberSchemaItemTest) {
SmartObject obj;
- ISchemaItemPtr item = TNumberSchemaItem<int>::create(
- TSchemaItemParameter<int>(-120), TSchemaItemParameter<int>(100),
- TSchemaItemParameter<int>(-38));
+ ISchemaItemPtr item =
+ TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(-120),
+ TSchemaItemParameter<int>(100),
+ TSchemaItemParameter<int>(-38));
obj[0] = -121;
obj[1] = -120;
@@ -411,7 +418,8 @@ TEST(test_int_array_validate, test_NumberSchemaItemTest) {
/**
* Test NumberSchemaItem as DOUBLE with no default value
*
- * Create SchemaItem without default value. Method setDefaultValue should always return false
+ * Create SchemaItem without default value. Method setDefaultValue should always
+ *return false
* and leave SmartObject in previous state.
**/
TEST(test_double_no_default_value, test_NumberSchemaItemTest) {
@@ -419,37 +427,38 @@ TEST(test_double_no_default_value, test_NumberSchemaItemTest) {
SmartObject obj;
- ISchemaItemPtr item = TNumberSchemaItem<double>::create(); // No default value, no min, no max
+ ISchemaItemPtr item =
+ TNumberSchemaItem<double>::create(); // No default value, no min, no max
- //Object int
+ // Object int
obj = 5.79;
ASSERT_EQ(5.79, obj.asDouble());
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Obj bool
+ // Obj bool
obj = true;
ASSERT_TRUE(obj.asBool());
resultType = item->validate(obj);
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
- //Set default value
+ // Set default value
bool resDefault = item->setDefaultValue(obj);
EXPECT_FALSE(resDefault);
resultType = item->validate(obj);
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
EXPECT_TRUE(obj.asBool());
- //Obj string
+ // Obj string
obj = "Test";
ASSERT_EQ(std::string("Test"), obj.asString());
resultType = item->validate(obj);
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
- //Set default value
+ // Set default value
resDefault = item->setDefaultValue(obj);
EXPECT_FALSE(resDefault);
resultType = item->validate(obj);
@@ -467,14 +476,14 @@ TEST(test_double_min_value, test_NumberSchemaItemTest) {
ISchemaItemPtr item = TNumberSchemaItem<double>::create(
TSchemaItemParameter<double>(10.0)); // No default value, no max value
- //Object double correct
+ // Object double correct
obj = 10.000001;
ASSERT_EQ(10.000001, obj.asDouble());
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object double incorrect
+ // Object double incorrect
obj = 9.999999;
ASSERT_EQ(9.999999, obj.asDouble());
@@ -498,23 +507,24 @@ TEST(test_double_max_value, test_NumberSchemaItemTest) {
SmartObject obj;
ISchemaItemPtr item = TNumberSchemaItem<double>::create(
- TSchemaItemParameter<double>(), TSchemaItemParameter<double>(749.0)); // No default value, no min value
+ TSchemaItemParameter<double>(),
+ TSchemaItemParameter<double>(749.0)); // No default value, no min value
- //Object double correct
+ // Object double correct
obj = 749.0;
ASSERT_EQ(749.0, obj.asDouble());
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object double incorrect
+ // Object double incorrect
obj = 749.0001;
ASSERT_EQ(749.0001, obj.asDouble());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
- //Object double correct
+ // Object double correct
obj = -750.0;
ASSERT_EQ(-750.0, obj.asDouble());
@@ -534,34 +544,33 @@ TEST(test_double_min_max_value, test_NumberSchemaItemTest) {
TSchemaItemParameter<double>(-949.0),
TSchemaItemParameter<double>(749.0)); // No default value
- //Object double correct
+ // Object double correct
obj = 749.0;
ASSERT_EQ(749.0, obj.asDouble());
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object double incorrect
+ // Object double incorrect
obj = 749.001;
ASSERT_EQ(749.001, obj.asDouble());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
- //Object double correct
+ // Object double correct
obj = -949.0;
ASSERT_EQ(-949.0, obj.asDouble());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object double incorrect
+ // Object double incorrect
obj = -949.00001;
ASSERT_EQ(-949.00001, obj.asDouble());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
-
}
/**
@@ -572,46 +581,47 @@ TEST(test_double_correct_default_value, test_NumberSchemaItemTest) {
SmartObject obj;
- ISchemaItemPtr item = TNumberSchemaItem<double>::create(
- TSchemaItemParameter<double>(-12000.0),
- TSchemaItemParameter<double>(100.0), TSchemaItemParameter<double>(-38.0));
+ ISchemaItemPtr item =
+ TNumberSchemaItem<double>::create(TSchemaItemParameter<double>(-12000.0),
+ TSchemaItemParameter<double>(100.0),
+ TSchemaItemParameter<double>(-38.0));
- //Object double correct
+ // Object double correct
obj = -12000.0;
ASSERT_EQ(-12000.0, obj.asDouble());
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object double incorrect
+ // Object double incorrect
obj = -12000.01;
ASSERT_EQ(-12000.01, obj.asDouble());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
- //Object double correct
+ // Object double correct
obj = 100.0;
ASSERT_EQ(100.0, obj.asDouble());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object double incorrect
+ // Object double incorrect
obj = 100.001;
ASSERT_EQ(100.001, obj.asDouble());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
- //Set default value
+ // Set default value
bool resDefault = item->setDefaultValue(obj);
EXPECT_TRUE(resDefault);
resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
EXPECT_EQ(-38.0, obj.asDouble());
- //Object string
+ // Object string
obj = "string";
resultType = item->validate(obj);
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
@@ -631,45 +641,46 @@ TEST(test_double_default_value_out_of_range, test_NumberSchemaItemTest) {
SmartObject obj;
ISchemaItemPtr item = TNumberSchemaItem<double>::create(
- TSchemaItemParameter<double>(90.0), TSchemaItemParameter<double>(100.0),
+ TSchemaItemParameter<double>(90.0),
+ TSchemaItemParameter<double>(100.0),
TSchemaItemParameter<double>(50.0)); // Default value out of range
- //Object double correct
+ // Object double correct
obj = 90.0;
ASSERT_EQ(90.0, obj.asDouble());
int resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object double incorrect
+ // Object double incorrect
obj = 89.999;
ASSERT_EQ(89.999, obj.asDouble());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
- //Object double correct
+ // Object double correct
obj = 100.0;
ASSERT_EQ(100.0, obj.asDouble());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OK, resultType);
- //Object double incorrect
+ // Object double incorrect
obj = 100.001;
ASSERT_EQ(100.001, obj.asDouble());
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
- //Set default value
+ // Set default value
bool resDefault = item->setDefaultValue(obj);
EXPECT_TRUE(resDefault);
resultType = item->validate(obj);
EXPECT_EQ(Errors::OUT_OF_RANGE, resultType);
EXPECT_EQ(50.0, obj.asDouble());
- //Object string
+ // Object string
obj = "string";
resultType = item->validate(obj);
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
@@ -685,9 +696,10 @@ TEST(test_double_map_validate, test_NumberSchemaItemTest) {
SmartObject obj;
- ISchemaItemPtr item = TNumberSchemaItem<double>::create(
- TSchemaItemParameter<double>(-120.0), TSchemaItemParameter<double>(100.0),
- TSchemaItemParameter<double>(-38.0));
+ ISchemaItemPtr item =
+ TNumberSchemaItem<double>::create(TSchemaItemParameter<double>(-120.0),
+ TSchemaItemParameter<double>(100.0),
+ TSchemaItemParameter<double>(-38.0));
obj["min"] = -120.0;
obj["out_of_min"] = -120.001;
@@ -728,9 +740,10 @@ TEST(test_double_array_validate, test_NumberSchemaItemTest) {
SmartObject obj;
- ISchemaItemPtr item = TNumberSchemaItem<double>::create(
- TSchemaItemParameter<double>(-120.0), TSchemaItemParameter<double>(100.0),
- TSchemaItemParameter<double>(-38.0));
+ ISchemaItemPtr item =
+ TNumberSchemaItem<double>::create(TSchemaItemParameter<double>(-120.0),
+ TSchemaItemParameter<double>(100.0),
+ TSchemaItemParameter<double>(-38.0));
obj[0] = -120.001;
obj[1] = -120.0;
@@ -791,7 +804,7 @@ TEST(test_int_double_value, test_NumberSchemaItemTest) {
EXPECT_EQ(Errors::INVALID_VALUE, resultType);
}
-TEST(test_double_int_value, DISABLED_test_NumberSchemaItemTest) {
+TEST(test_double_int_value, test_NumberSchemaItemTest) {
using namespace NsSmartDeviceLink::NsSmartObjects;
ISchemaItemPtr item = TNumberSchemaItem<double>::create(
diff --git a/src/components/smart_objects/test/SmartObjectConvertionTime_test.cc b/src/components/smart_objects/test/SmartObjectConvertionTime_test.cc
index f1bf1df697..d9f099afb1 100644
--- a/src/components/smart_objects/test/SmartObjectConvertionTime_test.cc
+++ b/src/components/smart_objects/test/SmartObjectConvertionTime_test.cc
@@ -1,6 +1,7 @@
-//TODO
-//this test file should be refactored. Now it doesn't test anything.
-//Previously it tests equality of objects but should test time for object's conversion
+// TODO
+// this test file should be refactored. Now it doesn't test anything.
+// Previously it tests equality of objects but should test time for object's
+// conversion
/*
* Copyright (c) 2014, Ford Motor Company
* All rights reserved.
@@ -87,32 +88,27 @@ enum eType {
}
namespace MessageTypeTest {
-enum eType {
- INVALID_ENUM = -1,
- request,
- response,
- notification
-};
+enum eType { INVALID_ENUM = -1, request, response, notification };
}
class SmartObjectConvertionTimeTest : public ::testing::Test {
protected:
-
double getConvertionTimeToJsonV2Format(const SmartObject& srcObj,
std::string& jsonString) {
timespec convertionStartTime, convertionEndTime;
clock_gettime(CLOCK_REALTIME, &convertionStartTime);
// SmartObjects --> JSON
- NsSmartDeviceLink::NsJSONHandler::Formatters::CFormatterJsonSDLRPCv2::toString(
- srcObj, jsonString);
+ NsSmartDeviceLink::NsJSONHandler::Formatters::CFormatterJsonSDLRPCv2::
+ toString(srcObj, jsonString);
clock_gettime(CLOCK_REALTIME, &convertionEndTime);
- return static_cast<double>(convertionEndTime.tv_sec
- - convertionStartTime.tv_sec)
- + static_cast<double>(convertionEndTime.tv_nsec
- - convertionStartTime.tv_nsec) * 1e-9;
+ return static_cast<double>(convertionEndTime.tv_sec -
+ convertionStartTime.tv_sec) +
+ static_cast<double>(convertionEndTime.tv_nsec -
+ convertionStartTime.tv_nsec) *
+ 1e-9;
}
double getConvertionTimeFromJsonV2Format(std::string& jsonString,
@@ -121,16 +117,20 @@ class SmartObjectConvertionTimeTest : public ::testing::Test {
clock_gettime(CLOCK_REALTIME, &convertionStartTime);
// JSON --> SmartObjects
- NsSmartDeviceLink::NsJSONHandler::Formatters::CFormatterJsonSDLRPCv2::fromString<
- FunctionIdTest::eType, MessageTypeTest::eType>(
- jsonString, dstObj, FunctionIdTest::RegisterAppInterface,
- MessageTypeTest::request, 13);
+ NsSmartDeviceLink::NsJSONHandler::Formatters::CFormatterJsonSDLRPCv2::
+ fromString<FunctionIdTest::eType, MessageTypeTest::eType>(
+ jsonString,
+ dstObj,
+ FunctionIdTest::RegisterAppInterface,
+ MessageTypeTest::request,
+ 13);
clock_gettime(CLOCK_REALTIME, &convertionEndTime);
- return static_cast<double>(convertionEndTime.tv_sec
- - convertionStartTime.tv_sec)
- + static_cast<double>(convertionEndTime.tv_nsec
- - convertionStartTime.tv_nsec) * 1e-9;
+ return static_cast<double>(convertionEndTime.tv_sec -
+ convertionStartTime.tv_sec) +
+ static_cast<double>(convertionEndTime.tv_nsec -
+ convertionStartTime.tv_nsec) *
+ 1e-9;
}
double getConvertionTimeToJsonV1Format(const SmartObject& srcObj,
@@ -139,14 +139,15 @@ class SmartObjectConvertionTimeTest : public ::testing::Test {
clock_gettime(CLOCK_REALTIME, &convertionStartTime);
// SmartObjects --> JSON
- NsSmartDeviceLink::NsJSONHandler::Formatters::CFormatterJsonSDLRPCv1::toString(
- srcObj, jsonString);
+ NsSmartDeviceLink::NsJSONHandler::Formatters::CFormatterJsonSDLRPCv1::
+ toString(srcObj, jsonString);
clock_gettime(CLOCK_REALTIME, &convertionEndTime);
- return static_cast<double>(convertionEndTime.tv_sec
- - convertionStartTime.tv_sec)
- + static_cast<double>(convertionEndTime.tv_nsec
- - convertionStartTime.tv_nsec) * 1e-9;
+ return static_cast<double>(convertionEndTime.tv_sec -
+ convertionStartTime.tv_sec) +
+ static_cast<double>(convertionEndTime.tv_nsec -
+ convertionStartTime.tv_nsec) *
+ 1e-9;
}
double getConvertionTimeFromJsonV1Format(std::string& jsonString,
@@ -155,14 +156,16 @@ class SmartObjectConvertionTimeTest : public ::testing::Test {
clock_gettime(CLOCK_REALTIME, &convertionStartTime);
// JSON --> SmartObjects
- NsSmartDeviceLink::NsJSONHandler::Formatters::CFormatterJsonSDLRPCv1::fromString<
- FunctionIdTest::eType, MessageTypeTest::eType>(jsonString, dstObj);
+ NsSmartDeviceLink::NsJSONHandler::Formatters::CFormatterJsonSDLRPCv1::
+ fromString<FunctionIdTest::eType, MessageTypeTest::eType>(jsonString,
+ dstObj);
clock_gettime(CLOCK_REALTIME, &convertionEndTime);
- return static_cast<double>(convertionEndTime.tv_sec
- - convertionStartTime.tv_sec)
- + static_cast<double>(convertionEndTime.tv_nsec
- - convertionStartTime.tv_nsec) * 1e-9;
+ return static_cast<double>(convertionEndTime.tv_sec -
+ convertionStartTime.tv_sec) +
+ static_cast<double>(convertionEndTime.tv_nsec -
+ convertionStartTime.tv_nsec) *
+ 1e-9;
}
void calculateConvertionTime(SmartObject& srcObj, SmartObject& dstObj) {
@@ -173,56 +176,60 @@ class SmartObjectConvertionTimeTest : public ::testing::Test {
for (int i = 0; i < cycles; i++) {
convertionToTime += getConvertionTimeToJsonV1Format(srcObj, jsonString);
-// printf("%s\n", jsonString.c_str());
- convertionFromTime += getConvertionTimeFromJsonV1Format(jsonString,
- dstObj);
+ // printf("%s\n", jsonString.c_str());
+ convertionFromTime +=
+ getConvertionTimeFromJsonV1Format(jsonString, dstObj);
}
printf(
"Format V1. Convertion TO time = %.8f, Convertion FROM time = %.8f\n",
- convertionToTime / cycles, convertionFromTime / cycles);
+ convertionToTime / cycles,
+ convertionFromTime / cycles);
- srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 1; // adjust protocol version
+ srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 1; // adjust protocol version
srcObj.getSchema().applySchema(dstObj, false);
// The objects are different after remove non-schemed fields
-// EXPECT_TRUE(srcObj == dstObj);
+ // EXPECT_TRUE(srcObj == dstObj);
convertionToTime = 0.0;
convertionFromTime = 0.0;
for (int i = 0; i < cycles; i++) {
convertionToTime += getConvertionTimeToJsonV2Format(srcObj, jsonString);
- convertionFromTime += getConvertionTimeFromJsonV2Format(jsonString,
- dstObj);
+ convertionFromTime +=
+ getConvertionTimeFromJsonV2Format(jsonString, dstObj);
}
printf(
"Format V2. Convertion TO time = %.8f, Convertion FROM time = %.8f\n",
- convertionToTime / cycles, convertionFromTime / cycles);
+ convertionToTime / cycles,
+ convertionFromTime / cycles);
- srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 2; // adjust protocol version
+ srcObj[S_PARAMS][S_PROTOCOL_VERSION] = 2; // adjust protocol version
dstObj.getSchema().applySchema(dstObj, false);
// The objects are different after remove non-schemed fields
-// EXPECT_TRUE(srcObj == dstObj);
+ // EXPECT_TRUE(srcObj == dstObj);
}
void calculateConvertionTimeWithJsonStringOutput(const SmartObject& srcObj,
SmartObject& dstObj) {
std::string jsonString;
- double convertionToTime = getConvertionTimeToJsonV1Format(srcObj,
- jsonString);
- double convertionFromTime = getConvertionTimeFromJsonV1Format(jsonString,
- dstObj);
+ double convertionToTime =
+ getConvertionTimeToJsonV1Format(srcObj, jsonString);
+ double convertionFromTime =
+ getConvertionTimeFromJsonV1Format(jsonString, dstObj);
printf("\nJSON string V1 = %s", jsonString.c_str());
printf(
"\nFormat V1. Convertion TO time = %.8f, Convertion FROM time = %.8f\n",
- convertionToTime, convertionFromTime);
+ convertionToTime,
+ convertionFromTime);
convertionToTime = getConvertionTimeToJsonV2Format(srcObj, jsonString);
convertionFromTime = getConvertionTimeFromJsonV2Format(jsonString, dstObj);
printf("\nJSON string V2 = %s", jsonString.c_str());
printf(
"\nFormat V2. Convertion TO time = %.8f, Convertion FROM time = %.8f\n",
- convertionToTime, convertionFromTime);
+ convertionToTime,
+ convertionFromTime);
}
// The basic Schema just for enum conversion (FunctionId and MessageType)
@@ -244,16 +251,19 @@ class SmartObjectConvertionTimeTest : public ::testing::Test {
TEnumSchemaItem<FunctionIdTest::eType>::create(
functionId_allowedEnumSubsetValues);
- ISchemaItemPtr messageType_SchemaItem = TEnumSchemaItem<
- MessageTypeTest::eType>::create(messageType_allowedEnumSubsetValues);
+ ISchemaItemPtr messageType_SchemaItem =
+ TEnumSchemaItem<MessageTypeTest::eType>::create(
+ messageType_allowedEnumSubsetValues);
CObjectSchemaItem::Members paramsMembersMap;
paramsMembersMap[NsSmartDeviceLink::NsJSONHandler::strings::S_FUNCTION_ID] =
CObjectSchemaItem::SMember(functionId_SchemaItem, true);
- paramsMembersMap[NsSmartDeviceLink::NsJSONHandler::strings::S_MESSAGE_TYPE] =
- CObjectSchemaItem::SMember(messageType_SchemaItem, true);
- paramsMembersMap[NsSmartDeviceLink::NsJSONHandler::strings::S_CORRELATION_ID] =
- CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ paramsMembersMap
+ [NsSmartDeviceLink::NsJSONHandler::strings::S_MESSAGE_TYPE] =
+ CObjectSchemaItem::SMember(messageType_SchemaItem, true);
+ paramsMembersMap
+ [NsSmartDeviceLink::NsJSONHandler::strings::S_CORRELATION_ID] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
std::map<std::string, CObjectSchemaItem::SMember> rootMembersMap;
rootMembersMap[NsSmartDeviceLink::NsJSONHandler::strings::S_PARAMS] =
@@ -263,7 +273,7 @@ class SmartObjectConvertionTimeTest : public ::testing::Test {
return CSmartSchema(CObjectSchemaItem::create(rootMembersMap));
}
- //Create SmartObjectSchema for test object
+ // Create SmartObjectSchema for test object
CSmartSchema initObjectSchema() {
std::set<TestType::eType> resultCode_allowedEnumSubsetValues;
resultCode_allowedEnumSubsetValues.insert(
@@ -292,32 +302,34 @@ class SmartObjectConvertionTimeTest : public ::testing::Test {
messageType_allowedEnumSubsetValues.insert(MessageTypeTest::response);
messageType_allowedEnumSubsetValues.insert(MessageTypeTest::notification);
- ISchemaItemPtr success_SchemaItem = CBoolSchemaItem::create(
- TSchemaItemParameter<bool>());
+ ISchemaItemPtr success_SchemaItem =
+ CBoolSchemaItem::create(TSchemaItemParameter<bool>());
ISchemaItemPtr resultCode_SchemaItem =
TEnumSchemaItem<TestType::eType>::create(
resultCode_allowedEnumSubsetValues,
TSchemaItemParameter<TestType::eType>());
- ISchemaItemPtr info_SchemaItem = CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(1000),
- TSchemaItemParameter<std::string>());
+ ISchemaItemPtr info_SchemaItem =
+ CStringSchemaItem::create(TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(1000),
+ TSchemaItemParameter<std::string>());
- ISchemaItemPtr tryAgainTime_SchemaItem = TNumberSchemaItem<int>::create(
- TSchemaItemParameter<int>(0), TSchemaItemParameter<int>(2000000000),
- TSchemaItemParameter<int>());
+ ISchemaItemPtr tryAgainTime_SchemaItem =
+ TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(0),
+ TSchemaItemParameter<int>(2000000000),
+ TSchemaItemParameter<int>());
std::map<std::string, CObjectSchemaItem::SMember> schemaMembersMap;
- schemaMembersMap["success"] = CObjectSchemaItem::SMember(success_SchemaItem,
- true);
- schemaMembersMap["resultCode"] = CObjectSchemaItem::SMember(
- resultCode_SchemaItem, true);
- schemaMembersMap["info"] = CObjectSchemaItem::SMember(info_SchemaItem,
- false);
- schemaMembersMap["tryAgainTime"] = CObjectSchemaItem::SMember(
- tryAgainTime_SchemaItem, true);
+ schemaMembersMap["success"] =
+ CObjectSchemaItem::SMember(success_SchemaItem, true);
+ schemaMembersMap["resultCode"] =
+ CObjectSchemaItem::SMember(resultCode_SchemaItem, true);
+ schemaMembersMap["info"] =
+ CObjectSchemaItem::SMember(info_SchemaItem, false);
+ schemaMembersMap["tryAgainTime"] =
+ CObjectSchemaItem::SMember(tryAgainTime_SchemaItem, true);
std::map<std::string, CObjectSchemaItem::SMember> paramsMembersMap;
paramsMembersMap[NsSmartDeviceLink::NsJSONHandler::strings::S_FUNCTION_ID] =
@@ -325,20 +337,24 @@ class SmartObjectConvertionTimeTest : public ::testing::Test {
TEnumSchemaItem<FunctionIdTest::eType>::create(
functionId_allowedEnumSubsetValues),
true);
- paramsMembersMap[NsSmartDeviceLink::NsJSONHandler::strings::S_MESSAGE_TYPE] =
- CObjectSchemaItem::SMember(
- TEnumSchemaItem<MessageTypeTest::eType>::create(
- messageType_allowedEnumSubsetValues),
- true);
- paramsMembersMap[NsSmartDeviceLink::NsJSONHandler::strings::S_CORRELATION_ID] =
- CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
- paramsMembersMap[NsSmartDeviceLink::NsJSONHandler::strings::S_PROTOCOL_VERSION] =
- CObjectSchemaItem::SMember(
- TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(1),
- TSchemaItemParameter<int>(2)),
- true);
- paramsMembersMap[NsSmartDeviceLink::NsJSONHandler::strings::S_PROTOCOL_TYPE] =
- CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ paramsMembersMap
+ [NsSmartDeviceLink::NsJSONHandler::strings::S_MESSAGE_TYPE] =
+ CObjectSchemaItem::SMember(
+ TEnumSchemaItem<MessageTypeTest::eType>::create(
+ messageType_allowedEnumSubsetValues),
+ true);
+ paramsMembersMap
+ [NsSmartDeviceLink::NsJSONHandler::strings::S_CORRELATION_ID] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
+ paramsMembersMap
+ [NsSmartDeviceLink::NsJSONHandler::strings::S_PROTOCOL_VERSION] =
+ CObjectSchemaItem::SMember(
+ TNumberSchemaItem<int>::create(TSchemaItemParameter<int>(1),
+ TSchemaItemParameter<int>(2)),
+ true);
+ paramsMembersMap
+ [NsSmartDeviceLink::NsJSONHandler::strings::S_PROTOCOL_TYPE] =
+ CObjectSchemaItem::SMember(TNumberSchemaItem<int>::create(), true);
std::map<std::string, CObjectSchemaItem::SMember> rootMembersMap;
rootMembersMap[NsSmartDeviceLink::NsJSONHandler::strings::S_MSG_PARAMS] =
@@ -535,8 +551,11 @@ TEST_F(SmartObjectConvertionTimeTest, test_array_convertion) {
calculateConvertionTime(srcObj, dstObj);
// Fourth iteration
- printf("\n Array object [%d x %d x %d x %d].\n", arraySize, arraySize,
- arraySize, arraySize);
+ printf("\n Array object [%d x %d x %d x %d].\n",
+ arraySize,
+ arraySize,
+ arraySize,
+ arraySize);
innerObj = arrayObj;
for (int i = 0; i < arraySize; i++) {
arrayObj[i] = innerObj;
@@ -552,8 +571,12 @@ TEST_F(SmartObjectConvertionTimeTest, test_array_convertion) {
calculateConvertionTime(srcObj, dstObj);
// Last iteration
- printf("\n Array object [%d x %d x %d x %d x %d].\n", arraySize, arraySize,
- arraySize, arraySize, arraySize);
+ printf("\n Array object [%d x %d x %d x %d x %d].\n",
+ arraySize,
+ arraySize,
+ arraySize,
+ arraySize,
+ arraySize);
innerObj = arrayObj;
for (int i = 0; i < arraySize; i++) {
arrayObj[i] = innerObj;
@@ -611,7 +634,6 @@ TEST_F(SmartObjectConvertionTimeTest, test_object_without_enum_convertion) {
printf("\n Object without enum.\n");
calculateConvertionTime(srcObj, dstObj);
}
-
}
}
}
@@ -620,95 +642,144 @@ TEST_F(SmartObjectConvertionTimeTest, test_object_without_enum_convertion) {
namespace NsSmartDeviceLink {
namespace NsSmartObjects {
-template<>
-const EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::eType>::EnumToCStringMap EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::eType>::enum_to_cstring_map_ =
- EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::eType>::InitEnumToCStringMap();
-
-template<>
-const EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::eType>::CStringToEnumMap EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::eType>::cstring_to_enum_map_ =
- EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::eType>::InitCStringToEnumMap();
-
-template<>
+template <>
+const EnumConversionHelper<test::components::SmartObjects::
+ SmartObjectConvertionTimeTest::TestType::eType>::
+ EnumToCStringMap EnumConversionHelper<
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::eType>::enum_to_cstring_map_ =
+ EnumConversionHelper<
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::eType>::InitEnumToCStringMap();
+
+template <>
+const EnumConversionHelper<test::components::SmartObjects::
+ SmartObjectConvertionTimeTest::TestType::eType>::
+ CStringToEnumMap EnumConversionHelper<
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::eType>::cstring_to_enum_map_ =
+ EnumConversionHelper<
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::eType>::InitCStringToEnumMap();
+
+template <>
const char* const EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::eType>::cstring_values_[] =
- { "APPLICATION_NOT_REGISTERED", "SUCCESS", "TOO_MANY_PENDING_REQUESTS",
- "REJECTED", "INVALID_DATA", "OUT_OF_MEMORY", "ABORTED",
- "USER_DISALLOWED", "GENERIC_ERROR", "DISALLOWED" };
-
-template<>
-const test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::eType EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::eType>::enum_values_[] =
- {
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::APPLICATION_NOT_REGISTERED,
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::SUCCESS,
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::TOO_MANY_PENDING_REQUESTS,
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::REJECTED,
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::INVALID_DATA,
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::OUT_OF_MEMORY,
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::ABORTED,
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::USER_DISALLOWED,
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::GENERIC_ERROR,
- test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::DISALLOWED };
-
-template<>
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::
+ eType>::cstring_values_[] = {"APPLICATION_NOT_REGISTERED",
+ "SUCCESS",
+ "TOO_MANY_PENDING_REQUESTS",
+ "REJECTED",
+ "INVALID_DATA",
+ "OUT_OF_MEMORY",
+ "ABORTED",
+ "USER_DISALLOWED",
+ "GENERIC_ERROR",
+ "DISALLOWED"};
+
+template <>
+const test::components::SmartObjects::SmartObjectConvertionTimeTest::TestType::
+ eType EnumConversionHelper<
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::eType>::enum_values_[] = {
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::APPLICATION_NOT_REGISTERED,
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::SUCCESS,
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::TOO_MANY_PENDING_REQUESTS,
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::REJECTED,
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::INVALID_DATA,
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::OUT_OF_MEMORY,
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::ABORTED,
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::USER_DISALLOWED,
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::GENERIC_ERROR,
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ TestType::DISALLOWED};
+
+template <>
const EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::FunctionIdTest::eType>::EnumToCStringMap EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::FunctionIdTest::eType>::enum_to_cstring_map_ =
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ FunctionIdTest::eType>::EnumToCStringMap
EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::FunctionIdTest::eType>::InitEnumToCStringMap();
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ FunctionIdTest::eType>::enum_to_cstring_map_ =
+ EnumConversionHelper<
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ FunctionIdTest::eType>::InitEnumToCStringMap();
-template<>
+template <>
const EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::FunctionIdTest::eType>::CStringToEnumMap EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::FunctionIdTest::eType>::cstring_to_enum_map_ =
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ FunctionIdTest::eType>::CStringToEnumMap
EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::FunctionIdTest::eType>::InitCStringToEnumMap();
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ FunctionIdTest::eType>::cstring_to_enum_map_ =
+ EnumConversionHelper<
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ FunctionIdTest::eType>::InitCStringToEnumMap();
-template<>
+template <>
const char* const EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::FunctionIdTest::eType>::cstring_values_[] =
- { "RegisterAppInterface", "UnregisterAppInterface", "SetGlobalProperties" };
-
-template<>
-const test::components::SmartObjects::SmartObjectConvertionTimeTest::FunctionIdTest::eType EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::FunctionIdTest::eType>::enum_values_[] =
- {
- test::components::SmartObjects::SmartObjectConvertionTimeTest::FunctionIdTest::RegisterAppInterface,
- test::components::SmartObjects::SmartObjectConvertionTimeTest::FunctionIdTest::UnregisterAppInterface,
- test::components::SmartObjects::SmartObjectConvertionTimeTest::FunctionIdTest::SetGlobalProperties };
-
-template<>
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ FunctionIdTest::eType>::cstring_values_[] = {
+ "RegisterAppInterface", "UnregisterAppInterface", "SetGlobalProperties"};
+
+template <>
+const test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ FunctionIdTest::eType EnumConversionHelper<
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ FunctionIdTest::eType>::enum_values_[] = {
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ FunctionIdTest::RegisterAppInterface,
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ FunctionIdTest::UnregisterAppInterface,
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ FunctionIdTest::SetGlobalProperties};
+
+template <>
const EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::MessageTypeTest::eType>::EnumToCStringMap EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::MessageTypeTest::eType>::enum_to_cstring_map_ =
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ MessageTypeTest::eType>::EnumToCStringMap
EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::MessageTypeTest::eType>::InitEnumToCStringMap();
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ MessageTypeTest::eType>::enum_to_cstring_map_ =
+ EnumConversionHelper<
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ MessageTypeTest::eType>::InitEnumToCStringMap();
-template<>
+template <>
const EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::MessageTypeTest::eType>::CStringToEnumMap EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::MessageTypeTest::eType>::cstring_to_enum_map_ =
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ MessageTypeTest::eType>::CStringToEnumMap
EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::MessageTypeTest::eType>::InitCStringToEnumMap();
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ MessageTypeTest::eType>::cstring_to_enum_map_ =
+ EnumConversionHelper<
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ MessageTypeTest::eType>::InitCStringToEnumMap();
-template<>
+template <>
const char* const EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::MessageTypeTest::eType>::cstring_values_[] =
- { "request", "response", "notification" };
-
-template<>
-const test::components::SmartObjects::SmartObjectConvertionTimeTest::MessageTypeTest::eType EnumConversionHelper<
- test::components::SmartObjects::SmartObjectConvertionTimeTest::MessageTypeTest::eType>::enum_values_[] =
- {
- test::components::SmartObjects::SmartObjectConvertionTimeTest::MessageTypeTest::request,
- test::components::SmartObjects::SmartObjectConvertionTimeTest::MessageTypeTest::response,
- test::components::SmartObjects::SmartObjectConvertionTimeTest::MessageTypeTest::notification };
-
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ MessageTypeTest::eType>::cstring_values_[] = {
+ "request", "response", "notification"};
+
+template <>
+const test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ MessageTypeTest::eType EnumConversionHelper<
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ MessageTypeTest::eType>::enum_values_[] = {
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ MessageTypeTest::request,
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ MessageTypeTest::response,
+ test::components::SmartObjects::SmartObjectConvertionTimeTest::
+ MessageTypeTest::notification};
}
}
diff --git a/src/components/smart_objects/test/SmartObjectDraft_test.cc b/src/components/smart_objects/test/SmartObjectDraft_test.cc
index 85c97c2625..2932a68167 100644
--- a/src/components/smart_objects/test/SmartObjectDraft_test.cc
+++ b/src/components/smart_objects/test/SmartObjectDraft_test.cc
@@ -190,7 +190,7 @@ TEST(SmartObjectsDraftTest, test_helper_methods) {
// ---- DOUBLE ---- //
obj = 3.14;
ASSERT_EQ(3.14, obj.asDouble());
- //TEST_COMPONENTS_SMART_OBJECTS_SMARTOBJECTDRAFTTEST_H_
+ // TEST_COMPONENTS_SMART_OBJECTS_SMARTOBJECTDRAFTTEST_H_
// ---- CHAR ---- //
obj = 'a';
ASSERT_EQ('a', obj.asChar());
@@ -358,7 +358,7 @@ TEST(SmartObjectsDraftTest, compare_map_type) {
ASSERT_NE(other_value2, SmartObject());
}
// TODO(Ezamakhov): add test for conversion string/int/double
-}// namespace SmartObjectDraftTest
+} // namespace SmartObjectDraftTest
} // namespace SmartObjects
} // namespace components
} // namespace test
diff --git a/src/components/smart_objects/test/SmartObjectStress_test.cc b/src/components/smart_objects/test/SmartObjectStress_test.cc
index 4fb7b2efc0..da6e804e2b 100644
--- a/src/components/smart_objects/test/SmartObjectStress_test.cc
+++ b/src/components/smart_objects/test/SmartObjectStress_test.cc
@@ -59,11 +59,14 @@ class StressTestHelper : public ::testing::Test {
std::string to_string(const double value) const {
// Content is the same as in SmartObject::convert_double_to_string
std::stringstream ss;
- ss << std::fixed << std::setprecision(10) << value; //convert double to string w fixed notation, hi precision
- std::string s = ss.str(); //output to std::string
- s.erase(s.find_last_not_of('0') + 1, std::string::npos); //remove trailing 000s (123.1200 => 123.12, 123.000 => 123.)
+ ss << std::fixed << std::setprecision(10)
+ << value; // convert double to string w fixed notation, hi precision
+ std::string s = ss.str(); // output to std::string
+ s.erase(s.find_last_not_of('0') + 1,
+ std::string::npos); // remove trailing 000s (123.1200 => 123.12,
+ // 123.000 => 123.)
if (s[s.size() - 1] == '.') {
- s.erase(s.end() - 1); //remove dangling decimal (123. => 123)
+ s.erase(s.end() - 1); // remove dangling decimal (123. => 123)
}
return s;
}
@@ -82,8 +85,8 @@ class StressTestHelper : public ::testing::Test {
typedef std::map<std::string, std::string> VerificationMap;
VerificationMap mVerifyMap;
- std::vector<std::string> split(const std::string &s, char delim) const {
- std::vector < std::string > elems;
+ std::vector<std::string> split(const std::string& s, char delim) const {
+ std::vector<std::string> elems;
std::stringstream ss(s);
std::string item;
@@ -94,62 +97,63 @@ class StressTestHelper : public ::testing::Test {
return elems;
}
- std::string generate_key(const char *pPrefix, const int index) const {
+ std::string generate_key(const char* pPrefix, const int index) const {
char buff[32];
sprintf(buff, "%s%d", pPrefix, index);
return std::string(buff);
}
- void makeRandomObject(SmartObject &obj, const int size,
+ void makeRandomObject(SmartObject& obj,
+ const int size,
std::string key_path) {
int type_id = rand() % 8;
switch (type_id) {
- case 0: // int
+ case 0: // int
{
int iVal = rand();
obj = iVal;
mVerifyMap[key_path] = to_string(iVal);
- //std::cout << "Created int, value: " << iVal << std::endl;
+ // std::cout << "Created int, value: " << iVal << std::endl;
break;
}
- case 1: // bool
+ case 1: // bool
{
bool bVal = static_cast<bool>(rand() % 2);
obj = bVal;
mVerifyMap[key_path] = to_string(bVal);
- //std::cout << "Created bool, value: " << to_string(bVal) << std::endl;
+ // std::cout << "Created bool, value: " << to_string(bVal) << std::endl;
break;
}
- case 2: // double
+ case 2: // double
{
double dVal = 100.0 / (rand() % 200);
obj = dVal;
mVerifyMap[key_path] = to_string(dVal);
- //std::cout << "Created double, value: " << dVal << std::endl;
+ // std::cout << "Created double, value: " << dVal << std::endl;
break;
}
- case 3: // char
+ case 3: // char
{
char cVal = get_random_char();
obj = cVal;
mVerifyMap[key_path] = to_string(cVal);
- //std::cout << "Created char, value: " << cVal << std::endl;
+ // std::cout << "Created char, value: " << cVal << std::endl;
break;
}
- case 4: // string
+ case 4: // string
{
std::string strVal(rand() % 200, get_random_char());
- obj = strVal; // string with random char filled random size
+ obj = strVal; // string with random char filled random size
mVerifyMap[key_path] = strVal;
- //std::cout << "Created string, value: " << strVal << std::endl;
+ // std::cout << "Created string, value: " << strVal << std::endl;
break;
}
- case 5: // map
+ case 5: // map
if (size <= 0)
break;
- //std::cout << "Creating a map with size: " << size << std::endl;
+ // std::cout << "Creating a map with size: " << size << std::endl;
mVerifyMap[key_path] = "map";
for (int i = 0; i < size; i++) {
std::string key = generate_key("M", i);
@@ -157,23 +161,25 @@ class StressTestHelper : public ::testing::Test {
obj[key] = key;
#else
obj[key] = SmartObject();
- makeRandomObject(obj[key], size - 1, key_path + key + ' '); // recursion
-#endif // MAP_WORKAROUND
+ makeRandomObject(
+ obj[key], size - 1, key_path + key + ' '); // recursion
+#endif // MAP_WORKAROUND
}
break;
- case 6: // array
+ case 6: // array
if (size <= 0)
break;
- //std::cout << "Creating an array with size: " << size << std::endl;
+ // std::cout << "Creating an array with size: " << size << std::endl;
mVerifyMap[key_path] = "array";
for (int i = 0; i < size; i++) {
- obj[i] = SmartObject(); // just init it as an array
- makeRandomObject(obj[i], size - 1,
+ obj[i] = SmartObject(); // just init it as an array
+ makeRandomObject(obj[i],
+ size - 1,
key_path + generate_key("A", i) + ' '); // recursion
}
break;
- case 7: // binary
+ case 7: // binary
int dataSize = rand() % 200;
char randomChar = get_random_char();
std::string strDataVal(dataSize, randomChar);
@@ -183,37 +189,38 @@ class StressTestHelper : public ::testing::Test {
NsSmartDeviceLink::NsSmartObjects::SmartBinary binaryVal(dataSize,
randomChar);
- obj = binaryVal; // string with binary data filled with random chars
+ obj = binaryVal; // string with binary data filled with random chars
mVerifyMap[key_path] = strVal;
- //std::cout << "Created string, value: " << strVal << std::endl;
+ // std::cout << "Created string, value: " << strVal << std::endl;
break;
}
}
- SmartObject get_object(SmartObject &rootObj, const std::string &path) const {
- std::vector < std::string > obj_tokens;
+ SmartObject get_object(SmartObject& rootObj, const std::string& path) const {
+ std::vector<std::string> obj_tokens;
SmartObject lastObj = rootObj;
obj_tokens = split(path, ' ');
for (size_t i = 0; i < obj_tokens.size(); i++) {
- if (obj_tokens[i][0] == 'A') // array
- {
- int index = atoi(&(obj_tokens[i].c_str()[1])); // get integer skipping first char
+ if (obj_tokens[i][0] == 'A') // array
+ {
+ int index = atoi(
+ &(obj_tokens[i].c_str()[1])); // get integer skipping first char
#ifdef COPY_SUB_OBJECTS_WORKAROUND
- lastObj = SmartObject(lastObj[index]);
+ lastObj = SmartObject(lastObj[index]);
#else
- lastObj = lastObj[index]; // go to the child object
+ lastObj = lastObj[index]; // go to the child object
#endif
- } else if (obj_tokens[i][0] == 'M') // map
- {
+ } else if (obj_tokens[i][0] == 'M') // map
+ {
#ifdef COPY_SUB_OBJECTS_WORKAROUND
lastObj = SmartObject(lastObj[obj_tokens[i]]);
#else
- lastObj = lastObj[obj_tokens[i]]; // go to the child object
+ lastObj = lastObj[obj_tokens[i]]; // go to the child object
#endif
} else {
- //FAIL();
+ // FAIL();
EXPECT_TRUE(false);
}
}
@@ -222,11 +229,14 @@ class StressTestHelper : public ::testing::Test {
};
/*
- * The test creates the initial SmartObject and use it as an array for the next SmartObjects.
+ * The test creates the initial SmartObject and use it as an array for the next
+ * SmartObjects.
* Each next SmartObject is randomly assigned to some type.
- * If one of the object happens to be a container it fills it with SmartObject of random type. The amount of these
+ * If one of the object happens to be a container it fills it with SmartObject
+ * of random type. The amount of these
* objects is the size of the parent container -1.
- * The iteration continues until all nodes are simple SmartObjects (not arrays or maps)
+ * The iteration continues until all nodes are simple SmartObjects (not arrays
+ * or maps)
*/
TEST_F(StressTestHelper, StressTest) {
SmartObject objects;
@@ -242,7 +252,8 @@ TEST_F(StressTestHelper, StressTest) {
}
for (VerificationMap::const_iterator it = mVerifyMap.begin();
- it != mVerifyMap.end(); it++) {
+ it != mVerifyMap.end();
+ it++) {
std::string value(it->second);
SmartObject obj = get_object(objects, it->first);
@@ -264,8 +275,8 @@ TEST_F(StressTestHelper, StressTest) {
ASSERT_EQ(NsSmartDeviceLink::NsSmartObjects::SmartType_Binary,
obj.getType());
- NsSmartDeviceLink::NsSmartObjects::SmartBinary binaryData = obj
- .asBinary();
+ NsSmartDeviceLink::NsSmartObjects::SmartBinary binaryData =
+ obj.asBinary();
ASSERT_EQ(etalonData.size(), binaryData.size());
for (size_t i = 0; i < etalonData.size(); ++i) {
@@ -280,25 +291,27 @@ TEST_F(StressTestHelper, StressTest) {
}
#ifdef NO_INCLUSIVE_MAPS
- if (!value.compare("map"))
- {
+ if (!value.compare("map")) {
std::vector<std::string> path = split(it->first, ' ');
- std::string map_value = path[path.size()-1];
+ std::string map_value = path[path.size() - 1];
ASSERT_EQ(map_value, static_cast<std::string>(obj));
continue;
}
#endif
if (value.compare("map") && value.compare("array")) {
- //std::cout << "Verification key: " << it->first << " Value: " << value << std::endl;
- //std::cout << "Object Value: " << static_cast<std::string>(obj) << std::endl;
+ // std::cout << "Verification key: " << it->first << " Value: " << value
+ // << std::endl;
+ // std::cout << "Object Value: " << static_cast<std::string>(obj) <<
+ // std::endl;
if (!value.compare("true")) {
ASSERT_TRUE(obj.asBool());
} else if (!value.compare("false")) {
ASSERT_FALSE(obj.asBool());
} else {
- ASSERT_EQ(value, obj.asString())<< "Object value is not correct. Object path: " << it->first;
+ ASSERT_EQ(value, obj.asString())
+ << "Object value is not correct. Object path: " << it->first;
}
}
}
@@ -314,22 +327,22 @@ TEST_F(StressTestHelper, ExtraManualDebugTest) {
obj[4] = true;
obj[5] = 3.704;
obj[6] = SmartObject();
- obj[6][0] =
- std::string(
- "ttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt");
+ obj[6][0] = std::string(
+ "tttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttttt"
+ "ttttttttttttttttt");
obj[6][1] = 'K';
obj[6][2] = 0.735294;
obj[6][3] = 'I';
obj[6][4] = SmartObject();
obj[6][4]["M0"] = 0.59432;
- SmartObject & refObj = obj[6][4];
+ SmartObject& refObj = obj[6][4];
refObj["M1"]["M0"]["M0"][0] = true;
- // FIXME: Figure out why there's a trailing zero while converting from double to string
+ // FIXME: Figure out why there's a trailing zero while converting from double
+ // to string
ASSERT_EQ("0.59432", get_object(obj, "A6 A4 M0").asString());
ASSERT_TRUE(get_object(obj, "A6 A4 M1 M0 M0 A0").asBool());
}
-
}
}
}
diff --git a/src/components/smart_objects/test/SmartObjectUnit_test.cc b/src/components/smart_objects/test/SmartObjectUnit_test.cc
index d1d790f9d4..cd5cd0c131 100644
--- a/src/components/smart_objects/test/SmartObjectUnit_test.cc
+++ b/src/components/smart_objects/test/SmartObjectUnit_test.cc
@@ -42,7 +42,6 @@ using namespace NsSmartDeviceLink::NsSmartObjects;
class TestHelper : public ::testing::Test {
protected:
-
void makeMapObject(SmartObject& obj, const int size) const {
char i_key[8], j_key[8], k_key[8], value[8];
@@ -68,51 +67,54 @@ class TestHelper : public ::testing::Test {
sprintf(k_key, "k_%d", k);
sprintf(value, "%d", i + j + k);
- ASSERT_EQ(std::string(value), obj[i_key][j_key][k_key].asString())<<
- "Wrong value in the map at [" << i_key << "][" << j_key << "][" << k_key << "]";
+ ASSERT_EQ(std::string(value), obj[i_key][j_key][k_key].asString())
+ << "Wrong value in the map at [" << i_key << "][" << j_key << "]["
+ << k_key << "]";
}
- }
+ }
- void makeArrayObject(SmartObject& obj, int size, int base = 0) {
- for (int i = 0; i < size; i++)
- for (int j = 0; j < size; j++)
+ void makeArrayObject(SmartObject& obj, int size, int base = 0) {
+ for (int i = 0; i < size; i++)
+ for (int j = 0; j < size; j++)
for (int k = 0; k < size; k++) {
obj[i][j][k] = base + i + j + k;
}
- }
+ }
- void checkArrayObject(SmartObject& obj, int size, int base = 0) {
- for (int i = 0; i < size; i++)
- for (int j = 0; j < size; j++)
+ void checkArrayObject(SmartObject& obj, int size, int base = 0) {
+ for (int i = 0; i < size; i++)
+ for (int j = 0; j < size; j++)
for (int k = 0; k < size; k++) {
- ASSERT_EQ(base + i + j + k, obj[i][j][k].asInt()) <<
- "Wrong value in the array at index: " << i << ", " << j << ", " << k;
+ ASSERT_EQ(base + i + j + k, obj[i][j][k].asInt())
+ << "Wrong value in the array at index: " << i << ", " << j << ", "
+ << k;
}
- }
- };
+ }
+};
- /*
- * Tests different types sequentially
- */
+/*
+ * Tests different types sequentially
+ */
TEST(BasicMixtedTypes, test_SmartObjectUnitTest) {
SmartObject obj;
- ASSERT_EQ(invalid_int_value, obj.asInt())<< "Wrong cast to int just after construction";
+ ASSERT_EQ(invalid_int_value, obj.asInt())
+ << "Wrong cast to int just after construction";
obj = 10;
- ASSERT_EQ(10, obj.asInt())<< "Wrong cast to int";
+ ASSERT_EQ(10, obj.asInt()) << "Wrong cast to int";
obj = "some string";
- ASSERT_EQ("some string", obj.asString())<< "Wrong cast to std::string";
+ ASSERT_EQ("some string", obj.asString()) << "Wrong cast to std::string";
obj = false;
- ASSERT_FALSE(obj.asBool())<< "Wrong cast to bool";
+ ASSERT_FALSE(obj.asBool()) << "Wrong cast to bool";
obj = 'A';
- ASSERT_EQ('A', obj.asChar())<< "Wrong cast to char";
+ ASSERT_EQ('A', obj.asChar()) << "Wrong cast to char";
obj = 3.14;
- ASSERT_EQ(3.14, obj.asDouble())<< "Wrong cast to double";
+ ASSERT_EQ(3.14, obj.asDouble()) << "Wrong cast to double";
// array test
for (int i = 0; i < 100; i++) {
@@ -132,23 +134,23 @@ TEST(BasicMixtedTypes, test_SmartObjectUnitTest) {
TEST_F(TestHelper, BasicArrayTest) {
SmartObject obj;
- ASSERT_EQ(invalid_int_value,
- obj[0].asInt())<< "Wrong value at accessing non existent index";
- ASSERT_EQ(invalid_int_value,
- obj["non_existent_key"].asInt())<< "Wrong value at accessing non existent key";
+ ASSERT_EQ(invalid_int_value, obj[0].asInt())
+ << "Wrong value at accessing non existent index";
+ ASSERT_EQ(invalid_int_value, obj["non_existent_key"].asInt())
+ << "Wrong value at accessing non existent key";
obj[0] = 1;
- ASSERT_EQ(1, obj[0].asInt())<< "Wrong value at 0 index";
+ ASSERT_EQ(1, obj[0].asInt()) << "Wrong value at 0 index";
obj[1] = 2;
- ASSERT_EQ(2, obj[1].asInt())<< "Wrong value at 1 index";
+ ASSERT_EQ(2, obj[1].asInt()) << "Wrong value at 1 index";
obj[0][0] = 3;
obj[1][0] = 1;
- ASSERT_EQ(3, obj[0][0].asInt())<< "Wrong value at index 0, 0";
+ ASSERT_EQ(3, obj[0][0].asInt()) << "Wrong value at index 0, 0";
obj[0][0][0] = 4;
obj[0][1][0] = 5;
- ASSERT_EQ(4, obj[0][0][0].asInt())<< "Wrong value at index 0, 0, 0";
+ ASSERT_EQ(4, obj[0][0][0].asInt()) << "Wrong value at index 0, 0, 0";
const int size = 32;
makeArrayObject(obj, size);
@@ -159,16 +161,17 @@ TEST_F(TestHelper, BasicArrayTest) {
TEST_F(TestHelper, BasicMapTest) {
SmartObject obj;
- ASSERT_EQ(invalid_int_value,
- obj["non_existent_key"].asInt())<< "Wrong value for non existent key";
+ ASSERT_EQ(invalid_int_value, obj["non_existent_key"].asInt())
+ << "Wrong value for non existent key";
obj["abc"]["def"]["ghi"] = 5;
- ASSERT_EQ(5, obj["abc"]["def"]["ghi"].asInt())<< "Wrong value for triple map";
+ ASSERT_EQ(5, obj["abc"]["def"]["ghi"].asInt())
+ << "Wrong value for triple map";
obj["123"]["456"]["789"] = "string test";
- ASSERT_EQ("string test", obj["123"]["456"]["789"].asString())<<
- "Wrong value for triple map";
+ ASSERT_EQ("string test", obj["123"]["456"]["789"].asString())
+ << "Wrong value for triple map";
const int size = 32;
@@ -179,33 +182,36 @@ TEST_F(TestHelper, BasicMapTest) {
TEST(ConstructorsTest, test_SmartObjectUnitTest) {
SmartObject objInt(5678);
- ASSERT_EQ(5678, objInt.asInt())<< "Wrong constructor with int param";
+ ASSERT_EQ(5678, objInt.asInt()) << "Wrong constructor with int param";
const char* c_str = "test c_string";
SmartObject obj_c_str(c_str);
- ASSERT_EQ("test c_string", obj_c_str.asString())<< "Wrong constructor with c_str param";
+ ASSERT_EQ("test c_string", obj_c_str.asString())
+ << "Wrong constructor with c_str param";
SmartObject obj_std_str(std::string("test std_string"));
ASSERT_EQ(std::string("test std_string"), obj_std_str.asString());
SmartObject obj_char('R');
- ASSERT_EQ('R', obj_char.asChar())<< "Wrong constructor with char param";
+ ASSERT_EQ('R', obj_char.asChar()) << "Wrong constructor with char param";
SmartObject obj_double(-0.4321);
- ASSERT_EQ(-0.4321, obj_double.asDouble())<< "Wrong constructor with double param";
+ ASSERT_EQ(-0.4321, obj_double.asDouble())
+ << "Wrong constructor with double param";
SmartObject obj_bool(true);
- ASSERT_TRUE(obj_bool.asBool())<< "Wrong constructor with bool param";
+ ASSERT_TRUE(obj_bool.asBool()) << "Wrong constructor with bool param";
SmartObject src_obj;
- src_obj["key_1"] = "value_1"; // FIXME: String assignment crashes test
+ src_obj["key_1"] = "value_1"; // FIXME: String assignment crashes test
src_obj["key_2"]["sub_key_1"] = "value_2";
SmartObject dst_obj(src_obj);
- ASSERT_EQ("value_1", dst_obj["key_1"].asString())<< "Copy constructor is not correct";
- ASSERT_EQ("value_2", dst_obj["key_2"]["sub_key_1"].asString())<<
- "Copy constructor is not correct";
+ ASSERT_EQ("value_1", dst_obj["key_1"].asString())
+ << "Copy constructor is not correct";
+ ASSERT_EQ("value_2", dst_obj["key_2"]["sub_key_1"].asString())
+ << "Copy constructor is not correct";
}
TEST(FromString, TypeConversion) {
@@ -379,7 +385,7 @@ TEST(FromDouble, TypeConversion) {
SmartObject obj;
obj = 0.1;
- ASSERT_EQ("0.1", obj.asString()); // FIXME: result 0.100000
+ ASSERT_EQ("0.1", obj.asString()); // FIXME: result 0.100000
ASSERT_EQ(0, obj.asInt());
ASSERT_EQ(invalid_char_value, obj.asChar());
ASSERT_EQ(0.1, obj.asDouble());
@@ -438,23 +444,23 @@ TEST_F(TestHelper, AssignmentTest) {
objSrc = -6;
objDst = 7;
objDst = objSrc;
- ASSERT_EQ(-6, objDst.asInt())<< "Wrong assignment for int object";
+ ASSERT_EQ(-6, objDst.asInt()) << "Wrong assignment for int object";
objSrc = "Some test string";
objDst = "Other string";
objDst = objSrc;
- ASSERT_EQ("Some test string",
- objDst.asString())<< "Wrong assignment for std::string object";
+ ASSERT_EQ("Some test string", objDst.asString())
+ << "Wrong assignment for std::string object";
objSrc = 0.5;
objDst = 4;
objDst = objSrc;
- ASSERT_EQ(0.5, objDst.asDouble())<< "Wrong assignment for double object";
+ ASSERT_EQ(0.5, objDst.asDouble()) << "Wrong assignment for double object";
objSrc = true;
objDst = false;
objDst = objSrc;
- ASSERT_TRUE(objDst.asBool())<< "Wrong assignment for bool object";
+ ASSERT_TRUE(objDst.asBool()) << "Wrong assignment for bool object";
const int size = 32;
makeMapObject(objSrc, size);
@@ -471,30 +477,30 @@ TEST_F(TestHelper, AssignmentTest) {
TEST_F(TestHelper, SizeTest) {
SmartObject obj;
- ASSERT_EQ(0u, obj.length())<< "Wrong size for the uninitialized object";
+ ASSERT_EQ(0u, obj.length()) << "Wrong size for the uninitialized object";
obj = 1234;
- ASSERT_EQ(0u, obj.length())<< "Wrong size for the int object";
+ ASSERT_EQ(0u, obj.length()) << "Wrong size for the int object";
std::string str("Some test very long string");
obj = str;
- ASSERT_EQ(str.size(), obj.length())<<
- "The size of the object containing string is not correct";
+ ASSERT_EQ(str.size(), obj.length())
+ << "The size of the object containing string is not correct";
obj = true;
- ASSERT_EQ(0u, obj.length())<< "Wrong size of the true";
+ ASSERT_EQ(0u, obj.length()) << "Wrong size of the true";
obj = 0.1234;
- ASSERT_EQ(0u, obj.length())<< "Wrong size of the double";
+ ASSERT_EQ(0u, obj.length()) << "Wrong size of the double";
obj = 'A';
- ASSERT_EQ(0u, obj.length())<< "Wrong size of the char";
+ ASSERT_EQ(0u, obj.length()) << "Wrong size of the char";
makeMapObject(obj, 12);
- ASSERT_EQ(12u, obj.length())<< "Wrong size of the object containing map";
+ ASSERT_EQ(12u, obj.length()) << "Wrong size of the object containing map";
makeArrayObject(obj, 21);
- ASSERT_EQ(21u, obj.length())<< "Wrong size of the object containing array";
+ ASSERT_EQ(21u, obj.length()) << "Wrong size of the object containing array";
}
TEST(CopyObjectsTest, SmartObjectTest) {
@@ -537,7 +543,8 @@ TEST(MapEraseTest, SmartObjectTest) {
ASSERT_EQ(2u, srcObj.length());
ASSERT_EQ(-1, srcObj["two"].asInt());
- // The element "two" was accessed in the previous line so the element has been created
+ // The element "two" was accessed in the previous line so the element has been
+ // created
ASSERT_EQ(3u, srcObj.length());
srcObj["two"] = 2;
@@ -574,11 +581,11 @@ TEST(MapEraseTest, SmartObjectTest) {
ASSERT_TRUE(srcObj["one"].erase("two"));
ASSERT_EQ(0u, srcObj["one"].length());
- srcObj = 1234; // not a map
+ srcObj = 1234; // not a map
ASSERT_FALSE(srcObj.erase("one"));
}
// TODO: Add a test to check accessing an array at strange indexes.
-}// namespace SmartObjectUnitTest
+} // namespace SmartObjectUnitTest
} // namespace SmartObjects
} // namespace components
} // namespace test
diff --git a/src/components/smart_objects/test/StringSchemaItem_test.cc b/src/components/smart_objects/test/StringSchemaItem_test.cc
index 5fe179a7e1..c5c2b4dee0 100644
--- a/src/components/smart_objects/test/StringSchemaItem_test.cc
+++ b/src/components/smart_objects/test/StringSchemaItem_test.cc
@@ -45,16 +45,18 @@ namespace SchemaItem {
/**
* Test StringSchemaItem no default value
*
- * Create SchemaItem without default value. Method setDefaultValue should always return false
+ * Create SchemaItem without default value. Method setDefaultValue should always
+ *return false
* and leave SmartObject in previous state.
**/
TEST(test_no_default_value, test_StringSchemaItemTest) {
using namespace NsSmartDeviceLink::NsSmartObjects;
SmartObject obj;
- ISchemaItemPtr item = CStringSchemaItem::create(); // No default value, no max length
+ ISchemaItemPtr item =
+ CStringSchemaItem::create(); // No default value, no max length
- //Object - valid string
+ // Object - valid string
obj = "New valid string";
ASSERT_EQ(std::string("New valid string"), obj.asString());
@@ -64,7 +66,7 @@ TEST(test_no_default_value, test_StringSchemaItemTest) {
EXPECT_FALSE(resDefault);
EXPECT_EQ(std::string("New valid string"), obj.asString());
- //Obj - bool
+ // Obj - bool
obj = true;
resultType = item->validate(obj);
@@ -73,7 +75,7 @@ TEST(test_no_default_value, test_StringSchemaItemTest) {
EXPECT_FALSE(resDefault);
EXPECT_TRUE(obj.asBool());
- //Object - number
+ // Object - number
obj = 3.1415926;
resultType = item->validate(obj);
@@ -89,19 +91,23 @@ TEST(test_no_default_value, test_StringSchemaItemTest) {
/**
* Test StringSchemaItem with default value
*
- * Create SchemaItem with default value. Method setDefaultValue should return true,
+ * Create SchemaItem with default value. Method setDefaultValue should return
+ *true,
* String SmartObject should contain default value.
- * Not string SmartObject should converted to StringObject and setted up by the default value.
+ * Not string SmartObject should converted to StringObject and setted up by the
+ *default value.
**/
TEST(test_item_with_default_value, test_StringSchemaItemTest) {
using namespace NsSmartDeviceLink::NsSmartObjects;
SmartObject obj;
ISchemaItemPtr item = CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(), TSchemaItemParameter<size_t>(),
- TSchemaItemParameter<std::string>("Default string")); // Default value, no max length
+ TSchemaItemParameter<size_t>(),
+ TSchemaItemParameter<size_t>(),
+ TSchemaItemParameter<std::string>(
+ "Default string")); // Default value, no max length
- //Object - valid string
+ // Object - valid string
obj = "New valid string";
ASSERT_EQ(std::string("New valid string"), obj.asString());
@@ -111,7 +117,7 @@ TEST(test_item_with_default_value, test_StringSchemaItemTest) {
EXPECT_TRUE(resDefault);
EXPECT_EQ(std::string("Default string"), obj.asString());
- //Obj - bool
+ // Obj - bool
obj = true;
resultType = item->validate(obj);
@@ -120,7 +126,7 @@ TEST(test_item_with_default_value, test_StringSchemaItemTest) {
EXPECT_TRUE(resDefault);
EXPECT_EQ(std::string("Default string"), obj.asString());
- //Object - number
+ // Object - number
obj = 3.1415926;
resultType = item->validate(obj);
@@ -141,10 +147,11 @@ TEST(test_item_with_max_length, test_StringSchemaItemTest) {
SmartObject obj;
ISchemaItemPtr item = CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(25),
+ TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(25),
TSchemaItemParameter<std::string>("Default string"));
- //Object - valid string
+ // Object - valid string
obj = "New valid string";
ASSERT_EQ(std::string("New valid string"), obj.asString());
@@ -154,7 +161,7 @@ TEST(test_item_with_max_length, test_StringSchemaItemTest) {
EXPECT_TRUE(resDefault);
EXPECT_EQ(std::string("Default string"), obj.asString());
- //Object - too long string
+ // Object - too long string
obj = "New very very loooooong string";
ASSERT_EQ(std::string("New very very loooooong string"), obj.asString());
@@ -173,7 +180,8 @@ TEST(test_map_validate, test_StringSchemaItemTest) {
SmartObject obj;
ISchemaItemPtr item = CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(25),
+ TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(25),
TSchemaItemParameter<std::string>("Default string"));
obj["str"] = "New valid string";
@@ -233,7 +241,8 @@ TEST(test_array_validate, test_StringSchemaItemTest) {
SmartObject obj;
ISchemaItemPtr item = CStringSchemaItem::create(
- TSchemaItemParameter<size_t>(0), TSchemaItemParameter<size_t>(25),
+ TSchemaItemParameter<size_t>(0),
+ TSchemaItemParameter<size_t>(25),
TSchemaItemParameter<std::string>("Default string"));
obj[0] = "New valid string";
@@ -267,7 +276,7 @@ TEST(test_array_validate, test_StringSchemaItemTest) {
resDefault = item->setDefaultValue(obj[4]);
EXPECT_TRUE(resDefault);
- //Set default value for non-initialized element
+ // Set default value for non-initialized element
resDefault = item->setDefaultValue(obj[5]);
EXPECT_TRUE(resDefault);
diff --git a/src/components/smart_objects/test/map_performance_test.cc b/src/components/smart_objects/test/map_performance_test.cc
index e7e9ccffac..35863da420 100644
--- a/src/components/smart_objects/test/map_performance_test.cc
+++ b/src/components/smart_objects/test/map_performance_test.cc
@@ -41,7 +41,7 @@ typedef std::vector<std::string> Value;
typedef std::map<Key, Value> Map;
namespace {
-void MakeMapObject(Map &obj, const int size) {
+void MakeMapObject(Map& obj, const int size) {
char i_key[8], j_key[8];
Value array;
diff --git a/src/components/smart_objects/test/smart_object_performance_test.cc b/src/components/smart_objects/test/smart_object_performance_test.cc
index 72b6c1fa6d..e699da54fe 100644
--- a/src/components/smart_objects/test/smart_object_performance_test.cc
+++ b/src/components/smart_objects/test/smart_object_performance_test.cc
@@ -40,7 +40,7 @@
using namespace NsSmartDeviceLink::NsSmartObjects;
namespace {
-void MakeMapObject(SmartObject &obj, const int size) {
+void MakeMapObject(SmartObject& obj, const int size) {
char i_key[8], j_key[8];
SmartObject array;
@@ -60,7 +60,7 @@ TEST(SmartObjectPerformanceTest, SmartObjectPerformance) {
SmartObject object;
MakeMapObject(object, 100);
- std::set < std::string > keys = object.enumerate();
+ std::set<std::string> keys = object.enumerate();
for (std::set<std::string>::iterator i = keys.begin(); i != keys.end(); ++i) {
printf("%s - ", i->c_str());
SmartArray* array = object[*i].asArray();
diff --git a/src/components/telemetry_monitor/CMakeLists.txt b/src/components/telemetry_monitor/CMakeLists.txt
new file mode 100644
index 0000000000..f3004dc61e
--- /dev/null
+++ b/src/components/telemetry_monitor/CMakeLists.txt
@@ -0,0 +1,69 @@
+# Copyright (c) 2016, Ford Motor Company
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer.
+#
+# Redistributions in binary form must reproduce the above copyright notice,
+# this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided with the
+# distribution.
+#
+# Neither the name of the Ford Motor Company nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+
+
+set(TELEMETRY_MONITOR_SRC_DIR ${COMPONENTS_DIR}/telemetry_monitor/src)
+
+include_directories (
+ include
+ ${COMPONENTS_DIR}/utils/include/
+ ${COMPONENTS_DIR}/protocol_handler/include/
+ ${COMPONENTS_DIR}/connection_handler/include/
+ ${COMPONENTS_DIR}/transport_manager/include/
+ ${COMPONENTS_DIR}/application_manager/include/
+ ${COMPONENTS_DIR}/policy/include/
+ ${COMPONENTS_DIR}/hmi_message_handler/include/
+ ${COMPONENTS_DIR}/formatters/include/
+ ${COMPONENTS_DIR}/media_manager/include/
+ ${COMPONENTS_DIR}/smart_objects/include/
+ ${COMPONENTS_DIR}/config_profile/include/
+ ${JSONCPP_INCLUDE_DIRECTORY}
+ ${CMAKE_BINARY_DIR}/src/components/
+ ${LOG4CXX_INCLUDE_DIRECTORY}
+)
+
+set(SOURCES
+ ${TELEMETRY_MONITOR_SRC_DIR}/metric_wrapper.cc
+ ${TELEMETRY_MONITOR_SRC_DIR}/telemetry_monitor.cc
+ ${TELEMETRY_MONITOR_SRC_DIR}/application_manager_observer.cc
+ ${TELEMETRY_MONITOR_SRC_DIR}/transport_manager_observer.cc
+ ${TELEMETRY_MONITOR_SRC_DIR}/protocol_handler_observer.cc
+ ${TELEMETRY_MONITOR_SRC_DIR}/application_manager_metric_wrapper.cc
+ ${TELEMETRY_MONITOR_SRC_DIR}/transport_manager_metric_wrapper.cc
+ ${TELEMETRY_MONITOR_SRC_DIR}/protocol_handler_metric_wrapper.cc
+)
+
+add_library("TelemetryMonitor" ${SOURCES})
+target_link_libraries("TelemetryMonitor" ${LIBRARIES})
+add_dependencies("TelemetryMonitor" HMI_API MOBILE_API)
+
+if(BUILD_TESTS)
+ add_subdirectory(test)
+endif()
diff --git a/src/components/telemetry_monitor/include/telemetry_monitor/application_manager_metric_wrapper.h b/src/components/telemetry_monitor/include/telemetry_monitor/application_manager_metric_wrapper.h
new file mode 100644
index 0000000000..d35de52e3b
--- /dev/null
+++ b/src/components/telemetry_monitor/include/telemetry_monitor/application_manager_metric_wrapper.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_APPLICATION_MANAGER_MECTRIC_WRAPPER_H_
+#define SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_APPLICATION_MANAGER_MECTRIC_WRAPPER_H_
+
+#include <string>
+
+#include "telemetry_monitor/metric_wrapper.h"
+#include "telemetry_monitor/application_manager_observer.h"
+
+namespace telemetry_monitor {
+
+class ApplicationManagerObserver;
+
+class ApplicationManagerMetricWrapper : public MetricWrapper {
+ public:
+ utils::SharedPtr<application_manager::AMTelemetryObserver::MessageMetric>
+ message_metric;
+ virtual Json::Value GetJsonMetric();
+};
+}
+#endif // SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_APPLICATION_MANAGER_MECTRIC_WRAPPER_H_
diff --git a/src/components/telemetry_monitor/include/telemetry_monitor/application_manager_observer.h b/src/components/telemetry_monitor/include/telemetry_monitor/application_manager_observer.h
new file mode 100644
index 0000000000..ecb9c8002a
--- /dev/null
+++ b/src/components/telemetry_monitor/include/telemetry_monitor/application_manager_observer.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_APPLICATION_MANAGER_OBSERVER_H_
+#define SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_APPLICATION_MANAGER_OBSERVER_H_
+
+#include "utils/message_queue.h"
+#include "application_manager/telemetry_observer.h"
+#include "telemetry_monitor/application_manager_metric_wrapper.h"
+
+namespace telemetry_monitor {
+
+class TelemetryMonitor;
+
+class ApplicationManagerObserver
+ : public application_manager::AMTelemetryObserver {
+ public:
+ explicit ApplicationManagerObserver(TelemetryMonitor* telemetry_monitor);
+ virtual void OnMessage(utils::SharedPtr<MessageMetric> metric);
+
+ private:
+ TelemetryMonitor* telemetry_monitor_;
+};
+}
+#endif // SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_APPLICATION_MANAGER_OBSERVER_H_
diff --git a/src/components/telemetry_monitor/include/telemetry_monitor/json_keys.h b/src/components/telemetry_monitor/include/telemetry_monitor/json_keys.h
new file mode 100644
index 0000000000..899c76b2e8
--- /dev/null
+++ b/src/components/telemetry_monitor/include/telemetry_monitor/json_keys.h
@@ -0,0 +1,52 @@
+/*
+ *
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_JSON_KEYS_H_
+#define SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_JSON_KEYS_H_
+
+namespace telemetry_monitor {
+namespace strings {
+const char logger[] = "logger";
+const char begin[] = "begin";
+const char end[] = "end";
+const char data_size[] = "data_size";
+const char message_id[] = "message_id";
+const char session_id[] = "session_id";
+const char correlation_id[] = "correlation_id";
+const char connection_key[] = "connection_key";
+const char stime[] = "stime";
+const char utime[] = "utime";
+const char memory[] = "RAM";
+}
+}
+#endif // SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_JSON_KEYS_H_
diff --git a/src/components/telemetry_monitor/include/telemetry_monitor/metric_wrapper.h b/src/components/telemetry_monitor/include/telemetry_monitor/metric_wrapper.h
new file mode 100644
index 0000000000..b4d7ed12cb
--- /dev/null
+++ b/src/components/telemetry_monitor/include/telemetry_monitor/metric_wrapper.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_MECTRIC_WRAPPER_H_
+#define SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_MECTRIC_WRAPPER_H_
+
+#include <string>
+#include "utils/resource_usage.h"
+#include "json/json.h"
+
+namespace telemetry_monitor {
+
+class MetricWrapper {
+ utils::ResourseUsage* resources;
+
+ public:
+ MetricWrapper();
+ /*
+ * @brief get current cpu and memory info and store it as member
+ */
+ bool grabResources();
+ virtual std::string GetStyledString();
+ virtual Json::Value GetJsonMetric();
+ virtual ~MetricWrapper();
+
+ protected:
+ void Clear();
+};
+
+} // namespace telemetry_monitor
+#endif // SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_MECTRIC_WRAPPER_H_
diff --git a/src/components/telemetry_monitor/include/telemetry_monitor/protocol_handler_metric_wrapper.h b/src/components/telemetry_monitor/include/telemetry_monitor/protocol_handler_metric_wrapper.h
new file mode 100644
index 0000000000..bc4e4c8e53
--- /dev/null
+++ b/src/components/telemetry_monitor/include/telemetry_monitor/protocol_handler_metric_wrapper.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_PROTOCOL_HANDLER_MECTRIC_WRAPPER_H_
+#define SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_PROTOCOL_HANDLER_MECTRIC_WRAPPER_H_
+
+#include <string>
+#include "utils/shared_ptr.h"
+#include "telemetry_monitor/metric_wrapper.h"
+#include "protocol_handler_observer.h"
+
+namespace telemetry_monitor {
+
+class ProtocolHandlerMecticWrapper : public MetricWrapper {
+ public:
+ utils::SharedPtr<protocol_handler::PHTelemetryObserver::MessageMetric>
+ message_metric;
+ virtual Json::Value GetJsonMetric();
+};
+} // namespace telemetry_monitor
+#endif // SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_PROTOCOL_HANDLER_MECTRIC_WRAPPER_H_
diff --git a/src/components/telemetry_monitor/include/telemetry_monitor/protocol_handler_observer.h b/src/components/telemetry_monitor/include/telemetry_monitor/protocol_handler_observer.h
new file mode 100644
index 0000000000..69e5658382
--- /dev/null
+++ b/src/components/telemetry_monitor/include/telemetry_monitor/protocol_handler_observer.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_PROTOCOL_HANDLER_OBSERVER_H_
+#define SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_PROTOCOL_HANDLER_OBSERVER_H_
+
+#include "protocol_handler/telemetry_observer.h"
+#include "utils/message_queue.h"
+
+namespace telemetry_monitor {
+
+class TelemetryMonitor;
+
+class ProtocolHandlerObserver : public protocol_handler::PHTelemetryObserver {
+ public:
+ explicit ProtocolHandlerObserver(TelemetryMonitor* telemetry_monitor);
+
+ virtual void StartMessageProcess(uint32_t message_id,
+ const TimevalStruct& start_time);
+
+ virtual void EndMessageProcess(utils::SharedPtr<MessageMetric> m);
+
+ private:
+ TelemetryMonitor* telemetry_monitor_;
+ std::map<uint32_t, TimevalStruct> time_starts;
+};
+} // namespace telemetry_monitor
+#endif // SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_PROTOCOL_HANDLER_OBSERVER_H_
diff --git a/src/components/telemetry_monitor/include/telemetry_monitor/telemetry_monitor.h b/src/components/telemetry_monitor/include/telemetry_monitor/telemetry_monitor.h
new file mode 100644
index 0000000000..49895de8d3
--- /dev/null
+++ b/src/components/telemetry_monitor/include/telemetry_monitor/telemetry_monitor.h
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_H_
+#define SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_H_
+
+#include <string>
+
+#include "utils/shared_ptr.h"
+#include "utils/message_queue.h"
+#include "utils/threads/thread.h"
+#include "utils/threads/thread_delegate.h"
+#include "telemetry_monitor/metric_wrapper.h"
+#include "telemetry_monitor/application_manager_observer.h"
+#include "application_manager/application_manager_impl.h"
+#include "telemetry_monitor/transport_manager_observer.h"
+#include "transport_manager/transport_manager_impl.h"
+#include "protocol_handler_observer.h"
+#include "protocol_handler/protocol_handler_impl.h"
+
+namespace telemetry_monitor {
+
+using ::utils::MessageQueue;
+
+class Streamer : public threads::ThreadDelegate {
+ public:
+ explicit Streamer(TelemetryMonitor* const server);
+ ~Streamer();
+ void threadMain() OVERRIDE;
+ void exitThreadMain() OVERRIDE;
+
+ virtual void PushMessage(utils::SharedPtr<MetricWrapper> metric);
+ volatile bool is_client_connected_;
+
+ private:
+ void Start();
+ void Stop();
+ bool IsReady() const;
+ bool Send(const std::string& msg);
+ void ShutDownAndCloseSocket(int32_t socket_fd);
+ TelemetryMonitor* const kserver_;
+ int32_t server_socket_fd_;
+ int32_t client_socket_fd_;
+ volatile bool stop_flag_;
+ MessageQueue<utils::SharedPtr<MetricWrapper> > messages_;
+ DISALLOW_COPY_AND_ASSIGN(Streamer);
+};
+
+class TelemetryMonitor {
+ public:
+ TelemetryMonitor(const std::string& server_address, uint16_t port);
+ virtual ~TelemetryMonitor();
+ virtual void Init(TelemetryObservable<protocol_handler::PHTelemetryObserver>*
+ protocol_handler,
+ TelemetryObservable<
+ application_manager::AMTelemetryObserver>* app_manager,
+ TelemetryObservable<transport_manager::TMTelemetryObserver>*
+ transport_manager);
+ virtual void Stop();
+ virtual void Start();
+ virtual void SendMetric(utils::SharedPtr<MetricWrapper> metric);
+ void set_streamer(Streamer* streamer);
+ const std::string& ip() const;
+ int16_t port() const;
+
+ private:
+ std::string server_address_;
+ int16_t port_;
+ bool is_ready_;
+ threads::Thread* thread_;
+ Streamer* streamer_;
+ ApplicationManagerObserver app_observer;
+ TransportManagerObserver tm_observer;
+ ProtocolHandlerObserver ph_observer;
+
+ DISALLOW_COPY_AND_ASSIGN(TelemetryMonitor);
+};
+} // namespace telemetry_monitor
+#endif // SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_H_
diff --git a/src/components/telemetry_monitor/include/telemetry_monitor/transport_manager_metric_wrapper.h b/src/components/telemetry_monitor/include/telemetry_monitor/transport_manager_metric_wrapper.h
new file mode 100644
index 0000000000..9cb158fa98
--- /dev/null
+++ b/src/components/telemetry_monitor/include/telemetry_monitor/transport_manager_metric_wrapper.h
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_TRANSPORT_MANAGER_MECTRIC_WRAPPER_H_
+#define SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_TRANSPORT_MANAGER_MECTRIC_H_
+
+#include <string>
+#include "telemetry_monitor/metric_wrapper.h"
+#include "telemetry_monitor/transport_manager_observer.h"
+
+namespace telemetry_monitor {
+
+class TransportManagerMecticWrapper : public MetricWrapper {
+ public:
+ utils::SharedPtr<transport_manager::TMTelemetryObserver::MessageMetric>
+ message_metric;
+ virtual Json::Value GetJsonMetric();
+};
+} // namespace telemetry_monitor
+#endif // SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_TRANSPORT_MANAGER_MECTRIC_WRAPPER_H_
diff --git a/src/components/telemetry_monitor/include/telemetry_monitor/transport_manager_observer.h b/src/components/telemetry_monitor/include/telemetry_monitor/transport_manager_observer.h
new file mode 100644
index 0000000000..bff5834586
--- /dev/null
+++ b/src/components/telemetry_monitor/include/telemetry_monitor/transport_manager_observer.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_TRANSPORT_MANAGER_OBSERVER_H_
+#define SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_TRANSPORT_MANAGER_OBSERVER_H_
+
+#include "transport_manager/telemetry_observer.h"
+#include "utils/message_queue.h"
+#include "utils/date_time.h"
+
+namespace telemetry_monitor {
+
+class TelemetryMonitor;
+
+class TransportManagerObserver : public transport_manager::TMTelemetryObserver {
+ public:
+ explicit TransportManagerObserver(TelemetryMonitor* telemetry_monitor);
+ virtual void StartRawMsg(const protocol_handler::RawMessage* ptr);
+ virtual void StopRawMsg(const protocol_handler::RawMessage* ptr);
+
+ private:
+ TelemetryMonitor* telemetry_monitor_;
+ std::map<const protocol_handler::RawMessage*, TimevalStruct> time_starts;
+};
+} // namespace telemetry_monitor
+#endif // SRC_COMPONENTS_TELEMETRY_MONITOR_INCLUDE_TELEMETRY_MONITOR_TRANSPORT_MANAGER_OBSERVER_H_
diff --git a/src/components/telemetry_monitor/src/application_manager_metric_wrapper.cc b/src/components/telemetry_monitor/src/application_manager_metric_wrapper.cc
new file mode 100644
index 0000000000..b693d9df22
--- /dev/null
+++ b/src/components/telemetry_monitor/src/application_manager_metric_wrapper.cc
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "telemetry_monitor/application_manager_metric_wrapper.h"
+#include "telemetry_monitor/json_keys.h"
+#include "application_manager/smart_object_keys.h"
+#include "utils/convert_utils.h"
+
+namespace telemetry_monitor {
+
+Json::Value ApplicationManagerMetricWrapper::GetJsonMetric() {
+ Json::Value result = MetricWrapper::GetJsonMetric();
+ result[strings::logger] = "ApplicationManager";
+ result[strings::begin] =
+ Json::Int64(date_time::DateTime::getuSecs(message_metric->begin));
+ result[strings::end] =
+ Json::Int64(date_time::DateTime::getuSecs(message_metric->end));
+ const NsSmartDeviceLink::NsSmartObjects::SmartObject& params =
+ message_metric->message->getElement(application_manager::strings::params);
+ result[strings::correlation_id] = utils::ConvertInt64ToLongLongInt(
+ params[application_manager::strings::correlation_id].asInt());
+ result[strings::connection_key] = utils::ConvertInt64ToLongLongInt(
+ params[application_manager::strings::connection_key].asInt());
+ return result;
+}
+} // namespace telemetry_monitor
diff --git a/src/components/telemetry_monitor/src/application_manager_observer.cc b/src/components/telemetry_monitor/src/application_manager_observer.cc
new file mode 100644
index 0000000000..cb390eddeb
--- /dev/null
+++ b/src/components/telemetry_monitor/src/application_manager_observer.cc
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "telemetry_monitor/application_manager_observer.h"
+#include "utils/shared_ptr.h"
+#include "telemetry_monitor/telemetry_monitor.h"
+#include "telemetry_monitor/application_manager_metric_wrapper.h"
+
+namespace telemetry_monitor {
+
+ApplicationManagerObserver::ApplicationManagerObserver(
+ TelemetryMonitor* telemetry_monitor)
+ : telemetry_monitor_(telemetry_monitor) {}
+
+void ApplicationManagerObserver::OnMessage(
+ utils::SharedPtr<MessageMetric> metric) {
+ ApplicationManagerMetricWrapper* m = new ApplicationManagerMetricWrapper();
+ m->message_metric = metric;
+ m->grabResources();
+ telemetry_monitor_->SendMetric(m);
+}
+} // namespace telemetry_monitor
diff --git a/src/components/telemetry_monitor/src/metric_wrapper.cc b/src/components/telemetry_monitor/src/metric_wrapper.cc
new file mode 100644
index 0000000000..937a705ef7
--- /dev/null
+++ b/src/components/telemetry_monitor/src/metric_wrapper.cc
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "telemetry_monitor/metric_wrapper.h"
+#include "telemetry_monitor/json_keys.h"
+
+namespace telemetry_monitor {
+
+MetricWrapper::MetricWrapper() : resources(NULL) {}
+
+bool MetricWrapper::grabResources() {
+ Clear();
+ resources = utils::Resources::getCurrentResourseUsage();
+ if (NULL != resources) {
+ return true;
+ } else {
+ return false;
+ }
+ flush(std::cout);
+}
+
+std::string MetricWrapper::GetStyledString() {
+ return GetJsonMetric().toStyledString();
+}
+
+Json::Value MetricWrapper::GetJsonMetric() {
+ Json::Value result;
+ if (resources) {
+ result[strings::stime] = resources->stime;
+ result[strings::utime] = resources->utime;
+ result[strings::memory] = resources->memory;
+ }
+ return result;
+}
+
+void MetricWrapper::Clear() {
+ if (NULL != resources) {
+ delete resources;
+ resources = NULL;
+ }
+}
+
+MetricWrapper::~MetricWrapper() {
+ Clear();
+}
+}
diff --git a/src/components/telemetry_monitor/src/protocol_handler_metric_wrapper.cc b/src/components/telemetry_monitor/src/protocol_handler_metric_wrapper.cc
new file mode 100644
index 0000000000..335f0dbb29
--- /dev/null
+++ b/src/components/telemetry_monitor/src/protocol_handler_metric_wrapper.cc
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "telemetry_monitor/protocol_handler_metric_wrapper.h"
+#include "json/json.h"
+#include "telemetry_monitor/json_keys.h"
+
+namespace telemetry_monitor {
+
+Json::Value ProtocolHandlerMecticWrapper::GetJsonMetric() {
+ Json::Value result = MetricWrapper::GetJsonMetric();
+ result[strings::logger] = "ProtocolHandler";
+ result[strings::begin] =
+ Json::Int64(date_time::DateTime::getuSecs(message_metric->begin));
+ result[strings::end] =
+ Json::Int64(date_time::DateTime::getuSecs(message_metric->end));
+ result[strings::message_id] = message_metric->message_id;
+ result[strings::connection_key] = message_metric->connection_key;
+ return result;
+}
+
+} // namespace telemetry_monitor
diff --git a/src/components/telemetry_monitor/src/protocol_handler_observer.cc b/src/components/telemetry_monitor/src/protocol_handler_observer.cc
new file mode 100644
index 0000000000..2244cb2259
--- /dev/null
+++ b/src/components/telemetry_monitor/src/protocol_handler_observer.cc
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "utils/date_time.h"
+#include "telemetry_monitor/protocol_handler_observer.h"
+#include "telemetry_monitor/protocol_handler_metric_wrapper.h"
+#include "telemetry_monitor/telemetry_monitor.h"
+
+namespace telemetry_monitor {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "TelemetryMonitor")
+
+ProtocolHandlerObserver::ProtocolHandlerObserver(
+ TelemetryMonitor* telemetry_monitor)
+ : telemetry_monitor_(telemetry_monitor) {}
+
+void ProtocolHandlerObserver::StartMessageProcess(
+ uint32_t message_id, const TimevalStruct& start_time) {
+ if (message_id == 0) {
+ return;
+ }
+ if (time_starts.find(message_id) != time_starts.end()) {
+ LOG4CXX_DEBUG(
+ logger_,
+ "Already waiting for stop processing for Message ID: " << message_id);
+ return;
+ }
+ time_starts[message_id] = start_time;
+}
+
+void ProtocolHandlerObserver::EndMessageProcess(
+ utils::SharedPtr<MessageMetric> m) {
+ uint32_t message_id = m->message_id;
+ std::map<uint32_t, TimevalStruct>::const_iterator it =
+ time_starts.find(message_id);
+ if (it == time_starts.end()) {
+ LOG4CXX_WARN(logger_, "Cant find start time for message" << message_id);
+ return;
+ }
+ m->begin = time_starts[message_id];
+ m->end = date_time::DateTime::getCurrentTime();
+ ProtocolHandlerMecticWrapper* metric = new ProtocolHandlerMecticWrapper();
+ metric->message_metric = m;
+ metric->grabResources();
+ telemetry_monitor_->SendMetric(metric);
+}
+} // namespace telemetry_monitor
diff --git a/src/components/telemetry_monitor/src/telemetry_monitor.cc b/src/components/telemetry_monitor/src/telemetry_monitor.cc
new file mode 100644
index 0000000000..759b843961
--- /dev/null
+++ b/src/components/telemetry_monitor/src/telemetry_monitor.cc
@@ -0,0 +1,287 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "telemetry_monitor/telemetry_monitor.h"
+
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <sys/select.h>
+#include <sys/time.h>
+#include <netinet/in.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+
+#include "transport_manager/transport_manager_default.h"
+#include "utils/resource_usage.h"
+#include "telemetry_monitor/telemetry_observable.h"
+
+namespace telemetry_monitor {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "TelemetryMonitor")
+
+TelemetryMonitor::TelemetryMonitor(const std::string& server_address,
+ uint16_t port)
+ : server_address_(server_address)
+ , port_(port)
+ , thread_(NULL)
+ , streamer_(NULL)
+ , app_observer(this)
+ , tm_observer(this)
+ , ph_observer(this) {}
+
+void TelemetryMonitor::Start() {
+ streamer_ = new Streamer(this);
+ thread_ = threads::CreateThread("TelemetryMonitor", streamer_);
+}
+
+void TelemetryMonitor::set_streamer(Streamer* streamer) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (thread_ && !thread_->is_running()) {
+ thread_->set_delegate(streamer);
+ if (streamer_) {
+ delete streamer_;
+ }
+ streamer_ = streamer;
+ } else {
+ LOG4CXX_ERROR(logger_, "Unable to replace streamer if it is active");
+ }
+}
+
+const std::string& TelemetryMonitor::ip() const {
+ return server_address_;
+}
+
+int16_t TelemetryMonitor::port() const {
+ return port_;
+}
+
+TelemetryMonitor::~TelemetryMonitor() {
+ Stop();
+}
+
+void TelemetryMonitor::Init(
+ TelemetryObservable<protocol_handler::PHTelemetryObserver>*
+ protocol_handler,
+ TelemetryObservable<application_manager::AMTelemetryObserver>* app_manager,
+ TelemetryObservable<transport_manager::TMTelemetryObserver>*
+ transport_manager) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK_OR_RETURN_VOID(streamer_);
+
+ app_manager->SetTelemetryObserver(&app_observer);
+ transport_manager->SetTelemetryObserver(&tm_observer);
+ protocol_handler->SetTelemetryObserver(&ph_observer);
+
+ DCHECK_OR_RETURN_VOID(thread_);
+ thread_->start(threads::ThreadOptions());
+}
+
+void TelemetryMonitor::Stop() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (thread_) {
+ thread_->stop();
+ thread_->join();
+ threads::DeleteThread(thread_);
+ }
+ thread_ = NULL;
+}
+
+void TelemetryMonitor::SendMetric(utils::SharedPtr<MetricWrapper> metric) {
+ if ((NULL != streamer_) && streamer_->is_client_connected_) {
+ streamer_->PushMessage(metric);
+ }
+}
+
+Streamer::Streamer(TelemetryMonitor* const server)
+ : is_client_connected_(false)
+ , kserver_(server)
+ , server_socket_fd_(0)
+ , client_socket_fd_(0)
+ , stop_flag_(false) {}
+
+Streamer::~Streamer() {
+ Stop();
+}
+
+void Streamer::threadMain() {
+ LOG4CXX_AUTO_TRACE(logger_);
+
+ Start();
+ while (!stop_flag_) {
+ LOG4CXX_INFO(logger_, "Server socket is listening ");
+ client_socket_fd_ = accept(server_socket_fd_, NULL, NULL);
+ if (0 > client_socket_fd_) {
+ LOG4CXX_ERROR(logger_, "Cant open socket . Socket is busy ");
+ Stop();
+ break;
+ }
+ LOG4CXX_INFO(logger_, "Client connected");
+
+ is_client_connected_ = true;
+ while (is_client_connected_) {
+ while (!messages_.empty()) {
+ utils::SharedPtr<MetricWrapper> metric;
+ if (!messages_.pop(metric)) {
+ continue;
+ }
+ is_client_connected_ = Send(metric->GetStyledString());
+ }
+
+ if (!IsReady()) {
+ LOG4CXX_INFO(logger_, "Client disconnected.");
+ break;
+ }
+
+ messages_.wait();
+ }
+ }
+}
+
+void Streamer::exitThreadMain() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ Stop();
+ messages_.Shutdown();
+}
+
+void Streamer::Start() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ server_socket_fd_ = socket(AF_INET, SOCK_STREAM, 0);
+
+ if (0 >= server_socket_fd_) {
+ LOG4CXX_ERROR(logger_, "Server open error");
+ return;
+ } else {
+ LOG4CXX_DEBUG(logger_, "Server socket : " << server_socket_fd_);
+ }
+
+ int32_t optval = 1;
+ if (-1 == setsockopt(server_socket_fd_,
+ SOL_SOCKET,
+ SO_REUSEADDR,
+ &optval,
+ sizeof optval)) {
+ LOG4CXX_ERROR(logger_, "Unable to set sockopt");
+ return;
+ }
+
+ sockaddr_in serv_addr_ = {0};
+ serv_addr_.sin_addr.s_addr = inet_addr(kserver_->ip().c_str());
+ serv_addr_.sin_family = AF_INET;
+ serv_addr_.sin_port = htons(kserver_->port());
+
+ if (-1 == bind(server_socket_fd_,
+ reinterpret_cast<struct sockaddr*>(&serv_addr_),
+ sizeof(serv_addr_))) {
+ LOG4CXX_ERROR(logger_,
+ "Unable to bind server " << kserver_->ip().c_str() << ':'
+ << kserver_->port());
+ return;
+ }
+ if (-1 == listen(server_socket_fd_, 1)) {
+ LOG4CXX_ERROR(logger_, "Streamer listen error " << strerror(errno));
+ return;
+ }
+}
+
+void Streamer::ShutDownAndCloseSocket(int32_t socket_fd) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (0 < socket_fd) {
+ LOG4CXX_INFO(logger_, "Shutdown socket");
+ if (-1 == ::shutdown(socket_fd, SHUT_RDWR)) {
+ LOG4CXX_ERROR(logger_, "Unable to shutdown socket");
+ }
+ if (-1 == close(socket_fd)) {
+ LOG4CXX_ERROR(logger_, "Unable to close socket");
+ }
+ } else {
+ LOG4CXX_WARN(logger_, "Socket in not connected: " << socket_fd);
+ }
+}
+
+void Streamer::Stop() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (stop_flag_) {
+ LOG4CXX_WARN(logger_, "Already Stopped");
+ return;
+ }
+ stop_flag_ = true;
+ messages_.Reset();
+ LOG4CXX_WARN(logger_, "Stop server_socket_fd_");
+ ShutDownAndCloseSocket(server_socket_fd_);
+ server_socket_fd_ = -1;
+
+ LOG4CXX_WARN(logger_, "Stop client_socket_fd_");
+ ShutDownAndCloseSocket(client_socket_fd_);
+ client_socket_fd_ = -1;
+ is_client_connected_ = false;
+}
+
+bool Streamer::IsReady() const {
+ bool result = true;
+ fd_set fds;
+ FD_ZERO(&fds);
+ FD_SET(client_socket_fd_, &fds);
+ TimevalStruct tv = {0, 0};
+ tv.tv_sec = 5; // set a 5 second timeout
+ tv.tv_usec = 0;
+
+ const int retval = select(client_socket_fd_ + 1, 0, &fds, 0, &tv);
+
+ if (-1 == retval) {
+ LOG4CXX_ERROR(logger_, "An error occurred");
+ result = false;
+ } else if (0 == retval) {
+ LOG4CXX_ERROR(logger_, "The timeout expired");
+ result = false;
+ }
+
+ return result;
+}
+
+bool Streamer::Send(const std::string& msg) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ if (!IsReady()) {
+ LOG4CXX_ERROR(logger_, " Socket is not ready");
+ return false;
+ }
+
+ if (-1 == ::send(client_socket_fd_, msg.c_str(), msg.size(), MSG_NOSIGNAL)) {
+ LOG4CXX_ERROR(logger_, " Unable to send");
+ return false;
+ }
+ return true;
+}
+
+void Streamer::PushMessage(utils::SharedPtr<MetricWrapper> metric) {
+ messages_.push(metric);
+}
+} // namespace telemetry_monitor
diff --git a/src/components/telemetry_monitor/src/transport_manager_metric_wrapper.cc b/src/components/telemetry_monitor/src/transport_manager_metric_wrapper.cc
new file mode 100644
index 0000000000..a891aa1118
--- /dev/null
+++ b/src/components/telemetry_monitor/src/transport_manager_metric_wrapper.cc
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "telemetry_monitor/transport_manager_metric_wrapper.h"
+#include "json/json.h"
+#include "telemetry_monitor/json_keys.h"
+#include "application_manager/smart_object_keys.h"
+
+namespace telemetry_monitor {
+
+Json::Value TransportManagerMecticWrapper::GetJsonMetric() {
+ Json::Value result = MetricWrapper::GetJsonMetric();
+ result[strings::logger] = "TransportManager";
+ result[strings::begin] =
+ Json::Int64(date_time::DateTime::getuSecs(message_metric->begin));
+ result[strings::end] =
+ Json::Int64(date_time::DateTime::getuSecs(message_metric->end));
+ result[strings::data_size] = static_cast<uint32_t>(message_metric->data_size);
+ return result;
+}
+
+} // namespace telemetry_monitor
diff --git a/src/components/telemetry_monitor/src/transport_manager_observer.cc b/src/components/telemetry_monitor/src/transport_manager_observer.cc
new file mode 100644
index 0000000000..b3e57ac22a
--- /dev/null
+++ b/src/components/telemetry_monitor/src/transport_manager_observer.cc
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "telemetry_monitor/transport_manager_observer.h"
+
+#include <time.h>
+
+#include "telemetry_monitor/transport_manager_metric_wrapper.h"
+#include "telemetry_monitor/telemetry_monitor.h"
+
+namespace telemetry_monitor {
+
+TransportManagerObserver::TransportManagerObserver(
+ TelemetryMonitor* telemetry_monitor)
+ : telemetry_monitor_(telemetry_monitor) {}
+
+void TransportManagerObserver::StartRawMsg(
+ const protocol_handler::RawMessage* ptr) {
+ time_starts[ptr] = date_time::DateTime::getCurrentTime();
+}
+
+void TransportManagerObserver::StopRawMsg(
+ const protocol_handler::RawMessage* ptr) {
+ std::map<const protocol_handler::RawMessage*, TimevalStruct>::const_iterator
+ it;
+ it = time_starts.find(ptr);
+ if (it != time_starts.end()) {
+ TransportManagerMecticWrapper* m = new TransportManagerMecticWrapper();
+ m->message_metric =
+ new transport_manager::TMTelemetryObserver::MessageMetric();
+ m->message_metric->begin = it->second;
+ m->message_metric->end = date_time::DateTime::getCurrentTime();
+ m->message_metric->data_size = ptr->data_size();
+ m->grabResources();
+ telemetry_monitor_->SendMetric(m);
+ }
+}
+
+} // namespace telemetry_monitor
diff --git a/src/components/telemetry_monitor/test/CMakeLists.txt b/src/components/telemetry_monitor/test/CMakeLists.txt
new file mode 100644
index 0000000000..7d2de19854
--- /dev/null
+++ b/src/components/telemetry_monitor/test/CMakeLists.txt
@@ -0,0 +1,89 @@
+# Copyright (c) 2015, Ford Motor Company
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer.
+#
+# Redistributions in binary form must reproduce the above copyright notice,
+# this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided with the
+# distribution.
+#
+# Neither the name of the Ford Motor Company nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+
+if(BUILD_TESTS)
+
+include_directories(
+ include
+ ${GMOCK_INCLUDE_DIRECTORY}
+ ${COMPONENTS_DIR}/telemetry_monitor/include
+ ${COMPONENTS_DIR}/utils/include
+ ${COMPONENTS_DIR}/protocol_handler/include
+ ${COMPONENTS_DIR}/application_manager/include
+ ${COMPONENTS_DIR}/resumption/include
+ ${JSONCPP_INCLUDE_DIRECTORY}
+)
+
+
+set(testSources
+ metric_wrapper_test.cc
+ telemetry_monitor_test.cc
+ protocol_handler_metric_test.cc
+ protocol_handler_observer_test.cc
+ transport_manager_metric_test.cc
+ transport_manager_observer_test.cc
+ application_manager_metric_test.cc
+ application_manager_observer_test.cc
+)
+
+set(testLibraries
+ gmock
+ TelemetryMonitor
+ jsoncpp
+ Utils
+ MediaManager
+ ProtocolHandler
+ v4_protocol_v1_2_no_extra
+ SmartObjects
+ ProtocolLibrary
+ ConfigProfile
+ ApplicationManager
+ MessageHelper
+ Resumption
+ jsoncpp
+ transport_manager
+ MediaManager
+ ProtocolHandler
+ connectionHandler
+)
+
+if (BUILD_USB_SUPPORT)
+ list(APPEND testLibraries Libusb-1.0.16)
+endif()
+
+if (BUILD_BT_SUPPORT)
+ list(APPEND testLibraries bluetooth)
+endif()
+
+file(COPY log4cxx.properties DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+
+create_test("telemetry_monitor_test" "${testSources}" "${testLibraries}")
+
+endif()
diff --git a/src/components/telemetry_monitor/test/application_manager_metric_test.cc b/src/components/telemetry_monitor/test/application_manager_metric_test.cc
new file mode 100644
index 0000000000..5d97ac3528
--- /dev/null
+++ b/src/components/telemetry_monitor/test/application_manager_metric_test.cc
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "telemetry_monitor/json_keys.h"
+#include "utils/resource_usage.h"
+#include "application_manager/smart_object_keys.h"
+#include "telemetry_monitor/application_manager_metric_wrapper.h"
+
+namespace test {
+namespace components {
+namespace telemetry_monitor_test {
+
+using namespace ::telemetry_monitor;
+
+TEST(ApplicationManagerMetricWrapper, grabResources) {
+ ApplicationManagerMetricWrapper metric_test;
+ EXPECT_TRUE(metric_test.grabResources());
+}
+
+TEST(ApplicationManagerMetricWrapper, GetJsonMetric) {
+ ApplicationManagerMetricWrapper metric_test;
+
+ TimevalStruct start_time;
+ start_time.tv_sec = 1;
+ start_time.tv_usec = 0;
+
+ TimevalStruct end_time;
+ end_time.tv_sec = 10;
+ end_time.tv_usec = 0;
+ metric_test.message_metric =
+ new application_manager::AMTelemetryObserver::MessageMetric();
+ metric_test.message_metric->begin = start_time;
+ metric_test.message_metric->end = end_time;
+ NsSmartDeviceLink::NsSmartObjects::SmartObject obj;
+ obj["params"][application_manager::strings::correlation_id] = 11;
+ obj["params"][application_manager::strings::connection_key] = 12;
+ metric_test.message_metric->message =
+ new NsSmartDeviceLink::NsSmartObjects::SmartObject(obj);
+ Json::Value jvalue = metric_test.GetJsonMetric();
+
+ EXPECT_EQ("null\n",
+ jvalue[telemetry_monitor::strings::stime].toStyledString());
+ EXPECT_EQ("null\n",
+ jvalue[telemetry_monitor::strings::utime].toStyledString());
+ EXPECT_EQ("null\n",
+ jvalue[telemetry_monitor::strings::memory].toStyledString());
+
+ EXPECT_EQ(date_time::DateTime::getuSecs(start_time),
+ jvalue[telemetry_monitor::strings::begin].asInt64());
+ EXPECT_EQ(date_time::DateTime::getuSecs(end_time),
+ jvalue[telemetry_monitor::strings::end].asInt64());
+ EXPECT_EQ(obj["params"][application_manager::strings::correlation_id].asInt(),
+ jvalue[telemetry_monitor::strings::correlation_id].asInt64());
+ EXPECT_EQ(obj["params"][application_manager::strings::connection_key].asInt(),
+ jvalue[telemetry_monitor::strings::connection_key].asInt());
+}
+
+TEST(ApplicationManagerMetricWrapper, GetJsonMetricWithGrabResources) {
+ ApplicationManagerMetricWrapper metric_test;
+ utils::ResourseUsage* resources = utils::Resources::getCurrentResourseUsage();
+ EXPECT_TRUE(metric_test.grabResources());
+
+ TimevalStruct start_time;
+ start_time.tv_sec = 1;
+ start_time.tv_usec = 0;
+
+ TimevalStruct end_time;
+ end_time.tv_sec = 10;
+ end_time.tv_usec = 0;
+
+ metric_test.message_metric =
+ new application_manager::AMTelemetryObserver::MessageMetric();
+ metric_test.message_metric->begin = start_time;
+ metric_test.message_metric->end = end_time;
+ NsSmartDeviceLink::NsSmartObjects::SmartObject obj;
+ obj["params"][application_manager::strings::correlation_id] = 11;
+ obj["params"][application_manager::strings::connection_key] = 12;
+ metric_test.message_metric->message =
+ new NsSmartDeviceLink::NsSmartObjects::SmartObject(obj);
+ Json::Value jvalue = metric_test.GetJsonMetric();
+
+ EXPECT_EQ(date_time::DateTime::getuSecs(start_time),
+ jvalue[telemetry_monitor::strings::begin].asInt64());
+ EXPECT_EQ(date_time::DateTime::getuSecs(end_time),
+ jvalue[telemetry_monitor::strings::end].asInt64());
+ EXPECT_EQ(obj["params"][application_manager::strings::correlation_id].asInt(),
+ jvalue[telemetry_monitor::strings::correlation_id].asInt64());
+ EXPECT_EQ(obj["params"][application_manager::strings::connection_key].asInt(),
+ jvalue[telemetry_monitor::strings::connection_key].asInt());
+
+ EXPECT_EQ(date_time::DateTime::getuSecs(start_time),
+ jvalue[telemetry_monitor::strings::begin].asInt64());
+ EXPECT_EQ(date_time::DateTime::getuSecs(end_time),
+ jvalue[telemetry_monitor::strings::end].asInt64());
+
+ EXPECT_NEAR(
+ resources->stime, jvalue[telemetry_monitor::strings::stime].asInt(), 1);
+ EXPECT_NEAR(
+ resources->utime, jvalue[telemetry_monitor::strings::utime].asInt(), 1);
+ EXPECT_EQ(resources->memory,
+ jvalue[telemetry_monitor::strings::memory].asInt());
+
+ delete resources;
+}
+
+} // namespace telemetry_monitor
+} // namespace components
+} // namespace test
diff --git a/src/components/telemetry_monitor/test/application_manager_observer_test.cc b/src/components/telemetry_monitor/test/application_manager_observer_test.cc
new file mode 100644
index 0000000000..09ef04a2d8
--- /dev/null
+++ b/src/components/telemetry_monitor/test/application_manager_observer_test.cc
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "telemetry_monitor/mock_telemetry_monitor.h"
+#include "application_manager/telemetry_observer.h"
+#include "telemetry_monitor/application_manager_metric_wrapper.h"
+#include "telemetry_monitor/application_manager_observer.h"
+#include "utils/shared_ptr.h"
+#include "telemetry_monitor/telemetry_monitor.h"
+
+namespace test {
+namespace components {
+namespace telemetry_monitor_test {
+
+using namespace telemetry_monitor;
+using ::testing::_;
+
+TEST(ApplicationManagerObserver, CallOnMessage) {
+ MockTelemetryMonitor mock_telemetry_monitor;
+ ApplicationManagerObserver app_observer(&mock_telemetry_monitor);
+ typedef application_manager::AMTelemetryObserver::MessageMetric AMMetric;
+ utils::SharedPtr<AMMetric> ptr =
+ application_manager::AMTelemetryObserver::MessageMetricSharedPtr();
+ EXPECT_CALL(mock_telemetry_monitor, SendMetric(_));
+ app_observer.OnMessage(ptr);
+}
+
+} // namespace telemetry_monitor
+} // namespace components
+} // namespace test
diff --git a/src/components/telemetry_monitor/test/include/telemetry_monitor/mock_telemetry_monitor.h b/src/components/telemetry_monitor/test/include/telemetry_monitor/mock_telemetry_monitor.h
new file mode 100644
index 0000000000..0ef5a530fd
--- /dev/null
+++ b/src/components/telemetry_monitor/test/include/telemetry_monitor/mock_telemetry_monitor.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_MOCK_TELEMETRY_MONITOR_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_MOCK_TELEMETRY_MONITOR_H_
+
+#include <string>
+#include "gmock/gmock.h"
+#include "telemetry_monitor/telemetry_monitor.h"
+#include "telemetry_monitor/metric_wrapper.h"
+#include "utils/shared_ptr.h"
+
+namespace test {
+namespace components {
+namespace telemetry_monitor_test {
+
+class MockTelemetryMonitor : public telemetry_monitor::TelemetryMonitor {
+ public:
+ MockTelemetryMonitor() : telemetry_monitor::TelemetryMonitor("", 0u) {}
+ MOCK_METHOD1(Init, void(protocol_handler::ProtocolHandlerImpl* ph));
+ MOCK_METHOD0(Stop, void());
+ MOCK_METHOD0(Start, void());
+ MOCK_METHOD1(SendMetric,
+ void(utils::SharedPtr<telemetry_monitor::MetricWrapper> metric));
+};
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_MOCK_TELEMETRY_MONITOR_H_
diff --git a/src/components/time_tester/test/log4cxx.properties b/src/components/telemetry_monitor/test/log4cxx.properties
index 68adbfa7f3..68adbfa7f3 100644
--- a/src/components/time_tester/test/log4cxx.properties
+++ b/src/components/telemetry_monitor/test/log4cxx.properties
diff --git a/src/components/telemetry_monitor/test/metric_wrapper_test.cc b/src/components/telemetry_monitor/test/metric_wrapper_test.cc
new file mode 100644
index 0000000000..91361f3df2
--- /dev/null
+++ b/src/components/telemetry_monitor/test/metric_wrapper_test.cc
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "telemetry_monitor/metric_wrapper.h"
+#include "telemetry_monitor/json_keys.h"
+#include "json/json.h"
+#include "utils/resource_usage.h"
+
+namespace test {
+namespace components {
+namespace telemetry_monitor_test {
+
+using namespace ::telemetry_monitor;
+
+TEST(MetricWrapper, grabResources) {
+ MetricWrapper metric_test;
+ EXPECT_TRUE(metric_test.grabResources());
+}
+
+TEST(MetricWrapper, GetJsonMetricWithoutGrab) {
+ MetricWrapper metric_test;
+ Json::Value jvalue = metric_test.GetJsonMetric();
+
+ EXPECT_EQ("null\n", jvalue[strings::stime].toStyledString());
+ EXPECT_EQ("null\n", jvalue[strings::utime].toStyledString());
+ EXPECT_EQ("null\n", jvalue[strings::memory].toStyledString());
+}
+
+TEST(MetricWrapper, GetJsonMetricWithGrabResources) {
+ MetricWrapper metric_test;
+ utils::ResourseUsage* resources = utils::Resources::getCurrentResourseUsage();
+ EXPECT_TRUE(resources != NULL);
+ EXPECT_TRUE(metric_test.grabResources());
+ Json::Value jvalue = metric_test.GetJsonMetric();
+
+ EXPECT_TRUE(jvalue[strings::stime].isInt());
+ EXPECT_TRUE(jvalue[strings::utime].isInt());
+ EXPECT_TRUE(jvalue[strings::memory].isInt());
+ EXPECT_NE("null/n", jvalue[strings::stime].toStyledString());
+ EXPECT_NE("null/n", jvalue[strings::utime].toStyledString());
+ EXPECT_NE("null/n", jvalue[strings::memory].toStyledString());
+
+ EXPECT_NEAR(resources->stime, jvalue[strings::stime].asInt(), 1);
+ EXPECT_NEAR(resources->utime, jvalue[strings::utime].asInt(), 1);
+ EXPECT_EQ(resources->memory, jvalue[strings::memory].asInt());
+
+ delete resources;
+}
+
+} // namespace telemetry_monitor
+} // namespace components
+} // namespace test
diff --git a/src/components/telemetry_monitor/test/protocol_handler_metric_test.cc b/src/components/telemetry_monitor/test/protocol_handler_metric_test.cc
new file mode 100644
index 0000000000..e41aeb6edd
--- /dev/null
+++ b/src/components/telemetry_monitor/test/protocol_handler_metric_test.cc
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "telemetry_monitor/json_keys.h"
+#include "json/json.h"
+#include "utils/resource_usage.h"
+#include "telemetry_monitor/protocol_handler_metric_wrapper.h"
+#include "protocol_handler/telemetry_observer.h"
+
+namespace test {
+namespace components {
+namespace telemetry_monitor_test {
+
+using namespace ::telemetry_monitor;
+
+TEST(ProtocolHandlerMetricTest, grabResources) {
+ ProtocolHandlerMecticWrapper metric_test;
+ EXPECT_TRUE(metric_test.grabResources());
+}
+
+TEST(ProtocolHandlerMetricTest, GetJsonMetric) {
+ ProtocolHandlerMecticWrapper metric_test;
+
+ TimevalStruct start_time;
+ start_time.tv_sec = 1;
+ start_time.tv_usec = 0;
+
+ TimevalStruct end_time;
+ end_time.tv_sec = 10;
+ end_time.tv_usec = 0;
+ metric_test.message_metric =
+ new protocol_handler::PHTelemetryObserver::MessageMetric();
+ metric_test.message_metric->begin = start_time;
+ metric_test.message_metric->end = end_time;
+ metric_test.message_metric->message_id = 5;
+ metric_test.message_metric->connection_key = 2;
+ Json::Value jvalue = metric_test.GetJsonMetric();
+
+ EXPECT_EQ("\"ProtocolHandler\"\n", jvalue[strings::logger].toStyledString());
+ EXPECT_EQ("null\n", jvalue[strings::stime].toStyledString());
+ EXPECT_EQ("null\n", jvalue[strings::utime].toStyledString());
+ EXPECT_EQ("null\n", jvalue[strings::memory].toStyledString());
+
+ EXPECT_EQ(date_time::DateTime::getuSecs(start_time),
+ jvalue[strings::begin].asInt64());
+ EXPECT_EQ(date_time::DateTime::getuSecs(end_time),
+ jvalue[strings::end].asInt64());
+ EXPECT_EQ(5, jvalue[strings::message_id].asInt64());
+ EXPECT_EQ(2, jvalue[strings::connection_key].asInt());
+}
+
+TEST(ProtocolHandlerMetricTest, GetJsonMetricWithGrabResources) {
+ ProtocolHandlerMecticWrapper metric_test;
+ utils::ResourseUsage* resources = utils::Resources::getCurrentResourseUsage();
+ EXPECT_TRUE(resources != NULL);
+ EXPECT_TRUE(metric_test.grabResources());
+
+ TimevalStruct start_time;
+ start_time.tv_sec = 1;
+ start_time.tv_usec = 0;
+
+ TimevalStruct end_time;
+ end_time.tv_sec = 10;
+ end_time.tv_usec = 0;
+ metric_test.message_metric =
+ new protocol_handler::PHTelemetryObserver::MessageMetric();
+ metric_test.message_metric->begin = start_time;
+ metric_test.message_metric->end = end_time;
+ metric_test.message_metric->message_id = 5;
+ metric_test.message_metric->connection_key = 2;
+ Json::Value jvalue = metric_test.GetJsonMetric();
+
+ EXPECT_TRUE(jvalue[strings::stime].isInt());
+ EXPECT_TRUE(jvalue[strings::utime].isInt());
+ EXPECT_TRUE(jvalue[strings::memory].isInt());
+ EXPECT_NE("null/n", jvalue[strings::stime].toStyledString());
+ EXPECT_NE("null/n", jvalue[strings::utime].toStyledString());
+ EXPECT_NE("null/n", jvalue[strings::memory].toStyledString());
+
+ EXPECT_EQ(date_time::DateTime::getuSecs(start_time),
+ jvalue[strings::begin].asInt64());
+ EXPECT_EQ(date_time::DateTime::getuSecs(end_time),
+ jvalue[strings::end].asInt64());
+ EXPECT_EQ(5, jvalue[strings::message_id].asInt64());
+ EXPECT_EQ(2, jvalue[strings::connection_key].asInt());
+
+ EXPECT_NEAR(resources->stime, jvalue[strings::stime].asInt(), 1);
+ EXPECT_NEAR(resources->utime, jvalue[strings::utime].asInt(), 1);
+ EXPECT_EQ(resources->memory, jvalue[strings::memory].asInt());
+ delete resources;
+}
+
+} // namespace telemetry_monitor
+} // namespace components
+} // namespace test
diff --git a/src/components/telemetry_monitor/test/protocol_handler_observer_test.cc b/src/components/telemetry_monitor/test/protocol_handler_observer_test.cc
new file mode 100644
index 0000000000..784e809da6
--- /dev/null
+++ b/src/components/telemetry_monitor/test/protocol_handler_observer_test.cc
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "telemetry_monitor/telemetry_monitor.h"
+#include "telemetry_monitor/mock_telemetry_monitor.h"
+#include "protocol_handler/telemetry_observer.h"
+
+namespace test {
+namespace components {
+namespace telemetry_monitor_test {
+
+using namespace telemetry_monitor;
+using ::testing::_;
+
+TEST(ProtocolHandlerObserverTest, MessageProcess) {
+ MockTelemetryMonitor mock_telemetry_monitor;
+
+ ProtocolHandlerObserver pr_handler(&mock_telemetry_monitor);
+ uint32_t message_id = 1;
+ TimevalStruct start_time;
+ start_time.tv_sec = 1;
+ start_time.tv_usec = 0;
+ pr_handler.StartMessageProcess(message_id, start_time);
+
+ typedef protocol_handler::PHTelemetryObserver::MessageMetric MetricType;
+ utils::SharedPtr<MetricType> message_metric = new MetricType();
+ message_metric->message_id = 1;
+ EXPECT_CALL(mock_telemetry_monitor, SendMetric(_));
+ pr_handler.EndMessageProcess(message_metric);
+}
+
+TEST(ProtocolHandlerObserverTest, MessageProcessWithZeroMessageId) {
+ MockTelemetryMonitor mock_telemetry_monitor;
+
+ ProtocolHandlerObserver pr_handler(&mock_telemetry_monitor);
+ uint32_t message_id = 0;
+ TimevalStruct start_time;
+ start_time.tv_sec = 1;
+ start_time.tv_usec = 0;
+ pr_handler.StartMessageProcess(message_id, start_time);
+
+ typedef protocol_handler::PHTelemetryObserver::MessageMetric MetricType;
+ utils::SharedPtr<MetricType> message_metric = new MetricType();
+ message_metric->message_id = 0;
+ EXPECT_CALL(mock_telemetry_monitor, SendMetric(_)).Times(0);
+ pr_handler.EndMessageProcess(message_metric);
+}
+
+} // namespace telemetry_monitor_test
+} // namespace components
+} // namespace test
diff --git a/src/components/telemetry_monitor/test/telemetry_monitor_test.cc b/src/components/telemetry_monitor/test/telemetry_monitor_test.cc
new file mode 100644
index 0000000000..8c48a51304
--- /dev/null
+++ b/src/components/telemetry_monitor/test/telemetry_monitor_test.cc
@@ -0,0 +1,106 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "telemetry_monitor/telemetry_monitor.h"
+#include "protocol_handler/telemetry_observer.h"
+#include "protocol_handler/protocol_handler.h"
+#include "protocol_handler//mock_protocol_handler.h"
+#include "protocol_handler/mock_session_observer.h"
+#include "protocol_handler/mock_protocol_handler_settings.h"
+#include "connection_handler/mock_connection_handler.h"
+#include "transport_manager/mock_transport_manager.h"
+#include "telemetry_monitor/mock_telemetry_observable.h"
+
+using testing::Return;
+using testing::_;
+
+namespace test {
+namespace components {
+namespace telemetry_monitor_test {
+
+using namespace telemetry_monitor;
+
+class StreamerMock : public Streamer {
+ public:
+ StreamerMock(TelemetryMonitor* const server) : Streamer(server) {
+ is_client_connected_ = true;
+ }
+ MOCK_METHOD1(PushMessage, void(utils::SharedPtr<MetricWrapper> metric));
+};
+
+TEST(TelemetryMonitorTest, MessageProcess) {
+ const std::string& server_address = "server_address";
+ const uint16_t port = 12345;
+ MockTelemetryObservable am_observeble;
+
+ transport_manager_test::MockTransportManager transport_manager_mock;
+ testing::NiceMock<connection_handler_test::MockConnectionHandler>
+ connection_handler_mock;
+ testing::NiceMock<
+ ::test::components::protocol_handler_test::MockProtocolHandlerSettings>
+ protocol_handler_settings_mock;
+ ::test::components::protocol_handler_test::MockSessionObserver
+ session_observer_mock;
+
+ const size_t init_value = 1000u;
+ ON_CALL(protocol_handler_settings_mock, maximum_payload_size())
+ .WillByDefault(Return(init_value));
+ ON_CALL(protocol_handler_settings_mock, message_frequency_time())
+ .WillByDefault(Return(init_value));
+ ON_CALL(protocol_handler_settings_mock, malformed_message_filtering())
+ .WillByDefault(Return(init_value));
+ ON_CALL(protocol_handler_settings_mock, multiframe_waiting_timeout())
+ .WillByDefault(Return(init_value));
+ protocol_handler::ProtocolHandlerImpl protocol_handler_mock(
+ protocol_handler_settings_mock,
+ session_observer_mock,
+ connection_handler_mock,
+ transport_manager_mock);
+
+ EXPECT_CALL(am_observeble, SetTelemetryObserver(_));
+ EXPECT_CALL(transport_manager_mock, SetTelemetryObserver(_));
+ telemetry_monitor::TelemetryMonitor telemetry_monitor(server_address, port);
+ StreamerMock streamer_mock(&telemetry_monitor);
+ telemetry_monitor.Start();
+
+ telemetry_monitor.set_streamer(&streamer_mock);
+ telemetry_monitor.Init(
+ &protocol_handler_mock, &am_observeble, &transport_manager_mock);
+ utils::SharedPtr<telemetry_monitor::MetricWrapper> test_metric;
+ EXPECT_CALL(streamer_mock, PushMessage(test_metric));
+ telemetry_monitor.SendMetric(test_metric);
+}
+
+} // namespace telemetry_monitor
+} // namespace components
+} // namespace test
diff --git a/src/components/telemetry_monitor/test/transport_manager_metric_test.cc b/src/components/telemetry_monitor/test/transport_manager_metric_test.cc
new file mode 100644
index 0000000000..9e485ce4f1
--- /dev/null
+++ b/src/components/telemetry_monitor/test/transport_manager_metric_test.cc
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "telemetry_monitor/json_keys.h"
+#include "json/json.h"
+#include "utils/resource_usage.h"
+#include "telemetry_monitor/transport_manager_metric_wrapper.h"
+#include "protocol_handler/telemetry_observer.h"
+
+namespace test {
+namespace components {
+namespace telemetry_monitor_test {
+
+using namespace ::telemetry_monitor;
+
+TEST(TransportManagerMetricWrapper, grabResources) {
+ TransportManagerMecticWrapper metric_test;
+ EXPECT_TRUE(metric_test.grabResources());
+}
+
+TEST(TransportManagerMetricWrapper, GetJsonMetric) {
+ TransportManagerMecticWrapper metric_test;
+
+ TimevalStruct start_time;
+ start_time.tv_sec = 1;
+ start_time.tv_usec = 0;
+
+ TimevalStruct end_time;
+ end_time.tv_sec = 10;
+ end_time.tv_usec = 0;
+ metric_test.message_metric =
+ new transport_manager::TMTelemetryObserver::MessageMetric();
+ metric_test.message_metric->begin = start_time;
+ metric_test.message_metric->end = end_time;
+ metric_test.message_metric->data_size = 1000;
+ Json::Value jvalue = metric_test.GetJsonMetric();
+
+ EXPECT_EQ("null\n", jvalue[strings::stime].toStyledString());
+ EXPECT_EQ("null\n", jvalue[strings::utime].toStyledString());
+ EXPECT_EQ("null\n", jvalue[strings::memory].toStyledString());
+
+ EXPECT_EQ(date_time::DateTime::getuSecs(start_time),
+ jvalue[strings::begin].asInt64());
+ EXPECT_EQ(date_time::DateTime::getuSecs(end_time),
+ jvalue[strings::end].asInt64());
+ EXPECT_EQ(1000, jvalue[strings::data_size].asInt());
+}
+
+TEST(TransportManagerMetricWrapper, GetJsonMetricWithGrabResources) {
+ TransportManagerMecticWrapper metric_test;
+ utils::ResourseUsage* resources = utils::Resources::getCurrentResourseUsage();
+ EXPECT_TRUE(resources != NULL);
+ EXPECT_TRUE(metric_test.grabResources());
+
+ TimevalStruct start_time;
+ start_time.tv_sec = 1;
+ start_time.tv_usec = 0;
+
+ TimevalStruct end_time;
+ end_time.tv_sec = 10;
+ end_time.tv_usec = 0;
+ metric_test.message_metric =
+ new transport_manager::TMTelemetryObserver::MessageMetric();
+ metric_test.message_metric->begin = start_time;
+ metric_test.message_metric->end = end_time;
+
+ metric_test.message_metric->data_size = 1000;
+ Json::Value jvalue = metric_test.GetJsonMetric();
+
+ EXPECT_EQ("\"TransportManager\"\n", jvalue[strings::logger].toStyledString());
+ EXPECT_EQ(date_time::DateTime::getuSecs(start_time),
+ jvalue[strings::begin].asInt64());
+ EXPECT_EQ(date_time::DateTime::getuSecs(end_time),
+ jvalue[strings::end].asInt64());
+ EXPECT_EQ(1000, jvalue[strings::data_size].asInt());
+
+ EXPECT_NEAR(resources->stime, jvalue[strings::stime].asInt(), 1);
+ EXPECT_NEAR(resources->utime, jvalue[strings::utime].asInt(), 1);
+ EXPECT_EQ(resources->memory, jvalue[strings::memory].asInt());
+
+ delete resources;
+}
+
+} // namespace telemetry_monitor
+} // namespace components
+} // namespace test
diff --git a/src/components/telemetry_monitor/test/transport_manager_observer_test.cc b/src/components/telemetry_monitor/test/transport_manager_observer_test.cc
new file mode 100644
index 0000000000..866ff25863
--- /dev/null
+++ b/src/components/telemetry_monitor/test/transport_manager_observer_test.cc
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "telemetry_monitor/mock_telemetry_monitor.h"
+#include "protocol_handler/telemetry_observer.h"
+#include "telemetry_monitor/transport_manager_metric_wrapper.h"
+#include "telemetry_monitor/transport_manager_observer.h"
+
+namespace test {
+namespace components {
+namespace telemetry_monitor_test {
+
+using namespace telemetry_monitor;
+using ::testing::_;
+
+TEST(TransportManagerObserverTest, MessageProcess) {
+ MockTelemetryMonitor mock_telemetry_monitor;
+ TransportManagerObserver tr_observer(&mock_telemetry_monitor);
+ protocol_handler::RawMessage* ptr =
+ new ::protocol_handler::RawMessage(0, 0, NULL, 0);
+ tr_observer.StartRawMsg(ptr);
+ EXPECT_CALL(mock_telemetry_monitor, SendMetric(_));
+ tr_observer.StopRawMsg(ptr);
+ delete ptr;
+}
+
+} // namespace telemetry_monitor
+} // namespace components
+} // namespace test
diff --git a/src/components/test_main.cc b/src/components/test_main.cc
index a0aee7614d..66013d78c4 100755..100644
--- a/src/components/test_main.cc
+++ b/src/components/test_main.cc
@@ -1,10 +1,12 @@
#include "gmock/gmock.h"
#include "utils/logger.h"
-
+#include "utils/custom_string.h"
+namespace custom_str = utils::custom_string;
int main(int argc, char** argv) {
- testing::InitGoogleMock(&argc, argv);
- const int result = RUN_ALL_TESTS();
- DEINIT_LOGGER();
- return result;
+ testing::InitGoogleMock(&argc, argv);
+ ::testing::DefaultValue<custom_str::CustomString>::Set(
+ custom_str::CustomString(""));
+ const int result = RUN_ALL_TESTS();
+ DEINIT_LOGGER();
+ return result;
}
-
diff --git a/src/components/time_tester/CMakeLists.txt b/src/components/time_tester/CMakeLists.txt
deleted file mode 100644
index 24f0fa98e3..0000000000
--- a/src/components/time_tester/CMakeLists.txt
+++ /dev/null
@@ -1,69 +0,0 @@
-# Copyright (c) 2014, Ford Motor Company
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# Redistributions of source code must retain the above copyright notice, this
-# list of conditions and the following disclaimer.
-#
-# Redistributions in binary form must reproduce the above copyright notice,
-# this list of conditions and the following
-# disclaimer in the documentation and/or other materials provided with the
-# distribution.
-#
-# Neither the name of the Ford Motor Company nor the names of its contributors
-# may be used to endorse or promote products derived from this software
-# without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-# POSSIBILITY OF SUCH DAMAGE.
-
-
-set(TIME_TESTER_SRC_DIR ${COMPONENTS_DIR}/time_tester/src)
-
-include_directories(
- include/time_tester
- ${COMPONENTS_DIR}/utils/include/
- ${COMPONENTS_DIR}/protocol_handler/include/
- ${COMPONENTS_DIR}/connection_handler/include/
- ${COMPONENTS_DIR}/transport_manager/include/
- ${COMPONENTS_DIR}/application_manager/include/
- ${COMPONENTS_DIR}/policy/src/policy/include/
- ${COMPONENTS_DIR}/hmi_message_handler/include/
- ${COMPONENTS_DIR}/formatters/include/
- ${COMPONENTS_DIR}/media_manager/include/
- ${COMPONENTS_DIR}/smart_objects/include/
- ${COMPONENTS_DIR}/config_profile/include/
- ${JSONCPP_INCLUDE_DIRECTORY}
- ${CMAKE_BINARY_DIR}/src/components/
- ${LOG4CXX_INCLUDE_DIRECTORY}
-)
-
-set(SOURCES
- ${TIME_TESTER_SRC_DIR}/metric_wrapper.cc
- ${TIME_TESTER_SRC_DIR}/time_manager.cc
- ${TIME_TESTER_SRC_DIR}/application_manager_observer.cc
- ${TIME_TESTER_SRC_DIR}/transport_manager_observer.cc
- ${TIME_TESTER_SRC_DIR}/protocol_handler_observer.cc
- ${TIME_TESTER_SRC_DIR}/application_manager_metric.cc
- ${TIME_TESTER_SRC_DIR}/transport_manager_metric.cc
- ${TIME_TESTER_SRC_DIR}/protocol_handler_metric.cc
-)
-
-add_library("TimeTester" ${SOURCES})
-target_link_libraries("TimeTester" ${LIBRARIES})
-add_dependencies("TimeTester" HMI_API MOBILE_API)
-
-if(BUILD_TESTS)
- add_subdirectory(test)
-endif()
diff --git a/src/components/time_tester/include/time_tester/application_manager_metric.h b/src/components/time_tester/include/time_tester/application_manager_metric.h
deleted file mode 100644
index 1c21c0f722..0000000000
--- a/src/components/time_tester/include/time_tester/application_manager_metric.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_APPLICATION_MANAGER_MECTRIC_WRAPPER_H_
-#define SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_APPLICATION_MANAGER_MECTRIC_WRAPPER_H_
-
-#include <string>
-
-#include "metric_wrapper.h"
-#include "application_manager_observer.h"
-
-
-namespace time_tester {
-
-class ApplicationManagerObserver;
-
-class ApplicationManagerMetricWrapper: public MetricWrapper {
-
- public:
- utils::SharedPtr<application_manager::AMMetricObserver::MessageMetric> message_metric;
-
- protected:
- virtual Json::Value GetJsonMetric();
-};
-
-}
-#endif // SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_APPLICATION_MANAGER_MECTRIC_WRAPPER_H_
diff --git a/src/components/time_tester/include/time_tester/application_manager_observer.h b/src/components/time_tester/include/time_tester/application_manager_observer.h
deleted file mode 100644
index 9c224f8920..0000000000
--- a/src/components/time_tester/include/time_tester/application_manager_observer.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_APPLICATION_MANAGER_OBSERVER_H_
-#define SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_APPLICATION_MANAGER_OBSERVER_H_
-
-#include "utils/message_queue.h"
-#include "application_manager/time_metric_observer.h"
-#include "application_manager_metric.h"
-
-
-namespace time_tester {
-
-class TimeManager;
-
-class ApplicationManagerObserver: public application_manager::AMMetricObserver {
- public:
- explicit ApplicationManagerObserver(TimeManager* time_manager);
- virtual void OnMessage(utils::SharedPtr<MessageMetric> metric);
-
- private:
- TimeManager* time_manager_;
-};
-
-}
-#endif // SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_APPLICATION_MANAGER_OBSERVER_H_
diff --git a/src/components/time_tester/include/time_tester/json_keys.h b/src/components/time_tester/include/time_tester/json_keys.h
deleted file mode 100644
index 532202067f..0000000000
--- a/src/components/time_tester/include/time_tester/json_keys.h
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- *
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_JSON_KEYS_H_
-#define SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_JSON_KEYS_H_
-
-namespace time_tester {
- namespace strings {
- const char logger[] = "logger";
- const char begin[] = "begin";
- const char end[] = "end";
- const char data_size[] = "data_size";
- const char message_id[] = "message_id";
- const char session_id[] = "session_id";
- const char correlation_id[] = "correlation_id";
- const char connection_key[] = "connection_key";
- const char stime[] = "stime";
- const char utime[] = "utime";
- const char memory[] = "RAM";
- }
-}
-#endif // SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_JSON_KEYS_H_
diff --git a/src/components/time_tester/include/time_tester/metric_wrapper.h b/src/components/time_tester/include/time_tester/metric_wrapper.h
deleted file mode 100644
index a1867824d4..0000000000
--- a/src/components/time_tester/include/time_tester/metric_wrapper.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_MECTRIC_H_
-#define SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_MECTRIC_H_
-
-#include <string>
-#include "utils/resource_usage.h"
-#include "json/json.h"
-
-namespace time_tester {
-
-class MetricWrapper {
- utils::ResourseUsage* resources;
- public:
- MetricWrapper();
- /*
- * @brief get current cpu and memory info and store it as member
- */
- bool grabResources();
- virtual std::string GetStyledString();
- virtual ~MetricWrapper();
- protected:
- virtual Json::Value GetJsonMetric();
- void Clear();
-};
-
-
-} // namespace time_tester
-#endif // SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_MECTRIC_H_
diff --git a/src/components/time_tester/include/time_tester/protocol_handler_metric.h b/src/components/time_tester/include/time_tester/protocol_handler_metric.h
deleted file mode 100644
index 47db117a39..0000000000
--- a/src/components/time_tester/include/time_tester/protocol_handler_metric.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_PROTOCOL_HANDLER_MECTRIC_H_
-#define SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_PROTOCOL_HANDLER_MECTRIC_H_
-
-#include <string>
-#include "utils/shared_ptr.h"
-#include "metric_wrapper.h"
-#include "protocol_handler_observer.h"
-
-namespace time_tester {
-
-class ProtocolHandlerMecticWrapper: public MetricWrapper {
-
- public:
- utils::SharedPtr<protocol_handler::PHMetricObserver::MessageMetric> message_metric;
- protected:
- virtual Json::Value GetJsonMetric();
-};
-} // namespace time_tester
-#endif // SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_PROTOCOL_HANDLER_MECTRIC_H_
diff --git a/src/components/time_tester/include/time_tester/protocol_handler_observer.h b/src/components/time_tester/include/time_tester/protocol_handler_observer.h
deleted file mode 100644
index 4c962cfc84..0000000000
--- a/src/components/time_tester/include/time_tester/protocol_handler_observer.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_PROTOCOL_HANDLER_OBSERVER_H_
-#define SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_PROTOCOL_HANDLER_OBSERVER_H_
-
-#include "protocol_handler/time_metric_observer.h"
-#include "utils/message_queue.h"
-
-namespace time_tester {
-
-class TimeManager;
-
-class ProtocolHandlerObserver: public protocol_handler::PHMetricObserver {
- public:
- explicit ProtocolHandlerObserver(TimeManager* time_manager);
-
- virtual void StartMessageProcess(uint32_t message_id, const TimevalStruct& start_time);
-
- virtual void EndMessageProcess(utils::SharedPtr<MessageMetric> m);
-
- private:
- TimeManager* time_manager_;
- std::map<uint32_t, TimevalStruct> time_starts;
-};
-} // namespace time_tester
-#endif // SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_PROTOCOL_HANDLER_OBSERVER_H_
diff --git a/src/components/time_tester/include/time_tester/time_manager.h b/src/components/time_tester/include/time_tester/time_manager.h
deleted file mode 100644
index dc56d3682c..0000000000
--- a/src/components/time_tester/include/time_tester/time_manager.h
+++ /dev/null
@@ -1,98 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TIME_MANAGER_INCLUDE_TIME_MANAGER_MEDIA_MANAGER_H_
-#define SRC_COMPONENTS_TIME_MANAGER_INCLUDE_TIME_MANAGER_MEDIA_MANAGER_H_
-
-#include <string>
-
-#include "utils/shared_ptr.h"
-#include "utils/message_queue.h"
-#include "utils/threads/thread.h"
-#include "utils/singleton.h"
-#include "utils/threads/thread_delegate.h"
-#include "metric_wrapper.h"
-#include "application_manager_observer.h"
-#include "application_manager/application_manager_impl.h"
-#include "transport_manager_observer.h"
-#include "transport_manager/transport_manager_impl.h"
-#include "protocol_handler_observer.h"
-#include "protocol_handler/protocol_handler_impl.h"
-
-namespace time_tester {
-
-using ::utils::MessageQueue;
-
-class TimeManager {
- public:
- TimeManager();
- ~TimeManager();
- void Init(protocol_handler::ProtocolHandlerImpl* ph);
- void Stop();
- void SendMetric(utils::SharedPtr<MetricWrapper> metric);
- private:
-
- class Streamer : public threads::ThreadDelegate {
- public:
- explicit Streamer(TimeManager* const server);
- ~Streamer();
- void threadMain() OVERRIDE;
- void exitThreadMain() OVERRIDE;
- bool IsReady() const;
- void Start();
- void Stop();
- bool Send(const std::string &msg);
- void PushMessage(utils::SharedPtr<MetricWrapper> metric);
- volatile bool is_client_connected_;
- private:
- void ShutDownAndCloseSocket(int32_t socket_fd);
- TimeManager* const server_;
- int32_t server_socket_fd_;
- int32_t client_socket_fd_;
- volatile bool stop_flag_;
- MessageQueue<utils::SharedPtr<MetricWrapper> > messages_;
- DISALLOW_COPY_AND_ASSIGN(Streamer);
- };
-
- int16_t port_;
- std::string ip_;
- bool is_ready_;
- threads::Thread* thread_;
- Streamer* streamer_;
- ApplicationManagerObserver app_observer;
- TransportManagerObserver tm_observer;
- ProtocolHandlerObserver ph_observer;
-
- DISALLOW_COPY_AND_ASSIGN(TimeManager);
-};
-} // namespace time_manager
-#endif // SRC_COMPONENTS_TIME_MANAGER_INCLUDE_TIME_MANAGER_MEDIA_MANAGER_H_
diff --git a/src/components/time_tester/include/time_tester/transport_manager_metric.h b/src/components/time_tester/include/time_tester/transport_manager_metric.h
deleted file mode 100644
index 25261b007c..0000000000
--- a/src/components/time_tester/include/time_tester/transport_manager_metric.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_TRANSPORT_MANAGER_MECTRIC_H_
-#define SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_TRANSPORT_MANAGER_MECTRIC_H_
-
-#include <string>
-#include "metric_wrapper.h"
-#include "transport_manager_observer.h"
-
-namespace time_tester {
-
-class TransportManagerMecticWrapper: public MetricWrapper {
- public:
- utils::SharedPtr<transport_manager::TMMetricObserver::MessageMetric> message_metric;
- protected:
- virtual Json::Value GetJsonMetric();
-};
-} // namespace time_tester
-#endif // SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_TRANSPORT_MANAGER_MECTRIC_H_
diff --git a/src/components/time_tester/include/time_tester/transport_manager_observer.h b/src/components/time_tester/include/time_tester/transport_manager_observer.h
deleted file mode 100644
index bd46ba0822..0000000000
--- a/src/components/time_tester/include/time_tester/transport_manager_observer.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_TRANSPORT_MANAGER_OBSERVER_H_
-#define SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_TRANSPORT_MANAGER_OBSERVER_H_
-
-#include "transport_manager/time_metric_observer.h"
-#include "utils/message_queue.h"
-#include "utils/date_time.h"
-
-namespace time_tester {
-
-class TimeManager;
-
-class TransportManagerObserver: public transport_manager::TMMetricObserver {
- public:
- explicit TransportManagerObserver(TimeManager* time_manager);
- virtual void StartRawMsg(const protocol_handler::RawMessage* ptr);
- virtual void StopRawMsg(const protocol_handler::RawMessage* ptr);
- private:
- TimeManager* time_manager_;
- std::map<const protocol_handler::RawMessage*, TimevalStruct> time_starts;
-};
-} // namespace time_tester
-#endif // SRC_COMPONENTS_TIME_TESTER_INCLUDE_TIME_TESTER_TRANSPORT_MANAGER_OBSERVER_H_
diff --git a/src/components/time_tester/src/application_manager_metric.cc b/src/components/time_tester/src/application_manager_metric.cc
deleted file mode 100644
index 251323dc4f..0000000000
--- a/src/components/time_tester/src/application_manager_metric.cc
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "application_manager_metric.h"
-#include "json_keys.h"
-#include "application_manager/smart_object_keys.h"
-
-namespace time_tester {
-
-Json::Value ApplicationManagerMetricWrapper::GetJsonMetric() {
- Json::Value result = MetricWrapper::GetJsonMetric();
- result[strings::logger] = "ApplicationManager";
- result[strings::begin] =
- Json::Int64(date_time::DateTime::getuSecs(message_metric->begin));
- result[strings::end] =
- Json::Int64(date_time::DateTime::getuSecs(message_metric->end));
- const NsSmartDeviceLink::NsSmartObjects::SmartObject& params =
- message_metric->message->getElement(application_manager::strings::params);
- result[strings::correlation_id] =
- params[application_manager::strings::correlation_id].asInt();
- result[strings::connection_key] =
- params[application_manager::strings::connection_key].asInt();
- return result;
-}
-} // namespace time_tester
diff --git a/src/components/time_tester/src/application_manager_observer.cc b/src/components/time_tester/src/application_manager_observer.cc
deleted file mode 100644
index c0d87a0551..0000000000
--- a/src/components/time_tester/src/application_manager_observer.cc
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-#include "application_manager_observer.h"
-#include "utils/shared_ptr.h"
-#include "time_manager.h"
-#include "application_manager_metric.h"
-
-namespace time_tester {
-
-ApplicationManagerObserver::ApplicationManagerObserver(TimeManager* time_manager):
- time_manager_(time_manager) {
-}
-
-void ApplicationManagerObserver::OnMessage(utils::SharedPtr<MessageMetric> metric) {
- ApplicationManagerMetricWrapper* m = new ApplicationManagerMetricWrapper();
- m->message_metric = metric;
- m->grabResources();
- time_manager_->SendMetric(m);
-}
-} // namespace time_tester
diff --git a/src/components/time_tester/src/metric_wrapper.cc b/src/components/time_tester/src/metric_wrapper.cc
deleted file mode 100644
index 2922bf35cb..0000000000
--- a/src/components/time_tester/src/metric_wrapper.cc
+++ /dev/null
@@ -1,46 +0,0 @@
-#include "metric_wrapper.h"
-#include "json_keys.h"
-
-namespace time_tester {
-
- MetricWrapper::MetricWrapper():
- resources(NULL) {
- }
-
-bool MetricWrapper::grabResources() {
- Clear();
- resources = utils::Resources::getCurrentResourseUsage();
- if (NULL != resources) {
- return true;
- } else {
- return false;
- }
- flush(std::cout);
-}
-
-std::string MetricWrapper::GetStyledString() {
- return GetJsonMetric().toStyledString();
-}
-
-Json::Value MetricWrapper::GetJsonMetric() {
- Json::Value result;
- if (resources) {
- result[strings::stime] = resources->stime;
- result[strings::utime] = resources->utime;
- result[strings::memory] = resources->memory;
- }
- return result;
-}
-
-void MetricWrapper::Clear() {
- if (NULL != resources) {
- delete resources;
- resources = NULL;
- }
-}
-
-MetricWrapper::~MetricWrapper() {
- Clear();
-}
-
-}
diff --git a/src/components/time_tester/src/protocol_handler_metric.cc b/src/components/time_tester/src/protocol_handler_metric.cc
deleted file mode 100644
index 93e08642f1..0000000000
--- a/src/components/time_tester/src/protocol_handler_metric.cc
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "protocol_handler_metric.h"
-#include "json/json.h"
-#include "json_keys.h"
-
-namespace time_tester {
-
-Json::Value ProtocolHandlerMecticWrapper::GetJsonMetric() {
- Json::Value result = MetricWrapper::GetJsonMetric();
- result[strings::logger] = "ProtocolHandler";
- result[strings::begin] =
- Json::Int64(date_time::DateTime::getuSecs(message_metric->begin));
- result[strings::end] =
- Json::Int64(date_time::DateTime::getuSecs(message_metric->end));
- result[strings::message_id] = message_metric->message_id;
- result[strings::connection_key] = message_metric->connection_key;
- return result;
-}
-
-} // namespace time_tester
diff --git a/src/components/time_tester/src/protocol_handler_observer.cc b/src/components/time_tester/src/protocol_handler_observer.cc
deleted file mode 100644
index 0ad6ec1c0d..0000000000
--- a/src/components/time_tester/src/protocol_handler_observer.cc
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "protocol_handler_observer.h"
-#include "utils/date_time.h"
-#include "protocol_handler_metric.h"
-#include "time_manager.h"
-
-namespace time_tester {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")
-
-ProtocolHandlerObserver::ProtocolHandlerObserver(TimeManager *time_manager):
- time_manager_(time_manager) {
-}
-
-void ProtocolHandlerObserver::StartMessageProcess(uint32_t message_id,
- const TimevalStruct &start_time) {
- if (message_id == 0) {
- return;
- }
- if (time_starts.find(message_id) != time_starts.end()) {
- LOG4CXX_INFO(logger_, "Message ID already wait for stop processing" << message_id);
- return;
- }
- time_starts[message_id] = start_time;
-}
-
-void ProtocolHandlerObserver::EndMessageProcess(utils::SharedPtr<MessageMetric> m) {
- uint32_t message_id = m->message_id;
- std::map<uint32_t, TimevalStruct>::const_iterator it = time_starts.find(message_id);
- if (it == time_starts.end()) {
- LOG4CXX_WARN(logger_, "Cant find start time for message" << message_id);
- return;
- }
- m->begin= time_starts[message_id];
- m->end = date_time::DateTime::getCurrentTime();
- ProtocolHandlerMecticWrapper* metric = new ProtocolHandlerMecticWrapper();
- metric->message_metric = m;
- metric->grabResources();
- time_manager_->SendMetric(metric);
-}
-} //namespace time_tester
diff --git a/src/components/time_tester/src/time_manager.cc b/src/components/time_tester/src/time_manager.cc
deleted file mode 100644
index db389dbda0..0000000000
--- a/src/components/time_tester/src/time_manager.cc
+++ /dev/null
@@ -1,253 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "time_manager.h"
-
-#include <sys/socket.h>
-#include <sys/types.h>
-#include <sys/select.h>
-#include <sys/time.h>
-#include <netinet/in.h>
-#include <arpa/inet.h>
-#include <unistd.h>
-#include <string.h>
-
-#include "transport_manager/transport_manager_default.h"
-#include "config_profile/profile.h"
-#include "utils/resource_usage.h"
-
-namespace time_tester {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "TimeManager")
-
-TimeManager::TimeManager():
- thread_(NULL),
- streamer_(NULL),
- app_observer(this),
- tm_observer(this),
- ph_observer(this) {
- ip_ = profile::Profile::instance()->server_address();
- port_ = profile::Profile::instance()->time_testing_port();
- streamer_ = new Streamer(this);
- thread_ = threads::CreateThread("TimeManager", streamer_ );
-}
-
-TimeManager::~TimeManager() {
- Stop();
-}
-
-void TimeManager::Init(protocol_handler::ProtocolHandlerImpl* ph) {
- LOG4CXX_AUTO_TRACE(logger_);
- DCHECK(ph);
- if (!ph) {
- LOG4CXX_DEBUG(logger_, "ProtocolHandler poiner is NULL");
- return;
- }
-
- application_manager::ApplicationManagerImpl::instance()->SetTimeMetricObserver(&app_observer);
- transport_manager::TransportManagerDefault::instance()->SetTimeMetricObserver(&tm_observer);
- ph->SetTimeMetricObserver(&ph_observer);
- thread_->start(threads::ThreadOptions());
-}
-
-void TimeManager::Stop() {
- LOG4CXX_AUTO_TRACE(logger_);
- threads::DeleteThread(thread_);
- thread_ = NULL;
-}
-
-void TimeManager::SendMetric(utils::SharedPtr<MetricWrapper> metric) {
- if ((NULL != streamer_ )&& streamer_->is_client_connected_) {
- streamer_->PushMessage(metric);
- }
-}
-
-TimeManager::Streamer::Streamer(
- TimeManager* const server)
- : is_client_connected_(false),
- server_(server),
- server_socket_fd_(0),
- client_socket_fd_(0),
- stop_flag_(false) {
-}
-
-TimeManager::Streamer::~Streamer() {
- Stop();
-}
-
-void TimeManager::Streamer::threadMain() {
- LOG4CXX_AUTO_TRACE(logger_);
-
- Start();
- while (!stop_flag_) {
- LOG4CXX_INFO(logger_, "Server socket is listening ");
- client_socket_fd_ = accept(server_socket_fd_, NULL, NULL);
- if (0 > client_socket_fd_) {
- LOG4CXX_ERROR(logger_, "Cant open socket . Socket is busy ");
- Stop();
- break;
- }
- LOG4CXX_INFO(logger_, "Client connected");
-
- is_client_connected_ = true;
- while (is_client_connected_) {
- while (!messages_.empty()) {
- utils::SharedPtr<MetricWrapper> metric = messages_.pop();
- is_client_connected_ = Send(metric->GetStyledString());
- }
-
- if (!IsReady()) {
- LOG4CXX_INFO(logger_, "Client disconnected.");
- break;
- }
-
- messages_.wait();
- }
- }
-}
-
-void TimeManager::Streamer::exitThreadMain() {
- LOG4CXX_AUTO_TRACE(logger_);
- Stop();
- messages_.Shutdown();
-}
-
-void TimeManager::Streamer::Start() {
- LOG4CXX_AUTO_TRACE(logger_);
- server_socket_fd_ = socket(AF_INET, SOCK_STREAM, 0);
-
- if (0 >= server_socket_fd_) {
- LOG4CXX_ERROR_EXT(logger_, "Server open error");
- return;
- } else {
- LOG4CXX_DEBUG(logger_, "Server socket : " << server_socket_fd_);
- }
-
- int32_t optval = 1;
- if (-1 == setsockopt(server_socket_fd_, SOL_SOCKET, SO_REUSEADDR,
- &optval, sizeof optval)) {
- LOG4CXX_ERROR_EXT(logger_, "Unable to set sockopt");
- return;
- }
-
- sockaddr_in serv_addr_ = { 0 };
- serv_addr_.sin_addr.s_addr = inet_addr(server_->ip_.c_str());
- serv_addr_.sin_family = AF_INET;
- serv_addr_.sin_port = htons(server_->port_);
-
- if (-1 == bind(server_socket_fd_,
- reinterpret_cast<struct sockaddr*>(&serv_addr_),
- sizeof(serv_addr_))) {
- LOG4CXX_ERROR(logger_, "Unable to bind server "
- << server_->ip_.c_str() << ':' << server_->port_);
- return;
- }
- if (-1 == listen(server_socket_fd_, 1)) {
- LOG4CXX_ERROR(logger_, "Streamer listen error " << strerror(errno) );
- return;
- }
-}
-
-void TimeManager::Streamer::ShutDownAndCloseSocket(int32_t socket_fd) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (0 < socket_fd){
- LOG4CXX_INFO(logger_, "Shutdown socket");
- if (-1 == ::shutdown(socket_fd, SHUT_RDWR)) {
- LOG4CXX_ERROR(logger_, "Unable to shutdown socket");
- }
- if (-1 == close(socket_fd)) {
- LOG4CXX_ERROR(logger_, "Unable to close socket");
- }
- } else {
- LOG4CXX_WARN(logger_, "Socket in not connected: " << socket_fd);
- }
-}
-
-void TimeManager::Streamer::Stop() {
- LOG4CXX_AUTO_TRACE(logger_);
- if (stop_flag_) {
- LOG4CXX_WARN(logger_, "Already Stopped");
- return;
- }
- stop_flag_ = true;
- messages_.Reset();
- LOG4CXX_WARN(logger_, "Stop server_socket_fd_");
- ShutDownAndCloseSocket(server_socket_fd_);
- server_socket_fd_ = -1;
-
- LOG4CXX_WARN(logger_, "Stop client_socket_fd_");
- ShutDownAndCloseSocket(client_socket_fd_);
- client_socket_fd_ = -1;
- is_client_connected_ = false;
-}
-
-bool TimeManager::Streamer::IsReady() const {
- bool result = true;
- fd_set fds;
- FD_ZERO(&fds);
- FD_SET(client_socket_fd_, &fds);
- TimevalStruct tv = {0, 0};
- tv.tv_sec = 5; // set a 5 second timeout
- tv.tv_usec = 0;
-
- const int retval = select(client_socket_fd_ + 1, 0, &fds, 0, &tv);
-
- if (-1 == retval) {
- LOG4CXX_ERROR_EXT(logger_, "An error occurred");
- result = false;
- } else if (0 == retval) {
- LOG4CXX_ERROR_EXT(logger_, "The timeout expired");
- result = false;
- }
-
- return result;
-}
-
-bool TimeManager::Streamer::Send(const std::string& msg) {
- LOG4CXX_AUTO_TRACE(logger_);
- if (!IsReady()) {
- LOG4CXX_ERROR_EXT(logger_, " Socket is not ready");
- return false;
- }
-
- if (-1 == ::send(client_socket_fd_, msg.c_str(),
- msg.size(), MSG_NOSIGNAL)) {
- LOG4CXX_ERROR_EXT(logger_, " Unable to send");
- return false;
- }
- return true;
-}
-
-void TimeManager::Streamer::PushMessage(utils::SharedPtr<MetricWrapper> metric) {
- messages_.push(metric);
-}
-} // namespace time_tester
diff --git a/src/components/time_tester/src/transport_manager_metric.cc b/src/components/time_tester/src/transport_manager_metric.cc
deleted file mode 100644
index a7c9ecb5a2..0000000000
--- a/src/components/time_tester/src/transport_manager_metric.cc
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "transport_manager_metric.h"
-#include "json/json.h"
-#include "json_keys.h"
-#include "application_manager/smart_object_keys.h"
-
-namespace time_tester {
-
-Json::Value TransportManagerMecticWrapper::GetJsonMetric() {
- Json::Value result = MetricWrapper::GetJsonMetric();
- result[strings::logger] = "TransportManager";
- result[strings::begin] =
- Json::Int64(date_time::DateTime::getuSecs(message_metric->begin));
- result[strings::end] =
- Json::Int64(date_time::DateTime::getuSecs(message_metric->end));
- result[strings::data_size] = static_cast<uint32_t>(message_metric->data_size);
- return result;
-}
-
-} // namespace time_tester
diff --git a/src/components/time_tester/src/transport_manager_observer.cc b/src/components/time_tester/src/transport_manager_observer.cc
deleted file mode 100644
index 6c63a576e7..0000000000
--- a/src/components/time_tester/src/transport_manager_observer.cc
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-#include "transport_manager_observer.h"
-
-#include <time.h>
-
-#include "transport_manager_metric.h"
-#include "time_manager.h"
-
-namespace time_tester {
-
-TransportManagerObserver::TransportManagerObserver(TimeManager* time_manager):
- time_manager_ (time_manager) {
-}
-
-void TransportManagerObserver::StartRawMsg(const protocol_handler::RawMessage* ptr) {
- time_starts[ptr] = date_time::DateTime::getCurrentTime();
-}
-
-void TransportManagerObserver::StopRawMsg(const protocol_handler::RawMessage* ptr) {
- std::map<const protocol_handler::RawMessage*, TimevalStruct>::const_iterator it;
- it = time_starts.find(ptr);
- if (it != time_starts.end()) {
- TransportManagerMecticWrapper* m = new TransportManagerMecticWrapper();
- m->message_metric = new transport_manager::TMMetricObserver::MessageMetric();
- m->message_metric->begin = it->second;
- m->message_metric->end = date_time::DateTime::getCurrentTime();
- m->message_metric->data_size = ptr->data_size();
- m->grabResources();
- time_manager_->SendMetric(m);
- }
-}
-
-} //namespace time_tester
diff --git a/src/components/time_tester/test/CMakeLists.txt b/src/components/time_tester/test/CMakeLists.txt
deleted file mode 100644
index 006f6a430f..0000000000
--- a/src/components/time_tester/test/CMakeLists.txt
+++ /dev/null
@@ -1,93 +0,0 @@
-# Copyright (c) 2015, Ford Motor Company
-# All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are met:
-#
-# Redistributions of source code must retain the above copyright notice, this
-# list of conditions and the following disclaimer.
-#
-# Redistributions in binary form must reproduce the above copyright notice,
-# this list of conditions and the following
-# disclaimer in the documentation and/or other materials provided with the
-# distribution.
-#
-# Neither the name of the Ford Motor Company nor the names of its contributors
-# may be used to endorse or promote products derived from this software
-# without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
-# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
-# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
-# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
-# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
-# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
-# POSSIBILITY OF SUCH DAMAGE.
-
-if(BUILD_TESTS)
-
-include_directories (
- ${CMAKE_SOURCE_DIR}/src/3rd_party-static/gmock-1.7.0/include
- ${CMAKE_SOURCE_DIR}/src/3rd_party-static/gmock-1.7.0/gtest/include
- ${COMPONENTS_DIR}/include/utils
- ${COMPONENTS_DIR}/include/protocol_handler
- ${COMPONENTS_DIR}/time_tester/include
- ${COMPONENTS_DIR}/utils/include
- ${COMPONENTS_DIR}/protocol_handler/include
- ${COMPONENTS_DIR}/application_manager/include
- ${COMPONENTS_DIR}/protocol_handler/test
- )
-
-
-set(testSources
- #metric_wrapper_test.cc
- #time_manager_test.cc
- #protocol_handler_metric_test.cc
- protocol_handler_observer_test.cc
- #transport_manager_metric_test.cc
- transport_manager_observer_test.cc
- #application_manager_metric_test.cc
- application_manager_observer_test.cc
-)
-
-set(testLibraries
- gmock
- TimeTester
- jsoncpp
- Utils
- MediaManager
- ProtocolHandler
- v4_protocol_v1_2_no_extra
- SmartObjects
- ProtocolLibrary
- ConfigProfile
- connectionHandler
- ApplicationManager
- Resumption
- jsoncpp
- transport_manager
- MediaManager
- ProtocolHandler
-)
-
-if (BUILD_USB_SUPPORT)
- list(APPEND testLibraries Libusb-1.0.16)
-endif()
-
-if (BUILD_BT_SUPPORT)
- list(APPEND testLibraries bluetooth)
-endif()
-
-if (BUILD_AVAHI_SUPPORT)
- list(APPEND testLibraries avahi-client avahi-common)
-endif()
-
-file(COPY log4cxx.properties DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
-
-create_test("time_tester_test" "${testSources}" "${testLibraries}")
-
-endif()
diff --git a/src/components/time_tester/test/application_manager_metric_test.cc b/src/components/time_tester/test/application_manager_metric_test.cc
deleted file mode 100644
index 7d09cc85c9..0000000000
--- a/src/components/time_tester/test/application_manager_metric_test.cc
+++ /dev/null
@@ -1,118 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "gtest/gtest.h"
-#include "json_keys.h"
-#include "utils/resource_usage.h"
-#include "application_manager/smart_object_keys.h"
-#include "application_manager_metric.h"
-
-namespace test {
-namespace components {
-namespace time_tester_test {
-
-using namespace ::time_tester;
-
-TEST(ApplicationManagerMetricWrapper, grabResources) {
- ApplicationManagerMetricWrapper metric_test;
- EXPECT_TRUE(metric_test.grabResources());
-}
-
-TEST(ApplicationManagerMetricWrapper, GetJsonMetric) {
- ApplicationManagerMetricWrapper metric_test;
-
- TimevalStruct start_time;
- start_time.tv_sec = 1;
- start_time.tv_usec = 0;
-
- TimevalStruct end_time;
- end_time.tv_sec = 10;
- end_time.tv_usec = 0;
- metric_test.message_metric = new application_manager::AMMetricObserver::MessageMetric();
- metric_test.message_metric->begin = start_time;
- metric_test.message_metric->end = end_time;
- NsSmartDeviceLink::NsSmartObjects::SmartObject obj;
- obj["params"][application_manager::strings::correlation_id] = 11;
- obj["params"][application_manager::strings::connection_key] = 12;
- metric_test.message_metric->message = new NsSmartDeviceLink::NsSmartObjects::SmartObject(obj);
- Json::Value jvalue = metric_test.GetJsonMetric();
-
- EXPECT_EQ("null\n", jvalue[time_tester::strings::stime].toStyledString());
- EXPECT_EQ("null\n", jvalue[time_tester::strings::utime].toStyledString());
- EXPECT_EQ("null\n", jvalue[time_tester::strings::memory].toStyledString());
-
- EXPECT_EQ(date_time::DateTime::getuSecs(start_time), jvalue[time_tester::strings::begin].asInt64());
- EXPECT_EQ(date_time::DateTime::getuSecs(end_time), jvalue[time_tester::strings::end].asInt64());
- EXPECT_EQ(obj["params"][application_manager::strings::correlation_id].asInt(), jvalue[time_tester::strings::correlation_id].asInt64());
- EXPECT_EQ(obj["params"][application_manager::strings::connection_key].asInt(), jvalue[time_tester::strings::connection_key].asInt());
-}
-
-TEST(ApplicationManagerMetricWrapper, GetJsonMetricWithGrabResources) {
- ApplicationManagerMetricWrapper metric_test;
- utils::ResourseUsage* resources = utils::Resources::getCurrentResourseUsage();
- EXPECT_TRUE(metric_test.grabResources());
-
- TimevalStruct start_time;
- start_time.tv_sec = 1;
- start_time.tv_usec = 0;
-
- TimevalStruct end_time;
- end_time.tv_sec = 10;
- end_time.tv_usec = 0;
-
- metric_test.message_metric = new application_manager::AMMetricObserver::MessageMetric();
- metric_test.message_metric->begin = start_time;
- metric_test.message_metric->end = end_time;
- NsSmartDeviceLink::NsSmartObjects::SmartObject obj;
- obj["params"][application_manager::strings::correlation_id] = 11;
- obj["params"][application_manager::strings::connection_key] = 12;
- metric_test.message_metric->message = new NsSmartDeviceLink::NsSmartObjects::SmartObject(obj);
- Json::Value jvalue = metric_test.GetJsonMetric();
-
- EXPECT_EQ(date_time::DateTime::getuSecs(start_time), jvalue[time_tester::strings::begin].asInt64());
- EXPECT_EQ(date_time::DateTime::getuSecs(end_time), jvalue[time_tester::strings::end].asInt64());
- EXPECT_EQ(obj["params"][application_manager::strings::correlation_id].asInt(), jvalue[time_tester::strings::correlation_id].asInt64());
- EXPECT_EQ(obj["params"][application_manager::strings::connection_key].asInt(), jvalue[time_tester::strings::connection_key].asInt());
-
- EXPECT_EQ(date_time::DateTime::getuSecs(start_time), jvalue[time_tester::strings::begin].asInt64());
- EXPECT_EQ(date_time::DateTime::getuSecs(end_time), jvalue[time_tester::strings::end].asInt64());
-
- EXPECT_NEAR(resources->stime, jvalue[time_tester::strings::stime].asInt(),1);
- EXPECT_NEAR(resources->utime, jvalue[time_tester::strings::utime].asInt(),1);
- EXPECT_EQ(resources->memory, jvalue[time_tester::strings::memory].asInt());
-
- delete resources;
-}
-
-} // namespace time_tester
-} // namespace components
-} // namespace test
diff --git a/src/components/time_tester/test/application_manager_observer_test.cc b/src/components/time_tester/test/application_manager_observer_test.cc
deleted file mode 100644
index f63394e4f2..0000000000
--- a/src/components/time_tester/test/application_manager_observer_test.cc
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "gtest/gtest.h"
-#include "include/time_manager_mock.h"
-#include "application_manager/time_metric_observer.h"
-#include "application_manager_metric.h"
-#include "application_manager_observer.h"
-#include "utils/shared_ptr.h"
-#include "time_manager.h"
-
-namespace test {
-namespace components {
-namespace time_tester_test {
-
-using namespace time_tester;
-using ::testing::_;
-
-TEST(ApplicationManagerObserver, DISABLED_CallOnMessage) {
- TimeManagerMock time_manager_mock;
- ApplicationManagerObserver app_observer(&time_manager_mock);
- typedef application_manager::AMMetricObserver::MessageMetric AMMetric;
- utils::SharedPtr<AMMetric> ptr = application_manager::AMMetricObserver::MessageMetricSharedPtr();
- EXPECT_CALL(time_manager_mock, SendMetric(_));
- app_observer.OnMessage(ptr);
-}
-
-} // namespace time_tester
-} // namespace components
-} // namespace test
diff --git a/src/components/time_tester/test/include/time_manager_mock.h b/src/components/time_tester/test/include/time_manager_mock.h
deleted file mode 100644
index dfdfa2da7b..0000000000
--- a/src/components/time_tester/test/include/time_manager_mock.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TEST_COMPONENTS_TIME_MANAGER_INCLUDE_TIME_MANAGER_MOCK_H_
-#define TEST_COMPONENTS_TIME_MANAGER_INCLUDE_TIME_MANAGER_MOCK_H_
-
-#include <gmock/gmock.h>
-#include "time_manager.h"
-#include "metric_wrapper.h"
-namespace test {
-namespace components {
-namespace time_tester_test {
-
-using namespace time_tester;
-/*
- * MOCK implementation of ::security_manager::SecurityManager
- */
-class TimeManagerMock : public time_tester::TimeManager {
- public:
- MOCK_METHOD1(Init, void(protocol_handler::ProtocolHandlerImpl* ph));
- MOCK_METHOD0(Stop, void());
- MOCK_METHOD0(Start, void());
- MOCK_METHOD1(SendMetric, void(utils::SharedPtr<MetricWrapper> metric));
-};
-} // time_tester_test
-} // components
-} // test
-#endif // TEST_COMPONENTS_TIME_MANAGER_INCLUDE_TIME_MANAGER_MOCK_H_
diff --git a/src/components/time_tester/test/metric_wrapper_test.cc b/src/components/time_tester/test/metric_wrapper_test.cc
deleted file mode 100644
index 5eddf0fb62..0000000000
--- a/src/components/time_tester/test/metric_wrapper_test.cc
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "gtest/gtest.h"
-#include "metric_wrapper.h"
-#include "json_keys.h"
-#include "json/json.h"
-#include "utils/resource_usage.h"
-
-namespace test {
-namespace components {
-namespace time_tester_test {
-
-using namespace ::time_tester;
-
-TEST(MetricWrapper, grabResources) {
- MetricWrapper metric_test;
- EXPECT_TRUE(metric_test.grabResources());
-}
-
-TEST(MetricWrapper, GetJsonMetricWithoutGrab) {
- MetricWrapper metric_test;
- Json::Value jvalue = metric_test.GetJsonMetric();
-
- EXPECT_EQ("null\n", jvalue[strings::stime].toStyledString());
- EXPECT_EQ("null\n", jvalue[strings::utime].toStyledString());
- EXPECT_EQ("null\n", jvalue[strings::memory].toStyledString());
-}
-
-TEST(MetricWrapper, GetJsonMetricWithGrabResources) {
- MetricWrapper metric_test;
- utils::ResourseUsage* resources = utils::Resources::getCurrentResourseUsage();
- EXPECT_TRUE(resources != NULL);
- EXPECT_TRUE(metric_test.grabResources());
- Json::Value jvalue = metric_test.GetJsonMetric();
-
- EXPECT_TRUE(jvalue[strings::stime].isInt());
- EXPECT_TRUE(jvalue[strings::utime].isInt());
- EXPECT_TRUE(jvalue[strings::memory].isInt());
- EXPECT_NE("null/n", jvalue[strings::stime].toStyledString());
- EXPECT_NE("null/n", jvalue[strings::utime].toStyledString());
- EXPECT_NE("null/n", jvalue[strings::memory].toStyledString());
-
- EXPECT_NEAR(resources->stime, jvalue[strings::stime].asInt(),1);
- EXPECT_NEAR(resources->utime, jvalue[strings::utime].asInt(),1);
- EXPECT_EQ(resources->memory, jvalue[strings::memory].asInt());
-
- delete resources;
-}
-
-} // namespace time_tester
-} // namespace components
-} // namespace test
diff --git a/src/components/time_tester/test/protocol_handler_metric_test.cc b/src/components/time_tester/test/protocol_handler_metric_test.cc
deleted file mode 100644
index 150e1205fe..0000000000
--- a/src/components/time_tester/test/protocol_handler_metric_test.cc
+++ /dev/null
@@ -1,119 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "gtest/gtest.h"
-#include "json_keys.h"
-#include "json/json.h"
-#include "utils/resource_usage.h"
-#include "protocol_handler_metric.h"
-#include "protocol_handler/time_metric_observer.h"
-
-namespace test {
-namespace components {
-namespace time_tester_test {
-
-using namespace ::time_tester;
-
-TEST(ProtocolHandlerMetricTest, grabResources) {
- ProtocolHandlerMecticWrapper metric_test;
- EXPECT_TRUE(metric_test.grabResources());
-}
-
-TEST(ProtocolHandlerMetricTest, GetJsonMetric) {
- ProtocolHandlerMecticWrapper metric_test;
-
- TimevalStruct start_time;
- start_time.tv_sec = 1;
- start_time.tv_usec = 0;
-
- TimevalStruct end_time;
- end_time.tv_sec = 10;
- end_time.tv_usec = 0;
- metric_test.message_metric = new protocol_handler::PHMetricObserver::MessageMetric();
- metric_test.message_metric->begin = start_time;
- metric_test.message_metric->end = end_time;
- metric_test.message_metric->message_id = 5;
- metric_test.message_metric->connection_key = 2;
- Json::Value jvalue = metric_test.GetJsonMetric();
-
- EXPECT_EQ("\"ProtocolHandler\"\n", jvalue[strings::logger].toStyledString());
- EXPECT_EQ("null\n", jvalue[strings::stime].toStyledString());
- EXPECT_EQ("null\n", jvalue[strings::utime].toStyledString());
- EXPECT_EQ("null\n", jvalue[strings::memory].toStyledString());
-
- EXPECT_EQ(date_time::DateTime::getuSecs(start_time), jvalue[strings::begin].asInt64());
- EXPECT_EQ(date_time::DateTime::getuSecs(end_time), jvalue[strings::end].asInt64());
- EXPECT_EQ(5, jvalue[strings::message_id].asInt64());
- EXPECT_EQ(2, jvalue[strings::connection_key].asInt());
-}
-
-TEST(ProtocolHandlerMetricTest, GetJsonMetricWithGrabResources) {
- ProtocolHandlerMecticWrapper metric_test;
- utils::ResourseUsage* resources = utils::Resources::getCurrentResourseUsage();
- EXPECT_TRUE(resources != NULL);
- EXPECT_TRUE(metric_test.grabResources());
-
- TimevalStruct start_time;
- start_time.tv_sec = 1;
- start_time.tv_usec = 0;
-
- TimevalStruct end_time;
- end_time.tv_sec = 10;
- end_time.tv_usec = 0;
- metric_test.message_metric = new protocol_handler::PHMetricObserver::MessageMetric();
- metric_test.message_metric->begin = start_time;
- metric_test.message_metric->end = end_time;
- metric_test.message_metric->message_id = 5;
- metric_test.message_metric->connection_key = 2;
- Json::Value jvalue = metric_test.GetJsonMetric();
-
- EXPECT_TRUE(jvalue[strings::stime].isInt());
- EXPECT_TRUE(jvalue[strings::utime].isInt());
- EXPECT_TRUE(jvalue[strings::memory].isInt());
- EXPECT_NE("null/n", jvalue[strings::stime].toStyledString());
- EXPECT_NE("null/n", jvalue[strings::utime].toStyledString());
- EXPECT_NE("null/n", jvalue[strings::memory].toStyledString());
-
- EXPECT_EQ(date_time::DateTime::getuSecs(start_time), jvalue[strings::begin].asInt64());
- EXPECT_EQ(date_time::DateTime::getuSecs(end_time), jvalue[strings::end].asInt64());
- EXPECT_EQ(5, jvalue[strings::message_id].asInt64());
- EXPECT_EQ(2, jvalue[strings::connection_key].asInt());
-
- EXPECT_NEAR(resources->stime, jvalue[strings::stime].asInt(),1);
- EXPECT_NEAR(resources->utime, jvalue[strings::utime].asInt(),1);
- EXPECT_EQ(resources->memory, jvalue[strings::memory].asInt());
- delete resources;
-}
-
-} // namespace time_tester
-} // namespace components
-} // namespace test
diff --git a/src/components/time_tester/test/protocol_handler_observer_test.cc b/src/components/time_tester/test/protocol_handler_observer_test.cc
deleted file mode 100644
index 8922334aee..0000000000
--- a/src/components/time_tester/test/protocol_handler_observer_test.cc
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "gtest/gtest.h"
-#include "time_manager.h"
-#include "include/time_manager_mock.h"
-#include "protocol_handler/time_metric_observer.h"
-
-namespace test {
-namespace components {
-namespace time_tester_test {
-
-using namespace time_tester;
-using ::testing::_;
-
-TEST(ProtocolHandlerObserverTest, DISABLED_MessageProcess) {
- TimeManagerMock time_manager_mock;
-
- ProtocolHandlerObserver pr_handler(&time_manager_mock);
- uint32_t message_id = 1;
- TimevalStruct start_time;
- start_time.tv_sec = 1;
- start_time.tv_usec = 0;
- pr_handler.StartMessageProcess(message_id, start_time);
-
- typedef protocol_handler::PHMetricObserver::MessageMetric MetricType;
- utils::SharedPtr<MetricType> message_metric = new MetricType();
- message_metric->message_id = 1;
- EXPECT_CALL(time_manager_mock, SendMetric(_));
- pr_handler.EndMessageProcess(message_metric);
-}
-
-TEST(ProtocolHandlerObserverTest, MessageProcessWithZeroMessageId) {
- TimeManagerMock time_manager_mock;
-
- ProtocolHandlerObserver pr_handler(&time_manager_mock);
- uint32_t message_id = 0;
- TimevalStruct start_time;
- start_time.tv_sec = 1;
- start_time.tv_usec = 0;
- pr_handler.StartMessageProcess(message_id, start_time);
-
- typedef protocol_handler::PHMetricObserver::MessageMetric MetricType;
- utils::SharedPtr<MetricType> message_metric = new MetricType();
- message_metric->message_id = 0;
- EXPECT_CALL(time_manager_mock, SendMetric(_)).Times(0);
- pr_handler.EndMessageProcess(message_metric);
-}
-
-} // namespace time_tester
-} // namespace components
-} // namespace test
diff --git a/src/components/time_tester/test/time_manager_test.cc b/src/components/time_tester/test/time_manager_test.cc
deleted file mode 100644
index 60f3bd6814..0000000000
--- a/src/components/time_tester/test/time_manager_test.cc
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "gtest/gtest.h"
-#include "gmock/gmock.h"
-#include "time_manager.h"
-#include "protocol_handler/time_metric_observer.h"
-#include "protocol_handler.h"
-#include "include/protocol_handler_mock.h"
-
-namespace test {
-namespace components {
-namespace time_tester_test {
-
-using namespace time_tester;
-
-class StreamerMock : public Streamer {
- public:
- StreamerMock(TimeManager* const server)
- : Streamer(server) {
- is_client_connected_ = true;
- }
- MOCK_METHOD1(PushMessage,void(utils::SharedPtr<MetricWrapper> metric));
-};
-
-TEST(TimeManagerTest, DISABLED_MessageProcess) {
- //TODO(AK) APPLINK-13351 Disable due to refactor TimeTester
- protocol_handler_test::TransportManagerMock transport_manager_mock;
- protocol_handler::ProtocolHandlerImpl protocol_handler_mock(&transport_manager_mock, 0, 0, 0, 0, 0);
- TimeManager * time_manager = new TimeManager();
- // Streamer will be deleted by Thread
- StreamerMock* streamer_mock = new StreamerMock(time_manager);
- time_manager->set_streamer(streamer_mock);
- time_manager->Init(&protocol_handler_mock);
- utils::SharedPtr<MetricWrapper> test_metric;
- EXPECT_CALL(*streamer_mock, PushMessage(test_metric));
- time_manager->SendMetric(test_metric);
- delete time_manager;
-}
-
-} // namespace time_tester
-} // namespace components
-} // namespace test
diff --git a/src/components/time_tester/test/transport_manager_metric_test.cc b/src/components/time_tester/test/transport_manager_metric_test.cc
deleted file mode 100644
index 2bb09416ed..0000000000
--- a/src/components/time_tester/test/transport_manager_metric_test.cc
+++ /dev/null
@@ -1,110 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "gtest/gtest.h"
-#include "json_keys.h"
-#include "json/json.h"
-#include "utils/resource_usage.h"
-#include "transport_manager_metric.h"
-#include "protocol_handler/time_metric_observer.h"
-
-namespace test {
-namespace components {
-namespace time_tester_test {
-
-using namespace ::time_tester;
-
-TEST(TransportManagerMetricWrapper, grabResources) {
- TransportManagerMecticWrapper metric_test;
- EXPECT_TRUE(metric_test.grabResources());
-}
-
-TEST(TransportManagerMetricWrapper, GetJsonMetric) {
- TransportManagerMecticWrapper metric_test;
-
- TimevalStruct start_time;
- start_time.tv_sec = 1;
- start_time.tv_usec = 0;
-
- TimevalStruct end_time;
- end_time.tv_sec = 10;
- end_time.tv_usec = 0;
- metric_test.message_metric = new transport_manager::TMMetricObserver::MessageMetric();
- metric_test.message_metric->begin = start_time;
- metric_test.message_metric->end = end_time;
- metric_test.message_metric->data_size = 1000;
- Json::Value jvalue = metric_test.GetJsonMetric();
-
- EXPECT_EQ("null\n", jvalue[strings::stime].toStyledString());
- EXPECT_EQ("null\n", jvalue[strings::utime].toStyledString());
- EXPECT_EQ("null\n", jvalue[strings::memory].toStyledString());
-
- EXPECT_EQ(date_time::DateTime::getuSecs(start_time), jvalue[strings::begin].asInt64());
- EXPECT_EQ(date_time::DateTime::getuSecs(end_time), jvalue[strings::end].asInt64());
- EXPECT_EQ(1000, jvalue[strings::data_size].asInt());
-}
-
-TEST(TransportManagerMetricWrapper, GetJsonMetricWithGrabResources) {
- TransportManagerMecticWrapper metric_test;
- utils::ResourseUsage* resources = utils::Resources::getCurrentResourseUsage();
- EXPECT_TRUE(resources != NULL);
- EXPECT_TRUE(metric_test.grabResources());
-
- TimevalStruct start_time;
- start_time.tv_sec = 1;
- start_time.tv_usec = 0;
-
- TimevalStruct end_time;
- end_time.tv_sec = 10;
- end_time.tv_usec = 0;
- metric_test.message_metric = new transport_manager::TMMetricObserver::MessageMetric();
- metric_test.message_metric->begin = start_time;
- metric_test.message_metric->end = end_time;
-
- metric_test.message_metric->data_size = 1000;
- Json::Value jvalue = metric_test.GetJsonMetric();
-
- EXPECT_EQ("\"TransportManager\"\n", jvalue[strings::logger].toStyledString());
- EXPECT_EQ(date_time::DateTime::getuSecs(start_time), jvalue[strings::begin].asInt64());
- EXPECT_EQ(date_time::DateTime::getuSecs(end_time), jvalue[strings::end].asInt64());
- EXPECT_EQ(1000, jvalue[strings::data_size].asInt());
-
- EXPECT_NEAR(resources->stime, jvalue[strings::stime].asInt(),1);
- EXPECT_NEAR(resources->utime, jvalue[strings::utime].asInt(),1);
- EXPECT_EQ(resources->memory, jvalue[strings::memory].asInt());
-
- delete resources;
-}
-
-} // namespace time_tester
-} // namespace components
-} // namespace test
diff --git a/src/components/time_tester/test/transport_manager_observer_test.cc b/src/components/time_tester/test/transport_manager_observer_test.cc
deleted file mode 100644
index 9dcf27bd97..0000000000
--- a/src/components/time_tester/test/transport_manager_observer_test.cc
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "gtest/gtest.h"
-#include "include/time_manager_mock.h"
-#include "protocol_handler/time_metric_observer.h"
-#include "transport_manager_metric.h"
-#include "transport_manager_observer.h"
-
-namespace test {
-namespace components {
-namespace time_tester_test {
-
-using namespace time_tester;
-using ::testing::_;
-
-TEST(TransportManagerObserverTest, DISABLED_MessageProcess) {
- TimeManagerMock time_manager_mock;
- TransportManagerObserver tr_observer(&time_manager_mock);
- protocol_handler::RawMessage* ptr = new ::protocol_handler::RawMessage(0, 0, NULL, 0);
- tr_observer.StartRawMsg(ptr);
- EXPECT_CALL(time_manager_mock, SendMetric(_));
- tr_observer.StopRawMsg(ptr);
- delete ptr;
-}
-
-} // namespace time_tester
-} // namespace components
-} // namespace test
diff --git a/src/components/transport_manager/CMakeLists.txt b/src/components/transport_manager/CMakeLists.txt
index 764f1cdafa..fbe6018d6a 100644
--- a/src/components/transport_manager/CMakeLists.txt
+++ b/src/components/transport_manager/CMakeLists.txt
@@ -60,11 +60,6 @@ set (SOURCES
${TM_SRC_DIR}/tcp/tcp_connection_factory.cc
)
-if (BUILD_AVAHI_SUPPORT)
- list (APPEND SOURCES
- ${TM_SRC_DIR}/tcp/dnssd_service_browser.cc
- )
-endif()
if (BUILD_BT_SUPPORT)
list (APPEND SOURCES
${TM_SRC_DIR}/bluetooth/bluetooth_device_scanner.cc
@@ -109,11 +104,6 @@ if (BUILD_USB_SUPPORT)
endif()
endif(BUILD_USB_SUPPORT)
-
-if (BUILD_AVAHI_SUPPORT)
- target_link_libraries(${target} avahi-common)
-endif()
-
if(ENABLE_LOG)
target_link_libraries(${target} log4cxx -L${LOG4CXX_LIBS_DIRECTORY})
endif()
diff --git a/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_connection_factory.h b/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_connection_factory.h
index 4d1d474377..cdc820e555 100644
--- a/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_connection_factory.h
+++ b/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_connection_factory.h
@@ -48,15 +48,14 @@ class TransportAdapterController;
*/
class BluetoothConnectionFactory : public ServerConnectionFactory {
public:
-
/**
* @brief Constructor.
*
* @param controller Pointer to the device adapter controller.
*/
BluetoothConnectionFactory(TransportAdapterController* controller);
- protected:
+ protected:
/**
* @brief Start BT connection factory.
*/
@@ -68,8 +67,8 @@ class BluetoothConnectionFactory : public ServerConnectionFactory {
* @param device_uid Device unique identifier.
* @param ap_handle Handle of application.
*/
- virtual TransportAdapter::Error CreateConnection(const DeviceUID& device_uid,
- const ApplicationHandle& app_handle);
+ virtual TransportAdapter::Error CreateConnection(
+ const DeviceUID& device_uid, const ApplicationHandle& app_handle);
/**
* @brief
@@ -88,6 +87,7 @@ class BluetoothConnectionFactory : public ServerConnectionFactory {
* @brief Destructor.
*/
virtual ~BluetoothConnectionFactory();
+
private:
TransportAdapterController* controller_;
};
diff --git a/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_device.h b/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_device.h
index f28147a3b5..5194873597 100644
--- a/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_device.h
+++ b/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_device.h
@@ -56,7 +56,6 @@ typedef std::vector<uint8_t> RfcommChannelVector;
*/
class BluetoothDevice : public Device {
public:
-
/**
* @brief Return device unique identifier.
*
@@ -69,9 +68,11 @@ class BluetoothDevice : public Device {
*
* @param address Bluetooth address.
* @param name Human-readable device name.
- * @param rfcomm_channels List of RFCOMM channels where SmartDeviceLink service has been discovered.
+ * @param rfcomm_channels List of RFCOMM channels where SmartDeviceLink
+ *service has been discovered.
**/
- BluetoothDevice(const bdaddr_t& device_address, const char* device_name,
+ BluetoothDevice(const bdaddr_t& device_address,
+ const char* device_name,
const RfcommChannelVector& rfcomm_channels);
/**
@@ -112,7 +113,8 @@ class BluetoothDevice : public Device {
bdaddr_t address_;
/**
- * @brief List of RFCOMM channels where SmartDeviceLink service has been discovered.
+ * @brief List of RFCOMM channels where SmartDeviceLink service has been
+ *discovered.
**/
RfcommChannelVector rfcomm_channels_;
};
diff --git a/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_device_scanner.h b/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_device_scanner.h
index d1bed9b3dc..764b64fef3 100644
--- a/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_device_scanner.h
+++ b/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_device_scanner.h
@@ -62,11 +62,14 @@ class BluetoothDeviceScanner : public DeviceScanner {
/**
* @brief Constructor.
* @param controller Transport adapter controller
- * @param auto_repeat_search true - autorepeated or continous device search, false - search on demand
- * @param repeat_search_pause_sec - pause between device searches, 0 means continous search
+ * @param auto_repeat_search true - autorepeated or continous device search,
+ * false - search on demand
+ * @param repeat_search_pause_sec - pause between device searches, 0 means
+ * continous search
*/
BluetoothDeviceScanner(TransportAdapterController* controller,
- bool auto_repeat_search, int repeat_search_pause_sec);
+ bool auto_repeat_search,
+ int repeat_search_pause_sec);
/**
* @brief Destructor.
*/
@@ -75,8 +78,8 @@ class BluetoothDeviceScanner : public DeviceScanner {
* @brief Main thread initialization.
*/
void Thread();
- protected:
+ protected:
/**
* @brief Start device scanner.
*
@@ -103,12 +106,13 @@ class BluetoothDeviceScanner : public DeviceScanner {
* false - not initialized.
*/
virtual bool IsInitialised() const;
- private:
- class BluetoothDeviceScannerDelegate: public threads::ThreadDelegate {
+ private:
+ class BluetoothDeviceScannerDelegate : public threads::ThreadDelegate {
public:
explicit BluetoothDeviceScannerDelegate(BluetoothDeviceScanner* scanner);
void threadMain() OVERRIDE;
+
private:
BluetoothDeviceScanner* scanner_;
};
@@ -116,7 +120,8 @@ class BluetoothDeviceScanner : public DeviceScanner {
typedef std::vector<uint8_t> RfcommChannelVector;
/**
- * @brief Waits for external scan request or time out for repeated search or terminate request
+ * @brief Waits for external scan request or time out for repeated search or
+ * terminate request
*/
void TimedWaitForDeviceScanRequest();
@@ -126,7 +131,7 @@ class BluetoothDeviceScanner : public DeviceScanner {
* @return List of RFCOMM-channels lists
*/
std::vector<RfcommChannelVector> DiscoverSmartDeviceLinkRFCOMMChannels(
- const std::vector<bdaddr_t>& device_addresses);
+ const std::vector<bdaddr_t>& device_addresses);
/**
* @brief Finds RFCOMM-channels of SDL enabled applications for given device
@@ -134,10 +139,11 @@ class BluetoothDeviceScanner : public DeviceScanner {
* @return true - if search was OK, false if it failed
*/
bool DiscoverSmartDeviceLinkRFCOMMChannels(const bdaddr_t& device_address,
- RfcommChannelVector* discovered);
+ RfcommChannelVector* discovered);
/**
- * @brief Summarizes the total list of devices (paired and scanned) and notifies controller
+ * @brief Summarizes the total list of devices (paired and scanned) and
+ * notifies controller
*/
void UpdateTotalDeviceList();
@@ -147,10 +153,12 @@ class BluetoothDeviceScanner : public DeviceScanner {
void DoInquiry();
/**
- * @brief Checks if given devices have SDL service and creates appropriate BluetoothDevice objects
+ * @brief Checks if given devices have SDL service and creates appropriate
+ * BluetoothDevice objects
* @param bd_address List of bluetooth addresses to check
* @param device_handle HCI handle
- * @param[out] discovered_devices List of created BluetoothDevice objects to fill
+ * @param[out] discovered_devices List of created BluetoothDevice objects to
+ * fill
*/
void CheckSDLServiceOnDevices(const std::vector<bdaddr_t>& bd_address,
int device_handle,
diff --git a/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_socket_connection.h b/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_socket_connection.h
index 3de77ab529..3f524dac0f 100644
--- a/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_socket_connection.h
+++ b/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_socket_connection.h
@@ -48,7 +48,6 @@ class TransportAdapterController;
*/
class BluetoothSocketConnection : public ThreadedSocketConnection {
public:
-
/**
* @brief Constructor.
*
@@ -64,8 +63,8 @@ class BluetoothSocketConnection : public ThreadedSocketConnection {
* @brief Destructor.
*/
virtual ~BluetoothSocketConnection();
- protected:
+ protected:
/**
* @brief Establish connection.
*
diff --git a/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_transport_adapter.h b/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_transport_adapter.h
index 69a588fd37..82e85bac70 100644
--- a/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_transport_adapter.h
+++ b/src/components/transport_manager/include/transport_manager/bluetooth/bluetooth_transport_adapter.h
@@ -49,14 +49,15 @@ class BluetoothTransportAdapter : public TransportAdapterImpl {
/**
* @brief Constructor.
*/
- BluetoothTransportAdapter();
+ BluetoothTransportAdapter(resumption::LastState& last_state,
+ const TransportManagerSettings& settings);
/**
* @brief Destructor.
*/
virtual ~BluetoothTransportAdapter();
- protected:
+ protected:
/**
* @brief Return type of device.
*/
diff --git a/src/components/transport_manager/include/transport_manager/tcp/dnssd_service_browser.h b/src/components/transport_manager/include/transport_manager/tcp/dnssd_service_browser.h
deleted file mode 100644
index 079494d035..0000000000
--- a/src/components/transport_manager/include/transport_manager/tcp/dnssd_service_browser.h
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * \file dnssd_service_browser.h
- * \brief DnssdServiceBrowser class header file.
- *
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TCP_DNSSD_SERVICE_BROWSER_H_
-#define SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TCP_DNSSD_SERVICE_BROWSER_H_
-
-#include <avahi-client/client.h>
-#include <avahi-client/lookup.h>
-#include <avahi-common/error.h>
-#include <avahi-common/thread-watch.h>
-
-#include <string>
-#include <vector>
-
-#include "utils/lock.h"
-#include "transport_manager/transport_adapter/device_scanner.h"
-#include "transport_manager/transport_adapter/transport_adapter.h"
-
-namespace transport_manager {
-
-namespace transport_adapter {
-
-struct DnssdServiceRecord {
- AvahiIfIndex interface;
- AvahiProtocol protocol;
- std::string domain_name;
- std::string host_name;
- std::string name;
- std::string type;
- uint16_t port;
- uint32_t addr;
-};
-
-#define DNSSD_DEFAULT_SERVICE_TYPE "_ford-sdlapp._tcp"
-
-/**
- * @brief DNS service discovery class.
- */
-class DnssdServiceBrowser : public DeviceScanner {
- public:
- /**
- * @brief Constructor.
- *
- * @param controller Pointer to the device adapter controller.
- */
- explicit DnssdServiceBrowser(class TransportAdapterController* controller);
- virtual ~DnssdServiceBrowser();
-
- protected:
- virtual TransportAdapter::Error Init();
- virtual TransportAdapter::Error Scan();
- virtual void Terminate();
- virtual bool IsInitialised() const;
-
- private:
- TransportAdapter::Error CreateAvahiClientAndBrowser();
- void AddService(AvahiIfIndex interface, AvahiProtocol protocol,
- const char *name, const char *type, const char *domain);
- void RemoveService(AvahiIfIndex interface, AvahiProtocol protocol,
- const char *name, const char *type, const char *domain);
-
- void OnClientConnected();
- void OnClientFailure();
-
- DeviceVector PrepareDeviceVector() const;
-
- void ServiceResolved(const DnssdServiceRecord& service_record);
- void ServiceResolveFailed(const DnssdServiceRecord& service_record);
-
- friend void AvahiClientCallback(AvahiClient *avahi_client,
- AvahiClientState avahi_client_state,
- void* data);
- friend void AvahiServiceBrowserCallback(
- AvahiServiceBrowser *avahi_service_browser, AvahiIfIndex interface,
- AvahiProtocol protocol, AvahiBrowserEvent event, const char *name,
- const char *type, const char *domain, AvahiLookupResultFlags flags,
- void* data);
-
- friend void AvahiServiceResolverCallback(
- AvahiServiceResolver* avahi_service_resolver, AvahiIfIndex interface,
- AvahiProtocol protocol, AvahiResolverEvent event, const char* name,
- const char* type, const char* domain, const char* host_name,
- const AvahiAddress* avahi_address, uint16_t port, AvahiStringList* txt,
- AvahiLookupResultFlags flags, void *data);
-
- TransportAdapterController* controller_;
-
- AvahiServiceBrowser* avahi_service_browser_;
- AvahiThreadedPoll* avahi_threaded_poll_;
- AvahiClient* avahi_client_;
-
- typedef std::vector<DnssdServiceRecord> ServiceRecords;
- ServiceRecords service_records_;
-
- sync_primitives::Lock mutex_;
-
- bool initialised_;
-};
-
-} // namespace transport_adapter
-} // namespace transport_manager
-
-#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TCP_DNSSD_SERVICE_BROWSER_H_
diff --git a/src/components/transport_manager/include/transport_manager/tcp/tcp_client_listener.h b/src/components/transport_manager/include/transport_manager/tcp/tcp_client_listener.h
index d5a24f07eb..2640049ecc 100644
--- a/src/components/transport_manager/include/transport_manager/tcp/tcp_client_listener.h
+++ b/src/components/transport_manager/include/transport_manager/tcp/tcp_client_listener.h
@@ -59,7 +59,8 @@ class TcpClientListener : public ClientConnectionListener {
* @param enable_keepalive If true enables TCP keepalive on accepted
*connections
*/
- TcpClientListener(TransportAdapterController* controller, uint16_t port,
+ TcpClientListener(TransportAdapterController* controller,
+ uint16_t port,
bool enable_keepalive);
/**
@@ -70,7 +71,8 @@ class TcpClientListener : public ClientConnectionListener {
/**
* @brief Run TCP client listener.
*
- * @return Error information about possible reason of starting TCP listener listener failure.
+ * @return Error information about possible reason of starting TCP listener
+ *listener failure.
*/
virtual TransportAdapter::Error Init();
@@ -99,6 +101,20 @@ class TcpClientListener : public ClientConnectionListener {
*/
virtual TransportAdapter::Error StopListening();
+#ifdef BUILD_TESTS
+ uint16_t port() const {
+ return port_;
+ }
+
+ int get_socket() const {
+ return socket_;
+ }
+
+ threads::Thread* thread() const {
+ return thread_;
+ }
+#endif // BUILD_TESTS
+
private:
const uint16_t port_;
const bool enable_keepalive_;
@@ -115,6 +131,7 @@ class TcpClientListener : public ClientConnectionListener {
explicit ListeningThreadDelegate(TcpClientListener* parent);
virtual void threadMain();
void exitThreadMain();
+
private:
TcpClientListener* parent_;
};
diff --git a/src/components/transport_manager/include/transport_manager/tcp/tcp_device.h b/src/components/transport_manager/include/transport_manager/tcp/tcp_device.h
index 45bcc405d7..981ba9f6ee 100644
--- a/src/components/transport_manager/include/transport_manager/tcp/tcp_device.h
+++ b/src/components/transport_manager/include/transport_manager/tcp/tcp_device.h
@@ -121,7 +121,7 @@ class TcpDevice : public Device {
*
* @return Application's port No.
*/
- int GetApplicationPort(const ApplicationHandle app_handle) const;
+ virtual int GetApplicationPort(const ApplicationHandle app_handle) const;
/**
* @brief Return address.
diff --git a/src/components/transport_manager/include/transport_manager/tcp/tcp_socket_connection.h b/src/components/transport_manager/include/transport_manager/tcp/tcp_socket_connection.h
index 432a0aa760..4d7901f4f0 100644
--- a/src/components/transport_manager/include/transport_manager/tcp/tcp_socket_connection.h
+++ b/src/components/transport_manager/include/transport_manager/tcp/tcp_socket_connection.h
@@ -77,7 +77,8 @@ class TcpSocketConnection : public ThreadedSocketConnection {
};
/**
- * @brief Class responsible for communication over sockets that originated by server.
+ * @brief Class responsible for communication over sockets that originated by
+ * server.
*/
class TcpServerOiginatedSocketConnection : public ThreadedSocketConnection {
public:
@@ -89,8 +90,8 @@ class TcpServerOiginatedSocketConnection : public ThreadedSocketConnection {
* @param controller Pointer to the device adapter controller.
*/
TcpServerOiginatedSocketConnection(const DeviceUID& device_uid,
- const ApplicationHandle& app_handle,
- TransportAdapterController* controller);
+ const ApplicationHandle& app_handle,
+ TransportAdapterController* controller);
/**
* @brief Destructor.
diff --git a/src/components/transport_manager/include/transport_manager/tcp/tcp_transport_adapter.h b/src/components/transport_manager/include/transport_manager/tcp/tcp_transport_adapter.h
index 5c1582230a..5431b4455d 100644
--- a/src/components/transport_manager/include/transport_manager/tcp/tcp_transport_adapter.h
+++ b/src/components/transport_manager/include/transport_manager/tcp/tcp_transport_adapter.h
@@ -49,7 +49,9 @@ class TcpTransportAdapter : public TransportAdapterImpl {
/**
* @brief Constructor.
*/
- explicit TcpTransportAdapter(uint16_t port);
+ explicit TcpTransportAdapter(uint16_t port,
+ resumption::LastState& last_state,
+ const TransportManagerSettings& settings);
/**
* @brief Destructor.
diff --git a/src/components/transport_manager/include/transport_manager/telemetry_observer.h b/src/components/transport_manager/include/transport_manager/telemetry_observer.h
new file mode 100644
index 0000000000..1097feaecb
--- /dev/null
+++ b/src/components/transport_manager/include/transport_manager/telemetry_observer.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TIME_METRIC_OBSERVER_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TIME_METRIC_OBSERVER_H_
+
+#include "transport_manager/common.h"
+#include "protocol/raw_message.h"
+#include "utils/date_time.h"
+
+namespace transport_manager {
+
+class TMTelemetryObserver {
+ public:
+ struct MessageMetric {
+ TimevalStruct begin;
+ TimevalStruct end;
+ size_t data_size;
+ };
+ virtual void StartRawMsg(const protocol_handler::RawMessage* ptr) = 0;
+ virtual void StopRawMsg(const protocol_handler::RawMessage* ptr) = 0;
+
+ virtual ~TMTelemetryObserver() {}
+};
+} // transport_manager
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TIME_METRIC_OBSERVER_H_
diff --git a/src/components/transport_manager/include/transport_manager/time_metric_observer.h b/src/components/transport_manager/include/transport_manager/time_metric_observer.h
deleted file mode 100644
index ce59a9b4c4..0000000000
--- a/src/components/transport_manager/include/transport_manager/time_metric_observer.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TIME_METRIC_OBSERVER_H_
-#define SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TIME_METRIC_OBSERVER_H_
-
-#include "transport_manager/common.h"
-#include "protocol/raw_message.h"
-#include "utils/date_time.h"
-
-namespace transport_manager {
-
-class TMMetricObserver {
- public:
- struct MessageMetric {
- TimevalStruct begin;
- TimevalStruct end;
- size_t data_size;
- };
- virtual void StartRawMsg(const protocol_handler::RawMessage* ptr) = 0;
- virtual void StopRawMsg(const protocol_handler::RawMessage* ptr) = 0;
-
- virtual ~TMMetricObserver(){}
-};
-} // transport_manager
-#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TIME_METRIC_OBSERVER_H_
diff --git a/src/components/transport_manager/include/transport_manager/transport_adapter/client_connection_listener.h b/src/components/transport_manager/include/transport_manager/transport_adapter/client_connection_listener.h
index 018dd46810..8df2c4d299 100644
--- a/src/components/transport_manager/include/transport_manager/transport_adapter/client_connection_listener.h
+++ b/src/components/transport_manager/include/transport_manager/transport_adapter/client_connection_listener.h
@@ -35,10 +35,8 @@
#include "transport_manager/transport_adapter/transport_adapter.h"
-
namespace transport_manager {
-
namespace transport_adapter {
/**
@@ -49,7 +47,8 @@ class ClientConnectionListener {
/**
* @brief Run client connection listener.
*
- * @return Error information about possible reason of starting client listener failure.
+ * @return Error information about possible reason of starting client listener
+ *failure.
*/
virtual TransportAdapter::Error Init() = 0;
@@ -79,8 +78,7 @@ class ClientConnectionListener {
/**
* @brief Destructor.
*/
- virtual ~ClientConnectionListener() {
- }
+ virtual ~ClientConnectionListener() {}
};
} // namespace transport_adapter
diff --git a/src/components/transport_manager/include/transport_manager/transport_adapter/connection.h b/src/components/transport_manager/include/transport_manager/transport_adapter/connection.h
index e3f0b3d1d7..537e94b055 100644
--- a/src/components/transport_manager/include/transport_manager/transport_adapter/connection.h
+++ b/src/components/transport_manager/include/transport_manager/transport_adapter/connection.h
@@ -58,7 +58,8 @@ class Connection {
*
* @return Error Information about possible reason of sending data failure.
*/
- virtual TransportAdapter::Error SendData(::protocol_handler::RawMessagePtr message) = 0;
+ virtual TransportAdapter::Error SendData(
+ ::protocol_handler::RawMessagePtr message) = 0;
/**
* @brief Disconnect the current connection.
@@ -70,4 +71,4 @@ typedef utils::SharedPtr<Connection> ConnectionSPtr;
} // namespace transport_adapter
} // namespace transport_manager
-#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_ADAPTER_CONNECTION_H_
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_ADAPTER_CONNECTION_H_
diff --git a/src/components/transport_manager/include/transport_manager/transport_adapter/device_scanner.h b/src/components/transport_manager/include/transport_manager/transport_adapter/device_scanner.h
index 36759a9385..6e58f692a9 100644
--- a/src/components/transport_manager/include/transport_manager/transport_adapter/device_scanner.h
+++ b/src/components/transport_manager/include/transport_manager/transport_adapter/device_scanner.h
@@ -76,8 +76,7 @@ class DeviceScanner {
/**
* @brief Destructor.
*/
- virtual ~DeviceScanner() {
- }
+ virtual ~DeviceScanner() {}
};
} // namespace transport_adapter
diff --git a/src/components/transport_manager/include/transport_manager/transport_adapter/server_connection_factory.h b/src/components/transport_manager/include/transport_manager/transport_adapter/server_connection_factory.h
index 19c37aa6a6..3cd93e1316 100644
--- a/src/components/transport_manager/include/transport_manager/transport_adapter/server_connection_factory.h
+++ b/src/components/transport_manager/include/transport_manager/transport_adapter/server_connection_factory.h
@@ -41,7 +41,8 @@ namespace transport_manager {
namespace transport_adapter {
/**
- * @brief Implement transport dependent connection that was originated by the user.
+ * @brief Implement transport dependent connection that was originated by the
+ * user.
*/
class ServerConnectionFactory {
public:
@@ -79,8 +80,7 @@ class ServerConnectionFactory {
/**
* @brief Destructor.
*/
- virtual ~ServerConnectionFactory() {
- }
+ virtual ~ServerConnectionFactory() {}
};
} // namespace transport_adapter
diff --git a/src/components/transport_manager/include/transport_manager/transport_adapter/threaded_socket_connection.h b/src/components/transport_manager/include/transport_manager/transport_adapter/threaded_socket_connection.h
index d764979fbd..ab0c5cbf85 100644
--- a/src/components/transport_manager/include/transport_manager/transport_adapter/threaded_socket_connection.h
+++ b/src/components/transport_manager/include/transport_manager/transport_adapter/threaded_socket_connection.h
@@ -140,6 +140,7 @@ class ThreadedSocketConnection : public Connection {
explicit SocketConnectionDelegate(ThreadedSocketConnection* connection);
void threadMain() OVERRIDE;
void exitThreadMain() OVERRIDE;
+
private:
ThreadedSocketConnection* connection_;
};
diff --git a/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_controller.h b/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_controller.h
index f0148ad1af..0b38f82637 100644
--- a/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_controller.h
+++ b/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_controller.h
@@ -42,8 +42,7 @@ namespace transport_adapter {
class TransportAdapterController {
public:
- virtual ~TransportAdapterController() {
- }
+ virtual ~TransportAdapterController() {}
/**
* @brief Add device to the container(map), if container doesn't hold it yet.
@@ -55,7 +54,8 @@ class TransportAdapterController {
virtual DeviceSptr AddDevice(DeviceSptr device) = 0;
/**
- * @brief Search for device in container of devices, if it is not there - adds it.
+ * @brief Search for device in container of devices, if it is not there - adds
+ *it.
*
* @param devices Container(vector) of smart pointers to devices.
*/
@@ -100,7 +100,8 @@ class TransportAdapterController {
const ApplicationHandle& app_handle) = 0;
/**
- * @brief Make state of specified connection - ESTABLISHED and launch OnConnectDone event in device adapter listener.
+ * @brief Make state of specified connection - ESTABLISHED and launch
+ *OnConnectDone event in device adapter listener.
*
* @param devcie_handle Device unique identifier.
* @param app_handle Handle of application.
@@ -109,7 +110,8 @@ class TransportAdapterController {
const ApplicationHandle& app_handle) = 0;
/**
- * @brief Delete connection from the container of connections and launch OnConnectFailed event in the device adapter listener.
+ * @brief Delete connection from the container of connections and launch
+ *OnConnectFailed event in the device adapter listener.
*
* @param device_handle Device unique identifier.
* @param app_handle Handle of application.
@@ -119,7 +121,7 @@ class TransportAdapterController {
const ConnectError& error) = 0;
/**
- * @brief Make state of specified connection - FINILIZING.
+ * @brief Make state of specified connection - FINALISING.
*
* @param device_handle Device unique identifier.
* @param app_handle Handle of application.
@@ -128,7 +130,8 @@ class TransportAdapterController {
const ApplicationHandle& app_handle) = 0;
/**
- * @brief Set specified connection state to FINALISING and launch OnUnexpectedDisconnect event in the device adapter listener.
+ * @brief Set specified connection state to FINALISING and launch
+ *OnUnexpectedDisconnect event in the device adapter listener.
*
* @param device_handle Device unique identifier.
* @param app_handle Handle of application.
@@ -147,7 +150,8 @@ class TransportAdapterController {
const DisconnectDeviceError& error) = 0;
/**
- * @brief Delete specified connection from the container(map) of connections and launch event in the device adapter listener.
+ * @brief Delete specified connection from the container(map) of connections
+ *and launch event in the device adapter listener.
*
* @param device_handle Device unique identifier.
* @param app_handle Handle of application.
@@ -155,13 +159,13 @@ class TransportAdapterController {
virtual void DisconnectDone(const DeviceUID& device_handle,
const ApplicationHandle& app_handle) = 0;
- /**
- * @brief Launch OnDataReceiveDone event in the device adapter listener.
- *
- * @param device_handle Device unique identifier.
- * @param app_handle Handle of application.
- * @param message Smart pointer to the raw message.
- */
+ /**
+ * @brief Launch OnDataReceiveDone event in the device adapter listener.
+ *
+ * @param device_handle Device unique identifier.
+ * @param app_handle Handle of application.
+ * @param message Smart pointer to the raw message.
+ */
virtual void DataReceiveDone(const DeviceUID& device_handle,
const ApplicationHandle& app_handle,
::protocol_handler::RawMessagePtr message) = 0;
@@ -198,7 +202,8 @@ class TransportAdapterController {
*/
virtual void DataSendFailed(const DeviceUID& device_handle,
const ApplicationHandle& app_handle,
- ::protocol_handler::RawMessagePtr message, const DataSendError&) = 0;
+ ::protocol_handler::RawMessagePtr message,
+ const DataSendError&) = 0;
};
} // namespace transport_adapter
diff --git a/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_impl.h b/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_impl.h
index 5306a7af5a..3dedead540 100644
--- a/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_impl.h
+++ b/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_impl.h
@@ -41,13 +41,16 @@
#include "utils/lock.h"
#include "utils/rwlock.h"
+
#include "transport_manager/transport_adapter/transport_adapter.h"
#include "transport_manager/transport_adapter/transport_adapter_controller.h"
#include "transport_manager/transport_adapter/connection.h"
+#include "transport_manager/transport_manager_settings.h"
+#include "resumption/last_state.h"
-#ifdef TIME_TESTER
-#include "transport_manager/time_metric_observer.h"
-#endif // TIME_TESTER
+#ifdef TELEMETRY_MONITOR
+#include "transport_manager/telemetry_observer.h"
+#endif // TELEMETRY_MONITOR
namespace transport_manager {
@@ -75,7 +78,9 @@ class TransportAdapterImpl : public TransportAdapter,
**/
TransportAdapterImpl(DeviceScanner* device_scanner,
ServerConnectionFactory* server_connection_factory,
- ClientConnectionListener* client_connection_listener);
+ ClientConnectionListener* client_connection_listener,
+ resumption::LastState& last_state,
+ const TransportManagerSettings& settings);
/**
* @brief Destructor.
@@ -88,7 +93,7 @@ class TransportAdapterImpl : public TransportAdapter,
* @return true if initialized.
* @return false if not initialized.
*/
- virtual bool IsInitialised() const;
+ bool IsInitialised() const OVERRIDE;
public:
/**
@@ -98,20 +103,20 @@ class TransportAdapterImpl : public TransportAdapter,
*
* @return Error information about possible reason of failure.
**/
- virtual TransportAdapter::Error Init();
+ TransportAdapter::Error Init() OVERRIDE;
/**
* @brief Stops device adapter
* Called from transport manager to stop device adapter
*/
- virtual void Terminate();
+ void Terminate() OVERRIDE;
/**
* @brief Add listener to the container(list) of device adapter listeners.
*
* @param listener Pointer to the device adapter listener.
*/
- virtual void AddListener(TransportAdapterListener* listener);
+ void AddListener(TransportAdapterListener* listener) OVERRIDE;
/**
* @brief Start scanning for new devices.
@@ -120,7 +125,7 @@ class TransportAdapterImpl : public TransportAdapter,
*
* @return Error information about possible reason of search devices failure.
**/
- virtual TransportAdapter::Error SearchDevices();
+ TransportAdapter::Error SearchDevices() OVERRIDE;
/**
* @brief Connect to the specified application discovered on device.
@@ -130,15 +135,16 @@ class TransportAdapterImpl : public TransportAdapter,
*
* @return Error information about possible reason of failure.
**/
- virtual TransportAdapter::Error Connect(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle);
+ TransportAdapter::Error Connect(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle) OVERRIDE;
/**
* @brief Connect to all applications discovered on device
* @param device_handle Handle of device
* @return Error information about connecting applications on device
*/
- virtual TransportAdapter::Error ConnectDevice(const DeviceUID& device_handle);
+ TransportAdapter::Error ConnectDevice(
+ const DeviceUID& device_handle) OVERRIDE;
/**
* @brief Disconnect from specified session.
@@ -148,8 +154,9 @@ class TransportAdapterImpl : public TransportAdapter,
*
* @return Error information about possible reason of disconnecting failure.
**/
- virtual TransportAdapter::Error Disconnect(
- const DeviceUID& device_handle, const ApplicationHandle& app_handle);
+ TransportAdapter::Error Disconnect(
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle) OVERRIDE;
/**
* @brief Disconnect from all sessions on specified device.
@@ -159,8 +166,8 @@ class TransportAdapterImpl : public TransportAdapter,
* @return Error information about possible reason of disconnecting from
*specified device failure.
**/
- virtual TransportAdapter::Error DisconnectDevice(
- const DeviceUID& device_handle);
+ TransportAdapter::Error DisconnectDevice(
+ const DeviceUID& device_handle) OVERRIDE;
/**
* @brief Send frame of data.
@@ -171,51 +178,52 @@ class TransportAdapterImpl : public TransportAdapter,
*
* @return Error information about possible reason of sending data failure
**/
- virtual TransportAdapter::Error SendData(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const ::protocol_handler::RawMessagePtr data);
+ TransportAdapter::Error SendData(
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ::protocol_handler::RawMessagePtr data) OVERRIDE;
/**
* @brief Start client listener.
*
* @return Error information about possible reason of failure.
*/
- virtual TransportAdapter::Error StartClientListening();
+ TransportAdapter::Error StartClientListening() OVERRIDE;
/**
* @brief Stop client listener.
*
* @return Error information about possible reason of failure.
*/
- virtual TransportAdapter::Error StopClientListening();
+ TransportAdapter::Error StopClientListening() OVERRIDE;
/**
* @brief Notify that device scanner is available.
*
* @return True - available, false - not available.
*/
- virtual bool IsSearchDevicesSupported() const;
+ bool IsSearchDevicesSupported() const OVERRIDE;
/**
* @brief Notify that server connection factory is available.
*
* @return True - available, false - not available.
*/
- virtual bool IsServerOriginatedConnectSupported() const;
+ bool IsServerOriginatedConnectSupported() const OVERRIDE;
/**
* @brief Notify that listener of client connection is available.
*
* @return True - available, false - not available.
*/
- virtual bool IsClientOriginatedConnectSupported() const;
+ bool IsClientOriginatedConnectSupported() const OVERRIDE;
/**
* @brief Create container(vector) of device unique identifiers.
*
* @return Container(vector) of device unique identifiers.
*/
- virtual DeviceList GetDeviceList() const;
+ DeviceList GetDeviceList() const OVERRIDE;
/**
* @brief Get container(vector) of application unique identifiers that
@@ -225,8 +233,8 @@ class TransportAdapterImpl : public TransportAdapter,
*
* @return Container(vector) that holds application unique identifiers.
*/
- virtual ApplicationList GetApplicationList(const DeviceUID& device_handle)
- const;
+ ApplicationList GetApplicationList(
+ const DeviceUID& device_handle) const OVERRIDE;
/**
* @brief Find device in the internal container(map).
@@ -235,7 +243,7 @@ class TransportAdapterImpl : public TransportAdapter,
*
* @return Smart pointer to device.
*/
- virtual DeviceSptr FindDevice(const DeviceUID& device_handle) const;
+ DeviceSptr FindDevice(const DeviceUID& device_handle) const OVERRIDE;
/**
* @brief Search for device in container of devices, if it is not there - adds
@@ -243,18 +251,18 @@ class TransportAdapterImpl : public TransportAdapter,
*
* @param devices Container(vector) of smart pointers to devices.
*/
- virtual void SearchDeviceDone(const DeviceVector& devices);
+ void SearchDeviceDone(const DeviceVector& devices) OVERRIDE;
- virtual void ApplicationListUpdated(const DeviceUID& device_handle);
+ void ApplicationListUpdated(const DeviceUID& device_handle) OVERRIDE;
- virtual void FindNewApplicationsRequest();
+ void FindNewApplicationsRequest() OVERRIDE;
/**
* @brief Launch OnSearchDeviceFailed event in device adapter listener.
*
* @param error Error class that contains details of this error situation.
*/
- virtual void SearchDeviceFailed(const SearchDeviceError& error);
+ void SearchDeviceFailed(const SearchDeviceError& error) OVERRIDE;
/**
* @brief Add device to the container(map), if container doesn't hold it yet.
@@ -263,7 +271,7 @@ class TransportAdapterImpl : public TransportAdapter,
*
* @return Smart pointer to the device.
*/
- virtual DeviceSptr AddDevice(DeviceSptr device);
+ DeviceSptr AddDevice(DeviceSptr device) OVERRIDE;
/**
* @brief Create connection and fill its parameters.
@@ -272,30 +280,30 @@ class TransportAdapterImpl : public TransportAdapter,
* @param device_handle Device unique identifier.
* @param app_handle Handle of application.
*/
- virtual void ConnectionCreated(ConnectionSPtr connection,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle);
+ void ConnectionCreated(ConnectionSPtr connection,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle) OVERRIDE;
/**
- * @brief Set state of specified connection - FINILIZING.
+ * @brief Set state of specified connection - FINALISING.
*
* @param device_handle Device unique identifier.
* @param app_handle Handle of application.
*/
- virtual void ConnectionFinished(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle);
+ void ConnectionFinished(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle) OVERRIDE;
/**
- * @brief Set specified connection state to FINILIZING and launch
+ * @brief Set specified connection state to FINALISING and launch
*OnUnexpectedDisconnect event in the device adapter listener.
*
* @param device_handle Device unique identifier.
* @param app_handle Handle of application.
* @param error Error class that contains details of this error situation.
*/
- virtual void ConnectionAborted(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const CommunicationError& error);
+ void ConnectionAborted(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const CommunicationError& error) OVERRIDE;
/**
* @brief Set state of specified connection - ESTABLISHED and launch
@@ -304,8 +312,8 @@ class TransportAdapterImpl : public TransportAdapter,
* @param devcie_handle Device unique identifier.
* @param app_handle Handle of application.
*/
- virtual void ConnectDone(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle);
+ void ConnectDone(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle) OVERRIDE;
/**
* @brief Delete connection from the container of connections and launch
@@ -314,17 +322,26 @@ class TransportAdapterImpl : public TransportAdapter,
* @param device_handle Device unique identifier.
* @param app_handle Handle of application.
*/
- virtual void ConnectFailed(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const ConnectError& error);
+ void ConnectFailed(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ConnectError& error) OVERRIDE;
+
+ /**
+ * @brief Remove marked as FINALISING connection from accounting.
+ *
+ * @param device_handle Device unique identifier.
+ * @param app_handle Handle of application.
+ */
+ void RemoveFinalizedConnection(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle) OVERRIDE;
/**
* @brief Remove specified device and all its connections
* @param device_handle Device unique identifier.
* @param error Error class that contains details of this error situation.
*/
- virtual void DeviceDisconnected(const DeviceUID& device_handle,
- const DisconnectDeviceError& error);
+ void DeviceDisconnected(const DeviceUID& device_handle,
+ const DisconnectDeviceError& error) OVERRIDE;
/**
* @brief Delete specified connection from the container(map) of connections
@@ -333,8 +350,8 @@ class TransportAdapterImpl : public TransportAdapter,
* @param device_handle Device unique identifier.
* @param app_handle Handle of application.
*/
- virtual void DisconnectDone(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle);
+ void DisconnectDone(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle) OVERRIDE;
/**
* @brief Launch OnDataReceiveDone event in the device adapter listener.
@@ -343,9 +360,9 @@ class TransportAdapterImpl : public TransportAdapter,
* @param app_handle Handle of application.
* @param message Smart pointer to the raw message.
*/
- virtual void DataReceiveDone(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- ::protocol_handler::RawMessagePtr message);
+ void DataReceiveDone(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ ::protocol_handler::RawMessagePtr message) OVERRIDE;
/**
* @brief Launch OnDataReceiveFailed event in the device adapter listener.
@@ -354,9 +371,9 @@ class TransportAdapterImpl : public TransportAdapter,
* @param app_handle Handle of application.
* @param error Class that contains details of this error situation.
*/
- virtual void DataReceiveFailed(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const DataReceiveError& error);
+ void DataReceiveFailed(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const DataReceiveError& error) OVERRIDE;
/**
* @brief Launch OnDataSendDone event in the device adapter listener.
@@ -365,9 +382,9 @@ class TransportAdapterImpl : public TransportAdapter,
* @param app_handle Handle of application.
* @param message Smart pointer to raw message.
*/
- virtual void DataSendDone(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- ::protocol_handler::RawMessagePtr message);
+ void DataSendDone(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ ::protocol_handler::RawMessagePtr message) OVERRIDE;
/**
* @brief Launch OnDataSendFailed event in the device adapter listener.
@@ -377,10 +394,10 @@ class TransportAdapterImpl : public TransportAdapter,
* @param message Smart pointer to raw message.
* @param error Class that contains details of this error situation.
*/
- virtual void DataSendFailed(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- ::protocol_handler::RawMessagePtr message,
- const DataSendError& error);
+ void DataSendFailed(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ ::protocol_handler::RawMessagePtr message,
+ const DataSendError& error) OVERRIDE;
/**
* @brief Return name of device.
@@ -389,29 +406,29 @@ class TransportAdapterImpl : public TransportAdapter,
*
* @return String with name.
*/
- virtual std::string DeviceName(const DeviceUID& device_id) const;
+ std::string DeviceName(const DeviceUID& device_id) const OVERRIDE;
/**
* @brief Allows to obtain connection type used by device.
* @return connection type.
*/
- virtual std::string GetConnectionType() const;
+ std::string GetConnectionType() const OVERRIDE;
-#ifdef TIME_TESTER
+#ifdef TELEMETRY_MONITOR
/**
* @brief Setup observer for time metric.
*
* @param observer - pointer to observer
*/
- void SetTimeMetricObserver(TMMetricObserver* observer);
+ void SetTelemetryObserver(TMTelemetryObserver* observer);
/**
* @brief Return Time metric observer
*
* @param return pointer to Time metric observer
*/
- virtual TMMetricObserver* GetTimeMetricObserver();
-#endif // TIME_TESTER
+ TMTelemetryObserver* GetTelemetryObserver() OVERRIDE;
+#endif // TELEMETRY_MONITOR
protected:
/**
@@ -431,7 +448,6 @@ class TransportAdapterImpl : public TransportAdapter,
*/
virtual bool ToBeAutoConnected(DeviceSptr device) const;
-
/**
* @brief Returns true if \a device is to be disconnected automatically when
* all applications will be closed
@@ -446,8 +462,13 @@ class TransportAdapterImpl : public TransportAdapter,
*
* @return pointer to the connection.
*/
- ConnectionSPtr FindEstablishedConnection(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle) const;
+ virtual ConnectionSPtr FindEstablishedConnection(
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle) const;
+
+ const TransportManagerSettings& get_settings() const {
+ return settings_;
+ }
private:
/**
@@ -489,11 +510,7 @@ class TransportAdapterImpl : public TransportAdapter,
ConnectionSPtr connection;
DeviceUID device_id;
ApplicationHandle app_handle;
- enum {
- NEW,
- ESTABLISHED,
- FINALISING
- } state;
+ enum { NEW, ESTABLISHED, FINALISING } state;
};
/**
@@ -528,12 +545,16 @@ class TransportAdapterImpl : public TransportAdapter,
mutable sync_primitives::RWLock connections_lock_;
protected:
-#ifdef TIME_TESTER
+#ifdef TELEMETRY_MONITOR
/**
* @brief Pointer to time metric observer
*/
- TMMetricObserver* metric_observer_;
-#endif // TIME_TESTER
+ TMTelemetryObserver* metric_observer_;
+#endif // TELEMETRY_MONITOR
+
+ resumption::LastState& last_state() const {
+ return last_state_;
+ }
/**
* @brief Pointer to the device scanner.
@@ -549,9 +570,12 @@ class TransportAdapterImpl : public TransportAdapter,
* @brief Pointer to the factory of connections initiated from client.
*/
ClientConnectionListener* client_connection_listener_;
+
+ resumption::LastState& last_state_;
+ const TransportManagerSettings& settings_;
};
} // namespace transport_adapter
} // namespace transport_manager
-#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_ADAPTER_TRANSPORT_ADAPTER_IMPL_H_
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_ADAPTER_TRANSPORT_ADAPTER_IMPL_H_
diff --git a/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_listener.h b/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_listener.h
index 3c302caf14..0a1eeb6b4a 100644
--- a/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_listener.h
+++ b/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_listener.h
@@ -50,11 +50,11 @@ class TransportAdapterListener {
/**
* @brief Destructor.
*/
- virtual ~TransportAdapterListener() {
- }
+ virtual ~TransportAdapterListener() {}
/**
- * @brief Search specified device adapter in the container of shared pointers to device adapters to be sure it is available,
+ * @brief Search specified device adapter in the container of shared pointers
+ *to device adapters to be sure it is available,
* launch event ON_SEARCH_DONE in transport manager.
*
* @param transport_adapter Pointer to the device adapter.
@@ -63,11 +63,13 @@ class TransportAdapterListener {
const TransportAdapter* transport_adapter) = 0;
/**
- * @brief Search specified device adapter in the container of shared pointers to device adapters to be sure it is available, create search device error,
+ * @brief Search specified device adapter in the container of shared pointers
+ *to device adapters to be sure it is available, create search device error,
* launch event ON_SEARCH_FAIL in transport manager.
*
* @param transport_adapter Pointer to the device adapter.
- * @param error Error class with information about possible reason of search device failure.
+ * @param error Error class with information about possible reason of search
+ *device failure.
*/
virtual void OnSearchDeviceFailed(const TransportAdapter* transport_adapter,
const SearchDeviceError& error) = 0;
@@ -86,10 +88,12 @@ class TransportAdapterListener {
* @brief Reaction to "Find new applications" request
* @param adapter Current transport adapter
*/
- virtual void OnFindNewApplicationsRequest(const TransportAdapter* adapter) = 0;
+ virtual void OnFindNewApplicationsRequest(
+ const TransportAdapter* adapter) = 0;
/**
- * @brief Search specified device adapter in the container of shared pointers to device adapters to be sure it is available,
+ * @brief Search specified device adapter in the container of shared pointers
+ *to device adapters to be sure it is available,
* launch event ON_CONNECT_DONE in transport manager.
*
* @param device_adater Pointer to the device adapter.
@@ -101,13 +105,15 @@ class TransportAdapterListener {
const ApplicationHandle& app_handle) = 0;
/**
- * @brief Search specified device adapter in the container of shared pointers to device adapters to be sure it is available,
+ * @brief Search specified device adapter in the container of shared pointers
+ *to device adapters to be sure it is available,
* launch event ON_CONNECT_FAIL in transport manager.
*
* @param transport_adapter Pointer to the device adapter.
* @param device Device unique identifier.
* @param app_id Handle of application.
- * @param error Error class with information about possible reason of connect failure.
+ * @param error Error class with information about possible reason of connect
+ *failure.
*/
virtual void OnConnectFailed(const TransportAdapter* transport_adapter,
const DeviceUID& device_handle,
@@ -126,20 +132,23 @@ class TransportAdapterListener {
const ApplicationHandle& app_handle) = 0;
/**
- * @brief Search specified device adapter in the container of shared pointers to device adapters to be sure it is available,
+ * @brief Search specified device adapter in the container of shared pointers
+ *to device adapters to be sure it is available,
* launch event ON_UNEXPECTED_DISCONNECT in transport manager.
*
* @param transport_adapter Pointer to the device adapter.
* @param device Device unique identifier.
* @param app_id Handle of application.
- * @param error Error class with information about possible reason of unexpected Disconnect.
+ * @param error Error class with information about possible reason of
+ *unexpected Disconnect.
*/
virtual void OnUnexpectedDisconnect(const TransportAdapter* transport_adapter,
const DeviceUID& device_handle,
const ApplicationHandle& app_handle,
const CommunicationError& error) = 0;
/**
- * @brief Search specified device adapter in the container of shared pointers to device adapters to be sure it is available,
+ * @brief Search specified device adapter in the container of shared pointers
+ *to device adapters to be sure it is available,
* launch event ON_DISCONNECT_DONE in transport manager.
*
* @param transport_adapter Pointer to the device adapter.
@@ -151,13 +160,15 @@ class TransportAdapterListener {
const ApplicationHandle& app_handle) = 0;
/**
- * @brief Search specified device adapter in the container of shared pointers to device adapters to be sure it is available, create Disconnect error,
+ * @brief Search specified device adapter in the container of shared pointers
+ *to device adapters to be sure it is available, create Disconnect error,
* launch event ON_DISCONNECT_FAIL in transport manager.
*
* @param transport_adapter Pointer to the device adapter.
* @param device Device unique identifier.
* @param app_id Handle of application.
- * @param error Error class with information about possible reason of Disconnect failure.
+ * @param error Error class with information about possible reason of
+ *Disconnect failure.
*/
virtual void OnDisconnectFailed(const TransportAdapter* transport_adapter,
const DeviceUID& device_handle,
@@ -178,14 +189,17 @@ class TransportAdapterListener {
*
* @param transport_adapter Pointer to the device adapter.
* @param device Device unique identifier.
- * @param error Error class with information about possible reason of Disconnect from device failure.
+ * @param error Error class with information about possible reason of
+ *Disconnect from device failure.
*/
virtual void OnDisconnectDeviceFailed(
- const TransportAdapter* transport_adapter, const DeviceUID& device_handle,
+ const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
const DisconnectDeviceError& error) = 0;
/**
- * @brief Search specified device adapter in the container of shared pointers to device adapters to be sure it is available, create error,
+ * @brief Search specified device adapter in the container of shared pointers
+ *to device adapters to be sure it is available, create error,
* launch event ON_RECEIVED_DONE in transport manager.
*
* @param transport_adapter Pointer to the device adapter.
@@ -193,28 +207,33 @@ class TransportAdapterListener {
* @param app_id Handle of application.
* @param data_container Smart pointer to the raw message.
*/
- virtual void OnDataSendDone(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const ::protocol_handler::RawMessagePtr data_container) = 0;
+ virtual void OnDataSendDone(
+ const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ::protocol_handler::RawMessagePtr data_container) = 0;
/**
- * @brief Search specified device adapter in the container of shared pointers to device adapters to be sure it is available, create data receive error,
+ * @brief Search specified device adapter in the container of shared pointers
+ *to device adapters to be sure it is available, create data receive error,
* launch event ON_RECEIVED_DONE in transport manager.
*
* @param transport_adapter Pointer to the device adapter.
* @param device Device unique identifier.
* @param app_id Handle of application.
- * @param error Error class with information about possible reason of data receive failure.
+ * @param error Error class with information about possible reason of data
+ *receive failure.
*/
- virtual void OnDataSendFailed(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const ::protocol_handler::RawMessagePtr data_container,
- const DataSendError& error) = 0;
+ virtual void OnDataSendFailed(
+ const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ::protocol_handler::RawMessagePtr data_container,
+ const DataSendError& error) = 0;
/**
- * @brief Search specified device adapter in the container of shared pointers to device adapters to be sure it is available, create error,
+ * @brief Search specified device adapter in the container of shared pointers
+ *to device adapters to be sure it is available, create error,
* launch event ON_SEND_DONE in transport manager.
*
* @param transport_adapter Pointer to the device adapter.
@@ -222,13 +241,15 @@ class TransportAdapterListener {
* @param app_id Handle of application.
* @param data_container Smart pointer to the raw message.
*/
- virtual void OnDataReceiveDone(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const ::protocol_handler::RawMessagePtr data_container) = 0;
+ virtual void OnDataReceiveDone(
+ const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ::protocol_handler::RawMessagePtr data_container) = 0;
/**
- * @brief Search specified device adapter in the container of shared pointers to device adapters to be sure it is available, create data send error,
+ * @brief Search specified device adapter in the container of shared pointers
+ * to device adapters to be sure it is available, create data send error,
* launch event ON_SEND_FAIL in transport manager.
*/
virtual void OnDataReceiveFailed(const TransportAdapter* transport_adapter,
@@ -237,7 +258,8 @@ class TransportAdapterListener {
const DataReceiveError& error) = 0;
/**
- * @brief Search specified device adapter in the container of shared pointers to device adapters to be sure it is available, create error,
+ * @brief Search specified device adapter in the container of shared pointers
+ *to device adapters to be sure it is available, create error,
* launch event ON_COMMUNICATION_ERROR in transport manager.
*
* @param transport_adapter Pointer to the device adapter.
diff --git a/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_listener_impl.h b/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_listener_impl.h
index 87d71ea56f..a0daa7b594 100644
--- a/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_listener_impl.h
+++ b/src/components/transport_manager/include/transport_manager/transport_adapter/transport_adapter_listener_impl.h
@@ -36,13 +36,12 @@
#include "transport_manager/common.h"
#include "transport_manager/transport_adapter/transport_adapter_listener.h"
#include "transport_manager/transport_adapter/transport_adapter.h"
+#include "transport_manager/transport_manager.h"
namespace transport_manager {
using transport_manager::transport_adapter::TransportAdapter;
-class TransportManagerImpl;
-
/**
* @brief Implementation of TransportAdapterListener class.
*/
@@ -72,10 +71,10 @@ class TransportAdapterListenerImpl
/**
* @brief Constructor.
*
- * @param manager Pointer to the transport manager implementation class.
+ * @param manager Pointer to the transport manager class.
* @param adapter Pointer to the transport adapter associated with listener.
*/
- TransportAdapterListenerImpl(TransportManagerImpl* manager,
+ TransportAdapterListenerImpl(TransportManager* manager,
TransportAdapter* adapter);
/**
@@ -100,7 +99,7 @@ class TransportAdapterListenerImpl
const SearchDeviceError& error);
/**
- * @brief Passes notification to TransportManagerImpl
+ * @brief Passes notification to TransportManager
*
* @param adapter Transport adapter that sent notification
*/
@@ -223,10 +222,11 @@ class TransportAdapterListenerImpl
* @param app_id Handle of application.
* @param data_container Smart pointer to the raw message.
*/
- virtual void OnDataReceiveDone(const TransportAdapter* adapter,
- const DeviceUID& device,
- const ApplicationHandle& app_id,
- const ::protocol_handler::RawMessagePtr data_container);
+ virtual void OnDataReceiveDone(
+ const TransportAdapter* adapter,
+ const DeviceUID& device,
+ const ApplicationHandle& app_id,
+ const ::protocol_handler::RawMessagePtr data_container);
/**
* @brief Search specified device adapter in the container of shared pointers
@@ -254,21 +254,23 @@ class TransportAdapterListenerImpl
* @param app_id Handle of application.
* @param data_container Smart pointer to the raw message.
*/
- virtual void OnDataSendDone(const TransportAdapter* adapter,
- const DeviceUID& device,
- const ApplicationHandle& app_id,
- const ::protocol_handler::RawMessagePtr data_container);
+ virtual void OnDataSendDone(
+ const TransportAdapter* adapter,
+ const DeviceUID& device,
+ const ApplicationHandle& app_id,
+ const ::protocol_handler::RawMessagePtr data_container);
/**
* @brief Search specified device adapter in the container of shared pointers
* to device adapters to be sure it is available, create data send error,
* launch event ON_SEND_FAIL in transport manager.
*/
- virtual void OnDataSendFailed(const TransportAdapter* adapter,
- const DeviceUID& device,
- const ApplicationHandle& app_id,
- const ::protocol_handler::RawMessagePtr data_container,
- const DataSendError& error);
+ virtual void OnDataSendFailed(
+ const TransportAdapter* adapter,
+ const DeviceUID& device,
+ const ApplicationHandle& app_id,
+ const ::protocol_handler::RawMessagePtr data_container,
+ const DataSendError& error);
/**
* @brief Search specified device adapter in the container of shared pointers
@@ -284,7 +286,7 @@ class TransportAdapterListenerImpl
const ApplicationHandle& app_id);
private:
- TransportManagerImpl* transport_manager_impl_;
+ TransportManager* transport_manager_;
TransportAdapter* transport_adapter_;
};
} // namespace transport_manager
diff --git a/src/components/transport_manager/include/transport_manager/transport_manager_default.h b/src/components/transport_manager/include/transport_manager/transport_manager_default.h
index 6857a5c670..e89562a28d 100644
--- a/src/components/transport_manager/include/transport_manager/transport_manager_default.h
+++ b/src/components/transport_manager/include/transport_manager/transport_manager_default.h
@@ -36,35 +36,34 @@
#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_DEFAULT_H_
#define SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_DEFAULT_H_
-#include "utils/singleton.h"
-
#include "transport_manager/transport_manager_impl.h"
+namespace resumption {
+class LastState;
+}
+
namespace transport_manager {
/**
* @brief Default realization of transport_manager_impl class.
*/
-class TransportManagerDefault : public TransportManagerImpl,
- public utils::Singleton<TransportManagerDefault> {
+class TransportManagerDefault : public TransportManagerImpl {
+ public:
+ explicit TransportManagerDefault(const TransportManagerSettings& settings);
/**
* @brief Initialize transport manager.
*
* @return Code error.
*/
- virtual int Init();
+ int Init(resumption::LastState& last_state) OVERRIDE;
/**
* @brief Destructor.
*/
virtual ~TransportManagerDefault();
- TransportManagerDefault();
-
DISALLOW_COPY_AND_ASSIGN(TransportManagerDefault);
-
- FRIEND_BASE_SINGLETON_CLASS(TransportManagerDefault);
};
}
diff --git a/src/components/transport_manager/include/transport_manager/transport_manager_impl.h b/src/components/transport_manager/include/transport_manager/transport_manager_impl.h
index 4c38716f3f..289df3535d 100644
--- a/src/components/transport_manager/include/transport_manager/transport_manager_impl.h
+++ b/src/components/transport_manager/include/transport_manager/transport_manager_impl.h
@@ -36,28 +36,46 @@
#include <queue>
#include <map>
#include <list>
+#include <vector>
+#include <utility>
#include <algorithm>
-#include "utils/timer_thread.h"
+#include "utils/timer.h"
+#include "utils/timer_task_impl.h"
+#include "utils/rwlock.h"
#include "transport_manager/transport_manager.h"
#include "transport_manager/transport_manager_listener.h"
#include "transport_manager/transport_adapter/transport_adapter_listener_impl.h"
#include "protocol/common.h"
-#ifdef TIME_TESTER
-#include "transport_manager/time_metric_observer.h"
-#endif // TIME_TESTER
+#ifdef TELEMETRY_MONITOR
+#include "transport_manager/telemetry_observer.h"
+#include "telemetry_monitor/telemetry_observable.h"
+#endif // TELEMETRY_MONITOR
#include "utils/threads/message_loop_thread.h"
#include "transport_manager/transport_adapter/transport_adapter_event.h"
+#include "transport_manager/transport_manager_settings.h"
namespace transport_manager {
+typedef threads::MessageLoopThread<std::queue<protocol_handler::RawMessagePtr> >
+ RawMessageLoopThread;
+typedef threads::MessageLoopThread<std::queue<TransportAdapterEvent> >
+ TransportAdapterEventLoopThread;
+typedef utils::SharedPtr<timer::Timer> TimerSPtr;
+
/**
* @brief Implementation of transport manager.s
*/
-class TransportManagerImpl : public TransportManager,
- public threads::MessageLoopThread<std::queue<protocol_handler::RawMessagePtr> >::Handler,
- public threads::MessageLoopThread<std::queue<TransportAdapterEvent> >::Handler {
+class TransportManagerImpl
+ : public TransportManager,
+ public RawMessageLoopThread::Handler,
+ public TransportAdapterEventLoopThread::Handler
+#ifdef TELEMETRY_MONITOR
+ ,
+ public telemetry_monitor::TelemetryObservable<TMTelemetryObserver>
+#endif // TELEMETRY_MONITOR
+ {
public:
struct Connection {
ConnectionUID id;
@@ -69,24 +87,29 @@ class TransportManagerImpl : public TransportManager,
/**
* @brief Structure that contains internal connection parameters
*/
- struct ConnectionInternal: public Connection {
+ struct ConnectionInternal : public Connection {
TransportManagerImpl* transport_manager;
TransportAdapter* transport_adapter;
- typedef timer::TimerThread<ConnectionInternal> TimerInternal;
- typedef utils::SharedPtr<TimerInternal> TimerInternalSharedPointer;
- TimerInternalSharedPointer timer;
- bool shutDown;
+ TimerSPtr timer;
+ bool shutdown_;
DeviceHandle device_handle_;
int messages_count;
ConnectionInternal(TransportManagerImpl* transport_manager,
TransportAdapter* transport_adapter,
- const ConnectionUID& id, const DeviceUID& dev_id,
+ const ConnectionUID id,
+ const DeviceUID& dev_id,
const ApplicationHandle& app_id,
- const DeviceHandle& device_handle);
+ const DeviceHandle device_handle);
+
void DisconnectFailedRoutine();
};
+
public:
+ /**
+ * @brief Constructor.
+ **/
+ explicit TransportManagerImpl(const TransportManagerSettings& settings);
/**
* @brief Destructor.
@@ -98,20 +121,20 @@ class TransportManagerImpl : public TransportManager,
*
* @return Code error.
*/
- virtual int Init();
+ int Init(resumption::LastState& last_state) OVERRIDE;
/**
* Reinitializes transport manager
* @return Error code
*/
- virtual int Reinit();
+ virtual int Reinit() OVERRIDE;
/**
* @brief Start scanning for new devices.
*
* @return Code error.
**/
- virtual int SearchDevices();
+ int SearchDevices() OVERRIDE;
/**
* @brief Connect to all applications discovered on device.
@@ -120,7 +143,7 @@ class TransportManagerImpl : public TransportManager,
*
* @return Code error.
**/
- virtual int ConnectDevice(const DeviceHandle& device_id);
+ int ConnectDevice(const DeviceHandle device_id) OVERRIDE;
/**
* @brief Disconnect from all applications connected on device.
@@ -129,7 +152,7 @@ class TransportManagerImpl : public TransportManager,
*
* @return Code error.
**/
- virtual int DisconnectDevice(const DeviceHandle& device_id);
+ int DisconnectDevice(const DeviceHandle device_id) OVERRIDE;
/**
* @brief Disconnect from applications connected on device by connection
@@ -139,14 +162,14 @@ class TransportManagerImpl : public TransportManager,
*
* @return Code error.
**/
- virtual int Disconnect(const ConnectionUID& connection_id);
+ int Disconnect(const ConnectionUID connection_id) OVERRIDE;
/**
* @brief Disconnect and clear all unreceived data.
*
* @param connection Connection unique identifier.
*/
- virtual int DisconnectForce(const ConnectionUID& connection_id);
+ int DisconnectForce(const ConnectionUID connection_id) OVERRIDE;
/**
* @brief Post new message in queue for massages destined to device.
*
@@ -154,7 +177,8 @@ class TransportManagerImpl : public TransportManager,
*
* @return Code error.
**/
- virtual int SendMessageToDevice(const protocol_handler::RawMessagePtr message);
+ int SendMessageToDevice(
+ const protocol_handler::RawMessagePtr message) OVERRIDE;
/**
* @brief Post event in the event queue.
@@ -163,7 +187,7 @@ class TransportManagerImpl : public TransportManager,
*
* @return Code error.
**/
- virtual int ReceiveEventFromDevice(const TransportAdapterEvent& event);
+ int ReceiveEventFromDevice(const TransportAdapterEvent& event) OVERRIDE;
/**
* @brief Post listener to the container of transport manager listeners.
@@ -172,9 +196,9 @@ class TransportManagerImpl : public TransportManager,
*
* @return Code error.
**/
- virtual int AddEventListener(TransportManagerListener* listener);
+ int AddEventListener(TransportManagerListener* listener) OVERRIDE;
- virtual int Stop();
+ int Stop() OVERRIDE;
/**
* @brief Add device adapter to the container of device adapters.
@@ -183,8 +207,8 @@ class TransportManagerImpl : public TransportManager,
*
* @return Code error.
**/
- virtual int AddTransportAdapter(
- transport_adapter::TransportAdapter* transport_adapter);
+ int AddTransportAdapter(
+ transport_adapter::TransportAdapter* transport_adapter) OVERRIDE;
/**
* @brief Remove device from the container that hold devices.
@@ -193,7 +217,7 @@ class TransportManagerImpl : public TransportManager,
*
* @return Code error.
**/
- virtual int RemoveDevice(const DeviceHandle& device);
+ int RemoveDevice(const DeviceHandle device) OVERRIDE;
/**
* @brief Turns on or off visibility of SDL to mobile devices
@@ -202,7 +226,7 @@ class TransportManagerImpl : public TransportManager,
*
* @return Code error.
*/
- virtual int Visibility(const bool& on_off) const;
+ int Visibility(const bool& on_off) const OVERRIDE;
/**
* @brief Updates total device list with info from specific transport adapter.
@@ -210,28 +234,29 @@ class TransportManagerImpl : public TransportManager,
*/
void UpdateDeviceList(TransportAdapter* ta);
-#ifdef TIME_TESTER
+#ifdef TELEMETRY_MONITOR
/**
* @brief Setup observer for time metric.
*
* @param observer - pointer to observer
*/
- void SetTimeMetricObserver(TMMetricObserver* observer);
-#endif // TIME_TESTER
-
+ void SetTelemetryObserver(TMTelemetryObserver* observer);
+#endif // TELEMETRY_MONITOR
/**
* @brief Constructor.
**/
TransportManagerImpl();
- protected:
+ const TransportManagerSettings& get_settings() const;
+ protected:
template <class Proc, class... Args>
void RaiseEvent(Proc proc, Args... args) {
for (TransportManagerListenerList::iterator it =
transport_manager_listener_.begin();
- it != transport_manager_listener_.end(); ++it) {
+ it != transport_manager_listener_.end();
+ ++it) {
((*it)->*proc)(args...);
}
}
@@ -264,9 +289,9 @@ class TransportManagerImpl : public TransportManager,
*/
bool is_initialized_;
-#ifdef TIME_TESTER
- TMMetricObserver* metric_observer_;
-#endif // TIME_TESTER
+#ifdef TELEMETRY_MONITOR
+ TMTelemetryObserver* metric_observer_;
+#endif // TELEMETRY_MONITOR
private:
/**
@@ -282,19 +307,24 @@ class TransportManagerImpl : public TransportManager,
}
DeviceHandle UidToHandle(const DeviceUID& dev_uid, bool& is_new) {
- ConversionTable::iterator it = std::find(
- conversion_table_.begin(), conversion_table_.end(), dev_uid);
- if (it != conversion_table_.end()) {
- is_new = false;
- return std::distance(conversion_table_.begin(), it) +
- 1; // handle begin since 1 (one)
+ {
+ sync_primitives::AutoReadLock lock(conversion_table_lock);
+ ConversionTable::iterator it = std::find(
+ conversion_table_.begin(), conversion_table_.end(), dev_uid);
+ if (it != conversion_table_.end()) {
+ is_new = false;
+ return std::distance(conversion_table_.begin(), it) +
+ 1; // handle begin since 1 (one)
+ }
}
is_new = true;
+ sync_primitives::AutoWriteLock lock(conversion_table_lock);
conversion_table_.push_back(dev_uid);
return conversion_table_.size(); // handle begin since 1 (one)
}
- DeviceUID HandleToUid(DeviceHandle handle) {
+ DeviceUID HandleToUid(const DeviceHandle handle) {
+ sync_primitives::AutoReadLock lock(conversion_table_lock);
if (handle == 0 || handle > conversion_table_.size()) {
return DeviceUID();
}
@@ -302,6 +332,7 @@ class TransportManagerImpl : public TransportManager,
}
ConversionTable conversion_table_;
+ sync_primitives::RWLock conversion_table_lock;
};
/**
@@ -312,22 +343,27 @@ class TransportManagerImpl : public TransportManager,
explicit TransportManagerImpl(const TransportManagerImpl&);
int connection_id_counter_;
+ sync_primitives::RWLock connections_lock_;
std::vector<ConnectionInternal> connections_;
- std::map<DeviceUID, TransportAdapter*> device_to_adapter_map_;
+ sync_primitives::RWLock device_to_adapter_map_lock_;
+ typedef std::map<DeviceUID, TransportAdapter*> DeviceToAdapterMap;
+ DeviceToAdapterMap device_to_adapter_map_;
std::vector<TransportAdapter*> transport_adapters_;
/** For keep listeners which were add TMImpl */
std::map<TransportAdapter*, TransportAdapterListenerImpl*>
transport_adapter_listeners_;
- threads::MessageLoopThread<std::queue<protocol_handler::RawMessagePtr> > message_queue_;
- threads::MessageLoopThread<std::queue<TransportAdapterEvent> > event_queue_;
-
+ RawMessageLoopThread message_queue_;
+ TransportAdapterEventLoopThread event_queue_;
+ const TransportManagerSettings& settings_;
typedef std::vector<std::pair<const TransportAdapter*, DeviceInfo> >
- DeviceInfoList;
+ DeviceInfoList;
+ sync_primitives::RWLock device_list_lock_;
DeviceInfoList device_list_;
void AddConnection(const ConnectionInternal& c);
- void RemoveConnection(uint32_t id);
- ConnectionInternal* GetConnection(const ConnectionUID& id);
+ void RemoveConnection(const uint32_t id,
+ transport_adapter::TransportAdapter* transport_adapter);
+ ConnectionInternal* GetConnection(const ConnectionUID id);
ConnectionInternal* GetConnection(const DeviceUID& device,
const ApplicationHandle& application);
@@ -335,12 +371,15 @@ class TransportManagerImpl : public TransportManager,
ConnectionUID id,
std::map<ConnectionUID, std::pair<unsigned int, unsigned char*> >&
container,
- unsigned char* data, unsigned int data_size);
- bool GetFrameSize(unsigned char* data, unsigned int data_size,
+ unsigned char* data,
+ unsigned int data_size);
+ bool GetFrameSize(unsigned char* data,
+ unsigned int data_size,
unsigned int& frame_size);
bool GetFrame(std::map<ConnectionUID,
std::pair<unsigned int, unsigned char*> >& container,
- ConnectionUID id, unsigned int frame_size,
+ ConnectionUID id,
+ unsigned int frame_size,
unsigned char** frame);
void OnDeviceListUpdated(TransportAdapter* ta);
@@ -348,9 +387,6 @@ class TransportManagerImpl : public TransportManager,
void TerminateAllAdapters();
int InitAllAdapters();
static Connection convert(const ConnectionInternal& p);
-};
-// class ;
-
+}; // class TransportManagerImpl
} // namespace transport_manager
-
-#endif
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_IMPL_H_
diff --git a/src/components/transport_manager/include/transport_manager/usb/common.h b/src/components/transport_manager/include/transport_manager/usb/common.h
index 283d224536..1c6011dbb2 100644
--- a/src/components/transport_manager/include/transport_manager/usb/common.h
+++ b/src/components/transport_manager/include/transport_manager/usb/common.h
@@ -53,14 +53,14 @@ static const uint16_t kAoaPid2 = 0x2d01;
static const uint8_t kAoaInterfaceSubclass = 0xff;
static const uint16_t kAppleVid = 0x05ac;
-static const uint16_t kApplePid1 = 0x1290; // iPhone
-static const uint16_t kApplePid2 = 0x1292; // iPhone 3G
-static const uint16_t kApplePid3 = 0x1294; // iPhone 3GS
-static const uint16_t kApplePid4 = 0x1297; // iPhone 4
-static const uint16_t kApplePid5 = 0x129a; // iPad
-static const uint16_t kApplePid6 = 0x129f; // iPad 2
-static const uint16_t kApplePid7 = 0x12a0; // iPhone 4S
-static const uint16_t kApplePid8 = 0x12a8; // iPhone 5
+static const uint16_t kApplePid1 = 0x1290; // iPhone
+static const uint16_t kApplePid2 = 0x1292; // iPhone 3G
+static const uint16_t kApplePid3 = 0x1294; // iPhone 3GS
+static const uint16_t kApplePid4 = 0x1297; // iPhone 4
+static const uint16_t kApplePid5 = 0x129a; // iPad
+static const uint16_t kApplePid6 = 0x129f; // iPad 2
+static const uint16_t kApplePid7 = 0x12a0; // iPhone 4S
+static const uint16_t kApplePid8 = 0x12a8; // iPhone 5
static const int kUsbConfiguration = 1;
@@ -70,7 +70,9 @@ class UsbDeviceListener {
public:
virtual ~UsbDeviceListener() {}
- UsbHandlerSptr GetUsbHandler() { return usb_handler_; }
+ UsbHandlerSptr GetUsbHandler() {
+ return usb_handler_;
+ }
void SetUsbHandler(UsbHandlerSptr usb_handler) {
usb_handler_ = usb_handler;
@@ -86,23 +88,24 @@ class UsbDeviceListener {
inline bool IsGoogleAccessory(const PlatformUsbDevice* device) {
return (kAoaVid == device->vendor_id()) &&
- ((kAoaPid1 == device->product_id()) || (kAoaPid2 == device->product_id()));
+ ((kAoaPid1 == device->product_id()) ||
+ (kAoaPid2 == device->product_id()));
}
inline bool IsAppleIAPDevice(const PlatformUsbDevice* device) {
return (kAppleVid == device->vendor_id()) &&
- ((kApplePid1 == device->product_id()) ||
- (kApplePid2 == device->product_id()) ||
- (kApplePid3 == device->product_id()) ||
- (kApplePid4 == device->product_id()) ||
- (kApplePid5 == device->product_id()) ||
- (kApplePid6 == device->product_id()) ||
- (kApplePid7 == device->product_id()));
+ ((kApplePid1 == device->product_id()) ||
+ (kApplePid2 == device->product_id()) ||
+ (kApplePid3 == device->product_id()) ||
+ (kApplePid4 == device->product_id()) ||
+ (kApplePid5 == device->product_id()) ||
+ (kApplePid6 == device->product_id()) ||
+ (kApplePid7 == device->product_id()));
}
inline bool IsAppleIAP2Device(const PlatformUsbDevice* device) {
return (kAppleVid == device->vendor_id()) &&
- (kApplePid8 == device->product_id());
+ (kApplePid8 == device->product_id());
}
inline bool IsAppleDevice(const PlatformUsbDevice* device) {
diff --git a/src/components/transport_manager/include/transport_manager/usb/libusb/platform_usb_device.h b/src/components/transport_manager/include/transport_manager/usb/libusb/platform_usb_device.h
index b90c504a4b..1aa6881b38 100644
--- a/src/components/transport_manager/include/transport_manager/usb/libusb/platform_usb_device.h
+++ b/src/components/transport_manager/include/transport_manager/usb/libusb/platform_usb_device.h
@@ -45,19 +45,32 @@ namespace transport_adapter {
class PlatformUsbDevice {
public:
- uint8_t bus_number() const { return bus_number_; }
- uint8_t address() const { return address_; }
- uint16_t vendor_id() const { return vendor_id_; }
- uint16_t product_id() const { return product_id_; }
+ uint8_t bus_number() const {
+ return bus_number_;
+ }
+ uint8_t address() const {
+ return address_;
+ }
+ uint16_t vendor_id() const {
+ return vendor_id_;
+ }
+ uint16_t product_id() const {
+ return product_id_;
+ }
std::string GetManufacturer() const;
std::string GetProductName() const;
std::string GetSerialNumber() const;
- PlatformUsbDevice(uint8_t bus, uint8_t address,
+ PlatformUsbDevice(uint8_t bus,
+ uint8_t address,
const libusb_device_descriptor& device_descriptor,
libusb_device* device_libusb,
libusb_device_handle* device_handle_libusb);
- libusb_device_handle* GetLibusbHandle() { return libusb_device_handle_; }
- libusb_device* GetLibusbDevice() { return libusb_device_; }
+ libusb_device_handle* GetLibusbHandle() {
+ return libusb_device_handle_;
+ }
+ libusb_device* GetLibusbDevice() {
+ return libusb_device_;
+ }
private:
std::string GetDescString(uint8_t index) const;
diff --git a/src/components/transport_manager/include/transport_manager/usb/libusb/usb_connection.h b/src/components/transport_manager/include/transport_manager/usb/libusb/usb_connection.h
index 7c1fbd4551..bad1cd7117 100644
--- a/src/components/transport_manager/include/transport_manager/usb/libusb/usb_connection.h
+++ b/src/components/transport_manager/include/transport_manager/usb/libusb/usb_connection.h
@@ -49,12 +49,14 @@ class UsbConnection : public Connection {
UsbConnection(const DeviceUID& device_uid,
const ApplicationHandle& app_handle,
TransportAdapterController* controller,
- const UsbHandlerSptr usb_handler, PlatformUsbDevice* device);
+ const UsbHandlerSptr usb_handler,
+ PlatformUsbDevice* device);
bool Init();
virtual ~UsbConnection();
protected:
- virtual TransportAdapter::Error SendData(::protocol_handler::RawMessagePtr message);
+ virtual TransportAdapter::Error SendData(
+ ::protocol_handler::RawMessagePtr message);
virtual TransportAdapter::Error Disconnect();
private:
diff --git a/src/components/transport_manager/include/transport_manager/usb/libusb/usb_handler.h b/src/components/transport_manager/include/transport_manager/usb/libusb/usb_handler.h
index 215b66f6e3..b2ebd3a977 100644
--- a/src/components/transport_manager/include/transport_manager/usb/libusb/usb_handler.h
+++ b/src/components/transport_manager/include/transport_manager/usb/libusb/usb_handler.h
@@ -72,10 +72,11 @@ class UsbHandler {
friend void UsbTransferSequenceCallback(libusb_transfer* transfer);
private:
- class UsbHandlerDelegate: public threads::ThreadDelegate {
+ class UsbHandlerDelegate : public threads::ThreadDelegate {
public:
explicit UsbHandlerDelegate(UsbHandler* handler);
void threadMain() OVERRIDE;
+
private:
UsbHandler* handler_;
};
@@ -97,10 +98,14 @@ class UsbHandler {
libusb_hotplug_callback_handle left_callback_handle_;
friend void* UsbHandlerThread(void* data);
- friend int ArrivedCallback(libusb_context* context, libusb_device* device,
- libusb_hotplug_event event, void* data);
- friend int LeftCallback(libusb_context* context, libusb_device* device,
- libusb_hotplug_event event, void* data);
+ friend int ArrivedCallback(libusb_context* context,
+ libusb_device* device,
+ libusb_hotplug_event event,
+ void* data);
+ friend int LeftCallback(libusb_context* context,
+ libusb_device* device,
+ libusb_hotplug_event event,
+ void* data);
};
} // namespace transport_adapter
diff --git a/src/components/transport_manager/include/transport_manager/usb/qnx/platform_usb_device.h b/src/components/transport_manager/include/transport_manager/usb/qnx/platform_usb_device.h
index ab35f862c6..9755a5eacd 100644
--- a/src/components/transport_manager/include/transport_manager/usb/qnx/platform_usb_device.h
+++ b/src/components/transport_manager/include/transport_manager/usb/qnx/platform_usb_device.h
@@ -45,19 +45,30 @@ namespace transport_adapter {
class PlatformUsbDevice {
public:
- uint8_t bus_number() const { return bus_number_; }
- uint8_t address() const { return address_; }
- uint16_t vendor_id() const { return vendor_id_; }
- uint16_t product_id() const { return product_id_; }
+ uint8_t bus_number() const {
+ return bus_number_;
+ }
+ uint8_t address() const {
+ return address_;
+ }
+ uint16_t vendor_id() const {
+ return vendor_id_;
+ }
+ uint16_t product_id() const {
+ return product_id_;
+ }
std::string GetManufacturer() const;
std::string GetProductName() const;
std::string GetSerialNumber() const;
- PlatformUsbDevice(usbd_device_instance_t* instance, usbd_device* device,
+ PlatformUsbDevice(usbd_device_instance_t* instance,
+ usbd_device* device,
const usbd_device_descriptor_t& device_descriptor);
const usbd_device_instance_t& GetDeviceInstance() {
return usbd_device_instance_;
}
- usbd_device* GetUsbdDevice() { return usbd_device_; }
+ usbd_device* GetUsbdDevice() {
+ return usbd_device_;
+ }
private:
std::string GetDescString(uint8_t index) const;
diff --git a/src/components/transport_manager/include/transport_manager/usb/qnx/usb_connection.h b/src/components/transport_manager/include/transport_manager/usb/qnx/usb_connection.h
index d55c887bd1..e9f7344ee2 100644
--- a/src/components/transport_manager/include/transport_manager/usb/qnx/usb_connection.h
+++ b/src/components/transport_manager/include/transport_manager/usb/qnx/usb_connection.h
@@ -47,6 +47,7 @@ namespace transport_adapter {
class UsbConnection : public Connection {
static const uint32_t kInBufferSize = 2048;
+
public:
UsbConnection(const DeviceUID& device_uid,
const ApplicationHandle& app_handle,
@@ -57,9 +58,12 @@ class UsbConnection : public Connection {
bool Init();
virtual ~UsbConnection();
+
protected:
- virtual TransportAdapter::Error SendData(::protocol_handler::RawMessagePtr message);
+ virtual TransportAdapter::Error SendData(
+ ::protocol_handler::RawMessagePtr message);
virtual TransportAdapter::Error Disconnect();
+
private:
friend void InTransferCallback(usbd_urb* urb, usbd_pipe*, void*);
friend void OutTransferCallback(usbd_urb* urb, usbd_pipe*, void*);
diff --git a/src/components/transport_manager/include/transport_manager/usb/usb_aoa_adapter.h b/src/components/transport_manager/include/transport_manager/usb/usb_aoa_adapter.h
index b0d8c1e453..92a813ed7c 100644
--- a/src/components/transport_manager/include/transport_manager/usb/usb_aoa_adapter.h
+++ b/src/components/transport_manager/include/transport_manager/usb/usb_aoa_adapter.h
@@ -44,7 +44,8 @@ namespace transport_adapter {
class UsbAoaAdapter : public TransportAdapterImpl {
public:
- UsbAoaAdapter();
+ UsbAoaAdapter(resumption::LastState& last_state,
+ const TransportManagerSettings& settings);
virtual ~UsbAoaAdapter();
protected:
diff --git a/src/components/transport_manager/include/transport_manager/usb/usb_control_transfer.h b/src/components/transport_manager/include/transport_manager/usb/usb_control_transfer.h
index c701a86e0a..a3597ff3d4 100644
--- a/src/components/transport_manager/include/transport_manager/usb/usb_control_transfer.h
+++ b/src/components/transport_manager/include/transport_manager/usb/usb_control_transfer.h
@@ -46,14 +46,9 @@ class UsbControlOutTransfer;
class UsbControlTransfer {
public:
- enum TransferDirection {
- IN,
- OUT
- };
+ enum TransferDirection { IN, OUT };
- enum RequestType {
- VENDOR
- };
+ enum RequestType { VENDOR };
virtual ~UsbControlTransfer() {}
virtual TransferDirection Direction() const = 0;
@@ -67,21 +62,27 @@ class UsbControlTransfer {
class UsbControlInTransfer : public UsbControlTransfer {
public:
virtual ~UsbControlInTransfer() {}
- virtual TransferDirection Direction() const { return IN; }
+ virtual TransferDirection Direction() const {
+ return IN;
+ }
virtual bool OnCompleted(unsigned char* data) const = 0;
};
class UsbControlOutTransfer : public UsbControlTransfer {
public:
virtual ~UsbControlOutTransfer() {}
- virtual TransferDirection Direction() const { return OUT; }
+ virtual TransferDirection Direction() const {
+ return OUT;
+ }
virtual const char* Data() const = 0;
};
class UsbControlTransferSequence {
public:
typedef std::list<UsbControlTransfer*> Transfers;
- const Transfers& transfers() const { return transfers_; }
+ const Transfers& transfers() const {
+ return transfers_;
+ }
virtual ~UsbControlTransferSequence() {
for (Transfers::iterator it = transfers_.begin(); it != transfers_.end();
diff --git a/src/components/transport_manager/include/transport_manager/usb/usb_device.h b/src/components/transport_manager/include/transport_manager/usb/usb_device.h
index 48c5867f90..fdcfb6e155 100644
--- a/src/components/transport_manager/include/transport_manager/usb/usb_device.h
+++ b/src/components/transport_manager/include/transport_manager/usb/usb_device.h
@@ -45,11 +45,14 @@ namespace transport_adapter {
class UsbDevice : public Device {
public:
- UsbDevice(PlatformUsbDevice* usb_device, const std::string& name,
+ UsbDevice(PlatformUsbDevice* usb_device,
+ const std::string& name,
const DeviceUID& unique_device_id)
: Device(name, unique_device_id), usb_device_(usb_device) {}
- PlatformUsbDevice* usb_device() const { return usb_device_; }
+ PlatformUsbDevice* usb_device() const {
+ return usb_device_;
+ }
protected:
virtual ~UsbDevice() {}
diff --git a/src/components/transport_manager/src/bluetooth/bluetooth_connection_factory.cc b/src/components/transport_manager/src/bluetooth/bluetooth_connection_factory.cc
index 02224baf4e..bb27493701 100644
--- a/src/components/transport_manager/src/bluetooth/bluetooth_connection_factory.cc
+++ b/src/components/transport_manager/src/bluetooth/bluetooth_connection_factory.cc
@@ -45,20 +45,20 @@ namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
BluetoothConnectionFactory::BluetoothConnectionFactory(
- TransportAdapterController* controller)
- : controller_(controller) {
-}
+ TransportAdapterController* controller)
+ : controller_(controller) {}
TransportAdapter::Error BluetoothConnectionFactory::Init() {
return TransportAdapter::OK;
}
TransportAdapter::Error BluetoothConnectionFactory::CreateConnection(
- const DeviceUID& device_uid, const ApplicationHandle& app_handle) {
- LOG4CXX_TRACE(logger_, "enter. device_uid: " << &device_uid << ", app_handle: " <<
- &app_handle);
+ const DeviceUID& device_uid, const ApplicationHandle& app_handle) {
+ LOG4CXX_TRACE(logger_,
+ "enter. device_uid: " << &device_uid
+ << ", app_handle: " << &app_handle);
BluetoothSocketConnection* connection(
- new BluetoothSocketConnection(device_uid, app_handle, controller_));
+ new BluetoothSocketConnection(device_uid, app_handle, controller_));
TransportAdapter::Error error = connection->Start();
if (TransportAdapter::OK != error) {
LOG4CXX_ERROR(logger_, "connection::Start() failed");
@@ -68,15 +68,13 @@ TransportAdapter::Error BluetoothConnectionFactory::CreateConnection(
return error;
}
-void BluetoothConnectionFactory::Terminate() {
-}
+void BluetoothConnectionFactory::Terminate() {}
bool BluetoothConnectionFactory::IsInitialised() const {
return true;
}
-BluetoothConnectionFactory::~BluetoothConnectionFactory() {
-}
+BluetoothConnectionFactory::~BluetoothConnectionFactory() {}
} // namespace transport_adapter
} // namespace transport_manager
diff --git a/src/components/transport_manager/src/bluetooth/bluetooth_device.cc b/src/components/transport_manager/src/bluetooth/bluetooth_device.cc
index c8061a7ac5..038515170d 100644
--- a/src/components/transport_manager/src/bluetooth/bluetooth_device.cc
+++ b/src/components/transport_manager/src/bluetooth/bluetooth_device.cc
@@ -54,19 +54,22 @@ CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
bool BluetoothDevice::GetRfcommChannel(const ApplicationHandle app_handle,
uint8_t* channel_out) {
- LOG4CXX_TRACE(logger_, "enter. app_handle: " << app_handle << ", channel_out: " <<
- channel_out);
+ LOG4CXX_TRACE(logger_,
+ "enter. app_handle: " << app_handle
+ << ", channel_out: " << channel_out);
if (app_handle < 0 || app_handle > std::numeric_limits<uint8_t>::max()) {
LOG4CXX_TRACE(logger_,
- "exit with FALSE. Condition: app_handle < 0 || app_handle > numeric_limits::max()");
+ "exit with FALSE. Condition: app_handle < 0 || app_handle > "
+ "numeric_limits::max()");
return false;
}
const uint8_t channel = static_cast<uint8_t>(app_handle);
- RfcommChannelVector::const_iterator it = std::find(rfcomm_channels_.begin(),
- rfcomm_channels_.end(),
- channel);
+ RfcommChannelVector::const_iterator it =
+ std::find(rfcomm_channels_.begin(), rfcomm_channels_.end(), channel);
if (it == rfcomm_channels_.end()) {
- LOG4CXX_TRACE(logger_, "exit with FALSE. Condition: channel not found in RfcommChannelVector");
+ LOG4CXX_TRACE(
+ logger_,
+ "exit with FALSE. Condition: channel not found in RfcommChannelVector");
return false;
}
*channel_out = channel;
@@ -82,31 +85,31 @@ std::string BluetoothDevice::GetUniqueDeviceId(const bdaddr_t& device_address) {
return std::string("BT-") + device_address_string;
}
-BluetoothDevice::BluetoothDevice(const bdaddr_t& device_address, const char* device_name,
+BluetoothDevice::BluetoothDevice(const bdaddr_t& device_address,
+ const char* device_name,
const RfcommChannelVector& rfcomm_channels)
- : Device(device_name, GetUniqueDeviceId(device_address)),
- address_(device_address),
- rfcomm_channels_(rfcomm_channels) {
-}
+ : Device(device_name, GetUniqueDeviceId(device_address))
+ , address_(device_address)
+ , rfcomm_channels_(rfcomm_channels) {}
bool BluetoothDevice::IsSameAs(const Device* other) const {
LOG4CXX_TRACE(logger_, "enter. device: " << other);
bool result = false;
const BluetoothDevice* other_bluetooth_device =
- dynamic_cast<const BluetoothDevice*>(other);
+ dynamic_cast<const BluetoothDevice*>(other);
if (0 != other_bluetooth_device) {
- if (0
- == memcmp(&address_, &other_bluetooth_device->address_,
- sizeof(bdaddr_t))) {
+ if (0 == memcmp(&address_,
+ &other_bluetooth_device->address_,
+ sizeof(bdaddr_t))) {
result = true;
}
}
if (result) {
- LOG4CXX_TRACE(logger_, "exit with TRUE");
+ LOG4CXX_TRACE(logger_, "exit with TRUE");
} else {
- LOG4CXX_TRACE(logger_, "exit with FALSE");
+ LOG4CXX_TRACE(logger_, "exit with FALSE");
}
return result;
}
diff --git a/src/components/transport_manager/src/bluetooth/bluetooth_device_scanner.cc b/src/components/transport_manager/src/bluetooth/bluetooth_device_scanner.cc
index c422d895d0..85e6dc3f96 100644
--- a/src/components/transport_manager/src/bluetooth/bluetooth_device_scanner.cc
+++ b/src/components/transport_manager/src/bluetooth/bluetooth_device_scanner.cc
@@ -92,35 +92,49 @@ int FindPairedDevs(std::vector<bdaddr_t>* result) {
result->push_back(address);
}
}
- delete [] buffer;
+ delete[] buffer;
buffer = new char[1028];
}
pclose(pipe);
LOG4CXX_TRACE(logger_, "exit with 0");
- delete [] buffer;
+ delete[] buffer;
return 0;
}
} // namespace
BluetoothDeviceScanner::BluetoothDeviceScanner(
- TransportAdapterController* controller, bool auto_repeat_search,
- int auto_repeat_pause_sec)
- : controller_(controller),
- thread_(NULL),
- shutdown_requested_(false),
- ready_(true),
- device_scan_requested_(false),
- device_scan_requested_lock_(),
- device_scan_requested_cv_(),
- auto_repeat_search_(auto_repeat_search),
- auto_repeat_pause_sec_(auto_repeat_pause_sec) {
- uint8_t smart_device_link_service_uuid_data[] = { 0x93, 0x6D, 0xA0, 0x1F,
- 0x9A, 0xBD, 0x4D, 0x9D, 0x80, 0xC7, 0x02, 0xAF, 0x85, 0xC8, 0x22, 0xA8
- };
+ TransportAdapterController* controller,
+ bool auto_repeat_search,
+ int auto_repeat_pause_sec)
+ : controller_(controller)
+ , thread_(NULL)
+ , shutdown_requested_(false)
+ , ready_(true)
+ , device_scan_requested_(false)
+ , device_scan_requested_lock_()
+ , device_scan_requested_cv_()
+ , auto_repeat_search_(auto_repeat_search)
+ , auto_repeat_pause_sec_(auto_repeat_pause_sec) {
+ uint8_t smart_device_link_service_uuid_data[] = {0x93,
+ 0x6D,
+ 0xA0,
+ 0x1F,
+ 0x9A,
+ 0xBD,
+ 0x4D,
+ 0x9D,
+ 0x80,
+ 0xC7,
+ 0x02,
+ 0xAF,
+ 0x85,
+ 0xC8,
+ 0x22,
+ 0xA8};
sdp_uuid128_create(&smart_device_link_service_uuid_,
smart_device_link_service_uuid_data);
thread_ = threads::CreateThread("BT Device Scaner",
- new BluetoothDeviceScannerDelegate(this));
+ new BluetoothDeviceScannerDelegate(this));
}
BluetoothDeviceScanner::~BluetoothDeviceScanner() {
@@ -129,7 +143,6 @@ BluetoothDeviceScanner::~BluetoothDeviceScanner() {
threads::DeleteThread(thread_);
}
-
bool BluetoothDeviceScanner::IsInitialised() const {
return thread_ && thread_->is_running();
}
@@ -137,9 +150,11 @@ bool BluetoothDeviceScanner::IsInitialised() const {
void BluetoothDeviceScanner::UpdateTotalDeviceList() {
LOG4CXX_AUTO_TRACE(logger_);
DeviceVector devices;
- devices.insert(devices.end(), paired_devices_with_sdl_.begin(),
+ devices.insert(devices.end(),
+ paired_devices_with_sdl_.begin(),
paired_devices_with_sdl_.end());
- devices.insert(devices.end(), found_devices_with_sdl_.begin(),
+ devices.insert(devices.end(),
+ found_devices_with_sdl_.begin(),
found_devices_with_sdl_.end());
controller_->SearchDeviceDone(devices);
}
@@ -169,12 +184,13 @@ void BluetoothDeviceScanner::DoInquiry() {
}
}
- LOG4CXX_INFO(logger_, "Check rfcomm channel on "
- << paired_devices_.size() << " paired devices.");
+ LOG4CXX_INFO(logger_,
+ "Check rfcomm channel on " << paired_devices_.size()
+ << " paired devices.");
paired_devices_with_sdl_.clear();
- CheckSDLServiceOnDevices(paired_devices_, device_handle,
- &paired_devices_with_sdl_);
+ CheckSDLServiceOnDevices(
+ paired_devices_, device_handle, &paired_devices_with_sdl_);
UpdateTotalDeviceList();
LOG4CXX_INFO(logger_, "Starting hci_inquiry on device " << device_id);
@@ -182,20 +198,23 @@ void BluetoothDeviceScanner::DoInquiry() {
const size_t max_devices = 256u;
inquiry_info* inquiry_info_list = new inquiry_info[max_devices];
- const int number_of_devices = hci_inquiry(device_id, inquiry_time,
- max_devices, 0, &inquiry_info_list,
- IREQ_CACHE_FLUSH);
+ const int number_of_devices = hci_inquiry(device_id,
+ inquiry_time,
+ max_devices,
+ 0,
+ &inquiry_info_list,
+ IREQ_CACHE_FLUSH);
if (number_of_devices >= 0) {
LOG4CXX_INFO(logger_,
"hci_inquiry: found " << number_of_devices << " devices");
- std::vector < bdaddr_t > found_devices(number_of_devices);
+ std::vector<bdaddr_t> found_devices(number_of_devices);
for (int i = 0; i < number_of_devices; ++i) {
found_devices[i] = inquiry_info_list[i].bdaddr;
}
found_devices_with_sdl_.clear();
- CheckSDLServiceOnDevices(found_devices, device_handle,
- &found_devices_with_sdl_);
+ CheckSDLServiceOnDevices(
+ found_devices, device_handle, &found_devices_with_sdl_);
}
UpdateTotalDeviceList();
controller_->FindNewApplicationsRequest();
@@ -210,12 +229,15 @@ void BluetoothDeviceScanner::DoInquiry() {
}
void BluetoothDeviceScanner::CheckSDLServiceOnDevices(
- const std::vector<bdaddr_t>& bd_addresses, int device_handle,
- DeviceVector* discovered_devices) {
- LOG4CXX_TRACE(logger_, "enter. bd_addresses: " << &bd_addresses << ", device_handle: " <<
- device_handle << ", discovered_devices: " << discovered_devices);
+ const std::vector<bdaddr_t>& bd_addresses,
+ int device_handle,
+ DeviceVector* discovered_devices) {
+ LOG4CXX_TRACE(logger_,
+ "enter. bd_addresses: "
+ << &bd_addresses << ", device_handle: " << device_handle
+ << ", discovered_devices: " << discovered_devices);
std::vector<RfcommChannelVector> sdl_rfcomm_channels =
- DiscoverSmartDeviceLinkRFCOMMChannels(bd_addresses);
+ DiscoverSmartDeviceLinkRFCOMMChannels(bd_addresses);
for (size_t i = 0; i < bd_addresses.size(); ++i) {
if (sdl_rfcomm_channels[i].empty()) {
@@ -224,9 +246,12 @@ void BluetoothDeviceScanner::CheckSDLServiceOnDevices(
const bdaddr_t& bd_address = bd_addresses[i];
char deviceName[256];
- int hci_read_remote_name_ret = hci_read_remote_name(
- device_handle, &bd_address, sizeof(deviceName) / sizeof(deviceName[0]),
- deviceName, 0);
+ int hci_read_remote_name_ret =
+ hci_read_remote_name(device_handle,
+ &bd_address,
+ sizeof(deviceName) / sizeof(deviceName[0]),
+ deviceName,
+ 0);
if (hci_read_remote_name_ret != 0) {
LOG4CXX_ERROR_WITH_ERRNO(logger_, "hci_read_remote_name failed");
@@ -235,8 +260,8 @@ void BluetoothDeviceScanner::CheckSDLServiceOnDevices(
sizeof(deviceName) / sizeof(deviceName[0]));
}
- Device* bluetooth_device = new BluetoothDevice(bd_address, deviceName,
- sdl_rfcomm_channels[i]);
+ Device* bluetooth_device =
+ new BluetoothDevice(bd_address, deviceName, sdl_rfcomm_channels[i]);
if (bluetooth_device) {
LOG4CXX_INFO(logger_, "Bluetooth device created successfully");
discovered_devices->push_back(bluetooth_device);
@@ -249,7 +274,7 @@ void BluetoothDeviceScanner::CheckSDLServiceOnDevices(
std::vector<BluetoothDeviceScanner::RfcommChannelVector>
BluetoothDeviceScanner::DiscoverSmartDeviceLinkRFCOMMChannels(
- const std::vector<bdaddr_t>& device_addresses) {
+ const std::vector<bdaddr_t>& device_addresses) {
LOG4CXX_TRACE(logger_, "enter device_addresses: " << &device_addresses);
const size_t size = device_addresses.size();
std::vector<RfcommChannelVector> result(size);
@@ -264,7 +289,7 @@ BluetoothDeviceScanner::DiscoverSmartDeviceLinkRFCOMMChannels(
continue;
}
const bool final = DiscoverSmartDeviceLinkRFCOMMChannels(
- device_addresses[i], &result[i]);
+ device_addresses[i], &result[i]);
if (final) {
processed[i] = true;
++processed_count;
@@ -275,18 +300,21 @@ BluetoothDeviceScanner::DiscoverSmartDeviceLinkRFCOMMChannels(
}
sleep(attempt_timeout);
}
- LOG4CXX_TRACE(logger_, "exit with vector<RfcommChannelVector>: size = " << result.size());
+ LOG4CXX_TRACE(
+ logger_,
+ "exit with vector<RfcommChannelVector>: size = " << result.size());
return result;
}
bool BluetoothDeviceScanner::DiscoverSmartDeviceLinkRFCOMMChannels(
- const bdaddr_t& device_address, RfcommChannelVector* channels) {
- LOG4CXX_TRACE(logger_, "enter. device_address: " << &device_address << ", channels: " <<
- channels);
- static bdaddr_t any_address = { { 0, 0, 0, 0, 0, 0 } };
+ const bdaddr_t& device_address, RfcommChannelVector* channels) {
+ LOG4CXX_TRACE(logger_,
+ "enter. device_address: " << &device_address
+ << ", channels: " << channels);
+ static bdaddr_t any_address = {{0, 0, 0, 0, 0, 0}};
sdp_session_t* sdp_session = sdp_connect(
- &any_address, &device_address, SDP_RETRY_IF_BUSY | SDP_WAIT_ON_CLOSE);
+ &any_address, &device_address, SDP_RETRY_IF_BUSY | SDP_WAIT_ON_CLOSE);
if (sdp_session == 0) {
bool result = !(errno == 31 || errno == 16 || errno == 117 || errno == 114);
if (result) {
@@ -297,14 +325,16 @@ bool BluetoothDeviceScanner::DiscoverSmartDeviceLinkRFCOMMChannels(
return result;
}
- sdp_list_t* search_list = sdp_list_append(0,
- &smart_device_link_service_uuid_);
+ sdp_list_t* search_list =
+ sdp_list_append(0, &smart_device_link_service_uuid_);
uint32_t range = 0x0000ffff;
sdp_list_t* attr_list = sdp_list_append(0, &range);
sdp_list_t* response_list = 0;
- if (0 == sdp_service_search_attr_req(sdp_session, search_list,
- SDP_ATTR_REQ_RANGE, attr_list,
+ if (0 == sdp_service_search_attr_req(sdp_session,
+ search_list,
+ SDP_ATTR_REQ_RANGE,
+ attr_list,
&response_list)) {
for (sdp_list_t* r = response_list; 0 != r; r = r->next) {
sdp_record_t* sdp_record = static_cast<sdp_record_t*>(r->data);
@@ -352,21 +382,23 @@ bool BluetoothDeviceScanner::DiscoverSmartDeviceLinkRFCOMMChannels(
std::stringstream rfcomm_channels_string;
for (RfcommChannelVector::const_iterator it = channels->begin();
- it != channels->end(); ++it) {
+ it != channels->end();
+ ++it) {
if (it != channels->begin()) {
rfcomm_channels_string << ", ";
}
rfcomm_channels_string << static_cast<uint32_t>(*it);
}
- LOG4CXX_INFO(logger_,
- "SmartDeviceLink service was discovered on device "
- << BluetoothDevice::GetUniqueDeviceId(device_address)
- << " at channel(s): " << rfcomm_channels_string.str().c_str());
+ LOG4CXX_INFO(
+ logger_,
+ "SmartDeviceLink service was discovered on device "
+ << BluetoothDevice::GetUniqueDeviceId(device_address)
+ << " at channel(s): " << rfcomm_channels_string.str().c_str());
} else {
LOG4CXX_INFO(logger_,
"SmartDeviceLink service was not discovered on device "
- << BluetoothDevice::GetUniqueDeviceId(device_address));
+ << BluetoothDevice::GetUniqueDeviceId(device_address));
}
LOG4CXX_TRACE(logger_, "exit with TRUE");
return true;
@@ -410,7 +442,8 @@ void BluetoothDeviceScanner::TimedWaitForDeviceScanRequest() {
sync_primitives::AutoLock auto_lock(device_scan_requested_lock_);
while (!(device_scan_requested_ || shutdown_requested_)) {
const sync_primitives::ConditionalVariable::WaitStatus wait_status =
- device_scan_requested_cv_.WaitFor(auto_lock, auto_repeat_pause_sec_ * 1000);
+ device_scan_requested_cv_.WaitFor(auto_lock,
+ auto_repeat_pause_sec_ * 1000);
if (wait_status == sync_primitives::ConditionalVariable::kTimeout) {
LOG4CXX_INFO(logger_, "Bluetooth scanner timeout, performing scan");
device_scan_requested_ = true;
@@ -421,7 +454,7 @@ void BluetoothDeviceScanner::TimedWaitForDeviceScanRequest() {
TransportAdapter::Error BluetoothDeviceScanner::Init() {
LOG4CXX_AUTO_TRACE(logger_);
- if(!thread_->start()) {
+ if (!thread_->start()) {
LOG4CXX_ERROR(logger_, "Bluetooth device scanner thread start failed");
return TransportAdapter::FAIL;
}
@@ -468,10 +501,9 @@ TransportAdapter::Error BluetoothDeviceScanner::Scan() {
return ret;
}
-BluetoothDeviceScanner::BluetoothDeviceScannerDelegate::BluetoothDeviceScannerDelegate(
- BluetoothDeviceScanner* scanner)
- : scanner_(scanner) {
-}
+BluetoothDeviceScanner::BluetoothDeviceScannerDelegate::
+ BluetoothDeviceScannerDelegate(BluetoothDeviceScanner* scanner)
+ : scanner_(scanner) {}
void BluetoothDeviceScanner::BluetoothDeviceScannerDelegate::threadMain() {
LOG4CXX_AUTO_TRACE(logger_);
@@ -481,4 +513,3 @@ void BluetoothDeviceScanner::BluetoothDeviceScannerDelegate::threadMain() {
} // namespace transport_adapter
} // namespace transport_manager
-
diff --git a/src/components/transport_manager/src/bluetooth/bluetooth_socket_connection.cc b/src/components/transport_manager/src/bluetooth/bluetooth_socket_connection.cc
index d6f9f26317..5f1eed4c5e 100644
--- a/src/components/transport_manager/src/bluetooth/bluetooth_socket_connection.cc
+++ b/src/components/transport_manager/src/bluetooth/bluetooth_socket_connection.cc
@@ -51,13 +51,12 @@ namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
BluetoothSocketConnection::BluetoothSocketConnection(
- const DeviceUID& device_uid, const ApplicationHandle& app_handle,
- TransportAdapterController* controller)
- : ThreadedSocketConnection(device_uid, app_handle, controller) {
-}
+ const DeviceUID& device_uid,
+ const ApplicationHandle& app_handle,
+ TransportAdapterController* controller)
+ : ThreadedSocketConnection(device_uid, app_handle, controller) {}
-BluetoothSocketConnection::~BluetoothSocketConnection() {
-}
+BluetoothSocketConnection::~BluetoothSocketConnection() {}
bool BluetoothSocketConnection::Establish(ConnectError** error) {
LOG4CXX_AUTO_TRACE(logger_);
@@ -65,21 +64,22 @@ bool BluetoothSocketConnection::Establish(ConnectError** error) {
DeviceSptr device = controller()->FindDevice(device_handle());
BluetoothDevice* bluetooth_device =
- static_cast<BluetoothDevice*>(device.get());
+ static_cast<BluetoothDevice*>(device.get());
uint8_t rfcomm_channel;
if (!bluetooth_device->GetRfcommChannel(application_handle(),
&rfcomm_channel)) {
LOG4CXX_DEBUG(logger_,
- "Application " << application_handle() << " not found");
+ "Application " << application_handle() << " not found");
*error = new ConnectError();
LOG4CXX_TRACE(logger_, "exit with FALSE");
return false;
}
- struct sockaddr_rc remoteSocketAddress = { 0 };
+ struct sockaddr_rc remoteSocketAddress = {0};
remoteSocketAddress.rc_family = AF_BLUETOOTH;
- memcpy(&remoteSocketAddress.rc_bdaddr, &bluetooth_device->address(),
+ memcpy(&remoteSocketAddress.rc_bdaddr,
+ &bluetooth_device->address(),
sizeof(bdaddr_t));
remoteSocketAddress.rc_channel = rfcomm_channel;
@@ -92,13 +92,14 @@ bool BluetoothSocketConnection::Establish(ConnectError** error) {
rfcomm_socket = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
if (-1 == rfcomm_socket) {
LOG4CXX_ERROR_WITH_ERRNO(logger_,
- "Failed to create RFCOMM socket for device " << device_handle());
+ "Failed to create RFCOMM socket for device "
+ << device_handle());
*error = new ConnectError();
LOG4CXX_TRACE(logger_, "exit with FALSE");
return false;
}
connect_status = ::connect(rfcomm_socket,
- (struct sockaddr*) &remoteSocketAddress,
+ (struct sockaddr*)&remoteSocketAddress,
sizeof(remoteSocketAddress));
if (0 == connect_status) {
LOG4CXX_DEBUG(logger_, "rfcomm Connect ok");
@@ -116,9 +117,11 @@ bool BluetoothSocketConnection::Establish(ConnectError** error) {
} while (--attempts > 0);
LOG4CXX_INFO(logger_, "rfcomm Connect attempts finished");
if (0 != connect_status) {
- LOG4CXX_DEBUG(logger_,
- "Failed to Connect to remote device " << BluetoothDevice::GetUniqueDeviceId(
- remoteSocketAddress.rc_bdaddr) << " for session " << this);
+ LOG4CXX_DEBUG(
+ logger_,
+ "Failed to Connect to remote device "
+ << BluetoothDevice::GetUniqueDeviceId(remoteSocketAddress.rc_bdaddr)
+ << " for session " << this);
*error = new ConnectError();
LOG4CXX_TRACE(logger_, "exit with FALSE");
return false;
diff --git a/src/components/transport_manager/src/bluetooth/bluetooth_transport_adapter.cc b/src/components/transport_manager/src/bluetooth/bluetooth_transport_adapter.cc
index 966c0f9b76..a82c40ca15 100644
--- a/src/components/transport_manager/src/bluetooth/bluetooth_transport_adapter.cc
+++ b/src/components/transport_manager/src/bluetooth/bluetooth_transport_adapter.cc
@@ -42,8 +42,6 @@
#include <set>
#include <bluetooth/bluetooth.h>
-#include "resumption/last_state.h"
-
#include "transport_manager/bluetooth/bluetooth_transport_adapter.h"
#include "transport_manager/bluetooth/bluetooth_device_scanner.h"
#include "transport_manager/bluetooth/bluetooth_connection_factory.h"
@@ -56,13 +54,15 @@ namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
-BluetoothTransportAdapter::~BluetoothTransportAdapter() {
-}
+BluetoothTransportAdapter::~BluetoothTransportAdapter() {}
-BluetoothTransportAdapter::BluetoothTransportAdapter()
- : TransportAdapterImpl(new BluetoothDeviceScanner(this, true, 0),
- new BluetoothConnectionFactory(this), 0) {
-}
+BluetoothTransportAdapter::BluetoothTransportAdapter(
+ resumption::LastState& last_state, const TransportManagerSettings& settings)
+ : TransportAdapterImpl(new BluetoothDeviceScanner(this, true, 0),
+ new BluetoothConnectionFactory(this),
+ NULL,
+ last_state,
+ settings) {}
DeviceType BluetoothTransportAdapter::GetDeviceType() const {
return BLUETOOTH;
@@ -73,14 +73,15 @@ void BluetoothTransportAdapter::Store() const {
Json::Value bluetooth_adapter_dictionary;
Json::Value devices_dictionary;
DeviceList device_ids = GetDeviceList();
- for (DeviceList::const_iterator i = device_ids.begin(); i != device_ids.end(); ++i) {
+ for (DeviceList::const_iterator i = device_ids.begin(); i != device_ids.end();
+ ++i) {
DeviceUID device_id = *i;
DeviceSptr device = FindDevice(device_id);
- if (!device) { // device could have been disconnected
+ if (!device) { // device could have been disconnected
continue;
}
utils::SharedPtr<BluetoothDevice> bluetooth_device =
- DeviceSptr::static_pointer_cast<BluetoothDevice>(device);
+ DeviceSptr::static_pointer_cast<BluetoothDevice>(device);
Json::Value device_dictionary;
device_dictionary["name"] = bluetooth_device->name();
char address[18];
@@ -88,15 +89,19 @@ void BluetoothTransportAdapter::Store() const {
device_dictionary["address"] = std::string(address);
Json::Value applications_dictionary;
ApplicationList app_ids = bluetooth_device->GetApplicationList();
- for (ApplicationList::const_iterator j = app_ids.begin(); j != app_ids.end(); ++j) {
+ for (ApplicationList::const_iterator j = app_ids.begin();
+ j != app_ids.end();
+ ++j) {
ApplicationHandle app_handle = *j;
- if (FindEstablishedConnection(bluetooth_device->unique_device_id(), app_handle)) {
+ if (FindEstablishedConnection(bluetooth_device->unique_device_id(),
+ app_handle)) {
uint8_t rfcomm_channel;
bluetooth_device->GetRfcommChannel(app_handle, &rfcomm_channel);
Json::Value application_dictionary;
char rfcomm_channel_record[4];
sprintf(rfcomm_channel_record, "%u", rfcomm_channel);
- application_dictionary["rfcomm_channel"] = std::string(rfcomm_channel_record);
+ application_dictionary["rfcomm_channel"] =
+ std::string(rfcomm_channel_record);
applications_dictionary.append(application_dictionary);
}
}
@@ -106,8 +111,8 @@ void BluetoothTransportAdapter::Store() const {
}
}
bluetooth_adapter_dictionary["devices"] = devices_dictionary;
- resumption::LastState::instance()->dictionary["TransportManager"]["BluetoothAdapter"] =
- bluetooth_adapter_dictionary;
+ last_state().dictionary["TransportManager"]["BluetoothAdapter"] =
+ bluetooth_adapter_dictionary;
LOG4CXX_TRACE(logger_, "exit");
}
@@ -115,34 +120,39 @@ bool BluetoothTransportAdapter::Restore() {
LOG4CXX_TRACE(logger_, "enter");
bool errors_occured = false;
const Json::Value bluetooth_adapter_dictionary =
- resumption::LastState::instance()->dictionary["TransportManager"]["BluetoothAdapter"];
- const Json::Value devices_dictionary = bluetooth_adapter_dictionary["devices"];
+ last_state().dictionary["TransportManager"]["BluetoothAdapter"];
+ const Json::Value devices_dictionary =
+ bluetooth_adapter_dictionary["devices"];
for (Json::Value::const_iterator i = devices_dictionary.begin();
- i != devices_dictionary.end(); ++i) {
+ i != devices_dictionary.end();
+ ++i) {
const Json::Value device_dictionary = *i;
std::string name = device_dictionary["name"].asString();
std::string address_record = device_dictionary["address"].asString();
bdaddr_t address;
str2ba(address_record.c_str(), &address);
RfcommChannelVector rfcomm_channels;
- const Json::Value applications_dictionary = device_dictionary["applications"];
+ const Json::Value applications_dictionary =
+ device_dictionary["applications"];
for (Json::Value::const_iterator j = applications_dictionary.begin();
- j != applications_dictionary.end(); ++j) {
+ j != applications_dictionary.end();
+ ++j) {
const Json::Value application_dictionary = *j;
std::string rfcomm_channel_record =
- application_dictionary["rfcomm_channel"].asString();
+ application_dictionary["rfcomm_channel"].asString();
uint8_t rfcomm_channel =
- static_cast<uint8_t>(atoi(rfcomm_channel_record.c_str()));
+ static_cast<uint8_t>(atoi(rfcomm_channel_record.c_str()));
rfcomm_channels.push_back(rfcomm_channel);
}
BluetoothDevice* bluetooth_device =
- new BluetoothDevice(address, name.c_str(), rfcomm_channels);
+ new BluetoothDevice(address, name.c_str(), rfcomm_channels);
DeviceSptr device(bluetooth_device);
AddDevice(device);
- for (RfcommChannelVector::const_iterator j =
- rfcomm_channels.begin(); j != rfcomm_channels.end(); ++j) {
+ for (RfcommChannelVector::const_iterator j = rfcomm_channels.begin();
+ j != rfcomm_channels.end();
+ ++j) {
ApplicationHandle app_handle =
- *j; // for Bluetooth device app_handle is just RFCOMM channel
+ *j; // for Bluetooth device app_handle is just RFCOMM channel
if (Error::OK != Connect(device->unique_device_id(), app_handle)) {
errors_occured = true;
}
diff --git a/src/components/transport_manager/src/tcp/dnssd_service_browser.cc b/src/components/transport_manager/src/tcp/dnssd_service_browser.cc
deleted file mode 100644
index 3571ac8156..0000000000
--- a/src/components/transport_manager/src/tcp/dnssd_service_browser.cc
+++ /dev/null
@@ -1,378 +0,0 @@
-/*
- *
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <algorithm>
-#include <map>
-#include "utils/logger.h"
-
-#include "transport_manager/transport_adapter/transport_adapter_impl.h"
-#include "transport_manager/tcp/tcp_device.h"
-#include "transport_manager/tcp/dnssd_service_browser.h"
-
-
-namespace transport_manager {
-namespace transport_adapter {
-
-CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
-
-
-bool operator==(const DnssdServiceRecord& a, const DnssdServiceRecord& b) {
- return a.name == b.name && a.type == b.type && a.interface == b.interface
- && a.protocol == b.protocol && a.domain_name == b.domain_name;
-}
-
-void DnssdServiceBrowser::Terminate() {
- LOG4CXX_AUTO_TRACE(logger_);
- if (0 != avahi_threaded_poll_) {
- avahi_threaded_poll_stop(avahi_threaded_poll_);
- }
- if (0 != avahi_service_browser_) {
- avahi_service_browser_free(avahi_service_browser_);
- avahi_service_browser_ = NULL;
- }
- if (0 != avahi_client_) {
- avahi_client_free(avahi_client_);
- avahi_client_ = NULL;
- }
- if (0 != avahi_threaded_poll_) {
- avahi_threaded_poll_free(avahi_threaded_poll_);
- avahi_threaded_poll_ = NULL;
- }
-}
-
-bool DnssdServiceBrowser::IsInitialised() const {
- return initialised_;
-}
-
-DnssdServiceBrowser::DnssdServiceBrowser(TransportAdapterController* controller)
- : controller_(controller),
- avahi_service_browser_(0),
- avahi_threaded_poll_(0),
- avahi_client_(0),
- service_records_(),
- mutex_(),
- initialised_(false) {
-}
-
-DnssdServiceBrowser::~DnssdServiceBrowser() {
-}
-
-void DnssdServiceBrowser::OnClientConnected() {
- initialised_ = true;
- LOG4CXX_INFO(logger_, "AvahiClient ready");
-}
-
-void DnssdServiceBrowser::OnClientFailure() {
- LOG4CXX_AUTO_TRACE(logger_);
- const int avahi_errno = avahi_client_errno(avahi_client_);
- if (avahi_errno == AVAHI_ERR_DISCONNECTED) {
- LOG4CXX_DEBUG(logger_, "AvahiClient disconnected");
- CreateAvahiClientAndBrowser();
- } else {
- LOG4CXX_ERROR(logger_,
- "AvahiClient failure: " << avahi_strerror(avahi_errno));
- }
-}
-
-void AvahiClientCallback(AvahiClient* avahi_client,
- AvahiClientState avahi_client_state, void* data) {
- LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(
- logger_,
- "avahi_client " << avahi_client << ", avahi_client_state " << avahi_client_state << ", data " << data);
- DnssdServiceBrowser* dnssd_service_browser =
- static_cast<DnssdServiceBrowser*>(data);
-
- switch (avahi_client_state) {
- case AVAHI_CLIENT_S_RUNNING:
- dnssd_service_browser->OnClientConnected();
- LOG4CXX_DEBUG(logger_, "avahi_client_state: AVAHI_CLIENT_S_RUNNING");
- break;
- case AVAHI_CLIENT_FAILURE:
- dnssd_service_browser->OnClientFailure();
- LOG4CXX_DEBUG(logger_, "avahi_client_state: AVAHI_CLIENT_FAILURE");
- break;
- default: {
- LOG4CXX_ERROR(logger_,
- "Unknown avahi_client_state: " << avahi_client_state);
- }
- }
-}
-
-void AvahiServiceBrowserCallback(AvahiServiceBrowser* avahi_service_browser,
- AvahiIfIndex interface, AvahiProtocol protocol,
- AvahiBrowserEvent event, const char* name,
- const char* type, const char* domain,
- AvahiLookupResultFlags flags, void* data) {
- LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(
- logger_,
- "avahi_service_browser " << avahi_service_browser << " interface " << interface <<
- " protocol " << protocol << " event " << event << " name " << name <<
- " type " << type << " domain " << domain << " flags " << flags << " data " << data);
- DnssdServiceBrowser* dnssd_service_browser =
- static_cast<DnssdServiceBrowser*>(data);
-
- switch (event) {
- case AVAHI_BROWSER_FAILURE:
- LOG4CXX_ERROR(
- logger_,
- "AvahiServiceBrowser failure: " << avahi_strerror(avahi_client_errno(
- avahi_service_browser_get_client(avahi_service_browser))));
- break;
-
- case AVAHI_BROWSER_NEW:
- dnssd_service_browser->AddService(interface, protocol, name, type,
- domain);
- LOG4CXX_DEBUG(logger_, "event: AVAHI_BROWSER_NEW");
- break;
-
- case AVAHI_BROWSER_REMOVE:
- dnssd_service_browser->RemoveService(interface, protocol, name, type,
- domain);
- LOG4CXX_DEBUG(logger_, "event: AVAHI_BROWSER_REMOVE");
- break;
-
- case AVAHI_BROWSER_ALL_FOR_NOW:
- LOG4CXX_DEBUG(logger_, "event: AVAHI_BROWSER_ALL_FOR_NOW");
- break;
- case AVAHI_BROWSER_CACHE_EXHAUSTED:
- LOG4CXX_DEBUG(logger_, "event: AVAHI_BROWSER_CACHE_EXHAUSTED");
- break;
- }
- LOG4CXX_TRACE(logger_, "exit");
-}
-
-void DnssdServiceBrowser::ServiceResolved(
- const DnssdServiceRecord& service_record) {
- LOG4CXX_AUTO_TRACE(logger_);
- sync_primitives::AutoLock locker(mutex_);
- ServiceRecords::iterator service_record_it = std::find(
- service_records_.begin(), service_records_.end(), service_record);
- if (service_record_it != service_records_.end()) {
- *service_record_it = service_record;
- }
- DeviceVector device_vector = PrepareDeviceVector();
- controller_->SearchDeviceDone(device_vector);
-}
-
-void DnssdServiceBrowser::ServiceResolveFailed(
- const DnssdServiceRecord& service_record) {
- LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(logger_,
- "AvahiServiceResolver failure for: " << service_record.name);
- sync_primitives::AutoLock locker(mutex_);
- ServiceRecords::iterator service_record_it = std::find(
- service_records_.begin(), service_records_.end(), service_record);
- if (service_record_it != service_records_.end()) {
- service_records_.erase(service_record_it);
- }
-}
-
-void AvahiServiceResolverCallback(AvahiServiceResolver* avahi_service_resolver,
- AvahiIfIndex interface,
- AvahiProtocol protocol,
- AvahiResolverEvent event, const char* name,
- const char* type, const char* domain,
- const char* host_name,
- const AvahiAddress* avahi_address,
- uint16_t port, AvahiStringList* txt,
- AvahiLookupResultFlags flags, void* data) {
- LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(
- logger_,
- "avahi_service_resolver " << avahi_service_resolver << " interface " << interface <<
- " protocol " << protocol << " event " << event << " name " << name <<
- " type " << type << " domain " << domain << " host_name " << host_name <<
- " avahi_address " << avahi_address << " port " << port <<
- " txt " << txt << " flags " << flags << " data " << data);
- DnssdServiceBrowser* dnssd_service_browser =
- static_cast<DnssdServiceBrowser*>(data);
-
- DnssdServiceRecord service_record;
- service_record.interface = interface;
- service_record.protocol = protocol;
- service_record.domain_name = domain;
- service_record.host_name = host_name;
- service_record.name = name;
- service_record.type = type;
- switch (event) {
- case AVAHI_RESOLVER_FOUND:
- service_record.addr = avahi_address->data.ipv4.address;
- service_record.port = port;
- dnssd_service_browser->ServiceResolved(service_record);
- LOG4CXX_DEBUG(logger_, "event: AVAHI_RESOLVER_FOUND");
- break;
- case AVAHI_RESOLVER_FAILURE:
- dnssd_service_browser->ServiceResolveFailed(service_record);
- LOG4CXX_DEBUG(logger_, "event: AVAHI_RESOLVER_FAILURE");
- break;
- }
-
- avahi_service_resolver_free(avahi_service_resolver);
-}
-
-TransportAdapter::Error DnssdServiceBrowser::CreateAvahiClientAndBrowser() {
- LOG4CXX_AUTO_TRACE(logger_);
- if (0 != avahi_service_browser_) {
- avahi_service_browser_free(avahi_service_browser_);
- avahi_service_browser_ = NULL;
- }
- if (0 != avahi_client_) {
- avahi_client_free(avahi_client_);
- avahi_client_ = NULL;
- }
-
- int avahi_error;
- avahi_client_ = avahi_client_new(
- avahi_threaded_poll_get(avahi_threaded_poll_), AVAHI_CLIENT_NO_FAIL,
- AvahiClientCallback, this, &avahi_error);
- if (0 == avahi_client_) {
- LOG4CXX_ERROR(
- logger_,
- "Failed to create AvahiClient: " << avahi_strerror(avahi_error));
- return TransportAdapter::FAIL;
- }
-
- mutex_.Acquire();
- service_records_.clear();
- mutex_.Release();
-
- avahi_service_browser_ = avahi_service_browser_new(
- avahi_client_, AVAHI_IF_UNSPEC, /* TODO use only required iface */
- AVAHI_PROTO_INET, DNSSD_DEFAULT_SERVICE_TYPE, NULL, /* use default domain */
- static_cast<AvahiLookupFlags>(0), AvahiServiceBrowserCallback, this);
- return TransportAdapter::OK;
-}
-
-TransportAdapter::Error DnssdServiceBrowser::Init() {
- LOG4CXX_AUTO_TRACE(logger_);
- avahi_threaded_poll_ = avahi_threaded_poll_new();
- if (0 == avahi_threaded_poll_) {
- LOG4CXX_ERROR(logger_, "Failed to create AvahiThreadedPoll");
- return TransportAdapter::FAIL;
- }
-
- const TransportAdapter::Error err = CreateAvahiClientAndBrowser();
- if (err != TransportAdapter::OK) {
- LOG4CXX_ERROR(logger_, "Error " << err);
- return err;
- }
-
- const int poll_start_status = avahi_threaded_poll_start(avahi_threaded_poll_);
- if (0 != poll_start_status) {
- LOG4CXX_ERROR(logger_, "Failed to start AvahiThreadedPoll");
- return TransportAdapter::FAIL;
- }
- return TransportAdapter::OK;
-}
-
-TransportAdapter::Error DnssdServiceBrowser::Scan() {
- return TransportAdapter::NOT_SUPPORTED;
-}
-
-void DnssdServiceBrowser::AddService(AvahiIfIndex interface,
- AvahiProtocol protocol, const char* name,
- const char* type, const char* domain) {
- LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(
- logger_,
- "interface " << interface << " protocol " << protocol << " name " << name << " type " << type << " domain " << domain);
- DnssdServiceRecord record;
- record.interface = interface;
- record.protocol = protocol;
- record.domain_name = domain;
- record.name = name;
- record.type = type;
-
- sync_primitives::AutoLock locker(mutex_);
- if (service_records_.end()
- == std::find(service_records_.begin(), service_records_.end(), record)) {
- service_records_.push_back(record);
- avahi_service_resolver_new(avahi_client_, interface, protocol, name, type,
- domain, AVAHI_PROTO_INET,
- static_cast<AvahiLookupFlags>(0),
- AvahiServiceResolverCallback, this);
- }
-}
-
-void DnssdServiceBrowser::RemoveService(AvahiIfIndex interface,
- AvahiProtocol protocol,
- const char* name, const char* type,
- const char* domain) {
- LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(
- logger_,
- "interface " << interface << " protocol " << protocol << " name " << name << " type " << type << " domain " << domain);
- DnssdServiceRecord record;
- record.interface = interface;
- record.protocol = protocol;
- record.name = name;
- record.type = type;
- record.domain_name = domain;
-
- sync_primitives::AutoLock locker(mutex_);
- service_records_.erase(
- std::remove(service_records_.begin(), service_records_.end(), record),
- service_records_.end());
-}
-
-DeviceVector DnssdServiceBrowser::PrepareDeviceVector() const {
- LOG4CXX_AUTO_TRACE(logger_);
- std::map<uint32_t, TcpDevice*> devices;
- for (ServiceRecords::const_iterator it = service_records_.begin();
- it != service_records_.end(); ++it) {
- const DnssdServiceRecord& service_record = *it;
- if (service_record.host_name.empty()) {
- continue;
- }
- if (devices[service_record.addr] == 0) {
- devices[service_record.addr] = new TcpDevice(service_record.addr,
- service_record.host_name);
- }
- if (devices[service_record.addr] != 0) {
- devices[service_record.addr]->AddDiscoveredApplication(
- service_record.port);
- }
- }
- DeviceVector device_vector;
- device_vector.reserve(devices.size());
- for (std::map<uint32_t, TcpDevice*>::const_iterator it = devices.begin();
- it != devices.end(); ++it) {
- device_vector.push_back(DeviceSptr(it->second));
- }
- return device_vector;
-}
-
-} // namespace transport_adapter
-} // namespace transport_manager
diff --git a/src/components/transport_manager/src/tcp/tcp_client_listener.cc b/src/components/transport_manager/src/tcp/tcp_client_listener.cc
index 28a3c389da..a075b1afb7 100644
--- a/src/components/transport_manager/src/tcp/tcp_client_listener.cc
+++ b/src/components/transport_manager/src/tcp/tcp_client_listener.cc
@@ -42,12 +42,12 @@
#include <sys/sysctl.h>
#include <sys/socket.h>
#ifdef __linux__
-# include <linux/tcp.h>
+#include <linux/tcp.h>
#else // __linux__
-# include <sys/time.h>
-# include <netinet/in.h>
-# include <netinet/tcp.h>
-# include <netinet/tcp_var.h>
+#include <sys/time.h>
+#include <netinet/in.h>
+#include <netinet/tcp.h>
+#include <netinet/tcp_var.h>
#endif // __linux__
#include <sstream>
@@ -66,12 +66,12 @@ CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
TcpClientListener::TcpClientListener(TransportAdapterController* controller,
const uint16_t port,
const bool enable_keepalive)
- : port_(port),
- enable_keepalive_(enable_keepalive),
- controller_(controller),
- thread_(0),
- socket_(-1),
- thread_stop_requested_(false) {
+ : port_(port)
+ , enable_keepalive_(enable_keepalive)
+ , controller_(controller)
+ , thread_(0)
+ , socket_(-1)
+ , thread_stop_requested_(false) {
thread_ = threads::CreateThread("TcpClientListener",
new ListeningThreadDelegate(this));
}
@@ -86,7 +86,7 @@ TransportAdapter::Error TcpClientListener::Init() {
return TransportAdapter::FAIL;
}
- sockaddr_in server_address = { 0 };
+ sockaddr_in server_address = {0};
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port_);
server_address.sin_addr.s_addr = INADDR_ANY;
@@ -94,7 +94,8 @@ TransportAdapter::Error TcpClientListener::Init() {
int optval = 1;
setsockopt(socket_, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
- if (bind(socket_, reinterpret_cast<sockaddr*>(&server_address),
+ if (bind(socket_,
+ reinterpret_cast<sockaddr*>(&server_address),
sizeof(server_address)) != 0) {
LOG4CXX_ERROR_WITH_ERRNO(logger_, "bind() failed");
return TransportAdapter::FAIL;
@@ -148,8 +149,8 @@ void SetKeepaliveOptions(const int fd) {
setsockopt(fd, IPPROTO_TCP, TCP_KEEPIDLE, &keepidle, sizeof(keepidle));
setsockopt(fd, IPPROTO_TCP, TCP_KEEPCNT, &keepcnt, sizeof(keepcnt));
setsockopt(fd, IPPROTO_TCP, TCP_KEEPINTVL, &keepintvl, sizeof(keepintvl));
- setsockopt(fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &user_timeout,
- sizeof(user_timeout));
+ setsockopt(
+ fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &user_timeout, sizeof(user_timeout));
#elif defined(__QNX__) // __linux__
// TODO(KKolodiy): Out of order!
const int kMidLength = 4;
@@ -177,7 +178,7 @@ void SetKeepaliveOptions(const int fd) {
tval.tv_sec = keepidle;
setsockopt(fd, SOL_SOCKET, SO_KEEPALIVE, &yes, sizeof(yes));
setsockopt(fd, IPPROTO_TCP, TCP_KEEPALIVE, &tval, sizeof(tval));
-#endif // __QNX__
+#endif // __QNX__
}
void TcpClientListener::Loop() {
@@ -185,9 +186,8 @@ void TcpClientListener::Loop() {
while (!thread_stop_requested_) {
sockaddr_in client_address;
socklen_t client_address_size = sizeof(client_address);
- const int connection_fd = accept(socket_,
- (struct sockaddr*) &client_address,
- &client_address_size);
+ const int connection_fd = accept(
+ socket_, (struct sockaddr*)&client_address, &client_address_size);
if (thread_stop_requested_) {
LOG4CXX_DEBUG(logger_, "thread_stop_requested_");
close(connection_fd);
@@ -206,7 +206,8 @@ void TcpClientListener::Loop() {
}
char device_name[32];
- strncpy(device_name, inet_ntoa(client_address.sin_addr),
+ strncpy(device_name,
+ inet_ntoa(client_address.sin_addr),
sizeof(device_name) / sizeof(device_name[0]));
LOG4CXX_INFO(logger_, "Connected client " << device_name);
@@ -214,16 +215,15 @@ void TcpClientListener::Loop() {
SetKeepaliveOptions(connection_fd);
}
- TcpDevice* tcp_device = new TcpDevice(client_address.sin_addr.s_addr,
- device_name);
+ TcpDevice* tcp_device =
+ new TcpDevice(client_address.sin_addr.s_addr, device_name);
DeviceSptr device = controller_->AddDevice(tcp_device);
tcp_device = static_cast<TcpDevice*>(device.get());
- const ApplicationHandle app_handle = tcp_device->AddIncomingApplication(
- connection_fd);
+ const ApplicationHandle app_handle =
+ tcp_device->AddIncomingApplication(connection_fd);
- TcpSocketConnection* connection(
- new TcpSocketConnection(device->unique_device_id(), app_handle,
- controller_));
+ TcpSocketConnection* connection(new TcpSocketConnection(
+ device->unique_device_id(), app_handle, controller_));
connection->set_socket(connection_fd);
const TransportAdapter::Error error = connection->Start();
if (error != TransportAdapter::OK) {
@@ -237,11 +237,12 @@ void TcpClientListener::StopLoop() {
thread_stop_requested_ = true;
// We need to connect to the listening socket to unblock accept() call
int byesocket = socket(AF_INET, SOCK_STREAM, 0);
- sockaddr_in server_address = { 0 };
+ sockaddr_in server_address = {0};
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port_);
server_address.sin_addr.s_addr = INADDR_ANY;
- connect(byesocket, reinterpret_cast<sockaddr*>(&server_address),
+ connect(byesocket,
+ reinterpret_cast<sockaddr*>(&server_address),
sizeof(server_address));
shutdown(byesocket, SHUT_RDWR);
close(byesocket);
@@ -250,8 +251,9 @@ void TcpClientListener::StopLoop() {
TransportAdapter::Error TcpClientListener::StartListening() {
LOG4CXX_AUTO_TRACE(logger_);
if (thread_->is_running()) {
- LOG4CXX_WARN(logger_,
- "TransportAdapter::BAD_STATE. Listener has already been started");
+ LOG4CXX_WARN(
+ logger_,
+ "TransportAdapter::BAD_STATE. Listener has already been started");
return TransportAdapter::BAD_STATE;
}
@@ -273,8 +275,7 @@ void TcpClientListener::ListeningThreadDelegate::threadMain() {
TcpClientListener::ListeningThreadDelegate::ListeningThreadDelegate(
TcpClientListener* parent)
- : parent_(parent) {
-}
+ : parent_(parent) {}
TransportAdapter::Error TcpClientListener::StopListening() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/transport_manager/src/tcp/tcp_connection_factory.cc b/src/components/transport_manager/src/tcp/tcp_connection_factory.cc
index 7c6c06ddc0..5b1e9af6cb 100644
--- a/src/components/transport_manager/src/tcp/tcp_connection_factory.cc
+++ b/src/components/transport_manager/src/tcp/tcp_connection_factory.cc
@@ -42,8 +42,7 @@ CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
TcpConnectionFactory::TcpConnectionFactory(
TransportAdapterController* controller)
- : controller_(controller) {
-}
+ : controller_(controller) {}
TransportAdapter::Error TcpConnectionFactory::Init() {
return TransportAdapter::OK;
@@ -52,13 +51,12 @@ TransportAdapter::Error TcpConnectionFactory::Init() {
TransportAdapter::Error TcpConnectionFactory::CreateConnection(
const DeviceUID& device_uid, const ApplicationHandle& app_handle) {
LOG4CXX_AUTO_TRACE(logger_);
- LOG4CXX_DEBUG(
- logger_,
- "DeviceUID: " << &device_uid << ", ApplicationHandle: " << &app_handle);
+ LOG4CXX_DEBUG(logger_,
+ "DeviceUID: " << &device_uid
+ << ", ApplicationHandle: " << &app_handle);
TcpServerOiginatedSocketConnection* connection(
- new TcpServerOiginatedSocketConnection(device_uid, app_handle,
- controller_));
- controller_->ConnectionCreated(connection, device_uid, app_handle);
+ new TcpServerOiginatedSocketConnection(
+ device_uid, app_handle, controller_));
if (connection->Start() == TransportAdapter::OK) {
LOG4CXX_DEBUG(logger_, "TCP connection initialised");
return TransportAdapter::OK;
@@ -68,15 +66,13 @@ TransportAdapter::Error TcpConnectionFactory::CreateConnection(
}
}
-void TcpConnectionFactory::Terminate() {
-}
+void TcpConnectionFactory::Terminate() {}
bool TcpConnectionFactory::IsInitialised() const {
return true;
}
-TcpConnectionFactory::~TcpConnectionFactory() {
-}
+TcpConnectionFactory::~TcpConnectionFactory() {}
} // namespace transport_adapter
} // namespace transport_manager
diff --git a/src/components/transport_manager/src/tcp/tcp_device.cc b/src/components/transport_manager/src/tcp/tcp_device.cc
index 2dacd9e8a2..d3f132759a 100644
--- a/src/components/transport_manager/src/tcp/tcp_device.cc
+++ b/src/components/transport_manager/src/tcp/tcp_device.cc
@@ -33,19 +33,16 @@
#include "utils/logger.h"
#include "transport_manager/tcp/tcp_device.h"
-
namespace transport_manager {
namespace transport_adapter {
-//CREATE_LOGGERPTR_LOCAL(logger_, "TransportManager")
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
-
TcpDevice::TcpDevice(const in_addr_t& in_addr, const std::string& name)
- : Device(name, name),
- applications_mutex_(),
- in_addr_(in_addr),
- last_handle_(0) {
+ : Device(name, name)
+ , applications_mutex_()
+ , in_addr_(in_addr)
+ , last_handle_(0) {
LOG4CXX_AUTO_TRACE(logger_);
}
@@ -70,7 +67,9 @@ ApplicationList TcpDevice::GetApplicationList() const {
sync_primitives::AutoLock locker(applications_mutex_);
ApplicationList app_list;
for (std::map<ApplicationHandle, Application>::const_iterator it =
- applications_.begin(); it != applications_.end(); ++it) {
+ applications_.begin();
+ it != applications_.end();
+ ++it) {
app_list.push_back(it->first);
}
return app_list;
@@ -118,8 +117,8 @@ TcpDevice::~TcpDevice() {
int TcpDevice::GetApplicationSocket(const ApplicationHandle app_handle) const {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "ApplicationHandle: " << app_handle);
- std::map<ApplicationHandle, Application>::const_iterator it = applications_
- .find(app_handle);
+ std::map<ApplicationHandle, Application>::const_iterator it =
+ applications_.find(app_handle);
if (applications_.end() == it) {
LOG4CXX_WARN(logger_, "Application was not found");
return -1;
@@ -135,8 +134,8 @@ int TcpDevice::GetApplicationSocket(const ApplicationHandle app_handle) const {
int TcpDevice::GetApplicationPort(const ApplicationHandle app_handle) const {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, "ApplicationHandle: " << app_handle);
- std::map<ApplicationHandle, Application>::const_iterator it = applications_
- .find(app_handle);
+ std::map<ApplicationHandle, Application>::const_iterator it =
+ applications_.find(app_handle);
if (applications_.end() == it) {
LOG4CXX_WARN(logger_, "Application was not found");
return -1;
diff --git a/src/components/transport_manager/src/tcp/tcp_socket_connection.cc b/src/components/transport_manager/src/tcp/tcp_socket_connection.cc
index c5d0e88d84..acab9f555f 100644
--- a/src/components/transport_manager/src/tcp/tcp_socket_connection.cc
+++ b/src/components/transport_manager/src/tcp/tcp_socket_connection.cc
@@ -51,24 +51,21 @@ CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
TcpSocketConnection::TcpSocketConnection(const DeviceUID& device_uid,
const ApplicationHandle& app_handle,
TransportAdapterController* controller)
- : ThreadedSocketConnection(device_uid, app_handle, controller) {
-}
+ : ThreadedSocketConnection(device_uid, app_handle, controller) {}
-TcpSocketConnection::~TcpSocketConnection() {
-}
+TcpSocketConnection::~TcpSocketConnection() {}
bool TcpSocketConnection::Establish(ConnectError** error) {
return true;
}
TcpServerOiginatedSocketConnection::TcpServerOiginatedSocketConnection(
- const DeviceUID& device_uid, const ApplicationHandle& app_handle,
+ const DeviceUID& device_uid,
+ const ApplicationHandle& app_handle,
TransportAdapterController* controller)
- : ThreadedSocketConnection(device_uid, app_handle, controller) {
-}
+ : ThreadedSocketConnection(device_uid, app_handle, controller) {}
-TcpServerOiginatedSocketConnection::~TcpServerOiginatedSocketConnection() {
-}
+TcpServerOiginatedSocketConnection::~TcpServerOiginatedSocketConnection() {}
bool TcpServerOiginatedSocketConnection::Establish(ConnectError** error) {
LOG4CXX_AUTO_TRACE(logger_);
@@ -84,9 +81,9 @@ bool TcpServerOiginatedSocketConnection::Establish(ConnectError** error) {
const int port = tcp_device->GetApplicationPort(application_handle());
if (-1 == port) {
- LOG4CXX_ERROR(
- logger_,
- "Application port for " << application_handle() << " not found");
+ LOG4CXX_ERROR(logger_,
+ "Application port for " << application_handle()
+ << " not found");
*error = new ConnectError();
return false;
}
@@ -98,17 +95,17 @@ bool TcpServerOiginatedSocketConnection::Establish(ConnectError** error) {
return false;
}
- struct sockaddr_in addr = { 0 };
+ struct sockaddr_in addr = {0};
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = tcp_device->in_addr();
addr.sin_port = htons(port);
LOG4CXX_DEBUG(logger_,
- "Connecting " << inet_ntoa(addr.sin_addr) << ":" << port);
- if (::connect(socket, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
- LOG4CXX_ERROR(
- logger_,
- "Failed to connect for application " << application_handle() << ", error " << errno);
+ "Connecting " << inet_ntoa(addr.sin_addr) << ":" << port);
+ if (::connect(socket, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
+ LOG4CXX_ERROR(logger_,
+ "Failed to connect for application " << application_handle()
+ << ", error " << errno);
*error = new ConnectError();
::close(socket);
return false;
diff --git a/src/components/transport_manager/src/tcp/tcp_transport_adapter.cc b/src/components/transport_manager/src/tcp/tcp_transport_adapter.cc
index 3998c02ab9..a389deb517 100644
--- a/src/components/transport_manager/src/tcp/tcp_transport_adapter.cc
+++ b/src/components/transport_manager/src/tcp/tcp_transport_adapter.cc
@@ -42,33 +42,26 @@
#include "utils/logger.h"
#include "utils/threads/thread_delegate.h"
-#include "resumption/last_state.h"
#include "transport_manager/tcp/tcp_client_listener.h"
#include "transport_manager/tcp/tcp_connection_factory.h"
#include "transport_manager/tcp/tcp_device.h"
-#ifdef AVAHI_SUPPORT
-#include "transport_manager/tcp/dnssd_service_browser.h"
-#endif
-
namespace transport_manager {
namespace transport_adapter {
-CREATE_LOGGERPTR_GLOBAL(logger_, "TransportAdapterImpl")
+CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
-TcpTransportAdapter::TcpTransportAdapter(const uint16_t port)
- : TransportAdapterImpl(
-#ifdef AVAHI_SUPPORT
- new DnssdServiceBrowser(this),
-#else
- NULL,
-#endif
+TcpTransportAdapter::TcpTransportAdapter(
+ const uint16_t port,
+ resumption::LastState& last_state,
+ const TransportManagerSettings& settings)
+ : TransportAdapterImpl(NULL,
new TcpConnectionFactory(this),
- new TcpClientListener(this, port, true)) {
-}
+ new TcpClientListener(this, port, true),
+ last_state,
+ settings) {}
-TcpTransportAdapter::~TcpTransportAdapter() {
-}
+TcpTransportAdapter::~TcpTransportAdapter() {}
DeviceType TcpTransportAdapter::GetDeviceType() const {
return TCP;
@@ -80,14 +73,14 @@ void TcpTransportAdapter::Store() const {
Json::Value devices_dictionary;
DeviceList device_ids = GetDeviceList();
for (DeviceList::const_iterator i = device_ids.begin(); i != device_ids.end();
- ++i) {
+ ++i) {
DeviceUID device_id = *i;
DeviceSptr device = FindDevice(device_id);
if (!device) { // device could have been disconnected
continue;
}
- utils::SharedPtr<TcpDevice> tcp_device = DeviceSptr::static_pointer_cast<
- TcpDevice>(device);
+ utils::SharedPtr<TcpDevice> tcp_device =
+ DeviceSptr::static_pointer_cast<TcpDevice>(device);
Json::Value device_dictionary;
device_dictionary["name"] = tcp_device->name();
struct in_addr address;
@@ -96,7 +89,8 @@ void TcpTransportAdapter::Store() const {
Json::Value applications_dictionary;
ApplicationList app_ids = tcp_device->GetApplicationList();
for (ApplicationList::const_iterator j = app_ids.begin();
- j != app_ids.end(); ++j) {
+ j != app_ids.end();
+ ++j) {
ApplicationHandle app_handle = *j;
if (FindEstablishedConnection(tcp_device->unique_device_id(),
app_handle)) {
@@ -116,18 +110,19 @@ void TcpTransportAdapter::Store() const {
}
}
tcp_adapter_dictionary["devices"] = devices_dictionary;
- Json::Value& dictionary = resumption::LastState::instance()->dictionary;
+ Json::Value& dictionary = last_state().dictionary;
dictionary["TransportManager"]["TcpAdapter"] = tcp_adapter_dictionary;
}
bool TcpTransportAdapter::Restore() {
LOG4CXX_AUTO_TRACE(logger_);
bool errors_occurred = false;
- const Json::Value tcp_adapter_dictionary = resumption::LastState::instance()
- ->dictionary["TransportManager"]["TcpAdapter"];
+ const Json::Value tcp_adapter_dictionary =
+ last_state().dictionary["TransportManager"]["TcpAdapter"];
const Json::Value devices_dictionary = tcp_adapter_dictionary["devices"];
for (Json::Value::const_iterator i = devices_dictionary.begin();
- i != devices_dictionary.end(); ++i) {
+ i != devices_dictionary.end();
+ ++i) {
const Json::Value device_dictionary = *i;
std::string name = device_dictionary["name"].asString();
std::string address_record = device_dictionary["address"].asString();
@@ -138,7 +133,8 @@ bool TcpTransportAdapter::Restore() {
const Json::Value applications_dictionary =
device_dictionary["applications"];
for (Json::Value::const_iterator j = applications_dictionary.begin();
- j != applications_dictionary.end(); ++j) {
+ j != applications_dictionary.end();
+ ++j) {
const Json::Value application_dictionary = *j;
std::string port_record = application_dictionary["port"].asString();
int port = atoi(port_record.c_str());
@@ -155,4 +151,3 @@ bool TcpTransportAdapter::Restore() {
} // namespace transport_adapter
} // namespace transport_manager
-
diff --git a/src/components/transport_manager/src/transport_adapter/threaded_socket_connection.cc b/src/components/transport_manager/src/transport_adapter/threaded_socket_connection.cc
index f520841a47..5e9f3d941d 100644
--- a/src/components/transport_manager/src/transport_adapter/threaded_socket_connection.cc
+++ b/src/components/transport_manager/src/transport_adapter/threaded_socket_connection.cc
@@ -49,19 +49,20 @@ namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
ThreadedSocketConnection::ThreadedSocketConnection(
- const DeviceUID& device_id, const ApplicationHandle& app_handle,
+ const DeviceUID& device_id,
+ const ApplicationHandle& app_handle,
TransportAdapterController* controller)
- : read_fd_(-1),
- write_fd_(-1),
- controller_(controller),
- frames_to_send_(),
- frames_to_send_mutex_(),
- socket_(-1),
- terminate_flag_(false),
- unexpected_disconnect_(false),
- device_uid_(device_id),
- app_handle_(app_handle),
- thread_(NULL) {
+ : read_fd_(-1)
+ , write_fd_(-1)
+ , controller_(controller)
+ , frames_to_send_()
+ , frames_to_send_mutex_()
+ , socket_(-1)
+ , terminate_flag_(false)
+ , unexpected_disconnect_(false)
+ , device_uid_(device_id)
+ , app_handle_(app_handle)
+ , thread_(NULL) {
const std::string thread_name = std::string("Socket ") + device_handle();
thread_ = threads::CreateThread(thread_name.c_str(),
new SocketConnectionDelegate(this));
@@ -100,8 +101,8 @@ TransportAdapter::Error ThreadedSocketConnection::Start() {
LOG4CXX_ERROR(logger_, "pipe creation failed");
return TransportAdapter::FAIL;
}
- const int fcntl_ret = fcntl(read_fd_, F_SETFL,
- fcntl(read_fd_, F_GETFL) | O_NONBLOCK);
+ const int fcntl_ret =
+ fcntl(read_fd_, F_SETFL, fcntl(read_fd_, F_GETFL) | O_NONBLOCK);
if (0 != fcntl_ret) {
LOG4CXX_ERROR(logger_, "fcntl failed");
return TransportAdapter::FAIL;
@@ -119,8 +120,8 @@ void ThreadedSocketConnection::Finalize() {
LOG4CXX_AUTO_TRACE(logger_);
if (unexpected_disconnect_) {
LOG4CXX_DEBUG(logger_, "unexpected_disconnect");
- controller_->ConnectionAborted(device_handle(), application_handle(),
- CommunicationError());
+ controller_->ConnectionAborted(
+ device_handle(), application_handle(), CommunicationError());
} else {
LOG4CXX_DEBUG(logger_, "not unexpected_disconnect");
controller_->ConnectionFinished(device_handle(), application_handle());
@@ -161,7 +162,7 @@ TransportAdapter::Error ThreadedSocketConnection::Disconnect() {
void ThreadedSocketConnection::threadMain() {
LOG4CXX_AUTO_TRACE(logger_);
- controller_->ConnectionCreated(this, device_uid_, app_handle_);
+ controller_->ConnectionCreated(this, device_handle(), application_handle());
ConnectError* connect_error = NULL;
if (!Establish(&connect_error)) {
LOG4CXX_ERROR(logger_, "Connection Establish failed");
@@ -179,8 +180,8 @@ void ThreadedSocketConnection::threadMain() {
LOG4CXX_INFO(logger_, "removing message");
::protocol_handler::RawMessagePtr message = frames_to_send_.front();
frames_to_send_.pop();
- controller_->DataSendFailed(device_handle(), application_handle(),
- message, DataSendError());
+ controller_->DataSendFailed(
+ device_handle(), application_handle(), message, DataSendError());
}
}
@@ -199,8 +200,8 @@ void ThreadedSocketConnection::Transmit() {
const bool is_queue_empty_on_poll = IsFramesToSendQueueEmpty();
- poll_fds[0].events = POLLIN | POLLPRI
- | (is_queue_empty_on_poll ? 0 : POLLOUT);
+ poll_fds[0].events =
+ POLLIN | POLLPRI | (is_queue_empty_on_poll ? 0 : POLLOUT);
poll_fds[1].fd = read_fd_;
poll_fds[1].events = POLLIN | POLLPRI;
@@ -210,10 +211,10 @@ void ThreadedSocketConnection::Transmit() {
Abort();
return;
}
- LOG4CXX_DEBUG(
- logger_,
- "poll is ok " << this << " revents0: " << std::hex << poll_fds[0].revents <<
- " revents1:" << std::hex << poll_fds[1].revents);
+ LOG4CXX_DEBUG(logger_,
+ "poll is ok " << this << " revents0: " << std::hex
+ << poll_fds[0].revents << " revents1:" << std::hex
+ << poll_fds[1].revents);
// error check
if (0 != (poll_fds[1].revents & (POLLERR | POLLHUP | POLLNVAL))) {
LOG4CXX_ERROR(logger_,
@@ -276,13 +277,13 @@ bool ThreadedSocketConnection::Receive() {
bytes_read = recv(socket_, buffer, sizeof(buffer), MSG_DONTWAIT);
if (bytes_read > 0) {
- LOG4CXX_DEBUG(
- logger_,
- "Received " << bytes_read << " bytes for connection " << this);
+ LOG4CXX_DEBUG(logger_,
+ "Received " << bytes_read << " bytes for connection "
+ << this);
::protocol_handler::RawMessagePtr frame(
new protocol_handler::RawMessage(0, 0, buffer, bytes_read));
- controller_->DataReceiveDone(device_handle(), application_handle(),
- frame);
+ controller_->DataReceiveDone(
+ device_handle(), application_handle(), frame);
} else if (bytes_read < 0) {
if (EAGAIN != errno && EWOULDBLOCK != errno) {
LOG4CXX_ERROR_WITH_ERRNO(logger_,
@@ -311,8 +312,8 @@ bool ThreadedSocketConnection::Send() {
while (!frames_to_send_local.empty()) {
LOG4CXX_INFO(logger_, "frames_to_send is not empty");
::protocol_handler::RawMessagePtr frame = frames_to_send_local.front();
- const ssize_t bytes_sent = ::send(socket_, frame->data() + offset,
- frame->data_size() - offset, 0);
+ const ssize_t bytes_sent =
+ ::send(socket_, frame->data() + offset, frame->data_size() - offset, 0);
if (bytes_sent >= 0) {
LOG4CXX_DEBUG(logger_, "bytes_sent >= 0");
@@ -327,8 +328,8 @@ bool ThreadedSocketConnection::Send() {
LOG4CXX_ERROR_WITH_ERRNO(logger_, "Send failed for connection " << this);
frames_to_send_local.pop();
offset = 0;
- controller_->DataSendFailed(device_handle(), application_handle(), frame,
- DataSendError());
+ controller_->DataSendFailed(
+ device_handle(), application_handle(), frame, DataSendError());
}
}
@@ -337,8 +338,7 @@ bool ThreadedSocketConnection::Send() {
ThreadedSocketConnection::SocketConnectionDelegate::SocketConnectionDelegate(
ThreadedSocketConnection* connection)
- : connection_(connection) {
-}
+ : connection_(connection) {}
void ThreadedSocketConnection::SocketConnectionDelegate::threadMain() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/transport_manager/src/transport_adapter/transport_adapter_impl.cc b/src/components/transport_manager/src/transport_adapter/transport_adapter_impl.cc
index 170cb7b734..5638eecdee 100644
--- a/src/components/transport_manager/src/transport_adapter/transport_adapter_impl.cc
+++ b/src/components/transport_manager/src/transport_adapter/transport_adapter_impl.cc
@@ -32,6 +32,7 @@
#include "config_profile/profile.h"
#include "utils/logger.h"
+#include "utils/helpers.h"
#include "transport_manager/transport_adapter/transport_adapter_impl.h"
#include "transport_manager/transport_adapter/transport_adapter_listener.h"
@@ -45,31 +46,36 @@ namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
namespace {
DeviceTypes devicesType = {
- std::make_pair(AOA, std::string("USB")),
- std::make_pair(PASA_AOA, std::string("USB")),
- std::make_pair(MME, std::string("USB")),
- std::make_pair(BLUETOOTH, std::string("BLUETOOTH")),
- std::make_pair(PASA_BLUETOOTH, std::string("BLUETOOTH")),
- std::make_pair(TCP, std::string("WIFI"))
-};
+ std::make_pair(AOA, std::string("USB_AOA")),
+ std::make_pair(PASA_AOA, std::string("USB_AOA")),
+ std::make_pair(MME, std::string("USB_IOS")),
+ std::make_pair(BLUETOOTH, std::string("BLUETOOTH")),
+ std::make_pair(PASA_BLUETOOTH, std::string("BLUETOOTH")),
+ std::make_pair(TCP, std::string("WIFI"))};
}
TransportAdapterImpl::TransportAdapterImpl(
- DeviceScanner* device_scanner,
- ServerConnectionFactory* server_connection_factory,
- ClientConnectionListener* client_connection_listener)
- : listeners_(),
- initialised_(0),
- devices_(),
- devices_mutex_(),
- connections_(),
- connections_lock_(),
-#ifdef TIME_TESTER
- metric_observer_(NULL),
-#endif // TIME_TESTER
- device_scanner_(device_scanner),
- server_connection_factory_(server_connection_factory),
- client_connection_listener_(client_connection_listener) {
+ DeviceScanner* device_scanner,
+ ServerConnectionFactory* server_connection_factory,
+ ClientConnectionListener* client_connection_listener,
+ resumption::LastState& last_state,
+ const TransportManagerSettings& settings)
+ : listeners_()
+ , initialised_(0)
+ , devices_()
+ , devices_mutex_()
+ , connections_()
+ , connections_lock_()
+ ,
+#ifdef TELEMETRY_MONITOR
+ metric_observer_(NULL)
+ ,
+#endif // TELEMETRY_MONITOR
+ device_scanner_(device_scanner)
+ , server_connection_factory_(server_connection_factory)
+ , client_connection_listener_(client_connection_listener)
+ , last_state_(last_state)
+ , settings_(settings) {
}
TransportAdapterImpl::~TransportAdapterImpl() {
@@ -81,12 +87,16 @@ TransportAdapterImpl::~TransportAdapterImpl() {
LOG4CXX_DEBUG(logger_, "device_scanner_ deleted.");
}
if (server_connection_factory_) {
- LOG4CXX_DEBUG(logger_, "Deleting server_connection_factory " << server_connection_factory_);
+ LOG4CXX_DEBUG(logger_,
+ "Deleting server_connection_factory "
+ << server_connection_factory_);
delete server_connection_factory_;
LOG4CXX_DEBUG(logger_, "server_connection_factory deleted.");
}
if (client_connection_listener_) {
- LOG4CXX_DEBUG(logger_, "Deleting client_connection_listener_ " << client_connection_listener_);
+ LOG4CXX_DEBUG(logger_,
+ "Deleting client_connection_listener_ "
+ << client_connection_listener_);
delete client_connection_listener_;
LOG4CXX_DEBUG(logger_, "client_connection_listener_ deleted.");
}
@@ -95,15 +105,20 @@ TransportAdapterImpl::~TransportAdapterImpl() {
void TransportAdapterImpl::Terminate() {
if (device_scanner_) {
device_scanner_->Terminate();
- LOG4CXX_DEBUG(logger_, "device_scanner_ " << device_scanner_ << " terminated.");
+ LOG4CXX_DEBUG(logger_,
+ "device_scanner_ " << device_scanner_ << " terminated.");
}
if (server_connection_factory_) {
server_connection_factory_->Terminate();
- LOG4CXX_DEBUG(logger_, "server_connection_factory " << server_connection_factory_ << " terminated.");
+ LOG4CXX_DEBUG(logger_,
+ "server_connection_factory " << server_connection_factory_
+ << " terminated.");
}
if (client_connection_listener_) {
client_connection_listener_->Terminate();
- LOG4CXX_DEBUG(logger_, "client_connection_listener_ " << client_connection_listener_ << " terminated.");
+ LOG4CXX_DEBUG(logger_,
+ "client_connection_listener_ " << client_connection_listener_
+ << " terminated.");
}
ConnectionMap connections;
@@ -114,8 +129,8 @@ void TransportAdapterImpl::Terminate() {
LOG4CXX_DEBUG(logger_, "Connections deleted");
- devices_mutex_.Acquire();
DeviceMap devices;
+ devices_mutex_.Acquire();
std::swap(devices, devices_);
devices_mutex_.Release();
devices.clear();
@@ -140,7 +155,7 @@ TransportAdapter::Error TransportAdapterImpl::Init() {
initialised_ = (error == OK);
- if (profile::Profile::instance()->use_last_state()) {
+ if (get_settings().use_last_state()) {
if (!Restore()) {
LOG4CXX_WARN(logger_, "could not restore transport adapter state");
error = FAIL;
@@ -165,9 +180,10 @@ TransportAdapter::Error TransportAdapterImpl::SearchDevices() {
}
TransportAdapter::Error TransportAdapterImpl::Connect(
- const DeviceUID& device_id, const ApplicationHandle& app_handle) {
- LOG4CXX_TRACE(logger_, "enter. DeviceUID " << device_id << " ApplicationHandle " <<
- app_handle);
+ const DeviceUID& device_id, const ApplicationHandle& app_handle) {
+ LOG4CXX_TRACE(logger_,
+ "enter. DeviceUID " << device_id << " ApplicationHandle "
+ << app_handle);
if (server_connection_factory_ == 0) {
LOG4CXX_TRACE(logger_, "exit with NOT_SUPPORTED");
return NOT_SUPPORTED;
@@ -179,8 +195,8 @@ TransportAdapter::Error TransportAdapterImpl::Connect(
connections_lock_.AcquireForWriting();
const bool already_exists =
- connections_.end() !=
- connections_.find(std::make_pair(device_id, app_handle));
+ connections_.end() !=
+ connections_.find(std::make_pair(device_id, app_handle));
if (!already_exists) {
ConnectionInfo& info = connections_[std::make_pair(device_id, app_handle)];
info.app_handle = app_handle;
@@ -194,7 +210,7 @@ TransportAdapter::Error TransportAdapterImpl::Connect(
}
const TransportAdapter::Error err =
- server_connection_factory_->CreateConnection(device_id, app_handle);
+ server_connection_factory_->CreateConnection(device_id, app_handle);
if (TransportAdapter::OK != err) {
connections_lock_.AcquireForWriting();
connections_.erase(std::make_pair(device_id, app_handle));
@@ -205,7 +221,7 @@ TransportAdapter::Error TransportAdapterImpl::Connect(
}
TransportAdapter::Error TransportAdapterImpl::ConnectDevice(
- const DeviceUID& device_handle) {
+ const DeviceUID& device_handle) {
LOG4CXX_TRACE(logger_, "enter with device_handle: " << &device_handle);
DeviceSptr device = FindDevice(device_handle);
if (device) {
@@ -219,9 +235,10 @@ TransportAdapter::Error TransportAdapterImpl::ConnectDevice(
}
TransportAdapter::Error TransportAdapterImpl::Disconnect(
- const DeviceUID& device_id, const ApplicationHandle& app_handle) {
- LOG4CXX_TRACE(logger_, "enter. device_id: " << &device_id << ", device_id: " <<
- &device_id);
+ const DeviceUID& device_id, const ApplicationHandle& app_handle) {
+ LOG4CXX_TRACE(logger_,
+ "enter. device_id: " << &device_id
+ << ", device_id: " << &device_id);
if (!initialised_) {
LOG4CXX_TRACE(logger_, "exit with BAD_STATE");
return BAD_STATE;
@@ -238,7 +255,7 @@ TransportAdapter::Error TransportAdapterImpl::Disconnect(
}
TransportAdapter::Error TransportAdapterImpl::DisconnectDevice(
- const DeviceUID& device_id) {
+ const DeviceUID& device_id) {
LOG4CXX_TRACE(logger_, "enter. device_id: " << &device_id);
if (!initialised_) {
LOG4CXX_TRACE(logger_, "exit with BAD_STATE");
@@ -249,15 +266,20 @@ TransportAdapter::Error TransportAdapterImpl::DisconnectDevice(
std::vector<ConnectionInfo> to_disconnect;
connections_lock_.AcquireForReading();
- for (ConnectionMap::const_iterator i = connections_.begin(); i != connections_.end(); ++i) {
+ for (ConnectionMap::const_iterator i = connections_.begin();
+ i != connections_.end();
+ ++i) {
ConnectionInfo info = i->second;
- if (info.device_id == device_id && info.state != ConnectionInfo::FINALISING) {
+ if (info.device_id == device_id &&
+ info.state != ConnectionInfo::FINALISING) {
to_disconnect.push_back(info);
}
}
connections_lock_.Release();
- for (std::vector<ConnectionInfo>::const_iterator j = to_disconnect.begin(); j != to_disconnect.end(); ++j) {
+ for (std::vector<ConnectionInfo>::const_iterator j = to_disconnect.begin();
+ j != to_disconnect.end();
+ ++j) {
ConnectionInfo info = *j;
if (OK != info.connection->Disconnect()) {
error = FAIL;
@@ -269,10 +291,12 @@ TransportAdapter::Error TransportAdapterImpl::DisconnectDevice(
}
TransportAdapter::Error TransportAdapterImpl::SendData(
- const DeviceUID& device_id, const ApplicationHandle& app_handle,
- const ::protocol_handler::RawMessagePtr data) {
- LOG4CXX_TRACE(logger_, "enter. device_id: " << &device_id << ", app_handle: " <<
- &app_handle << ", data: " << data);
+ const DeviceUID& device_id,
+ const ApplicationHandle& app_handle,
+ const ::protocol_handler::RawMessagePtr data) {
+ LOG4CXX_TRACE(logger_,
+ "enter. device_id: " << &device_id << ", app_handle: "
+ << &app_handle << ", data: " << data);
if (!initialised_) {
LOG4CXX_TRACE(logger_, "exit with BAD_STATE");
return BAD_STATE;
@@ -315,9 +339,8 @@ TransportAdapter::Error TransportAdapterImpl::StopClientListening() {
return BAD_STATE;
}
TransportAdapter::Error err = client_connection_listener_->StopListening();
- for(DeviceMap::iterator it = devices_.begin();
- it != devices_.end();
- ++it) {
+ sync_primitives::AutoLock locker(devices_mutex_);
+ for (DeviceMap::iterator it = devices_.begin(); it != devices_.end(); ++it) {
it->second->Stop();
}
LOG4CXX_TRACE(logger_, "exit with error: " << err);
@@ -332,7 +355,8 @@ DeviceList TransportAdapterImpl::GetDeviceList() const {
++it) {
devices.push_back(it->first);
}
- LOG4CXX_TRACE(logger_, "exit with DeviceList. It's' size = " << devices.size());
+ LOG4CXX_TRACE(logger_,
+ "exit with DeviceList. It's' size = " << devices.size());
return devices;
}
@@ -359,7 +383,8 @@ DeviceSptr TransportAdapterImpl::AddDevice(DeviceSptr device) {
return existing_device;
} else {
for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
+ it != listeners_.end();
+ ++it) {
(*it)->OnDeviceListUpdated(this);
}
if (ToBeAutoConnected(device)) {
@@ -392,9 +417,9 @@ void TransportAdapterImpl::SearchDeviceDone(const DeviceVector& devices) {
devices_mutex_.Release();
if (!device_found) {
- LOG4CXX_INFO(logger_, "Adding new device " << device->unique_device_id()
- << " (\"" << device->name()
- << "\")");
+ LOG4CXX_INFO(logger_,
+ "Adding new device " << device->unique_device_id() << " (\""
+ << device->name() << "\")");
}
device->set_keep_on_disconnect(true);
@@ -404,7 +429,8 @@ void TransportAdapterImpl::SearchDeviceDone(const DeviceVector& devices) {
connections_lock_.AcquireForReading();
std::set<DeviceUID> connected_devices;
for (ConnectionMap::const_iterator it = connections_.begin();
- it != connections_.end(); ++it) {
+ it != connections_.end();
+ ++it) {
const ConnectionInfo& info = it->second;
if (info.state != ConnectionInfo::FINALISING) {
connected_devices.insert(info.device_id);
@@ -428,12 +454,14 @@ void TransportAdapterImpl::SearchDeviceDone(const DeviceVector& devices) {
devices_mutex_.Release();
for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
+ it != listeners_.end();
+ ++it) {
(*it)->OnDeviceListUpdated(this);
(*it)->OnSearchDeviceDone(this);
}
- for (DeviceMap::iterator it = new_devices.begin(); it != new_devices.end(); ++it) {
+ for (DeviceMap::iterator it = new_devices.begin(); it != new_devices.end();
+ ++it) {
DeviceSptr device = it->second;
if (ToBeAutoConnected(device)) {
ConnectDevice(device);
@@ -442,14 +470,16 @@ void TransportAdapterImpl::SearchDeviceDone(const DeviceVector& devices) {
LOG4CXX_TRACE(logger_, "exit");
}
-void TransportAdapterImpl::ApplicationListUpdated(const DeviceUID& device_handle) {
+void TransportAdapterImpl::ApplicationListUpdated(
+ const DeviceUID& device_handle) {
// default implementation does nothing
// and is reimplemented in MME transport adapter only
}
void TransportAdapterImpl::FindNewApplicationsRequest() {
LOG4CXX_TRACE(logger_, "enter");
- for (TransportAdapterListenerList::iterator i = listeners_.begin(); i != listeners_.end();
+ for (TransportAdapterListenerList::iterator i = listeners_.begin();
+ i != listeners_.end();
++i) {
TransportAdapterListener* listener = *i;
listener->OnFindNewApplicationsRequest(this);
@@ -460,7 +490,8 @@ void TransportAdapterImpl::FindNewApplicationsRequest() {
void TransportAdapterImpl::SearchDeviceFailed(const SearchDeviceError& error) {
LOG4CXX_TRACE(logger_, "enter");
for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
+ it != listeners_.end();
+ ++it) {
(*it)->OnSearchDeviceFailed(this, error);
}
LOG4CXX_TRACE(logger_, "exit");
@@ -479,15 +510,18 @@ bool TransportAdapterImpl::IsServerOriginatedConnectSupported() const {
}
bool TransportAdapterImpl::IsClientOriginatedConnectSupported() const {
- LOG4CXX_TRACE(logger_, "IsClientOriginatedConnectSupported");
+ LOG4CXX_AUTO_TRACE(logger_);
return client_connection_listener_ != 0;
}
void TransportAdapterImpl::ConnectionCreated(
- ConnectionSPtr connection, const DeviceUID& device_id,
- const ApplicationHandle& app_handle) {
- LOG4CXX_TRACE(logger_, "enter connection:" << connection << ", device_id: " << &device_id
- << ", app_handle: " << &app_handle);
+ ConnectionSPtr connection,
+ const DeviceUID& device_id,
+ const ApplicationHandle& app_handle) {
+ LOG4CXX_TRACE(logger_,
+ "enter connection:" << connection
+ << ", device_id: " << &device_id
+ << ", app_handle: " << &app_handle);
connections_lock_.AcquireForReading();
ConnectionInfo& info = connections_[std::make_pair(device_id, app_handle)];
info.app_handle = app_handle;
@@ -500,26 +534,34 @@ void TransportAdapterImpl::ConnectionCreated(
void TransportAdapterImpl::DeviceDisconnected(
const DeviceUID& device_handle, const DisconnectDeviceError& error) {
const DeviceUID device_uid = device_handle;
- LOG4CXX_TRACE(logger_, "enter. device_handle: " << &device_uid << ", error: " <<
- &error);
+ LOG4CXX_TRACE(logger_,
+ "enter. device_handle: " << &device_uid
+ << ", error: " << &error);
ApplicationList app_list = GetApplicationList(device_uid);
- for (ApplicationList::const_iterator i = app_list.begin(); i != app_list.end(); ++i) {
+ for (ApplicationList::const_iterator i = app_list.begin();
+ i != app_list.end();
+ ++i) {
ApplicationHandle app_handle = *i;
for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
+ it != listeners_.end();
+ ++it) {
TransportAdapterListener* listener = *it;
- listener->OnUnexpectedDisconnect(this, device_uid, app_handle, CommunicationError());
+ listener->OnUnexpectedDisconnect(
+ this, device_uid, app_handle, CommunicationError());
}
}
for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
+ it != listeners_.end();
+ ++it) {
TransportAdapterListener* listener = *it;
listener->OnDisconnectDeviceDone(this, device_uid);
}
connections_lock_.AcquireForWriting();
- for (ApplicationList::const_iterator i = app_list.begin(); i != app_list.end(); ++i) {
+ for (ApplicationList::const_iterator i = app_list.begin();
+ i != app_list.end();
+ ++i) {
ApplicationHandle app_handle = *i;
connections_.erase(std::make_pair(device_uid, app_handle));
}
@@ -529,16 +571,18 @@ void TransportAdapterImpl::DeviceDisconnected(
LOG4CXX_TRACE(logger_, "exit");
}
-bool TransportAdapterImpl::IsSingleApplication(const DeviceUID& device_uid,
- const ApplicationHandle& app_uid) {
+bool TransportAdapterImpl::IsSingleApplication(
+ const DeviceUID& device_uid, const ApplicationHandle& app_uid) {
sync_primitives::AutoReadLock locker(connections_lock_);
for (ConnectionMap::const_iterator it = connections_.begin();
- it != connections_.end(); ++it) {
+ it != connections_.end();
+ ++it) {
const DeviceUID& current_device_id = it->first.first;
const ApplicationHandle& current_app_handle = it->first.second;
if (current_device_id == device_uid && current_app_handle != app_uid) {
LOG4CXX_DEBUG(logger_,
- "break. Condition: current_device_id == device_id && current_app_handle != app_handle");
+ "break. Condition: current_device_id == device_id && "
+ "current_app_handle != app_handle");
return false;
}
@@ -546,23 +590,25 @@ bool TransportAdapterImpl::IsSingleApplication(const DeviceUID& device_uid,
return true;
}
-void TransportAdapterImpl::DisconnectDone(
- const DeviceUID& device_handle, const ApplicationHandle& app_handle) {
+void TransportAdapterImpl::DisconnectDone(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle) {
const DeviceUID device_uid = device_handle;
const ApplicationHandle app_uid = app_handle;
- LOG4CXX_TRACE(logger_, "enter. device_id: " << &device_uid << ", app_handle: " <<
- &app_uid);
+ LOG4CXX_TRACE(logger_,
+ "enter. device_id: " << &device_uid
+ << ", app_handle: " << &app_uid);
DeviceSptr device = FindDevice(device_handle);
if (!device) {
LOG4CXX_WARN(logger_, "Device: uid " << &device_uid << " not found");
return;
}
- bool device_disconnected = ToBeAutoDisconnected(device) &&
- IsSingleApplication(device_uid, app_uid);
+ bool device_disconnected =
+ ToBeAutoDisconnected(device) && IsSingleApplication(device_uid, app_uid);
for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
+ it != listeners_.end();
+ ++it) {
TransportAdapterListener* listener = *it;
listener->OnDisconnectDone(this, device_uid, app_uid);
if (device_disconnected) {
@@ -581,53 +627,64 @@ void TransportAdapterImpl::DisconnectDone(
LOG4CXX_TRACE(logger_, "exit");
}
-void TransportAdapterImpl::DataReceiveDone(const DeviceUID& device_id,
+void TransportAdapterImpl::DataReceiveDone(
+ const DeviceUID& device_id,
const ApplicationHandle& app_handle,
::protocol_handler::RawMessagePtr message) {
- LOG4CXX_TRACE(logger_, "enter. device_id: " << &device_id << ", app_handle: " <<
- &app_handle << ", message: " << message);
+ LOG4CXX_TRACE(logger_,
+ "enter. device_id: " << &device_id
+ << ", app_handle: " << &app_handle
+ << ", message: " << message);
-#ifdef TIME_TESTER
+#ifdef TELEMETRY_MONITOR
if (metric_observer_) {
metric_observer_->StartRawMsg(message.get());
}
-#endif // TIME_TESTER
+#endif // TELEMETRY_MONITOR
+
for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
+ it != listeners_.end();
+ ++it) {
(*it)->OnDataReceiveDone(this, device_id, app_handle, message);
}
LOG4CXX_TRACE(logger_, "exit");
}
void TransportAdapterImpl::DataReceiveFailed(
- const DeviceUID& device_id, const ApplicationHandle& app_handle,
- const DataReceiveError& error) {
+ const DeviceUID& device_id,
+ const ApplicationHandle& app_handle,
+ const DataReceiveError& error) {
LOG4CXX_TRACE(logger_, "enter");
for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
+ it != listeners_.end();
+ ++it) {
(*it)->OnDataReceiveFailed(this, device_id, app_handle, error);
}
LOG4CXX_TRACE(logger_, "exit");
}
-void TransportAdapterImpl::DataSendDone(const DeviceUID& device_id,
- const ApplicationHandle& app_handle,
- ::protocol_handler::RawMessagePtr message) {
+void TransportAdapterImpl::DataSendDone(
+ const DeviceUID& device_id,
+ const ApplicationHandle& app_handle,
+ ::protocol_handler::RawMessagePtr message) {
LOG4CXX_TRACE(logger_, "enter");
for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
+ it != listeners_.end();
+ ++it) {
(*it)->OnDataSendDone(this, device_id, app_handle, message);
}
LOG4CXX_TRACE(logger_, "exit");
}
-void TransportAdapterImpl::DataSendFailed(const DeviceUID& device_id,
+void TransportAdapterImpl::DataSendFailed(
+ const DeviceUID& device_id,
const ApplicationHandle& app_handle,
::protocol_handler::RawMessagePtr message,
const DataSendError& error) {
LOG4CXX_TRACE(logger_, "enter");
for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
+ it != listeners_.end();
+ ++it) {
(*it)->OnDataSendFailed(this, device_id, app_handle, message, error);
}
LOG4CXX_TRACE(logger_, "exit");
@@ -636,8 +693,8 @@ void TransportAdapterImpl::DataSendFailed(const DeviceUID& device_id,
DeviceSptr TransportAdapterImpl::FindDevice(const DeviceUID& device_id) const {
LOG4CXX_TRACE(logger_, "enter. device_id: " << &device_id);
DeviceSptr ret;
- LOG4CXX_DEBUG(logger_, "devices_.size() = " << devices_.size());
sync_primitives::AutoLock locker(devices_mutex_);
+ LOG4CXX_DEBUG(logger_, "devices_.size() = " << devices_.size());
DeviceMap::const_iterator it = devices_.find(device_id);
if (it != devices_.end()) {
ret = it->second;
@@ -650,11 +707,12 @@ DeviceSptr TransportAdapterImpl::FindDevice(const DeviceUID& device_id) const {
void TransportAdapterImpl::ConnectDone(const DeviceUID& device_id,
const ApplicationHandle& app_handle) {
- LOG4CXX_TRACE(logger_, "enter. device_id: " << &device_id << ", app_handle: " <<
- &app_handle);
+ LOG4CXX_TRACE(logger_,
+ "enter. device_id: " << &device_id
+ << ", app_handle: " << &app_handle);
connections_lock_.AcquireForReading();
ConnectionMap::iterator it_conn =
- connections_.find(std::make_pair(device_id, app_handle));
+ connections_.find(std::make_pair(device_id, app_handle));
if (it_conn != connections_.end()) {
ConnectionInfo& info = it_conn->second;
info.state = ConnectionInfo::ESTABLISHED;
@@ -662,7 +720,8 @@ void TransportAdapterImpl::ConnectDone(const DeviceUID& device_id,
connections_lock_.Release();
for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
+ it != listeners_.end();
+ ++it) {
(*it)->OnConnectDone(this, device_id, app_handle);
}
@@ -671,21 +730,48 @@ void TransportAdapterImpl::ConnectDone(const DeviceUID& device_id,
}
void TransportAdapterImpl::ConnectFailed(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle, const ConnectError& error) {
+ const ApplicationHandle& app_handle,
+ const ConnectError& error) {
const DeviceUID device_uid = device_handle;
const ApplicationHandle app_uid = app_handle;
- LOG4CXX_TRACE(logger_, "enter. device_id: " << &device_uid << ", app_handle: " <<
- &app_uid << ", error: " << &error);
+ LOG4CXX_TRACE(logger_,
+ "enter. device_id: " << &device_uid << ", app_handle: "
+ << &app_uid << ", error: " << &error);
connections_lock_.AcquireForWriting();
connections_.erase(std::make_pair(device_uid, app_uid));
connections_lock_.Release();
for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
+ it != listeners_.end();
+ ++it) {
(*it)->OnConnectFailed(this, device_uid, app_uid, error);
}
LOG4CXX_TRACE(logger_, "exit");
}
+void TransportAdapterImpl::RemoveFinalizedConnection(
+ const DeviceUID& device_handle, const ApplicationHandle& app_handle) {
+ const DeviceUID device_uid = device_handle;
+ const ApplicationHandle app_uid = app_handle;
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoWriteLock lock(connections_lock_);
+ ConnectionMap::iterator it_conn =
+ connections_.find(std::make_pair(device_uid, app_handle));
+ if (it_conn == connections_.end()) {
+ LOG4CXX_WARN(logger_,
+ "Device_id: " << &device_uid << ", app_handle: " << &app_uid
+ << " connection not found");
+ return;
+ }
+ const ConnectionInfo& info = it_conn->second;
+ if (info.state != ConnectionInfo::FINALISING) {
+ LOG4CXX_WARN(logger_,
+ "Device_id: " << &device_uid << ", app_handle: " << &app_uid
+ << " connection not finalized");
+ return;
+ }
+ connections_.erase(it_conn);
+}
+
void TransportAdapterImpl::AddListener(TransportAdapterListener* listener) {
LOG4CXX_TRACE(logger_, "enter");
listeners_.push_back(listener);
@@ -693,26 +779,30 @@ void TransportAdapterImpl::AddListener(TransportAdapterListener* listener) {
}
ApplicationList TransportAdapterImpl::GetApplicationList(
- const DeviceUID& device_id) const {
+ const DeviceUID& device_id) const {
LOG4CXX_TRACE(logger_, "enter. device_id: " << &device_id);
DeviceSptr device = FindDevice(device_id);
if (device.valid()) {
ApplicationList lst = device->GetApplicationList();
- LOG4CXX_TRACE(logger_, "exit with ApplicationList. It's size = " << lst.size() <<
- " Condition: device.valid()");
+ LOG4CXX_TRACE(logger_,
+ "exit with ApplicationList. It's size = "
+ << lst.size() << " Condition: device.valid()");
return lst;
}
- LOG4CXX_TRACE(logger_, "exit with empty ApplicationList. Condition: NOT device.valid()");
+ LOG4CXX_TRACE(
+ logger_,
+ "exit with empty ApplicationList. Condition: NOT device.valid()");
return ApplicationList();
}
void TransportAdapterImpl::ConnectionFinished(
- const DeviceUID& device_id, const ApplicationHandle& app_handle) {
- LOG4CXX_TRACE(logger_, "enter. device_id: " << &device_id << ", app_handle: " <<
- &app_handle);
+ const DeviceUID& device_id, const ApplicationHandle& app_handle) {
+ LOG4CXX_TRACE(logger_,
+ "enter. device_id: " << &device_id
+ << ", app_handle: " << &app_handle);
connections_lock_.AcquireForReading();
ConnectionMap::iterator it =
- connections_.find(std::make_pair(device_id, app_handle));
+ connections_.find(std::make_pair(device_id, app_handle));
if (it != connections_.end()) {
ConnectionInfo& info = it->second;
info.state = ConnectionInfo::FINALISING;
@@ -721,11 +811,13 @@ void TransportAdapterImpl::ConnectionFinished(
}
void TransportAdapterImpl::ConnectionAborted(
- const DeviceUID& device_id, const ApplicationHandle& app_handle,
- const CommunicationError& error) {
+ const DeviceUID& device_id,
+ const ApplicationHandle& app_handle,
+ const CommunicationError& error) {
ConnectionFinished(device_id, app_handle);
for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
+ it != listeners_.end();
+ ++it) {
(*it)->OnUnexpectedDisconnect(this, device_id, app_handle, error);
}
}
@@ -738,19 +830,22 @@ bool TransportAdapterImpl::IsInitialised() const {
}
if (device_scanner_ && !device_scanner_->IsInitialised()) {
LOG4CXX_TRACE(logger_,
- "exit with FALSE. Condition: device_scanner_ && !device_scanner_->IsInitialised()");
+ "exit with FALSE. Condition: device_scanner_ && "
+ "!device_scanner_->IsInitialised()");
return false;
}
if (server_connection_factory_ &&
!server_connection_factory_->IsInitialised()) {
LOG4CXX_TRACE(logger_,
- "exit with FALSE. Condition: server_connection_factory_ && !server_connection_factory_->IsInitialised()");
+ "exit with FALSE. Condition: server_connection_factory_ && "
+ "!server_connection_factory_->IsInitialised()");
return false;
}
if (client_connection_listener_ &&
!client_connection_listener_->IsInitialised()) {
LOG4CXX_TRACE(logger_,
- "exit with FALSE. Condition: client_connection_listener_ && !client_connection_listener_->IsInitialised()");
+ "exit with FALSE. Condition: client_connection_listener_ && "
+ "!client_connection_listener_->IsInitialised()");
return false;
}
LOG4CXX_TRACE(logger_, "exit with TRUE");
@@ -770,20 +865,19 @@ std::string TransportAdapterImpl::GetConnectionType() const {
return devicesType[GetDeviceType()];
}
-#ifdef TIME_TESTER
-void TransportAdapterImpl::SetTimeMetricObserver(TMMetricObserver* observer) {
+#ifdef TELEMETRY_MONITOR
+void TransportAdapterImpl::SetTelemetryObserver(TMTelemetryObserver* observer) {
metric_observer_ = observer;
}
-#endif // TIME_TESTER
+#endif // TELEMETRY_MONITOR
-#ifdef TIME_TESTER
-TMMetricObserver* TransportAdapterImpl::GetTimeMetricObserver() {
+#ifdef TELEMETRY_MONITOR
+TMTelemetryObserver* TransportAdapterImpl::GetTelemetryObserver() {
return metric_observer_;
}
-#endif // TIME_TESTER
+#endif // TELEMETRY_MONITOR
-void TransportAdapterImpl::Store() const {
-}
+void TransportAdapterImpl::Store() const {}
bool TransportAdapterImpl::Restore() {
return true;
@@ -798,13 +892,14 @@ bool TransportAdapterImpl::ToBeAutoDisconnected(DeviceSptr device) const {
}
ConnectionSPtr TransportAdapterImpl::FindEstablishedConnection(
- const DeviceUID& device_id, const ApplicationHandle& app_handle) const {
- LOG4CXX_TRACE(logger_, "enter. device_id: " << &device_id << ", app_handle: " <<
- &app_handle);
+ const DeviceUID& device_id, const ApplicationHandle& app_handle) const {
+ LOG4CXX_TRACE(logger_,
+ "enter. device_id: " << &device_id
+ << ", app_handle: " << &app_handle);
ConnectionSPtr connection;
connections_lock_.AcquireForReading();
ConnectionMap::const_iterator it =
- connections_.find(std::make_pair(device_id, app_handle));
+ connections_.find(std::make_pair(device_id, app_handle));
if (it != connections_.end()) {
const ConnectionInfo& info = it->second;
if (info.state == ConnectionInfo::ESTABLISHED) {
@@ -820,13 +915,16 @@ TransportAdapter::Error TransportAdapterImpl::ConnectDevice(DeviceSptr device) {
LOG4CXX_TRACE(logger_, "enter. device: " << device);
DeviceUID device_id = device->unique_device_id();
ApplicationList app_list = device->GetApplicationList();
- LOG4CXX_INFO(logger_, "Device " << device->name() << " has "
- << app_list.size() << " applications.");
+ LOG4CXX_INFO(logger_,
+ "Device " << device->name() << " has " << app_list.size()
+ << " applications.");
bool errors_occurred = false;
- for (ApplicationList::iterator it = app_list.begin(); it != app_list.end(); ++it) {
+ for (ApplicationList::iterator it = app_list.begin(); it != app_list.end();
+ ++it) {
const ApplicationHandle app_handle = *it;
- LOG4CXX_DEBUG(logger_, "Attempt to connect device " << device_id <<
- ", channel " << app_handle);
+ LOG4CXX_DEBUG(logger_,
+ "Attempt to connect device " << device_id << ", channel "
+ << app_handle);
const Error error = Connect(device_id, app_handle);
switch (error) {
case OK:
@@ -836,9 +934,10 @@ TransportAdapter::Error TransportAdapterImpl::ConnectDevice(DeviceSptr device) {
LOG4CXX_DEBUG(logger_, "error = ALREADY_EXISTS");
break;
default:
- LOG4CXX_ERROR(logger_, "Connect to device " << device_id <<
- ", channel " << app_handle <<
- " failed with error " << error);
+ LOG4CXX_ERROR(logger_,
+ "Connect to device " << device_id << ", channel "
+ << app_handle
+ << " failed with error " << error);
errors_occurred = true;
LOG4CXX_DEBUG(logger_, "switch (error), default case");
break;
@@ -863,7 +962,8 @@ void TransportAdapterImpl::RemoveDevice(const DeviceUID& device_handle) {
if (!device->keep_on_disconnect()) {
devices_.erase(i);
for (TransportAdapterListenerList::iterator it = listeners_.begin();
- it != listeners_.end(); ++it) {
+ it != listeners_.end();
+ ++it) {
TransportAdapterListener* listener = *it;
listener->OnDeviceListUpdated(this);
}
diff --git a/src/components/transport_manager/src/transport_adapter/transport_adapter_listener_impl.cc b/src/components/transport_manager/src/transport_adapter/transport_adapter_listener_impl.cc
index f73748de52..2ab19ade86 100644
--- a/src/components/transport_manager/src/transport_adapter/transport_adapter_listener_impl.cc
+++ b/src/components/transport_manager/src/transport_adapter/transport_adapter_listener_impl.cc
@@ -42,236 +42,334 @@ namespace transport_manager {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
TransportAdapterListenerImpl::TransportAdapterListenerImpl(
- TransportManagerImpl* manager, TransportAdapter* adapter) :
- transport_manager_impl_(manager), transport_adapter_(adapter) {
-}
+ TransportManager* manager, TransportAdapter* adapter)
+ : transport_manager_(manager), transport_adapter_(adapter) {}
void TransportAdapterListenerImpl::OnSearchDeviceDone(
- const TransportAdapter* adapter) {
+ const TransportAdapter* adapter) {
LOG4CXX_TRACE(logger_, "enter. adapter* " << adapter);
const TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_DONE,
- transport_adapter_, "", 0, ::protocol_handler::RawMessagePtr(), BaseErrorPtr());
- if (transport_manager::E_SUCCESS
- != transport_manager_impl_->ReceiveEventFromDevice(event)) {
+ TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_DONE,
+ transport_adapter_,
+ "",
+ 0,
+ ::protocol_handler::RawMessagePtr(),
+ BaseErrorPtr());
+ if (transport_manager_ != NULL &&
+ transport_manager::E_SUCCESS !=
+ transport_manager_->ReceiveEventFromDevice(event)) {
LOG4CXX_WARN(logger_, "Failed to receive event from device");
}
LOG4CXX_TRACE(logger_, "exit");
}
void TransportAdapterListenerImpl::OnSearchDeviceFailed(
- const TransportAdapter* adapter, const SearchDeviceError& error) {
- LOG4CXX_TRACE(logger_, "enter. adapter: " << adapter << ", error: " << &error);
+ const TransportAdapter* adapter, const SearchDeviceError& error) {
+ LOG4CXX_TRACE(logger_,
+ "enter. adapter: " << adapter << ", error: " << &error);
SearchDeviceError* err = new SearchDeviceError(error);
const TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_FAIL,
- transport_adapter_, "", 0, ::protocol_handler::RawMessagePtr(), BaseErrorPtr(err));
- if (transport_manager::E_SUCCESS
- != transport_manager_impl_->ReceiveEventFromDevice(event)) {
+ TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_FAIL,
+ transport_adapter_,
+ "",
+ 0,
+ ::protocol_handler::RawMessagePtr(),
+ BaseErrorPtr(err));
+ if (transport_manager_ != NULL &&
+ transport_manager::E_SUCCESS !=
+ transport_manager_->ReceiveEventFromDevice(event)) {
LOG4CXX_WARN(logger_, "Failed to receive event from device");
}
LOG4CXX_TRACE(logger_, "exit");
}
void TransportAdapterListenerImpl::OnDeviceListUpdated(
- const TransportAdapter* adapter) {
+ const TransportAdapter* adapter) {
LOG4CXX_TRACE(logger_, "enter. adapter* " << adapter);
const TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_DEVICE_LIST_UPDATED,
- transport_adapter_, "", 0, ::protocol_handler::RawMessagePtr(), BaseErrorPtr());
- if (transport_manager::E_SUCCESS
- != transport_manager_impl_->ReceiveEventFromDevice(event)) {
+ TransportAdapterListenerImpl::EventTypeEnum::ON_DEVICE_LIST_UPDATED,
+ transport_adapter_,
+ "",
+ 0,
+ ::protocol_handler::RawMessagePtr(),
+ BaseErrorPtr());
+ if (transport_manager_ != NULL &&
+ transport_manager::E_SUCCESS !=
+ transport_manager_->ReceiveEventFromDevice(event)) {
LOG4CXX_WARN(logger_, "Failed to receive event from device");
}
LOG4CXX_TRACE(logger_, "exit");
}
void TransportAdapterListenerImpl::OnFindNewApplicationsRequest(
- const TransportAdapter* adapter) {
+ const TransportAdapter* adapter) {
LOG4CXX_TRACE(logger_, "enter. adapter* " << adapter);
const TransportAdapterEvent event(
- TransportAdapterListenerImpl::ON_FIND_NEW_APPLICATIONS_REQUEST,
- transport_adapter_, "", 0, ::protocol_handler::RawMessagePtr(), BaseErrorPtr());
- if (transport_manager::E_SUCCESS
- != transport_manager_impl_->ReceiveEventFromDevice(event)) {
+ TransportAdapterListenerImpl::ON_FIND_NEW_APPLICATIONS_REQUEST,
+ transport_adapter_,
+ "",
+ 0,
+ ::protocol_handler::RawMessagePtr(),
+ BaseErrorPtr());
+ if (transport_manager_ != NULL &&
+ transport_manager::E_SUCCESS !=
+ transport_manager_->ReceiveEventFromDevice(event)) {
LOG4CXX_WARN(logger_, "Failed to receive event from device");
}
LOG4CXX_TRACE(logger_, "exit");
}
void TransportAdapterListenerImpl::OnConnectDone(
- const TransportAdapter* adapter, const DeviceUID& device,
- const ApplicationHandle& application_id) {
- LOG4CXX_TRACE(logger_, "enter adapter*: " << adapter << ", device: " << &device <<
- ", application_id: " << &application_id);
+ const TransportAdapter* adapter,
+ const DeviceUID& device,
+ const ApplicationHandle& application_id) {
+ LOG4CXX_TRACE(logger_,
+ "enter adapter*: " << adapter << ", device: " << &device
+ << ", application_id: " << &application_id);
const TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_DONE,
- transport_adapter_, device, application_id, ::protocol_handler::RawMessagePtr(),
- BaseErrorPtr(new BaseError()));
- if (transport_manager::E_SUCCESS
- != transport_manager_impl_->ReceiveEventFromDevice(event)) {
+ TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_DONE,
+ transport_adapter_,
+ device,
+ application_id,
+ ::protocol_handler::RawMessagePtr(),
+ BaseErrorPtr(new BaseError()));
+ if (transport_manager_ != NULL &&
+ transport_manager::E_SUCCESS !=
+ transport_manager_->ReceiveEventFromDevice(event)) {
LOG4CXX_WARN(logger_, "Failed to receive event from device");
}
LOG4CXX_TRACE(logger_, "exit");
}
void TransportAdapterListenerImpl::OnConnectFailed(
- const TransportAdapter* adapter, const DeviceUID& device,
- const ApplicationHandle& app_id, const ConnectError& error) {
- LOG4CXX_TRACE(logger_, "enter. adapter: " << adapter << ", device: " << &device <<
- ", application_id: " << &app_id << ", error: " << &error);
+ const TransportAdapter* adapter,
+ const DeviceUID& device,
+ const ApplicationHandle& app_id,
+ const ConnectError& error) {
+ LOG4CXX_TRACE(logger_,
+ "enter. adapter: " << adapter << ", device: " << &device
+ << ", application_id: " << &app_id
+ << ", error: " << &error);
ConnectError* err = new ConnectError(error);
const TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_FAIL,
- transport_adapter_, device, app_id, ::protocol_handler::RawMessagePtr(), BaseErrorPtr(err));
- if (transport_manager::E_SUCCESS
- != transport_manager_impl_->ReceiveEventFromDevice(event)) {
+ TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_FAIL,
+ transport_adapter_,
+ device,
+ app_id,
+ ::protocol_handler::RawMessagePtr(),
+ BaseErrorPtr(err));
+ if (transport_manager_ != NULL &&
+ transport_manager::E_SUCCESS !=
+ transport_manager_->ReceiveEventFromDevice(event)) {
LOG4CXX_WARN(logger_, "Failed to receive event from device");
}
LOG4CXX_TRACE(logger_, "exit");
}
void TransportAdapterListenerImpl::OnDisconnectDone(
- const TransportAdapter* adapter, const DeviceUID& device,
- const ApplicationHandle& app_id) {
- LOG4CXX_TRACE(logger_, "enter. adapter: " << adapter << ", device: " << &device <<
- ", application_id: " << &app_id);
+ const TransportAdapter* adapter,
+ const DeviceUID& device,
+ const ApplicationHandle& app_id) {
+ LOG4CXX_TRACE(logger_,
+ "enter. adapter: " << adapter << ", device: " << &device
+ << ", application_id: " << &app_id);
const TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_DONE,
- transport_adapter_, device, app_id, ::protocol_handler::RawMessagePtr(),
- BaseErrorPtr(new BaseError()));
- if (transport_manager::E_SUCCESS
- != transport_manager_impl_->ReceiveEventFromDevice(event)) {
+ TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_DONE,
+ transport_adapter_,
+ device,
+ app_id,
+ ::protocol_handler::RawMessagePtr(),
+ BaseErrorPtr(new BaseError()));
+ if (transport_manager_ != NULL &&
+ transport_manager::E_SUCCESS !=
+ transport_manager_->ReceiveEventFromDevice(event)) {
LOG4CXX_WARN(logger_, "Failed to receive event from device");
}
LOG4CXX_TRACE(logger_, "exit");
}
void TransportAdapterListenerImpl::OnDisconnectFailed(
- const TransportAdapter* adapter, const DeviceUID& device,
- const ApplicationHandle& app_id, const DisconnectError& error) {
- LOG4CXX_TRACE(logger_, "enter. adapter: " << adapter << ", device: " << &device <<
- ", application_id: " << &app_id << ", error: " << &error);
+ const TransportAdapter* adapter,
+ const DeviceUID& device,
+ const ApplicationHandle& app_id,
+ const DisconnectError& error) {
+ LOG4CXX_TRACE(logger_,
+ "enter. adapter: " << adapter << ", device: " << &device
+ << ", application_id: " << &app_id
+ << ", error: " << &error);
DisconnectError* err = new DisconnectError(error);
const TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_FAIL,
- transport_adapter_, device, app_id, ::protocol_handler::RawMessagePtr(), BaseErrorPtr(err));
- if (transport_manager::E_SUCCESS
- != transport_manager_impl_->ReceiveEventFromDevice(event)) {
+ TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_FAIL,
+ transport_adapter_,
+ device,
+ app_id,
+ ::protocol_handler::RawMessagePtr(),
+ BaseErrorPtr(err));
+ if (transport_manager_ != NULL &&
+ transport_manager::E_SUCCESS !=
+ transport_manager_->ReceiveEventFromDevice(event)) {
LOG4CXX_WARN(logger_, "Failed to receive event from device");
}
LOG4CXX_TRACE(logger_, "exit");
}
void TransportAdapterListenerImpl::OnDisconnectDeviceDone(
- const TransportAdapter* adapter, const DeviceUID& device) {
-}
+ const TransportAdapter* adapter, const DeviceUID& device) {}
void TransportAdapterListenerImpl::OnDisconnectDeviceFailed(
- const TransportAdapter* adapter, const DeviceUID& device,
- const DisconnectDeviceError& error) {
-}
+ const TransportAdapter* adapter,
+ const DeviceUID& device,
+ const DisconnectDeviceError& error) {}
void TransportAdapterListenerImpl::OnDataReceiveDone(
- const TransportAdapter* adapter, const DeviceUID& device,
- const ApplicationHandle& app_id, const ::protocol_handler::RawMessagePtr data_container) {
- LOG4CXX_TRACE(logger_, "enter. adapter: " << adapter << ", device: " << &device <<
- ", application_id: " << &app_id << ", data_container: " << data_container);
+ const TransportAdapter* adapter,
+ const DeviceUID& device,
+ const ApplicationHandle& app_id,
+ const ::protocol_handler::RawMessagePtr data_container) {
+ LOG4CXX_TRACE(logger_,
+ "enter. adapter: " << adapter << ", device: " << &device
+ << ", application_id: " << &app_id
+ << ", data_container: " << data_container);
const TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_DONE,
- transport_adapter_, device, app_id, data_container,
- BaseErrorPtr(new BaseError()));
- if (transport_manager::E_SUCCESS
- != transport_manager_impl_->ReceiveEventFromDevice(event)) {
+ TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_DONE,
+ transport_adapter_,
+ device,
+ app_id,
+ data_container,
+ BaseErrorPtr(new BaseError()));
+ if (transport_manager_ != NULL &&
+ transport_manager::E_SUCCESS !=
+ transport_manager_->ReceiveEventFromDevice(event)) {
LOG4CXX_WARN(logger_, "Failed to receive event from device");
}
LOG4CXX_TRACE(logger_, "exit");
}
void TransportAdapterListenerImpl::OnDataReceiveFailed(
- const TransportAdapter* adapter, const DeviceUID& device,
- const ApplicationHandle& app_id, const DataReceiveError& error) {
- LOG4CXX_TRACE(logger_, "enter. adapter: " << adapter << ", device: " << &device <<
- ", application_id: " << &app_id << ", error: " << &error);
+ const TransportAdapter* adapter,
+ const DeviceUID& device,
+ const ApplicationHandle& app_id,
+ const DataReceiveError& error) {
+ LOG4CXX_TRACE(logger_,
+ "enter. adapter: " << adapter << ", device: " << &device
+ << ", application_id: " << &app_id
+ << ", error: " << &error);
DataReceiveError* err = new DataReceiveError(error);
const TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_FAIL,
- transport_adapter_, device, app_id, ::protocol_handler::RawMessagePtr(), BaseErrorPtr(err));
- if (transport_manager::E_SUCCESS
- != transport_manager_impl_->ReceiveEventFromDevice(event)) {
+ TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_FAIL,
+ transport_adapter_,
+ device,
+ app_id,
+ ::protocol_handler::RawMessagePtr(),
+ BaseErrorPtr(err));
+ if (transport_manager_ != NULL &&
+ transport_manager::E_SUCCESS !=
+ transport_manager_->ReceiveEventFromDevice(event)) {
LOG4CXX_WARN(logger_, "Failed to receive event from device");
}
LOG4CXX_TRACE(logger_, "exit");
}
void TransportAdapterListenerImpl::OnDataSendDone(
- const TransportAdapter* adapter, const DeviceUID& device,
- const ApplicationHandle& app_id, const ::protocol_handler::RawMessagePtr data_container) {
- LOG4CXX_TRACE(logger_, "enter. adapter: " << adapter << ", device: " << &device <<
- ", application_id: " << &app_id << ", data_container: " << data_container);
+ const TransportAdapter* adapter,
+ const DeviceUID& device,
+ const ApplicationHandle& app_id,
+ const ::protocol_handler::RawMessagePtr data_container) {
+ LOG4CXX_TRACE(logger_,
+ "enter. adapter: " << adapter << ", device: " << &device
+ << ", application_id: " << &app_id
+ << ", data_container: " << data_container);
const TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_DONE,
- transport_adapter_, device, app_id, data_container,
- new BaseError());
- if (transport_manager::E_SUCCESS
- != transport_manager_impl_->ReceiveEventFromDevice(event)) {
+ TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_DONE,
+ transport_adapter_,
+ device,
+ app_id,
+ data_container,
+ new BaseError());
+ if (transport_manager_ != NULL &&
+ transport_manager::E_SUCCESS !=
+ transport_manager_->ReceiveEventFromDevice(event)) {
LOG4CXX_WARN(logger_, "Failed to receive event from device");
}
LOG4CXX_TRACE(logger_, "exit");
}
void TransportAdapterListenerImpl::OnDataSendFailed(
- const TransportAdapter* adapter, const DeviceUID& device,
- const ApplicationHandle& app_id, const ::protocol_handler::RawMessagePtr data_container,
- const DataSendError& error) {
- LOG4CXX_TRACE(logger_, "enter. adapter: " << adapter << ", device: " << &device <<
- ", application_id: " << &app_id << ", data_container: " << data_container << ", error: "
- << &error);
+ const TransportAdapter* adapter,
+ const DeviceUID& device,
+ const ApplicationHandle& app_id,
+ const ::protocol_handler::RawMessagePtr data_container,
+ const DataSendError& error) {
+ LOG4CXX_TRACE(logger_,
+ "enter. adapter: " << adapter << ", device: " << &device
+ << ", application_id: " << &app_id
+ << ", data_container: " << data_container
+ << ", error: " << &error);
DataSendError* err = new DataSendError(error);
const TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_FAIL,
- transport_adapter_, device, app_id, data_container, BaseErrorPtr(err));
- if (transport_manager::E_SUCCESS
- != transport_manager_impl_->ReceiveEventFromDevice(event)) {
+ TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_FAIL,
+ transport_adapter_,
+ device,
+ app_id,
+ data_container,
+ BaseErrorPtr(err));
+ if (transport_manager_ != NULL &&
+ transport_manager::E_SUCCESS !=
+ transport_manager_->ReceiveEventFromDevice(event)) {
LOG4CXX_WARN(logger_, "Failed to receive event from device");
}
LOG4CXX_TRACE(logger_, "exit");
}
void TransportAdapterListenerImpl::OnConnectRequested(
- const TransportAdapter* adapter, const DeviceUID& device_handle,
- const ApplicationHandle& app_handle) {
-}
+ const TransportAdapter* adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle) {}
void TransportAdapterListenerImpl::OnUnexpectedDisconnect(
- const TransportAdapter* adapter, const DeviceUID& device,
- const ApplicationHandle& application, const CommunicationError& error) {
- LOG4CXX_TRACE(logger_, "enter. adapter: " << adapter << ", device: " << &device <<
- ", application: " << &application << ", error: " << &error);
+ const TransportAdapter* adapter,
+ const DeviceUID& device,
+ const ApplicationHandle& application,
+ const CommunicationError& error) {
+ LOG4CXX_TRACE(logger_,
+ "enter. adapter: " << adapter << ", device: " << &device
+ << ", application: " << &application
+ << ", error: " << &error);
CommunicationError* err = new CommunicationError(error);
const TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_UNEXPECTED_DISCONNECT,
- transport_adapter_, device, application, ::protocol_handler::RawMessagePtr(), BaseErrorPtr(err));
- if (transport_manager::E_SUCCESS
- != transport_manager_impl_->ReceiveEventFromDevice(event)) {
+ TransportAdapterListenerImpl::EventTypeEnum::ON_UNEXPECTED_DISCONNECT,
+ transport_adapter_,
+ device,
+ application,
+ ::protocol_handler::RawMessagePtr(),
+ BaseErrorPtr(err));
+ if (transport_manager_ != NULL &&
+ transport_manager::E_SUCCESS !=
+ transport_manager_->ReceiveEventFromDevice(event)) {
LOG4CXX_WARN(logger_, "Failed to receive event from device");
}
LOG4CXX_TRACE(logger_, "exit");
}
void TransportAdapterListenerImpl::OnCommunicationError(
- const TransportAdapter* adapter, const DeviceUID& device,
- const ApplicationHandle& app_id) {
- LOG4CXX_TRACE(logger_, "enter. adapter: " << adapter << ", device: " << &device <<
- ", application_id: " << &app_id);
+ const TransportAdapter* adapter,
+ const DeviceUID& device,
+ const ApplicationHandle& app_id) {
+ LOG4CXX_TRACE(logger_,
+ "enter. adapter: " << adapter << ", device: " << &device
+ << ", application_id: " << &app_id);
const TransportAdapterEvent event(
- TransportAdapterListenerImpl::EventTypeEnum::ON_COMMUNICATION_ERROR,
- transport_adapter_, device, app_id, ::protocol_handler::RawMessagePtr(),
- BaseErrorPtr(new BaseError()));
- if (transport_manager::E_SUCCESS
- != transport_manager_impl_->ReceiveEventFromDevice(event)) {
+ TransportAdapterListenerImpl::EventTypeEnum::ON_COMMUNICATION_ERROR,
+ transport_adapter_,
+ device,
+ app_id,
+ ::protocol_handler::RawMessagePtr(),
+ BaseErrorPtr(new BaseError()));
+ if (transport_manager_ != NULL &&
+ transport_manager::E_SUCCESS !=
+ transport_manager_->ReceiveEventFromDevice(event)) {
LOG4CXX_WARN(logger_, "Failed to receive event from device");
}
LOG4CXX_TRACE(logger_, "exit");
}
-} // namespace transport_manager
+} // namespace transport_manager
diff --git a/src/components/transport_manager/src/transport_manager_default.cc b/src/components/transport_manager/src/transport_manager_default.cc
index 835c2c17ed..31f398233b 100644
--- a/src/components/transport_manager/src/transport_manager_default.cc
+++ b/src/components/transport_manager/src/transport_manager_default.cc
@@ -32,9 +32,6 @@
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
-
-#include "config_profile/profile.h"
-
#include "transport_manager/transport_manager_default.h"
#include "transport_manager/tcp/tcp_transport_adapter.h"
#include "utils/logger.h"
@@ -43,65 +40,67 @@
#include "transport_manager/bluetooth/bluetooth_transport_adapter.h"
#endif
-
#if defined(USB_SUPPORT)
#include "transport_manager/usb/usb_aoa_adapter.h"
#endif // USB_SUPPORT
-
-
namespace transport_manager {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
-int TransportManagerDefault::Init() {
+TransportManagerDefault::TransportManagerDefault(
+ const TransportManagerSettings& settings)
+ : TransportManagerImpl(settings) {}
+
+int TransportManagerDefault::Init(resumption::LastState& last_state) {
LOG4CXX_TRACE(logger_, "enter");
- if (E_SUCCESS != TransportManagerImpl::Init()) {
- LOG4CXX_TRACE(logger_, "exit with E_TM_IS_NOT_INITIALIZED. Condition: E_SUCCESS != TransportManagerImpl::Init()");
+ if (E_SUCCESS != TransportManagerImpl::Init(last_state)) {
+ LOG4CXX_TRACE(logger_,
+ "exit with E_TM_IS_NOT_INITIALIZED. Condition: E_SUCCESS != "
+ "TransportManagerImpl::Init()");
return E_TM_IS_NOT_INITIALIZED;
}
- transport_adapter::TransportAdapterImpl* ta;
-#ifdef BLUETOOTH_SUPPORT
- ta = new transport_adapter::BluetoothTransportAdapter;
-
-#ifdef TIME_TESTER
+#ifdef BLUETOOTH_SUPPORT
+ transport_adapter::TransportAdapterImpl* ta_bluetooth =
+ new transport_adapter::BluetoothTransportAdapter(last_state,
+ get_settings());
+#ifdef TELEMETRY_MONITOR
if (metric_observer_) {
- ta->SetTimeMetricObserver(metric_observer_);
+ ta_bluetooth->SetTelemetryObserver(metric_observer_);
}
-#endif // TIME_TESTER
- AddTransportAdapter(ta);
+#endif // TELEMETRY_MONITOR
+ AddTransportAdapter(ta_bluetooth);
+ ta_bluetooth = NULL;
#endif
-
- uint16_t port = profile::Profile::instance()->transport_manager_tcp_adapter_port();
- ta = new transport_adapter::TcpTransportAdapter(port);
-#ifdef TIME_TESTER
+ const uint16_t port = get_settings().transport_manager_tcp_adapter_port();
+ transport_adapter::TransportAdapterImpl* ta_tcp =
+ new transport_adapter::TcpTransportAdapter(
+ port, last_state, get_settings());
+#ifdef TELEMETRY_MONITOR
if (metric_observer_) {
- ta->SetTimeMetricObserver(metric_observer_);
+ ta_tcp->SetTelemetryObserver(metric_observer_);
}
-#endif // TIME_TESTER
- AddTransportAdapter(ta);
-
+#endif // TELEMETRY_MONITOR
+ AddTransportAdapter(ta_tcp);
+ ta_tcp = NULL;
#if defined(USB_SUPPORT)
- ta = new transport_adapter::UsbAoaAdapter();
-#ifdef TIME_TESTER
+ transport_adapter::TransportAdapterImpl* ta_usb =
+ new transport_adapter::UsbAoaAdapter(last_state, get_settings());
+#ifdef TELEMETRY_MONITOR
if (metric_observer_) {
- ta->SetTimeMetricObserver(metric_observer_);
+ ta_usb->SetTelemetryObserver(metric_observer_);
}
-#endif // TIME_TESTER
- AddTransportAdapter(ta);
+#endif // TELEMETRY_MONITOR
+ AddTransportAdapter(ta_usb);
+ ta_usb = NULL;
#endif // USB_SUPPORT
-
-
LOG4CXX_TRACE(logger_, "exit with E_SUCCESS");
return E_SUCCESS;
}
TransportManagerDefault::~TransportManagerDefault() {}
-TransportManagerDefault::TransportManagerDefault()
- : TransportManagerImpl() {}
-
} // namespace transport_manager
diff --git a/src/components/transport_manager/src/transport_manager_impl.cc b/src/components/transport_manager/src/transport_manager_impl.cc
index 6c3edd7b91..113d280c8d 100644
--- a/src/components/transport_manager/src/transport_manager_impl.cc
+++ b/src/components/transport_manager/src/transport_manager_impl.cc
@@ -40,9 +40,12 @@
#include <limits>
#include <functional>
#include <sstream>
+#include <iostream>
#include "utils/macro.h"
#include "utils/logger.h"
+#include "utils/make_shared.h"
+#include "utils/timer_task_impl.h"
#include "transport_manager/common.h"
#include "transport_manager/transport_manager_listener.h"
#include "transport_manager/transport_manager_listener_empty.h"
@@ -57,25 +60,29 @@ namespace transport_manager {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
TransportManagerImpl::Connection TransportManagerImpl::convert(
- const TransportManagerImpl::ConnectionInternal& p) {
+ const TransportManagerImpl::ConnectionInternal& p) {
LOG4CXX_TRACE(logger_, "enter. ConnectionInternal: " << &p);
TransportManagerImpl::Connection c;
c.application = p.application;
c.device = p.device;
c.id = p.id;
- LOG4CXX_TRACE(logger_, "exit with TransportManagerImpl::Connection. It's ConnectionUID = "
- << c.id);
+ LOG4CXX_TRACE(
+ logger_,
+ "exit with TransportManagerImpl::Connection. It's ConnectionUID = "
+ << c.id);
return c;
}
-TransportManagerImpl::TransportManagerImpl()
- : is_initialized_(false),
-#ifdef TIME_TESTER
- metric_observer_(NULL),
-#endif // TIME_TESTER
- connection_id_counter_(0),
- message_queue_("TM MessageQueue", this),
- event_queue_("TM EventQueue", this) {
+TransportManagerImpl::TransportManagerImpl(
+ const TransportManagerSettings& settings)
+ : is_initialized_(false)
+#ifdef TELEMETRY_MONITOR
+ , metric_observer_(NULL)
+#endif // TELEMETRY_MONITOR
+ , connection_id_counter_(0)
+ , message_queue_("TM MessageQueue", this)
+ , event_queue_("TM EventQueue", this)
+ , settings_(settings) {
LOG4CXX_TRACE(logger_, "TransportManager has created");
}
@@ -85,38 +92,43 @@ TransportManagerImpl::~TransportManagerImpl() {
event_queue_.Shutdown();
for (std::vector<TransportAdapter*>::iterator it =
- transport_adapters_.begin();
- it != transport_adapters_.end(); ++it) {
+ transport_adapters_.begin();
+ it != transport_adapters_.end();
+ ++it) {
delete *it;
}
for (std::map<TransportAdapter*, TransportAdapterListenerImpl*>::iterator it =
- transport_adapter_listeners_.begin();
- it != transport_adapter_listeners_.end(); ++it) {
+ transport_adapter_listeners_.begin();
+ it != transport_adapter_listeners_.end();
+ ++it) {
delete it->second;
}
LOG4CXX_INFO(logger_, "TransportManager object destroyed");
}
-int TransportManagerImpl::ConnectDevice(const DeviceHandle& device_handle) {
+int TransportManagerImpl::ConnectDevice(const DeviceHandle device_handle) {
LOG4CXX_TRACE(logger_, "enter. DeviceHandle: " << &device_handle);
if (!this->is_initialized_) {
LOG4CXX_ERROR(logger_, "TransportManager is not initialized.");
- LOG4CXX_TRACE(logger_,
- "exit with E_TM_IS_NOT_INITIALIZED. Condition: !this->is_initialized_");
+ LOG4CXX_TRACE(
+ logger_,
+ "exit with E_TM_IS_NOT_INITIALIZED. Condition: !this->is_initialized_");
return E_TM_IS_NOT_INITIALIZED;
}
DeviceUID device_id = converter_.HandleToUid(device_handle);
- LOG4CXX_DEBUG(logger_, "Convert handle to id " << device_id);
+ LOG4CXX_DEBUG(logger_, "Convert handle to id:" << device_id);
- transport_adapter::TransportAdapter* ta = device_to_adapter_map_[device_id];
- if (NULL == ta) {
+ sync_primitives::AutoReadLock lock(device_to_adapter_map_lock_);
+ DeviceToAdapterMap::iterator it = device_to_adapter_map_.find(device_id);
+ if (it == device_to_adapter_map_.end()) {
LOG4CXX_ERROR(logger_, "No device adapter found by id " << device_id);
LOG4CXX_TRACE(logger_, "exit with E_INVALID_HANDLE. Condition: NULL == ta");
return E_INVALID_HANDLE;
}
+ transport_adapter::TransportAdapter* ta = it->second;
TransportAdapter::Error ta_error = ta->ConnectDevice(device_id);
int err = (TransportAdapter::OK == ta_error) ? E_SUCCESS : E_INTERNAL_ERROR;
@@ -124,46 +136,54 @@ int TransportManagerImpl::ConnectDevice(const DeviceHandle& device_handle) {
return err;
}
-int TransportManagerImpl::DisconnectDevice(const DeviceHandle& device_handle) {
+int TransportManagerImpl::DisconnectDevice(const DeviceHandle device_handle) {
LOG4CXX_TRACE(logger_, "enter. DeviceHandle: " << &device_handle);
if (!this->is_initialized_) {
LOG4CXX_ERROR(logger_, "TransportManager is not initialized.");
- LOG4CXX_TRACE(logger_,
- "exit with E_TM_IS_NOT_INITIALIZED. Condition: !this->is_initialized_");
+ LOG4CXX_TRACE(
+ logger_,
+ "exit with E_TM_IS_NOT_INITIALIZED. Condition: !this->is_initialized_");
return E_TM_IS_NOT_INITIALIZED;
}
DeviceUID device_id = converter_.HandleToUid(device_handle);
- LOG4CXX_DEBUG(logger_, "Convert handle to id" << device_id);
+ LOG4CXX_DEBUG(logger_, "Convert handle to id:" << device_id);
- transport_adapter::TransportAdapter* ta = device_to_adapter_map_[device_id];
- if (NULL == ta) {
+ sync_primitives::AutoReadLock lock(device_to_adapter_map_lock_);
+ DeviceToAdapterMap::iterator it = device_to_adapter_map_.find(device_id);
+ if (it == device_to_adapter_map_.end()) {
LOG4CXX_WARN(logger_, "No device adapter found by id " << device_id);
LOG4CXX_TRACE(logger_, "exit with E_INVALID_HANDLE. Condition: NULL == ta");
return E_INVALID_HANDLE;
}
+ transport_adapter::TransportAdapter* ta = it->second;
ta->DisconnectDevice(device_id);
LOG4CXX_TRACE(logger_, "exit with E_SUCCESS");
return E_SUCCESS;
}
-int TransportManagerImpl::Disconnect(const ConnectionUID& cid) {
+int TransportManagerImpl::Disconnect(const ConnectionUID cid) {
LOG4CXX_TRACE(logger_, "enter. ConnectionUID: " << &cid);
if (!this->is_initialized_) {
LOG4CXX_ERROR(logger_, "TransportManager is not initialized.");
- LOG4CXX_TRACE(logger_,
- "exit with E_TM_IS_NOT_INITIALIZED. Condition: !this->is_initialized_");
+ LOG4CXX_TRACE(
+ logger_,
+ "exit with E_TM_IS_NOT_INITIALIZED. Condition: !this->is_initialized_");
return E_TM_IS_NOT_INITIALIZED;
}
+ sync_primitives::AutoReadLock lock(connections_lock_);
ConnectionInternal* connection = GetConnection(cid);
if (NULL == connection) {
- LOG4CXX_ERROR(logger_, "TransportManagerImpl::Disconnect: Connection does not exist.");
- LOG4CXX_TRACE(logger_, "exit with E_INVALID_HANDLE. Condition: NULL == connection");
+ LOG4CXX_ERROR(
+ logger_,
+ "TransportManagerImpl::Disconnect: Connection does not exist.");
+ LOG4CXX_TRACE(logger_,
+ "exit with E_INVALID_HANDLE. Condition: NULL == connection");
return E_INVALID_HANDLE;
}
connection->transport_adapter->Disconnect(connection->device,
- connection->application);
+ connection->application);
// TODO(dchmerev@luxoft.com): Return disconnect timeout
/*
int messages_count = 0;
@@ -180,7 +200,7 @@ int TransportManagerImpl::Disconnect(const ConnectionUID& cid) {
connection->shutDown = true;
const uint32_t disconnect_timeout =
- profile::Profile::instance()->transport_manager_disconnect_timeout();
+ get_settings().transport_manager_disconnect_timeout();
if (disconnect_timeout > 0) {
connection->timer->start(disconnect_timeout);
}
@@ -193,24 +213,27 @@ int TransportManagerImpl::Disconnect(const ConnectionUID& cid) {
return E_SUCCESS;
}
-int TransportManagerImpl::DisconnectForce(const ConnectionUID& cid) {
+int TransportManagerImpl::DisconnectForce(const ConnectionUID cid) {
LOG4CXX_TRACE(logger_, "enter ConnectionUID: " << &cid);
if (false == this->is_initialized_) {
LOG4CXX_ERROR(logger_, "TransportManager is not initialized.");
LOG4CXX_TRACE(logger_,
- "exit with E_TM_IS_NOT_INITIALIZED. Condition: false == this->is_initialized_");
+ "exit with E_TM_IS_NOT_INITIALIZED. Condition: false == "
+ "this->is_initialized_");
return E_TM_IS_NOT_INITIALIZED;
}
+ sync_primitives::AutoReadLock lock(connections_lock_);
const ConnectionInternal* connection = GetConnection(cid);
if (NULL == connection) {
LOG4CXX_ERROR(
- logger_,
- "TransportManagerImpl::DisconnectForce: Connection does not exist.");
- LOG4CXX_TRACE(logger_, "exit with E_INVALID_HANDLE. Condition: NULL == connection");
+ logger_,
+ "TransportManagerImpl::DisconnectForce: Connection does not exist.");
+ LOG4CXX_TRACE(logger_,
+ "exit with E_INVALID_HANDLE. Condition: NULL == connection");
return E_INVALID_HANDLE;
}
connection->transport_adapter->Disconnect(connection->device,
- connection->application);
+ connection->application);
LOG4CXX_TRACE(logger_, "exit with E_SUCCESS");
return E_SUCCESS;
}
@@ -224,8 +247,10 @@ int TransportManagerImpl::AddEventListener(TransportManagerListener* listener) {
void TransportManagerImpl::DisconnectAllDevices() {
LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoReadLock lock(device_list_lock_);
for (DeviceInfoList::iterator i = device_list_.begin();
- i != device_list_.end(); ++i) {
+ i != device_list_.end();
+ ++i) {
DeviceInfo& device = i->second;
DisconnectDevice(device.device_handle());
}
@@ -234,7 +259,8 @@ void TransportManagerImpl::DisconnectAllDevices() {
void TransportManagerImpl::TerminateAllAdapters() {
LOG4CXX_AUTO_TRACE(logger_);
for (std::vector<TransportAdapter*>::iterator i = transport_adapters_.begin();
- i != transport_adapters_.end(); ++i) {
+ i != transport_adapters_.end();
+ ++i) {
(*i)->Terminate();
}
}
@@ -242,7 +268,8 @@ void TransportManagerImpl::TerminateAllAdapters() {
int TransportManagerImpl::InitAllAdapters() {
LOG4CXX_AUTO_TRACE(logger_);
for (std::vector<TransportAdapter*>::iterator i = transport_adapters_.begin();
- i != transport_adapters_.end(); ++i) {
+ i != transport_adapters_.end();
+ ++i) {
if ((*i)->Init() != TransportAdapter::OK) {
return E_ADAPTERS_FAIL;
}
@@ -267,48 +294,61 @@ int TransportManagerImpl::Stop() {
return E_SUCCESS;
}
-int TransportManagerImpl::SendMessageToDevice(const ::protocol_handler::RawMessagePtr message) {
+int TransportManagerImpl::SendMessageToDevice(
+ const ::protocol_handler::RawMessagePtr message) {
LOG4CXX_TRACE(logger_, "enter. RawMessageSptr: " << message);
- LOG4CXX_INFO(logger_, "Send message to device called with arguments "
- << message.get());
+ LOG4CXX_INFO(logger_,
+ "Send message to device called with arguments "
+ << message.get());
if (false == this->is_initialized_) {
LOG4CXX_ERROR(logger_, "TM is not initialized.");
LOG4CXX_TRACE(logger_,
- "exit with E_TM_IS_NOT_INITIALIZED. Condition: false == this->is_initialized_");
+ "exit with E_TM_IS_NOT_INITIALIZED. Condition: false == "
+ "this->is_initialized_");
return E_TM_IS_NOT_INITIALIZED;
}
- const ConnectionInternal* connection =
- GetConnection(message->connection_key());
- if (NULL == connection) {
- LOG4CXX_ERROR(logger_, "Connection with id " << message->connection_key()
- << " does not exist.");
- LOG4CXX_TRACE(logger_, "exit with E_INVALID_HANDLE. Condition: NULL == connection");
- return E_INVALID_HANDLE;
- }
+ {
+ sync_primitives::AutoReadLock lock(connections_lock_);
+ const ConnectionInternal* connection =
+ GetConnection(message->connection_key());
+ if (NULL == connection) {
+ LOG4CXX_ERROR(logger_,
+ "Connection with id " << message->connection_key()
+ << " does not exist.");
+ LOG4CXX_TRACE(
+ logger_, "exit with E_INVALID_HANDLE. Condition: NULL == connection");
+ return E_INVALID_HANDLE;
+ }
- if (connection->shutDown) {
- LOG4CXX_ERROR(logger_, "TransportManagerImpl::Disconnect: Connection is to shut down.");
- LOG4CXX_TRACE(logger_,
- "exit with E_CONNECTION_IS_TO_SHUTDOWN. Condition: connection->shutDown");
- return E_CONNECTION_IS_TO_SHUTDOWN;
+ if (connection->shutdown_) {
+ LOG4CXX_ERROR(
+ logger_,
+ "TransportManagerImpl::Disconnect: Connection is to shut down.");
+ LOG4CXX_TRACE(logger_,
+ "exit with E_CONNECTION_IS_TO_SHUTDOWN. Condition: "
+ "connection->shutDown");
+ return E_CONNECTION_IS_TO_SHUTDOWN;
+ }
}
-#ifdef TIME_TESTER
+#ifdef TELEMETRY_MONITOR
if (metric_observer_) {
metric_observer_->StartRawMsg(message.get());
}
-#endif // TIME_TESTER
+#endif // TELEMETRY_MONITOR
this->PostMessage(message);
LOG4CXX_TRACE(logger_, "exit with E_SUCCESS");
return E_SUCCESS;
}
-int TransportManagerImpl::ReceiveEventFromDevice(const TransportAdapterEvent& event) {
+int TransportManagerImpl::ReceiveEventFromDevice(
+ const TransportAdapterEvent& event) {
LOG4CXX_TRACE(logger_, "enter. TransportAdapterEvent: " << &event);
if (!is_initialized_) {
LOG4CXX_ERROR(logger_, "TM is not initialized.");
LOG4CXX_TRACE(logger_,
- "exit with E_TM_IS_NOT_INITIALIZED. Condition: false == this->is_initialized_");
+ "exit with E_TM_IS_NOT_INITIALIZED. Condition: false == "
+ "this->is_initialized_");
return E_TM_IS_NOT_INITIALIZED;
}
this->PostEvent(event);
@@ -316,35 +356,39 @@ int TransportManagerImpl::ReceiveEventFromDevice(const TransportAdapterEvent& ev
return E_SUCCESS;
}
-int TransportManagerImpl::RemoveDevice(const DeviceHandle& device_handle) {
+int TransportManagerImpl::RemoveDevice(const DeviceHandle device_handle) {
LOG4CXX_TRACE(logger_, "enter. DeviceHandle: " << &device_handle);
DeviceUID device_id = converter_.HandleToUid(device_handle);
if (false == this->is_initialized_) {
LOG4CXX_ERROR(logger_, "TM is not initialized.");
LOG4CXX_TRACE(logger_,
- "exit with E_TM_IS_NOT_INITIALIZED. Condition: false == this->is_initialized_");
+ "exit with E_TM_IS_NOT_INITIALIZED. Condition: false == "
+ "this->is_initialized_");
return E_TM_IS_NOT_INITIALIZED;
}
+ sync_primitives::AutoWriteLock lock(device_to_adapter_map_lock_);
device_to_adapter_map_.erase(device_id);
LOG4CXX_TRACE(logger_, "exit with E_SUCCESS");
return E_SUCCESS;
}
int TransportManagerImpl::AddTransportAdapter(
- transport_adapter::TransportAdapter* transport_adapter) {
+ transport_adapter::TransportAdapter* transport_adapter) {
LOG4CXX_TRACE(logger_, "enter. TransportAdapter: " << transport_adapter);
if (transport_adapter_listeners_.find(transport_adapter) !=
transport_adapter_listeners_.end()) {
LOG4CXX_ERROR(logger_, "Adapter already exists.");
LOG4CXX_TRACE(logger_,
- "exit with E_ADAPTER_EXISTS. Condition: transport_adapter_listeners_.find(transport_adapter) != transport_adapter_listeners_.end()");
+ "exit with E_ADAPTER_EXISTS. Condition: "
+ "transport_adapter_listeners_.find(transport_adapter) != "
+ "transport_adapter_listeners_.end()");
return E_ADAPTER_EXISTS;
}
transport_adapter_listeners_[transport_adapter] =
- new TransportAdapterListenerImpl(this, transport_adapter);
+ new TransportAdapterListenerImpl(this, transport_adapter);
transport_adapter->AddListener(
- transport_adapter_listeners_[transport_adapter]);
+ transport_adapter_listeners_[transport_adapter]);
if (transport_adapter->IsInitialised() ||
transport_adapter->Init() == TransportAdapter::OK) {
@@ -358,8 +402,9 @@ int TransportManagerImpl::SearchDevices() {
LOG4CXX_TRACE(logger_, "enter");
if (!this->is_initialized_) {
LOG4CXX_ERROR(logger_, "TM is not initialized");
- LOG4CXX_TRACE(logger_,
- "exit with E_TM_IS_NOT_INITIALIZED. Condition: !this->is_initialized_");
+ LOG4CXX_TRACE(
+ logger_,
+ "exit with E_TM_IS_NOT_INITIALIZED. Condition: !this->is_initialized_");
return E_TM_IS_NOT_INITIALIZED;
}
@@ -368,28 +413,30 @@ int TransportManagerImpl::SearchDevices() {
bool success_occurred = false;
for (std::vector<TransportAdapter*>::iterator it =
- transport_adapters_.begin();
- it != transport_adapters_.end(); ++it) {
+ transport_adapters_.begin();
+ it != transport_adapters_.end();
+ ++it) {
LOG4CXX_DEBUG(logger_, "Iterating over transport adapters");
TransportAdapter::Error scanResult = (*it)->SearchDevices();
if (transport_adapter::TransportAdapter::OK == scanResult) {
success_occurred = true;
} else {
- LOG4CXX_ERROR(logger_, "Transport Adapter search failed "
- << *it << "[" << (*it)->GetDeviceType()
- << "]");
+ LOG4CXX_ERROR(logger_,
+ "Transport Adapter search failed "
+ << *it << "[" << (*it)->GetDeviceType() << "]");
switch (scanResult) {
case transport_adapter::TransportAdapter::NOT_SUPPORTED: {
- LOG4CXX_ERROR(logger_, "Search feature is not supported "
- << *it << "[" << (*it)->GetDeviceType()
- << "]");
- LOG4CXX_DEBUG(logger_, "scanResult = TransportAdapter::NOT_SUPPORTED");
+ LOG4CXX_ERROR(logger_,
+ "Search feature is not supported "
+ << *it << "[" << (*it)->GetDeviceType() << "]");
+ LOG4CXX_DEBUG(logger_,
+ "scanResult = TransportAdapter::NOT_SUPPORTED");
break;
}
case transport_adapter::TransportAdapter::BAD_STATE: {
- LOG4CXX_ERROR(logger_, "Transport Adapter has bad state " << *it << "[" <<
- (*it)->GetDeviceType()
- << "]");
+ LOG4CXX_ERROR(logger_,
+ "Transport Adapter has bad state "
+ << *it << "[" << (*it)->GetDeviceType() << "]");
LOG4CXX_DEBUG(logger_, "scanResult = TransportAdapter::BAD_STATE");
break;
}
@@ -401,20 +448,24 @@ int TransportManagerImpl::SearchDevices() {
}
}
}
- int transport_adapter_search = (success_occurred || transport_adapters_.empty())
- ? E_SUCCESS
- : E_ADAPTERS_FAIL;
+ int transport_adapter_search =
+ (success_occurred || transport_adapters_.empty()) ? E_SUCCESS
+ : E_ADAPTERS_FAIL;
if (transport_adapter_search == E_SUCCESS) {
LOG4CXX_TRACE(logger_,
- "exit with E_SUCCESS. Condition: success_occured || transport_adapters_.empty()");
+ "exit with E_SUCCESS. Condition: success_occured || "
+ "transport_adapters_.empty()");
} else {
LOG4CXX_TRACE(logger_,
- "exit with E_ADAPTERS_FAIL. Condition: success_occured || transport_adapters_.empty()");
+ "exit with E_ADAPTERS_FAIL. Condition: success_occured || "
+ "transport_adapters_.empty()");
}
return transport_adapter_search;
}
-int TransportManagerImpl::Init() {
+int TransportManagerImpl::Init(resumption::LastState& last_state) {
+ // Last state requred to initialize Transport adapters
+ UNUSED(last_state);
LOG4CXX_TRACE(logger_, "enter");
is_initialized_ = true;
LOG4CXX_TRACE(logger_, "exit with E_SUCCESS");
@@ -434,24 +485,27 @@ int TransportManagerImpl::Visibility(const bool& on_off) const {
TransportAdapter::Error ret;
LOG4CXX_DEBUG(logger_, "Visibility change requested to " << on_off);
- if (false == this->is_initialized_) {
+ if (!is_initialized_) {
LOG4CXX_ERROR(logger_, "TM is not initialized");
LOG4CXX_TRACE(logger_,
- "exit with E_TM_IS_NOT_INITIALIZED. Condition: false == this->is_initialized_");
+ "exit with E_TM_IS_NOT_INITIALIZED. Condition: false == "
+ "is_initialized_");
return E_TM_IS_NOT_INITIALIZED;
}
for (std::vector<TransportAdapter*>::const_iterator it =
- transport_adapters_.begin();
- it != transport_adapters_.end(); ++it) {
+ transport_adapters_.begin();
+ it != transport_adapters_.end();
+ ++it) {
if (on_off) {
ret = (*it)->StartClientListening();
} else {
ret = (*it)->StopClientListening();
}
if (TransportAdapter::Error::NOT_SUPPORTED == ret) {
- LOG4CXX_DEBUG(logger_, "Visibility change is not supported for adapter "
- << *it << "[" << (*it)->GetDeviceType() << "]");
+ LOG4CXX_DEBUG(logger_,
+ "Visibility change is not supported for adapter "
+ << *it << "[" << (*it)->GetDeviceType() << "]");
}
}
LOG4CXX_TRACE(logger_, "exit with E_SUCCESS");
@@ -461,29 +515,35 @@ int TransportManagerImpl::Visibility(const bool& on_off) const {
void TransportManagerImpl::UpdateDeviceList(TransportAdapter* ta) {
LOG4CXX_TRACE(logger_, "enter. TransportAdapter: " << ta);
std::set<DeviceInfo> old_devices;
- for (DeviceInfoList::iterator it = device_list_.begin();
- it != device_list_.end();) {
- if (it->first == ta) {
- old_devices.insert(it->second);
- it = device_list_.erase(it);
- } else {
- ++it;
+ std::set<DeviceInfo> new_devices;
+ {
+ sync_primitives::AutoWriteLock lock(device_list_lock_);
+ for (DeviceInfoList::iterator it = device_list_.begin();
+ it != device_list_.end();) {
+ if (it->first == ta) {
+ old_devices.insert(it->second);
+ it = device_list_.erase(it);
+ } else {
+ ++it;
+ }
}
- }
- std::set<DeviceInfo> new_devices;
- const DeviceList dev_list = ta->GetDeviceList();
- for (DeviceList::const_iterator it = dev_list.begin();
- it != dev_list.end(); ++it) {
- DeviceHandle device_handle = converter_.UidToHandle(*it);
- DeviceInfo info(device_handle, *it, ta->DeviceName(*it), ta->GetConnectionType());
- device_list_.push_back(std::make_pair(ta, info));
- new_devices.insert(info);
+ const DeviceList dev_list = ta->GetDeviceList();
+ for (DeviceList::const_iterator it = dev_list.begin(); it != dev_list.end();
+ ++it) {
+ DeviceHandle device_handle = converter_.UidToHandle(*it);
+ DeviceInfo info(
+ device_handle, *it, ta->DeviceName(*it), ta->GetConnectionType());
+ device_list_.push_back(std::make_pair(ta, info));
+ new_devices.insert(info);
+ }
}
std::set<DeviceInfo> added_devices;
- std::set_difference(new_devices.begin(), new_devices.end(),
- old_devices.begin(), old_devices.end(),
+ std::set_difference(new_devices.begin(),
+ new_devices.end(),
+ old_devices.begin(),
+ old_devices.end(),
std::inserter(added_devices, added_devices.begin()));
for (std::set<DeviceInfo>::const_iterator it = added_devices.begin();
it != added_devices.end();
@@ -492,8 +552,10 @@ void TransportManagerImpl::UpdateDeviceList(TransportAdapter* ta) {
}
std::set<DeviceInfo> removed_devices;
- std::set_difference(old_devices.begin(), old_devices.end(),
- new_devices.begin(), new_devices.end(),
+ std::set_difference(old_devices.begin(),
+ old_devices.end(),
+ new_devices.begin(),
+ new_devices.end(),
std::inserter(removed_devices, removed_devices.begin()));
for (std::set<DeviceInfo>::const_iterator it = removed_devices.begin();
@@ -504,7 +566,8 @@ void TransportManagerImpl::UpdateDeviceList(TransportAdapter* ta) {
LOG4CXX_TRACE(logger_, "exit");
}
-void TransportManagerImpl::PostMessage(const ::protocol_handler::RawMessagePtr message) {
+void TransportManagerImpl::PostMessage(
+ const ::protocol_handler::RawMessagePtr message) {
LOG4CXX_TRACE(logger_, "enter. RawMessageSptr: " << message);
message_queue_.PostMessage(message);
LOG4CXX_TRACE(logger_, "exit");
@@ -516,77 +579,98 @@ void TransportManagerImpl::PostEvent(const TransportAdapterEvent& event) {
event_queue_.PostMessage(event);
}
+const TransportManagerSettings& TransportManagerImpl::get_settings() const {
+ return settings_;
+}
+
void TransportManagerImpl::AddConnection(const ConnectionInternal& c) {
- LOG4CXX_TRACE(logger_, "enter ConnectionInternal: " << &c);
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_, "ConnectionInternal: " << &c);
+ sync_primitives::AutoWriteLock lock(connections_lock_);
connections_.push_back(c);
- LOG4CXX_TRACE(logger_, "exit");
}
-void TransportManagerImpl::RemoveConnection(uint32_t id) {
- LOG4CXX_TRACE(logger_, "enter Id: " << id);
+void TransportManagerImpl::RemoveConnection(
+ const uint32_t id, transport_adapter::TransportAdapter* transport_adapter) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_, "Id: " << id);
+ sync_primitives::AutoWriteLock lock(connections_lock_);
for (std::vector<ConnectionInternal>::iterator it = connections_.begin();
- it != connections_.end(); ++it) {
+ it != connections_.end();
+ ++it) {
if (it->id == id) {
connections_.erase(it);
+ if (transport_adapter) {
+ transport_adapter->RemoveFinalizedConnection(it->device,
+ it->application);
+ }
break;
}
}
- LOG4CXX_TRACE(logger_, "exit");
}
TransportManagerImpl::ConnectionInternal* TransportManagerImpl::GetConnection(
- const ConnectionUID& id) {
- LOG4CXX_TRACE(logger_, "enter. ConnectionUID: " << &id);
+ const ConnectionUID id) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_, "ConnectionUID: " << &id);
for (std::vector<ConnectionInternal>::iterator it = connections_.begin();
- it != connections_.end(); ++it) {
+ it != connections_.end();
+ ++it) {
if (it->id == id) {
- LOG4CXX_TRACE(logger_, "exit with ConnectionInternal. It's address: " << &*it);
+ LOG4CXX_DEBUG(logger_, "ConnectionInternal. It's address: " << &*it);
return &*it;
}
}
- LOG4CXX_TRACE(logger_, "exit with NULL");
return NULL;
}
TransportManagerImpl::ConnectionInternal* TransportManagerImpl::GetConnection(
- const DeviceUID& device, const ApplicationHandle& application) {
- LOG4CXX_TRACE(logger_, "enter DeviceUID: " << &device << "ApplicationHandle: " <<
- &application);
+ const DeviceUID& device, const ApplicationHandle& application) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ LOG4CXX_DEBUG(logger_,
+ "DeviceUID: " << &device
+ << "ApplicationHandle: " << &application);
for (std::vector<ConnectionInternal>::iterator it = connections_.begin();
- it != connections_.end(); ++it) {
+ it != connections_.end();
+ ++it) {
if (it->device == device && it->application == application) {
- LOG4CXX_TRACE(logger_, "exit with ConnectionInternal. It's address: " << &*it);
+ LOG4CXX_DEBUG(logger_, "ConnectionInternal. It's address: " << &*it);
return &*it;
}
}
- LOG4CXX_TRACE(logger_, "exit with NULL");
return NULL;
}
void TransportManagerImpl::OnDeviceListUpdated(TransportAdapter* ta) {
LOG4CXX_TRACE(logger_, "enter. TransportAdapter: " << ta);
const DeviceList device_list = ta->GetDeviceList();
- LOG4CXX_INFO(logger_, "DEVICE_LIST_UPDATED " << device_list.size());
+ LOG4CXX_DEBUG(logger_, "DEVICE_LIST_UPDATED " << device_list.size());
for (DeviceList::const_iterator it = device_list.begin();
- it != device_list.end(); ++it) {
+ it != device_list.end();
+ ++it) {
+ device_to_adapter_map_lock_.AcquireForWriting();
device_to_adapter_map_.insert(std::make_pair(*it, ta));
+ device_to_adapter_map_lock_.Release();
DeviceHandle device_handle = converter_.UidToHandle(*it);
- DeviceInfo info(device_handle, *it, ta->DeviceName(*it), ta->GetConnectionType());
+ DeviceInfo info(
+ device_handle, *it, ta->DeviceName(*it), ta->GetConnectionType());
RaiseEvent(&TransportManagerListener::OnDeviceFound, info);
}
UpdateDeviceList(ta);
std::vector<DeviceInfo> device_infos;
+ device_list_lock_.AcquireForReading();
for (DeviceInfoList::const_iterator it = device_list_.begin();
- it != device_list_.end(); ++it) {
+ it != device_list_.end();
+ ++it) {
device_infos.push_back(it->second);
}
+ device_list_lock_.Release();
RaiseEvent(&TransportManagerListener::OnDeviceListUpdated, device_infos);
LOG4CXX_TRACE(logger_, "exit");
}
void TransportManagerImpl::Handle(TransportAdapterEvent event) {
LOG4CXX_TRACE(logger_, "enter");
- ConnectionInternal* connection = GetConnection(event.device_uid, event.application_id);
switch (event.event_type) {
case TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_DONE: {
RaiseEvent(&TransportManagerListener::OnScanDevicesFinished);
@@ -611,81 +695,110 @@ void TransportManagerImpl::Handle(TransportAdapterEvent event) {
break;
}
case TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_DONE: {
- const DeviceHandle device_handle = converter_.UidToHandle(event.device_uid);
- AddConnection(ConnectionInternal(this, event.transport_adapter, ++connection_id_counter_,
- event.device_uid, event.application_id,
+ const DeviceHandle device_handle =
+ converter_.UidToHandle(event.device_uid);
+ AddConnection(ConnectionInternal(this,
+ event.transport_adapter,
+ ++connection_id_counter_,
+ event.device_uid,
+ event.application_id,
device_handle));
- RaiseEvent(&TransportManagerListener::OnConnectionEstablished,
- DeviceInfo(device_handle, event.device_uid,
- event.transport_adapter->DeviceName(event.device_uid),
- event.transport_adapter->GetConnectionType()),
- connection_id_counter_);
+ RaiseEvent(
+ &TransportManagerListener::OnConnectionEstablished,
+ DeviceInfo(device_handle,
+ event.device_uid,
+ event.transport_adapter->DeviceName(event.device_uid),
+ event.transport_adapter->GetConnectionType()),
+ connection_id_counter_);
LOG4CXX_DEBUG(logger_, "event_type = ON_CONNECT_DONE");
break;
}
case TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_FAIL: {
- RaiseEvent(&TransportManagerListener::OnConnectionFailed,
- DeviceInfo(converter_.UidToHandle(event.device_uid), event.device_uid,
- event.transport_adapter->DeviceName(event.device_uid),
- event.transport_adapter->GetConnectionType()),
- ConnectError());
+ RaiseEvent(
+ &TransportManagerListener::OnConnectionFailed,
+ DeviceInfo(converter_.UidToHandle(event.device_uid),
+ event.device_uid,
+ event.transport_adapter->DeviceName(event.device_uid),
+ event.transport_adapter->GetConnectionType()),
+ ConnectError());
LOG4CXX_DEBUG(logger_, "event_type = ON_CONNECT_FAIL");
break;
}
case TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_DONE: {
+ connections_lock_.AcquireForReading();
+ ConnectionInternal* connection =
+ GetConnection(event.device_uid, event.application_id);
if (NULL == connection) {
LOG4CXX_ERROR(logger_, "Connection not found");
LOG4CXX_DEBUG(logger_,
"event_type = ON_DISCONNECT_DONE && NULL == connection");
+ connections_lock_.Release();
break;
}
- RaiseEvent(&TransportManagerListener::OnConnectionClosed,
- connection->id);
- RemoveConnection(connection->id);
+ const ConnectionUID id = connection->id;
+ connections_lock_.Release();
+
+ RaiseEvent(&TransportManagerListener::OnConnectionClosed, id);
+ RemoveConnection(id, connection->transport_adapter);
LOG4CXX_DEBUG(logger_, "event_type = ON_DISCONNECT_DONE");
break;
}
case TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_FAIL: {
- const DeviceHandle device_handle = converter_.UidToHandle(event.device_uid);
+ const DeviceHandle device_handle =
+ converter_.UidToHandle(event.device_uid);
RaiseEvent(&TransportManagerListener::OnDisconnectFailed,
- device_handle, DisconnectDeviceError());
+ device_handle,
+ DisconnectDeviceError());
LOG4CXX_DEBUG(logger_, "event_type = ON_DISCONNECT_FAIL");
break;
}
case TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_DONE: {
-#ifdef TIME_TESTER
+#ifdef TELEMETRY_MONITOR
if (metric_observer_) {
metric_observer_->StopRawMsg(event.event_data.get());
}
-#endif // TIME_TESTER
+#endif // TELEMETRY_MONITOR
+ sync_primitives::AutoReadLock lock(connections_lock_);
+ ConnectionInternal* connection =
+ GetConnection(event.device_uid, event.application_id);
if (connection == NULL) {
- LOG4CXX_ERROR(logger_, "Connection ('" << event.device_uid << ", "
- << event.application_id
- << ") not found");
- LOG4CXX_DEBUG(logger_, "event_type = ON_SEND_DONE. Condition: NULL == connection");
+ LOG4CXX_ERROR(logger_,
+ "Connection ('" << event.device_uid << ", "
+ << event.application_id << ") not found");
+ LOG4CXX_DEBUG(
+ logger_,
+ "event_type = ON_SEND_DONE. Condition: NULL == connection");
break;
}
RaiseEvent(&TransportManagerListener::OnTMMessageSend, event.event_data);
- if (connection->shutDown && --connection->messages_count == 0) {
- connection->timer->stop();
+ if (connection->shutdown_ && --connection->messages_count == 0) {
+ connection->timer->Stop();
connection->transport_adapter->Disconnect(connection->device,
- connection->application);
+ connection->application);
}
LOG4CXX_DEBUG(logger_, "event_type = ON_SEND_DONE");
break;
}
case TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_FAIL: {
-#ifdef TIME_TESTER
+#ifdef TELEMETRY_MONITOR
if (metric_observer_) {
metric_observer_->StopRawMsg(event.event_data.get());
}
-#endif // TIME_TESTER
- if (connection == NULL) {
- LOG4CXX_ERROR(logger_, "Connection ('" << event.device_uid << ", "
- << event.application_id
- << ") not found");
- LOG4CXX_DEBUG(logger_, "event_type = ON_SEND_FAIL. Condition: NULL == connection");
- break;
+#endif // TELEMETRY_MONITOR
+ {
+ sync_primitives::AutoReadLock lock(connections_lock_);
+ ConnectionInternal* connection =
+ GetConnection(event.device_uid, event.application_id);
+ if (connection == NULL) {
+ LOG4CXX_ERROR(logger_,
+ "Connection ('" << event.device_uid << ", "
+ << event.application_id
+ << ") not found");
+ LOG4CXX_DEBUG(
+ logger_,
+ "event_type = ON_SEND_FAIL. Condition: NULL == connection");
+ break;
+ }
}
// TODO(YK): start timer here to wait before notify caller
@@ -702,34 +815,48 @@ void TransportManagerImpl::Handle(TransportAdapterEvent event) {
break;
}
case TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_DONE: {
- if (connection == NULL) {
- LOG4CXX_ERROR(logger_, "Connection ('" << event.device_uid << ", "
- << event.application_id
- << ") not found");
- LOG4CXX_DEBUG(logger_, "event_type = ON_RECEIVED_DONE. Condition: NULL == connection");
- break;
+ {
+ sync_primitives::AutoReadLock lock(connections_lock_);
+ ConnectionInternal* connection =
+ GetConnection(event.device_uid, event.application_id);
+ if (connection == NULL) {
+ LOG4CXX_ERROR(logger_,
+ "Connection ('" << event.device_uid << ", "
+ << event.application_id
+ << ") not found");
+ LOG4CXX_DEBUG(
+ logger_,
+ "event_type = ON_RECEIVED_DONE. Condition: NULL == connection");
+ break;
+ }
+ event.event_data->set_connection_key(connection->id);
}
- event.event_data->set_connection_key(connection->id);
-#ifdef TIME_TESTER
+#ifdef TELEMETRY_MONITOR
if (metric_observer_) {
metric_observer_->StopRawMsg(event.event_data.get());
}
-#endif // TIME_TESTER
- RaiseEvent(&TransportManagerListener::OnTMMessageReceived, event.event_data);
+#endif // TELEMETRY_MONITOR
+ RaiseEvent(&TransportManagerListener::OnTMMessageReceived,
+ event.event_data);
LOG4CXX_DEBUG(logger_, "event_type = ON_RECEIVED_DONE");
break;
}
case TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_FAIL: {
LOG4CXX_DEBUG(logger_, "Event ON_RECEIVED_FAIL");
+ connections_lock_.AcquireForReading();
+ ConnectionInternal* connection =
+ GetConnection(event.device_uid, event.application_id);
if (connection == NULL) {
- LOG4CXX_ERROR(logger_, "Connection ('" << event.device_uid << ", "
- << event.application_id
- << ") not found");
+ LOG4CXX_ERROR(logger_,
+ "Connection ('" << event.device_uid << ", "
+ << event.application_id << ") not found");
+ connections_lock_.Release();
break;
}
+ connections_lock_.Release();
RaiseEvent(&TransportManagerListener::OnTMMessageReceiveFailed,
- connection->id, *static_cast<DataReceiveError*>(event.event_error.get()));
+ *static_cast<DataReceiveError*>(event.event_error.get()));
LOG4CXX_DEBUG(logger_, "event_type = ON_RECEIVED_FAIL");
break;
}
@@ -737,16 +864,23 @@ void TransportManagerImpl::Handle(TransportAdapterEvent event) {
LOG4CXX_DEBUG(logger_, "event_type = ON_COMMUNICATION_ERROR");
break;
}
- case TransportAdapterListenerImpl::EventTypeEnum::ON_UNEXPECTED_DISCONNECT: {
+ case TransportAdapterListenerImpl::EventTypeEnum::
+ ON_UNEXPECTED_DISCONNECT: {
+ connections_lock_.AcquireForReading();
+ ConnectionInternal* connection =
+ GetConnection(event.device_uid, event.application_id);
if (connection) {
+ const ConnectionUID id = connection->id;
+ connections_lock_.Release();
RaiseEvent(&TransportManagerListener::OnUnexpectedDisconnect,
- connection->id,
+ id,
*static_cast<CommunicationError*>(event.event_error.get()));
- RemoveConnection(connection->id);
+ RemoveConnection(id, connection->transport_adapter);
} else {
- LOG4CXX_ERROR(logger_, "Connection ('" << event.device_uid << ", "
- << event.application_id
- << ") not found");
+ connections_lock_.Release();
+ LOG4CXX_ERROR(logger_,
+ "Connection ('" << event.device_uid << ", "
+ << event.application_id << ") not found");
}
LOG4CXX_DEBUG(logger_, "eevent_type = ON_UNEXPECTED_DISCONNECT");
break;
@@ -755,40 +889,42 @@ void TransportManagerImpl::Handle(TransportAdapterEvent event) {
LOG4CXX_TRACE(logger_, "exit");
}
-#ifdef TIME_TESTER
-void TransportManagerImpl::SetTimeMetricObserver(TMMetricObserver* observer) {
+#ifdef TELEMETRY_MONITOR
+void TransportManagerImpl::SetTelemetryObserver(TMTelemetryObserver* observer) {
metric_observer_ = observer;
}
-#endif // TIME_TESTER
+#endif // TELEMETRY_MONITOR
void TransportManagerImpl::Handle(::protocol_handler::RawMessagePtr msg) {
LOG4CXX_TRACE(logger_, "enter");
+ sync_primitives::AutoReadLock lock(connections_lock_);
ConnectionInternal* connection = GetConnection(msg->connection_key());
if (connection == NULL) {
- LOG4CXX_WARN(logger_, "Connection " << msg->connection_key() << " not found");
+ LOG4CXX_WARN(logger_,
+ "Connection " << msg->connection_key() << " not found");
RaiseEvent(&TransportManagerListener::OnTMMessageSendFailed,
- DataSendTimeoutError(), msg);
+ DataSendTimeoutError(),
+ msg);
return;
}
TransportAdapter* transport_adapter = connection->transport_adapter;
- LOG4CXX_DEBUG(logger_, "Got adapter "
- << transport_adapter << "["
- << transport_adapter->GetDeviceType() << "]"
- << " by session id "
- << msg->connection_key());
+ LOG4CXX_DEBUG(logger_,
+ "Got adapter " << transport_adapter << "["
+ << transport_adapter->GetDeviceType() << "]"
+ << " by session id " << msg->connection_key());
if (NULL == transport_adapter) {
- std::string error_text =
- "Transport adapter is not found";
+ std::string error_text = "Transport adapter is not found";
LOG4CXX_ERROR(logger_, error_text);
RaiseEvent(&TransportManagerListener::OnTMMessageSendFailed,
- DataSendError(error_text), msg);
+ DataSendError(error_text),
+ msg);
} else {
if (TransportAdapter::OK ==
transport_adapter->SendData(
- connection->device, connection->application, msg)) {
- LOG4CXX_INFO(logger_, "Data sent to adapter");
+ connection->device, connection->application, msg)) {
+ LOG4CXX_TRACE(logger_, "Data sent to adapter");
} else {
LOG4CXX_ERROR(logger_, "Data sent error");
RaiseEvent(&TransportManagerListener::OnTMMessageSendFailed,
@@ -800,15 +936,23 @@ void TransportManagerImpl::Handle(::protocol_handler::RawMessagePtr msg) {
}
TransportManagerImpl::ConnectionInternal::ConnectionInternal(
- TransportManagerImpl* transport_manager, TransportAdapter* transport_adapter,
- const ConnectionUID& id, const DeviceUID& dev_id, const ApplicationHandle& app_id,
- const DeviceHandle& device_handle)
- : transport_manager(transport_manager),
- transport_adapter(transport_adapter),
- timer(new TimerInternal("TM DiscRoutine", this, &ConnectionInternal::DisconnectFailedRoutine)),
- shutDown(false),
- device_handle_(device_handle),
- messages_count(0) {
+ TransportManagerImpl* transport_manager,
+ TransportAdapter* transport_adapter,
+ const ConnectionUID id,
+ const DeviceUID& dev_id,
+ const ApplicationHandle& app_id,
+ const DeviceHandle device_handle)
+ : transport_manager(transport_manager)
+ , transport_adapter(transport_adapter)
+ , timer(utils::MakeShared<timer::Timer,
+ const char*,
+ ::timer::TimerTaskImpl<ConnectionInternal>*>(
+ "TM DiscRoutine",
+ new ::timer::TimerTaskImpl<ConnectionInternal>(
+ this, &ConnectionInternal::DisconnectFailedRoutine)))
+ , shutdown_(false)
+ , device_handle_(device_handle)
+ , messages_count(0) {
Connection::id = id;
Connection::device = dev_id;
Connection::application = app_id;
@@ -817,12 +961,11 @@ TransportManagerImpl::ConnectionInternal::ConnectionInternal(
void TransportManagerImpl::ConnectionInternal::DisconnectFailedRoutine() {
LOG4CXX_TRACE(logger_, "enter");
transport_manager->RaiseEvent(&TransportManagerListener::OnDisconnectFailed,
- device_handle_, DisconnectDeviceError());
- shutDown = false;
- timer->stop();
+ device_handle_,
+ DisconnectDeviceError());
+ shutdown_ = false;
+ timer->Stop();
LOG4CXX_TRACE(logger_, "exit");
}
} // namespace transport_manager
-
-
diff --git a/src/components/transport_manager/src/usb/libusb/platform_usb_device.cc b/src/components/transport_manager/src/usb/libusb/platform_usb_device.cc
index 1ca1a54b32..33709cf0f6 100644
--- a/src/components/transport_manager/src/usb/libusb/platform_usb_device.cc
+++ b/src/components/transport_manager/src/usb/libusb/platform_usb_device.cc
@@ -41,27 +41,29 @@ namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
-
PlatformUsbDevice::PlatformUsbDevice(
- uint8_t bus_number, uint8_t address,
- const libusb_device_descriptor& device_descriptor,
- libusb_device* device_libusb, libusb_device_handle* device_handle_libusb)
- : bus_number_(bus_number),
- address_(address),
- vendor_id_(device_descriptor.idVendor),
- product_id_(device_descriptor.idProduct),
- device_descriptor_(device_descriptor),
- libusb_device_handle_(device_handle_libusb),
- libusb_device_(device_libusb) {}
+ uint8_t bus_number,
+ uint8_t address,
+ const libusb_device_descriptor& device_descriptor,
+ libusb_device* device_libusb,
+ libusb_device_handle* device_handle_libusb)
+ : bus_number_(bus_number)
+ , address_(address)
+ , vendor_id_(device_descriptor.idVendor)
+ , product_id_(device_descriptor.idProduct)
+ , device_descriptor_(device_descriptor)
+ , libusb_device_handle_(device_handle_libusb)
+ , libusb_device_(device_libusb) {}
std::string PlatformUsbDevice::GetDescString(uint8_t index) const {
LOG4CXX_TRACE(logger_, "enter. index: " << int(index));
unsigned char buf[128];
const int libusb_ret = libusb_get_string_descriptor_ascii(
- libusb_device_handle_, index, buf, sizeof(buf));
+ libusb_device_handle_, index, buf, sizeof(buf));
if (libusb_ret < 0) {
- LOG4CXX_ERROR(logger_, "Failed to get USB string descriptor: "
- << libusb_error_name(libusb_ret));
+ LOG4CXX_ERROR(logger_,
+ "Failed to get USB string descriptor: "
+ << libusb_error_name(libusb_ret));
LOG4CXX_TRACE(logger_, "exit with empty string");
return "";
}
diff --git a/src/components/transport_manager/src/usb/libusb/usb_connection.cc b/src/components/transport_manager/src/usb/libusb/usb_connection.cc
index b8096514bc..409209b2b2 100644
--- a/src/components/transport_manager/src/usb/libusb/usb_connection.cc
+++ b/src/components/transport_manager/src/usb/libusb/usb_connection.cc
@@ -48,32 +48,30 @@ namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
-
UsbConnection::UsbConnection(const DeviceUID& device_uid,
const ApplicationHandle& app_handle,
TransportAdapterController* controller,
const UsbHandlerSptr usb_handler,
PlatformUsbDevice* device)
- : device_uid_(device_uid),
- app_handle_(app_handle),
- controller_(controller),
- usb_handler_(usb_handler),
- libusb_device_(device->GetLibusbDevice()),
- device_handle_(device->GetLibusbHandle()),
- in_endpoint_(0),
- in_endpoint_max_packet_size_(0),
- out_endpoint_(0),
- out_endpoint_max_packet_size_(0),
- in_buffer_(NULL),
- in_transfer_(NULL),
- out_transfer_(0),
- out_messages_(),
- current_out_message_(),
- bytes_sent_(0),
- disconnecting_(false),
- waiting_in_transfer_cancel_(false),
- waiting_out_transfer_cancel_(false) {
-}
+ : device_uid_(device_uid)
+ , app_handle_(app_handle)
+ , controller_(controller)
+ , usb_handler_(usb_handler)
+ , libusb_device_(device->GetLibusbDevice())
+ , device_handle_(device->GetLibusbHandle())
+ , in_endpoint_(0)
+ , in_endpoint_max_packet_size_(0)
+ , out_endpoint_(0)
+ , out_endpoint_max_packet_size_(0)
+ , in_buffer_(NULL)
+ , in_transfer_(NULL)
+ , out_transfer_(0)
+ , out_messages_()
+ , current_out_message_()
+ , bytes_sent_(0)
+ , disconnecting_(false)
+ , waiting_in_transfer_cancel_(false)
+ , waiting_out_transfer_cancel_(false) {}
UsbConnection::~UsbConnection() {
LOG4CXX_TRACE(logger_, "enter with this" << this);
@@ -94,22 +92,30 @@ void OutTransferCallback(libusb_transfer* transfer) {
bool UsbConnection::PostInTransfer() {
LOG4CXX_TRACE(logger_, "enter");
- libusb_fill_bulk_transfer(in_transfer_, device_handle_, in_endpoint_,
- in_buffer_, in_endpoint_max_packet_size_,
- InTransferCallback, this, 0);
+ libusb_fill_bulk_transfer(in_transfer_,
+ device_handle_,
+ in_endpoint_,
+ in_buffer_,
+ in_endpoint_max_packet_size_,
+ InTransferCallback,
+ this,
+ 0);
const int libusb_ret = libusb_submit_transfer(in_transfer_);
if (LIBUSB_SUCCESS != libusb_ret) {
- LOG4CXX_ERROR(logger_, "libusb_submit_transfer failed: "
- << libusb_error_name(libusb_ret));
- LOG4CXX_TRACE(logger_,
- "exit with FALSE. Condition: LIBUSB_SUCCESS != libusb_submit_transfer");
+ LOG4CXX_ERROR(
+ logger_,
+ "libusb_submit_transfer failed: " << libusb_error_name(libusb_ret));
+ LOG4CXX_TRACE(
+ logger_,
+ "exit with FALSE. Condition: LIBUSB_SUCCESS != libusb_submit_transfer");
return false;
}
LOG4CXX_TRACE(logger_, "exit with TRUE");
return true;
}
-std::string hex_data(const unsigned char* const buffer, const int actual_length) {
+std::string hex_data(const unsigned char* const buffer,
+ const int actual_length) {
std::ostringstream hexdata;
for (int i = 0; i < actual_length; ++i) {
hexdata << " " << std::hex << std::setw(2) << std::setfill('0')
@@ -122,23 +128,26 @@ void UsbConnection::OnInTransfer(libusb_transfer* transfer) {
LOG4CXX_TRACE(logger_, "enter with Libusb_transfer*: " << transfer);
if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
LOG4CXX_DEBUG(logger_,
- "USB incoming transfer, size:" << transfer->actual_length
- << ", data:" << hex_data(transfer->buffer, transfer->actual_length));
+ "USB incoming transfer, size:"
+ << transfer->actual_length << ", data:"
+ << hex_data(transfer->buffer, transfer->actual_length));
::protocol_handler::RawMessagePtr data(new protocol_handler::RawMessage(
- 0, 0, in_buffer_, transfer->actual_length));
+ 0, 0, in_buffer_, transfer->actual_length));
controller_->DataReceiveDone(device_uid_, app_handle_, data);
} else {
- LOG4CXX_ERROR(logger_, "USB incoming transfer failed: "
- << libusb_error_name(transfer->status));
- controller_->DataReceiveFailed(device_uid_, app_handle_,
- DataReceiveError());
+ LOG4CXX_ERROR(logger_,
+ "USB incoming transfer failed: "
+ << libusb_error_name(transfer->status));
+ controller_->DataReceiveFailed(
+ device_uid_, app_handle_, DataReceiveError());
}
if (disconnecting_) {
waiting_in_transfer_cancel_ = false;
} else {
if (!PostInTransfer()) {
- LOG4CXX_ERROR(logger_, "USB incoming transfer failed with "
- << "LIBUSB_TRANSFER_NO_DEVICE. Abort connection.");
+ LOG4CXX_ERROR(logger_,
+ "USB incoming transfer failed with "
+ << "LIBUSB_TRANSFER_NO_DEVICE. Abort connection.");
AbortConnection();
}
}
@@ -166,17 +175,24 @@ bool UsbConnection::PostOutTransfer() {
LOG4CXX_TRACE(logger_, "exit with FALSE. Condition: 0 == out_transfer_");
return false;
}
- libusb_fill_bulk_transfer(out_transfer_, device_handle_, out_endpoint_,
+ libusb_fill_bulk_transfer(out_transfer_,
+ device_handle_,
+ out_endpoint_,
current_out_message_->data() + bytes_sent_,
current_out_message_->data_size() - bytes_sent_,
- OutTransferCallback, this, 0);
+ OutTransferCallback,
+ this,
+ 0);
const int libusb_ret = libusb_submit_transfer(out_transfer_);
if (LIBUSB_SUCCESS != libusb_ret) {
- LOG4CXX_ERROR(logger_, "libusb_submit_transfer failed: "
- << libusb_error_name(libusb_ret) << ". Abort connection.");
+ LOG4CXX_ERROR(
+ logger_,
+ "libusb_submit_transfer failed: " << libusb_error_name(libusb_ret)
+ << ". Abort connection.");
AbortConnection();
- LOG4CXX_TRACE(logger_, "exit with FALSE. Condition: "
- << "LIBUSB_SUCCESS != libusb_fill_bulk_transfer");
+ LOG4CXX_TRACE(logger_,
+ "exit with FALSE. Condition: "
+ << "LIBUSB_SUCCESS != libusb_fill_bulk_transfer");
return false;
}
LOG4CXX_TRACE(logger_, "exit with TRUE");
@@ -189,16 +205,18 @@ void UsbConnection::OnOutTransfer(libusb_transfer* transfer) {
if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
bytes_sent_ += transfer->actual_length;
if (bytes_sent_ == current_out_message_->data_size()) {
- LOG4CXX_DEBUG(logger_, "USB out transfer, data sent: "
- << current_out_message_.get());
+ LOG4CXX_DEBUG(
+ logger_,
+ "USB out transfer, data sent: " << current_out_message_.get());
controller_->DataSendDone(device_uid_, app_handle_, current_out_message_);
PopOutMessage();
}
} else {
- LOG4CXX_ERROR(logger_, "USB out transfer failed: "
- << libusb_error_name(transfer->status));
- controller_->DataSendFailed(device_uid_, app_handle_, current_out_message_,
- DataSendError());
+ LOG4CXX_ERROR(
+ logger_,
+ "USB out transfer failed: " << libusb_error_name(transfer->status));
+ controller_->DataSendFailed(
+ device_uid_, app_handle_, current_out_message_, DataSendError());
PopOutMessage();
}
if (!current_out_message_.valid()) {
@@ -209,11 +227,13 @@ void UsbConnection::OnOutTransfer(libusb_transfer* transfer) {
LOG4CXX_TRACE(logger_, "exit");
}
-TransportAdapter::Error UsbConnection::SendData(::protocol_handler::RawMessagePtr message) {
+TransportAdapter::Error UsbConnection::SendData(
+ ::protocol_handler::RawMessagePtr message) {
LOG4CXX_TRACE(logger_, "enter with RawMessagePtr: " << message.get());
if (disconnecting_) {
- LOG4CXX_TRACE(logger_, "exit with TransportAdapter::BAD_STATE. Condition: "
- << "disconnecting_");
+ LOG4CXX_TRACE(logger_,
+ "exit with TransportAdapter::BAD_STATE. Condition: "
+ << "disconnecting_");
return TransportAdapter::BAD_STATE;
}
sync_primitives::AutoLock locker(out_messages_mutex_);
@@ -222,9 +242,11 @@ TransportAdapter::Error UsbConnection::SendData(::protocol_handler::RawMessagePt
} else {
current_out_message_ = message;
if (!PostOutTransfer()) {
- controller_->DataSendFailed(device_uid_, app_handle_, message,
- DataSendError());
- LOG4CXX_TRACE(logger_, "exit with TransportAdapter::FAIL. Condition: !PostOutTransfer()");
+ controller_->DataSendFailed(
+ device_uid_, app_handle_, message, DataSendError());
+ LOG4CXX_TRACE(
+ logger_,
+ "exit with TransportAdapter::FAIL. Condition: !PostOutTransfer()");
return TransportAdapter::FAIL;
}
}
@@ -240,19 +262,22 @@ void UsbConnection::Finalise() {
disconnecting_ = true;
if (out_transfer_) {
waiting_out_transfer_cancel_ = true;
- if ( LIBUSB_SUCCESS != libusb_cancel_transfer(out_transfer_)) {
+ if (LIBUSB_SUCCESS != libusb_cancel_transfer(out_transfer_)) {
waiting_out_transfer_cancel_ = false;
}
}
if (in_transfer_) {
waiting_in_transfer_cancel_ = true;
- if ( LIBUSB_SUCCESS != libusb_cancel_transfer(in_transfer_)) {
+ if (LIBUSB_SUCCESS != libusb_cancel_transfer(in_transfer_)) {
waiting_in_transfer_cancel_ = false;
}
}
- for (std::list<protocol_handler::RawMessagePtr>::iterator it = out_messages_.begin();
- it != out_messages_.end(); it = out_messages_.erase(it)) {
- controller_->DataSendFailed(device_uid_, app_handle_, *it, DataSendError());
+ for (std::list<protocol_handler::RawMessagePtr>::iterator it =
+ out_messages_.begin();
+ it != out_messages_.end();
+ it = out_messages_.erase(it)) {
+ controller_->DataSendFailed(
+ device_uid_, app_handle_, *it, DataSendError());
}
}
while (waiting_in_transfer_cancel_ || waiting_out_transfer_cancel_) {
@@ -263,7 +288,8 @@ void UsbConnection::Finalise() {
void UsbConnection::AbortConnection() {
LOG4CXX_TRACE(logger_, "enter");
- controller_->ConnectionAborted(device_uid_, app_handle_, CommunicationError());
+ controller_->ConnectionAborted(
+ device_uid_, app_handle_, CommunicationError());
Disconnect();
LOG4CXX_TRACE(logger_, "exit");
}
@@ -292,8 +318,8 @@ bool UsbConnection::Init() {
controller_->ConnectDone(device_uid_, app_handle_);
if (!PostInTransfer()) {
LOG4CXX_ERROR(logger_, "PostInTransfer failed. Call ConnectionAborted");
- controller_->ConnectionAborted(device_uid_, app_handle_,
- CommunicationError());
+ controller_->ConnectionAborted(
+ device_uid_, app_handle_, CommunicationError());
LOG4CXX_TRACE(logger_, "exit with FALSE. Condition: !PostInTransfer()");
return false;
}
@@ -306,11 +332,13 @@ bool UsbConnection::FindEndpoints() {
LOG4CXX_TRACE(logger_, "enter");
struct libusb_config_descriptor* config;
const int libusb_ret =
- libusb_get_active_config_descriptor(libusb_device_, &config);
+ libusb_get_active_config_descriptor(libusb_device_, &config);
if (LIBUSB_SUCCESS != libusb_ret) {
- LOG4CXX_ERROR(logger_, "libusb_get_active_config_descriptor failed: "
- << libusb_error_name(libusb_ret));
- LOG4CXX_TRACE(logger_, "exit with FALSE. Condition: LIBUSB_SUCCESS != libusb_ret");
+ LOG4CXX_ERROR(logger_,
+ "libusb_get_active_config_descriptor failed: "
+ << libusb_error_name(libusb_ret));
+ LOG4CXX_TRACE(logger_,
+ "exit with FALSE. Condition: LIBUSB_SUCCESS != libusb_ret");
return false;
}
@@ -323,10 +351,10 @@ bool UsbConnection::FindEndpoints() {
const libusb_interface_descriptor& iface_desc = interface.altsetting[i];
for (int i = 0; i < iface_desc.bNumEndpoints; ++i) {
const libusb_endpoint_descriptor& endpoint_desc =
- iface_desc.endpoint[i];
+ iface_desc.endpoint[i];
const uint8_t endpoint_dir =
- endpoint_desc.bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK;
+ endpoint_desc.bEndpointAddress & LIBUSB_ENDPOINT_DIR_MASK;
if (find_in_endpoint && endpoint_dir == LIBUSB_ENDPOINT_IN) {
in_endpoint_ = endpoint_desc.bEndpointAddress;
in_endpoint_max_packet_size_ = endpoint_desc.wMaxPacketSize;
diff --git a/src/components/transport_manager/src/usb/libusb/usb_handler.cc b/src/components/transport_manager/src/usb/libusb/usb_handler.cc
index 776bb56c5d..c62e80d1be 100644
--- a/src/components/transport_manager/src/usb/libusb/usb_handler.cc
+++ b/src/components/transport_manager/src/usb/libusb/usb_handler.cc
@@ -76,15 +76,15 @@ class UsbHandler::ControlTransferSequenceState {
};
UsbHandler::UsbHandler()
- : shutdown_requested_(false),
- thread_(NULL),
- usb_device_listeners_(),
- devices_(),
- transfer_sequences_(),
- device_handles_to_close_(),
- libusb_context_(NULL),
- arrived_callback_handle_(),
- left_callback_handle_() {
+ : shutdown_requested_(false)
+ , thread_(NULL)
+ , usb_device_listeners_()
+ , devices_()
+ , transfer_sequences_()
+ , device_handles_to_close_()
+ , libusb_context_(NULL)
+ , arrived_callback_handle_()
+ , left_callback_handle_() {
thread_ = threads::CreateThread("UsbHandler", new UsbHandlerDelegate(this));
}
@@ -113,7 +113,8 @@ void UsbHandler::DeviceArrived(libusb_device* device_libusb) {
libusb_device_descriptor descriptor;
int libusb_ret = libusb_get_device_descriptor(device_libusb, &descriptor);
if (LIBUSB_SUCCESS != libusb_ret) {
- LOG4CXX_ERROR(logger_, "libusb_get_device_descriptor failed: " << libusb_ret);
+ LOG4CXX_ERROR(logger_,
+ "libusb_get_device_descriptor failed: " << libusb_ret);
LOG4CXX_TRACE(logger_, "exit. Condition: LIBUSB_SUCCESS != libusb_ret");
return;
}
@@ -121,7 +122,8 @@ void UsbHandler::DeviceArrived(libusb_device* device_libusb) {
libusb_device_handle* device_handle_libusb;
libusb_ret = libusb_open(device_libusb, &device_handle_libusb);
if (libusb_ret != LIBUSB_SUCCESS) {
- LOG4CXX_ERROR(logger_, "libusb_open failed: " << libusb_error_name(libusb_ret));
+ LOG4CXX_ERROR(logger_,
+ "libusb_open failed: " << libusb_error_name(libusb_ret));
LOG4CXX_TRACE(logger_, "exit. Condition: libusb_ret != LIBUSB_SUCCESS");
return;
}
@@ -129,17 +131,20 @@ void UsbHandler::DeviceArrived(libusb_device* device_libusb) {
int configuration;
libusb_ret = libusb_get_configuration(device_handle_libusb, &configuration);
if (LIBUSB_SUCCESS != libusb_ret) {
- LOG4CXX_INFO(logger_, "libusb_get_configuration failed: " << libusb_error_name(
- libusb_ret));
+ LOG4CXX_INFO(
+ logger_,
+ "libusb_get_configuration failed: " << libusb_error_name(libusb_ret));
LOG4CXX_TRACE(logger_, "exit. Condition: LIBUSB_SUCCESS != libusb_ret");
return;
}
if (configuration != kUsbConfiguration) {
- libusb_ret = libusb_set_configuration(device_handle_libusb, kUsbConfiguration);
+ libusb_ret =
+ libusb_set_configuration(device_handle_libusb, kUsbConfiguration);
if (LIBUSB_SUCCESS != libusb_ret) {
- LOG4CXX_INFO(logger_, "libusb_set_configuration failed: " << libusb_error_name(
- libusb_ret));
+ LOG4CXX_INFO(
+ logger_,
+ "libusb_set_configuration failed: " << libusb_error_name(libusb_ret));
LOG4CXX_TRACE(logger_, "exit. Condition: LIBUSB_SUCCESS != libusb_ret");
return;
}
@@ -147,20 +152,25 @@ void UsbHandler::DeviceArrived(libusb_device* device_libusb) {
libusb_ret = libusb_claim_interface(device_handle_libusb, 0);
if (LIBUSB_SUCCESS != libusb_ret) {
- LOG4CXX_INFO(logger_, "libusb_claim_interface failed: " << libusb_error_name(libusb_ret));
+ LOG4CXX_INFO(
+ logger_,
+ "libusb_claim_interface failed: " << libusb_error_name(libusb_ret));
CloseDeviceHandle(device_handle_libusb);
LOG4CXX_TRACE(logger_, "exit. Condition: LIBUSB_SUCCESS != libusb_ret");
return;
}
- PlatformUsbDevice* device(new PlatformUsbDevice(bus_number, device_address,
- descriptor, device_libusb,
- device_handle_libusb));
+ PlatformUsbDevice* device(new PlatformUsbDevice(bus_number,
+ device_address,
+ descriptor,
+ device_libusb,
+ device_handle_libusb));
devices_.push_back(device);
for (std::list<UsbDeviceListener*>::iterator it =
- usb_device_listeners_.begin();
- it != usb_device_listeners_.end(); ++it) {
+ usb_device_listeners_.begin();
+ it != usb_device_listeners_.end();
+ ++it) {
(*it)->OnDeviceArrived(device);
}
LOG4CXX_TRACE(logger_, "exit");
@@ -181,8 +191,9 @@ void UsbHandler::DeviceLeft(libusb_device* device_libusb) {
}
for (std::list<UsbDeviceListener*>::iterator it =
- usb_device_listeners_.begin();
- it != usb_device_listeners_.end(); ++it) {
+ usb_device_listeners_.begin();
+ it != usb_device_listeners_.end();
+ ++it) {
(*it)->OnDeviceLeft(device);
}
@@ -202,12 +213,13 @@ void UsbHandler::DeviceLeft(libusb_device* device_libusb) {
}
void UsbHandler::StartControlTransferSequence(
- UsbControlTransferSequence* sequence, PlatformUsbDevice* device) {
- LOG4CXX_TRACE(logger_, "enter. UsbControlTransferSequence* " << sequence <<
- "PlatformUsbDevice* " << device);
+ UsbControlTransferSequence* sequence, PlatformUsbDevice* device) {
+ LOG4CXX_TRACE(logger_,
+ "enter. UsbControlTransferSequence* "
+ << sequence << "PlatformUsbDevice* " << device);
TransferSequences::iterator it = transfer_sequences_.insert(
- transfer_sequences_.end(),
- new ControlTransferSequenceState(this, sequence, device));
+ transfer_sequences_.end(),
+ new ControlTransferSequenceState(this, sequence, device));
SubmitControlTransfer(*it);
LOG4CXX_TRACE(logger_, "exit");
}
@@ -216,26 +228,32 @@ void UsbHandler::CloseDeviceHandle(libusb_device_handle* device_handle) {
device_handles_to_close_.push_back(device_handle);
}
-int ArrivedCallback(libusb_context* context, libusb_device* device,
- libusb_hotplug_event event, void* data) {
- LOG4CXX_TRACE(logger_, "enter. libusb device arrived (bus number "
- << static_cast<int>(libusb_get_bus_number(device))
- << ", device address "
- << static_cast<int>(
- libusb_get_device_address(device)) << ")");
+int ArrivedCallback(libusb_context* context,
+ libusb_device* device,
+ libusb_hotplug_event event,
+ void* data) {
+ LOG4CXX_TRACE(logger_,
+ "enter. libusb device arrived (bus number "
+ << static_cast<int>(libusb_get_bus_number(device))
+ << ", device address "
+ << static_cast<int>(libusb_get_device_address(device))
+ << ")");
UsbHandler* usb_handler = static_cast<UsbHandler*>(data);
usb_handler->DeviceArrived(device);
LOG4CXX_TRACE(logger_, "exit with 0");
return 0;
}
-int LeftCallback(libusb_context* context, libusb_device* device,
- libusb_hotplug_event event, void* data) {
- LOG4CXX_TRACE(logger_, "enter libusb device left (bus number "
- << static_cast<int>(libusb_get_bus_number(device))
- << ", device address "
- << static_cast<int>(
- libusb_get_device_address(device)) << ")");
+int LeftCallback(libusb_context* context,
+ libusb_device* device,
+ libusb_hotplug_event event,
+ void* data) {
+ LOG4CXX_TRACE(logger_,
+ "enter libusb device left (bus number "
+ << static_cast<int>(libusb_get_bus_number(device))
+ << ", device address "
+ << static_cast<int>(libusb_get_device_address(device))
+ << ")");
UsbHandler* usb_handler = static_cast<UsbHandler*>(data);
usb_handler->DeviceLeft(device);
LOG4CXX_TRACE(logger_, "exit with 0");
@@ -249,49 +267,63 @@ TransportAdapter::Error UsbHandler::Init() {
if (LIBUSB_SUCCESS != libusb_ret) {
LOG4CXX_ERROR(logger_, "libusb_init failed: " << libusb_ret);
LOG4CXX_TRACE(logger_,
- "exit with TransportAdapter::FAIL. Condition: LIBUSB_SUCCESS != libusb_ret");
+ "exit with TransportAdapter::FAIL. Condition: LIBUSB_SUCCESS "
+ "!= libusb_ret");
return TransportAdapter::FAIL;
}
if (!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)) {
LOG4CXX_ERROR(logger_, "LIBUSB_CAP_HAS_HOTPLUG not supported");
LOG4CXX_TRACE(logger_,
- "exit with TransportAdapter::FAIL. Condition: !libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)");
+ "exit with TransportAdapter::FAIL. Condition: "
+ "!libusb_has_capability(LIBUSB_CAP_HAS_HOTPLUG)");
return TransportAdapter::FAIL;
}
- libusb_ret = libusb_hotplug_register_callback(
- libusb_context_, LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED,
- LIBUSB_HOTPLUG_ENUMERATE, LIBUSB_HOTPLUG_MATCH_ANY,
- LIBUSB_HOTPLUG_MATCH_ANY, LIBUSB_HOTPLUG_MATCH_ANY, ArrivedCallback, this,
- &arrived_callback_handle_);
+ libusb_ret =
+ libusb_hotplug_register_callback(libusb_context_,
+ LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED,
+ LIBUSB_HOTPLUG_ENUMERATE,
+ LIBUSB_HOTPLUG_MATCH_ANY,
+ LIBUSB_HOTPLUG_MATCH_ANY,
+ LIBUSB_HOTPLUG_MATCH_ANY,
+ ArrivedCallback,
+ this,
+ &arrived_callback_handle_);
if (LIBUSB_SUCCESS != libusb_ret) {
LOG4CXX_ERROR(logger_,
"libusb_hotplug_register_callback failed: " << libusb_ret);
LOG4CXX_TRACE(logger_,
- "exit with TransportAdapter::FAIL. Condition: LIBUSB_SUCCESS != libusb_ret");
+ "exit with TransportAdapter::FAIL. Condition: LIBUSB_SUCCESS "
+ "!= libusb_ret");
return TransportAdapter::FAIL;
}
- libusb_ret = libusb_hotplug_register_callback(
- libusb_context_, LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT,
- static_cast<libusb_hotplug_flag>(0), LIBUSB_HOTPLUG_MATCH_ANY,
- LIBUSB_HOTPLUG_MATCH_ANY, LIBUSB_HOTPLUG_MATCH_ANY, LeftCallback, this,
- &left_callback_handle_);
+ libusb_ret =
+ libusb_hotplug_register_callback(libusb_context_,
+ LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT,
+ static_cast<libusb_hotplug_flag>(0),
+ LIBUSB_HOTPLUG_MATCH_ANY,
+ LIBUSB_HOTPLUG_MATCH_ANY,
+ LIBUSB_HOTPLUG_MATCH_ANY,
+ LeftCallback,
+ this,
+ &left_callback_handle_);
if (LIBUSB_SUCCESS != libusb_ret) {
LOG4CXX_ERROR(logger_,
"libusb_hotplug_register_callback failed: " << libusb_ret);
LOG4CXX_TRACE(logger_,
- "exit with TransportAdapter::FAIL. Condition: LIBUSB_SUCCESS != libusb_ret");
+ "exit with TransportAdapter::FAIL. Condition: LIBUSB_SUCCESS "
+ "!= libusb_ret");
return TransportAdapter::FAIL;
}
if (!thread_->start()) {
- LOG4CXX_ERROR(logger_, "USB device scanner thread start failed, error code");
- LOG4CXX_TRACE(logger_,
- "exit with TransportAdapter::FAIL.");
+ LOG4CXX_ERROR(logger_,
+ "USB device scanner thread start failed, error code");
+ LOG4CXX_TRACE(logger_, "exit with TransportAdapter::FAIL.");
return TransportAdapter::FAIL;
}
return TransportAdapter::OK;
@@ -315,7 +347,7 @@ void UsbHandler::Thread() {
}
for (std::list<libusb_device_handle*>::iterator it =
- device_handles_to_close_.begin();
+ device_handles_to_close_.begin();
it != device_handles_to_close_.end();
it = device_handles_to_close_.erase(it)) {
libusb_close(*it);
@@ -327,14 +359,16 @@ void UsbHandler::Thread() {
void UsbTransferSequenceCallback(libusb_transfer* transfer) {
LOG4CXX_TRACE(logger_, "enter. libusb_transfer* " << transfer);
UsbHandler::ControlTransferSequenceState* sequence_state =
- static_cast<UsbHandler::ControlTransferSequenceState*>(transfer->user_data);
+ static_cast<UsbHandler::ControlTransferSequenceState*>(
+ transfer->user_data);
sequence_state->usb_handler()->ControlTransferCallback(transfer);
LOG4CXX_TRACE(logger_, "exit");
}
void UsbHandler::SubmitControlTransfer(
- ControlTransferSequenceState* sequence_state) {
- LOG4CXX_TRACE(logger_, "enter. ControlTransferSequenceState* " << sequence_state);
+ ControlTransferSequenceState* sequence_state) {
+ LOG4CXX_TRACE(logger_,
+ "enter. ControlTransferSequenceState* " << sequence_state);
UsbControlTransfer* transfer = sequence_state->CurrentTransfer();
if (NULL == transfer) {
LOG4CXX_TRACE(logger_, "exit. Condition: NULL == transfer");
@@ -366,7 +400,7 @@ void UsbHandler::SubmitControlTransfer(
const uint16_t length = transfer->Length();
unsigned char* buffer =
- static_cast<unsigned char*>(malloc(length + LIBUSB_CONTROL_SETUP_SIZE));
+ static_cast<unsigned char*>(malloc(length + LIBUSB_CONTROL_SETUP_SIZE));
if (NULL == buffer) {
LOG4CXX_ERROR(logger_, "buffer allocation failed");
libusb_free_transfer(libusb_transfer);
@@ -375,22 +409,26 @@ void UsbHandler::SubmitControlTransfer(
return;
}
- libusb_fill_control_setup(buffer, request_type | endpoint_direction, request,
- value, index, length);
+ libusb_fill_control_setup(
+ buffer, request_type | endpoint_direction, request, value, index, length);
if (0 != length && endpoint_direction == LIBUSB_ENDPOINT_OUT) {
const char* data = static_cast<UsbControlOutTransfer*>(transfer)->Data();
memcpy(buffer + LIBUSB_CONTROL_SETUP_SIZE, data, length);
}
- libusb_fill_control_transfer(
- libusb_transfer, sequence_state->device()->GetLibusbHandle(), buffer,
- UsbTransferSequenceCallback, sequence_state, 0);
+ libusb_fill_control_transfer(libusb_transfer,
+ sequence_state->device()->GetLibusbHandle(),
+ buffer,
+ UsbTransferSequenceCallback,
+ sequence_state,
+ 0);
libusb_transfer->flags = LIBUSB_TRANSFER_FREE_BUFFER;
const int libusb_ret = libusb_submit_transfer(libusb_transfer);
if (LIBUSB_SUCCESS != libusb_ret) {
- LOG4CXX_ERROR(logger_, "libusb_submit_transfer failed: "
- << libusb_error_name(libusb_ret));
+ LOG4CXX_ERROR(
+ logger_,
+ "libusb_submit_transfer failed: " << libusb_error_name(libusb_ret));
libusb_free_transfer(libusb_transfer);
sequence_state->Finish();
}
@@ -400,7 +438,7 @@ void UsbHandler::SubmitControlTransfer(
void UsbHandler::ControlTransferCallback(libusb_transfer* transfer) {
LOG4CXX_TRACE(logger_, "enter. libusb_transfer* " << transfer);
ControlTransferSequenceState* sequence_state =
- static_cast<ControlTransferSequenceState*>(transfer->user_data);
+ static_cast<ControlTransferSequenceState*>(transfer->user_data);
if (transfer->status == LIBUSB_TRANSFER_COMPLETED) {
LOG4CXX_INFO(logger_, "USB control transfer completed");
UsbControlTransfer* current_transfer = sequence_state->CurrentTransfer();
@@ -408,8 +446,8 @@ void UsbHandler::ControlTransferCallback(libusb_transfer* transfer) {
if (current_transfer &&
current_transfer->Direction() == UsbControlTransfer::IN) {
submit_next =
- static_cast<UsbControlInTransfer*>(current_transfer)
- ->OnCompleted(libusb_control_transfer_get_data(transfer));
+ static_cast<UsbControlInTransfer*>(current_transfer)
+ ->OnCompleted(libusb_control_transfer_get_data(transfer));
}
sequence_state->Next();
@@ -427,13 +465,14 @@ void UsbHandler::ControlTransferCallback(libusb_transfer* transfer) {
}
UsbHandler::ControlTransferSequenceState::ControlTransferSequenceState(
- UsbHandler* usb_handler, UsbControlTransferSequence* sequence,
- PlatformUsbDevice* device)
- : usb_handler_(usb_handler),
- device_(device),
- finished_(false),
- sequence_(sequence),
- current_transfer_(sequence->transfers().begin()) {}
+ UsbHandler* usb_handler,
+ UsbControlTransferSequence* sequence,
+ PlatformUsbDevice* device)
+ : usb_handler_(usb_handler)
+ , device_(device)
+ , finished_(false)
+ , sequence_(sequence)
+ , current_transfer_(sequence->transfers().begin()) {}
UsbHandler::ControlTransferSequenceState::~ControlTransferSequenceState() {
delete sequence_;
@@ -448,16 +487,21 @@ UsbControlTransfer* UsbHandler::ControlTransferSequenceState::Next() {
if (++current_transfer_ == sequence_->transfers().end()) {
Finish();
LOG4CXX_TRACE(logger_,
- "exit with NULL. Condition: ++current_transfer_ == sequence_->transfers().end()");
+ "exit with NULL. Condition: ++current_transfer_ == "
+ "sequence_->transfers().end()");
return NULL;
} else {
- LOG4CXX_TRACE(logger_, "exit with UsbControlTransfer* " << *current_transfer_ <<
- ".Condition: ++current_transfer_ !== sequence_->transfers().end()");
+ LOG4CXX_TRACE(logger_,
+ "exit with UsbControlTransfer* "
+ << *current_transfer_
+ << ".Condition: ++current_transfer_ !== "
+ "sequence_->transfers().end()");
return *current_transfer_;
}
}
-UsbControlTransfer* UsbHandler::ControlTransferSequenceState::CurrentTransfer() {
+UsbControlTransfer*
+UsbHandler::ControlTransferSequenceState::CurrentTransfer() {
return finished_ ? NULL : *current_transfer_;
}
@@ -465,10 +509,8 @@ void UsbHandler::ControlTransferSequenceState::Finish() {
finished_ = true;
}
-UsbHandler::UsbHandlerDelegate::UsbHandlerDelegate(
- UsbHandler* handler)
- : handler_(handler) {
-}
+UsbHandler::UsbHandlerDelegate::UsbHandlerDelegate(UsbHandler* handler)
+ : handler_(handler) {}
void UsbHandler::UsbHandlerDelegate::threadMain() {
LOG4CXX_AUTO_TRACE(logger_);
diff --git a/src/components/transport_manager/src/usb/qnx/platform_usb_device.cc b/src/components/transport_manager/src/usb/qnx/platform_usb_device.cc
index 132fe52cae..e85ab12b10 100644
--- a/src/components/transport_manager/src/usb/qnx/platform_usb_device.cc
+++ b/src/components/transport_manager/src/usb/qnx/platform_usb_device.cc
@@ -44,15 +44,16 @@ namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
PlatformUsbDevice::PlatformUsbDevice(
- usbd_device_instance_t* instance, usbd_device* device,
+ usbd_device_instance_t* instance,
+ usbd_device* device,
const usbd_device_descriptor_t& device_descriptor)
- : bus_number_(instance->path),
- address_(instance->devno),
- vendor_id_(instance->ident.vendor),
- product_id_(instance->ident.device),
- device_descriptor_(device_descriptor),
- usbd_device_instance_(*instance),
- usbd_device_(device) {}
+ : bus_number_(instance->path)
+ , address_(instance->devno)
+ , vendor_id_(instance->ident.vendor)
+ , product_id_(instance->ident.device)
+ , device_descriptor_(device_descriptor)
+ , usbd_device_instance_(*instance)
+ , usbd_device_(device) {}
std::string PlatformUsbDevice::GetDescString(uint8_t index) const {
char* str = usbd_string(usbd_device_, index, 0);
diff --git a/src/components/transport_manager/src/usb/qnx/usb_connection.cc b/src/components/transport_manager/src/usb/qnx/usb_connection.cc
index a3844b2e04..516a367ebc 100644
--- a/src/components/transport_manager/src/usb/qnx/usb_connection.cc
+++ b/src/components/transport_manager/src/usb/qnx/usb_connection.cc
@@ -52,30 +52,31 @@ UsbConnection::UsbConnection(const DeviceUID& device_uid,
TransportAdapterController* controller,
const UsbHandlerSptr libusb_handler,
PlatformUsbDevice* device)
- : device_uid_(device_uid),
- app_handle_(app_handle),
- controller_(controller),
- libusb_handler_(libusb_handler),
- usbd_device_(device->GetUsbdDevice()),
- in_pipe_(NULL),
- out_pipe_(NULL),
- in_buffer_(NULL),
- out_buffer_(NULL),
- in_urb_(NULL),
- out_urb_(NULL),
- out_messages_(),
- current_out_message_(),
- out_messages_mutex_(),
- bytes_sent_(0),
- disconnecting_(false),
- pending_in_transfer_(false),
- pending_out_transfer_(false) {
-}
+ : device_uid_(device_uid)
+ , app_handle_(app_handle)
+ , controller_(controller)
+ , libusb_handler_(libusb_handler)
+ , usbd_device_(device->GetUsbdDevice())
+ , in_pipe_(NULL)
+ , out_pipe_(NULL)
+ , in_buffer_(NULL)
+ , out_buffer_(NULL)
+ , in_urb_(NULL)
+ , out_urb_(NULL)
+ , out_messages_()
+ , current_out_message_()
+ , out_messages_mutex_()
+ , bytes_sent_(0)
+ , disconnecting_(false)
+ , pending_in_transfer_(false)
+ , pending_out_transfer_(false) {}
UsbConnection::~UsbConnection() {
Finalise();
- if (in_urb_) usbd_free_urb(in_urb_);
- if (out_urb_) usbd_free_urb(out_urb_);
+ if (in_urb_)
+ usbd_free_urb(in_urb_);
+ if (out_urb_)
+ usbd_free_urb(out_urb_);
if (in_pipe_) {
const int close_pipe_rc = usbd_close_pipe(in_pipe_);
@@ -121,9 +122,9 @@ void UsbConnection::OnInTransfer(usbd_urb* urb) {
LOG4CXX_ERROR(logger_, "Get in urb status failed: " << urb_status_rc);
error = true;
}
- LOG4CXX_INFO(logger_, "USB in transfer, status " << std::hex << status
- << ", length " << std::dec
- << len);
+ LOG4CXX_INFO(logger_,
+ "USB in transfer, status " << std::hex << status << ", length "
+ << std::dec << len);
if (!error) {
switch (status) {
@@ -139,18 +140,19 @@ void UsbConnection::OnInTransfer(usbd_urb* urb) {
if (error) {
LOG4CXX_ERROR(logger_, "USB in transfer failed");
- controller_->DataReceiveFailed(device_uid_, app_handle_,
- DataReceiveError());
+ controller_->DataReceiveFailed(
+ device_uid_, app_handle_, DataReceiveError());
} else {
- ::protocol_handler::RawMessagePtr msg(new protocol_handler::RawMessage(0, 0, in_buffer_, len));
+ ::protocol_handler::RawMessagePtr msg(
+ new protocol_handler::RawMessage(0, 0, in_buffer_, len));
controller_->DataReceiveDone(device_uid_, app_handle_, msg);
}
pending_in_transfer_ = false;
if (!disconnecting_) {
if (!PostInTransfer()) {
- controller_->ConnectionAborted(device_uid_, app_handle_,
- CommunicationError());
+ controller_->ConnectionAborted(
+ device_uid_, app_handle_, CommunicationError());
Disconnect();
}
}
@@ -173,8 +175,8 @@ bool UsbConnection::PostOutTransfer() {
usbd_setup_bulk(out_urb_, URB_DIR_OUT, out_buffer_, len);
LOG4CXX_INFO(logger_, "out transfer :" << len);
pending_out_transfer_ = true;
- const int io_rc = usbd_io(out_urb_, out_pipe_, OutTransferCallback, this,
- USBD_TIME_INFINITY);
+ const int io_rc = usbd_io(
+ out_urb_, out_pipe_, OutTransferCallback, this, USBD_TIME_INFINITY);
if (EOK != io_rc) {
pending_out_transfer_ = false;
usbd_free(out_buffer_);
@@ -194,9 +196,9 @@ void UsbConnection::OnOutTransfer(usbd_urb* urb) {
LOG4CXX_ERROR(logger_, "Get out urb status failed: " << urb_status_rc);
error = true;
}
- LOG4CXX_INFO(logger_, "USB out transfer, status " << std::hex << status
- << ", length " << std::dec
- << len);
+ LOG4CXX_INFO(logger_,
+ "USB out transfer, status " << std::hex << status << ", length "
+ << std::dec << len);
if (!error) {
switch (status) {
@@ -214,14 +216,15 @@ void UsbConnection::OnOutTransfer(usbd_urb* urb) {
if (error) {
LOG4CXX_ERROR(logger_, "USB out transfer failed");
- controller_->DataSendFailed(device_uid_, app_handle_, current_out_message_,
- DataSendError());
+ controller_->DataSendFailed(
+ device_uid_, app_handle_, current_out_message_, DataSendError());
PopOutMessage();
} else {
bytes_sent_ += len;
if (bytes_sent_ == current_out_message_->data_size()) {
- LOG4CXX_INFO(logger_, "USB out transfer, data sent: "
- << current_out_message_.get());
+ LOG4CXX_INFO(
+ logger_,
+ "USB out transfer, data sent: " << current_out_message_.get());
controller_->DataSendDone(device_uid_, app_handle_, current_out_message_);
PopOutMessage();
}
@@ -234,7 +237,8 @@ void UsbConnection::OnOutTransfer(usbd_urb* urb) {
}
}
-TransportAdapter::Error UsbConnection::SendData(::protocol_handler::RawMessagePtr message) {
+TransportAdapter::Error UsbConnection::SendData(
+ ::protocol_handler::RawMessagePtr message) {
if (disconnecting_) {
return TransportAdapter::BAD_STATE;
}
@@ -244,8 +248,8 @@ TransportAdapter::Error UsbConnection::SendData(::protocol_handler::RawMessagePt
} else {
current_out_message_ = message;
if (!PostOutTransfer()) {
- controller_->DataSendFailed(device_uid_, app_handle_, message,
- DataSendError());
+ controller_->DataSendFailed(
+ device_uid_, app_handle_, message, DataSendError());
}
}
return TransportAdapter::OK;
@@ -257,11 +261,14 @@ void UsbConnection::Finalise() {
disconnecting_ = true;
usbd_abort_pipe(in_pipe_);
usbd_abort_pipe(out_pipe_);
- for (std::list<protocol_handler::RawMessagePtr>::iterator it = out_messages_.begin();
- it != out_messages_.end(); it = out_messages_.erase(it)) {
+ for (std::list<protocol_handler::RawMessagePtr>::iterator it =
+ out_messages_.begin();
+ it != out_messages_.end();
+ it = out_messages_.erase(it)) {
controller_->DataSendFailed(device_uid_, app_handle_, *it, DataSendError());
}
- while (pending_in_transfer_ || pending_out_transfer_) sched_yield();
+ while (pending_in_transfer_ || pending_out_transfer_)
+ sched_yield();
}
TransportAdapter::Error UsbConnection::Disconnect() {
@@ -272,7 +279,8 @@ TransportAdapter::Error UsbConnection::Disconnect() {
}
bool UsbConnection::Init() {
- if (!OpenEndpoints()) return false;
+ if (!OpenEndpoints())
+ return false;
in_urb_ = usbd_alloc_urb(NULL);
out_urb_ = usbd_alloc_urb(NULL);
@@ -290,8 +298,8 @@ bool UsbConnection::Init() {
controller_->ConnectDone(device_uid_, app_handle_);
if (!PostInTransfer()) {
- controller_->ConnectionAborted(device_uid_, app_handle_,
- CommunicationError());
+ controller_->ConnectionAborted(
+ device_uid_, app_handle_, CommunicationError());
return true;
}
@@ -315,21 +323,25 @@ bool UsbConnection::OpenEndpoints() {
int cfg = 0;
bool found = false;
while (!found) {
- config_desc =
- usbd_parse_descriptors(usbd_device_, device_desc_node,
- USB_DESC_CONFIGURATION, cfg++, &cfg_desc_node);
+ config_desc = usbd_parse_descriptors(usbd_device_,
+ device_desc_node,
+ USB_DESC_CONFIGURATION,
+ cfg++,
+ &cfg_desc_node);
if (config_desc == NULL) {
break;
}
- LOG4CXX_INFO(logger_, "USB configuration "
- << static_cast<int>(config_desc->configuration
- .bConfigurationValue));
+ LOG4CXX_INFO(logger_,
+ "USB configuration " << static_cast<int>(
+ config_desc->configuration.bConfigurationValue));
int iface = 0;
usbd_desc_node* iface_desc_node;
while (!found) {
- iface_desc =
- usbd_parse_descriptors(usbd_device_, cfg_desc_node,
- USB_DESC_INTERFACE, iface++, &iface_desc_node);
+ iface_desc = usbd_parse_descriptors(usbd_device_,
+ cfg_desc_node,
+ USB_DESC_INTERFACE,
+ iface++,
+ &iface_desc_node);
if (iface_desc == NULL) {
break;
}
@@ -338,11 +350,11 @@ bool UsbConnection::OpenEndpoints() {
#endif
const uint8_t interface_subclass =
iface_desc->interface.bInterfaceSubClass;
- LOG4CXX_INFO(logger_, "USB interface number "
- << static_cast<int>(interface_number)
- << ", subclass " << std::hex
- << static_cast<int>(interface_subclass)
- << std::dec);
+ LOG4CXX_INFO(logger_,
+ "USB interface number "
+ << static_cast<int>(interface_number) << ", subclass "
+ << std::hex << static_cast<int>(interface_subclass)
+ << std::dec);
if (interface_subclass != 0xff) {
continue;
}
@@ -352,15 +364,16 @@ bool UsbConnection::OpenEndpoints() {
while (true) {
usbd_descriptors_t* endpoint_desc = usbd_parse_descriptors(
usbd_device_, iface_desc_node, USB_DESC_ENDPOINT, endpoint++, NULL);
- if (NULL == endpoint_desc) break;
+ if (NULL == endpoint_desc)
+ break;
const uint8_t attributes = endpoint_desc->endpoint.bmAttributes;
if ((attributes & 0x03) == USB_ATTRIB_BULK) {
const uint8_t endpoint_address =
endpoint_desc->endpoint.bEndpointAddress;
- LOG4CXX_INFO(logger_, "Endpoint with address "
- << std::hex
- << static_cast<int>(endpoint_address)
- << std::dec << " found");
+ LOG4CXX_INFO(logger_,
+ "Endpoint with address "
+ << std::hex << static_cast<int>(endpoint_address)
+ << std::dec << " found");
if (endpoint_address & USB_ENDPOINT_IN) {
if (NULL == in_endpoint_desc) {
in_endpoint_desc = endpoint_desc;
@@ -378,7 +391,8 @@ bool UsbConnection::OpenEndpoints() {
}
}
- if (!found) return false;
+ if (!found)
+ return false;
int open_pipe_rc = usbd_open_pipe(usbd_device_, in_endpoint_desc, &in_pipe_);
if (EOK != open_pipe_rc) {
diff --git a/src/components/transport_manager/src/usb/qnx/usb_handler.cc b/src/components/transport_manager/src/usb/qnx/usb_handler.cc
index d78b6c8184..2336a05f16 100644
--- a/src/components/transport_manager/src/usb/qnx/usb_handler.cc
+++ b/src/components/transport_manager/src/usb/qnx/usb_handler.cc
@@ -53,10 +53,10 @@ UsbHandler* usb_handler;
}
UsbHandler::UsbHandler()
- : usb_device_listeners_(),
- devices_(),
- usbd_general_connection_(NULL),
- usbd_aoa_connection_(NULL) {
+ : usb_device_listeners_()
+ , devices_()
+ , usbd_general_connection_(NULL)
+ , usbd_aoa_connection_(NULL) {
usb_handler = this;
}
@@ -65,15 +65,15 @@ UsbHandler::~UsbHandler() {
if (usbd_general_connection_) {
const int disconnect_rc = usbd_disconnect(usbd_general_connection_);
if (EOK != disconnect_rc) {
- LOG4CXX_ERROR(logger_, "usbd_disconnect failed, error code "
- << disconnect_rc);
+ LOG4CXX_ERROR(logger_,
+ "usbd_disconnect failed, error code " << disconnect_rc);
}
}
if (usbd_aoa_connection_) {
const int disconnect_rc = usbd_disconnect(usbd_aoa_connection_);
if (EOK != disconnect_rc) {
- LOG4CXX_ERROR(logger_, "usbd_disconnect failed, error code "
- << disconnect_rc);
+ LOG4CXX_ERROR(logger_,
+ "usbd_disconnect failed, error code " << disconnect_rc);
}
}
}
@@ -87,7 +87,8 @@ void UsbHandler::DeviceArrived(usbd_connection* connection,
usbd_device_instance_t* instance) {
for (Devices::const_iterator it = devices_.begin(); it != devices_.end();
++it) {
- if ((*it)->GetDeviceInstance() == *instance) return;
+ if ((*it)->GetDeviceInstance() == *instance)
+ return;
}
usbd_device* device_usbd = 0;
const int attach_rc = usbd_attach(connection, instance, 0, &device_usbd);
@@ -109,7 +110,8 @@ void UsbHandler::DeviceArrived(usbd_connection* connection,
devices_.push_back(device);
for (std::list<UsbDeviceListener*>::iterator it =
usb_device_listeners_.begin();
- it != usb_device_listeners_.end(); ++it) {
+ it != usb_device_listeners_.end();
+ ++it) {
(*it)->OnDeviceArrived(device);
}
}
@@ -128,7 +130,8 @@ void UsbHandler::DeviceLeft(usbd_device_instance_t* instance) {
for (std::list<UsbDeviceListener*>::iterator it =
usb_device_listeners_.begin();
- it != usb_device_listeners_.end(); ++it) {
+ it != usb_device_listeners_.end();
+ ++it) {
(*it)->OnDeviceLeft(device);
}
@@ -163,7 +166,8 @@ void UsbHandler::StartControlTransferSequence(
for (UsbControlTransferSequence::Transfers::const_iterator it =
sequence->transfers().begin();
- it != sequence->transfers().end(); ++it) {
+ it != sequence->transfers().end();
+ ++it) {
UsbControlTransfer* transfer = *it;
usbd_urb* urb = usbd_alloc_urb(NULL);
@@ -187,15 +191,21 @@ void UsbHandler::StartControlTransferSequence(
UsbControlOutTransfer* out_transfer =
static_cast<UsbControlOutTransfer*>(transfer);
std::copy(out_transfer->Data(),
- out_transfer->Data() + out_transfer->Length(), buf);
+ out_transfer->Data() + out_transfer->Length(),
+ buf);
} else {
assert(0);
}
assert(transfer->Type() == UsbControlTransfer::VENDOR);
- usbd_setup_vendor(urb, flags, transfer->Request(), USB_TYPE_VENDOR,
- transfer->Value(), transfer->Index(), buf,
+ usbd_setup_vendor(urb,
+ flags,
+ transfer->Request(),
+ USB_TYPE_VENDOR,
+ transfer->Value(),
+ transfer->Index(),
+ buf,
transfer->Length());
const int io_rc = usbd_io(urb, usb_pipe, 0, 0, USBD_TIME_DEFAULT);
@@ -211,7 +221,8 @@ void UsbHandler::StartControlTransferSequence(
}
usbd_free(buf);
usbd_free_urb(urb);
- if (!submit_next) break;
+ if (!submit_next)
+ break;
}
usbd_close_pipe(usb_pipe);
@@ -220,56 +231,66 @@ void UsbHandler::StartControlTransferSequence(
void ArrivedCallback(usbd_connection* connection,
usbd_device_instance_t* instance) {
- if (kAoaVid == instance->ident.vendor) return;
- LOG4CXX_INFO(logger_, "USB device arrived (path "
- << static_cast<int>(instance->path) << ", devno "
- << static_cast<int>(instance->devno) << ", config "
- << static_cast<int>(instance->config) << ", iface "
- << static_cast<int>(instance->iface) << ")");
+ if (kAoaVid == instance->ident.vendor)
+ return;
+ LOG4CXX_INFO(logger_,
+ "USB device arrived (path "
+ << static_cast<int>(instance->path) << ", devno "
+ << static_cast<int>(instance->devno) << ", config "
+ << static_cast<int>(instance->config) << ", iface "
+ << static_cast<int>(instance->iface) << ")");
usb_handler->DeviceArrived(connection, instance);
}
void ArrivedAoaCallback(usbd_connection* connection,
usbd_device_instance_t* instance) {
- if (kAoaVid != instance->ident.vendor) return;
- LOG4CXX_INFO(logger_, "USB AOA device arrived (path "
- << static_cast<int>(instance->path) << ", devno "
- << static_cast<int>(instance->devno) << ", config "
- << static_cast<int>(instance->config) << ", iface "
- << static_cast<int>(instance->iface) << ")");
+ if (kAoaVid != instance->ident.vendor)
+ return;
+ LOG4CXX_INFO(logger_,
+ "USB AOA device arrived (path "
+ << static_cast<int>(instance->path) << ", devno "
+ << static_cast<int>(instance->devno) << ", config "
+ << static_cast<int>(instance->config) << ", iface "
+ << static_cast<int>(instance->iface) << ")");
usb_handler->DeviceArrived(connection, instance);
}
void LeftCallback(usbd_connection* connection,
usbd_device_instance_t* instance) {
- if (kAoaVid == instance->ident.vendor) return;
- LOG4CXX_INFO(logger_, "USB device left (path "
- << static_cast<int>(instance->path) << ", devno "
- << static_cast<int>(instance->devno) << ", config "
- << static_cast<int>(instance->config) << ", iface "
- << static_cast<int>(instance->iface) << ")");
+ if (kAoaVid == instance->ident.vendor)
+ return;
+ LOG4CXX_INFO(logger_,
+ "USB device left (path "
+ << static_cast<int>(instance->path) << ", devno "
+ << static_cast<int>(instance->devno) << ", config "
+ << static_cast<int>(instance->config) << ", iface "
+ << static_cast<int>(instance->iface) << ")");
usb_handler->DeviceLeft(instance);
}
void LeftAoaCallback(usbd_connection* connection,
usbd_device_instance_t* instance) {
- if (kAoaVid != instance->ident.vendor) return;
- LOG4CXX_INFO(logger_, "USB AOA device left (path "
- << static_cast<int>(instance->path) << ", devno "
- << static_cast<int>(instance->devno) << ", config "
- << static_cast<int>(instance->config) << ", iface "
- << static_cast<int>(instance->iface) << ")");
+ if (kAoaVid != instance->ident.vendor)
+ return;
+ LOG4CXX_INFO(logger_,
+ "USB AOA device left (path "
+ << static_cast<int>(instance->path) << ", devno "
+ << static_cast<int>(instance->devno) << ", config "
+ << static_cast<int>(instance->config) << ", iface "
+ << static_cast<int>(instance->iface) << ")");
usb_handler->DeviceLeft(instance);
}
TransportAdapter::Error UsbHandler::Init() {
{
- usbd_device_ident_t interest = {
- USBD_CONNECT_WILDCARD, USBD_CONNECT_WILDCARD, kAoaInterfaceSubclass,
- USBD_CONNECT_WILDCARD, USBD_CONNECT_WILDCARD};
+ usbd_device_ident_t interest = {USBD_CONNECT_WILDCARD,
+ USBD_CONNECT_WILDCARD,
+ kAoaInterfaceSubclass,
+ USBD_CONNECT_WILDCARD,
+ USBD_CONNECT_WILDCARD};
usbd_funcs_t funcs = {_USBDI_NFUNCS, ArrivedCallback, LeftCallback, NULL};
- usbd_connect_parm_t cparms = {NULL, USB_VERSION, USBD_VERSION, 0, 0,
- NULL, 0, &interest, &funcs};
+ usbd_connect_parm_t cparms = {
+ NULL, USB_VERSION, USBD_VERSION, 0, 0, NULL, 0, &interest, &funcs};
const int connect_rc = usbd_connect(&cparms, &usbd_general_connection_);
@@ -279,13 +300,15 @@ TransportAdapter::Error UsbHandler::Init() {
}
}
{
- usbd_device_ident_t interest = {
- kAoaVid, USBD_CONNECT_WILDCARD, USBD_CONNECT_WILDCARD,
- kAoaInterfaceSubclass, USBD_CONNECT_WILDCARD};
- usbd_funcs_t funcs = {_USBDI_NFUNCS, ArrivedAoaCallback,
- LeftAoaCallback, NULL};
- usbd_connect_parm_t cparms = {NULL, USB_VERSION, USBD_VERSION, 0, 0,
- NULL, 0, &interest, &funcs};
+ usbd_device_ident_t interest = {kAoaVid,
+ USBD_CONNECT_WILDCARD,
+ USBD_CONNECT_WILDCARD,
+ kAoaInterfaceSubclass,
+ USBD_CONNECT_WILDCARD};
+ usbd_funcs_t funcs = {
+ _USBDI_NFUNCS, ArrivedAoaCallback, LeftAoaCallback, NULL};
+ usbd_connect_parm_t cparms = {
+ NULL, USB_VERSION, USBD_VERSION, 0, 0, NULL, 0, &interest, &funcs};
const int connect_rc = usbd_connect(&cparms, &usbd_aoa_connection_);
diff --git a/src/components/transport_manager/src/usb/usb_aoa_adapter.cc b/src/components/transport_manager/src/usb/usb_aoa_adapter.cc
index 6363fb7bf9..3462b557ce 100644
--- a/src/components/transport_manager/src/usb/usb_aoa_adapter.cc
+++ b/src/components/transport_manager/src/usb/usb_aoa_adapter.cc
@@ -43,14 +43,18 @@ namespace transport_manager {
namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
-UsbAoaAdapter::UsbAoaAdapter()
- : TransportAdapterImpl(new UsbDeviceScanner(this),
- new UsbConnectionFactory(this), 0),
- is_initialised_(false),
- usb_handler_(new UsbHandler()) {
+UsbAoaAdapter::UsbAoaAdapter(resumption::LastState& last_state,
+ const TransportManagerSettings& settings)
+ : TransportAdapterImpl(new UsbDeviceScanner(this),
+ new UsbConnectionFactory(this),
+ NULL,
+ last_state,
+ settings)
+ , is_initialised_(false)
+ , usb_handler_(new UsbHandler()) {
static_cast<UsbDeviceScanner*>(device_scanner_)->SetUsbHandler(usb_handler_);
static_cast<UsbConnectionFactory*>(server_connection_factory_)
- ->SetUsbHandler(usb_handler_);
+ ->SetUsbHandler(usb_handler_);
}
UsbAoaAdapter::~UsbAoaAdapter() {}
@@ -67,14 +71,16 @@ TransportAdapter::Error UsbAoaAdapter::Init() {
LOG4CXX_TRACE(logger_, "enter");
TransportAdapter::Error error = usb_handler_->Init();
if (error != TransportAdapter::OK) {
- LOG4CXX_TRACE(logger_, "exit with error " << error <<
- ". Condition: error != TransportAdapter::OK");
+ LOG4CXX_TRACE(logger_,
+ "exit with error "
+ << error << ". Condition: error != TransportAdapter::OK");
return error;
}
error = TransportAdapterImpl::Init();
if (error != TransportAdapter::OK) {
- LOG4CXX_TRACE(logger_, "exit with error " << error <<
- ". Condition: error != TransportAdapter::OK");
+ LOG4CXX_TRACE(logger_,
+ "exit with error "
+ << error << ". Condition: error != TransportAdapter::OK");
return error;
}
is_initialised_ = true;
diff --git a/src/components/transport_manager/src/usb/usb_connection_factory.cc b/src/components/transport_manager/src/usb/usb_connection_factory.cc
index 4562473536..28992d8f40 100644
--- a/src/components/transport_manager/src/usb/usb_connection_factory.cc
+++ b/src/components/transport_manager/src/usb/usb_connection_factory.cc
@@ -47,8 +47,8 @@ namespace transport_adapter {
CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
UsbConnectionFactory::UsbConnectionFactory(
- TransportAdapterController* controller)
- : controller_(controller), usb_handler_() {}
+ TransportAdapterController* controller)
+ : controller_(controller), usb_handler_() {}
TransportAdapter::Error UsbConnectionFactory::Init() {
return TransportAdapter::OK;
@@ -59,30 +59,38 @@ void UsbConnectionFactory::SetUsbHandler(const UsbHandlerSptr usb_handler) {
}
TransportAdapter::Error UsbConnectionFactory::CreateConnection(
- const DeviceUID& device_uid, const ApplicationHandle& app_handle) {
- LOG4CXX_TRACE(logger_, "enter DeviceUID: " << &device_uid << ", ApplicationHandle: " <<
- &app_handle);
+ const DeviceUID& device_uid, const ApplicationHandle& app_handle) {
+ LOG4CXX_TRACE(logger_,
+ "enter DeviceUID: " << &device_uid
+ << ", ApplicationHandle: " << &app_handle);
DeviceSptr device = controller_->FindDevice(device_uid);
if (!device.valid()) {
LOG4CXX_ERROR(logger_, "device " << device_uid << " not found");
- LOG4CXX_TRACE(logger_,
- "exit with TransportAdapter::BAD_PARAM. Condition: !device.valid()");
+ LOG4CXX_TRACE(
+ logger_,
+ "exit with TransportAdapter::BAD_PARAM. Condition: !device.valid()");
return TransportAdapter::BAD_PARAM;
}
UsbDevice* usb_device = static_cast<UsbDevice*>(device.get());
- UsbConnection* usb_connection =
- new UsbConnection(device_uid, app_handle, controller_, usb_handler_,
- usb_device->usb_device());
+ UsbConnection* usb_connection = new UsbConnection(device_uid,
+ app_handle,
+ controller_,
+ usb_handler_,
+ usb_device->usb_device());
controller_->ConnectionCreated(usb_connection, device_uid, app_handle);
if (usb_connection->Init()) {
LOG4CXX_INFO(logger_, "USB connection initialised");
- LOG4CXX_TRACE(logger_, "exit with TransportAdapter::OK. Condition: USB connection initialised");
+ LOG4CXX_TRACE(logger_,
+ "exit with TransportAdapter::OK. Condition: USB connection "
+ "initialised");
return TransportAdapter::OK;
} else {
- LOG4CXX_TRACE(logger_, "exit with TransportAdapter::FAIL. Condition: USB connection NOT initialised");
+ LOG4CXX_TRACE(logger_,
+ "exit with TransportAdapter::FAIL. Condition: USB connection "
+ "NOT initialised");
return TransportAdapter::FAIL;
}
}
diff --git a/src/components/transport_manager/src/usb/usb_device_scanner.cc b/src/components/transport_manager/src/usb/usb_device_scanner.cc
index dfc9f4697c..092fd29f1a 100644
--- a/src/components/transport_manager/src/usb/usb_device_scanner.cc
+++ b/src/components/transport_manager/src/usb/usb_device_scanner.cc
@@ -47,8 +47,7 @@ CREATE_LOGGERPTR_GLOBAL(logger_, "TransportManager")
class AoaInitSequence : public UsbControlTransferSequence {
public:
AoaInitSequence();
- virtual ~AoaInitSequence() {
- }
+ virtual ~AoaInitSequence() {}
private:
class AoaGetProtocolRequest;
@@ -88,15 +87,12 @@ void UsbDeviceScanner::OnDeviceLeft(PlatformUsbDevice* device) {
}
UsbDeviceScanner::UsbDeviceScanner(TransportAdapterController* controller)
- : controller_(controller) {
-}
+ : controller_(controller) {}
-UsbDeviceScanner::~UsbDeviceScanner() {
-}
+UsbDeviceScanner::~UsbDeviceScanner() {}
class AoaInitSequence::AoaGetProtocolRequest : public UsbControlInTransfer {
- virtual ~AoaGetProtocolRequest() {
- }
+ virtual ~AoaGetProtocolRequest() {}
virtual RequestType Type() const {
return VENDOR;
}
@@ -126,14 +122,10 @@ class AoaInitSequence::AoaGetProtocolRequest : public UsbControlInTransfer {
class AoaInitSequence::AoaSendIdString : public UsbControlOutTransfer {
public:
AoaSendIdString(uint16_t index, const char* string, uint16_t length)
- : index_(index),
- string_(string),
- length_(length) {
- }
+ : index_(index), string_(string), length_(length) {}
private:
- virtual ~AoaSendIdString() {
- }
+ virtual ~AoaSendIdString() {}
virtual RequestType Type() const {
return VENDOR;
}
@@ -158,8 +150,7 @@ class AoaInitSequence::AoaSendIdString : public UsbControlOutTransfer {
};
class AoaInitSequence::AoaTurnIntoAccessoryMode : public UsbControlOutTransfer {
- virtual ~AoaTurnIntoAccessoryMode() {
- }
+ virtual ~AoaTurnIntoAccessoryMode() {}
virtual RequestType Type() const {
return VENDOR;
}
@@ -187,8 +178,7 @@ static char version[] = "1.0";
static char uri[] = "http://www.smartdevicelink.org";
static char serial_num[] = "N000000";
-AoaInitSequence::AoaInitSequence()
- : UsbControlTransferSequence() {
+AoaInitSequence::AoaInitSequence() : UsbControlTransferSequence() {
AddTransfer(new AoaGetProtocolRequest);
AddTransfer(new AoaSendIdString(0, manufacturer, sizeof(manufacturer)));
AddTransfer(new AoaSendIdString(1, model_name, sizeof(model_name)));
@@ -212,13 +202,13 @@ void UsbDeviceScanner::SupportedDeviceFound(PlatformUsbDevice* device) {
devices_mutex_.Acquire();
devices_.push_back(device);
devices_mutex_.Release();
- LOG4CXX_DEBUG(
- logger_,
- "USB device (bus number " << static_cast<int>(device->bus_number())
- << ", address " << static_cast<int>(device->address())
- << ") identified as: " << device->GetManufacturer()
- << ", " << device->GetProductName()
- << ", serial: " << device->GetSerialNumber());
+ LOG4CXX_DEBUG(logger_,
+ "USB device (bus number "
+ << static_cast<int>(device->bus_number()) << ", address "
+ << static_cast<int>(device->address())
+ << ") identified as: " << device->GetManufacturer() << ", "
+ << device->GetProductName()
+ << ", serial: " << device->GetSerialNumber());
UpdateList();
}
@@ -235,9 +225,9 @@ void UsbDeviceScanner::UpdateList() {
DeviceVector device_vector;
devices_mutex_.Acquire();
for (Devices::const_iterator it = devices_.begin(); it != devices_.end();
- ++it) {
- const std::string device_name = (*it)->GetManufacturer() + " "
- + (*it)->GetProductName();
+ ++it) {
+ const std::string device_name =
+ (*it)->GetManufacturer() + " " + (*it)->GetProductName();
std::ostringstream oss;
oss << (*it)->GetManufacturer() << ":" << (*it)->GetProductName() << ":"
<< (*it)->GetSerialNumber();
@@ -251,8 +241,7 @@ void UsbDeviceScanner::UpdateList() {
controller_->SearchDeviceDone(device_vector);
}
-void UsbDeviceScanner::Terminate() {
-}
+void UsbDeviceScanner::Terminate() {}
bool UsbDeviceScanner::IsInitialised() const {
return true;
diff --git a/src/components/transport_manager/test/CMakeLists.txt b/src/components/transport_manager/test/CMakeLists.txt
index c38804e86c..da20f1d43c 100644
--- a/src/components/transport_manager/test/CMakeLists.txt
+++ b/src/components/transport_manager/test/CMakeLists.txt
@@ -32,15 +32,14 @@ if(BUILD_TESTS)
set(TM_TEST_DIR ${COMPONENTS_DIR}/transport_manager/test)
include_directories(
+ include
${LOG4CXX_INCLUDE_DIRECTORY}
${GMOCK_INCLUDE_DIRECTORY}
${COMPONENTS_DIR}/smart_objects/include
${COMPONENTS_DIR}/transport_manager/include
${COMPONENTS_DIR}/utils/include
- ${COMPONENTS_DIR}/include
${COMPONENTS_DIR}/connection_handler/include
${JSONCPP_INCLUDE_DIRECTORY}
- ${CMAKE_BINARY_DIR}
)
set(LIBRARIES
@@ -62,21 +61,17 @@ if (BUILD_BT_SUPPORT)
list(APPEND LIBRARIES bluetooth)
endif()
-if (BUILD_AVAHI_SUPPORT)
- list(APPEND LIBRARIES avahi-client avahi-common)
-endif()
-
set(SOURCES
- ${TM_TEST_DIR}/transport_manager_default_test.cc
- #${TM_TEST_DIR}/transport_manager_impl_test.cc
- #${TM_TEST_DIR}/dnssd_service_browser_test.cc
+ ${TM_TEST_DIR}/transport_manager_impl_test.cc
${TM_TEST_DIR}/transport_adapter_test.cc
- #${TM_TEST_DIR}/transport_adapter_listener_test.cc
+ ${TM_TEST_DIR}/transport_adapter_listener_test.cc
${TM_TEST_DIR}/tcp_transport_adapter_test.cc
${TM_TEST_DIR}/tcp_device_test.cc
- #${TM_TEST_DIR}/tcp_client_listener_test.cc
+ ${TM_TEST_DIR}/tcp_client_listener_test.cc
+ ${TM_TEST_DIR}/transport_manager_default_test.cc
)
create_test("transport_manager_test" "${SOURCES}" "${LIBRARIES}")
file(COPY smartDeviceLink_test.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+file(COPY app_info_storage2 DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
endif()
diff --git a/src/components/transport_manager/test/app_info_storage2 b/src/components/transport_manager/test/app_info_storage2
new file mode 100644
index 0000000000..794c8b90bc
--- /dev/null
+++ b/src/components/transport_manager/test/app_info_storage2
@@ -0,0 +1,99 @@
+{
+ "TransportManager" : {
+ "BluetoothAdapter" : null,
+ "TcpAdapter" : {
+ "devices" : [
+ {
+ "address" : "57.48.0.1",
+ "applications" : [
+ {
+ "port" : "12345"
+ }
+ ],
+ "name" : "unique_device_name0"
+ },
+ {
+ "address" : "57.48.0.2",
+ "applications" : [
+ {
+ "port" : "12345"
+ }
+ ],
+ "name" : "unique_device_name1"
+ },
+ {
+ "address" : "57.48.0.3",
+ "applications" : [
+ {
+ "port" : "12345"
+ }
+ ],
+ "name" : "unique_device_name2"
+ },
+ {
+ "address" : "57.48.0.4",
+ "applications" : [
+ {
+ "port" : "12345"
+ }
+ ],
+ "name" : "unique_device_name3"
+ },
+ {
+ "address" : "57.48.0.5",
+ "applications" : [
+ {
+ "port" : "12345"
+ }
+ ],
+ "name" : "unique_device_name4"
+ },
+ {
+ "address" : "57.48.0.6",
+ "applications" : [
+ {
+ "port" : "12345"
+ }
+ ],
+ "name" : "unique_device_name5"
+ },
+ {
+ "address" : "57.48.0.7",
+ "applications" : [
+ {
+ "port" : "12345"
+ }
+ ],
+ "name" : "unique_device_name6"
+ },
+ {
+ "address" : "57.48.0.8",
+ "applications" : [
+ {
+ "port" : "12345"
+ }
+ ],
+ "name" : "unique_device_name7"
+ },
+ {
+ "address" : "57.48.0.9",
+ "applications" : [
+ {
+ "port" : "12345"
+ }
+ ],
+ "name" : "unique_device_name8"
+ },
+ {
+ "address" : "57.48.0.10",
+ "applications" : [
+ {
+ "port" : "12345"
+ }
+ ],
+ "name" : "unique_device_name9"
+ }
+ ]
+ }
+ }
+}
diff --git a/src/components/transport_manager/test/dnssd_service_browser_test.cc b/src/components/transport_manager/test/dnssd_service_browser_test.cc
deleted file mode 100644
index 6eb2ad45f6..0000000000
--- a/src/components/transport_manager/test/dnssd_service_browser_test.cc
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "gmock/gmock.h"
-
-#include "transport_manager/transport_adapter/transport_adapter_controller.h"
-#include "transport_manager/tcp/dnssd_service_browser.h"
-
-namespace transport_manager {
-namespace transport_adapter {
-
-class MockTransportAdapterController : public TransportAdapterController {
- public:
- MOCK_METHOD1(AddDevice, DeviceSptr(DeviceSptr device));
- MOCK_METHOD1(SearchDeviceDone, void(const DeviceVector& devices));
- MOCK_METHOD1(SearchDeviceFailed, void(const SearchDeviceError& error));
- MOCK_CONST_METHOD1(FindDevice, DeviceSptr(const DeviceUID& device_handle));
- MOCK_METHOD3(ConnectionCreated,
- void(ConnectionSPtr connection, const DeviceUID& device_handle,
- const ApplicationHandle& app_handle));
- MOCK_METHOD2(ConnectDone, void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle));
- MOCK_METHOD3(ConnectFailed, void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const ConnectError& error));
- MOCK_METHOD2(ConnectionFinished, void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle));
- MOCK_METHOD3(ConnectionAborted, void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const CommunicationError& error));
- MOCK_METHOD2(DisconnectDone, void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle));
- MOCK_METHOD3(DataReceiveDone,
- void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const ::protocol_handler::RawMessagePtr message));
- MOCK_METHOD3(DataReceiveFailed, void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const DataReceiveError& error));
- MOCK_METHOD3(DataSendDone,
- void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const ::protocol_handler::RawMessagePtr message));
- MOCK_METHOD4(DataSendFailed,
- void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const ::protocol_handler::RawMessagePtr message,
- const DataSendError& error));
- MOCK_METHOD0(FindNewApplicationsRequest, void());
- MOCK_METHOD0(AckDevices, void());
- MOCK_METHOD1(ApplicationListUpdated, void(const DeviceUID& device_handle));
- MOCK_METHOD2(DeviceDisconnected, void(const DeviceUID& device_handle,
- const DisconnectDeviceError& error));
-};
-
-TEST(DnssdServiceBrowser, DISABLED_Init) {
- // Arrange
- MockTransportAdapterController controller;
- DnssdServiceBrowser dnssd_service_browser(&controller);
- // Check values after creation. Nothing is initialized
- EXPECT_TRUE(NULL == dnssd_service_browser.avahi_service_browser());
- EXPECT_TRUE(NULL == dnssd_service_browser.avahi_threaded_poll());
- EXPECT_TRUE(NULL == dnssd_service_browser.avahi_client());
- // Act
- const TransportAdapter::Error error = dnssd_service_browser.Init();
- ASSERT_EQ(TransportAdapter::OK, error);
-
- while (!dnssd_service_browser.IsInitialised()) {
- sleep(0);
- }
- ASSERT_TRUE(dnssd_service_browser.IsInitialised());
- // Check values are initialized and threaded poll started
- EXPECT_FALSE(NULL == dnssd_service_browser.avahi_service_browser());
- EXPECT_FALSE(NULL == dnssd_service_browser.avahi_threaded_poll());
- EXPECT_FALSE(NULL == dnssd_service_browser.avahi_client());
-}
-
-TEST(DnssdServiceBrowser, DISABLED_IsInitialized_ExpectFalse) {
- // Arrange
- MockTransportAdapterController controller;
- DnssdServiceBrowser dnssd_service_browser(&controller);
- // Check
- EXPECT_FALSE(dnssd_service_browser.IsInitialised());
-}
-
-TEST(DnssdServiceBrowser, DISABLED_Terminate_ExpectTerminated) {
- // Arrange
- MockTransportAdapterController controller;
- DnssdServiceBrowser dnssd_service_browser(&controller);
- // Init service browser and client
- const TransportAdapter::Error error = dnssd_service_browser.Init();
- ASSERT_EQ(TransportAdapter::OK, error);
-
- while (!dnssd_service_browser.IsInitialised()) {
- sleep(0);
- }
- ASSERT_TRUE(dnssd_service_browser.IsInitialised());
- // Client & browser are initialized and successfully started
- EXPECT_FALSE(NULL == dnssd_service_browser.avahi_service_browser());
- EXPECT_FALSE(NULL == dnssd_service_browser.avahi_threaded_poll());
- EXPECT_FALSE(NULL == dnssd_service_browser.avahi_client());
- dnssd_service_browser.Terminate();
- // Checks everything successfully terminated
- EXPECT_TRUE(NULL == dnssd_service_browser.avahi_service_browser());
- EXPECT_TRUE(NULL == dnssd_service_browser.avahi_threaded_poll());
- EXPECT_TRUE(NULL == dnssd_service_browser.avahi_client());
-}
-
-TEST(DnssdServiceBrowser, DISABLED_Scan_ExpectNotSupported) {
- // Arrange
- MockTransportAdapterController controller;
- DnssdServiceBrowser dnssd_service_browser(&controller);
- // At this moment Scan() can only return NOT SUPPORTED value
- EXPECT_EQ(TransportAdapter::NOT_SUPPORTED, dnssd_service_browser.Scan());
-}
-
-} // namespace transport_adapter
-} // namespace transport_manager
diff --git a/src/components/transport_manager/test/include/client_connection_listener_mock.h b/src/components/transport_manager/test/include/client_connection_listener_mock.h
deleted file mode 100644
index 009814f531..0000000000
--- a/src/components/transport_manager/test/include/client_connection_listener_mock.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_CLIENT_CONNECTION_LISTENER_MOCK_H_
-#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_CLIENT_CONNECTION_LISTENER_MOCK_H_
-
-#include "gmock/gmock.h"
-#include "transport_manager/transport_adapter/client_connection_listener.h"
-
-namespace test {
-namespace components {
-namespace transport_manager_test {
-
-class ClientConnectionListenerMock
- : public ::transport_manager::transport_adapter::ClientConnectionListener {
- public:
- MOCK_METHOD0(
- Init, ::transport_manager::transport_adapter::TransportAdapter::Error());
- MOCK_METHOD0(Terminate, void());
- MOCK_CONST_METHOD0(IsInitialised, bool());
- MOCK_METHOD0(
- StartListening,
- ::transport_manager::transport_adapter::TransportAdapter::Error());
- MOCK_METHOD0(
- StopListening,
- ::transport_manager::transport_adapter::TransportAdapter::Error());
-};
-
-} // namespace transport_manager_test
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_CLIENT_CONNECTION_LISTENER_MOCK_H_
diff --git a/src/components/transport_manager/test/include/connection_mock.h b/src/components/transport_manager/test/include/connection_mock.h
deleted file mode 100644
index 9e35e9a008..0000000000
--- a/src/components/transport_manager/test/include/connection_mock.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_CONNECTION_MOCK_H_
-#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_CONNECTION_MOCK_H_
-
-#include "gmock/gmock.h"
-#include "transport_manager/transport_adapter/connection.h"
-
-namespace test {
-namespace components {
-namespace transport_manager_test {
-
-using namespace ::transport_manager::transport_adapter;
-
-class ConnectionMock : public Connection {
- public:
- MOCK_METHOD1(SendData, TransportAdapter::Error(
- ::protocol_handler::RawMessagePtr message));
- MOCK_METHOD0(Disconnect, TransportAdapter::Error());
-};
-
-} // namespace transport_manager_test
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_CONNECTION_MOCK_H_
diff --git a/src/components/transport_manager/test/include/device_mock.h b/src/components/transport_manager/test/include/device_mock.h
deleted file mode 100644
index 53a0ca53fc..0000000000
--- a/src/components/transport_manager/test/include/device_mock.h
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_DEVICE_MOCK_H_
-#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_DEVICE_MOCK_H_
-
-#include "gmock/gmock.h"
-#include "transport_manager/transport_adapter/device.h"
-#include "transport_manager/common.h"
-#include "transport_manager/tcp/tcp_device.h"
-
-namespace test {
-namespace components {
-namespace transport_manager_test {
-
-class DeviceMock : public ::transport_manager::transport_adapter::Device {
- public:
- DeviceMock(const std::string& name, const std::string& unique_device_id)
- : Device(name, unique_device_id) {}
- MOCK_CONST_METHOD1(IsSameAs, bool(const Device* other_device));
- MOCK_CONST_METHOD0(GetApplicationList, std::vector<int>());
- MOCK_METHOD0(Stop, void());
-};
-
-class TCPDeviceMock : public ::transport_manager::transport_adapter::TcpDevice {
- public:
- TCPDeviceMock(const uint32_t& in_addr_t, const std::string& name)
- : TcpDevice(in_addr_t, name) {}
- MOCK_CONST_METHOD1(IsSameAs, bool(const Device* other_device));
- MOCK_CONST_METHOD0(GetApplicationList, std::vector<int>());
- MOCK_METHOD0(Stop, void());
- MOCK_CONST_METHOD1(
- GetApplicationPort,
- int(const ::transport_manager::ApplicationHandle app_handle));
-};
-
-} // namespace transport_manager_test
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_DEVICE_MOCK_H_
diff --git a/src/components/transport_manager/test/include/device_scanner_mock.h b/src/components/transport_manager/test/include/device_scanner_mock.h
deleted file mode 100644
index ea98af7f23..0000000000
--- a/src/components/transport_manager/test/include/device_scanner_mock.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_DEVICE_SCANNER_MOCK_H_
-#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_DEVICE_SCANNER_MOCK_H_
-
-#include "gmock/gmock.h"
-#include "transport_manager/transport_adapter/device_scanner.h"
-
-namespace test {
-namespace components {
-namespace transport_manager_test {
-
-class DeviceScannerMock
- : public ::transport_manager::transport_adapter::DeviceScanner {
- public:
- MOCK_METHOD0(
- Init, ::transport_manager::transport_adapter::TransportAdapter::Error());
- MOCK_METHOD0(
- Scan, ::transport_manager::transport_adapter::TransportAdapter::Error());
- MOCK_METHOD0(Terminate, void());
- MOCK_CONST_METHOD0(IsInitialised, bool());
-};
-
-} // namespace transport_manager_test
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_DEVICE_SCANNER_MOCK_H_
diff --git a/src/components/transport_manager/test/include/mock_application.h b/src/components/transport_manager/test/include/mock_application.h
deleted file mode 100644
index 7ec71ebb1e..0000000000
--- a/src/components/transport_manager/test/include/mock_application.h
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * mock_application.h
- *
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MOCK_APPLICATION_H_
-#define MOCK_APPLICATION_H_
-
-#include <pthread.h>
-
-#include <sstream>
-#include <string>
-
-#include <transport_manager/common.h>
-#include <transport_manager/transport_manager.h>
-#include <transport_manager/transport_adapter/transport_adapter_impl.h>
-#include <transport_manager/transport_manager_impl.h>
-#include "mock_device_scanner.h"
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-class MockDevice;
-using ::transport_manager::ApplicationHandle;
-
-class MockApplication {
- public:
- const MockDevice *device;
- ApplicationHandle handle;
- pthread_t workerThread;
- pthread_cond_t ready_cond;
- pthread_mutex_t ready_mutex;
- int sockfd;
- bool active;
- private:
- std::string socket_name_;
- public:
- MockApplication(const MockDevice* device, ApplicationHandle id);
- void Start();
- void Stop();
- const std::string &socket_name() const {
- return socket_name_;
- }
-};
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
-
-#endif /* MOCK_APPLICATION_H_ */
diff --git a/src/components/transport_manager/test/include/mock_connection.h b/src/components/transport_manager/test/include/mock_connection.h
deleted file mode 100644
index 8f67107065..0000000000
--- a/src/components/transport_manager/test/include/mock_connection.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * \file mock_connection.h
- * \brief
- *
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKCONNECTION_H_
-#define APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKCONNECTION_H_
-
-#include "transport_manager/common.h"
-#include "transport_manager/error.h"
-#include "transport_manager/transport_adapter/transport_adapter_impl.h"
-#include "transport_manager/transport_adapter/threaded_socket_connection.h"
-
-using ::transport_manager::ApplicationHandle;
-using ::transport_manager::DeviceHandle;
-using ::transport_manager::transport_adapter::Connection;
-using ::transport_manager::transport_adapter::TransportAdapterController;
-using ::transport_manager::ConnectError;
-using ::transport_manager::transport_adapter::ThreadedSocketConnection;
-using ::transport_manager::transport_adapter::TransportAdapter;
-namespace test {
-namespace components {
-namespace transport_manager {
-
-class MockTransportAdapter;
-
-class MockConnection : public ThreadedSocketConnection{
- public:
- MockConnection(const ::transport_manager::DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- TransportAdapterController* adapter);
- bool Establish(ConnectError **error);
-};
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
-
-#endif /* APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKCONNECTION_H_ */
diff --git a/src/components/transport_manager/test/include/mock_connection_factory.h b/src/components/transport_manager/test/include/mock_connection_factory.h
deleted file mode 100644
index afead19cb6..0000000000
--- a/src/components/transport_manager/test/include/mock_connection_factory.h
+++ /dev/null
@@ -1,69 +0,0 @@
-/*
- * \file mock_connection_factory.h
- * \brief
- *
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKCONNECTIONFACTORY_H_
-#define APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKCONNECTIONFACTORY_H_
-
-#include "transport_manager/transport_adapter/server_connection_factory.h"
-
-using ::transport_manager::ApplicationHandle;
-using ::transport_manager::DeviceHandle;
-using ::transport_manager::transport_adapter::TransportAdapter;
-using ::transport_manager::transport_adapter::ServerConnectionFactory;
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-class MockTransportAdapter;
-
-class MockConnectionFactory : public ServerConnectionFactory {
- public:
- MockConnectionFactory(MockTransportAdapter *adapter);
- TransportAdapter::Error Init() { return TransportAdapter::OK; }
- TransportAdapter::Error CreateConnection(const ::transport_manager::DeviceUID& device_handle,
- const ApplicationHandle& app_handle);
- void Terminate() {}
- bool IsInitialised() const { return true; }
-
- private:
- MockTransportAdapter *controller_;
-};
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
-
-#endif /* APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKCONNECTIONFACTORY_H_ */
diff --git a/src/components/transport_manager/test/include/mock_device.h b/src/components/transport_manager/test/include/mock_device.h
deleted file mode 100644
index 1225f851d7..0000000000
--- a/src/components/transport_manager/test/include/mock_device.h
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * \file mock_device.h
- * \brief
- *
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKDEVICE_H_
-#define APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKDEVICE_H_
-
-#include "transport_manager/common.h"
-#include "transport_manager/transport_adapter/transport_adapter_impl.h"
-
-#include "gtest/gtest.h"
-#include "gmock/gmock.h"
-#include <transport_manager/transport_adapter/transport_adapter_impl.h>
-#include <transport_manager/transport_manager_impl.h>
-#include "mock_device_scanner.h"
-#include "mock_application.h"
-
-using ::transport_manager::ApplicationList;
-using ::transport_manager::transport_adapter::Device;
-using ::transport_manager::transport_adapter::TransportAdapterController;
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-class MockDevice : public ::transport_manager::transport_adapter::Device {
-
- pthread_mutex_t device_started_mutex;
- std::vector<MockApplication> applications_;
- int applications_cnt_;
- TransportAdapterController *controller_;
- public:
- MockDevice(const std::string& name, const std::string& id,
- TransportAdapterController * controller)
- : Device(name, id),
- applications_cnt_(0),
- controller_(controller) {
- }
- const ApplicationHandle addApplication();
- void Start();
- void Stop();
- bool IsSameAs(const Device* other) const;
- ApplicationList GetApplicationList() const;
- bool operator == (const MockDevice &other);
-};
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
-
-#endif /* APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKDEVICE_H_ */
diff --git a/src/components/transport_manager/test/include/mock_device_scanner.h b/src/components/transport_manager/test/include/mock_device_scanner.h
deleted file mode 100644
index 6ebae39a7c..0000000000
--- a/src/components/transport_manager/test/include/mock_device_scanner.h
+++ /dev/null
@@ -1,76 +0,0 @@
-/*
- * \file mock_device_scanner.h
- * \brief
- *
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKDEVICESCANNER_H_
-#define APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKDEVICESCANNER_H_
-
-#include "transport_manager/transport_adapter/device_scanner.h"
-
-using ::transport_manager::transport_adapter::TransportAdapter;
-using ::transport_manager::transport_adapter::DeviceScanner;
-using ::transport_manager::transport_adapter::DeviceVector;
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-class MockTransportAdapter;
-
-class MockDeviceScanner : public DeviceScanner {
- public:
- MockDeviceScanner(MockTransportAdapter *adapter);
- void reset();
- void AddDevice(const std::string& name, const std::string& unique_id, bool start = true);
- void RemoveDevice(const std::string& name);
- void fail_further_search() { is_search_failed_ = true; }
-
- protected:
- TransportAdapter::Error Init();
- TransportAdapter::Error Scan();
- void Terminate();
- bool IsInitialised() const;
-
- private:
- MockTransportAdapter *controller_;
- DeviceVector devices_;
- bool is_initialized_;
- bool is_search_failed_;
-};
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
-
-#endif /* APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKDEVICESCANNER_H_ */
diff --git a/src/components/transport_manager/test/include/mock_transport_adapter.h b/src/components/transport_manager/test/include/mock_transport_adapter.h
deleted file mode 100644
index 85f0da76dc..0000000000
--- a/src/components/transport_manager/test/include/mock_transport_adapter.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * \file mock_transport_adapter.h
- * \brief
- *
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKDEVICEADAPTER_H_
-#define APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKDEVICEADAPTER_H_
-
-#include "transport_manager/transport_adapter/transport_adapter_impl.h"
-
-using ::transport_manager::transport_adapter::TransportAdapterImpl;
-using ::transport_manager::transport_adapter::DeviceType;
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-class MockDeviceScanner;
-
-class MockTransportAdapter : public TransportAdapterImpl {
- public:
- MockTransportAdapter();
- MockDeviceScanner* get_device_scanner() const;
- DeviceType GetDeviceType() const { return DeviceType::UNKNOWN; }
- void reset();
-};
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
-
-#endif /* APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_MOCKDEVICEADAPTER_H_ */
diff --git a/src/components/transport_manager/test/include/mock_transport_adapter_listener.h b/src/components/transport_manager/test/include/mock_transport_adapter_listener.h
deleted file mode 100644
index 5b68cadaa3..0000000000
--- a/src/components/transport_manager/test/include/mock_transport_adapter_listener.h
+++ /dev/null
@@ -1,94 +0,0 @@
-/*
- * \file mock_transport_adapter_listener.h
- * \brief
- *
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MOCK_transport_adapter_LISTENER_H_
-#define MOCK_transport_adapter_LISTENER_H_
-
-#include <gmock/gmock.h>
-
-#include "transport_manager/transport_adapter/transport_adapter_listener.h"
-
-using namespace transport_manager;
-using transport_manager::transport_adapter::TransportAdapter;
-using transport_manager::transport_adapter::TransportAdapterListener;
-
-namespace test {
-namespace components {
-namespace transport_manager {
-using namespace ::protocol_handler;
-
-class MockTransportAdapterListener : public TransportAdapterListener {
- public:
- MOCK_METHOD1(OnSearchDeviceDone,
- void(const TransportAdapter* transport_adapter));
- MOCK_METHOD0(AckDevices,void());
- MOCK_METHOD2(OnSearchDeviceFailed,
- void(const TransportAdapter* transport_adapter, const SearchDeviceError& error));
- MOCK_METHOD1(OnFindNewApplicationsRequest,
- void(const TransportAdapter* adapter));
- MOCK_METHOD1(OnDeviceListUpdated,
- void(const TransportAdapter* transport_adapter));
- MOCK_METHOD3(OnConnectDone,
- void(const TransportAdapter* transport_adapter, const DeviceUID& device_handle, const ApplicationHandle& app_handle));
- MOCK_METHOD4(OnConnectFailed,
- void(const TransportAdapter* transport_adapter, const DeviceUID& device_handle, const ApplicationHandle& app_handle, const ConnectError& error));
- MOCK_METHOD4(OnUnexpectedDisconnect,
- void(const TransportAdapter* transport_adapter, const DeviceUID& device_handle, const ApplicationHandle& app_handle, const CommunicationError& error));
- MOCK_METHOD3(OnDisconnectDone,
- void(const TransportAdapter* transport_adapter, const DeviceUID& device_handle, const ApplicationHandle& app_handle));
- MOCK_METHOD4(OnDisconnectFailed,
- void(const TransportAdapter* transport_adapter, const DeviceUID& device_handle, const ApplicationHandle& app_handle, const DisconnectError& error));
- MOCK_METHOD2(OnDisconnectDeviceDone,
- void(const TransportAdapter* transport_adapter, const DeviceUID& device_handle));
- MOCK_METHOD3(OnDisconnectDeviceFailed,
- void(const TransportAdapter* transport_adapter, const DeviceUID& device_handle, const DisconnectDeviceError& error));
- MOCK_METHOD4(OnDataSendDone,
- void(const TransportAdapter* transport_adapter, const DeviceUID& device_handle, const ApplicationHandle& app_handle, const RawMessagePtr data_container));
- MOCK_METHOD5(OnDataSendFailed,
- void(const TransportAdapter* transport_adapter, const DeviceUID& device_handle, const ApplicationHandle& app_handle, const RawMessagePtr data_container, const DataSendError& error));
- MOCK_METHOD4(OnDataReceiveDone,
- void(const TransportAdapter* transport_adapter, const DeviceUID& device_handle, const ApplicationHandle& app_handle, const RawMessagePtr data_container));
- MOCK_METHOD4(OnDataReceiveFailed,
- void(const TransportAdapter* transport_adapter, const DeviceUID& device_handle, const ApplicationHandle& app_handle, const DataReceiveError& error));
- MOCK_METHOD3(OnCommunicationError,
- void(const TransportAdapter* transport_adapter, const DeviceUID& device_handle, const ApplicationHandle& app_handle));
- MOCK_METHOD3(OnConnectRequested, void(const TransportAdapter*, const DeviceUID&, const ApplicationHandle&));
-};
-
-}
-}
-}
-
-#endif /* MOCK_transport_adapter_LISTENER_H_ */
diff --git a/src/components/transport_manager/test/include/mock_transport_manager_listener.h b/src/components/transport_manager/test/include/mock_transport_manager_listener.h
deleted file mode 100644
index 9518e1a92a..0000000000
--- a/src/components/transport_manager/test/include/mock_transport_manager_listener.h
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * \file mock_transport_adapter_listener.h
- * \brief
- *
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef MOCK_TRANSPORT_MANAGER_LISTENER_H
-#define MOCK_TRANSPORT_MANAGER_LISTENER_H
-
-#include <gmock/gmock.h>
-
-#include "transport_manager/common.h"
-#include "transport_manager/info.h"
-#include "transport_manager/transport_adapter/transport_adapter.h"
-#include "transport_manager/transport_manager_listener.h"
-
-using ::transport_manager::ApplicationList;
-using ::transport_manager::ApplicationHandle;
-using ::transport_manager::transport_adapter::TransportAdapter;
-using ::transport_manager::SearchDeviceError;
-using ::transport_manager::ConnectionUID;
-using ::transport_manager::ConnectError;
-using ::transport_manager::DisconnectError;
-using ::transport_manager::DisconnectDeviceError;
-using ::transport_manager::DataSendError;
-using ::transport_manager::DataReceiveError;
-using ::transport_manager::CommunicationError;
-using ::transport_manager::DeviceInfo;
-using ::transport_manager::DeviceHandle;
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-class MockTransportManagerListener :
- public ::transport_manager::TransportManagerListener {
- public:
- MOCK_METHOD1(OnDeviceListUpdated, void(const std::vector<DeviceInfo>&));
- MOCK_METHOD0(OnFindNewApplicationsRequest, void());
- MOCK_METHOD1(OnDeviceFound, void(const DeviceInfo &device_info));
- MOCK_METHOD1(OnDeviceAdded, void(const DeviceInfo &device_info));
- MOCK_METHOD1(OnDeviceRemoved, void(const DeviceInfo &device_info));
- MOCK_METHOD0(OnNoDeviceFound, void());
- MOCK_METHOD0(OnScanDevicesFinished, void());
- MOCK_METHOD1(OnScanDevicesFailed, void(const SearchDeviceError& error));
-
- MOCK_METHOD2(OnConnectionEstablished, void(const DeviceInfo& device_info,
- const ConnectionUID &connection_id));
- MOCK_METHOD2(OnConnectionFailed, void(const DeviceInfo& device_info,
- const ConnectError& error));
-
- MOCK_METHOD1(OnConnectionClosed, void(ConnectionUID connection_id));
- MOCK_METHOD2(OnConnectionClosedFailure, void (ConnectionUID connection_id,
- const DisconnectError& error));
- MOCK_METHOD2(OnUnexpectedDisconnect, void (ConnectionUID connection_id,
- const CommunicationError& error));
- MOCK_METHOD2(OnDeviceConnectionLost, void (const DeviceHandle& device,
- const DisconnectDeviceError& error));
- MOCK_METHOD2(OnDisconnectFailed, void (const DeviceHandle& device,
- const DisconnectDeviceError& error));
-
- MOCK_METHOD1(OnTMMessageReceived, void(const RawMessagePtr data_container));
- MOCK_METHOD2(OnTMMessageReceiveFailed, void(ConnectionUID connection_id,
- const DataReceiveError& error));
- MOCK_METHOD1(OnTMMessageSend, void(const RawMessagePtr message));
- MOCK_METHOD2(OnTMMessageSendFailed, void(const DataSendError& error,
- const RawMessagePtr message));
-};
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
-
-#endif /* MOCK_TRANSPORT_MANAGER_LISTENER_H */
diff --git a/src/components/transport_manager/test/include/raw_message_matcher.h b/src/components/transport_manager/test/include/raw_message_matcher.h
deleted file mode 100644
index 89f1cdd182..0000000000
--- a/src/components/transport_manager/test/include/raw_message_matcher.h
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * \file raw_message_matcher.h
- * \brief matcher RawMessagePtr
- *
- * Copyright (c) 2013, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef APPLINK_TEST_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_RAW_MESSAGE_MATCHER_H_
-#define APPLINK_TEST_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_RAW_MESSAGE_MATCHER_H_
-
-#include <gmock/gmock.h>
-
-#include "transport_manager/common.h"
-#include "protocol/common.h"
-
-using ::testing::Matcher;
-using ::testing::MatcherInterface;
-using ::testing::MatchResultListener;
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-using namespace ::protocol_handler;
-
-class RawMessageMatcher : public MatcherInterface<RawMessagePtr> {
- public:
- explicit RawMessageMatcher(RawMessagePtr ptr);
-
- virtual bool MatchAndExplain(const RawMessagePtr ptr,
- MatchResultListener* listener) const;
- virtual void DescribeTo(::std::ostream* os) const;
- virtual void DescribeNegationTo(::std::ostream* os) const;
-
- private:
- const RawMessagePtr ptr_;
-};
-
-inline const Matcher<RawMessagePtr> RawMessageEq(RawMessagePtr msg) {
- return MakeMatcher(new RawMessageMatcher(msg));
-}
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
-
-#endif /* APPLINK_TEST_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_RAW_MESSAGE_MATCHER_H_ */
diff --git a/src/components/transport_manager/test/include/server_connection_factory_mock.h b/src/components/transport_manager/test/include/server_connection_factory_mock.h
deleted file mode 100644
index cbf922e464..0000000000
--- a/src/components/transport_manager/test/include/server_connection_factory_mock.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_SERVER_CONNECTION_FACTORY_MOCK_H_
-#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_SERVER_CONNECTION_FACTORY_MOCK_H_
-
-#include "gmock/gmock.h"
-#include "transport_manager/transport_adapter/server_connection_factory.h"
-
-namespace test {
-namespace components {
-namespace transport_manager_test {
-
-class ServerConnectionFactoryMock : public ::transport_manager::transport_adapter::ServerConnectionFactory {
- public:
- MOCK_METHOD0(Init, ::transport_manager::transport_adapter::TransportAdapter::Error());
- MOCK_METHOD0(Terminate, void());
- MOCK_CONST_METHOD0(IsInitialised, bool());
- MOCK_METHOD2(CreateConnection,
- ::transport_manager::transport_adapter::TransportAdapter::Error(const std::string&,
- const int& app_handle));
-};
-
-} // namespace transport_manager_test
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_SERVER_CONNECTION_FACTORY_MOCK_H_
diff --git a/src/components/transport_manager/test/include/time_metric_observer_mock.h b/src/components/transport_manager/test/include/time_metric_observer_mock.h
deleted file mode 100644
index 5936f8c655..0000000000
--- a/src/components/transport_manager/test/include/time_metric_observer_mock.h
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TIME_METRIC_OBSERVER_MOCK_H_
-#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TIME_METRIC_OBSERVER_MOCK_H_
-
-#include <string>
-#include "gmock/gmock.h"
-#include "transport_manager/time_metric_observer.h"
-#include "protocol/raw_message.h"
-
-namespace test {
-namespace components {
-namespace transport_manager_test {
-
-class TMMetricObserverMock: public ::transport_manager::TMMetricObserver {
- public:
- MOCK_METHOD1(StartRawMsg,
- void(const protocol_handler::RawMessage* ptr));
- MOCK_METHOD1(StopRawMsg,
- void(const protocol_handler::RawMessage* ptr));
-};
-} // namespace transport_manager_test
-} // namespace components
-} // namespace test
-#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TIME_METRIC_OBSERVER_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_adapter_controller_mock.h b/src/components/transport_manager/test/include/transport_adapter_controller_mock.h
deleted file mode 100644
index c0c7155e43..0000000000
--- a/src/components/transport_manager/test/include/transport_adapter_controller_mock.h
+++ /dev/null
@@ -1,92 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_CONTROLLER_MOCK_H_
-#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_CONTROLLER_MOCK_H_
-
-#include "gmock/gmock.h"
-#include "transport_manager/transport_adapter/transport_adapter_controller.h"
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-using namespace ::transport_manager::transport_adapter;
-
-class TransportAdapterControllerMock : public TransportAdapterController {
- public:
- MOCK_METHOD1(AddDevice, DeviceSptr(DeviceSptr device));
- MOCK_METHOD1(SearchDeviceDone, void(DeviceVector device));
- MOCK_METHOD1(ApplicationListUpdated,
- ApplicationListUpdated(const DeviceUID& device_handle));
- MOCK_METHOD0(FindNewApplicationsRequest, void());
- MOCK_METHOD1(SearchDeviceFailed, void(const SearchDeviceError& error));
- MOCK_CONST_METHOD1(FindDevice, DeviceSptr(const DeviceUID& device_handle));
- MOCK_CONST_METHOD3(FindDevice, void(ConnectionSPtr connection,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle));
- MOCK_METHOD2(ConnectDone, void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle));
- MOCK_METHOD3(ConnectFailed, void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const ConnectError& error));
- MOCK_METHOD2(ConnectionFinished, void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle));
- MOCK_METHOD3(ConnectionAborted, void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const CommunicationError& error));
- MOCK_METHOD2(DeviceDisconnected, void(const DeviceUID& device_handle,
- const DisconnectDeviceError& error));
- MOCK_METHOD2(DisconnectDone, void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle));
- MOCK_METHOD3(DataReceiveDone,
- void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- ::protocol_handler::RawMessagePtr message));
- MOCK_METHOD3(DataReceiveFailed, void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const DataReceiveError& error));
- MOCK_METHOD3(DataSendDone, void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- ::protocol_handler::RawMessagePtr message));
- MOCK_METHOD3(DataReceiveFailed,
- void(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- ::protocol_handler::RawMessagePtr message,
- const DataSendError& error));
-};
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_CONTROLLER_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_adapter_listener_mock.h b/src/components/transport_manager/test/include/transport_adapter_listener_mock.h
deleted file mode 100644
index 88b5cf4b66..0000000000
--- a/src/components/transport_manager/test/include/transport_adapter_listener_mock.h
+++ /dev/null
@@ -1,123 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_LISTENER_MOCK_H_
-#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_LISTENER_MOCK_H_
-
-#include "gmock/gmock.h"
-#include "transport_manager/transport_adapter/transport_adapter_listener.h"
-
-namespace test {
-namespace components {
-namespace transport_manager_test {
-
-using namespace transport_manager;
-using transport_adapter::TransportAdapter;
-using transport_adapter::TransportAdapterListener;
-
-class TransportAdapterListenerMock : public TransportAdapterListener {
- public:
- MOCK_METHOD1(OnSearchDeviceDone,
- void(const TransportAdapter* transport_adapter));
- MOCK_METHOD2(OnSearchDeviceFailed,
- void(const TransportAdapter* transport_adapter,
- const SearchDeviceError& error));
- MOCK_METHOD1(OnDeviceListUpdated,
- void(const TransportAdapter* transport_adapter));
- MOCK_METHOD1(OnFindNewApplicationsRequest,
- void(const TransportAdapter* transport_adapter));
- MOCK_METHOD3(OnConnectDone,
- void(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle));
- MOCK_METHOD4(OnConnectFailed,
- void(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const ConnectError& error));
- MOCK_METHOD3(OnConnectRequested,
- void(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle));
- MOCK_METHOD4(OnUnexpectedDisconnect,
- void(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const CommunicationError& error));
- MOCK_METHOD3(OnDisconnectDone,
- void(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle));
- MOCK_METHOD4(OnDisconnectFailed,
- void(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const DisconnectError& error));
- MOCK_METHOD2(OnDisconnectDeviceDone,
- void(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle));
- MOCK_METHOD3(OnDisconnectDeviceFailed,
- void(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const DisconnectDeviceError& error));
- MOCK_METHOD4(OnDataSendDone,
- void(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const ::protocol_handler::RawMessagePtr data_container));
- MOCK_METHOD5(OnDataSendFailed,
- void(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const ::protocol_handler::RawMessagePtr data_container,
- const DataSendError& error));
- MOCK_METHOD4(OnDataReceiveDone,
- void(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const ::protocol_handler::RawMessagePtr data_container));
- MOCK_METHOD4(OnDataReceiveFailed,
- void(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- const DataReceiveError& error));
- MOCK_METHOD3(OnCommunicationError,
- void(const TransportAdapter* transport_adapter,
- const DeviceUID& device_handle,
- const ApplicationHandle& app_handle));
-};
-
-} // namespace transport_manager_test
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_LISTENER_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_adapter_mock.h b/src/components/transport_manager/test/include/transport_adapter_mock.h
deleted file mode 100644
index 86e044d13b..0000000000
--- a/src/components/transport_manager/test/include/transport_adapter_mock.h
+++ /dev/null
@@ -1,104 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_MOCK_H_
-#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_MOCK_H_
-
-#include "gmock/gmock.h"
-#include "transport_manager/transport_adapter/transport_adapter.h"
-
-namespace test {
-namespace components {
-namespace transport_manager_test {
-
-class TransportAdapterMock
- : public ::transport_manager::transport_adapter::TransportAdapter {
- public:
- MOCK_CONST_METHOD0(GetDeviceType,
- ::transport_manager::transport_adapter::DeviceType());
- MOCK_CONST_METHOD0(GetConnectionType, ::transport_manager::ConnectionType());
- MOCK_CONST_METHOD0(IsInitialised, bool());
- MOCK_METHOD0(
- Init, ::transport_manager::transport_adapter::TransportAdapter::Error());
- MOCK_METHOD0(Terminate, void());
- MOCK_METHOD1(
- AddListener,
- void(::transport_manager::transport_adapter::TransportAdapterListener*
- listener));
- MOCK_CONST_METHOD0(IsSearchDevicesSupported, bool());
- MOCK_METHOD0(
- SearchDevices,
- ::transport_manager::transport_adapter::TransportAdapter::Error());
- MOCK_CONST_METHOD0(IsServerOriginatedConnectSupported, bool());
- MOCK_METHOD2(Connect,
- ::transport_manager::transport_adapter::TransportAdapter::Error(
- const ::transport_manager::DeviceUID& device_handle,
- const ::transport_manager::ApplicationHandle& app_handle));
- MOCK_METHOD1(ConnectDevice,
- ::transport_manager::transport_adapter::TransportAdapter::Error(
- const ::transport_manager::DeviceUID& device_handle));
- MOCK_CONST_METHOD0(IsClientOriginatedConnectSupported, bool());
- MOCK_METHOD0(
- StartClientListening,
- ::transport_manager::transport_adapter::TransportAdapter::Error());
- MOCK_METHOD0(
- StopClientListening,
- ::transport_manager::transport_adapter::TransportAdapter::Error());
- MOCK_METHOD2(Disconnect,
- ::transport_manager::transport_adapter::TransportAdapter::Error(
- const ::transport_manager::DeviceUID& device_handle,
- const ::transport_manager::ApplicationHandle& app_handle));
- MOCK_METHOD1(DisconnectDevice,
- Error(const ::transport_manager::DeviceUID& device_handle));
- MOCK_METHOD3(SendData,
- ::transport_manager::transport_adapter::TransportAdapter::Error(
- const ::transport_manager::DeviceUID& device_handle,
- const ::transport_manager::ApplicationHandle& app_handle,
- const protocol_handler::RawMessagePtr data));
- MOCK_CONST_METHOD0(GetDeviceList, ::transport_manager::DeviceList());
- MOCK_CONST_METHOD1(GetApplicationList,
- ::transport_manager::ApplicationList(
- const ::transport_manager::DeviceUID& device_handle));
- MOCK_CONST_METHOD1(
- DeviceName,
- std::string(const ::transport_manager::DeviceUID& device_handle));
-
-#ifdef TIME_TESTER
- MOCK_METHOD0(GetTimeMetricObserver, ::transport_manager::TMMetricObserver*());
-#endif // TIME_TESTER
-};
-
-} // namespace transport_manager_test
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_manager/client_connection_listener_mock.h b/src/components/transport_manager/test/include/transport_manager/client_connection_listener_mock.h
new file mode 100644
index 0000000000..6378e69932
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/client_connection_listener_mock.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_CLIENT_CONNECTION_LISTENER_MOCK_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_CLIENT_CONNECTION_LISTENER_MOCK_H_
+
+#include "gmock/gmock.h"
+#include "transport_manager/transport_adapter/client_connection_listener.h"
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+class MockClientConnectionListener
+ : public ::transport_manager::transport_adapter::ClientConnectionListener {
+ public:
+ MOCK_METHOD0(
+ Init, ::transport_manager::transport_adapter::TransportAdapter::Error());
+ MOCK_METHOD0(Terminate, void());
+ MOCK_CONST_METHOD0(IsInitialised, bool());
+ MOCK_METHOD0(
+ StartListening,
+ ::transport_manager::transport_adapter::TransportAdapter::Error());
+ MOCK_METHOD0(
+ StopListening,
+ ::transport_manager::transport_adapter::TransportAdapter::Error());
+};
+
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_CLIENT_CONNECTION_LISTENER_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_manager/connection_mock.h b/src/components/transport_manager/test/include/transport_manager/connection_mock.h
new file mode 100644
index 0000000000..fbcfcb2271
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/connection_mock.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_CONNECTION_MOCK_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_CONNECTION_MOCK_H_
+
+#include "gmock/gmock.h"
+#include "transport_manager/transport_adapter/connection.h"
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+using namespace ::transport_manager::transport_adapter;
+
+class MockConnection : public Connection {
+ public:
+ MOCK_METHOD1(
+ SendData,
+ TransportAdapter::Error(::protocol_handler::RawMessagePtr message));
+ MOCK_METHOD0(Disconnect, TransportAdapter::Error());
+};
+
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_CONNECTION_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_manager/device_mock.h b/src/components/transport_manager/test/include/transport_manager/device_mock.h
new file mode 100644
index 0000000000..aac28fac11
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/device_mock.h
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_DEVICE_MOCK_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_DEVICE_MOCK_H_
+
+#include "gmock/gmock.h"
+#include "transport_manager/transport_adapter/device.h"
+#include "transport_manager/common.h"
+#include "transport_manager/tcp/tcp_device.h"
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+class MockDevice : public ::transport_manager::transport_adapter::Device {
+ public:
+ MockDevice(const std::string& name, const std::string& unique_device_id)
+ : Device(name, unique_device_id) {}
+ MOCK_CONST_METHOD1(IsSameAs, bool(const Device* other_device));
+ MOCK_CONST_METHOD0(GetApplicationList, std::vector<int>());
+ MOCK_METHOD0(Stop, void());
+};
+
+class MockTCPDevice : public ::transport_manager::transport_adapter::TcpDevice {
+ public:
+ MockTCPDevice(const uint32_t& in_addr_t, const std::string& name)
+ : TcpDevice(in_addr_t, name) {}
+ MOCK_CONST_METHOD1(IsSameAs, bool(const Device* other_device));
+ MOCK_CONST_METHOD0(GetApplicationList, std::vector<int>());
+ MOCK_METHOD0(Stop, void());
+ MOCK_CONST_METHOD1(
+ GetApplicationPort,
+ int(const ::transport_manager::ApplicationHandle app_handle));
+};
+
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_DEVICE_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_manager/device_scanner_mock.h b/src/components/transport_manager/test/include/transport_manager/device_scanner_mock.h
new file mode 100644
index 0000000000..d751994e9a
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/device_scanner_mock.h
@@ -0,0 +1,58 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_DEVICE_SCANNER_MOCK_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_DEVICE_SCANNER_MOCK_H_
+
+#include "gmock/gmock.h"
+#include "transport_manager/transport_adapter/device_scanner.h"
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+class MockDeviceScanner
+ : public ::transport_manager::transport_adapter::DeviceScanner {
+ public:
+ MOCK_METHOD0(
+ Init, ::transport_manager::transport_adapter::TransportAdapter::Error());
+ MOCK_METHOD0(
+ Scan, ::transport_manager::transport_adapter::TransportAdapter::Error());
+ MOCK_METHOD0(Terminate, void());
+ MOCK_CONST_METHOD0(IsInitialised, bool());
+};
+
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_DEVICE_SCANNER_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_manager/mock_telemetry_observer.h b/src/components/transport_manager/test/include/transport_manager/mock_telemetry_observer.h
new file mode 100644
index 0000000000..9d4e86728b
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/mock_telemetry_observer.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TEST_MOCK_TELEMETRY_OBSERVER_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TEST_MOCK_TELEMETRY_OBSERVER_H_
+
+#include "gmock/gmock.h"
+#include "transport_manager/telemetry_observer.h"
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+class MockTMTelemetryObserver
+ : public ::transport_manager::TMTelemetryObserver {
+ public:
+ MOCK_METHOD1(StartRawMsg, void(const protocol_handler::RawMessage* ptr));
+ MOCK_METHOD1(StopRawMsg, void(const protocol_handler::RawMessage* ptr));
+};
+
+} // transport_manager_test
+} // components
+} // test
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_TEST_MOCK_TELEMETRY_OBSERVER_H_
diff --git a/src/components/transport_manager/test/include/transport_manager/mock_transport_adapter_listener.h b/src/components/transport_manager/test/include/transport_manager/mock_transport_adapter_listener.h
new file mode 100644
index 0000000000..c6862c19d6
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/mock_transport_adapter_listener.h
@@ -0,0 +1,128 @@
+/*
+ * \file mock_transport_adapter_listener.h
+ * \brief
+ *
+ * Copyright (c) 2013, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef MOCK_transport_adapter_LISTENER_H_
+#define MOCK_transport_adapter_LISTENER_H_
+
+#include <gmock/gmock.h>
+
+#include "transport_manager/transport_adapter/transport_adapter_listener.h"
+
+using namespace transport_manager;
+using transport_manager::transport_adapter::TransportAdapter;
+using transport_manager::transport_adapter::TransportAdapterListener;
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+using namespace ::protocol_handler;
+
+class MockTransportAdapterListener : public TransportAdapterListener {
+ public:
+ MOCK_METHOD1(OnSearchDeviceDone,
+ void(const TransportAdapter* transport_adapter));
+ MOCK_METHOD0(AckDevices, void());
+ MOCK_METHOD2(OnSearchDeviceFailed,
+ void(const TransportAdapter* transport_adapter,
+ const SearchDeviceError& error));
+ MOCK_METHOD1(OnFindNewApplicationsRequest,
+ void(const TransportAdapter* adapter));
+ MOCK_METHOD1(OnDeviceListUpdated,
+ void(const TransportAdapter* transport_adapter));
+ MOCK_METHOD3(OnConnectDone,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ MOCK_METHOD4(OnConnectFailed,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ConnectError& error));
+ MOCK_METHOD4(OnUnexpectedDisconnect,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const CommunicationError& error));
+ MOCK_METHOD3(OnDisconnectDone,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ MOCK_METHOD4(OnDisconnectFailed,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const DisconnectError& error));
+ MOCK_METHOD2(OnDisconnectDeviceDone,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle));
+ MOCK_METHOD3(OnDisconnectDeviceFailed,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const DisconnectDeviceError& error));
+ MOCK_METHOD4(OnDataSendDone,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const RawMessagePtr data_container));
+ MOCK_METHOD5(OnDataSendFailed,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const RawMessagePtr data_container,
+ const DataSendError& error));
+ MOCK_METHOD4(OnDataReceiveDone,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const RawMessagePtr data_container));
+ MOCK_METHOD4(OnDataReceiveFailed,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const DataReceiveError& error));
+ MOCK_METHOD3(OnCommunicationError,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ MOCK_METHOD3(OnConnectRequested,
+ void(const TransportAdapter*,
+ const DeviceUID&,
+ const ApplicationHandle&));
+};
+}
+}
+}
+
+#endif /* MOCK_transport_adapter_LISTENER_H_ */
diff --git a/src/components/transport_manager/test/include/transport_manager/mock_transport_manager_impl.h b/src/components/transport_manager/test/include/transport_manager/mock_transport_manager_impl.h
new file mode 100644
index 0000000000..e94586a856
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/mock_transport_manager_impl.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_MOCK_TRANSPORT_MANAGER_IMPL_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_MOCK_TRANSPORT_MANAGER_IMPL_H_
+
+#include "gmock/gmock.h"
+#include "config_profile/profile.h"
+#include "transport_manager/transport_manager_impl.h"
+#include "transport_manager/mock_transport_manager_settings.h"
+#include "transport_manager/transport_manager_settings.h"
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+class MockTransportManagerImpl
+ : public ::transport_manager::TransportManagerImpl {
+ public:
+ explicit MockTransportManagerImpl(MockTransportManagerSettings& settings)
+ : ::transport_manager::TransportManagerImpl(settings) {}
+
+ int TestReceiveEventFromDevice(
+ const ::transport_manager::TransportAdapterEvent& event) {
+ return ::transport_manager::TransportManagerImpl::ReceiveEventFromDevice(
+ event);
+ }
+
+ void TestHandle(::transport_manager::TransportAdapterEvent test_event) {
+ Handle(test_event);
+ }
+
+ void TestHandle(::protocol_handler::RawMessagePtr msg) {
+ Handle(msg);
+ }
+};
+
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_MOCK_TRANSPORT_MANAGER_IMPL_H_
diff --git a/src/components/transport_manager/test/include/transport_manager/raw_message_matcher.h b/src/components/transport_manager/test/include/transport_manager/raw_message_matcher.h
new file mode 100644
index 0000000000..8f20afff60
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/raw_message_matcher.h
@@ -0,0 +1,76 @@
+/*
+ * \file raw_message_matcher.h
+ * \brief matcher RawMessagePtr
+ *
+ * Copyright (c) 2013, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef APPLINK_TEST_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_RAW_MESSAGE_MATCHER_H_
+#define APPLINK_TEST_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_RAW_MESSAGE_MATCHER_H_
+
+#include <gmock/gmock.h>
+
+#include "transport_manager/common.h"
+#include "protocol/common.h"
+
+using ::testing::Matcher;
+using ::testing::MatcherInterface;
+using ::testing::MatchResultListener;
+
+namespace test {
+namespace components {
+namespace transport_manager {
+
+using namespace ::protocol_handler;
+
+class RawMessageMatcher : public MatcherInterface<RawMessagePtr> {
+ public:
+ explicit RawMessageMatcher(RawMessagePtr ptr);
+
+ virtual bool MatchAndExplain(const RawMessagePtr ptr,
+ MatchResultListener* listener) const;
+ virtual void DescribeTo(::std::ostream* os) const;
+ virtual void DescribeNegationTo(::std::ostream* os) const;
+
+ private:
+ const RawMessagePtr ptr_;
+};
+
+inline const Matcher<RawMessagePtr> RawMessageEq(RawMessagePtr msg) {
+ return MakeMatcher(new RawMessageMatcher(msg));
+}
+
+} // namespace transport_manager
+} // namespace components
+} // namespace test
+
+#endif /* APPLINK_TEST_COMPONENTS_TRANSPORT_MANAGER_INCLUDE_TRANSPORT_MANAGER_RAW_MESSAGE_MATCHER_H_ \
+ */
diff --git a/src/components/transport_manager/test/include/transport_manager/server_connection_factory_mock.h b/src/components/transport_manager/test/include/transport_manager/server_connection_factory_mock.h
new file mode 100644
index 0000000000..795d9492fc
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/server_connection_factory_mock.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_SERVER_CONNECTION_FACTORY_MOCK_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_SERVER_CONNECTION_FACTORY_MOCK_H_
+
+#include "gmock/gmock.h"
+#include "transport_manager/transport_adapter/server_connection_factory.h"
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+class MockServerConnectionFactory
+ : public ::transport_manager::transport_adapter::ServerConnectionFactory {
+ public:
+ MOCK_METHOD0(
+ Init, ::transport_manager::transport_adapter::TransportAdapter::Error());
+ MOCK_METHOD0(Terminate, void());
+ MOCK_CONST_METHOD0(IsInitialised, bool());
+ MOCK_METHOD2(CreateConnection,
+ ::transport_manager::transport_adapter::TransportAdapter::Error(
+ const std::string&, const int& app_handle));
+};
+
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_SERVER_CONNECTION_FACTORY_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_manager/tcp/mock_tcp_transport_adapter.h b/src/components/transport_manager/test/include/transport_manager/tcp/mock_tcp_transport_adapter.h
new file mode 100644
index 0000000000..432e4f3fa0
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/tcp/mock_tcp_transport_adapter.h
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_TCP_MOCK_TCP_TRANSPORT_ADAPTER_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_TCP_MOCK_TCP_TRANSPORT_ADAPTER_H_
+
+#include "gmock/gmock.h"
+#include "transport_manager/tcp/tcp_transport_adapter.h"
+#include "transport_manager/transport_manager_settings.h"
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+using namespace ::transport_manager::transport_adapter;
+
+class MockTCPTransportAdapter : public TcpTransportAdapter {
+ public:
+ MockTCPTransportAdapter(
+ uint16_t port,
+ resumption::LastState& last_state,
+ const transport_manager::TransportManagerSettings& settings)
+ : TcpTransportAdapter(port, last_state, settings) {}
+ MOCK_CONST_METHOD2(FindEstablishedConnection,
+ ConnectionSPtr(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+
+ MOCK_CONST_METHOD1(FindDevice, DeviceSptr(const DeviceUID& device_handle));
+ MOCK_METHOD2(Connect,
+ TransportAdapter::Error(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ void CallStore() {
+ Store();
+ }
+ bool CallRestore() {
+ return Restore();
+ }
+};
+
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_TCP_MOCK_TCP_TRANSPORT_ADAPTER_H_
diff --git a/src/components/transport_manager/test/include/transport_manager/transport_adapter/mock_transport_adapter_impl.h b/src/components/transport_manager/test/include/transport_manager/transport_adapter/mock_transport_adapter_impl.h
new file mode 100644
index 0000000000..c576c3de6c
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/transport_adapter/mock_transport_adapter_impl.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_ADAPTER_MOCK_TRANSPORT_ADAPTER_IMPL_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_ADAPTER_MOCK_TRANSPORT_ADAPTER_IMPL_H_
+
+#include "gmock/gmock.h"
+#include "transport_manager/transport_adapter/transport_adapter_impl.h"
+#include "transport_manager/transport_manager_settings.h"
+
+using ::transport_manager::transport_adapter::TransportAdapterImpl;
+using ::transport_manager::transport_adapter::DeviceScanner;
+using ::transport_manager::transport_adapter::ServerConnectionFactory;
+using ::transport_manager::transport_adapter::ClientConnectionListener;
+using ::transport_manager::transport_adapter::DeviceType;
+using ::transport_manager::transport_adapter::ConnectionSPtr;
+using ::transport_manager::DeviceUID;
+using ::transport_manager::ApplicationHandle;
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+class MockTransportAdapterImpl : public TransportAdapterImpl {
+ public:
+ MockTransportAdapterImpl(
+ DeviceScanner* device_scanner,
+ ServerConnectionFactory* server_connection_factory,
+ ClientConnectionListener* client_connection_listener,
+ resumption::LastState& last_state,
+ const transport_manager::TransportManagerSettings& settings)
+ : TransportAdapterImpl(device_scanner,
+ server_connection_factory,
+ client_connection_listener,
+ last_state,
+ settings) {}
+
+ ConnectionSPtr FindStatedConnection(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle) {
+ return this->FindEstablishedConnection(device_handle, app_handle);
+ }
+ virtual ~MockTransportAdapterImpl(){};
+
+ virtual DeviceType GetDeviceType() const {
+ return UNKNOWN;
+ }
+
+ MOCK_CONST_METHOD0(Store, void());
+ MOCK_METHOD0(Restore, bool());
+};
+
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_ADAPTER_MOCK_TRANSPORT_ADAPTER_IMPL_H_
diff --git a/src/components/transport_manager/test/include/transport_manager/transport_adapter_controller_mock.h b/src/components/transport_manager/test/include/transport_manager/transport_adapter_controller_mock.h
new file mode 100644
index 0000000000..1dc6839ac9
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/transport_adapter_controller_mock.h
@@ -0,0 +1,101 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_CONTROLLER_MOCK_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_CONTROLLER_MOCK_H_
+
+#include "gmock/gmock.h"
+#include "transport_manager/transport_adapter/transport_adapter_controller.h"
+
+namespace test {
+namespace components {
+namespace transport_manager {
+
+using namespace ::transport_manager::transport_adapter;
+
+class TransportAdapterControllerMock : public TransportAdapterController {
+ public:
+ MOCK_METHOD1(AddDevice, DeviceSptr(DeviceSptr device));
+ MOCK_METHOD1(SearchDeviceDone, void(DeviceVector device));
+ MOCK_METHOD1(ApplicationListUpdated,
+ ApplicationListUpdated(const DeviceUID& device_handle));
+ MOCK_METHOD0(FindNewApplicationsRequest, void());
+ MOCK_METHOD1(SearchDeviceFailed, void(const SearchDeviceError& error));
+ MOCK_CONST_METHOD1(FindDevice, DeviceSptr(const DeviceUID& device_handle));
+ MOCK_CONST_METHOD3(FindDevice,
+ void(ConnectionSPtr connection,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ MOCK_METHOD2(ConnectDone,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ MOCK_METHOD3(ConnectFailed,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ConnectError& error));
+ MOCK_METHOD2(ConnectionFinished,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ MOCK_METHOD3(ConnectionAborted,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const CommunicationError& error));
+ MOCK_METHOD2(DeviceDisconnected,
+ void(const DeviceUID& device_handle,
+ const DisconnectDeviceError& error));
+ MOCK_METHOD2(DisconnectDone,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ MOCK_METHOD3(DataReceiveDone,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ ::protocol_handler::RawMessagePtr message));
+ MOCK_METHOD3(DataReceiveFailed,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const DataReceiveError& error));
+ MOCK_METHOD3(DataSendDone,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ ::protocol_handler::RawMessagePtr message));
+ MOCK_METHOD3(DataReceiveFailed,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ ::protocol_handler::RawMessagePtr message,
+ const DataSendError& error));
+};
+
+} // namespace transport_manager
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_CONTROLLER_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_manager/transport_adapter_listener_mock.h b/src/components/transport_manager/test/include/transport_manager/transport_adapter_listener_mock.h
new file mode 100644
index 0000000000..a2577ad9ee
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/transport_adapter_listener_mock.h
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_LISTENER_MOCK_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_LISTENER_MOCK_H_
+
+#include "gmock/gmock.h"
+#include "transport_manager/transport_adapter/transport_adapter_listener.h"
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+namespace tm = transport_manager;
+namespace ta = tm::transport_adapter;
+using ta::TransportAdapter;
+using ta::TransportAdapterListener;
+using tm::SearchDeviceError;
+using tm::DeviceUID;
+using tm::ApplicationHandle;
+using tm::ConnectError;
+using tm::CommunicationError;
+using tm::DisconnectError;
+using tm::DisconnectDeviceError;
+using tm::DataSendError;
+using tm::DataReceiveError;
+
+class MockTransportAdapterListener : public TransportAdapterListener {
+ public:
+ MOCK_METHOD1(OnSearchDeviceDone,
+ void(const TransportAdapter* transport_adapter));
+ MOCK_METHOD2(OnSearchDeviceFailed,
+ void(const TransportAdapter* transport_adapter,
+ const SearchDeviceError& error));
+ MOCK_METHOD1(OnDeviceListUpdated,
+ void(const TransportAdapter* transport_adapter));
+ MOCK_METHOD1(OnFindNewApplicationsRequest,
+ void(const TransportAdapter* transport_adapter));
+ MOCK_METHOD3(OnConnectDone,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ MOCK_METHOD4(OnConnectFailed,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ConnectError& error));
+ MOCK_METHOD3(OnConnectRequested,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ MOCK_METHOD4(OnUnexpectedDisconnect,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const CommunicationError& error));
+ MOCK_METHOD3(OnDisconnectDone,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ MOCK_METHOD4(OnDisconnectFailed,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const DisconnectError& error));
+ MOCK_METHOD2(OnDisconnectDeviceDone,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle));
+ MOCK_METHOD3(OnDisconnectDeviceFailed,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const DisconnectDeviceError& error));
+ MOCK_METHOD4(OnDataSendDone,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ::protocol_handler::RawMessagePtr data_container));
+ MOCK_METHOD5(OnDataSendFailed,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ::protocol_handler::RawMessagePtr data_container,
+ const DataSendError& error));
+ MOCK_METHOD4(OnDataReceiveDone,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ::protocol_handler::RawMessagePtr data_container));
+ MOCK_METHOD4(OnDataReceiveFailed,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const DataReceiveError& error));
+ MOCK_METHOD3(OnCommunicationError,
+ void(const TransportAdapter* transport_adapter,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+};
+
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_LISTENER_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_manager/transport_adapter_mock.h b/src/components/transport_manager/test/include/transport_manager/transport_adapter_mock.h
new file mode 100644
index 0000000000..d12741f49a
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/transport_adapter_mock.h
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_MOCK_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_MOCK_H_
+
+#include "gmock/gmock.h"
+#include "transport_manager/transport_adapter/transport_adapter.h"
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+class MockTransportAdapter
+ : public ::transport_manager::transport_adapter::TransportAdapter {
+ public:
+ MOCK_CONST_METHOD0(GetDeviceType,
+ ::transport_manager::transport_adapter::DeviceType());
+ MOCK_CONST_METHOD0(GetConnectionType, ::transport_manager::ConnectionType());
+ MOCK_CONST_METHOD0(IsInitialised, bool());
+ MOCK_METHOD0(
+ Init, ::transport_manager::transport_adapter::TransportAdapter::Error());
+ MOCK_METHOD0(Terminate, void());
+ MOCK_METHOD1(
+ AddListener,
+ void(::transport_manager::transport_adapter::TransportAdapterListener*
+ listener));
+ MOCK_CONST_METHOD0(IsSearchDevicesSupported, bool());
+ MOCK_METHOD0(
+ SearchDevices,
+ ::transport_manager::transport_adapter::TransportAdapter::Error());
+ MOCK_CONST_METHOD0(IsServerOriginatedConnectSupported, bool());
+ MOCK_METHOD2(Connect,
+ ::transport_manager::transport_adapter::TransportAdapter::Error(
+ const ::transport_manager::DeviceUID& device_handle,
+ const ::transport_manager::ApplicationHandle& app_handle));
+ MOCK_METHOD1(ConnectDevice,
+ ::transport_manager::transport_adapter::TransportAdapter::Error(
+ const ::transport_manager::DeviceUID& device_handle));
+ MOCK_CONST_METHOD0(IsClientOriginatedConnectSupported, bool());
+ MOCK_METHOD0(
+ StartClientListening,
+ ::transport_manager::transport_adapter::TransportAdapter::Error());
+ MOCK_METHOD0(
+ StopClientListening,
+ ::transport_manager::transport_adapter::TransportAdapter::Error());
+ MOCK_METHOD2(RemoveFinalizedConnection,
+ void(const ::transport_manager::DeviceUID& device_handle,
+ const ::transport_manager::ApplicationHandle& app_handle));
+ MOCK_METHOD2(Disconnect,
+ ::transport_manager::transport_adapter::TransportAdapter::Error(
+ const ::transport_manager::DeviceUID& device_handle,
+ const ::transport_manager::ApplicationHandle& app_handle));
+ MOCK_METHOD1(DisconnectDevice,
+ Error(const ::transport_manager::DeviceUID& device_handle));
+ MOCK_METHOD3(SendData,
+ ::transport_manager::transport_adapter::TransportAdapter::Error(
+ const ::transport_manager::DeviceUID& device_handle,
+ const ::transport_manager::ApplicationHandle& app_handle,
+ const protocol_handler::RawMessagePtr data));
+ MOCK_CONST_METHOD0(GetDeviceList, ::transport_manager::DeviceList());
+ MOCK_CONST_METHOD1(GetApplicationList,
+ ::transport_manager::ApplicationList(
+ const ::transport_manager::DeviceUID& device_handle));
+ MOCK_CONST_METHOD1(
+ DeviceName,
+ std::string(const ::transport_manager::DeviceUID& device_handle));
+
+#ifdef TELEMETRY_MONITOR
+ MOCK_METHOD0(GetTelemetryObserver,
+ ::transport_manager::TMTelemetryObserver*());
+#endif // TELEMETRY_MONITOR
+};
+
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_ADAPTER_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_manager/transport_manager_impl_mock.h b/src/components/transport_manager/test/include/transport_manager/transport_manager_impl_mock.h
new file mode 100644
index 0000000000..e5b0468968
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/transport_manager_impl_mock.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_TRANSPORT_MANAGER_IMPL_MOCK_H_
+#define APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_TRANSPORT_MANAGER_IMPL_MOCK_H_
+
+#include "gmock/gmock.h"
+#include "transport_manager/transport_manager_impl.h"
+
+namespace test {
+namespace components {
+namespace transport_manager {
+
+using namespace ::transport_manager;
+
+class TransportManagerImplMock : public TransportManagerImpl {
+ public:
+ MOCK_METHOD1(ReceiveEventFromDevice, int(const TransportAdapterEvent& event));
+};
+
+} // namespace transport_manager
+} // namespace components
+} // namespace test
+
+#endif // APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_TRANSPORT_MANAGER_IMPL_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_manager/transport_manager_listener_mock.h b/src/components/transport_manager/test/include/transport_manager/transport_manager_listener_mock.h
new file mode 100644
index 0000000000..30f602119d
--- /dev/null
+++ b/src/components/transport_manager/test/include/transport_manager/transport_manager_listener_mock.h
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_LISTENER_MOCK_H_
+#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_LISTENER_MOCK_H_
+
+#include <vector>
+#include <gmock/gmock.h>
+#include "transport_manager/transport_manager_listener.h"
+#include "protocol/raw_message.h"
+
+namespace test {
+namespace components {
+namespace transport_manager_test {
+
+using namespace transport_manager;
+using ::protocol_handler::RawMessage;
+using ::protocol_handler::RawMessagePtr;
+
+class TransportManagerListenerMock : public TransportManagerListener {
+ public:
+ MOCK_METHOD1(OnDeviceListUpdated,
+ void(const std::vector<DeviceInfo>& device_info));
+ MOCK_METHOD0(OnFindNewApplicationsRequest, void());
+ MOCK_METHOD1(OnDeviceFound, void(const DeviceInfo& device_info));
+ MOCK_METHOD1(OnDeviceAdded, void(const DeviceInfo& device_info));
+ MOCK_METHOD1(OnDeviceRemoved, void(const DeviceInfo& device_info));
+ MOCK_METHOD0(OnScanDevicesFinished, void());
+ MOCK_METHOD1(OnScanDevicesFailed, void(const SearchDeviceError& error));
+ MOCK_METHOD2(OnConnectionEstablished,
+ void(const DeviceInfo& device_info,
+ const ConnectionUID connection_id));
+ MOCK_METHOD2(OnConnectionFailed,
+ void(const DeviceInfo& device_info, const ConnectError& error));
+ MOCK_METHOD1(OnConnectionClosed, void(const ConnectionUID connection_id));
+ MOCK_METHOD2(OnUnexpectedDisconnect,
+ void(const ConnectionUID connection_id,
+ const CommunicationError& error));
+ MOCK_METHOD2(OnConnectionClosedFailure,
+ void(const ConnectionUID connection_id,
+ const DisconnectError& error));
+ MOCK_METHOD2(OnDeviceConnectionLost,
+ void(const DeviceHandle& device,
+ const DisconnectDeviceError& error));
+ MOCK_METHOD2(OnDisconnectFailed,
+ void(const DeviceHandle& device,
+ const DisconnectDeviceError& error));
+ MOCK_METHOD1(OnTMMessageReceived,
+ void(const ::protocol_handler::RawMessagePtr message));
+ MOCK_METHOD1(OnTMMessageReceiveFailed, void(const DataReceiveError& error));
+ MOCK_METHOD1(OnTMMessageSend,
+ void(const ::protocol_handler::RawMessagePtr message));
+ MOCK_METHOD2(OnTMMessageSendFailed,
+ void(const DataSendError& error,
+ const ::protocol_handler::RawMessagePtr message));
+};
+
+} // namespace transport_manager_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_LISTENER_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_manager_impl_mock.h b/src/components/transport_manager/test/include/transport_manager_impl_mock.h
deleted file mode 100644
index bb73f1fa49..0000000000
--- a/src/components/transport_manager/test/include/transport_manager_impl_mock.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_TRANSPORT_MANAGER_IMPL_MOCK_H_
-#define APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_TRANSPORT_MANAGER_IMPL_MOCK_H_
-
-#include "gmock/gmock.h"
-#include "transport_manager/transport_manager_impl.h"
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-using namespace ::transport_manager;
-
-class TransportManagerImplMock : public TransportManagerImpl {
- public:
- MOCK_METHOD1(ReceiveEventFromDevice, int(const TransportAdapterEvent& event));
-};
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
-
-#endif // APPLINK_TEST_COMPONENTS_TRANSPORTMANAGER_INCLUDE_TRANSPORT_MANAGER_IMPL_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_manager_listener_mock.h b/src/components/transport_manager/test/include/transport_manager_listener_mock.h
deleted file mode 100644
index 29758159f1..0000000000
--- a/src/components/transport_manager/test/include/transport_manager_listener_mock.h
+++ /dev/null
@@ -1,89 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_LISTENER_MOCK_H_
-#define SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_LISTENER_MOCK_H_
-
-#include <vector>
-#include <gmock/gmock.h>
-#include "transport_manager/transport_manager_listener.h"
-#include "protocol/raw_message.h"
-
-namespace test {
-namespace components {
-namespace transport_manager_test {
-
-using namespace transport_manager;
-using ::protocol_handler::RawMessage;
-using ::protocol_handler::RawMessagePtr;
-
-class TransportManagerListenerMock : public TransportManagerListener {
- public:
- MOCK_METHOD1(OnDeviceListUpdated, void(const std::vector<DeviceInfo>&));
- MOCK_METHOD0(OnFindNewApplicationsRequest, void());
- MOCK_METHOD1(OnDeviceFound, void(const DeviceInfo& device_info));
- MOCK_METHOD1(OnDeviceAdded, void(const DeviceInfo& device_info));
- MOCK_METHOD1(OnDeviceRemoved, void(const DeviceInfo& device_info));
- MOCK_METHOD0(OnNoDeviceFound, void());
- MOCK_METHOD0(OnScanDevicesFinished, void());
- MOCK_METHOD1(OnScanDevicesFailed, void(const SearchDeviceError& error));
-
- MOCK_METHOD2(OnConnectionEstablished,
- void(const DeviceInfo& device_info,
- const ConnectionUID& connection_id));
- MOCK_METHOD2(OnConnectionFailed,
- void(const DeviceInfo& device_info, const ConnectError& error));
-
- MOCK_METHOD1(OnConnectionClosed, void(ConnectionUID connection_id));
- MOCK_METHOD2(OnConnectionClosedFailure,
- void(ConnectionUID connection_id, const DisconnectError& error));
- MOCK_METHOD2(OnUnexpectedDisconnect, void(ConnectionUID connection_id,
- const CommunicationError& error));
- MOCK_METHOD2(OnDeviceConnectionLost,
- void(const DeviceHandle& device,
- const DisconnectDeviceError& error));
- MOCK_METHOD2(OnDisconnectFailed, void(const DeviceHandle& device,
- const DisconnectDeviceError& error));
-
- MOCK_METHOD1(OnTMMessageReceived, void(const RawMessagePtr data_container));
- MOCK_METHOD2(OnTMMessageReceiveFailed, void(ConnectionUID connection_id,
- const DataReceiveError& error));
- MOCK_METHOD1(OnTMMessageSend, void(const RawMessagePtr message));
- MOCK_METHOD2(OnTMMessageSendFailed,
- void(const DataSendError& error, const RawMessagePtr message));
-};
-
-} // namespace transport_manager_test
-} // namespace components
-} // namespace test
-
-#endif // SRC_COMPONENTS_TRANSPORT_MANAGER_TEST_INCLUDE_TRANSPORT_MANAGER_LISTENER_MOCK_H_
diff --git a/src/components/transport_manager/test/include/transport_manager_mock.h b/src/components/transport_manager/test/include/transport_manager_mock.h
deleted file mode 100644
index 6593f992de..0000000000
--- a/src/components/transport_manager/test/include/transport_manager_mock.h
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef TEST_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_MOCK_H_
-#define TEST_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_MOCK_H_
-
-#include <gmock/gmock.h>
-#include <string>
-#include "transport_manager/transport_manager.h"
-#include "transport_manager/transport_adapter/transport_adapter_event.h"
-
-namespace test {
-namespace components {
-namespace transport_manager_test {
-
-using ::transport_manager::DeviceHandle;
-using ::transport_manager::ConnectionUID;
-using ::transport_manager::transport_adapter::TransportAdapter;
-using ::transport_manager::TransportAdapterEvent;
-using ::transport_manager::TransportManagerListener;
-/*
- * MOCK implementation of ::transport_manager::TransportManager interface
- */
-class TransportManagerMock: public ::transport_manager::TransportManager {
- public:
- MOCK_METHOD0(Init,
- int());
- MOCK_METHOD0(Reinit,
- int());
- MOCK_METHOD0(SearchDevices,
- int());
- MOCK_METHOD1(ConnectDevice,
- int(const DeviceHandle &));
- MOCK_METHOD1(DisconnectDevice,
- int(const DeviceHandle &));
- MOCK_METHOD1(Disconnect,
- int(const ConnectionUID &));
- MOCK_METHOD1(DisconnectForce,
- int(const ConnectionUID &));
- MOCK_METHOD1(SendMessageToDevice,
- int(const ::protocol_handler::RawMessagePtr));
- MOCK_METHOD1(ReceiveEventFromDevice,
- int(const TransportAdapterEvent&));
- MOCK_METHOD1(AddTransportAdapter,
- int(TransportAdapter *));
- MOCK_METHOD1(AddEventListener,
- int(TransportManagerListener *));
- MOCK_METHOD0(Stop,
- int());
- MOCK_METHOD1(RemoveDevice,
- int(const DeviceHandle &));
- MOCK_CONST_METHOD1(Visibility,
- int(const bool &));
-};
-} // namespace transport_manager_test
-} // namespace components
-} // namespace test
-#endif // TEST_COMPONENTS_INCLUDE_TRANSPORT_MANAGER_TRANSPORT_MANAGER_MOCK_H_
diff --git a/src/components/transport_manager/test/mock_application.cc b/src/components/transport_manager/test/mock_application.cc
deleted file mode 100644
index 72f99cb744..0000000000
--- a/src/components/transport_manager/test/mock_application.cc
+++ /dev/null
@@ -1,147 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <pthread.h>
-#include <sys/socket.h>
-#include <sys/un.h>
-
-#include "include/mock_application.h"
-#include "include/mock_device.h"
-
-namespace {
-
-struct workerData {
- int sockfd;
-};
-
-void *applicationWorker(void *p) {
- workerData *data = static_cast<workerData*>(p);
- char *buf = new char[2 * 1024 * 1024];
- ssize_t len;
-
- while (true) {
- len = recv(data->sockfd, buf, 2 * 1024 * 1024, 0);
- if (len == 0)
- break;
- send(data->sockfd, buf, len, 0);
- }
- delete[] buf;
- delete data;
- return NULL;
-}
-
-void * applicationListener(void *p) {
- using test::components::transport_manager::MockApplication;
- MockApplication *app = static_cast<MockApplication*>(p);
-
- unlink(app->socket_name().c_str());
-
- app->sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
- if (app->sockfd == -1) {
- // TODO: indicate error
- return NULL;
- }
- sockaddr_un my_addr;
- memset(&my_addr, 0, sizeof(my_addr));
- strcpy(my_addr.sun_path, app->socket_name().c_str());
- my_addr.sun_family = AF_UNIX;
- int res = bind(app->sockfd, reinterpret_cast<sockaddr*>(&my_addr),
- sizeof(my_addr));
- if (res == -1) {
- return NULL;
- }
-
- res = listen(app->sockfd, 5);
- if (res == -1) {
- return NULL;
- }
-
- pthread_mutex_lock(&app->ready_mutex);
- app->active = true;
- pthread_cond_signal(&app->ready_cond);
- pthread_mutex_unlock(&app->ready_mutex);
-
- while (app->active) {
- socklen_t addr_size;
- sockaddr peer_addr;
-
- int peer_socket = accept(app->sockfd, &peer_addr, &addr_size);
- if (peer_socket != -1) {
- pthread_t t;
- workerData* data = new workerData();
- data->sockfd = peer_socket;
- pthread_create(&t, NULL, &applicationWorker, data);
- }
- }
-
- unlink(app->socket_name().c_str());
-
- return NULL;
-}
-}
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-MockApplication::MockApplication(const MockDevice *device, ApplicationHandle id)
- : device(device),
- handle(id),
- workerThread(0),
- sockfd(-1),
- active(false) {
- std::ostringstream oss;
- oss << "mockDevice" << device->unique_device_id() << "-" << id;
- socket_name_ = oss.str();
-}
-
-void MockApplication::Start() {
-
- pthread_cond_init(&ready_cond, NULL);
- pthread_mutex_init(&ready_mutex, NULL);
-
- pthread_mutex_lock(&ready_mutex);
- pthread_create(&workerThread, NULL, &applicationListener, this);
- pthread_cond_wait(&ready_cond, &ready_mutex);
- pthread_mutex_unlock(&ready_mutex);
-}
-
-void MockApplication::Stop() {
- active = false;
- shutdown(sockfd, SHUT_RDWR);
- close(sockfd);
- pthread_join(workerThread, NULL);
-}
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
diff --git a/src/components/transport_manager/test/mock_connection.cc b/src/components/transport_manager/test/mock_connection.cc
deleted file mode 100644
index 8f385764a0..0000000000
--- a/src/components/transport_manager/test/mock_connection.cc
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <cstring>
-
-#include <sys/socket.h>
-#include <sys/un.h>
-#include <sstream>
-#include "transport_manager/common.h"
-#include "include/mock_connection.h"
-
-#include <algorithm>
-
-#include "include/mock_transport_adapter.h"
-
-using ::transport_manager::transport_adapter::TransportAdapterController;
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-MockConnection::MockConnection(const ::transport_manager::DeviceUID& device_handle,
- const ApplicationHandle& app_handle,
- TransportAdapterController* controller)
- : ThreadedSocketConnection(device_handle, app_handle, controller) {
-}
-
-bool MockConnection::Establish(ConnectError **error) {
- int peer_sock = socket(AF_UNIX, SOCK_STREAM, 0);
- sockaddr_un my_addr;
- memset(&my_addr, 0, sizeof(my_addr));
- std::ostringstream iss;
- iss << "mockDevice" << device_handle() << "-" << application_handle();
- strcpy(my_addr.sun_path, iss.str().c_str());
- my_addr.sun_family = AF_UNIX;
- int res = ::connect(peer_sock, reinterpret_cast<sockaddr*>(&my_addr),
- sizeof(my_addr));
- if (res != -1) {
- set_socket(peer_sock);
- return true;
- }
- *error = new ConnectError();
- return false;
-}
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
-
diff --git a/src/components/transport_manager/test/mock_connection_factory.cc b/src/components/transport_manager/test/mock_connection_factory.cc
deleted file mode 100644
index 392ad79511..0000000000
--- a/src/components/transport_manager/test/mock_connection_factory.cc
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-
-#include "include/mock_connection.h"
-#include "include/mock_connection_factory.h"
-
-#include <algorithm>
-
-#include "include/mock_device.h"
-#include "include/mock_transport_adapter.h"
-
-using ::transport_manager::transport_adapter::DeviceSptr;
-using ::transport_manager::ConnectError;
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-MockConnectionFactory::MockConnectionFactory(MockTransportAdapter *controller)
- : controller_(controller) {}
-
-TransportAdapter::Error MockConnectionFactory::CreateConnection(
- const ::transport_manager::DeviceUID& device_handle,
- const ApplicationHandle& app_handle) {
-
- MockConnection *conn = new MockConnection(device_handle, app_handle, controller_);
- conn->Start();
- return TransportAdapter::OK;
-}
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
diff --git a/src/components/transport_manager/test/mock_device.cc b/src/components/transport_manager/test/mock_device.cc
deleted file mode 100644
index 8e346e9d54..0000000000
--- a/src/components/transport_manager/test/mock_device.cc
+++ /dev/null
@@ -1,85 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "include/mock_device.h"
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-const ApplicationHandle MockDevice::addApplication() {
- MockApplication app(this, applications_cnt_++);
- app.device = this;
- app.active = false;
- applications_.push_back(app);
- return app.handle;
-}
-
-void MockDevice::Start() {
- for (std::vector<MockApplication>::iterator it = applications_.begin();
- it != applications_.end();
- ++it) {
- it->Start();
- }
-}
-
-void MockDevice::Stop() {
- for (std::vector<MockApplication>::iterator it = applications_.begin();
- it != applications_.end();
- ++it) {
- it->Stop();
- }
-}
-
-bool MockDevice::IsSameAs(const Device* other) const {
- return unique_device_id() == other->unique_device_id();
-}
-
-static ApplicationHandle get_handle(const MockApplication& app) {
- return app.handle;
-}
-
-ApplicationList MockDevice::GetApplicationList() const {
- ApplicationList rc(applications_.size());
- std::transform(
- applications_.begin(), applications_.end(), rc.begin(),
- &get_handle);
- return rc;
-}
-
-bool MockDevice::operator ==(const MockDevice& other) {
- return IsSameAs(&other);
-}
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
diff --git a/src/components/transport_manager/test/mock_device_scanner.cc b/src/components/transport_manager/test/mock_device_scanner.cc
deleted file mode 100644
index a243162668..0000000000
--- a/src/components/transport_manager/test/mock_device_scanner.cc
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "include/mock_device_scanner.h"
-#include "include/mock_transport_adapter.h"
-#include "include/mock_device.h"
-
-using ::transport_manager::SearchDeviceError;
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-MockDeviceScanner::MockDeviceScanner(MockTransportAdapter *controller)
- : controller_(controller),
- is_initialized_(false),
- is_search_failed_(false) {
-}
-
-TransportAdapter::Error MockDeviceScanner::Init() {
- is_initialized_ = true;
- return TransportAdapter::OK;
-}
-
-TransportAdapter::Error MockDeviceScanner::Scan() {
- if (is_search_failed_) {
- controller_->SearchDeviceFailed(SearchDeviceError());
- } else {
- controller_->SearchDeviceDone(devices_);
- }
- return TransportAdapter::OK;
-}
-
-void MockDeviceScanner::Terminate() {
-}
-
-void MockDeviceScanner::reset() {
- is_search_failed_ = false;
- for (DeviceVector::iterator it = devices_.begin();
- it != devices_.end();
- ++it) {
- static_cast<MockDevice*>(it->get())->Stop();
- }
- devices_.clear();
-}
-
-bool MockDeviceScanner::IsInitialised() const {
- return is_initialized_;
-}
-
-void MockDeviceScanner::AddDevice(const std::string& name,
- const std::string& unique_id, bool start) {
- MockDevice* dev = new MockDevice(name, unique_id, controller_);
- dev->addApplication();
- if (start) {
- dev->Start();
- }
- devices_.push_back(dev);
-}
-
-void MockDeviceScanner::RemoveDevice(const std::string& name) {
- for (DeviceVector::iterator t = devices_.begin(); t != devices_.end(); ++t) {
- if ((*t)->name() == name) {
- devices_.erase(t);
- break;
- }
- }
-}
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
-
-// vim: set ts=2 sw=2 et:
diff --git a/src/components/transport_manager/test/mock_transport_adapter.cc b/src/components/transport_manager/test/mock_transport_adapter.cc
deleted file mode 100644
index 8612ca363b..0000000000
--- a/src/components/transport_manager/test/mock_transport_adapter.cc
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "include/mock_connection.h"
-#include "include/mock_device.h"
-#include "include/mock_transport_adapter.h"
-#include "include/mock_device_scanner.h"
-#include "include/mock_connection_factory.h"
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-MockTransportAdapter::MockTransportAdapter()
- : TransportAdapterImpl(new MockDeviceScanner(this),
- new MockConnectionFactory(this), NULL) {}
-
-void MockTransportAdapter::reset() {
- get_device_scanner()->reset();
-}
-
-MockDeviceScanner* MockTransportAdapter::get_device_scanner() const {
- return static_cast<MockDeviceScanner*>(device_scanner_);
-}
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
diff --git a/src/components/transport_manager/test/raw_message_matcher.cc b/src/components/transport_manager/test/raw_message_matcher.cc
index 289009d0c1..130ddc96c8 100644
--- a/src/components/transport_manager/test/raw_message_matcher.cc
+++ b/src/components/transport_manager/test/raw_message_matcher.cc
@@ -37,25 +37,25 @@ namespace test {
namespace components {
namespace transport_manager {
-RawMessageMatcher::RawMessageMatcher(RawMessagePtr ptr)
- : ptr_(ptr) {}
+RawMessageMatcher::RawMessageMatcher(RawMessagePtr ptr) : ptr_(ptr) {}
bool RawMessageMatcher::MatchAndExplain(const RawMessagePtr msg,
- MatchResultListener* listener) const {
+ MatchResultListener* listener) const {
if (msg->data_size() != ptr_->data_size()) {
- return ::std::equal(msg->data(), msg->data() + msg->data_size(), ptr_->data());
+ return ::std::equal(
+ msg->data(), msg->data() + msg->data_size(), ptr_->data());
} else
return false;
}
void RawMessageMatcher::DescribeTo(::std::ostream* os) const {
- *os << "data_ is " ;
+ *os << "data_ is ";
::std::ostream_iterator<unsigned char> out(*os);
::std::copy(ptr_->data(), ptr_->data() + ptr_->data_size(), out);
}
void RawMessageMatcher::DescribeNegationTo(::std::ostream* os) const {
- *os << "data_ is not " ;
+ *os << "data_ is not ";
::std::ostream_iterator<unsigned char> out(*os);
::std::copy(ptr_->data(), ptr_->data() + ptr_->data_size(), out);
}
diff --git a/src/components/transport_manager/test/tcp_client_listener_test.cc b/src/components/transport_manager/test/tcp_client_listener_test.cc
index 916f8bac58..782b363a38 100644
--- a/src/components/transport_manager/test/tcp_client_listener_test.cc
+++ b/src/components/transport_manager/test/tcp_client_listener_test.cc
@@ -31,9 +31,9 @@
*/
#include "gtest/gtest.h"
-#include "include/transport_adapter_mock.h"
+#include "transport_manager/transport_adapter_mock.h"
#include "transport_manager/tcp/tcp_client_listener.h"
-#include "include/transport_manager_mock.h"
+#include "transport_manager/mock_transport_manager.h"
#include "transport_manager/transport_adapter/transport_adapter_controller.h"
#include "transport_manager/transport_adapter/device.h"
@@ -45,34 +45,65 @@ using ::testing::Return;
using namespace ::transport_manager;
using namespace ::transport_manager::transport_adapter;
-class MockTransportAdapterController: public TransportAdapterController {
-public:
- MOCK_METHOD1(AddDevice,DeviceSptr(DeviceSptr device));
- MOCK_METHOD0(AckDevices,void());
- MOCK_METHOD1(SearchDeviceDone, void(const DeviceVector& devices));
- MOCK_METHOD1(SearchDeviceFailed, void(const SearchDeviceError& error));
- MOCK_CONST_METHOD1(FindDevice, DeviceSptr(const DeviceUID& device_handle));
- MOCK_METHOD3(ConnectionCreated, void(ConnectionSPtr connection, const DeviceUID& device_handle, const ApplicationHandle& app_handle));
- MOCK_METHOD2(ConnectDone, void(const DeviceUID& device_handle, const ApplicationHandle& app_handle));
- MOCK_METHOD3(ConnectFailed, void(const DeviceUID& device_handle, const ApplicationHandle& app_handle, const ConnectError& error));
- MOCK_METHOD2(ConnectionFinished, void(const DeviceUID& device_handle, const ApplicationHandle& app_handle));
- MOCK_METHOD3(ConnectionAborted,void(const DeviceUID& device_handle, const ApplicationHandle& app_handle, const CommunicationError& error));
- MOCK_METHOD2(DisconnectDone, void(const DeviceUID& device_handle, const ApplicationHandle& app_handle));
- MOCK_METHOD3(DataReceiveDone, void(const DeviceUID& device_handle, const ApplicationHandle& app_handle, const ::protocol_handler::RawMessagePtr message));
- MOCK_METHOD3(DataReceiveFailed, void(const DeviceUID& device_handle, const ApplicationHandle& app_handle, const DataReceiveError& error));
- MOCK_METHOD3(DataSendDone, void(const DeviceUID& device_handle, const ApplicationHandle& app_handle, const ::protocol_handler::RawMessagePtr message));
- MOCK_METHOD4(DataSendFailed, void(const DeviceUID& device_handle, const ApplicationHandle& app_handle, const ::protocol_handler::RawMessagePtr message, const DataSendError& error));
- MOCK_METHOD0(FindNewApplicationsRequest, void());
- MOCK_METHOD1(ApplicationListUpdated, void(const DeviceUID& device_handle));
- MOCK_METHOD2(DeviceDisconnected, void (const DeviceUID& device_handle,const DisconnectDeviceError& error));
+class MockTransportAdapterController : public TransportAdapterController {
+ public:
+ MOCK_METHOD1(AddDevice, DeviceSptr(DeviceSptr device));
+ MOCK_METHOD0(AckDevices, void());
+ MOCK_METHOD1(SearchDeviceDone, void(const DeviceVector& devices));
+ MOCK_METHOD1(SearchDeviceFailed, void(const SearchDeviceError& error));
+ MOCK_CONST_METHOD1(FindDevice, DeviceSptr(const DeviceUID& device_handle));
+ MOCK_METHOD3(ConnectionCreated,
+ void(ConnectionSPtr connection,
+ const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ MOCK_METHOD2(ConnectDone,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ MOCK_METHOD3(ConnectFailed,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ConnectError& error));
+ MOCK_METHOD2(ConnectionFinished,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ MOCK_METHOD3(ConnectionAborted,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const CommunicationError& error));
+ MOCK_METHOD2(DisconnectDone,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle));
+ MOCK_METHOD3(DataReceiveDone,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ::protocol_handler::RawMessagePtr message));
+ MOCK_METHOD3(DataReceiveFailed,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const DataReceiveError& error));
+ MOCK_METHOD3(DataSendDone,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ::protocol_handler::RawMessagePtr message));
+ MOCK_METHOD4(DataSendFailed,
+ void(const DeviceUID& device_handle,
+ const ApplicationHandle& app_handle,
+ const ::protocol_handler::RawMessagePtr message,
+ const DataSendError& error));
+ MOCK_METHOD0(FindNewApplicationsRequest, void());
+ MOCK_METHOD1(ApplicationListUpdated, void(const DeviceUID& device_handle));
+ MOCK_METHOD2(DeviceDisconnected,
+ void(const DeviceUID& device_handle,
+ const DisconnectDeviceError& error));
};
class TcpClientListenerTest : public ::testing::Test {
public:
TcpClientListenerTest()
- : port_(0),
- enable_keep_alive_(false),
- tcp_client_listener_(&adapter_controller_mock_, port_, enable_keep_alive_) {}
+ : port_(0)
+ , enable_keep_alive_(false)
+ , tcp_client_listener_(
+ &adapter_controller_mock_, port_, enable_keep_alive_) {}
protected:
uint16_t port_;
@@ -88,7 +119,7 @@ TEST_F(TcpClientListenerTest, Ctor_test) {
}
TEST_F(TcpClientListenerTest, IsInitialised) {
- EXPECT_TRUE(tcp_client_listener_.IsInitialised());
+ EXPECT_TRUE(tcp_client_listener_.IsInitialised());
}
TEST_F(TcpClientListenerTest, Init) {
@@ -98,4 +129,3 @@ TEST_F(TcpClientListenerTest, Init) {
} // namespace transport_manager_test
} // namespace components
} // namespace test
-
diff --git a/src/components/transport_manager/test/tcp_device_test.cc b/src/components/transport_manager/test/tcp_device_test.cc
index 961ebe6954..55fa5ac5d3 100644
--- a/src/components/transport_manager/test/tcp_device_test.cc
+++ b/src/components/transport_manager/test/tcp_device_test.cc
@@ -45,7 +45,9 @@ class TestDevice : public Device {
public:
TestDevice(const uint32_t& in_addr, const std::string& name)
: Device(name, name), in_addr_(in_addr) {}
- bool IsSameAs(const Device* other_device) const { return true; }
+ bool IsSameAs(const Device* other_device) const {
+ return true;
+ }
ApplicationList GetApplicationList() const {
ApplicationList app_list;
return app_list;
diff --git a/src/components/transport_manager/test/tcp_transport_adapter_test.cc b/src/components/transport_manager/test/tcp_transport_adapter_test.cc
index d849d94d48..60732f0328 100644
--- a/src/components/transport_manager/test/tcp_transport_adapter_test.cc
+++ b/src/components/transport_manager/test/tcp_transport_adapter_test.cc
@@ -33,12 +33,15 @@
#include "gtest/gtest.h"
#include "transport_manager/tcp/tcp_transport_adapter.h"
#include "transport_manager/transport_adapter/connection.h"
-#include "config_profile/profile.h"
#include "resumption/last_state.h"
#include "protocol/raw_message.h"
-#include "include/transport_adapter_listener_mock.h"
-#include "include/device_mock.h"
-#include "include/connection_mock.h"
+#include "transport_manager/transport_adapter_listener_mock.h"
+#include "transport_manager/device_mock.h"
+#include "transport_manager/connection_mock.h"
+#include "transport_manager/tcp/mock_tcp_transport_adapter.h"
+#include "transport_manager/mock_transport_manager_settings.h"
+
+#include "utils/make_shared.h"
namespace test {
namespace components {
@@ -51,45 +54,21 @@ using namespace ::protocol_handler;
using namespace ::transport_manager;
using namespace transport_manager::transport_adapter;
-class TestTCPTransportAdapter : public TcpTransportAdapter {
- public:
- TestTCPTransportAdapter(uint16_t port) : TcpTransportAdapter(port) {
- ::profile::Profile::instance()->config_file_name(
- "smartDeviceLink_test.ini");
- }
- MOCK_CONST_METHOD2(FindEstablishedConnection,
- ConnectionSPtr(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle));
-
- MOCK_CONST_METHOD1(FindDevice, DeviceSptr(const DeviceUID& device_handle));
- MOCK_METHOD2(Connect,
- TransportAdapter::Error(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle));
- void CallStore() { Store(); }
- bool CallRestore() { return Restore(); }
-};
-
class TcpAdapterTest : public ::testing::Test {
protected:
- static void SetUpTestCase() {
- ::profile::Profile::instance()->config_file_name(
- "smartDeviceLink_test.ini");
- }
- virtual void SetUp() {
- resumption::LastState::instance()->dictionary = Json::Value();
- }
-
- virtual void TearDown() { resumption::LastState::destroy(); }
-
+ TcpAdapterTest() : last_state_("app_storage_folder", "app_info_storage") {}
+ MockTransportManagerSettings transport_manager_settings;
+ resumption::LastState last_state_;
const uint32_t port = 12345;
const std::string string_port = "12345";
};
-TEST_F(TcpAdapterTest, DISABLED_StoreDataWithOneDeviceAndOneApplication) {
+TEST_F(TcpAdapterTest, StoreDataWithOneDeviceAndOneApplication) {
// Prepare
- TestTCPTransportAdapter transport_adapter(port);
+ MockTCPTransportAdapter transport_adapter(
+ port, last_state_, transport_manager_settings);
std::string uniq_id = "unique_device_name";
- utils::SharedPtr<TCPDeviceMock> mockdev = new TCPDeviceMock(port, uniq_id);
+ utils::SharedPtr<MockTCPDevice> mockdev = new MockTCPDevice(port, uniq_id);
transport_adapter.AddDevice(mockdev);
std::vector<std::string> devList = transport_adapter.GetDeviceList();
@@ -100,7 +79,7 @@ TEST_F(TcpAdapterTest, DISABLED_StoreDataWithOneDeviceAndOneApplication) {
std::vector<int> intList = {app_handle};
EXPECT_CALL(*mockdev, GetApplicationList()).WillOnce(Return(intList));
- ConnectionSPtr mock_connection = new ConnectionMock();
+ ConnectionSPtr mock_connection = new MockConnection();
EXPECT_CALL(transport_adapter, FindDevice(uniq_id)).WillOnce(Return(mockdev));
EXPECT_CALL(transport_adapter, FindEstablishedConnection(uniq_id, app_handle))
.WillOnce(Return(mock_connection));
@@ -110,8 +89,8 @@ TEST_F(TcpAdapterTest, DISABLED_StoreDataWithOneDeviceAndOneApplication) {
transport_adapter.CallStore();
// Check that value is saved
- Json::Value& tcp_dict = resumption::LastState::instance()
- ->dictionary["TransportManager"]["TcpAdapter"];
+ Json::Value& tcp_dict =
+ last_state_.dictionary["TransportManager"]["TcpAdapter"];
ASSERT_TRUE(tcp_dict.isObject());
ASSERT_FALSE(tcp_dict["devices"].isNull());
@@ -123,17 +102,18 @@ TEST_F(TcpAdapterTest, DISABLED_StoreDataWithOneDeviceAndOneApplication) {
EXPECT_EQ(uniq_id, tcp_dict["devices"][0]["name"].asString());
}
-TEST_F(TcpAdapterTest, DISABLED_StoreDataWithSeveralDevicesAndOneApplication) {
+TEST_F(TcpAdapterTest, StoreDataWithSeveralDevicesAndOneApplication) {
// Prepare
- TestTCPTransportAdapter transport_adapter(port);
+ MockTCPTransportAdapter transport_adapter(
+ port, last_state_, transport_manager_settings);
const uint32_t count_dev = 10;
- utils::SharedPtr<TCPDeviceMock> mockdev[count_dev];
+ utils::SharedPtr<MockTCPDevice> mockdev[count_dev];
std::string uniq_id[count_dev];
for (uint32_t i = 0; i < count_dev; i++) {
char numb[12];
std::snprintf(numb, 12, "%d", i);
uniq_id[i] = "unique_device_name" + std::string(numb);
- mockdev[i] = new TCPDeviceMock(port, uniq_id[i]);
+ mockdev[i] = new MockTCPDevice(port, uniq_id[i]);
EXPECT_CALL(*(mockdev[i]), IsSameAs(_)).WillRepeatedly(Return(false));
transport_adapter.AddDevice(mockdev[i]);
}
@@ -145,7 +125,7 @@ TEST_F(TcpAdapterTest, DISABLED_StoreDataWithSeveralDevicesAndOneApplication) {
const int app_handle = 1;
std::vector<int> intList = {app_handle};
- ConnectionSPtr mock_connection = new ConnectionMock();
+ ConnectionSPtr mock_connection = new MockConnection();
for (uint32_t i = 0; i < count_dev; i++) {
EXPECT_CALL(transport_adapter, FindDevice(uniq_id[i]))
.WillOnce(Return(mockdev[i]));
@@ -161,8 +141,8 @@ TEST_F(TcpAdapterTest, DISABLED_StoreDataWithSeveralDevicesAndOneApplication) {
transport_adapter.CallStore();
// Check that values are saved
- Json::Value& tcp_dict = resumption::LastState::instance()
- ->dictionary["TransportManager"]["TcpAdapter"];
+ Json::Value& tcp_dict =
+ last_state_.dictionary["TransportManager"]["TcpAdapter"];
ASSERT_TRUE(tcp_dict.isObject());
ASSERT_FALSE(tcp_dict["devices"].isNull());
for (uint32_t i = 0; i < count_dev; i++) {
@@ -175,18 +155,19 @@ TEST_F(TcpAdapterTest, DISABLED_StoreDataWithSeveralDevicesAndOneApplication) {
}
}
-TEST_F(TcpAdapterTest, DISABLED_StoreDataWithSeveralDevicesAndSeveralApplications) {
+TEST_F(TcpAdapterTest, StoreDataWithSeveralDevicesAndSeveralApplications) {
// Prepare
- TestTCPTransportAdapter transport_adapter(port);
+ MockTCPTransportAdapter transport_adapter(
+ port, last_state_, transport_manager_settings);
const uint32_t count_dev = 10;
- utils::SharedPtr<TCPDeviceMock> mockdev[count_dev];
+ utils::SharedPtr<MockTCPDevice> mockdev[count_dev];
std::string uniq_id[count_dev];
for (uint32_t i = 0; i < count_dev; i++) {
char numb[12];
std::snprintf(numb, 12, "%d", i);
uniq_id[i] = "unique_device_name" + std::string(numb);
- mockdev[i] = new TCPDeviceMock(port, uniq_id[i]);
+ mockdev[i] = new MockTCPDevice(port, uniq_id[i]);
EXPECT_CALL(*(mockdev[i]), IsSameAs(_)).WillRepeatedly(Return(false));
transport_adapter.AddDevice(mockdev[i]);
}
@@ -200,7 +181,7 @@ TEST_F(TcpAdapterTest, DISABLED_StoreDataWithSeveralDevicesAndSeveralApplication
std::vector<int> intList = {app_handle[0], app_handle[1], app_handle[2]};
const std::string ports[connection_count] = {"11111", "67890", "98765"};
const int int_port[connection_count] = {11111, 67890, 98765};
- ConnectionSPtr mock_connection = new ConnectionMock();
+ ConnectionSPtr mock_connection = new MockConnection();
for (uint32_t i = 0; i < count_dev; i++) {
EXPECT_CALL(transport_adapter, FindDevice(uniq_id[i]))
.WillOnce(Return(mockdev[i]));
@@ -217,8 +198,8 @@ TEST_F(TcpAdapterTest, DISABLED_StoreDataWithSeveralDevicesAndSeveralApplication
transport_adapter.CallStore();
// Check that value is saved
- Json::Value& tcp_dict = resumption::LastState::instance()
- ->dictionary["TransportManager"]["TcpAdapter"];
+ Json::Value& tcp_dict =
+ last_state_.dictionary["TransportManager"]["TcpAdapter"];
ASSERT_TRUE(tcp_dict.isObject());
ASSERT_FALSE(tcp_dict["devices"].isNull());
@@ -235,9 +216,10 @@ TEST_F(TcpAdapterTest, DISABLED_StoreDataWithSeveralDevicesAndSeveralApplication
TEST_F(TcpAdapterTest, StoreData_ConnectionNotExist_DataNotStored) {
// Prepare
- TestTCPTransportAdapter transport_adapter(port);
+ MockTCPTransportAdapter transport_adapter(
+ port, last_state_, transport_manager_settings);
std::string uniq_id = "unique_device_name";
- utils::SharedPtr<TCPDeviceMock> mockdev = new TCPDeviceMock(port, uniq_id);
+ utils::SharedPtr<MockTCPDevice> mockdev = new MockTCPDevice(port, uniq_id);
transport_adapter.AddDevice(mockdev);
std::vector<std::string> devList = transport_adapter.GetDeviceList();
@@ -254,25 +236,25 @@ TEST_F(TcpAdapterTest, StoreData_ConnectionNotExist_DataNotStored) {
// Check that value is not saved
Json::Value& tcp_dict =
- resumption::LastState::instance()
- ->dictionary["TransportManager"]["TcpAdapter"]["devices"];
+ last_state_.dictionary["TransportManager"]["TcpAdapter"]["devices"];
ASSERT_TRUE(tcp_dict.isNull());
}
TEST_F(TcpAdapterTest, RestoreData_DataNotStored) {
Json::Value& tcp_adapter_dictionary =
- resumption::LastState::instance()
- ->dictionary["TransportManager"]["TcpAdapter"];
+ last_state_.dictionary["TransportManager"]["TcpAdapter"];
tcp_adapter_dictionary = Json::Value();
- TestTCPTransportAdapter transport_adapter(port);
+ MockTCPTransportAdapter transport_adapter(
+ port, last_state_, transport_manager_settings);
EXPECT_CALL(transport_adapter, Connect(_, _)).Times(0);
EXPECT_TRUE(transport_adapter.CallRestore());
}
-TEST_F(TcpAdapterTest, DISABLED_StoreDataWithOneDevice_RestoreData) {
- TestTCPTransportAdapter transport_adapter(port);
+TEST_F(TcpAdapterTest, StoreDataWithOneDevice_RestoreData) {
+ MockTCPTransportAdapter transport_adapter(
+ port, last_state_, transport_manager_settings);
std::string uniq_id = "unique_device_name";
- utils::SharedPtr<TCPDeviceMock> mockdev = new TCPDeviceMock(port, uniq_id);
+ utils::SharedPtr<MockTCPDevice> mockdev = new MockTCPDevice(port, uniq_id);
transport_adapter.AddDevice(mockdev);
std::vector<std::string> devList = transport_adapter.GetDeviceList();
@@ -283,7 +265,7 @@ TEST_F(TcpAdapterTest, DISABLED_StoreDataWithOneDevice_RestoreData) {
std::vector<int> intList = {app_handle};
EXPECT_CALL(*mockdev, GetApplicationList()).WillOnce(Return(intList));
- ConnectionSPtr mock_connection = new ConnectionMock();
+ ConnectionSPtr mock_connection = new MockConnection();
EXPECT_CALL(transport_adapter, FindDevice(uniq_id)).WillOnce(Return(mockdev));
EXPECT_CALL(transport_adapter, FindEstablishedConnection(uniq_id, app_handle))
.WillOnce(Return(mock_connection));
@@ -302,17 +284,18 @@ TEST_F(TcpAdapterTest, DISABLED_StoreDataWithOneDevice_RestoreData) {
EXPECT_EQ(uniq_id, devList[0]);
}
-TEST_F(TcpAdapterTest, DISABLED_StoreDataWithSeveralDevices_RestoreData) {
- TestTCPTransportAdapter transport_adapter(port);
+TEST_F(TcpAdapterTest, StoreDataWithSeveralDevices_RestoreData) {
+ MockTCPTransportAdapter transport_adapter(
+ port, last_state_, transport_manager_settings);
const uint32_t count_dev = 10;
- utils::SharedPtr<TCPDeviceMock> mockdev[count_dev];
+ utils::SharedPtr<MockTCPDevice> mockdev[count_dev];
std::string uniq_id[count_dev];
for (uint32_t i = 0; i < count_dev; i++) {
char numb[12];
std::snprintf(numb, 12, "%d", i);
uniq_id[i] = "unique_device_name" + std::string(numb);
- mockdev[i] = new TCPDeviceMock(port, uniq_id[i]);
+ mockdev[i] = new MockTCPDevice(port, uniq_id[i]);
EXPECT_CALL(*(mockdev[i]), IsSameAs(_)).WillRepeatedly(Return(false));
transport_adapter.AddDevice(mockdev[i]);
}
@@ -324,7 +307,7 @@ TEST_F(TcpAdapterTest, DISABLED_StoreDataWithSeveralDevices_RestoreData) {
const int app_handle = 1;
std::vector<int> intList = {app_handle};
- ConnectionSPtr mock_connection = new ConnectionMock();
+ ConnectionSPtr mock_connection = new MockConnection();
for (uint32_t i = 0; i < count_dev; i++) {
EXPECT_CALL(transport_adapter, FindDevice(uniq_id[i]))
.WillOnce(Return(mockdev[i]));
diff --git a/src/components/transport_manager/test/transport_adapter_listener_test.cc b/src/components/transport_manager/test/transport_adapter_listener_test.cc
index 4d0ff4ec20..d56949301c 100644
--- a/src/components/transport_manager/test/transport_adapter_listener_test.cc
+++ b/src/components/transport_manager/test/transport_adapter_listener_test.cc
@@ -31,9 +31,9 @@
*/
#include "gtest/gtest.h"
-#include "include/transport_adapter_mock.h"
+#include "transport_manager/transport_adapter_mock.h"
#include "transport_manager/transport_adapter/transport_adapter_listener_impl.h"
-#include "include/transport_manager_mock.h"
+#include "transport_manager/mock_transport_manager.h"
namespace test {
namespace components {
@@ -45,15 +45,15 @@ using namespace ::transport_manager;
class TransportAdapterListenerTest : public ::testing::Test {
public:
TransportAdapterListenerTest()
- : app_handle(1),
- dev_id("device_id"),
- transport_listener(&tr_mock, &adapter_mock) {}
+ : app_handle(1)
+ , dev_id("device_id")
+ , transport_listener(&tr_mock, &adapter_mock) {}
protected:
const int app_handle;
const std::string dev_id;
- TransportManagerMock tr_mock;
- TransportAdapterMock adapter_mock;
+ MockTransportManager tr_mock;
+ MockTransportAdapter adapter_mock;
TransportAdapterListenerImpl transport_listener;
};
@@ -75,7 +75,9 @@ TEST_F(TransportAdapterListenerTest, OnCommunicationError) {
tr_mock,
ReceiveEventFromDevice(IsEvent(
TransportAdapterListenerImpl::EventTypeEnum::ON_COMMUNICATION_ERROR,
- &adapter_mock, dev_id, app_handle))).WillOnce(Return(E_SUCCESS));
+ &adapter_mock,
+ dev_id,
+ app_handle))).WillOnce(Return(E_SUCCESS));
transport_listener.OnCommunicationError(&adapter_mock, dev_id, app_handle);
}
@@ -83,8 +85,9 @@ TEST_F(TransportAdapterListenerTest, OnConnectDone) {
EXPECT_CALL(tr_mock,
ReceiveEventFromDevice(IsEvent(
TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_DONE,
- &adapter_mock, dev_id, app_handle)))
- .WillOnce(Return(E_SUCCESS));
+ &adapter_mock,
+ dev_id,
+ app_handle))).WillOnce(Return(E_SUCCESS));
transport_listener.OnConnectDone(&adapter_mock, dev_id, app_handle);
}
@@ -94,8 +97,9 @@ TEST_F(TransportAdapterListenerTest, OnConnectFailed) {
EXPECT_CALL(tr_mock,
ReceiveEventFromDevice(IsEvent(
TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_FAIL,
- &adapter_mock, dev_id, app_handle)))
- .WillOnce(Return(E_SUCCESS));
+ &adapter_mock,
+ dev_id,
+ app_handle))).WillOnce(Return(E_SUCCESS));
transport_listener.OnConnectFailed(&adapter_mock, dev_id, app_handle, er);
}
@@ -105,10 +109,12 @@ TEST_F(TransportAdapterListenerTest, OnDataReceiveDone) {
EXPECT_CALL(tr_mock,
ReceiveEventFromDevice(IsEvent(
TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_DONE,
- &adapter_mock, dev_id, app_handle, data_container)))
- .WillOnce(Return(E_SUCCESS));
- transport_listener.OnDataReceiveDone(&adapter_mock, dev_id, app_handle,
- data_container);
+ &adapter_mock,
+ dev_id,
+ app_handle,
+ data_container))).WillOnce(Return(E_SUCCESS));
+ transport_listener.OnDataReceiveDone(
+ &adapter_mock, dev_id, app_handle, data_container);
}
TEST_F(TransportAdapterListenerTest, OnDataReceiveFailed) {
@@ -117,10 +123,11 @@ TEST_F(TransportAdapterListenerTest, OnDataReceiveFailed) {
EXPECT_CALL(tr_mock,
ReceiveEventFromDevice(IsEvent(
TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_FAIL,
- &adapter_mock, dev_id, app_handle)))
- .WillOnce(Return(E_SUCCESS));
- transport_listener.OnDataReceiveFailed(&adapter_mock, dev_id, app_handle,
- err);
+ &adapter_mock,
+ dev_id,
+ app_handle))).WillOnce(Return(E_SUCCESS));
+ transport_listener.OnDataReceiveFailed(
+ &adapter_mock, dev_id, app_handle, err);
}
TEST_F(TransportAdapterListenerTest, OnDataSendDone) {
@@ -131,10 +138,12 @@ TEST_F(TransportAdapterListenerTest, OnDataSendDone) {
EXPECT_CALL(tr_mock,
ReceiveEventFromDevice(IsEvent(
TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_DONE,
- &adapter_mock, dev_id, app_handle, data_container)))
- .WillOnce(Return(E_SUCCESS));
- transport_listener.OnDataSendDone(&adapter_mock, dev_id, app_handle,
- data_container);
+ &adapter_mock,
+ dev_id,
+ app_handle,
+ data_container))).WillOnce(Return(E_SUCCESS));
+ transport_listener.OnDataSendDone(
+ &adapter_mock, dev_id, app_handle, data_container);
}
TEST_F(TransportAdapterListenerTest, OnDataSendFailed) {
@@ -146,10 +155,12 @@ TEST_F(TransportAdapterListenerTest, OnDataSendFailed) {
EXPECT_CALL(tr_mock,
ReceiveEventFromDevice(IsEvent(
TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_FAIL,
- &adapter_mock, dev_id, app_handle, data_container)))
- .WillOnce(Return(E_SUCCESS));
- transport_listener.OnDataSendFailed(&adapter_mock, dev_id, app_handle,
- data_container, err);
+ &adapter_mock,
+ dev_id,
+ app_handle,
+ data_container))).WillOnce(Return(E_SUCCESS));
+ transport_listener.OnDataSendFailed(
+ &adapter_mock, dev_id, app_handle, data_container, err);
}
TEST_F(TransportAdapterListenerTest, OnDeviceListUpdated) {
@@ -157,7 +168,9 @@ TEST_F(TransportAdapterListenerTest, OnDeviceListUpdated) {
tr_mock,
ReceiveEventFromDevice(IsEvent(
TransportAdapterListenerImpl::EventTypeEnum::ON_DEVICE_LIST_UPDATED,
- &adapter_mock, "", 0))).WillOnce(Return(E_SUCCESS));
+ &adapter_mock,
+ "",
+ 0))).WillOnce(Return(E_SUCCESS));
transport_listener.OnDeviceListUpdated(&adapter_mock);
}
@@ -166,7 +179,9 @@ TEST_F(TransportAdapterListenerTest, OnDisconnectDeviceDone) {
tr_mock,
ReceiveEventFromDevice(IsEvent(
TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_DONE,
- &adapter_mock, dev_id, app_handle))).WillOnce(Return(E_SUCCESS));
+ &adapter_mock,
+ dev_id,
+ app_handle))).WillOnce(Return(E_SUCCESS));
transport_listener.OnDisconnectDone(&adapter_mock, dev_id, app_handle);
}
@@ -177,15 +192,20 @@ TEST_F(TransportAdapterListenerTest, OnDisconnectFailed) {
tr_mock,
ReceiveEventFromDevice(IsEvent(
TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_FAIL,
- &adapter_mock, dev_id, app_handle))).WillOnce(Return(E_SUCCESS));
+ &adapter_mock,
+ dev_id,
+ app_handle))).WillOnce(Return(E_SUCCESS));
transport_listener.OnDisconnectFailed(&adapter_mock, dev_id, app_handle, err);
}
TEST_F(TransportAdapterListenerTest, OnFindNewApplicationsRequest) {
- EXPECT_CALL(tr_mock, ReceiveEventFromDevice(IsEvent(
- TransportAdapterListenerImpl::EventTypeEnum::
- ON_FIND_NEW_APPLICATIONS_REQUEST,
- &adapter_mock, "", 0))).WillOnce(Return(E_SUCCESS));
+ EXPECT_CALL(tr_mock,
+ ReceiveEventFromDevice(
+ IsEvent(TransportAdapterListenerImpl::EventTypeEnum::
+ ON_FIND_NEW_APPLICATIONS_REQUEST,
+ &adapter_mock,
+ "",
+ 0))).WillOnce(Return(E_SUCCESS));
transport_listener.OnFindNewApplicationsRequest(&adapter_mock);
}
@@ -193,7 +213,9 @@ TEST_F(TransportAdapterListenerTest, OnSearchDeviceDone) {
EXPECT_CALL(tr_mock,
ReceiveEventFromDevice(IsEvent(
TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_DONE,
- &adapter_mock, "", 0))).WillOnce(Return(E_SUCCESS));
+ &adapter_mock,
+ "",
+ 0))).WillOnce(Return(E_SUCCESS));
transport_listener.OnSearchDeviceDone(&adapter_mock);
}
@@ -203,7 +225,9 @@ TEST_F(TransportAdapterListenerTest, OnSearchDeviceFailed) {
EXPECT_CALL(tr_mock,
ReceiveEventFromDevice(IsEvent(
TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_FAIL,
- &adapter_mock, "", 0))).WillOnce(Return(E_SUCCESS));
+ &adapter_mock,
+ "",
+ 0))).WillOnce(Return(E_SUCCESS));
transport_listener.OnSearchDeviceFailed(&adapter_mock, er);
}
@@ -214,9 +238,11 @@ TEST_F(TransportAdapterListenerTest, OnUnexpectedDisconnect) {
tr_mock,
ReceiveEventFromDevice(IsEvent(
TransportAdapterListenerImpl::EventTypeEnum::ON_UNEXPECTED_DISCONNECT,
- &adapter_mock, dev_id, app_handle))).WillOnce(Return(E_SUCCESS));
- transport_listener.OnUnexpectedDisconnect(&adapter_mock, dev_id, app_handle,
- err);
+ &adapter_mock,
+ dev_id,
+ app_handle))).WillOnce(Return(E_SUCCESS));
+ transport_listener.OnUnexpectedDisconnect(
+ &adapter_mock, dev_id, app_handle, err);
}
} // namespace transport_manager_test
diff --git a/src/components/transport_manager/test/transport_adapter_test.cc b/src/components/transport_manager/test/transport_adapter_test.cc
index 679cd90643..5d34a2f02f 100644
--- a/src/components/transport_manager/test/transport_adapter_test.cc
+++ b/src/components/transport_manager/test/transport_adapter_test.cc
@@ -31,19 +31,23 @@
*/
#include "gtest/gtest.h"
-#include "include/device_scanner_mock.h"
-#include "include/client_connection_listener_mock.h"
-#include "include/server_connection_factory_mock.h"
-#include "include/device_mock.h"
-#include "include/connection_mock.h"
-#include "include/transport_adapter_listener_mock.h"
+#include "transport_manager/device_scanner_mock.h"
+#include "transport_manager/client_connection_listener_mock.h"
+#include "transport_manager/server_connection_factory_mock.h"
+#include "transport_manager/device_mock.h"
+#include "transport_manager/connection_mock.h"
+#include "transport_manager/transport_adapter_listener_mock.h"
+#include "transport_manager/transport_adapter/mock_transport_adapter_impl.h"
+#include "transport_manager/mock_transport_manager_settings.h"
#include "transport_manager/transport_adapter/transport_adapter_impl.h"
#include "transport_manager/transport_adapter/transport_adapter_listener.h"
#include "transport_manager/transport_adapter/transport_adapter_controller.h"
#include "transport_manager/transport_adapter/connection.h"
-#include "config_profile/profile.h"
#include "protocol/raw_message.h"
+#include "utils/make_shared.h"
+#include "resumption/last_state.h"
+#include "config_profile/profile.h"
namespace test {
namespace components {
@@ -51,56 +55,39 @@ namespace transport_manager_test {
using ::testing::Return;
using ::testing::_;
-
+using ::testing::NiceMock;
using namespace ::transport_manager;
using namespace ::protocol_handler;
-
-class TestTransportAdapter : public TransportAdapterImpl {
- public:
- TestTransportAdapter(DeviceScanner* device_scanner,
- ServerConnectionFactory* server_connection_factory,
- ClientConnectionListener* client_connection_listener)
- : TransportAdapterImpl(device_scanner, server_connection_factory,
- client_connection_listener) {
- }
-
- ConnectionSPtr FindStatedConnection(const DeviceUID& device_handle,
- const ApplicationHandle& app_handle) {
- return this->FindEstablishedConnection(device_handle, app_handle);
- }
- virtual ~TestTransportAdapter(){};
-
- virtual DeviceType GetDeviceType() const { return UNKNOWN; }
-
- MOCK_CONST_METHOD0(Store, void());
- MOCK_METHOD0(Restore, bool());
-};
-
class TransportAdapterTest : public ::testing::Test {
protected:
- virtual void SetUp() {
+ TransportAdapterTest()
+ : last_state_("app_storage_folder", "app_info_storage") {}
+
+ void SetUp() OVERRIDE {
dev_id = "device_id";
uniq_id = "unique_device_id";
app_handle = 1;
+ ON_CALL(transport_manager_settings, use_last_state())
+ .WillByDefault(Return(true));
}
- static void SetUpTestCase() {
- ::profile::Profile::instance()->config_file_name(
- "smartDeviceLink_test.ini");
- }
-
+ NiceMock<MockTransportManagerSettings> transport_manager_settings;
+ resumption::LastState last_state_;
std::string dev_id;
std::string uniq_id;
int app_handle;
};
TEST_F(TransportAdapterTest, Init) {
- DeviceScannerMock* dev_mock = new DeviceScannerMock();
- ClientConnectionListenerMock* clientMock = new ClientConnectionListenerMock();
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(dev_mock, serverMock, clientMock);
-
+ MockDeviceScanner* dev_mock = new MockDeviceScanner();
+ MockClientConnectionListener* clientMock = new MockClientConnectionListener();
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(dev_mock,
+ serverMock,
+ clientMock,
+ last_state_,
+ transport_manager_settings);
EXPECT_CALL(*dev_mock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(*clientMock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(*serverMock, Init()).WillOnce(Return(TransportAdapter::OK));
@@ -115,9 +102,10 @@ TEST_F(TransportAdapterTest, Init) {
}
TEST_F(TransportAdapterTest, SearchDevices_WithoutScanner) {
- ClientConnectionListenerMock* clientMock = new ClientConnectionListenerMock();
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(NULL, serverMock, clientMock);
+ MockClientConnectionListener* clientMock = new MockClientConnectionListener();
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(
+ NULL, serverMock, clientMock, last_state_, transport_manager_settings);
EXPECT_CALL(*clientMock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(*serverMock, Init()).WillOnce(Return(TransportAdapter::OK));
@@ -131,8 +119,9 @@ TEST_F(TransportAdapterTest, SearchDevices_WithoutScanner) {
}
TEST_F(TransportAdapterTest, SearchDevices_DeviceNotInitialized) {
- DeviceScannerMock* dev_mock = new DeviceScannerMock();
- TestTransportAdapter transport_adapter(dev_mock, NULL, NULL);
+ MockDeviceScanner* dev_mock = new MockDeviceScanner();
+ MockTransportAdapterImpl transport_adapter(
+ dev_mock, NULL, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(*dev_mock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
@@ -145,8 +134,9 @@ TEST_F(TransportAdapterTest, SearchDevices_DeviceNotInitialized) {
}
TEST_F(TransportAdapterTest, SearchDevices_DeviceInitialized) {
- DeviceScannerMock* dev_mock = new DeviceScannerMock();
- TestTransportAdapter transport_adapter(dev_mock, NULL, NULL);
+ MockDeviceScanner* dev_mock = new MockDeviceScanner();
+ MockTransportAdapterImpl transport_adapter(
+ dev_mock, NULL, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(*dev_mock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
@@ -160,12 +150,12 @@ TEST_F(TransportAdapterTest, SearchDevices_DeviceInitialized) {
}
TEST_F(TransportAdapterTest, SearchDeviceDone_DeviceExisting) {
- TestTransportAdapter transport_adapter(NULL, NULL, NULL);
+ MockTransportAdapterImpl transport_adapter(
+ NULL, NULL, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
-
- utils::SharedPtr<DeviceMock> mockdev = new DeviceMock(dev_id, uniq_id);
+ utils::SharedPtr<MockDevice> mockdev = new MockDevice(dev_id, uniq_id);
transport_adapter.AddDevice(mockdev);
std::vector<utils::SharedPtr<Device>> devList;
@@ -176,11 +166,12 @@ TEST_F(TransportAdapterTest, SearchDeviceDone_DeviceExisting) {
}
TEST_F(TransportAdapterTest, SearchDeviceFailed) {
- TestTransportAdapter transport_adapter(NULL, NULL, NULL);
+ MockTransportAdapterImpl transport_adapter(
+ NULL, NULL, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
- TransportAdapterListenerMock mock_listener;
+ MockTransportAdapterListener mock_listener;
transport_adapter.AddListener(&mock_listener);
SearchDeviceError er;
@@ -189,24 +180,24 @@ TEST_F(TransportAdapterTest, SearchDeviceFailed) {
}
TEST_F(TransportAdapterTest, AddDevice) {
- TestTransportAdapter transport_adapter(NULL, NULL, NULL);
+ MockTransportAdapterImpl transport_adapter(
+ NULL, NULL, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
-
-
- TransportAdapterListenerMock mock_listener;
+ MockTransportAdapterListener mock_listener;
transport_adapter.AddListener(&mock_listener);
- DeviceMock* mockdev = new DeviceMock(dev_id, uniq_id);
+ MockDevice* mockdev = new MockDevice(dev_id, uniq_id);
EXPECT_CALL(mock_listener, OnDeviceListUpdated(_));
transport_adapter.AddDevice(mockdev);
}
TEST_F(TransportAdapterTest, Connect_ServerNotSupported) {
- ClientConnectionListenerMock* clientMock = new ClientConnectionListenerMock();
- TestTransportAdapter transport_adapter(NULL, NULL, clientMock);
+ MockClientConnectionListener* clientMock = new MockClientConnectionListener();
+ MockTransportAdapterImpl transport_adapter(
+ NULL, NULL, clientMock, last_state_, transport_manager_settings);
EXPECT_CALL(*clientMock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
@@ -221,15 +212,14 @@ TEST_F(TransportAdapterTest, Connect_ServerNotSupported) {
}
TEST_F(TransportAdapterTest, Connect_ServerNotInitialized) {
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(NULL, serverMock, NULL);
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(
+ NULL, serverMock, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(*serverMock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
-
-
EXPECT_CALL(*serverMock, IsInitialised()).WillOnce(Return(false));
EXPECT_CALL(*serverMock, CreateConnection(dev_id, app_handle)).Times(0);
TransportAdapter::Error res = transport_adapter.Connect(dev_id, app_handle);
@@ -239,15 +229,14 @@ TEST_F(TransportAdapterTest, Connect_ServerNotInitialized) {
}
TEST_F(TransportAdapterTest, Connect_Success) {
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(NULL, serverMock, NULL);
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(
+ NULL, serverMock, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(*serverMock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
-
-
EXPECT_CALL(*serverMock, IsInitialised()).WillOnce(Return(true));
EXPECT_CALL(*serverMock, CreateConnection(dev_id, app_handle))
.WillOnce(Return(TransportAdapter::OK));
@@ -258,15 +247,14 @@ TEST_F(TransportAdapterTest, Connect_Success) {
}
TEST_F(TransportAdapterTest, Connect_DeviceAddedTwice) {
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(NULL, serverMock, NULL);
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(
+ NULL, serverMock, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(*serverMock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
-
-
EXPECT_CALL(*serverMock, IsInitialised()).WillOnce(Return(true));
EXPECT_CALL(*serverMock, CreateConnection(dev_id, app_handle))
.WillOnce(Return(TransportAdapter::OK));
@@ -282,13 +270,12 @@ TEST_F(TransportAdapterTest, Connect_DeviceAddedTwice) {
}
TEST_F(TransportAdapterTest, ConnectDevice_ServerNotAdded_DeviceAdded) {
- TestTransportAdapter transport_adapter(NULL, NULL, NULL);
+ MockTransportAdapterImpl transport_adapter(
+ NULL, NULL, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
-
-
- DeviceMock* mockdev = new DeviceMock(dev_id, uniq_id);
+ MockDevice* mockdev = new MockDevice(dev_id, uniq_id);
transport_adapter.AddDevice(mockdev);
std::vector<std::string> devList = transport_adapter.GetDeviceList();
@@ -304,9 +291,9 @@ TEST_F(TransportAdapterTest, ConnectDevice_ServerNotAdded_DeviceAdded) {
}
TEST_F(TransportAdapterTest, ConnectDevice_DeviceNotAdded) {
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(NULL, serverMock, NULL);
-
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(
+ NULL, serverMock, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(*serverMock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
@@ -322,23 +309,21 @@ TEST_F(TransportAdapterTest, ConnectDevice_DeviceNotAdded) {
}
TEST_F(TransportAdapterTest, ConnectDevice_DeviceAdded) {
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(NULL, serverMock, NULL);
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(
+ NULL, serverMock, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(*serverMock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
-
-
- DeviceMock* mockdev = new DeviceMock(dev_id, uniq_id);
+ MockDevice* mockdev = new MockDevice(dev_id, uniq_id);
transport_adapter.AddDevice(mockdev);
std::vector<std::string> devList = transport_adapter.GetDeviceList();
ASSERT_EQ(1u, devList.size());
EXPECT_EQ(uniq_id, devList[0]);
-
int app_handle = 1;
std::vector<int> intList = {app_handle};
EXPECT_CALL(*mockdev, GetApplicationList()).WillOnce(Return(intList));
@@ -353,23 +338,21 @@ TEST_F(TransportAdapterTest, ConnectDevice_DeviceAdded) {
}
TEST_F(TransportAdapterTest, ConnectDevice_DeviceAddedTwice) {
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(NULL, serverMock, NULL);
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(
+ NULL, serverMock, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(*serverMock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
-
-
- DeviceMock* mockdev = new DeviceMock(dev_id, uniq_id);
+ MockDevice* mockdev = new MockDevice(dev_id, uniq_id);
transport_adapter.AddDevice(mockdev);
std::vector<std::string> devList = transport_adapter.GetDeviceList();
ASSERT_EQ(1u, devList.size());
EXPECT_EQ(uniq_id, devList[0]);
-
int app_handle = 1;
std::vector<int> intList = {app_handle};
EXPECT_CALL(*mockdev, GetApplicationList()).WillOnce(Return(intList));
@@ -393,22 +376,21 @@ TEST_F(TransportAdapterTest, ConnectDevice_DeviceAddedTwice) {
}
TEST_F(TransportAdapterTest, Disconnect_ConnectDoneSuccess) {
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(NULL, serverMock, NULL);
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(
+ NULL, serverMock, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(*serverMock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
-
-
EXPECT_CALL(*serverMock, IsInitialised()).WillOnce(Return(true));
EXPECT_CALL(*serverMock, CreateConnection(dev_id, app_handle))
.WillOnce(Return(TransportAdapter::OK));
TransportAdapter::Error res = transport_adapter.Connect(dev_id, app_handle);
EXPECT_EQ(TransportAdapter::OK, res);
- ConnectionMock* mock_connection = new ConnectionMock();
+ MockConnection* mock_connection = new MockConnection();
transport_adapter.ConnectionCreated(mock_connection, dev_id, app_handle);
EXPECT_CALL(transport_adapter, Store());
@@ -424,21 +406,21 @@ TEST_F(TransportAdapterTest, Disconnect_ConnectDoneSuccess) {
}
TEST_F(TransportAdapterTest, DisconnectDevice_DeviceAddedConnectionCreated) {
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(NULL, serverMock, NULL);
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(
+ NULL, serverMock, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(*serverMock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
- DeviceMock* mockdev = new DeviceMock(dev_id, uniq_id);
+ MockDevice* mockdev = new MockDevice(dev_id, uniq_id);
transport_adapter.AddDevice(mockdev);
std::vector<std::string> devList = transport_adapter.GetDeviceList();
ASSERT_EQ(1u, devList.size());
EXPECT_EQ(uniq_id, devList[0]);
-
std::vector<int> intList = {app_handle};
EXPECT_CALL(*mockdev, GetApplicationList()).WillOnce(Return(intList));
@@ -448,7 +430,7 @@ TEST_F(TransportAdapterTest, DisconnectDevice_DeviceAddedConnectionCreated) {
TransportAdapter::Error res = transport_adapter.ConnectDevice(uniq_id);
EXPECT_EQ(TransportAdapter::OK, res);
- ConnectionMock* mock_connection = new ConnectionMock();
+ MockConnection* mock_connection = new MockConnection();
transport_adapter.ConnectionCreated(mock_connection, uniq_id, app_handle);
EXPECT_CALL(*mock_connection, Disconnect())
@@ -461,17 +443,18 @@ TEST_F(TransportAdapterTest, DisconnectDevice_DeviceAddedConnectionCreated) {
}
TEST_F(TransportAdapterTest, DeviceDisconnected) {
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(NULL, serverMock, NULL);
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(
+ NULL, serverMock, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(*serverMock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
- TransportAdapterListenerMock mock_listener;
+ MockTransportAdapterListener mock_listener;
transport_adapter.AddListener(&mock_listener);
- DeviceMock* mockdev = new DeviceMock(dev_id, uniq_id);
+ MockDevice* mockdev = new MockDevice(dev_id, uniq_id);
EXPECT_CALL(mock_listener, OnDeviceListUpdated(_));
transport_adapter.AddDevice(mockdev);
@@ -488,12 +471,13 @@ TEST_F(TransportAdapterTest, DeviceDisconnected) {
TransportAdapter::Error res = transport_adapter.ConnectDevice(uniq_id);
EXPECT_EQ(TransportAdapter::OK, res);
- ConnectionMock* mock_connection = new ConnectionMock();
+ MockConnection* mock_connection = new MockConnection();
transport_adapter.ConnectionCreated(mock_connection, uniq_id, app_handle);
EXPECT_CALL(*mockdev, GetApplicationList()).WillOnce(Return(intList));
- EXPECT_CALL(mock_listener, OnUnexpectedDisconnect(&transport_adapter, uniq_id,
- app_handle, _));
+ EXPECT_CALL(
+ mock_listener,
+ OnUnexpectedDisconnect(&transport_adapter, uniq_id, app_handle, _));
EXPECT_CALL(mock_listener,
OnDisconnectDeviceDone(&transport_adapter, uniq_id));
EXPECT_CALL(mock_listener, OnDeviceListUpdated(&transport_adapter));
@@ -504,8 +488,9 @@ TEST_F(TransportAdapterTest, DeviceDisconnected) {
}
TEST_F(TransportAdapterTest, AbortedConnectSuccess) {
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(NULL, serverMock, NULL);
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(
+ NULL, serverMock, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(*serverMock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
@@ -517,7 +502,7 @@ TEST_F(TransportAdapterTest, AbortedConnectSuccess) {
TransportAdapter::Error res = transport_adapter.Connect(dev_id, app_handle);
EXPECT_EQ(TransportAdapter::OK, res);
- TransportAdapterListenerMock mock_listener;
+ MockTransportAdapterListener mock_listener;
transport_adapter.AddListener(&mock_listener);
CommunicationError ce;
@@ -528,9 +513,10 @@ TEST_F(TransportAdapterTest, AbortedConnectSuccess) {
}
TEST_F(TransportAdapterTest, SendData) {
- DeviceScannerMock* dev_mock = new DeviceScannerMock();
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(dev_mock, serverMock, NULL);
+ MockDeviceScanner* dev_mock = new MockDeviceScanner();
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(
+ dev_mock, serverMock, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(*dev_mock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(*serverMock, Init()).WillOnce(Return(TransportAdapter::OK));
@@ -543,7 +529,7 @@ TEST_F(TransportAdapterTest, SendData) {
TransportAdapter::Error res = transport_adapter.Connect(dev_id, app_handle);
EXPECT_EQ(TransportAdapter::OK, res);
- ConnectionMock* mock_connection = new ConnectionMock();
+ MockConnection* mock_connection = new MockConnection();
transport_adapter.ConnectionCreated(mock_connection, dev_id, app_handle);
EXPECT_CALL(transport_adapter, Store());
@@ -563,10 +549,14 @@ TEST_F(TransportAdapterTest, SendData) {
}
TEST_F(TransportAdapterTest, SendData_ConnectionNotEstablished) {
- DeviceScannerMock* dev_mock = new DeviceScannerMock();
- ClientConnectionListenerMock* clientMock = new ClientConnectionListenerMock();
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(dev_mock, serverMock, clientMock);
+ MockDeviceScanner* dev_mock = new MockDeviceScanner();
+ MockClientConnectionListener* clientMock = new MockClientConnectionListener();
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(dev_mock,
+ serverMock,
+ clientMock,
+ last_state_,
+ transport_manager_settings);
EXPECT_CALL(*dev_mock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(*clientMock, Init()).WillOnce(Return(TransportAdapter::OK));
@@ -580,7 +570,7 @@ TEST_F(TransportAdapterTest, SendData_ConnectionNotEstablished) {
TransportAdapter::Error res = transport_adapter.Connect(dev_id, app_handle);
EXPECT_EQ(TransportAdapter::OK, res);
- ConnectionMock* mock_connection = new ConnectionMock();
+ MockConnection* mock_connection = new MockConnection();
transport_adapter.ConnectionCreated(mock_connection, dev_id, app_handle);
const unsigned int kSize = 3;
@@ -597,9 +587,10 @@ TEST_F(TransportAdapterTest, SendData_ConnectionNotEstablished) {
}
TEST_F(TransportAdapterTest, StartClientListening_ClientNotInitialized) {
- DeviceScannerMock* dev_mock = new DeviceScannerMock();
- ClientConnectionListenerMock* clientMock = new ClientConnectionListenerMock();
- TestTransportAdapter transport_adapter(dev_mock, NULL, clientMock);
+ MockDeviceScanner* dev_mock = new MockDeviceScanner();
+ MockClientConnectionListener* clientMock = new MockClientConnectionListener();
+ MockTransportAdapterImpl transport_adapter(
+ dev_mock, NULL, clientMock, last_state_, transport_manager_settings);
EXPECT_CALL(*dev_mock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(*clientMock, Init()).WillOnce(Return(TransportAdapter::OK));
@@ -617,9 +608,10 @@ TEST_F(TransportAdapterTest, StartClientListening_ClientNotInitialized) {
}
TEST_F(TransportAdapterTest, StartClientListening) {
- DeviceScannerMock* dev_mock = new DeviceScannerMock();
- ClientConnectionListenerMock* clientMock = new ClientConnectionListenerMock();
- TestTransportAdapter transport_adapter(dev_mock, NULL, clientMock);
+ MockDeviceScanner* dev_mock = new MockDeviceScanner();
+ MockClientConnectionListener* clientMock = new MockClientConnectionListener();
+ MockTransportAdapterImpl transport_adapter(
+ dev_mock, NULL, clientMock, last_state_, transport_manager_settings);
EXPECT_CALL(*dev_mock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(*clientMock, Init()).WillOnce(Return(TransportAdapter::OK));
@@ -638,10 +630,14 @@ TEST_F(TransportAdapterTest, StartClientListening) {
}
TEST_F(TransportAdapterTest, StopClientListening_Success) {
- DeviceScannerMock* dev_mock = new DeviceScannerMock();
- ClientConnectionListenerMock* clientMock = new ClientConnectionListenerMock();
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(dev_mock, serverMock, clientMock);
+ MockDeviceScanner* dev_mock = new MockDeviceScanner();
+ MockClientConnectionListener* clientMock = new MockClientConnectionListener();
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(dev_mock,
+ serverMock,
+ clientMock,
+ last_state_,
+ transport_manager_settings);
EXPECT_CALL(*dev_mock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(*clientMock, Init()).WillOnce(Return(TransportAdapter::OK));
@@ -668,10 +664,14 @@ TEST_F(TransportAdapterTest, StopClientListening_Success) {
}
TEST_F(TransportAdapterTest, FindNewApplicationsRequest) {
- DeviceScannerMock* dev_mock = new DeviceScannerMock();
- ClientConnectionListenerMock* clientMock = new ClientConnectionListenerMock();
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(dev_mock, serverMock, clientMock);
+ MockDeviceScanner* dev_mock = new MockDeviceScanner();
+ MockClientConnectionListener* clientMock = new MockClientConnectionListener();
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(dev_mock,
+ serverMock,
+ clientMock,
+ last_state_,
+ transport_manager_settings);
EXPECT_CALL(*dev_mock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(*clientMock, Init()).WillOnce(Return(TransportAdapter::OK));
@@ -679,7 +679,7 @@ TEST_F(TransportAdapterTest, FindNewApplicationsRequest) {
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
- TransportAdapterListenerMock mock_listener;
+ MockTransportAdapterListener mock_listener;
transport_adapter.AddListener(&mock_listener);
EXPECT_CALL(mock_listener, OnFindNewApplicationsRequest(&transport_adapter));
@@ -691,11 +691,12 @@ TEST_F(TransportAdapterTest, FindNewApplicationsRequest) {
}
TEST_F(TransportAdapterTest, GetDeviceAndApplicationLists) {
- TestTransportAdapter transport_adapter(NULL, NULL, NULL);
+ MockTransportAdapterImpl transport_adapter(
+ NULL, NULL, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
transport_adapter.Init();
- DeviceMock* mockdev = new DeviceMock(dev_id, uniq_id);
+ MockDevice* mockdev = new MockDevice(dev_id, uniq_id);
transport_adapter.AddDevice(mockdev);
std::vector<std::string> devList = transport_adapter.GetDeviceList();
@@ -708,12 +709,12 @@ TEST_F(TransportAdapterTest, GetDeviceAndApplicationLists) {
std::vector<int> res = transport_adapter.GetApplicationList(uniq_id);
ASSERT_EQ(1u, res.size());
EXPECT_EQ(intList[0], res[0]);
-
}
TEST_F(TransportAdapterTest, FindEstablishedConnection) {
- ServerConnectionFactoryMock* serverMock = new ServerConnectionFactoryMock();
- TestTransportAdapter transport_adapter(NULL, serverMock, NULL);
+ MockServerConnectionFactory* serverMock = new MockServerConnectionFactory();
+ MockTransportAdapterImpl transport_adapter(
+ NULL, serverMock, NULL, last_state_, transport_manager_settings);
EXPECT_CALL(*serverMock, Init()).WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(transport_adapter, Restore()).WillOnce(Return(true));
@@ -725,7 +726,7 @@ TEST_F(TransportAdapterTest, FindEstablishedConnection) {
TransportAdapter::Error res = transport_adapter.Connect(dev_id, app_handle);
EXPECT_EQ(TransportAdapter::OK, res);
- ConnectionSPtr mock_connection = new ConnectionMock();
+ ConnectionSPtr mock_connection = new MockConnection();
transport_adapter.ConnectionCreated(mock_connection, dev_id, app_handle);
EXPECT_CALL(transport_adapter, Store());
diff --git a/src/components/transport_manager/test/transport_manager_default_test.cc b/src/components/transport_manager/test/transport_manager_default_test.cc
index 4e0bd94845..8207737d93 100644
--- a/src/components/transport_manager/test/transport_manager_default_test.cc
+++ b/src/components/transport_manager/test/transport_manager_default_test.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -32,15 +32,44 @@
#include "gtest/gtest.h"
#include "transport_manager/transport_manager.h"
#include "transport_manager/transport_manager_default.h"
+#include "resumption/last_state.h"
+#include "transport_manager/mock_transport_manager_settings.h"
+#include "resumption/last_state.h"
namespace test {
-namespace test_transport_manager_instance {
-TEST(TestTransportManagerDefault, CreateOnlyInstance) {
- transport_manager::TransportManager* instance =
- transport_manager::TransportManagerDefault::instance();
- ASSERT_EQ(instance, transport_manager::TransportManagerDefault::instance());
- transport_manager::TransportManagerDefault::destroy();
+namespace components {
+namespace transport_manager_test {
+
+using ::testing::Return;
+
+TEST(TestTransportManagerDefault, Init_LastStateNotUsed) {
+ MockTransportManagerSettings transport_manager_settings;
+ transport_manager::TransportManagerDefault transport_manager(
+ transport_manager_settings);
+ resumption::LastState last_state("app_storage_folder", "app_info_storage2");
+
+ EXPECT_CALL(transport_manager_settings, use_last_state())
+ .WillRepeatedly(Return(false));
+ EXPECT_CALL(transport_manager_settings, transport_manager_tcp_adapter_port())
+ .WillRepeatedly(Return(1u));
+ transport_manager.Init(last_state);
+}
+
+TEST(TestTransportManagerDefault, Init_LastStateUsed) {
+ MockTransportManagerSettings transport_manager_settings;
+ transport_manager::TransportManagerDefault transport_manager(
+ transport_manager_settings);
+ resumption::LastState last_state("app_storage_folder", "app_info_storage2");
+
+ EXPECT_CALL(transport_manager_settings, use_last_state())
+ .WillRepeatedly(Return(true));
+ EXPECT_CALL(transport_manager_settings, transport_manager_tcp_adapter_port())
+ .WillRepeatedly(Return(1u));
+
+ transport_manager.Init(last_state);
+ transport_manager.Stop();
}
+} // namespace transport_manager_test
+} // namespace components
} // namespace test
-} // namespace test_transport_manager_instance
diff --git a/src/components/transport_manager/test/transport_manager_impl_test.cc b/src/components/transport_manager/test/transport_manager_impl_test.cc
index 8ee1d70887..ddfd827358 100644
--- a/src/components/transport_manager/test/transport_manager_impl_test.cc
+++ b/src/components/transport_manager/test/transport_manager_impl_test.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2015, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -30,17 +30,24 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
+#include <string>
#include "gtest/gtest.h"
#include "protocol/raw_message.h"
#include "transport_manager/common.h"
#include "transport_manager/transport_manager_impl.h"
-#include "include/transport_adapter_mock.h"
-#include "include/transport_manager_listener_mock.h"
-#include "include/transport_adapter_listener_mock.h"
-#include "include/time_metric_observer_mock.h"
+#include "transport_manager/mock_telemetry_observer.h"
+#include "transport_manager/transport_manager_listener_mock.h"
+#include "transport_manager/mock_transport_adapter_listener.h"
+#include "transport_manager/mock_telemetry_observer.h"
+#include "transport_manager/transport_adapter_mock.h"
+#include "transport_manager/mock_transport_manager_impl.h"
+#include "transport_manager/mock_transport_manager_settings.h"
+#include "utils/make_shared.h"
+#include "utils/shared_ptr.h"
-#include "transport_manager/transport_adapter/transport_adapter_event.h"
+#include "resumption/last_state.h"
+#include "utils/make_shared.h"
using ::testing::_;
using ::testing::AtLeast;
@@ -49,377 +56,410 @@ using ::testing::Return;
using ::protocol_handler::RawMessage;
using ::protocol_handler::RawMessagePtr;
+using utils::MakeShared;
+
namespace test {
namespace components {
namespace transport_manager_test {
-using namespace ::transport_manager;
-
-class TransportManagerTest : public TransportManagerImpl {
- public:
- void TestHandle(TransportAdapterEvent test_event) { Handle(test_event); }
-};
+const std::string kAppStorageFolder = "app_storage_folder";
+const std::string kAppInfoFolder = "app_info_folder";
+const int kAsyncExpectationsTimeout = 10000;
class TransportManagerImplTest : public ::testing::Test {
protected:
- virtual void SetUp() {
- tm.Init();
- mock_adapter = new TransportAdapterMock();
- tm_listener = new TransportManagerListenerMock();
-
- EXPECT_EQ(E_SUCCESS, tm.AddEventListener(tm_listener));
- EXPECT_CALL(*mock_adapter, AddListener(_));
- EXPECT_CALL(*mock_adapter, IsInitialised()).WillOnce(Return(true));
- EXPECT_EQ(::transport_manager::E_SUCCESS,
- tm.AddTransportAdapter(mock_adapter));
-
- device_handle_ = 1;
+ TransportManagerImplTest()
+ : tm_(settings)
+ , device_handle_(1)
+ , mac_address_("MA:CA:DR:ES:S")
+ , dev_info_(device_handle_, mac_address_, "TestDeviceName", "BTMAC") {}
+
+ void SetUp() OVERRIDE {
+ resumption::LastState last_state_("app_storage_folder", "app_info_storage");
+ tm_.Init(last_state_);
+ mock_adapter_ = new MockTransportAdapter();
+ tm_listener_ = MakeShared<TransportManagerListenerMock>();
+
+#ifdef TELEMETRY_MONITOR
+ tm_.SetTelemetryObserver(&mock_metric_observer_);
+#endif // TELEMETRY_MONITOR
+ EXPECT_EQ(E_SUCCESS, tm_.AddEventListener(tm_listener_.get()));
+ EXPECT_CALL(*mock_adapter_, AddListener(_));
+ EXPECT_CALL(*mock_adapter_, IsInitialised()).WillOnce(Return(true));
+ EXPECT_EQ(E_SUCCESS, tm_.AddTransportAdapter(mock_adapter_));
+
connection_key_ = 1;
- mac_address_ = "MA:CA:DR:ES:S";
- error_ = new BaseError();
+ error_ = MakeShared<BaseError>();
const unsigned int version_protocol_ = 1;
const unsigned int kSize = 12;
- unsigned char data[kSize] = {0x20, 0x07, 0x01, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
+ unsigned char data[kSize] = {
+ 0x20, 0x07, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
test_message_ =
- new RawMessage(connection_key_, version_protocol_, data, kSize);
+ MakeShared<RawMessage>(connection_key_, version_protocol_, data, kSize);
}
- virtual void TearDown() { delete tm_listener; }
-
- void HandleDeviceListUpdated();
- void HandleConnection();
- void HandleSendDone();
- void HandleSendFailed();
- void HandleSearchDone();
- void HandleSearchFail();
- void HandleFindNewApplicationsRequest();
- void HandleConnectionFailed();
- void HandleConnectionClosed();
- void HandleDisconnectionFailed();
- void HandleReceiveDone();
-
- TransportManagerTest tm;
- TransportAdapterMock* mock_adapter;
-
- TransportManagerListenerMock* tm_listener;
-
- const ApplicationHandle application_id = 1;
-
- // count of connections
- ConnectionUID connection_key_;
- RawMessagePtr test_message_;
- DeviceHandle device_handle_;
- std::string mac_address_;
-
- DeviceList dev;
- BaseErrorPtr error_;
-};
-
-void TransportManagerImplTest::HandleDeviceListUpdated() {
- int type = static_cast<int>(
- TransportAdapterListenerImpl::EventTypeEnum::ON_DEVICE_LIST_UPDATED);
- const DeviceInfo dev_info(device_handle_, mac_address_, "TestDeviceName",
- "BTMAC");
-
- TransportAdapterEvent test_event(type, mock_adapter, dev_info.mac_address(),
- application_id, test_message_, error_);
- dev.push_back(dev_info.mac_address());
- std::vector<DeviceInfo> vector_dev_info;
- std::vector<DeviceInfo>::iterator it = vector_dev_info.begin();
- vector_dev_info.insert(it, dev_info);
-
- EXPECT_CALL(*mock_adapter, GetDeviceList())
- .Times(AtLeast(1))
- .WillRepeatedly(Return(dev));
- EXPECT_CALL(*mock_adapter, DeviceName(dev_info.mac_address()))
- .Times(AtLeast(1))
- .WillRepeatedly(Return(dev_info.name()));
- EXPECT_CALL(*mock_adapter, GetConnectionType())
- .Times(AtLeast(1))
- .WillRepeatedly(Return(dev_info.connection_type()));
-
- EXPECT_CALL(*tm_listener, OnDeviceFound(dev_info));
- EXPECT_CALL(*tm_listener, OnDeviceAdded(dev_info));
- EXPECT_CALL(*tm_listener, OnDeviceListUpdated(vector_dev_info));
-
- tm.TestHandle(test_event);
- dev.pop_back();
-}
-
-void TransportManagerImplTest::HandleConnection() {
- int type = static_cast<int>(
- TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_DONE);
- const DeviceInfo dev_info(device_handle_, mac_address_, "TestDeviceName",
- "BTMAC");
-
- TransportAdapterEvent test_event(type, mock_adapter, dev_info.mac_address(),
- application_id, test_message_, error_);
-
- EXPECT_CALL(*mock_adapter, DeviceName(dev_info.mac_address()))
- .WillOnce(Return(dev_info.name()));
- EXPECT_CALL(*mock_adapter, GetConnectionType())
- .WillOnce(Return(dev_info.connection_type()));
-
- EXPECT_CALL(*tm_listener, OnConnectionEstablished(dev_info, connection_key_));
-
- tm.TestHandle(test_event);
-}
-
-void TransportManagerImplTest::HandleConnectionFailed() {
- int type = static_cast<int>(
- TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_FAIL);
+ void HandleDeviceListUpdated() {
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_DEVICE_LIST_UPDATED);
+
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ dev_info_.mac_address(),
+ application_id_,
+ test_message_,
+ error_);
+ device_list_.push_back(dev_info_.mac_address());
+ std::vector<DeviceInfo> vector_dev_info;
+ vector_dev_info.push_back(dev_info_);
+
+ EXPECT_CALL(*mock_adapter_, GetDeviceList())
+ .Times(AtLeast(1))
+ .WillRepeatedly(Return(device_list_));
+ EXPECT_CALL(*mock_adapter_, DeviceName(dev_info_.mac_address()))
+ .Times(AtLeast(1))
+ .WillRepeatedly(Return(dev_info_.name()));
+ EXPECT_CALL(*mock_adapter_, GetConnectionType())
+ .Times(AtLeast(1))
+ .WillRepeatedly(Return(dev_info_.connection_type()));
+
+ EXPECT_CALL(*tm_listener_, OnDeviceFound(dev_info_));
+ EXPECT_CALL(*tm_listener_, OnDeviceAdded(dev_info_));
+ EXPECT_CALL(*tm_listener_, OnDeviceListUpdated(vector_dev_info));
+
+ tm_.TestHandle(test_event);
+ device_list_.pop_back();
+ }
- const DeviceInfo dev_info(device_handle_, mac_address_, "TestDeviceName",
- "BTMAC");
+ void HandleConnection() {
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_DONE);
- TransportAdapterEvent test_event(type, mock_adapter, dev_info.mac_address(),
- application_id, test_message_, error_);
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ dev_info_.mac_address(),
+ application_id_,
+ test_message_,
+ error_);
- EXPECT_CALL(*mock_adapter, DeviceName(dev_info.mac_address()))
- .WillOnce(Return(dev_info.name()));
- EXPECT_CALL(*mock_adapter, GetConnectionType())
- .WillOnce(Return(dev_info.connection_type()));
+ EXPECT_CALL(*mock_adapter_, DeviceName(dev_info_.mac_address()))
+ .WillOnce(Return(dev_info_.name()));
+ EXPECT_CALL(*mock_adapter_, GetConnectionType())
+ .WillOnce(Return(dev_info_.connection_type()));
- EXPECT_CALL(*tm_listener, OnConnectionFailed(dev_info, _));
+ EXPECT_CALL(*tm_listener_,
+ OnConnectionEstablished(dev_info_, connection_key_));
- tm.TestHandle(test_event);
-}
+ tm_.TestHandle(test_event);
+ }
-void TransportManagerImplTest::HandleSendDone() {
- int type = static_cast<int>(
- TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_DONE);
- TransportAdapterEvent test_event(type, mock_adapter, mac_address_,
- application_id, test_message_, error_);
+ void HandleConnectionFailed() {
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_CONNECT_FAIL);
- EXPECT_CALL(*tm_listener, OnTMMessageSend(test_message_));
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ dev_info_.mac_address(),
+ application_id_,
+ test_message_,
+ error_);
- tm.TestHandle(test_event);
-}
+ EXPECT_CALL(*mock_adapter_, DeviceName(dev_info_.mac_address()))
+ .WillOnce(Return(dev_info_.name()));
+ EXPECT_CALL(*mock_adapter_, GetConnectionType())
+ .WillOnce(Return(dev_info_.connection_type()));
-void TransportManagerImplTest::HandleReceiveDone() {
- int type = static_cast<int>(
- TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_DONE);
- TransportAdapterEvent test_event(type, mock_adapter, mac_address_,
- application_id, test_message_, error_);
+ EXPECT_CALL(*tm_listener_, OnConnectionFailed(dev_info_, _));
- EXPECT_CALL(*tm_listener, OnTMMessageReceived(test_message_));
+ tm_.TestHandle(test_event);
+ }
- tm.TestHandle(test_event);
-}
+ void HandleSendDone() {
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_DONE);
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
+#ifdef TELEMETRY_MONITOR
+ EXPECT_CALL(mock_metric_observer_, StopRawMsg(test_event.event_data.get()));
+#endif // TELEMETRY_MONITOR
+ EXPECT_CALL(*tm_listener_, OnTMMessageSend(test_message_));
+
+ tm_.TestHandle(test_event);
+ }
-void TransportManagerImplTest::HandleSendFailed() {
- int type = static_cast<int>(
- TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_FAIL);
+ void HandleReceiveDone() {
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_DONE);
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
+#ifdef TELEMETRY_MONITOR
+ EXPECT_CALL(mock_metric_observer_, StopRawMsg(_));
+#endif // TELEMETRY_MONITOR
+ EXPECT_CALL(*tm_listener_, OnTMMessageReceived(test_message_));
+
+ tm_.TestHandle(test_event);
+ }
- TransportAdapterEvent test_event(type, mock_adapter, mac_address_,
- application_id, test_message_, error_);
+ void HandleSendFailed() {
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_FAIL);
+
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
+#ifdef TELEMETRY_MONITOR
+ EXPECT_CALL(mock_metric_observer_, StopRawMsg(_));
+#endif // TELEMETRY_MONITOR
+ tm_.TestHandle(test_event);
+ }
- tm.TestHandle(test_event);
-}
+ void HandleSearchDone() {
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_DONE);
-void TransportManagerImplTest::HandleSearchDone() {
- int type = static_cast<int>(
- TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_DONE);
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
- TransportAdapterEvent test_event(type, mock_adapter, mac_address_,
- application_id, test_message_, error_);
+ EXPECT_CALL(*tm_listener_, OnScanDevicesFinished());
- EXPECT_CALL(*tm_listener, OnScanDevicesFinished());
+ tm_.TestHandle(test_event);
+ }
- tm.TestHandle(test_event);
-}
+ void HandleSearchFail() {
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_FAIL);
-void TransportManagerImplTest::HandleSearchFail() {
- int type = static_cast<int>(
- TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_FAIL);
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
- TransportAdapterEvent test_event(type, mock_adapter, mac_address_,
- application_id, test_message_, error_);
+ EXPECT_CALL(*tm_listener_, OnScanDevicesFailed(_));
- EXPECT_CALL(*tm_listener, OnScanDevicesFailed(_));
+ tm_.TestHandle(test_event);
+ }
- tm.TestHandle(test_event);
-}
+ void HandleFindNewApplicationsRequest() {
+ const int type =
+ static_cast<int>(TransportAdapterListenerImpl::EventTypeEnum::
+ ON_FIND_NEW_APPLICATIONS_REQUEST);
-void TransportManagerImplTest::HandleFindNewApplicationsRequest() {
- int type = static_cast<int>(TransportAdapterListenerImpl::EventTypeEnum::
- ON_FIND_NEW_APPLICATIONS_REQUEST);
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
- TransportAdapterEvent test_event(type, mock_adapter, mac_address_,
- application_id, test_message_, error_);
+ EXPECT_CALL(*tm_listener_, OnFindNewApplicationsRequest());
- EXPECT_CALL(*tm_listener, OnFindNewApplicationsRequest());
+ tm_.TestHandle(test_event);
+ }
- tm.TestHandle(test_event);
-}
+ void HandleConnectionClosed() {
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_DONE);
-void TransportManagerImplTest::HandleConnectionClosed() {
- int type = static_cast<int>(
- TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_DONE);
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
- TransportAdapterEvent test_event(type, mock_adapter, mac_address_,
- application_id, test_message_, error_);
+ EXPECT_CALL(*tm_listener_, OnConnectionClosed(application_id_));
+ EXPECT_CALL(*mock_adapter_,
+ RemoveFinalizedConnection(mac_address_, application_id_));
- EXPECT_CALL(*tm_listener, OnConnectionClosed(application_id));
+ tm_.TestHandle(test_event);
+ }
- tm.TestHandle(test_event);
-}
+ void HandleDisconnectionFailed() {
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_FAIL);
-void TransportManagerImplTest::HandleDisconnectionFailed() {
- int type = static_cast<int>(
- TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_FAIL);
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
- TransportAdapterEvent test_event(type, mock_adapter, mac_address_,
- application_id, test_message_, error_);
+ EXPECT_CALL(*tm_listener_, OnDisconnectFailed(device_handle_, _));
- EXPECT_CALL(*tm_listener, OnDisconnectFailed(device_handle_, _));
+ tm_.TestHandle(test_event);
+ }
- tm.TestHandle(test_event);
-}
+ void UninitializeTM() {
+ EXPECT_CALL(*mock_adapter_, Terminate());
+ ASSERT_EQ(E_SUCCESS, tm_.Stop());
+ }
+ MockTransportManagerSettings settings;
+ MockTransportManagerImpl tm_;
+#ifdef TELEMETRY_MONITOR
+ MockTMTelemetryObserver mock_metric_observer_;
+#endif // TELEMETRY_MONITOR
+ MockTransportAdapter* mock_adapter_;
-TEST(TransportManagerTest, SearchDevices_AdaptersNotAdded) {
- TransportManagerTest tm;
- tm.Init();
+ utils::SharedPtr<TransportManagerListenerMock> tm_listener_;
- EXPECT_EQ(E_SUCCESS, tm.SearchDevices());
-}
+ const ApplicationHandle application_id_ = 1;
-TEST(TransportManagerTest, AddTransportAdapter) {
- TransportManagerTest tm;
- tm.Init();
+ ConnectionUID connection_key_;
+ RawMessagePtr test_message_;
+ DeviceHandle device_handle_;
+ std::string mac_address_;
- TransportAdapterMock* mock_adapter = new TransportAdapterMock();
- TransportManagerListenerMock* tm_listener =
- new TransportManagerListenerMock();
+ const DeviceInfo dev_info_;
+ DeviceList device_list_;
+ BaseErrorPtr error_;
+};
- EXPECT_EQ(E_SUCCESS, tm.AddEventListener(tm_listener));
- EXPECT_CALL(*mock_adapter, AddListener(_));
- EXPECT_CALL(*mock_adapter, IsInitialised()).WillOnce(Return(false));
- EXPECT_CALL(*mock_adapter, Init()).WillOnce(Return(TransportAdapter::OK));
- EXPECT_EQ(::transport_manager::E_SUCCESS,
- tm.AddTransportAdapter(mock_adapter));
+TEST_F(TransportManagerImplTest, SearchDevices_AdaptersNotAdded) {
+ EXPECT_CALL(*mock_adapter_, SearchDevices())
+ .WillOnce(
+ Return(transport_manager::transport_adapter::TransportAdapter::OK));
+ EXPECT_EQ(E_SUCCESS, tm_.SearchDevices());
}
TEST_F(TransportManagerImplTest, AddTransportAdapterSecondTime) {
- EXPECT_EQ(E_ADAPTER_EXISTS, tm.AddTransportAdapter(mock_adapter));
+ EXPECT_EQ(E_ADAPTER_EXISTS, tm_.AddTransportAdapter(mock_adapter_));
}
TEST_F(TransportManagerImplTest, ConnectDevice) {
HandleDeviceListUpdated();
- EXPECT_CALL(*mock_adapter, ConnectDevice(mac_address_))
+ EXPECT_CALL(*mock_adapter_, ConnectDevice(mac_address_))
.WillOnce(Return(TransportAdapter::OK));
- EXPECT_EQ(E_SUCCESS, tm.ConnectDevice(device_handle_));
+ EXPECT_EQ(E_SUCCESS, tm_.ConnectDevice(device_handle_));
}
TEST_F(TransportManagerImplTest, ConnectDevice_DeviceNotHandled) {
- EXPECT_CALL(*mock_adapter, ConnectDevice(mac_address_)).Times(0);
- EXPECT_EQ(E_INVALID_HANDLE, tm.ConnectDevice(device_handle_));
+ EXPECT_CALL(*mock_adapter_, ConnectDevice(mac_address_)).Times(0);
+ EXPECT_EQ(E_INVALID_HANDLE, tm_.ConnectDevice(device_handle_));
}
TEST_F(TransportManagerImplTest, ConnectDevice_DeviceNotConnected) {
HandleDeviceListUpdated();
- EXPECT_CALL(*mock_adapter, ConnectDevice(mac_address_))
+ EXPECT_CALL(*mock_adapter_, ConnectDevice(mac_address_))
.WillOnce(Return(TransportAdapter::FAIL));
- EXPECT_EQ(E_INTERNAL_ERROR, tm.ConnectDevice(device_handle_));
+ EXPECT_EQ(E_INTERNAL_ERROR, tm_.ConnectDevice(device_handle_));
}
TEST_F(TransportManagerImplTest, DisconnectDevice) {
HandleDeviceListUpdated();
- EXPECT_CALL(*mock_adapter, ConnectDevice(mac_address_))
+ EXPECT_CALL(*mock_adapter_, ConnectDevice(mac_address_))
.WillOnce(Return(TransportAdapter::OK));
- EXPECT_EQ(E_SUCCESS, tm.ConnectDevice(device_handle_));
+ EXPECT_EQ(E_SUCCESS, tm_.ConnectDevice(device_handle_));
- EXPECT_CALL(*mock_adapter, DisconnectDevice(mac_address_))
+ EXPECT_CALL(*mock_adapter_, DisconnectDevice(mac_address_))
.WillOnce(Return(TransportAdapter::OK));
- EXPECT_EQ(E_SUCCESS, tm.DisconnectDevice(device_handle_));
+ EXPECT_EQ(E_SUCCESS, tm_.DisconnectDevice(device_handle_));
}
TEST_F(TransportManagerImplTest, DisconnectDevice_ConnectionFailed) {
HandleDeviceListUpdated();
- EXPECT_CALL(*mock_adapter, ConnectDevice(mac_address_))
+ EXPECT_CALL(*mock_adapter_, ConnectDevice(mac_address_))
.WillOnce(Return(TransportAdapter::FAIL));
- EXPECT_EQ(E_INTERNAL_ERROR, tm.ConnectDevice(device_handle_));
+ EXPECT_EQ(E_INTERNAL_ERROR, tm_.ConnectDevice(device_handle_));
- EXPECT_CALL(*mock_adapter, DisconnectDevice(mac_address_))
+ EXPECT_CALL(*mock_adapter_, DisconnectDevice(mac_address_))
.WillOnce(Return(TransportAdapter::FAIL));
- EXPECT_EQ(E_INTERNAL_ERROR, tm.DisconnectDevice(device_handle_));
+ // Even with fail, we get Success
+ EXPECT_EQ(E_SUCCESS, tm_.DisconnectDevice(device_handle_));
}
TEST_F(TransportManagerImplTest, DisconnectDevice_DeviceNotConnected) {
- EXPECT_CALL(*mock_adapter, DisconnectDevice(mac_address_)).Times(0);
- EXPECT_EQ(E_INVALID_HANDLE, tm.DisconnectDevice(device_handle_));
+ EXPECT_CALL(*mock_adapter_, DisconnectDevice(mac_address_)).Times(0);
+ EXPECT_EQ(E_INVALID_HANDLE, tm_.DisconnectDevice(device_handle_));
}
TEST_F(TransportManagerImplTest, Disconnect) {
// Arrange
HandleConnection();
- EXPECT_CALL(*mock_adapter, Disconnect(mac_address_, application_id))
+ EXPECT_CALL(*mock_adapter_, Disconnect(mac_address_, application_id_))
.WillOnce(Return(TransportAdapter::OK));
// Assert
- EXPECT_EQ(E_SUCCESS, tm.Disconnect(connection_key_));
+ EXPECT_EQ(E_SUCCESS, tm_.Disconnect(connection_key_));
}
TEST_F(TransportManagerImplTest, Disconnect_DisconnectionFailed) {
// Arrange
HandleConnection();
- EXPECT_CALL(*mock_adapter, Disconnect(mac_address_, application_id))
+ EXPECT_CALL(*mock_adapter_, Disconnect(mac_address_, application_id_))
.WillOnce(Return(TransportAdapter::FAIL));
// Assert
- EXPECT_EQ(E_INTERNAL_ERROR, tm.Disconnect(connection_key_));
+ // Even with fail, we get Success
+ EXPECT_EQ(E_SUCCESS, tm_.Disconnect(connection_key_));
}
TEST_F(TransportManagerImplTest, Disconnect_ConnectionNotExist) {
- EXPECT_CALL(*mock_adapter, Disconnect(mac_address_, application_id)).Times(0);
+ EXPECT_CALL(*mock_adapter_, Disconnect(mac_address_, application_id_))
+ .Times(0);
// Assert
- EXPECT_EQ(E_INVALID_HANDLE, tm.Disconnect(connection_key_));
+ EXPECT_EQ(E_INVALID_HANDLE, tm_.Disconnect(connection_key_));
}
TEST_F(TransportManagerImplTest, Disconnect_ConnectionDoesNotExists) {
// Arrange
HandleDeviceListUpdated();
- EXPECT_CALL(*mock_adapter, ConnectDevice(mac_address_))
+ EXPECT_CALL(*mock_adapter_, ConnectDevice(mac_address_))
.WillRepeatedly(Return(TransportAdapter::OK));
- EXPECT_EQ(E_SUCCESS, tm.ConnectDevice(device_handle_));
+ EXPECT_EQ(E_SUCCESS, tm_.ConnectDevice(device_handle_));
- EXPECT_CALL(*mock_adapter, Disconnect(mac_address_, application_id))
+ EXPECT_CALL(*mock_adapter_, Disconnect(mac_address_, application_id_))
.WillRepeatedly(Return(TransportAdapter::OK));
// Assert
- EXPECT_EQ(E_INVALID_HANDLE, tm.Disconnect(connection_key_));
+ EXPECT_EQ(E_INVALID_HANDLE, tm_.Disconnect(connection_key_));
}
-TEST_F(TransportManagerImplTest, DisconnectForce) {
+TEST_F(TransportManagerImplTest, DisconnectForce_TMIsInitialized) {
// Arrange
HandleConnection();
- EXPECT_CALL(*mock_adapter, Disconnect(mac_address_, application_id))
+ EXPECT_CALL(*mock_adapter_, Disconnect(mac_address_, application_id_))
.WillRepeatedly(Return(TransportAdapter::OK));
// Assert
- EXPECT_EQ(E_SUCCESS, tm.DisconnectForce(connection_key_));
+ EXPECT_EQ(E_SUCCESS, tm_.DisconnectForce(connection_key_));
}
TEST_F(TransportManagerImplTest, DisconnectForce_) {
// Arrange
HandleConnection();
- EXPECT_CALL(*mock_adapter, Disconnect(mac_address_, application_id))
+ EXPECT_CALL(*mock_adapter_, Disconnect(mac_address_, application_id_))
.WillRepeatedly(Return(TransportAdapter::OK));
// Assert
- EXPECT_EQ(E_SUCCESS, tm.DisconnectForce(connection_key_));
+ EXPECT_EQ(E_SUCCESS, tm_.DisconnectForce(connection_key_));
}
TEST_F(TransportManagerImplTest, SearchDevices_DeviceConnected) {
HandleDeviceListUpdated();
- EXPECT_CALL(*mock_adapter, SearchDevices())
+ EXPECT_CALL(*mock_adapter_, SearchDevices())
.WillOnce(Return(TransportAdapter::OK));
- EXPECT_EQ(E_SUCCESS, tm.SearchDevices());
+ EXPECT_EQ(E_SUCCESS, tm_.SearchDevices());
HandleSearchDone();
}
@@ -427,270 +467,259 @@ TEST_F(TransportManagerImplTest, SearchDevices_DeviceConnected) {
TEST_F(TransportManagerImplTest, SearchDevices_DeviceNotFound) {
HandleDeviceListUpdated();
- EXPECT_CALL(*mock_adapter, SearchDevices())
+ EXPECT_CALL(*mock_adapter_, SearchDevices())
.WillOnce(Return(TransportAdapter::FAIL));
- EXPECT_EQ(E_ADAPTERS_FAIL, tm.SearchDevices());
+ EXPECT_EQ(E_ADAPTERS_FAIL, tm_.SearchDevices());
}
TEST_F(TransportManagerImplTest, SearchDevices_AdapterNotSupported) {
HandleDeviceListUpdated();
- EXPECT_CALL(*mock_adapter, SearchDevices())
+ EXPECT_CALL(*mock_adapter_, SearchDevices())
.WillOnce(Return(TransportAdapter::NOT_SUPPORTED));
- EXPECT_EQ(E_ADAPTERS_FAIL, tm.SearchDevices());
+ EXPECT_EQ(E_ADAPTERS_FAIL, tm_.SearchDevices());
}
TEST_F(TransportManagerImplTest, SearchDevices_AdapterWithBadState) {
HandleDeviceListUpdated();
- EXPECT_CALL(*mock_adapter, SearchDevices())
+ EXPECT_CALL(*mock_adapter_, SearchDevices())
.WillOnce(Return(TransportAdapter::BAD_STATE));
- EXPECT_EQ(E_ADAPTERS_FAIL, tm.SearchDevices());
+ EXPECT_EQ(E_ADAPTERS_FAIL, tm_.SearchDevices());
}
TEST_F(TransportManagerImplTest, SendMessageToDevice) {
// Arrange
HandleConnection();
- EXPECT_CALL(*mock_adapter,
- SendData(mac_address_, application_id, test_message_))
+ EXPECT_CALL(*mock_adapter_,
+ SendData(mac_address_, application_id_, test_message_))
.WillOnce(Return(TransportAdapter::OK));
- EXPECT_EQ(E_SUCCESS, tm.SendMessageToDevice(test_message_));
- testing::Mock::AsyncVerifyAndClearExpectations(10000);
+#ifdef TELEMETRY_MONITOR
+ EXPECT_CALL(mock_metric_observer_, StartRawMsg(test_message_.get()));
+#endif // TELEMETRY_MONITOR
+
+ EXPECT_EQ(E_SUCCESS, tm_.SendMessageToDevice(test_message_));
+ testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout);
}
TEST_F(TransportManagerImplTest, SendMessageToDevice_SendingFailed) {
// Arrange
HandleConnection();
- TMMetricObserverMock* mock_metric_observer = new TMMetricObserverMock();
- tm.SetTimeMetricObserver(mock_metric_observer);
+ MockTMTelemetryObserver* mock_metric_observer = new MockTMTelemetryObserver();
+ tm_.SetTelemetryObserver(mock_metric_observer);
EXPECT_CALL(*mock_metric_observer, StartRawMsg(_));
- EXPECT_CALL(*mock_adapter,
- SendData(mac_address_, application_id, test_message_))
+ EXPECT_CALL(*mock_adapter_,
+ SendData(mac_address_, application_id_, test_message_))
.WillOnce(Return(TransportAdapter::FAIL));
- EXPECT_CALL(*tm_listener, OnTMMessageSendFailed(_, test_message_));
- EXPECT_EQ(E_SUCCESS, tm.SendMessageToDevice(test_message_));
+ EXPECT_CALL(*tm_listener_, OnTMMessageSendFailed(_, test_message_));
+ EXPECT_EQ(E_SUCCESS, tm_.SendMessageToDevice(test_message_));
EXPECT_CALL(*mock_metric_observer, StopRawMsg(_)).Times(0);
delete mock_metric_observer;
- testing::Mock::AsyncVerifyAndClearExpectations(10000);
+ testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout);
}
TEST_F(TransportManagerImplTest, SendMessageToDevice_StartTimeObserver) {
// Arrange
HandleConnection();
- TMMetricObserverMock* mock_metric_observer = new TMMetricObserverMock();
- tm.SetTimeMetricObserver(mock_metric_observer);
- EXPECT_CALL(*mock_adapter,
- SendData(mac_address_, application_id, test_message_))
+ MockTMTelemetryObserver* mock_metric_observer = new MockTMTelemetryObserver();
+ tm_.SetTelemetryObserver(mock_metric_observer);
+ EXPECT_CALL(*mock_adapter_,
+ SendData(mac_address_, application_id_, test_message_))
.WillOnce(Return(TransportAdapter::OK));
EXPECT_CALL(*mock_metric_observer, StartRawMsg(_));
- EXPECT_EQ(E_SUCCESS, tm.SendMessageToDevice(test_message_));
+ EXPECT_EQ(E_SUCCESS, tm_.SendMessageToDevice(test_message_));
delete mock_metric_observer;
- testing::Mock::AsyncVerifyAndClearExpectations(10000);
+ testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout);
}
TEST_F(TransportManagerImplTest, SendMessageToDevice_SendDone) {
// Arrange
HandleConnection();
- TMMetricObserverMock* mock_metric_observer = new TMMetricObserverMock();
- tm.SetTimeMetricObserver(mock_metric_observer);
- EXPECT_CALL(*mock_adapter,
- SendData(mac_address_, application_id, test_message_))
+ EXPECT_CALL(*mock_adapter_,
+ SendData(mac_address_, application_id_, test_message_))
.WillOnce(Return(TransportAdapter::OK));
- EXPECT_CALL(*mock_metric_observer, StartRawMsg(_));
-
- EXPECT_EQ(E_SUCCESS, tm.SendMessageToDevice(test_message_));
+ EXPECT_CALL(mock_metric_observer_, StartRawMsg(test_message_.get()));
+ EXPECT_EQ(E_SUCCESS, tm_.SendMessageToDevice(test_message_));
- EXPECT_CALL(*mock_metric_observer, StopRawMsg(_));
HandleSendDone();
- delete mock_metric_observer;
- testing::Mock::AsyncVerifyAndClearExpectations(10000);
+ testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout);
}
TEST_F(TransportManagerImplTest, SendMessageFailed_GetHandleSendFailed) {
// Arrange
HandleConnection();
- TMMetricObserverMock* mock_metric_observer = new TMMetricObserverMock();
- tm.SetTimeMetricObserver(mock_metric_observer);
- EXPECT_CALL(*mock_metric_observer, StartRawMsg(_));
-
- EXPECT_CALL(*mock_adapter,
- SendData(mac_address_, application_id, test_message_))
+ EXPECT_CALL(*mock_adapter_,
+ SendData(mac_address_, application_id_, test_message_))
.WillOnce(Return(TransportAdapter::FAIL));
-
- EXPECT_CALL(*tm_listener, OnTMMessageSendFailed(_, test_message_));
- EXPECT_EQ(E_SUCCESS, tm.SendMessageToDevice(test_message_));
-
- EXPECT_CALL(*mock_metric_observer, StopRawMsg(_));
+ EXPECT_CALL(mock_metric_observer_, StartRawMsg(test_message_.get()));
+ EXPECT_CALL(*tm_listener_, OnTMMessageSendFailed(_, test_message_));
+ EXPECT_EQ(E_SUCCESS, tm_.SendMessageToDevice(test_message_));
HandleSendFailed();
- delete mock_metric_observer;
- testing::Mock::AsyncVerifyAndClearExpectations(10000);
+ testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout);
}
TEST_F(TransportManagerImplTest, RemoveDevice_DeviceWasAdded) {
// Arrange
HandleDeviceListUpdated();
- EXPECT_CALL(*mock_adapter, ConnectDevice(mac_address_))
+ EXPECT_CALL(*mock_adapter_, ConnectDevice(mac_address_))
.WillOnce(Return(TransportAdapter::OK));
- EXPECT_EQ(E_SUCCESS, tm.ConnectDevice(device_handle_));
+ EXPECT_EQ(E_SUCCESS, tm_.ConnectDevice(device_handle_));
// Assert
- EXPECT_EQ(E_SUCCESS, tm.RemoveDevice(device_handle_));
+ EXPECT_EQ(E_SUCCESS, tm_.RemoveDevice(device_handle_));
}
TEST_F(TransportManagerImplTest, SetVisibilityOn_StartClientListening) {
- EXPECT_CALL(*mock_adapter, StartClientListening())
+ EXPECT_CALL(*mock_adapter_, StartClientListening())
.WillOnce(Return(TransportAdapter::OK));
- EXPECT_EQ(::transport_manager::E_SUCCESS, tm.Visibility(true));
+ EXPECT_EQ(::transport_manager::E_SUCCESS, tm_.Visibility(true));
}
TEST_F(TransportManagerImplTest, SetVisibilityOff_StopClientListening) {
- EXPECT_CALL(*mock_adapter, StopClientListening())
+ EXPECT_CALL(*mock_adapter_, StopClientListening())
.WillOnce(Return(TransportAdapter::OK));
- EXPECT_EQ(::transport_manager::E_SUCCESS, tm.Visibility(false));
+ EXPECT_EQ(::transport_manager::E_SUCCESS, tm_.Visibility(false));
}
TEST_F(TransportManagerImplTest, StopTransportManager) {
HandleDeviceListUpdated();
- EXPECT_CALL(*mock_adapter, ConnectDevice(mac_address_))
+ EXPECT_CALL(*mock_adapter_, ConnectDevice(mac_address_))
.WillRepeatedly(Return(TransportAdapter::OK));
- EXPECT_EQ(E_SUCCESS, tm.ConnectDevice(device_handle_));
+ EXPECT_EQ(E_SUCCESS, tm_.ConnectDevice(device_handle_));
- EXPECT_CALL(*mock_adapter, DisconnectDevice(mac_address_))
+ EXPECT_CALL(*mock_adapter_, DisconnectDevice(mac_address_))
.WillRepeatedly(Return(TransportAdapter::OK));
- EXPECT_CALL(*mock_adapter, Terminate());
- EXPECT_EQ(E_SUCCESS, tm.Stop());
+ EXPECT_CALL(*mock_adapter_, Terminate());
+ EXPECT_EQ(E_SUCCESS, tm_.Stop());
}
TEST_F(TransportManagerImplTest, Reinit) {
- EXPECT_CALL(*mock_adapter, Terminate());
- EXPECT_CALL(*mock_adapter, Init()).WillOnce(Return(TransportAdapter::OK));
- EXPECT_EQ(E_SUCCESS, tm.Reinit());
+ EXPECT_CALL(*mock_adapter_, Terminate());
+ EXPECT_CALL(*mock_adapter_, Init()).WillOnce(Return(TransportAdapter::OK));
+ EXPECT_EQ(E_SUCCESS, tm_.Reinit());
}
TEST_F(TransportManagerImplTest, Reinit_InitAdapterFailed) {
- EXPECT_CALL(*mock_adapter, Terminate());
- EXPECT_CALL(*mock_adapter, Init()).WillOnce(Return(TransportAdapter::FAIL));
- EXPECT_EQ(E_ADAPTERS_FAIL, tm.Reinit());
+ EXPECT_CALL(*mock_adapter_, Terminate());
+ EXPECT_CALL(*mock_adapter_, Init()).WillOnce(Return(TransportAdapter::FAIL));
+ EXPECT_EQ(E_ADAPTERS_FAIL, tm_.Reinit());
}
TEST_F(TransportManagerImplTest, UpdateDeviceList_AddNewDevice) {
- const DeviceInfo dev_info(device_handle_, mac_address_, "TestDeviceName",
- "BTMAC");
+ device_list_.push_back(dev_info_.mac_address());
- dev.push_back(dev_info.mac_address());
- std::vector<DeviceInfo> vector_dev_info;
- std::vector<DeviceInfo>::iterator it = vector_dev_info.begin();
- vector_dev_info.insert(it, dev_info);
-
- EXPECT_CALL(*mock_adapter, GetDeviceList()).WillOnce(Return(dev));
- EXPECT_CALL(*mock_adapter, DeviceName(dev_info.mac_address()))
- .WillOnce(Return(dev_info.name()));
- EXPECT_CALL(*mock_adapter, GetConnectionType())
- .WillOnce(Return(dev_info.connection_type()));
- EXPECT_CALL(*tm_listener, OnDeviceAdded(dev_info));
+ EXPECT_CALL(*mock_adapter_, GetDeviceList()).WillOnce(Return(device_list_));
+ EXPECT_CALL(*mock_adapter_, DeviceName(dev_info_.mac_address()))
+ .WillOnce(Return(dev_info_.name()));
+ EXPECT_CALL(*mock_adapter_, GetConnectionType())
+ .WillOnce(Return(dev_info_.connection_type()));
+ EXPECT_CALL(*tm_listener_, OnDeviceAdded(dev_info_));
- tm.UpdateDeviceList(mock_adapter);
- dev.pop_back();
+ tm_.UpdateDeviceList(mock_adapter_);
+ device_list_.pop_back();
}
TEST_F(TransportManagerImplTest, UpdateDeviceList_RemoveDevice) {
- const DeviceInfo dev_info(device_handle_, mac_address_, "TestDeviceName",
- "BTMAC");
-
- dev.push_back(dev_info.mac_address());
- std::vector<DeviceInfo> vector_dev_info;
- std::vector<DeviceInfo>::iterator it = vector_dev_info.begin();
- vector_dev_info.insert(it, dev_info);
+ device_list_.push_back(dev_info_.mac_address());
::testing::InSequence seq;
- EXPECT_CALL(*mock_adapter, GetDeviceList()).WillOnce(Return(dev));
- EXPECT_CALL(*mock_adapter, GetConnectionType())
- .WillOnce(Return(dev_info.connection_type()));
- EXPECT_CALL(*mock_adapter, DeviceName(dev_info.mac_address()))
- .WillOnce(Return(dev_info.name()));
- EXPECT_CALL(*tm_listener, OnDeviceAdded(dev_info));
- tm.UpdateDeviceList(mock_adapter);
- dev.pop_back();
+ EXPECT_CALL(*mock_adapter_, GetDeviceList()).WillOnce(Return(device_list_));
+ EXPECT_CALL(*mock_adapter_, GetConnectionType())
+ .WillOnce(Return(dev_info_.connection_type()));
+ EXPECT_CALL(*mock_adapter_, DeviceName(dev_info_.mac_address()))
+ .WillOnce(Return(dev_info_.name()));
+ EXPECT_CALL(*tm_listener_, OnDeviceAdded(dev_info_));
+ tm_.UpdateDeviceList(mock_adapter_);
+ device_list_.pop_back();
// Device list is empty now
- EXPECT_CALL(*mock_adapter, GetDeviceList()).WillOnce(Return(dev));
- EXPECT_CALL(*tm_listener, OnDeviceRemoved(dev_info));
- tm.UpdateDeviceList(mock_adapter);
+ EXPECT_CALL(*mock_adapter_, GetDeviceList()).WillOnce(Return(device_list_));
+ EXPECT_CALL(*tm_listener_, OnDeviceRemoved(dev_info_));
+ tm_.UpdateDeviceList(mock_adapter_);
}
/*
* Tests which check correct handling and receiving events
*/
TEST_F(TransportManagerImplTest, ReceiveEventFromDevice_OnSearchDeviceDone) {
- int type = static_cast<int>(
+ const int type = static_cast<int>(
TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_DONE);
- TransportAdapterEvent test_event(type, mock_adapter, mac_address_,
- application_id, test_message_, error_);
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
- EXPECT_CALL(*tm_listener, OnScanDevicesFinished());
+ EXPECT_CALL(*tm_listener_, OnScanDevicesFinished());
- tm.ReceiveEventFromDevice(test_event);
- testing::Mock::AsyncVerifyAndClearExpectations(10000);
+ tm_.ReceiveEventFromDevice(test_event);
+ testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout);
}
TEST_F(TransportManagerImplTest, ReceiveEventFromDevice_OnSearchDeviceFail) {
- int type = static_cast<int>(
+ const int type = static_cast<int>(
TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_FAIL);
- TransportAdapterEvent test_event(type, mock_adapter, mac_address_,
- application_id, test_message_, error_);
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
- EXPECT_CALL(*tm_listener, OnScanDevicesFailed(_));
+ EXPECT_CALL(*tm_listener_, OnScanDevicesFailed(_));
- tm.ReceiveEventFromDevice(test_event);
- testing::Mock::AsyncVerifyAndClearExpectations(10000);
+ tm_.ReceiveEventFromDevice(test_event);
+ testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout);
}
TEST_F(TransportManagerImplTest, ReceiveEventFromDevice_DeviceListUpdated) {
- int type = static_cast<int>(
+ const int type = static_cast<int>(
TransportAdapterListenerImpl::EventTypeEnum::ON_DEVICE_LIST_UPDATED);
- const DeviceInfo dev_info(device_handle_, mac_address_, "TestDeviceName",
- "BTMAC");
- TransportAdapterEvent test_event(type, mock_adapter, dev_info.mac_address(),
- application_id, test_message_, error_);
- dev.push_back(dev_info.mac_address());
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ dev_info_.mac_address(),
+ application_id_,
+ test_message_,
+ error_);
+ device_list_.push_back(dev_info_.mac_address());
std::vector<DeviceInfo> vector_dev_info;
- std::vector<DeviceInfo>::iterator it = vector_dev_info.begin();
- vector_dev_info.insert(it, dev_info);
+ vector_dev_info.push_back(dev_info_);
- EXPECT_CALL(*mock_adapter, GetDeviceList())
+ EXPECT_CALL(*mock_adapter_, GetDeviceList())
.Times(AtLeast(1))
- .WillRepeatedly(Return(dev));
- EXPECT_CALL(*mock_adapter, DeviceName(dev_info.mac_address()))
+ .WillRepeatedly(Return(device_list_));
+ EXPECT_CALL(*mock_adapter_, DeviceName(dev_info_.mac_address()))
.Times(AtLeast(1))
- .WillRepeatedly(Return(dev_info.name()));
- EXPECT_CALL(*mock_adapter, GetConnectionType())
+ .WillRepeatedly(Return(dev_info_.name()));
+ EXPECT_CALL(*mock_adapter_, GetConnectionType())
.Times(AtLeast(1))
- .WillRepeatedly(Return(dev_info.connection_type()));
+ .WillRepeatedly(Return(dev_info_.connection_type()));
- EXPECT_CALL(*tm_listener, OnDeviceFound(dev_info));
- EXPECT_CALL(*tm_listener, OnDeviceAdded(dev_info));
- EXPECT_CALL(*tm_listener, OnDeviceListUpdated(vector_dev_info));
+ EXPECT_CALL(*tm_listener_, OnDeviceFound(dev_info_));
+ EXPECT_CALL(*tm_listener_, OnDeviceAdded(dev_info_));
+ EXPECT_CALL(*tm_listener_, OnDeviceListUpdated(vector_dev_info));
- tm.ReceiveEventFromDevice(test_event);
- dev.pop_back();
- testing::Mock::AsyncVerifyAndClearExpectations(10000);
+ tm_.ReceiveEventFromDevice(test_event);
+ device_list_.pop_back();
+ testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout);
}
TEST_F(TransportManagerImplTest, CheckEvents) {
@@ -712,6 +741,333 @@ TEST_F(TransportManagerImplTest, CheckReceiveEvent) {
HandleReceiveDone();
}
+TEST_F(TransportManagerImplTest, CheckReceiveFailedEvent) {
+ // Arrange
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_FAIL);
+
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
+ // Check before act
+ HandleConnection();
+ // Act and Assert
+ EXPECT_CALL(*tm_listener_, OnTMMessageReceiveFailed(_));
+ tm_.TestHandle(test_event);
+}
+
+TEST_F(TransportManagerImplTest, CheckUnexpectedDisconnect) {
+ // Arrange
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_UNEXPECTED_DISCONNECT);
+
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
+ // Check before act
+ HandleConnection();
+ // Act and Assert
+ EXPECT_CALL(*tm_listener_, OnUnexpectedDisconnect(connection_key_, _));
+ EXPECT_CALL(*mock_adapter_,
+ RemoveFinalizedConnection(mac_address_, application_id_));
+ tm_.TestHandle(test_event);
+}
+
+TEST_F(TransportManagerImplTest, ConnectDevice_TMIsNotInitialized) {
+ // Check before Act
+ UninitializeTM();
+ // Act and Assert
+ EXPECT_CALL(*mock_adapter_, ConnectDevice(_)).Times(0);
+ EXPECT_EQ(E_TM_IS_NOT_INITIALIZED, tm_.ConnectDevice(device_handle_));
+}
+
+TEST_F(TransportManagerImplTest, DisconnectDevice_TMIsNotInitialized) {
+ // Check before Act
+ UninitializeTM();
+ // Act and Assert
+ EXPECT_CALL(*mock_adapter_, DisconnectDevice(_)).Times(0);
+ EXPECT_EQ(E_TM_IS_NOT_INITIALIZED, tm_.DisconnectDevice(device_handle_));
+}
+
+TEST_F(TransportManagerImplTest, Disconnect_TMIsNotInitialized) {
+ // Check before Act
+ UninitializeTM();
+ // Act and Assert
+ EXPECT_CALL(*mock_adapter_, Disconnect(_, _)).Times(0);
+ EXPECT_EQ(E_TM_IS_NOT_INITIALIZED, tm_.Disconnect(connection_key_));
+}
+
+TEST_F(TransportManagerImplTest, DisconnectForce_TMIsNotInitialized) {
+ // Check before Act
+ UninitializeTM();
+ // Act and Assert
+ EXPECT_CALL(*mock_adapter_, Disconnect(_, _)).Times(0);
+ EXPECT_EQ(E_TM_IS_NOT_INITIALIZED, tm_.DisconnectForce(connection_key_));
+}
+
+TEST_F(TransportManagerImplTest, DisconnectForce_ConnectionNotExist) {
+ // SetUp does not add connections
+ // Act and Assert
+ EXPECT_CALL(*mock_adapter_, Disconnect(_, _)).Times(0);
+ EXPECT_EQ(E_INVALID_HANDLE, tm_.DisconnectForce(connection_key_));
+}
+
+TEST_F(TransportManagerImplTest, Stop_TMIsNotInitialized) {
+ // Check before Act
+ UninitializeTM();
+ // Act and Assert
+ EXPECT_CALL(*mock_adapter_, DisconnectDevice(_)).Times(0);
+ EXPECT_CALL(*mock_adapter_, Terminate()).Times(0);
+ EXPECT_EQ(E_TM_IS_NOT_INITIALIZED, tm_.Stop());
+}
+
+TEST_F(TransportManagerImplTest, SendMessageToDevice_TMIsNotInitialized) {
+ // Check before Act
+ UninitializeTM();
+ // Act and Assert
+ EXPECT_CALL(*mock_adapter_, SendData(_, _, _)).Times(0);
+ EXPECT_CALL(*tm_listener_, OnTMMessageSendFailed(_, _)).Times(0);
+ EXPECT_EQ(E_TM_IS_NOT_INITIALIZED, tm_.SendMessageToDevice(test_message_));
+}
+
+TEST_F(TransportManagerImplTest, SendMessageToDevice_ConnectionNotExist) {
+ // SetUp does not add connections
+ // Act and Assert
+ EXPECT_CALL(*mock_adapter_, SendData(_, _, _)).Times(0);
+ EXPECT_CALL(*tm_listener_, OnTMMessageSendFailed(_, _)).Times(0);
+ EXPECT_EQ(E_INVALID_HANDLE, tm_.SendMessageToDevice(test_message_));
+}
+
+TEST_F(TransportManagerImplTest, ReceiveEventFromDevice_TMIsNotInitialized) {
+ // Arrange
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_SEARCH_DONE);
+ TransportAdapterEvent test_event(
+ type, NULL, mac_address_, application_id_, test_message_, error_);
+ // Check before Act
+ UninitializeTM();
+ // Act and Assert
+ EXPECT_CALL(*tm_listener_, OnScanDevicesFinished()).Times(0);
+ EXPECT_EQ(E_TM_IS_NOT_INITIALIZED, tm_.ReceiveEventFromDevice(test_event));
+}
+
+TEST_F(TransportManagerImplTest, RemoveDevice_TMIsNotInitialized) {
+ // Check before Act
+ UninitializeTM();
+ // Act and Assert
+ EXPECT_EQ(E_TM_IS_NOT_INITIALIZED, tm_.RemoveDevice(device_handle_));
+}
+
+TEST_F(TransportManagerImplTest, Visibility_TMIsNotInitialized) {
+ // Arrange
+ const bool visible = true;
+ // Check before Act
+ UninitializeTM();
+ // Act and Assert
+ EXPECT_CALL(*mock_adapter_, StartClientListening()).Times(0);
+ EXPECT_EQ(E_TM_IS_NOT_INITIALIZED, tm_.Visibility(visible));
+}
+
+TEST_F(TransportManagerImplTest, HandleMessage_ConnectionNotExist) {
+ EXPECT_CALL(*mock_adapter_,
+ SendData(mac_address_, application_id_, test_message_)).Times(0);
+ EXPECT_CALL(*tm_listener_, OnTMMessageSendFailed(_, test_message_));
+
+ tm_.TestHandle(test_message_);
+ testing::Mock::AsyncVerifyAndClearExpectations(kAsyncExpectationsTimeout);
+}
+
+TEST_F(TransportManagerImplTest, SearchDevices_TMIsNotInitialized) {
+ // Check before Act
+ UninitializeTM();
+ // Act and Assert
+ EXPECT_CALL(*mock_adapter_, SearchDevices()).Times(0);
+ EXPECT_EQ(E_TM_IS_NOT_INITIALIZED, tm_.SearchDevices());
+}
+
+TEST_F(TransportManagerImplTest, SetVisibilityOn_TransportAdapterNotSupported) {
+ EXPECT_CALL(*mock_adapter_, StartClientListening())
+ .WillOnce(Return(TransportAdapter::NOT_SUPPORTED));
+ EXPECT_EQ(E_SUCCESS, tm_.Visibility(true));
+}
+
+TEST_F(TransportManagerImplTest,
+ SetVisibilityOff_TransportAdapterNotSupported) {
+ EXPECT_CALL(*mock_adapter_, StopClientListening())
+ .WillOnce(Return(TransportAdapter::NOT_SUPPORTED));
+ EXPECT_EQ(E_SUCCESS, tm_.Visibility(false));
+}
+
+TEST_F(TransportManagerImplTest,
+ UpdateDeviceList_AddDevices_TwoTransportAdapters) {
+ // Arrange
+ MockTransportAdapter* second_mock_adapter = new MockTransportAdapter();
+ device_list_.push_back(dev_info_.mac_address());
+ // Check before Act
+ EXPECT_CALL(*second_mock_adapter, AddListener(_));
+ EXPECT_CALL(*second_mock_adapter, IsInitialised()).WillOnce(Return(true));
+ EXPECT_EQ(E_SUCCESS, tm_.AddTransportAdapter(second_mock_adapter));
+
+ // Act and Assert
+ EXPECT_CALL(*second_mock_adapter, GetDeviceList())
+ .WillOnce(Return(device_list_));
+ EXPECT_CALL(*second_mock_adapter, DeviceName(dev_info_.mac_address()))
+ .WillOnce(Return(dev_info_.name()));
+ EXPECT_CALL(*second_mock_adapter, GetConnectionType())
+ .WillOnce(Return(dev_info_.connection_type()));
+ EXPECT_CALL(*tm_listener_, OnDeviceAdded(dev_info_));
+ tm_.UpdateDeviceList(second_mock_adapter);
+
+ EXPECT_CALL(*mock_adapter_, GetDeviceList()).WillOnce(Return(device_list_));
+ EXPECT_CALL(*mock_adapter_, DeviceName(dev_info_.mac_address()))
+ .WillOnce(Return(dev_info_.name()));
+ EXPECT_CALL(*mock_adapter_, GetConnectionType())
+ .WillOnce(Return(dev_info_.connection_type()));
+ EXPECT_CALL(*tm_listener_, OnDeviceAdded(dev_info_));
+ tm_.UpdateDeviceList(mock_adapter_);
+
+ device_list_.pop_back();
+}
+
+TEST_F(TransportManagerImplTest,
+ UpdateDeviceList_RemoveDevices_TwoTransportAdapters) {
+ // Arrange
+ MockTransportAdapter* second_mock_adapter = new MockTransportAdapter();
+ device_list_.push_back(dev_info_.mac_address());
+ // Check before Act
+ EXPECT_CALL(*second_mock_adapter, AddListener(_));
+ EXPECT_CALL(*second_mock_adapter, IsInitialised()).WillOnce(Return(true));
+ EXPECT_EQ(E_SUCCESS, tm_.AddTransportAdapter(second_mock_adapter));
+
+ // Act and Assert
+ EXPECT_CALL(*second_mock_adapter, GetDeviceList())
+ .WillOnce(Return(device_list_));
+ EXPECT_CALL(*second_mock_adapter, DeviceName(dev_info_.mac_address()))
+ .WillOnce(Return(dev_info_.name()));
+ EXPECT_CALL(*second_mock_adapter, GetConnectionType())
+ .WillOnce(Return(dev_info_.connection_type()));
+ EXPECT_CALL(*tm_listener_, OnDeviceAdded(dev_info_));
+ tm_.UpdateDeviceList(second_mock_adapter);
+
+ EXPECT_CALL(*mock_adapter_, GetDeviceList()).WillOnce(Return(device_list_));
+ EXPECT_CALL(*mock_adapter_, DeviceName(dev_info_.mac_address()))
+ .WillOnce(Return(dev_info_.name()));
+ EXPECT_CALL(*mock_adapter_, GetConnectionType())
+ .WillOnce(Return(dev_info_.connection_type()));
+ EXPECT_CALL(*tm_listener_, OnDeviceAdded(dev_info_));
+ tm_.UpdateDeviceList(mock_adapter_);
+
+ device_list_.pop_back();
+
+ EXPECT_CALL(*second_mock_adapter, GetDeviceList())
+ .WillOnce(Return(device_list_));
+ EXPECT_CALL(*tm_listener_, OnDeviceRemoved(dev_info_));
+ tm_.UpdateDeviceList(second_mock_adapter);
+
+ EXPECT_CALL(*mock_adapter_, GetDeviceList()).WillOnce(Return(device_list_));
+ EXPECT_CALL(*tm_listener_, OnDeviceRemoved(dev_info_));
+ tm_.UpdateDeviceList(mock_adapter_);
+}
+
+TEST_F(TransportManagerImplTest,
+ CheckEventOnDisconnectDone_ConnectionNotExist) {
+ // SetUp does not add connections
+ // Arrange
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_DISCONNECT_DONE);
+
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
+
+ // Act and Assert
+ EXPECT_CALL(*tm_listener_, OnConnectionClosed(_)).Times(0);
+
+ tm_.TestHandle(test_event);
+}
+
+TEST_F(TransportManagerImplTest, CheckEventOnSendDone_ConnectionNotExist) {
+ // SetUp does not add connections
+ // Arrange
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_SEND_DONE);
+
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
+#ifdef TELEMETRY_MONITOR
+ // Act and Assert
+ EXPECT_CALL(mock_metric_observer_, StopRawMsg(_));
+#endif // TELEMETRY_MONITOR
+ EXPECT_CALL(*tm_listener_, OnTMMessageSend(_)).Times(0);
+
+ tm_.TestHandle(test_event);
+}
+
+TEST_F(TransportManagerImplTest, CheckEventOnReceivedDone_ConnectionNotExist) {
+ // SetUp does not add connections
+ // Arrange
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_DONE);
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
+#ifdef TELEMETRY_MONITOR
+ // Act and Assert
+ EXPECT_CALL(mock_metric_observer_, StopRawMsg(_)).Times(0);
+#endif // TELEMETRY_MONITOR
+ EXPECT_CALL(*tm_listener_, OnTMMessageReceived(_)).Times(0);
+ tm_.TestHandle(test_event);
+}
+
+TEST_F(TransportManagerImplTest, CheckEventOnReceivedFail_ConnectionNotExist) {
+ // SetUp does not add connections
+ // Arrange
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_RECEIVED_FAIL);
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
+ // Act and Assert
+ EXPECT_CALL(*tm_listener_, OnTMMessageReceiveFailed(_)).Times(0);
+ tm_.TestHandle(test_event);
+}
+
+TEST_F(TransportManagerImplTest,
+ CheckEventOnUnexpectedDisconnect_ConnectionNotExist) {
+ // SetUp does not add connections
+ // Arrange
+ const int type = static_cast<int>(
+ TransportAdapterListenerImpl::EventTypeEnum::ON_UNEXPECTED_DISCONNECT);
+ TransportAdapterEvent test_event(type,
+ mock_adapter_,
+ mac_address_,
+ application_id_,
+ test_message_,
+ error_);
+ // Act and Assert
+ EXPECT_CALL(*tm_listener_, OnUnexpectedDisconnect(_, _)).Times(0);
+ tm_.TestHandle(test_event);
+}
+
} // namespace transport_manager_test
} // namespace components
} // namespace test
diff --git a/src/components/transport_manager/test/transport_manager_instance_test.cc b/src/components/transport_manager/test/transport_manager_instance_test.cc
deleted file mode 100644
index b5a251ba5e..0000000000
--- a/src/components/transport_manager/test/transport_manager_instance_test.cc
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*
- Tests transport manager functionality with single device adapter that behaves correctly and single client
- Following sequence is tested:
- - TM created and runned
- - TM client registered as listener
- - TM client requests device scaning
- - single device was returned to TM client with onDeviceListUpdated callback
- - TM client calls "connect" on found device
- - device adapter sends onApplicationConnected
- - TM client receives onApplicationConnected
- - device adapter sends three data parts that represents single frame
- - TM client receives single frame with onFrameReceived callback
- - TM client calls sendFrame with some frame data and user data
- - TM client receives onFrameSendCompleted
- - TM client calls DisconnectDevice
- - TM client receives onApplicationDisconnected
- */
-
-#include <stddef.h>
-#include <stdio.h>
-
-#include "gtest/gtest.h"
-#include "gmock/gmock.h"
-
-#include "../../include/transport_manager/transport_manager.h"
-#include "../include/transport_manager/transport_adapter/transport_adapter.h"
-#include "../include/transport_manager/common.h"
-#include "../include/transport_manager/transport_manager_impl.h"
-#include "../include/transport_manager/transport_manager_default.h"
-#include "../../connection_handler/include/connection_handler/connection_handler.h"
-
-
-namespace test{
-namespace test_transport_manager_instance {
-TEST(test_transport_manager_instance, test_transport_manager_instance)
-{
- transport_manager::TransportManager *Instance = transport_manager::TransportManagerDefault::instance();
- ASSERT_EQ(Instance, transport_manager::TransportManagerDefault::instance());
-}
-
-}}
diff --git a/src/components/transport_manager/test/transport_manager_test.cc b/src/components/transport_manager/test/transport_manager_test.cc
deleted file mode 100644
index 551931788c..0000000000
--- a/src/components/transport_manager/test/transport_manager_test.cc
+++ /dev/null
@@ -1,394 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-#include <pthread.h>
-
-#include "protocol/common.h"
-#include "transport_manager/info.h"
-#include "transport_manager/common.h"
-#include "transport_manager/transport_manager_impl.h"
-
-#include "include/raw_message_matcher.h"
-#include "include/mock_transport_adapter.h"
-#include "include/mock_device.h"
-#include "include/mock_transport_manager_listener.h"
-#include "transport_manager/transport_manager_listener_empty.h"
-
-//for instance test
-#include "transport_manager/transport_manager.h"
-#include "transport_manager/transport_adapter/transport_adapter.h"
-#include "transport_manager/transport_manager_default.h"
-#include "connection_handler/connection_handler.h"
-
-using ::testing::_;
-using ::testing::AtLeast;
-
-using ::transport_manager::ApplicationHandle;
-using ::transport_manager::DeviceHandle;
-using ::transport_manager::TransportManager;
-using ::transport_manager::TransportManagerImpl;
-using ::transport_manager::DeviceUID;
-using ::transport_manager::DeviceInfo;
-
-namespace test {
-namespace components {
-namespace transport_manager {
-
-ACTION_P(SignalTest, test) {
- if (test->thread_id != pthread_self()) {
- pthread_mutex_lock(&test->test_mutex);
- pthread_cond_signal(&test->test_cond);
- pthread_mutex_unlock(&test->test_mutex);
- } else {
- test->one_thread = true;
- }
-}
-
-class TransportManagerTest : public ::testing::Test {
- public:
- volatile bool one_thread;
- pthread_t thread_id;
- static pthread_mutex_t test_mutex;
- static pthread_cond_t test_cond;
- int number;
-
- protected:
- static TransportManagerImpl *tm;
- static MockTransportAdapter *mock_adapter;
- static MockTransportManagerListener *tm_listener;
-
- static void SetUpTestCase() {
- pthread_mutex_init(&test_mutex, NULL);
- pthread_cond_init(&test_cond, NULL);
- mock_adapter = new MockTransportAdapter();
- mock_adapter->Init();
- //TransportManagerAttr cfg{0};
- tm = new TransportManagerImpl();
-
- tm_listener = new MockTransportManagerListener();
- tm->AddEventListener(tm_listener);
- tm->AddTransportAdapter(mock_adapter);
- tm->Init();
- }
-
- static void TearDownTestCase() {
- tm->Stop();
- delete tm_listener;
- pthread_cond_destroy(&test_cond);
- pthread_mutex_destroy(&test_mutex);
- }
-
- virtual void SetUp() {
- one_thread = false;
- thread_id = pthread_self();
- mock_adapter->reset();
- pthread_mutex_lock(&test_mutex);
- }
-
- virtual void TearDown() { pthread_mutex_unlock(&test_mutex); }
-
- bool waitCond(int seconds) {
- if (one_thread) return true;
- timespec elapsed;
- clock_gettime(CLOCK_REALTIME, &elapsed);
- elapsed.tv_sec += seconds;
- return pthread_cond_timedwait(&test_cond, &test_mutex, &elapsed) !=
- ETIMEDOUT;
- }
-};
-
-TransportManagerImpl *TransportManagerTest::tm;
-
-class MyTransportListener
- : public ::transport_manager::TransportManagerListenerEmpty {
- public:
- explicit MyTransportListener(TransportManagerTest *test)
- : TransportManagerListenerEmpty(),
- connection(0),
- device_handle(0),
- test(test) {}
- ConnectionUID connection;
- DeviceHandle device_handle;
- void OnConnectionEstablished(const DeviceInfo &device,
- const ConnectionUID &connection_id) {
- connection = connection_id;
-
- pthread_mutex_lock(&test->test_mutex);
- pthread_cond_signal(&test->test_cond);
- pthread_mutex_unlock(&test->test_mutex);
- }
-
- void OnDeviceFound(const DeviceInfo &device_info) {
- device_handle = device_info.device_handle();
- }
-
- void OnScanDevicesFinished() {
- pthread_mutex_lock(&test->test_mutex);
- pthread_cond_signal(&test->test_cond);
- pthread_mutex_unlock(&test->test_mutex);
- }
-
- void OnTMMessageReceived(const RawMessagePtr message) {
- static int count = 0;
- if (++count == 100) {
- pthread_mutex_lock(&test->test_mutex);
- pthread_cond_signal(&test->test_cond);
- pthread_mutex_unlock(&test->test_mutex);
- }
- }
-
- void OnTMMessageSend(const RawMessagePtr message) {
- }
-
- private:
- TransportManagerTest *test;
-};
-
-pthread_mutex_t TransportManagerTest::test_mutex;
-pthread_cond_t TransportManagerTest::test_cond;
-
-MockTransportAdapter *TransportManagerTest::mock_adapter = NULL;
-MockTransportManagerListener *TransportManagerTest::tm_listener = NULL;
-
-
-
-TEST_F(TransportManagerTest, ScanDeviceFailed) {
-
- //assert
- EXPECT_CALL(*tm_listener, OnDeviceFound(_)).Times(0);
- EXPECT_CALL(*tm_listener, OnScanDevicesFailed(_)).WillOnce(
- SignalTest(this));
-
- //act
- mock_adapter->get_device_scanner()->fail_further_search();
- tm->SearchDevices();
-
- //assert
- EXPECT_TRUE(waitCond(1));
-
- //act
- mock_adapter->get_device_scanner()->reset();
-}
-
-TEST_F(TransportManagerTest, ScanDeviceNoFound) {
-
- //assert
- EXPECT_CALL(*tm_listener, OnScanDevicesFailed(_)).Times(0);
- EXPECT_CALL(*tm_listener, OnDeviceFound(_)).Times(0);
- EXPECT_CALL(*tm_listener, OnScanDevicesFinished()).WillOnce(SignalTest(this));
-
- EXPECT_CALL(*tm_listener, OnDeviceListUpdated(_));
-
- //act
- tm->SearchDevices();
-
- //assert
- EXPECT_TRUE(waitCond(1));
-
- //act
- mock_adapter->get_device_scanner()->reset();
-}
-
-TEST_F(TransportManagerTest, ScanDeviceDone) {
-
- //assert
- EXPECT_CALL(*tm_listener, OnScanDevicesFailed(_)).Times(0);
- EXPECT_CALL(*tm_listener, OnDeviceFound(_));
- EXPECT_CALL(*tm_listener, OnScanDevicesFinished()).WillOnce(SignalTest(this));
-
- //added to fixed warnings
- EXPECT_CALL(*tm_listener, OnDeviceAdded(_)).Times(3);
- EXPECT_CALL(*tm_listener, OnDeviceListUpdated(_));
- EXPECT_CALL(*tm_listener, OnDeviceRemoved(_)).Times(3);
-
- //act
- mock_adapter->get_device_scanner()->AddDevice("TestDevice", "MA:CA:DR:ES:S");
- tm->SearchDevices();
-
- //assert
- EXPECT_TRUE(waitCond(1));
-
- //act
- mock_adapter->get_device_scanner()->reset();
-}
-
-TEST_F(TransportManagerTest, ScanManyDeviceDone) {
-
-
- //assert
- EXPECT_CALL(*tm_listener, OnScanDevicesFailed(_)).Times(0);
- EXPECT_CALL(*tm_listener, OnDeviceFound(_)).Times(2);
- EXPECT_CALL(*tm_listener, OnScanDevicesFinished()).WillOnce(SignalTest(this));
-
- //assert
- EXPECT_CALL(*tm_listener, OnDeviceListUpdated(_));
- //act
- mock_adapter->get_device_scanner()->AddDevice("TestDevice1",
- "MA:CA:DR:ES:S1");
- mock_adapter->get_device_scanner()->AddDevice("TestDevice2",
- "MA:CA:DR:ES:S2");
- tm->SearchDevices();
-
- //assert
- EXPECT_TRUE(waitCond(1));
-
- //act
- mock_adapter->get_device_scanner()->reset();
-}
-
-
-TEST_F(TransportManagerTest, ConnectAddDeviceCannotFailConnection) {
-
- //arrange
- const DeviceInfo kInfo(1, "MA:CA:DR:ES:S", "TestDeviceName", "BTMAC");
- const ConnectionUID kConnection = 1;
-
- //assert
- EXPECT_CALL(*tm_listener, OnDeviceFound(_));
- EXPECT_CALL(*tm_listener, OnScanDevicesFinished());
-
- EXPECT_CALL(*tm_listener, OnDeviceAdded(_));
- EXPECT_CALL(*tm_listener, OnDeviceListUpdated(_));
-
- //act
- MyTransportListener *myListener = new MyTransportListener(this);
- mock_adapter->get_device_scanner()->AddDevice(kInfo.name(),
- kInfo.mac_address());
- tm->AddEventListener(myListener);
- tm->SearchDevices();
-
- //assert
- EXPECT_TRUE(waitCond(10));
-
- EXPECT_CALL(*tm_listener, OnConnectionFailed(_, _)).Times(0);
- EXPECT_CALL(*tm_listener, OnConnectionEstablished(kInfo, kConnection));
-
- //act
- tm->ConnectDevice(kInfo.device_handle());
-
- //assert
- EXPECT_TRUE(waitCond(10));
-
- //act
- mock_adapter->get_device_scanner()->reset();
-}
-
-
-//TODO{ALeshin}: APPLINK-10846
-//TEST_F(TransportManagerTest, ConnectDeviceSendReciveMessage) {
-
-// //arrange
-// const ConnectionUID kConnection = 1;
-// const int kTimes = 99; // Times of send message //if kTimes>99 OnTMMessageSend will fail
-// const unsigned int kVersionProtocol = 1;
-
-
-// //assert
-// EXPECT_CALL(*tm_listener, OnTMMessageSendFailed(_, _)).Times(0);
-// EXPECT_CALL(*tm_listener, OnTMMessageReceiveFailed(_, _)).Times(0);
-// EXPECT_CALL(*tm_listener, OnConnectionClosed(kConnection)).Times(0);
-
-// EXPECT_CALL(*tm_listener, OnTMMessageSend(_)).Times(kTimes);
-// EXPECT_CALL(*tm_listener, OnTMMessageReceived(_)).Times(kTimes);
-
-// //act
-// const unsigned int kSize = 12;
-// unsigned char data[kSize] = {0x20, 0x07, 0x01, 0x00, 0x00, 0x00,
-// 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
-// for (int i = 0; i < kTimes; ++i) {
-// const RawMessagePtr kMessage =
-// new RawMessage(kConnection, kVersionProtocol, data, kSize);
-// tm->SendMessageToDevice(kMessage);
-// usleep(1000);
-// }
-
-// //assert
-// EXPECT_TRUE(waitCond(10));
-
-// //act
-// mock_adapter->get_device_scanner()->reset();
-//}
-
-//TODO{ALeshin}: APPLINK-10846
-//TEST_F(TransportManagerTest, ConnectAddDeviceCannotFailClose) {
-
-// //arrange
-// const DeviceInfo kInfo(1, "MA:CA:DR:ES:S", "TestDeviceName", "BTMAC");
-// const ConnectionUID kConnection = 1;
-
-// //assert
-// EXPECT_CALL(*tm_listener, OnDeviceFound(_));
-// EXPECT_CALL(*tm_listener, OnScanDevicesFinished());
-// EXPECT_CALL(*tm_listener, OnDeviceListUpdated(_));
-
-
-// //act
-// MyTransportListener *myListener = new MyTransportListener(this);
-// mock_adapter->get_device_scanner()->AddDevice(kInfo.name(),
-// kInfo.mac_address());
-// tm->AddEventListener(myListener);
-// tm->SearchDevices();
-
-// //assert
-// EXPECT_TRUE(waitCond(10));
-
-// EXPECT_CALL(*tm_listener, OnConnectionClosedFailure(_, _)).Times(0);
-// EXPECT_CALL(*tm_listener, OnDisconnectFailed(kInfo.device_handle(), _))
-// .Times(0);
-// EXPECT_CALL(*tm_listener, OnConnectionClosed(kConnection)).WillOnce(SignalTest(this));
-
-// //act
-// tm->DisconnectDevice(kInfo.device_handle());
-
-// //assert
-// EXPECT_TRUE(waitCond(10));
-
-// //act
-// tm->Stop();
-// delete myListener;
-// mock_adapter->get_device_scanner()->reset();
-//}
-
-
-} // namespace transport_manager
-} // namespace components
-} // namespace test
-
-
-namespace test{
-namespace test_transport_manager_instance {
-TEST(testTransportManager, CreateOnlyInstance)
-{
- transport_manager::TransportManager *Instance = transport_manager::TransportManagerDefault::instance();
- ASSERT_EQ(Instance, transport_manager::TransportManagerDefault::instance());
- delete Instance;
-}
-}}
diff --git a/src/components/utils/CMakeLists.txt b/src/components/utils/CMakeLists.txt
index af5afa028a..f72d43e546 100644
--- a/src/components/utils/CMakeLists.txt
+++ b/src/components/utils/CMakeLists.txt
@@ -56,6 +56,9 @@ set (SOURCES
${UTILS_SRC_DIR}/resource_usage.cc
${UTILS_SRC_DIR}/appenders_loader.cc
${UTILS_SRC_DIR}/gen_hash.cc
+ ${UTILS_SRC_DIR}/convert_utils.cc
+ ${UTILS_SRC_DIR}/custom_string.cc
+ ${UTILS_SRC_DIR}/timer.cc
)
if(ENABLE_LOG)
@@ -82,6 +85,14 @@ endif()
add_library("Utils" ${SOURCES})
+if (CMAKE_SYSTEM_NAME STREQUAL "QNX")
+ # --- QDB Wrapper
+ add_subdirectory(./src/qdb_wrapper)
+else ()
+ # --- SQLite Wrapper
+ add_subdirectory(./src/sqlite_wrapper)
+endif ()
+
if(${CMAKE_SYSTEM_NAME} MATCHES "Linux")
list(APPEND LIBRARIES dl)
endif()
@@ -91,6 +102,8 @@ if(ENABLE_LOG)
list(APPEND LIBRARIES log4cxx -L${LOG4CXX_LIBS_DIRECTORY})
list(APPEND LIBRARIES apr-1 -L${APR_LIBS_DIRECTORY})
list(APPEND LIBRARIES aprutil-1 -L${APR_UTIL_LIBS_DIRECTORY})
+ list(APPEND LIBRARIES ConfigProfile)
+
ADD_DEPENDENCIES(Utils install-3rd_party_logger)
endif()
@@ -100,6 +113,7 @@ endif()
target_link_libraries("Utils" ${LIBRARIES})
+
if(BUILD_TESTS)
add_subdirectory(test)
endif()
diff --git a/src/components/utils/include/utils/appenders_loader.h b/src/components/utils/include/utils/appenders_loader.h
index 03d3217994..65556e6862 100644
--- a/src/components/utils/include/utils/appenders_loader.h
+++ b/src/components/utils/include/utils/appenders_loader.h
@@ -40,6 +40,7 @@ class AppendersLoader {
AppendersLoader();
~AppendersLoader();
bool Loaded() const;
+
private:
void* handle_;
};
diff --git a/src/components/utils/include/utils/back_trace.h b/src/components/utils/include/utils/back_trace.h
index f2410e36bc..180714e5a6 100644
--- a/src/components/utils/include/utils/back_trace.h
+++ b/src/components/utils/include/utils/back_trace.h
@@ -68,8 +68,8 @@ class Backtrace {
std::vector<void*> backtrace_;
};
-std::ostream& operator<< (std::ostream& os, const Backtrace& bt);
+std::ostream& operator<<(std::ostream& os, const Backtrace& bt);
-} // namespace utils
+} // namespace utils
-#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_BACK_TRACE_H_
+#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_BACK_TRACE_H_
diff --git a/src/components/utils/include/utils/bitstream.h b/src/components/utils/include/utils/bitstream.h
index 9bf41d187f..13eacc6cb1 100644
--- a/src/components/utils/include/utils/bitstream.h
+++ b/src/components/utils/include/utils/bitstream.h
@@ -32,7 +32,7 @@
#ifndef SRC_COMPONENTS_UTILS_INCLUDE_UTILS_BITSTREAM_H_
#define SRC_COMPONENTS_UTILS_INCLUDE_UTILS_BITSTREAM_H_
-#include "stdint.h"
+#include <stdint.h>
#include <climits>
#include <cstring>
@@ -57,12 +57,21 @@ class BitStream {
// Mark stream as badly-formed.
// Should be called by Extract* family of procedures if they decide
// that stream is invalid
- void MarkBad() { bad_ = true; }
+ void MarkBad() {
+ bad_ = true;
+ }
// Predicates to check whether there were errors while parsing
// Stream is good when it is created
- bool IsGood() { return !bad_; }
- bool IsBad() { return bad_; }
- operator bool() { return IsGood(); }
+ bool IsGood() {
+ return !bad_;
+ }
+ bool IsBad() {
+ return bad_;
+ }
+ operator bool() {
+ return IsGood();
+ }
+
private:
// These two functions are used for internal stream checks only
// Stream parser procedures must not define their logic depending on
@@ -78,13 +87,13 @@ class BitStream {
// Extract single value, amount of bits read from stream depends on T size
// If there is not enough data in the stream, stream is marked bad
- template<typename T>
+ template <typename T>
void Extract(T& val);
// Read single value, amount of bits read from stream is signaled by |bits|
// parameter. T must be wide enough to hold this amount of bits.
// If there is not enough data in the stream, stream is marked bad
- template<typename T>
+ template <typename T>
void ExtractBits(T& val, size_t bits);
// Extract |length| bytes from the stream. Stream read position
@@ -94,10 +103,11 @@ class BitStream {
private:
const uint8_t* bytes_;
- const size_t bytes_count_;
+ const size_t bytes_count_;
size_t byte_offset_;
size_t bit_offset_;
bool bad_;
+
private:
friend void Extract(BitStream*, uint8_t*);
friend void Extract(BitStream*, uint8_t*, size_t);
@@ -105,7 +115,6 @@ class BitStream {
friend void Extract(BitStream*, uint32_t*, size_t);
friend void Extract(BitStream*, std::string*, size_t);
friend void Extract(BitStream*, std::vector<uint8_t>*, size_t);
-
};
// Extract single byte from stream
@@ -133,16 +142,15 @@ void Extract(BitStream* bs, std::string* str, size_t length);
// vector |data|. If stream is too short it is marked bad.
void Extract(BitStream* bs, std::vector<uint8_t>* data, size_t length);
-
// Template member definitions
-template<typename T>
+template <typename T>
void BitStream::Extract(T& val) {
// Slow but simple implementation
// It's a space for bit stream reading optimization
ExtractBits(val, sizeof(val) * CHAR_BIT);
}
-template<typename T>
+template <typename T>
void BitStream::ExtractBits(T& val, size_t bits) {
DCHECK(sizeof(val) * CHAR_BIT >= bits);
if (IsGood()) {
@@ -164,7 +172,6 @@ void BitStream::ExtractBits(T& val, size_t bits) {
}
}
-} // namespace utils
-
+} // namespace utils
-#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_BITSTREAM_H_
+#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_BITSTREAM_H_
diff --git a/src/components/utils/include/utils/convert_utils.h b/src/components/utils/include/utils/convert_utils.h
new file mode 100644
index 0000000000..0609164a60
--- /dev/null
+++ b/src/components/utils/include/utils/convert_utils.h
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_UTILS_INCLUDE_UTILS_CONVERT_UTILS_H_
+#define SRC_COMPONENTS_UTILS_INCLUDE_UTILS_CONVERT_UTILS_H_
+
+#include <stdint.h>
+#include <limits>
+
+namespace utils {
+
+/**
+ * Convert int64 value to long long int value
+ * Using when int64 value should be assign to JSON value
+ */
+long long int ConvertInt64ToLongLongInt(const int64_t value);
+
+/**
+ * Convert long long int value to int64 value
+ */
+int64_t ConvertLongLongIntToInt64(const long long int value);
+
+/**
+ * Convert uint64 value to unsigned long long int value
+ * Using when uint64 value should be assign to JSON value
+ */
+unsigned long long int ConvertUInt64ToLongLongUInt(const uint64_t value);
+
+/**
+ * Convert unsigned long long int value to uint64 value
+ */
+uint64_t ConvertLongLongUIntToUInt64(const unsigned long long int value);
+
+/**
+ * Convert one number value to another type value
+ */
+template <typename InputType, typename OutputType>
+OutputType SafeStaticCast(const InputType value) {
+ DCHECK_OR_RETURN(value >= std::numeric_limits<OutputType>::min(),
+ std::numeric_limits<OutputType>::min());
+ DCHECK_OR_RETURN(value <= std::numeric_limits<OutputType>::max(),
+ std::numeric_limits<OutputType>::max());
+ return static_cast<OutputType>(value);
+}
+
+} // namespace utils
+
+#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_CONVERT_UTILS_H_
diff --git a/src/components/utils/include/utils/file_system.h b/src/components/utils/include/utils/file_system.h
index a132837ca0..5862241c9c 100644
--- a/src/components/utils/include/utils/file_system.h
+++ b/src/components/utils/include/utils/file_system.h
@@ -41,7 +41,6 @@
namespace file_system {
-
/**
* @brief Get available disc space.
*
@@ -147,6 +146,13 @@ void Close(std::ofstream* file_stream);
std::string CurrentWorkingDirectory();
/**
+ * @brief Allows to obtaine absolute path for certain path.
+ * @param path the file name for which absolute path have to be calculated.
+ * @return absolute path for certain path.
+ */
+std::string GetAbsolutePath(const std::string& path);
+
+/**
* @brief Removes file
*
* @param name path to file
@@ -158,7 +164,8 @@ bool DeleteFile(const std::string& name);
* @brief Removes directory.
*
* @param name path to directory.
- * @param is_recursively true if you need delete directory recursively, otherwise false.
+ * @param is_recursively true if you need delete directory recursively,
+ *otherwise false.
* @return returns true if the directory is successfully deleted.
*/
bool RemoveDirectory(const std::string& directory_name,
@@ -213,8 +220,7 @@ bool WriteBinaryFile(const std::string& name,
* @param result read data
* @return returns true if the operation is successfully.
*/
-bool ReadBinaryFile(const std::string& name,
- std::vector<uint8_t>& result);
+bool ReadBinaryFile(const std::string& name, std::vector<uint8_t>& result);
bool ReadFile(const std::string& name, std::string& result);
@@ -248,8 +254,7 @@ uint64_t GetFileModificationTime(const std::string& path);
* @param dst Destination file path
* @return if result success return true
*/
-bool CopyFile(const std::string& src,
- const std::string& dst);
+bool CopyFile(const std::string& src, const std::string& dst);
/**
* @brief Move file from source to destination
@@ -258,8 +263,8 @@ bool CopyFile(const std::string& src,
* @param dst Destination file path
* @return if result success return true
*/
-bool MoveFile(const std::string& src,
- const std::string& dst);
+bool MoveFile(const std::string& src, const std::string& dst);
+
void remove_directory_content(const std::string& directory_name);
} // namespace file_system
diff --git a/src/components/utils/include/utils/gen_hash.h b/src/components/utils/include/utils/gen_hash.h
index e4102d36db..acb2e28a1d 100644
--- a/src/components/utils/include/utils/gen_hash.h
+++ b/src/components/utils/include/utils/gen_hash.h
@@ -37,6 +37,10 @@
namespace utils {
+namespace custom_string {
+class CustomString;
+}
+
/**
* @brief generate random alphanumeric string of specified length
* @param size length of random string
@@ -45,6 +49,32 @@ namespace utils {
const std::string gen_hash(size_t size);
+/**
+ * @brief Allows to generate hash from the specified string.
+ * The djb2 algorithm uses for hash generation.
+ * @param str_to_hash - the string from which hash should be generated.
+ * @return integer hash for the specified string.
+ */
+int32_t Djb2HashFromString(const std::string& str_to_hash);
+
+/**
+ * @brief Generates hash.
+ * The faq6 algorithm uses for hash generation.
+ * @param str_to_hash - the CustomSting contains ASCII or UTF8 string from which
+ * hash should be generated.
+ * @return uint32_t hash for the specified string.
+ */
+uint32_t CaseInsensitiveFaq6HashFromString(
+ const custom_string::CustomString& str_to_hash);
+
+/**
+ * @brief Transforms input string to lower case and then generates hash.
+ * The faq6 algorithm uses for hash generation.
+ * @param str_to_hash - the string from which hash should be generated.
+ * @return uint32_t hash for the specified string.
+ */
+uint32_t CaseInsensitiveFaq6HashFromString(const char* cstr);
+
} // namespace utils
#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_GEN_HASH_H_
diff --git a/src/components/utils/include/utils/helpers.h b/src/components/utils/include/utils/helpers.h
index e616dd56c1..17d4af27a1 100644
--- a/src/components/utils/include/utils/helpers.h
+++ b/src/components/utils/include/utils/helpers.h
@@ -31,12 +31,13 @@
*/
#ifndef SRC_COMPONENTS_UTILS_INCLUDE_UTILS_HELPERS_H
#define SRC_COMPONENTS_UTILS_INCLUDE_UTILS_HELPERS_H
-
+#include <algorithm>
/**
* These helpers allows to simplify compare strategy between some objects.
* Suppose user has some enum with value E with some numbers of possible values
* enum E {V1, V2, V3, V5};
- * So we want to know if some user-input value is belong to one of the enum's subset.
+ * So we want to know if some user-input value is belong to one of the enum's
+ *subset.
* Usually user has to do next routine
*
* E input_value = V3;
@@ -56,64 +57,72 @@
*/
namespace helpers {
- template<typename T>
- bool EQ (T what, T to) {
- return what == to;
- }
+template <typename T>
+bool EQ(T what, T to) {
+ return what == to;
+}
+
+template <typename T>
+bool NEQ(T what, T to) {
+ return !EQ<T>(what, to);
+}
- template<typename T>
- bool NEQ (T what, T to) {
- return !EQ<T>(what, to);
- }
+template <class U = bool>
+bool ALL(U what, U to) {
+ return what && to;
+}
- template<class U = bool>
- bool ALL (U what, U to) {
- return what && to;
- }
+template <class U = bool>
+bool ONE(U what, U to) {
+ return what || to;
+}
- template<class U = bool>
- bool ONE (U what, U to) {
- return what || to;
- }
+template <typename T,
+ bool (*CompareType)(T, T),
+ bool (*CmpStrategy)(bool, bool)>
+bool Compare(T what, T to) {
+ return CompareType(what, to);
+}
- template <typename T,
- bool (*CompareType)(T ,T),
- bool (*CmpStrategy)(bool ,bool)>
- bool Compare (T what, T to) {
- return CompareType(what, to);
- }
+template <typename T,
+ bool (*CompareType)(T, T),
+ bool (*CmpStrategy)(bool, bool)>
+bool Compare(T what, T to, T to1) {
+ return CmpStrategy(Compare<T, CompareType, CmpStrategy>(what, to),
+ Compare<T, CompareType, CmpStrategy>(what, to1));
+}
- template <typename T,
- bool (*CompareType)(T ,T),
- bool (*CmpStrategy)(bool, bool)>
- bool Compare(T what, T to, T to1) {
- return CmpStrategy(Compare<T, CompareType, CmpStrategy>(what, to),
- Compare<T, CompareType, CmpStrategy>(what, to1));
- }
+template <typename T,
+ bool (*CompareType)(T, T),
+ bool (*CmpStrategy)(bool, bool)>
+bool Compare(T what, T to, T to1, T to2) {
+ return CmpStrategy(Compare<T, CompareType, CmpStrategy>(what, to, to1),
+ Compare<T, CompareType, CmpStrategy>(what, to2));
+}
- template <typename T,
- bool (*CompareType)(T ,T),
- bool (*CmpStrategy)(bool, bool)>
- bool Compare(T what, T to, T to1, T to2) {
- return CmpStrategy(Compare<T, CompareType, CmpStrategy>(what, to, to1),
- Compare<T, CompareType, CmpStrategy>(what, to2));
- }
+template <typename T,
+ bool (*CompareType)(T, T),
+ bool (*CmpStrategy)(bool, bool)>
+bool Compare(T what, T to, T to1, T to2, T to3) {
+ return CmpStrategy(Compare<T, CompareType, CmpStrategy>(what, to, to1, to2),
+ Compare<T, CompareType, CmpStrategy>(what, to3));
+}
- template <typename T,
- bool (*CompareType)(T ,T),
- bool (*CmpStrategy)(bool, bool)>
- bool Compare(T what, T to, T to1, T to2, T to3) {
- return CmpStrategy(Compare<T, CompareType, CmpStrategy>(what, to, to1, to2),
- Compare<T, CompareType, CmpStrategy>(what, to3));
- }
+template <typename T,
+ bool (*CompareType)(T, T),
+ bool (*CmpStrategy)(bool, bool)>
+bool Compare(T what, T to, T to1, T to2, T to3, T to4) {
+ return CmpStrategy(
+ Compare<T, CompareType, CmpStrategy>(what, to, to1, to2, to3),
+ Compare<T, CompareType, CmpStrategy>(what, to4));
+}
- template <typename T,
- bool (*CompareType)(T ,T),
- bool (*CmpStrategy)(bool, bool)>
- bool Compare(T what, T to, T to1, T to2, T to3, T to4) {
- return CmpStrategy(Compare<T, CompareType, CmpStrategy>(what, to, to1, to2, to3),
- Compare<T, CompareType, CmpStrategy>(what, to4));
- }
+template <typename Container>
+bool in_range(const Container& container,
+ const typename Container::value_type& value) {
+ return std::find(container.begin(), container.end(), value) !=
+ container.end();
+}
}
-#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_HELPERS_H
+#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_HELPERS_H
diff --git a/src/components/utils/include/utils/log_message_loop_thread.h b/src/components/utils/include/utils/log_message_loop_thread.h
index 87b6c7e531..deea1a07c0 100644
--- a/src/components/utils/include/utils/log_message_loop_thread.h
+++ b/src/components/utils/include/utils/log_message_loop_thread.h
@@ -39,7 +39,6 @@
#include "utils/macro.h"
#include "utils/threads/message_loop_thread.h"
-#include "utils/singleton.h"
namespace logger {
@@ -54,26 +53,20 @@ typedef struct {
typedef std::queue<LogMessage> LogMessageQueue;
-typedef threads::MessageLoopThread<LogMessageQueue> LogMessageLoopThreadTemplate;
+typedef threads::MessageLoopThread<LogMessageQueue>
+ LogMessageLoopThreadTemplate;
class LogMessageHandler : public LogMessageLoopThreadTemplate::Handler {
public:
virtual void Handle(const LogMessage message) OVERRIDE;
};
-class LogMessageLoopThread :
- public LogMessageLoopThreadTemplate,
- public utils::Singleton<LogMessageLoopThread> {
-
+class LogMessageLoopThread : public LogMessageLoopThreadTemplate {
public:
- ~LogMessageLoopThread();
-
- private:
LogMessageLoopThread();
+ ~LogMessageLoopThread();
-DISALLOW_COPY_AND_ASSIGN(LogMessageLoopThread);
-FRIEND_BASE_SINGLETON_CLASS(LogMessageLoopThread);
-
+ DISALLOW_COPY_AND_ASSIGN(LogMessageLoopThread);
};
} // namespace logger
diff --git a/src/components/utils/include/utils/qdb_wrapper/sql_database.h b/src/components/utils/include/utils/qdb_wrapper/sql_database.h
new file mode 100644
index 0000000000..ba5c8a722a
--- /dev/null
+++ b/src/components/utils/include/utils/qdb_wrapper/sql_database.h
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_DATABASE_H_
+#define SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_DATABASE_H_
+
+#include <qdb/qdb.h>
+#include <string>
+#include "qdb_wrapper/sql_error.h"
+#include "utils/lock.h"
+
+namespace utils {
+namespace dbms {
+
+class SQLQuery;
+
+/**
+ * Represents a connection to a database.
+ */
+class SQLDatabase {
+ public:
+ explicit SQLDatabase(const std::string& db_name);
+ ~SQLDatabase();
+
+ /**
+ * Opens connection to the temporary in-memory database
+ * @return true if successfully
+ */
+ bool Open();
+
+ /**
+ * Closes connection to the database
+ */
+ void Close();
+
+ /**
+ * Begins a transaction on the database
+ * @return true if successfully
+ */
+ bool BeginTransaction();
+
+ /**
+ * Commits a transaction to the database
+ * @return true if successfully
+ */
+ bool CommitTransaction();
+
+ /**
+ * Rolls back a transaction on the database
+ * @return true if successfully
+ */
+ bool RollbackTransaction();
+
+ /**
+ * Gets information about the last error that occurred on the database
+ * @return last error
+ */
+ SQLError LastError() const;
+
+ /**
+ * Call backup for opened DB
+ */
+ bool Backup();
+
+ protected:
+ /**
+ * Gets connection to the SQLite database
+ * @return pointer to connection
+ */
+ qdb_hdl_t* conn() const;
+
+ private:
+ /**
+ * The connection to the SQLite database
+ */
+ qdb_hdl_t* conn_;
+
+ /**
+ * Lock for guarding connection to database
+ */
+ sync_primitives::Lock conn_lock_;
+
+ /**
+ * The database name
+ */
+ std::string db_name_;
+
+ /**
+ * The last error that occurred on the database
+ */
+ Error error_;
+
+ /**
+ * Execs query for internal using in this class
+ * @param query sql query without return results
+ * @return true if query was executed successfully
+ */
+ inline bool Exec(const std::string& query);
+
+ friend class SQLQuery;
+};
+
+} // namespace dbms
+} // namespace utils
+
+#endif // SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_DATABASE_H_
diff --git a/src/components/utils/include/utils/qdb_wrapper/sql_error.h b/src/components/utils/include/utils/qdb_wrapper/sql_error.h
new file mode 100644
index 0000000000..25fd558308
--- /dev/null
+++ b/src/components/utils/include/utils/qdb_wrapper/sql_error.h
@@ -0,0 +1,80 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_ERROR_H_
+#define SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_ERROR_H_
+
+#include <string>
+
+namespace utils {
+namespace dbms {
+
+typedef enum Error {
+ OK = 0, /* Successful result */
+ ERROR /* Error */
+} Error;
+
+/**
+ * Provides SQL database error information
+ */
+class SQLError {
+ public:
+ SQLError(Error number, const std::string& text = "");
+
+ /**
+ * Gets number of error
+ * @return error number
+ */
+ Error number() const;
+
+ /**
+ * Gets text description of the error
+ * @return text
+ */
+ std::string text() const;
+
+ private:
+ /**
+ * Number of the error
+ */
+ Error number_;
+
+ /**
+ * Description of the error
+ */
+ mutable std::string text_;
+};
+
+} // namespace dbms
+} // namespace utils
+
+#endif // SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_ERROR_H_
diff --git a/src/components/utils/include/utils/qdb_wrapper/sql_query.h b/src/components/utils/include/utils/qdb_wrapper/sql_query.h
new file mode 100644
index 0000000000..f1da6ccad9
--- /dev/null
+++ b/src/components/utils/include/utils/qdb_wrapper/sql_query.h
@@ -0,0 +1,265 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_QUERY_H_
+#define SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_QUERY_H_
+
+#include <stdint.h>
+#include <qdb/qdb.h>
+#include <string>
+#include <vector>
+#include <utility>
+#include "qdb_wrapper/sql_error.h"
+#include "utils/lock.h"
+
+namespace utils {
+namespace dbms {
+
+class SQLDatabase;
+
+/**
+ * Provides a means of executing and manipulating SQL statements
+ */
+class SQLQuery {
+ public:
+ explicit SQLQuery(SQLDatabase* db);
+ ~SQLQuery();
+
+ /**
+ * Prepares the SQL query for executing
+ * @param query the utf-8 string of SQL query
+ * @return true if successfully
+ */
+ bool Prepare(const std::string& query);
+
+ /**
+ * Resets the binds of query for re-executing
+ * @return true if successfully
+ */
+ bool Reset();
+
+ /**
+ * Deletes prepared SQL query
+ */
+ void Finalize();
+
+ /**
+ * Executes SQL query without make binds
+ * @param query the utf-8 string of SQL query
+ * @return true if successfull
+ */
+ bool Exec(const std::string& query);
+
+ /**
+ * Executes prepared SQL query and positions the query on the first record
+ * @return true if successfull
+ */
+ bool Exec();
+
+ /**
+ * Retrieves the next record in the result, if available,
+ * and positions the query on the retrieved record
+ * @return true if record was retrieved successfully, false if a error was
+ * or the result is empty or was retrieves last record
+ */
+ bool Next();
+
+ /**
+ * Binds null in the prepared query
+ * @param pos position of param in the query
+ */
+ void Bind(int pos);
+
+ /**
+ * Binds int value in the prepared query.
+ * @param pos position of param in the query
+ * @param value value of param
+ */
+ void Bind(int pos, int value);
+
+ /**
+ * Binds int64_t value in the prepared query.
+ * @param pos position of param in the query
+ * @param value value of param
+ */
+ void Bind(int pos, int64_t value);
+
+ /**
+ * Binds double value in the prepared query.
+ * @param pos position of param in the query
+ * @param value value of param
+ */
+ void Bind(int pos, double value);
+
+ /**
+ * Binds bool value in the prepared query.
+ * @param pos position of param in the query
+ * @param value value of param
+ */
+ void Bind(int pos, bool value);
+
+ /**
+ * Binds string in the prepared query.
+ * @param pos position of param in the query
+ * @param value utf-8 string
+ */
+ void Bind(int pos, const std::string& value);
+
+ /**
+ * Gets value in the result record
+ * @param pos position of value
+ * @return boolean value
+ */
+ bool GetBoolean(int pos) const;
+
+ /**
+ * Gets value in the result record
+ * @param pos position of value
+ * @return integer value
+ */
+ int GetInteger(int pos) const;
+
+ /**
+ * Gets value in the result record
+ * @param pos position of value
+ * @return unsigned integer value
+ */
+ uint32_t GetUInteger(int pos) const;
+
+ /**
+ * Gets value in the result record
+ * @param pos position of value
+ * @return int64_t value
+ */
+ int64_t GetLongInt(int pos) const;
+
+ /**
+ * Gets value in the result record
+ * @param pos position of value
+ * @return double value
+ */
+ double GetDouble(int pos) const;
+
+ /**
+ * Gets value in the result record
+ * @param pos position of value
+ * @return string value
+ */
+ std::string GetString(int pos) const;
+
+ /**
+ * Checks if value is null
+ * @param pos position of value
+ * @return true if value is null
+ */
+ bool IsNull(int pos) const;
+
+ /**
+ * Gets last id of insert row
+ * @return id of insert row
+ */
+ int64_t LastInsertId() const;
+
+ /**
+ * Gets string of the query
+ * @return string of the query
+ */
+ const std::string& query() const;
+
+ /**
+ * Gets information about the last error that occurred on the database
+ * @return last error
+ */
+ SQLError LastError() const;
+
+ private:
+ /**
+ * The instantiation of database
+ */
+ SQLDatabase* db_;
+
+ /**
+ * The string of query
+ */
+ std::string query_;
+
+ /**
+ * The id of SQL statement in QDB
+ */
+ int statement_;
+
+ /**
+ * Containers for keeping bind data
+ */
+ std::vector<std::pair<int, int64_t> > int_binds_;
+ std::vector<std::pair<int, double> > double_binds_;
+ std::vector<std::pair<int, std::string> > string_binds_;
+ std::vector<int> null_binds_;
+
+ /**
+ * The array for binging data to the prepare query
+ */
+ qdb_binding_t* bindings_;
+
+ /**
+ * Lock for guarding bindings
+ */
+ sync_primitives::Lock bindings_lock_;
+
+ /**
+ * The result of query
+ */
+ qdb_result_t* result_;
+
+ /**
+ * The current row in result for select
+ */
+ int current_row_;
+
+ /**
+ * The number of rows in a result
+ */
+ int rows_;
+
+ /**
+ * The last error that occurred with this query
+ */
+ Error error_;
+
+ uint8_t SetBinds();
+ bool Result();
+};
+
+} // namespace dbms
+} // namespace utils
+
+#endif // SRC_COMPONENTS_POLICY_QDB_WRAPPER_INCLUDE_QDB_WRAPPER_SQL_QUERY_H_
diff --git a/src/components/utils/include/utils/resource_usage.h b/src/components/utils/include/utils/resource_usage.h
index ff90b2c22f..4dd8a7eafd 100644
--- a/src/components/utils/include/utils/resource_usage.h
+++ b/src/components/utils/include/utils/resource_usage.h
@@ -44,8 +44,8 @@
#include "utils/logger.h"
-#define MAX_COMM_LEN 128
-#define MAX_CMDLINE_LEN 128
+#define MAX_COMM_LEN 128
+#define MAX_CMDLINE_LEN 128
namespace utils {
@@ -56,7 +56,7 @@ struct ResourseUsage {
};
class Resources {
- public:
+ public:
typedef uint32_t MemInfo;
#if defined(__QNXNTO__)
typedef procfs_info PidStats;
@@ -108,19 +108,18 @@ class Resources {
unsigned long long delayacct_blkio_ticks;
unsigned long guest_time;
long int cguest_time;
- };
+ };
#else
#endif
- public:
- /*
- * @brief Returns current resource usage of process
- * @return Raw pointer on ResourseUsage if success, otherwise return NULL
- */
+ public:
+ /*
+ * @brief Returns current resource usage of process
+ * @return Raw pointer on ResourseUsage if success, otherwise return NULL
+ */
static ResourseUsage* getCurrentResourseUsage();
-private:
-
+ private:
#ifdef BUILD_TESTS
friend class ResourceUsagePrivateTest;
FRIEND_TEST(ResourceUsagePrivateTest, ReadStatFileTest);
@@ -134,7 +133,8 @@ private:
/*
* @brief reads /proc/PID/stat file on linux
* do not work on QNX ( return false, output wan't be changed )
- * @param output - storage for result string ( there will be separated content of /proc/PID/stat )
+ * @param output - storage for result string ( there will be separated content
+ * of /proc/PID/stat )
* @return true on succes false onb fail
*/
static bool ReadStatFile(std::string& output);
@@ -171,9 +171,6 @@ private:
*/
static const char* proc;
};
-
}
-
-
#endif /* SRC_COMPONENTS_UTILS_INCLUDE_UTILS_RESOURCE_USAGE_H_ */
diff --git a/src/components/utils/include/utils/signals.h b/src/components/utils/include/utils/signals.h
index 6c91836309..48120d53cd 100644
--- a/src/components/utils/include/utils/signals.h
+++ b/src/components/utils/include/utils/signals.h
@@ -34,15 +34,15 @@
#define SRC_COMPONENTS_UTILS_INCLUDE_UTILS_SIGNALS_H_
#ifdef __QNXNTO__
-typedef void (*sighandler_t) (int);
+typedef void (*sighandler_t)(int);
#else
#include <signal.h>
#endif
namespace utils {
-bool SubscribeToTerminateSignal(sighandler_t func);
-bool SubscribeToFaultSignal(sighandler_t func);
+bool UnsibscribeFromTermination();
+bool WaitTerminationSignals(sighandler_t sig_handler);
} // namespace utils
diff --git a/src/components/utils/include/utils/singleton.h b/src/components/utils/include/utils/singleton.h
index fff7294d1c..b73780ee1d 100644
--- a/src/components/utils/include/utils/singleton.h
+++ b/src/components/utils/include/utils/singleton.h
@@ -43,15 +43,13 @@ namespace deleters {
class DummyDeleter {
public:
- void grab(void* pointer) {
- }
+ void grab(void* pointer) {}
};
-template<typename T>
+template <typename T>
class Deleter {
public:
- Deleter() : pointer_(0) {
- }
+ Deleter() : pointer_(0) {}
~Deleter() {
if (pointer_) {
delete pointer_;
@@ -60,69 +58,68 @@ class Deleter {
void grab(T* pointer) {
pointer_ = pointer;
}
+
private:
T* pointer_;
};
} // namespace deleters
-template<typename T, class Deleter = deleters::DummyDeleter>
+template <typename T, class Deleter = deleters::DummyDeleter>
class Singleton {
-/**
- * @brief Singleton template
- * Singleton classes must derive from this template specialized with class itself:
- *
- * class MySingleton : public Singleton<MySingleton> {...};
- *
- * All such classes must declare instance() method as friend
- * by adding FRIEND_BASE_SINGLETON_CLASS macro from macro.h to class definition:
- *
- * FRIEND_BASE_SINGLETON_CLASS(MySingleton);
- *
- * Instance of this class (if created) can be deleted by Deleter destructor
- * which is called after main() (or from exit())
- * This requires T destructor to be accessible for Deleter (e.g. public)
- * Deleter template parameter can be specified with any class
- * with public default constructor, destructor and method
- * void grab(T*);
- * However, default Deleter specification does nothing
- *
- * Also instance can be deleted explicitly by calling destroy() method
- *
- * Both instance() and destroy() methods are thread safe
- * but not thread safety between simultaneous calls
- * of instance() and destroy() is cared about
- */
+ /**
+ * @brief Singleton template
+ * Singleton classes must derive from this template specialized with class
+ *itself:
+ *
+ * class MySingleton : public Singleton<MySingleton> {...};
+ *
+ * All such classes must declare instance() method as friend
+ * by adding FRIEND_BASE_SINGLETON_CLASS macro from macro.h to class
+ *definition:
+ *
+ * FRIEND_BASE_SINGLETON_CLASS(MySingleton);
+ *
+ * Instance of this class (if created) can be deleted by Deleter destructor
+ * which is called after main() (or from exit())
+ * This requires T destructor to be accessible for Deleter (e.g. public)
+ * Deleter template parameter can be specified with any class
+ * with public default constructor, destructor and method
+ * void grab(T*);
+ * However, default Deleter specification does nothing
+ *
+ * Also instance can be deleted explicitly by calling destroy() method
+ *
+ * Both instance() and destroy() methods are thread safe
+ * but not thread safety between simultaneous calls
+ * of instance() and destroy() is cared about
+ */
public:
-/**
- * @brief Returns the singleton of class
- */
+ /**
+ * @brief Returns the singleton of class
+ */
static T* instance();
-/**
- * @brief Destroys the singleton (if it had been created)
- */
+ /**
+ * @brief Destroys the singleton (if it had been created)
+ */
static void destroy();
-/**
- * @brief Checks whether the singleton exists
- */
+ /**
+ * @brief Checks whether the singleton exists
+ */
static bool exists();
private:
-
static T** instance_pointer();
static Deleter* deleter();
static sync_primitives::Lock lock_;
};
-
-template<typename T, class Deleter>
+template <typename T, class Deleter>
sync_primitives::Lock Singleton<T, Deleter>::lock_;
-
-template<typename T, class Deleter>
+template <typename T, class Deleter>
T* Singleton<T, Deleter>::instance() {
-
T* local_instance;
atomic_pointer_assign(local_instance, *instance_pointer());
memory_barrier();
@@ -142,9 +139,8 @@ T* Singleton<T, Deleter>::instance() {
return local_instance;
}
-template<typename T, class Deleter>
+template <typename T, class Deleter>
void Singleton<T, Deleter>::destroy() {
-
T* local_instance;
atomic_pointer_assign(local_instance, *instance_pointer());
memory_barrier();
@@ -162,18 +158,18 @@ void Singleton<T, Deleter>::destroy() {
}
}
-template<typename T, class Deleter>
+template <typename T, class Deleter>
bool Singleton<T, Deleter>::exists() {
return *instance_pointer() != 0;
}
-template<typename T, class Deleter>
+template <typename T, class Deleter>
T** Singleton<T, Deleter>::instance_pointer() {
static T* instance = 0;
return &instance;
}
-template<typename T, class Deleter>
+template <typename T, class Deleter>
Deleter* Singleton<T, Deleter>::deleter() {
static Deleter deleter;
return &deleter;
diff --git a/src/components/utils/include/utils/sqlite_wrapper/sql_database.h b/src/components/utils/include/utils/sqlite_wrapper/sql_database.h
new file mode 100644
index 0000000000..720628ef3c
--- /dev/null
+++ b/src/components/utils/include/utils/sqlite_wrapper/sql_database.h
@@ -0,0 +1,167 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_DATABASE_H_
+#define SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_DATABASE_H_
+
+#include <string>
+#include "utils/sqlite_wrapper/sql_error.h"
+#include "utils/lock.h"
+
+struct sqlite3;
+
+namespace utils {
+namespace dbms {
+
+class SQLQuery;
+
+/**
+ * Represents a connection to a database.
+ */
+class SQLDatabase {
+ public:
+ SQLDatabase();
+ explicit SQLDatabase(const std::string& filename);
+ ~SQLDatabase();
+
+ /**
+ * Opens connection to the temporary in-memory database
+ * @return true if successfully
+ */
+ bool Open();
+
+ /**
+ * Closes connection to the database
+ */
+ void Close();
+
+ /**
+ * Begins a transaction on the database
+ * @return true if successfully
+ */
+ bool BeginTransaction();
+
+ /**
+ * Commits a transaction to the database
+ * @return true if successfully
+ */
+ bool CommitTransaction();
+
+ /**
+ * Rolls back a transaction on the database
+ * @return true if successfully
+ */
+ bool RollbackTransaction();
+
+ /**
+ * Gets information about the last error that occurred on the database
+ * @return last error
+ */
+ SQLError LastError() const;
+
+ /**
+ * Sets path to database
+ * If the database is already opened then need reopen it
+ */
+ void set_path(const std::string& path);
+
+ /**
+ * @brief get_path databse location path.
+ *
+ * @return the path to the database location
+ */
+ std::string get_path() const;
+
+ /**
+ * Checks if database is read/write
+ * @return true if database is read/write
+ */
+ bool IsReadWrite();
+
+ /**
+ * Call backup for opened DB
+ */
+ bool Backup();
+
+ protected:
+ /**
+ * Gets connection to the SQLite database
+ * @return pointer to connection
+ */
+ sqlite3* conn() const;
+
+ private:
+ /**
+ * The connection to the SQLite database
+ */
+ sqlite3* conn_;
+
+ /**
+ * Lock for guarding connection to database
+ */
+ sync_primitives::Lock conn_lock_;
+
+ /**
+ * The filename of database
+ */
+ std::string databasename_;
+
+ /**
+ * The last error that occurred on the database
+ */
+ int error_;
+
+ /**
+ * The temporary in-memory database
+ * @see SQLite manual
+ */
+ static const std::string kInMemory;
+
+ /**
+ * The extension of filename of database
+ */
+ static const std::string kExtension;
+
+ /**
+ * Execs query for internal using in this class
+ * @param query sql query without return results
+ * @return true if query was executed successfully
+ */
+ inline bool Exec(const std::string& query);
+
+ friend class SQLQuery;
+};
+
+} // namespace dbms
+} // namespace utils
+
+#endif // SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_DATABASE_H_
diff --git a/src/components/utils/include/utils/sqlite_wrapper/sql_error.h b/src/components/utils/include/utils/sqlite_wrapper/sql_error.h
new file mode 100644
index 0000000000..8a53e12169
--- /dev/null
+++ b/src/components/utils/include/utils/sqlite_wrapper/sql_error.h
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_ERROR_H_
+#define SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_ERROR_H_
+
+#include <string>
+
+namespace utils {
+namespace dbms {
+
+typedef enum Error {
+ OK = 0, /* Successful result */
+ ERROR, /* SQL error or missing database */
+ INTERNAL, /* Internal logic error in SQLite */
+ PERM, /* Access permission denied */
+ ABORT, /* Callback routine requested an abort */
+ BUSY, /* The database file is locked */
+ LOCKED, /* A table in the database is locked */
+ NOMEM, /* A malloc() failed */
+ READONLY, /* Attempt to write a readonly database */
+ INTERRUPT, /* Operation terminated by sqlite3_interrupt()*/
+ IOERR, /* Some kind of disk I/O error occurred */
+ CORRUPT, /* The database disk image is malformed */
+ NOTFOUND, /* Unknown opcode in sqlite3_file_control() */
+ FULL, /* Insertion failed because database is full */
+ CANTOPEN, /* Unable to open the database file */
+ PROTOCOL, /* Database lock protocol error */
+ EMPTY, /* Database is empty */
+ SCHEMA, /* The database schema changed */
+ TOOBIG, /* String or BLOB exceeds size limit */
+ CONSTRAINT, /* Abort due to constraint violation */
+ MISMATCH, /* Data type mismatch */
+ MISUSE, /* Library used incorrectly */
+ NOLFS, /* Uses OS features not supported on host */
+ AUTH, /* Authorization denied */
+ FORMAT, /* Auxiliary database format error */
+ RANGE, /* 2nd parameter to sqlite3_bind out of range */
+ NOTADB, /* File opened that is not a database file */
+ NOTICE, /* Notifications from sqlite3_log() */
+ WARNING, /* Warnings from sqlite3_log() */
+ ROW = 100, /* sqlite3_step() has another row ready */
+ DONE = 101 /* sqlite3_step() has finished executing */
+} Error;
+
+/**
+ * Provides SQL database error information
+ */
+class SQLError {
+ public:
+ SQLError(Error number, const std::string& text = "");
+
+ /**
+ * Gets number of error
+ * @return error number
+ */
+ Error number() const;
+
+ /**
+ * Gets text description of the error
+ * @return text
+ */
+ std::string text() const;
+
+ private:
+ /**
+ * Number of the error
+ */
+ Error number_;
+
+ /**
+ * Description of the error
+ */
+ mutable std::string text_;
+};
+
+} // namespace dbms
+} // namespace utils
+
+#endif // SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_ERROR_H_
diff --git a/src/components/utils/include/utils/sqlite_wrapper/sql_query.h b/src/components/utils/include/utils/sqlite_wrapper/sql_query.h
new file mode 100644
index 0000000000..de75e37c62
--- /dev/null
+++ b/src/components/utils/include/utils/sqlite_wrapper/sql_query.h
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_QUERY_H_
+#define SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_QUERY_H_
+
+#include <stdint.h>
+#include <string>
+#include "utils/sqlite_wrapper/sql_error.h"
+#include "utils/lock.h"
+
+struct sqlite3_stmt;
+
+namespace utils {
+namespace dbms {
+
+class SQLDatabase;
+
+/**
+ * Provides a means of executing and manipulating SQL statements
+ */
+class SQLQuery {
+ public:
+ explicit SQLQuery(SQLDatabase* db);
+ ~SQLQuery();
+
+ /**
+ * Prepares the SQL query for executing
+ * @param query the utf-8 string of SQL query
+ * @return true if successfully
+ */
+ bool Prepare(const std::string& query);
+
+ /**
+ * Resets the binds of query for re-executing
+ * @return true if successfully
+ */
+ bool Reset();
+
+ /**
+ * Deletes prepared SQL query
+ */
+ void Finalize();
+
+ /**
+ * Executes SQL query without make binds
+ * @param query the utf-8 string of SQL query
+ * @return true if successfull
+ */
+ bool Exec(const std::string& query);
+
+ /**
+ * Executes prepared SQL query and positions the query on the first record
+ * @return true if successfull
+ */
+ bool Exec();
+
+ /**
+ * Retrieves the next record in the result, if available,
+ * and positions the query on the retrieved record
+ * @return true if record was retrieved successfully, false if a error was
+ * or the result is empty or was retrieves last record
+ */
+ bool Next();
+
+ /**
+ * Binds null in the prepared query
+ * @param pos position of param in the query
+ */
+ void Bind(int pos);
+
+ /**
+ * Binds int value in the prepared query.
+ * @param pos position of param in the query
+ * @param value value of param
+ */
+ void Bind(int pos, int value);
+
+ /**
+ * Binds int64_t value in the prepared query.
+ * @param pos position of param in the query
+ * @param value value of param
+ */
+ void Bind(int pos, int64_t value);
+
+ /**
+ * Binds double value in the prepared query.
+ * @param pos position of param in the query
+ * @param value value of param
+ */
+ void Bind(int pos, double value);
+
+ /**
+ * Binds bool value in the prepared query.
+ * @param pos position of param in the query
+ * @param value value of param
+ */
+ void Bind(int pos, bool value);
+
+ /**
+ * Binds string in the prepared query.
+ * @param pos position of param in the query
+ * @param value utf-8 string
+ */
+ void Bind(int pos, const std::string& value);
+
+ /**
+ * Gets value in the result record
+ * @param pos position of value
+ * @return boolean value
+ */
+ bool GetBoolean(int pos) const;
+
+ /**
+ * Gets value in the result record
+ * @param pos position of value
+ * @return integer value
+ */
+ int GetInteger(int pos) const;
+
+ /**
+ * Gets value in the result record
+ * @param pos position of value
+ * @return unsigned integer value
+ */
+ uint32_t GetUInteger(int pos) const;
+
+ /**
+ * Gets value in the result record
+ * @param pos position of value
+ * @return int64_t value
+ */
+ int64_t GetLongInt(int pos) const;
+
+ /**
+ * Gets value in the result record
+ * @param pos position of value
+ * @return double value
+ */
+ double GetDouble(int pos) const;
+
+ /**
+ * Gets value in the result record
+ * @param pos position of value
+ * @return string value
+ */
+ std::string GetString(int pos) const;
+
+ /**
+ * Checks if value is null
+ * @param pos position of value
+ * @return true if value is null
+ */
+ bool IsNull(int pos) const;
+
+ /**
+ * Gets last id of insert row
+ * @return id of insert row
+ */
+ int64_t LastInsertId() const;
+
+ /**
+ * Gets string of the query
+ * @return string of the query
+ */
+ const std::string& query() const;
+
+ /**
+ * Gets information about the last error that occurred on the database
+ * @return last error
+ */
+ SQLError LastError() const;
+
+ private:
+ /**
+ * The instantiation of database
+ */
+ SQLDatabase& db_;
+
+ /**
+ * The string of query
+ */
+ std::string query_;
+
+ /**
+ * The SQL statement in SQLite
+ */
+ sqlite3_stmt* statement_;
+
+ /**
+ * Lock for guarding statement
+ */
+ sync_primitives::Lock statement_lock_;
+
+ /**
+ * The last error that occurred with this query
+ */
+ int error_;
+};
+
+} // namespace dbms
+} // namespace utils
+
+#endif // SRC_COMPONENTS_POLICY_SQLITE_WRAPPER_INCLUDE_SQLITE_WRAPPER_SQL_QUERY_H_
diff --git a/src/components/utils/include/utils/stl_utils.h b/src/components/utils/include/utils/stl_utils.h
index 70fbadbd5e..4a4e3d2fe8 100644
--- a/src/components/utils/include/utils/stl_utils.h
+++ b/src/components/utils/include/utils/stl_utils.h
@@ -40,45 +40,48 @@ namespace utils {
* Utility class that automatically deletes STL collection of
* freestore objects
*/
-template<class T>
+template <class T>
class StlCollectionDeleter {
public:
typedef T Collection;
- StlCollectionDeleter(T* collection)
- : collection_(collection) {
+ StlCollectionDeleter(T* collection) : collection_(collection) {
DCHECK(collection_);
}
~StlCollectionDeleter() {
- for (typename Collection::iterator i = collection_->begin(), end =
- collection_->end(); i != end; ++i) {
+ for (typename Collection::iterator i = collection_->begin(),
+ end = collection_->end();
+ i != end;
+ ++i) {
delete *i;
*i = NULL;
}
}
+
private:
Collection* collection_;
};
-template<class T>
+template <class T>
class StlMapDeleter {
public:
typedef T Collection;
- StlMapDeleter(T* collection)
- : collection_(collection) {
+ StlMapDeleter(T* collection) : collection_(collection) {
DCHECK(collection_);
}
~StlMapDeleter() {
- for (typename Collection::iterator i = collection_->begin(), end =
- collection_->end(); i != end; ++i) {
+ for (typename Collection::iterator i = collection_->begin(),
+ end = collection_->end();
+ i != end;
+ ++i) {
delete i->second;
i->second = NULL;
}
-
}
+
private:
Collection* collection_;
};
} // namespace utils
-#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_STL_UTILS_H_
+#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_STL_UTILS_H_
diff --git a/src/components/utils/include/utils/threads/pulse_thread_delegate.h b/src/components/utils/include/utils/threads/pulse_thread_delegate.h
index 207b64caaf..623e12b261 100644
--- a/src/components/utils/include/utils/threads/pulse_thread_delegate.h
+++ b/src/components/utils/include/utils/threads/pulse_thread_delegate.h
@@ -42,9 +42,11 @@ namespace threads {
/**
* @brief This ThreadDelegate derivative is designed
* to implement threads waiting for QNX Pulse messages
- * When constucted, an instance of this class creates QNX channel and connects to it
+ * When constucted, an instance of this class creates QNX channel and connects
+ * to it
* In exitThreadMain() channel is disconnected and destroyed
- * In threadMain() endless loop event is armed via pure virtual method ArmEvent()
+ * In threadMain() endless loop event is armed via pure virtual method
+ * ArmEvent()
* and thread blocks on MsgReceivePulse() waiting for Pulse
* When Pulse comes, OnPulse() pure virtual method is invoked
* Subclassed must implement ArmEvent() for events of interest
@@ -52,39 +54,42 @@ namespace threads {
*/
class PulseThreadDelegate : public ThreadDelegate {
public:
-/**
- * @brief default constructor
- */
+ /**
+ * @brief default constructor
+ */
PulseThreadDelegate();
virtual void threadMain();
virtual void exitThreadMain();
protected:
-/**
- * @brief This method is to be implemented to arm events of interest
- * @param event pointer to structure sigevent
- * @return If this method returns true, thread is blocked on MsgReceivePulse() waiting for Pulse
- */
+ /**
+ * @brief This method is to be implemented to arm events of interest
+ * @param event pointer to structure sigevent
+ * @return If this method returns true, thread is blocked on
+ * MsgReceivePulse() waiting for Pulse
+ */
virtual bool ArmEvent(struct sigevent* event) = 0;
-/**
- * @brief This method is invoked from threadMain() when Pulse comes
- */
+ /**
+ * @brief This method is invoked from threadMain() when Pulse comes
+ */
virtual void OnPulse() = 0;
/**
* This method is to be initialize child class
* @return If this method returns false, thread will be stopped
*/
- virtual bool Init() { return true; }
+ virtual bool Init() {
+ return true;
+ }
-/**
- * Finalizes thread
- * Can free resources
- */
+ /**
+ * Finalizes thread
+ * Can free resources
+ */
virtual void Finalize() {}
private:
- enum {PULSE_CODE = _PULSE_CODE_MINAVAIL + 1};
+ enum { PULSE_CODE = _PULSE_CODE_MINAVAIL + 1 };
volatile bool run_;
int chid_;
diff --git a/src/components/utils/include/utils/threads/thread_manager.h b/src/components/utils/include/utils/threads/thread_manager.h
index d72abb428f..3f53c902c4 100644
--- a/src/components/utils/include/utils/threads/thread_manager.h
+++ b/src/components/utils/include/utils/threads/thread_manager.h
@@ -51,7 +51,7 @@
#include "utils/threads/thread_delegate.h"
namespace threads {
- class Thread;
+class Thread;
/*
* This class is here currently to remember names associated to threads.
@@ -69,12 +69,13 @@ class ThreadManager : public utils::Singleton<ThreadManager> {
};
ThreadManager() {}
MessageQueue<ThreadDesc> threads_to_terminate;
+
private:
DISALLOW_COPY_AND_ASSIGN(ThreadManager);
FRIEND_BASE_SINGLETON_CLASS(ThreadManager);
};
-} // namespace threads
+} // namespace threads
-#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_THREADS_THREAD_MANAGER_H_
+#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_THREADS_THREAD_MANAGER_H_
diff --git a/src/components/utils/include/utils/threads/thread_validator.h b/src/components/utils/include/utils/threads/thread_validator.h
index dc2d138e2e..2e7dac02ab 100644
--- a/src/components/utils/include/utils/threads/thread_validator.h
+++ b/src/components/utils/include/utils/threads/thread_validator.h
@@ -68,11 +68,11 @@ class SingleThreadSimpleValidator {
// of classes being checked for absence of concurrent access
void AssertRunningOnCreationThread() const;
PlatformThreadHandle creation_thread_id() const;
+
private:
const PlatformThreadHandle creation_thread_id_;
};
-
/*
* This is bit more sophisticated debug helper which allows
* objects being checked to be transferred between threads.
@@ -97,10 +97,11 @@ class SingleThreadValidator {
// of classes being checked for absence of unintended concurrent
// access
void AssertRunningOnValidThread() const;
+
private:
mutable PlatformThreadHandle owning_thread_id_;
};
-} // namespace threads
+} // namespace threads
-#endif // SRC_COMPONENTS_UTILS_INCLUDE_THREADS_THREAD_VALIDATOR_H_
+#endif // SRC_COMPONENTS_UTILS_INCLUDE_THREADS_THREAD_VALIDATOR_H_
diff --git a/src/components/utils/include/utils/timer.h b/src/components/utils/include/utils/timer.h
new file mode 100644
index 0000000000..690c9df5dc
--- /dev/null
+++ b/src/components/utils/include/utils/timer.h
@@ -0,0 +1,217 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#ifndef SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_H_
+#define SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_H_
+
+#include <string>
+#include <stdint.h>
+#include <memory>
+
+#include "utils/macro.h"
+#include "utils/lock.h"
+#include "utils/timer_task.h"
+#include "utils/threads/thread.h"
+#include "utils/threads/thread_delegate.h"
+
+namespace timer {
+
+typedef uint32_t Milliseconds;
+
+/**
+ * @brief Timer calls custom callback function after
+ * specified timeout has been elapsed.
+ * Thread-safe class
+ */
+class Timer {
+ public:
+ /**
+ * @brief Constructor
+ * Does not start timer
+ * @param name Timer name for identification
+ * @param task Task for tracking
+ */
+ Timer(const std::string& name, TimerTask* task);
+
+ /**
+ * @brief Destructor
+ * Stops timer if it's running
+ */
+ ~Timer();
+
+ /**
+ * @brief Starts timer with specified timeout
+ * @param timeout Timer timeout
+ * @param single_shot Single shot flag for timer
+ */
+ void Start(const Milliseconds timeout, const bool single_shot);
+
+ /**
+ * @brief Stops timer if it's running
+ */
+ void Stop();
+
+ /**
+ * @brief Gets current timer status
+ * @return True in case of timer is running, false otherwise
+ */
+ bool is_running() const;
+
+ /**
+ * @brief Gets current timer timeout
+ * @return Current timeout in milliseconds.
+ * Null if timer has not been started
+ */
+ Milliseconds timeout() const;
+
+ private:
+ /**
+ * @brief Delegate for timer thread
+ */
+ class TimerDelegate : public threads::ThreadDelegate {
+ public:
+ /**
+ * @brief Constructor
+ * @param timer Timer instance pointer for callback calling
+ */
+ TimerDelegate(const Timer* timer, sync_primitives::Lock& state_lock_ref);
+
+ /**
+ * @brief Sets timer timeout
+ * @param timeout Timeout in milliseconds to be set
+ */
+ void set_timeout(const Milliseconds timeout);
+
+ /**
+ * @brief Gets timer timeout
+ * @return Timer timeout
+ */
+ Milliseconds timeout() const;
+
+ /**
+ * @brief Sets timer delegate stop flag
+ * @param stop_flag Bool flag to be set
+ */
+ void set_stop_flag(const bool stop_flag);
+
+ /**
+ * @brief Gets timer delegate stop flag
+ * @return Delegate stop flag
+ */
+ bool stop_flag() const;
+
+ /**
+ * @brief Sets timer delegate finalized flag
+ * @param finalized_flag Bool flag to be set
+ */
+ void set_finalized_flag(const bool finalized_flag);
+
+ /**
+ * @brief Gets timer delegate finalized flag
+ * @return Delegate finalized flag
+ */
+ bool finalized_flag() const;
+
+ void threadMain() OVERRIDE;
+ void exitThreadMain() OVERRIDE;
+
+ private:
+ const Timer* timer_;
+ Milliseconds timeout_;
+
+ /**
+ * @brief Stop flag shows if timer should be stopped
+ * after next iteration
+ */
+ bool stop_flag_;
+
+ /**
+ * @brief Finalized flag shows if timer is finalized
+ * and cannot be restarted until actual thread stopping
+ */
+ bool finalized_flag_;
+
+ sync_primitives::Lock& state_lock_ref_;
+ sync_primitives::ConditionalVariable state_condition_;
+
+ DISALLOW_COPY_AND_ASSIGN(TimerDelegate);
+ };
+
+ /**
+ * @brief Sets up timer delegate to start state.
+ * Not thread-safe
+ * @param timeout Timer timeout
+ */
+ void StartDelegate(const Milliseconds timeout) const;
+
+ /**
+ * @brief Sets up timer delegate to stop state.
+ * Not thread-safe
+ */
+ void StopDelegate() const;
+
+ /**
+ * @brief Starts timer thread.
+ * Not thread-safe
+ */
+ void StartThread();
+
+ /**
+ * @brief Stops timer thread.
+ * Not thread-safe
+ */
+ void StopThread();
+
+ /**
+ * @brief Callback called on timeout.
+ * Not thread-safe
+ */
+ void OnTimeout() const;
+
+ const std::string name_;
+ TimerTask* task_;
+
+ mutable sync_primitives::Lock state_lock_;
+
+ mutable std::auto_ptr<TimerDelegate> delegate_;
+ threads::Thread* thread_;
+
+ /**
+ * @brief Single shot flag shows if timer should be fired once
+ */
+ bool single_shot_;
+
+ DISALLOW_COPY_AND_ASSIGN(Timer);
+};
+
+} // namespace timer
+
+#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_H_
diff --git a/src/components/utils/include/utils/timer_task.h b/src/components/utils/include/utils/timer_task.h
new file mode 100644
index 0000000000..199fd804de
--- /dev/null
+++ b/src/components/utils/include/utils/timer_task.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_TASK_H_
+#define SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_TASK_H_
+
+namespace timer {
+
+/**
+ * @brief The TimerTask interface
+ */
+class TimerTask {
+ public:
+ /**
+ * @brief this method calls callback from callee
+ */
+ virtual void run() const = 0;
+
+ virtual ~TimerTask() {}
+};
+
+} // namespace timer
+
+#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_TASK_H_
diff --git a/src/components/utils/include/utils/timer_task_impl.h b/src/components/utils/include/utils/timer_task_impl.h
new file mode 100644
index 0000000000..28618551ec
--- /dev/null
+++ b/src/components/utils/include/utils/timer_task_impl.h
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_TASK_IMPL_H_
+#define SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_TASK_IMPL_H_
+
+#include "utils/timer_task.h"
+#include "utils/macro.h"
+
+namespace timer {
+
+/**
+ * @brief The TaskImpl is proxy-template class for calling callback from Timer
+ */
+template <typename Trackable>
+class TimerTaskImpl : public TimerTask {
+ public:
+ typedef void (Trackable::*CallbackFunction)();
+
+ TimerTaskImpl(Trackable* trackable, CallbackFunction callback);
+ ~TimerTaskImpl();
+ /**
+ * @brief run method which call callback function from callee
+ */
+ void run() const OVERRIDE;
+
+ private:
+ Trackable* callee_;
+ CallbackFunction callback_;
+};
+
+// Implementation
+template <typename Trackable>
+TimerTaskImpl<Trackable>::TimerTaskImpl(Trackable* trackable,
+ CallbackFunction callback)
+ : callee_(trackable), callback_(callback) {}
+
+template <typename Trackable>
+TimerTaskImpl<Trackable>::~TimerTaskImpl() {
+ callee_ = NULL;
+}
+
+template <typename Trackable>
+void TimerTaskImpl<Trackable>::run() const {
+ DCHECK_OR_RETURN_VOID(callee_ && callback_)
+ (callee_->*callback_)();
+}
+} // namespace timer
+
+#endif // SRC_COMPONENTS_UTILS_INCLUDE_UTILS_TIMER_TASK_IMPL_H_
diff --git a/src/components/utils/src/auto_trace.cc b/src/components/utils/src/auto_trace.cc
index 5104851a51..0379630319 100644
--- a/src/components/utils/src/auto_trace.cc
+++ b/src/components/utils/src/auto_trace.cc
@@ -38,30 +38,28 @@
namespace logger {
-AutoTrace::AutoTrace(
- log4cxx::LoggerPtr logger,
- const log4cxx::spi::LocationInfo& location) :
- logger_(logger), location_(location) {
- if (logger_->isTraceEnabled()) {
+AutoTrace::AutoTrace(log4cxx::LoggerPtr logger,
+ const log4cxx::spi::LocationInfo& location)
+ : logger_(logger), location_(location) {
+ if (logger::logs_enabled() && logger_->isTraceEnabled()) {
push_log(logger_,
::log4cxx::Level::getTrace(),
"Enter",
apr_time_now(),
location_,
- ::log4cxx::spi::LoggingEvent::getCurrentThreadName()
- );
+ ::log4cxx::spi::LoggingEvent::getCurrentThreadName());
}
}
AutoTrace::~AutoTrace() {
- if (logger_->isTraceEnabled()) {
+ if (logger::logs_enabled() && logger_->isTraceEnabled()) {
push_log(logger_,
::log4cxx::Level::getTrace(),
"Exit",
apr_time_now(),
- location_, // the location corresponds rather to creation of autotrace object than to deletion
- ::log4cxx::spi::LoggingEvent::getCurrentThreadName()
- );
+ location_, // the location corresponds rather to creation of
+ // autotrace object than to deletion
+ ::log4cxx::spi::LoggingEvent::getCurrentThreadName());
}
}
diff --git a/src/components/utils/src/back_trace.cc b/src/components/utils/src/back_trace.cc
index f49c60b467..c587643cc6 100644
--- a/src/components/utils/src/back_trace.cc
+++ b/src/components/utils/src/back_trace.cc
@@ -67,16 +67,16 @@ string demangle(const char* symbol) {
Backtrace::Backtrace(int32_t count, int32_t skip_top)
: thread_id_(threads::Thread::CurrentId()) {
- int32_t skip = skip_top + 1; // Skip this constructor
- vector<void*> full_trace (count + skip);
+ int32_t skip = skip_top + 1; // Skip this constructor
+ vector<void*> full_trace(count + skip);
int32_t captured = backtrace(&full_trace.front(), count + skip);
int32_t first_call = std::min(captured, skip);
int32_t last_call = std::min(first_call + count, captured);
- backtrace_.assign(full_trace.begin() + first_call, full_trace.begin() + last_call);
+ backtrace_.assign(full_trace.begin() + first_call,
+ full_trace.begin() + last_call);
}
-Backtrace::~Backtrace() {
-}
+Backtrace::~Backtrace() {}
vector<string> Backtrace::CallStack() const {
vector<string> callstack;
@@ -93,15 +93,16 @@ threads::PlatformThreadHandle Backtrace::ThreadId() const {
return thread_id_;
}
-ostream& operator<< (ostream& os, const Backtrace& bt) {
+ostream& operator<<(ostream& os, const Backtrace& bt) {
const vector<string> symbols = bt.CallStack();
- os<<"Stack trace ("<<bt.ThreadId()<<")\n";
+ os << "Stack trace (" << bt.ThreadId() << ")\n";
if (symbols.empty()) {
- os<<"Not available"<<std::endl;
- } else for (size_t i = 0; i < symbols.size(); ++i) {
- os<<symbols[i]<<std::endl;
- }
+ os << "Not available" << std::endl;
+ } else
+ for (size_t i = 0; i < symbols.size(); ++i) {
+ os << symbols[i] << std::endl;
+ }
return os;
}
-} // namespace utils
+} // namespace utils
diff --git a/src/components/utils/src/bitstream.cc b/src/components/utils/src/bitstream.cc
index ae353b44c6..e0cc502d54 100644
--- a/src/components/utils/src/bitstream.cc
+++ b/src/components/utils/src/bitstream.cc
@@ -34,15 +34,13 @@
namespace utils {
BitStream::BitStream(uint8_t* bytes, size_t bytes_count)
- : bytes_(bytes),
- bytes_count_(bytes_count),
- byte_offset_(0),
- bit_offset_(0),
- bad_(false) {
-}
+ : bytes_(bytes)
+ , bytes_count_(bytes_count)
+ , byte_offset_(0)
+ , bit_offset_(0)
+ , bad_(false) {}
-BitStream::~BitStream() {
-}
+BitStream::~BitStream() {}
size_t BitStream::FullBytesLeft() {
size_t left = bytes_count_ - byte_offset_;
@@ -104,7 +102,7 @@ void Extract(BitStream* bs, std::string* str, size_t length) {
bs->MarkBad();
return;
}
- str->resize(length+1);
+ str->resize(length + 1);
void* stringdata = &(*str)[0];
bs->ExtractBytes(stringdata, length);
str->resize(length);
@@ -129,4 +127,3 @@ void Extract(BitStream* bs, std::vector<uint8_t>* data, size_t length) {
}
} // namespace utils
-
diff --git a/src/components/utils/src/conditional_variable_posix.cc b/src/components/utils/src/conditional_variable_posix.cc
index 2928cac9db..50ebc74556 100644
--- a/src/components/utils/src/conditional_variable_posix.cc
+++ b/src/components/utils/src/conditional_variable_posix.cc
@@ -49,44 +49,43 @@ CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")
ConditionalVariable::ConditionalVariable() {
pthread_condattr_t attrs;
- int32_t initialized = pthread_condattr_init(&attrs);
+ int initialized = pthread_condattr_init(&attrs);
if (initialized != 0)
- LOG4CXX_ERROR(logger_, "Failed to initialize "
- "conditional variable attributes");
+ LOG4CXX_ERROR(logger_,
+ "Failed to initialize "
+ "conditional variable attributes");
pthread_condattr_setclock(&attrs, CLOCK_MONOTONIC);
initialized = pthread_cond_init(&cond_var_, &attrs);
if (initialized != 0)
- LOG4CXX_ERROR(logger_, "Failed to initialize "
- "conditional variable");
- int32_t rv = pthread_condattr_destroy(&attrs);
+ LOG4CXX_ERROR(logger_,
+ "Failed to initialize "
+ "conditional variable");
+ int rv = pthread_condattr_destroy(&attrs);
if (rv != 0)
- LOG4CXX_ERROR(logger_, "Failed to destroy "
- "conditional variable attributes");
+ LOG4CXX_ERROR(logger_,
+ "Failed to destroy "
+ "conditional variable attributes");
}
ConditionalVariable::~ConditionalVariable() {
pthread_cond_destroy(&cond_var_);
-
}
void ConditionalVariable::NotifyOne() {
- int32_t signaled = pthread_cond_signal(&cond_var_);
+ int signaled = pthread_cond_signal(&cond_var_);
if (signaled != 0)
LOG4CXX_ERROR(logger_, "Failed to signal conditional variable");
-
}
void ConditionalVariable::Broadcast() {
- int32_t signaled = pthread_cond_broadcast(&cond_var_);
+ int signaled = pthread_cond_broadcast(&cond_var_);
if (signaled != 0)
LOG4CXX_ERROR(logger_, "Failed to broadcast conditional variable");
-
}
bool ConditionalVariable::Wait(Lock& lock) {
lock.AssertTakenAndMarkFree();
- int32_t wait_status = pthread_cond_wait(&cond_var_,
- &lock.mutex_);
+ int wait_status = pthread_cond_wait(&cond_var_, &lock.mutex_);
lock.AssertFreeAndMarkTaken();
if (wait_status != 0) {
LOG4CXX_ERROR(logger_, "Failed to wait for conditional variable");
@@ -98,8 +97,7 @@ bool ConditionalVariable::Wait(Lock& lock) {
bool ConditionalVariable::Wait(AutoLock& auto_lock) {
Lock& lock = auto_lock.GetLock();
lock.AssertTakenAndMarkFree();
- int32_t wait_status = pthread_cond_wait(&cond_var_,
- &lock.mutex_);
+ int wait_status = pthread_cond_wait(&cond_var_, &lock.mutex_);
lock.AssertFreeAndMarkTaken();
if (wait_status != 0) {
LOG4CXX_ERROR(logger_, "Failed to wait for conditional variable");
@@ -109,24 +107,23 @@ bool ConditionalVariable::Wait(AutoLock& auto_lock) {
}
ConditionalVariable::WaitStatus ConditionalVariable::WaitFor(
- AutoLock& auto_lock, int32_t milliseconds){
+ AutoLock& auto_lock, uint32_t milliseconds) {
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
timespec wait_interval;
- wait_interval.tv_sec = now.tv_sec +
- (milliseconds / kMillisecondsPerSecond);
- wait_interval.tv_nsec = now.tv_nsec +
+ wait_interval.tv_sec = now.tv_sec + (milliseconds / kMillisecondsPerSecond);
+ wait_interval.tv_nsec =
+ now.tv_nsec +
(milliseconds % kMillisecondsPerSecond) * kNanosecondsPerMillisecond;
wait_interval.tv_sec += wait_interval.tv_nsec / kNanosecondsPerSecond;
wait_interval.tv_nsec %= kNanosecondsPerSecond;
Lock& lock = auto_lock.GetLock();
lock.AssertTakenAndMarkFree();
- int32_t timedwait_status = pthread_cond_timedwait(&cond_var_,
- &lock.mutex_,
- &wait_interval);
+ int timedwait_status =
+ pthread_cond_timedwait(&cond_var_, &lock.mutex_, &wait_interval);
lock.AssertFreeAndMarkTaken();
WaitStatus wait_status = kNoTimeout;
- switch(timedwait_status) {
+ switch (timedwait_status) {
case 0: {
wait_status = kNoTimeout;
break;
@@ -140,10 +137,13 @@ ConditionalVariable::WaitStatus ConditionalVariable::WaitFor(
break;
}
default: {
- LOG4CXX_ERROR(logger_, "Failed to timewait for conditional variable timedwait_status: " << timedwait_status);
+ LOG4CXX_ERROR(
+ logger_,
+ "Failed to timewait for conditional variable timedwait_status: "
+ << timedwait_status);
}
}
return wait_status;
}
-} // namespace sync_primitives
+} // namespace sync_primitives
diff --git a/src/components/utils/src/convert_utils.cc b/src/components/utils/src/convert_utils.cc
new file mode 100644
index 0000000000..319b231a96
--- /dev/null
+++ b/src/components/utils/src/convert_utils.cc
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "utils/convert_utils.h"
+#include <stdint.h>
+#include <limits>
+#include <algorithm>
+#include "utils/macro.h"
+
+long long int utils::ConvertInt64ToLongLongInt(const int64_t value) {
+ DCHECK(value >= std::numeric_limits<long long int>::min());
+ DCHECK(value <= std::numeric_limits<long long int>::max());
+ return static_cast<long long int>(value);
+}
+
+int64_t utils::ConvertLongLongIntToInt64(const long long int value) {
+ DCHECK_OR_RETURN(
+ value >= std::numeric_limits<int64_t>::min(),
+ std::min<int64_t>(value, std::numeric_limits<int64_t>::min()));
+ DCHECK_OR_RETURN(
+ value <= std::numeric_limits<int64_t>::max(),
+ std::max<int64_t>(value, std::numeric_limits<int64_t>::max()));
+ return static_cast<int64_t>(value);
+}
+
+unsigned long long int utils::ConvertUInt64ToLongLongUInt(
+ const uint64_t value) {
+ DCHECK(value >= std::numeric_limits<unsigned long long int>::min());
+ DCHECK(value <= std::numeric_limits<unsigned long long int>::max());
+ return static_cast<unsigned long long int>(value);
+}
+
+uint64_t utils::ConvertLongLongUIntToUInt64(
+ const unsigned long long int value) {
+ DCHECK_OR_RETURN(
+ value >= std::numeric_limits<uint64_t>::min(),
+ std::min<uint64_t>(value, std::numeric_limits<uint64_t>::min()));
+ DCHECK_OR_RETURN(
+ value <= std::numeric_limits<uint64_t>::max(),
+ std::max<uint64_t>(value, std::numeric_limits<uint64_t>::max()));
+
+ return static_cast<uint64_t>(value);
+}
diff --git a/src/components/utils/src/custom_string.cc b/src/components/utils/src/custom_string.cc
new file mode 100644
index 0000000000..e7fc4cfd6a
--- /dev/null
+++ b/src/components/utils/src/custom_string.cc
@@ -0,0 +1,201 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "utils/custom_string.h"
+#include <cwchar>
+#include <cstdlib>
+#include <clocale>
+#include <cwctype>
+#include <new>
+#include <algorithm>
+#include <string.h>
+#include "utils/logger.h"
+#include "utils/macro.h"
+
+namespace {
+namespace custom_str = utils::custom_string;
+
+// Calculates amount of characters in UTF string
+size_t CalculateLengthOfString(const char* str) {
+ size_t length_of_string = 0;
+ for (size_t i = 0; str[i] != '\0'; ++i) {
+ if ((str[i] & custom_str::kHigestByteOfUTF8Byte2) !=
+ custom_str::kByteOfUTF8) {
+ ++length_of_string;
+ }
+ }
+ return length_of_string;
+}
+
+// Converts string to unicode string.
+std::wstring ConvertUTFToWString(const char* str) {
+ size_t size = CalculateLengthOfString(str);
+ std::vector<wchar_t> wchar_array(size + 1, L'\0');
+
+ std::string current_locale = setlocale(LC_ALL, NULL);
+ setlocale(LC_ALL, ""); // system locale
+ mbstowcs(&(wchar_array.front()), str, size);
+ setlocale(LC_ALL, current_locale.c_str());
+ return std::wstring(&(wchar_array.front()));
+}
+
+// Converts string to lower case unicode string.
+void ConvertWStringToLowerCase(std::wstring& str) {
+ const std::string current_locale = setlocale(LC_ALL, NULL);
+ setlocale(LC_ALL, "");
+ std::transform(str.begin(), str.end(), str.begin(), towlower);
+ setlocale(LC_ALL, current_locale.c_str());
+}
+}
+
+namespace utils {
+namespace custom_string {
+
+CustomString::CustomString() : amount_characters_(0), is_ascii_string_(true) {}
+
+CustomString::CustomString(const std::string& str)
+ : mb_string_(str), amount_characters_(0), is_ascii_string_(true) {
+ InitData();
+}
+
+CustomString::CustomString(const char* str)
+ : mb_string_(str), amount_characters_(0), is_ascii_string_(true) {
+ InitData();
+}
+
+CustomString::CustomString(size_t n, char c)
+ : mb_string_(n, c), amount_characters_(0), is_ascii_string_(true) {
+ InitData();
+}
+
+size_t CustomString::size() const {
+ return amount_characters_;
+}
+
+size_t CustomString::length() const {
+ return amount_characters_;
+}
+
+size_t CustomString::length_bytes() const {
+ return mb_string_.size();
+}
+
+bool CustomString::is_ascii_string() const {
+ return is_ascii_string_;
+}
+
+bool CustomString::empty() const {
+ return 0 == amount_characters_;
+}
+
+bool CustomString::operator==(const CustomString& str) const {
+ return mb_string_ == str.mb_string_;
+}
+
+bool CustomString::operator==(const std::string& str) const {
+ return mb_string_ == str;
+}
+
+CustomString& CustomString::operator=(const char* str) {
+ mb_string_ = str;
+ InitData();
+ return *this;
+}
+
+CustomString CustomString::operator+(const CustomString& str) const {
+ return *this + str.AsMBString();
+}
+
+CustomString CustomString::operator+(const std::string& str) const {
+ if (!str.empty()) {
+ CustomString result_str(mb_string_ + str);
+ return result_str;
+ }
+ return *this;
+}
+
+char CustomString::at(size_t pos) const {
+ DCHECK_OR_RETURN((is_ascii_string_ && pos < amount_characters_), '\0');
+ return mb_string_.at(pos);
+}
+
+int CustomString::compare(const char* str) const {
+ return mb_string_.compare(str);
+}
+
+int CustomString::compare(const std::string& str) const {
+ return mb_string_.compare(str);
+}
+
+bool CustomString::CompareIgnoreCase(const CustomString& str) const {
+ if (is_ascii_string() && str.is_ascii_string()) {
+ return !strcasecmp(c_str(), str.c_str());
+ }
+ std::wstring wstr_first(ConvertUTFToWString(mb_string_.c_str()));
+ std::wstring wstr_second(ConvertUTFToWString(str.c_str()));
+ ConvertWStringToLowerCase(wstr_first);
+ ConvertWStringToLowerCase(wstr_second);
+ return wstr_first == wstr_second;
+}
+
+bool CustomString::CompareIgnoreCase(const char* str) const {
+ return CompareIgnoreCase(CustomString(str));
+}
+
+const char* CustomString::c_str() const {
+ return mb_string_.c_str();
+}
+
+std::wstring CustomString::ToWString() const {
+ return ConvertUTFToWString(mb_string_.c_str());
+}
+
+std::string CustomString::AsMBString() const {
+ return mb_string_;
+}
+
+std::wstring CustomString::ToWStringLowerCase() const {
+ std::wstring wstr(ConvertUTFToWString(mb_string_.c_str()));
+ ConvertWStringToLowerCase(wstr);
+ return wstr;
+}
+
+void CustomString::InitData() {
+ if (mb_string_.empty()) {
+ return;
+ }
+ amount_characters_ = CalculateLengthOfString(mb_string_.c_str());
+ is_ascii_string_ = amount_characters_ == mb_string_.size();
+}
+
+} // namespace custom_string
+} // namespace utils
diff --git a/src/components/utils/src/date_time.cc b/src/components/utils/src/date_time.cc
index 42a199e0fb..fdf0926eb2 100644
--- a/src/components/utils/src/date_time.cc
+++ b/src/components/utils/src/date_time.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -34,72 +34,108 @@
#include <stdint.h>
#include "utils/date_time.h"
-
namespace date_time {
- TimevalStruct DateTime::getCurrentTime() {
- TimevalStruct currentTime;
- timezone timeZone;
+TimevalStruct DateTime::getCurrentTime() {
+ TimevalStruct currentTime;
+ timezone timeZone;
- gettimeofday(&currentTime, &timeZone);
+ gettimeofday(&currentTime, &timeZone);
- return currentTime;
- }
+ return currentTime;
+}
-int64_t date_time::DateTime::getSecs(const TimevalStruct &time) {
- return static_cast<int64_t>(time.tv_sec);
+int64_t date_time::DateTime::getSecs(const TimevalStruct& time) {
+ const TimevalStruct times = ConvertionUsecs(time);
+ return static_cast<int64_t>(times.tv_sec);
}
-int64_t DateTime::getmSecs(const TimevalStruct &time) {
- return static_cast<int64_t>(time.tv_sec) * MILLISECONDS_IN_SECOND
- + time.tv_usec / MICROSECONDS_IN_MILLISECONDS;
+int64_t DateTime::getmSecs(const TimevalStruct& time) {
+ const TimevalStruct times = ConvertionUsecs(time);
+ return static_cast<int64_t>(times.tv_sec) * MILLISECONDS_IN_SECOND +
+ times.tv_usec / MICROSECONDS_IN_MILLISECOND;
}
-int64_t DateTime::getuSecs(const TimevalStruct &time) {
- return static_cast<int64_t>(time.tv_sec) * MILLISECONDS_IN_SECOND
- * MICROSECONDS_IN_MILLISECONDS + time.tv_usec;
+int64_t DateTime::getuSecs(const TimevalStruct& time) {
+ const TimevalStruct times = ConvertionUsecs(time);
+ return static_cast<int64_t>(times.tv_sec) * MILLISECONDS_IN_SECOND *
+ MICROSECONDS_IN_MILLISECOND +
+ times.tv_usec;
}
int64_t DateTime::calculateTimeSpan(const TimevalStruct& sinceTime) {
return calculateTimeDiff(getCurrentTime(), sinceTime);
}
-int64_t DateTime::calculateTimeDiff(const TimevalStruct &time1,
- const TimevalStruct &time2){
+int64_t DateTime::calculateTimeDiff(const TimevalStruct& time1,
+ const TimevalStruct& time2) {
+ const TimevalStruct times1 = ConvertionUsecs(time1);
+ const TimevalStruct times2 = ConvertionUsecs(time2);
TimevalStruct ret;
- if (Greater(time1, time2)) {
- ret = Sub(time1, time2);
+ if (Greater(times1, times2)) {
+ ret = Sub(times1, times2);
} else {
- ret = Sub(time2, time1);
+ ret = Sub(times2, times1);
}
return getmSecs(ret);
}
+void DateTime::AddMilliseconds(TimevalStruct& time, uint32_t milliseconds) {
+ const uint32_t sec = milliseconds / MILLISECONDS_IN_SECOND;
+ const uint32_t usec =
+ (milliseconds % MILLISECONDS_IN_SECOND) * MICROSECONDS_IN_MILLISECOND;
+ time.tv_sec += sec;
+ time.tv_usec += usec;
+ time = ConvertionUsecs(time);
+}
+
TimevalStruct DateTime::Sub(const TimevalStruct& time1,
const TimevalStruct& time2) {
+ const TimevalStruct times1 = ConvertionUsecs(time1);
+ const TimevalStruct times2 = ConvertionUsecs(time2);
TimevalStruct ret;
- timersub(&time1, &time2, &ret);
+ timersub(&times1, &times2, &ret);
return ret;
}
bool DateTime::Greater(const TimevalStruct& time1, const TimevalStruct& time2) {
- return timercmp(&time1, &time2, >);
+ const TimevalStruct times1 = ConvertionUsecs(time1);
+ const TimevalStruct times2 = ConvertionUsecs(time2);
+ return timercmp(&times1, &times2, > );
}
bool DateTime::Less(const TimevalStruct& time1, const TimevalStruct& time2) {
- return timercmp(&time1, &time2, <);
+ const TimevalStruct times1 = ConvertionUsecs(time1);
+ const TimevalStruct times2 = ConvertionUsecs(time2);
+ return timercmp(&times1, &times2, < );
}
bool DateTime::Equal(const TimevalStruct& time1, const TimevalStruct& time2) {
- return !timercmp(&time1, &time2, !=);
+ const TimevalStruct times1 = ConvertionUsecs(time1);
+ const TimevalStruct times2 = ConvertionUsecs(time2);
+ return !timercmp(&times1, &times2, != );
}
-TimeCompare date_time::DateTime::compareTime(const TimevalStruct &time1, const TimevalStruct &time2) {
- if (Greater(time1, time2)) return GREATER;
- if (Less(time1, time2)) return LESS;
+TimeCompare date_time::DateTime::compareTime(const TimevalStruct& time1,
+ const TimevalStruct& time2) {
+ if (Greater(time1, time2))
+ return GREATER;
+ if (Less(time1, time2))
+ return LESS;
return EQUAL;
}
+TimevalStruct date_time::DateTime::ConvertionUsecs(const TimevalStruct& time) {
+ if (time.tv_usec >= MICROSECONDS_IN_SECOND) {
+ TimevalStruct time1;
+ time1.tv_sec = static_cast<int64_t>(time.tv_sec) +
+ (time.tv_usec / MICROSECONDS_IN_SECOND);
+ time1.tv_usec = static_cast<int64_t>(time.tv_usec) % MICROSECONDS_IN_SECOND;
+ return time1;
+ }
+ return time;
+}
+
} // namespace date_time
bool operator<(const TimevalStruct& time1, const TimevalStruct& time2) {
@@ -109,3 +145,8 @@ bool operator<(const TimevalStruct& time1, const TimevalStruct& time2) {
bool operator==(const TimevalStruct& time1, const TimevalStruct& time2) {
return date_time::DateTime::Equal(time1, time2);
}
+
+const TimevalStruct operator-(const TimevalStruct& time1,
+ const TimevalStruct& time2) {
+ return date_time::DateTime::Sub(time1, time2);
+}
diff --git a/src/components/utils/src/file_system.cc b/src/components/utils/src/file_system.cc
index f9e3bb2dbc..91ff0c3b07 100644
--- a/src/components/utils/src/file_system.cc
+++ b/src/components/utils/src/file_system.cc
@@ -43,12 +43,13 @@
// TODO(VS): lint error: Streams are highly discouraged.
#include <fstream>
#include <cstddef>
+#include <cstdio>
#include <algorithm>
CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")
uint64_t file_system::GetAvailableDiskSpace(const std::string& path) {
- struct statvfs fsInfo = { 0 };
+ struct statvfs fsInfo = {0};
if (statvfs(path.c_str(), &fsInfo) == 0) {
return fsInfo.f_bsize * fsInfo.f_bfree;
} else {
@@ -56,9 +57,9 @@ uint64_t file_system::GetAvailableDiskSpace(const std::string& path) {
}
}
-int64_t file_system::FileSize(const std::string &path) {
+int64_t file_system::FileSize(const std::string& path) {
if (file_system::FileExists(path)) {
- struct stat file_info = { 0 };
+ struct stat file_info = {0};
stat(path.c_str(), &file_info);
return file_info.st_size;
}
@@ -74,20 +75,19 @@ size_t file_system::DirectorySize(const std::string& path) {
struct dirent dir_element_;
struct dirent* dir_element = &dir_element_;
#else
- char* direntbuffer =
- new char[offsetof(struct dirent, d_name) +
- pathconf(path.c_str(), _PC_NAME_MAX) + 1];
- struct dirent* dir_element = new(direntbuffer) dirent;
+ char* direntbuffer = new char[offsetof(struct dirent, d_name) +
+ pathconf(path.c_str(), _PC_NAME_MAX) + 1];
+ struct dirent* dir_element = new (direntbuffer) dirent;
#endif
struct dirent* result = NULL;
- struct stat file_info = { 0 };
+ struct stat file_info = {0};
directory = opendir(path.c_str());
if (NULL != directory) {
return_code = readdir_r(directory, dir_element, &result);
for (; NULL != result && 0 == return_code;
return_code = readdir_r(directory, dir_element, &result)) {
- if (0 == strcmp(result->d_name, "..")
- || 0 == strcmp(result->d_name, ".")) {
+ if (0 == strcmp(result->d_name, "..") ||
+ 0 == strcmp(result->d_name, ".")) {
continue;
}
std::string full_element_path = path + "/" + result->d_name;
@@ -131,7 +131,7 @@ bool file_system::CreateDirectoryRecursively(const std::string& path) {
}
bool file_system::IsDirectory(const std::string& name) {
- struct stat status = { 0 };
+ struct stat status = {0};
if (-1 == stat(name.c_str(), &status)) {
return false;
@@ -141,7 +141,7 @@ bool file_system::IsDirectory(const std::string& name) {
}
bool file_system::DirectoryExists(const std::string& name) {
- struct stat status = { 0 };
+ struct stat status = {0};
if (-1 == stat(name.c_str(), &status) || !S_ISDIR(status.st_mode)) {
return false;
@@ -151,7 +151,7 @@ bool file_system::DirectoryExists(const std::string& name) {
}
bool file_system::FileExists(const std::string& name) {
- struct stat status = { 0 };
+ struct stat status = {0};
if (-1 == stat(name.c_str(), &status)) {
return false;
@@ -159,9 +159,9 @@ bool file_system::FileExists(const std::string& name) {
return true;
}
-bool file_system::Write(
- const std::string& file_name, const std::vector<uint8_t>& data,
- std::ios_base::openmode mode) {
+bool file_system::Write(const std::string& file_name,
+ const std::vector<uint8_t>& data,
+ std::ios_base::openmode mode) {
std::ofstream file(file_name.c_str(), std::ios_base::binary | mode);
if (file.is_open()) {
for (uint32_t i = 0; i < data.size(); ++i) {
@@ -175,15 +175,13 @@ bool file_system::Write(
std::ofstream* file_system::Open(const std::string& file_name,
std::ios_base::openmode mode) {
-
-
std::ofstream* file = new std::ofstream();
- file->open( file_name.c_str(),std::ios_base::binary | mode);
+ file->open(file_name.c_str(), std::ios_base::binary | mode);
if (file->is_open()) {
-
return file;
}
+ delete file;
return NULL;
}
@@ -215,6 +213,15 @@ std::string file_system::CurrentWorkingDirectory() {
return std::string(path);
}
+std::string file_system::GetAbsolutePath(const std::string& path) {
+ char abs_path[PATH_MAX];
+ if (NULL == realpath(path.c_str(), abs_path)) {
+ return std::string();
+ }
+
+ return std::string(abs_path);
+}
+
bool file_system::DeleteFile(const std::string& name) {
if (FileExists(name) && IsAccessible(name, W_OK)) {
return !remove(name.c_str());
@@ -232,7 +239,7 @@ void file_system::remove_directory_content(const std::string& directory_name) {
char* direntbuffer =
new char[offsetof(struct dirent, d_name) +
pathconf(directory_name.c_str(), _PC_NAME_MAX) + 1];
- struct dirent* dir_element = new(direntbuffer) dirent;
+ struct dirent* dir_element = new (direntbuffer) dirent;
#endif
struct dirent* result = NULL;
@@ -243,8 +250,8 @@ void file_system::remove_directory_content(const std::string& directory_name) {
for (; NULL != result && 0 == return_code;
return_code = readdir_r(directory, dir_element, &result)) {
- if (0 == strcmp(result->d_name, "..")
- || 0 == strcmp(result->d_name, ".")) {
+ if (0 == strcmp(result->d_name, "..") ||
+ 0 == strcmp(result->d_name, ".")) {
continue;
}
@@ -267,8 +274,7 @@ void file_system::remove_directory_content(const std::string& directory_name) {
bool file_system::RemoveDirectory(const std::string& directory_name,
bool is_recursively) {
- if (DirectoryExists(directory_name)
- && IsAccessible(directory_name, W_OK)) {
+ if (DirectoryExists(directory_name) && IsAccessible(directory_name, W_OK)) {
if (is_recursively) {
remove_directory_content(directory_name);
}
@@ -291,7 +297,7 @@ bool file_system::IsReadingAllowed(const std::string& name) {
}
std::vector<std::string> file_system::ListFiles(
- const std::string& directory_name) {
+ const std::string& directory_name) {
std::vector<std::string> listFiles;
if (!DirectoryExists(directory_name)) {
return listFiles;
@@ -306,7 +312,7 @@ std::vector<std::string> file_system::ListFiles(
char* direntbuffer =
new char[offsetof(struct dirent, d_name) +
pathconf(directory_name.c_str(), _PC_NAME_MAX) + 1];
- struct dirent* dir_element = new(direntbuffer) dirent;
+ struct dirent* dir_element = new (direntbuffer) dirent;
#endif
struct dirent* result = NULL;
@@ -316,8 +322,8 @@ std::vector<std::string> file_system::ListFiles(
for (; NULL != result && 0 == return_code;
return_code = readdir_r(directory, dir_element, &result)) {
- if (0 == strcmp(result->d_name, "..")
- || 0 == strcmp(result->d_name, ".")) {
+ if (0 == strcmp(result->d_name, "..") ||
+ 0 == strcmp(result->d_name, ".")) {
continue;
}
@@ -325,7 +331,6 @@ std::vector<std::string> file_system::ListFiles(
}
closedir(directory);
-
}
#ifdef __QNXNTO__
@@ -338,7 +343,7 @@ std::vector<std::string> file_system::ListFiles(
bool file_system::WriteBinaryFile(const std::string& name,
const std::vector<uint8_t>& contents) {
using namespace std;
- ofstream output(name.c_str(), ios_base::binary|ios_base::trunc);
+ ofstream output(name.c_str(), ios_base::binary | ios_base::trunc);
output.write(reinterpret_cast<const char*>(&contents.front()),
contents.size());
return output.good();
@@ -353,7 +358,7 @@ bool file_system::ReadBinaryFile(const std::string& name,
std::ifstream file(name.c_str(), std::ios_base::binary);
std::ostringstream ss;
ss << file.rdbuf();
- const std::string& s = ss.str();
+ const std::string s = ss.str();
result.resize(s.length());
std::copy(s.begin(), s.end(), result.begin());
@@ -377,29 +382,20 @@ const std::string file_system::ConvertPathForURL(const std::string& path) {
std::string::const_iterator it_path_end = path.end();
const std::string reserved_symbols = "!#$&'()*+,:;=?@[] ";
- std::string::const_iterator it_sym = reserved_symbols.begin();
- std::string::const_iterator it_sym_end = reserved_symbols.end();
-
+ size_t pos = std::string::npos;
std::string converted_path;
- while (it_path != it_path_end) {
- it_sym = reserved_symbols.begin();
- for (; it_sym != it_sym_end; ++it_sym) {
-
- if (*it_path == *it_sym) {
- const size_t size = 100;
- char percent_value[size];
- snprintf(percent_value, size, "%%%x", *it_path);
- converted_path += percent_value;
- ++it_path;
- continue;
- }
+ for (; it_path != it_path_end; ++it_path) {
+ pos = reserved_symbols.find_first_of(*it_path);
+ if (pos != std::string::npos) {
+ const size_t size = 100;
+ char percent_value[size];
+ snprintf(percent_value, size, "%%%x", *it_path);
+ converted_path += percent_value;
+ } else {
+ converted_path += *it_path;
}
-
- converted_path += *it_path;
- ++it_path;
}
-
return converted_path;
}
@@ -413,7 +409,6 @@ bool file_system::CreateFile(const std::string& path) {
}
}
-
uint64_t file_system::GetFileModificationTime(const std::string& path) {
struct stat info;
stat(path.c_str(), &info);
@@ -424,8 +419,7 @@ uint64_t file_system::GetFileModificationTime(const std::string& path) {
#endif
}
-bool file_system::CopyFile(const std::string& src,
- const std::string& dst) {
+bool file_system::CopyFile(const std::string& src, const std::string& dst) {
if (!FileExists(src) || FileExists(dst) || !CreateFile(dst)) {
return false;
}
@@ -437,14 +431,27 @@ bool file_system::CopyFile(const std::string& src,
return true;
}
-bool file_system::MoveFile(const std::string& src,
- const std::string& dst) {
- if (!CopyFile(src, dst)) {
- return false;
- }
- if (!DeleteFile(src)) {
- DeleteFile(dst);
- return false;
+bool file_system::MoveFile(const std::string& src, const std::string& dst) {
+ if (std::rename(src.c_str(), dst.c_str()) == 0) {
+ return true;
+ } else {
+ // In case of src and dst on different file systems std::rename returns
+ // an error (at least on QNX).
+ // Seems, streams are not recommended for use, so have
+ // to find another way to do this.
+ std::ifstream s_src(src, std::ios::binary);
+ if (!s_src.good()) {
+ return false;
+ }
+ std::ofstream s_dst(dst, std::ios::binary);
+ if (!s_dst.good()) {
+ return false;
+ }
+ s_dst << s_src.rdbuf();
+ s_dst.close();
+ s_src.close();
+ DeleteFile(src);
+ return true;
}
- return true;
+ return false;
}
diff --git a/src/components/utils/src/gen_hash.cc b/src/components/utils/src/gen_hash.cc
index 6ac5c217c3..a43b8feb03 100644
--- a/src/components/utils/src/gen_hash.cc
+++ b/src/components/utils/src/gen_hash.cc
@@ -31,15 +31,18 @@
*/
#include "utils/gen_hash.h"
-
#include <cstdlib>
+#include <string>
+#include <locale>
+#include "utils/custom_string.h"
namespace utils {
const std::string gen_hash(size_t size) {
- static const char symbols[] = "0123456789"
- "abcdefghijklmnopqrstuvwxyz"
- "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+ static const char symbols[] =
+ "0123456789"
+ "abcdefghijklmnopqrstuvwxyz"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const size_t capacity = sizeof(symbols) - 1;
std::string hash(size, '\0');
@@ -50,4 +53,55 @@ const std::string gen_hash(size_t size) {
return hash;
}
+int32_t Djb2HashFromString(const std::string& str_to_hash) {
+ uint32_t hash = 5381U;
+ std::string::const_iterator it = str_to_hash.begin();
+ std::string::const_iterator it_end = str_to_hash.end();
+
+ for (; it != it_end; ++it) {
+ hash = ((hash << 5) + hash) + (*it);
+ }
+
+ // Reset sign bit in case it has been set.
+ // This is needed to avoid overflow for signed int.
+ const int32_t result = hash & 0x7FFFFFFF;
+ return result;
+}
+
+uint32_t CaseInsensitiveFaq6HashFromString(const char* cstr) {
+ uint32_t hash = 0;
+ std::locale loc;
+ for (; *cstr; ++cstr) {
+ char lower_char = std::tolower(*cstr, loc);
+ hash += static_cast<uint32_t>(lower_char);
+ hash += (hash << 10);
+ hash ^= (hash >> 6);
+ }
+ hash += (hash << 3);
+ hash ^= (hash >> 11);
+ hash += (hash << 15);
+
+ return hash;
+}
+
+uint32_t CaseInsensitiveFaq6HashFromString(
+ const custom_string::CustomString& str_to_hash) {
+ uint32_t hash = 0;
+ if (str_to_hash.is_ascii_string()) {
+ hash = CaseInsensitiveFaq6HashFromString(str_to_hash.c_str());
+ } else {
+ const std::wstring& wstr = str_to_hash.ToWStringLowerCase();
+ size_t size = wstr.size();
+ for (size_t i = 0; i < size; ++i) {
+ hash += static_cast<uint32_t>(wstr[i]);
+ hash += (hash << 10);
+ hash ^= (hash >> 6);
+ }
+ hash += (hash << 3);
+ hash ^= (hash >> 11);
+ hash += (hash << 15);
+ }
+ return hash;
+}
+
} // namespace utils
diff --git a/src/components/utils/src/lock_posix.cc b/src/components/utils/src/lock_posix.cc
index d2837708fa..0a678123f0 100644
--- a/src/components/utils/src/lock_posix.cc
+++ b/src/components/utils/src/lock_posix.cc
@@ -31,12 +31,11 @@
*/
#include "utils/lock.h"
-
#include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
-
+#include <cstring>
#include "utils/logger.h"
namespace sync_primitives {
@@ -45,38 +44,20 @@ CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")
Lock::Lock()
#ifndef NDEBUG
- : lock_taken_(0),
- is_mutex_recursive_(false)
-#endif // NDEBUG
+ : lock_taken_(0)
+ , is_mutex_recursive_(false)
+#endif // NDEBUG
{
- const int32_t status = pthread_mutex_init(&mutex_, NULL);
- if (status != 0) {
- LOG4CXX_ERROR(logger_, "Failed to initialize mutex");
- }
+ Init(false);
}
-Lock::Lock(bool is_mutex_recursive)
+Lock::Lock(bool is_recursive)
#ifndef NDEBUG
- : lock_taken_(0),
- is_mutex_recursive_(is_mutex_recursive)
-#endif // NDEBUG
+ : lock_taken_(0)
+ , is_mutex_recursive_(is_recursive)
+#endif // NDEBUG
{
- int32_t status;
-
- if (is_mutex_recursive) {
- pthread_mutexattr_t attr;
-
- pthread_mutexattr_init(&attr);
- pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
- status = pthread_mutex_init(&mutex_, &attr);
- pthread_mutexattr_destroy(&attr);
- } else {
- status = pthread_mutex_init(&mutex_, NULL);
- }
-
- if (status != 0) {
- LOG4CXX_ERROR(logger_, "Failed to initialize mutex");
- }
+ Init(is_recursive);
}
Lock::~Lock() {
@@ -87,14 +68,19 @@ Lock::~Lock() {
#endif
int32_t status = pthread_mutex_destroy(&mutex_);
if (status != 0) {
- LOG4CXX_ERROR(logger_, "Failed to destroy mutex " << &mutex_ << ": " << strerror(status));
+ LOG4CXX_ERROR(logger_,
+ "Failed to destroy mutex " << &mutex_ << ": "
+ << strerror(status));
}
}
void Lock::Acquire() {
const int32_t status = pthread_mutex_lock(&mutex_);
if (status != 0) {
- LOG4CXX_ERROR(logger_, "Failed to acquire mutex " << &mutex_ << ": " << strerror(status));
+ LOG4CXX_FATAL(logger_,
+ "Failed to acquire mutex " << &mutex_ << ": "
+ << strerror(status));
+ DCHECK(status != 0);
} else {
AssertFreeAndMarkTaken();
}
@@ -104,7 +90,9 @@ void Lock::Release() {
AssertTakenAndMarkFree();
const int32_t status = pthread_mutex_unlock(&mutex_);
if (status != 0) {
- LOG4CXX_ERROR(logger_, "Failed to unlock mutex" << &mutex_ << ": " << strerror(status));
+ LOG4CXX_ERROR(logger_,
+ "Failed to unlock mutex" << &mutex_ << ": "
+ << strerror(status));
}
}
@@ -136,4 +124,23 @@ void Lock::AssertTakenAndMarkFree() {
}
#endif
+void Lock::Init(bool is_recursive) {
+ pthread_mutexattr_t attr;
+ pthread_mutexattr_init(&attr);
+
+ const int32_t mutex_type =
+ is_recursive ? PTHREAD_MUTEX_RECURSIVE : PTHREAD_MUTEX_ERRORCHECK;
+
+ pthread_mutexattr_settype(&attr, mutex_type);
+ const int32_t status = pthread_mutex_init(&mutex_, &attr);
+
+ pthread_mutexattr_destroy(&attr);
+
+ if (status != 0) {
+ LOG4CXX_FATAL(logger_,
+ "Failed to initialize mutex. " << std::strerror(status));
+ DCHECK(status != 0);
+ }
+}
+
} // namespace sync_primitives
diff --git a/src/components/utils/src/log_message_loop_thread.cc b/src/components/utils/src/log_message_loop_thread.cc
index 1403a5f712..77bc8107eb 100644
--- a/src/components/utils/src/log_message_loop_thread.cc
+++ b/src/components/utils/src/log_message_loop_thread.cc
@@ -43,13 +43,12 @@ void LogMessageHandler::Handle(const LogMessage message) {
message.threadName);
}
-LogMessageLoopThread::LogMessageLoopThread() :
- LogMessageLoopThreadTemplate("Logger", new LogMessageHandler()) {
-}
+LogMessageLoopThread::LogMessageLoopThread()
+ : LogMessageLoopThreadTemplate("Logger", new LogMessageHandler()) {}
LogMessageLoopThread::~LogMessageLoopThread() {
-// we'll have to drop messages
-// while deleting logger thread
+ // we'll have to drop messages
+ // while deleting logger thread
logger_status = DeletingLoggerThread;
}
diff --git a/src/components/utils/src/logger.cc b/src/components/utils/src/logger.cc
index 72c85424d3..4e93ca3d14 100644
--- a/src/components/utils/src/logger.cc
+++ b/src/components/utils/src/logger.cc
@@ -32,20 +32,25 @@
#include "utils/logger.h"
#include "utils/log_message_loop_thread.h"
+#include "utils/logger_status.h"
#include <apr_time.h>
-void deinit_logger () {
- CREATE_LOGGERPTR_LOCAL (logger_, "Logger");
+void deinit_logger() {
+ CREATE_LOGGERPTR_LOCAL(logger_, "Utils")
LOG4CXX_DEBUG(logger_, "Logger deinitialization");
- logger::LogMessageLoopThread::destroy();
+ logger::set_logs_enabled(false);
+ logger::delete_log_message_loop_thread();
log4cxx::LoggerPtr rootLogger = log4cxx::Logger::getRootLogger();
- log4cxx::spi::LoggerRepositoryPtr repository = rootLogger->getLoggerRepository();
+ log4cxx::spi::LoggerRepositoryPtr repository =
+ rootLogger->getLoggerRepository();
log4cxx::LoggerList loggers = repository->getCurrentLoggers();
- for (log4cxx::LoggerList::iterator i = loggers.begin(); i != loggers.end(); ++i) {
+ for (log4cxx::LoggerList::iterator i = loggers.begin(); i != loggers.end();
+ ++i) {
log4cxx::LoggerPtr logger = *i;
logger->removeAllAppenders();
}
rootLogger->removeAllAppenders();
+ logger::logger_status = logger::LoggerThreadNotCreated;
}
log4cxx_time_t time_now() {
diff --git a/src/components/utils/src/push_log.cc b/src/components/utils/src/push_log.cc
index 49525a4f27..6e16c99181 100644
--- a/src/components/utils/src/push_log.cc
+++ b/src/components/utils/src/push_log.cc
@@ -36,33 +36,67 @@
namespace logger {
+static bool logs_enabled_ = false;
+static LogMessageLoopThread* log_message_loop_thread = NULL;
+
bool push_log(log4cxx::LoggerPtr logger,
log4cxx::LevelPtr level,
const std::string& entry,
log4cxx_time_t timeStamp,
const log4cxx::spi::LocationInfo& location,
- const log4cxx::LogString& threadName
- ) {
+ const log4cxx::LogString& threadName) {
if (LoggerThreadCreated == logger_status) {
- LogMessage message = {logger, level, entry, timeStamp, location, threadName};
- LogMessageLoopThread::instance()->PostMessage(message);
- return true;
+ LogMessage message = {
+ logger, level, entry, timeStamp, location, threadName};
+ if (log_message_loop_thread) {
+ log_message_loop_thread->PostMessage(message);
+ return true;
+ }
}
if (LoggerThreadNotCreated == logger_status) {
logger_status = CreatingLoggerThread;
-// we'll have to drop messages
-// while creating logger thread
- LogMessage message = {logger, level, entry, timeStamp, location, threadName};
- LogMessageLoopThread::instance()->PostMessage(message);
+ // we'll have to drop messages
+ // while creating logger thread
+ create_log_message_loop_thread();
+ LogMessage message = {
+ logger, level, entry, timeStamp, location, threadName};
+ log_message_loop_thread->PostMessage(message);
logger_status = LoggerThreadCreated;
return true;
}
-// also we drop messages
-// while deleting logger thread
+ // also we drop messages
+ // while deleting logger thread
return false;
}
+bool logs_enabled() {
+ return logs_enabled_;
+}
+
+void set_logs_enabled(bool state) {
+ logs_enabled_ = state;
+}
+
+void create_log_message_loop_thread() {
+ if (!log_message_loop_thread) {
+ log_message_loop_thread = new LogMessageLoopThread();
+ }
+}
+
+void delete_log_message_loop_thread() {
+ delete log_message_loop_thread;
+ log_message_loop_thread = NULL;
+}
+
+void flush_logger() {
+ logger::LoggerStatus old_status = logger::logger_status;
+ // Stop pushing new messages to the log queue
+ logger::logger_status = logger::DeletingLoggerThread;
+ log_message_loop_thread->WaitDumpQueue();
+ logger::logger_status = old_status;
+}
+
} // namespace logger
diff --git a/src/components/utils/src/qdb_wrapper/CMakeLists.txt b/src/components/utils/src/qdb_wrapper/CMakeLists.txt
new file mode 100644
index 0000000000..c19321568e
--- /dev/null
+++ b/src/components/utils/src/qdb_wrapper/CMakeLists.txt
@@ -0,0 +1,54 @@
+# Copyright (c) 2013, Ford Motor Company
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer.
+#
+# Redistributions in binary form must reproduce the above copyright notice,
+# this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided with the
+# distribution.
+#
+# Neither the name of the Ford Motor Company nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+
+set(target dbms)
+
+include_directories(${COMPONENTS_DIR}/utils/include/utils)
+
+set(SOURCES
+ ./sql_database.cc
+ ./sql_query.cc
+ ./sql_error.cc
+)
+
+add_library(${target} ${SOURCES})
+target_link_libraries(${target} qdb Utils)
+
+if (CMAKE_SYSTEM_NAME STREQUAL "QNX")
+ file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/policy.ini DESTINATION ${CMAKE_BINARY_DIR}/src/appMain)
+ file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/qdbserver.sh DESTINATION ${CMAKE_BINARY_DIR}/src/appMain)
+endif ()
+
+if (CMAKE_SYSTEM_NAME STREQUAL "QNX")
+ install(FILES policy.ini DESTINATION bin)
+ install(FILES qdbserver.sh DESTINATION bin
+ PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ
+ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)
+endif ()
diff --git a/src/components/policy/src/policy/qdb_wrapper/policy.ini b/src/components/utils/src/qdb_wrapper/policy.ini
index e22a07e815..e22a07e815 100644
--- a/src/components/policy/src/policy/qdb_wrapper/policy.ini
+++ b/src/components/utils/src/qdb_wrapper/policy.ini
diff --git a/src/components/policy/src/policy/qdb_wrapper/qdbserver.sh b/src/components/utils/src/qdb_wrapper/qdbserver.sh
index 40ecbea518..40ecbea518 100755
--- a/src/components/policy/src/policy/qdb_wrapper/qdbserver.sh
+++ b/src/components/utils/src/qdb_wrapper/qdbserver.sh
diff --git a/src/components/utils/src/qdb_wrapper/sql_database.cc b/src/components/utils/src/qdb_wrapper/sql_database.cc
new file mode 100644
index 0000000000..b95fe17845
--- /dev/null
+++ b/src/components/utils/src/qdb_wrapper/sql_database.cc
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2013, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <cstring>
+#include "qdb_wrapper/sql_database.h"
+#include "utils/logger.h"
+
+namespace utils {
+namespace dbms {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")
+
+SQLDatabase::SQLDatabase(const std::string& db_name)
+ : conn_(NULL), db_name_(db_name), error_(Error::OK) {}
+
+SQLDatabase::~SQLDatabase() {
+ Close();
+}
+
+bool SQLDatabase::Open() {
+ sync_primitives::AutoLock auto_lock(conn_lock_);
+ if (conn_)
+ return true;
+ conn_ = qdb_connect(db_name_.c_str(), 0);
+ if (conn_ == NULL) {
+ error_ = Error::ERROR;
+ return false;
+ }
+ return true;
+}
+
+void SQLDatabase::Close() {
+ sync_primitives::AutoLock auto_lock(conn_lock_);
+ if (conn_) {
+ if (qdb_disconnect(conn_) != -1) {
+ conn_ = NULL;
+ } else {
+ error_ = Error::ERROR;
+ }
+ }
+}
+
+bool SQLDatabase::BeginTransaction() {
+ return Exec("BEGIN TRANSACTION");
+}
+
+bool SQLDatabase::CommitTransaction() {
+ return Exec("COMMIT TRANSACTION");
+}
+
+bool SQLDatabase::RollbackTransaction() {
+ return Exec("ROLLBACK TRANSACTION");
+}
+
+bool SQLDatabase::Exec(const std::string& query) {
+ sync_primitives::AutoLock auto_lock(conn_lock_);
+ if (qdb_statement(conn_, query.c_str()) == -1) {
+ error_ = Error::ERROR;
+ return false;
+ }
+ return true;
+}
+
+SQLError SQLDatabase::LastError() const {
+ return SQLError(error_, qdb_geterrmsg(conn_));
+}
+
+qdb_hdl_t* SQLDatabase::conn() const {
+ return conn_;
+}
+
+bool SQLDatabase::Backup() {
+ if (qdb_backup(conn_, QDB_ATTACH_DEFAULT) == -1) {
+ error_ = Error::ERROR;
+ LOG4CXX_ERROR(logger_, "Backup returned error: " << std::strerror(errno));
+ return false;
+ }
+ LOG4CXX_INFO(logger_, "Backup was successful.");
+ return true;
+}
+
+} // namespace dbms
+} // namespace utils
diff --git a/src/components/utils/src/qdb_wrapper/sql_error.cc b/src/components/utils/src/qdb_wrapper/sql_error.cc
new file mode 100644
index 0000000000..c99a4d2ae3
--- /dev/null
+++ b/src/components/utils/src/qdb_wrapper/sql_error.cc
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2013, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "qdb_wrapper/sql_error.h"
+
+namespace utils {
+namespace dbms {
+
+SQLError::SQLError(Error number, const std::string& text)
+ : number_(number), text_(text) {}
+
+Error SQLError::number() const {
+ return number_;
+}
+
+std::string SQLError::text() const {
+ if (!text_.empty()) {
+ return text_;
+ }
+ switch (number_) {
+ case OK:
+ text_ = "Successful result";
+ break;
+ case ERROR:
+ text_ = "Error";
+ break;
+ default:
+ text_ = "Unknown error";
+ }
+ return text_;
+}
+
+} // namespace dbms
+} // namespace utils
diff --git a/src/components/utils/src/qdb_wrapper/sql_query.cc b/src/components/utils/src/qdb_wrapper/sql_query.cc
new file mode 100644
index 0000000000..e5facb5853
--- /dev/null
+++ b/src/components/utils/src/qdb_wrapper/sql_query.cc
@@ -0,0 +1,293 @@
+/*
+ * Copyright (c) 2013, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "qdb_wrapper/sql_query.h"
+#include <string.h>
+#include <cassert>
+#include <algorithm>
+#include "qdb_wrapper/sql_database.h"
+#include "utils/logger.h"
+#include <errno.h>
+
+namespace utils {
+namespace dbms {
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")
+
+class SetBindInteger {
+ public:
+ explicit SetBindInteger(qdb_binding_t* array) : array_(array) {}
+ void operator()(const std::pair<int, int64_t>& x) {
+ // In QDB the number of position for binding starts since 1.
+ QDB_SETARRAYBIND_INT(array_, x.first + 1, x.second);
+ }
+
+ private:
+ qdb_binding_t* array_;
+};
+
+class SetBindReal {
+ public:
+ explicit SetBindReal(qdb_binding_t* array) : array_(array) {}
+ void operator()(const std::pair<int, double>& x) {
+ // In QDB the number of position for binding starts since 1.
+ QDB_SETARRAYBIND_REAL(array_, x.first + 1, x.second);
+ }
+
+ private:
+ qdb_binding_t* array_;
+};
+
+class SetBindText {
+ public:
+ explicit SetBindText(qdb_binding_t* array) : array_(array) {}
+ void operator()(const std::pair<int, std::string>& x) {
+ // In QDB the number of position for binding starts since 1.
+ QDB_SETARRAYBIND_TEXT(array_, x.first + 1, x.second.c_str());
+ }
+
+ private:
+ qdb_binding_t* array_;
+};
+
+class SetBindNull {
+ public:
+ explicit SetBindNull(qdb_binding_t* array) : array_(array) {}
+ void operator()(int x) {
+ // In QDB the number of position for binding starts since 1.
+ QDB_SETARRAYBIND_NULL(array_, x + 1);
+ }
+
+ private:
+ qdb_binding_t* array_;
+};
+
+SQLQuery::SQLQuery(SQLDatabase* db)
+ : db_(db)
+ , query_("")
+ , statement_(-1)
+ , bindings_(NULL)
+ , result_(NULL)
+ , current_row_(0)
+ , rows_(0)
+ , error_(Error::OK) {}
+
+SQLQuery::~SQLQuery() {
+ Finalize();
+ db_->Close();
+ delete db_;
+}
+
+bool SQLQuery::Prepare(const std::string& query) {
+ query_ = query;
+ statement_ = qdb_stmt_init(db_->conn(), query.c_str(), query.length() + 1);
+ if (statement_ == -1) {
+ LOG4CXX_DEBUG(logger_, "Prepare error: " << strerror(errno));
+ error_ = Error::ERROR;
+ return false;
+ }
+ return true;
+}
+
+uint8_t SQLQuery::SetBinds() {
+ uint8_t binding_count = int_binds_.size() + double_binds_.size() +
+ string_binds_.size() + null_binds_.size();
+
+ bindings_ = new qdb_binding_t[binding_count];
+
+ std::for_each(
+ int_binds_.begin(), int_binds_.end(), SetBindInteger(bindings_));
+ std::for_each(
+ double_binds_.begin(), double_binds_.end(), SetBindReal(bindings_));
+ std::for_each(
+ string_binds_.begin(), string_binds_.end(), SetBindText(bindings_));
+ std::for_each(null_binds_.begin(), null_binds_.end(), SetBindNull(bindings_));
+
+ return binding_count;
+}
+
+bool SQLQuery::Result() {
+ result_ = qdb_getresult(db_->conn());
+ if (!result_) {
+ error_ = Error::ERROR;
+ return false;
+ }
+ rows_ = qdb_rows(result_);
+ if (rows_ == -1) {
+ rows_ = 0;
+ error_ = Error::ERROR;
+ return false;
+ }
+ return true;
+}
+
+bool SQLQuery::Exec() {
+ sync_primitives::AutoLock auto_lock(bindings_lock_);
+ if (result_)
+ return true;
+
+ current_row_ = 0;
+ uint8_t binding_count = SetBinds();
+ if (qdb_stmt_exec(db_->conn(), statement_, bindings_, binding_count) == -1) {
+ error_ = Error::ERROR;
+ return false;
+ }
+ return Result();
+}
+
+bool SQLQuery::Next() {
+ ++current_row_;
+ return Exec() && current_row_ < rows_;
+}
+
+bool SQLQuery::Reset() {
+ sync_primitives::AutoLock auto_lock(bindings_lock_);
+ int_binds_.clear();
+ double_binds_.clear();
+ string_binds_.clear();
+ null_binds_.clear();
+ delete[] bindings_;
+ bindings_ = NULL;
+ rows_ = 0;
+ current_row_ = 0;
+ if (result_ && qdb_freeresult(result_) == -1) {
+ error_ = Error::ERROR;
+ return false;
+ }
+ result_ = NULL;
+ return true;
+}
+
+void SQLQuery::Finalize() {
+ if (Reset() && qdb_stmt_free(db_->conn(), statement_) != -1) {
+ statement_ = 0;
+ } else {
+ error_ = Error::ERROR;
+ }
+}
+
+bool SQLQuery::Exec(const std::string& query) {
+ query_ = query;
+ if (qdb_statement(db_->conn(), query.c_str()) == -1) {
+ error_ = Error::ERROR;
+ return false;
+ }
+ return true;
+}
+
+void SQLQuery::Bind(int pos, int value) {
+ int_binds_.push_back(std::make_pair(pos, value));
+}
+
+void SQLQuery::Bind(int pos, int64_t value) {
+ int_binds_.push_back(std::make_pair(pos, value));
+}
+
+void SQLQuery::Bind(int pos, double value) {
+ double_binds_.push_back(std::make_pair(pos, value));
+}
+
+void SQLQuery::Bind(int pos, bool value) {
+ Bind(pos, static_cast<int>(value));
+}
+
+void SQLQuery::Bind(int pos, const std::string& value) {
+ string_binds_.push_back(std::make_pair(pos, value));
+}
+
+void SQLQuery::Bind(int pos) {
+ null_binds_.push_back(pos);
+}
+
+bool SQLQuery::GetBoolean(int pos) const {
+ return static_cast<bool>(GetInteger(pos));
+}
+
+int SQLQuery::GetInteger(int pos) const {
+ void* ret = qdb_cell(result_, current_row_, pos);
+ if (rows_ != 0 && ret) {
+ return *static_cast<int*>(ret);
+ }
+ return 0;
+}
+
+uint32_t SQLQuery::GetUInteger(int pos) const {
+ void* ret = qdb_cell(result_, current_row_, pos);
+ if (rows_ != 0 && ret) {
+ return *static_cast<uint32_t*>(ret);
+ }
+ return 0;
+}
+
+int64_t SQLQuery::GetLongInt(int pos) const {
+ void* ret = qdb_cell(result_, current_row_, pos);
+ if (rows_ != 0 && ret) {
+ return *static_cast<int64_t*>(ret);
+ }
+ return 0;
+}
+
+double SQLQuery::GetDouble(int pos) const {
+ void* ret = qdb_cell(result_, current_row_, pos);
+ if (rows_ != 0 && ret) {
+ return *static_cast<double*>(ret);
+ }
+ return 0;
+}
+
+std::string SQLQuery::GetString(int pos) const {
+ void* ret = qdb_cell(result_, current_row_, pos);
+ if (rows_ != 0 && ret) {
+ return static_cast<const char*>(ret);
+ }
+ return "";
+}
+
+bool SQLQuery::IsNull(int pos) const {
+ return rows_ == 0 || qdb_cell_type(result_, current_row_, pos) == QDB_NULL;
+}
+
+const std::string& SQLQuery::query() const {
+ // TODO(KKolodiy): may return string query with value of arguments
+ return query_;
+}
+
+SQLError SQLQuery::LastError() const {
+ return SQLError(error_, qdb_geterrmsg(db_->conn()));
+}
+
+int64_t SQLQuery::LastInsertId() const {
+ return qdb_last_insert_rowid(db_->conn(), result_);
+}
+
+} // namespace dbms
+} // namespace utils
diff --git a/src/components/utils/src/resource_usage.cc b/src/components/utils/src/resource_usage.cc
index 62c8d25b82..385c2bfa2e 100644
--- a/src/components/utils/src/resource_usage.cc
+++ b/src/components/utils/src/resource_usage.cc
@@ -47,7 +47,7 @@ bool Resources::ReadStatFile(std::string& output) {
if (false == file_system::FileExists(filename)) {
return false;
}
- if (false == file_system::ReadFile(filename,output)) {
+ if (false == file_system::ReadFile(filename, output)) {
return false;
}
return true;
@@ -60,61 +60,95 @@ bool Resources::GetProcInfo(Resources::PidStats& output) {
return false;
}
uint32_t num_succes = sscanf(proc_buf.c_str(),
- "%d" //pid
- " %*s"//com
- " %c" //state
- " %d" //ppid
- " %d" //pgrp
- " %d" //session
- " %d" //tty_nr
- " %d" //tpgid
- " %u" //flags
- " %lu" //minflt
- " %lu" //cminflt
- " %lu" //majflt
- " %lu" //cmajflt
- " %lu" //utime
- " %lu" //stime
- " %ld" //cutime
- " %ld" //cstime
- " %ld" //priority
- " %ld" //nice
- " %ld" //num_threads
- " %ld" //itrealvalue
- " %llu" //starttime
- " %lu" //vsize
- " %ld" //rss
- " %lu" //rsslim
- " %lu" //startcode
- " %lu" //endcode
- " %lu" //startstack
- " %lu" //kstkesp
- " %lu" //kstkip
- " %lu" //signal
- " %lu" //blocked
- " %lu" //sigignore
- " %lu" //sigcatch
- " %lu" //wchan
- " %lu" //nswap
- " %lu" //cnswap
- " %d" //exit_signal
- " %d" //processor
- " %u" //rt_priority
- " %u" //policy
- " %llu" //delayacct_blkio_ticks
- " %lu" //guest_time
- " %ld" //cguest_time
- ,&(output.pid), &(output.state), &(output.ppid), &(output.pgrp), &(output.session),
- &(output.tty_nr), &(output.tpgid), &(output.flags), &(output.minflt), &(output.cminflt),
- &(output.majflt), &(output.cmajflt), &(output.utime), &(output.stime), &(output.cutime),
- &(output.cstime), &(output.priority), &( output.nice), &(output.num_threads), &(output.itrealvalue),
- &(output.starttime), &(output.vsize), &(output.rss), &(output.rsslim), &(output.startcode),
- &(output.endcode), &(output.startstack), &(output.kstkesp), &(output.kstkeip), &(output.signal),
- &(output.blocked), &(output.sigignore), &(output.sigcatch), &(output.wchan), &(output.nswap),
- &(output.cnswap), &(output.exit_signal), &(output.processor), &(output.rt_priority), &(output.policy),
- &(output.delayacct_blkio_ticks), &(output.guest_time), &(output.cguest_time)
- );
- if(num_succes != 43) { // 43 is number of iteams in Resources::PidStats
+ "%d" // pid
+ " %*s" // com
+ " %c" // state
+ " %d" // ppid
+ " %d" // pgrp
+ " %d" // session
+ " %d" // tty_nr
+ " %d" // tpgid
+ " %u" // flags
+ " %lu" // minflt
+ " %lu" // cminflt
+ " %lu" // majflt
+ " %lu" // cmajflt
+ " %lu" // utime
+ " %lu" // stime
+ " %ld" // cutime
+ " %ld" // cstime
+ " %ld" // priority
+ " %ld" // nice
+ " %ld" // num_threads
+ " %ld" // itrealvalue
+ " %llu" // starttime
+ " %lu" // vsize
+ " %ld" // rss
+ " %lu" // rsslim
+ " %lu" // startcode
+ " %lu" // endcode
+ " %lu" // startstack
+ " %lu" // kstkesp
+ " %lu" // kstkip
+ " %lu" // signal
+ " %lu" // blocked
+ " %lu" // sigignore
+ " %lu" // sigcatch
+ " %lu" // wchan
+ " %lu" // nswap
+ " %lu" // cnswap
+ " %d" // exit_signal
+ " %d" // processor
+ " %u" // rt_priority
+ " %u" // policy
+ " %llu" // delayacct_blkio_ticks
+ " %lu" // guest_time
+ " %ld" // cguest_time
+ ,
+ &(output.pid),
+ &(output.state),
+ &(output.ppid),
+ &(output.pgrp),
+ &(output.session),
+ &(output.tty_nr),
+ &(output.tpgid),
+ &(output.flags),
+ &(output.minflt),
+ &(output.cminflt),
+ &(output.majflt),
+ &(output.cmajflt),
+ &(output.utime),
+ &(output.stime),
+ &(output.cutime),
+ &(output.cstime),
+ &(output.priority),
+ &(output.nice),
+ &(output.num_threads),
+ &(output.itrealvalue),
+ &(output.starttime),
+ &(output.vsize),
+ &(output.rss),
+ &(output.rsslim),
+ &(output.startcode),
+ &(output.endcode),
+ &(output.startstack),
+ &(output.kstkesp),
+ &(output.kstkeip),
+ &(output.signal),
+ &(output.blocked),
+ &(output.sigignore),
+ &(output.sigcatch),
+ &(output.wchan),
+ &(output.nswap),
+ &(output.cnswap),
+ &(output.exit_signal),
+ &(output.processor),
+ &(output.rt_priority),
+ &(output.policy),
+ &(output.delayacct_blkio_ticks),
+ &(output.guest_time),
+ &(output.cguest_time));
+ if (num_succes != 43) { // 43 is number of iteams in Resources::PidStats
LOG4CXX_ERROR(logger_, "Couldn't parse all iteams in /proc/PID/stat file");
return false;
}
@@ -122,8 +156,9 @@ bool Resources::GetProcInfo(Resources::PidStats& output) {
#elif defined(__QNXNTO__)
int fd = open(GetProcPath().c_str(), O_RDONLY);
if (0 >= fd) {
- LOG4CXX_ERROR(logger_, "Failed open process proc file : " << GetProcPath() <<
- "; error no : " << strerror( errno ) );
+ LOG4CXX_ERROR(logger_,
+ "Failed open process proc file : "
+ << GetProcPath() << "; error no : " << strerror(errno));
close(fd);
return false;
@@ -134,9 +169,9 @@ bool Resources::GetProcInfo(Resources::PidStats& output) {
#endif
}
-bool Resources::GetMemInfo(Resources::MemInfo &output) {
+bool Resources::GetMemInfo(Resources::MemInfo& output) {
bool result = false;
- #if defined(OS_LINUX)
+#if defined(OS_LINUX)
Resources::PidStats pid_stat;
if (false == GetProcInfo(pid_stat)) {
LOG4CXX_ERROR(logger_, "Failed to get proc info");
@@ -154,7 +189,7 @@ bool Resources::GetMemInfo(Resources::MemInfo &output) {
LOG4CXX_ERROR(logger_, "Unable to access to " << proc);
result = false;
return result;
- }
+ }
if (0 == readdir(proc_dir)) {
LOG4CXX_ERROR(logger_, "Unable to read : " << proc_dir);
closedir(proc_dir);
@@ -163,9 +198,9 @@ bool Resources::GetMemInfo(Resources::MemInfo &output) {
}
closedir(proc_dir);
if (-1 == stat(as_path.c_str(), &st) || 0 == st.st_size) {
- LOG4CXX_ERROR(logger_, "Unable to stat : " << as_path.c_str());
- result = false;
- return result;
+ LOG4CXX_ERROR(logger_, "Unable to stat : " << as_path.c_str());
+ result = false;
+ return result;
}
output = st.st_size;
result = true;
@@ -186,9 +221,9 @@ std::string Resources::GetStatPath() {
std::string Resources::GetProcPath() {
char buffer[1024];
pid_t my_pid = getpid();
- snprintf(buffer, sizeof(buffer), "%s%d/", proc , my_pid);
+ snprintf(buffer, sizeof(buffer), "%s%d/", proc, my_pid);
std::string filename(buffer);
return filename;
}
-} // namespace utils
+} // namespace utils
diff --git a/src/components/utils/src/signals_linux.cc b/src/components/utils/src/signals_linux.cc
index 2e598d1b0f..274c254716 100644
--- a/src/components/utils/src/signals_linux.cc
+++ b/src/components/utils/src/signals_linux.cc
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2014, Ford Motor Company
+ * Copyright (c) 2016, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -35,29 +35,49 @@
#include "utils/signals.h"
-namespace utils {
+bool utils::UnsibscribeFromTermination() {
+ // Disable some system signals receiving in thread
+ // by blocking those signals
+ // (system signals processes only in the main thread)
+ // Mustn't block all signals!
+ // See "Advanced Programming in the UNIX Environment, 3rd Edition"
+ // (http://poincare.matf.bg.ac.rs/~ivana//courses/ps/sistemi_knjige/pomocno/apue.pdf,
+ // "12.8. Threads and Signals".
+ sigset_t signal_set;
+ sigemptyset(&signal_set);
+ sigaddset(&signal_set, SIGINT);
+ sigaddset(&signal_set, SIGTERM);
-bool SubscribeToTerminateSignal(sighandler_t func) {
+ return !pthread_sigmask(SIG_BLOCK, &signal_set, NULL);
+}
+
+namespace {
+bool CatchSIGSEGV(sighandler_t handler) {
struct sigaction act;
- act.sa_handler = func;
+
+ act.sa_handler = handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
- bool sigint_subscribed = (sigaction(SIGINT, &act, NULL) == 0);
- bool sigterm_subscribed = (sigaction(SIGTERM, &act, NULL) == 0);
-
- return sigint_subscribed && sigterm_subscribed;
+ return !sigaction(SIGSEGV, &act, NULL);
}
+} // namespace
-bool SubscribeToFaultSignal(sighandler_t func) {
- struct sigaction act;
- act.sa_handler = func;
- sigemptyset(&act.sa_mask);
- act.sa_flags = SA_RESETHAND; // we only want to catch SIGSEGV once to flush logger queue
+bool utils::WaitTerminationSignals(sighandler_t sig_handler) {
+ sigset_t signal_set;
+ int sig = -1;
- bool sigsegv_subscribed = (sigaction(SIGSEGV, &act, NULL) == 0);
+ sigemptyset(&signal_set);
+ sigaddset(&signal_set, SIGINT);
+ sigaddset(&signal_set, SIGTERM);
- return sigsegv_subscribed;
-}
+ if (!CatchSIGSEGV(sig_handler)) {
+ return false;
+ }
-} // namespace utils
+ if (!sigwait(&signal_set, &sig)) {
+ sig_handler(sig);
+ return true;
+ }
+ return false;
+}
diff --git a/src/components/utils/src/sqlite_wrapper/CMakeLists.txt b/src/components/utils/src/sqlite_wrapper/CMakeLists.txt
new file mode 100644
index 0000000000..9a3f3cdd0f
--- /dev/null
+++ b/src/components/utils/src/sqlite_wrapper/CMakeLists.txt
@@ -0,0 +1,44 @@
+# Copyright (c) 2013, Ford Motor Company
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer.
+#
+# Redistributions in binary form must reproduce the above copyright notice,
+# this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided with the
+# distribution.
+#
+# Neither the name of the Ford Motor Company nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+
+set(target dbms)
+
+find_package(Sqlite3 REQUIRED)
+
+include_directories(${COMPONENTS_DIR}/utils/include/utils)
+
+set(SOURCES
+ ./sql_database.cc
+ ./sql_query.cc
+ ./sql_error.cc
+)
+
+add_library(${target} ${SOURCES})
+target_link_libraries(${target} Utils)
diff --git a/src/components/utils/src/sqlite_wrapper/sql_database.cc b/src/components/utils/src/sqlite_wrapper/sql_database.cc
new file mode 100644
index 0000000000..bf19275bac
--- /dev/null
+++ b/src/components/utils/src/sqlite_wrapper/sql_database.cc
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2013, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "sqlite_wrapper/sql_database.h"
+#include <sqlite3.h>
+
+namespace utils {
+namespace dbms {
+
+const std::string SQLDatabase::kInMemory = ":memory:";
+const std::string SQLDatabase::kExtension = ".sqlite";
+
+SQLDatabase::SQLDatabase()
+ : conn_(NULL), databasename_(kInMemory), error_(SQLITE_OK) {}
+
+SQLDatabase::SQLDatabase(const std::string& db_name)
+ : conn_(NULL), databasename_(db_name + kExtension), error_(SQLITE_OK) {}
+
+SQLDatabase::~SQLDatabase() {
+ Close();
+}
+
+bool SQLDatabase::Open() {
+ sync_primitives::AutoLock auto_lock(conn_lock_);
+ if (conn_)
+ return true;
+ error_ = sqlite3_open(databasename_.c_str(), &conn_);
+ return error_ == SQLITE_OK;
+}
+
+bool SQLDatabase::IsReadWrite() {
+ const char* schema = "main";
+ return sqlite3_db_readonly(conn_, schema) == 0;
+}
+
+void SQLDatabase::Close() {
+ if (!conn_) {
+ return;
+ }
+
+ sync_primitives::AutoLock auto_lock(conn_lock_);
+ error_ = sqlite3_close(conn_);
+ if (error_ == SQLITE_OK) {
+ conn_ = NULL;
+ }
+}
+
+bool SQLDatabase::BeginTransaction() {
+ return Exec("BEGIN TRANSACTION");
+}
+
+bool SQLDatabase::CommitTransaction() {
+ return Exec("COMMIT TRANSACTION");
+}
+
+bool SQLDatabase::RollbackTransaction() {
+ return Exec("ROLLBACK TRANSACTION");
+}
+
+bool SQLDatabase::Exec(const std::string& query) {
+ sync_primitives::AutoLock auto_lock(conn_lock_);
+ error_ = sqlite3_exec(conn_, query.c_str(), NULL, NULL, NULL);
+ return error_ == SQLITE_OK;
+}
+
+SQLError SQLDatabase::LastError() const {
+ return SQLError(Error(error_));
+}
+
+sqlite3* SQLDatabase::conn() const {
+ return conn_;
+}
+
+void SQLDatabase::set_path(const std::string& path) {
+ databasename_ = path + databasename_;
+}
+
+std::string SQLDatabase::get_path() const {
+ return databasename_;
+}
+
+bool SQLDatabase::Backup() {
+ return true;
+}
+} // namespace dbms
+} // namespace utils
diff --git a/src/components/utils/src/sqlite_wrapper/sql_error.cc b/src/components/utils/src/sqlite_wrapper/sql_error.cc
new file mode 100644
index 0000000000..9062731a81
--- /dev/null
+++ b/src/components/utils/src/sqlite_wrapper/sql_error.cc
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2013, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "sqlite_wrapper/sql_error.h"
+
+namespace utils {
+namespace dbms {
+
+SQLError::SQLError(Error number, const std::string& text)
+ : number_(number), text_(text) {}
+
+Error SQLError::number() const {
+ return number_;
+}
+
+std::string SQLError::text() const {
+ if (!text_.empty()) {
+ return text_;
+ }
+ switch (number_) {
+ case OK:
+ text_ = "Successful result";
+ break;
+ case ERROR:
+ text_ = "SQL error or missing database";
+ break;
+ case INTERNAL:
+ text_ = "Internal logic error in SQLite";
+ break;
+ case PERM:
+ text_ = "Access permission denied";
+ break;
+ case ABORT:
+ text_ = "Callback routine requested an abort";
+ break;
+ case BUSY:
+ text_ = "The database file is locked";
+ break;
+ case LOCKED:
+ text_ = "A table in the database is locked";
+ break;
+ case NOMEM:
+ text_ = "A malloc() failed";
+ break;
+ case READONLY:
+ text_ = "Attempt to write a readonly database";
+ break;
+ case INTERRUPT:
+ text_ = "Operation terminated by sqlite3_interrupt()";
+ break;
+ case IOERR:
+ text_ = "Some kind of disk I/O error occurred";
+ break;
+ case CORRUPT:
+ text_ = "The database disk image is malformed";
+ break;
+ case NOTFOUND:
+ text_ = "Unknown opcode in sqlite3_file_control()";
+ break;
+ case FULL:
+ text_ = "Insertion failed because database is full";
+ break;
+ case CANTOPEN:
+ text_ = "Unable to open the database file";
+ break;
+ case PROTOCOL:
+ text_ = "Database lock protocol error";
+ break;
+ case EMPTY:
+ text_ = "Database is empty";
+ break;
+ case SCHEMA:
+ text_ = "The database schema changed";
+ break;
+ case TOOBIG:
+ text_ = "String or BLOB exceeds size limit";
+ break;
+ case CONSTRAINT:
+ text_ = "Abort due to constraint violation";
+ break;
+ case MISMATCH:
+ text_ = "Data type mismatch";
+ break;
+ case MISUSE:
+ text_ = "Library used incorrectly";
+ break;
+ case NOLFS:
+ text_ = "Uses OS features not supported on host";
+ break;
+ case AUTH:
+ text_ = "Authorization denied";
+ break;
+ case FORMAT:
+ text_ = "Auxiliary database format error";
+ break;
+ case RANGE:
+ text_ = "2nd parameter to sqlite3_bind out of range";
+ break;
+ case NOTADB:
+ text_ = "File opened that is not a database file";
+ break;
+ case NOTICE:
+ text_ = "Notifications from sqlite3_log()";
+ break;
+ case WARNING:
+ text_ = "Warnings from sqlite3_log()";
+ break;
+ case ROW:
+ text_ = "sqlite3_step() has another row ready";
+ break;
+ case DONE:
+ text_ = "sqlite3_step() has finished executing";
+ break;
+ default:
+ text_ = "Unknown error";
+ }
+ return text_;
+}
+
+} // namespace dbms
+} // namespace utils
diff --git a/src/components/utils/src/sqlite_wrapper/sql_query.cc b/src/components/utils/src/sqlite_wrapper/sql_query.cc
new file mode 100644
index 0000000000..5a62ec360d
--- /dev/null
+++ b/src/components/utils/src/sqlite_wrapper/sql_query.cc
@@ -0,0 +1,161 @@
+/*
+ * Copyright (c) 2013, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "sqlite_wrapper/sql_query.h"
+#include <sqlite3.h>
+#include <cassert>
+#include "sqlite_wrapper/sql_database.h"
+
+namespace utils {
+namespace dbms {
+
+SQLQuery::SQLQuery(SQLDatabase* db)
+ : db_(*db), query_(""), statement_(NULL), error_(SQLITE_OK) {}
+
+SQLQuery::~SQLQuery() {
+ Finalize();
+}
+
+bool SQLQuery::Prepare(const std::string& query) {
+ Finalize();
+ sync_primitives::AutoLock auto_lock(statement_lock_);
+ if (statement_)
+ return false;
+ error_ = sqlite3_prepare(
+ db_.conn(), query.c_str(), query.length(), &statement_, NULL);
+ query_ = query;
+ return error_ == SQLITE_OK;
+}
+
+bool SQLQuery::Exec() {
+ error_ = sqlite3_step(statement_);
+ return error_ == SQLITE_ROW || error_ == SQLITE_DONE;
+}
+
+bool SQLQuery::Next() {
+ error_ = sqlite3_step(statement_);
+ return error_ == SQLITE_ROW;
+}
+
+bool SQLQuery::Reset() {
+ error_ = sqlite3_reset(statement_);
+ return error_ == SQLITE_OK;
+}
+
+void SQLQuery::Finalize() {
+ sync_primitives::AutoLock auto_lock(statement_lock_);
+ error_ = sqlite3_finalize(statement_);
+ if (error_ == SQLITE_OK) {
+ statement_ = NULL;
+ }
+}
+
+bool SQLQuery::Exec(const std::string& query) {
+ query_ = query;
+ error_ = sqlite3_exec(db_.conn(), query.c_str(), NULL, NULL, NULL);
+ return error_ == SQLITE_OK;
+}
+
+void SQLQuery::Bind(int pos, int value) {
+ // In SQLite the number of position for binding starts since 1.
+ error_ = sqlite3_bind_int(statement_, pos + 1, value);
+}
+
+void SQLQuery::Bind(int pos, int64_t value) {
+ // In SQLite the number of position for binding starts since 1.
+ error_ = sqlite3_bind_int64(statement_, pos + 1, value);
+}
+
+void SQLQuery::Bind(int pos, double value) {
+ // In SQLite the number of position for binding starts since 1.
+ error_ = sqlite3_bind_double(statement_, pos + 1, value);
+}
+
+void SQLQuery::Bind(int pos, bool value) {
+ Bind(pos, static_cast<int>(value));
+}
+
+void SQLQuery::Bind(int pos, const std::string& value) {
+ // In SQLite the number of position for binding starts since 1.
+ error_ = sqlite3_bind_text(
+ statement_, pos + 1, value.c_str(), value.length(), SQLITE_TRANSIENT);
+}
+
+bool SQLQuery::GetBoolean(int pos) const {
+ return static_cast<bool>(GetInteger(pos));
+}
+
+int SQLQuery::GetInteger(int pos) const {
+ return sqlite3_column_int(statement_, pos);
+}
+
+uint32_t SQLQuery::GetUInteger(int pos) const {
+ return static_cast<uint32_t>(sqlite3_column_int64(statement_, pos));
+}
+
+int64_t SQLQuery::GetLongInt(int pos) const {
+ return static_cast<int64_t>(sqlite3_column_int64(statement_, pos));
+}
+
+double SQLQuery::GetDouble(int pos) const {
+ return sqlite3_column_double(statement_, pos);
+}
+
+std::string SQLQuery::GetString(int pos) const {
+ const unsigned char* str = sqlite3_column_text(statement_, pos);
+ return str ? reinterpret_cast<const char*>(str) : "";
+}
+
+const std::string& SQLQuery::query() const {
+ // TODO(KKolodiy): may return string query with value of arguments
+ return query_;
+}
+
+bool SQLQuery::IsNull(int pos) const {
+ return sqlite3_column_type(statement_, pos) == SQLITE_NULL;
+}
+
+void SQLQuery::Bind(int pos) {
+ // In SQLite the number of position for binding starts since 1.
+ error_ = sqlite3_bind_null(statement_, pos + 1);
+}
+
+SQLError SQLQuery::LastError() const {
+ return SQLError(Error(error_));
+}
+
+int64_t SQLQuery::LastInsertId() const {
+ return sqlite3_last_insert_rowid(db_.conn());
+}
+
+} // namespace dbms
+} // namespace utils
diff --git a/src/components/utils/src/system.cc b/src/components/utils/src/system.cc
index 70659419a7..6c3cf56133 100644
--- a/src/components/utils/src/system.cc
+++ b/src/components/utils/src/system.cc
@@ -30,13 +30,13 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifdef __QNX__
-# include <process.h>
+#include <process.h>
#else // __QNX__
-# include <sys/types.h>
-# include <sys/wait.h>
-# include <sys/stat.h>
-# include <fcntl.h>
-# include <unistd.h>
+#include <sys/types.h>
+#include <sys/wait.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <unistd.h>
#endif // __QNX__
#include <algorithm>
@@ -52,13 +52,12 @@ namespace utils {
CREATE_LOGGERPTR_LOCAL(logger_, "Utils")
struct GetCString {
- char * operator ()(const std::string& string) {
+ char* operator()(const std::string& string) {
return const_cast<char*>(string.c_str());
}
};
-System::System(const std::string& command)
- : command_(command) {
+System::System(const std::string& command) : command_(command) {
argv_.push_back(command);
}
@@ -88,7 +87,7 @@ bool System::Execute() {
bool System::Execute(bool wait) {
size_t size = argv_.size();
- char * *argv = new char*[size + 1];
+ char** argv = new char* [size + 1];
std::transform(argv_.begin(), argv_.end(), argv, GetCString());
argv[size] = NULL;
@@ -97,8 +96,9 @@ bool System::Execute(bool wait) {
delete[] argv;
if (ret == -1) {
- LOG4CXX_ERROR(logger_, "Can't execute command: " << command_
- << " Errno is: " << std::strerror(errno));
+ LOG4CXX_ERROR(logger_,
+ "Can't execute command: " << command_ << " Errno is: "
+ << std::strerror(errno));
return false;
}
@@ -137,7 +137,7 @@ bool System::Execute(bool wait) {
dup2(fd_dev0, STDERR_FILENO);
size_t size = argv_.size();
- char * *argv = new char*[size + 1];
+ char** argv = new char* [size + 1];
std::transform(argv_.begin(), argv_.end(), argv, GetCString());
argv[size] = NULL;
diff --git a/src/components/utils/src/threads/async_runner.cc b/src/components/utils/src/threads/async_runner.cc
index 4a00317911..131aaa3f78 100644
--- a/src/components/utils/src/threads/async_runner.cc
+++ b/src/components/utils/src/threads/async_runner.cc
@@ -38,13 +38,12 @@
namespace threads {
-CREATE_LOGGERPTR_GLOBAL(logger_, "AsyncRunner");
+CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")
-AsyncRunner::AsyncRunner(const std::string &thread_name)
- : executor_(new AsyncRunnerDelegate) {
+AsyncRunner::AsyncRunner(const std::string& thread_name)
+ : executor_(new AsyncRunnerDelegate) {
LOG4CXX_AUTO_TRACE(logger_);
- thread_ = threads::CreateThread(thread_name.c_str(),
- executor_);
+ thread_ = threads::CreateThread(thread_name.c_str(), executor_);
thread_->start();
}
@@ -65,9 +64,7 @@ AsyncRunner::~AsyncRunner() {
threads::DeleteThread(thread_);
}
-AsyncRunner::AsyncRunnerDelegate::AsyncRunnerDelegate()
- : stop_flag_(false) {
-}
+AsyncRunner::AsyncRunnerDelegate::AsyncRunnerDelegate() : stop_flag_(false) {}
void AsyncRunner::AsyncRunnerDelegate::processDelegate() {
if (!delegates_queue_.empty()) {
@@ -113,4 +110,4 @@ void AsyncRunner::AsyncRunnerDelegate::runDelegate(ThreadDelegate* delegate) {
delegate_notifier_.NotifyOne();
}
-} // namespace policy.
+} // namespace policy.
diff --git a/src/components/utils/src/threads/posix_thread.cc b/src/components/utils/src/threads/posix_thread.cc
index 8f481a82f3..5118e5291b 100644
--- a/src/components/utils/src/threads/posix_thread.cc
+++ b/src/components/utils/src/threads/posix_thread.cc
@@ -34,14 +34,11 @@
#include <limits.h>
#include <stddef.h>
#include <signal.h>
-
-#ifdef BUILD_TESTS
-// Temporary fix for UnitTest until APPLINK-9987 is resolved
-#include <unistd.h>
-#endif
+#include <pthread.h>
+#include <algorithm>
+#include <functional>
#include "utils/threads/thread.h"
-#include "pthread.h"
#include "utils/atomic.h"
#include "utils/threads/thread_delegate.h"
#include "utils/logger.h"
@@ -58,7 +55,8 @@ namespace threads {
CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")
-size_t Thread::kMinStackSize = PTHREAD_STACK_MIN; /* Ubuntu : 16384 ; QNX : 256; */
+size_t Thread::kMinStackSize =
+ PTHREAD_STACK_MIN; /* Ubuntu : 16384 ; QNX : 256; */
void Thread::cleanup(void* arg) {
LOG4CXX_AUTO_TRACE(logger_);
@@ -82,42 +80,41 @@ void* Thread::threadFunc(void* arg) {
// running = 1
// finalized = 1
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
- LOG4CXX_DEBUG(logger_,
- "Thread #" << pthread_self() << " started successfully");
threads::Thread* thread = reinterpret_cast<Thread*>(arg);
DCHECK(thread);
pthread_cleanup_push(&cleanup, thread);
- thread->state_lock_.Acquire();
- thread->state_cond_.Broadcast();
+ thread->state_lock_.Acquire();
+ thread->state_cond_.Broadcast();
- while (!thread->finalized_) {
- LOG4CXX_DEBUG(logger_, "Thread #" << pthread_self() << " iteration");
- thread->run_cond_.Wait(thread->state_lock_);
- LOG4CXX_DEBUG(
- logger_,
- "Thread #" << pthread_self() << " execute. " << "stopped_ = " << thread->stopped_ << "; finalized_ = " << thread->finalized_);
- if (!thread->stopped_ && !thread->finalized_) {
- thread->isThreadRunning_ = true;
- pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
- pthread_testcancel();
-
- thread->state_lock_.Release();
- thread->delegate_->threadMain();
- thread->state_lock_.Acquire();
-
- pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
- thread->isThreadRunning_ = false;
- }
- thread->state_cond_.Broadcast();
- LOG4CXX_DEBUG(logger_,
- "Thread #" << pthread_self() << " finished iteration");
+ while (!thread->finalized_) {
+ LOG4CXX_DEBUG(logger_, "Thread #" << pthread_self() << " iteration");
+ thread->run_cond_.Wait(thread->state_lock_);
+ LOG4CXX_DEBUG(logger_,
+ "Thread #" << pthread_self() << " execute. "
+ << "stopped_ = " << thread->stopped_
+ << "; finalized_ = " << thread->finalized_);
+ if (!thread->stopped_ && !thread->finalized_) {
+ thread->isThreadRunning_ = true;
+ pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
+ pthread_testcancel();
+
+ thread->state_lock_.Release();
+ thread->delegate_->threadMain();
+ thread->state_lock_.Acquire();
+
+ pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
+ thread->isThreadRunning_ = false;
}
+ thread->state_cond_.Broadcast();
+ LOG4CXX_DEBUG(logger_,
+ "Thread #" << pthread_self() << " finished iteration");
+ }
- thread->state_lock_.Release();
- pthread_cleanup_pop(1);
+ thread->state_lock_.Release();
+ pthread_cleanup_pop(1);
LOG4CXX_DEBUG(logger_,
"Thread #" << pthread_self() << " exited successfully");
@@ -130,22 +127,22 @@ void Thread::SetNameForId(const PlatformThreadHandle& thread_id,
name.erase(THREAD_NAME_SIZE);
const int rc = pthread_setname_np(thread_id, name.c_str());
if (rc != EOK) {
- LOG4CXX_WARN(
- logger_,
- "Couldn't set pthread name \"" << name << "\", error code " << rc << " (" << strerror(rc) << ")");
+ LOG4CXX_WARN(logger_,
+ "Couldn't set pthread name \"" << name << "\", error code "
+ << rc << " (" << strerror(rc)
+ << ")");
}
}
Thread::Thread(const char* name, ThreadDelegate* delegate)
- : name_(name ? name : "undefined"),
- delegate_(delegate),
- handle_(0),
- thread_options_(),
- isThreadRunning_(0),
- stopped_(false),
- finalized_(false),
- thread_created_(false) {
-}
+ : name_(name ? name : "undefined")
+ , delegate_(delegate)
+ , handle_(0)
+ , thread_options_()
+ , isThreadRunning_(0)
+ , stopped_(false)
+ , finalized_(false)
+ , thread_created_(false) {}
bool Thread::start() {
return start(thread_options_);
@@ -155,6 +152,10 @@ PlatformThreadHandle Thread::CurrentId() {
return pthread_self();
}
+bool Thread::IsCurrentThread() const {
+ return pthread_equal(CurrentId(), thread_handle());
+}
+
bool Thread::start(const ThreadOptions& options) {
LOG4CXX_AUTO_TRACE(logger_);
@@ -171,9 +172,9 @@ bool Thread::start(const ThreadOptions& options) {
}
if (isThreadRunning_) {
- LOG4CXX_TRACE(
- logger_,
- "EXIT thread "<< name_ << " #" << handle_ << " is already running");
+ LOG4CXX_TRACE(logger_,
+ "EXIT thread " << name_ << " #" << handle_
+ << " is already running");
return true;
}
@@ -182,17 +183,20 @@ bool Thread::start(const ThreadOptions& options) {
pthread_attr_t attributes;
int pthread_result = pthread_attr_init(&attributes);
if (pthread_result != EOK) {
- LOG4CXX_WARN(
- logger_,
- "Couldn't init pthread attributes. Error code = " << pthread_result << " (\"" << strerror(pthread_result) << "\")");
+ LOG4CXX_WARN(logger_,
+ "Couldn't init pthread attributes. Error code = "
+ << pthread_result << " (\"" << strerror(pthread_result)
+ << "\")");
}
if (!thread_options_.is_joinable()) {
- pthread_result = pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
+ pthread_result =
+ pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED);
if (pthread_result != EOK) {
- LOG4CXX_WARN(
- logger_,
- "Couldn't set detach state attribute. Error code = " << pthread_result << " (\"" << strerror(pthread_result) << "\")");
+ LOG4CXX_WARN(logger_,
+ "Couldn't set detach state attribute. Error code = "
+ << pthread_result << " (\"" << strerror(pthread_result)
+ << "\")");
thread_options_.is_joinable(false);
}
}
@@ -201,13 +205,14 @@ bool Thread::start(const ThreadOptions& options) {
if (stack_size >= Thread::kMinStackSize) {
pthread_result = pthread_attr_setstacksize(&attributes, stack_size);
if (pthread_result != EOK) {
- LOG4CXX_WARN(
- logger_,
- "Couldn't set stacksize = " << stack_size << ". Error code = " << pthread_result << " (\"" << strerror(pthread_result) << "\")");
+ LOG4CXX_WARN(logger_,
+ "Couldn't set stacksize = "
+ << stack_size << ". Error code = " << pthread_result
+ << " (\"" << strerror(pthread_result) << "\")");
}
- }
- else {
- ThreadOptions thread_options_temp(Thread::kMinStackSize, thread_options_.is_joinable());
+ } else {
+ ThreadOptions thread_options_temp(Thread::kMinStackSize,
+ thread_options_.is_joinable());
thread_options_ = thread_options_temp;
}
@@ -222,28 +227,33 @@ bool Thread::start(const ThreadOptions& options) {
state_cond_.Wait(auto_lock);
thread_created_ = true;
} else {
- LOG4CXX_ERROR(
- logger_,
- "Couldn't create thread " << name_ << ". Error code = " << pthread_result << " (\"" << strerror(pthread_result) << "\")");
+ LOG4CXX_ERROR(logger_,
+ "Couldn't create thread "
+ << name_ << ". Error code = " << pthread_result
+ << " (\"" << strerror(pthread_result) << "\")");
}
}
stopped_ = false;
run_cond_.NotifyOne();
- LOG4CXX_DEBUG(
- logger_,
- "Thread " << name_ << " #" << handle_ << " started. pthread_result = " << pthread_result);
+ LOG4CXX_DEBUG(logger_,
+ "Thread " << name_ << " #" << handle_ << " started."
+ << " pthread_result = " << pthread_result);
pthread_attr_destroy(&attributes);
return pthread_result == EOK;
}
+void Thread::yield() {
+ sched_yield();
+}
+
void Thread::stop() {
LOG4CXX_AUTO_TRACE(logger_);
sync_primitives::AutoLock auto_lock(state_lock_);
stopped_ = true;
- LOG4CXX_DEBUG(logger_, "Stopping thread #" << handle_
- << " \"" << name_ << " \"");
+ LOG4CXX_DEBUG(logger_,
+ "Stopping thread #" << handle_ << " \"" << name_ << "\"");
if (delegate_ && isThreadRunning_) {
delegate_->exitThreadMain();
@@ -255,7 +265,7 @@ void Thread::stop() {
void Thread::join() {
LOG4CXX_AUTO_TRACE(logger_);
- DCHECK(!pthread_equal(pthread_self(), handle_));
+ DCHECK_OR_RETURN_VOID(!IsCurrentThread());
stop();
@@ -263,6 +273,10 @@ void Thread::join() {
run_cond_.NotifyOne();
if (isThreadRunning_) {
if (!pthread_equal(pthread_self(), handle_)) {
+ LOG4CXX_DEBUG(logger_,
+ "Waiting for #" << handle_
+ << " finished iteration in thread #"
+ << pthread_self());
state_cond_.Wait(auto_lock);
}
}
diff --git a/src/components/utils/src/threads/pulse_thread_delegate.cc b/src/components/utils/src/threads/pulse_thread_delegate.cc
index 68db5dcbea..37e6c670d1 100644
--- a/src/components/utils/src/threads/pulse_thread_delegate.cc
+++ b/src/components/utils/src/threads/pulse_thread_delegate.cc
@@ -61,7 +61,8 @@ PulseThreadDelegate::PulseThreadDelegate() : run_(false) {
void PulseThreadDelegate::threadMain() {
if (!Init()) {
- LOG4CXX_ERROR(logger_, "Failed to initialize thread for QNX channel " << chid_);
+ LOG4CXX_ERROR(logger_,
+ "Failed to initialize thread for QNX channel " << chid_);
return;
}
while (run_) {
@@ -77,13 +78,14 @@ void PulseThreadDelegate::threadMain() {
OnPulse();
break;
}
- }
- else {
+ } else {
if (run_) {
- LOG4CXX_WARN(logger_, "Error occurred while waiting for pulse on QNX channel " << chid_);
- }
- else {
- LOG4CXX_INFO(logger_, "QNX channel " << chid_ << " is apparently destroyed");
+ LOG4CXX_WARN(logger_,
+ "Error occurred while waiting for pulse on QNX channel "
+ << chid_);
+ } else {
+ LOG4CXX_INFO(logger_,
+ "QNX channel " << chid_ << " is apparently destroyed");
}
}
}
@@ -97,16 +99,14 @@ void PulseThreadDelegate::exitThreadMain() {
LOG4CXX_TRACE(logger_, "Disconnecting from QNX channel " << chid_);
if (ConnectDetach(coid_) != -1) {
LOG4CXX_DEBUG(logger_, "Disconnected from QNX channel " << chid_);
- }
- else {
+ } else {
LOG4CXX_WARN(logger_, "Failed to disconnect from QNX channel " << chid_);
}
LOG4CXX_TRACE(logger_, "Destroying QNX channel " << chid_);
- if (ChannelDestroy(chid_) != -1) { // unblocks MsgReceivePulse()
+ if (ChannelDestroy(chid_) != -1) { // unblocks MsgReceivePulse()
LOG4CXX_DEBUG(logger_, "QNX channel " << chid_ << " destroyed");
- }
- else {
+ } else {
LOG4CXX_WARN(logger_, "Failed to destroy QNX channel " << chid_);
}
}
diff --git a/src/components/utils/src/threads/thread_delegate.cc b/src/components/utils/src/threads/thread_delegate.cc
index 1436ea3377..7bdce000da 100644
--- a/src/components/utils/src/threads/thread_delegate.cc
+++ b/src/components/utils/src/threads/thread_delegate.cc
@@ -47,7 +47,7 @@ ThreadDelegate::~ThreadDelegate() {
void ThreadDelegate::exitThreadMain() {
if (thread_) {
- if (thread_->thread_handle() == pthread_self()) {
+ if (thread_->IsCurrentThread()) {
pthread_exit(NULL);
} else {
pthread_cancel(thread_->thread_handle());
@@ -55,8 +55,8 @@ void ThreadDelegate::exitThreadMain() {
}
}
-void ThreadDelegate::set_thread(Thread *thread) {
- DCHECK(thread && !thread->is_running());
+void ThreadDelegate::set_thread(Thread* thread) {
+ DCHECK(thread);
thread_ = thread;
}
diff --git a/src/components/utils/src/threads/thread_manager.cc b/src/components/utils/src/threads/thread_manager.cc
index 528dc8c4de..2959a86cb7 100644
--- a/src/components/utils/src/threads/thread_manager.cc
+++ b/src/components/utils/src/threads/thread_manager.cc
@@ -51,4 +51,4 @@ namespace threads {
CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")
-} // namespace threads
+} // namespace threads
diff --git a/src/components/utils/src/threads/thread_validator.cc b/src/components/utils/src/threads/thread_validator.cc
index 99b812c456..4024522ae4 100644
--- a/src/components/utils/src/threads/thread_validator.cc
+++ b/src/components/utils/src/threads/thread_validator.cc
@@ -39,39 +39,32 @@ namespace threads {
CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")
SingleThreadSimpleValidator::SingleThreadSimpleValidator()
- : creation_thread_id_(Thread::CurrentId()) {
-}
+ : creation_thread_id_(Thread::CurrentId()) {}
-SingleThreadSimpleValidator::~SingleThreadSimpleValidator() {
-}
+SingleThreadSimpleValidator::~SingleThreadSimpleValidator() {}
void SingleThreadSimpleValidator::AssertRunningOnCreationThread() const {
PlatformThreadHandle current_id = Thread::CurrentId();
if (creation_thread_id_ != current_id) {
- LOG4CXX_ERROR(logger_, "Single-threaded object created at thread "
- << creation_thread_id_
- <<" is accessed from thread "
- << current_id
+ LOG4CXX_ERROR(logger_,
+ "Single-threaded object created at thread "
+ << creation_thread_id_ << " is accessed from thread "
+ << current_id
#ifdef BACKTRACE_SUPPORT
- << "\n"
- << utils::Backtrace()
+ << "\n" << utils::Backtrace()
#endif
- );
+ );
}
}
-PlatformThreadHandle SingleThreadSimpleValidator::creation_thread_id() const
-{
+PlatformThreadHandle SingleThreadSimpleValidator::creation_thread_id() const {
return creation_thread_id_;
}
-
SingleThreadValidator::SingleThreadValidator()
- : owning_thread_id_(Thread::CurrentId()){
-}
+ : owning_thread_id_(Thread::CurrentId()) {}
-SingleThreadValidator::~SingleThreadValidator() {
-}
+SingleThreadValidator::~SingleThreadValidator() {}
void SingleThreadValidator::PassToThread(PlatformThreadHandle thread_id) const {
owning_thread_id_ = thread_id;
@@ -80,18 +73,17 @@ void SingleThreadValidator::PassToThread(PlatformThreadHandle thread_id) const {
void SingleThreadValidator::AssertRunningOnValidThread() const {
PlatformThreadHandle current_id = Thread::CurrentId();
if (owning_thread_id_ != current_id) {
- LOG4CXX_ERROR(logger_, "Single-threaded object owned by thread "
- << owning_thread_id_
- << " is accessed from thread "
- << current_id << "\n"
+ LOG4CXX_ERROR(logger_,
+ "Single-threaded object owned by thread "
+ << owning_thread_id_ << " is accessed from thread "
+ << current_id << "\n"
#ifdef BACKTRACE_SUPPORT
- << utils::Backtrace()
+ << utils::Backtrace()
#endif
- );
+ );
}
}
-
-} // namespace threads
+} // namespace threads
// vim: set ts=2 sw=2 et:
diff --git a/src/components/utils/src/timer.cc b/src/components/utils/src/timer.cc
new file mode 100644
index 0000000000..00272a73eb
--- /dev/null
+++ b/src/components/utils/src/timer.cc
@@ -0,0 +1,209 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+#include "utils/timer.h"
+
+#include <string>
+
+#include "utils/macro.h"
+#include "utils/logger.h"
+#include "utils/lock.h"
+#include "utils/timer_task.h"
+#include "utils/conditional_variable.h"
+#include "utils/threads/thread.h"
+#include "utils/threads/thread_delegate.h"
+
+CREATE_LOGGERPTR_GLOBAL(logger_, "Utils")
+
+timer::Timer::Timer(const std::string& name, TimerTask* task)
+ : name_(name)
+ , task_(task)
+ , state_lock_()
+ , delegate_(new TimerDelegate(this, state_lock_))
+ , thread_(threads::CreateThread(name_.c_str(), delegate_.get()))
+ , single_shot_(true) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ DCHECK(!name_.empty());
+ DCHECK(task_);
+ DCHECK(thread_);
+ LOG4CXX_DEBUG(logger_, "Timer " << name_ << " has been created");
+}
+
+timer::Timer::~Timer() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock auto_lock(state_lock_);
+ StopThread();
+ StopDelegate();
+ single_shot_ = true;
+
+ delegate_.release();
+ DeleteThread(thread_);
+ DCHECK(task_);
+ delete task_;
+ LOG4CXX_DEBUG(logger_, "Timer " << name_ << " has been destroyed");
+}
+
+void timer::Timer::Start(const Milliseconds timeout, const bool single_shot) {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock auto_lock(state_lock_);
+ StopThread();
+ single_shot_ = single_shot;
+ StartDelegate(timeout);
+ StartThread();
+ LOG4CXX_DEBUG(logger_, "Timer " << name_ << " has been started");
+}
+
+void timer::Timer::Stop() {
+ LOG4CXX_AUTO_TRACE(logger_);
+ sync_primitives::AutoLock auto_lock(state_lock_);
+ StopThread();
+ StopDelegate();
+ single_shot_ = true;
+ LOG4CXX_DEBUG(logger_, "Timer " << name_ << " has been stopped");
+}
+
+bool timer::Timer::is_running() const {
+ sync_primitives::AutoLock auto_lock(state_lock_);
+ return !delegate_->stop_flag();
+}
+
+timer::Milliseconds timer::Timer::timeout() const {
+ sync_primitives::AutoLock auto_lock(state_lock_);
+ return delegate_->timeout();
+}
+
+void timer::Timer::StartDelegate(const Milliseconds timeout) const {
+ delegate_->set_stop_flag(false);
+ delegate_->set_timeout(timeout);
+}
+
+void timer::Timer::StopDelegate() const {
+ delegate_->set_stop_flag(true);
+ delegate_->set_timeout(0);
+}
+
+void timer::Timer::StartThread() {
+ if (delegate_->finalized_flag()) {
+ return;
+ }
+
+ DCHECK_OR_RETURN_VOID(thread_);
+ if (!thread_->IsCurrentThread()) {
+ thread_->start();
+ }
+}
+
+void timer::Timer::StopThread() {
+ if (delegate_->finalized_flag()) {
+ return;
+ }
+
+ DCHECK_OR_RETURN_VOID(thread_);
+ if (!thread_->IsCurrentThread()) {
+ delegate_->set_finalized_flag(true);
+ {
+ sync_primitives::AutoUnlock auto_unlock(state_lock_);
+ thread_->join();
+ }
+ delegate_->set_finalized_flag(false);
+ }
+}
+
+void timer::Timer::OnTimeout() const {
+ {
+ sync_primitives::AutoLock auto_lock(state_lock_);
+ if (single_shot_) {
+ StopDelegate();
+ }
+ }
+
+ DCHECK_OR_RETURN_VOID(task_);
+ task_->run();
+}
+
+timer::Timer::TimerDelegate::TimerDelegate(
+ const Timer* timer, sync_primitives::Lock& state_lock_ref)
+ : timer_(timer)
+ , timeout_(0)
+ , stop_flag_(true)
+ , finalized_flag_(false)
+ , state_lock_ref_(state_lock_ref)
+ , state_condition_() {
+ DCHECK(timer_);
+}
+
+void timer::Timer::TimerDelegate::set_timeout(const Milliseconds timeout) {
+ timeout_ = timeout;
+}
+
+timer::Milliseconds timer::Timer::TimerDelegate::timeout() const {
+ return timeout_;
+}
+
+void timer::Timer::TimerDelegate::set_stop_flag(const bool stop_flag) {
+ stop_flag_ = stop_flag;
+}
+
+bool timer::Timer::TimerDelegate::stop_flag() const {
+ return stop_flag_;
+}
+
+void timer::Timer::TimerDelegate::set_finalized_flag(
+ const bool finalized_flag) {
+ finalized_flag_ = finalized_flag;
+}
+
+bool timer::Timer::TimerDelegate::finalized_flag() const {
+ return finalized_flag_;
+}
+
+void timer::Timer::TimerDelegate::threadMain() {
+ sync_primitives::AutoLock auto_lock(state_lock_ref_);
+ while (!stop_flag_ && !finalized_flag_) {
+ LOG4CXX_DEBUG(logger_, "Milliseconds left to wait: " << timeout_);
+ if (sync_primitives::ConditionalVariable::kTimeout ==
+ state_condition_.WaitFor(auto_lock, timeout_)) {
+ LOG4CXX_DEBUG(logger_,
+ "Timer has finished counting. Timeout (ms): " << timeout_);
+ if (timer_) {
+ sync_primitives::AutoUnlock auto_unlock(auto_lock);
+ timer_->OnTimeout();
+ }
+ } else {
+ LOG4CXX_DEBUG(logger_, "Timer has been force reset");
+ }
+ }
+}
+
+void timer::Timer::TimerDelegate::exitThreadMain() {
+ sync_primitives::AutoLock auto_lock(state_lock_ref_);
+ state_condition_.NotifyOne();
+}
diff --git a/src/components/utils/test/CMakeLists.txt b/src/components/utils/test/CMakeLists.txt
index d194f7628a..6ec12a17e6 100644
--- a/src/components/utils/test/CMakeLists.txt
+++ b/src/components/utils/test/CMakeLists.txt
@@ -32,23 +32,21 @@ if(BUILD_TESTS)
include_directories (
${JSONCPP_INCLUDE_DIRECTORY}
- ${CMAKE_SOURCE_DIR}/src/3rd_party-static/gmock-1.7.0/include
- ${CMAKE_SOURCE_DIR}/src/3rd_party-static/gmock-1.7.0/gtest/include
- ${COMPONENTS_DIR}/utils/include/utils
- ${COMPONENTS_DIR}/include/utils
+ ${GMOCK_INCLUDE_DIRECTORY}
+ ${COMPONENTS_DIR}/utils/include
${COMPONENTS_DIR}/rpc_base/include
${COMPONENTS_DIR}/utils/test/include
+ ${COMPONENTS_DIR}/policy/include
)
set(testSources
messagemeter_test.cc
file_system_test.cc
- #date_time_test.cc
+ date_time_test.cc
system_test.cc
- signals_linux_test.cc
thread_validator_test.cc
conditional_variable_test.cc
- #message_queue_test.cc
+ message_queue_test.cc
resource_usage_test.cc
bitstream_test.cc
prioritized_queue_test.cc
@@ -57,27 +55,28 @@ set(testSources
singleton_test.cc
#posix_thread_test.cc
stl_utils_test.cc
- #timer_thread_test.cc
rwlock_posix_test.cc
async_runner_test.cc
- #shared_ptr_test.cc
- #scope_guard_test.cc
- #atomic_object_test.cc
+ shared_ptr_test.cc
+ scope_guard_test.cc
+ atomic_object_test.cc
+ message_loop_thread_test.cc
+ custom_string_test.cc
+ timer_test.cc
)
set(testLibraries
gmock
Utils
Policy
+ ConfigProfile
)
-include_directories(${COMPONENTS_DIR}/policy/src/policy/policy_table/table_struct_ext)
-
if (CMAKE_SYSTEM_NAME STREQUAL "QNX")
# --- Tests for QDB Wrapper
list (APPEND testSources
- # ./qdb_wrapper/sql_database_test.cc
- # ./qdb_wrapper/sql_query_test.cc
+ ./qdb_wrapper/sql_database_test.cc
+ ./qdb_wrapper/sql_query_test.cc
)
file(COPY qdbserver.sh DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
file(COPY test-qdb.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
@@ -86,12 +85,9 @@ else ()
# --- Tests for SQLite Wrapper
find_package(Sqlite3 REQUIRED)
list (APPEND testSources
- # ./sqlite_wrapper/sql_database_test.cc
- # ./sqlite_wrapper/sql_query_test.cc
- # generated_code_with_sqlite_test.cc
-
- # TODO{ALeshin} APPLINK-11132 AssertTrue in SetUpTestCase() return false
- #policy_manager_impl_stress_test.cc
+ ./sqlite_wrapper/sql_database_test.cc
+ ./sqlite_wrapper/sql_query_test.cc
+ generated_code_with_sqlite_test.cc
)
list (APPEND testLibraries sqlite3)
endif()
@@ -107,7 +103,10 @@ endif()
file(COPY testscript.sh DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
file(COPY log4cxx.properties DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+file(COPY smartDeviceLink.ini DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
create_test("utils_test" "${testSources}" "${testLibraries}")
+add_subdirectory(test_generator)
+
endif()
diff --git a/src/components/utils/test/async_runner_test.cc b/src/components/utils/test/async_runner_test.cc
index e0db33bb96..9badbadf1c 100644
--- a/src/components/utils/test/async_runner_test.cc
+++ b/src/components/utils/test/async_runner_test.cc
@@ -30,14 +30,15 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include <stdlib.h>
#include <ctime>
-#include "lock.h"
-#include "threads/async_runner.h"
-#include "utils/conditional_variable.h"
+#include <stdlib.h>
#include "gtest/gtest.h"
+#include "utils/lock.h"
+#include "utils/conditional_variable.h"
+#include "utils/threads/async_runner.h"
+
namespace test {
namespace components {
namespace utils {
@@ -59,9 +60,7 @@ class TestThreadDelegate : public ThreadDelegate {
class AsyncRunnerTest : public ::testing::Test {
public:
- AsyncRunnerTest()
- : kDelegatesNum_(1),
- asr_pt_(NULL) {
+ AsyncRunnerTest() : kDelegatesNum_(1), asr_pt_(NULL) {
CreateAsyncRunner();
CreateThreadsArray();
}
@@ -75,13 +74,13 @@ class AsyncRunnerTest : public ::testing::Test {
Lock test_lock_;
uint32_t kDelegatesNum_;
ConditionalVariable cond_var_;
- TestThreadDelegate **delegates_;
- AsyncRunner *asr_pt_;
+ TestThreadDelegate** delegates_;
+ AsyncRunner* asr_pt_;
void CreateThreadsArray() {
srand(std::time(NULL));
kDelegatesNum_ = (rand() % 20 + 1);
- delegates_ = new TestThreadDelegate*[kDelegatesNum_];
+ delegates_ = new TestThreadDelegate* [kDelegatesNum_];
}
void DeleteThreadsArray() {
@@ -111,8 +110,9 @@ TEST_F(AsyncRunnerTest, ASyncRunManyDelegates_ExpectSuccessfulAllDelegatesRun) {
EXPECT_EQ(kDelegatesNum_, check_value);
}
-//TODO(VVeremjova) APPLINK-12834 Sometimes delegates do not run
-TEST_F(AsyncRunnerTest, DISABLED_RunManyDelegatesAndStop_ExpectSuccessfulDelegatesStop) {
+// TODO(VVeremjova) APPLINK-12834 Sometimes delegates do not run
+TEST_F(AsyncRunnerTest,
+ DISABLED_RunManyDelegatesAndStop_ExpectSuccessfulDelegatesStop) {
AutoLock lock(test_lock_);
// Clear global value before test
check_value = 0;
@@ -138,4 +138,3 @@ TEST_F(AsyncRunnerTest, DISABLED_RunManyDelegatesAndStop_ExpectSuccessfulDelegat
} // namespace utils
} // namespace components
} // namespace test
-
diff --git a/src/components/utils/test/auto_trace_test.cc b/src/components/utils/test/auto_trace_test.cc
index a53f4aa1e0..1290ce7e96 100644
--- a/src/components/utils/test/auto_trace_test.cc
+++ b/src/components/utils/test/auto_trace_test.cc
@@ -30,73 +30,116 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
+#include <fstream>
+#include <ctime>
+
#include "gtest/gtest.h"
#include "utils/auto_trace.h"
-#include "logger.h"
-#include <fstream>
+#include "utils/logger.h"
+#include "utils/log_message_loop_thread.h"
+#include "utils/threads/message_loop_thread.h"
+#include "utils/file_system.h"
+#include "utils/threads/thread.h"
+#include "utils/date_time.h"
+#include "utils/logger_status.h"
+#include "utils/helpers.h"
namespace test {
namespace components {
-namespace utils {
+namespace utils_test {
using namespace ::logger;
-CREATE_LOGGERPTR_GLOBAL(logger_, "AutoTraceTestLog");
+CREATE_LOGGERPTR_GLOBAL(logger_, "AutoTraceTestLog")
+
+namespace {
+const std::string kFileName =
+ file_system::CurrentWorkingDirectory() + "/AutoTraceTestLogFile.log";
+} // namespace
void Preconditions() {
- //delete file with previous logs
- const char* file_name = "AutoTraceTestLogFile.log";
- std::remove(file_name);
+ // Delete file with previous logs
+ if (file_system::FileExists(kFileName)) {
+ // If logger is active now deleting log file cause undefined befaviour.
+ DEINIT_LOGGER();
+ ASSERT_TRUE(file_system::DeleteFile(kFileName))
+ << "Can't delete AutoTraceTestLogFile.log";
+ }
}
void InitLogger() {
- INIT_LOGGER("log4cxx.properties");
+ // Set enabled logs
+ INIT_LOGGER("log4cxx.properties", true);
+ // DEINIT_LOGGER will be called in test_main.cc
}
-void CreateDeleteAutoTrace(const std::string & testlog) {
+void CreateDeleteAutoTrace(const std::string& testlog) {
LOG4CXX_AUTO_TRACE(logger_);
LOG4CXX_DEBUG(logger_, testlog);
}
-bool CheckTraceInFile(const std::string & testlog) {
-
- bool isLogFound = false;
- std::string line;
-
- std::ifstream file_log("AutoTraceTestLogFile.log");
+/**
+ * @brief IsLogLineContains cheks if log line contains debug message with
+ * specified debug message
+ * @param log_line line to search in
+ * @param debug_level expected debug level
+ * @param debug_log_message expected debug message
+ * @return true if debug_message exist in log_line with debug_level
+ */
+bool IsLogLineContains(const std::string& log_line,
+ const std::string& debug_level,
+ const std::string& debug_message) {
+ return log_line.find(debug_level) != std::string::npos &&
+ log_line.find(debug_message) != std::string::npos;
+}
- if (file_log.is_open()) {
- while (getline(file_log, line)) {
- std::size_t found = line.find(testlog);
- std::size_t founddebug = line.find("DEBUG");
- if ((found != std::string::npos) && (founddebug != std::string::npos)) {
- isLogFound = true;
- break;
- }
- }
- file_log.close();
- } else {
- std::cout << "file cannot be opened \n";
+/**
+ * @brief CheckAutoTraceDebugInFile chacks if logfile contains autotrace and
+ * debug for test AutoTrace_WriteToFile_ReadCorrectString
+ * @param debug_message message that should be logged with DEBUG level
+ * @return true if trace enter, trace exit, debug message exist in log file
+ */
+bool CheckAutoTraceDebugInFile(const std::string& debug_message) {
+ using namespace helpers;
+ const std::string debug_log_level = "DEBUG";
+ const std::string trace_log_level = "TRACE";
+ const std::string enter_message = ": Enter";
+ const std::string exit_message = ": Exit";
+ std::ifstream file_log(kFileName);
+ if (!file_log.is_open()) {
+ return false;
}
- return isLogFound;
-}
-void DeinitLogger() {
- DEINIT_LOGGER();
+ bool debug_found = false;
+ bool trace_enter = false;
+ bool trace_exit = false;
+ for (std::string line;
+ Compare<bool, EQ, ONE>(false, debug_found, trace_enter, trace_exit) &&
+ getline(file_log, line);) {
+ debug_found = debug_found
+ ? debug_found
+ : IsLogLineContains(line, debug_log_level, debug_message);
+ trace_enter = trace_enter
+ ? trace_enter
+ : IsLogLineContains(line, trace_log_level, enter_message);
+ trace_exit = trace_exit
+ ? trace_exit
+ : IsLogLineContains(line, trace_log_level, exit_message);
+ }
+ file_log.close();
+ return Compare<bool, EQ, ALL>(true, debug_found, trace_enter, trace_exit);
}
-
-//TODO(VVeremjova) APPLINK-12832 Logger does not write debug information in file
-TEST(AutoTraceTest, DISABLED_Basic) {
- const std::string testlog =
- "Test trace is working!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!";
+// TODO(DTrunov) : Enable after APPLINK-25006 will be resolved
+TEST(AutoTraceTest, DISABLED_AutoTrace_WriteToFile_ReadCorrectString) {
+ const std::string testlog = "Test trace is working!";
Preconditions();
InitLogger();
CreateDeleteAutoTrace(testlog);
- DeinitLogger();
- ASSERT_TRUE(CheckTraceInFile(testlog));
+ FLUSH_LOGGER();
+ ASSERT_TRUE(CheckAutoTraceDebugInFile(testlog));
}
-} // namespace utils
+} // namespace utils_test
} // namespace components
} // namespace test
diff --git a/src/components/utils/test/back_trace_test.cc b/src/components/utils/test/back_trace_test.cc
index 12d5df81fc..071c4d3342 100644
--- a/src/components/utils/test/back_trace_test.cc
+++ b/src/components/utils/test/back_trace_test.cc
@@ -40,11 +40,10 @@ namespace utils {
using namespace ::utils;
TEST(BackTraceTest, CallStackShouldNotBeEmpty) {
-
- //arrange
+ // arrange
Backtrace newtrace = Backtrace();
- std::vector < std::string > symbols = newtrace.CallStack();
- //assert
+ std::vector<std::string> symbols = newtrace.CallStack();
+ // assert
ASSERT_FALSE(symbols.empty());
}
diff --git a/src/components/utils/test/bitstream_test.cc b/src/components/utils/test/bitstream_test.cc
index 07a80bde07..df27aaa835 100644
--- a/src/components/utils/test/bitstream_test.cc
+++ b/src/components/utils/test/bitstream_test.cc
@@ -42,19 +42,19 @@ namespace utils {
using ::utils::BitStream;
TEST(BitstreamTest, CreateBitstream_WithDataWithDatasize_BitStreamIsGood) {
-
- //arrange
+ // arrange
uint8_t data = 10;
size_t bits = 2;
BitStream bs(&data, bits);
- //assert
+ // assert
EXPECT_TRUE(bs.IsGood());
}
-TEST(BitstreamTest, ExtractBitstreamInUint8_ExtractAllData_BitStreamIsGoodDataExtractedCorrectly) {
-
- //arrange
+TEST(
+ BitstreamTest,
+ ExtractBitstreamInUint8_ExtractAllData_BitStreamIsGoodDataExtractedCorrectly) {
+ // arrange
uint8_t data = 10;
size_t bits = 2;
BitStream bs(&data, bits);
@@ -62,15 +62,15 @@ TEST(BitstreamTest, ExtractBitstreamInUint8_ExtractAllData_BitStreamIsGoodDataEx
uint8_t extract_data = 0;
Extract(&bs, &extract_data);
- //assert
+ // assert
EXPECT_TRUE(bs.IsGood());
EXPECT_EQ(data, extract_data);
}
-TEST(BitstreamTest, ExtractBitstreamInUint8_WithDataWithZeroSize_BitStreamIsBad) {
-
- //arrange
+TEST(BitstreamTest,
+ ExtractBitstreamInUint8_WithDataWithZeroSize_BitStreamIsBad) {
+ // arrange
uint8_t data = 10;
size_t bits = 0;
BitStream bs(&data, bits);
@@ -78,13 +78,14 @@ TEST(BitstreamTest, ExtractBitstreamInUint8_WithDataWithZeroSize_BitStreamIsBad)
uint8_t extract_data = 0;
Extract(&bs, &extract_data);
- //assert
+ // assert
EXPECT_TRUE(bs.IsBad());
}
-TEST(BitstreamTest, ExtractBitstreamInUint32_WithDatasizeEq4_BitStreamIsGoodDataExtractedCorrectly) {
-
- //arrange
+TEST(
+ BitstreamTest,
+ ExtractBitstreamInUint32_WithDatasizeEq4_BitStreamIsGoodDataExtractedCorrectly) {
+ // arrange
uint8_t data = 10;
size_t bits = 4;
BitStream bs(&data, bits);
@@ -92,14 +93,12 @@ TEST(BitstreamTest, ExtractBitstreamInUint32_WithDatasizeEq4_BitStreamIsGoodData
uint32_t extract_data = 0;
Extract(&bs, &extract_data);
- //assert
+ // assert
EXPECT_TRUE(bs.IsGood());
-
}
TEST(BitstreamTest, ExtractBitstreamInUint32_DatasizeLess4_BitStreamIsBad) {
-
- //arrange
+ // arrange
uint8_t data = 10;
size_t bits = 3;
BitStream bs(&data, bits);
@@ -107,14 +106,12 @@ TEST(BitstreamTest, ExtractBitstreamInUint32_DatasizeLess4_BitStreamIsBad) {
uint32_t extract_data = 0;
Extract(&bs, &extract_data);
- //assert
+ // assert
EXPECT_TRUE(bs.IsBad());
-
}
TEST(BitstreamTest, ExtractFullBitstream_WithDataWithDatasize_BitStreamIsGood) {
-
- //arrange
+ // arrange
uint8_t data = 10;
size_t bits = 8;
BitStream bs(&data, bits);
@@ -123,15 +120,15 @@ TEST(BitstreamTest, ExtractFullBitstream_WithDataWithDatasize_BitStreamIsGood) {
Extract(&bs, &extract_data, bits);
- //assert
+ // assert
EXPECT_TRUE(bs.IsGood());
EXPECT_EQ(data, extract_data);
}
-TEST(BitstreamTest, ExtractBitstreamInString_WithDataWithDatasize_BitStreamIsGood) {
-
- //arrange
+TEST(BitstreamTest,
+ ExtractBitstreamInString_WithDataWithDatasize_BitStreamIsGood) {
+ // arrange
uint8_t data = 10;
size_t bits = 2;
BitStream bs(&data, bits);
@@ -141,46 +138,45 @@ TEST(BitstreamTest, ExtractBitstreamInString_WithDataWithDatasize_BitStreamIsGoo
Extract(&bs, &strdata, length);
- //assert
+ // assert
EXPECT_TRUE(bs.IsGood());
}
TEST(BitstreamTest, CreateBitstream_NoDataZeroDatasize_BitStreamIsGood) {
-
- //arrange
- uint8_t *data = NULL;
+ // arrange
+ uint8_t* data = NULL;
size_t bits = 0;
BitStream bs(data, bits);
- //assert
+ // assert
EXPECT_TRUE(bs.IsGood());
}
-TEST(BitstreamTest, CreateBitstream_NoDataWithUpperboundDataSize_BitStreamIsGood) {
-
- //arrange
- uint8_t *data = NULL;
+TEST(BitstreamTest,
+ CreateBitstream_NoDataWithUpperboundDataSize_BitStreamIsGood) {
+ // arrange
+ uint8_t* data = NULL;
size_t bits = 65535;
BitStream bs(data, bits);
- //assert
+ // assert
EXPECT_TRUE(bs.IsGood());
}
-TEST(BitstreamTest, CreateBitstream_WithUpperboundDataWithLessDataSize_BitStreamIsGood) {
-
- //arrange
+TEST(BitstreamTest,
+ CreateBitstream_WithUpperboundDataWithLessDataSize_BitStreamIsGood) {
+ // arrange
uint8_t data = 255;
size_t bits = sizeof(char);
BitStream bs(&data, bits);
- //assert
+ // assert
EXPECT_TRUE(bs.IsGood());
}
-TEST(BitstreamTest, ExtractBitstream_WithUpperboundDataWithLessDataSize_BitStreamIsGood) {
-
- //arrange
+TEST(BitstreamTest,
+ ExtractBitstream_WithUpperboundDataWithLessDataSize_BitStreamIsGood) {
+ // arrange
uint8_t data = 255;
size_t bits = sizeof(char);
BitStream bs(&data, bits);
@@ -188,13 +184,13 @@ TEST(BitstreamTest, ExtractBitstream_WithUpperboundDataWithLessDataSize_BitStrea
uint8_t extract_data = 0;
Extract(&bs, &extract_data, bits);
- //assert
+ // assert
EXPECT_TRUE(bs.IsGood());
}
-TEST(BitstreamTest, ExtractBitstream_WithUpperboundDataWithZeroDataSize_BitStreamIsGood) {
-
- //arrange
+TEST(BitstreamTest,
+ ExtractBitstream_WithUpperboundDataWithZeroDataSize_BitStreamIsGood) {
+ // arrange
uint8_t data = 255;
size_t bits = 0;
BitStream bs(&data, bits);
@@ -202,26 +198,25 @@ TEST(BitstreamTest, ExtractBitstream_WithUpperboundDataWithZeroDataSize_BitStrea
uint8_t extract_data = 0;
Extract(&bs, &extract_data, bits);
- //assert
+ // assert
EXPECT_TRUE(bs.IsGood());
}
TEST(BitstreamTest, ExtractBitstream_WithDataMarkedBad_ExpectIsBad) {
-
- //arrange
+ // arrange
uint8_t data = 255;
size_t bits = sizeof(int);
BitStream bs(&data, bits);
- //assert
+ // assert
EXPECT_TRUE(bs.IsGood());
- //act
+ // act
bs.MarkBad();
- //assert
+ // assert
EXPECT_TRUE(bs.IsBad());
- //act
+ // act
Extract(&bs, &data, bits);
- //arrange
+ // arrange
EXPECT_TRUE(bs.IsBad());
}
diff --git a/src/components/utils/test/conditional_variable_test.cc b/src/components/utils/test/conditional_variable_test.cc
index a898732ffc..8c3bd7db8c 100644
--- a/src/components/utils/test/conditional_variable_test.cc
+++ b/src/components/utils/test/conditional_variable_test.cc
@@ -30,13 +30,13 @@
* POSSIBILITY OF SUCH DAMAGE.
*/
-#include <pthread.h>
#include <iostream>
-
-#include "lock.h"
-#include "macro.h"
+#include <pthread.h>
#include "gtest/gtest.h"
+
+#include "utils/lock.h"
+#include "utils/macro.h"
#include "utils/conditional_variable.h"
namespace test {
@@ -45,22 +45,20 @@ namespace utils {
class ConditionalVariableTest : public ::testing::Test {
public:
- ConditionalVariableTest()
- : test_value_("initialized"),
- counter_(0) {
- }
+ ConditionalVariableTest() : test_value_("initialized"), counter_(0) {}
void check_counter();
void task_one();
- static void* check_counter_helper(void *context) {
- (reinterpret_cast<ConditionalVariableTest *>(context))->check_counter();
+ static void* check_counter_helper(void* context) {
+ (reinterpret_cast<ConditionalVariableTest*>(context))->check_counter();
return NULL;
}
- static void* task_one_helper(void *context) {
- (reinterpret_cast<ConditionalVariableTest *>(context))->task_one();
+ static void* task_one_helper(void* context) {
+ (reinterpret_cast<ConditionalVariableTest*>(context))->task_one();
return NULL;
}
+
protected:
std::string test_value_;
sync_primitives::ConditionalVariable cond_var_;
@@ -73,10 +71,13 @@ void ConditionalVariableTest::check_counter() {
sync_primitives::AutoLock test_lock(test_mutex_);
if (counter_ <= 1) {
counter_++;
- cond_var_.Wait(test_mutex_); // Mutex unlock & Thread sleeps until Notification
- }
- else if(counter_ == 2) { // Checking for equal 2 in this specific case. Because we were waiting for 2 threads to be finished
- cond_var_.Broadcast(); // Notify All threads waiting on conditional variable
+ cond_var_.Wait(
+ test_mutex_); // Mutex unlock & Thread sleeps until Notification
+ } else if (counter_ == 2) { // Checking for equal 2 in this specific case.
+ // Because we were waiting for 2 threads to be
+ // finished
+ cond_var_
+ .Broadcast(); // Notify All threads waiting on conditional variable
}
}
@@ -84,18 +85,18 @@ void ConditionalVariableTest::check_counter() {
void ConditionalVariableTest::task_one() {
sync_primitives::AutoLock test_lock(test_mutex_);
test_value_ = "changed by thread 1";
- cond_var_.NotifyOne(); // Notify At least one thread waiting on conditional variable
+ cond_var_.NotifyOne(); // Notify At least one thread waiting on conditional
+ // variable
test_value_ = "changed again by thread 1";
}
-TEST_F(ConditionalVariableTest, CheckNotifyOne_OneThreadNotified_ExpectSuccessful) {
+TEST_F(ConditionalVariableTest,
+ CheckNotifyOne_OneThreadNotified_ExpectSuccessful) {
pthread_t thread1;
sync_primitives::AutoLock test_lock(test_mutex_);
test_value_ = "changed by main thread";
- const bool thread_created = pthread_create(&thread1,
- NULL,
- &ConditionalVariableTest::task_one_helper,
- this);
+ const bool thread_created = pthread_create(
+ &thread1, NULL, &ConditionalVariableTest::task_one_helper, this);
ASSERT_FALSE(thread_created) << "thread1 is not created!";
test_value_ = "changed twice by main thread";
cond_var_.WaitFor(test_lock, 2000);
@@ -103,30 +104,29 @@ TEST_F(ConditionalVariableTest, CheckNotifyOne_OneThreadNotified_ExpectSuccessfu
EXPECT_EQ(last_value, test_value_);
}
-TEST_F(ConditionalVariableTest, CheckBroadcast_AllThreadsNotified_ExpectSuccessful) {
+TEST_F(ConditionalVariableTest,
+ CheckBroadcast_AllThreadsNotified_ExpectSuccessful) {
pthread_t thread1;
pthread_t thread2;
- bool thread_created = pthread_create(&thread1,
- NULL,
- &ConditionalVariableTest::check_counter_helper,
- this);
+ bool thread_created = pthread_create(
+ &thread1, NULL, &ConditionalVariableTest::check_counter_helper, this);
ASSERT_FALSE(thread_created) << "thread1 is not created!";
- thread_created = pthread_create(&thread2,
- NULL,
- &ConditionalVariableTest::check_counter_helper,
- this);
+ thread_created = pthread_create(
+ &thread2, NULL, &ConditionalVariableTest::check_counter_helper, this);
ASSERT_FALSE(thread_created) << "thread2 is not created!";
check_counter();
EXPECT_EQ(2u, counter_);
}
-TEST_F(ConditionalVariableTest, CheckWaitForWithTimeout1sec_ThreadBlockedForTimeout_ExpectSuccessfulWakeUp) {
+TEST_F(
+ ConditionalVariableTest,
+ CheckWaitForWithTimeout1sec_ThreadBlockedForTimeout_ExpectSuccessfulWakeUp) {
sync_primitives::AutoLock test_lock(test_mutex_);
- sync_primitives::ConditionalVariable::WaitStatus wait_st = cond_var_.WaitFor(test_lock, 1000);
+ sync_primitives::ConditionalVariable::WaitStatus wait_st =
+ cond_var_.WaitFor(test_lock, 1000);
EXPECT_EQ(sync_primitives::ConditionalVariable::kTimeout, wait_st);
}
} // namespace utils
} // namespace components
} // namespace test
-
diff --git a/src/components/utils/test/custom_string_test.cc b/src/components/utils/test/custom_string_test.cc
new file mode 100644
index 0000000000..3610bfb36b
--- /dev/null
+++ b/src/components/utils/test/custom_string_test.cc
@@ -0,0 +1,319 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <iostream>
+#include <string>
+#include "gtest/gtest.h"
+#include "utils/custom_string.h"
+
+namespace custom_str = utils::custom_string;
+
+namespace test {
+namespace components {
+namespace utils {
+
+std::string CreateMultibyteString(uint8_t* array, size_t array_size) {
+ return std::string(array, array + array_size);
+}
+
+class CustomStringTest : public ::testing::TestWithParam<std::string> {
+ protected:
+ static void SetUpTestCase() {
+ const size_t kSizeStr = 8;
+ uint8_t array[] = {0xD0,
+ 0xA2,
+ 0xD0,
+ 0xB5,
+ 0xD1,
+ 0x81,
+ 0xD1,
+ 0x82}; // Array contains russian word "Тест"
+ mbstring1_ = CreateMultibyteString(array, kSizeStr);
+ mbstring2_ = mbstring1_ + "abc";
+ amount_symbols_mbstring1_ = 4; // amount of symbols from string mbstring1_
+ amount_symbols_mbstring2_ = 7; // amount of symbols from string mbstring2_
+ amount_bytes_mbstring1_ = mbstring1_.size();
+ amount_bytes_mbstring2_ = mbstring2_.size();
+ }
+
+ public:
+ static std::string mbstring1_; // String contains russian word "Тест"
+ static std::string
+ mbstring2_; // String contains russian word with ASCII symbols "Тестabc"
+ static size_t amount_symbols_mbstring1_;
+ static size_t amount_symbols_mbstring2_;
+ static size_t amount_bytes_mbstring1_;
+ static size_t amount_bytes_mbstring2_;
+};
+
+std::string CustomStringTest::mbstring1_ = "";
+std::string CustomStringTest::mbstring2_ = "";
+size_t CustomStringTest::amount_symbols_mbstring1_ = 0;
+size_t CustomStringTest::amount_symbols_mbstring2_ = 0;
+size_t CustomStringTest::amount_bytes_mbstring1_ = 0;
+size_t CustomStringTest::amount_bytes_mbstring2_ = 0;
+
+TEST_F(CustomStringTest,
+ AddASCIIStringToCustomString_ExpectCorrectSizeAndIsASCIIStringEQTrue) {
+ std::string str("Test string");
+ custom_str::CustomString obj(str);
+
+ EXPECT_EQ(str.size(), obj.size());
+ EXPECT_EQ(str.length(), obj.length());
+ EXPECT_EQ(str.size(), obj.length_bytes());
+ EXPECT_TRUE(obj.is_ascii_string());
+ EXPECT_FALSE(obj.empty());
+}
+
+TEST_F(CustomStringTest,
+ AddEmptyToCustomString_ExpectCorrectSizeAndIsASCIIStringEQTrue) {
+ std::string str;
+ custom_str::CustomString obj(str);
+
+ EXPECT_EQ(str.size(), obj.size());
+ EXPECT_EQ(str.length(), obj.length());
+ EXPECT_EQ(str.size(), obj.length_bytes());
+ EXPECT_TRUE(obj.is_ascii_string());
+ EXPECT_TRUE(obj.empty());
+}
+
+TEST_F(CustomStringTest,
+ AddEmptyToCustomString_ExpectCorrectWorkOfMethodAsMBString) {
+ std::string str;
+ custom_str::CustomString obj(str);
+ EXPECT_TRUE(str == obj.AsMBString());
+}
+
+TEST_F(CustomStringTest,
+ AddASCIIStringToCustomString_ExpectCorrectWorkOfMethodAsMBString) {
+ std::string str("Test string");
+ custom_str::CustomString obj(str);
+ EXPECT_TRUE(str == obj.AsMBString());
+}
+
+TEST_F(CustomStringTest,
+ AddASCIIStringToCustomString_ExpectCorrectWorkOfAppendOperator) {
+ custom_str::CustomString obj("Test string");
+ custom_str::CustomString obj1("abc");
+ custom_str::CustomString obj_empty;
+ std::string str("abc");
+ std::string str_empty;
+ std::string str_result("Test stringabc");
+ std::string str_result1("Test string");
+ custom_str::CustomString obj_result;
+ obj_result = obj + obj1;
+ EXPECT_TRUE(str_result == obj_result.AsMBString());
+ obj_result = obj + obj_empty;
+ EXPECT_TRUE(str_result1 == obj_result.AsMBString());
+ obj_result = obj + str;
+ EXPECT_TRUE(str_result == obj_result.AsMBString());
+ obj_result = obj + str_empty;
+ EXPECT_TRUE(str_result1 == obj_result.AsMBString());
+}
+
+TEST_F(CustomStringTest,
+ AddEmptyStringToCustomString_ExpectCorrectWorkOfAppendOperator) {
+ custom_str::CustomString obj_empty;
+ custom_str::CustomString obj("abc");
+ custom_str::CustomString obj_empty1;
+ std::string str("abc");
+ std::string str_empty;
+ custom_str::CustomString obj_result;
+ obj_result = obj_empty + obj;
+ EXPECT_TRUE(str == obj_result.AsMBString());
+ obj_result = obj_empty + obj_empty1;
+ EXPECT_TRUE(str_empty == obj_result.AsMBString());
+ obj_result = obj_empty + str;
+ EXPECT_TRUE(str == obj_result.AsMBString());
+ obj_result = obj_empty + str_empty;
+ EXPECT_TRUE(str_empty == obj_result.AsMBString());
+}
+
+TEST_F(
+ CustomStringTest,
+ AddASCIIAndEmptyStringToCustomString_ExpectCorrectWorkOfCompareOperator) {
+ custom_str::CustomString obj_empty;
+ custom_str::CustomString obj_empty1;
+ custom_str::CustomString obj("abc");
+ custom_str::CustomString obj1("abc");
+ std::string str_empty;
+ std::string str("abc");
+
+ EXPECT_TRUE(obj_empty == obj_empty1);
+ EXPECT_FALSE(obj_empty == obj1);
+ EXPECT_TRUE(obj_empty == str_empty);
+ EXPECT_FALSE(obj_empty == str);
+ EXPECT_TRUE(obj == obj1);
+ EXPECT_TRUE(obj == str);
+ EXPECT_FALSE(obj == str_empty);
+}
+
+TEST_F(CustomStringTest,
+ AddASCIIAndEmptyStringToCustomString_ExpectCorrectWorkOfCompareMethod) {
+ custom_str::CustomString obj_empty;
+ custom_str::CustomString obj("abc");
+ std::string str_empty;
+ std::string str("abc");
+
+ EXPECT_TRUE(obj_empty.compare(str_empty) == 0);
+ EXPECT_TRUE(obj_empty.compare(str) != 0);
+ EXPECT_TRUE(obj_empty.compare("") == 0);
+ EXPECT_TRUE(obj_empty.compare("abc") != 0);
+ EXPECT_TRUE(obj.compare(str_empty) != 0);
+ EXPECT_TRUE(obj.compare(str) == 0);
+ EXPECT_TRUE(obj.compare("") != 0);
+ EXPECT_TRUE(obj.compare("abc") == 0);
+}
+
+TEST_F(CustomStringTest,
+ AddASCIIStringToCustomString_ExpectCorrectWorkOfAtMethod) {
+ std::string str("abc");
+ custom_str::CustomString obj(str);
+ for (size_t i = 0; i < obj.size(); ++i) {
+ EXPECT_TRUE(obj.at(i) == str[i]);
+ }
+}
+
+TEST_F(
+ CustomStringTest,
+ AddASCIIAndEmptyStringToCustomString_ExpectCorrectWorkOfCompareIgnoreCaseMethod) {
+ custom_str::CustomString obj_empty;
+ custom_str::CustomString obj_empty1;
+ custom_str::CustomString obj("abc");
+ custom_str::CustomString obj1("AbC");
+ custom_str::CustomString obj2("AbCd");
+
+ EXPECT_TRUE(obj_empty.CompareIgnoreCase(obj_empty1));
+ EXPECT_FALSE(obj_empty.CompareIgnoreCase(obj));
+ EXPECT_TRUE(obj.CompareIgnoreCase(obj1));
+ EXPECT_TRUE(obj.CompareIgnoreCase(obj));
+ EXPECT_FALSE(obj.CompareIgnoreCase(obj2));
+ EXPECT_FALSE(obj.CompareIgnoreCase(obj_empty));
+}
+
+TEST_F(CustomStringTest,
+ AddASCIIStringToCustomString_ExpectCorrectWorkOfToWStringMethod) {
+ custom_str::CustomString obj("abc");
+ std::wstring wstr(L"abc");
+ EXPECT_TRUE(wstr == obj.ToWString());
+}
+
+TEST_F(CustomStringTest,
+ AddUTF8StringToCustomString_ExpectCorrectSizeAndIsASCIIStringEQFalse) {
+ custom_str::CustomString obj(CustomStringTest::mbstring1_);
+ EXPECT_EQ(obj.size(), CustomStringTest::amount_symbols_mbstring1_);
+ EXPECT_EQ(obj.length(), CustomStringTest::amount_symbols_mbstring1_);
+ EXPECT_EQ(obj.length_bytes(), CustomStringTest::amount_bytes_mbstring1_);
+ EXPECT_FALSE(obj.is_ascii_string());
+}
+
+TEST_F(
+ CustomStringTest,
+ AddMixingUTF8WithASCIIStringToCustomString_ExpectCorrectSizeAndIsASCIIStringEQFalse) {
+ custom_str::CustomString obj(CustomStringTest::mbstring2_);
+ EXPECT_EQ(obj.size(), CustomStringTest::amount_symbols_mbstring2_);
+ EXPECT_EQ(obj.length(), CustomStringTest::amount_symbols_mbstring2_);
+ EXPECT_EQ(obj.length_bytes(), CustomStringTest::amount_bytes_mbstring2_);
+ EXPECT_FALSE(obj.is_ascii_string());
+}
+
+TEST_F(
+ CustomStringTest,
+ AddUTF8StringAndMixingUTF8WithASCIIToCustomString_ExpectCorrectWorkOfMethodAsMBString) {
+ custom_str::CustomString obj(CustomStringTest::mbstring1_);
+ custom_str::CustomString obj1(CustomStringTest::mbstring2_);
+ EXPECT_TRUE(CustomStringTest::mbstring1_ == obj.AsMBString());
+ EXPECT_TRUE(CustomStringTest::mbstring2_ == obj1.AsMBString());
+}
+
+TEST_F(CustomStringTest,
+ AddUTF8StringToCustomString_ExpectCorrectConvertingToWString) {
+ custom_str::CustomString obj(CustomStringTest::mbstring1_);
+ custom_str::CustomString obj1(CustomStringTest::mbstring2_);
+ std::wstring wstr1(L"Тест");
+ std::wstring wstr2(L"Тестabc");
+ EXPECT_TRUE(wstr1 == obj.ToWString());
+ EXPECT_TRUE(wstr2 == obj1.ToWString());
+}
+
+TEST_F(
+ CustomStringTest,
+ AddSameMultiByteStringsToCustomString_ExpectCorrectCaseSensetiveComparing) {
+ custom_str::CustomString obj(CustomStringTest::mbstring1_);
+ custom_str::CustomString obj_1(CustomStringTest::mbstring1_);
+ EXPECT_TRUE(obj == obj_1);
+ EXPECT_TRUE(obj == CustomStringTest::mbstring1_);
+ EXPECT_EQ(0, obj.compare(CustomStringTest::mbstring1_.c_str()));
+ EXPECT_EQ(0, obj.compare(CustomStringTest::mbstring1_));
+}
+
+TEST_F(
+ CustomStringTest,
+ AddDiferenceMultiByteStringsToCustomString_ExpectCorrectCaseSensetiveComparing) {
+ custom_str::CustomString obj(CustomStringTest::mbstring1_);
+ custom_str::CustomString obj1(CustomStringTest::mbstring2_);
+ EXPECT_FALSE(obj == obj1);
+ EXPECT_FALSE(obj == CustomStringTest::mbstring2_);
+ EXPECT_TRUE(obj.compare(CustomStringTest::mbstring2_) != 0);
+}
+
+TEST_F(
+ CustomStringTest,
+ AddDiferenceMultiByteStringsToCustomString_ExpectCorrectCaseInsensitiveComparing) {
+ custom_str::CustomString obj(CustomStringTest::mbstring1_);
+ custom_str::CustomString obj1(CustomStringTest::mbstring2_);
+ EXPECT_FALSE(obj.CompareIgnoreCase(obj1));
+ EXPECT_FALSE(obj.CompareIgnoreCase(CustomStringTest::mbstring2_.c_str()));
+}
+
+TEST_F(
+ CustomStringTest,
+ AddSameMultiByteStringsToCustomString_ExpectCorrectCaseInsensitiveComparing) {
+ const size_t kSizeStr = 8;
+ uint8_t array[] = {0xD1,
+ 0x82,
+ 0xD0,
+ 0xB5,
+ 0xD1,
+ 0x81,
+ 0xD0,
+ 0xA2}; // String contains russian word "тесТ"
+ std::string mbstring = CreateMultibyteString(array, kSizeStr);
+ custom_str::CustomString obj(CustomStringTest::mbstring1_);
+ custom_str::CustomString obj1(mbstring);
+ EXPECT_TRUE(obj.CompareIgnoreCase(obj1));
+ EXPECT_TRUE(obj.CompareIgnoreCase(mbstring.c_str()));
+}
+
+} // namespace utils
+} // namespace components
+} // namespace test
diff --git a/src/components/utils/test/data_accessor_test.cc b/src/components/utils/test/data_accessor_test.cc
index 105ec8517f..b15310ff3f 100644
--- a/src/components/utils/test/data_accessor_test.cc
+++ b/src/components/utils/test/data_accessor_test.cc
@@ -39,31 +39,28 @@ namespace components {
namespace utils {
TEST(DataAccessorTest, CreateDataAccessor) {
-
- //arrange
+ // arrange
int test_value = 10;
sync_primitives::Lock testSet_lock_;
DataAccessor<int> testdata(test_value, testSet_lock_);
int data_from_testdata = testdata.GetData();
- //assert
+ // assert
EXPECT_EQ(test_value, data_from_testdata);
}
TEST(DataAccessorTest, CreateDataAccessor_MutexIsLocked_CannotLockItAgain) {
-
- //arrange
+ // arrange
int test_value = 10;
sync_primitives::Lock testSet_lock_;
DataAccessor<int> testdata(test_value, testSet_lock_);
- //assert
+ // assert
EXPECT_FALSE(testSet_lock_.Try());
}
TEST(DataAccessorTest, CopyDataAccessor_GetDataFromDataAccessors) {
-
- //arrange
+ // arrange
int test_value = 10;
sync_primitives::Lock testSet_lock_;
DataAccessor<int> testdata(test_value, testSet_lock_);
@@ -72,15 +69,15 @@ TEST(DataAccessorTest, CopyDataAccessor_GetDataFromDataAccessors) {
int data_from_testdata = testdata.GetData();
int data_from_testdata_copy = testdata_copy.GetData();
- //assert
+ // assert
EXPECT_EQ(data_from_testdata, data_from_testdata_copy);
EXPECT_FALSE(testSet_lock_.Try());
}
-TEST(DataAccessorTest,ChangedDataInDataAccessor_ChangeData_DataInDataAccessorIsChanged) {
-
- //arrange
+TEST(DataAccessorTest,
+ ChangedDataInDataAccessor_ChangeData_DataInDataAccessorIsChanged) {
+ // arrange
int test_value = 10;
sync_primitives::Lock testSet_lock_;
DataAccessor<int> testdata(test_value, testSet_lock_);
@@ -88,32 +85,31 @@ TEST(DataAccessorTest,ChangedDataInDataAccessor_ChangeData_DataInDataAccessorIsC
int data_from_testdata_after_change = testdata.GetData();
- //assert
+ // assert
EXPECT_EQ(test_value, data_from_testdata_after_change);
}
-TEST(DataAccessorTest, DeleteDataAccessor_CreatedOneDeleteOneThread_MutexIsUnlocked) {
-
- //arrange
+TEST(DataAccessorTest,
+ DeleteDataAccessor_CreatedOneDeleteOneThread_MutexIsUnlocked) {
+ // arrange
int test_value = 10;
sync_primitives::Lock testSet_lock_;
{
DataAccessor<int> testdata(test_value, testSet_lock_);
- //assert
+ // assert
EXPECT_FALSE(testSet_lock_.Try());
}
- //assert
+ // assert
EXPECT_TRUE(testSet_lock_.Try());
testSet_lock_.Release();
-
}
-TEST(DataAccessorTest, DeleteDataAccessor_CreatedThreadAndCopyDeleteBothThreads_MutexIsUnlocked) {
-
- //arrange
+TEST(DataAccessorTest,
+ DeleteDataAccessor_CreatedThreadAndCopyDeleteBothThreads_MutexIsUnlocked) {
+ // arrange
int test_value = 10;
sync_primitives::Lock testSet_lock_;
{
@@ -121,18 +117,16 @@ TEST(DataAccessorTest, DeleteDataAccessor_CreatedThreadAndCopyDeleteBothThreads_
{
DataAccessor<int> testdata_copy(testdata);
- //assert
+ // assert
EXPECT_FALSE(testSet_lock_.Try());
}
- //assert
+ // assert
EXPECT_FALSE(testSet_lock_.Try());
-
}
- //assert
+ // assert
EXPECT_TRUE(testSet_lock_.Try());
testSet_lock_.Release();
-
}
} // namespace utils
diff --git a/src/components/utils/test/date_time_test.cc b/src/components/utils/test/date_time_test.cc
index db2b101825..fc34b7a998 100644
--- a/src/components/utils/test/date_time_test.cc
+++ b/src/components/utils/test/date_time_test.cc
@@ -39,165 +39,163 @@ namespace utils {
using namespace date_time;
TEST(DateTimeTest, GetCurrentTime) {
-
- //arrange
+ // arrange
const TimevalStruct time1 = date_time::DateTime::getCurrentTime();
- //assert
+ // assert
ASSERT_NE(0, time1.tv_sec);
ASSERT_GE(time1.tv_usec, 0);
- //act
+ // act
const TimevalStruct time2 = date_time::DateTime::getCurrentTime();
- //assert
+ // assert
ASSERT_NE(0, time2.tv_sec);
ASSERT_GE(time2.tv_usec, 0);
ASSERT_GE(time2.tv_sec, time1.tv_sec);
}
TEST(DateTimeTest, GetSecs) {
- //arrange
+ // arrange
TimevalStruct time;
time.tv_sec = 1;
- time.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_MILLISECONDS;
+ time.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_MILLISECOND;
- //assert
+ // assert
ASSERT_EQ(1, date_time::DateTime::getSecs(time));
}
TEST(DateTimeTest, GetmSecs) {
- //arrange
+ // arrange
TimevalStruct time;
time.tv_sec = 1;
- time.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_MILLISECONDS;
+ time.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_MILLISECOND;
- int64_t expect_value = time.tv_sec
- * date_time::DateTime::MILLISECONDS_IN_SECOND
- + time.tv_usec / date_time::DateTime::MICROSECONDS_IN_MILLISECONDS;
- //assert
+ int64_t expect_value =
+ time.tv_sec * date_time::DateTime::MILLISECONDS_IN_SECOND +
+ time.tv_usec / date_time::DateTime::MICROSECONDS_IN_MILLISECOND;
+ // assert
ASSERT_EQ(expect_value, date_time::DateTime::getmSecs(time));
}
TEST(DateTimeTest, GetuSecs) {
- //arrange
+ // arrange
TimevalStruct time;
time.tv_sec = 3;
time.tv_usec = 4;
- int64_t expect_value = time.tv_sec
- * date_time::DateTime::MILLISECONDS_IN_SECOND
- * date_time::DateTime::MICROSECONDS_IN_MILLISECONDS + time.tv_usec;
- //assert
+ int64_t expect_value = time.tv_sec *
+ date_time::DateTime::MILLISECONDS_IN_SECOND *
+ date_time::DateTime::MICROSECONDS_IN_MILLISECOND +
+ time.tv_usec;
+ // assert
ASSERT_EQ(expect_value, date_time::DateTime::getuSecs(time));
}
TEST(DateTimeTest, GetuSecsmSecs) {
- //arrange
+ // arrange
TimevalStruct time;
time.tv_sec = 5;
time.tv_usec = 6;
- int64_t expect_value = date_time::DateTime::getuSecs(time)
- / date_time::DateTime::MICROSECONDS_IN_MILLISECONDS;
+ int64_t expect_value = date_time::DateTime::getuSecs(time) /
+ date_time::DateTime::MICROSECONDS_IN_MILLISECOND;
- //assert
+ // assert
ASSERT_EQ(expect_value, date_time::DateTime::getmSecs(time));
}
TEST(DateTimeTest, CalculateTimeSpan) {
- //arrange
+ // arrange
const TimevalStruct time = date_time::DateTime::getCurrentTime();
const uint32_t sleep_time_mSec = 10;
- usleep(sleep_time_mSec * date_time::DateTime::MICROSECONDS_IN_MILLISECONDS);
+ usleep(sleep_time_mSec * date_time::DateTime::MICROSECONDS_IN_MILLISECOND);
- //assert
+ // assert
ASSERT_GE(date_time::DateTime::calculateTimeSpan(time), sleep_time_mSec);
}
TEST(DateTimeTest, CalculateTimeDiff) {
-
- //arrange
+ // arrange
TimevalStruct time1;
time1.tv_sec = 1;
- time1.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_MILLISECONDS;
+ time1.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_MILLISECOND;
TimevalStruct time2;
time2.tv_sec = 3;
- time2.tv_usec = 4 * date_time::DateTime::MICROSECONDS_IN_MILLISECONDS;
+ time2.tv_usec = 4 * date_time::DateTime::MICROSECONDS_IN_MILLISECOND;
- //time2 to time1
+ // time2 to time1
TimevalStruct diff1;
diff1.tv_sec = time2.tv_sec - time1.tv_sec;
diff1.tv_usec = time2.tv_usec - time1.tv_usec;
- const int64_t mSecDiff = static_cast<int64_t>(diff1.tv_sec) * 1000
- + diff1.tv_usec / 1000;
+ const int64_t mSecDiff =
+ static_cast<int64_t>(diff1.tv_sec) * 1000 + diff1.tv_usec / 1000;
- //assert
+ // assert
ASSERT_EQ(mSecDiff, date_time::DateTime::calculateTimeDiff(time2, time1));
- //time1 to time2
+ // time1 to time2
TimevalStruct diff2;
diff2.tv_sec = time1.tv_sec - time2.tv_sec;
diff2.tv_usec = time1.tv_usec - time2.tv_usec;
- const int64_t mSecDiff2 = -(static_cast<int64_t>(diff2.tv_sec) * 1000
- + diff2.tv_usec / 1000);
+ const int64_t mSecDiff2 =
+ -(static_cast<int64_t>(diff2.tv_sec) * 1000 + diff2.tv_usec / 1000);
- //assert
+ // assert
ASSERT_EQ(mSecDiff2, date_time::DateTime::calculateTimeDiff(time1, time2));
}
TEST(DateTimeTest, CalculateEqualTimeDiff) {
TimevalStruct time1;
time1.tv_sec = 1;
- time1.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_MILLISECONDS;
+ time1.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_MILLISECOND;
TimevalStruct time2;
time2.tv_sec = 1;
- time2.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_MILLISECONDS;
+ time2.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_MILLISECOND;
ASSERT_EQ(0, date_time::DateTime::calculateTimeDiff(time2, time1));
ASSERT_EQ(0, date_time::DateTime::calculateTimeDiff(time1, time2));
}
TEST(DateTimeTest, compareTime) {
-
- //arrange
+ // arrange
TimevalStruct time1;
time1.tv_sec = 1;
- time1.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_MILLISECONDS;
+ time1.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_MILLISECOND;
TimevalStruct time2;
time2.tv_sec = 2;
- time2.tv_usec = 4 * date_time::DateTime::MICROSECONDS_IN_MILLISECONDS;
+ time2.tv_usec = 4 * date_time::DateTime::MICROSECONDS_IN_MILLISECOND;
- //assert
+ // assert
ASSERT_EQ(LESS, date_time::DateTime::compareTime(time1, time2));
ASSERT_EQ(GREATER, date_time::DateTime::compareTime(time2, time1));
ASSERT_NE(EQUAL, date_time::DateTime::compareTime(time2, time1));
- //act
+ // act
TimevalStruct time3 = date_time::DateTime::Sub(time2, time1);
- //assert
+ // assert
ASSERT_EQ(EQUAL, date_time::DateTime::compareTime(time1, time3));
}
TEST(DateTimeTest, GetSecs_UsecConvertedInSec) {
- //arrange
+ // arrange
TimevalStruct time1;
time1.tv_sec = 0;
time1.tv_usec = date_time::DateTime::MICROSECONDS_IN_SECOND;
- //assert
+ // assert
ASSERT_EQ(1, date_time::DateTime::getSecs(time1));
}
TEST(DateTimeTest, compareTime_UsecConvertedInSec) {
- //arrange
+ // arrange
TimevalStruct time1;
time1.tv_sec = 1;
time1.tv_usec = 0;
@@ -206,14 +204,14 @@ TEST(DateTimeTest, compareTime_UsecConvertedInSec) {
time2.tv_sec = 0;
time2.tv_usec = date_time::DateTime::MICROSECONDS_IN_SECOND;
- //assert
+ // assert
ASSERT_EQ(1, date_time::DateTime::getSecs(time1));
ASSERT_EQ(1, date_time::DateTime::getSecs(time2));
ASSERT_EQ(EQUAL, date_time::DateTime::compareTime(time1, time2));
}
TEST(DateTimeTest, compareEqualTime_UsecConvertedInSec) {
- //arrange
+ // arrange
TimevalStruct time1;
time1.tv_sec = 1;
time1.tv_usec = 0;
@@ -222,12 +220,12 @@ TEST(DateTimeTest, compareEqualTime_UsecConvertedInSec) {
time2.tv_sec = 0;
time2.tv_usec = date_time::DateTime::MICROSECONDS_IN_SECOND;
- //assert
+ // assert
ASSERT_TRUE(date_time::DateTime::Equal(time1, time2));
}
TEST(DateTimeTest, compareLessTime_UsecConvertedInSec) {
- //arrange
+ // arrange
TimevalStruct time1;
time1.tv_sec = 1;
time1.tv_usec = 0;
@@ -236,12 +234,12 @@ TEST(DateTimeTest, compareLessTime_UsecConvertedInSec) {
time2.tv_sec = 0;
time2.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_SECOND;
- //assert
+ // assert
ASSERT_TRUE(date_time::DateTime::Less(time1, time2));
}
TEST(DateTimeTest, compareGreaterTime_UsecConvertedInSec) {
- //arrange
+ // arrange
TimevalStruct time1;
time1.tv_sec = 1;
time1.tv_usec = 0;
@@ -250,12 +248,12 @@ TEST(DateTimeTest, compareGreaterTime_UsecConvertedInSec) {
time2.tv_sec = 0;
time2.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_SECOND;
- //assert
+ // assert
ASSERT_TRUE(date_time::DateTime::Greater(time2, time1));
}
TEST(DateTimeTest, CalculateTimeSub_UsecConvertedInSec) {
- //arrange
+ // arrange
TimevalStruct time1;
time1.tv_sec = 1;
time1.tv_usec = 0;
@@ -266,12 +264,12 @@ TEST(DateTimeTest, CalculateTimeSub_UsecConvertedInSec) {
TimevalStruct time3 = date_time::DateTime::Sub(time2, time1);
- //assert
+ // assert
ASSERT_EQ(EQUAL, date_time::DateTime::compareTime(time1, time3));
}
TEST(DateTimeTest, CalculateTimeDiff_UsecConvertedInSec) {
- //arrange
+ // arrange
TimevalStruct time1;
time1.tv_sec = 2;
time1.tv_usec = 5 * date_time::DateTime::MICROSECONDS_IN_SECOND;
@@ -280,13 +278,13 @@ TEST(DateTimeTest, CalculateTimeDiff_UsecConvertedInSec) {
time2.tv_sec = 3;
time2.tv_usec = 1 * date_time::DateTime::MICROSECONDS_IN_SECOND;
- //assert
+ // assert
ASSERT_EQ(3000, date_time::DateTime::calculateTimeDiff(time2, time1));
ASSERT_EQ(3000, date_time::DateTime::calculateTimeDiff(time1, time2));
}
TEST(DateTimeTest, CalculateEqualTimeDiff_UsecConvertedInSec) {
- //arrange
+ // arrange
TimevalStruct time1;
time1.tv_sec = 2;
time1.tv_usec = 2 * date_time::DateTime::MICROSECONDS_IN_SECOND;
@@ -295,13 +293,13 @@ TEST(DateTimeTest, CalculateEqualTimeDiff_UsecConvertedInSec) {
time2.tv_sec = 3;
time2.tv_usec = 1 * date_time::DateTime::MICROSECONDS_IN_SECOND;
- //assert
+ // assert
ASSERT_EQ(0, date_time::DateTime::calculateTimeDiff(time2, time1));
ASSERT_EQ(0, date_time::DateTime::calculateTimeDiff(time1, time2));
}
TEST(DateTimeTest, CalculateEqualTimeSub_UsecConvertedInSec) {
- //arrange
+ // arrange
TimevalStruct time1;
time1.tv_sec = 3;
time1.tv_usec = 0;
@@ -316,12 +314,13 @@ TEST(DateTimeTest, CalculateEqualTimeSub_UsecConvertedInSec) {
TimevalStruct time_expected;
time_expected.tv_sec = 0;
time_expected.tv_usec = 0;
- //assert
+ // assert
ASSERT_EQ(EQUAL, date_time::DateTime::compareTime(time_expected, time3));
ASSERT_EQ(EQUAL, date_time::DateTime::compareTime(time_expected, time4));
}
-TEST(DateTimeTest, AddMilliseconds_SetMillisecondMultiplesSecond_ExpectChangeTime) {
+TEST(DateTimeTest,
+ AddMilliseconds_SetMillisecondMultiplesSecond_ExpectChangeTime) {
TimevalStruct time1;
time1.tv_sec = 3;
time1.tv_usec = 0;
@@ -331,7 +330,8 @@ TEST(DateTimeTest, AddMilliseconds_SetMillisecondMultiplesSecond_ExpectChangeTim
ASSERT_EQ(0, time1.tv_usec);
}
-TEST(DateTimeTest, AddMilliseconds_SetMillisecondNotMultiplesSecond_ExpectChangeTime) {
+TEST(DateTimeTest,
+ AddMilliseconds_SetMillisecondNotMultiplesSecond_ExpectChangeTime) {
TimevalStruct time1;
uint32_t milliseconds = 7500;
time1.tv_sec = 3;
@@ -341,7 +341,8 @@ TEST(DateTimeTest, AddMilliseconds_SetMillisecondNotMultiplesSecond_ExpectChange
ASSERT_EQ(500000, time1.tv_usec);
}
-TEST(DateTimeTest, AddMilliseconds_SetMilliSecondLessThenSeconds_ExpectChangeTime) {
+TEST(DateTimeTest,
+ AddMilliseconds_SetMilliSecondLessThenSeconds_ExpectChangeTime) {
TimevalStruct time1;
uint32_t milliseconds = 500;
time1.tv_sec = 3;
@@ -351,7 +352,8 @@ TEST(DateTimeTest, AddMilliseconds_SetMilliSecondLessThenSeconds_ExpectChangeTim
ASSERT_EQ(500000, time1.tv_usec);
}
-TEST(DateTimeTest, AddMilliseconds_SetMillisecondEqualNull_ExpectNotChangeTime) {
+TEST(DateTimeTest,
+ AddMilliseconds_SetMillisecondEqualNull_ExpectNotChangeTime) {
TimevalStruct time1;
uint32_t milliseconds = 0;
time1.tv_sec = 3;
@@ -371,32 +373,31 @@ TEST(DateTimeTest, AddMilliseconds_SetOverlowMicrosecond_ExpectChangeTime) {
ASSERT_EQ(100000, time1.tv_usec);
}
-TEST(DateTimeTest, Operator_minus_TimevalStruct_positive){
- TimevalStruct time1;
- TimevalStruct time2;
- TimevalStruct time3;
- time1.tv_sec = 3;
- time1.tv_usec = 0;
- time2.tv_sec = 3;
- time2.tv_usec = 0;
- time3.tv_sec = 2;
- time3.tv_usec = 9000000;
- ASSERT_EQ(0, date_time::DateTime::getSecs(time1 - time2));
- ASSERT_EQ(8000000, date_time::DateTime::getuSecs(time3 - time1));
+TEST(DateTimeTest, Operator_minus_TimevalStruct_positive) {
+ TimevalStruct time1;
+ TimevalStruct time2;
+ TimevalStruct time3;
+ time1.tv_sec = 3;
+ time1.tv_usec = 0;
+ time2.tv_sec = 3;
+ time2.tv_usec = 0;
+ time3.tv_sec = 2;
+ time3.tv_usec = 9000000;
+ ASSERT_EQ(0, date_time::DateTime::getSecs(time1 - time2));
+ ASSERT_EQ(8000000, date_time::DateTime::getuSecs(time3 - time1));
}
-TEST(DateTimeTest, Operator_minus_TimevalStruct_negative){
- TimevalStruct time1;
- TimevalStruct time2;
- time1.tv_sec = 3;
- time1.tv_usec = 0;
- time2.tv_sec = 2;
- time2.tv_usec = 9000000;
- ASSERT_NE(1, date_time::DateTime::getSecs(time1 - time2));
- ASSERT_NE(-8000000, date_time::DateTime::getSecs(time2 - time1));
+TEST(DateTimeTest, Operator_minus_TimevalStruct_negative) {
+ TimevalStruct time1;
+ TimevalStruct time2;
+ time1.tv_sec = 3;
+ time1.tv_usec = 0;
+ time2.tv_sec = 2;
+ time2.tv_usec = 9000000;
+ ASSERT_NE(1, date_time::DateTime::getSecs(time1 - time2));
+ ASSERT_NE(-8000000, date_time::DateTime::getSecs(time2 - time1));
}
-
} // namespace utils
} // namespace components
} // namespace test
diff --git a/src/components/utils/test/file_system_test.cc b/src/components/utils/test/file_system_test.cc
index 4e36608f9f..1d90721680 100644
--- a/src/components/utils/test/file_system_test.cc
+++ b/src/components/utils/test/file_system_test.cc
@@ -32,6 +32,9 @@
#include <algorithm>
#include <fstream>
+#include <vector>
+#include <string>
+
#include "gtest/gtest.h"
#include "utils/file_system.h"
@@ -39,10 +42,24 @@ namespace test {
namespace components {
namespace utils {
+typedef std::vector<std::string> StringArray;
+
using namespace file_system;
-TEST(FileSystemTest, CreateDeleteDirectory) {
+namespace {
+StringArray MergeStringsToArray(const std::string& first,
+ const std::string& second) {
+ StringArray array_of_strings;
+ array_of_strings.reserve(2);
+
+ array_of_strings.push_back(first);
+ array_of_strings.push_back(second);
+ return array_of_strings;
+}
+}
+
+TEST(FileSystemTest, CreateDeleteDirectory) {
ASSERT_FALSE(DirectoryExists("./Test directory"));
// Directory creation
CreateDirectory("./Test directory");
@@ -69,12 +86,12 @@ TEST(FileSystemTest, CreateDirectoryTwice) {
// Directory removing
EXPECT_TRUE(RemoveDirectory("./Test directory", false));
- //try delete directory again
+ // Try to delete directory again
EXPECT_FALSE(RemoveDirectory("./Test directory", false));
EXPECT_FALSE(DirectoryExists("./Test directory"));
}
-TEST(FileSystemTest,DeleteDirectoryRecursively) {
+TEST(FileSystemTest, DeleteDirectoryRecursively) {
ASSERT_FALSE(DirectoryExists("./Test directory"));
// Create directories
CreateDirectory("./Test directory");
@@ -119,9 +136,8 @@ TEST(FileSystemTest, CreateDirectoryRecursivelyDeleteRecursively) {
TEST(FileSystemTest, TwiceCreateDirectoryRecursivelyDeleteRecursivelyOnce) {
ASSERT_FALSE(DirectoryExists("./Test directory"));
// Create directories recursively
- EXPECT_TRUE(
- CreateDirectoryRecursively(
- "./Test directory/Test directory 2/Test directory 3"));
+ EXPECT_TRUE(CreateDirectoryRecursively(
+ "./Test directory/Test directory 2/Test directory 3"));
// Check that all directories are created
EXPECT_TRUE(DirectoryExists("./Test directory"));
@@ -136,9 +152,8 @@ TEST(FileSystemTest, TwiceCreateDirectoryRecursivelyDeleteRecursivelyOnce) {
IsDirectory("./Test directory/Test directory 2/Test directory 3"));
// Create directories recursively second time
- EXPECT_TRUE(
- CreateDirectoryRecursively(
- "./Test directory/Test directory 2/Test directory 3"));
+ EXPECT_TRUE(CreateDirectoryRecursively(
+ "./Test directory/Test directory 2/Test directory 3"));
EXPECT_TRUE(DirectoryExists("./Test directory"));
@@ -167,7 +182,7 @@ TEST(FileSystemTest, CreateDeleteFile) {
// Delete file
EXPECT_TRUE(DeleteFile("./test file"));
- //try delete file again
+ // Try to delete file again
EXPECT_FALSE(DeleteFile("./test file"));
EXPECT_FALSE(FileExists("./test file"));
}
@@ -264,11 +279,11 @@ TEST(FileSystemTest, OpenFileWriteInFileStream) {
delete test_file;
// Read data from file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
-// Check data
+ // Check data
for (uint i = 0; i < data_size; ++i) {
EXPECT_EQ(data[i], result[i]);
}
@@ -300,7 +315,7 @@ TEST(FileSystemTest, CannotWriteInClosedFileStream) {
delete test_file;
// Read data from file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_TRUE(result.empty());
@@ -327,7 +342,7 @@ TEST(FileSystemTest, CreateWriteInFileStream_CreateFileAgain_FileRewritten) {
Close(test_file);
delete test_file;
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
@@ -351,7 +366,7 @@ TEST(FileSystemTest, CreateFileStream_WriteInFile_FileStreamNotClosed) {
// Write data in file
uint32_t data_size = 4;
- std::vector < uint8_t > data;
+ std::vector<uint8_t> data;
for (uint i = 0; i < data_size; ++i) {
data.push_back(i);
}
@@ -363,7 +378,7 @@ TEST(FileSystemTest, CreateFileStream_WriteInFile_FileStreamNotClosed) {
Close(test_file);
delete test_file;
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
@@ -371,7 +386,8 @@ TEST(FileSystemTest, CreateFileStream_WriteInFile_FileStreamNotClosed) {
EXPECT_FALSE(FileExists("./test file"));
}
-TEST(FileSystemTest, CreateFileStream_WriteInFileWriteInFileStream_FileIncludeLastData) {
+TEST(FileSystemTest,
+ CreateFileStream_WriteInFileWriteInFileStream_FileIncludeLastData) {
ASSERT_FALSE(FileExists("./test file"));
// Create and open file
@@ -380,7 +396,7 @@ TEST(FileSystemTest, CreateFileStream_WriteInFileWriteInFileStream_FileIncludeLa
// Write data in file
uint32_t data_size = 4;
- std::vector < uint8_t > data;
+ std::vector<uint8_t> data;
for (uint i = 0; i < data_size; ++i) {
data.push_back(i);
}
@@ -399,7 +415,7 @@ TEST(FileSystemTest, CreateFileStream_WriteInFileWriteInFileStream_FileIncludeLa
Close(test_file);
delete test_file;
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
@@ -451,7 +467,7 @@ TEST(FileSystemTest, WriteInFilestreamTwice_FileRewritten) {
delete test_file;
delete test_file_2;
// Check file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
// Check data
@@ -503,7 +519,7 @@ TEST(FileSystemTest, WriteInFilestreamConsequentially_FileRewritten) {
delete test_file;
delete test_file_2;
// Check file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
@@ -529,7 +545,7 @@ TEST(FileSystemTest, CreateFileTwiceWriteInFileTwice) {
EXPECT_TRUE(FileExists("./test file"));
uint32_t data_size = 4;
- std::vector < uint8_t > data;
+ std::vector<uint8_t> data;
for (uint i = 0; i < data_size; ++i) {
data.push_back(i);
}
@@ -540,7 +556,7 @@ TEST(FileSystemTest, CreateFileTwiceWriteInFileTwice) {
EXPECT_TRUE(CreateFile("./test file"));
EXPECT_TRUE(CreateFile("./test file"));
- std::vector < uint8_t > data_2;
+ std::vector<uint8_t> data_2;
for (uint i = 0; i < data_size; ++i) {
data_2.push_back(i + data_size);
}
@@ -549,7 +565,7 @@ TEST(FileSystemTest, CreateFileTwiceWriteInFileTwice) {
EXPECT_TRUE(Write("./test file", data_2));
// Check file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
@@ -574,21 +590,21 @@ TEST(FileSystemTest, WriteInFileTwiceFileRewritten) {
// Write data in file
uint32_t data_size = 4;
- std::vector < uint8_t > data;
+ std::vector<uint8_t> data;
for (uint i = 0; i < data_size; ++i) {
data.push_back(i);
}
EXPECT_TRUE(Write("./test file", data));
// Write data to file again
- std::vector < uint8_t > data_2;
+ std::vector<uint8_t> data_2;
for (uint i = 0; i < data_size; ++i) {
data_2.push_back(i + data_size);
}
EXPECT_TRUE(Write("./test file", data_2));
// Check file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
@@ -610,7 +626,7 @@ TEST(FileSystemTest, WriteDataInTheEndOfFile) {
EXPECT_TRUE(FileExists("./test file"));
int32_t data_size = 4;
- std::vector < uint8_t > data;
+ std::vector<uint8_t> data;
for (int i = 0; i < data_size; ++i) {
data.push_back(i);
}
@@ -619,7 +635,7 @@ TEST(FileSystemTest, WriteDataInTheEndOfFile) {
EXPECT_TRUE(Write("./test file", data));
// Write in file second time
- std::vector < uint8_t > data_2;
+ std::vector<uint8_t> data_2;
for (int i = 0; i < data_size; ++i) {
data_2.push_back(i + data_size);
}
@@ -628,11 +644,11 @@ TEST(FileSystemTest, WriteDataInTheEndOfFile) {
EXPECT_TRUE(Write("./test file", data_2, std::ios_base::app));
// Check file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
- std::vector < uint8_t > data_check;
+ std::vector<uint8_t> data_check;
for (int i = 0; i < 2 * data_size; ++i) {
data_check.push_back(i);
}
@@ -647,7 +663,8 @@ TEST(FileSystemTest, WriteDataInTheEndOfFile) {
EXPECT_FALSE(FileExists("./test file"));
}
-TEST(FileSystemTest, WriteInFileStream_WriteInFileInTheEndOfFile_FileIncludeBothData) {
+TEST(FileSystemTest,
+ WriteInFileStream_WriteInFileInTheEndOfFile_FileIncludeBothData) {
ASSERT_FALSE(FileExists("./test file"));
// Create and open file
@@ -656,7 +673,7 @@ TEST(FileSystemTest, WriteInFileStream_WriteInFileInTheEndOfFile_FileIncludeBoth
// Write data in file
uint32_t data_size = 4;
- std::vector < uint8_t > data;
+ std::vector<uint8_t> data;
for (uint i = 0; i < data_size; ++i) {
data.push_back(i);
}
@@ -669,7 +686,7 @@ TEST(FileSystemTest, WriteInFileStream_WriteInFileInTheEndOfFile_FileIncludeBoth
delete test_file;
// Write in file second time
- std::vector < uint8_t > data_2;
+ std::vector<uint8_t> data_2;
for (uint i = 0; i < data_size; ++i) {
data_2.push_back(i + data_size);
}
@@ -678,11 +695,11 @@ TEST(FileSystemTest, WriteInFileStream_WriteInFileInTheEndOfFile_FileIncludeBoth
EXPECT_TRUE(Write("./test file", data_2, std::ios_base::app));
// Check file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
- std::vector < uint8_t > data_check;
+ std::vector<uint8_t> data_check;
for (uint i = 0; i < 2 * data_size; ++i) {
data_check.push_back(i);
}
@@ -717,7 +734,7 @@ TEST(FileSystemTest, OpenFileStreamForRead_WriteInFileStream) {
EXPECT_FALSE(test_file->is_open());
// Read data from file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
@@ -738,7 +755,7 @@ TEST(FileSystemTest, OpenFileStreamForRead_WriteInFileStream) {
TEST(FileSystemTest, WriteFileNotExists) {
ASSERT_FALSE(FileExists("./test file"));
- unsigned char tmp[] = { 't', 'e', 's', 't' };
+ unsigned char tmp[] = {'t', 'e', 's', 't'};
std::vector<unsigned char> data(tmp, tmp + 4);
EXPECT_TRUE(Write("./test file", data));
// File now exists
@@ -751,7 +768,7 @@ TEST(FileSystemTest, WriteFileReadFile) {
ASSERT_FALSE(FileExists("./test file"));
EXPECT_TRUE(CreateFile("./test file"));
- unsigned char tmp[] = { 't', 'e', 's', 't' };
+ unsigned char tmp[] = {'t', 'e', 's', 't'};
std::vector<unsigned char> data(tmp, tmp + 4);
EXPECT_TRUE(Write("./test file", data));
@@ -770,12 +787,12 @@ TEST(FileSystemTest, WriteBinaryDataReadBinaryFile) {
ASSERT_FALSE(FileExists("./test file"));
EXPECT_TRUE(CreateFile("./test file"));
- uint8_t tmp[] = { 1, 2, 3, 4};
+ uint8_t tmp[] = {1, 2, 3, 4};
std::vector<uint8_t> data(tmp, tmp + 4);
EXPECT_TRUE(WriteBinaryFile("./test file", data));
// Read data from file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
EXPECT_EQ(data, result);
@@ -790,7 +807,7 @@ TEST(FileSystemTest, WriteBinaryDataTwice_FileRewritten) {
EXPECT_TRUE(FileExists("./test file"));
int32_t data_size = 4;
- std::vector < uint8_t > data;
+ std::vector<uint8_t> data;
for (int i = 0; i < data_size; ++i) {
data.push_back(i);
}
@@ -798,7 +815,7 @@ TEST(FileSystemTest, WriteBinaryDataTwice_FileRewritten) {
EXPECT_TRUE(WriteBinaryFile("./test file", data));
// Write in file second time
- std::vector < uint8_t > data_2;
+ std::vector<uint8_t> data_2;
for (int i = 0; i < data_size; ++i) {
data_2.push_back(i + data_size);
}
@@ -807,7 +824,7 @@ TEST(FileSystemTest, WriteBinaryDataTwice_FileRewritten) {
EXPECT_TRUE(WriteBinaryFile("./test file", data_2));
// Check file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
@@ -825,7 +842,7 @@ TEST(FileSystemTest, WriteBinaryDataFileNotExists) {
ASSERT_FALSE(FileExists("./test file"));
int32_t data_size = 4;
- std::vector < uint8_t > data;
+ std::vector<uint8_t> data;
for (int i = 0; i < data_size; ++i) {
data.push_back(i);
}
@@ -839,13 +856,13 @@ TEST(FileSystemTest, WriteBinaryDataFileNotExists) {
TEST(FileSystemTest, WriteDataAsBinaryData) {
ASSERT_FALSE(FileExists("./test file"));
- unsigned char tmp[] = { 't', 'e', 's', 't' };
+ unsigned char tmp[] = {'t', 'e', 's', 't'};
std::vector<unsigned char> data(tmp, tmp + 4);
EXPECT_TRUE(WriteBinaryFile("./test file", data));
ASSERT_TRUE(FileExists("./test file"));
// Check file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
@@ -867,7 +884,7 @@ TEST(FileSystemTest, WriteEmptyData) {
ASSERT_TRUE(FileExists("./test file"));
// Check file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_TRUE(result.empty());
@@ -884,7 +901,7 @@ TEST(FileSystemTest, WriteEmptyDataAsBinaryData) {
ASSERT_TRUE(FileExists("./test file"));
// Check file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_TRUE(result.empty());
@@ -896,14 +913,14 @@ TEST(FileSystemTest, WriteBinaryData_WriteDataInTheEndOfFile) {
ASSERT_FALSE(FileExists("./test file"));
// Write binary file
- unsigned char tmp[] = { 't', 'e', 's', 't' };
+ unsigned char tmp[] = {'t', 'e', 's', 't'};
std::vector<unsigned char> data(tmp, tmp + 4);
EXPECT_TRUE(WriteBinaryFile("./test file", data));
ASSERT_TRUE(FileExists("./test file"));
// Write in file second time
int32_t data_size = 4;
- std::vector < uint8_t > data_2;
+ std::vector<uint8_t> data_2;
for (int i = 0; i < data_size; ++i) {
data_2.push_back(i);
}
@@ -912,7 +929,7 @@ TEST(FileSystemTest, WriteBinaryData_WriteDataInTheEndOfFile) {
EXPECT_TRUE(Write("./test file", data_2, std::ios_base::app));
// Check file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
@@ -934,7 +951,7 @@ TEST(FileSystemTest, CreateFile_WriteDataWithFlagOpenForReading) {
EXPECT_TRUE(CreateFile("./test file"));
// Write data in file
int32_t data_size = 4;
- std::vector < uint8_t > data;
+ std::vector<uint8_t> data;
for (int i = 0; i < data_size; ++i) {
data.push_back(i);
}
@@ -942,7 +959,7 @@ TEST(FileSystemTest, CreateFile_WriteDataWithFlagOpenForReading) {
EXPECT_TRUE(FileExists("./test file"));
// Check file
- std::vector < uint8_t > result;
+ std::vector<uint8_t> result;
EXPECT_TRUE(ReadBinaryFile("./test file", result));
EXPECT_FALSE(result.empty());
@@ -956,12 +973,13 @@ TEST(FileSystemTest, CreateFile_WriteDataWithFlagOpenForReading) {
EXPECT_FALSE(FileExists("./test file"));
}
-TEST(FileSystemTest, FileDoesNotCreated_WriteFileWithFlagOpenForReadingIsImpossible) {
+TEST(FileSystemTest,
+ FileIsntCreated_WriteFileWithFlagOpenForReadingIsImpossible) {
ASSERT_FALSE(FileExists("./test file"));
// Write data in file is impossible
int32_t data_size = 4;
- std::vector < uint8_t > data;
+ std::vector<uint8_t> data;
for (int i = 0; i < data_size; ++i) {
data.push_back(i);
}
@@ -974,7 +992,7 @@ TEST(FileSystemTest, WriteFileGetSize) {
EXPECT_TRUE(CreateFile("./test file"));
EXPECT_EQ(0, FileSize("./test file"));
- unsigned char tmp[] = { 't', 'e', 's', 't' };
+ unsigned char tmp[] = {'t', 'e', 's', 't'};
std::vector<unsigned char> data(tmp, tmp + 4);
EXPECT_TRUE(Write("./test file", data));
@@ -1007,7 +1025,7 @@ TEST(FileSystemTest, GetFileModificationTime) {
uint64_t modif_time = GetFileModificationTime("./test file");
EXPECT_LE(0ul, modif_time);
- std::vector < uint8_t > data(1, 1);
+ std::vector<uint8_t> data(1, 1);
EXPECT_TRUE(WriteBinaryFile("./test file", data));
EXPECT_LE(0ul, GetFileModificationTime("./test file"));
@@ -1021,7 +1039,7 @@ TEST(FileSystemTest, ListFiles) {
ASSERT_FALSE(DirectoryExists("./Test directory"));
CreateDirectory("./Test directory");
- std::vector < std::string > list;
+ std::vector<std::string> list;
list = ListFiles("./Test directory");
EXPECT_TRUE(list.empty());
@@ -1046,7 +1064,7 @@ TEST(FileSystemTest, ListFilesIncludeSubdirectory) {
ASSERT_FALSE(DirectoryExists("./Test directory"));
CreateDirectoryRecursively("./Test directory/Test directory 2/");
- std::vector < std::string > list;
+ std::vector<std::string> list;
list = ListFiles("./Test directory");
EXPECT_FALSE(list.empty());
EXPECT_EQ(1u, list.size());
@@ -1060,7 +1078,7 @@ TEST(FileSystemTest, ListFilesDoesNotIncludeFilesInSubdirectory) {
ASSERT_FALSE(DirectoryExists("./Test directory"));
CreateDirectoryRecursively("./Test directory/Test directory 2/");
- std::vector < std::string > list;
+ std::vector<std::string> list;
list = ListFiles("./Test directory");
EXPECT_FALSE(list.empty());
@@ -1079,14 +1097,13 @@ TEST(FileSystemTest, ListFilesDoesNotIncludeFilesInSubdirectory) {
}
TEST(FileSystemTest, GetAvailableDiskSpace) {
-
// Get available disk space before directory with file creaction and after
uint64_t available_space = GetAvailableDiskSpace(".");
EXPECT_NE(0u, available_space);
ASSERT_FALSE(DirectoryExists("./Test directory"));
CreateDirectory("./Test directory");
- unsigned char tmp[] = { 't', 'e', 's', 't' };
+ unsigned char tmp[] = {'t', 'e', 's', 't'};
std::vector<unsigned char> data(tmp, tmp + 4);
EXPECT_TRUE(Write("./Test directory/test file", data));
@@ -1115,7 +1132,7 @@ TEST(FileSystemTest, DirectorySize) {
// Get size of nonempty directory with empty file
EXPECT_EQ(0u, DirectorySize("./Test directory"));
- unsigned char tmp[] = { 't', 'e', 's', 't' };
+ unsigned char tmp[] = {'t', 'e', 's', 't'};
std::vector<unsigned char> data(tmp, tmp + 4);
EXPECT_TRUE(Write("./Test directory/test file", data));
@@ -1159,7 +1176,7 @@ TEST(FileSystemTest, DeleteAllContentInDirectory) {
DirectoryExists("./Test directory/Test directory 2/Test directory 3"));
EXPECT_FALSE(DirectoryExists("./Test directory/Test directory 2"));
- std::vector < std::string > list;
+ std::vector<std::string> list;
list = ListFiles("./Test directory");
EXPECT_TRUE(list.empty());
@@ -1169,6 +1186,91 @@ TEST(FileSystemTest, DeleteAllContentInDirectory) {
EXPECT_FALSE(DirectoryExists("./Test directory"));
}
+TEST(FileSystemTest, GetAbsolutePath) {
+ const std::string& abs_path = GetAbsolutePath(".");
+ // Getting absolute current path from system
+ const std::string& absolute_current_path = CurrentWorkingDirectory();
+ EXPECT_EQ('/', abs_path[0]);
+ EXPECT_EQ(absolute_current_path, abs_path);
+}
+
+TEST(FileSystemTest,
+ GetAbsolutePath_InvalidOrEmptyPathName_EmptyAbsolutePathName) {
+ // Array of invalid paths
+ const StringArray rel_path = MergeStringsToArray("not_exists_dir", " ");
+
+ // Check
+ for (size_t i = 0; i < rel_path.size(); ++i) {
+ const std::string& path_for_check = GetAbsolutePath(rel_path[i]);
+ EXPECT_EQ("", path_for_check);
+ }
+}
+
+TEST(FileSystemTest, GetAbsolutePath_ValidRelPaths_CorrectAbsolutePath) {
+ // Array of relative dirs
+ const StringArray rel_path = MergeStringsToArray(
+ "first_level_path", "first_level_path/second_level_path1");
+
+ // Create some directories in current
+ CreateDirectoryRecursively(rel_path[1]);
+ // Get absolute current dir
+ const std::string& absolute_current_dir = GetAbsolutePath(".");
+ // Check
+ for (size_t i = 0; i < rel_path.size(); ++i) {
+ // Concating rel_path to current dir path
+ const std::string& correct_absolute_path =
+ absolute_current_dir + "/" + rel_path[i];
+ // Get absolute path for rel dir
+ const std::string& path_for_check = GetAbsolutePath(rel_path[i]);
+ EXPECT_EQ(correct_absolute_path, path_for_check);
+ }
+ // Cleanup after test case
+ if (DirectoryExists(rel_path[0])) {
+ RemoveDirectory(rel_path[0], true);
+ }
+}
+
+TEST(FileSystemTest,
+ GetAbsolutePath_ValidRelPathsFromParrentDir_CorrectAbsolutePath) {
+ // Array of relative dirs
+ const StringArray rel_path = MergeStringsToArray(
+ "../first_level_path", "../first_level_path/second_level_path1");
+
+ // Create some directories in parrent of this
+ CreateDirectoryRecursively(rel_path[1]);
+
+ // Get absolute parrent dir
+ const std::string& absolute_parrent_dir = GetAbsolutePath("../");
+ // Check
+ for (size_t i = 0; i < rel_path.size(); ++i) {
+ // Concatenation rel_path to current dir path
+ const std::string& relative_dir_name = rel_path[i].substr(3);
+ const std::string& correct_absolute_path =
+ absolute_parrent_dir + "/" + relative_dir_name;
+ // Get absolute path for rel dir
+ const std::string& path_for_check = GetAbsolutePath(rel_path[i]);
+ EXPECT_EQ(correct_absolute_path, path_for_check);
+ }
+ // Cleanup after test case
+ if (DirectoryExists(rel_path[0])) {
+ RemoveDirectory(rel_path[0], true);
+ }
+}
+
+TEST(FileSystemTest, GetAbsolutePath_TrickiPath_CorrectAbsolutePath) {
+ // Array of relative dirs
+ const StringArray rel_path =
+ MergeStringsToArray("../src/../../application_manager/../utils/test",
+ "../../../components/utils/test");
+
+ const std::string& absolute_current_path = CurrentWorkingDirectory();
+ for (size_t i = 0; i < rel_path.size(); ++i) {
+ // Get absolute path for rel dir
+ const std::string& path_for_check = GetAbsolutePath(rel_path[i]);
+ EXPECT_EQ(absolute_current_path, path_for_check);
+ }
+}
+
} // namespace utils
} // namespace components
} // namespace test
diff --git a/src/components/utils/test/generated_code_with_sqlite_test.cc b/src/components/utils/test/generated_code_with_sqlite_test.cc
new file mode 100644
index 0000000000..0feb040f49
--- /dev/null
+++ b/src/components/utils/test/generated_code_with_sqlite_test.cc
@@ -0,0 +1,217 @@
+/* Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <sqlite3.h>
+#include "gtest/gtest.h"
+#include "utils/generated_code_with_sqlite_test.h"
+
+namespace rpc {
+
+class GeneratedCodeTest : public ::testing::Test {
+ public:
+ static void SetUpTestCase() {
+ sqlite3* conn;
+ sqlite3_open((kDatabaseName + ".sqlite").c_str(), &conn);
+ sqlite3_exec(conn, kEndpointsCreation.c_str(), NULL, NULL, NULL);
+ sqlite3_exec(conn, kEndpointsContent.c_str(), NULL, NULL, NULL);
+ sqlite3_exec(conn, kAppPoliciesCreation.c_str(), NULL, NULL, NULL);
+ sqlite3_exec(conn, kGroupsCreation.c_str(), NULL, NULL, NULL);
+ sqlite3_close(conn);
+ }
+
+ static void TearDownTestCase() {
+ remove((kDatabaseName + ".sqlite").c_str());
+ }
+
+ static const std::string kDatabaseName;
+ static const std::string kEndpointsCreation;
+ static const std::string kEndpointsContent;
+ static const std::string kAppPoliciesCreation;
+ static const std::string kGroupsCreation;
+};
+
+const std::string GeneratedCodeTest::kDatabaseName = "test_db";
+
+const std::string GeneratedCodeTest::kEndpointsCreation =
+ "CREATE TABLE Endpoints ("
+ "endpoint_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ "service_id VARCHAR(45) NOT NULL,"
+ "application_id VARCHAR(45),"
+ "url VARCHAR(45) NOT NULL,"
+ "is_default INTEGER NOT NULL CHECK(is_default>=0))";
+
+const std::string GeneratedCodeTest::kEndpointsContent =
+ "INSERT INTO Endpoints "
+ "VALUES (1, '0x07', null, 'http://url.example.com', 1)";
+
+const std::string GeneratedCodeTest::kAppPoliciesCreation =
+ "CREATE TABLE AppPolicies ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ "application_id VARCHAR(45),"
+ "priority VARCHAR(45),"
+ "is_default INTEGER NOT NULL CHECK(is_default>=0))";
+
+const std::string GeneratedCodeTest::kGroupsCreation =
+ "CREATE TABLE Groups ("
+ "id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"
+ "application_id VARCHAR(45) NOT NULL,"
+ "group_name VARCHAR(45) NOT NULL )";
+
+TEST_F(GeneratedCodeTest,
+ FindSectionEndpoints_OpenDBSetDefaultUrl_ExpectDefaultUrl) {
+ // arrange
+ dbms::SQLDatabase db(GeneratedCodeTest::kDatabaseName);
+
+ // assert
+ EXPECT_TRUE(db.Open());
+ policy_table::ServiceEndpoints ep;
+
+ // assert
+ EXPECT_TRUE(policy_table::FindSection(&db, ep));
+ EXPECT_EQ(1u, ep.size());
+
+ // act
+ std::string url = ep["0x07"]["default"].front();
+
+ // assert
+ EXPECT_EQ("http://url.example.com", url);
+}
+
+TEST_F(GeneratedCodeTest,
+ RemoveSectionEndpoints_RemoveSectionEndpoints_Expect0EndPoints) {
+ // arrange
+ dbms::SQLDatabase db(GeneratedCodeTest::kDatabaseName);
+
+ // assert
+ EXPECT_TRUE(db.Open());
+
+ // act
+ policy_table::ServiceEndpoints ep;
+
+ // assert
+ EXPECT_TRUE(policy_table::RemoveSection(&db, ep));
+ dbms::SQLQuery sqlquery(&db);
+
+ // act
+ std::string check_query = "select count (*) from endpoints";
+
+ // assert
+ EXPECT_TRUE(sqlquery.Prepare(check_query));
+ EXPECT_TRUE(sqlquery.Exec());
+ // Index for binding starts from 1, index for results starts from 0
+ EXPECT_EQ(0, sqlquery.GetInteger(0));
+}
+
+TEST_F(GeneratedCodeTest,
+ UpdateSectionEndpoints_SetUrlPoint_ExpectPointEqualsUrl) {
+ // arrange
+ dbms::SQLDatabase db(GeneratedCodeTest::kDatabaseName);
+
+ // assert
+ EXPECT_TRUE(db.Open());
+
+ // act
+ std::string test_url = "http://url.example.com";
+
+ policy_table::URL urls;
+ urls.push_back(test_url);
+
+ policy_table::URLList urllist;
+ urllist["default"] = urls;
+
+ policy_table::ServiceEndpoints ep;
+ ep["0x07"] = urllist;
+
+ // assert
+ EXPECT_TRUE(policy_table::UpdateSection(&db, ep));
+
+ dbms::SQLQuery sqlquery(&db);
+ std::string num_of_records_check = "select count (*) from endpoints";
+
+ // assert
+ EXPECT_TRUE(sqlquery.Prepare(num_of_records_check));
+ EXPECT_TRUE(sqlquery.Exec());
+ // Index for binding starts from 1, index for results starts from 0
+ EXPECT_EQ(1, sqlquery.GetInteger(0));
+ EXPECT_TRUE(sqlquery.Reset());
+
+ // act
+ std::string url_check_query = "select * from endpoints";
+
+ // assert
+ EXPECT_TRUE(sqlquery.Prepare(url_check_query));
+ EXPECT_TRUE(sqlquery.Exec());
+ // Index for binding starts from 1, index for results starts from 0
+ EXPECT_EQ(test_url, sqlquery.GetString(3));
+}
+
+TEST_F(GeneratedCodeTest,
+ UpdateSectionAppPolicies_SetAppParams_ExpectDBHasThem) {
+ // arrange
+ dbms::SQLDatabase db(GeneratedCodeTest::kDatabaseName);
+
+ // assert
+ EXPECT_TRUE(db.Open());
+
+ // act
+ policy_table::ApplicationPolicies ap;
+ const std::string application_id = "12345678";
+ ap[application_id].groups.push_back("Base-4");
+ ap[application_id].priority = policy_table::P_NORMAL;
+
+ // assert
+ EXPECT_TRUE(policy_table::UpdateSection(&db, ap));
+
+ // act
+ dbms::SQLQuery sqlquery(&db);
+
+ // assert
+ EXPECT_TRUE(sqlquery.Prepare("select count (*) from AppPolicies"));
+ EXPECT_TRUE(sqlquery.Exec());
+ // Index for binding starts from 1, index for results starts from 0
+ EXPECT_EQ(1, sqlquery.GetInteger(0));
+ EXPECT_TRUE(sqlquery.Reset());
+
+ EXPECT_TRUE(sqlquery.Prepare("select count (*) from Groups"));
+ EXPECT_TRUE(sqlquery.Exec());
+ // Index for binding starts from 1, index for results starts from 0
+ EXPECT_EQ(1, sqlquery.GetInteger(0));
+ EXPECT_TRUE(sqlquery.Reset());
+
+ EXPECT_TRUE(sqlquery.Prepare(
+ "select application_id from Groups where group_name='Base-4'"));
+ EXPECT_TRUE(sqlquery.Exec());
+ // Index for binding starts from 1, index for results starts from 0
+ EXPECT_EQ(application_id, sqlquery.GetString(0));
+ EXPECT_TRUE(sqlquery.Reset());
+}
+
+} // namespace rpc
diff --git a/src/components/utils/test/include/utils/generated_code_with_sqlite_test.h b/src/components/utils/test/include/utils/generated_code_with_sqlite_test.h
new file mode 100644
index 0000000000..8455639c07
--- /dev/null
+++ b/src/components/utils/test/include/utils/generated_code_with_sqlite_test.h
@@ -0,0 +1,407 @@
+/* Copyright (c) 2013, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_GENERATED_CODE_WITH_SQLITE_TEST_H_
+#define SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_GENERATED_CODE_WITH_SQLITE_TEST_H_
+
+#include <string>
+#include "policy/policy_table/types.h"
+#include "rpc_base/rpc_base.h"
+#include "utils/sqlite_wrapper/sql_query.h"
+#include "utils/sqlite_wrapper/sql_database.h"
+
+namespace policy_table = rpc::policy_table_interface_base;
+namespace dbms = utils::dbms;
+
+namespace rpc {
+namespace policy_table_interface_base {
+
+bool FindSection(dbms::SQLDatabase* db, policy_table::ServiceEndpoints& ep) {
+ /*
+ * Following table structure is assumed:
+ *
+ * table Endpoints
+ * index, service_type, application_id, url, is_default
+ *
+ * If url belongs to default section, application_id should be null and
+ *is_defaut = true
+ * Otherwise application_id should be set and is_default = false
+ */
+
+ std::string query = "select * from Endpoints";
+
+ dbms::SQLQuery sqlquery(db);
+ sqlquery.Prepare(query);
+ if (!sqlquery.Exec()) {
+ return false;
+ }
+
+ /*
+ * Following query result is assumed (data from wp1_policy_table.json):
+ * 1, 0x07, null, http://applinkqa.trafficmanager.net/api/policies, true
+ */
+
+ policy_table::URL urls;
+ urls.push_back(sqlquery.GetString(3));
+
+ policy_table::URLList urllist;
+ if (sqlquery.GetBoolean(4)) {
+ urllist["default"] = urls;
+ } else {
+ urllist[sqlquery.GetString(2)] = urls;
+ }
+
+ policy_table::ServiceEndpoints new_ep;
+ new_ep[sqlquery.GetString(1)] = urllist;
+
+ ep = new_ep;
+
+ return true;
+}
+
+bool FindSection(dbms::SQLDatabase* db, policy_table::ModuleConfig& mc) {
+ policy_table::ModuleConfig new_mc;
+ FindSection(db, new_mc.endpoints);
+ mc = new_mc;
+
+ return true;
+}
+
+bool RemoveSection(dbms::SQLDatabase* db,
+ const policy_table::ApplicationPolicies& ap) {
+ dbms::SQLQuery sqlquery(db);
+ bool is_policies_removed = sqlquery.Exec("delete from AppPolicies");
+ // bool is_nicknames_removed = sqlquery.Exec("delete from Nicknames");
+ bool is_groups_removed = sqlquery.Exec("delete from Groups");
+
+ return is_policies_removed /*&& is_nicknames_removed*/ && is_groups_removed;
+}
+
+bool RemoveSection(dbms::SQLDatabase* db,
+ const policy_table::ServiceEndpoints& ep) {
+ std::string query = "delete from Endpoints";
+ dbms::SQLQuery sqlquery(db);
+ return sqlquery.Exec(query);
+}
+
+bool RemoveSection(dbms::SQLDatabase* db,
+ const policy_table::ModuleConfig& mc) {
+ // std::string query = "delete * from ModuleConfig";
+ // sqlite::SQLQuery sqlquery(db);
+ // sqlquery.Exec(query);
+
+ return RemoveSection(db, mc.endpoints);
+}
+
+bool RemoveSection(dbms::SQLDatabase* db,
+ const policy_table::FunctionalGroupings& fg) {
+ std::string query = "delete from FunctionalGroups";
+ dbms::SQLQuery sqlquery(db);
+ return sqlquery.Exec(query);
+}
+
+bool UpdateSection(dbms::SQLDatabase* db,
+ const policy_table::ServiceEndpoints& ep) {
+ /*
+ * Following table structure is assumed:
+ *
+ * table Endpoints
+ * index, service_type, application_id, url, is_default
+ *
+ * If url belongs to default section, application_id should be null and
+ *is_defaut = true
+ * Otherwise application_id should be set and is_default = false
+ */
+
+ // According to documentation, we have to REPLACE this part on update coming,
+ // so we delete all data first;
+ if (!RemoveSection(db, ep)) {
+ return false;
+ }
+
+ std::string query = "insert into Endpoints values(?,?,?,?,?)";
+ dbms::SQLQuery sqlquery(db);
+ sqlquery.Prepare(query);
+
+ policy_table::ServiceEndpoints::const_iterator it_ep = ep.begin();
+ policy_table::ServiceEndpoints::const_iterator it_ep_end = ep.end();
+
+ // TODO: use define for int from stdint.h
+ for (int index = 1; it_ep != it_ep_end; ++it_ep, ++index) {
+ policy_table::URLList::const_iterator it_urllist = (*it_ep).second.begin();
+ policy_table::URLList::const_iterator it_urllist_end =
+ (*it_ep).second.end();
+
+ for (; it_urllist != it_urllist_end; ++it_urllist) {
+ policy_table::URL::const_iterator it_url = (*it_urllist).second.begin();
+ policy_table::URL::const_iterator it_url_end = (*it_urllist).second.end();
+
+ for (; it_url != it_url_end; ++it_url) {
+ // Index binding
+ sqlquery.Bind(0, index);
+
+ // Service type binding
+ sqlquery.Bind(1, (*it_ep).first);
+
+ // Application_id and is_default binding
+ std::string url_list_name = (*it_urllist).first;
+ if ("default" == url_list_name) {
+ sqlquery.Bind(2, "null");
+ sqlquery.Bind(4, true);
+ } else {
+ sqlquery.Bind(2, url_list_name);
+ sqlquery.Bind(4, false);
+ }
+
+ // URL binding
+ sqlquery.Bind(3, (*it_url));
+
+ if (sqlquery.Exec()) {
+ sqlquery.Reset();
+ } else {
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+bool UpdateSection(dbms::SQLDatabase* db,
+ const policy_table::ModuleConfig& mc) {
+ UpdateSection(db, mc.endpoints);
+ return true;
+}
+
+bool UpdateSection(dbms::SQLDatabase* db,
+ const policy_table::FunctionalGroupings& fg) {
+ /*
+ * Following table structure is assumed:
+ *
+ * table Rpcs - list of all available RPC commands
+ * index, rpc
+ *
+ * table HmiLevels -list of all available hmi levels
+ * index, hmi_level
+ *
+ * table Groups - list of functional group names
+ * index, group_name
+ *
+ * table FunctionalGroups - list of functional groups
+ * index, group_name_id, rpc_id, hmi_level_id
+ *
+ */
+
+ // According to documentation, we have to REPLACE this part on update coming,
+ // so we delete all data first;
+ if (!RemoveSection(db, fg)) {
+ return false;
+ }
+
+ std::string query =
+ "insert into FunctionalGroups values("
+ "?,"
+ "(select index from Groups where group_name=?),"
+ "(select index from Rpcs where rpc=?),"
+ "(select index from HmiLevels where hmi_levels=?)";
+
+ dbms::SQLQuery sqlquery(db);
+ sqlquery.Prepare(query);
+
+ policy_table::FunctionalGroupings::const_iterator it_fg = fg.begin();
+ policy_table::FunctionalGroupings::const_iterator it_fg_end = fg.end();
+
+ for (int index = 1; it_fg != it_fg_end; ++it_fg, ++index) {
+ policy_table::Rpcs rpcs = (*it_fg).second;
+ policy_table::Rpc::const_iterator it_rpcs = rpcs.rpcs.begin();
+ policy_table::Rpc::const_iterator it_rpcs_end = rpcs.rpcs.end();
+
+ for (; it_rpcs != it_rpcs_end; ++it_rpcs) {
+ policy_table::RpcParameters rpc_params = (*it_rpcs).second;
+
+ policy_table::HmiLevels::const_iterator it_hmi_levels =
+ rpc_params.hmi_levels.begin();
+ policy_table::HmiLevels::const_iterator it_hmi_levels_end =
+ rpc_params.hmi_levels.end();
+
+ for (; it_hmi_levels != it_hmi_levels_end; ++it_hmi_levels) {
+ // Index binding
+ sqlquery.Bind(0, index);
+
+ // Group name binding
+ sqlquery.Bind(1, (*it_fg).first);
+
+ // RPC name binding
+ sqlquery.Bind(2, (*it_rpcs).first);
+
+ // Hmi levels binding
+ sqlquery.Bind(3, (*it_hmi_levels));
+ if (sqlquery.Exec()) {
+ sqlquery.Reset();
+ } else {
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+bool UpdateSection(dbms::SQLDatabase* db, const policy_table::Table& pt) {
+ UpdateSection(db, pt.policy_table.module_config);
+ UpdateSection(db, pt.policy_table.functional_groupings);
+ return true;
+}
+
+bool UpdateSection(dbms::SQLDatabase* db,
+ const policy_table::ApplicationPolicies& ap) {
+ /*
+ * Following structure is assumed:
+ *
+ * table Groups - list of functional groups for application
+ * index, application_id, functional_group_id
+ *
+ * table Nicknames - list of nickname for application
+ * index, application_id, nickname
+ *
+ * table AppPolicies - policies for applications
+ * index, application_id, priority, is_default
+ *
+ */
+
+ // According to documentation, we have to REPLACE this part on update coming,
+ // so we delete all data first;
+ if (!RemoveSection(db, ap)) {
+ return false;
+ }
+
+ std::string groups_query =
+ "insert into Groups values ("
+ "?,"
+ "?,"
+ "?)";
+ dbms::SQLQuery groups_sqlquery(db);
+ groups_sqlquery.Prepare(groups_query);
+
+ std::string nicknames_query = "insert into Nicknames values(?,?,?)";
+ dbms::SQLQuery nicknames_sqlquery(db);
+ nicknames_sqlquery.Prepare(nicknames_query);
+
+ std::string app_policies_query = "insert into AppPolicies values(?,?,?,?)";
+ dbms::SQLQuery app_policies_sqlquery(db);
+ app_policies_sqlquery.Prepare(app_policies_query);
+
+ policy_table::ApplicationPolicies::const_iterator it_ap = ap.begin();
+ policy_table::ApplicationPolicies::const_iterator it_ap_end = ap.end();
+
+ for (int index = 0; it_ap != it_ap_end; ++it_ap, ++index) {
+ // Index binding for AppPolicies table
+ app_policies_sqlquery.Bind(0, index);
+
+ std::string app_policy_name = (*it_ap).first;
+ bool is_default_policy = "default" == app_policy_name ? true : false;
+ if (is_default_policy) {
+ app_policies_sqlquery.Bind(1, "null");
+ app_policies_sqlquery.Bind(3, true);
+ } else {
+ app_policies_sqlquery.Bind(1, app_policy_name);
+ app_policies_sqlquery.Bind(3, false);
+ }
+
+ // Struct contains groups, nicknames, priority for application/default
+ // section
+ policy_table::ApplicationParams app_params = (*it_ap).second;
+
+ // Priority binding
+ app_policies_sqlquery.Bind(2, app_params.priority);
+ app_policies_sqlquery.Bind(2, "Dummy priority parameter");
+
+ // Add record to AppPolicies table
+ if (app_policies_sqlquery.Exec()) {
+ app_policies_sqlquery.Reset();
+ } else {
+ return false;
+ }
+
+ if (!is_default_policy) {
+ // Seems, there is generator issue with Optional type inheritance
+ // It should have pubic inheritance from type T to have array
+ // begin/end methods in its interface
+ // To be discussed with I.Kozyrenko
+
+ // policy_table::StringArray::const_iterator it_nicknames =
+ // app_params.nicknames.begin();
+ // policy_table::StringArray::const_iterator it_nicknames_end =
+ // app_params.nicknames.end();
+ //
+ // for (int nick_index = 0;it_nicknames != it_nicknames_end; ++
+ // it_nicknames, ++nick_index) {
+ // nicknames_sqlquery.Bind(0, nick_index);
+ // nicknames_sqlquery.Bind(1, app_policy_name);
+ //
+ // nicknames_sqlquery.Bind(2, (*it_nicknames));
+ //
+ // if (nicknames_sqlquery.Exec()) {
+ // nicknames_sqlquery.Reset();
+ // } else {
+ // return false;
+ // }
+ // }
+
+ policy_table::Strings::const_iterator it_groups =
+ app_params.groups.begin();
+ policy_table::Strings::const_iterator it_groups_end =
+ app_params.groups.end();
+
+ for (int group_index = 0; it_groups != it_groups_end;
+ ++it_groups, ++group_index) {
+ groups_sqlquery.Bind(0, group_index);
+ groups_sqlquery.Bind(1, app_policy_name);
+ groups_sqlquery.Bind(2, (*it_groups));
+
+ if (groups_sqlquery.Exec()) {
+ groups_sqlquery.Reset();
+ } else {
+ return false;
+ }
+ }
+ }
+ }
+
+ return true;
+}
+
+} // namespace policy_table_interface_base
+} // namespace rpc
+
+#endif // SRC_COMPONENTS_POLICY_TEST_POLICY_INCLUDE_GENERATED_CODE_WITH_SQLITE_TEST_H_
diff --git a/src/components/utils/test/include/utils/mock_timer_task.h b/src/components/utils/test/include/utils/mock_timer_task.h
new file mode 100644
index 0000000000..06ac893c81
--- /dev/null
+++ b/src/components/utils/test/include/utils/mock_timer_task.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef SRC_COMPONENTS_UTILS_TEST_INCLUDE_UTILS_MOCK_TIMER_TASK_H_
+#define SRC_COMPONENTS_UTILS_TEST_INCLUDE_UTILS_MOCK_TIMER_TASK_H_
+
+#include "gmock/gmock.h"
+#include "utils/timer_task.h"
+
+namespace test {
+namespace components {
+namespace timer_test {
+
+class MockTimerTask : public timer::TimerTask {
+ public:
+ MOCK_CONST_METHOD0(run, void());
+};
+
+} // namespace timer_test
+} // namespace components
+} // namespace test
+
+#endif // SRC_COMPONENTS_UTILS_TEST_INCLUDE_UTILS_MOCK_TIMER_TASK_H_
diff --git a/src/components/utils/test/include/utils/test_handler.h b/src/components/utils/test/include/utils/test_handler.h
new file mode 100644
index 0000000000..34127b7bdd
--- /dev/null
+++ b/src/components/utils/test/include/utils/test_handler.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <queue>
+
+#include "utils/macro.h"
+#include "utils/threads/message_loop_thread.h"
+
+namespace test {
+namespace components {
+namespace utils_test {
+
+typedef std::queue<bool> BoolQueue;
+typedef threads::MessageLoopThread<BoolQueue> TestLoopThread;
+
+class TestHandler : public TestLoopThread::Handler {
+ virtual void Handle(const BoolQueue::value_type test_value) OVERRIDE {}
+};
+
+} // namespace utils_test
+} // namespace components
+} // namespace test
diff --git a/src/components/utils/test/log_message_loop_thread_test.cc b/src/components/utils/test/log_message_loop_thread_test.cc
index 789bf62f45..14515961bb 100644
--- a/src/components/utils/test/log_message_loop_thread_test.cc
+++ b/src/components/utils/test/log_message_loop_thread_test.cc
@@ -42,34 +42,16 @@ namespace utils {
using namespace ::logger;
using ::testing::_;
-TEST(LogMessageLoopThread,CreateLogMessageSingleton) {
- //if logger_status is LoggerThreadNotCreated or LoggerThreadCreated,
- // creation of singleton will be impossible
- logger::logger_status = CreatingLoggerThread;
-
- LogMessageLoopThread *instance_1 = LogMessageLoopThread::instance();
- LogMessageLoopThread *instance_2 = LogMessageLoopThread::instance();
-
- //assert
- EXPECT_EQ(instance_1, instance_2);
-
- LogMessageLoopThread::destroy();
-
- EXPECT_FALSE(LogMessageLoopThread::exists());
- logger::logger_status = LoggerThreadNotCreated;
-}
-
TEST(LogMessageLoopThread, DestroyLogMessage_loggerStatusDeletingLogger) {
logger::logger_status = CreatingLoggerThread;
- LogMessageLoopThread::instance();
-
- //assert
+ LogMessageLoopThread* loop_thread = new LogMessageLoopThread();
+ // assert
EXPECT_EQ(CreatingLoggerThread, logger::logger_status);
- //act
- LogMessageLoopThread::destroy();
+ // act
+ delete loop_thread;
- //assert
+ // assert
EXPECT_EQ(DeletingLoggerThread, logger::logger_status);
logger::logger_status = LoggerThreadNotCreated;
@@ -84,10 +66,10 @@ TEST(LogMessageLoopThread, HandleNeverCalled) {
logger::logger_status = CreatingLoggerThread;
MockLogMessageTest mmock;
- EXPECT_CALL(mmock,Handle(_)).Times(0);
- LogMessageLoopThread::instance();
+ EXPECT_CALL(mmock, Handle(_)).Times(0);
+ LogMessageLoopThread* loop_thread = new LogMessageLoopThread();
- LogMessageLoopThread::destroy();
+ delete loop_thread;
logger::logger_status = LoggerThreadNotCreated;
}
diff --git a/src/components/utils/test/message_loop_thread_test.cc b/src/components/utils/test/message_loop_thread_test.cc
new file mode 100644
index 0000000000..c2a8c6851d
--- /dev/null
+++ b/src/components/utils/test/message_loop_thread_test.cc
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "utils/test_handler.h"
+
+namespace test {
+namespace components {
+namespace utils_test {
+
+TEST(MessageLoopThreadTest, GetMessageQueueSize_AddValueToQueue_CorrectSize) {
+ TestHandler test_handler;
+ TestLoopThread message_loop_thread("test", &test_handler);
+
+ ASSERT_EQ(0u, message_loop_thread.GetMessageQueueSize());
+
+ message_loop_thread.PostMessage(true);
+ ASSERT_EQ(1u, message_loop_thread.GetMessageQueueSize());
+}
+
+} // namespace utils_test
+} // namespace components
+} // namespace test
diff --git a/src/components/utils/test/message_queue_test.cc b/src/components/utils/test/message_queue_test.cc
index 8ce7196b07..d80016c6a8 100644
--- a/src/components/utils/test/message_queue_test.cc
+++ b/src/components/utils/test/message_queue_test.cc
@@ -43,21 +43,20 @@ using ::utils::MessageQueue;
class MessageQueueTest : public testing::Test {
public:
MessageQueueTest()
- : test_val_1("Hello,"),
- test_val_2("Beautiful "),
- test_val_3("World!"),
- test_line(""),
- check_value(false) {
- }
+ : test_val_1("Hello,")
+ , test_val_2("Beautiful ")
+ , test_val_3("World!")
+ , test_line("")
+ , check_value(false) {}
void add_one_element_to_queue();
void extract_from_queue();
void add_three_elements_to_queue();
void ShutDownQueue();
- static void* add_one_element_to_queue_helper(void *context);
- static void* extract_from_queue_helper(void *context);
- static void* add_three_elements_to_queue_helper(void *context);
- static void* ShutDownQueue_helper(void *context);
+ static void* add_one_element_to_queue_helper(void* context);
+ static void* extract_from_queue_helper(void* context);
+ static void* add_three_elements_to_queue_helper(void* context);
+ static void* ShutDownQueue_helper(void* context);
protected:
MessageQueue<std::string> test_queue;
@@ -96,20 +95,20 @@ void MessageQueueTest::ShutDownQueue() {
pthread_exit(NULL);
}
-void* MessageQueueTest::add_one_element_to_queue_helper(void *context) {
- (reinterpret_cast<MessageQueueTest *>(context))->add_one_element_to_queue();
+void* MessageQueueTest::add_one_element_to_queue_helper(void* context) {
+ (reinterpret_cast<MessageQueueTest*>(context))->add_one_element_to_queue();
return NULL;
}
-void* MessageQueueTest::extract_from_queue_helper(void *context) {
- (reinterpret_cast<MessageQueueTest *>(context))->extract_from_queue();
+void* MessageQueueTest::extract_from_queue_helper(void* context) {
+ (reinterpret_cast<MessageQueueTest*>(context))->extract_from_queue();
return NULL;
}
-void* MessageQueueTest::add_three_elements_to_queue_helper(void *context) {
- (reinterpret_cast<MessageQueueTest *>(context))->add_three_elements_to_queue();
+void* MessageQueueTest::add_three_elements_to_queue_helper(void* context) {
+ (reinterpret_cast<MessageQueueTest*>(context))->add_three_elements_to_queue();
return NULL;
}
-void* MessageQueueTest::ShutDownQueue_helper(void *context) {
- (reinterpret_cast<MessageQueueTest *>(context))->ShutDownQueue();
+void* MessageQueueTest::ShutDownQueue_helper(void* context) {
+ (reinterpret_cast<MessageQueueTest*>(context))->ShutDownQueue();
return NULL;
}
@@ -119,9 +118,13 @@ TEST_F(MessageQueueTest, DefaultCtorTest_ExpectEmptyQueueCreated) {
ASSERT_EQ(test_value, test_queue.empty());
}
-TEST_F(MessageQueueTest, MessageQueuePushThreeElementsTest_ExpectThreeElementsAdded) {
+TEST_F(MessageQueueTest,
+ MessageQueuePushThreeElementsTest_ExpectThreeElementsAdded) {
pthread_t thread1;
- pthread_create(&thread1, NULL, &MessageQueueTest::add_three_elements_to_queue_helper, this);
+ pthread_create(&thread1,
+ NULL,
+ &MessageQueueTest::add_three_elements_to_queue_helper,
+ this);
pthread_join(thread1, NULL);
// check if 3 elements were added successfully
ASSERT_EQ(3u, test_queue.size());
@@ -140,12 +143,15 @@ TEST_F(MessageQueueTest, NotEmptyMessageQueueResetTest_ExpectEmptyQueue) {
ASSERT_EQ(0u, test_queue.size());
}
-TEST_F(MessageQueueTest, MessageQueuePopOneElementTest_ExpectOneElementRemovedFromQueue) {
+TEST_F(MessageQueueTest,
+ MessageQueuePopOneElementTest_ExpectOneElementRemovedFromQueue) {
pthread_t thread1;
pthread_t thread2;
// Creating threads with thread function mentioned above
- pthread_create(&thread1, NULL, &MessageQueueTest::add_one_element_to_queue_helper, this);
- pthread_create(&thread2, NULL, &MessageQueueTest::extract_from_queue_helper, this);
+ pthread_create(
+ &thread1, NULL, &MessageQueueTest::add_one_element_to_queue_helper, this);
+ pthread_create(
+ &thread2, NULL, &MessageQueueTest::extract_from_queue_helper, this);
// Primary thread waits until thread 2 to be finished
pthread_join(thread2, NULL);
// Check if first element was removed successfully
@@ -154,7 +160,8 @@ TEST_F(MessageQueueTest, MessageQueuePopOneElementTest_ExpectOneElementRemovedFr
ASSERT_EQ(0u, test_queue.size());
}
-TEST_F(MessageQueueTest, MessageQueueShutdownTest_ExpectMessageQueueWillBeShutDown) {
+TEST_F(MessageQueueTest,
+ MessageQueueShutdownTest_ExpectMessageQueueWillBeShutDown) {
pthread_t thread1;
// Creating thread with thread function mentioned above
pthread_create(&thread1, NULL, &MessageQueueTest::ShutDownQueue_helper, this);
diff --git a/src/components/utils/test/messagemeter_test.cc b/src/components/utils/test/messagemeter_test.cc
index 6c13ab345e..69db658542 100644
--- a/src/components/utils/test/messagemeter_test.cc
+++ b/src/components/utils/test/messagemeter_test.cc
@@ -1,5 +1,5 @@
/*
-* Copyright (c) 2014, Ford Motor Company
+* Copyright (c) 2015, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
@@ -40,44 +40,40 @@
#include "utils/messagemeter.h"
#include "utils/date_time.h"
-namespace test {
-namespace components {
-namespace utils {
+namespace test {
+namespace components {
+namespace utils {
// Pair of values <second, msecond>
typedef std::pair<int, int> TimePair;
-const TimePair testing_time_pairs[] = { TimePair(0, 50),
- TimePair(0, 100),
- TimePair(0, 200),
- TimePair(0, 500),
- TimePair(0, 900),
- TimePair(1, 0),
- TimePair(1, 500) };
-
-class MessageMeterTest: public ::testing::TestWithParam<TimePair> {
+const TimePair testing_time_pairs[] = {TimePair(0, 50),
+ TimePair(0, 100),
+ TimePair(0, 200),
+ TimePair(0, 500),
+ TimePair(0, 900),
+ TimePair(1, 0),
+ TimePair(1, 500)};
+
+class MessageMeterTest : public ::testing::TestWithParam<TimePair> {
protected:
void SetUp() OVERRIDE {
- usecs = date_time::DateTime::MICROSECONDS_IN_MILLISECONDS;
+ usecs = date_time::DateTime::MICROSECONDS_IN_MILLISECOND;
id1 = 0x0;
id2 = 0xABCDEF;
id3 = 0xFEBCDA;
const TimePair time_pair = GetParam();
- EXPECT_GT(usecs,
- time_pair.second) << "Wrong time (msecs) value";
+ EXPECT_GT(usecs, time_pair.second) << "Wrong time (msecs) value";
time_range.tv_sec = time_pair.first;
time_range.tv_usec = time_pair.second * usecs;
- EXPECT_LT(0,
- date_time::DateTime::getuSecs(time_range))
+ EXPECT_LT(0, date_time::DateTime::getuSecs(time_range))
<< "Wrong test case with null range value";
meter.set_time_range(time_range);
- // Get range in msec less than original for correct waitng in tests
- time_range_msecs = date_time::DateTime::getmSecs(time_range) * 0.95;
- }
- void TearDown() OVERRIDE {
+ time_range_msecs = date_time::DateTime::getmSecs(time_range);
}
+ void TearDown() OVERRIDE {}
::utils::MessageMeter<int> meter;
TimevalStruct time_range = {0, 0};
int64_t time_range_msecs;
@@ -87,29 +83,28 @@ class MessageMeterTest: public ::testing::TestWithParam<TimePair> {
TEST(MessageMeterTest, DefaultTimeRange) {
const ::utils::MessageMeter<int> default_meter;
- const TimevalStruct time_second {1, 0};
+ const TimevalStruct time_second{1, 0};
EXPECT_EQ(time_second, default_meter.time_range());
}
TEST(MessageMeterTest, TimeRangeSetter) {
::utils::MessageMeter<int> meter;
- TimevalStruct time_range {0, 0};
+ TimevalStruct time_range{0, 0};
const int test_count_secs = 1000;
// Skip 1000th msec value as wrong for TimevalStruct
const int test_count_msecs = 999;
for (int sec = test_count_secs; sec >= 0; --sec) {
for (int msec = test_count_msecs; msec >= 0; --msec) {
time_range.tv_sec = sec;
- time_range.tv_usec = msec * date_time::DateTime::MICROSECONDS_IN_MILLISECONDS;
+ time_range.tv_usec =
+ msec * date_time::DateTime::MICROSECONDS_IN_MILLISECOND;
// Setter TimevalStruct
meter.set_time_range(time_range);
- EXPECT_EQ(time_range,
- meter.time_range()) << sec << "." << msec << " sec";
+ EXPECT_EQ(time_range, meter.time_range()) << sec << "." << msec << " sec";
// Setter mSecs
meter.set_time_range(sec * date_time::DateTime::MILLISECONDS_IN_SECOND +
msec);
- EXPECT_EQ(time_range,
- meter.time_range()) << sec << "." << msec << " sec";
+ EXPECT_EQ(time_range, meter.time_range()) << sec << "." << msec << " sec";
}
}
}
@@ -118,160 +113,148 @@ TEST(MessageMeterTest, AddingWithNullTimeRange) {
::utils::MessageMeter<int> meter;
const int id1 = 1;
const int id2 = 2;
- const TimevalStruct null_time_range {0, 0};
+ const TimevalStruct null_time_range{0, 0};
meter.set_time_range(null_time_range);
for (int i = 0; i < 10000; ++i) {
// 1st Connection
- EXPECT_EQ(0u,
- meter.TrackMessage(id1));
- EXPECT_EQ(0u,
- meter.Frequency(id1));
+ EXPECT_EQ(0u, meter.TrackMessage(id1));
+ EXPECT_EQ(0u, meter.Frequency(id1));
// 2d Connection
- EXPECT_EQ(0u,
- meter.TrackMessage(id2));
- EXPECT_EQ(0u,
- meter.Frequency(id2));
+ EXPECT_EQ(0u, meter.TrackMessage(id2));
+ EXPECT_EQ(0u, meter.Frequency(id2));
}
}
-TEST_P(MessageMeterTest, AddingOverPeriod) {
+TEST_P(MessageMeterTest, TrackMessage_AddingOverPeriod_CorrectCountOfMessages) {
size_t messages = 0;
const TimevalStruct start_time = date_time::DateTime::getCurrentTime();
// Add messages for less range period
- while (date_time::DateTime::calculateTimeSpan(start_time)
- < time_range_msecs) {
+ int64_t time_span;
+ while ((time_span = date_time::DateTime::calculateTimeSpan(start_time)) <
+ time_range_msecs) {
++messages;
- EXPECT_EQ(messages,
- meter.TrackMessage(id1));
- EXPECT_EQ(messages,
- meter.Frequency(id1));
+
+ size_t tracked_frequency = meter.TrackMessage(id1);
+ size_t frequency = meter.Frequency(id1);
+
+ EXPECT_GE(messages, tracked_frequency)
+ << "Tracked messages can`t be over cycles.";
+
+ if (messages > frequency) {
+ EXPECT_GE(time_range_msecs, time_span);
+ break;
+ }
+ EXPECT_EQ(tracked_frequency, frequency);
}
}
-TEST_P(MessageMeterTest, AddingOverPeriod_MultiIds) {
+TEST_P(MessageMeterTest,
+ TrackMessage_AddingOverPeriodMultiIds_CorrectCountOfMessages) {
size_t messages = 0;
const TimevalStruct start_time = date_time::DateTime::getCurrentTime();
// Add messages for less range period
- while (date_time::DateTime::calculateTimeSpan(start_time)
- < time_range_msecs) {
+ int64_t time_span;
+ while ((time_span = date_time::DateTime::calculateTimeSpan(start_time)) <
+ time_range_msecs) {
++messages;
- // 1st Connection
- EXPECT_EQ(messages,
- meter.TrackMessage(id1));
- EXPECT_EQ(messages,
- meter.Frequency(id1));
- // 2d Connection
- EXPECT_EQ(messages,
- meter.TrackMessage(id2));
- EXPECT_EQ(messages,
- meter.Frequency(id2));
-
- // 3d Connection
- EXPECT_EQ(messages,
- meter.TrackMessage(id3));
- EXPECT_EQ(messages,
- meter.Frequency(id3));
+ size_t tracked_frequency_id1 = meter.TrackMessage(id1);
+ size_t tracked_frequency_id2 = meter.TrackMessage(id2);
+ size_t tracked_frequency_id3 = meter.TrackMessage(id3);
+ size_t frequency_id1 = meter.Frequency(id1);
+ size_t frequency_id2 = meter.Frequency(id2);
+ size_t frequency_id3 = meter.Frequency(id3);
+
+ EXPECT_GE(messages, tracked_frequency_id1)
+ << "Tracked messages can`t be over cycles.";
+ EXPECT_GE(messages, tracked_frequency_id2)
+ << "Tracked messages can`t be over cycles.";
+ EXPECT_GE(messages, tracked_frequency_id3)
+ << "Tracked messages can`t be over cycles.";
+
+ if (messages > frequency_id1 || messages > frequency_id2 ||
+ messages > frequency_id3) {
+ EXPECT_GE(time_range_msecs, time_span);
+ break;
+ }
+ EXPECT_EQ(tracked_frequency_id1, frequency_id1);
+ EXPECT_EQ(tracked_frequency_id2, frequency_id2);
+ EXPECT_EQ(tracked_frequency_id3, frequency_id3);
}
}
-TEST_P(MessageMeterTest, CountingOverPeriod) {
+TEST_P(MessageMeterTest, Frequency_CountingOverPeriod_CorrectCountOfMessages) {
const size_t one_message = 1;
const TimevalStruct start_time = date_time::DateTime::getCurrentTime();
- EXPECT_EQ(one_message,
- meter.TrackMessage(id1));
- EXPECT_EQ(one_message,
- meter.TrackMessage(id2));
- EXPECT_EQ(one_message,
- meter.TrackMessage(id3));
- const int sleep_usecs = 500;
+ EXPECT_EQ(one_message, meter.TrackMessage(id1));
+ EXPECT_EQ(one_message, meter.TrackMessage(id2));
+ EXPECT_EQ(one_message, meter.TrackMessage(id3));
+
// Check messages count over period
- while (date_time::DateTime::calculateTimeSpan(start_time)
- < time_range_msecs) {
- usleep(sleep_usecs);
- EXPECT_EQ(one_message,
- meter.Frequency(id1));
- EXPECT_EQ(one_message,
- meter.Frequency(id2));
- EXPECT_EQ(one_message,
- meter.Frequency(id3));
+ int64_t time_span;
+ while ((time_span = date_time::DateTime::calculateTimeSpan(start_time)) <
+ time_range_msecs) {
+ usleep(time_range_msecs);
+
+ if (one_message != meter.Frequency(id1) ||
+ one_message != meter.Frequency(id2) ||
+ one_message != meter.Frequency(id3)) {
+ EXPECT_GE(time_range_msecs, time_span);
+ break;
+ }
}
}
TEST_P(MessageMeterTest, CountingOutOfPeriod) {
const size_t one_message = 1;
- EXPECT_EQ(one_message,
- meter.TrackMessage(id1));
- EXPECT_EQ(one_message,
- meter.TrackMessage(id2));
- EXPECT_EQ(one_message,
- meter.TrackMessage(id3));
+ EXPECT_EQ(one_message, meter.TrackMessage(id1));
+ EXPECT_EQ(one_message, meter.TrackMessage(id2));
+ EXPECT_EQ(one_message, meter.TrackMessage(id3));
// sleep more than time range
usleep(time_range_msecs * usecs * 1.1);
- EXPECT_EQ(0u,
- meter.Frequency(id1));
- EXPECT_EQ(0u,
- meter.Frequency(id2));
- EXPECT_EQ(0u,
- meter.Frequency(id3));
+ EXPECT_EQ(0u, meter.Frequency(id1));
+ EXPECT_EQ(0u, meter.Frequency(id2));
+ EXPECT_EQ(0u, meter.Frequency(id3));
}
TEST_P(MessageMeterTest, ClearId) {
const size_t one_message = 1;
- EXPECT_EQ(one_message,
- meter.TrackMessage(id1));
- EXPECT_EQ(one_message,
- meter.TrackMessage(id2));
- EXPECT_EQ(one_message,
- meter.TrackMessage(id3));
+ EXPECT_EQ(one_message, meter.TrackMessage(id1));
+ EXPECT_EQ(one_message, meter.TrackMessage(id2));
+ EXPECT_EQ(one_message, meter.TrackMessage(id3));
meter.RemoveIdentifier(id1);
- EXPECT_EQ(0u,
- meter.Frequency(id1));
- EXPECT_EQ(one_message,
- meter.Frequency(id2));
- EXPECT_EQ(one_message,
- meter.Frequency(id3));
+ EXPECT_EQ(0u, meter.Frequency(id1));
+ EXPECT_EQ(one_message, meter.Frequency(id2));
+ EXPECT_EQ(one_message, meter.Frequency(id3));
meter.RemoveIdentifier(id2);
- EXPECT_EQ(0u,
- meter.Frequency(id1));
- EXPECT_EQ(0u,
- meter.Frequency(id2));
- EXPECT_EQ(one_message,
- meter.Frequency(id3));
+ EXPECT_EQ(0u, meter.Frequency(id1));
+ EXPECT_EQ(0u, meter.Frequency(id2));
+ EXPECT_EQ(one_message, meter.Frequency(id3));
meter.RemoveIdentifier(id3);
- EXPECT_EQ(0u,
- meter.Frequency(id1));
- EXPECT_EQ(0u,
- meter.Frequency(id2));
- EXPECT_EQ(0u,
- meter.Frequency(id3));
+ EXPECT_EQ(0u, meter.Frequency(id1));
+ EXPECT_EQ(0u, meter.Frequency(id2));
+ EXPECT_EQ(0u, meter.Frequency(id3));
}
TEST_P(MessageMeterTest, ClearIds) {
const size_t one_message = 1;
- EXPECT_EQ(one_message,
- meter.TrackMessage(id1));
- EXPECT_EQ(one_message,
- meter.TrackMessage(id2));
- EXPECT_EQ(one_message,
- meter.TrackMessage(id3));
+ EXPECT_EQ(one_message, meter.TrackMessage(id1));
+ EXPECT_EQ(one_message, meter.TrackMessage(id2));
+ EXPECT_EQ(one_message, meter.TrackMessage(id3));
meter.ClearIdentifiers();
- EXPECT_EQ(0u,
- meter.Frequency(id2));
- EXPECT_EQ(0u,
- meter.Frequency(id2));
- EXPECT_EQ(0u,
- meter.Frequency(id3));
+ EXPECT_EQ(0u, meter.Frequency(id2));
+ EXPECT_EQ(0u, meter.Frequency(id2));
+ EXPECT_EQ(0u, meter.Frequency(id3));
}
INSTANTIATE_TEST_CASE_P(MessageMeterTestCase,
diff --git a/src/components/utils/test/posix_thread_test.cc b/src/components/utils/test/posix_thread_test.cc
index d597f036d0..f98794d08a 100644
--- a/src/components/utils/test/posix_thread_test.cc
+++ b/src/components/utils/test/posix_thread_test.cc
@@ -41,13 +41,14 @@ namespace utils {
using namespace sync_primitives;
using namespace threads;
-// TODO(AByzhynar): Change this to use Gtest class to create all variables for every TEST_F
+// TODO(AByzhynar): Change this to use Gtest class to create all variables for
+// every TEST_F
// TODO(AByzhynar): Add multithreading tests
namespace {
const uint32_t MAX_SIZE = 20;
const size_t MyStackSize = 32768;
-const char *threadName("test thread");
+const char* threadName("test thread");
const std::string test_thread_name("THREAD");
sync_primitives::ConditionalVariable cond_var_;
sync_primitives::Lock test_mutex_;
@@ -56,9 +57,7 @@ sync_primitives::Lock test_mutex_;
// ThreadDelegate successor
class TestThreadDelegate : public threads::ThreadDelegate {
public:
- TestThreadDelegate()
- : check_value_(false) {
- }
+ TestThreadDelegate() : check_value_(false) {}
void threadMain() {
AutoLock test_lock(test_mutex_);
check_value_ = true;
@@ -68,14 +67,15 @@ class TestThreadDelegate : public threads::ThreadDelegate {
bool check_value() const {
return check_value_;
}
+
private:
bool check_value_;
};
TEST(PosixThreadTest, CreateThread_ExpectThreadCreated) {
// Arrange
- threads::Thread *thread = NULL;
- TestThreadDelegate *threadDelegate = new TestThreadDelegate();
+ threads::Thread* thread = NULL;
+ TestThreadDelegate* threadDelegate = new TestThreadDelegate();
// Create thread
ASSERT_NO_THROW(thread = CreateThread(threadName, threadDelegate));
EXPECT_TRUE(thread != NULL);
@@ -89,8 +89,8 @@ TEST(PosixThreadTest, CreateThread_ExpectThreadCreated) {
TEST(PosixThreadTest, CheckCreatedThreadName_ExpectCorrectName) {
// Arrange
- threads::Thread *thread = NULL;
- threads::ThreadDelegate *threadDelegate = new TestThreadDelegate();
+ threads::Thread* thread = NULL;
+ threads::ThreadDelegate* threadDelegate = new TestThreadDelegate();
// Create thread
ASSERT_NO_THROW(thread = CreateThread(threadName, threadDelegate));
// Check thread was created with correct name
@@ -100,10 +100,11 @@ TEST(PosixThreadTest, CheckCreatedThreadName_ExpectCorrectName) {
EXPECT_EQ(NULL, thread->delegate());
}
-TEST(PosixThreadTest, CheckCreatedThreadNameChangeToLongName_ExpectThreadNameReduced) {
+TEST(PosixThreadTest,
+ CheckCreatedThreadNameChangeToLongName_ExpectThreadNameReduced) {
// Arrange
- threads::Thread *thread = NULL;
- TestThreadDelegate *threadDelegate = new TestThreadDelegate();
+ threads::Thread* thread = NULL;
+ TestThreadDelegate* threadDelegate = new TestThreadDelegate();
AutoLock test_lock(test_mutex_);
// Create thread
ASSERT_NO_THROW(thread = CreateThread(threadName, threadDelegate));
@@ -124,14 +125,17 @@ TEST(PosixThreadTest, CheckCreatedThreadNameChangeToLongName_ExpectThreadNameRed
EXPECT_EQ(NULL, thread->delegate());
}
-TEST(PosixThreadTest, StartCreatedThreadWithOptionsJoinableAndMyStackSize_ExpectMyStackSizeStackAndJoinableThreadStarted) {
+TEST(
+ PosixThreadTest,
+ StartCreatedThreadWithOptionsJoinableAndMyStackSize_ExpectMyStackSizeStackAndJoinableThreadStarted) {
// Arrange
- threads::Thread *thread = NULL;
- TestThreadDelegate *threadDelegate = new TestThreadDelegate();
+ threads::Thread* thread = NULL;
+ TestThreadDelegate* threadDelegate = new TestThreadDelegate();
AutoLock test_lock(test_mutex_);
// Create thread
ASSERT_NO_THROW(thread = CreateThread(threadName, threadDelegate));
- // Start thread with following options (Stack size = 32768 & thread is joinable)
+ // Start thread with following options (Stack size = 32768 & thread is
+ // joinable)
thread->start(threads::ThreadOptions(MyStackSize));
// Check thread is joinable
EXPECT_TRUE(thread->is_joinable());
@@ -144,10 +148,12 @@ TEST(PosixThreadTest, StartCreatedThreadWithOptionsJoinableAndMyStackSize_Expect
EXPECT_EQ(NULL, thread->delegate());
}
-TEST(PosixThreadTest, StartCreatedThreadWithDefaultOptions_ExpectZeroStackAndJoinableThreadStarted) {
+TEST(
+ PosixThreadTest,
+ StartCreatedThreadWithDefaultOptions_ExpectZeroStackAndJoinableThreadStarted) {
// Arrange
- threads::Thread *thread = NULL;
- TestThreadDelegate *threadDelegate = new TestThreadDelegate();
+ threads::Thread* thread = NULL;
+ TestThreadDelegate* threadDelegate = new TestThreadDelegate();
AutoLock test_lock(test_mutex_);
// Create thread
ASSERT_NO_THROW(thread = CreateThread(threadName, threadDelegate));
@@ -164,10 +170,12 @@ TEST(PosixThreadTest, StartCreatedThreadWithDefaultOptions_ExpectZeroStackAndJoi
EXPECT_EQ(NULL, thread->delegate());
}
-TEST(PosixThreadTest, StartThreadWithZeroStackAndDetached_ExpectMinimumStackAndDetachedThreadStarted) {
+TEST(
+ PosixThreadTest,
+ StartThreadWithZeroStackAndDetached_ExpectMinimumStackAndDetachedThreadStarted) {
// Arrange
- threads::Thread *thread = NULL;
- TestThreadDelegate *threadDelegate = new TestThreadDelegate();
+ threads::Thread* thread = NULL;
+ TestThreadDelegate* threadDelegate = new TestThreadDelegate();
AutoLock test_lock(test_mutex_);
// Create thread
ASSERT_NO_THROW(thread = CreateThread(threadName, threadDelegate));
@@ -184,10 +192,12 @@ TEST(PosixThreadTest, StartThreadWithZeroStackAndDetached_ExpectMinimumStackAndD
EXPECT_EQ(NULL, thread->delegate());
}
-TEST(PosixThreadTest, DISABLED_CheckCreatedThreadNameChangeToEmpty_ExpectThreadNameChangedToEmpty) {
+TEST(
+ PosixThreadTest,
+ DISABLED_CheckCreatedThreadNameChangeToEmpty_ExpectThreadNameChangedToEmpty) {
// Arrange
- threads::Thread *thread = NULL;
- TestThreadDelegate *threadDelegate = new TestThreadDelegate();
+ threads::Thread* thread = NULL;
+ TestThreadDelegate* threadDelegate = new TestThreadDelegate();
AutoLock test_lock(test_mutex_);
// Create thread
ASSERT_NO_THROW(thread = CreateThread(threadName, threadDelegate));
@@ -208,10 +218,11 @@ TEST(PosixThreadTest, DISABLED_CheckCreatedThreadNameChangeToEmpty_ExpectThreadN
EXPECT_EQ(NULL, thread->delegate());
}
-TEST(PosixThreadTest, CheckCreatedThreadNameChangeToShortName_ExpectThreadNameChangedToShort) {
+TEST(PosixThreadTest,
+ CheckCreatedThreadNameChangeToShortName_ExpectThreadNameChangedToShort) {
// Arrange
- threads::Thread *thread = NULL;
- TestThreadDelegate *threadDelegate = new TestThreadDelegate();
+ threads::Thread* thread = NULL;
+ TestThreadDelegate* threadDelegate = new TestThreadDelegate();
AutoLock test_lock(test_mutex_);
// Create thread
ASSERT_NO_THROW(thread = CreateThread(threadName, threadDelegate));
@@ -235,13 +246,14 @@ TEST(PosixThreadTest, CheckCreatedThreadNameChangeToShortName_ExpectThreadNameCh
TEST(PosixThreadTest, StartThread_ExpectThreadStarted) {
// Arrange
- threads::Thread *thread = NULL;
- TestThreadDelegate *threadDelegate = new TestThreadDelegate();
+ threads::Thread* thread = NULL;
+ TestThreadDelegate* threadDelegate = new TestThreadDelegate();
AutoLock test_lock(test_mutex_);
// Create thread
ASSERT_NO_THROW(thread = CreateThread(threadName, threadDelegate));
// Start created thread
- EXPECT_TRUE(thread->start(threads::ThreadOptions(threads::Thread::kMinStackSize)));
+ EXPECT_TRUE(
+ thread->start(threads::ThreadOptions(threads::Thread::kMinStackSize)));
cond_var_.WaitFor(test_lock, 10000);
EXPECT_TRUE(threadDelegate->check_value());
DeleteThread(thread);
@@ -253,17 +265,19 @@ TEST(PosixThreadTest, StartOneThreadTwice_ExpectTheSameThreadStartedTwice) {
// Arrange
PlatformThreadHandle thread1_id;
PlatformThreadHandle thread2_id;
- threads::Thread *thread = NULL;
- TestThreadDelegate *threadDelegate = new TestThreadDelegate();
+ threads::Thread* thread = NULL;
+ TestThreadDelegate* threadDelegate = new TestThreadDelegate();
AutoLock test_lock(test_mutex_);
// Create thread
ASSERT_NO_THROW(thread = CreateThread(threadName, threadDelegate));
// Start created thread
- EXPECT_TRUE(thread->start(threads::ThreadOptions(threads::Thread::kMinStackSize)));
+ EXPECT_TRUE(
+ thread->start(threads::ThreadOptions(threads::Thread::kMinStackSize)));
thread1_id = thread->CurrentId();
thread->stop();
// Try to start thread again
- EXPECT_TRUE(thread->start(threads::ThreadOptions(threads::Thread::kMinStackSize)));
+ EXPECT_TRUE(
+ thread->start(threads::ThreadOptions(threads::Thread::kMinStackSize)));
thread2_id = thread->CurrentId();
EXPECT_EQ(thread1_id, thread2_id);
cond_var_.WaitFor(test_lock, 10000);
@@ -273,17 +287,19 @@ TEST(PosixThreadTest, StartOneThreadTwice_ExpectTheSameThreadStartedTwice) {
EXPECT_EQ(NULL, thread->delegate());
}
-TEST(PosixThreadTest, StartOneThreadAgainAfterRename_ExpectRenamedThreadStarted) {
+TEST(PosixThreadTest,
+ StartOneThreadAgainAfterRename_ExpectRenamedThreadStarted) {
// Arrange
PlatformThreadHandle thread1_id;
PlatformThreadHandle thread2_id;
- threads::Thread *thread = NULL;
- TestThreadDelegate *threadDelegate = new TestThreadDelegate();
+ threads::Thread* thread = NULL;
+ TestThreadDelegate* threadDelegate = new TestThreadDelegate();
AutoLock test_lock(test_mutex_);
// Create thread
ASSERT_NO_THROW(thread = CreateThread(threadName, threadDelegate));
// Start created thread
- EXPECT_TRUE(thread->start(threads::ThreadOptions(threads::Thread::kMinStackSize)));
+ EXPECT_TRUE(
+ thread->start(threads::ThreadOptions(threads::Thread::kMinStackSize)));
thread1_id = thread->CurrentId();
// Rename started thread. Name will be cut to 15 symbols + '\0'
// This is the limit in current POSIX thread implementation
@@ -295,7 +311,8 @@ TEST(PosixThreadTest, StartOneThreadAgainAfterRename_ExpectRenamedThreadStarted)
EXPECT_EQ(test_thread_name, std::string(name));
// Stop thread
thread->stop();
- EXPECT_TRUE(thread->start(threads::ThreadOptions(threads::Thread::kMinStackSize)));
+ EXPECT_TRUE(
+ thread->start(threads::ThreadOptions(threads::Thread::kMinStackSize)));
thread2_id = thread->CurrentId();
// Expect the same thread started with the the same name
EXPECT_EQ(test_thread_name, std::string(name));
diff --git a/src/components/utils/test/prioritized_queue_test.cc b/src/components/utils/test/prioritized_queue_test.cc
index 19e168cdce..ef105f6c4e 100644
--- a/src/components/utils/test/prioritized_queue_test.cc
+++ b/src/components/utils/test/prioritized_queue_test.cc
@@ -41,16 +41,13 @@ using ::utils::PrioritizedQueue;
class TestMessage {
public:
- TestMessage()
- : priority(0) {
- }
+ TestMessage() : priority(0) {}
TestMessage(std::string message, size_t msg_priority)
- : msg_(message),
- priority(msg_priority) {
- }
+ : msg_(message), priority(msg_priority) {}
size_t PriorityOrder() const;
std::string msg() const;
- friend bool operator==(const TestMessage &msg1, const TestMessage &msg2);
+ friend bool operator==(const TestMessage& msg1, const TestMessage& msg2);
+
private:
std::string msg_;
size_t priority;
@@ -64,9 +61,9 @@ std::string TestMessage::msg() const {
return msg_;
}
-bool operator==(const TestMessage &msg1, const TestMessage &msg2) {
- return (msg1.msg() == msg2.msg()
- && msg1.PriorityOrder() == msg2.PriorityOrder());
+bool operator==(const TestMessage& msg1, const TestMessage& msg2) {
+ return (msg1.msg() == msg2.msg() &&
+ msg1.PriorityOrder() == msg2.PriorityOrder());
}
class PrioritizedQueueTest : public testing::Test {
@@ -108,13 +105,15 @@ TEST_F(PrioritizedQueueTest, AddFourElementsTest_ExpectQueueNotEmpty) {
EXPECT_FALSE(test_queue.empty());
}
-TEST_F(PrioritizedQueueTest, CheckMessageOrder_ExpectMessageWithHighestPriorityAddedFirst) {
+TEST_F(PrioritizedQueueTest,
+ CheckMessageOrder_ExpectMessageWithHighestPriorityAddedFirst) {
// Creating 4 messages with different priorities
TestMessage message1("Ford", 111);
TestMessage message2("Hello", 21);
TestMessage message3("Luxoft", 14);
TestMessage message4("from", 4);
- // Adding created messages to Prioritized queue. Expect queue ordered according priority
+ // Adding created messages to Prioritized queue. Expect queue ordered
+ // according priority
test_queue.push(message4);
test_queue.push(message3);
test_queue.push(message1);
@@ -123,7 +122,8 @@ TEST_F(PrioritizedQueueTest, CheckMessageOrder_ExpectMessageWithHighestPriorityA
EXPECT_EQ(message1, test_queue.front());
}
-TEST_F(PrioritizedQueueTest, Push_AddMessagesWithEqualPriority_ExpectMessagesWithEqualPriorityAdded) {
+TEST_F(PrioritizedQueueTest,
+ Push_AddMessagesWithEqualPriority_ExpectMessagesWithEqualPriorityAdded) {
// Creating 2 messages with the same priorities
TestMessage message1("Hello", 111);
TestMessage message2("Luxoft", 111);
@@ -134,14 +134,17 @@ TEST_F(PrioritizedQueueTest, Push_AddMessagesWithEqualPriority_ExpectMessagesWit
EXPECT_EQ(2u, test_queue.size());
}
-TEST_F(PrioritizedQueueTest, Pop_OneElementInPriorityQueue_ExpectQueueStillAliveWithRestMessagesWithEqualPriority) {
+TEST_F(
+ PrioritizedQueueTest,
+ Pop_OneElementInPriorityQueue_ExpectQueueStillAliveWithRestMessagesWithEqualPriority) {
// Creating 4 messages with same priorities
TestMessage message1("Ford's", 111);
TestMessage message2("Partner", 111);
// Adding created messages to Prioritized queue.
test_queue.push(message1);
test_queue.push(message2);
- // Expect 2 messages were added successfully to One element of prioritized queue
+ // Expect 2 messages were added successfully to One element of prioritized
+ // queue
EXPECT_EQ(2u, test_queue.size());
// Extracting first element from the queue
EXPECT_EQ(message1, test_queue.front());
@@ -153,7 +156,9 @@ TEST_F(PrioritizedQueueTest, Pop_OneElementInPriorityQueue_ExpectQueueStillAlive
EXPECT_EQ(0u, test_queue.size());
}
-TEST_F(PrioritizedQueueTest, Pop_TwoElementsInPriorityQueue_ExpectElementErasedIfOnlyOneWithConcretePriorityExist) {
+TEST_F(
+ PrioritizedQueueTest,
+ Pop_TwoElementsInPriorityQueue_ExpectElementErasedIfOnlyOneWithConcretePriorityExist) {
// Creating 2 messages with same priority and 1 with different
TestMessage message1("Hello", 111);
TestMessage message2("Luxoft", 111);
@@ -162,7 +167,8 @@ TEST_F(PrioritizedQueueTest, Pop_TwoElementsInPriorityQueue_ExpectElementErasedI
test_queue.push(message1);
test_queue.push(message2);
test_queue.push(message3);
- // Expect 3 messages were added successfully to Two elements of prioritized queue
+ // Expect 3 messages were added successfully to Two elements of prioritized
+ // queue
EXPECT_EQ(3u, test_queue.size());
// Extracting first element from the queue
EXPECT_EQ(message1, test_queue.front());
@@ -177,7 +183,8 @@ TEST_F(PrioritizedQueueTest, Pop_TwoElementsInPriorityQueue_ExpectElementErasedI
EXPECT_EQ(0u, test_queue.size());
}
-TEST_F(PrioritizedQueueTest, NotEmptyPrioritizedQueuePopElement_ExpectQueueDecreasedOneElement) {
+TEST_F(PrioritizedQueueTest,
+ NotEmptyPrioritizedQueuePopElement_ExpectQueueDecreasedOneElement) {
// Creating 4 prioritized messages
TestMessage message1("Alice", 111);
TestMessage message2("in", 14);
diff --git a/src/components/utils/test/qdb_wrapper/sql_database_test.cc b/src/components/utils/test/qdb_wrapper/sql_database_test.cc
new file mode 100644
index 0000000000..881141f18c
--- /dev/null
+++ b/src/components/utils/test/qdb_wrapper/sql_database_test.cc
@@ -0,0 +1,139 @@
+/* Copyright (c) 2013, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <cstdlib>
+
+#include "gtest/gtest.h"
+
+#include "qdb_wrapper/sql_error.h"
+#include "qdb_wrapper/sql_database.h"
+
+using ::utils::dbms::SQLError;
+using ::utils::dbms::SQLDatabase;
+
+namespace test {
+namespace components {
+namespace utils {
+namespace dbms {
+
+::testing::AssertionResult IsError(SQLError error) {
+ if (error.number() != ::utils::dbms::OK) {
+ return ::testing::AssertionSuccess() << error.text();
+ } else {
+ return ::testing::AssertionFailure() << error.text();
+ }
+}
+
+TEST(SQLDatabaseTest, OpenClose) {
+ SQLDatabase db("test-database");
+ bool ret = db.Open();
+ EXPECT_FALSE(IsError(db.LastError()));
+ ASSERT_TRUE(ret);
+
+ db.Close();
+ EXPECT_FALSE(IsError(db.LastError()));
+}
+
+TEST(SQLDatabaseTest, DoubleOpen) {
+ SQLDatabase db("test-database");
+ bool ret = db.Open();
+ EXPECT_FALSE(IsError(db.LastError()));
+ ASSERT_TRUE(ret);
+ ret = db.Open();
+ EXPECT_FALSE(IsError(db.LastError()));
+ ASSERT_TRUE(ret);
+ db.Close();
+}
+
+TEST(SQLDatabaseTest, DoubleClose) {
+ SQLDatabase db("test-database");
+ bool ret = db.Open();
+ EXPECT_FALSE(IsError(db.LastError()));
+ ASSERT_TRUE(ret);
+
+ db.Close();
+ EXPECT_FALSE(IsError(db.LastError()));
+ db.Close();
+ EXPECT_FALSE(IsError(db.LastError()));
+}
+
+TEST(SQLDatabaseTest, CloseWithoutOpen) {
+ SQLDatabase db("test-database");
+ db.Close();
+ EXPECT_FALSE(IsError(db.LastError()));
+}
+
+TEST(SQLDatabaseTest, CommitTransaction) {
+ SQLDatabase db("test-database");
+ ASSERT_TRUE(db.Open());
+ EXPECT_TRUE(db.BeginTransaction());
+ EXPECT_FALSE(IsError(db.LastError()));
+ EXPECT_TRUE(db.CommitTransaction());
+ EXPECT_FALSE(IsError(db.LastError()));
+ db.Close();
+}
+
+TEST(SQLDatabaseTest, RollbackTransaction) {
+ SQLDatabase db("test-database");
+ ASSERT_TRUE(db.Open());
+ EXPECT_TRUE(db.BeginTransaction());
+ EXPECT_FALSE(IsError(db.LastError()));
+ EXPECT_TRUE(db.RollbackTransaction());
+ EXPECT_FALSE(IsError(db.LastError()));
+ db.Close();
+}
+
+TEST(SQLDatabaseTest, FailedCommitTransaction) {
+ SQLDatabase db("test-database");
+ ASSERT_TRUE(db.Open());
+ EXPECT_FALSE(db.CommitTransaction());
+ EXPECT_TRUE(IsError(db.LastError()));
+ db.Close();
+}
+
+TEST(SQLDatabaseTest, FailedRollbackTransaction) {
+ SQLDatabase db("test-database");
+ ASSERT_TRUE(db.Open());
+ EXPECT_FALSE(db.RollbackTransaction());
+ EXPECT_TRUE(IsError(db.LastError()));
+ db.Close();
+}
+
+TEST(SQLDatabaseTest, BadTransaction) {
+ SQLDatabase db("test-database");
+ EXPECT_FALSE(db.BeginTransaction());
+ EXPECT_TRUE(IsError(db.LastError()));
+}
+
+} // namespace dbms
+} // namespace utils
+} // namespace components
+} // namespace test
diff --git a/src/components/utils/test/qdb_wrapper/sql_query_test.cc b/src/components/utils/test/qdb_wrapper/sql_query_test.cc
new file mode 100644
index 0000000000..6c866ffb9d
--- /dev/null
+++ b/src/components/utils/test/qdb_wrapper/sql_query_test.cc
@@ -0,0 +1,311 @@
+/* Copyright (c) 2013, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <qdb/qdb.h>
+#include <string>
+
+#include "gtest/gtest.h"
+
+#include "qdb_wrapper/sql_error.h"
+#include "qdb_wrapper/sql_database.h"
+#include "qdb_wrapper/sql_query.h"
+
+using ::utils::dbms::SQLError;
+using ::utils::dbms::SQLDatabase;
+using ::utils::dbms::SQLQuery;
+
+namespace test {
+namespace components {
+namespace utils {
+namespace dbms {
+
+class SQLQueryTest : public ::testing::Test {
+ protected:
+ static qdb_hdl_t* conn;
+ static const std::string kDatabaseName;
+
+ static void SetUpTestCase() {
+ conn = qdb_connect(kDatabaseName.c_str(), 0);
+ ASSERT_TRUE(conn);
+ int ret = qdb_statement(conn,
+ "CREATE TABLE testTable (integerValue INTEGER,"
+ " doubleValue REAL, stringValue TEXT)");
+ ASSERT_NE(-1, ret);
+ }
+
+ static void TearDownTestCase() {
+ qdb_statement(conn, "DROP TABLE IF EXISTS testTable");
+ qdb_disconnect(conn);
+ }
+
+ void SetUp() {
+ qdb_statement(conn, "DELETE FROM testTable");
+ }
+
+ ::testing::AssertionResult IsError(SQLError error) {
+ if (error.number() != ::policy::dbms::OK) {
+ return ::testing::AssertionSuccess() << error.text();
+ } else {
+ return ::testing::AssertionFailure() << error.text();
+ }
+ }
+};
+
+qdb_hdl_t* SQLQueryTest::conn = 0;
+const std::string SQLQueryTest::kDatabaseName = "test-query";
+
+TEST_F(SQLQueryTest, Query) {
+ const std::string kSelect("SELECT * FROM testTable WHERE integerValue = ?");
+
+ SQLDatabase* db = new SQLDatabase(kDatabaseName);
+ ASSERT_TRUE(db->Open());
+
+ SQLQuery query(db);
+ query.Prepare(kSelect);
+ EXPECT_STREQ(kSelect.c_str(), query.query().c_str());
+}
+
+TEST_F(SQLQueryTest, ExecString) {
+ const std::string kInsert(
+ "INSERT INTO testTable"
+ " (integerValue, doubleValue, stringValue)"
+ " VALUES(1, 1.1, 'one-один')");
+
+ SQLDatabase* db = new SQLDatabase(kDatabaseName);
+ ASSERT_TRUE(db->Open());
+
+ SQLQuery query(db);
+ EXPECT_TRUE(query.Exec(kInsert));
+ EXPECT_FALSE(IsError(query.LastError()));
+}
+
+TEST_F(SQLQueryTest, BindInteger) {
+ const std::string kInsert("INSERT INTO testTable (integerValue) VALUES (?)");
+ const int kIntegerValue = 2;
+
+ SQLDatabase* db = new SQLDatabase(kDatabaseName);
+ ASSERT_TRUE(db->Open());
+
+ SQLQuery query(db);
+ EXPECT_TRUE(query.Prepare(kInsert));
+ EXPECT_FALSE(IsError(query.LastError()));
+ query.Bind(0, kIntegerValue);
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Exec());
+ EXPECT_FALSE(IsError(query.LastError()));
+}
+
+TEST_F(SQLQueryTest, BindDouble) {
+ const std::string kInsert("INSERT INTO testTable (doubleValue) VALUES (?)");
+ const double kDoubleValue = 3.3;
+
+ SQLDatabase* db = new SQLDatabase(kDatabaseName);
+ ASSERT_TRUE(db->Open());
+ SQLQuery query(db);
+ EXPECT_TRUE(query.Prepare(kInsert));
+ EXPECT_FALSE(IsError(query.LastError()));
+ query.Bind(0, kDoubleValue);
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Exec());
+ EXPECT_FALSE(IsError(query.LastError()));
+}
+
+TEST_F(SQLQueryTest, BindString) {
+ const std::string kInsert("INSERT INTO testTable (stringValue) VALUES (?)");
+ const std::string kStringValue = "four-четыре";
+
+ SQLDatabase* db = new SQLDatabase(kDatabaseName);
+ ASSERT_TRUE(db->Open());
+
+ SQLQuery query(db);
+ EXPECT_TRUE(query.Prepare(kInsert));
+ EXPECT_FALSE(IsError(query.LastError()));
+ query.Bind(0, kStringValue);
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Exec());
+ EXPECT_FALSE(IsError(query.LastError()));
+}
+
+TEST_F(SQLQueryTest, BindAllTypes) {
+ const std::string kInsert(
+ "INSERT INTO testTable (integerValue, doubleValue,"
+ " stringValue) VALUES (?, ?, ?)");
+ const int kIntegerValue = 5;
+ const double kDoubleValue = 5.5;
+ const std::string kStringValue = "five-пять";
+
+ SQLDatabase* db = new SQLDatabase(kDatabaseName);
+ ASSERT_TRUE(db->Open());
+
+ SQLQuery query(db);
+ EXPECT_TRUE(query.Prepare(kInsert));
+ EXPECT_FALSE(IsError(query.LastError()));
+ query.Bind(0, kIntegerValue);
+ EXPECT_FALSE(IsError(query.LastError()));
+ query.Bind(1, kDoubleValue);
+ EXPECT_FALSE(IsError(query.LastError()));
+ query.Bind(2, kStringValue);
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Exec());
+ EXPECT_FALSE(IsError(query.LastError()));
+}
+
+TEST_F(SQLQueryTest, Value) {
+ const char* insert =
+ "INSERT INTO testTable "
+ "(integerValue, doubleValue, stringValue) "
+ "VALUES (6, 6.6, 'six-шесть');";
+ ASSERT_NE(-1, qdb_statement(conn, insert));
+
+ const std::string kSelect(
+ "SELECT integerValue, doubleValue, stringValue"
+ " FROM testTable WHERE integerValue = 6");
+ const int kIntegerValue = 6;
+ const double kDoubleValue = 6.6;
+ const std::string kStringValue = "six-шесть";
+
+ SQLDatabase* db = new SQLDatabase(kDatabaseName);
+ ASSERT_TRUE(db->Open());
+
+ SQLQuery query(db);
+ EXPECT_TRUE(query.Prepare(kSelect));
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Exec());
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_EQ(kIntegerValue, query.GetInteger(0));
+ EXPECT_EQ(kDoubleValue, query.GetDouble(1));
+ EXPECT_EQ(kStringValue, query.GetString(2));
+ EXPECT_FALSE(query.Next());
+ EXPECT_FALSE(IsError(query.LastError()));
+}
+
+TEST_F(SQLQueryTest, EmptySelect) {
+ const std::string kSelect(
+ "SELECT integerValue, doubleValue, stringValue"
+ " FROM testTable WHERE 0");
+ SQLDatabase* db = new SQLDatabase(kDatabaseName);
+ ASSERT_TRUE(db->Open());
+
+ SQLQuery query(db);
+ EXPECT_TRUE(query.Prepare(kSelect));
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Exec());
+ EXPECT_FALSE(IsError(query.LastError()));
+}
+
+TEST_F(SQLQueryTest, NextAndBind) {
+ const char* insert =
+ "INSERT INTO testTable "
+ "(integerValue, doubleValue, stringValue) "
+ "VALUES (7, 7.7, 'seven-семь');";
+ ASSERT_NE(-1, qdb_statement(conn, insert));
+
+ const std::string kSelect(
+ "SELECT integerValue, doubleValue, stringValue"
+ " FROM testTable WHERE integerValue = ?");
+ const int kIntegerValue = 7;
+ const double kDoubleValue = 7.7;
+ const std::string kStringValue = "seven-семь";
+
+ SQLDatabase* db = new SQLDatabase(kDatabaseName);
+ ASSERT_TRUE(db->Open());
+
+ SQLQuery query(db);
+ ASSERT_TRUE(query.Prepare(kSelect));
+ EXPECT_FALSE(IsError(query.LastError()));
+ query.Bind(0, kIntegerValue);
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Exec());
+ ASSERT_FALSE(IsError(query.LastError()));
+ EXPECT_EQ(kIntegerValue, query.GetInteger(0));
+ EXPECT_EQ(kDoubleValue, query.GetDouble(1));
+ EXPECT_EQ(kStringValue, query.GetString(2));
+ EXPECT_FALSE(query.Next());
+ EXPECT_FALSE(IsError(query.LastError()));
+}
+
+TEST_F(SQLQueryTest, LastInsertId) {
+ const char* create =
+ "CREATE TABLE idTable ( "
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "value TEXT)";
+ ASSERT_NE(-1, qdb_statement(conn, create));
+
+ const int64_t kExpectId = 1;
+ const std::string kValue("Test last id of insert row");
+ const std::string kInsert("INSERT INTO idTable (value) VALUES(?)");
+
+ SQLDatabase* db = new SQLDatabase(kDatabaseName);
+ ASSERT_TRUE(db->Open());
+
+ SQLQuery query(db);
+ ASSERT_TRUE(query.Prepare(kInsert));
+ EXPECT_FALSE(IsError(query.LastError()));
+ query.Bind(0, kValue);
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Exec());
+ ASSERT_FALSE(IsError(query.LastError()));
+ EXPECT_EQ(kExpectId, query.LastInsertId());
+
+ ASSERT_NE(-1, qdb_statement(conn, "DROP TABLE idTable"));
+}
+
+TEST_F(SQLQueryTest, BindNull) {
+ const std::string kInsert(
+ "INSERT INTO testTable (`integerValue`)"
+ " VALUES (?)");
+ SQLDatabase* db = new SQLDatabase(kDatabaseName);
+ ASSERT_TRUE(db->Open());
+
+ SQLQuery query(db);
+ ASSERT_TRUE(query.Prepare(kInsert));
+ EXPECT_FALSE(IsError(query.LastError()));
+ query.Bind(0);
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Exec());
+ ASSERT_FALSE(IsError(query.LastError()));
+}
+
+TEST_F(SQLQueryTest, DoublePrepare) {
+ SQLDatabase* db = new SQLDatabase(kDatabaseName);
+ ASSERT_TRUE(db->Open());
+
+ SQLQuery query(db);
+ EXPECT_TRUE(query.Prepare("SELECT * FROM testTable"));
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Prepare("SELECT * FROM testTable"));
+ EXPECT_FALSE(IsError(query.LastError()));
+}
+
+} // namespace dbms
+} // namespace utils
+} // namespace components
+} // namespace test
diff --git a/src/components/utils/test/resource_usage_test.cc b/src/components/utils/test/resource_usage_test.cc
index cac5dc2e31..96b4fe4b49 100644
--- a/src/components/utils/test/resource_usage_test.cc
+++ b/src/components/utils/test/resource_usage_test.cc
@@ -60,25 +60,24 @@ TEST_F(ResourceUsagePrivateTest, GetMemInfoTest) {
}
TEST_F(ResourceUsagePrivateTest, GetStatPathTest_FileExists) {
- //arrange
+ // arrange
std::string filename = res.GetStatPath();
- //assert
+ // assert
EXPECT_TRUE(file_system::FileExists(filename));
}
TEST_F(ResourceUsagePrivateTest, GetStatPathTest_ReadFile) {
- //arrange
+ // arrange
std::string filename = res.GetStatPath();
std::string output;
- //assert
+ // assert
EXPECT_TRUE(file_system::ReadFile(filename, output));
-
}
TEST_F(ResourceUsagePrivateTest, GetProcPathTest) {
- ///arrange
+ /// arrange
std::string fd = res.GetProcPath();
std::string filename = res.GetStatPath();
- //assert
+ // assert
EXPECT_EQ(filename, fd + "/stat");
}
}
@@ -88,7 +87,8 @@ namespace components {
namespace utils_test {
TEST(ResourceUsageTest, SuccesfulGrabResources) {
- ::utils::ResourseUsage* resources = ::utils::Resources::getCurrentResourseUsage();
+ ::utils::ResourseUsage* resources =
+ ::utils::Resources::getCurrentResourseUsage();
EXPECT_TRUE(resources != NULL);
delete resources;
}
diff --git a/src/components/utils/test/rwlock_posix_test.cc b/src/components/utils/test/rwlock_posix_test.cc
index 779b57ff32..6cb140f4c5 100644
--- a/src/components/utils/test/rwlock_posix_test.cc
+++ b/src/components/utils/test/rwlock_posix_test.cc
@@ -72,20 +72,20 @@ class RWlockTest : public ::testing::Test {
}
}
- static void* ReadLock_helper(void *context) {
- RWlockTest *temp = reinterpret_cast<RWlockTest *>(context);
+ static void* ReadLock_helper(void* context) {
+ RWlockTest* temp = reinterpret_cast<RWlockTest*>(context);
temp->ReadLock();
return NULL;
}
- static void* TryReadLock_helper(void *context) {
- RWlockTest *temp = reinterpret_cast<RWlockTest *>(context);
+ static void* TryReadLock_helper(void* context) {
+ RWlockTest* temp = reinterpret_cast<RWlockTest*>(context);
temp->ExpectReadLockFail();
return NULL;
}
- static void* TryWriteLock_helper(void *context) {
- RWlockTest *temp = reinterpret_cast<RWlockTest *>(context);
+ static void* TryWriteLock_helper(void* context) {
+ RWlockTest* temp = reinterpret_cast<RWlockTest*>(context);
temp->ExpectWriteLockFail();
return NULL;
}
@@ -101,7 +101,8 @@ TEST_F(RWlockTest, AcquireForReading_ExpectAccessForReading) {
EXPECT_TRUE(test_rwlock.AcquireForReading());
// Try to lock rw lock for reading again
EXPECT_TRUE(test_rwlock.AcquireForReading());
- // Creating kNumThreads threads, starting them with callback function, waits until all of them finished
+ // Creating kNumThreads threads, starting them with callback function, waits
+ // until all of them finished
ThreadsDispatcher(&RWlockTest::ReadLock_helper);
// Releasing RW locks
EXPECT_TRUE(test_rwlock.Release());
@@ -113,7 +114,8 @@ TEST_F(RWlockTest, AcquireForReading_ExpectNoAccessForWriting) {
EXPECT_TRUE(test_rwlock.AcquireForReading());
// Try to lock rw lock for writing
EXPECT_FALSE(test_rwlock.TryAcquireForWriting());
- // Creating kNumThreads threads, starting them with callback function, waits until all of them finished
+ // Creating kNumThreads threads, starting them with callback function, waits
+ // until all of them finished
ThreadsDispatcher(&RWlockTest::TryWriteLock_helper);
EXPECT_TRUE(test_rwlock.Release());
}
@@ -123,7 +125,8 @@ TEST_F(RWlockTest, AcquireForWriting_ExpectNoAccessForReading) {
EXPECT_TRUE(test_rwlock.AcquireForWriting());
// Try to lock rw lock for reading
EXPECT_FALSE(test_rwlock.TryAcquireForReading());
- // Creating kNumThreads threads, starting them with callback function, waits until all of them finished
+ // Creating kNumThreads threads, starting them with callback function, waits
+ // until all of them finished
ThreadsDispatcher(&RWlockTest::TryReadLock_helper);
EXPECT_TRUE(test_rwlock.Release());
}
@@ -133,7 +136,8 @@ TEST_F(RWlockTest, AcquireForWriting_ExpectNoMoreAccessForWriting) {
EXPECT_TRUE(test_rwlock.AcquireForWriting());
// Try to lock rw lock for reading
EXPECT_FALSE(test_rwlock.TryAcquireForWriting());
- // Creating kNumThreads threads, starting them with callback function, waits until all of them finished
+ // Creating kNumThreads threads, starting them with callback function, waits
+ // until all of them finished
ThreadsDispatcher(&RWlockTest::TryWriteLock_helper);
EXPECT_TRUE(test_rwlock.Release());
}
diff --git a/src/components/utils/test/shared_ptr_test.cc b/src/components/utils/test/shared_ptr_test.cc
index 92d867fe76..85682073aa 100644
--- a/src/components/utils/test/shared_ptr_test.cc
+++ b/src/components/utils/test/shared_ptr_test.cc
@@ -42,20 +42,20 @@ namespace utils {
namespace SharedPtrTest {
class CMockObject {
- public:
- CMockObject(int id);
- virtual ~CMockObject();
- virtual int getId() const;
+ public:
+ CMockObject(int id);
+ virtual ~CMockObject();
+ virtual int getId() const;
- MOCK_METHOD0(destructor, void ());
+ MOCK_METHOD0(destructor, void());
- private:
- int mId_;
+ private:
+ int mId_;
};
class CExtendedMockObject : public CMockObject {
- public:
- CExtendedMockObject(int id);
+ public:
+ CExtendedMockObject(int id);
};
} // namespace CMockObject
@@ -66,9 +66,7 @@ class CExtendedMockObject : public CMockObject {
using namespace test::components::utils::SharedPtrTest;
using ::testing::NiceMock;
-CMockObject::CMockObject(int id)
- : mId_(id) {
-}
+CMockObject::CMockObject(int id) : mId_(id) {}
CMockObject::~CMockObject() {
destructor();
@@ -78,9 +76,7 @@ int CMockObject::getId() const {
return mId_;
}
-CExtendedMockObject::CExtendedMockObject(int id)
- : CMockObject(id) {
-}
+CExtendedMockObject::CExtendedMockObject(int id) : CMockObject(id) {}
typedef utils::SharedPtr<CMockObject> tMockObjectPtr;
typedef utils::SharedPtr<CExtendedMockObject> tExtendedMockObjectPtr;
@@ -120,9 +116,9 @@ TEST(SharedPtrTest, CopyConstructorTest) {
ASSERT_EQ(1, p3->getId());
ASSERT_EQ(3u, *(p3.get_ReferenceCounter()));
{
- tMockObjectPtr p4 = p3;
- ASSERT_EQ(1, p4->getId());
- ASSERT_EQ(4u, *(p3.get_ReferenceCounter()));
+ tMockObjectPtr p4 = p3;
+ ASSERT_EQ(1, p4->getId());
+ ASSERT_EQ(4u, *(p3.get_ReferenceCounter()));
}
// Check reference counter decreased
ASSERT_EQ(3u, *(p3.get_ReferenceCounter()));
@@ -283,10 +279,9 @@ TEST(SharedPtrTest, LessThanOperatorTest) {
// Checks
if (object1 < object2) {
- ASSERT_TRUE(p1 < p2);
- }
- else {
- ASSERT_FALSE(p1 < p2);
+ ASSERT_TRUE(p1 < p2);
+ } else {
+ ASSERT_FALSE(p1 < p2);
}
EXPECT_CALL(*object1, destructor());
@@ -309,7 +304,8 @@ TEST(SharedPtrTest, StaticPointerCastTest_DerivedToBase_ExpectCastOk) {
ASSERT_EQ(2, ep1->getId());
ASSERT_EQ(1u, *(ep1.get_ReferenceCounter()));
// Cast from SharedPtr to Derived class to SharedPtr to Base class
- p1 = utils::SharedPtr<CExtendedMockObject>::static_pointer_cast< CMockObject >(ep1);
+ p1 = utils::SharedPtr<CExtendedMockObject>::static_pointer_cast<CMockObject>(
+ ep1);
// Checks
ASSERT_EQ(2, p1->getId());
ASSERT_EQ(2u, *(p1.get_ReferenceCounter()));
@@ -334,7 +330,8 @@ TEST(SharedPtrTest, StaticPointerCastTest_BaseToDerived_ExpectCastOk) {
ASSERT_EQ(2, ep1->getId());
ASSERT_EQ(1u, *(ep1.get_ReferenceCounter()));
// Cast from SharedPtr to Base class to SharedPtr to Derived class
- ep1 = utils::SharedPtr<CMockObject>::static_pointer_cast<CExtendedMockObject>(p1);
+ ep1 = utils::SharedPtr<CMockObject>::static_pointer_cast<CExtendedMockObject>(
+ p1);
// Checks
ASSERT_EQ(1, ep1->getId());
ASSERT_EQ(2u, *(ep1.get_ReferenceCounter()));
@@ -359,7 +356,8 @@ TEST(SharedPtrTest, DynamicPointerCastTest_DerivedToBase_ExpectCastOk) {
ASSERT_EQ(2, ep1->getId());
ASSERT_EQ(1u, *(ep1.get_ReferenceCounter()));
// Cast from SharedPtr to Derived class to SharedPtr to Base class
- p1 = utils::SharedPtr<CExtendedMockObject>::dynamic_pointer_cast< CMockObject >(ep1);
+ p1 = utils::SharedPtr<CExtendedMockObject>::dynamic_pointer_cast<CMockObject>(
+ ep1);
// Checks
ASSERT_EQ(2, p1->getId());
ASSERT_EQ(2u, *(p1.get_ReferenceCounter()));
@@ -384,7 +382,9 @@ TEST(SharedPtrTest, DynamicPointerCastTest_BaseToDerived_ExpectNullPtr) {
ASSERT_EQ(2, ep1->getId());
ASSERT_EQ(1u, *(ep1.get_ReferenceCounter()));
// Cast from SharedPtr to Base class to SharedPtr to Derived class
- ep1 = utils::SharedPtr<CMockObject>::dynamic_pointer_cast<CExtendedMockObject>(p1);
+ ep1 =
+ utils::SharedPtr<CMockObject>::dynamic_pointer_cast<CExtendedMockObject>(
+ p1);
// Checks
ASSERT_EQ(NULL, ep1);
@@ -539,6 +539,7 @@ TEST(SharedPtrTest, StressTest) {
}
}
}
- printf("%zu objects created, %zu pointers copied\n", objectCreated,
+ printf("%zu objects created, %zu pointers copied\n",
+ objectCreated,
pointersCopied);
}
diff --git a/src/components/utils/test/signals_linux_test.cc b/src/components/utils/test/signals_linux_test.cc
deleted file mode 100644
index 263f240ec8..0000000000
--- a/src/components/utils/test/signals_linux_test.cc
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2014, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <unistd.h>
-#include <assert.h>
-#include "gtest/gtest.h"
-#include "utils/signals.h"
-
-namespace test {
-namespace components {
-namespace utils {
-
-void handler(int sig) {
-}
-
-TEST(SignalsLinuxTest, SubscribeToTerminateSignal_Positive) {
- ASSERT_TRUE(::utils::SubscribeToTerminateSignal(handler));
-}
-
-TEST(SignalsLinuxTest, SubscribeToFaultSignal_Positive) {
- ASSERT_TRUE(::utils::SubscribeToFaultSignal(handler));
-}
-
-} // namespace utils
-} // namespace components
-} // namespace test
diff --git a/src/components/utils/test/singleton_test.cc b/src/components/utils/test/singleton_test.cc
index 8a9e6b31e1..3bad45a7d7 100644
--- a/src/components/utils/test/singleton_test.cc
+++ b/src/components/utils/test/singleton_test.cc
@@ -42,7 +42,6 @@ using ::utils::Singleton;
class SingletonTest : public ::utils::Singleton<SingletonTest> {
public:
-
void SetValue(int value) {
test_value = value;
}
@@ -50,128 +49,129 @@ class SingletonTest : public ::utils::Singleton<SingletonTest> {
return test_value;
}
- FRIEND_BASE_SINGLETON_CLASS (SingletonTest);
+ FRIEND_BASE_SINGLETON_CLASS(SingletonTest);
+
private:
int test_value;
};
TEST(SingletonTest, CreateAndDestroySingleton) {
- //assert
+ // assert
ASSERT_EQ(SingletonTest::instance(), SingletonTest::instance());
ASSERT_EQ(0, SingletonTest::instance()->GetValue());
ASSERT_TRUE(SingletonTest::exists());
SingletonTest::instance()->SetValue(5);
ASSERT_EQ(5, SingletonTest::instance()->GetValue());
- //act
+ // act
SingletonTest::destroy();
- //assert
+ // assert
ASSERT_FALSE(SingletonTest::exists());
}
TEST(SingletonTest, DestroySingletonTwice) {
- //assert
+ // assert
ASSERT_EQ(0, SingletonTest::instance()->GetValue());
ASSERT_TRUE(SingletonTest::exists());
- //act
+ // act
SingletonTest::destroy();
- //assert
+ // assert
ASSERT_FALSE(SingletonTest::exists());
- //act
+ // act
SingletonTest::destroy();
- //assert
+ // assert
ASSERT_FALSE(SingletonTest::exists());
}
TEST(SingletonTest, DeleteSingletonCreateAnother) {
- //arrange
+ // arrange
SingletonTest::instance()->SetValue(10);
- //assert
+ // assert
ASSERT_TRUE(SingletonTest::exists());
ASSERT_EQ(10, SingletonTest::instance()->GetValue());
- //act
+ // act
SingletonTest::destroy();
- //assert
+ // assert
ASSERT_FALSE(SingletonTest::exists());
- //act
+ // act
SingletonTest::instance();
- //assert
+ // assert
ASSERT_EQ(0, SingletonTest::instance()->GetValue());
ASSERT_TRUE(SingletonTest::exists());
SingletonTest::destroy();
}
void* func_pthread1(void*) {
- SingletonTest* singleton_in_other_thread = SingletonTest::instance();
+ SingletonTest* singleton_in_other_thread = SingletonTest::instance();
pthread_exit(singleton_in_other_thread);
return NULL;
}
-void* func_pthread2(void * value) {
- SingletonTest * instance = reinterpret_cast<SingletonTest *>(value);
+void* func_pthread2(void* value) {
+ SingletonTest* instance = reinterpret_cast<SingletonTest*>(value);
instance->destroy();
- pthread_exit (NULL);
+ pthread_exit(NULL);
return NULL;
}
TEST(SingletonTest, CreateSingletonInDifferentThreads) {
- //arrange
+ // arrange
SingletonTest::instance();
ASSERT_TRUE(SingletonTest::exists());
pthread_t thread1;
pthread_create(&thread1, NULL, func_pthread1, NULL);
- void *instance2;
+ void* instance2;
pthread_join(thread1, &instance2);
- SingletonTest * instance_2 = reinterpret_cast<SingletonTest *>(instance2);
+ SingletonTest* instance_2 = reinterpret_cast<SingletonTest*>(instance2);
- //assert
+ // assert
ASSERT_EQ(SingletonTest::instance(), instance_2);
- //act
+ // act
SingletonTest::destroy();
- //assert
+ // assert
ASSERT_FALSE(SingletonTest::exists());
}
TEST(SingletonTest, CreateDeleteSingletonInDifferentThreads) {
- //arrange
+ // arrange
pthread_t thread1;
pthread_create(&thread1, NULL, func_pthread1, NULL);
pthread_t thread2;
pthread_create(&thread2, NULL, func_pthread1, NULL);
- void *instance1;
+ void* instance1;
pthread_join(thread1, &instance1);
- SingletonTest * instance_1 = reinterpret_cast<SingletonTest *>(instance1);
+ SingletonTest* instance_1 = reinterpret_cast<SingletonTest*>(instance1);
- void *instance2;
+ void* instance2;
pthread_join(thread2, &instance2);
- SingletonTest * instance_2 = reinterpret_cast<SingletonTest *>(instance2);
+ SingletonTest* instance_2 = reinterpret_cast<SingletonTest*>(instance2);
- //assert
+ // assert
ASSERT_TRUE(instance_1->exists());
ASSERT_TRUE(instance_2->exists());
ASSERT_EQ(instance_1, instance_2);
- //act
+ // act
SingletonTest::destroy();
- //assert
+ // assert
ASSERT_FALSE(instance_1->exists());
ASSERT_FALSE(instance_2->exists());
}
TEST(SingletonTest, DeleteSingletonInDifferentThread) {
- //arrange
+ // arrange
SingletonTest::instance();
ASSERT_TRUE(SingletonTest::exists());
@@ -180,7 +180,7 @@ TEST(SingletonTest, DeleteSingletonInDifferentThread) {
pthread_join(thread1, NULL);
- //assert
+ // assert
ASSERT_FALSE(SingletonTest::exists());
}
diff --git a/src/components/utils/test/smartDeviceLink.ini b/src/components/utils/test/smartDeviceLink.ini
new file mode 100644
index 0000000000..8172b3dea6
--- /dev/null
+++ b/src/components/utils/test/smartDeviceLink.ini
@@ -0,0 +1,19 @@
+; The INI-file consists of different chapters.
+; Each chapter begins with the line containing
+; the name in square brackets. Syntax:
+; [chapter]
+; The chapters consists of a set of items with a
+; assigned value. The syntax is:
+; item=value
+; All white spaces an second encounters of chapters
+; or items will be ignored.
+; Remarks start with semicolon or star as first character.
+; It is allowed for names of chapters and items to
+; contain semicolon and star. Possible syntax is:
+; [ chapter ] ;Remark
+; item = value ;Remark
+
+[MAIN]
+
+; All logging event could be dropped by setting $LogsEnabled to false
+LogsEnabled = true
diff --git a/src/components/utils/test/sqlite_wrapper/sql_database_test.cc b/src/components/utils/test/sqlite_wrapper/sql_database_test.cc
new file mode 100644
index 0000000000..bd278a863f
--- /dev/null
+++ b/src/components/utils/test/sqlite_wrapper/sql_database_test.cc
@@ -0,0 +1,223 @@
+/* Copyright (c) 2014, Ford Motor Company
+* All rights reserved.
+*
+* Redistribution and use in source and binary forms, with or without
+* modification, are permitted provided that the following conditions are met:
+*
+* Redistributions of source code must retain the above copyright notice, this
+* list of conditions and the following disclaimer.
+*
+* Redistributions in binary form must reproduce the above copyright notice,
+* this list of conditions and the following
+* disclaimer in the documentation and/or other materials provided with the
+* distribution.
+*
+* Neither the name of the Ford Motor Company nor the names of its contributors
+* may be used to endorse or promote products derived from this software
+* without specific prior written permission.
+*
+* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+* POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include "gtest/gtest.h"
+#include "utils/sqlite_wrapper/sql_error.h"
+#include "utils/sqlite_wrapper/sql_database.h"
+
+using ::utils::dbms::SQLError;
+using ::utils::dbms::SQLDatabase;
+
+namespace test {
+namespace components {
+namespace utils {
+namespace dbms {
+
+::testing::AssertionResult IsError(SQLError error) {
+ if (error.number() != ::utils::dbms::OK) {
+ return ::testing::AssertionSuccess() << error.text();
+ } else {
+ return ::testing::AssertionFailure() << error.text();
+ }
+}
+
+TEST(SQLDatabaseTest, OpenCloseMemory_OpenAndCloseDB_ActsWithoutError) {
+ // arrange
+ SQLDatabase db;
+ bool ret = db.Open();
+
+ // assert
+ EXPECT_FALSE(IsError(db.LastError()));
+ ASSERT_TRUE(ret);
+
+ // act
+ db.Close();
+
+ // assert
+ EXPECT_FALSE(IsError(db.LastError()));
+}
+
+TEST(SQLDatabaseTest, OpenCloseFile_OpenAndCloseSpecifiedDB_ActsWithoutError) {
+ // arrange
+ SQLDatabase db("test-database");
+ bool ret = db.Open();
+
+ // assert
+ EXPECT_FALSE(IsError(db.LastError()));
+ ASSERT_TRUE(ret);
+
+ // act
+ db.Close();
+
+ // assert
+ EXPECT_FALSE(IsError(db.LastError()));
+
+ remove("test-database.sqlite");
+}
+
+TEST(SQLDatabaseTest, OpenDBTwice_NoError) {
+ // arrange
+ SQLDatabase db;
+ bool ret = db.Open();
+
+ // assert
+ EXPECT_FALSE(IsError(db.LastError()));
+ ASSERT_TRUE(ret);
+
+ // act
+ ret = db.Open();
+
+ // assert
+ EXPECT_FALSE(IsError(db.LastError()));
+ ASSERT_TRUE(ret);
+
+ db.Close();
+}
+
+TEST(SQLDatabaseTest, CloseDBTwice_NoError) {
+ // arrange
+ SQLDatabase db;
+ bool ret = db.Open();
+
+ // assert
+ EXPECT_FALSE(IsError(db.LastError()));
+ ASSERT_TRUE(ret);
+
+ // act
+ db.Close();
+
+ // assert
+ EXPECT_FALSE(IsError(db.LastError()));
+
+ // act
+ db.Close();
+
+ // assert
+ EXPECT_FALSE(IsError(db.LastError()));
+}
+
+TEST(SQLDatabaseTest, Close_DBWasNotOpened_NoError) {
+ // act
+ SQLDatabase db;
+ db.Close();
+
+ // assert
+ EXPECT_FALSE(IsError(db.LastError()));
+}
+
+TEST(SQLDatabaseTest,
+ CommitTransaction_StartAndCommitTransaction_ExpectActsWithoutError) {
+ // arrange
+ SQLDatabase db;
+
+ // assert
+ ASSERT_TRUE(db.Open());
+ EXPECT_TRUE(db.BeginTransaction());
+ EXPECT_FALSE(IsError(db.LastError()));
+ EXPECT_TRUE(db.CommitTransaction());
+ EXPECT_FALSE(IsError(db.LastError()));
+
+ db.Close();
+}
+
+TEST(SQLDatabaseTest,
+ RollbackTransaction_StartAndRollbackTransaction_ExpectActsWithoutError) {
+ // arrange
+ SQLDatabase db;
+
+ // assert
+ ASSERT_TRUE(db.Open());
+ EXPECT_TRUE(db.BeginTransaction());
+ EXPECT_FALSE(IsError(db.LastError()));
+ EXPECT_TRUE(db.RollbackTransaction());
+ EXPECT_FALSE(IsError(db.LastError()));
+
+ db.Close();
+}
+
+TEST(SQLDatabaseTest,
+ FailedCommitTransaction_CommitTransactionWithoutBeginning_ExpectError) {
+ // arrange
+ SQLDatabase db;
+
+ // assert
+ ASSERT_TRUE(db.Open());
+ EXPECT_FALSE(db.CommitTransaction());
+ EXPECT_TRUE(IsError(db.LastError()));
+
+ db.Close();
+}
+
+TEST(
+ SQLDatabaseTest,
+ FailedRollbackTransaction_RollbackTransactionWithoutBeginning_ExpectError) {
+ // arrange
+ SQLDatabase db;
+
+ // assert
+ ASSERT_TRUE(db.Open());
+ EXPECT_FALSE(db.RollbackTransaction());
+ EXPECT_TRUE(IsError(db.LastError()));
+
+ db.Close();
+}
+
+TEST(SQLDatabaseTest, BadTransaction_BeginTransitionWithoutOpenDB_ExpectError) {
+ // arrange
+ SQLDatabase db;
+
+ // assert
+ EXPECT_FALSE(db.BeginTransaction());
+ EXPECT_TRUE(IsError(db.LastError()));
+}
+
+TEST(SQLDatabaseTest, IsReadWrite_FirstOpenDBIsRWSecondIsNot) {
+ // arrange
+ SQLDatabase db("test-database");
+
+ // assert
+ ASSERT_TRUE(db.Open());
+ EXPECT_TRUE(db.IsReadWrite());
+ db.Close();
+ chmod("test-database.sqlite", S_IRUSR);
+
+ // assert
+ ASSERT_TRUE(db.Open());
+ EXPECT_FALSE(db.IsReadWrite());
+
+ db.Close();
+ remove("test-database.sqlite");
+}
+
+} // namespace dbms
+} // namespace utils
+} // namespace components
+} // namespace test
diff --git a/src/components/utils/test/sqlite_wrapper/sql_query_test.cc b/src/components/utils/test/sqlite_wrapper/sql_query_test.cc
new file mode 100644
index 0000000000..958fed93fa
--- /dev/null
+++ b/src/components/utils/test/sqlite_wrapper/sql_query_test.cc
@@ -0,0 +1,380 @@
+/* Copyright (c) 2014, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <string>
+#include <sqlite3.h>
+
+#include "gtest/gtest.h"
+
+#include "utils/sqlite_wrapper/sql_error.h"
+#include "utils/sqlite_wrapper/sql_database.h"
+#include "utils/sqlite_wrapper/sql_query.h"
+
+using ::utils::dbms::SQLError;
+using ::utils::dbms::SQLDatabase;
+using ::utils::dbms::SQLQuery;
+
+namespace test {
+namespace components {
+namespace utils {
+namespace dbms {
+
+class SQLQueryTest : public ::testing::Test {
+ protected:
+ static sqlite3* conn;
+ static const std::string kDatabaseName;
+
+ static void SetUpTestCase() {
+ sqlite3_open((kDatabaseName + ".sqlite").c_str(), &conn);
+ sqlite3_exec(conn,
+ "CREATE TABLE testTable (integerValue INTEGER,"
+ " doubleValue REAL, stringValue TEXT)",
+ NULL,
+ NULL,
+ NULL);
+ }
+
+ static void TearDownTestCase() {
+ sqlite3_close(conn);
+ remove((kDatabaseName + ".sqlite").c_str());
+ }
+
+ void SetUp() {
+ sqlite3_exec(conn, "DELETE FROM testTable", NULL, NULL, NULL);
+ }
+
+ ::testing::AssertionResult IsError(SQLError error) {
+ if (error.number() != ::utils::dbms::OK) {
+ return ::testing::AssertionSuccess() << error.text();
+ } else {
+ return ::testing::AssertionFailure() << error.text();
+ }
+ }
+
+ ::testing::AssertionResult IsDone(SQLError error) {
+ if (error.number() == ::utils::dbms::DONE) {
+ return ::testing::AssertionSuccess() << error.text();
+ } else {
+ return ::testing::AssertionFailure() << error.text();
+ }
+ }
+
+ ::testing::AssertionResult IsRow(SQLError error) {
+ if (error.number() == ::utils::dbms::ROW) {
+ return ::testing::AssertionSuccess() << error.text();
+ } else {
+ return ::testing::AssertionFailure() << error.text();
+ }
+ }
+};
+
+sqlite3* SQLQueryTest::conn = 0;
+const std::string SQLQueryTest::kDatabaseName = "test-query";
+
+TEST_F(SQLQueryTest, Query_CreateQuery_QueryInDBEqualCreated) {
+ // arrange
+ const std::string kSelect("SELECT * FROM testTable WHERE integerValue = ?");
+ SQLDatabase db(kDatabaseName);
+
+ // assert
+ ASSERT_TRUE(db.Open());
+
+ // act
+ SQLQuery query(&db);
+ query.Prepare(kSelect);
+
+ // assert
+ EXPECT_STREQ(kSelect.c_str(), query.query().c_str());
+}
+
+TEST_F(SQLQueryTest, ExecString_ExecuteQuery_ActWithoutError) {
+ // arrange
+ const std::string kInsert(
+ "INSERT INTO testTable"
+ " (integerValue, doubleValue, stringValue)"
+ " VALUES(2, 3.4, 'five-пять')");
+ SQLDatabase db(kDatabaseName);
+ // assert
+ ASSERT_TRUE(db.Open());
+
+ // act
+ SQLQuery query(&db);
+
+ // assert
+ EXPECT_TRUE(query.Exec(kInsert));
+ EXPECT_FALSE(IsError(query.LastError()));
+}
+
+TEST_F(SQLQueryTest,
+ Bind_BindSeveralQueries_ExpectExecutedQueriesWithoutErrors) {
+ // arrange
+ const std::string kInsert1("INSERT INTO testTable (integerValue) VALUES (?)");
+ const std::string kInsert2("INSERT INTO testTable (doubleValue) VALUES (?)");
+ const std::string kInsert3("INSERT INTO testTable (stringValue) VALUES (?)");
+ const std::string kInsert4(
+ "INSERT INTO testTable (integerValue, doubleValue,"
+ " stringValue) VALUES (?, ?, ?)");
+ const int kIntegerValue = 1;
+ const double kDoubleValue = 2.3;
+ const std::string kStringValue = "four";
+
+ SQLDatabase db(kDatabaseName);
+
+ // assert
+ ASSERT_TRUE(db.Open());
+
+ // act
+ SQLQuery query1(&db);
+
+ // assert
+ EXPECT_TRUE(query1.Prepare(kInsert1));
+ EXPECT_FALSE(IsError(query1.LastError()));
+ query1.Bind(0, kIntegerValue);
+
+ // assert
+ EXPECT_FALSE(IsError(query1.LastError()));
+ EXPECT_TRUE(query1.Exec());
+ EXPECT_TRUE(IsDone(query1.LastError()));
+
+ // act
+ SQLQuery query2(&db);
+ // assert
+ EXPECT_TRUE(query2.Prepare(kInsert2));
+ EXPECT_FALSE(IsError(query2.LastError()));
+ query2.Bind(0, kDoubleValue);
+ // assert
+ EXPECT_FALSE(IsError(query2.LastError()));
+ EXPECT_TRUE(query2.Exec());
+ EXPECT_TRUE(IsDone(query2.LastError()));
+
+ // act
+ SQLQuery query3(&db);
+ EXPECT_TRUE(query3.Prepare(kInsert3));
+ EXPECT_FALSE(IsError(query3.LastError()));
+ query3.Bind(0, kStringValue);
+ // assert
+ EXPECT_FALSE(IsError(query3.LastError()));
+ EXPECT_TRUE(query3.Exec());
+ EXPECT_TRUE(IsDone(query3.LastError()));
+
+ // act
+ SQLQuery query4(&db);
+ // assert
+ EXPECT_TRUE(query4.Prepare(kInsert4));
+ EXPECT_FALSE(IsError(query4.LastError()));
+ query4.Bind(0, kIntegerValue);
+ query4.Bind(1, kDoubleValue);
+ query4.Bind(2, kStringValue);
+ // assert
+ EXPECT_FALSE(IsError(query4.LastError()));
+ EXPECT_TRUE(query4.Exec());
+ EXPECT_TRUE(IsDone(query4.LastError()));
+}
+
+TEST_F(SQLQueryTest, SetValue_InsertValues_ExpectDBHasInsertedValues) {
+ // arrange
+ const char* insert =
+ "INSERT INTO testTable "
+ "(integerValue, doubleValue, stringValue) "
+ "VALUES (1, 2.3, 'four');";
+
+ // assert
+ ASSERT_EQ(SQLITE_OK, sqlite3_exec(conn, insert, NULL, NULL, NULL));
+
+ // act
+ const std::string kSelect(
+ "SELECT integerValue, doubleValue, stringValue"
+ " FROM testTable");
+ const int kIntegerValue = 1;
+ const double kDoubleValue = 2.3;
+ const std::string kStringValue = "four";
+
+ SQLDatabase db(kDatabaseName);
+
+ // assert
+ ASSERT_TRUE(db.Open());
+
+ // act
+ SQLQuery query(&db);
+
+ // assert
+ EXPECT_TRUE(query.Prepare(kSelect));
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Exec());
+ EXPECT_TRUE(IsRow(query.LastError()));
+ EXPECT_EQ(kIntegerValue, query.GetInteger(0));
+ EXPECT_EQ(kDoubleValue, query.GetDouble(1));
+ EXPECT_EQ(kStringValue, query.GetString(2));
+ EXPECT_FALSE(query.Next());
+ EXPECT_TRUE(IsDone(query.LastError()));
+}
+
+TEST_F(SQLQueryTest, EmptySelect_SelectValuesEqual0_ExecWithoutErrors) {
+ // arrange
+ const std::string kSelect(
+ "SELECT integerValue, doubleValue, stringValue"
+ " FROM testTable WHERE 0");
+ SQLDatabase db(kDatabaseName);
+
+ // assert
+ ASSERT_TRUE(db.Open());
+
+ // act
+ SQLQuery query(&db);
+
+ // assert
+ EXPECT_TRUE(query.Prepare(kSelect));
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Exec());
+ EXPECT_TRUE(IsDone(query.LastError()));
+}
+
+TEST_F(
+ SQLQueryTest,
+ NextAndBind_InsertValuesAndBindQuery_ExecWithoutErrorsAndBindingQueryIsLast) {
+ // arrange
+ const char* insert =
+ "INSERT INTO testTable "
+ "(integerValue, doubleValue, stringValue) "
+ "VALUES (1, 2.3, 'four');";
+
+ // assert
+ ASSERT_EQ(SQLITE_OK, sqlite3_exec(conn, insert, NULL, NULL, NULL));
+
+ const std::string kSelect(
+ "SELECT integerValue, doubleValue, stringValue"
+ " FROM testTable WHERE stringValue = ?");
+
+ // act
+ const int kIntegerValue = 1;
+ const double kDoubleValue = 2.3;
+ const std::string kStringValue = "four";
+
+ SQLDatabase db(kDatabaseName);
+ ASSERT_TRUE(db.Open());
+
+ SQLQuery query(&db);
+
+ // assert
+ ASSERT_TRUE(query.Prepare(kSelect));
+ EXPECT_FALSE(IsError(query.LastError()));
+ // act
+ query.Bind(0, kStringValue);
+ // assert
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Exec());
+ ASSERT_TRUE(IsRow(query.LastError()));
+ EXPECT_EQ(kIntegerValue, query.GetInteger(0));
+ EXPECT_EQ(kDoubleValue, query.GetDouble(1));
+ EXPECT_EQ(kStringValue, query.GetString(2));
+ EXPECT_FALSE(query.Next());
+ EXPECT_TRUE(IsDone(query.LastError()));
+}
+
+TEST_F(SQLQueryTest, LastInsertId_InsertValuesAndBindQuery_GetExpectedId) {
+ // arrange
+ const char* create =
+ "CREATE TABLE idTable ( "
+ "id INTEGER PRIMARY KEY AUTOINCREMENT,"
+ "value TEXT)";
+
+ // assert
+ ASSERT_EQ(SQLITE_OK, sqlite3_exec(conn, create, NULL, NULL, NULL));
+
+ const int64_t kExpectId = 1;
+ const std::string kValue("Test last id of insert row");
+ const std::string kInsert("INSERT INTO idTable (value) VALUES(?)");
+
+ // act
+ SQLDatabase db(kDatabaseName);
+
+ // assert
+ ASSERT_TRUE(db.Open());
+
+ // act
+ SQLQuery query(&db);
+
+ // assert
+ ASSERT_TRUE(query.Prepare(kInsert));
+ EXPECT_FALSE(IsError(query.LastError()));
+
+ // act
+ query.Bind(0, kValue);
+ // assert
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Exec());
+ ASSERT_TRUE(IsDone(query.LastError()));
+ EXPECT_EQ(kExpectId, query.LastInsertId());
+
+ ASSERT_EQ(SQLITE_OK,
+ sqlite3_exec(conn, "DROP TABLE idTable", NULL, NULL, NULL));
+}
+
+TEST_F(SQLQueryTest, BindNull_BindWithoutValue_ActWithoutErrors) {
+ // arrange
+ const std::string kInsert(
+ "INSERT INTO testTable (`integerValue`)"
+ " VALUES (?)");
+ SQLDatabase db(kDatabaseName);
+ // assert
+ ASSERT_TRUE(db.Open());
+
+ // act
+ SQLQuery query(&db);
+
+ // assert
+ ASSERT_TRUE(query.Prepare(kInsert));
+ EXPECT_FALSE(IsError(query.LastError()));
+ query.Bind(0);
+ // assert
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Exec());
+ ASSERT_TRUE(IsDone(query.LastError()));
+}
+
+TEST_F(SQLQueryTest, DoublePrepare_TwicePrepareQuery_ActWithoutErrors) {
+ // arrange
+ SQLDatabase db(kDatabaseName);
+ // assert
+ ASSERT_TRUE(db.Open());
+ // act
+ SQLQuery query(&db);
+ // assert
+ EXPECT_TRUE(query.Prepare("SELECT * FROM testTable"));
+ EXPECT_FALSE(IsError(query.LastError()));
+ EXPECT_TRUE(query.Prepare("SELECT * FROM testTable"));
+ EXPECT_FALSE(IsError(query.LastError()));
+}
+
+} // namespace dbms
+} // namespace utils
+} // namespace components
+} // namespace test
diff --git a/src/components/utils/test/stl_utils_test.cc b/src/components/utils/test/stl_utils_test.cc
index dfc00de982..1fbde052f1 100644
--- a/src/components/utils/test/stl_utils_test.cc
+++ b/src/components/utils/test/stl_utils_test.cc
@@ -44,8 +44,7 @@ using ::utils::StlMapDeleter;
class TestObject {
public:
- ~TestObject() {
- }
+ ~TestObject() {}
};
typedef std::map<int, TestObject*> TestMap;
@@ -56,9 +55,7 @@ TEST(StlDeleter, DestructMapWithOneElement) {
test_map[1] = new TestObject();
EXPECT_EQ(1u, test_map.size());
- {
- StlMapDeleter<TestMap> test_list_deleter_(&test_map);
- }
+ { StlMapDeleter<TestMap> test_list_deleter_(&test_map); }
EXPECT_EQ(1u, test_map.size());
EXPECT_EQ(NULL, test_map[1]);
}
@@ -69,9 +66,7 @@ TEST(StlDeleter, DestructMapWithSeveralElements) {
test_map[2] = new TestObject();
EXPECT_EQ(2u, test_map.size());
- {
- StlMapDeleter<TestMap> test_list_deleter_(&test_map);
- }
+ { StlMapDeleter<TestMap> test_list_deleter_(&test_map); }
EXPECT_EQ(2u, test_map.size());
EXPECT_EQ(NULL, test_map[1]);
EXPECT_EQ(NULL, test_map[2]);
@@ -82,9 +77,7 @@ TEST(StlDeleter, DestructVectorWithOneElement) {
test_vector.push_back(new TestObject());
EXPECT_EQ(1u, test_vector.size());
- {
- StlCollectionDeleter<TestVector> test_list_deleter_(&test_vector);
- }
+ { StlCollectionDeleter<TestVector> test_list_deleter_(&test_vector); }
EXPECT_EQ(1u, test_vector.size());
EXPECT_EQ(NULL, test_vector[0]);
}
@@ -95,9 +88,7 @@ TEST(StlDeleter, DestructVectorWithSeveralElements) {
test_vector.push_back(new TestObject());
EXPECT_EQ(2u, test_vector.size());
- {
- StlCollectionDeleter<TestVector> test_list_deleter_(&test_vector);
- }
+ { StlCollectionDeleter<TestVector> test_list_deleter_(&test_vector); }
EXPECT_EQ(2u, test_vector.size());
EXPECT_EQ(NULL, test_vector[0]);
EXPECT_EQ(NULL, test_vector[1]);
diff --git a/src/components/utils/test/system_test.cc b/src/components/utils/test/system_test.cc
index 42307998b4..aced77f849 100644
--- a/src/components/utils/test/system_test.cc
+++ b/src/components/utils/test/system_test.cc
@@ -62,7 +62,6 @@ TEST(SystemTest, Constructor_WithFileNameCommandName_ExpectArgsStored) {
// Check if actual number of arguments arec correct
int vec_size = object.argv().size();
ASSERT_EQ(vec_size, 1); // Correct number of arguments is 1
-
}
TEST(SystemTest, AddTwoArgsToCommand_ExpectTwoArgsAdded) {
@@ -93,33 +92,39 @@ TEST(SystemTest, AddTwoArgsToCommand_CheckOrder_ExpectOrderCorrect) {
EXPECT_STREQ(object.argv()[2].c_str(), args[1]);
}
-
-
TEST(SystemTest, SynchronousInvokeWithExistingCommand_ExpectSuccessfull) {
const std::string test_command("./testscript.sh");
System object(test_command);
- // Check if Execute() method is working properly with synchronous command invoke
+ // Check if Execute() method is working properly with synchronous command
+ // invoke
ASSERT_TRUE(object.Execute(true));
}
-TEST(SystemTest, SynchronousInvokeWithEmptyCommand_IncorrectCommand_ExpectFailed) {
+TEST(SystemTest,
+ SynchronousInvokeWithEmptyCommand_IncorrectCommand_ExpectFailed) {
const std::string test_command(""); // any incorrect command
System object(test_command);
- // Check if Execute() method will fail with not correct command (synchronous command invoke)
+ // Check if Execute() method will fail with not correct command (synchronous
+ // command invoke)
ASSERT_FALSE(object.Execute(true));
}
TEST(SystemTest, ASynchronousInvokeEmptyCommand_InvokeSuccessfull) {
- const std::string test_command(""); // Possible to put here any command (existing or incorrect)
- const std::string test_list_args("anything"); // as command will never be executed from child process
- System object(test_command, test_list_args); // as parrent process does not wait for child process to be finished
-
- // Check if Execute() method is working properly with asynchronous command invoke
+ const std::string test_command(
+ ""); // Possible to put here any command (existing or incorrect)
+ const std::string test_list_args(
+ "anything"); // as command will never be executed from child process
+ System object(test_command, test_list_args); // as parrent process does not
+ // wait for child process to be
+ // finished
+
+ // Check if Execute() method is working properly with asynchronous command
+ // invoke
ASSERT_TRUE(object.Execute());
}
-} // namespace utils
-} // namespace components
-} // namespace test
+} // namespace utils
+} // namespace components
+} // namespace test
diff --git a/src/components/utils/test/test_generator/CMakeLists.txt b/src/components/utils/test/test_generator/CMakeLists.txt
new file mode 100644
index 0000000000..170fb3f10b
--- /dev/null
+++ b/src/components/utils/test/test_generator/CMakeLists.txt
@@ -0,0 +1,65 @@
+# Copyright (c) 2015, Ford Motor Company
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer.
+#
+# Redistributions in binary form must reproduce the above copyright notice,
+# this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided with the
+# distribution.
+#
+# Neither the name of the Ford Motor Company nor the names of its contributors
+# may be used to endorse or promote products derived from this software
+# without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+# POSSIBILITY OF SUCH DAMAGE.
+
+if(BUILD_TESTS)
+
+include_directories (
+ ${JSONCPP_INCLUDE_DIRECTORY}
+ ${CMAKE_SOURCE_DIR}/src/3rd_party-static/gmock-1.7.0/include
+ ${CMAKE_SOURCE_DIR}/src/3rd_party-static/gmock-1.7.0/gtest/include
+ ${CMAKE_SOURCE_DIR}/tools/interfaceGenerator
+ ${CMAKE_CURRENT_BINARY_DIR}
+ ${COMPONENTS_DIR}/utils/include/utils
+ ${COMPONENTS_DIR}/include/utils
+)
+
+set(full_xml_name "${CMAKE_CURRENT_SOURCE_DIR}/MOBILE_API.xml")
+
+add_custom_target( generate_version
+ COMMAND ${INTEFRACE_GENERATOR_CMD} ${full_xml_name} "mobile_apis"
+ ${CMAKE_CURRENT_BINARY_DIR} "--parser-type" "sdlrpcv2"
+ DEPENDS ${INTERFACE_GENERATOR_DEPENDENCIES} ${full_xml_name}
+ VERBATIM
+ )
+
+set(testLibraries
+ gmock
+ Utils
+)
+
+set(testSources
+ generated_msg_version_test.cc
+)
+
+file(COPY MOBILE_API.xml DESTINATION ${CMAKE_CURRENT_BINARY_DIR})
+create_test("generator_test" "${testSources}" "${testLibraries}")
+add_dependencies("generator_test" generate_version)
+
+endif()
diff --git a/src/components/utils/test/test_generator/MOBILE_API.xml b/src/components/utils/test/test_generator/MOBILE_API.xml
new file mode 100644
index 0000000000..01ea48dce9
--- /dev/null
+++ b/src/components/utils/test/test_generator/MOBILE_API.xml
@@ -0,0 +1,4999 @@
+<?xml version="1.0" standalone="no"?>
+<?xml-stylesheet type="text/xml" href="protocol2html.xsl"?>
+
+<interface name="Ford Sync RAPI" version="3.1" date="2015-11-13">
+
+ <enum name="Result" internal_scope="base">
+ <element name="SUCCESS">
+ <description>The request succeeded</description>
+ </element>
+ <element name="UNSUPPORTED_REQUEST">
+ <description>The request is not supported by Sync</description>
+ </element>
+ <element name="UNSUPPORTED_RESOURCE">
+ <description>
+ A button that was requested for subscription is not supported under the current system.
+ NOTE: could become a more generic UNSUPPORTED_RESOURCE by merging with VEHIVLE_DATA_NOT_AVAILABLE.
+ </description>
+ </element>
+ <element name="DISALLOWED">
+ <description>RPC is not authorized in local policy table.</description>
+ </element>
+ <element name="REJECTED">
+ <description>
+ The requested command was rejected, e.g. because mobile app is in background and cannot perform any HMI commands.
+ Or an HMI command (e.g. Speak) is rejected because a higher priority HMI command (e.g. Alert) is playing.
+ </description>
+ </element>
+ <element name="ABORTED">
+ <description>
+ A command was aborted, for example due to user interaction (e.g. user pressed button).
+ Or an HMI command (e.g. Speak) is aborted because a higher priority HMI command (e.g. Alert) was requested.
+ </description>
+ </element>
+ <element name="IGNORED">
+ <description>
+ A command was ignored, because the intended result is already in effect.
+ For example, SetMediaClockTimer was used to pause the media clock although the clock is paused already.
+ NOTE: potentially replaces SUBSCRIBED_ALREADY
+ </description>
+ </element>
+ <element name="RETRY">
+ <description>The user interrupted the RPC (e.g. PerformAudioPassThru) and indicated to start over. Note, the app must issue the new RPC.</description>
+ </element>
+ <element name="IN_USE">
+ <description>
+ The data may not be changed, because it is currently in use.
+ For example when trying to delete a command set that is currently involved in an interaction.
+ </description>
+ </element>
+ <element name="VEHICLE_DATA_NOT_AVAILABLE">
+ <description>The requested vehicle data is not available on this vehicle or is not published.</description>
+ </element>
+ <element name="TIMED_OUT">
+ <description>Overlay reached the maximum timeout and closed.</description>
+ </element>
+ <element name="INVALID_DATA">
+ <description>
+ The data sent is invalid. For example:
+ Invalid Json syntax
+ Parameters out of bounds (number or enum range)
+ Mandatory parameters not provided
+ Parameter provided with wrong type
+ Invalid characters
+ Empty string
+ </description>
+ </element>
+ <element name="CHAR_LIMIT_EXCEEDED"/>
+ <element name="INVALID_ID">
+ <description>
+ One of the provided IDs is not valid. For example
+ This applies to CorrelationID, SubscriptionID [@TODO if SubscriptionID is used], CommandID, MenuID, [@TODO: missed one?]
+ </description>
+ </element>
+ <element name="DUPLICATE_NAME">
+ <description>There was a conflict with an registered name (application or menu item) or vr command</description>
+ </element>
+ <element name="APPLICATION_NOT_REGISTERED">
+ <description>An command can not be executed because no application has been registered with RegisterApplication.</description>
+ </element>
+ <element name="WRONG_LANGUAGE">
+ <description>
+ The requested language is currently not supported.
+ Might be because of a mismatch of the currently active language on Sync and the requested language
+ </description>
+ </element>
+ <element name="OUT_OF_MEMORY">
+ <description>The system could not process the request because the necessary memory couldn't be allocated</description>
+ </element>
+ <element name="TOO_MANY_PENDING_REQUESTS">
+ <description>There are too many requests pending (means, that the response has not been delivered, yet).</description>
+ <designdescription>There may be a maximum of 1000 pending requests at a time.</designdescription>
+ </element>
+ <element name="TOO_MANY_APPLICATIONS">
+ <description>There are already too many registered applications</description>
+ </element>
+ <element name="APPLICATION_REGISTERED_ALREADY">
+ <description>RegisterApplication has been called again, after a RegisterApplication was successful before.</description>
+ </element>
+ <element name="WARNINGS">
+ <description>The RPC (e.g. SubscribeVehicleData) executed successfully but one or more items have a warning or failure.</description>
+ </element>
+ <element name="GENERIC_ERROR">
+ <description>Provided data is valid but something went wrong in the lower layers.</description>
+ </element>
+ <element name="USER_DISALLOWED">
+ <description>RPC is included in a functional group explicitly blocked by the user.</description>
+ </element>
+ <element name="UNSUPPORTED_VERSION">
+ <description>Sync doesn't support the protocol that is requested by the mobile application</description>
+ </element>
+ <element name="VEHICLE_DATA_NOT_ALLOWED">
+ <description>The user has turned off access to vehicle data, and it is globally unavailable to mobile applications.</description>
+ </element>
+ <element name="FILE_NOT_FOUND">
+ <description>A specified file could not be found on Sync.</description>
+ </element>
+ <element name="CANCEL_ROUTE">
+ <description>User selected to Cancel Route.</description>
+ </element>
+ <element name="TRUNCATED_DATA">
+ <description>The RPC (e.g. ReadDID) executed successfully but the data exceeded the platform maximum threshold and thus, only part of the data is available.</description>
+ </element>
+ <element name="SAVED">
+ <description>The RPC (e.g. Slider) executed successfully and the user elected to save the current position / value.</description>
+ </element>
+ <element name="INVALID_CERT">
+ <description>The certificate provided during authentication is invalid.</description>
+ </element>
+ <element name="EXPIRED_CERT">
+ <description>The certificate provided during authentication is expired.</description>
+ </element>
+ <element name="RESUME_FAILED">
+ <description>The provided hash ID does not match the hash of the current set of registered data or the core could not resume the previous data.</description>
+ </element>
+ </enum>
+
+ <enum name="ButtonPressMode">
+ <element name="LONG">
+ <description>
+ A button was released, after it was pressed for a long time
+ Actual timing is defined by Sync and may vary
+ </description>
+ </element>
+ <element name="SHORT">
+ <description>
+ A button was released, after it was pressed for a short time
+ Actual timing is defined by Sync and may vary
+ </description>
+ </element>
+ </enum>
+
+ <enum name="ButtonEventMode">
+ <element name="BUTTONUP">
+ <description>A button has been released up</description>
+ </element>
+ <element name="BUTTONDOWN">
+ <description>A button has been pressed down</description>
+ </element>
+ </enum>
+
+ <enum name="Language">
+ <element name="EN-US" internal_name="EN_US">
+ <description>English - US</description>
+ </element>
+ <element name="ES-MX" internal_name="ES_MX">
+ <description>Spanish - Mexico</description>
+ </element>
+ <element name="FR-CA" internal_name="FR_CA">
+ <description>French - Canada</description>
+ </element>
+ <element name="DE-DE" internal_name="DE_DE">
+ <description>German - Germany</description>
+ </element>
+ <element name="ES-ES" internal_name="ES_ES">
+ <description>Spanish - Spain</description>
+ </element>
+ <element name="EN-GB" internal_name="EN_GB">
+ <description>English - GB</description>
+ </element>
+ <element name="RU-RU" internal_name="RU_RU">
+ <description>Russian - Russia</description>
+ </element>
+ <element name="TR-TR" internal_name="TR_TR">
+ <description>Turkish - Turkey</description>
+ </element>
+ <element name="PL-PL" internal_name="PL_PL">
+ <description>Polish - Poland</description>
+ </element>
+ <element name="FR-FR" internal_name="FR_FR">
+ <description>French - France</description>
+ </element>
+ <element name="IT-IT" internal_name="IT_IT">
+ <description>Italian - Italy</description>
+ </element>
+ <element name="SV-SE" internal_name="SV_SE">
+ <description>Swedish - Sweden</description>
+ </element>
+ <element name="PT-PT" internal_name="PT_PT">
+ <description>Portuguese - Portugal</description>
+ </element>
+ <element name="NL-NL" internal_name="NL_NL">
+ <description>Dutch (Standard) - Netherlands</description>
+ </element>
+ <element name="EN-AU" internal_name="EN_AU">
+ <description>English - Australia</description>
+ </element>
+ <element name="ZH-CN" internal_name="ZH_CN">
+ <description>Mandarin - China</description>
+ </element>
+ <element name="ZH-TW" internal_name="ZH_TW">
+ <description>Mandarin - Taiwan</description>
+ </element>
+ <element name="JA-JP" internal_name="JA_JP">
+ <description>Japanese - Japan</description>
+ </element>
+ <element name="AR-SA" internal_name="AR_SA">
+ <description>Arabic - Saudi Arabia</description>
+ </element>
+ <element name="KO-KR" internal_name="KO_KR">
+ <description>Korean - South Korea</description>
+ </element>
+ <element name="PT-BR" internal_name="PT_BR">
+ <description>Portuguese - Brazil</description>
+ </element>
+ <element name="CS-CZ" internal_name="CS_CZ">
+ <description>Czech - Czech Republic</description>
+ </element>
+ <element name="DA-DK" internal_name="DA_DK">
+ <description>Danish - Denmark</description>
+ </element>
+ <element name="NO-NO" internal_name="NO_NO">
+ <description>Norwegian - Norway</description>
+ </element>
+ <element name="NL-BE" internal_name="NL_BE">
+ <description>Dutch (Flemish) - Belgium</description>
+ </element>
+ <element name="EL-GR" internal_name="EL_GR">
+ <description>Greek - Greece</description>
+ </element>
+ <element name="HU-HU" internal_name="HU_HU">
+ <description>Hungarian - Hungary</description>
+ </element>
+ <element name="FI-FI" internal_name="FI_FI">
+ <description>Finnish - Finland</description>
+ </element>
+ <element name="SK-SK" internal_name="SK_SK">
+ <description>Slovak - Slovakia</description>
+ </element>
+</enum>
+
+ <enum name="UpdateMode">
+ <description>Describes how the media clock timer should behave on the platform</description>
+ <element name="COUNTUP" />
+ <description>Starts the media clock timer counting upwards, as in time elapsed.</description>
+ <element name="COUNTDOWN" />
+ <description>Starts the media clock timer counting downwards, as in time remaining.</description>
+ <element name="PAUSE" />
+ <description>Pauses the media clock timer</description>
+ <element name="RESUME" />
+ <description>Resume the media clock timer</description>
+ <element name="CLEAR" />
+ <description>Clears the media clock timer (previously done through Show->mediaClock)</description>
+ </enum>
+
+ <enum name="TimerMode">
+ <element name="UP" />
+ <description>Causes the media clock timer to update from 0:00 to a specified time</description>
+ <element name="DOWN" />
+ <description>Causes the media clock timer to update from a specified time to 0:00</description>
+ <element name="NONE" />
+ <description>Indicates to not use the media clock timer</description>
+ </enum>
+
+ <enum name="InteractionMode">
+ <description>For application-requested interactions, this mode indicates the method in which the user is notified and uses the interaction.</description>
+ <element name="MANUAL_ONLY" />
+ <description>
+ This mode causes the interaction to only occur on the display, meaning the choices are provided only via the display.
+ Selections are made with the OK and Seek Right and Left, Tune Up and Down buttons.
+ </description>
+ <element name="VR_ONLY" />
+ <description>
+ This mode causes the interaction to only occur using V4.
+ Selections are made by saying the command.
+ </description>
+ <element name="BOTH" />
+ <description>
+ This mode causes both a VR and display selection option for an interaction.
+ Selections can be made either from the menu display or by speaking the command.
+ </description>
+ </enum>
+
+ <enum name="LayoutMode">
+ <description>For touchscreen interactions, the mode of how the choices are presented.</description>
+ <element name="ICON_ONLY" />
+ <description>
+ This mode causes the interaction to display the previous set of choices as icons.
+ </description>
+ <element name="ICON_WITH_SEARCH" />
+ <description>
+ This mode causes the interaction to display the previous set of choices as icons along with a search field in the HMI.
+ </description>
+ <element name="LIST_ONLY" />
+ <description>
+ This mode causes the interaction to display the previous set of choices as a list.
+ </description>
+ <element name="LIST_WITH_SEARCH" />
+ <description>
+ This mode causes the interaction to display the previous set of choices as a list along with a search field in the HMI.
+ </description>
+ <element name="KEYBOARD" />
+ <description>
+ This mode causes the interaction to immediately display a keyboard entry through the HMI.
+ </description>
+ </enum>
+
+ <enum name="HMILevel">
+ <description>Enumeraction that describes current levels of HMI.</description>
+ <element name="FULL" internal_name="HMI_FULL" />
+ <element name="LIMITED" internal_name="HMI_LIMITED" />
+ <element name="BACKGROUND" internal_name="HMI_BACKGROUND" />
+ <element name="NONE" internal_name="HMI_NONE" />
+ </enum>
+
+ <enum name="AudioStreamingState">
+ <description>Enumeraction that describes possible states of audio streaming.</description>
+ <element name="AUDIBLE" />
+ <element name="ATTENUATED" />
+ <element name="NOT_AUDIBLE" />
+ </enum>
+
+ <enum name="SystemAction">
+ <description>Enumeration that describes system actions that can be triggered.</description>
+ <element name="DEFAULT_ACTION">
+ <description>Default action occurs. Standard behavior (e.g. SoftButton clears overlay).</description>
+ </element>
+ <element name="STEAL_FOCUS">
+ <description>App is brought into HMI_FULL.</description>
+ </element>
+ <element name="KEEP_CONTEXT">
+ <description>Current system context is maintained. An overlay is persisted even though a SoftButton has been pressed and the notification sent.</description>
+ </element>
+ </enum>
+
+ <enum name="SystemContext">
+ <description>Enumeration that describes possible contexts an app's HMI might be in.</description>
+ <description>Communicated to whichever app is in HMI FULL, except Alert.</description>
+ <element name="MAIN" internal_name="SYSCTXT_MAIN">
+ <description>The app's persistent display (whether media/non-media/navigation) is fully visible onscreen.</description>
+ </element>
+ <element name="VRSESSION" internal_name="SYSCTXT_VRSESSION">
+ <description>The system is currently in a VR session (with whatever dedicated VR screen being overlaid onscreen).</description>
+ </element>
+ <element name="MENU" internal_name="SYSCTXT_MENU">
+ <description>The system is currently displaying an in-App menu onscreen.</description>
+ </element>
+ <element name="HMI_OBSCURED" internal_name="SYSCTXT_HMI_OBSCURED">
+ <description>The app's display HMI is currently being obscured by either a system or other app's overlay.</description>
+ </element>
+ <element name="ALERT" internal_name="SYSCTXT_ALERT">
+ <description>Broadcast only to whichever app has an alert currently being displayed.</description>
+ </element>
+ </enum>
+
+ <enum name="SoftButtonType">
+ <description>Contains information about the SoftButton capabilities.</description>
+ <element name="TEXT" internal_name="SBT_TEXT"/>
+ <element name="IMAGE" internal_name="SBT_IMAGE"/>
+ <element name="BOTH" internal_name="SBT_BOTH"/>
+ </enum>
+
+ <enum name="AppInterfaceUnregisteredReason">
+ <description>Error code, which comes from sync side.</description>
+ <element name="USER_EXIT" />
+ <element name="IGNITION_OFF" />
+ <element name="BLUETOOTH_OFF" />
+ <element name="USB_DISCONNECTED" />
+ <element name="REQUEST_WHILE_IN_NONE_HMI_LEVEL" />
+ <element name="TOO_MANY_REQUESTS" />
+ <element name="DRIVER_DISTRACTION_VIOLATION" />
+ <element name="LANGUAGE_CHANGE" />
+ <element name="MASTER_RESET" />
+ <element name="FACTORY_DEFAULTS" />
+ <element name="APP_UNAUTHORIZED" />
+ <element name="PROTOCOL_VIOLATION" />
+ </enum>
+
+ <enum name="TriggerSource">
+ <description>Indicates the source from where the command was triggered.</description>
+ <element name="MENU" internal_name="TS_MENU" />
+ <element name="VR" internal_name="TS_VR" />
+ <element name="KEYBOARD" internal_name="TS_KEYBOARD" />
+ </enum>
+
+ <enum name="HmiZoneCapabilities">
+ <description>Contains information about the HMI zone capabilities.</description>
+ <description>For future use.</description>
+ <element name="FRONT" />
+ <element name="BACK" />
+ </enum>
+
+ <enum name="SpeechCapabilities">
+ <description>Contains information about the TTS capabilities.</description>
+ <element name="TEXT" internal_name="SC_TEXT"/>
+ <element name="SAPI_PHONEMES" />
+ <element name="LHPLUS_PHONEMES" />
+ <element name="PRE_RECORDED" />
+ <element name="SILENCE" />
+ </enum>
+
+ <enum name="VrCapabilities">
+ <description>Contains information about the VR capabilities.</description>
+ <element name="TEXT" internal_name="VR_TEXT"/>
+ </enum>
+
+ <enum name="PrerecordedSpeech">
+ <description>Contains a list of prerecorded speech items present on the platform.</description>
+ <element name="HELP_JINGLE" />
+ <element name="INITIAL_JINGLE" />
+ <element name="LISTEN_JINGLE" />
+ <element name="POSITIVE_JINGLE" />
+ <element name="NEGATIVE_JINGLE" />
+ </enum>
+
+ <enum name="SamplingRate">
+ <description>Describes different sampling options for PerformAudioPassThru.</description>
+ <element name="8KHZ" internal_name="SamplingRate_8KHZ"/>
+ <element name="16KHZ" internal_name="SamplingRate_16KHZ"/>
+ <element name="22KHZ" internal_name="SamplingRate_22KHZ"/>
+ <element name="44KHZ" internal_name="SamplingRate_44KHZ"/>
+ </enum>
+
+ <enum name="BitsPerSample">
+ <description>Describes different quality options for PerformAudioPassThru.</description>
+ <element name="8_BIT" internal_name="BitsPerSample_8_BIT"/>
+ <element name="16_BIT" internal_name="BitsPerSample_16_BIT"/>
+ </enum>
+
+ <enum name="AudioType">
+ <description>Describes different audio type options for PerformAudioPassThru.</description>
+ <element name="PCM" />
+ </enum>
+
+ <struct name="HMICapabilities">
+ <param name="navigation" type="Boolean" mandatory="false">
+ <description>Availability of build in Nav. True: Available, False: Not Available</description>
+ </param>
+ <param name="phoneCall" type="Boolean" mandatory="false">
+ <description>Availability of build in phone. True: Available, False: Not Available</description>
+ </param>
+ </struct>
+
+ <struct name="AudioPassThruCapabilities">
+ <description>Describes different audio type configurations for PerformAudioPassThru.</description>
+ <description>e.g. {8kHz,8-bit,PCM}</description>
+ <param name="samplingRate" type="SamplingRate"/>
+ <param name="bitsPerSample" type="BitsPerSample"/>
+ <param name="audioType" type="AudioType"/>
+ </struct>
+
+ <enum name="VehicleDataType">
+ <description>Defines the data types that can be published and subscribed to.</description>
+ <element name="VEHICLEDATA_GPS">
+ <description>Notifies GPSData may be subscribed</description>
+ </element>
+ <element name="VEHICLEDATA_SPEED" />
+ <element name="VEHICLEDATA_RPM" />
+ <element name="VEHICLEDATA_FUELLEVEL" />
+ <element name="VEHICLEDATA_FUELLEVEL_STATE" />
+ <element name="VEHICLEDATA_FUELCONSUMPTION" />
+ <element name="VEHICLEDATA_EXTERNTEMP" />
+ <element name="VEHICLEDATA_VIN" />
+ <element name="VEHICLEDATA_PRNDL" />
+ <element name="VEHICLEDATA_TIREPRESSURE" />
+ <element name="VEHICLEDATA_ODOMETER" />
+ <element name="VEHICLEDATA_BELTSTATUS" />
+ <element name="VEHICLEDATA_BODYINFO" />
+ <element name="VEHICLEDATA_DEVICESTATUS" />
+ <element name="VEHICLEDATA_ECALLINFO" />
+ <element name="VEHICLEDATA_AIRBAGSTATUS" />
+ <element name="VEHICLEDATA_EMERGENCYEVENT" />
+ <element name="VEHICLEDATA_CLUSTERMODESTATUS" />
+ <element name="VEHICLEDATA_MYKEY" />
+ <element name="VEHICLEDATA_BRAKING" />
+ <element name="VEHICLEDATA_WIPERSTATUS" />
+ <element name="VEHICLEDATA_HEADLAMPSTATUS" />
+ <element name="VEHICLEDATA_BATTVOLTAGE" />
+ <element name="VEHICLEDATA_ENGINETORQUE" />
+ <element name="VEHICLEDATA_ACCPEDAL" />
+ <element name="VEHICLEDATA_STEERINGWHEEL" />
+ </enum>
+
+ <enum name="ButtonName">
+ <description>Defines the hard (physical) and soft (touchscreen) buttons available from SYNC</description>
+ <element name="OK" />
+ <element name="SEEKLEFT" />
+ <element name="SEEKRIGHT" />
+ <element name="TUNEUP" />
+ <element name="TUNEDOWN" />
+ <element name="PRESET_0" />
+ <element name="PRESET_1" />
+ <element name="PRESET_2" />
+ <element name="PRESET_3" />
+ <element name="PRESET_4" />
+ <element name="PRESET_5" />
+ <element name="PRESET_6" />
+ <element name="PRESET_7" />
+ <element name="PRESET_8" />
+ <element name="PRESET_9" />
+ <element name="CUSTOM_BUTTON" />
+ <element name="SEARCH" />
+ </enum>
+
+ <enum name="MediaClockFormat">
+ <element name="CLOCK1">
+ <description>
+ minutesFieldWidth = 2;minutesFieldMax = 19;secondsFieldWidth = 2;secondsFieldMax = 99;maxHours = 19;maxMinutes = 59;maxSeconds = 59;
+ used for Type II and CID headunits
+ </description>
+ </element>
+ <element name="CLOCK2">
+ <description>
+ minutesFieldWidth = 3;minutesFieldMax = 199;secondsFieldWidth = 2;secondsFieldMax = 99;maxHours = 59;maxMinutes = 59;maxSeconds = 59;
+ used for Type V headunit
+ </description>
+ </element>
+ <element name="CLOCK3">
+ <description>
+ minutesFieldWidth = 2;minutesFieldMax = 59;secondsFieldWidth = 2;secondsFieldMax = 59;maxHours = 9;maxMinutes = 59;maxSeconds = 59;
+ used for GEN1.1 MFD3/4/5 headunits
+ </description>
+ </element>
+ <element name="CLOCKTEXT1">
+ <description>
+ 5 characters possible
+ Format: 1|sp c :|sp c c
+ 1|sp : digit "1" or space
+ c : character out of following character set: sp|0-9|[letters, see TypeII column in XLS. See [@TODO: create file ref]]
+ :|sp : colon or space
+ used for Type II headunit
+ </description>
+ </element>
+ <element name="CLOCKTEXT2">
+ <description>
+ 5 chars possible
+ Format: 1|sp c :|sp c c
+ 1|sp : digit "1" or space
+ c : character out of following character set: sp|0-9|[letters, see CID column in XLS. See [@TODO: create file ref]]
+ :|sp : colon or space
+ used for CID headunit
+ NOTE: difference between CLOCKTEXT1 and CLOCKTEXT2 is the supported character set
+ </description>
+ </element>
+ <element name="CLOCKTEXT3">
+ <description>
+ 6 chars possible
+ Format: 1|sp c c :|sp c c
+ 1|sp : digit "1" or space
+ c : character out of following character set: sp|0-9|[letters, see Type 5 column in XLS]. See [@TODO: create file ref]
+ :|sp : colon or space
+ used for Type V headunit
+ </description>
+ </element>
+ <element name="CLOCKTEXT4">
+ <description>
+ 6 chars possible
+ Format: c :|sp c c : c c
+ :|sp : colon or space
+ c : character out of following character set: sp|0-9|[letters].
+ used for GEN1.1 MFD3/4/5 headunits
+ </description>
+ </element>
+ </enum>
+
+ <enum name="DisplayType">
+ <description>See DAES for further infos regarding the displays</description>
+ <element name="CID"/>
+ <element name="TYPE2" />
+ <element name="TYPE5" />
+ <element name="NGN" />
+ <element name="GEN2_8_DMA" />
+ <element name="GEN2_6_DMA" />
+ <element name="MFD3" />
+ <element name="MFD4" />
+ <element name="MFD5" />
+ <element name="GEN3_8-INCH" internal_name="GEN3_8_INCH" />
+ </enum>
+
+ <enum name="TextFieldName">
+ <element name="mainField1">
+ <description>The first line of first set of main fields of the persistent display; applies to "Show"</description>
+ </element>
+
+ <element name="mainField2">
+ <description>The second line of first set of main fields of the persistent display; applies to "Show"</description>
+ </element>
+
+ <element name="mainField3">
+ <description>The first line of second set of main fields of persistent display; applies to "Show"</description>
+ </element>
+
+ <element name="mainField4">
+ <description>The second line of second set of main fields of the persistent display; applies to "Show"</description>
+ </element>
+
+ <element name="statusBar">
+ <description>The status bar on NGN; applies to "Show"</description>
+ </element>
+
+ <element name="mediaClock">
+ <description>Text value for MediaClock field; applies to "Show"</description>
+ </element>
+
+ <element name="mediaTrack">
+ <description>The track field of NGN and GEN1.1 MFD displays. This field is only available for media applications; applies to "Show"</description>
+ </element>
+
+ <element name="alertText1">
+ <description>The first line of the alert text field; applies to "Alert"</description>
+ </element>
+
+ <element name="alertText2">
+ <description>The second line of the alert text field; applies to "Alert"</description>
+ </element>
+
+ <element name="alertText3">
+ <description>The third line of the alert text field; applies to "Alert"</description>
+ </element>
+
+ <element name="scrollableMessageBody">
+ <description>Long form body of text that can include newlines and tabs; applies to "ScrollableMessage"</description>
+ </element>
+
+ <element name="initialInteractionText">
+ <description> First line suggestion for a user response (in the case of VR enabled interaction)</description>
+ </element>
+
+ <element name="navigationText1">
+ <description> First line of navigation text</description>
+ </element>
+
+ <element name="navigationText2">
+ <description> Second line of navigation text</description>
+ </element>
+
+ <element name="ETA">
+ <description> Estimated Time of Arrival time for navigation</description>
+ </element>
+
+ <element name="totalDistance">
+ <description> Total distance to destination for navigation</description>
+ </element>
+
+ <element name="audioPassThruDisplayText1">
+ <description> First line of text for audio pass thru</description>
+ </element>
+
+ <element name="audioPassThruDisplayText2">
+ <description> Second line of text for audio pass thru</description>
+ </element>
+
+ <element name="sliderHeader">
+ <description> Header text for slider</description>
+ </element>
+
+ <element name="sliderFooter">
+ <description> Footer text for slider</description>
+ </element>
+
+ <element name="menuName">
+ <description> Primary text for Choice</description>
+ </element>
+
+ <element name="secondaryText">
+ <description> Secondary text for Choice</description>
+ </element>
+
+ <element name="tertiaryText">
+ <description> Tertiary text for Choice</description>
+ </element>
+
+ <element name="menuTitle">
+ <description> Optional text to label an app menu button (for certain touchscreen platforms).</description>
+ </element>
+
+ <element name="timeToDestination">
+ <description> Time to destination</description>
+ </element>
+
+ <element name="navigationText">
+ <description>Navigation text for UpdateTurnList.</description>
+ </element>
+
+ <element name="notificationText">
+ <description> Footer text for slider</description>
+ </element>
+
+ <element name="locationName">
+ <description> Optional name / title of intended location for SendLocation.</description>
+ </element>
+
+ <element name="locationDescription">
+ <description> Optional description of intended location / establishment (if applicable) for SendLocation.</description>
+ </element>
+
+ <element name="addressLines">
+ <description> Optional location address (if applicable) for SendLocation.</description>
+ </element>
+
+ <element name="phoneNumber">
+ <description> Optional hone number of intended location / establishment (if applicable) for SendLocation.</description>
+ </element>
+
+ <element name="turnText">
+ <description> Turn text</description>
+ </element>
+
+ </enum>
+
+ <enum name="ImageFieldName">
+ <element name="softButtonImage">
+ <description>The image field for SoftButton</description>
+ </element>
+
+ <element name="choiceImage">
+ <description>The first image field for Choice</description>
+ </element>
+
+ <element name="choiceSecondaryImage">
+ <description>The secondary image field for Choice</description>
+ </element>
+
+ <element name="vrHelpItem">
+ <description>The image field for vrHelpItem</description>
+ </element>
+
+ <element name="turnIcon">
+ <description>The image field for Turn</description>
+ </element>
+
+ <element name="menuIcon">
+ <description>The image field for the menu icon in SetGlobalProperties</description>
+ </element>
+
+ <element name="cmdIcon">
+ <description>The image field for AddCommand</description>
+ </element>
+
+ <element name="appIcon">
+ <description>The image field for the app icon (set by setAppIcon)</description>
+ </element>
+
+ <element name="graphic">
+ <description>The image field for Show</description>
+ </element>
+
+ <element name="showConstantTBTIcon">
+ <description>The primary image field for ShowConstantTBT</description>
+ </element>
+
+ <element name="showConstantTBTNextTurnIcon">
+ <description>The secondary image field for ShowConstantTBT</description>
+ </element>
+
+ <element name="locationImage">
+ <description>The optional image of a destination / location</description>
+ </element>
+ </enum>
+
+ <enum name="PredefinedLayout" platform="documentation">
+ <description>Predefined screen layout.</description>
+
+ <element name="DEFAULT" rootscreen="true">
+ <description>
+ Default media / non-media screen.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="MEDIA" rootscreen="true">
+ <description>
+ Default Media screen.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="NON-MEDIA" internal_name="NON_MEDIA" rootscreen="true">
+ <description>
+ Default Non-media screen.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="ONSCREEN_PRESETS" rootscreen="true">
+ <description>
+ Custom root media screen containing app-defined onscreen presets.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="NAV_FULLSCREEN_MAP" rootscreen="true">
+ <description>
+ Custom root template screen containing full screen map with navigation controls.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="NAV_LIST" rootscreen="true">
+ <description>
+ Custom root template screen containing video represented list.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="NAV_KEYBOARD" rootscreen="true">
+ <description>
+ Custom root template screen containing video represented keyboard.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="GRAPHIC_WITH_TEXT" rootscreen="true">
+ <description>
+ Custom root template screen containing half-screen graphic with lines of text.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="TEXT_WITH_GRAPHIC" rootscreen="true">
+ <description>
+ Custom root template screen containing lines of text with half-screen graphic.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="TILES_ONLY" rootscreen="true">
+ <description>
+ Custom root template screen containing only tiled SoftButtons.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="TEXTBUTTONS_ONLY" rootscreen="true">
+ <description>
+ Custom root template screen containing only text SoftButtons.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="GRAPHIC_WITH_TILES" rootscreen="true">
+ <description>
+ Custom root template screen containing half-screen graphic with tiled SoftButtons.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="TILES_WITH_GRAPHIC" rootscreen="true">
+ <description>
+ Custom root template screen containing tiled SoftButtons with half-screen graphic.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="GRAPHIC_WITH_TEXT_AND_SOFTBUTTONS" rootscreen="true">
+ <description>
+ Custom root template screen containing half-screen graphic with text and SoftButtons.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="TEXT_AND_SOFTBUTTONS_WITH_GRAPHIC" rootscreen="true">
+ <description>
+ Custom root template screen containing text and SoftButtons with half-screen graphic.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="GRAPHIC_WITH_TEXTBUTTONS" rootscreen="true">
+ <description>
+ Custom root template screen containing half-screen graphic with text only SoftButtons.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="TEXTBUTTONS_WITH_GRAPHIC" rootscreen="true">
+ <description>
+ Custom root template screen containing text only SoftButtons with half-screen graphic.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="LARGE_GRAPHIC_WITH_SOFTBUTTONS" rootscreen="true">
+ <description>
+ Custom root template screen containing a large graphic and SoftButtons.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="DOUBLE_GRAPHIC_WITH_SOFTBUTTONS" rootscreen="true">
+ <description>
+ Custom root template screen containing two graphics and SoftButtons.
+ Can be set as a root screen.
+ </description>
+ </element>
+ <element name="LARGE_GRAPHIC_ONLY" rootscreen="true">
+ <description>
+ Custom root template screen containing only a large graphic.
+ Can be set as a root screen.
+ </description>
+ </element>
+ </enum>
+
+ <enum name="CharacterSet">
+ <description>The list of potential character sets</description>
+ <element name="TYPE2SET">
+ <description>See [@TODO: create file ref]</description>
+ </element>
+ <element name="TYPE5SET">
+ <description>See [@TODO: create file ref]</description>
+ </element>
+ <element name="CID1SET">
+ <description>See [@TODO: create file ref]</description>
+ </element>
+ <element name="CID2SET">
+ <description>See [@TODO: create file ref]</description>
+ </element>
+ </enum>
+
+ <enum name="TextAlignment">
+ <description>The list of possible alignments, left, right, or centered</description>
+ <element name="LEFT_ALIGNED" />
+ <element name="RIGHT_ALIGNED" />
+ <element name="CENTERED" />
+ </enum>
+
+ <enum name="TBTState">
+ <description>Enumeration that describes possible states of turn-by-turn client or AppLink app.</description>
+ <element name="ROUTE_UPDATE_REQUEST" />
+ <element name="ROUTE_ACCEPTED" />
+ <element name="ROUTE_REFUSED" />
+ <element name="ROUTE_CANCELLED" />
+ <element name="ETA_REQUEST" />
+ <element name="NEXT_TURN_REQUEST" />
+ <element name="ROUTE_STATUS_REQUEST" />
+ <element name="ROUTE_SUMMARY_REQUEST" />
+ <element name="TRIP_STATUS_REQUEST" />
+ <element name="ROUTE_UPDATE_REQUEST_TIMEOUT" />
+ </enum>
+
+ <enum name="DriverDistractionState">
+ <description>Enumeration that describes possible states of driver distraction.</description>
+ <element name="DD_ON" />
+ <element name="DD_OFF" />
+ </enum>
+
+ <enum name="ImageType">
+ <description>Contains information about the type of image.</description>
+ <element name="STATIC" />
+ <element name="DYNAMIC" />
+ </enum>
+
+ <struct name="Image">
+ <param name="value" minlength="0" maxlength="65535" type="String">
+ <description>Either the static hex icon value or the binary image file name identifier (sent by PutFile).</description>
+ </param>
+ <param name="imageType" type="ImageType">
+ <description>Describes, whether it is a static or dynamic image.</description>
+ </param>
+ </struct>
+
+ <struct name="SoftButton">
+ <param name="type" type="SoftButtonType">
+ <description>Describes, whether it is text, highlighted text, icon, or dynamic image. See softButtonType</description>
+ </param>
+ <param name="text" minlength="0" maxlength="500" type="String" mandatory="false">
+ <description>Optional text to display (if defined as TEXT or BOTH)</description>
+ </param>
+ <param name="image" type="Image" mandatory="false">
+ <description>Optional image struct for SoftButton (if defined as IMAGE or BOTH)</description>
+ </param>
+ <param name="isHighlighted" type="Boolean" defvalue="false" mandatory="false">
+ <description>
+ True, if highlighted
+ False, if not highlighted
+ </description>
+ </param>
+ <param name="softButtonID" type="Integer" minvalue="0" maxvalue="65535">
+ <description>Value which is returned via OnButtonPress / OnButtonEvent</description>
+ </param>
+ <param name="systemAction" type="SystemAction" defvalue="DEFAULT_ACTION" mandatory="false">
+ <description>Parameter indicating whether selecting a SoftButton shall call a specific system action. This is intended to allow Notifications to bring the callee into full / focus; or in the case of persistent overlays, the overlay can persist when a SoftButton is pressed.</description>
+ </param>
+ </struct>
+
+ <struct name="Choice">
+ <description>A choice is an option given to the user, which can be selected either by menu, or through voice recognition system.</description>
+ <param name="choiceID" type="Integer" minvalue="0" maxvalue="65535" />
+ <param name="menuName" type="String" maxlength="500" />
+ <param name="vrCommands" type="String" minsize="1" maxsize="100" maxlength="99" array="true" />
+ <param name="image" type="Image" mandatory="false"/>
+ <param name="secondaryText" maxlength="500" type="String" mandatory="false">
+ <description>Optional secondary text to display; e.g. address of POI in a search result entry</description>
+ </param>
+ <param name="tertiaryText" maxlength="500" type="String" mandatory="false">
+ <description>Optional tertiary text to display; e.g. distance to POI for a search result entry</description>
+ </param>
+ <param name="secondaryImage" type="Image" mandatory="false">
+ <description>Optional secondary image struct for choice</description>
+ </param>
+ </struct>
+
+ <struct name="VrHelpItem">
+ <param name="text" maxlength="500" type="String">
+ <description>Text to display for VR Help item</description>
+ </param>
+ <param name="image" type="Image" mandatory="false">
+ <description>Image struct for VR Help item</description>
+ </param>
+ <param name="position" type="Integer" minvalue="1" maxvalue="100">
+ <description>Position to display item in VR Help list</description>
+ </param>
+ </struct>
+
+ <struct name="SyncMsgVersion">
+ <description>Specifies the version number of the SYNC V4 protocol, that is supported by the mobile application</description>
+
+ <param name="majorVersion" type="Integer" minvalue="1" maxvalue="10">
+ <description>The major version indicates versions that is not-compatible to previous versions.</description>
+ </param>
+ <param name="minorVersion" type="Integer" minvalue="0" maxvalue="1000">
+ <description>The minor version indicates a change to a previous version that should still allow to be run on an older version (with limited functionality)</description>
+ </param>
+ </struct>
+
+ <enum name="GlobalProperty">
+ <description>The different global properties.</description>
+ <element name="HELPPROMPT">
+ <description>The property helpPrompt of setGlobalProperties</description>
+ </element>
+ <element name="TIMEOUTPROMPT">
+ <description>The property timeoutPrompt of setGlobalProperties</description>
+ </element>
+ <element name="VRHELPTITLE">
+ <description>The property vrHelpTitle of setGlobalProperties</description>
+ </element>
+ <element name="VRHELPITEMS">
+ <description>The property array of vrHelp of setGlobalProperties</description>
+ </element>
+ <element name="MENUNAME">
+ <description>The property in-app menu name of setGlobalProperties</description>
+ </element>
+ <element name="MENUICON">
+ <description>The property in-app menu icon of setGlobalProperties</description>
+ </element>
+ <element name="KEYBOARDPROPERTIES">
+ <description>The on-screen keyboard configuration of setGlobalProperties</description>
+ </element>
+ </enum>
+
+ <enum name="CompassDirection">
+ <description>The list of potential compass directions</description>
+ <element name="NORTH">
+ </element>
+ <element name="NORTHWEST">
+ </element>
+ <element name="WEST">
+ </element>
+ <element name="SOUTHWEST">
+ </element>
+ <element name="SOUTH">
+ </element>
+ <element name="SOUTHEAST">
+ </element>
+ <element name="EAST">
+ </element>
+ <element name="NORTHEAST">
+ </element>
+ </enum>
+
+ <enum name="Dimension">
+ <description>The supported dimensions of the GPS</description>
+ <element name="NO_FIX" internal_name="Dimension_NO_FIX">
+ <description>No GPS at all</description>
+ </element>
+ <element name="2D" internal_name="Dimension_2D">
+ <description>Longitude and lattitude</description>
+ </element>
+ <element name="3D" internal_name="Dimension_3D">
+ <description>Longitude and lattitude and altitude</description>
+ </element>
+ </enum>
+
+ <enum name="PRNDL">
+ <description>The selected gear.</description>
+ <element name="PARK">
+ <description>Parking</description>
+ </element>
+ <element name="REVERSE">
+ <description>Reverse gear</description>
+ </element>
+ <element name="NEUTRAL">
+ <description>No gear</description>
+ </element>
+ <element name="DRIVE">
+ </element>
+ <element name="SPORT">
+ <description>Drive Sport mode</description>
+ </element>
+ <element name="LOWGEAR">
+ <description>1st gear hold</description>
+ </element>
+ <element name="FIRST">
+ </element>
+ <element name="SECOND">
+ </element>
+ <element name="THIRD">
+ </element>
+ <element name="FOURTH">
+ </element>
+ <element name="FIFTH">
+ </element>
+ <element name="SIXTH">
+ </element>
+ <element name="SEVENTH">
+ </element>
+ <element name="EIGHTH">
+ </element>
+ <element name="UNKNOWN">
+ </element>
+ <element name="FAULT">
+ </element>
+ </enum>
+
+ <enum name="ComponentVolumeStatus">
+ <description>The volume status of a vehicle component.</description>
+ <element name="UNKNOWN" internal_name="CVS_UNKNOWN">
+ </element>
+ <element name="NORMAL" internal_name="CVS_NORMAL">
+ </element>
+ <element name="LOW" internal_name="CVS_LOW">
+ </element>
+ <element name="FAULT" internal_name="CVS_FAULT">
+ </element>
+ <element name="ALERT" internal_name="CVS_ALERT">
+ </element>
+ <element name="NOT_SUPPORTED" internal_name="CVS_NOT_SUPPORTED">
+ </element>
+ </enum>
+
+ <struct name="SingleTireStatus">
+ <param name="status" type="ComponentVolumeStatus">
+ <description>See ComponentVolumeStatus.</description>
+ </param>
+ </struct>
+
+ <enum name="WarningLightStatus">
+ <description>Reflects the status of a cluster instrument warning light.</description>
+ <element name="OFF" internal_name="WLS_OFF">
+ </element>
+ <element name="ON" internal_name="WLS_ON">
+ </element>
+ <element name="FLASH" internal_name="WLS_FLASH">
+ </element>
+ <element name="NOT_USED" internal_name="WLS_NOT_USED">
+ </element>
+ </enum>
+
+ <enum name="VehicleDataNotificationStatus">
+ <description>Reflects the status of a vehicle data notification.</description>
+ <element name="NOT_SUPPORTED" internal_name="VDNS_NOT_SUPPORTED">
+ </element>
+ <element name="NORMAL" internal_name="VDNS_NORMAL">
+ </element>
+ <element name="ACTIVE" internal_name="VDNS_ACTIVE">
+ </element>
+ <element name="NOT_USED" internal_name="VDNS_NOT_USED">
+ </element>
+ </enum>
+
+ <enum name="IgnitionStableStatus">
+ <description>Reflects the ignition switch stability.</description>
+ <element name="IGNITION_SWITCH_NOT_STABLE">
+ </element>
+ <element name="IGNITION_SWITCH_STABLE">
+ </element>
+ <element name="MISSING_FROM_TRANSMITTER">
+ </element>
+ </enum>
+
+ <enum name="IgnitionStatus">
+ <description>Reflects the status of ignition.</description>
+ <element name="UNKNOWN" internal_name="IS_UNKNOWN">
+ </element>
+ <element name="OFF" internal_name="IS_OFF">
+ </element>
+ <element name="ACCESSORY" internal_name="IS_ACCESSORY">
+ </element>
+ <element name="RUN" internal_name="IS_RUN">
+ </element>
+ <element name="START" internal_name="IS_START">
+ </element>
+ <element name="INVALID" internal_name="IS_INVALID">
+ </element>
+ </enum>
+
+ <enum name="VehicleDataEventStatus">
+ <description>Reflects the status of a vehicle data event; e.g. a seat belt event status.</description>
+ <element name="NO_EVENT" internal_name="VDES_NO_EVENT">
+ </element>
+ <element name="NO" internal_name="VDES_NO">
+ </element>
+ <element name="YES" internal_name="VDES_YES">
+ </element>
+ <element name="NOT_SUPPORTED" internal_name="VDES_NOT_SUPPORTED">
+ </element>
+ <element name="FAULT" internal_name="VDES_FAULT">
+ </element>
+ </enum>
+
+ <enum name="DeviceLevelStatus">
+ <description>Reflects the reported battery status of the connected device, if reported.</description>
+ <element name="ZERO_LEVEL_BARS">
+ </element>
+ <element name="ONE_LEVEL_BARS">
+ </element>
+ <element name="TWO_LEVEL_BARS">
+ </element>
+ <element name="THREE_LEVEL_BARS">
+ </element>
+ <element name="FOUR_LEVEL_BARS">
+ </element>
+ <element name="NOT_PROVIDED">
+ </element>
+ </enum>
+
+ <enum name="PrimaryAudioSource">
+ <description>Reflects the current primary audio source (if selected).</description>
+ <element name="NO_SOURCE_SELECTED">
+ </element>
+ <element name="USB">
+ </element>
+ <element name="USB2">
+ </element>
+ <element name="BLUETOOTH_STEREO_BTST">
+ </element>
+ <element name="LINE_IN">
+ </element>
+ <element name="IPOD">
+ </element>
+ <element name="MOBILE_APP">
+ </element>
+ </enum>
+
+ <enum name="WiperStatus">
+ <description>Reflects the status of the wipers.</description>
+ <element name="OFF" />
+ <element name="AUTO_OFF" />
+ <element name="OFF_MOVING" />
+ <element name="MAN_INT_OFF" />
+ <element name="MAN_INT_ON" />
+ <element name="MAN_LOW" />
+ <element name="MAN_HIGH" />
+ <element name="MAN_FLICK" />
+ <element name="WASH" />
+ <element name="AUTO_LOW" />
+ <element name="AUTO_HIGH" />
+ <element name="COURTESYWIPE" />
+ <element name="AUTO_ADJUST" />
+ <element name="STALLED" />
+ <element name="NO_DATA_EXISTS" />
+ </enum>
+
+ <enum name="VehicleDataStatus">
+ <description>Reflects the status of a binary vehicle data item.</description>
+ <element name="NO_DATA_EXISTS" internal_name="VDS_NO_DATA_EXISTS">
+ </element>
+ <element name="OFF" internal_name="VDS_OFF">
+ </element>
+ <element name="ON" internal_name="VDS_ON">
+ </element>
+ </enum>
+
+ <enum name="MaintenanceModeStatus">
+ <description>Reflects the status of a vehicle maintenance mode.</description>
+ <element name="NORMAL" internal_name="MMS_NORMAL">
+ </element>
+ <element name="NEAR" internal_name="MMS_NEAR">
+ </element>
+ <element name="ACTIVE" internal_name="MMS_ACTIVE">
+ </element>
+ <element name="FEATURE_NOT_PRESENT" internal_name="MMS_FEATURE_NOT_PRESENT">
+ </element>
+ </enum>
+
+ <enum name="VehicleDataActiveStatus">
+ <description>Reflects the status of given vehicle component.</description>
+ <element name="INACTIVE_NOT_CONFIRMED" internal_name="VDAS_INACTIVE_NOT_CONFIRMED">
+ </element>
+ <element name="INACTIVE_CONFIRMED" internal_name="VDAS_INACTIVE_CONFIRMED">
+ </element>
+ <element name="ACTIVE_NOT_CONFIRMED" internal_name="VDAS_ACTIVE_NOT_CONFIRMED">
+ </element>
+ <element name="ACTIVE_CONFIRMED" internal_name="VDAS_ACTIVE_CONFIRMED">
+ </element>
+ <element name="FAULT" internal_name="VDAS_FAULT">
+ </element>
+ </enum>
+
+ <enum name="AmbientLightStatus">
+ <description>Reflects the status of the ambient light sensor.</description>
+ <element name="NIGHT" />
+ <element name="TWILIGHT_1" />
+ <element name="TWILIGHT_2" />
+ <element name="TWILIGHT_3" />
+ <element name="TWILIGHT_4" />
+ <element name="DAY" />
+ <element name="UNKNOWN" />
+ <element name="INVALID" />
+ </enum>
+
+ <struct name="BeltStatus">
+ <param name="driverBeltDeployed" type="VehicleDataEventStatus">
+ <description>References signal "VedsDrvBelt_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="passengerBeltDeployed" type="VehicleDataEventStatus">
+ <description>References signal "VedsPasBelt_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="passengerBuckleBelted" type="VehicleDataEventStatus">
+ <description>References signal "VedsRw1PasBckl_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="driverBuckleBelted" type="VehicleDataEventStatus">
+ <description>References signal "VedsRw1DrvBckl_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="leftRow2BuckleBelted" type="VehicleDataEventStatus">
+ <description>References signal "VedsRw2lBckl_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="passengerChildDetected" type="VehicleDataEventStatus">
+ <description>References signal "VedsRw1PasChld_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="rightRow2BuckleBelted" type="VehicleDataEventStatus">
+ <description>References signal "VedsRw2rBckl_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="middleRow2BuckleBelted" type="VehicleDataEventStatus">
+ <description>References signal "VedsRw2mBckl_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="middleRow3BuckleBelted" type="VehicleDataEventStatus">
+ <description>References signal "VedsRw3mBckl_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="leftRow3BuckleBelted" type="VehicleDataEventStatus">
+ <description>References signal "VedsRw3lBckl_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="rightRow3BuckleBelted" type="VehicleDataEventStatus">
+ <description>References signal "VedsRw3rBckl_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="leftRearInflatableBelted" type="VehicleDataEventStatus">
+ <description>References signal "VedsRw2lRib_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="rightRearInflatableBelted" type="VehicleDataEventStatus">
+ <description>References signal "VedsRw2rRib_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="middleRow1BeltDeployed" type="VehicleDataEventStatus">
+ <description>References signal "VedsRw1mBelt_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="middleRow1BuckleBelted" type="VehicleDataEventStatus">
+ <description>References signal "VedsRw1mBckl_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ </struct>
+
+ <struct name="BodyInformation">
+ <param name="parkBrakeActive" type="Boolean">
+ <description>References signal "PrkBrkActv_B_Actl".</description>
+ </param>
+ <param name="ignitionStableStatus" type="IgnitionStableStatus">
+ <description>References signal "Ignition_Switch_Stable". See IgnitionStableStatus.</description>
+ </param>
+ <param name="ignitionStatus" type="IgnitionStatus">
+ <description>References signal "Ignition_status". See IgnitionStatus.</description>
+ </param>
+ <param name="driverDoorAjar" type="Boolean" mandatory="false">
+ <description>References signal "DrStatDrv_B_Actl".</description>
+ </param>
+ <param name="passengerDoorAjar" type="Boolean" mandatory="false">
+ <description>References signal "DrStatPsngr_B_Actl".</description>
+ </param>
+ <param name="rearLeftDoorAjar" type="Boolean" mandatory="false">
+ <description>References signal "DrStatRl_B_Actl".</description>
+ </param>
+ <param name="rearRightDoorAjar" type="Boolean" mandatory="false">
+ <description>References signal "DrStatRr_B_Actl".</description>
+ </param>
+ </struct>
+
+ <struct name="DeviceStatus">
+ <param name="voiceRecOn" type="Boolean">
+ <description>References signal "CPM_VoiceRec_STAT".</description>
+ </param>
+ <param name="btIconOn" type="Boolean">
+ <description>References signal "BT_ICON".</description>
+ </param>
+ <param name="callActive" type="Boolean">
+ <description>References signal "CPM_Call_Active_STAT".</description>
+ </param>
+ <param name="phoneRoaming" type="Boolean">
+ <description>References signal "CPM_Phone_Roaming_STAT".</description>
+ </param>
+ <param name="textMsgAvailable" type="Boolean">
+ <description>References signal "CPM_TextMsg_AVAL".</description>
+ </param>
+ <param name="battLevelStatus" type="DeviceLevelStatus">
+ <description>Device battery level status. References signal "CPM_Batt_Level_STAT". See DeviceLevelStatus.</description>
+ </param>
+ <param name="stereoAudioOutputMuted" type="Boolean">
+ <description>References signal "CPM_Stereo_Audio_Output".</description>
+ </param>
+ <param name="monoAudioOutputMuted" type="Boolean">
+ <description>References signal "CPM_Mono_Audio_Output".</description>
+ </param>
+ <param name="signalLevelStatus" type="DeviceLevelStatus">
+ <description>Device signal level status. References signal "CPM_Signal_Strength_STAT". See DeviceLevelStatus.</description>
+ </param>
+ <param name="primaryAudioSource" type="PrimaryAudioSource">
+ <description>References signal "CPM_Stereo_PAS_Source". See PrimaryAudioSource.</description>
+ </param>
+ <param name="eCallEventActive" type="Boolean">
+ <description>References signal "eCall_Event".</description>
+ </param>
+ </struct>
+
+ <struct name="HeadLampStatus">
+ <param name="lowBeamsOn" type="Boolean">
+ <description>Status of the low beam lamps. References signal "HeadLampLoActv_B_Stat".</description>
+ </param>
+ <param name="highBeamsOn" type="Boolean">
+ <description>Status of the high beam lamps. References signal "HeadLghtHiOn_B_Stat".</description>
+ </param>
+ <param name="ambientLightSensorStatus" type="AmbientLightStatus">
+ <description>Status of the ambient light sensor.</description>
+ </param>
+ </struct>
+
+ <struct name="engineInfo">
+ <param name="electricFuelConsumption" type="Float" minvalue="0" maxvalue="30000">
+ <description>
+ Indicates the electric fuel consumption in terms of gasoline equivalent volume to support fuel economy equivalent calculations.
+ Note:Plug-in vehicle use only!
+ References signal "ElFuelFlw_Vl_Dsply".
+ </description>
+ </param>
+ <param name="stateOfCharge" type="Float" minvalue="0" maxvalue="100">
+ <description>Percent state of charge for the high voltage battery. References signal "BattTracSoc_Pc_Dsply".</description>
+ </param>
+ <param name="fuelMaintenanceMode" type="MaintenanceModeStatus">
+ <description>Current status of fuel maintenance mode (if present on hybrid vehicles). References signal "FuelMaintMde_D_Dsply".</description>
+ </param>
+ <param name="distanceToEmpty" type="Float" minvalue="0" maxvalue="1000">
+ <description>
+ Electric range (DTE) in km. References signal "VehElRnge_L_Dsply".
+ 0xFFE = No Data Exists
+ 0xFFF = Fault
+ </description>
+ </param>
+ </struct>
+
+<!-- ~~~~~~~~~~~~~~~~~~~~~~~~ -->
+<!-- Ford Specific Data Items -->
+<!-- ~~~~~~~~~~~~~~~~~~~~~~~~ -->
+
+ <enum name="FuelCutoffStatus">
+ <description>Reflects the status of the RCM fuel cutoff.</description>
+ <element name="TERMINATE_FUEL" internal_name="FCS_TERMINATE_FUEL">
+ </element>
+ <element name="NORMAL_OPERATION" internal_name="FCS_NORMAL_OPERATION">
+ </element>
+ <element name="FAULT" internal_name="FCS_FAULT">
+ </element>
+ </enum>
+
+ <enum name="EmergencyEventType">
+ <description>Reflects the emergency event status of the vehicle.</description>
+ <element name="NO_EVENT" internal_name="EET_NO_EVENT">
+ </element>
+ <element name="FRONTAL" internal_name="EET_FRONTAL">
+ </element>
+ <element name="SIDE" internal_name="EET_SIDE">
+ </element>
+ <element name="REAR" internal_name="EET_REAR">
+ </element>
+ <element name="ROLLOVER" internal_name="EET_ROLLOVER">
+ </element>
+ <element name="NOT_SUPPORTED" internal_name="EET_NOT_SUPPORTED">
+ </element>
+ <element name="FAULT" internal_name="EET_FAULT">
+ </element>
+ </enum>
+
+ <enum name="ECallConfirmationStatus">
+ <description>Reflects the status of the eCall Notification.</description>
+ <element name="NORMAL" internal_name="ECCS_NORMAL">
+ </element>
+ <element name="CALL_IN_PROGRESS" internal_name="ECCS_CALL_IN_PROGRESS">
+ </element>
+ <element name="CALL_CANCELLED" internal_name="ECCS_CALL_CANCELLED">
+ </element>
+ <element name="CALL_COMPLETED">
+ </element>
+ <element name="CALL_UNSUCCESSFUL" internal_name="ECCS_CALL_UNSUCCESSFUL">
+ </element>
+ <element name="ECALL_CONFIGURED_OFF" internal_name="ECCS_ECALL_CONFIGURED_OFF">
+ </element>
+ <element name="CALL_COMPLETE_DTMF_TIMEOUT" internal_name="ECCS_CALL_COMPLETE_DTMF_TIMEOUT">
+ </element>
+ </enum>
+
+ <struct name="DeviceInfo">
+ <description>Various information abount connecting device.</description>
+
+ <param name="hardware" type="String" minlength="0" maxlength="500" mandatory="false">
+ <description>Device model</description>
+ </param>
+ <param name="firmwareRev" type="String" minlength="0" maxlength="500" mandatory="false">
+ <description>Device firmware revision</description>
+ </param>
+ <param name="os" type="String" minlength="0" maxlength="500" mandatory="false">
+ <description>Device OS</description>
+ </param>
+ <param name="osVersion" type="String" minlength="0" maxlength="500" mandatory="false">
+ <description>Device OS version</description>
+ </param>
+ <param name="carrier" type="String" minlength="0" maxlength="500" mandatory="false">
+ <description>Device mobile carrier (if applicable)</description>
+ </param>
+ <param name="maxNumberRFCOMMPorts" type="Integer" minvalue="0" maxvalue="100" mandatory="false">
+ <description>Omitted if connected not via BT.</description>
+ </param>
+
+ </struct>
+
+ <enum name="FileType">
+ <description>Enumeration listing possible file types.</description>
+ <element name="GRAPHIC_BMP" />
+ <element name="GRAPHIC_JPEG" />
+ <element name="GRAPHIC_PNG" />
+ <element name="AUDIO_WAVE" />
+ <element name="AUDIO_MP3" />
+ <element name="AUDIO_AAC" />
+ <element name="BINARY" />
+ <element name="JSON" />
+ </enum>
+
+ <enum name="PowerModeQualificationStatus">
+ <description>Reflects the status of the current power mode qualification.</description>
+ <element name="POWER_MODE_UNDEFINED">
+ </element>
+ <element name="POWER_MODE_EVALUATION_IN_PROGRESS">
+ </element>
+ <element name="NOT_DEFINED">
+ </element>
+ <element name="POWER_MODE_OK">
+ </element>
+ </enum>
+
+ <enum name="PowerModeStatus">
+ <description>Reflects the status of the current power mode.</description>
+ <element name="KEY_OUT">
+ </element>
+ <element name="KEY_RECENTLY_OUT">
+ </element>
+ <element name="KEY_APPROVED_0">
+ </element>
+ <element name="POST_ACCESORY_0">
+ </element>
+ <element name="ACCESORY_1">
+ </element>
+ <element name="POST_IGNITION_1">
+ </element>
+ <element name="IGNITION_ON_2">
+ </element>
+ <element name="RUNNING_2">
+ </element>
+ <element name="CRANK_3">
+ </element>
+ </enum>
+
+ <enum name="CarModeStatus">
+ <description>Reflects the status of the current car mode.</description>
+ <element name="NORMAL" internal_name="CMS_NORMAL">
+ </element>
+ <element name="FACTORY" internal_name="CMS_FACTORY">
+ </element>
+ <element name="TRANSPORT" internal_name="CMS_TRANSPORT">
+ </element>
+ <element name="CRASH" internal_name="CMS_CRASH">
+ </element>
+ </enum>
+
+ <struct name="ECallInfo">
+ <param name="eCallNotificationStatus" type="VehicleDataNotificationStatus">
+ <description>References signal "eCallNotification_4A". See VehicleDataNotificationStatus.</description>
+ </param>
+ <param name="auxECallNotificationStatus" type="VehicleDataNotificationStatus">
+ <description>References signal "eCallNotification". See VehicleDataNotificationStatus.</description>
+ </param>
+ <param name="eCallConfirmationStatus" type="ECallConfirmationStatus">
+ <description>References signal "eCallConfirmation". See ECallConfirmationStatus.</description>
+ </param>
+ </struct>
+
+ <struct name="AirbagStatus">
+ <param name="driverAirbagDeployed" type="VehicleDataEventStatus">
+ <description>References signal "VedsDrvBag_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="driverSideAirbagDeployed" type="VehicleDataEventStatus">
+ <description>References signal "VedsDrvSideBag_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="driverCurtainAirbagDeployed" type="VehicleDataEventStatus">
+ <description>References signal "VedsDrvCrtnBag_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="passengerAirbagDeployed" type="VehicleDataEventStatus">
+ <description>References signal "VedsPasBag_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="passengerCurtainAirbagDeployed" type="VehicleDataEventStatus">
+ <description>References signal "VedsPasCrtnBag_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="driverKneeAirbagDeployed" type="VehicleDataEventStatus">
+ <description>References signal "VedsKneeDrvBag_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="passengerSideAirbagDeployed" type="VehicleDataEventStatus">
+ <description>References signal "VedsPasSideBag_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ <param name="passengerKneeAirbagDeployed" type="VehicleDataEventStatus">
+ <description>References signal "VedsKneePasBag_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ </struct>
+
+ <struct name="EmergencyEvent">
+ <param name="emergencyEventType" type="EmergencyEventType">
+ <description>References signal "VedsEvntType_D_Ltchd". See EmergencyEventType.</description>
+ </param>
+ <param name="fuelCutoffStatus" type="FuelCutoffStatus">
+ <description>References signal "RCM_FuelCutoff". See FuelCutoffStatus.</description>
+ </param>
+ <param name="rolloverEvent" type="VehicleDataEventStatus">
+ <description>References signal "VedsEvntRoll_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+
+ <param name="maximumChangeVelocity" type="Integer" minvalue="0" maxvalue="255">
+ <description>References signal "VedsMaxDeltaV_D_Ltchd". Change in velocity in KPH. Additional reserved values:
+ 0x00 No event
+ 0xFE Not supported
+ 0xFF Fault
+ </description>
+ </param>
+ <param name="multipleEvents" type="VehicleDataEventStatus">
+ <description>References signal "VedsMultiEvnt_D_Ltchd". See VehicleDataEventStatus.</description>
+ </param>
+ </struct>
+
+ <struct name="ClusterModeStatus">
+ <param name="powerModeActive" type="Boolean">
+ <description>References signal "PowerMode_UB".</description>
+ </param>
+ <param name="powerModeQualificationStatus" type="PowerModeQualificationStatus">
+ <description>References signal "PowerModeQF". See PowerModeQualificationStatus.</description>
+ </param>
+ <param name="carModeStatus" type="CarModeStatus">
+ <description>References signal "CarMode". See CarMode.</description>
+ </param>
+ <param name="powerModeStatus" type="PowerModeStatus">
+ <description>References signal "PowerMode". See PowerMode.</description>
+ </param>
+ </struct>
+
+ <struct name="MyKey">
+ <param name="e911Override" type="VehicleDataStatus">
+ <description>Indicates whether e911 override is on. References signal "MyKey_e911Override_St". See VehicleDataStatus.</description>
+ </param>
+ </struct>
+
+<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
+<!-- / Ford Specific Data Items -->
+<!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~ -->
+
+ <enum name="VehicleDataResultCode">
+ <description>Enumeration that describes possible result codes of a vehicle data entry request.</description>
+ <element name="SUCCESS" internal_name="VDRC_SUCCESS"/>
+ <element name="TRUNCATED_DATA" internal_name="VDRC_TRUNCATED_DATA"/>
+ <element name="DISALLOWED" internal_name="VDRC_DISALLOWED"/>
+ <element name="USER_DISALLOWED" internal_name="VDRC_USER_DISALLOWED"/>
+ <element name="INVALID_ID" internal_name="VDRC_INVALID_ID"/>
+ <element name="VEHICLE_DATA_NOT_AVAILABLE" internal_name="VDRC_DATA_NOT_AVAILABLE"/>
+ <element name="DATA_ALREADY_SUBSCRIBED" internal_name="VDRC_DATA_ALREADY_SUBSCRIBED"/>
+ <element name="DATA_NOT_SUBSCRIBED" internal_name="VDRC_DATA_NOT_SUBSCRIBED"/>
+ <element name="IGNORED" internal_name="VDRC_IGNORED"/>
+ </enum>
+
+ <struct name="TireStatus">
+ <description>The status and pressure of the tires.</description>
+
+ <param name="pressureTelltale" type="WarningLightStatus">
+ <description>Status of the Tire Pressure Telltale. See WarningLightStatus.</description>
+ </param>
+ <param name="leftFront" type="SingleTireStatus">
+ <description>The status of the left front tire.</description>
+ </param>
+ <param name="rightFront" type="SingleTireStatus">
+ <description>The status of the right front tire.</description>
+ </param>
+ <param name="leftRear" type="SingleTireStatus">
+ <description>The status of the left rear tire.</description>
+ </param>
+ <param name="rightRear" type="SingleTireStatus">
+ <description>The status of the right rear tire.</description>
+ </param>
+ <param name="innerLeftRear" type="SingleTireStatus">
+ <description>The status of the inner left rear.</description>
+ </param>
+ <param name="innerRightRear" type="SingleTireStatus">
+ <description>The status of the inner right rear.</description>
+ </param>
+ </struct>
+
+ <struct name="GPSData">
+ <description>Struct with the GPS data.</description>
+ <param name="longitudeDegrees" type="Float" minvalue="-180" maxvalue="180">
+ </param>
+ <param name="latitudeDegrees" type="Float" minvalue="-90" maxvalue="90">
+ </param>
+ <param name="utcYear" type="Integer" minvalue="2010" maxvalue="2100">
+ <description>The current UTC year.</description>
+ </param>
+ <param name="utcMonth" type="Integer" minvalue="1" maxvalue="12">
+ <description>The current UTC month.</description>
+ </param>
+ <param name="utcDay" type="Integer" minvalue="1" maxvalue="31">
+ <description>The current UTC day.</description>
+ </param>
+ <param name="utcHours" type="Integer" minvalue="0" maxvalue="23">
+ <description>The current UTC hour.</description>
+ </param>
+ <param name="utcMinutes" type="Integer" minvalue="0" maxvalue="59">
+ <description>The current UTC minute.</description>
+ </param>
+ <param name="utcSeconds" type="Integer" minvalue="0" maxvalue="59">
+ <description>The current UTC second.</description>
+ </param>
+ <param name="compassDirection" type="CompassDirection">
+ <description>See CompassDirection.</description>
+ </param>
+ <param name="pdop" type="Float" minvalue="0" maxvalue="10" defvalue="0">
+ <description>PDOP. If undefined or unavailable, then value shall be set to 0.</description>
+ </param>
+ <param name="hdop" type="Float" minvalue="0" maxvalue="10" defvalue="0">
+ <description>HDOP. If value is unknown, value shall be set to 0.</description>
+ </param>
+ <param name="vdop" type="Float" minvalue="0" maxvalue="10" defvalue="0">
+ <description>VDOP. If value is unknown, value shall be set to 0.</description>
+ </param>
+ <param name="actual" type="Boolean">
+ <description>
+ True, if actual.
+ False, if infered.
+ </description>
+ </param>
+ <param name="satellites" type="Integer" minvalue="0" maxvalue="31">
+ <description>Number of satellites in view</description>
+ </param>
+ <param name="dimension" type="Dimension">
+ <description>See Dimension</description>
+ </param>
+ <param name="altitude" type="Float" minvalue="-10000" maxvalue="10000">
+ <description>Altitude in meters</description>
+ </param>
+ <param name="heading" type="Float" minvalue="0" maxvalue="359.99">
+ <description>The heading. North is 0. Resolution is 0.01</description>
+ </param>
+ <param name="speed" type="Float" minvalue="0" maxvalue="500">
+ <description>The speed in KPH</description>
+ </param>
+ </struct>
+
+ <struct name="VehicleDataResult">
+ <description>Individual published data request result</description>
+ <param name="dataType" type="VehicleDataType">
+ <description>Defined published data element type.</description>
+ </param>
+ <param name="resultCode" type="VehicleDataResultCode">
+ <description>Published data result code.</description>
+ </param>
+ </struct>
+
+ <struct name="DIDResult">
+ <description>Individual requested DID result and data</description>
+ <param name="resultCode" type="VehicleDataResultCode">
+ <description>Individual DID result code.</description>
+ </param>
+ <param name="didLocation" type="Integer" minvalue="0" maxvalue="65535" mandatory="true">
+ <description>Location of raw data from vehicle data DID</description>
+ </param>
+ <param name="data" type="String" maxlength="5000" mandatory="false">
+ <description>Raw DID-based data returned for requested element.</description>
+ </param>
+ </struct>
+
+ <struct name="StartTime">
+ <param name="hours" type="Integer" minvalue="0" maxvalue="59">
+ <description>
+ The hour of the media clock.
+ Some radios only support a max of 19 hours. If out of range, it will be rejected.
+ </description>
+ </param>
+ <param name="minutes" type="Integer" minvalue="0" maxvalue="59" />
+ <param name="seconds" type="Integer" minvalue="0" maxvalue="59" />
+ </struct>
+
+ <struct name="TextField">
+ <param name="name" type="TextFieldName">
+ <description>The name that identifies the field. See TextFieldName.</description>
+ </param>
+ <param name="characterSet" type="CharacterSet">
+ <description>The character set that is supported in this field. See CharacterSet.</description>
+ </param>
+ <param name="width" type="Integer" minvalue="1" maxvalue="500">
+ <description>The number of characters in one row of this field.</description>
+ </param>
+ <param name="rows" type="Integer" minvalue="1" maxvalue="8">
+ <description>The number of rows of this field.</description>
+ </param>
+ </struct>
+
+ <struct name="ImageResolution">
+ <param name="resolutionWidth" type="Integer" minvalue="1" maxvalue="10000">
+ <description>The image resolution width.</description>
+ </param>
+ <param name="resolutionHeight" type="Integer" minvalue="1" maxvalue="10000">
+ <description>The image resolution height.</description>
+ </param>
+ </struct>
+
+ <struct name="ImageField">
+ <param name="name" type="ImageFieldName">
+ <description>The name that identifies the field. See ImageFieldName.</description>
+ </param>
+ <param name="imageTypeSupported" type="FileType" array="true">
+ <description>The image types that are supported in this field. See FileType.</description>
+ </param>
+ <param name="imageResolution" type="ImageResolution">
+ <description>The image resolution of this field.</description>
+ </param>
+ </struct>
+
+ <struct name="TouchCoord">
+ <param name="x" type="Integer" mandatory="true" minvalue="0" maxvalue="10000">
+ <description>The x coordinate of the touch.</description>
+ </param>
+ <param name="y" type="Integer" mandatory="true" minvalue="0" maxvalue="10000">
+ <description>The y coordinate of the touch.</description>
+ </param>
+ </struct>
+
+ <enum name="TouchType">
+ <element name="BEGIN"/>
+ <element name="MOVE"/>
+ <element name="END"/>
+ </enum>
+
+ <struct name="TouchEvent">
+ <param name="id" type="Integer" mandatory="true" minvalue="0" maxvalue="9">
+ <description>
+ A touch's unique identifier. The application can track the current touch events by id.
+ If a touch event has type begin, the id should be added to the set of touches.
+ If a touch event has type end, the id should be removed from the set of touches.
+ </description>
+ </param>
+ <param name="ts" type="Integer" mandatory="true" array="true" minvalue="0" maxvalue="2147483647" minsize="1" maxsize="1000">
+ <description>
+ The time that the touch was recorded. This number can the time since the beginning of the session or something else as long as the units are in milliseconds.
+ The timestamp is used to determined the rate of change of position of a touch.
+ The application also uses the time to verify whether two touches, with different ids, are part of a single action by the user.
+ If there is only a single timestamp in this array, it is the same for every coordinate in the coordinates array.
+ </description>
+ </param>
+ <param name="c" type="TouchCoord" mandatory="true" array="true" minsize="1" maxsize="1000">
+ </param>
+ </struct>
+
+ <struct name="Coordinate">
+ <param name="xCoord" type="Integer" mandatory="true">
+ </param>
+ <param name="yCoord" type="Integer" mandatory="true">
+ </param>
+ </struct>
+
+ <struct name="TouchArea">
+ <param name="rotationAngle" type="Float" mandatory="false" minvalue="0" maxvalue="360">
+ </param>
+ <param name="radiusCoord" type="Coordinate" mandatory="true">
+ </param>
+ </struct>
+
+ <struct name="TouchEventCapabilities">
+ <param name="pressAvailable" type="Boolean" mandatory="true">
+ </param>
+ <param name="multiTouchAvailable" type="Boolean" mandatory="true">
+ </param>
+ <param name="doublePressAvailable" type="Boolean" mandatory="true">
+ </param>
+ </struct>
+
+ <struct name="ScreenParams">
+ <param name="resolution" type="ImageResolution" mandatory="true">
+ <description>The resolution of the prescribed screen area.</description>
+ </param>
+ <param name="touchEventAvailable" type="TouchEventCapabilities" mandatory="false">
+ <description>Types of screen touch events available in screen area.</description>
+ </param>
+ </struct>
+
+ <enum name="PermissionStatus">
+ <description>Enumeration that describes possible permission states of a policy table entry.</description>
+ <element name="ALLOWED" internal_name="PS_ALLOWED"/>
+ <element name="DISALLOWED" internal_name="PS_DISALLOWED"/>
+ <element name="USER_DISALLOWED" internal_name="PS_USER_DISALLOWED"/>
+ <element name="USER_CONSENT_PENDING" internal_name="PS_USER_CONSENT_PENDING"/>
+ </enum>
+
+ <struct name="HMIPermissions">
+ <param name="allowed" type="HMILevel" minsize="0" maxsize="100" array="true">
+ <description>A set of all HMI levels that are permitted for this given RPC.</description>
+ </param>
+ <param name="userDisallowed" type="HMILevel" minsize="0" maxsize="100" array="true">
+ <description>A set of all HMI levels that are prohibited for this given RPC.</description>
+ </param>
+ </struct>
+
+ <struct name="ParameterPermissions">
+ <param name="allowed" type="String" minsize="0" maxsize="100" maxlength = "100" array="true">
+ <description>A set of all parameters that are permitted for this given RPC.</description>
+ </param>
+ <param name="userDisallowed" type="String" minsize="0" maxsize="100" maxlength = "100" array="true">
+ <description>A set of all parameters that are prohibited for this given RPC.</description>
+ </param>
+ </struct>
+
+ <struct name="PermissionItem">
+ <param name="rpcName" type="String" maxlength="100">
+ <description>Name of the individual RPC in the policy table.</description>
+ </param>
+ <param name="hmiPermissions" type="HMIPermissions" />
+ <param name="parameterPermissions" type="ParameterPermissions" />
+ </struct>
+
+ <struct name="DisplayCapabilities">
+ <description>Contains information about the display capabilities.</description>
+ <param name="displayType" type="DisplayType">
+ <description>The type of the display. See DisplayType</description>
+ </param>
+ <param name="textFields" type="TextField" minsize="1" maxsize="100" array="true">
+ <description>A set of all fields that support text data. See TextField</description>
+ </param>
+ <param name="imageFields" type="ImageField" minsize="1" maxsize="100" array="true">
+ <description>A set of all fields that support images. See ImageField</description>
+ </param>
+ <param name="mediaClockFormats" type="MediaClockFormat" minsize="0" maxsize="100" array="true">
+ <description>A set of all supported formats of the media clock. See MediaClockFormat</description>
+ </param>
+ <param name="graphicSupported" type="Boolean">
+ <description>The display's persistent screen supports referencing a static or dynamic image.</description>
+ </param>
+ <param name="templatesAvailable" type="String" minsize="0" maxsize="100" maxlength="100" array="true">
+ <description>A set of all predefined persistent display templates available on headunit. To be referenced in SetDisplayLayout.</description>
+ </param>
+ <param name="screenParams" type="ScreenParams" mandatory="false">
+ <description>A set of all parameters related to a prescribed screen area (e.g. for video / touch input).</description>
+ </param>
+ <param name="numCustomPresetsAvailable" type="Integer" minvalue="1" maxvalue="100" mandatory="false">
+ <description>The number of on-screen custom presets available (if any); otherwise omitted.</description>
+ </param>
+ </struct>
+
+ <struct name="ButtonCapabilities">
+ <description>Contains information about a button's capabilities.</description>
+ <param name="name" type="ButtonName">
+ <description>The name of the button. See ButtonName.</description>
+ </param>
+ <param name="shortPressAvailable" type="Boolean">
+ <description>
+ The button supports a short press.
+ Whenever the button is pressed short, onButtonPressed( SHORT) will be invoked.
+ </description>
+ </param>
+ <param name="longPressAvailable" type="Boolean">
+ <description>
+ The button supports a LONG press.
+ Whenever the button is pressed long, onButtonPressed( LONG) will be invoked.
+ </description>
+ </param>
+ <param name="upDownAvailable" type="Boolean">
+ <description>
+ The button supports "button down" and "button up".
+ Whenever the button is pressed, onButtonEvent( DOWN) will be invoked.
+ Whenever the button is released, onButtonEvent( UP) will be invoked.
+ </description>
+ </param>
+ </struct>
+
+ <struct name="SoftButtonCapabilities">
+ <description>Contains information about a SoftButton's capabilities.</description>
+ <param name="shortPressAvailable" type="Boolean">
+ <description>
+ The button supports a short press.
+ Whenever the button is pressed short, onButtonPressed( SHORT) will be invoked.
+ </description>
+ </param>
+ <param name="longPressAvailable" type="Boolean">
+ <description>
+ The button supports a LONG press.
+ Whenever the button is pressed long, onButtonPressed( LONG) will be invoked.
+ </description>
+ </param>
+ <param name="upDownAvailable" type="Boolean">
+ <description>
+ The button supports "button down" and "button up".
+ Whenever the button is pressed, onButtonEvent( DOWN) will be invoked.
+ Whenever the button is released, onButtonEvent( UP) will be invoked.
+ </description>
+ </param>
+ <param name="imageSupported" type="Boolean">
+ <description>The button supports referencing a static or dynamic image.</description>
+ </param>
+ </struct>
+
+ <struct name="PresetBankCapabilities">
+ <description>Contains information about on-screen preset capabilities.</description>
+ <param name="onScreenPresetsAvailable" type="Boolean">
+ <description>Onscreen custom presets are available.</description>
+ </param>
+ </struct>
+
+ <struct name="MenuParams">
+ <param name="parentID" type="Integer" minvalue="0" maxvalue="2000000000" defvalue="0" mandatory="false">
+ <description>
+ unique ID of the sub menu, the command will be added to.
+ If not provided, it will be provided to the top level of the in application menu.
+ </description>
+ </param>
+
+ <param name="position" type="Integer" minvalue="0" maxvalue="1000" mandatory="false">
+ <description>
+ Position within the items that are are at top level of the in application menu.
+ 0 will insert at the front.
+ 1 will insert at the second position.
+ if position is greater or equal than the number of items on top level, the sub menu will be appended to the end.
+ If this param was omitted the entry will be added at the end.
+ </description>
+ </param>
+
+ <param name="menuName" type="String" maxlength="500">
+ <description>Text to show in the menu for this sub menu.</description>
+ </param>
+ </struct>
+
+ <struct name="TTSChunk">
+ <description>A TTS chunk, that consists of the text/phonemes to speak and the type (like text or SAPI)</description>
+ <param name="text" minlength="0" maxlength="500" type="String">
+ <description>
+ The text or phonemes to speak.
+ May not be empty.
+ </description>
+ </param>
+ <param name="type" type="SpeechCapabilities">
+ <description>Describes, whether it is text or a specific phoneme set. See SpeechCapabilities</description>
+ </param>
+ </struct>
+
+ <struct name="Turn">
+ <param name="navigationText" type="String" maxlength="500" mandatory="false">
+ </param>
+ <param name="turnIcon" type="Image" mandatory="false">
+ </param>
+ </struct>
+
+ <struct name="VehicleType">
+ <param name="make" type="String" maxlength="500" mandatory="false">
+ <description>Make of the vehicle, e.g. Ford</description>
+ </param>
+ <param name="model" type="String" maxlength="500" mandatory="false">
+ <description>Model of the vehicle, e.g. Fiesta</description>
+ </param>
+ <param name="modelYear" type="String" maxlength="500" mandatory="false">
+ <description>Model Year of the vehicle, e.g. 2013</description>
+ </param>
+ <param name="trim" type="String" maxlength="500" mandatory="false">
+ <description>Trim of the vehicle, e.g. SE</description>
+ </param>
+ </struct>
+
+ <enum name="KeyboardLayout">
+ <description>Enumeration listing possible keyboard layouts.</description>
+ <element name="QWERTY" />
+ <element name="QWERTZ" />
+ <element name="AZERTY" />
+ </enum>
+
+ <enum name="KeyboardEvent" platform="MobileNav">
+ <description>Enumeration listing possible keyboard events.</description>
+ <element name="KEYPRESS" />
+ <element name="ENTRY_SUBMITTED" />
+ <element name="ENTRY_VOICE" />
+ <element name="ENTRY_CANCELLED" />
+ <element name="ENTRY_ABORTED" />
+ </enum>
+
+ <enum name="KeypressMode">
+ <description>Enumeration listing possible keyboard events.</description>
+ <element name="SINGLE_KEYPRESS">
+ <description>Each keypress is individually sent as the user presses the keyboard keys.</description>
+ </element>
+ <element name="QUEUE_KEYPRESSES">
+ <description>The keypresses are queued and a string is eventually sent once the user chooses to submit their entry.</description>
+ </element>
+ <element name="RESEND_CURRENT_ENTRY">
+ <description>The keypresses are queue and a string is sent each time the user presses a keyboard key; the string contains the entire current entry.</description>
+ </element>
+ </enum>
+
+ <struct name="KeyboardProperties">
+ <description>Configuration of on-screen keyboard (if available).</description>
+
+ <param name="language" type="Language" mandatory="false">
+ <description>The keyboard language.</description>
+ </param>
+
+ <param name="keyboardLayout" type="KeyboardLayout" mandatory="false" >
+ <description>Desired keyboard layout.</description>
+ </param>
+
+ <param name="keypressMode" type="KeypressMode" mandatory="false" >
+ <description>
+ Desired keypress mode.
+ If omitted, this value will be set to RESEND_CURRENT_ENTRY.
+ </description>
+ </param>
+
+ <param name="limitedCharacterList" type="String" maxlength="1" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>Array of keyboard characters to enable.</description>
+ <description>All omitted characters will be greyed out (disabled) on the keyboard.</description>
+ <description>If omitted, the entire keyboard will be enabled.</description>
+ </param>
+
+ <param name="autoCompleteText" type="String" maxlength="1000" mandatory="false">
+ <description>Allows an app to prepopulate the text field with a suggested or completed entry as the user types</description>
+ </param>
+ </struct>
+
+ <enum name="RequestType">
+ <description>Enumeration listing possible asynchronous requests.</description>
+ <element name="HTTP" />
+ <element name="FILE_RESUME" />
+ <element name="AUTH_REQUEST" />
+ <element name="AUTH_CHALLENGE" />
+ <element name="AUTH_ACK" />
+ <element name="PROPRIETARY" />
+ <element name="QUERY_APPS" />
+ <element name="LAUNCH_APP" />
+ <element name="LOCK_SCREEN_ICON_URL" />
+ <element name="TRAFFIC_MESSAGE_CHANNEL" />
+ <element name="DRIVER_PROFILE" />
+ <element name="VOICE_SEARCH" />
+ <element name="NAVIGATION" />
+ <element name="PHONE" />
+ <element name="CLIMATE" />
+ <element name="SETTINGS" />
+ <element name="VEHICLE_DIAGNOSTICS" />
+ <element name="EMERGENCY" />
+ <element name="MEDIA" />
+ <element name="FOTA" />
+ </enum>
+
+ <enum name="AppHMIType">
+ <description>Enumeration listing possible app types.</description>
+ <element name="DEFAULT" />
+ <element name="COMMUNICATION" />
+ <element name="MEDIA" />
+ <element name="MESSAGING" />
+ <element name="NAVIGATION" />
+ <element name="INFORMATION" />
+ <element name="SOCIAL" />
+ <element name="BACKGROUND_PROCESS" />
+ <element name="TESTING" />
+ <element name="SYSTEM" />
+ </enum>
+
+ <enum name="FunctionID" internal_scope="base">
+ <description>Enumeration linking function names with function IDs in AppLink protocol.</description>
+ <description>Assumes enumeration starts at value 0.</description>
+ <element name="RESERVED" value="0" />
+<!--
+ Base Request / Response RPCs
+ Range = 0x 0000 0001 - 0x 0000 7FFF
+-->
+ <element name="RegisterAppInterfaceID" value="1" hexvalue="1" />
+ <element name="UnregisterAppInterfaceID" value="2" hexvalue="2" />
+ <element name="SetGlobalPropertiesID" value="3" hexvalue="3" />
+ <element name="ResetGlobalPropertiesID" value="4" hexvalue="4" />
+ <element name="AddCommandID" value="5" hexvalue="5" />
+ <element name="DeleteCommandID" value="6" hexvalue="6" />
+ <element name="AddSubMenuID" value="7" hexvalue="7" />
+ <element name="DeleteSubMenuID" value="8" hexvalue="8" />
+ <element name="CreateInteractionChoiceSetID" value="9" hexvalue="9" />
+ <element name="PerformInteractionID" value="10" hexvalue="A" />
+ <element name="DeleteInteractionChoiceSetID" value="11" hexvalue="B" />
+ <element name="AlertID" value="12" hexvalue="C" />
+ <element name="ShowID" value="13" hexvalue="D" />
+ <element name="SpeakID" value="14" hexvalue="E" />
+ <element name="SetMediaClockTimerID" value="15" hexvalue="F" />
+ <element name="PerformAudioPassThruID" value="16" hexvalue="10" />
+ <element name="EndAudioPassThruID" value="17" hexvalue="11" />
+ <element name="SubscribeButtonID" value="18" hexvalue="12" />
+ <element name="UnsubscribeButtonID" value="19" hexvalue="13" />
+ <element name="SubscribeVehicleDataID" value="20" hexvalue="14" />
+ <element name="UnsubscribeVehicleDataID" value="21" hexvalue="15" />
+ <element name="GetVehicleDataID" value="22" hexvalue="16" />
+ <element name="ReadDIDID" value="23" hexvalue="17" />
+ <element name="GetDTCsID" value="24" hexvalue="18" />
+ <element name="ScrollableMessageID" value="25" hexvalue="19" />
+ <element name="SliderID" value="26" hexvalue="1A" />
+ <element name="ShowConstantTBTID" value="27" hexvalue="1B" />
+ <element name="AlertManeuverID" value="28" hexvalue="1C" />
+ <element name="UpdateTurnListID" value="29" hexvalue="1D" />
+ <element name="ChangeRegistrationID" value="30" hexvalue="1E" />
+ <element name="GenericResponseID" value="31" hexvalue="1F" />
+ <element name="PutFileID" value="32" hexvalue="20" />
+ <element name="DeleteFileID" value="33" hexvalue="21" />
+ <element name="ListFilesID" value="34" hexvalue="22" />
+ <element name="SetAppIconID" value="35" hexvalue="23" />
+ <element name="SetDisplayLayoutID" value="36" hexvalue="24" />
+ <element name="DiagnosticMessageID" value="37" hexvalue="25" />
+ <element name="SystemRequestID" value="38" hexvalue="26" />
+ <element name="SendLocationID" value="39" hexvalue="27" />
+ <element name="DialNumberID" value="40" hexvalue="28" />
+
+
+
+<!--
+ Base Notifications
+ Range = 0x 0000 8000 - 0x 0000 FFFF
+-->
+
+ <element name="OnHMIStatusID" value="32768" hexvalue="8000" />
+ <element name="OnAppInterfaceUnregisteredID" value="32769" hexvalue="8001" />
+ <element name="OnButtonEventID" value="32770" hexvalue="8002" />
+ <element name="OnButtonPressID" value="32771" hexvalue="8003" />
+ <element name="OnVehicleDataID" value="32772" hexvalue="8004" />
+ <element name="OnCommandID" value="32773" hexvalue="8005" />
+ <element name="OnTBTClientStateID" value="32774" hexvalue="8006" />
+ <element name="OnDriverDistractionID" value="32775" hexvalue="8007" />
+ <element name="OnPermissionsChangeID" value="32776" hexvalue="8008" />
+ <element name="OnAudioPassThruID" value="32777" hexvalue="8009" />
+ <element name="OnLanguageChangeID" value="32778" hexvalue="800A" />
+ <element name="OnKeyboardInputID" value="32779" hexvalue="800B" />
+ <element name="OnTouchEventID" value="32780" hexvalue="800C" />
+ <element name="OnSystemRequestID" value="32781" hexvalue="800D" />
+ <element name="OnHashChangeID" value="32782" hexvalue="800E" />
+<!--
+ Ford Specific Request / Response RPCs
+ Range = 0x 0001 0000 - 0x 0001 7FFF
+-->
+
+
+<!--
+ Ford Specific Notifications
+ Range = 0x 0001 8000 - 0x 0001 FFFF
+-->
+
+ </enum>
+
+ <enum name="messageType">
+ <description>
+ Enumeration linking message types with function types in WiPro protocol.
+ Assumes enumeration starts at value 0.
+ </description>
+ <element name="request" value="0" />
+ <element name="response" value="1" />
+ <element name="notification" value="2" />
+ </enum>
+
+ <!-- Requests/Responses -->
+
+ <function name="RegisterAppInterface" functionID="RegisterAppInterfaceID" messagetype="request">
+ <description>
+ Establishes an interface with a mobile application.
+ Before registerAppInterface no other commands will be accepted/executed.
+ </description>
+
+ <param name="syncMsgVersion" type="SyncMsgVersion">
+ <description>See SyncMsgVersion</description>
+ </param>
+
+ <param name="appName" type="String" maxlength="100">
+ <description>
+ The mobile application name, e.g. "Ford Drive Green".
+ Needs to be unique over all applications.
+ May not be empty.
+ May not start with a new line character.
+ May not interfere with any name or synonym of previously registered applications and any predefined blacklist of words (global commands)
+ Needs to be unique over all applications. Applications with the same name will be rejected.
+ Only characters from char set [@TODO: Create char set (character/hex value) for each ACM and refer to] are supported.
+ </description>
+ </param>
+
+ <param name="ttsName" type="TTSChunk" minsize="1" maxsize="100" array="true" mandatory="false" >
+ <description>
+ TTS string for VR recognition of the mobile application name, e.g. "Ford Drive Green".
+ Meant to overcome any failing on speech engine in properly pronouncing / understanding app name.
+ Needs to be unique over all applications.
+ May not be empty.
+ May not start with a new line character.
+ </description>
+ </param>
+
+ <param name="ngnMediaScreenAppName" type="String" maxlength="100" mandatory="false">
+ <description>
+ Provides an abbreviated version of the app name (if needed), that will be displayed on the NGN media screen.
+ If not provided, the appName is used instead (and will be truncated if too long)
+ Only characters from char set [@TODO: Create char set (character/hex value) for each ACM and refer to] are supported.
+ </description>
+ </param>
+
+ <param name="vrSynonyms" type="String" maxlength="40" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>
+ Defines an additional voice recognition command.
+ May not interfere with any app name of previously registered applications and any predefined blacklist of words
+ (global commands)
+ Only characters from char set [@TODO: Create char set (character/hex value) for each ACM and refer to] are supported.
+ </description>
+ </param>
+
+ <param name="isMediaApplication" type="Boolean">
+ <description>
+ Indicates if the application is a media or a non-media application.
+ Only media applications will be able to stream audio to Sync that is audible outside of the BT media source.
+ </description>
+ </param>
+ <param name="languageDesired" type="Language" mandatory="true">
+ <description>
+ See Language
+ Current app’s expected VR+TTS language
+ If there is a mismatch with SYNC, the app will be able to change this registration with changeRegistration prior to app being brought into focus.
+ </description>
+ </param>
+ <param name="hmiDisplayLanguageDesired" type="Language" mandatory="true">
+ <description>
+ See Language
+ Current app’s expected display language
+ If there is a mismatch with SYNC, the app will be able to change this registration with changeRegistration prior to app being brought into focus.
+ </description>
+ </param>
+ <param name="appHMIType" type="AppHMIType" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>
+ See AppHMIType
+ List of all applicable app HMI types stating which HMI classifications to be given to the app.
+ e.g. for platforms like GEN2, this will determine which "corner(s)" the app can populate.
+ </description>
+ </param>
+ <param name="hashID" type="String" maxlength="100" mandatory="false">
+ <description>
+ ID used to uniquely identify current state of all app data that can persist through connection cycles (e.g. ignition cycles).
+ This registered data (commands, submenus, choice sets, etc.) can be reestablished without needing to explicitly reregister each piece.
+ If omitted, then the previous state of an app's commands, etc. will not be restored.
+ </description>
+ </param>
+ <param name="deviceInfo" type="DeviceInfo" mandatory="false">
+ <description>
+ See DeviceInfo.
+ </description>
+ </param>
+ <param name="appID" type="String" maxlength="100" mandatory="true">
+ <description>ID used to validate app with policy table entries</description>
+ </param>
+ </function>
+
+ <function name="RegisterAppInterface" functionID="RegisterAppInterfaceID" messagetype="response">
+ <description>The response to registerAppInterface</description>
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="DUPLICATE_NAME"/>
+ <element name="TOO_MANY_APPLICATIONS"/>
+ <element name="APPLICATION_REGISTERED_ALREADY"/>
+ <element name="UNSUPPORTED_VERSION"/>
+ <element name="WRONG_LANGUAGE"/>
+ <element name="DISALLOWED"/>
+ <element name="WARNINGS"/>
+ <element name="RESUME_FAILED"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ <param name="syncMsgVersion" type="SyncMsgVersion" mandatory="false">
+ <description>See SyncMsgVersion</description>
+ </param>
+
+ <param name="language" type="Language" mandatory="false">
+ <description>The currently active VR+TTS language on Sync. See "Language" for options.</description>
+ </param>
+
+ <param name="hmiDisplayLanguage" type="Language" mandatory="false">
+ <description>The currently active display language on Sync. See "Language" for options.</description>
+ </param>
+
+ <param name="displayCapabilities" type="DisplayCapabilities" mandatory="false">
+ <description>See DisplayCapabilities</description>
+ </param>
+
+ <param name="buttonCapabilities" type="ButtonCapabilities" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>See ButtonCapabilities</description >
+ </param>
+
+ <param name="softButtonCapabilities" type="SoftButtonCapabilities" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>If returned, the platform supports on-screen SoftButtons; see SoftButtonCapabilities.</description >
+ </param>
+
+ <param name="presetBankCapabilities" type="PresetBankCapabilities" mandatory="false">
+ <description>If returned, the platform supports custom on-screen Presets; see PresetBankCapabilities.</description >
+ </param>
+
+ <param name="hmiZoneCapabilities" type="HmiZoneCapabilities" minsize="1" maxsize="100" array="true" mandatory="false">
+ <issue creator="rs">If not used yet => remove</issue>
+ <description>See HmiZoneCapabilities</description>
+ </param>
+
+ <param name="speechCapabilities" type="SpeechCapabilities" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>See SpeechCapabilities</description>
+ </param>
+
+ <param name="vrCapabilities" type="VrCapabilities" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>See VrCapabilities</description>
+ </param>
+
+ <param name="audioPassThruCapabilities" type="AudioPassThruCapabilities" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>See AudioPassThruCapability</description>
+ </param>
+
+ <param name="vehicleType" type="VehicleType" mandatory="false">
+ <description>Specifies the vehicle's type. See VehicleType.</description>
+ </param>
+
+ <param name="prerecordedSpeech" type="PrerecordedSpeech" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>See PrerecordedSpeech</description>
+ </param>
+
+ <param name="supportedDiagModes" type="Integer" minvalue="0" maxvalue="255" array="true" minsize="1" maxsize="100" mandatory="false">
+ <description>
+ Specifies the white-list of supported diagnostic modes (0x00-0xFF) capable for DiagnosticMessage requests.
+ If a mode outside this list is requested, it will be rejected.
+ </description>
+ </param>
+ <param name="hmiCapabilities" type="HMICapabilities" mandatory="false">
+ <description>Specifies the HMI’s capabilities. See HMICapabilities.</description>
+ </param>
+ <param name="sdlVersion" type="String" maxlength="100" mandatory="false" platform="documentation">
+ <description>The SmartDeviceLink version.</description>
+ </param>
+ <param name="systemSoftwareVersion" type="String" maxlength="100" mandatory="false" platform="documentation">
+ <description>The software version of the system that implements the SmartDeviceLink core.</description>
+ </param>
+ </function>
+
+ <function name="UnregisterAppInterface" functionID="UnregisterAppInterfaceID" messagetype="request">
+ <description>
+ Closes an interface from a mobile application.
+ After unregisterAppInterface, no commands other than registerAppInterface will be accepted/executed.
+ Will fail, if no registerAppInterface was completed successfully before.
+ </description>
+ </function>
+
+ <function name="UnregisterAppInterface" functionID="UnregisterAppInterfaceID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ </function>
+
+ <function name="SetGlobalProperties" functionID="SetGlobalPropertiesID" messagetype="request">
+ <description>Allows setting global properties.</description>
+
+ <param name="helpPrompt" type="TTSChunk" minsize="1" maxsize="100" array="true" mandatory="false" >
+ <description>
+ The help prompt.
+ An array of text chunks of type TTSChunk. See TTSChunk.
+ The array must have at least one item.
+ </description>
+ </param>
+
+ <param name="timeoutPrompt" type="TTSChunk" minsize="1" maxsize="100" array="true" mandatory="false" >
+ <description>
+ Help text for a wait timeout.
+ An array of text chunks of type TTSChunk. See TTSChunk.
+ The array must have at least one item.
+ </description>
+ </param>
+
+ <param name="vrHelpTitle" type="String" maxlength="500" mandatory="false">
+ <description>
+ VR Help Title text.
+ If omitted on supported displays, the default SYNC help title shall be used.
+ If omitted and one or more vrHelp items are provided, the request will be rejected.
+ </description>
+ </param>
+
+ <param name="vrHelp" type="VrHelpItem" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>
+ VR Help Items.
+ If omitted on supported displays, the default AppLink VR help / What Can I Say? screen shall be used.
+ If the list of VR Help Items contains nonsequential positions (e.g. [1,2,4]), the RPC shall be rejected.
+ If omitted and a vrHelpTitle is provided, the request will be rejected.
+ </description>
+ </param>
+ <param name="menuTitle" maxlength="500" type="String" mandatory="false">
+ <description>Optional text to label an app menu button (for certain touchscreen platforms).</description>
+ </param>
+
+ <param name="menuIcon" type="Image" mandatory="false">
+ <description>>Optional icon to draw on an app menu button (for certain touchscreen platforms).</description>
+ </param>
+
+ <param name="keyboardProperties" type="KeyboardProperties" mandatory="false">
+ <description>On-screen keybaord configuration (if available).</description>
+ </param>
+ </function>
+
+ <function name="SetGlobalProperties" functionID="SetGlobalPropertiesID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="DISALLOWED"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ </function>
+
+ <function name="ResetGlobalProperties" functionID="ResetGlobalPropertiesID" messagetype="request">
+ <description>Allows resetting global properties.</description>
+
+ <param name="properties" type="GlobalProperty" minsize="1" maxsize="100" array="true" >
+ <description>Contains the names of all global properties (like timeoutPrompt) that should be unset. Resetting means, that they have the same value as at start up (default)</description>
+ </param>
+ </function>
+
+ <function name="ResetGlobalProperties" functionID="ResetGlobalPropertiesID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="DISALLOWED"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="AddCommand" functionID="AddCommandID" messagetype="request">
+ <description>
+ Adds a command to the in application menu.
+ Either menuParams or vrCommands must be provided.
+ </description>
+
+ <param name="cmdID" type="Integer" minvalue="0" maxvalue="2000000000" mandatory="true">
+ <description>unique ID of the command to add.</description>
+ </param>
+
+ <param name="menuParams" type="MenuParams" mandatory="false">
+ <description>Optional sub value containing menu parameters</description>
+ </param>
+
+ <param name="vrCommands" type="String" minsize="1" maxsize="100" maxlength="99" array="true" mandatory="false">
+ <description>
+ An array of strings to be used as VR synonyms for this command.
+ If this array is provided, it may not be empty.
+ </description>
+ </param>
+
+ <param name="cmdIcon" type="Image" mandatory="false">
+ <description>
+ Image struct determining whether static or dynamic icon.
+ If omitted on supported displays, no (or the default if applicable) icon shall be displayed.
+ </description>
+ </param>
+
+ </function>
+
+ <function name="AddCommand" functionID="AddCommandID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="INVALID_ID"/>
+ <element name="DUPLICATE_NAME"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ <element name="DISALLOWED"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ </function>
+
+ <function name="DeleteCommand" functionID="DeleteCommandID" messagetype="request">
+ <description>Deletes all commands from the in-application menu with the specified command id.</description>
+
+ <param name="cmdID" type="Integer" minvalue="0" maxvalue="2000000000">
+ <description>ID of the command(s) to delete.</description>
+ </param>
+
+ </function>
+
+ <function name="DeleteCommand" functionID="DeleteCommandID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="INVALID_ID"/>
+ <element name="IN_USE"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ </function>
+
+ <function name="AddSubMenu" functionID="AddSubMenuID" messagetype="request">
+ <description>Adds a sub menu to the in-application menu.</description>
+
+ <param name="menuID" type="Integer" minvalue="1" maxvalue="2000000000">
+ <description>unique ID of the sub menu to add.</description>
+ </param>
+
+ <param name="position" type="Integer" minvalue="0" maxvalue="1000" defvalue="1000" mandatory="false">
+ <description>
+ Position within the items that are are at top level of the in application menu.
+ 0 will insert at the front.
+ 1 will insert at the second position.
+ If position is greater or equal than the number of items on top level, the sub menu will be appended to the end.
+ Position of any submenu will always be located before the return and exit options
+ If this param was omitted the entry will be added at the end.
+ </description>
+ </param>
+
+ <param name="menuName" maxlength="500" type="String">
+ <description>Text to show in the menu for this sub menu.</description>
+ </param>
+ </function>
+
+ <function name="AddSubMenu" functionID="AddSubMenuID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="INVALID_ID"/>
+ <element name="DUPLICATE_NAME"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="DeleteSubMenu" functionID="DeleteSubMenuID" messagetype="request">
+ <description>Deletes a submenu from the in-application menu.</description>
+
+ <param name="menuID" type="Integer" minvalue="1" maxvalue="2000000000">
+ <description>The "menuID" of the submenu to delete. (See addSubMenu.menuID)</description>
+ </param>
+
+ </function>
+
+ <function name="DeleteSubMenu" functionID="DeleteSubMenuID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="INVALID_ID"/>
+ <element name="IN_USE"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ </function>
+
+ <function name="CreateInteractionChoiceSet" functionID="CreateInteractionChoiceSetID" messagetype="request">
+ <description>creates interaction choice set to be used later by performInteraction</description>
+
+ <param name="interactionChoiceSetID" type="Integer" minvalue="0" maxvalue="2000000000">
+ <description>Unique ID used for this interaction choice set.</description>
+ </param>
+
+ <param name="choiceSet" type="Choice" minsize="1" maxsize="100" array="true" />
+ </function>
+
+ <function name="CreateInteractionChoiceSet" functionID="CreateInteractionChoiceSetID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="INVALID_ID"/>
+ <element name="DUPLICATE_NAME"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="PerformInteraction" functionID="PerformInteractionID" messagetype="request">
+ <description>Triggers an interaction (e.g. "Permit GPS?" - Yes, no, Always Allow).</description>
+
+ <param name="initialText" type="String" maxlength="500" >
+ <description>Text to be displayed first.</description>
+ </param>
+
+ <param name="initialPrompt" type="TTSChunk" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>
+ This is the intial prompt spoken to the user at the start of an interaction.
+ An array of text chunks of type TTSChunk. See TTSChunk.
+ The array must have at least one item.
+ </description>
+ </param>
+
+ <param name="interactionMode" type="InteractionMode">
+ <description>See InteractionMode.</description>
+ </param>
+
+ <param name="interactionChoiceSetIDList" type="Integer" minsize="0" maxsize="100" minvalue="0" maxvalue="2000000000" array="true">
+ <description>List of interaction choice set IDs to use with an interaction.</description>
+ </param>
+
+ <param name="helpPrompt" type="TTSChunk" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>
+ Help text. This is the spoken string when a user speaks "help" when the interaction is occuring.
+ An array of text chunks of type TTSChunk. See TTSChunk.
+ The array must have at least one item.
+ </description>
+ </param>
+
+ <param name="timeoutPrompt" type="TTSChunk" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>
+ Timeout text. This text is spoken when a VR interaction times out.
+ An array of text chunks of type TTSChunk. See TTSChunk.
+ The array must have at least one item.
+ </description>
+ </param>
+
+ <param name="timeout" type="Integer" minvalue="5000" maxvalue="100000" defvalue="10000" mandatory="false">
+ <description>
+ Timeout in milliseconds.
+ If omitted a standard value of 10000 milliseconds is used.
+ Applies only to the menu portion of the interaction. The VR timeout will be handled by the platform.
+ </description>
+ </param>
+
+ <param name="vrHelp" type="VrHelpItem" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>
+ Ability to send suggested VR Help Items to display on-screen during Perform Interaction.
+ If omitted on supported displays, the default SYNC generated list of suggested choices shall be displayed.
+ </description>
+ </param>
+
+ <param name="interactionLayout" type="LayoutMode" mandatory="false">
+ <description>See LayoutMode.</description>
+ </param>
+
+ </function>
+
+ <function name="PerformInteraction" functionID="PerformInteractionID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="INVALID_ID"/>
+ <element name="DUPLICATE_NAME"/>
+ <element name="TIMED_OUT"/>
+ <element name="ABORTED"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ <element name="WARNINGS"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ <param name="choiceID" type="Integer" minvalue="0" maxvalue="2000000000" mandatory="false">
+ <description>
+ ID of the choice that was selected in response to PerformInteraction.
+ Only is valid if resultCode is SUCCESS.
+ </description>
+ </param>
+
+ <param name="manualTextEntry" type="String" maxlength="500" mandatory="false">
+ <description>
+ Manually entered text selection, e.g. through keyboard
+ Can be returned in lieu of choiceID, depending on trigger source
+ </description>
+ </param>
+
+ <param name="triggerSource" type="TriggerSource" mandatory="false">
+ <description>
+ See TriggerSource
+ Only is valid if resultCode is SUCCESS.
+ </description>
+ </param>
+
+ </function>
+
+ <function name="DeleteInteractionChoiceSet" functionID="DeleteInteractionChoiceSetID" messagetype="request">
+ <description>Deletes interaction choice set that has been created with "CreateInteractionChoiceSet".</description>
+ <description>The interaction may only be deleted when not currently in use by a "performInteraction".</description>
+
+ <param name="interactionChoiceSetID" type="Integer" minvalue="0" maxvalue="2000000000">
+ <description>ID of the interaction choice set to delete.</description>
+ </param>
+ </function>
+
+ <function name="DeleteInteractionChoiceSet" functionID="DeleteInteractionChoiceSetID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="INVALID_ID"/>
+ <element name="IN_USE"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="Alert" functionID="AlertID" messagetype="request">
+ <description>Shows an alert which typically consists of text-to-speech message and text on the display. At least either alertText1, alertText2 or TTSChunks need to be provided.</description>
+
+ <param name="alertText1" type="String" maxlength="500" mandatory="false">
+ <description>The first line of the alert text field</description>
+ </param>
+
+ <param name="alertText2" type="String" maxlength="500" mandatory="false">
+ <description>The second line of the alert text field</description>
+ </param>
+
+ <param name="alertText3" type="String" maxlength="500" mandatory="false">
+ <description>The optional third line of the alert text field</description>
+ </param>
+
+ <param name="ttsChunks" type="TTSChunk" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>
+ An array of text chunks of type TTSChunk. See TTSChunk.
+ The array must have at least one item.
+ </description>
+ </param>
+
+ <param name="duration" type="Integer" minvalue="3000" maxvalue="10000" defvalue="5000" mandatory="false">
+ <description>
+ Timeout in milliseconds.
+ Typical timeouts are 3-5 seconds.
+ If omitted, timeout is set to 5s.
+ </description>
+ </param>
+
+ <param name="playTone" type="Boolean" mandatory="false">
+ <description>
+ Defines if tone should be played. Tone is played before TTS.
+ If omitted, no tone is played.
+ </description>
+ </param>
+
+ <param name="progressIndicator" type="Boolean" mandatory="false" platform="MobileNav">
+ <description>
+ If supported on the given platform, the alert GUI will include some sort of animation indicating that loading of a feature is progressing. e.g. a spinning wheel or hourglass, etc.
+ </description>
+ </param>
+
+ <param name="softButtons" type="SoftButton" minsize="0" maxsize="4" array="true" mandatory="false">
+ <description>
+ App defined SoftButtons.
+ If omitted on supported displays, the displayed alert shall not have any SoftButtons.
+ </description>
+ </param>
+
+ </function>
+
+ <function name="Alert" functionID="AlertID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="ABORTED"/>
+ <element name="DISALLOWED"/>
+ <element name="USER_DISALLOWED"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ <element name="WARNINGS"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ <param name="tryAgainTime" type="Integer" minvalue="0" maxvalue="2000000000" mandatory="false">
+ <description>
+ Amount of time (in seconds) that an app must wait before resending an alert.
+ If provided, another system event or overlay currently has a higher priority than this alert.
+ An app must not send an alert without waiting at least the amount of time dictated.
+ </description>
+ </param>
+
+ </function>
+
+ <function name="Show" functionID="ShowID" messagetype="request">
+ <description>Updates the persistent display. Supported fields depend on display capabilities.</description>
+
+ <param name="mainField1" type="String" minlength="0" maxlength="500" mandatory="false">
+ <description>
+ The text that should be displayed in a single or upper display line.
+ If this text is not set, the text of mainField1 stays unchanged.
+ If this text is empty "", the field will be cleared.
+ </description>
+ </param>
+
+ <param name="mainField2" type="String" minlength="0" maxlength="500" mandatory="false">
+ <description>
+ The text that should be displayed on the second display line.
+ If this text is not set, the text of mainField2 stays unchanged.
+ If this text is empty "", the field will be cleared.
+ </description>
+ </param>
+
+ <param name="mainField3" type="String" minlength="0" maxlength="500" mandatory="false">
+ <description>
+ The text that should be displayed on the second "page" first display line.
+ If this text is not set, the text of mainField3 stays unchanged.
+ If this text is empty "", the field will be cleared.
+ </description>
+ </param>
+
+ <param name="mainField4" type="String" minlength="0" maxlength="500" mandatory="false">
+ <description>
+ The text that should be displayed on the second "page" second display line.
+ If this text is not set, the text of mainField4 stays unchanged.
+ If this text is empty "", the field will be cleared.
+ </description>
+ </param>
+
+ <param name="alignment" type="TextAlignment" mandatory="false">
+ <description>
+ Specifies how mainField1 and mainField2 texts should be aligned on display.
+ If omitted, texts will be centered.
+ </description>
+ </param>
+
+ <param name="statusBar" type="String" minlength="0" maxlength="500" mandatory="false">
+ <description>Requires investigation regarding the nav display capabilities. Potentially lower lowerStatusBar, upperStatusBar, titleBar, etc.</description>
+ </param>
+
+ <param name="mediaClock" type="String" minlength="0" maxlength="500" mandatory="false">
+ <description>
+ Text value for MediaClock field. Has to be properly formatted by Mobile App according to Sync capabilities.
+ If this text is set, any automatic media clock updates previously set with SetMediaClockTimer will be stopped.
+ </description>
+ </param>
+
+ <param name="mediaTrack" type="String" minlength="0" maxlength="500" mandatory="false">
+ <description>
+ The text that should be displayed in the track field.
+ This field is only valid for media applications on NGN type ACMs.
+ If this text is not set, the text of mediaTrack stays unchanged.
+ If this text is empty "", the field will be cleared.
+ </description>
+ </param>
+
+ <param name="graphic" type="Image" mandatory="false">
+ <description>
+ Image struct determining whether static or dynamic image to display in app.
+ If omitted on supported displays, the displayed graphic shall not change.
+ </description>
+ </param>
+
+ <param name="secondaryGraphic" type="Image" mandatory="false">
+ <description>
+ Image struct determining whether static or dynamic secondary image to display in app.
+ If omitted on supported displays, the displayed secondary graphic shall not change.
+ </description>
+ </param>
+
+
+ <param name="softButtons" type="SoftButton" minsize="0" maxsize="8" array="true" mandatory="false">
+ <description>
+ App defined SoftButtons.
+ If omitted on supported displays, the currently displayed SoftButton values will not change.
+ </description>
+ </param>
+
+ <param name="customPresets" type="String" maxlength="500" minsize="0" maxsize="10" array="true" mandatory="false">
+ <description>
+ App labeled on-screen presets (i.e. GEN2).
+ If omitted on supported displays, the presets will be shown as not defined.
+ </description>
+ </param>
+
+ </function>
+
+ <function name="Show" functionID="ShowID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="DISALLOWED"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ <element name="ABORTED"/>
+ <element name="WARNINGS"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="Speak" functionID="SpeakID" messagetype="request">
+ <description>Speaks a text.</description>
+
+ <param name="ttsChunks" type="TTSChunk" minsize="1" maxsize="100" array="true">
+ <description>
+ An array of text chunks of type TTSChunk. See TTSChunk.
+ The array must have at least one item.
+ </description>
+ </param>
+
+ </function>
+
+ <function name="Speak" functionID="SpeakID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="DISALLOWED"/>
+ <element name="ABORTED"/>
+ <element name="WARNINGS"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ </function>
+
+ <function name="SetMediaClockTimer" functionID="SetMediaClockTimerID" messagetype="request">
+ <description>Sets the initial media clock value and automatic update method.</description>
+
+ <param name="startTime" type="StartTime" mandatory="false">
+ <description>
+ See StartTime.
+ startTime must be provided for "COUNTUP" and "COUNTDOWN".
+ startTime will be ignored for "PAUSE", "RESUME", and "CLEAR"
+ </description>
+ </param>
+
+ <param name="endTime" type="StartTime" mandatory="false">
+ <description>
+ See StartTime.
+ endTime can be provided for "COUNTUP" and "COUNTDOWN"; to be used to calculate any visual progress bar (if not provided, this feature is ignored)
+ If endTime is greater then startTime for COUNTDOWN or less than startTime for COUNTUP, then the request will return an INVALID_DATA.
+ endTime will be ignored for "PAUSE", "RESUME", and "CLEAR"
+ </description>
+ </param>
+
+ <param name="updateMode" type="UpdateMode" mandatory="true">
+ <description>
+ Enumeration to control the media clock.
+ In case of pause, resume, or clear, the start time value is ignored and shall be left out. For resume, the time continues with the same value as it was when paused.
+ </description>
+ </param>
+ </function>
+
+ <function name="SetMediaClockTimer" functionID="SetMediaClockTimerID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="IGNORED"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="PerformAudioPassThru" functionID="PerformAudioPassThruID" messagetype="request">
+ <description>Starts audio pass thru session </description>
+ <param name="initialPrompt" type="TTSChunk" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>
+ SYNC will speak this prompt before opening the audio pass thru session.
+ An array of text chunks of type TTSChunk. See TTSChunk.
+ The array must have at least one item.
+ If omitted, then no initial prompt is spoken.
+ </description>
+ </param>
+ <param name="audioPassThruDisplayText1" type="String" mandatory="false" maxlength="500">
+ <description>First line of text displayed during audio capture.</description>
+ </param>
+ <param name="audioPassThruDisplayText2" type="String" mandatory="false" maxlength="500">
+ <description>Second line of text displayed during audio capture.</description>
+ </param>
+ <param name="samplingRate" type="SamplingRate" mandatory="true">
+ <description> This value shall be allowed at 8 khz or 16 or 22 or 44 khz.</description>
+ </param>
+ <param name="maxDuration" type="Integer" minvalue="1" maxvalue="1000000" mandatory="true">
+ <description>The maximum duration of audio recording in milliseconds. </description>
+ </param>
+ <param name="bitsPerSample" type="BitsPerSample" mandatory="true">
+ <description>Specifies the quality the audio is recorded. Currently 8 bit or 16 bit.</description>
+ </param>
+ <param name="audioType" type="AudioType" mandatory="true">
+ <description>Specifies the type of audio data being requested.</description>
+ </param>
+ <param name="muteAudio" type="Boolean" mandatory="false">
+ <description>
+ Defines if the current audio source should be muted during the APT session. If not, the audio source will play without interruption.
+ If omitted, the value is set to true.
+ </description>
+ </param>
+ </function>
+
+ <function name="PerformAudioPassThru" functionID="PerformAudioPassThruID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="DISALLOWED"/>
+ <element name="REJECTED"/>
+ <element name="ABORTED"/>
+ <element name="RETRY"/>
+ <element name="WARNINGS"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="EndAudioPassThru" functionID="EndAudioPassThruID" messagetype="request">
+ <description>When this request is invoked, the audio capture stops.</description>
+ </function>
+
+ <function name="EndAudioPassThru" functionID="EndAudioPassThruID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="DISALLOWED"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="SubscribeButton" functionID="SubscribeButtonID" messagetype="request">
+ <description>
+ Subscribes to built-in HMI buttons.
+ The application will be notified by the OnButtonEvent and OnButtonPress.
+ To unsubscribe the notifications, use unsubscribeButton.
+ </description>
+
+ <param name="buttonName" type="ButtonName">
+ <description>Name of the button to subscribe.</description>
+ </param>
+ </function>
+
+ <function name="SubscribeButton" functionID="SubscribeButtonID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="UNSUPPORTED_RESOURCE" />
+ <element name="IGNORED" />
+ <element name="REJECTED"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="UnsubscribeButton" functionID="UnsubscribeButtonID" messagetype="request">
+ <description>Unsubscribes from built-in HMI buttons.</description>
+
+ <param name="buttonName" type="ButtonName">
+ <description>Name of the button to unsubscribe.</description>
+ </param>
+ </function>
+
+ <function name="UnsubscribeButton" functionID="UnsubscribeButtonID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="UNSUPPORTED_RESOURCE" />
+ <element name="IGNORED" />
+ <element name="REJECTED"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="SubscribeVehicleData" functionID="SubscribeVehicleDataID" messagetype="request">
+ <description>
+ Subscribes for specific published data items.
+ The data will be only sent if it has changed.
+ The application will be notified by the onVehicleData notification whenever new data is available.
+ To unsubscribe the notifications, use unsubscribe with the same subscriptionType.
+ </description>
+
+ <param name="gps" type="Boolean" mandatory="false">
+ <description>See GPSData</description>
+ </param>
+ <param name="speed" type="Boolean" mandatory="false">
+ <description>The vehicle speed in kilometers per hour</description>
+ </param>
+ <param name="rpm" type="Boolean" mandatory="false">
+ <description>The number of revolutions per minute of the engine</description>
+ </param>
+ <param name="fuelLevel" type="Boolean" mandatory="false">
+ <description>The fuel level in the tank (percentage)</description>
+ </param>
+ <param name="fuelLevel_State" type="Boolean" mandatory="false">
+ <description>The fuel level state</description>
+ </param>
+ <param name="instantFuelConsumption" type="Boolean" mandatory="false">
+ <description>The instantaneous fuel consumption in microlitres</description>
+ </param>
+ <param name="externalTemperature" type="Boolean" mandatory="false">
+ <description>The external temperature in degrees celsius</description>
+ </param>
+ <param name="prndl" type="Boolean" mandatory="false">
+ <description>See PRNDL</description>
+ </param>
+ <param name="tirePressure" type="Boolean" mandatory="false">
+ <description>See TireStatus</description>
+ </param>
+ <param name="odometer" type="Boolean" mandatory="false">
+ <description>Odometer in km</description>
+ </param>
+ <param name="beltStatus" type="Boolean" mandatory="false">
+ <description>The status of the seat belts</description>
+ </param>
+ <param name="bodyInformation" type="Boolean" mandatory="false">
+ <description>The body information including power modes</description>
+ </param>
+ <param name="deviceStatus" type="Boolean" mandatory="false">
+ <description>The device status including signal and battery strength</description>
+ </param>
+ <param name="driverBraking" type="Boolean" mandatory="false">
+ <description>The status of the brake pedal</description>
+ </param>
+ <param name="wiperStatus" type="Boolean" mandatory="false">
+ <description>The status of the wipers</description>
+ </param>
+ <param name="headLampStatus" type="Boolean" mandatory="false">
+ <description>Status of the head lamps</description>
+ </param>
+ <param name="engineTorque" type="Boolean" mandatory="false">
+ <description>Torque value for engine (in Nm) on non-diesel variants</description>
+ </param>
+ <param name="accPedalPosition" type="Boolean" mandatory="false">
+ <description>Accelerator pedal position (percentage depressed)</description>
+ </param>
+ <param name="steeringWheelAngle" type="Boolean" mandatory="false">
+ <description>Current angle of the steering wheel (in deg)</description>
+ </param>
+
+ <!-- Ford Specific Data Items -->
+ <param name="eCallInfo" type="Boolean" mandatory="false">
+ <description>Emergency Call notification and confirmation data</description>
+ </param>
+ <param name="airbagStatus" type="Boolean" mandatory="false">
+ <description>The status of the air bags</description>
+ </param>
+ <param name="emergencyEvent" type="Boolean" mandatory="false">
+ <description>Information related to an emergency event (and if it occurred)</description>
+ </param>
+ <param name="clusterModeStatus" type="Boolean" mandatory="false">
+ <description>The status modes of the cluster</description>
+ </param>
+ <param name="myKey" type="Boolean" mandatory="false">
+ <description>Information related to the MyKey feature</description>
+ </param>
+
+ <!-- / Ford Specific Data Items -->
+
+ </function>
+
+ <function name="SubscribeVehicleData" functionID="SubscribeVehicleDataID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="WARNINGS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="IGNORED" />
+ <element name="DISALLOWED"/>
+ <element name="USER_DISALLOWED"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ <param name="gps" type="VehicleDataResult" mandatory="false">
+ <description>See GPSData</description>
+ </param>
+ <param name="speed" type="VehicleDataResult" mandatory="false">
+ <description>The vehicle speed in kilometers per hour</description>
+ </param>
+ <param name="rpm" type="VehicleDataResult" mandatory="false">
+ <description>The number of revolutions per minute of the engine</description>
+ </param>
+ <param name="fuelLevel" type="VehicleDataResult" mandatory="false">
+ <description>The fuel level in the tank (percentage)</description>
+ </param>
+ <param name="fuelLevel_State" type="VehicleDataResult" mandatory="false">
+ <description>The fuel level state</description>
+ </param>
+ <param name="instantFuelConsumption" type="VehicleDataResult" mandatory="false">
+ <description>The instantaneous fuel consumption in microlitres</description>
+ </param>
+ <param name="externalTemperature" type="VehicleDataResult" mandatory="false">
+ <description>The external temperature in degrees celsius.</description>
+ </param>
+ <param name="prndl" type="VehicleDataResult" mandatory="false">
+ <description>See PRNDL</description>
+ </param>
+ <param name="tirePressure" type="VehicleDataResult" mandatory="false">
+ <description>See TireStatus</description>
+ </param>
+ <param name="odometer" type="VehicleDataResult" mandatory="false">
+ <description>Odometer in km</description>
+ </param>
+ <param name="beltStatus" type="VehicleDataResult" mandatory="false">
+ <description>The status of the seat belts</description>
+ </param>
+ <param name="bodyInformation" type="VehicleDataResult" mandatory="false">
+ <description>The body information including power modes</description>
+ </param>
+ <param name="deviceStatus" type="VehicleDataResult" mandatory="false">
+ <description>The device status including signal and battery strength</description>
+ </param>
+ <param name="driverBraking" type="VehicleDataResult" mandatory="false">
+ <description>The status of the brake pedal</description>
+ </param>
+ <param name="wiperStatus" type="VehicleDataResult" mandatory="false">
+ <description>The status of the wipers</description>
+ </param>
+ <param name="headLampStatus" type="VehicleDataResult" mandatory="false">
+ <description>Status of the head lamps</description>
+ </param>
+ <param name="engineTorque" type="VehicleDataResult" mandatory="false">
+ <description>Torque value for engine (in Nm) on non-diesel variants</description>
+ </param>
+ <param name="accPedalPosition" type="VehicleDataResult" mandatory="false">
+ <description>Accelerator pedal position (percentage depressed)</description>
+ </param>
+ <param name="steeringWheelAngle" type="VehicleDataResult" mandatory="false">
+ <description>Current angle of the steering wheel (in deg)</description>
+ </param>
+
+ <!-- Ford Specific Data Items -->
+ <param name="eCallInfo" type="VehicleDataResult" mandatory="false">
+ <description>Emergency Call notification and confirmation data</description>
+ </param>
+ <param name="airbagStatus" type="VehicleDataResult" mandatory="false">
+ <description>The status of the air bags</description>
+ </param>
+ <param name="emergencyEvent" type="VehicleDataResult" mandatory="false">
+ <description>Information related to an emergency event (and if it occurred)</description>
+ </param>
+ <param name="clusterModes" type="VehicleDataResult" mandatory="false">
+ <description>The status modes of the cluster</description>
+ </param>
+ <param name="myKey" type="VehicleDataResult" mandatory="false">
+ <description>Information related to the MyKey feature</description>
+ </param>
+ <!-- / Ford Specific Data Items -->
+
+ </function>
+
+ <function name="UnsubscribeVehicleData" functionID="UnsubscribeVehicleDataID" messagetype="request">
+ <description>This function is used to unsubscribe the notifications from the subscribeVehicleData function.</description>
+
+ <param name="gps" type="Boolean" mandatory="false">
+ <description>See GPSData</description>
+ </param>
+ <param name="speed" type="Boolean" mandatory="false">
+ <description>The vehicle speed in kilometers per hour</description>
+ </param>
+ <param name="rpm" type="Boolean" mandatory="false">
+ <description>The number of revolutions per minute of the engine</description>
+ </param>
+ <param name="fuelLevel" type="Boolean" mandatory="false">
+ <description>The fuel level in the tank (percentage)</description>
+ </param>
+ <param name="fuelLevel_State" type="Boolean" mandatory="false">
+ <description>The fuel level state</description>
+ </param>
+ <param name="instantFuelConsumption" type="Boolean" mandatory="false">
+ <description>The instantaneous fuel consumption in microlitres</description>
+ </param>
+ <param name="externalTemperature" type="Boolean" mandatory="false">
+ <description>The external temperature in degrees celsius.</description>
+ </param>
+ <param name="prndl" type="Boolean" mandatory="false">
+ <description>See PRNDL</description>
+ </param>
+ <param name="tirePressure" type="Boolean" mandatory="false">
+ <description>See TireStatus</description>
+ </param>
+ <param name="odometer" type="Boolean" mandatory="false">
+ <description>Odometer in km</description>
+ </param>
+ <param name="beltStatus" type="Boolean" mandatory="false">
+ <description>The status of the seat belts</description>
+ </param>
+ <param name="bodyInformation" type="Boolean" mandatory="false">
+ <description>The body information including power modes</description>
+ </param>
+ <param name="deviceStatus" type="Boolean" mandatory="false">
+ <description>The device status including signal and battery strength</description>
+ </param>
+ <param name="driverBraking" type="Boolean" mandatory="false">
+ <description>The status of the brake pedal</description>
+ </param>
+ <param name="wiperStatus" type="Boolean" mandatory="false">
+ <description>The status of the wipers</description>
+ </param>
+ <param name="headLampStatus" type="Boolean" mandatory="false">
+ <description>Status of the head lamps</description>
+ </param>
+ <param name="engineTorque" type="Boolean" mandatory="false">
+ <description>Torque value for engine (in Nm) on non-diesel variants</description>
+ </param>
+ <param name="accPedalPosition" type="Boolean" mandatory="false">
+ <description>Accelerator pedal position (percentage depressed)</description>
+ </param>
+ <param name="steeringWheelAngle" type="Boolean" mandatory="false">
+ <description>Current angle of the steering wheel (in deg)</description>
+ </param>
+
+ <!-- Ford Specific Data Items -->
+ <param name="eCallInfo" type="Boolean" mandatory="false">
+ <description>Emergency Call notification and confirmation data</description>
+ </param>
+ <param name="airbagStatus" type="Boolean" mandatory="false">
+ <description>The status of the air bags</description>
+ </param>
+ <param name="emergencyEvent" type="Boolean" mandatory="false">
+ <description>Information related to an emergency event (and if it occurred)</description>
+ </param>
+ <param name="clusterModeStatus" type="Boolean" mandatory="false">
+ <description>The status modes of the cluster</description>
+ </param>
+ <param name="myKey" type="Boolean" mandatory="false">
+ <description>Information related to the MyKey feature</description>
+ </param>
+ <!-- / Ford Specific Data Items -->
+
+ </function>
+
+ <function name="UnsubscribeVehicleData" functionID="UnsubscribeVehicleDataID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="WARNINGS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="IGNORED" />
+ <element name="DISALLOWED"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ <param name="gps" type="VehicleDataResult" mandatory="false">
+ <description>See GPSData</description>
+ </param>
+ <param name="speed" type="VehicleDataResult" mandatory="false">
+ <description>The vehicle speed in kilometers per hour</description>
+ </param>
+ <param name="rpm" type="VehicleDataResult" mandatory="false">
+ <description>The number of revolutions per minute of the engine</description>
+ </param>
+ <param name="fuelLevel" type="VehicleDataResult" mandatory="false">
+ <description>The fuel level in the tank (percentage)</description>
+ </param>
+ <param name="fuelLevel_State" type="VehicleDataResult" mandatory="false">
+ <description>The fuel level state</description>
+ </param>
+ <param name="instantFuelConsumption" type="VehicleDataResult" mandatory="false">
+ <description>The instantaneous fuel consumption in microlitres</description>
+ </param>
+ <param name="externalTemperature" type="VehicleDataResult" mandatory="false">
+ <description>The external temperature in degrees celsius</description>
+ </param>
+ <param name="prndl" type="VehicleDataResult" mandatory="false">
+ <description>See PRNDL</description>
+ </param>
+ <param name="tirePressure" type="VehicleDataResult" mandatory="false">
+ <description>See TireStatus</description>
+ </param>
+ <param name="odometer" type="VehicleDataResult" mandatory="false">
+ <description>Odometer in km</description>
+ </param>
+ <param name="beltStatus" type="VehicleDataResult" mandatory="false">
+ <description>The status of the seat belts</description>
+ </param>
+ <param name="bodyInformation" type="VehicleDataResult" mandatory="false">
+ <description>The body information including power modes</description>
+ </param>
+ <param name="deviceStatus" type="VehicleDataResult" mandatory="false">
+ <description>The device status including signal and battery strength</description>
+ </param>
+ <param name="driverBraking" type="VehicleDataResult" mandatory="false">
+ <description>The status of the brake pedal</description>
+ </param>
+ <param name="wiperStatus" type="VehicleDataResult" mandatory="false">
+ <description>The status of the wipers</description>
+ </param>
+ <param name="headLampStatus" type="VehicleDataResult" mandatory="false">
+ <description>Status of the head lamps</description>
+ </param>
+ <param name="engineTorque" type="VehicleDataResult" mandatory="false">
+ <description>Torque value for engine (in Nm) on non-diesel variants</description>
+ </param>
+ <param name="accPedalPosition" type="VehicleDataResult" mandatory="false">
+ <description>Accelerator pedal position (percentage depressed)</description>
+ </param>
+ <param name="steeringWheelAngle" type="VehicleDataResult" mandatory="false">
+ <description>Current angle of the steering wheel (in deg)</description>
+ </param>
+
+ <!-- Ford Specific Data Items -->
+ <param name="eCallInfo" type="VehicleDataResult" mandatory="false">
+ <description>Emergency Call notification and confirmation data</description>
+ </param>
+ <param name="airbagStatus" type="VehicleDataResult" mandatory="false">
+ <description>The status of the air bags</description>
+ </param>
+ <param name="emergencyEvent" type="VehicleDataResult" mandatory="false">
+ <description>Information related to an emergency event (and if it occurred)</description>
+ </param>
+ <param name="clusterModes" type="VehicleDataResult" mandatory="false">
+ <description>The status modes of the cluster</description>
+ </param>
+ <param name="myKey" type="VehicleDataResult" mandatory="false">
+ <description>Information related to the MyKey feature</description>
+ </param>
+ <!-- / Ford Specific Data Items -->
+
+ </function>
+
+ <function name="GetVehicleData" functionID="GetVehicleDataID" messagetype="request">
+ <description>Non periodic vehicle data read request.</description>
+
+ <param name="gps" type="Boolean" mandatory="false">
+ <description>See GPSData</description>
+ </param>
+ <param name="speed" type="Boolean" mandatory="false">
+ <description>The vehicle speed in kilometers per hour</description>
+ </param>
+ <param name="rpm" type="Boolean" mandatory="false">
+ <description>The number of revolutions per minute of the engine</description>
+ </param>
+ <param name="fuelLevel" type="Boolean" mandatory="false">
+ <description>The fuel level in the tank (percentage)</description>
+ </param>
+ <param name="fuelLevel_State" type="Boolean" mandatory="false">
+ <description>The fuel level state</description>
+ </param>
+ <param name="instantFuelConsumption" type="Boolean" mandatory="false">
+ <description>The instantaneous fuel consumption in microlitres</description>
+ </param>
+ <param name="externalTemperature" type="Boolean" mandatory="false">
+ <description>The external temperature in degrees celsius</description>
+ </param>
+ <param name="vin" type="Boolean" mandatory="false">
+ <description>Vehicle identification number</description>
+ </param>
+ <param name="prndl" type="Boolean" mandatory="false">
+ <description>See PRNDL</description>
+ </param>
+ <param name="tirePressure" type="Boolean" mandatory="false">
+ <description>See TireStatus</description>
+ </param>
+ <param name="odometer" type="Boolean" mandatory="false">
+ <description>Odometer in km</description>
+ </param>
+ <param name="beltStatus" type="Boolean" mandatory="false">
+ <description>The status of the seat belts</description>
+ </param>
+ <param name="bodyInformation" type="Boolean" mandatory="false">
+ <description>The body information including ignition status and internal temp</description>
+ </param>
+ <param name="deviceStatus" type="Boolean" mandatory="false">
+ <description>The device status including signal and battery strength</description>
+ </param>
+ <param name="driverBraking" type="Boolean" mandatory="false">
+ <description>The status of the brake pedal</description>
+ </param>
+ <param name="wiperStatus" type="Boolean" mandatory="false">
+ <description>The status of the wipers</description>
+ </param>
+ <param name="headLampStatus" type="Boolean" mandatory="false">
+ <description>Status of the head lamps</description>
+ </param>
+ <param name="engineTorque" type="Boolean" mandatory="false">
+ <description>Torque value for engine (in Nm) on non-diesel variants</description>
+ </param>
+ <param name="accPedalPosition" type="Boolean" mandatory="false">
+ <description>Accelerator pedal position (percentage depressed)</description>
+ </param>
+ <param name="steeringWheelAngle" type="Boolean" mandatory="false">
+ <description>Current angle of the steering wheel (in deg)</description>
+ </param>
+
+ <!-- Ford Specific Data Items -->
+ <param name="eCallInfo" type="Boolean" mandatory="false">
+ <description>Emergency Call notification and confirmation data</description>
+ </param>
+ <param name="airbagStatus" type="Boolean" mandatory="false">
+ <description>The status of the air bags</description>
+ </param>
+ <param name="emergencyEvent" type="Boolean" mandatory="false">
+ <description>Information related to an emergency event (and if it occurred)</description>
+ </param>
+ <param name="clusterModeStatus" type="Boolean" mandatory="false">
+ <description>The status modes of the cluster</description>
+ </param>
+ <param name="myKey" type="Boolean" mandatory="false">
+ <description>Information related to the MyKey feature</description>
+ </param>
+ <!-- / Ford Specific Data Items -->
+
+ </function>
+
+ <function name="GetVehicleData" functionID="GetVehicleDataID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="VEHICLE_DATA_NOT_ALLOWED"/>
+ <element name="VEHICLE_DATA_NOT_AVAILABLE"/>
+ <element name="USER_DISALLOWED"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ <param name="gps" type="GPSData" mandatory="false">
+ <description>See GPSData</description>
+ </param>
+ <param name="speed" type="Float" minvalue="0" maxvalue="700" mandatory="false">
+ <description>The vehicle speed in kilometers per hour</description>
+ </param>
+ <param name="rpm" type="Integer" minvalue="0" maxvalue="20000" mandatory="false">
+ <description>The number of revolutions per minute of the engine</description>
+ </param>
+ <param name="fuelLevel" type="Float" minvalue="-6" maxvalue="106" mandatory="false">
+ <description>The fuel level in the tank (percentage)</description>
+ </param>
+ <param name="fuelLevel_State" type="ComponentVolumeStatus" mandatory="false">
+ <description>The fuel level state</description>
+ </param>
+ <param name="instantFuelConsumption" type="Float" minvalue="0" maxvalue="25575" mandatory="false">
+ <description>The instantaneous fuel consumption in microlitres</description>
+ </param>
+ <param name="externalTemperature" type="Float" minvalue="-40" maxvalue="100" mandatory="false">
+ <description>The external temperature in degrees celsius</description>
+ </param>
+ <param name="vin" type="String" maxlength="17" mandatory="false">
+ <description>Vehicle identification number</description>
+ </param>
+ <param name="prndl" type="PRNDL" mandatory="false">
+ <description>See PRNDL</description>
+ </param>
+ <param name="tirePressure" type="TireStatus" mandatory="false">
+ <description>See TireStatus</description>
+ </param>
+ <param name="odometer" type="Integer" minvalue="0" maxvalue="17000000" mandatory="false">
+ <description>Odometer in km</description>
+ </param>
+ <param name="beltStatus" type="BeltStatus" mandatory="false">
+ <description>The status of the seat belts</description>
+ </param>
+ <param name="bodyInformation" type="BodyInformation" mandatory="false">
+ <description>The body information including power modes</description>
+ </param>
+ <param name="deviceStatus" type="DeviceStatus" mandatory="false">
+ <description>The device status including signal and battery strength</description>
+ </param>
+ <param name="driverBraking" type="VehicleDataEventStatus" mandatory="false">
+ <description>The status of the brake pedal</description>
+ </param>
+ <param name="wiperStatus" type="WiperStatus" mandatory="false">
+ <description>The status of the wipers</description>
+ </param>
+ <param name="headLampStatus" type="HeadLampStatus" mandatory="false">
+ <description>Status of the head lamps</description>
+ </param>
+ <param name="engineTorque" type="Float" minvalue="-1000" maxvalue="2000" mandatory="false">
+ <description>Torque value for engine (in Nm) on non-diesel variants</description>
+ </param>
+ <param name="accPedalPosition" type="Float" minvalue="0" maxvalue="100" mandatory="false">
+ <description>Accelerator pedal position (percentage depressed)</description>
+ </param>
+ <param name="steeringWheelAngle" type="Float" minvalue="-2000" maxvalue="2000" mandatory="false">
+ <description>Current angle of the steering wheel (in deg)</description>
+ </param>
+
+ <!-- Ford Specific Data Items -->
+ <param name="eCallInfo" type="ECallInfo" mandatory="false">
+ <description>Emergency Call notification and confirmation data</description>
+ </param>
+ <param name="airbagStatus" type="AirbagStatus" mandatory="false">
+ <description>The status of the air bags</description>
+ </param>
+ <param name="emergencyEvent" type="EmergencyEvent" mandatory="false">
+ <description>Information related to an emergency event (and if it occurred)</description>
+ </param>
+ <param name="clusterModeStatus" type="ClusterModeStatus" mandatory="false">
+ <description>The status modes of the cluster</description>
+ </param>
+ <param name="myKey" type="MyKey" mandatory="false">
+ <description>Information related to the MyKey feature</description>
+ </param>
+ <!-- / Ford Specific Data Items -->
+
+ </function>
+
+ <function name="ReadDID" functionID="ReadDIDID" messagetype="request">
+ <description>Non periodic vehicle data read request</description>
+
+ <param name="ecuName" type="Integer" minvalue="0" maxvalue="65535" mandatory="true">
+ <description>Name of ECU.</description>
+ </param>
+ <param name="didLocation" type="Integer" minvalue="0" maxvalue="65535" minsize="1" maxsize="1000" array="true" mandatory="true">
+ <description>Get raw data from vehicle data DID location(s)</description>
+ </param>
+ </function>
+
+ <function name="ReadDID" functionID="ReadDIDID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="DISALLOWED"/>
+ <element name="USER_DISALLOWED"/>
+ <element name="TRUNCATED_DATA"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ <param name="didResult" type="DIDResult" minsize="0" maxsize="1000" array="true" mandatory="false">
+ <description>Array of requested DID results (with data if available).</description>
+ </param>
+
+ </function>
+
+ <function name="GetDTCs" functionID="GetDTCsID" messagetype="request">
+ <description>Vehicle module diagnostic trouble code request.</description>
+
+ <param name="ecuName" type="Integer" minvalue="0" maxvalue="65535" mandatory="true">
+ <description>Name of ECU.</description>
+ </param>
+
+ <param name="dtcMask" type="Integer" minvalue="0" maxvalue="255" mandatory="false">
+ <description>DTC Mask Byte to be sent in diagnostic request to module .</description>
+ </param>
+
+ </function>
+
+ <function name="GetDTCs" functionID="GetDTCsID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="DISALLOWED"/>
+ <element name="USER_DISALLOWED"/>
+ <element name="TRUNCATED_DATA"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ <param name="ecuHeader" type="Integer" minvalue="0" maxvalue="65535" mandatory="true">
+ <description>2 byte ECU Header for DTC response (as defined in VHR_Layout_Specification_DTCs.pdf)</description>
+ </param>
+
+ <param name="dtc" type="String" mandatory="false" minsize="1" maxsize="15" maxlength="10" array="true">
+ <description>
+ Array of all reported DTCs on module (ecuHeader contains information if list is truncated).
+ Each DTC is represented by 4 bytes (3 bytes of data and 1 byte status as defined in VHR_Layout_Specification_DTCs.pdf).
+ </description>
+ </param>
+
+ </function>
+
+ <function name="DiagnosticMessage" functionID="DiagnosticMessageID" messagetype="request">
+ <description>Non periodic vehicle diagnostic request</description>
+
+ <param name="targetID" type="Integer" minvalue="0" maxvalue="65535" mandatory="true">
+ <description>Name of target ECU.</description>
+ </param>
+
+ <param name="messageLength" type="Integer" minvalue="0" maxvalue="65535" mandatory="true">
+ <description>Length of message (in bytes).</description>
+ </param>
+
+ <param name="messageData" type="Integer" minvalue="0" maxvalue="255" minsize="1" maxsize="65535" array="true" mandatory="true">
+ <description>
+ Array of bytes comprising CAN message.
+ </description>
+ </param>
+ </function>
+
+ <function name="DiagnosticMessage" functionID="DiagnosticMessageID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="DISALLOWED"/>
+ <element name="USER_DISALLOWED"/>
+ <element name="TRUNCATED_DATA"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ <param name="messageDataResult" type="Integer" minvalue="0" maxvalue="255" minsize="1" maxsize="65535" array="true" mandatory="true">
+ <description>
+ Array of bytes comprising CAN message result.
+ </description>
+ </param>
+
+ </function>
+
+ <function name="ScrollableMessage" functionID="ScrollableMessageID" messagetype="request">
+ <description>Creates a full screen overlay containing a large block of formatted text that can be scrolled with up to 8 SoftButtons defined</description>
+ <param name="scrollableMessageBody" type="String" maxlength="500">
+ <description>Body of text that can include newlines and tabs.</description>
+ </param>
+ <param name="timeout" type="Integer" minvalue="1000" maxvalue="65535" defvalue="30000" mandatory="false">
+ <description>App defined timeout. Indicates how long of a timeout from the last action (i.e. scrolling message resets timeout).</description>
+ </param>
+ <param name="softButtons" type="SoftButton" minsize="0" maxsize="8" array="true" mandatory="false">
+ <description>
+ App defined SoftButtons.
+ If omitted on supported displays, only the system defined "Close" SoftButton will be displayed.
+ </description>
+ </param>
+ </function>
+
+ <function name="ScrollableMessage" functionID="ScrollableMessageID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="CHAR_LIMIT_EXCEEDED"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="DISALLOWED"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ <element name="REJECTED"/>
+ <element name="ABORTED"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ </function>
+
+ <function name="Slider" functionID="SliderID" messagetype="request">
+ <description>Creates a full screen or pop-up overlay (depending on platform) with a single user controlled slider.</description>
+ <param name="numTicks" type="Integer" minvalue="2" maxvalue="26" mandatory="true">
+ <description>Number of selectable items on a horizontal axis</description>
+ </param>
+ <param name="position" type="Integer" minvalue="1" maxvalue="26" mandatory="true">
+ <description>Initial position of slider control (cannot exceed numTicks)</description>
+ </param>
+ <param name="sliderHeader" type="String" maxlength="500" mandatory="true">
+ <description>Text header to display</description>
+ </param>
+ <param name="sliderFooter" type="String" maxlength="500" minsize="1" maxsize="26" array="true" mandatory="false">
+ <description>
+ Text footer to display (meant to display min/max threshold descriptors).
+ For a static text footer, only one footer string shall be provided in the array.
+ For a dynamic text footer, the number of footer text string in the array must match the numTicks value.
+ For a dynamic text footer, text array string should correlate with potential slider position index.
+ If omitted on supported displays, no footer text shall be displayed.
+ </description>
+ </param>
+ <param name="timeout" type="Integer" minvalue="1000" maxvalue="65535" defvalue="10000" mandatory="false">
+ <description>
+ App defined timeout. Indicates how long of a timeout from the last action (i.e. sliding control resets timeout).
+ If omitted, the value is set to 10000.
+ </description>
+ </param>
+ </function>
+
+ <function name="Slider" functionID="SliderID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="SAVED"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="DISALLOWED"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ <element name="REJECTED"/>
+ <element name="ABORTED"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ <param name="sliderPosition" type="Integer" minvalue="1" maxvalue="26" mandatory="false">
+ <description>
+ Current slider value returned when saved or canceled (aborted)
+ This value is only returned for resultCodes "SAVED" or "ABORTED"
+ </description>
+ </param>
+ </function>
+
+ <function name="ShowConstantTBT" functionID="ShowConstantTBTID" messagetype="request">
+ <param name="navigationText1" type="String" minlength="0" maxlength="500" mandatory="false">
+ </param>
+ <param name="navigationText2" type="String" minlength="0" maxlength="500" mandatory="false">
+ </param>
+ <param name="eta" type="String" minlength="0" maxlength="500" mandatory="false">
+ </param>
+ <param name="timeToDestination" type="String" minlength="0" maxlength="500" mandatory="false">
+ </param>
+ <param name="totalDistance" type="String" minlength="0" maxlength="500" mandatory="false">
+ </param>
+ <param name="turnIcon" type="Image" mandatory="false">
+ </param>
+ <param name="nextTurnIcon" type="Image" mandatory="false">
+ </param>
+ <param name="distanceToManeuver" type="Float" minvalue="0" maxvalue="1000000000" mandatory="false">
+ <description>
+ Fraction of distance till next maneuver (starting from when AlertManeuver is triggered).
+ Used to calculate progress bar.
+ </description>
+ </param>
+ <param name="distanceToManeuverScale" type="Float" minvalue="0" maxvalue="1000000000" mandatory="false">
+ <description>
+ Distance till next maneuver (starting from) from previous maneuver.
+ Used to calculate progress bar.
+ </description>
+ </param>
+ <param name="maneuverComplete" type="Boolean" mandatory="false">
+ <description>
+ If and when a maneuver has completed while an AlertManeuver is active, the app must send this value set to TRUE in order to clear the AlertManeuver overlay.
+ If omitted the value will be assumed as FALSE.
+ </description>
+ </param>
+ <param name="softButtons" type="SoftButton" minsize="0" maxsize="3" array="true" mandatory="false">
+ <description>
+ Three dynamic SoftButtons available (first SoftButton is fixed to "Turns").
+ If omitted on supported displays, the currently displayed SoftButton values will not change.
+ </description>
+ </param>
+ </function>
+
+ <function name="ShowConstantTBT" functionID="ShowConstantTBTID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="DISALLOWED"/>
+ <element name="UNSUPPORTED_REQUEST"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ </param>
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="AlertManeuver" functionID="AlertManeuverID" messagetype="request">
+ <param name="ttsChunks" type="TTSChunk" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>An array of text chunks of type TTSChunk. See TTSChunk</description>
+ </param>
+ <param name="softButtons" type="SoftButton" minsize="0" maxsize="3" array="true" mandatory="false">
+ <description>If omitted on supported displays, only the system defined "Close" SoftButton shall be displayed.</description>
+ </param>
+ </function>
+
+ <function name="AlertManeuver" functionID="AlertManeuverID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="IGNORED"/>
+ <element name="DISALLOWED"/>
+ <element name="UNSUPPORTED_REQUEST"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ <element name="ABORTED"/>
+ <element name="WARNINGS"/>
+ </param>
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="UpdateTurnList" functionID="UpdateTurnListID" messagetype="request">
+ <param name="turnList" type="Turn" minsize="1" maxsize="100" array="true" mandatory="false">
+ </param>
+ <param name="softButtons" type="SoftButton" minsize="0" maxsize="1" array="true" mandatory="false">
+ <description>If omitted on supported displays, app-defined SoftButton will be left blank.</description>
+ </param>
+ </function>
+
+ <function name="UpdateTurnList" functionID="UpdateTurnListID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="DISALLOWED"/>
+ <element name="UNSUPPORTED_REQUEST"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ </param>
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="ChangeRegistration" functionID="ChangeRegistrationID" messagetype="request">
+ <param name="language" type="Language" mandatory="true">
+ <description>Requested voice engine (VR+TTS) language registration</description>
+ </param>
+ <param name="hmiDisplayLanguage" type="Language" mandatory="true">
+ <description>Request display language registration</description>
+ </param>
+ <param name="appName" type="String" maxlength="100" mandatory="false">
+ <description>Request new app name registration</description>
+ </param>
+ <param name="ttsName" type="TTSChunk" minsize="1" maxsize="100" array="true" mandatory="false" >
+ <description>Request new ttsName registration</description>
+ </param>
+ <param name="ngnMediaScreenAppName" type="String" maxlength="100" mandatory="false">
+ <description>Request new app short name registration</description>
+ </param>
+ <param name="vrSynonyms" type="String" maxlength="40" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>Request new VR synonyms registration</description>
+ </param>
+
+</function>
+
+
+
+ <function name="ChangeRegistration" functionID="ChangeRegistrationID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description>
+ true, if successful
+ false, if failed
+ </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="DISALLOWED"/>
+ <element name="DUPLICATE_NAME"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ </function>
+
+ <function name="GenericResponse" functionID="GenericResponseID" messagetype="response">
+ <description>
+ Generic Response is sent, when the name of a received msg cannot be retrieved. Only used in case of an error.
+ Currently, only resultCode INVALID_DATA is used.
+ </description>
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="INVALID_DATA"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="PutFile" functionID="PutFileID" messagetype="request">
+ <description>
+ Used to push a binary data onto the SYNC module from a mobile device, such as icons and album art
+ Not supported on first generation SYNC vehicles.
+ Binary data is in binary part of hybrid msg.
+ </description>
+
+ <param name="syncFileName" type="String" maxlength="255" mandatory="true">
+ <description>File reference name.</description>
+ </param>
+
+ <param name="fileType" type="FileType" mandatory="true">
+ <description>Selected file type.</description>
+ </param>
+
+ <param name="persistentFile" type="Boolean" defvalue="false" mandatory="false">
+ <description>
+ Indicates if the file is meant to persist between sessions / ignition cycles.
+ If set to TRUE, then the system will aim to persist this file through session / cycles.
+ While files with this designation will have priority over others, they are subject to deletion by the system at any time.
+ In the event of automatic deletion by the system, the app will receive a rejection and have to resend the file.
+ If omitted, the value will be set to false.
+ </description>
+ </param>
+
+ <param name="systemFile" type="Boolean" defvalue="false" mandatory="false">
+ <description>Indicates if the file is meant to be passed thru core to elsewhere on the system.
+ If set to TRUE, then the system will instead pass the data thru as it arrives to a predetermined area outside of core. If omitted, the value will be set to false.</description>
+ </param>
+
+ <param name="offset" type="Integer" minvalue="0" maxvalue="100000000000" mandatory="false">
+ <description>Optional offset in bytes for resuming partial data chunks</description>
+ </param>
+
+ <param name="length" type="Integer" minvalue="0" maxvalue="100000000000" mandatory="false">
+ <description>Optional length in bytes for resuming partial data chunks</description>
+ </param>
+
+ </function>
+
+ <function name="PutFile" functionID="PutFileID" messagetype="response">
+ <description>Response is sent, when the file data was copied (success case). Or when an error occured.</description>
+ <description>Not supported on First generation SYNC vehicles. </description>
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="UNSUPPORTED_REQUEST"/>
+ </param>
+
+ <param name="spaceAvailable" type="Integer" minvalue="0" maxvalue="2000000000">
+ <description>
+ Provides the total local space available on SYNC for the registered app.
+ If the transfer has systemFile enabled, then the value will be set to 0 automatically.
+ </description>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="DeleteFile" functionID="DeleteFileID" messagetype="request">
+ <description>
+ Used to delete a file resident on the SYNC module in the app's local cache.
+ Not supported on first generation SYNC vehicles.
+ </description>
+
+ <param name="syncFileName" type="String" maxlength="255" mandatory="true">
+ <description>File reference name.</description>
+ </param>
+
+ </function>
+
+ <function name="DeleteFile" functionID="DeleteFileID" messagetype="response">
+ <description>
+ Response is sent, when the file data was deleted (success case). Or when an error occured.
+ Not supported on First generation SYNC vehicles.
+ </description>
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="UNSUPPORTED_REQUEST"/>
+ </param>
+
+ <param name="spaceAvailable" type="Integer" minvalue="0" maxvalue="2000000000">
+ <description>Provides the total local space available on SYNC for the registered app.</description>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="ListFiles" functionID="ListFilesID" messagetype="request">
+ <description>
+ Requests the current list of resident filenames for the registered app.
+ Not supported on first generation SYNC vehicles.
+ </description>
+ </function>
+
+ <function name="ListFiles" functionID="ListFilesID" messagetype="response">
+ <description>
+ Returns the current list of resident filenames for the registered app along with the current space available
+ Not supported on First generation SYNC vehicles.
+ </description>
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="UNSUPPORTED_REQUEST"/>
+ </param>
+
+ <param name="filenames" type="String" maxlength="500" minsize="0" maxsize="1000" array="true" mandatory="false">
+ <description>
+ An array of all filenames resident on SYNC for the given registered app.
+ If omitted, then no files currently reside on the system.
+ </description>
+ </param>
+
+ <param name="spaceAvailable" type="Integer" minvalue="0" maxvalue="2000000000">
+ <description>Provides the total local space available on SYNC for the registered app.</description>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <function name="SetAppIcon" functionID="SetAppIconID" messagetype="request">
+ <description>
+ Used to set existing local file on SYNC as the app's icon
+ Not supported on first generation SYNC vehicles.
+ </description>
+
+ <param name="syncFileName" type="String" maxlength="255" mandatory="true">
+ <description>File reference name.</description>
+ </param>
+
+ </function>
+
+ <function name="SetAppIcon" functionID="SetAppIconID" messagetype="response">
+ <description>
+ Response is sent, when the file data was copied (success case). Or when an error occured.
+ Not supported on First generation SYNC vehicles.
+ </description>
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="UNSUPPORTED_REQUEST"/>
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ </function>
+
+ <function name="SetDisplayLayout" functionID="SetDisplayLayoutID" messagetype="request">
+ <description>
+ Used to set an alternate display layout.
+ If not sent, default screen for given platform will be shown
+ </description>
+
+ <param name="displayLayout" type="String" maxlength="500" mandatory="true">
+ <description>
+ Predefined or dynamically created screen layout.
+ Currently only predefined screen layouts are defined.
+ </description>
+ </param>
+ </function>
+
+ <function name="OnHashChange" functionID="OnHashChangeID" messagetype="notification">
+ <description>
+ Notification containing an updated hashID which can be used over connection cycles (i.e. loss of connection, ignition cycles, etc.).
+ Sent after initial registration and subsequently after any change in the calculated hash of all persisted app data.
+ </description>
+
+ <param name="hashID" type="String" maxlength="100" mandatory="true">
+ <description>Calculated hash ID to be referenced during RegisterAppInterface.</description>
+ </param>
+ </function>
+
+ <function name="SetDisplayLayout" functionID="SetDisplayLayoutID" messagetype="response">
+
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="UNSUPPORTED_REQUEST"/>
+ </param>
+
+ <param name="displayCapabilities" type="DisplayCapabilities" mandatory="false">
+ <description>See DisplayCapabilities</description>
+ </param>
+
+ <param name="buttonCapabilities" type="ButtonCapabilities" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>See ButtonCapabilities</description >
+ </param>
+
+ <param name="softButtonCapabilities" type="SoftButtonCapabilities" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>If returned, the platform supports on-screen SoftButtons; see SoftButtonCapabilities.</description >
+ </param>
+
+ <param name="presetBankCapabilities" type="PresetBankCapabilities" mandatory="false">
+ <description>If returned, the platform supports custom on-screen Presets; see PresetBankCapabilities.</description >
+ </param>
+
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+
+ </function>
+
+ <function name="SystemRequest" functionID="SystemRequestID" messagetype="request">
+ <description>An asynchronous request from the device; binary data can be included in hybrid part of message for some requests (such as Authentication requests)</description>
+ <param name="requestType" type="RequestType" mandatory="true">
+ <description>The type of system request.</description>
+ </param>
+ <param name="fileName" type="String" maxlength="255" mandatory="false">
+ <description>The name of file.</description>
+ </param>
+ </function>
+
+ <function name="SystemRequest" functionID="SystemRequestID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="INVALID_CERT"/>
+ <element name="EXPIRED_CERT"/>
+ <element name="UNSUPPORTED_REQUEST"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ <element name="DISALLOWED"/>
+ <element name="ABORTED"/>
+ <element name="WARNINGS"/>
+ <element name="TIMED_OUT"/>
+ <element name="IGNORED"/>
+ </param>
+ </function>
+
+ <function name="SendLocation" functionID="SendLocationID" messagetype="request">
+ <param name="longitudeDegrees" type="Float" minvalue="-180" maxvalue="180" mandatory="true">
+ </param>
+ <param name="latitudeDegrees" type="Float" minvalue="-90" maxvalue="90" mandatory="true">
+ </param>
+ <param name="locationName" type="String" maxlength="500" mandatory="false">
+ <description>
+ Name / title of intended location
+ </description>
+ </param>
+ <param name="locationDescription" type="String" maxlength="500" mandatory="false">
+ <description>
+ Description intended location / establishment (if applicable)
+ </description>
+ </param>
+ <param name="addressLines" type="String" maxlength="500" minsize="0" maxsize="4" array="true" mandatory="false">
+ <description>
+ Location address (if applicable)
+ </description>
+ </param>
+ <param name="phoneNumber" type="String" maxlength="500" mandatory="false">
+ <description>
+ Phone number of intended location / establishment (if applicable)
+ </description>
+ </param>
+ <param name="locationImage" type="Image" mandatory="false">
+ <description>
+ Image / icon of intended location (if applicable and supported)
+ </description>
+ </param>
+ </function>
+
+ <function name="SendLocation" functionID="SendLocationID" messagetype="response" >
+ <param name="success" type="Boolean" platform="documentation">
+ <description> true, if successful; false, if failed </description>
+ </param>
+
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ <element name="UNSUPPORTED_RESOURCE"/>
+ <element name="DISALLOWED"/>
+ </param>
+ </function>
+
+ <function name="DialNumber" functionID="DialNumberID" messagetype="request">
+ <description>Dials a phone number and switches to phone application.</description>
+ <param name="number" type="String" maxlength="40">
+ <description>Phone number is a string, which can be up to 40 chars.</description>
+ </param>
+ </function>
+
+ <function name="DialNumber" functionID="DialNumberID" messagetype="response">
+ <param name="success" type="Boolean" platform="documentation">
+ <description>true, if successful</description>
+ <description>false, if failed</description>
+ </param>
+ <param name="resultCode" type="Result" platform="documentation">
+ <description>See Result</description>
+ <element name="SUCCESS"/>
+ <element name="INVALID_DATA"/>
+ <element name="OUT_OF_MEMORY"/>
+ <element name="TOO_MANY_PENDING_REQUESTS"/>
+ <element name="APPLICATION_NOT_REGISTERED"/>
+ <element name="GENERIC_ERROR"/>
+ <element name="REJECTED"/>
+ </param>
+ <param name="info" type="String" maxlength="1000" mandatory="false" platform="documentation">
+ <description>Provides additional human readable info regarding the result.</description>
+ </param>
+ </function>
+
+ <!-- Notifications -->
+
+ <function name="OnHMIStatus" functionID="OnHMIStatusID" messagetype="notification">
+ <param name="hmiLevel" type="HMILevel">
+ <description>See HMILevel</description>
+ </param>
+
+ <param name="audioStreamingState" type="AudioStreamingState">
+ <description>See AudioStreamingState</description>
+ </param>
+
+ <param name="systemContext" type="SystemContext">
+ <description>See SystemContext</description>
+ </param>
+ </function>
+
+ <function name="OnAppInterfaceUnregistered" functionID="OnAppInterfaceUnregisteredID" messagetype="notification">
+ <param name="reason" type="AppInterfaceUnregisteredReason">
+ <description>See AppInterfaceUnregisteredReason</description>
+ </param>
+ </function>
+
+ <function name="OnButtonEvent" functionID="OnButtonEventID" messagetype="notification">
+ <description>Notifies application of UP/DOWN events for buttons to which the application is subscribed.</description>
+ <param name="buttonName" type="ButtonName"/>
+ <param name="buttonEventMode" type="ButtonEventMode">
+ <description>Indicates whether this is an UP or DOWN event.</description>
+ </param>
+ <param name="customButtonID" type="Integer" minvalue="0" maxvalue="65536" mandatory="false">
+ <description>If ButtonName is "CUSTOM_BUTTON", this references the integer ID passed by a custom button. (e.g. softButton ID)</description>
+ </param>
+ </function>
+
+ <function name="OnButtonPress" functionID="OnButtonPressID" messagetype="notification">
+ <description>Notifies application of LONG/SHORT press events for buttons to which the application is subscribed.</description>
+ <param name="buttonName" type="ButtonName"/>
+ <param name="buttonPressMode" type="ButtonPressMode">
+ <description>Indicates whether this is a LONG or SHORT button press event.</description>
+ </param>
+ <param name="customButtonID" type="Integer" minvalue="0" maxvalue="65536" mandatory="false">
+ <description>If ButtonName is "CUSTOM_BUTTON", this references the integer ID passed by a custom button. (e.g. softButton ID)</description>
+ </param>
+ </function>
+
+ <function name="OnVehicleData" functionID="OnVehicleDataID" messagetype="notification">
+ <description>Callback for the periodic and non periodic vehicle data read function.</description>
+ <param name="gps" type="GPSData" mandatory="false">
+ <description>See GPSData</description>
+ </param>
+ <param name="speed" type="Float" minvalue="0" maxvalue="700" mandatory="false">
+ <description>The vehicle speed in kilometers per hour</description>
+ </param>
+ <param name="rpm" type="Integer" minvalue="0" maxvalue="20000" mandatory="false">
+ <description>The number of revolutions per minute of the engine</description>
+ </param>
+ <param name="fuelLevel" type="Float" minvalue="-6" maxvalue="106" mandatory="false">
+ <description>The fuel level in the tank (percentage)</description>
+ </param>
+ <param name="fuelLevel_State" type="ComponentVolumeStatus" mandatory="false">
+ <description>The fuel level state</description>
+ </param>
+ <param name="instantFuelConsumption" type="Float" minvalue="0" maxvalue="25575" mandatory="false">
+ <description>The instantaneous fuel consumption in microlitres</description>
+ </param>
+ <param name="externalTemperature" type="Float" minvalue="-40" maxvalue="100" mandatory="false">
+ <description>The external temperature in degrees celsius</description>
+ </param>
+ <param name="vin" type="String" maxlength="17" mandatory="false">
+ <description>Vehicle identification number.</description>
+ </param>
+ <param name="prndl" type="PRNDL" mandatory="false">
+ <description>See PRNDL</description>
+ </param>
+ <param name="tirePressure" type="TireStatus" mandatory="false">
+ <description>See TireStatus</description>
+ </param>
+ <param name="odometer" type="Integer" minvalue="0" maxvalue="17000000" mandatory="false">
+ <description>Odometer in km</description>
+ </param>
+ <param name="beltStatus" type="BeltStatus" mandatory="false">
+ <description>The status of the seat belts</description>
+ </param>
+ <param name="bodyInformation" type="BodyInformation" mandatory="false">
+ <description>The body information including power modes</description>
+ </param>
+ <param name="deviceStatus" type="DeviceStatus" mandatory="false">
+ <description>The device status including signal and battery strength</description>
+ </param>
+ <param name="driverBraking" type="VehicleDataEventStatus" mandatory="false">
+ <description>The status of the brake pedal</description>
+ </param>
+ <param name="wiperStatus" type="WiperStatus" mandatory="false">
+ <description>The status of the wipers</description>
+ </param>
+ <param name="headLampStatus" type="HeadLampStatus" mandatory="false">
+ <description>Status of the head lamps</description>
+ </param>
+ <param name="engineTorque" type="Float" minvalue="-1000" maxvalue="2000" mandatory="false">
+ <description>Torque value for engine (in Nm) on non-diesel variants</description>
+ </param>
+ <param name="accPedalPosition" type="Float" minvalue="0" maxvalue="100" mandatory="false">
+ <description>Accelerator pedal position (percentage depressed)</description>
+ </param>
+ <param name="steeringWheelAngle" type="Float" minvalue="-2000" maxvalue="2000" mandatory="false">
+ <description>Current angle of the steering wheel (in deg)</description>
+ </param>
+
+ <!-- Ford Specific Vehicle Data -->
+ <param name="eCallInfo" type="ECallInfo" mandatory="false">
+ <description>Emergency Call notification and confirmation data</description>
+ </param>
+ <param name="airbagStatus" type="AirbagStatus" mandatory="false">
+ <description>The status of the air bags</description>
+ </param>
+ <param name="emergencyEvent" type="EmergencyEvent" mandatory="false">
+ <description>Information related to an emergency event (and if it occurred)</description>
+ </param>
+ <param name="clusterModeStatus" type="ClusterModeStatus" mandatory="false">
+ <description>The status modes of the cluster</description>
+ </param>
+ <param name="myKey" type="MyKey" mandatory="false">
+ <description>Information related to the MyKey feature</description>
+ </param>
+ <!-- / Ford Specific Vehicle Data -->
+
+ </function>
+
+ <function name="OnCommand" functionID="OnCommandID" messagetype="notification">
+ <param name="cmdID" type="Integer" minvalue="0" maxvalue="2000000000">
+ <description>Command ID, which is related to a specific menu entry</description>
+ </param>
+
+ <param name="triggerSource" type="TriggerSource">
+ <description>See TriggerSource</description>
+ </param>
+ </function>
+
+ <function name="OnTBTClientState" functionID="OnTBTClientStateID" messagetype="notification" >
+ <description>Provides applications with notifications specific to the current TBT client status on the module</description>
+ <param name="state" type="TBTState">
+ <description>Current State of TBT client</description>
+ </param>
+ </function>
+
+ <function name="OnDriverDistraction" functionID="OnDriverDistractionID" messagetype="notification" >
+ <description>Provides driver distraction state to mobile applications</description>
+ <param name="state" type="DriverDistractionState">
+ <description>Current State of Driver Distraction</description>
+ </param>
+ </function>
+
+ <function name="OnPermissionsChange" functionID="OnPermissionsChangeID" messagetype="notification" >
+ <description>Provides update to app of which policy-table-enabled functions are available</description>
+ <param name="permissionItem" type="PermissionItem" minsize="0" maxsize="500" array="true">
+ <description>Change in permissions for a given set of RPCs</description>
+ </param>
+ </function>
+
+ <function name="OnAudioPassThru" functionID="OnAudioPassThruID" messagetype="notification">
+ <description>Binary data is in binary part of hybrid msg</description>
+ </function>
+
+ <function name="OnLanguageChange" functionID="OnLanguageChangeID" messagetype="notification">
+ <param name="language" type="Language">
+ <description>Current SYNC voice engine (VR+TTS) language</description>
+ </param>
+ <param name="hmiDisplayLanguage" type="Language">
+ <description>Current display language</description>
+ </param>
+ </function>
+
+ <function name="OnKeyboardInput" functionID="OnKeyboardInputID" messagetype="notification" platform="MobileNav">
+
+ <description>On-screen keyboard event.</description>
+ <description>Can be full string or individual keypresses depending on keyboard mode.</description>
+
+ <param name="event" type="KeyboardEvent" mandatory="true">
+ <description>On-screen keyboard input data.</description>
+ </param>
+
+ <param name="data" type="String" maxlength="500" mandatory="false">
+ <description>On-screen keyboard input data.</description>
+ <description>For dynamic keypress events, this will be the current compounded string of entry text.</description>
+ <description>For entry submission events, this will be the full text entry (this will always return regardless of the mode).</description>
+ <description>For entry cancelled and entry aborted events, this data param will be omitted.</description>
+ </param>
+
+ </function>
+
+
+ <function name="OnTouchEvent" functionID="OnTouchEventID" messagetype="notification" platform="MobileNav">
+ <description>Notifies about touch events on the screen's prescribed area</description>
+ <param name="type" type="TouchType" mandatory="true">
+ <description>The type of touch event.</description>
+ </param>
+ <param name="event" type="TouchEvent" mandatory="true" minsize="1" maxsize="10" array="true">
+ <description>List of all individual touches involved in this event.</description>
+ </param>
+ </function>
+
+ <function name="OnSystemRequest" functionID="OnSystemRequestID" messagetype="notification">
+ <description>
+ An asynchronous request from the system for specific data from the device or the cloud or response
+ to a request from the device or cloud Binary data can be included in hybrid part of message for some requests
+ (such as Authentication request responses)
+ </description>
+ <param name="requestType" type="RequestType" mandatory="true">
+ <description>The type of system request.</description>
+ </param>
+ <param name="url" type="String" maxlength="1000" minsize="1" maxsize="100" array="true" mandatory="false">
+ <description>
+ Optional array of URL(s) for HTTP requests.
+ If blank, the binary data shall be forwarded to the app.
+ If not blank, the binary data shall be forwarded to the url(s) with a provided timeout in seconds.
+ </description>
+ </param>
+ <param name="timeout" type="Integer" minvalue="0" maxvalue="2000000000" mandatory="false">
+ <description>
+ Optional timeout for HTTP requests
+ Required if a URL is provided
+ </description>
+ </param>
+ <param name="fileType" type="FileType" mandatory="false">
+ <description>Optional file type (meant for HTTP file requests).</description>
+ </param>
+ <param name="offset" type="Integer" minvalue="0" maxvalue="100000000000" mandatory="false">
+ <description>Optional offset in bytes for resuming partial data chunks</description>
+ </param>
+ <param name="length" type="Integer" minvalue="0" maxvalue="100000000000" mandatory="false">
+ <description>Optional length in bytes for resuming partial data chunks</description>
+ </param>
+ </function>
+
+<!-- ~~~~~~~~~~~~~~~~~~ -->
+<!-- Ford Specific APIs -->
+<!-- ~~~~~~~~~~~~~~~~~~ -->
+</interface>
diff --git a/src/components/utils/test/test_generator/generated_msg_version_test.cc b/src/components/utils/test/test_generator/generated_msg_version_test.cc
new file mode 100644
index 0000000000..e5a295ee96
--- /dev/null
+++ b/src/components/utils/test/test_generator/generated_msg_version_test.cc
@@ -0,0 +1,77 @@
+/*
+ * Copyright (c) 2015, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include <iostream>
+#include <fstream>
+#include <string>
+#include "gtest/gtest.h"
+#include "generated_msg_version.h"
+#include "utils/file_system.h"
+
+using namespace std;
+
+namespace test {
+namespace components {
+namespace utils {
+
+void get_version_from_file(int& first_version, int& second_version) {
+ // Supposed that major and minor version include one number
+ const std::string& absolute_current_path =
+ file_system::CurrentWorkingDirectory();
+ std::ifstream xml_file(absolute_current_path + "/MOBILE_API.xml");
+
+ std::string str;
+
+ ASSERT_TRUE(xml_file.is_open());
+ while (getline(xml_file, str)) {
+ std::size_t isfound = str.find("interface name");
+ if (isfound != std::string::npos) {
+ std::size_t snd = str.find(".");
+ ASSERT_TRUE(snd != std::string::npos);
+ first_version = str[snd - 1] - 48;
+ second_version = str[snd + 1] - 48;
+ break;
+ }
+ }
+}
+
+TEST(GeneratorTool, GetCorrectVersion) {
+ int first_version = 0;
+ int second_version = 0;
+ get_version_from_file(first_version, second_version);
+ EXPECT_EQ(first_version, application_manager::major_version);
+ EXPECT_EQ(second_version, application_manager::minor_version);
+}
+
+} // namespace utils
+} // namespace components
+} // namespace test
diff --git a/src/components/utils/test/thread_validator_test.cc b/src/components/utils/test/thread_validator_test.cc
index 16d9d12874..b6e21d7157 100644
--- a/src/components/utils/test/thread_validator_test.cc
+++ b/src/components/utils/test/thread_validator_test.cc
@@ -45,9 +45,8 @@ using namespace ::threads;
TEST(ThreadValidatorTest, CompareID_CurrentThreadAndPthread_AreEqual) {
SingleThreadSimpleValidator object;
ASSERT_EQ(object.creation_thread_id(), pthread_self());
-
}
-} // namespace utils
-} // namespace components
-} // namespace test
+} // namespace utils
+} // namespace components
+} // namespace test
diff --git a/src/components/utils/test/timer_test.cc b/src/components/utils/test/timer_test.cc
new file mode 100644
index 0000000000..63b3c663c3
--- /dev/null
+++ b/src/components/utils/test/timer_test.cc
@@ -0,0 +1,326 @@
+/*
+ * Copyright (c) 2016, Ford Motor Company
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *
+ * Redistributions of source code must retain the above copyright notice, this
+ * list of conditions and the following disclaimer.
+ *
+ * Redistributions in binary form must reproduce the above copyright notice,
+ * this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * Neither the name of the Ford Motor Company nor the names of its contributors
+ * may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+ * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+ * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "gtest/gtest.h"
+#include "utils/timer.h"
+#include "utils/mock_timer_task.h"
+#include "utils/conditional_variable.h"
+#include "utils/lock.h"
+#include "utils/macro.h"
+#include "utils/timer_task_impl.h"
+
+namespace test {
+namespace components {
+namespace timer_test {
+namespace {
+
+sync_primitives::Lock shot_lock;
+sync_primitives::ConditionalVariable shot_condition;
+
+const std::string kTimerName = "TestTimer";
+const bool kSingleShot = true;
+
+/*
+ * Default timeout used during timer testing.
+ * Value should be greater than at least 30 ms
+ * to avoid timer firing beetwen two sequental Start/Stop calls
+ */
+const uint32_t kDefaultTimeoutMs = 30u;
+const uint32_t kDefaultTimeoutRestartMs = 45u;
+
+class TestTask : public timer::TimerTask {
+ public:
+ TestTask() : timer_(NULL), calls_count_(0u) {}
+
+ void set_timer(timer::Timer* timer) {
+ timer_ = timer;
+ }
+
+ virtual void PerformTimer() const {}
+
+ void run() const OVERRIDE {
+ sync_primitives::AutoLock auto_lock(shot_lock);
+ ++calls_count_;
+ shot_condition.NotifyOne();
+ PerformTimer();
+ }
+
+ size_t calls_count() const {
+ return calls_count_;
+ }
+
+ protected:
+ mutable timer::Timer* timer_;
+ mutable size_t calls_count_;
+};
+
+class TestTaskWithStart : public TestTask {
+ public:
+ void PerformTimer() const OVERRIDE {
+ if (timer_) {
+ timer_->Start(kDefaultTimeoutRestartMs, !kSingleShot);
+ }
+ }
+};
+
+class TestTaskWithStop : public TestTask {
+ public:
+ void PerformTimer() const OVERRIDE {
+ if (timer_) {
+ timer_->Stop();
+ }
+ }
+};
+
+} // namespace
+
+// Start - Stop
+
+TEST(TimerTest, Start_Stop_NoLoop_NoCall) {
+ MockTimerTask* mock_task = new MockTimerTask();
+ EXPECT_CALL(*mock_task, run()).Times(0);
+
+ timer::Timer timer(kTimerName, mock_task);
+ EXPECT_FALSE(timer.is_running());
+ EXPECT_EQ(0u, timer.timeout());
+
+ timer.Start(kDefaultTimeoutMs, kSingleShot);
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutMs, timer.timeout());
+
+ timer.Stop();
+ EXPECT_FALSE(timer.is_running());
+ EXPECT_EQ(0u, timer.timeout());
+}
+
+TEST(TimerTest, Start_Stop_Loop_NoCall) {
+ MockTimerTask* mock_task = new MockTimerTask();
+ EXPECT_CALL(*mock_task, run()).Times(0);
+
+ timer::Timer timer(kTimerName, mock_task);
+ EXPECT_FALSE(timer.is_running());
+ EXPECT_EQ(0u, timer.timeout());
+
+ timer.Start(kDefaultTimeoutMs, !kSingleShot);
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutMs, timer.timeout());
+
+ timer.Stop();
+ EXPECT_FALSE(timer.is_running());
+ EXPECT_EQ(0u, timer.timeout());
+}
+
+TEST(TimerTest, Start_Stop_NoLoop_OneCall) {
+ sync_primitives::AutoLock auto_lock(shot_lock);
+ TestTask* task = new TestTask();
+
+ timer::Timer timer(kTimerName, task);
+ EXPECT_FALSE(timer.is_running());
+ EXPECT_EQ(0u, timer.timeout());
+
+ timer.Start(kDefaultTimeoutMs, kSingleShot);
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutMs, timer.timeout());
+
+ // Wait for 1 call
+ shot_condition.Wait(shot_lock);
+ EXPECT_FALSE(timer.is_running());
+
+ timer.Stop();
+ EXPECT_FALSE(timer.is_running());
+ EXPECT_EQ(0u, timer.timeout());
+
+ EXPECT_EQ(1u, task->calls_count());
+}
+
+TEST(TimerTest, Start_Stop_Loop_3Calls) {
+ const size_t loops_count = 3u;
+
+ sync_primitives::AutoLock auto_lock(shot_lock);
+ TestTask* task = new TestTask();
+
+ timer::Timer timer(kTimerName, task);
+ EXPECT_FALSE(timer.is_running());
+ EXPECT_EQ(0u, timer.timeout());
+
+ timer.Start(kDefaultTimeoutMs, !kSingleShot);
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutMs, timer.timeout());
+
+ // Wait for 3 calls
+ for (size_t i = 0; i < loops_count; ++i) {
+ shot_condition.Wait(shot_lock);
+ EXPECT_TRUE(timer.is_running());
+ }
+
+ timer.Stop();
+ EXPECT_FALSE(timer.is_running());
+ EXPECT_EQ(0u, timer.timeout());
+
+ EXPECT_EQ(loops_count, task->calls_count());
+}
+
+// Restart
+
+TEST(TimerTest, Restart_NoLoop_NoCall) {
+ MockTimerTask* mock_task = new MockTimerTask();
+ EXPECT_CALL(*mock_task, run()).Times(0);
+
+ timer::Timer timer(kTimerName, mock_task);
+
+ timer.Start(kDefaultTimeoutMs, kSingleShot);
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutMs, timer.timeout());
+
+ timer.Start(kDefaultTimeoutRestartMs, kSingleShot);
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutRestartMs, timer.timeout());
+}
+
+TEST(TimerTest, Restart_Loop_NoCall) {
+ MockTimerTask* mock_task = new MockTimerTask();
+ EXPECT_CALL(*mock_task, run()).Times(0);
+
+ timer::Timer timer(kTimerName, mock_task);
+
+ timer.Start(kDefaultTimeoutMs, !kSingleShot);
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutMs, timer.timeout());
+
+ timer.Start(kDefaultTimeoutRestartMs, !kSingleShot);
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutRestartMs, timer.timeout());
+}
+
+TEST(TimerTest, Restart_Loop_3Calls) {
+ const size_t loops_count = 3u;
+
+ sync_primitives::AutoLock auto_lock(shot_lock);
+ TestTask* task = new TestTask();
+ timer::Timer timer(kTimerName, task);
+
+ timer.Start(kDefaultTimeoutMs, !kSingleShot);
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutMs, timer.timeout());
+
+ // Wait for 3 calls
+ for (size_t i = 0; i < loops_count; ++i) {
+ shot_condition.Wait(shot_lock);
+ }
+ timer.Start(kDefaultTimeoutRestartMs, !kSingleShot);
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutRestartMs, timer.timeout());
+
+ EXPECT_EQ(loops_count, task->calls_count());
+}
+
+// Restart from call
+
+TEST(TimerTest, Restart_NoLoop_FromCall) {
+ sync_primitives::AutoLock auto_lock(shot_lock);
+ TestTask* task = new TestTaskWithStart();
+ timer::Timer timer(kTimerName, task);
+ task->set_timer(&timer);
+
+ timer.Start(kDefaultTimeoutMs, kSingleShot);
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutMs, timer.timeout());
+
+ // Wait for 1 calls
+ shot_condition.Wait(shot_lock);
+
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutRestartMs, timer.timeout());
+
+ EXPECT_EQ(1u, task->calls_count());
+}
+
+TEST(TimerTest, Restart_Loop_FromCall) {
+ sync_primitives::AutoLock auto_lock(shot_lock);
+ TestTask* task = new TestTaskWithStart();
+ timer::Timer timer(kTimerName, task);
+ task->set_timer(&timer);
+
+ timer.Start(kDefaultTimeoutMs, !kSingleShot);
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutMs, timer.timeout());
+
+ // Wait for 1 calls
+ shot_condition.Wait(shot_lock);
+
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutRestartMs, timer.timeout());
+
+ EXPECT_EQ(1u, task->calls_count());
+}
+
+// Stop from call
+
+TEST(TimerTest, Stop_Loop_FromCall) {
+ sync_primitives::AutoLock auto_lock(shot_lock);
+ TestTask* task = new TestTaskWithStop();
+ timer::Timer timer(kTimerName, task);
+ task->set_timer(&timer);
+
+ timer.Start(kDefaultTimeoutMs, !kSingleShot);
+ EXPECT_TRUE(timer.is_running());
+ EXPECT_EQ(kDefaultTimeoutMs, timer.timeout());
+
+ // Wait for 1 calls
+ shot_condition.Wait(shot_lock);
+
+ EXPECT_FALSE(timer.is_running());
+ EXPECT_EQ(0u, timer.timeout());
+
+ EXPECT_EQ(1u, task->calls_count());
+}
+
+// Delete running
+
+TEST(TimerTest, Delete_Running_NoLoop) {
+ MockTimerTask* mock_task = new MockTimerTask();
+ EXPECT_CALL(*mock_task, run()).Times(0);
+
+ timer::Timer* timer = new timer::Timer(kTimerName, mock_task);
+ EXPECT_FALSE(timer->is_running());
+ EXPECT_EQ(0u, timer->timeout());
+
+ timer->Start(kDefaultTimeoutMs, kSingleShot);
+ EXPECT_TRUE(timer->is_running());
+ EXPECT_EQ(kDefaultTimeoutMs, timer->timeout());
+
+ delete timer;
+}
+
+} // namespace timer_test
+} // namespace components
+} // namespace test
diff --git a/src/components/utils/test/timer_thread_test.cc b/src/components/utils/test/timer_thread_test.cc
deleted file mode 100644
index 6a758873f4..0000000000
--- a/src/components/utils/test/timer_thread_test.cc
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright (c) 2015, Ford Motor Company
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * Redistributions of source code must retain the above copyright notice, this
- * list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright notice,
- * this list of conditions and the following
- * disclaimer in the documentation and/or other materials provided with the
- * distribution.
- *
- * Neither the name of the Ford Motor Company nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include <pthread.h>
-#include <iostream>
-
-#include "lock.h"
-#include "macro.h"
-
-#include "gtest/gtest.h"
-#include "utils/conditional_variable.h"
-#include "utils/timer_thread.h"
-
-namespace test {
-namespace components {
-namespace utils {
-
-using namespace timer;
-using namespace sync_primitives;
-
-class TimerThreadTest : public ::testing::Test {
- public:
- TimerThreadTest()
- : check_val(0),
- val1(3),
- val2(4),
- wait_val(3000) {
- }
-
- void function() {
- AutoLock alock(lock_);
- ++check_val;
- condvar_.NotifyOne();
- }
-
- protected:
- uint32_t check_val;
- Lock lock_;
- ConditionalVariable condvar_;
- const uint32_t val1;
- const uint32_t val2;
- const uint32_t wait_val;
-};
-
-TEST_F(TimerThreadTest, StartTimerThreadWithTimeoutOneSec_ExpectSuccessfullInvokeCallbackFuncOnTimeout) {
- // Create Timer with TimerDeleagate
- TimerThread<TimerThreadTest> timer("Test", this, &TimerThreadTest::function,
- false);
- AutoLock alock(lock_);
- EXPECT_EQ(0u, check_val);
- timer.start(100);
- condvar_.WaitFor(alock, wait_val);
- EXPECT_EQ(1u, check_val);
-}
-
-TEST_F(TimerThreadTest, StartTimerThreadWithTimeoutOneSecInLoop_ExpectSuccessfullInvokeCallbackFuncOnEveryTimeout) {
- // Create Timer with TimerLooperDeleagate
- TimerThread<TimerThreadTest> timer("Test", this, &TimerThreadTest::function,
- true);
- AutoLock alock(lock_);
- EXPECT_EQ(0u, check_val);
- timer.start(100);
- while (check_val < val2) {
- condvar_.WaitFor(alock, wait_val);
- }
- // Check callback function was called 4 times
- EXPECT_EQ(val2, check_val);
-}
-
-TEST_F(TimerThreadTest, StopStartedTimerThreadWithTimeoutOneSecInLoop_ExpectSuccessfullStop) {
- // Create Timer with TimerLooperDeleagate
- TimerThread<TimerThreadTest> timer("Test", this, &TimerThreadTest::function,
- true);
- AutoLock alock(lock_);
- EXPECT_EQ(0u, check_val);
- timer.start(100);
- // Stop timer on 3rd second
- while (check_val < val2) {
- if (check_val == val1) {
- timer.stop();
- break;
- }
- condvar_.WaitFor(alock, wait_val);
- }
- EXPECT_EQ(val1, check_val);
-}
-
-TEST_F(TimerThreadTest, ChangeTimeoutForStartedTimerThreadWithTimeoutOneSecInLoop_ExpectSuccessfullStop) {
- // Create Timer with TimerLooperDeleagate
- TimerThread<TimerThreadTest> timer("Test", this, &TimerThreadTest::function,
- true);
- AutoLock alock(lock_);
- EXPECT_EQ(0u, check_val);
- timer.start(100);
- // Change timer timeout
- while (check_val < val2) {
- if (check_val == val1) {
- timer.updateTimeOut(200);
- }
- condvar_.WaitFor(alock, wait_val);
- }
- EXPECT_EQ(val2, check_val);
-}
-
-TEST_F(TimerThreadTest, CheckStartedTimerIsRunning_ExpectTrue) {
- // Create Timer with TimerLooperDeleagate
- TimerThread<TimerThreadTest> timer("Test", this, &TimerThreadTest::function,
- true);
- AutoLock alock(lock_);
- EXPECT_EQ(0u, check_val);
- timer.start(100);
- // Change timer timeout on 3rd second
- while (check_val < val1) {
- condvar_.WaitFor(alock, wait_val);
- // Check start is running
- EXPECT_TRUE(timer.isRunning());
- }
- EXPECT_EQ(val1, check_val);
-}
-
-} // namespace utils
-} // namespace components
-} // namespace test
-
diff --git a/src/plugins/appenders/safe_file_appender.cc b/src/plugins/appenders/safe_file_appender.cc
index 0d6cd614aa..ead775a1c6 100644
--- a/src/plugins/appenders/safe_file_appender.cc
+++ b/src/plugins/appenders/safe_file_appender.cc
@@ -37,10 +37,10 @@ using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(SafeFileAppender)
-void SafeFileAppender::subAppend(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) {
+void SafeFileAppender::subAppend(const spi::LoggingEventPtr& event,
+ log4cxx::helpers::Pool& p) {
try {
WriterAppender::subAppend(event, p);
- }
- catch (...) {
+ } catch (...) {
}
}
diff --git a/src/plugins/appenders/safe_file_appender.h b/src/plugins/appenders/safe_file_appender.h
index bcace8fa66..45299602ff 100644
--- a/src/plugins/appenders/safe_file_appender.h
+++ b/src/plugins/appenders/safe_file_appender.h
@@ -41,7 +41,8 @@ class SafeFileAppender : public FileAppender {
public:
DECLARE_LOG4CXX_OBJECT(SafeFileAppender)
protected:
- virtual void subAppend(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p);
+ virtual void subAppend(const spi::LoggingEventPtr& event,
+ log4cxx::helpers::Pool& p);
};
} // namespace log4cxx
diff --git a/src/plugins/appenders/safe_rolling_file_appender.cc b/src/plugins/appenders/safe_rolling_file_appender.cc
index 17e05adc91..7ed387d5c4 100644
--- a/src/plugins/appenders/safe_rolling_file_appender.cc
+++ b/src/plugins/appenders/safe_rolling_file_appender.cc
@@ -37,10 +37,10 @@ using namespace log4cxx::helpers;
IMPLEMENT_LOG4CXX_OBJECT(SafeRollingFileAppender)
-void SafeRollingFileAppender::subAppend(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p) {
+void SafeRollingFileAppender::subAppend(const spi::LoggingEventPtr& event,
+ log4cxx::helpers::Pool& p) {
try {
RollingFileAppenderSkeleton::subAppend(event, p);
- }
- catch (...) {
+ } catch (...) {
}
}
diff --git a/src/plugins/appenders/safe_rolling_file_appender.h b/src/plugins/appenders/safe_rolling_file_appender.h
index 593cc86aad..75832b7de7 100644
--- a/src/plugins/appenders/safe_rolling_file_appender.h
+++ b/src/plugins/appenders/safe_rolling_file_appender.h
@@ -41,7 +41,8 @@ class SafeRollingFileAppender : public RollingFileAppender {
public:
DECLARE_LOG4CXX_OBJECT(SafeRollingFileAppender)
protected:
- virtual void subAppend(const spi::LoggingEventPtr& event, log4cxx::helpers::Pool& p);
+ virtual void subAppend(const spi::LoggingEventPtr& event,
+ log4cxx::helpers::Pool& p);
};
} // namespace log4cxx
diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt
index 557c23f4e7..cf3e2c692c 100644
--- a/tools/CMakeLists.txt
+++ b/tools/CMakeLists.txt
@@ -5,7 +5,7 @@ include(ExternalProject)
set(intergen_SOURCES "${CMAKE_CURRENT_LIST_DIR}/intergen")
set(intergen_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/intergen")
set(intergen_INSTALL_DIR "${CMAKE_CURRENT_BINARY_DIR}/intergen")
-set(intergen_CMAKE_ARGS -DCMAKE_INSTALL_PREFIX=${intergen_INSTALL_DIR})
+set(intergen_CMAKE_ARGS -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER} -DCMAKE_C_COMPILER=${CMAKE_C_COMPILER} -DCMAKE_INSTALL_PREFIX=${intergen_INSTALL_DIR})
ExternalProject_Add(intergen
SOURCE_DIR ${intergen_SOURCES}
diff --git a/tools/InterfaceGenerator/Generator.py b/tools/InterfaceGenerator/Generator.py
index 5b5894bc00..932620c153 100755
--- a/tools/InterfaceGenerator/Generator.py
+++ b/tools/InterfaceGenerator/Generator.py
@@ -26,6 +26,7 @@ import generator.parsers.SDLRPCV2
import generator.parsers.JSONRPC
import generator.generators.SmartFactorySDLRPC
import generator.generators.SmartFactoryJSONRPC
+import MsgVersionGenerate
from generator.parsers.RPCBase import ParseError
from generator.generators.SmartFactoryBase import GenerateError
@@ -71,7 +72,6 @@ def _handle_fatal_error(error):
print
sys.exit(errno.EINVAL)
-
def main():
"""Main function of the generator that does actual work."""
@@ -101,6 +101,13 @@ Generating interface source code with following parameters:
except ParseError as error:
_handle_fatal_error(error)
+ # Parse sdl version from MOBILE_API.xml and create source file with this version
+ if src_xml_name == "MOBILE_API":
+ try:
+ MsgVersionGenerate.generate_msg_version(src_xml, output_dir)
+ except ParseError as error:
+ _handle_fatal_error(error)
+
# Generate SmartFactory source code from internal model
try:
code_generator.generate(interface,
diff --git a/tools/InterfaceGenerator/MsgVersionGenerate.py b/tools/InterfaceGenerator/MsgVersionGenerate.py
new file mode 100644
index 0000000000..7ff6c384d3
--- /dev/null
+++ b/tools/InterfaceGenerator/MsgVersionGenerate.py
@@ -0,0 +1,85 @@
+"""
+Generate file with major and minor msg_version.
+"""
+import xml.etree.ElementTree
+from string import Template
+import re
+from generator.parsers import RPCBase
+
+def generate_msg_version(file_name, path_to_storage):
+ """Parses MOBILE_API.xml in order to
+ receive major_version and minor_version
+ """
+ tree = xml.etree.ElementTree.parse(file_name)
+ root = tree.getroot()
+ if (root.tag == "interface" and "version" in root.attrib):
+ check_version_format(root.attrib["version"])
+ array = (root.attrib["version"]).split(".")
+ major_version = array[0]
+ minor_version = array[1]
+ if (major_version.isdigit() and minor_version.isdigit()):
+ data_for_storage = prepare_data_for_storage(major_version, minor_version)
+ store_data_to_file(path_to_storage, data_for_storage)
+ else:
+ raise RPCBase.ParseError("Attribute version has incorect value in MOBILE_API.xml")
+ else:
+ raise RPCBase.ParseError("Check MOBILE_API.xml file, parser can not find first element "
+ " with tag interface or atribute version")
+
+def store_data_to_file(path_to_storage, data_for_storage):
+ """Stores data with major and minor version
+ to file generated_msg_version.h
+ """
+ path_to_storage = path_to_storage + "/generated_msg_version.h"
+ fh = open(path_to_storage, 'w')
+ fh.write(data_for_storage)
+ fh.close()
+
+def check_version_format(version):
+ """Checks correctness of format of version
+ """
+ p = re.compile('\d+\\.\d+')
+ result = p.match(version)
+ if result == None or (result.end() != len(version)):
+ raise RPCBase.ParseError("Incorrect format of version please check MOBILE_API.xml. "
+ "Need format of version major_version.minor_version")
+
+def prepare_data_for_storage(major_version, minor_version):
+ """Prepares data to store to file.
+ """
+ temp = Template(
+ u'''/*Copyright (c) 2016, Ford Motor Company\n'''
+ u'''All rights reserved.\n'''
+ u'''Redistribution and use in source and binary forms, with or without\n'''
+ u'''modification, are permitted provided that the following conditions are met:\n'''
+ u'''Redistributions of source code must retain the above copyright notice, this\n'''
+ u'''list of conditions and the following disclaimer.\n'''
+ u'''Redistributions in binary form must reproduce the above copyright notice,\n'''
+ u'''this list of conditions and the following\n'''
+ u'''disclaimer in the documentation and/or other materials provided with the\n'''
+ u'''distribution.\n'''
+ u'''Neither the name of the Ford Motor Company nor the names of its contributors\n'''
+ u'''may be used to endorse or promote products derived from this software\n'''
+ u'''without specific prior written permission.\n'''
+ u'''THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n'''
+ u'''AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n'''
+ u'''IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n'''
+ u'''ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n'''
+ u'''LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n'''
+ u'''CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n'''
+ u'''SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n'''
+ u'''INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n'''
+ u'''CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n'''
+ u'''ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n'''
+ u'''POSSIBILITY OF SUCH DAMAGE.\n'''
+ u'''*/\n'''
+ u'''#ifndef GENERATED_MSG_VERSION_H\n'''
+ u'''#define GENERATED_MSG_VERSION_H\n\n'''
+ u'''namespace application_manager {\n\n'''
+ u'''const uint16_t major_version = $m_version;\n'''
+ u'''const uint16_t minor_version = $min_version;\n'''
+ u'''} // namespace application_manager\n'''
+ u'''#endif // GENERATED_MSG_VERSION_H''')
+ data_to_file = temp.substitute(m_version = major_version, min_version = minor_version)
+ return data_to_file
+
diff --git a/tools/InterfaceGenerator/generator/generators/SmartFactoryBase.py b/tools/InterfaceGenerator/generator/generators/SmartFactoryBase.py
index 2b372021c2..d13ac29c9b 100755
--- a/tools/InterfaceGenerator/generator/generators/SmartFactoryBase.py
+++ b/tools/InterfaceGenerator/generator/generators/SmartFactoryBase.py
@@ -1223,7 +1223,7 @@ class CodeGenerator(object):
_hpp_schema_file_tempalte = string.Template(
u'''/**\n'''
- u''' * @file ${class_name}.hpp\n'''
+ u''' * @file ${class_name}.h\n'''
u''' * @brief Generated class ${class_name} header file.\n'''
u''' *\n'''
u''' * This class is a part of SmartObjects solution. It provides\n'''
@@ -1280,7 +1280,7 @@ class CodeGenerator(object):
u'''#ifndef $guard\n'''
u'''#define $guard\n'''
u'''\n'''
- u'''#include "formatters/CSmartFactory.hpp"\n'''
+ u'''#include "formatters/CSmartFactory.h"\n'''
u'''#include "smart_objects/smart_schema.h"\n'''
u'''#include "smart_objects/schema_item.h"\n'''
u'''#include "utils/shared_ptr.h"\n'''
diff --git a/tools/InterfaceGenerator/generator/parsers/RPCBase.py b/tools/InterfaceGenerator/generator/parsers/RPCBase.py
index 2b3db62d56..22f3fd2c2d 100755
--- a/tools/InterfaceGenerator/generator/parsers/RPCBase.py
+++ b/tools/InterfaceGenerator/generator/parsers/RPCBase.py
@@ -568,7 +568,8 @@ class Parser(object):
default_value = self._get_bool_from_string(default_value);
param_type = Model.Boolean(default_value=default_value)
elif type_name == "Integer" or \
- type_name == "Float":
+ type_name == "Float" or \
+ type_name == "Double" :
min_value = self._extract_optional_number_attrib(
attrib, "minvalue", int if type_name == "Integer" else float)
max_value = self._extract_optional_number_attrib(
diff --git a/tools/Utils/generate_test_certificates.py b/tools/Utils/generate_test_certificates.py
new file mode 100755
index 0000000000..73b6f53cc8
--- /dev/null
+++ b/tools/Utils/generate_test_certificates.py
@@ -0,0 +1,279 @@
+#!/usr/bin/env python2
+# -*- coding: utf-8 -*-
+
+"""Generate certificates for testing
+ Usage:
+ generate_test_certificate.py --dir=<name of directory>
+"""
+
+import os
+import subprocess
+import tempfile
+from argparse import ArgumentParser
+from subprocess import check_call
+
+def run(command, *args):
+ """Application caller
+ wrap console call 'command args'
+ """
+ args_str = " " + " ".join(str(s) for s in list(args[0]))
+ if len(args_str) > 0 :
+ command += " " + args_str
+ print "Running", command
+ retcode = check_call(command, shell=True)
+ if retcode < 0:
+ raise RuntimeError("Child was terminated by signal")
+
+def openssl(*args):
+ """OpenSSL caller
+ wrap console call 'openssl args'
+ """
+ run("openssl", args)
+
+def gen_rsa_key(out_key_file, key_size):
+ """Private key generator
+ wrap console call 'openssl genrsa -out $out_key_file $key_size'
+ """
+ openssl("genrsa", "-out", out_key_file, key_size)
+
+def gen_root_cert(out_cert_file, key_file, days, answer):
+ """Root certificate generator
+ wrap console call 'openssl req -x509 -new -key $key_file -days $days -out $out_cert_file -subj $answer'
+ """
+ openssl("req -x509 -new -key", key_file, "-days", days, "-out", out_cert_file, "-subj", answer)
+
+def gen_cert(out_cert_file, key_file, ca_cert_file, ca_key_file, days, answer):
+ """Certificate generator
+ wrap console call
+ 'openssl req -new -key $key_file -days $days -out $out_cert_file -subj $answer'
+ 'openssl x509 -req -in $out_cert_file -CA $ca_cert_file -CAkey ca_key_file -CAcreateserial -out $out_cert_file -days 5000'
+ """
+ request_file = out_cert_file + ".req"
+ openssl("req -new -key", key_file, "-days", days, "-out", request_file, "-subj", answer)
+
+ openssl("x509 -hash -req -in", request_file, "-CA", ca_cert_file, "-CAkey", ca_key_file, \
+ "-CAcreateserial -out", out_cert_file, "-days", days)
+
+def gen_expire_cert(out_cert_file, key_file, ca_cert_file, ca_key_file, days, answer):
+ """Expired certificate generator
+ wrap console call
+ 'openssl req -new -key $key_file -days $days -out $out_cert_file -subj $answer'
+ 'openssl ca -batch -config $config_file_path -in $request_file -out $out_cert_file,
+ "-cert", ca_cert_file, "-keyfile", ca_key_file, "-startdate 150101000000Z -enddate 150314092653Z'
+ """
+ request_file = out_cert_file + ".req"
+ openssl("req -new -key", key_file, "-days", days, "-out", request_file, "-subj", answer)
+
+ # Create temporary files needed for expired certificate generation
+ temp_dir = tempfile.mkdtemp()
+ config_file_path = os.path.join(temp_dir, "database.conf")
+ database_file_path = os.path.join(temp_dir, "database")
+ serial_file_path = os.path.join(temp_dir, "serial")
+ # create file
+ open(database_file_path, 'w').close()
+
+ serial_file = open(serial_file_path, 'w')
+ serial_file.write("01")
+ serial_file.close();
+
+ current_dir = os.getcwd()
+ config_file = open(config_file_path, 'w')
+ config_file.write(
+ """[ ca ]
+ default_ca = ca_default
+
+ [ ca_default ]
+ dir = %s""" % (temp_dir, ) + """
+ certs = %s""" % (current_dir, ) + """
+ new_certs_dir = %s""" % (current_dir, ) + """
+ database = %s""" % (database_file_path, ) + """
+ serial = %s""" % (serial_file_path, ) + """
+ RANDFILE = $dir/ca.db.rand
+ certificate = %s""" % (os.path.abspath(ca_cert_file), ) + """
+ private_key = %s""" % (os.path.abspath(ca_key_file), ) + """
+ default_days = 365
+ default_crl_days = 30
+ default_md = md5
+ preserve = no
+ policy = generic_policy
+ [ generic_policy ]
+ countryName = optional
+ stateOrProvinceName = optional
+ localityName = optional
+ organizationName = optional
+ organizationalUnitName = optional
+ commonName = supplied
+ emailAddress = optional\n""")
+ config_file.close();
+
+ openssl("ca -batch -config", config_file_path, "-in", request_file, "-out", out_cert_file,
+ "-startdate 150101000000Z -enddate 150314092653Z")
+
+def gen_pkcs12(out, key_file, cert_file, verification_certificate) :
+ """Pem to PKCS#12 standard
+ wrap console call
+ 'openssl pkcs12 -export -out $out -inkey $key_file -in $cert_file -name 'SPT key and certificates' -certfile $certs'
+ """
+ openssl("pkcs12 -export -out", out, "-inkey", key_file, "-in", cert_file, \
+ "-name 'SPT key and certificates'", "-CAfile ", verification_certificate, \
+ " -passout pass:")
+
+ """
+ Encode certificate $out to base 64
+ """
+ with open(out, "rb") as cert:
+ with open(out + ".enc", "wb") as enc_cert:
+ enc_cert.write(cert.read().encode("base64"))
+
+def answers(name, app_id, country, state, locality, organization, unit, email) :
+ """Answer string generator
+ Generate answer for certificate creation with openssl
+ Country argument need to be 2 symbol size
+ """
+ if len(country) != 2 :
+ raise ValueError("Country argument need to be 2 symbol size")
+ answer ="'/C={0}/ST={1}/L={2}/O={3}".format(country, state, locality, organization)
+ answer +="/OU={0}/CN={1}/emailAddress={2}'".format(unit, name, email)
+ if len(app_id) > 0:
+ answer += "/serialNumber={0}".format(app_id)
+ return answer
+
+def concat_files(out_file_name, *args) :
+ print "Concatenate text files", args, "into", out_file_name
+ with open(out_file_name, 'w') as outfile:
+ for fname in args :
+ with open(fname) as infile :
+ outfile.write(infile.read())
+
+
+def main():
+ soft_verify_file = os.path.join("server", "server_root.key")
+ arg_parser = ArgumentParser(description='Welcome to SDL test certificate generator.')
+ arg_parser.add_argument('-d', '--dir', help="directory for certificate generating")
+ arg_parser.add_argument('-s', '--soft', help="do not override existing certificates if '%s' exists" % soft_verify_file, action='store_true' )
+ args = arg_parser.parse_args()
+ if args.dir:
+ if not os.path.exists(args.dir):
+ raise OSError("Input directory does not exist")
+ os.chdir(args.dir)
+ if args.soft:
+ if os.path.exists(soft_verify_file):
+ print "Root key file '%s' exists. Generation skipped according to soft mode." % (soft_verify_file, )
+ return
+
+ server_root_answer = answers("server_root", "", "US", "California", "Silicon Valley", "CAcert.org", "CAcert", "sample@cacert.org")
+ client_root_answer = answers("client_root", "", "US", "California", "Silicon Valley", "CAcert.org", "CAcert", "sample@cacert.org")
+ ford_server_answer = answers("FORD", "", "US", "Michigan", "Detroit", "FORD_SERVER", "FORD_SDL_SERVER" ,"sample@ford.com")
+ ford_client_answer = answers("FORD_CLIENT", "", "US", "Michigan", "Detroit", "FORD_CLIENT", "FORD_SDL_CLIENT" ,"sample@ford.com")
+ client_answer = answers("client", "SPT", "RU", "Russia", "St. Petersburg", "Luxoft", "HeadUnit" ,"sample@luxoft.com")
+ server_answer = answers("server", "SPT", "RU", "Russia", "St. Petersburg", "Luxoft", "Mobile" ,"sample@luxoft.com")
+ server_unsigned_answer = answers("server", "SPT", "RU", "Russia", "St. Petersburg", "Luxoft", "Mobile_unsigned" ,"sample@luxoft.com")
+ server_expired_answer = answers("server", "SPT", "RU", "Russia", "St. Petersburg", "Luxoft", "Mobile_expired" ,"sample@luxoft.com")
+ client_unsigned_answer = answers("client", "SPT", "RU", "Russia", "St. Petersburg", "Luxoft", "Mobile_unsigned" ,"sample@luxoft.com")
+ client_expired_answer = answers("client", "SPT", "RU", "Russia", "St. Petersburg", "Luxoft", "Mobile_expired" ,"sample@luxoft.com")
+ days = 10000
+
+ server_dir = "server"
+ client_dir = "client"
+ if not os.path.exists(server_dir):
+ os.mkdir(server_dir)
+ if not os.path.exists(client_dir):
+ os.mkdir(client_dir)
+
+ print " --== Root certificate generating SERVER==-- "
+ server_root_key_file = os.path.join(server_dir, "server_root.key")
+ assert soft_verify_file == server_root_key_file, 'Update soft key file path'
+ server_root_cert_file = os.path.join(server_dir, "server_root.crt")
+ gen_rsa_key(server_root_key_file, 2048)
+ gen_root_cert(server_root_cert_file, server_root_key_file, days, server_root_answer)
+
+ print " --== Root certificate generating CLIENT==-- "
+ client_root_key_file = os.path.join(client_dir, "client_root.key")
+ client_root_cert_file = os.path.join(client_dir, "client_root.crt")
+ gen_rsa_key(client_root_key_file, 2048)
+ gen_root_cert(client_root_cert_file, client_root_key_file, days, client_root_answer)
+
+ print
+ print " --== Ford server CA certificate generating ==-- "
+ ford_server_key_file = os.path.join(server_dir, "ford_server.key")
+ ford_server_cert_file = os.path.join(server_dir, "ford_server.crt")
+ gen_rsa_key(ford_server_key_file, 2048)
+ gen_cert(ford_server_cert_file, ford_server_key_file, server_root_cert_file, server_root_key_file, days, ford_server_answer)
+
+ print
+ print " --== Ford client CA certificate generating ==-- "
+ ford_client_key_file = os.path.join(client_dir, "ford_client.key")
+ ford_client_cert_file = os.path.join(client_dir, "ford_client.crt")
+ gen_rsa_key(ford_client_key_file, 2048)
+ gen_cert(ford_client_cert_file, ford_client_key_file, client_root_cert_file, client_root_key_file, days, ford_client_answer)
+
+ print
+ print " --== SDL and SPT adjustment ==-- "
+ server_verification_ca_cert_file = os.path.join(server_dir, "server_verification_ca_cetrificates.crt")
+ client_verification_ca_cert_file = os.path.join(client_dir, "client_verification_ca_cetrificates.crt")
+ concat_files(server_verification_ca_cert_file, server_root_cert_file, ford_server_cert_file)
+ concat_files(client_verification_ca_cert_file, client_root_cert_file, ford_client_cert_file)
+
+
+ print
+ print " --== Client certificate generating ==-- "
+ client_key_file = os.path.join(client_dir, "client.key")
+ client_cert_file = os.path.join(client_dir, "client.crt")
+ gen_rsa_key(client_key_file, 2048)
+ gen_cert(client_cert_file, client_key_file, ford_client_cert_file, ford_client_key_file, days, client_answer)
+
+
+ print
+ print " --== Server certificate generating ==-- "
+ server_key_file = os.path.join(server_dir, "server.key")
+ server_cert_file = os.path.join(server_dir, "server.crt")
+ server_pkcs12_file = os.path.join(server_dir, "spt_credential.p12")
+ gen_rsa_key(server_key_file, 2048)
+ gen_cert(server_cert_file, server_key_file, ford_server_cert_file, ford_server_key_file, days, server_answer)
+ gen_pkcs12(server_pkcs12_file, server_key_file, server_cert_file, client_verification_ca_cert_file)
+
+ print
+ print " --== Server unsigned certificate generating ==-- "
+ server_unsigned_cert_file = os.path.join(server_dir, "server_unsigned.crt")
+ server_pkcs12_unsigned_file = os.path.join(server_dir, "spt_credential_unsigned.p12")
+ gen_root_cert(server_unsigned_cert_file, server_key_file, days, server_unsigned_answer)
+ gen_pkcs12(server_pkcs12_unsigned_file, server_key_file, server_unsigned_cert_file, client_verification_ca_cert_file)
+
+ print
+ print " --== Server expired certificate generating ==-- "
+ server_expired_cert_file = os.path.join(server_dir, "server_expired.crt")
+ server_pkcs12_expired_file = os.path.join(server_dir, "spt_credential_expired.p12")
+ gen_expire_cert(server_expired_cert_file, server_key_file, ford_server_cert_file, ford_server_key_file, days, server_expired_answer)
+ gen_pkcs12(server_pkcs12_expired_file, server_key_file, server_expired_cert_file, client_verification_ca_cert_file)
+
+
+ print
+ print " --== Client pkcs12 certificate generating ==-- "
+ client_key_file = os.path.join(client_dir, "client.key")
+ client_cert_file = os.path.join(client_dir, "client.crt")
+ client_pkcs12_file = os.path.join(client_dir, "client_credential.p12")
+ gen_rsa_key(client_key_file, 2048)
+ gen_cert(client_cert_file, client_key_file, ford_client_cert_file, ford_client_key_file, days, client_answer)
+ gen_pkcs12(client_pkcs12_file, client_key_file, client_cert_file, server_verification_ca_cert_file)
+
+ print
+ print " --== Client pkcs12 unsigned certificate generating ==-- "
+ client_unsigned_cert_file = os.path.join(client_dir, "client_unsigned.crt")
+ client_pkcs12_unsigned_file = os.path.join(client_dir, "client_credential_unsigned.p12")
+ gen_root_cert(client_unsigned_cert_file, client_key_file, days, client_unsigned_answer)
+ gen_pkcs12(client_pkcs12_unsigned_file, client_key_file, client_unsigned_cert_file, server_verification_ca_cert_file)
+
+ print
+ print " --== Client pkcs12 expired certificate generating ==-- "
+ client_expired_cert_file = os.path.join(client_dir, "client_expired.crt")
+ client_pkcs12_expired_file = os.path.join(client_dir, "client_credential_expired.p12")
+ gen_expire_cert(client_expired_cert_file, client_key_file, ford_client_cert_file, ford_client_key_file, days, client_expired_answer)
+ gen_pkcs12(client_pkcs12_expired_file, client_key_file, client_expired_cert_file, server_verification_ca_cert_file)
+
+ subprocess.call(["c_rehash", server_dir])
+ subprocess.call(["c_rehash", client_dir])
+ print
+ print "All certificates have been generated"
+
+if __name__ == "__main__":
+ main()
diff --git a/tools/infrastructure/check_style.sh b/tools/infrastructure/check_style.sh
new file mode 100755
index 0000000000..f42a048b34
--- /dev/null
+++ b/tools/infrastructure/check_style.sh
@@ -0,0 +1,47 @@
+#!/usr/bin/env sh
+# Copyright (c) 2016 Ford Motor Company,
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions are met:
+#
+# * Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer.
+#
+# * Redistributions in binary form must reproduce the above copyright notice,
+# this list of conditions and the following disclaimer in the documentation
+# and/or other materials provided with the distribution.
+#
+# * Neither the name of Ford Motor Company nor the names of its
+# contributors may be used to endorse or promote products derived from
+# this software without specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
+# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+FILE_NAMES=$(find src -name \*.h -print -o -name \*.cpp -print -o -name \*.cc -print | grep -v 3rd_party)
+
+
+check_style() {
+ clang-format-3.6 -style=file $1 | diff $1 -
+}
+
+fix_style() {
+ clang-format-3.6 -style=file -i $1
+}
+
+if [ "$1" = "--fix" ]
+then
+ for FILE_NAME in $FILE_NAMES; do fix_style $FILE_NAME; done
+else
+ for FILE_NAME in $FILE_NAMES; do check_style $FILE_NAME; done
+fi
+
diff --git a/tools/infrastructure/collect_coverage.sh b/tools/infrastructure/collect_coverage.sh
new file mode 100755
index 0000000000..47559e6c47
--- /dev/null
+++ b/tools/infrastructure/collect_coverage.sh
@@ -0,0 +1,27 @@
+#!/usr/bin/env bash
+
+BUILD_DIR=$1
+COVERAGE_DIR=$BUILD_DIR/coverage
+REPORTS_DIR=$BUILD_DIR/coverage_reports
+
+if [ "$BUILD_DIR" = "" ]
+then
+ echo "You should specify your build directory as first argument "
+ echo "Example:"
+ echo "\t\$ collect_coverage.sh [PATH TO BUILD DIR]"
+ exit
+fi
+
+
+rm -rf $COVERAGE_DIR
+rm -rf $REPORTS_DIR -
+
+mkdir $COVERAGE_DIR
+lcov --quiet --capture --directory . --output-file $COVERAGE_DIR/full_report.info
+lcov --quiet --remove $COVERAGE_DIR/full_report.info '/usr/*' '*/test/*' '*/src/3rd*' '*/build/src/*' --output-file $COVERAGE_DIR/coverage.info
+
+mkdir $REPORTS_DIR
+genhtml --quiet $COVERAGE_DIR/coverage.info --output-directory $REPORTS_DIR
+html2text -width 150 $REPORTS_DIR/index.html
+tar -zcf coverage_report.tar.gz $REPORTS_DIR
+echo More information avaliable in $REPORTS_DIR/index.html
diff --git a/tools/infrastructure/format_src.py b/tools/infrastructure/format_src.py
new file mode 100644
index 0000000000..b7927b2708
--- /dev/null
+++ b/tools/infrastructure/format_src.py
@@ -0,0 +1,37 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+Format all sources with clang-format. All *.cc and *h in the src dir
+are affected. Excluded from formatting sources in the "3rd_party" and
+in the "3rd_party-static" dirs. For the formatting used ".clang-format"
+in the project root.
+"""
+
+import os
+from utils import setup_working_dir, walk_dir, run_cmd
+import re
+
+
+INCLUDE_PATTERNS = ['^.*\.cc$', '^.*\.h$', '^.*\.cpp$', '^.*\.hpp$']
+EXCLUDE_PATTERNS = ['^.*3rd_party.*$']
+FORMAT_CMD = 'clang-format -i -style=file {}'
+
+
+def main():
+ ''' Main logic '''
+ setup_working_dir()
+ print 'Current working dir is {}'.format(os.getcwd())
+
+ def action(file_path):
+ if re.match('|'.join(INCLUDE_PATTERNS), file_path, re.M | re.I):
+ if not re.match('|'.join(EXCLUDE_PATTERNS),
+ file_path,
+ re.M | re.I):
+ print 'Formatting file {}'.format(file_path)
+ run_cmd(FORMAT_CMD.format(file_path))
+ walk_dir('src', action)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tools/infrastructure/git-hooks/pre-commit b/tools/infrastructure/git-hooks/pre-commit
new file mode 100755
index 0000000000..9c46f195f3
--- /dev/null
+++ b/tools/infrastructure/git-hooks/pre-commit
@@ -0,0 +1,102 @@
+#!/bin/bash
+
+# Hide all unstaged changes to prevent any influence of the further checks
+function POP_STASHED() {
+ # pop stashed changes if working directory isn't clean
+ if [ -n "$IS_DIRTY" ]; then
+ git reset --hard HEAD > /dev/null
+ skipped=$(git ls-files -t | grep ^S | cut -d' ' -f2-)
+ git stash pop --index > /dev/null
+ echo "$skipped" | while read file; do git update-index --skip-worktree "$file"; done
+ fi
+}
+
+# determine working tree status
+IS_DIRTY=`[[ $(git diff --shortstat 2> /dev/null | tail -n1) != "" ]] && echo '*'`
+
+# stash not staged for commit changes
+if [ -n "$IS_DIRTY" ]; then
+ git stash save --keep-index
+ trap POP_STASHED EXIT
+fi
+# End of stashing
+
+if git rev-parse --verify HEAD >/dev/null 2>&1
+then
+ against=HEAD
+else
+ # Initial commit: diff against an empty tree object
+ against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
+fi
+
+# If you want to allow non-ASCII filenames set this variable to true.
+allownonascii=$(git config --bool hooks.allownonascii)
+
+# Redirect output to stderr.
+exec 1>&2
+
+# Cross platform projects tend to avoid non-ASCII filenames; prevent
+# them from being added to the repository. We exploit the fact that the
+# printable range starts at the space character and ends with tilde.
+if [ "$allownonascii" != "true" ] &&
+ # Note that the use of brackets around a tr range is ok here, (it's
+ # even required, for portability to Solaris 10's /usr/bin/tr), since
+ # the square bracket bytes happen to fall in the designated range.
+ test $(git diff --cached --name-only --diff-filter=A -z $against |
+ LC_ALL=C tr -d '[ -~]\0' | wc -c) != 0
+then
+ cat <<\EOF
+Error: Attempt to add a non-ASCII file name.
+
+This can cause problems if you want to work with people on other platforms.
+
+To be portable it is advisable to rename the file.
+
+If you know what you are doing you can disable this check using:
+
+ git config hooks.allownonascii true
+EOF
+ exit 1
+fi
+
+TEXT_DEFAULT="\\033[0;39m"
+TEXT_INFO="\\033[1;32m"
+TEXT_ERROR="\\033[1;31m"
+TEXT_UNDERLINE="\\0033[4m"
+TEXT_BOLD="\\0033[1m"
+
+# check for odd whitespace
+git diff --check --cached --color
+if [ "$?" -ne "0" ]; then
+ echo -e "$TEXT_ERROR" "Your changes introduce whitespace errors" "$TEXT_DEFAULT"
+ exit 1
+fi
+
+# Auto update c++ files with clang-format-3.6
+CLANG_FORMAT=clang-format-3.6
+# Verify clang-format
+CLANG_FORMAT_REQUIRED_VERSION=3.6
+CLANG_FORMAT_CURRENT_VERSION=$($CLANG_FORMAT -version)
+if [[ $CLANG_FORMAT_CURRENT_VERSION != *$CLANG_FORMAT_REQUIRED_VERSION* ]]
+then
+ echo -e "$TEXT_ERROR" "Wrong version of the clang-format. Required: $CLANG_FORMAT_REQUIRED_VERSION. Got: $CLANG_FORMAT_CURRENT_VERSION" "$TEXT_DEFAULT"
+ exit 1
+fi
+
+CPP_SRC_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E "(\.cc$|\.cpp$|\.h$|\.hpp$)" | grep -v "3rd_party")
+if [ -n "$CPP_SRC_FILES" ]; then
+ $CLANG_FORMAT -i -style=file $CPP_SRC_FILES
+ # Add possible changes after formating to the index
+ git add $CPP_SRC_FILES
+fi
+
+# Auto-check for pep8 in python code
+PYTHON_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -e '\.py$')
+
+if [ -n "$PYTHON_FILES" ]; then
+ flake8 $PYTHON_FILES
+ if [ "$?" -ne "0" ]; then
+ echo -e "$TEXT_ERROR" "Flake8 reports about the issues in the python scripts" "$TEXT_DEFAULT"
+ exit 2
+ fi
+fi
diff --git a/tools/infrastructure/install_hooks.py b/tools/infrastructure/install_hooks.py
new file mode 100644
index 0000000000..6f93e02c41
--- /dev/null
+++ b/tools/infrastructure/install_hooks.py
@@ -0,0 +1,40 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+"""
+Install (copy) git hooks
+"""
+
+import os
+import glob
+import shutil
+from utils import setup_working_dir
+
+
+def uninstall_hooks(hooks_dir):
+ print 'Deleting existing pre-commit hooks from {}'.format(hooks_dir)
+ files = glob.glob(os.path.join(hooks_dir, 'pre-commit*'))
+ for item in files:
+ os.remove(item)
+
+
+def install_hooks(src_dir, dst_dir):
+ print 'Installing pre-commit hooks'
+ src_files = glob.glob(os.path.join(src_dir, 'pre-commit*'))
+ for item in src_files:
+ shutil.copy(item, dst_dir)
+
+
+def main():
+ ''' Main logic '''
+ setup_working_dir()
+ print 'Current working dir is {}'.format(os.getcwd())
+ hooks_src_dir = os.path.join(
+ os.getcwd(), 'tools', 'infrastructure', 'git-hooks')
+ hooks_dst_dir = os.path.join(os.getcwd(), '.git', 'hooks')
+ uninstall_hooks(hooks_dst_dir)
+ install_hooks(hooks_src_dir, hooks_dst_dir)
+
+
+if __name__ == '__main__':
+ main()
diff --git a/tools/infrastructure/utils.py b/tools/infrastructure/utils.py
new file mode 100644
index 0000000000..ec1af42cce
--- /dev/null
+++ b/tools/infrastructure/utils.py
@@ -0,0 +1,43 @@
+# -*- coding: utf-8 -*-
+
+""" Misc utils used by other modules """
+
+import os
+import contextlib
+
+
+def setup_working_dir():
+ """ Prepare current working dir (in case if script is called from
+ outside). Set it to the project root.
+ """
+ os.chdir(os.path.join(os.path.dirname(
+ os.path.realpath(__file__)), os.pardir, os.pardir))
+
+
+def run_cmd(cmd_line):
+ import subprocess
+
+ return subprocess.call(cmd_line, shell=True)
+
+
+def walk_dir(directory, action, recursive=True):
+ """ Walks a directory, and executes the action on each file """
+ directory = os.path.abspath(directory)
+ for file in [file for file in os.listdir(directory) if file not in [os.curdir, os.pardir]]:
+ file_path = os.path.join(directory, file)
+ action(file_path)
+ if recursive and os.path.isdir(file_path):
+ walk_dir(file_path, action)
+
+
+@contextlib.contextmanager
+def working_directory(path):
+ """ A context manager which changes the working directory to the given
+ path, and then changes it back to it's previous value on exit.
+ """
+ prev_cwd = os.getcwd()
+ os.chdir(path)
+ try:
+ yield
+ finally:
+ os.chdir(prev_cwd)
diff --git a/tools/policy_table_validator/CMakeLists.txt b/tools/policy_table_validator/CMakeLists.txt
index 2a372d7ffa..7d9194e473 100644
--- a/tools/policy_table_validator/CMakeLists.txt
+++ b/tools/policy_table_validator/CMakeLists.txt
@@ -1,16 +1,15 @@
#set( CMAKE_VERBOSE_MAKEFILE on )
include_directories(
- ${CMAKE_SOURCE_DIR}/src/components/policy/src/policy/
- ${CMAKE_SOURCE_DIR}/src/components/rpc_base/include/
- ${CMAKE_SOURCE_DIR}/src/components/utils/include/
+ ${CMAKE_SOURCE_DIR}/src/components/policy/include
+ ${CMAKE_SOURCE_DIR}/src/components/rpc_base/include/
+ ${CMAKE_SOURCE_DIR}/src/components/utils/include/
${JSONCPP_INCLUDE_DIRECTORY}
)
link_directories (
- ${CMAKE_BINARY_DIR}/src/components/policy/src/policy/policy_table/table_struct/
- ${CMAKE_BINARY_DIR}/src/components/rpc_base/
+ ${CMAKE_BINARY_DIR}/src/components/rpc_base/
)
diff --git a/tools/policy_table_validator/main.cpp b/tools/policy_table_validator/main.cpp
index 16454ca128..509182edbf 100644
--- a/tools/policy_table_validator/main.cpp
+++ b/tools/policy_table_validator/main.cpp
@@ -1,6 +1,6 @@
#include <iostream>
#include <cstdlib>
-#include "policy_table/table_struct/types.h"
+#include "policy/policy_table/types.h"
#include "json/reader.h"
#include "utils/file_system.h"